<commit_before>#!/home/gzhao/mybin/bin/python

print __file__,"is running"
print __file__,"import std modules"
import os
import sys
import time
from optparse import OptionParser
print __file__,"import std modules successfully\n"

print __file__,"import local modules\n"
import facility
print __file__,"import local modules successfully\n"

def MainRun(Destdir="/home/gzhao/git/bcm_auto", Maillist="gzhao", Logdir=""):

    if os.path.isdir(Logdir):
        logpath = Logdir + time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) + '/'
    else:
        print "Log dir is invalid"
        return

    os.mkdir(logpath)
    print logpath

    os.chdir(Destdir)
    os.system('make deep_clean')

    if os.path.isfile("bcm963xx/targets/CLX900/bcmCLX900_nand_fs_image_128.w"):
        print "image exist, deep clean failed? Never mind,  deleted it first"
        os.remove("bcm963xx/targets/CLX900/bcmCLX900_nand_fs_image_128.w")
    else:
        res = "image deleted"

    msg = "Build commit:\n\n"
    commitOld = os.popen('git log -1').read()
    os.system('git pull origin zulu')
    commitNew = os.popen('git log -1').read()
    msg += commitNew

    if commitOld == commitNew:
        print "There has no update"
        res = "No need for 900 local build now"
        msg += "\nThere has no update from server side, do not build this time\n"
    else:

        msg += "\n=======================================================================\n"
        msg += "\nLog dir is " + logpath + "\n"
        msg += "\n=======================================================================\n"

        os.system('make >& ' + logpath + 'make.log')
        print msg

        if os.path.isfile("bcm963xx/targets/CLX900/bcmCLX900_nand_fs_image_128.w"):
            res = "900 local build successfully"
        else:
            res = "900 local build failed"
            msg += "\nLast make log:\n"
            msg += os.popen('tail -n 50 ' + logpath + 'make.log').read()

        msg += "\n\nThis is an auto send E-mail, please do not reply."
        print res
        print msg

    facility.Mail2(res, msg, From = "Builder@nanlnx-dragon")

if __name__ == '__main__':
    parser = OptionParser(usage="usage: %prog [options]", version="%prog 0.1")

    parser.add_option("-m", "--mail", dest="MailList", default="",
            help="when script failed, send a mail to inform others")

    parser.add_option("-d", "--destdir", dest="DestDir",
            default="/home/gzhao/git/bcm_auto",
            help="To locate the directory where the git repos is")

    parser.add_option("-l", "--logdir", dest="LogDir", default="",
            help="Use to set the log file directory")

    (options, args) = parser.parse_args()
    os.environ["MAILLIST"] = options.MailList

    MainRun(Destdir = options.DestDir,
           Maillist = options.MailList,
           Logdir = options.LogDir)
<commit_msg>Add some new feature.<commit_after>#!/home/gzhao/mybin/bin/python

print __file__,"is running"
print __file__,"import std modules"
import os
import sys
import time
from optparse import OptionParser
print __file__,"import std modules successfully\n"

print __file__,"import local modules\n"
import facility
print __file__,"import local modules successfully\n"

def MainRun(Destdir="/home/gzhao/git/bcm_auto", Maillist="gzhao", Logdir=""):

    if os.path.isdir(Logdir):
        logpath = Logdir + time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) + '/'
    else:
        print "Log dir is invalid"
        return

    os.chdir(Destdir)
    #os.system('make deep_clean')

    if os.path.isfile("bcm963xx/targets/CLX900/bcmCLX900_nand_fs_image_128.w"):
        print "image exist, deep clean failed? Never mind,  deleted it first"
        os.remove("bcm963xx/targets/CLX900/bcmCLX900_nand_fs_image_128.w")
    else:
        res = "image deleted"

    msg = "Build commit:\n\n"
    commitOld = os.popen('git log -1').read()
    updateMsg = os.popen('git pull origin zulu').read()
    commitNew = os.popen('git log -1').read()
    msg += commitNew
    msg += "\n=======================================================================\n"
    msg += "Update information:\n\n"
    msg += updateMsg

    if commitOld == commitNew:
        print "There has no update"
        res = "No need for 900 local build now"
        msg += "\nThere has no update from server side, do not build this time\n"
    else:
        os.mkdir(logpath)
        print logpath

        msg += "\n=======================================================================\n"
        msg += "\nLog dir is " + logpath + "\n"
        msg += "\n=======================================================================\n"

        os.system('make >& ' + logpath + 'make.log')
        print msg

        if os.path.isfile("bcm963xx/targets/CLX900/bcmCLX900_nand_fs_image_128.w"):
            res = "900 local build successfully"
        else:
            res = "900 local build failed"
            msg += "\nLast make log:\n"
            msg += os.popen('tail -n 50 ' + logpath + 'make.log').read()

        msg += "\n\nThis is an auto send E-mail, please do not reply."
        print res
        print msg

    facility.Mail2(res, msg, From = "Builder@nanlnx-dragon")

if __name__ == '__main__':
    parser = OptionParser(usage="usage: %prog [options]", version="%prog 0.1")

    parser.add_option("-m", "--mail", dest="MailList", default="",
            help="when script failed, send a mail to inform others")

    parser.add_option("-d", "--destdir", dest="DestDir",
            default="/home/gzhao/git/bcm_auto",
            help="To locate the directory where the git repos is")

    parser.add_option("-l", "--logdir", dest="LogDir", default="",
            help="Use to set the log file directory")

    (options, args) = parser.parse_args()
    os.environ["MAILLIST"] = options.MailList

    MainRun(Destdir = options.DestDir,
           Maillist = options.MailList,
           Logdir = options.LogDir)
<|endoftext|>


<commit_before>'''
A bunch of hackish fixups for testing of SpiderMonkey support. We should
get rid of these ASAP.
'''

import os
import sys
import math
import shutil
import subprocess

import emscripten

binaryen_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

js_target = sys.argv[1]
wast_target = sys.argv[2]

wasm_target = wast_target[:-5] + '.wasm'

base_wast_target = os.path.basename(wast_target)
base_wasm_target = os.path.basename(wasm_target)

def fix(js, before, after):
  assert js.count(before) == 1
  return js.replace(before, after)

# fix up js
js = open(js_target).read()
# send a buffer into wasm methods, not a typed array
js = fix(js,
         'instance = Wasm.instantiateModule(binary, info)',
         'instance = Wasm.instantiateModule(binary.buffer, info)')
# use the wasm, not wast
js = js.replace('"' + base_wast_target + '"', '"' + base_wasm_target + '"')
js = js.replace("'" + base_wast_target + "'", "'" + base_wasm_target + "'")
open(js_target, 'w').write(js)
shutil.copyfile(wast_target + '.mappedGlobals', wasm_target + '.mappedGlobals')

# lower cases, spidermonkey has no support for them
temp = wast_target + '.temp'
subprocess.check_call([os.path.join(binaryen_root, 'bin', 'binaryen-shell'),
                       wast_target, '--lower-case', '--print'],
                      stdout=open(temp, 'w'))
shutil.copyfile(temp, wast_target)

# fix up wast
wast = open(wast_target).read()
# tableswitch => br_table
wast = wast.replace('(tableswitch', '(br_table')
# memory to page sizes
PAGE_SIZE = 64 * 1024
memory_start = wast.find('(memory') + 1
memory_end = wast.find(')', memory_start)
memory = wast[memory_start:memory_end]
parts = memory.split(' ')
parts[1] = str(int(math.ceil(float(parts[1]) / PAGE_SIZE)))
if len(parts) == 3:
  parts[2] = str(int(math.ceil(float(parts[2]) / PAGE_SIZE)))
wast = wast[:memory_start] + ' '.join(parts) + \
       wast[memory_end:memory_end + 1] + \
       ' (export "memory" memory) ' + wast[memory_end + 1:]
open(wast_target, 'w').write(wast)

# convert to binary using spidermonkey
subprocess.check_call(emscripten.shared.SPIDERMONKEY_ENGINE + ['-e',
  'os.file.writeTypedArrayToFile("%s", new Uint8Array(wasmTextToBinary(os.file.readFile("%s"))))' % (wasm_target, wast_target)
])

<commit_msg>more python fixes<commit_after>'''
A bunch of hackish fixups for testing of SpiderMonkey support. We should
get rid of these ASAP.
'''

import os
import sys
import math
import shutil
import subprocess

import emscripten

binaryen_root = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

js_target = sys.argv[1]
wast_target = sys.argv[2]

wasm_target = wast_target[:-5] + '.wasm'

base_wast_target = os.path.basename(wast_target)
base_wasm_target = os.path.basename(wasm_target)

def fix(js, before, after):
  assert js.count(before) == 1
  return js.replace(before, after)

# fix up js
js = open(js_target).read()
# send a buffer into wasm methods, not a typed array
js = fix(js,
         'instance = Wasm.instantiateModule(binary, info)',
         'instance = Wasm.instantiateModule(binary.buffer, info)')
# use the wasm, not wast
js = js.replace('"' + base_wast_target + '"', '"' + base_wasm_target + '"')
js = js.replace("'" + base_wast_target + "'", "'" + base_wasm_target + "'")
open(js_target, 'w').write(js)
shutil.copyfile(wast_target + '.mappedGlobals', wasm_target + '.mappedGlobals')

# lower cases, spidermonkey has no support for them
temp = wast_target + '.temp'
subprocess.check_call([os.path.join(binaryen_root, 'bin', 'binaryen-shell'),
                       wast_target, '--lower-case', '--print'],
                      stdout=open(temp, 'w'))
shutil.copyfile(temp, wast_target)

# fix up wast
wast = open(wast_target).read()
# tableswitch => br_table
wast = wast.replace('(tableswitch', '(br_table')
# memory to page sizes
PAGE_SIZE = 64 * 1024
memory_start = wast.find('(memory') + 1
memory_end = wast.find(')', memory_start)
memory = wast[memory_start:memory_end]
parts = memory.split(' ')
parts[1] = str(int(math.ceil(float(parts[1]) / PAGE_SIZE)))
if len(parts) == 3:
  parts[2] = str(int(math.ceil(float(parts[2]) / PAGE_SIZE)))
wast = wast[:memory_start] + ' '.join(parts) + \
  wast[memory_end:memory_end + 1] + \
  ' (export "memory" memory) ' + wast[memory_end + 1:]
open(wast_target, 'w').write(wast)

# convert to binary using spidermonkey
subprocess.check_call(emscripten.shared.SPIDERMONKEY_ENGINE +
  ['-e', 'os.file.writeTypedArrayToFile("' + wasm_target + \
  '", new Uint8Array(wasmTextToBinary(os.file.readFile("' + \
  wast_target + '"))))'])
<|endoftext|>


<commit_before># -*- Mode: Python -*-

import os
import glob
import sys

import unittest

names = []
for filename in glob.iglob("test_*.py"):
  names.append(filename[:-3])

names.sort()

testLoader = unittest.TestLoader()
testSuite = testLoader.loadTestsFromNames(names)

runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(testSuite)

# Cleanup
try:
  os.rmdir("./test_data/blobs")
except OSError:
  pass

if os.path.isfile("./test_data/test_gir.db"):
  os.remove("./test_data/test_gir.db")

if not result.wasSuccessful():
	sys.exit(1)
<commit_msg>Import shutilso we can remove entire blobs directory<commit_after># -*- Mode: Python -*-

import os
import glob
import sys
import shutil

import unittest

names = []
for filename in glob.iglob("test_*.py"):
  names.append(filename[:-3])

names.sort()

testLoader = unittest.TestLoader()
testSuite = testLoader.loadTestsFromNames(names)

runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(testSuite)

# Cleanup
try:
  shutil.rmtree("./test_data/blobs")
except OSError:
  pass

if os.path.isfile("./test_data/test_gir.db"):
  os.remove("./test_data/test_gir.db")

if not result.wasSuccessful():
	sys.exit(1)
<|endoftext|>


<commit_before>from django.db.models import Q
from projects.models import Project, Story, StoryVersion

class ProjectQuerySetMixin(object):
    def get_queryset(self):
        if self.request.user.is_superuser:
            return Project.objects.all()
        else:
            return Project.objects.filter(coordinator=self.request.user)

class StoryQuerySetBaseMixin(object):
    def user_in_story_filter(self, story_objects, user):
        return story_objects.filter(Q(reporters__in=[user]) |
                                       Q(researchers__in=[user]) |
                                    Q(editors__in=[user]) |
                                    Q(copy_editors__in=[user]) |
                                    Q(fact_checkers__in=[user]) |
                                    Q(translators__in=[user]) |
                                    Q(artists__in=[user]) |
                                    Q(project__coordinator=user))

class StoryQuerySetMixin(StoryQuerySetBaseMixin):
    def get_queryset(self):
        if self.request.user.is_superuser:
            stories = Story.objects.all()
        else:
            stories = self.user_in_story_filter(Story.objects.all(), self.request.user)

        return stories

class StoryListQuerySetMixin(StoryQuerySetMixin):
    def get_queryset(self, project_id):
        stories = super(StoryListQuerySetMixin, self).get_queryset()
        return stories.filter(project__id=project_id)

class StoryVersionListQuerySetMixin(StoryQuerySetBaseMixin):
    def get_queryset(self, story_id):
        if self.request.user.is_superuser:
            return StoryVersion.objects.all()

        try:
            story = Story.objects.filter(id=story_id)
        except Story.DoesNotExist:
            return []

        print story
        story = self.user_in_story_filter(story, self.request.user)
        print story
        if story.count() == 0:
            print "0 count, woops!"
            return []

        return StoryVersion.objects.all()
<commit_msg>removal of print statements and formatting<commit_after>from django.db.models import Q
from projects.models import Project, Story, StoryVersion

class ProjectQuerySetMixin(object):
    def get_queryset(self):
        if self.request.user.is_superuser:
            return Project.objects.all()
        else:
            return Project.objects.filter(coordinator=self.request.user)

class StoryQuerySetBaseMixin(object):
    def user_in_story_filter(self, story_objects, user):
        return story_objects.filter(Q(reporters__in=[user]) |
                                    Q(researchers__in=[user]) |
                                    Q(editors__in=[user]) |
                                    Q(copy_editors__in=[user]) |
                                    Q(fact_checkers__in=[user]) |
                                    Q(translators__in=[user]) |
                                    Q(artists__in=[user]) |
                                    Q(project__coordinator=user))

class StoryQuerySetMixin(StoryQuerySetBaseMixin):
    def get_queryset(self):
        if self.request.user.is_superuser:
            stories = Story.objects.all()
        else:
            stories = self.user_in_story_filter(Story.objects.all(), self.request.user)

        return stories

class StoryListQuerySetMixin(StoryQuerySetMixin):
    def get_queryset(self, project_id):
        stories = super(StoryListQuerySetMixin, self).get_queryset()
        return stories.filter(project__id=project_id)

class StoryVersionListQuerySetMixin(StoryQuerySetBaseMixin):
    def get_queryset(self, story_id):
        if self.request.user.is_superuser:
            return StoryVersion.objects.all()

        try:
            story = Story.objects.filter(id=story_id)
        except Story.DoesNotExist:
            return []

        story = self.user_in_story_filter(story, self.request.user)

        if story.count() == 0:
            return []

        return StoryVersion.objects.all()
<|endoftext|>


<commit_before># Copyright (C) 2014 Chris Richards
#
# The following terms apply to all files associated
# with the software unless explicitly disclaimed in individual files.
#
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors
# and need not follow the licensing terms described here, provided that
# the new terms are clearly indicated on the first page of each file where
# they apply.
#
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
# FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
# ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
# DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
# MODIFICATIONS.

import usb
import usb.legacy

class Aviosys8800(object):
  def __init__(self):
    self.handle = None
    self.dev = None

  def open(self):
    # Find my device - idVendor = 0x067b idProduct = 0x2303
    newDev = usb.core.find(idVendor=0x067b, idProduct=0x2303)
    if newDev is None:
      raise ValueError('USB switch not found')

    newDev.set_configuration()
    # newDev.detach_kernel_driver(0)
    self.dev = usb.legacy.Device(newDev)
    self.handle = self.dev.open()
    # handle.detachKernelDriver(0)
    self.handle.claimInterface(0)

  def close(self):
    self.USB1(0x21,34,2,0,0)
    self.USB1(0x21,34,0,0,0)
    self.handle.releaseInterface()

  def init(self):
    self.USB2(0x40,1,1028.0)
    self.USB2(0x40,1,1028,1)
    self.USB2(0x40,1,1028,32)
    self.USB2(0x40,1,1028,33)
    self.USB2(0x40,1,1028,64)
    self.USB2(0x40,1,1028,65)
    self.USB2(0x40,1,1028,96)
    self.USB2(0x40,1,1028,97)
    self.USB2(0x40,1,1028,128)
    self.USB2(0x40,1,1028,129)
    self.USB2(0x40,1,1028,160)
    self.USB2(0x40,1,1028,161)
    self.USB1(0x40,1,0,1)
    self.USB1(0x40,1,1,0)
    self.USB1(0x40,1,2,68)
    #800
    self.USB1(0,1,1,0,0)
    self.USB1(0x21,32,0,0,7)
    self.USB1(0xc0,1,128,0,2)
    self.USB1(0xc0,1,129,0,2)
    #804
    self.USB1(0x40,1,1,0)
    self.USB1(0x40,1,0,1)
    self.USB1(0x21,34,1,0,0)
    #807
    self.USB1(0xc0,1,128,0,2)
    self.USB1(0xc0,1,129,0,2)
    self.USB1(0x40,1,1,0,0)
    #810
    self.USB1(0x40,1,0,1,0)
    self.USB1(0x21,34,3,0,0)
    self.USB1(0xc0,1,128,0,2)
    self.USB1(0x40,1,0,1,0)
    self.USB1(0xc0,1,128,0,2)
    #815
    self.USB1(0x40,1,0,1,0)
    self.USB1(0x21,32,0,0,7)
    self.USB1(0x40,1,2827,2,0)
    #818
    self.USB1(0x40,1,2313,0,0)
    self.USB1(0x40,1,2056,0,0)
    #820
    self.USB1(0xc0,1,129,0,2)
    self.USB1(0x40,1,1,32)
    self.USB1(0xc0,1,36237,0,4)

  def getStatus(self):
    status = self.USB1(0xc0,1,129,0,2)
    if status[0] == 0x20:
      return False
    if status[0] == 0xA0:
      return True
    raise ValueError('Unrecognised status')

  def turnOn(self):
    self.USB1(0x40,1,1,160)

  def turnOff(self):
    self.USB1(0x40,1,1,32)

  def USB1 (self, utype=0xC0, ureq=1, uvalue=0, uindex=1028, ubytes=0):
    if ubytes != 7:
      status=self.handle.controlMsg(int(utype), int(ureq), int(ubytes),  int(uvalue),int( uindex))
    else:
      ubuffer = 0xB0,0x4,0x0,0x0,0x2,0x7
      status=self.handle.controlMsg(int(utype), int(ureq), ubuffer,  int(uvalue), int(uindex))
    return status

  def USB2 (self, vtype, vreq=1, vvalue=1028, vindex=0, vbytes=0):
    self.USB1(0xc0,1,33924,0,1)
    self.USB1(vtype,vreq,vvalue,vindex,vbytes)
    self.USB1(0xc0,1,33924,0,1)
    self.USB1(0xc0,1,33667,0,1)
    return
<commit_msg>Attributes Lance and StackExchange answer<commit_after># Copyright (C) 2014 Chris Richards
#
# The following terms apply to all files associated
# with the software unless explicitly disclaimed in individual files.
#
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors
# and need not follow the licensing terms described here, provided that
# the new terms are clearly indicated on the first page of each file where
# they apply.
#
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
# FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
# ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
# DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
# MODIFICATIONS.

# With thanks to Lance: http://raspberrypi.stackexchange.com/users/1237/lance
# and this answer on StackExchange: http://raspberrypi.stackexchange.com/a/1685/19199

import usb
import usb.legacy

class Aviosys8800(object):
  def __init__(self):
    self.handle = None
    self.dev = None

  def open(self):
    # Find my device - idVendor = 0x067b idProduct = 0x2303
    newDev = usb.core.find(idVendor=0x067b, idProduct=0x2303)
    if newDev is None:
      raise ValueError('USB switch not found')

    newDev.set_configuration()
    # newDev.detach_kernel_driver(0)
    self.dev = usb.legacy.Device(newDev)
    self.handle = self.dev.open()
    # handle.detachKernelDriver(0)
    self.handle.claimInterface(0)

  def close(self):
    self.USB1(0x21,34,2,0,0)
    self.USB1(0x21,34,0,0,0)
    self.handle.releaseInterface()

  def init(self):
    self.USB2(0x40,1,1028.0)
    self.USB2(0x40,1,1028,1)
    self.USB2(0x40,1,1028,32)
    self.USB2(0x40,1,1028,33)
    self.USB2(0x40,1,1028,64)
    self.USB2(0x40,1,1028,65)
    self.USB2(0x40,1,1028,96)
    self.USB2(0x40,1,1028,97)
    self.USB2(0x40,1,1028,128)
    self.USB2(0x40,1,1028,129)
    self.USB2(0x40,1,1028,160)
    self.USB2(0x40,1,1028,161)
    self.USB1(0x40,1,0,1)
    self.USB1(0x40,1,1,0)
    self.USB1(0x40,1,2,68)
    #800
    self.USB1(0,1,1,0,0)
    self.USB1(0x21,32,0,0,7)
    self.USB1(0xc0,1,128,0,2)
    self.USB1(0xc0,1,129,0,2)
    #804
    self.USB1(0x40,1,1,0)
    self.USB1(0x40,1,0,1)
    self.USB1(0x21,34,1,0,0)
    #807
    self.USB1(0xc0,1,128,0,2)
    self.USB1(0xc0,1,129,0,2)
    self.USB1(0x40,1,1,0,0)
    #810
    self.USB1(0x40,1,0,1,0)
    self.USB1(0x21,34,3,0,0)
    self.USB1(0xc0,1,128,0,2)
    self.USB1(0x40,1,0,1,0)
    self.USB1(0xc0,1,128,0,2)
    #815
    self.USB1(0x40,1,0,1,0)
    self.USB1(0x21,32,0,0,7)
    self.USB1(0x40,1,2827,2,0)
    #818
    self.USB1(0x40,1,2313,0,0)
    self.USB1(0x40,1,2056,0,0)
    #820
    self.USB1(0xc0,1,129,0,2)
    self.USB1(0x40,1,1,32)
    self.USB1(0xc0,1,36237,0,4)

  def getStatus(self):
    status = self.USB1(0xc0,1,129,0,2)
    if status[0] == 0x20:
      return False
    if status[0] == 0xA0:
      return True
    raise ValueError('Unrecognised status')

  def turnOn(self):
    self.USB1(0x40,1,1,160)

  def turnOff(self):
    self.USB1(0x40,1,1,32)

  def USB1 (self, utype=0xC0, ureq=1, uvalue=0, uindex=1028, ubytes=0):
    if ubytes != 7:
      status=self.handle.controlMsg(int(utype), int(ureq), int(ubytes),  int(uvalue),int( uindex))
    else:
      ubuffer = 0xB0,0x4,0x0,0x0,0x2,0x7
      status=self.handle.controlMsg(int(utype), int(ureq), ubuffer,  int(uvalue), int(uindex))
    return status

  def USB2 (self, vtype, vreq=1, vvalue=1028, vindex=0, vbytes=0):
    self.USB1(0xc0,1,33924,0,1)
    self.USB1(vtype,vreq,vvalue,vindex,vbytes)
    self.USB1(0xc0,1,33924,0,1)
    self.USB1(0xc0,1,33667,0,1)
    return
<|endoftext|>


<commit_before>from flask import Flask, render_template, session, redirect, url_for
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)

class NameForm(Form):
    name = StringField('What\'s your name?', validators = [Required()])
    submit = SubmitField('Submit')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

@app.route('/', methods = ['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))

if __name__ == '__main__':
    manager.run()<commit_msg>added flash<commit_after>from flask import Flask, render_template, session, redirect, url_for, flash
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)

class NameForm(Form):
    name = StringField('What\'s your name?', validators = [Required()])
    submit = SubmitField('Submit')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500

@app.route('/', methods = ['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name')
        if old_name is not None and old_name != form.name.data
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        form.name.data = ''
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))

if __name__ == '__main__':
    manager.run()<|endoftext|>


<commit_before>#!/usr/bin/env python3
"""
Generate an eblif file targetting a given pb_type.xml file.
Used for testing a leaf pb_type can be placed and routed with Verilog to
Routing.

Primarily used by the vpr_test_pbtype cmake function (which is automatically part
of v2x_test_both cmake function).
"""

import argparse
import math
import os
import os.path
import subprocess
import sys
import tempfile

from typing import List

import lxml.etree as ET

from lib.flatten import flatten
from lib.pb_type import Port, ports, find_leaf

def blif(name: str, inputs: List[Port], outputs: List[Port]) -> str:
    """Generate a blif for a device with set of input and output ports.

    >>> print(blif('mod', ['A', 'B'], ['C', 'D']))
    .model top
    .inputs A B
    .outputs C D
    .subckt mod A=A B=B C=C D=D
    .cname mod
    .end
    >>> print(blif('mod', [('A', 2)], [('C', 2)]))
    .model top
    .inputs A0 A1
    .outputs C0 C1
    .subckt mod A[0]=A0 A[1]=A1 C[0]=C0 C[1]=C1
    .cname mod
    .end
    """
    inputs = list(flatten(inputs))
    outputs = list(flatten(outputs))

    return """\
.model top
.inputs {inputs}
.outputs {outputs}
.subckt {name} {iomap}
.cname {name}
.end""".format(
        name=name,
        inputs=" ".join(d for s, d in inputs),
        outputs=" ".join(s for d, s in outputs),
        iomap=" ".join("{}={}".format(s, d) for s, d in inputs + outputs),
    )

parser = argparse.ArgumentParser(description=__doc__)

parser.add_argument('--pb_type', '-p', help="""\
pb_type.xml file
""")

parser.add_argument(
    '--output',
    '-o',
    help="""\
Output filename, default '<name>.test.eblif'
"""
)

def main(args):
    args = parser.parse_args(args)

    pbtype_xml = ET.parse(args.pb_type)
    pbtype_xml.xinclude()

    pbtype_leaf = find_leaf(pbtype_xml.getroot())
    assert pbtype_leaf is not None, "Unable to find leaf <pb_type> tag in {}".format(
        args.pb_type
    )

    pbtype_name, clocks, inputs, outputs, carry = ports(pbtype_leaf)
    pbtype_subckt = pbtype_leaf.attrib['blif_model'][len('.subckt '):]
    iname = os.path.basename(args.pb_type)

    outfile = "{}.test.eblif".format(iname)
    if args.output is not None:
        outfile = args.output
    outfile = os.path.abspath(outfile)

    eblif = blif(pbtype_name, inputs, outputs)
    with open(outfile, "w") as f:
        f.write(eblif)

    return 0

if __name__ == "__main__":
    import doctest
    failure_count, test_count = doctest.testmod()
    assert test_count > 0
    assert failure_count == 0, "Doctests failed!"
    sys.exit(main(sys.argv[1:]))
<commit_msg>utils: Support LUTs when generating eblif output.<commit_after>#!/usr/bin/env python3
"""
Generate an eblif file targetting a given pb_type.xml file.
Used for testing a leaf pb_type can be placed and routed with Verilog to
Routing.

Primarily used by the vpr_test_pbtype cmake function (which is automatically part
of v2x_test_both cmake function).
"""

import argparse
import math
import os
import os.path
import subprocess
import sys
import tempfile

from typing import List

import lxml.etree as ET

from lib.flatten import flatten
from lib.pb_type import Port, ports, find_leaf

def blif(
        name: str, clocks: List[Port], inputs: List[Port], outputs: List[Port]
) -> str:
    """Generate an eblif for a subckt with set of input and output ports.

    >>> print(blif('mod', ['A'], ['B'], ['C', 'D']))
    .model top
    .inputs A B
    .outputs C D
    .subckt mod A=A B=B C=C D=D
    .cname mod
    .end
    >>> print(blif('mod', [], [('A', 2)], [('C', 2)]))
    .model top
    .inputs A0 A1
    .outputs C0 C1
    .subckt mod A[0]=A0 A[1]=A1 C[0]=C0 C[1]=C1
    .cname mod
    .end
    """
    inputs = list(flatten(clocks))+list(flatten(inputs))
    outputs = list(flatten(outputs))

    return """\
.model top
.inputs {inputs}
.outputs {outputs}
.subckt {name} {iomap}
.cname {name}
.end""".format(
        name=name,
        inputs=" ".join(d for s, d in inputs),
        outputs=" ".join(s for d, s in outputs),
        iomap=" ".join("{}={}".format(s, d) for s, d in inputs + outputs),
    )

def lut(
        name: str, clocks: List[Port], inputs: List[Port], outputs: List[Port]
) -> str:
    """Generate am eblif for a lut with set of input and output ports.

    >>> print(lut('mod', [], ['A', 'B'], ['D']))
    .model top
    .inputs A B
    .outputs D
    .names A B D
    .end
    >>> print(lut('mod', [], [('A', 2)], [('D', 1)]))
    .model top
    .inputs A0 A1
    .outputs D
    .names A0 A1 D
    .end
    """
    assert not clocks, "LUTs don't have clocks: {}".format(clocks)
    inputs = list(flatten(inputs))
    outputs = list(flatten(outputs))

    assert len(outputs) == 1

    return """\
.model top
.inputs {inputs}
.outputs {outputs}
.names {iomap}
.end""".format(
        inputs=" ".join(d for s, d in inputs),
        outputs=" ".join(s for d, s in outputs),
        iomap=" ".join("{}".format(d) for s, d in inputs + outputs),
    )

parser = argparse.ArgumentParser(description=__doc__)

parser.add_argument('--pb_type', '-p', help="""\
pb_type.xml file
""")

parser.add_argument(
    '--output',
    '-o',
    help="""\
Output filename, default '<name>.test.eblif'
"""
)

def main(args):
    args = parser.parse_args(args)

    pbtype_xml = ET.parse(args.pb_type)
    pbtype_xml.xinclude()

    pbtype_leaf = find_leaf(pbtype_xml.getroot())
    assert pbtype_leaf is not None, "Unable to find leaf <pb_type> tag in {}".format(
        args.pb_type
    )

    blif_model, clocks, inputs, outputs, carry = ports(pbtype_leaf)
    blif_model = pbtype_leaf.attrib['blif_model']

    if 'subckt' in blif_model:
        name = blif_model[len('.subckt '):]
        outputf = blif
    elif '.names' in blif_model:
        name = 'lut{}'.format(len(inputs))
        outputf = lut
    else:
        raise TypeError("Unknown blif_model {}".format(blif_model))

    iname = os.path.basename(args.pb_type)

    outfile = "{}.test.eblif".format(iname)
    if args.output is not None:
        outfile = args.output
    outfile = os.path.abspath(outfile)

    eblif = outputf(name, clocks, inputs, outputs)
    with open(outfile, "w") as f:
        f.write(eblif)

    return 0

if __name__ == "__main__":
    import doctest
    failure_count, test_count = doctest.testmod()
    assert test_count > 0
    assert failure_count == 0, "Doctests failed!"
    sys.exit(main(sys.argv[1:]))
<|endoftext|>


<commit_before>from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django_extensions.db.fields import UUIDField
from tools.short import make_https
from tasks.models import Tasks

class OrganizationManager(models.Manager):
    """Organization manager"""

    def get_with_user(self, name, user):
        """Get and add user if need"""
        organisation = self.get_or_create(name=name)[0]
        if not organisation.users.filter(id=user.id).exists():
            organisation.users.add(user)
        return organisation

class Organization(models.Model):
    """Organization model"""
    name = models.CharField(max_length=300, verbose_name=_('name'))
    users = models.ManyToManyField(
        User, related_name='organizations', verbose_name=_('users'),
    )

    objects = OrganizationManager()

    class Meta:
        verbose_name = _('Organization')
        verbose_name_plural = _('Organization')

    def __unicode__(self):
        return self.name

class ProjectManager(models.Manager):
    """Project manager"""

    def update_user_projects(self, user):
        """Alias for get_or_create_for_user but without return"""
        self.get_or_create_for_user(user)

    def get_or_create_for_user(self, user):
        """Get or create for user"""
        github_user = user.github.get_user()
        projects = [self._get_or_create_and_update(
            repo, user, str(github_user.avatar_url),
        ) for repo in github_user.get_repos('owner')]
        projects += self._get_for_user_organizations(
            user, github_user,
        )
        self.filter(owner=user).exclude(id__in=projects).delete()
        return self.get_for_user(user).order_by('-last_use')

    def _get_for_user_organizations(self, user, github_user):
        """Get for user organizations"""
        project_ids = []
        for github_organization in github_user.get_orgs():
            organization = Organization.objects.get_with_user(
                github_organization.login, user,
            )
            avatar = str(github_organization.avatar_url)
            project_ids += [self._get_or_create_and_update(
                repo, user, avatar, organization,
            ) for repo in github_organization.get_repos('owner')]
        return project_ids

    def _get_or_create_and_update(self, repo, user, icon, organization=None):
        """Get or create and update"""
        try:
            project = Project.objects.get(
                name=repo.full_name,
                url=repo.url,
                is_private=repo.private,
            )
        except Project.DoesNotExist:
            project = Project(
                owner=user,
                name=repo.full_name,
                url=repo.url,
                is_private=repo.private,
            )
        project.icon = icon
        project.save()
        return project.id

    def get_enabled_for_user(self, user):
        """Get enabled projects available for user"""
        return self.get_for_user(user).filter(is_enabled=True)

    def get_for_user(self, user):
        """Get for user"""
        return self.filter(
            Q(owner=user) | Q(organization__users=user)
        ).distinct()

class Project(models.Model):
    """Github project"""
    owner = models.ForeignKey(User, verbose_name=_('owner'))
    name = models.CharField(max_length=300, verbose_name=_('name'))
    url = models.URLField(verbose_name=_('url'))
    is_enabled = models.BooleanField(
        default=False, verbose_name=_('is enabled'),
    )
    last_use = models.DateTimeField(
        auto_now_add=True, verbose_name=_('last use'),
    )
    badge_url = models.CharField(
        blank=True, null=True,
        max_length=300, verbose_name=_('badge url'),
    )
    token = UUIDField(null=True, auto=True, verbose_name=_('token'))
    is_private = models.BooleanField(
        default=False, verbose_name=_('is private'),
    )
    icon = models.CharField(
        blank=True, null=True, max_length=300, verbose_name=_('icon'),
    )
    organization = models.ForeignKey(
        Organization, blank=True, null=True, verbose_name=_('organization'),
    )

    objects = ProjectManager()

    class Meta:
        verbose_name = _('Project')
        verbose_name_plural = _('Projects')
        ordering = ('-last_use', 'name')
        get_latest_by = ('-last_use',)

    def __unicode__(self):
        return self.name

    def get_badge_url(self, **kwargs):
        """Get or create https badge url"""
        if not self.badge_url:
            local_url = reverse('projects_badge', args=(self.name,))
            local_url += '?{}'.format('&'.join(
                '{}={}'.format(key, value) for key, value in kwargs.items(),
            ))
            self.badge_url = make_https(local_url)
            self.save()
        return self.badge_url

    def can_access(self, user):
        """Can access"""
        if self.is_private:
            if self.organization:
                if self.organization.users.filter(
                    id=user.id,
                ).exists():
                    return True
            return self.owner == user
        else:
            return True

    def get_allowed_users(self):
        """Get allowed users"""
        if self.organization:
            users = list(self.organization.users.all())
        else:
            users = []
        return [self.owner] + users

    @property
    def branches(self):
        """Get project branches"""
        return Tasks.find({'project': self.name}).distinct('commit.branch')

    @property
    def repo(self):
        """Github repo of project with read access"""
        if not hasattr(self, '_repo'):
            self._repo = self.owner.github.get_repo(self.name)
        return self._repo
<commit_msg>Set organization on project update<commit_after>from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django_extensions.db.fields import UUIDField
from tools.short import make_https
from tasks.models import Tasks

class OrganizationManager(models.Manager):
    """Organization manager"""

    def get_with_user(self, name, user):
        """Get and add user if need"""
        organisation = self.get_or_create(name=name)[0]
        if not organisation.users.filter(id=user.id).exists():
            organisation.users.add(user)
        return organisation

class Organization(models.Model):
    """Organization model"""
    name = models.CharField(max_length=300, verbose_name=_('name'))
    users = models.ManyToManyField(
        User, related_name='organizations', verbose_name=_('users'),
    )

    objects = OrganizationManager()

    class Meta:
        verbose_name = _('Organization')
        verbose_name_plural = _('Organization')

    def __unicode__(self):
        return self.name

class ProjectManager(models.Manager):
    """Project manager"""

    def update_user_projects(self, user):
        """Alias for get_or_create_for_user but without return"""
        self.get_or_create_for_user(user)

    def get_or_create_for_user(self, user):
        """Get or create for user"""
        github_user = user.github.get_user()
        projects = [self._get_or_create_and_update(
            repo, user, str(github_user.avatar_url),
        ) for repo in github_user.get_repos('owner')]
        projects += self._get_for_user_organizations(
            user, github_user,
        )
        self.filter(owner=user).exclude(id__in=projects).delete()
        return self.get_for_user(user).order_by('-last_use')

    def _get_for_user_organizations(self, user, github_user):
        """Get for user organizations"""
        project_ids = []
        for github_organization in github_user.get_orgs():
            organization = Organization.objects.get_with_user(
                github_organization.login, user,
            )
            avatar = str(github_organization.avatar_url)
            project_ids += [self._get_or_create_and_update(
                repo, user, avatar, organization,
            ) for repo in github_organization.get_repos('owner')]
        return project_ids

    def _get_or_create_and_update(self, repo, user, icon, organization=None):
        """Get or create and update"""
        try:
            project = Project.objects.get(
                name=repo.full_name,
                url=repo.url,
                is_private=repo.private,
            )
        except Project.DoesNotExist:
            project = Project(
                owner=user,
                name=repo.full_name,
                url=repo.url,
                is_private=repo.private,
            )
        project.organization = organization
        project.icon = icon
        project.save()
        return project.id

    def get_enabled_for_user(self, user):
        """Get enabled projects available for user"""
        return self.get_for_user(user).filter(is_enabled=True)

    def get_for_user(self, user):
        """Get for user"""
        return self.filter(
            Q(owner=user) | Q(organization__users=user)
        ).distinct()

class Project(models.Model):
    """Github project"""
    owner = models.ForeignKey(User, verbose_name=_('owner'))
    name = models.CharField(max_length=300, verbose_name=_('name'))
    url = models.URLField(verbose_name=_('url'))
    is_enabled = models.BooleanField(
        default=False, verbose_name=_('is enabled'),
    )
    last_use = models.DateTimeField(
        auto_now_add=True, verbose_name=_('last use'),
    )
    badge_url = models.CharField(
        blank=True, null=True,
        max_length=300, verbose_name=_('badge url'),
    )
    token = UUIDField(null=True, auto=True, verbose_name=_('token'))
    is_private = models.BooleanField(
        default=False, verbose_name=_('is private'),
    )
    icon = models.CharField(
        blank=True, null=True, max_length=300, verbose_name=_('icon'),
    )
    organization = models.ForeignKey(
        Organization, blank=True, null=True, verbose_name=_('organization'),
    )

    objects = ProjectManager()

    class Meta:
        verbose_name = _('Project')
        verbose_name_plural = _('Projects')
        ordering = ('-last_use', 'name')
        get_latest_by = ('-last_use',)

    def __unicode__(self):
        return self.name

    def get_badge_url(self, **kwargs):
        """Get or create https badge url"""
        if not self.badge_url:
            local_url = reverse('projects_badge', args=(self.name,))
            local_url += '?{}'.format('&'.join(
                '{}={}'.format(key, value) for key, value in kwargs.items(),
            ))
            self.badge_url = make_https(local_url)
            self.save()
        return self.badge_url

    def can_access(self, user):
        """Can access"""
        if self.is_private:
            if self.organization:
                if self.organization.users.filter(
                    id=user.id,
                ).exists():
                    return True
            return self.owner == user
        else:
            return True

    def get_allowed_users(self):
        """Get allowed users"""
        if self.organization:
            users = list(self.organization.users.all())
        else:
            users = []
        return [self.owner] + users

    @property
    def branches(self):
        """Get project branches"""
        return Tasks.find({'project': self.name}).distinct('commit.branch')

    @property
    def repo(self):
        """Github repo of project with read access"""
        if not hasattr(self, '_repo'):
            self._repo = self.owner.github.get_repo(self.name)
        return self._repo
<|endoftext|>


<commit_before>print("Hello")
<commit_msg>Second Commit<commit_after>def greeting(msg):
	print(msg)

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


<commit_before>from flask import Flask , render_template , request
app=Flask(__name__)

@app.route('/', methods=['GET','POST'])
def index():
    if request.method == 'GET':
        return render_template('techstitution.html')
    elif request.method == 'POST':
	return render_template('techstituion.html', error=error)

if __name__ == "__main__":
    app.run(debug=True,
        host="0.0.0.0",
        port=5555
)

<commit_msg>Delete hello.py<commit_after><|endoftext|>


<commit_before>import os
from flask import Flask, request

import astropy
print astropy.__version__

app = Flask(__name__)

@app.route('/')
def hello():
    return ""

if __name__ == '__main__':
    app.run()

<commit_msg>changed color<commit_after>import os
from flask import Flask, request

import astropy
print astropy.__version__

app = Flask(__name__)

@app.route('/')
def hello():
    return ""

if __name__ == '__main__':
    app.run()

<|endoftext|>


<commit_before>"""
Created on 18 Sep 2016

@author: Bruno Beloff (bruno.beloff@southcoastscience.com)c
"""

# import sys

from collections import OrderedDict

from scs_core.data.datum import Datum
from scs_core.data.json import JSONable

# --------------------------------------------------------------------------------------------------------------------

class A4Datum(JSONable):
    """
    classdocs
    """

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct(cls, calib, baseline, tc, temp, we_v, ae_v, no2_cnc=None):
        if calib is None or tc is None:
            return A4Datum(we_v, ae_v)

        # print("A4Datum: calib:%s baseline:%s tc:%s temp:%f we_v:%f ae_v:%f x_sens_sample:%s" %
        #       (calib, baseline, tc, temp, we_v, ae_v, x_sens_sample), file=sys.stderr)

        # weC...
        we_c = cls.__we_c(calib, tc, temp, we_v, ae_v)

        if we_c is None:
            return A4Datum(we_v, ae_v)

        if no2_cnc:
            we_c -= cls.__reverse_we_c(calib.we_no2_x_sens_mv, no2_cnc)

        # cnc...
        cnc = cls.__cnc(calib.we_sens_mv, we_c)

        baselined_cnc = cnc + baseline.offset

        return A4Datum(we_v, ae_v, we_c, baselined_cnc)

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def __we_c(cls, calib, tc, temp, we_v, ae_v):
        """
        Compute weC from sensor temperature compensation of weV, aeV
        """
        we_t = we_v - (float(calib.we_elc_mv) / 1000.0)
        ae_t = ae_v - (float(calib.ae_elc_mv) / 1000.0)

        we_c = tc.correct(calib, temp, we_t, ae_t)

        # print("A4Datum__we_c: we_t:%f ae_t:%f we_c:%s" % (we_t, ae_t, we_c), file=sys.stderr)

        return we_c

    @classmethod
    def __cnc(cls, sens_mv, we_c):
        """
        Compute cnc from weC (using primary sensitivity)
        """
        if we_c is None:
            return None

        cnc = (we_c * 1000.0) / sens_mv

        # print("A4Datum__cnc: we_c:%s cnc:%f" % (we_c, cnc), file=sys.stderr)

        return cnc

    @classmethod
    def __reverse_we_c(cls, sens_mv, cnc):
        """
        Compute weC from cnc (using cross-sensitivity)
        """
        we_c = (cnc * sens_mv) / 1000.0

        # print("__reverse_we_c: we_c:%s cnc:%f" % (we_c, cnc), file=sys.stderr)

        return we_c

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, we_v, ae_v, we_c=None, cnc=None):
        """
        Constructor
        """
        self.__we_v = Datum.float(we_v, 6)        # uncorrected working electrode voltage       V
        self.__ae_v = Datum.float(ae_v, 6)        # uncorrected auxiliary electrode voltage     V

        self.__we_c = Datum.float(we_c, 6)        # corrected working electrode voltage         V
        self.__cnc = Datum.float(cnc, 1)          # gas concentration                           ppb

    # ----------------------------------------------------------------------------------------------------------------

    def as_json(self):
        jdict = OrderedDict()

        jdict['weV'] = self.we_v
        jdict['aeV'] = self.ae_v

        jdict['weC'] = self.we_c                 # may be None
        jdict['cnc'] = self.cnc                  # may be None

        return jdict

    # ----------------------------------------------------------------------------------------------------------------

    @property
    def we_v(self):
        return self.__we_v

    @property
    def ae_v(self):
        return self.__ae_v

    @property
    def we_c(self):
        return self.__we_c

    @property
    def cnc(self):
        return self.__cnc

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "A4Datum:{we_v:%0.6f, ae_v:%0.6f, we_c:%s, cnc:%s}" % (self.we_v, self.ae_v, self.we_c, self.cnc)
<commit_msg>Returned led top-level script to scs_dev.<commit_after>"""
Created on 18 Sep 2016

@author: Bruno Beloff (bruno.beloff@southcoastscience.com)c
"""

# import sys

from collections import OrderedDict

from scs_core.data.datum import Datum
from scs_core.data.json import JSONable

# TODO: check whether formatting is required - "NO2": {"weV": 0.288567, "aeV": 0.306942, "weC": -7.5e-05, "cnc": -0.4}

# --------------------------------------------------------------------------------------------------------------------

class A4Datum(JSONable):
    """
    classdocs
    """

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def construct(cls, calib, baseline, tc, temp, we_v, ae_v, no2_cnc=None):
        if calib is None or tc is None:
            return A4Datum(we_v, ae_v)

        # print("A4Datum: calib:%s baseline:%s tc:%s temp:%f we_v:%f ae_v:%f x_sens_sample:%s" %
        #       (calib, baseline, tc, temp, we_v, ae_v, x_sens_sample), file=sys.stderr)

        # weC...
        we_c = cls.__we_c(calib, tc, temp, we_v, ae_v)

        if we_c is None:
            return A4Datum(we_v, ae_v)

        if no2_cnc:
            we_c -= cls.__reverse_we_c(calib.we_no2_x_sens_mv, no2_cnc)

        # cnc...
        cnc = cls.__cnc(calib.we_sens_mv, we_c)

        baselined_cnc = cnc + baseline.offset

        return A4Datum(we_v, ae_v, we_c, baselined_cnc)

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def __we_c(cls, calib, tc, temp, we_v, ae_v):
        """
        Compute weC from sensor temperature compensation of weV, aeV
        """
        we_t = we_v - (float(calib.we_elc_mv) / 1000.0)
        ae_t = ae_v - (float(calib.ae_elc_mv) / 1000.0)

        we_c = tc.correct(calib, temp, we_t, ae_t)

        # print("A4Datum__we_c: we_t:%f ae_t:%f we_c:%s" % (we_t, ae_t, we_c), file=sys.stderr)

        return we_c

    @classmethod
    def __cnc(cls, sens_mv, we_c):
        """
        Compute cnc from weC (using primary sensitivity)
        """
        if we_c is None:
            return None

        cnc = (we_c * 1000.0) / sens_mv

        # print("A4Datum__cnc: we_c:%s cnc:%f" % (we_c, cnc), file=sys.stderr)

        return cnc

    @classmethod
    def __reverse_we_c(cls, sens_mv, cnc):
        """
        Compute weC from cnc (using cross-sensitivity)
        """
        we_c = (cnc * sens_mv) / 1000.0

        # print("__reverse_we_c: we_c:%s cnc:%f" % (we_c, cnc), file=sys.stderr)

        return we_c

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, we_v, ae_v, we_c=None, cnc=None):
        """
        Constructor
        """
        self.__we_v = Datum.float(we_v, 6)        # uncorrected working electrode voltage       V
        self.__ae_v = Datum.float(ae_v, 6)        # uncorrected auxiliary electrode voltage     V

        self.__we_c = Datum.float(we_c, 6)        # corrected working electrode voltage         V
        self.__cnc = Datum.float(cnc, 1)          # gas concentration                           ppb

    # ----------------------------------------------------------------------------------------------------------------

    def as_json(self):
        jdict = OrderedDict()

        jdict['weV'] = self.we_v
        jdict['aeV'] = self.ae_v

        jdict['weC'] = self.we_c                 # may be None
        jdict['cnc'] = self.cnc                  # may be None

        return jdict

    # ----------------------------------------------------------------------------------------------------------------

    @property
    def we_v(self):
        return self.__we_v

    @property
    def ae_v(self):
        return self.__ae_v

    @property
    def we_c(self):
        return self.__we_c

    @property
    def cnc(self):
        return self.__cnc

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "A4Datum:{we_v:%0.6f, ae_v:%0.6f, we_c:%s, cnc:%s}" % (self.we_v, self.ae_v, self.we_c, self.cnc)
<|endoftext|>


<commit_before>from fasta import *

__version__ = '0.1.0'
<commit_msg>Clean up imports<commit_after>from fasta import Fasta, FastaIndex, FastaRecord

__version__ = '0.1.0'
<|endoftext|>


<commit_before>import pygame
import spyral
import copy

class Image(object):
    """
    The image is the basic drawable item in spyral. They can be created
    either by loading from common file formats, or by creating a new
    image and using some of the draw methods.

    | *size*: If *size* is passed, creates a new blank image of
      that size to draw on. Size should be an iterable with two
      elements
    | *filename*: If *filename* is set, the file with that name
      is loaded.
    """

    def __init__(self, filename = None, size = None):
        if size is not None and filename is not None:
            raise ValueError("Must specify exactly one of size and filename.")
        if size is None and filename is None:
            raise ValueError("Must specify exactly one of size and filename.")

        if size is not None:
            self._surf = pygame.Surface((int(size[0]), int(size[1])), pygame.SRCALPHA, 32)
            self._name = None
        else:
            self._surf = pygame.image.load(filename).convert_alpha()
            self._name = filename

    def get_width(self):
        return self._surf.get_width()

    def get_height(self):
        return self._surf.get_height()

    def get_size(self):
        """
        Returns the (width, height) of the image.
        """
        return self._surf.get_size()

    def fill(self, color):
        """
        Fills the entire surface with the specified color.
        """
        color = spyral.color._determine(color)
        self._surf.fill(color)

    def draw_rect(self, color, position, size, border_width = 0, anchor= 'topleft'):
        """
        Draws a rectangle on this surface. position = (x, y) specifies
        the top-left corner, and size = (width, height) specifies the
        width and height of the rectangle. border_width specifies the
        width of the border to draw. If it is 0, the rectangle is
        filled with the color specified. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        # We'll try to make sure that everything is okay later

        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor, size)
        pygame.draw.rect(self._surf, color, (position + offset, size), border_width)

    def draw_lines(self, color, points, width = 1, closed = False):
        """
        Draws a series of connected lines on a surface, with the
        vertices specified by points. This does not draw any sort of
        end caps on lines.

        If closed is True, the first and last point will be connected.
        If closed is True and width is 0, the shape will be filled.
        """
        color = spyral.color._determine(color)
        pygame.draw.aalines(self._surf, color, closed, points)

    def draw_circle(self, color, position, radius, width = 0, anchor= 'topleft'):
        """
        Draws a circle on this surface. position = (x, y) specifies
        the center of the circle, and radius the radius. If width is
        0, the circle is filled. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor)
        pygame.draw.circle(self._surf, color, position + offset, radius, width)

    def draw_ellipse(self, color, position, size, border_width = 0, anchor= 'topleft'):
        """
        Draws an ellipse on this surface. position = (x, y) specifies
        the top-left corner, and size = (width, height) specifies the
        width and height of the ellipse. border_width specifies the
        width of the border to draw. If it is 0, the ellipse is
        filled with the color specified. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        # We'll try to make sure that everything is okay later

        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor, size)
        pygame.draw.ellipse(self._surf, color, (position + offset, size), border_width)

    def draw_point(self, color, position, anchor= 'topleft'):
        """
        Draws a point on this surface. position = (x, y) specifies
        the position of the point. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor)
        self._surf.set_at(position + offset, color)

    def draw_image(self, image, position = (0, 0), anchor= 'topleft'):
        """
        Draws another image onto this one at the specified position. The anchor
        parameter is an :ref:`anchor position <anchors>`.
        """
        offset = self._calculate_offset(anchor, image._surf.get_size())
        self._surf.blit(image._surf, position + offset)

    def rotate(self, angle):
        """
        Rotates the image by *angle* degrees clockwise. This may change
        the image dimensions if the angle is not a multiple of 90.

        Successive rotations degrate image quality. Save a copy of the
        original if you plan to do many rotations.
        """
        self._surf = pygame.transform.rotate(self._surf, angle).convert_alpha()

    def scale(self, size):
        """
        Scales the image to the destination size.
        """
        self._surf = pygame.transform.smoothscale(self._surf, size).convert_alpha()

    def flip(self, xbool, ybool):
        """
        Flips the image horizontally, vertically, or both.
        """
        self._surf = pygame.transform.flip(self._surf, xbool, ybool).convert_alpha()

    def copy(self):
        """
        Returns a copy of this image that can be changed while preserving the
        original.
        """
        new = copy.copy(self)
        new._surf = self._surf.copy()
        return new

    def crop(self, position, size):
        """
        Removes the edges of an image, keeping the internal rectangle specified
        by position and size.
        """
        new = pygame.Surface((int(size[0]), int(size[1])), pygame.SRCALPHA, 32)
        new.blit(self._surf, (0,0), (position, size))
        self._surf = new

    def _calculate_offset(self, anchor_type, size = (0,0)):
        w, h = self._surf.get_size()
        w2, h2 = size
        a = anchor_type

        if a == 'topleft':
            return spyral.Vec2D(0, 0)
        elif a == 'topright':
            return spyral.Vec2D(w - w2, 0)
        elif a == 'midtop':
            return spyral.Vec2D( (w - w2) / 2., 0)
        elif a == 'bottomleft':
            return spyral.Vec2D(0, h - h2)
        elif a == 'bottomright':
            return spyral.Vec2D(w - w2, h - h2)
        elif a == 'midbottom':
            return spyral.Vec2D((w - w2) / 2., h - h2)
        elif a == 'midleft':
            return spyral.Vec2D(0, (h - h2) / 2.)
        elif a == 'midright':
            return spyral.Vec2D(w - w2, (h - h2) / 2.)
        elif a == 'center':
            return spyral.Vec2D((w - w2) / 2., (h - h2) / 2.)
        else:
            return spyral.Vec2D(a) - spyral.Vec2D(w2, h2)
<commit_msg>Minor image documentation update.<commit_after>import pygame
import spyral
import copy

class Image(object):
    """
    The image is the basic drawable item in spyral. They can be created
    either by loading from common file formats, or by creating a new
    image and using some of the draw methods. Images are not drawn on
    their own, they are placed as the *image* attribute on Sprites to
    be drawn.

    | *size*: If *size* is passed, creates a new blank image of
      that size to draw on. Size should be an iterable with two
      elements
    | *filename*: If *filename* is set, the file with that name
      is loaded.
    """

    def __init__(self, filename = None, size = None):
        if size is not None and filename is not None:
            raise ValueError("Must specify exactly one of size and filename.")
        if size is None and filename is None:
            raise ValueError("Must specify exactly one of size and filename.")

        if size is not None:
            self._surf = pygame.Surface((int(size[0]), int(size[1])), pygame.SRCALPHA, 32)
            self._name = None
        else:
            self._surf = pygame.image.load(filename).convert_alpha()
            self._name = filename

    def get_width(self):
        return self._surf.get_width()

    def get_height(self):
        return self._surf.get_height()

    def get_size(self):
        """
        Returns the (width, height) of the image.
        """
        return self._surf.get_size()

    def fill(self, color):
        """
        Fills the entire surface with the specified color.
        """
        color = spyral.color._determine(color)
        self._surf.fill(color)

    def draw_rect(self, color, position, size, border_width = 0, anchor= 'topleft'):
        """
        Draws a rectangle on this surface. position = (x, y) specifies
        the top-left corner, and size = (width, height) specifies the
        width and height of the rectangle. border_width specifies the
        width of the border to draw. If it is 0, the rectangle is
        filled with the color specified. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        # We'll try to make sure that everything is okay later

        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor, size)
        pygame.draw.rect(self._surf, color, (position + offset, size), border_width)

    def draw_lines(self, color, points, width = 1, closed = False):
        """
        Draws a series of connected lines on a surface, with the
        vertices specified by points. This does not draw any sort of
        end caps on lines.

        If closed is True, the first and last point will be connected.
        If closed is True and width is 0, the shape will be filled.
        """
        color = spyral.color._determine(color)
        pygame.draw.aalines(self._surf, color, closed, points)

    def draw_circle(self, color, position, radius, width = 0, anchor= 'topleft'):
        """
        Draws a circle on this surface. position = (x, y) specifies
        the center of the circle, and radius the radius. If width is
        0, the circle is filled. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor)
        pygame.draw.circle(self._surf, color, position + offset, radius, width)

    def draw_ellipse(self, color, position, size, border_width = 0, anchor= 'topleft'):
        """
        Draws an ellipse on this surface. position = (x, y) specifies
        the top-left corner, and size = (width, height) specifies the
        width and height of the ellipse. border_width specifies the
        width of the border to draw. If it is 0, the ellipse is
        filled with the color specified. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        # We'll try to make sure that everything is okay later

        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor, size)
        pygame.draw.ellipse(self._surf, color, (position + offset, size), border_width)

    def draw_point(self, color, position, anchor= 'topleft'):
        """
        Draws a point on this surface. position = (x, y) specifies
        the position of the point. The anchor parameter is an :ref:`anchor
        position <anchors>`.
        """
        color = spyral.color._determine(color)
        offset = self._calculate_offset(anchor)
        self._surf.set_at(position + offset, color)

    def draw_image(self, image, position = (0, 0), anchor= 'topleft'):
        """
        Draws another image onto this one at the specified position. The anchor
        parameter is an :ref:`anchor position <anchors>`.
        """
        offset = self._calculate_offset(anchor, image._surf.get_size())
        self._surf.blit(image._surf, position + offset)

    def rotate(self, angle):
        """
        Rotates the image by *angle* degrees clockwise. This may change
        the image dimensions if the angle is not a multiple of 90.

        Successive rotations degrate image quality. Save a copy of the
        original if you plan to do many rotations.
        """
        self._surf = pygame.transform.rotate(self._surf, angle).convert_alpha()

    def scale(self, size):
        """
        Scales the image to the destination size.
        """
        self._surf = pygame.transform.smoothscale(self._surf, size).convert_alpha()

    def flip(self, xbool, ybool):
        """
        Flips the image horizontally, vertically, or both.
        """
        self._surf = pygame.transform.flip(self._surf, xbool, ybool).convert_alpha()

    def copy(self):
        """
        Returns a copy of this image that can be changed while preserving the
        original.
        """
        new = copy.copy(self)
        new._surf = self._surf.copy()
        return new

    def crop(self, position, size):
        """
        Removes the edges of an image, keeping the internal rectangle specified
        by position and size.
        """
        new = pygame.Surface((int(size[0]), int(size[1])), pygame.SRCALPHA, 32)
        new.blit(self._surf, (0,0), (position, size))
        self._surf = new

    def _calculate_offset(self, anchor_type, size = (0,0)):
        w, h = self._surf.get_size()
        w2, h2 = size
        a = anchor_type

        if a == 'topleft':
            return spyral.Vec2D(0, 0)
        elif a == 'topright':
            return spyral.Vec2D(w - w2, 0)
        elif a == 'midtop':
            return spyral.Vec2D( (w - w2) / 2., 0)
        elif a == 'bottomleft':
            return spyral.Vec2D(0, h - h2)
        elif a == 'bottomright':
            return spyral.Vec2D(w - w2, h - h2)
        elif a == 'midbottom':
            return spyral.Vec2D((w - w2) / 2., h - h2)
        elif a == 'midleft':
            return spyral.Vec2D(0, (h - h2) / 2.)
        elif a == 'midright':
            return spyral.Vec2D(w - w2, (h - h2) / 2.)
        elif a == 'center':
            return spyral.Vec2D((w - w2) / 2., (h - h2) / 2.)
        else:
            return spyral.Vec2D(a) - spyral.Vec2D(w2, h2)
<|endoftext|>


<commit_before>import json
from io import StringIO
from typing import List, Dict, Any
import ui
import requests
from toolz import pluck
import pytablewriter

BASE_PATENT ='http://www.patentsview.org/api/patents/query'
BASE_ASSIGNEE = 'http://www.patentsview.org/api/assignees/query'

def make_query(query: str, fields: List[str], options: Dict[str, Any]) -> str:
    payload = ''.join(['q=', query,
                       '&f=', json.dumps(fields),
                       '&o=', json.dumps(options)])
    return payload

def get_info(payload: str, base=BASE_PATENT) -> Any:
    r = requests.get(BASE_PATENT, params=payload)
    if r.status_code == requests.codes.ok:
        return r
    else:
        r.raise_for_status()

def get_output(fields: List[str], response: Any) -> List[str]:
    patents = response['patents']
    return list(pluck(fields, patents))

def formated_output(fields: List[str], raw_output: List[str]) -> str:
    writer = pytablewriter.HtmlTableWriter()
    html_begin = '<!DOCTYPE HTML>\n\n\n'
    html_end = '\n\n'
    writer.table_name = 'Query Output\n'
    writer.header_list = fields
    writer.value_matrix = raw_output
    with StringIO() as f:
        f.write(html_begin)
        writer.stream = f
        writer.write_table()
        f.write(html_end)
        html_text = f.getvalue()
    return html_text

def input2query(queryfield: str, condition: str, value: str) -> Dict[str, Dict[str, str]]:
    return {condition:{queryfield:value}}

def join_queries(queries, join_condition='_and'):
    return {join_condition:queries}

if __name__ == '__main__':
#    query = {'_and': [{'_gte':{'patent_date':'2014-04-01'}}, {'_contains':{'assignee_organization':'KEMET'}}]}
    query1 = input2query('assignee_organization', '_contains', 'KEMET')
    query2 = input2query('patent_date', '_gte', '2014-04-01')
    query = join_queries([query1, query2], join_condition='_and')
    print(query)
    fields = ['patent_number', 'patent_title', 'patent_date']
    options = {'per_page':50}
    payload = make_query(query, fields, options)
    print('Query String\n', payload, '\n')
    r = get_info(payload)
    print('Encoded URL\n', r.url, '\n')
    print('Status Code\n', r.status_code, '\n')
    print('****Response****', '\n', r.json(), '\n\n')
    raw_output = get_output(fields, r.json())
    html_text = formated_output(fields, raw_output)
    v = ui.View()
    v.name = 'Test Web'
    web = ui.WebView()
    v.add_subview(web)
    web.height = 1024
    web.width = 720
    web.load_html(html_text)
    v.present('fullscreen')
<commit_msg>added input2output and removed some unused code<commit_after>import json
from io import StringIO
from typing import List, Dict, Any
import ui
import requests
from toolz import pluck
import pytablewriter
from outputviewcontroller import viewoutput

BASE_PATENT ='http://www.patentsview.org/api/patents/query'
BASE_ASSIGNEE = 'http://www.patentsview.org/api/assignees/query'

def make_query(query: str, fields: List[str], options: Dict[str, Any]) -> str:
    payload = ''.join(['q=', query,
                       '&f=', json.dumps(fields),
                       '&o=', json.dumps(options)])
    return payload

def get_info(payload: str, base=BASE_PATENT) -> Any:
    r = requests.get(BASE_PATENT, params=payload)
    if r.status_code == requests.codes.ok:
        return r
    else:
        r.raise_for_status()

def get_output(fields: List[str], response: Any) -> List[str]:
    patents = response['patents']
    return list(pluck(fields, patents))

def formated_output(fields: List[str], raw_output: List[str]) -> str:
    writer = pytablewriter.HtmlTableWriter()
    html_begin = '<!DOCTYPE HTML>\n\n\n'
    html_end = '\n\n'
    writer.table_name = 'Query Output\n'
    writer.header_list = fields
    writer.value_matrix = raw_output
    with StringIO() as f:
        f.write(html_begin)
        writer.stream = f
        writer.write_table()
        f.write(html_end)
        html_text = f.getvalue()
    return html_text

def input2output(query):
    fields = ['patent_number', 'patent_title', 'patent_date']
    options = {'per_page':50}
    payload = make_query(query, fields, options)
    print('Query String\n', payload, '\n')
    r = get_info(payload)
    print('Encoded URL\n', r.url, '\n')
    print('Status Code\n', r.status_code, '\n')
    print('****Response****', '\n', r.json(), '\n\n')
    raw_output = get_output(fields, r.json())
    html_text = formated_output(fields, raw_output)
    viewoutput(html_text)

if __name__ == '__main__':
    fields = ['patent_number', 'patent_title', 'patent_date']
    options = {'per_page':50}
    payload = make_query(query, fields, options)
    print('Query String\n', payload, '\n')
    r = get_info(payload)
    print('Encoded URL\n', r.url, '\n')
    print('Status Code\n', r.status_code, '\n')
    print('****Response****', '\n', r.json(), '\n\n')
    raw_output = get_output(fields, r.json())
    html_text = formated_output(fields, raw_output)
    v = ui.View()
    v.name = 'Test Web'
    web = ui.WebView()
    v.add_subview(web)
    web.height = 1024
    web.width = 720
    web.load_html(html_text)
    v.present('fullscreen')
<|endoftext|>


<commit_before>from django.shortcuts import render
from django.conf.urls import *
from django.contrib.auth.decorators import user_passes_test
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404

from .models import Protocol, Institution
from .forms import ProtocolForm, TopicFormSet
from hackfmi.utils import json_view

def can_add_protocols(user):
    return user.is_authenticated() and user.has_perm('protocols.add_protocol')

@user_passes_test(can_add_protocols)
def add(request):
    data = request.POST if request.POST else None
    protocol_form = ProtocolForm(data)
    topic_form = TopicFormSet(data)

    if protocol_form.is_valid() and topic_form.is_valid():
        protocol_form.save()
        topic_form.save()

    return render(request, 'protocols/add.html', locals())

def list_all_protocols(request):
    protocols = Protocol.objects.all()
    return render(request, 'protocols/list.html', locals())

@json_view
def search(request, name):
    institutions = Institution.objects.filter(name__icontains=name)

    json_data = [dict(name=institution.name) for institution in institutions]

    return json_data

def show_protocol(request, protocol_id):
    protocol = get_object_or_404(Protocol, id=protocol_id)
    return render(request, 'protocols/protocol.html', {"protocol_show": protocol})

def listing(request, page):
    protocols_list = Protocol.objects.all()
    paginator = Paginator(protocols_list, 30)

    protocols = paginator.page(page)

    return render(request, 'protocols/listing.html', {"protocols": protocols})
<commit_msg>Add institution id in json result<commit_after>from django.shortcuts import render
from django.conf.urls import *
from django.contrib.auth.decorators import user_passes_test
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404

from .models import Protocol, Institution
from .forms import ProtocolForm, TopicFormSet
from hackfmi.utils import json_view

def can_add_protocols(user):
    return user.is_authenticated() and user.has_perm('protocols.add_protocol')

@user_passes_test(can_add_protocols)
def add(request):
    data = request.POST if request.POST else None
    protocol_form = ProtocolForm(data)
    topic_form = TopicFormSet(data)

    if protocol_form.is_valid() and topic_form.is_valid():
        protocol_form.save()
        topic_form.save()

    return render(request, 'protocols/add.html', locals())

def list_all_protocols(request):
    protocols = Protocol.objects.all()
    return render(request, 'protocols/list.html', locals())

@json_view
def search(request, name):
    institutions = Institution.objects.filter(name__icontains=name)

    json_data = [dict(name=institution.name, id=institution.id) for institution in institutions]

    return json_data

def show_protocol(request, protocol_id):
    protocol = get_object_or_404(Protocol, id=protocol_id)
    return render(request, 'protocols/protocol.html', {"protocol_show": protocol})

def listing(request, page):
    protocols_list = Protocol.objects.all()
    paginator = Paginator(protocols_list, 30)

    protocols = paginator.page(page)

    return render(request, 'protocols/listing.html', {"protocols": protocols})
<|endoftext|>


<commit_before>#!/usr/bin/python

import argparse
import json
import yaml
import os
import sys

def get(d, key, default):
    if key in d:
        return d[key]
    else:
        return default

def get_in(d, keys, default):
    for key in keys:
        if key in d:
            d = d[key]
        else:
            return default
    return d

# Pointless..
#def assoc(d, key, value):
#    d[key] = value

def assoc_in(d, keys, value):
    for key in keys[:-1]:
        if key not in d:
            d[key] = dict()
        d = d[key]

    d[keys[-1]] = value

def update_in(d, keys, update_fn):
    value = get_in(d, keys, dict())
    assoc_in(d, keys, update_fn(value))

def update(d, key, update_fn):
    d[key] = update_fn(get(d, key, dict()))

def process_hosts(groups, data):
    for host_name, data_host in get(data, "hosts", dict()).iteritems():
        if "vars" in data_host:
            host_vars = get_in(groups, ["_meta", "hostvars", host_name], dict())
            host_vars.update(get(data_host, "vars", dict()))
            assoc_in(groups, ["_meta", "hostvars", host_name], host_vars)

        for group_name in get(data_host, "groups", list()):
            group_hosts = get_in(groups, [group_name, "hosts"], list())
            group_hosts.append(host_name)
            assoc_in(groups, [group_name, "hosts"], group_hosts)

    return groups

def process_groups(groups, data):
    #print(json.dumps(groups))
    for group_name, data_group in get(data, "groups", dict()).iteritems():
        group_hosts = get_in(groups, [group_name, "hosts"], list())
        group_vars = get_in(groups, [group_name, "vars"], dict())

        group_hosts += get(data_group, "hosts", list())

        group_vars.update(get(data_group, "vars", dict()))

        for include_name in get(data_group, "include", list()):
            group_hosts += get_in(groups, [include_name, "hosts"], list())

        for require_name in get(data_group, "require", list()):
            require_hosts = get_in(groups, [require_name, "hosts"], list())
            group_hosts[:] = [host_name for host_name in group_hosts if host_name in require_hosts]

        for exclude_name in get(data_group, "exclude", list()):
            exclude_hosts = get_in(groups, [exclude_name, "hosts"], list())
            group_hosts[:] = [host_name for host_name in group_hosts if host_name not in exclude_hosts]

        if len(group_hosts) > 0:
            assoc_in(groups, [group_name, "hosts"], group_hosts)

        if len(group_vars) > 0:
            assoc_in(groups, [group_name, "vars"], group_vars)

    return groups

def make_groups(data):
    groups = dict()
    meta = dict()
    groups["_meta"] = meta

    process_hosts(groups, data)
    process_groups(groups, data)

    for group_name, group in groups.iteritems():
        update(group, "hosts", lambda hosts: sorted(set(hosts)))

    meta.pop("hosts")
    return groups

def output_list_inventory(data):
    '''
    Output the --list data structure as JSON
    '''
    print json.dumps(make_groups(data))

def find_host(data, host_name):
    '''
    Find the given variables for the given host and output them as JSON
    '''

    print json.dumps(get_in(data, ["hosts", host_name, "vars"], dict()))

def main():
    '''
    Output dynamic inventory as JSON from statically defined data structures
    '''

    # Argument parsing
    parser = argparse.ArgumentParser(description="Ansible dynamic inventory")
    parser.add_argument("--list", help="Ansible inventory of all of the groups",
                        action="store_true", dest="list_inventory")
    parser.add_argument("--host", help="Ansible inventory of a particular host", action="store",
                        dest="ansible_host", type=str)
    parser.add_argument("--file", help="Inventory file", action="store",
                        dest="file", type=str)

    cli_args = parser.parse_args()
    list_inventory = cli_args.list_inventory
    ansible_host = cli_args.ansible_host
    inventory_file = cli_args.file

    if not inventory_file:
        if "ANSIBLE_HOSTS_YML" in os.environ:
            inventory_file = os.environ["ANSIBLE_HOSTS_YML"]

    if not inventory_file:
        inventory_file="hosts.yml"

    try:
        with open(inventory_file, 'r') as stream:
            data=yaml.load(stream)
            if list_inventory:
                output_list_inventory(data)

            if ansible_host:
                find_host(data, ansible_host)

    except Exception as exc:
        print(exc)
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__":
    main()
<commit_msg>Whitespace<commit_after>#!/usr/bin/python

import argparse
import json
import yaml
import os
import sys

def get(d, key, default):
    if key in d:
        return d[key]
    else:
        return default

def get_in(d, keys, default):
    for key in keys:
        if key in d:
            d = d[key]
        else:
            return default
    return d

# Pointless..
#def assoc(d, key, value):
#    d[key] = value

def assoc_in(d, keys, value):
    for key in keys[:-1]:
        if key not in d:
            d[key] = dict()
        d = d[key]

    d[keys[-1]] = value

def update_in(d, keys, update_fn):
    value = get_in(d, keys, dict())
    assoc_in(d, keys, update_fn(value))

def update(d, key, update_fn):
    d[key] = update_fn(get(d, key, dict()))

def process_hosts(groups, data):
    for host_name, data_host in get(data, "hosts", dict()).iteritems():
        if "vars" in data_host:
            host_vars = get_in(groups, ["_meta", "hostvars", host_name], dict())
            host_vars.update(get(data_host, "vars", dict()))
            assoc_in(groups, ["_meta", "hostvars", host_name], host_vars)

        for group_name in get(data_host, "groups", list()):
            group_hosts = get_in(groups, [group_name, "hosts"], list())
            group_hosts.append(host_name)
            assoc_in(groups, [group_name, "hosts"], group_hosts)

    return groups

def process_groups(groups, data):
    #print(json.dumps(groups))
    for group_name, data_group in get(data, "groups", dict()).iteritems():
        group_hosts = get_in(groups, [group_name, "hosts"], list())
        group_vars = get_in(groups, [group_name, "vars"], dict())

        group_hosts += get(data_group, "hosts", list())

        group_vars.update(get(data_group, "vars", dict()))

        for include_name in get(data_group, "include", list()):
            group_hosts += get_in(groups, [include_name, "hosts"], list())

        for require_name in get(data_group, "require", list()):
            require_hosts = get_in(groups, [require_name, "hosts"], list())
            group_hosts[:] = [host_name for host_name in group_hosts if host_name in require_hosts]

        for exclude_name in get(data_group, "exclude", list()):
            exclude_hosts = get_in(groups, [exclude_name, "hosts"], list())
            group_hosts[:] = [host_name for host_name in group_hosts if host_name not in exclude_hosts]

        if len(group_hosts) > 0:
            assoc_in(groups, [group_name, "hosts"], group_hosts)

        if len(group_vars) > 0:
            assoc_in(groups, [group_name, "vars"], group_vars)

    return groups

def make_groups(data):
    groups = dict()
    meta = dict()
    groups["_meta"] = meta

    process_hosts(groups, data)
    process_groups(groups, data)

    for group_name, group in groups.iteritems():
        update(group, "hosts", lambda hosts: sorted(set(hosts)))

    meta.pop("hosts")
    return groups

def output_list_inventory(data):
    '''
    Output the --list data structure as JSON
    '''
    print json.dumps(make_groups(data))

def find_host(data, host_name):
    '''
    Find the given variables for the given host and output them as JSON
    '''

    print json.dumps(get_in(data, ["hosts", host_name, "vars"], dict()))

def main():
    '''
    Output dynamic inventory as JSON from statically defined data structures
    '''

    # Argument parsing
    parser = argparse.ArgumentParser(description="Ansible dynamic inventory")
    parser.add_argument("--list", help="Ansible inventory of all of the groups",
                        action="store_true", dest="list_inventory")
    parser.add_argument("--host", help="Ansible inventory of a particular host", action="store",
                        dest="ansible_host", type=str)
    parser.add_argument("--file", help="Inventory file", action="store",
                        dest="file", type=str)

    cli_args = parser.parse_args()
    list_inventory = cli_args.list_inventory
    ansible_host = cli_args.ansible_host
    inventory_file = cli_args.file

    if not inventory_file:
        if "ANSIBLE_HOSTS_YML" in os.environ:
            inventory_file = os.environ["ANSIBLE_HOSTS_YML"]

    if not inventory_file:
        inventory_file="hosts.yml"

    try:
        with open(inventory_file, 'r') as stream:
            data=yaml.load(stream)
            if list_inventory:
                output_list_inventory(data)

            if ansible_host:
                find_host(data, ansible_host)

    except Exception as exc:
        print(exc)
        sys.exit(1)

    sys.exit(0)

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


<commit_before>"""
    viewer.utils
    ~~~~~~~~~~~~

    Various utilities.

    :copyright: © 2014 by Petr Zemek <s3rvac@gmail.com> and contributors
    :license: BSD, see LICENSE for more details
"""

import contextlib
import os

@contextlib.contextmanager
def chdir(dir):
    """A context manager that enables performing actions in the given
    directory.
    """
    cwd = os.getcwd()
    os.chdir(dir)
    try:
        yield
    finally:
        os.chdir(cwd)
<commit_msg>utils: Modify the module description.<commit_after>"""
    viewer.utils
    ~~~~~~~~~~~~

    General-purpose utilities.

    :copyright: © 2014 by Petr Zemek <s3rvac@gmail.com> and contributors
    :license: BSD, see LICENSE for more details
"""

import contextlib
import os

@contextlib.contextmanager
def chdir(dir):
    """A context manager that enables performing actions in the given
    directory.
    """
    cwd = os.getcwd()
    os.chdir(dir)
    try:
        yield
    finally:
        os.chdir(cwd)
<|endoftext|>


<commit_before># Django
import os
from django.apps import AppConfig

class ApiConfig(AppConfig):
    """Sets the configuration for the api app."""

    name = 'api'

    def ready(self):
        import algoliasearch_django as algoliasearch
        from .indexes import ChartIndex
        from .indexes import PersonIndex
        from .indexes import GroupIndex
        Chart = self.get_model('chart')
        Person = self.get_model('person')
        Group = self.get_model('group')
        algoliasearch.register(Chart, ChartIndex)
        algoliasearch.register(Person, PersonIndex)
        algoliasearch.register(Group, GroupIndex)
        return
<commit_msg>import signals<commit_after># Django
import os
from django.apps import AppConfig

class ApiConfig(AppConfig):
    """Sets the configuration for the api app."""

    name = 'api'

    def ready(self):
        import algoliasearch_django as algoliasearch
        import signals
        from .indexes import ChartIndex
        from .indexes import PersonIndex
        from .indexes import GroupIndex
        Chart = self.get_model('chart')
        Person = self.get_model('person')
        Group = self.get_model('group')
        algoliasearch.register(Chart, ChartIndex)
        algoliasearch.register(Person, PersonIndex)
        algoliasearch.register(Group, GroupIndex)
        return
<|endoftext|>