Exemplo n.º 1
0
    def __init__(self,
                 parent,
                 id=-1,
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.SP_3D | wx.SP_LIVE_UPDATE,
                 name='Crust Window',
                 rootObject=None,
                 rootLabel=None,
                 rootIsNamespace=True,
                 intro='',
                 locals=None,
                 InterpClass=None,
                 startupScript=None,
                 execStartupScript=True,
                 *args,
                 **kwds):
        """Create Crust instance."""
        wx.SplitterWindow.__init__(self, parent, id, pos, size, style, name)
        self.shell = Shell(parent=self,
                           introText=intro,
                           locals=locals,
                           InterpClass=InterpClass,
                           startupScript=startupScript,
                           execStartupScript=execStartupScript,
                           *args,
                           **kwds)
        self.editor = self.shell
        if rootObject is None:
            rootObject = self.shell.interp.locals
        self.notebook = wx.Notebook(parent=self, id=-1)
        self.shell.interp.locals['notebook'] = self.notebook
        self.filling = Filling(parent=self.notebook,
                               rootObject=rootObject,
                               rootLabel=rootLabel,
                               rootIsNamespace=rootIsNamespace)
        # Add 'filling' to the interpreter's locals.
        self.shell.interp.locals['filling'] = self.filling
        self.notebook.AddPage(page=self.filling, text='Namespace', select=True)

        self.display = Display(parent=self.notebook)
        self.notebook.AddPage(page=self.display, text='Display')
        # Add 'pp' (pretty print) to the interpreter's locals.
        self.shell.interp.locals['pp'] = self.display.setItem
        self.display.nbTab = self.notebook.GetPageCount() - 1

        self.calltip = Calltip(parent=self.notebook)
        self.notebook.AddPage(page=self.calltip, text='Calltip')

        self.sessionlisting = SessionListing(parent=self.notebook)
        self.notebook.AddPage(page=self.sessionlisting, text='History')

        self.dispatcherlisting = DispatcherListing(parent=self.notebook)
        self.notebook.AddPage(page=self.dispatcherlisting, text='Dispatcher')

        self.SplitHorizontally(self.shell, self.notebook, -self.sashoffset)
        self.SetMinimumPaneSize(100)

        self.Bind(wx.EVT_SIZE, self.SplitterOnSize)
        self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.OnChanged)
Exemplo n.º 2
0
    def test_chaining(self):
        sh = Shell(has_input=True)
        output = sh.run('cat -u').write('Hello, world!').output()
        self.assertEqual(output, ['Hello, world!'])

        output = shell('cat -u', has_input=True).write('Hello, world!').output()
        self.assertEqual(output, ['Hello, world!'])
Exemplo n.º 3
0
 def __init__(self, parent, filename=None):
     """Create EditorShellNotebook instance."""
     wx.Notebook.__init__(self, parent, id=-1)
     usePanels = True
     if usePanels:
         editorparent = editorpanel = wx.Panel(self, -1)
         shellparent = shellpanel = wx.Panel(self, -1)
     else:
         editorparent = self
         shellparent = self
     self.buffer = Buffer()
     self.editor = Editor(parent=editorparent)
     self.buffer.addEditor(self.editor)
     self.buffer.open(filename)
     self.shell = Shell(parent=shellparent,
                        locals=self.buffer.interp.locals,
                        style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER)
     self.buffer.interp.locals.clear()
     if usePanels:
         self.AddPage(page=editorpanel, text='Editor', select=True)
         self.AddPage(page=shellpanel, text='Shell')
         # Setup sizers
         editorsizer = wx.BoxSizer(wx.VERTICAL)
         editorsizer.Add(self.editor.window, 1, wx.EXPAND)
         editorpanel.SetSizer(editorsizer)
         editorpanel.SetAutoLayout(True)
         shellsizer = wx.BoxSizer(wx.VERTICAL)
         shellsizer.Add(self.shell, 1, wx.EXPAND)
         shellpanel.SetSizer(shellsizer)
         shellpanel.SetAutoLayout(True)
     else:
         self.AddPage(page=self.editor.window, text='Editor', select=True)
         self.AddPage(page=self.shell, text='Shell')
     self.editor.setFocus()
     wx.EVT_NOTEBOOK_PAGE_CHANGED(self, self.GetId(), self.OnPageChanged)
Exemplo n.º 4
0
    def test_chaining(self):
        sh = Shell(has_input=True)
        output = sh.run('cat -u').write('Hello, world!').output()
        self.assertEqual(output, ['Hello, world!'])

        output = shell('cat -u', has_input=True).write('Hello, world!').output()
        self.assertEqual(output, ['Hello, world!'])
Exemplo n.º 5
0
 def namespace_init(self, daemon):
     output = Shell.run('ip netns list')
     for line in output.split():
         if line == 'ns-' + daemon:
             return False
     Shell.run('ip netns add ns-%s' % daemon)
     return True
Exemplo n.º 6
0
 def create_interface(self, vip):
     try:
         vip=vip.split("/",1)[0]
         Shell.run('ifconfig lo:1 %s netmask 255.255.255.255 up' % (vip))
         logging.debug("Assigned VIP to the loopback interface")
     except Exception as ex:
           logging.error(ex)
Exemplo n.º 7
0
 def __init__(self, basename):
     self.print_backtrace = True
     self.reader = 0
     self.logger = None
     Shell.__init__(self, basename)
     self.register_commands(self, self.NOCARD_COMMANDS)
     self.set_prompt("(No card) ")
def transcode_picture(filename, layers):
    # {{{

    print(filename, layers)
    shell.run("trace kdu_transcode" + " -i " + filename +
              " -jpx_layers sYCC,0,1,2" + " -o " + "transcode_quality/" +
              filename + " Clayers=" + str(layers))
def is_ambari_installed():
	sh = Shell()
	output = sh.run('which ambari-server')
	if len(output[0]) == 0:
		return False
	else:
		return True
Exemplo n.º 10
0
 def namespace_init(self, daemon):
     output = Shell.run('ip netns list')
     for line in output.split():
         if line == 'ns-' + daemon:
             return False
     Shell.run('ip netns add ns-%s' % daemon)
     return True
Exemplo n.º 11
0
Arquivo: ycode.py Projeto: thgp/yoda
    def post(self):
    	sh = Shell()

    	for line in request.form['code'].split('\n'):
    		retval = sh.push(line)

        return {'retval': retval.strip() }
def transcode_images(layersub):
    # {{{
    log.debug("transcode_images={}".format(layersub))

    for key, value in layersub.items():
        pics_per_subband = (1 << (TRLs - key[1] - 1))
        for p in range(pics_per_subband * gop,
                       pics_per_subband * gop + pics_per_subband):
            if key[0] == 'L':
                fname = "L_" + str(key[1]) + '/' + str('%04d' %
                                                       (p + 1)) + ".jpx"
                transcode_picture(fname, fname, value)

                # {{{ Transcode GOP0, using the same number of subband layers than the last GOP
                if gop == 0:
                    fname = "L_" + str(key[1]) + '/' + str('%04d' %
                                                           (p)) + ".jpx"
                    value = layersub[("L", TRLs - 1)]
                    transcode_picture(fname, fname, value)
                # }}}

            elif key[0] == 'H':
                fname = "H_" + str(key[1]) + '/' + str('%04d' % p) + ".jpx"
                transcode_picture(fname, fname, value)

            elif key[0] == 'R':
                if value > 0:
                    fname = "R_" + str(key[1]) + '/' + str('%04d' % p) + ".j2c"
                    shell.run("trace cp " + fname + ' ' + destination + '/' +
                              fname)
Exemplo n.º 13
0
    def __init__(self, instance_path):
        # Call super init
        TSPLIB.__init__(self, instance_path)

        self._type = "vrp"

        # Set capacity
        self._capacity = int(
            Shell.run("grep CAPACITY " + instance_path +
                      " | cut -d':' -f2").strip())
        # Mim number of vehicles
        self._trucks = int(
            Shell.run("grep TRUCKS " + instance_path +
                      " | cut -d':' -f2").strip())

        # Load demand array
        with open(instance_path) as instance:
            read = False
            self._demand = list()
            for word in instance:
                # End loop if EOF
                if word.strip() == "DEPOT_SECTION":
                    break
                # If do, store tour
                if read:
                    s = word.split()
                    self._demand.append(int(s[1]))
                # If DEMAND_SECTION, set 'read'
                if word.strip() == "DEMAND_SECTION":
                    read = True

        if self._best_solution is not None:
            self._best_solution.load = self.routes_load(
                self._best_solution.routes)
Exemplo n.º 14
0
 def clear_interface(self, vip):
     try:
        vip=vip.split("/",1)[0]
        Shell.run('ifconfig lo:1 %s netmask 255.255.255.255 down' % (vip))
        logging.debug("Removed VIP from loopback interface due to all backend failures")
     except Exception as ex:
            logging.error(ex)
Exemplo n.º 15
0
 def create_interface(self, vip):
     try:
         vip = vip.split("/", 1)[0]
         Shell.run('ifconfig lo:1 %s netmask 255.255.255.255 up' % (vip))
         logging.debug("Assigned VIP to the loopback interface")
     except Exception as ex:
         logging.error(ex)
Exemplo n.º 16
0
def qstat(jid):
    """ Check job status """
    s = Shell()
    rc, out, m = s.cmd1("qstat %s | grep %s | awk '{print $5}'" % (jid, jid))
    if rc != 0:
        return None
    return out.strip('\n')
Exemplo n.º 17
0
def transcode_picture(filename, layers):
    # {{{

    log.debug("transcode_picture: {} {}".format(filename, layers))
    if layers > 0:
        shell.run("trace kdu_transcode" + " -i " + filename +
                  " -jpx_layers sYCC,0,1,2" + " -o " + "transcode_quality/" +
                  filename + " Clayers=" + str(layers))
Exemplo n.º 18
0
 def do_fire(self, objects):
     if self.fire_dt > 1000000 / self.FIRE_RATE:
         shell = Shell(-self.move_v * self.SPEED)
         shell.scale_factor = 1.75
         shell.setSprite(self.shell_texture)
         shell.sprite.position = self.sprite.position
         objects.append(shell)
         self.fire_dt = 0
def toDirectory():
    # {{{ Save to directory
    f = str(pwd) + "/../FSO_" + str(
        video.split("/")[len(video.split("/")) - 1]) + "_L" + str(
            layers) + "_T" + str(TRLs) + "_BS" + str(block_size) + "_SR" + str(
                search_range) + "_G" + str(GOPs) + "_" + str(slope) + ".dat"
    shell.run("rm -rf " + f + "; mkdir " + f)
    shell.run("cp " + str(pwd) + "/*.dat " + f)
Exemplo n.º 20
0
    def test__handle_output_norecord(self):
        sh = Shell(record_output=False, record_errors=False)
        self.assertEqual(sh._stdout, '')
        self.assertEqual(sh._stderr, '')

        sh._handle_output('another.txt\n', 'Error: Please supply an arg.')
        self.assertEqual(sh._stdout, '')
        self.assertEqual(sh._stderr, '')
Exemplo n.º 21
0
    def test__handle_output_norecord(self):
        sh = Shell(record_output=False, record_errors=False)
        self.assertEqual(sh._stdout, '')
        self.assertEqual(sh._stderr, '')

        sh._handle_output('another.txt\n', 'Error: Please supply an arg.')
        self.assertEqual(sh._stdout, '')
        self.assertEqual(sh._stderr, '')
Exemplo n.º 22
0
 def dead(self, map_group=None, enemy_group=None, fireball_group=None):
     self.settings.score_holder += self.settings.point_values['koopa']
     self.is_dead = True
     # if map_group and enemy_group and fireball_group:
     if map_group != None and enemy_group != None and fireball_group != None:
         s = Shell(self.screen, self.settings, self.rect.centerx,
                   self.rect.centery)
         s.add(map_group, enemy_group, fireball_group)
def is_hdp_select_installed():
	sh = Shell()
	output = sh.run('which hdp-select')
	
	if len(output[0]) == 0:
		return False
	else:
		return True
Exemplo n.º 24
0
    def setUp(self):
        super(ShellTestCase, self).setUp()
        self.test_dir = os.path.join('/tmp', 'python_shell')
        self.hello_path = os.path.join(self.test_dir, 'hello.txt')
        self.sh = Shell()

        shutil.rmtree(self.test_dir, ignore_errors=True)
        os.makedirs(self.test_dir)
Exemplo n.º 25
0
 def run(self):
     shell = Shell()
     print(self.three_level_dir_repr(), end='')
     command = input().strip()
     while(command != 'exit'):
         ret_msg = shell.process_command(command)
         print(ret_msg)
         print(self.three_level_dir_repr(), end='')
         command = input().strip()
def transcode_picture(filename_in, filename_out, layers):
    # {{{
    log.debug(
        "transcode_picture: {} to {}/{} with {} layers, from gop {}".format(
            filename_in, destination, filename_out, layers, gop + 1))
    if layers > 0:
        shell.run("trace kdu_transcode" + " -i " + filename_in +
                  " -jpx_layers sYCC,0,1,2" + " -o " + destination + "/" +
                  filename_out + " Clayers=" + str(layers))
Exemplo n.º 27
0
 def clear_interface(self, vip):
     try:
         vip = vip.split("/", 1)[0]
         Shell.run('ifconfig lo:1 %s netmask 255.255.255.255 down' % (vip))
         logging.debug(
             "Removed VIP from loopback interface due to all backend failures"
         )
     except Exception as ex:
         logging.error(ex)
Exemplo n.º 28
0
 def output(self):
   for ok in self.messages['ok']:
     print(Shell.color(ok, 'white', 'green'))
     
   for warning in self.messages['warning']:
     print(Shell.color(warning, 'yellow', 'black'))
     
   for error in self.messages['error']:
     print(Shell.color(error, 'white', 'red'))
Exemplo n.º 29
0
class EditorShellNotebook(wx.Notebook):
    """A notebook containing an editor page and a shell page."""
    def __init__(self, parent, filename=None):
        """Create EditorShellNotebook instance."""
        wx.Notebook.__init__(self, parent, id=-1)
        usePanels = True
        if usePanels:
            editorparent = editorpanel = wx.Panel(self, -1)
            shellparent = shellpanel = wx.Panel(self, -1)
        else:
            editorparent = self
            shellparent = self
        self.buffer = Buffer()
        self.editor = Editor(parent=editorparent)
        self.buffer.addEditor(self.editor)
        self.buffer.open(filename)
        self.shell = Shell(parent=shellparent,
                           locals=self.buffer.interp.locals,
                           style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER)
        self.buffer.interp.locals.clear()
        if usePanels:
            self.AddPage(page=editorpanel, text='Editor', select=True)
            self.AddPage(page=shellpanel, text='Shell')
            # Setup sizers
            editorsizer = wx.BoxSizer(wx.VERTICAL)
            editorsizer.Add(self.editor.window, 1, wx.EXPAND)
            editorpanel.SetSizer(editorsizer)
            editorpanel.SetAutoLayout(True)
            shellsizer = wx.BoxSizer(wx.VERTICAL)
            shellsizer.Add(self.shell, 1, wx.EXPAND)
            shellpanel.SetSizer(shellsizer)
            shellpanel.SetAutoLayout(True)
        else:
            self.AddPage(page=self.editor.window, text='Editor', select=True)
            self.AddPage(page=self.shell, text='Shell')
        self.editor.setFocus()
        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED,
                  self.OnPageChanged,
                  id=self.GetId())

    def OnPageChanged(self, event):
        """Page changed event handler."""
        selection = event.GetSelection()
        if selection == 0:
            self.editor.setFocus()
        else:
            self.shell.SetFocus()
        event.Skip()

    def SetFocus(self):
        wx.Notebook.SetFocus(self)
        selection = self.GetSelection()
        if selection == 0:
            self.editor.setFocus()
        else:
            self.shell.SetFocus()
Exemplo n.º 30
0
 def _get_master_ifname(self, daemon, ifname_instance):
     output = Shell.run('ip netns exec ns-%s ethtool -S %s' %
                        (daemon, ifname_instance))
     m = re.search(r'peer_ifindex: (\d+)', output)
     ifindex = m.group(1)
     output = Shell.run('ip link list')
     expr = '^' + ifindex + ': (\w+): '
     regex = re.compile(expr, re.MULTILINE)
     m = regex.search(output)
     return m.group(1)
Exemplo n.º 31
0
 def _add_shell_panel(self):
     """ Adds a python shell to the bottom pane. """
     logger.debug("Adding shell.")
     self._shell = Shell()
     self._shell.set_font(self._font)
     panel = self.window.get_bottom_panel()
     panel.add_item_with_stock_icon(self._shell, "DjangoShell",
                                    "Python Shell", STOCK_PYTHON)
     self._setup_shell_panel()
     panel.activate_item(self._shell)
Exemplo n.º 32
0
 def __init__(self, devdir, startsemlex, catroles):
     self.devdir = devdir
     self.allpatterns = {
     }  #extract|case|trigger|triggertype as key, value is [freq of pattern, [extracts, heads]]
     self.bestpatterns = [
     ]  #A simple list containing the idkeys of best patterns for lookup in self.allpatterns.
     self.semlex = startsemlex  #names of semantic categories are keys, lists of pairs words in each category and their heads are values
     self.catroles = catroles  #names of semantic categories are keys, the semantic role of each category is the value
     self.shell = Shell()
     self.data = Data()
Exemplo n.º 33
0
 def _add_dbshell_panel(self):
     """ Adds a database shell to the bottom pane. """
     logger.debug("Adding database shell panel.")
     self._dbshell = Shell()
     self._dbshell.set_font(self._font)
     panel = self.window.get_bottom_panel()
     panel.add_item_with_stock_icon(self._dbshell, "DjangoDbShell",
                                    "Database Shell", STOCK_DBSHELL)
     self._setup_dbshell_panel()
     panel.activate_item(self._dbshell)
Exemplo n.º 34
0
 def _get_master_ifname(self, daemon, ifname_instance):
     output = Shell.run('ip netns exec ns-%s ethtool -S %s' %
                        (daemon, ifname_instance))
     m = re.search(r'peer_ifindex: (\d+)', output)
     ifindex = m.group(1)
     output = Shell.run('ip link list')
     expr = '^' + ifindex + ': (\w+): '
     regex = re.compile(expr, re.MULTILINE)
     m = regex.search(output)
     return m.group(1)
Exemplo n.º 35
0
    def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.SP_3D|wx.SP_LIVE_UPDATE,
                 name='Crust Window', rootObject=None, rootLabel=None,
                 rootIsNamespace=True, intro='', locals=None,
                 InterpClass=None,
                 startupScript=None, execStartupScript=True,
                 *args, **kwds):
        """Create Crust instance."""
        wx.SplitterWindow.__init__(self, parent, id, pos, size, style, name)

        # Turn off the tab-traversal style that is automatically
        # turned on by wx.SplitterWindow.  We do this because on
        # Windows the event for Ctrl-Enter is stolen and used as a
        # navigation key, but the Shell window uses it to insert lines.
        style = self.GetWindowStyle()
        self.SetWindowStyle(style & ~wx.TAB_TRAVERSAL)
        
        self.shell = Shell(parent=self, introText=intro,
                           locals=locals, InterpClass=InterpClass,
                           startupScript=startupScript,
                           execStartupScript=execStartupScript,
                           *args, **kwds)
        self.editor = self.shell
        if rootObject is None:
            rootObject = self.shell.interp.locals
        self.notebook = wx.Notebook(parent=self, id=-1)
        self.shell.interp.locals['notebook'] = self.notebook
        self.filling = Filling(parent=self.notebook,
                               rootObject=rootObject,
                               rootLabel=rootLabel,
                               rootIsNamespace=rootIsNamespace)
        # Add 'filling' to the interpreter's locals.
        self.shell.interp.locals['filling'] = self.filling
        self.notebook.AddPage(page=self.filling, text='Namespace', select=True)
        
        self.display = Display(parent=self.notebook)
        self.notebook.AddPage(page=self.display, text='Display')
        # Add 'pp' (pretty print) to the interpreter's locals.
        self.shell.interp.locals['pp'] = self.display.setItem
        self.display.nbTab = self.notebook.GetPageCount()-1
        
        self.calltip = Calltip(parent=self.notebook)
        self.notebook.AddPage(page=self.calltip, text='Calltip')
        
        self.sessionlisting = SessionListing(parent=self.notebook)
        self.notebook.AddPage(page=self.sessionlisting, text='History')
        
        self.dispatcherlisting = DispatcherListing(parent=self.notebook)
        self.notebook.AddPage(page=self.dispatcherlisting, text='Dispatcher')
        
        self.SplitHorizontally(self.shell, self.notebook, -self.sashoffset)
        self.SetMinimumPaneSize(100)

        self.Bind(wx.EVT_SIZE, self.SplitterOnSize)
        self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.OnChanged)
Exemplo n.º 36
0
 def shooting(self, shells):
     """ The method is responsible for the behavior of the projectile. """
     if len(shells) < 10:
         if self.position:
             coordinates_shell = [round(self.x + 45), round(self.y + 22)]
             shell = Shell(coordinates_shell, 1)
         else:
             coordinates_shell = [round(self.x + 10), round(self.y + 22)]
             shell = Shell(coordinates_shell, -1)
         shells.append(shell)
     return shells
Exemplo n.º 37
0
 def __init__(self, use_dummy=False, filename=None, **kwargs):
     super(TestRoot, self).__init__(**kwargs)
     self.use_dummy = use_dummy
     self.filename = filename
     self.resetting = False
     self.shell = Shell()
     self.shell.bind(on_stdout=self.on_stdout)
     self.shell.bind(on_stderr=self.on_stderr)
     self.shell.bind(on_exit=self.on_exit)
     self.ids.quit.bind(on_press=lambda x: self.stop())
     self.ids.scan.bind(state=self.on_state_scan)
def install_nifi():

	logger.info('Attempting to install NiFi to the cluster')
	if not is_ambari_installed():
		logger.error('Ambari must be installed to install NiFi as well.')
		raise EnvironmentError('You must install the demo on the same node as the Ambari server. Install Ambari here or move to another node with Ambari installed before continuing')
	
	
	if not is_hdp_select_installed():
		installed = install_hdp_select()
		if not installed:
			logger.error('hdp-select must be installed to install NiFi')
			raise EnvironmentError('hdp-select could not be installed. Please install it manually and then re-run the setup.')

	conf = config.read_config('service-installer.conf')
	cmds = json.loads(conf['NIFI']['install-commands'])
	
	sh = Shell()
	logger.info('Getting HDP Version')
	version = sh.run(cmds[0])
	logger.info('HDP Version: ' + version[0])
	fixed_copy = cmds[2].replace('$VERSION', str(version[0])).replace('\n', '')
	fixed_remove = cmds[1].replace('$VERSION', str(version[0])).replace('\n', '')
	logger.info('NiFi Clean Command: ' + fixed_copy)
	logger.info('NiFi Copy Command: ' + fixed_remove)
	remove = sh.run(fixed_remove)
	copy = sh.run(fixed_copy)
	logger.info('Attempting to restart Ambari...')
	restart = sh.run(cmds[3])

	print("Please open the Ambari Interface and manually deploy the NiFi Service.")
	raw_input("Press enter twice to continue...")
	raw_input("Press enter once to continue...")
	
#	 We've copied the necessary files. Once that completes we need to add it to Ambari
	logger.info('Waiting for user to install service in Ambari to continue')
	print('Checking to make sure service is installed')
	ambari = config.read_config('global.conf')['AMBARI']
	installed = check_ambari_service_installed('NIFI', ambari)
	logger.info('NiFi installed successfully')
	cont = ''
	if not installed:
		print('Unable to contact Ambari Server. Unsure whether or not Zeppelin was installed')
		while not (cont == 'y' or cont == 'n'):
			cont = raw_input('Continue attempt to set up NiFi for demo?(y/n)')
			if not (cont == 'y' or cont == 'n'):
				print('Please enter "y" or "n"')
	else:
		cont = 'y'
	
	if cont == 'n':
		return False
	elif cont == 'y':
		return True
def is_hdp_select_installed():
  '''Checks if ``hdp-select`` is installed.
  
  Returns:
    bool: True if installed (available as shell command), False if not installed'''
  sh = Shell()
  output = sh.run('which hdp-select')
  
  if len(output[0]) == 0:
    return False
  else:
    return True
Exemplo n.º 40
0
 def __init__(self, frames, semlexcollection, patterncollection,
              prepcollection, language):
     self.shell = Shell()
     self.frames = frames  #Key is trigger ("trigger, active"), value is frame object
     self.filledframes = []
     self.semlex = {}
     self.patterns = {}
     self.prepositions = {}
     self.language = language
     self.semlexcollection = semlexcollection
     self.patterncollection = patterncollection
     self.prepcollection = prepcollection
Exemplo n.º 41
0
    def test__handle_output_simple(self):
        sh = Shell()
        self.assertEqual(sh._stdout, '')
        self.assertEqual(sh._stderr, '')

        sh._handle_output('another.txt\n', None)
        self.assertEqual(sh._stdout, 'another.txt\n')
        self.assertEqual(sh._stderr, '')

        sh._handle_output('something.txt\n', 'Error: Please supply an arg.\n')
        self.assertEqual(sh._stdout, 'another.txt\nsomething.txt\n')
        self.assertEqual(sh._stderr, 'Error: Please supply an arg.\n')
Exemplo n.º 42
0
def is_hdp_select_installed():
    '''Checks if ``hdp-select`` is installed.
  
  Returns:
    bool: True if installed (available as shell command), False if not installed'''
    sh = Shell()
    output = sh.run('which hdp-select')

    if len(output[0]) == 0:
        return False
    else:
        return True
Exemplo n.º 43
0
def main():
    CLOCK = None
    SIZE = (X, Y)

    pygame.init()
    SCREEN = pygame.display.set_mode(SIZE)
    CLOCK = pygame.time.Clock()

    SIZE = pygame.display.get_surface().get_size()
    background = Mountain(SIZE)
    tanks = [
        Tank(
            int(X * (0.5 - 0.4 * (max(-1, min(1, random.normal(direction)))))),
            direction, background) for direction in (LEFT, RIGHT)
    ]
    bg = background.render()
    print("blitting background")

    wind = random.randint(-10, 10)
    running = True
    player = 0
    while running:
        t = tanks[player]
        print("blitting tank  ", t.direction, " x=", t.x, " y=", t.y)
        wind += random.randint(-2, 2)
        t.draw(bg)
        panel = Panel(t)
        aiming = True
        while running and aiming:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    if e.key == pygame.K_ESCAPE:
                        running = False
                    if e.key == pygame.K_SPACE:
                        aiming = False
                panel.handle(e)
            SCREEN.blit(bg, (0, 0))
            panel.draw(wind, SCREEN)
            pygame.display.flip()

        if running:
            dt = 0
            s = Shell(t, wind=10)
            shot = True
            while shot:
                SCREEN.blit(bg, (0, 0))
                shot = s.animate(SCREEN, background, dt)
                pygame.display.flip()
                dt += 0.05
                CLOCK.tick(FPS)
            player = 1 - player

    pygame.display.quit()
def is_ambari_installed():
  '''Determines whether or not ``ambari-server`` is available (In order to start/stop/restart Ambari)
  
  Returns:
    bool: True is ``ambari-server`` is available as a shell command. False otherwise.
  
  '''
  sh = Shell()
  output = sh.run('which ambari-server')
  if len(output[0]) == 0:
    return False
  else:
    return True
Exemplo n.º 45
0
	def main_loop(self):
		while(self.__location <> "quit"):
			try:
				gesture = self.show(self.__location)
				if gesture[0] != "!":
					self.__history.append(gesture)
				page = self(gesture)
				if page is not None: self.__location = page
			except KeyboardInterrupt:
				break
			except Exception, e:
				Shell.show_message(`e`, 1)
				raise
Exemplo n.º 46
0
def teardown(pod_namespace, pod_name, docker_id):
    manager = LxcManager()
    short_id = docker_id[0:12]

    api = ContrailVRouterApi()

    uid, podName = getDockerPod(docker_id)
    vmi, _ = vrouter_interface_by_name(podName)
    if vmi is not None:
        api.delete_port(vmi)

    manager.clear_interfaces(short_id)
    Shell.run('ip netns delete %s' % short_id)
Exemplo n.º 47
0
    def interface_find_peer_name(self, nsname):
        ifname_instance = Shell.run(
            'ip netns exec %s ip link show eth0 | '
            'awk \'/eth0/{split($2, array, \":\"); print array[1];}\'' %
            nsname)
        logging.debug('instance interface %s' % ifname_instance)

        # Get ifindex of ifname_instance
        ns_ifindex = Shell.run('ip netns exec %s ethtool -S eth0 | '
                               'grep peer_ifindex | awk \'{print $2}\''
                               % (nsname))

        ifname = ifindex2name(int(ns_ifindex))
        return ifname
Exemplo n.º 48
0
    def interface_update(self, daemon, vmi, ifname_instance):
        """
        1. Make sure that the interface exists in the name space.
        2. Update the mac address.
        """
        output = Shell.run('ip netns exec ns-%s ip link list' % daemon)
        if not self._interface_list_contains(output, ifname_instance):
            ifname_master = self.create_interface('ns-%s' % daemon, ifname_instance)
        else:
            ifname_master = self._get_master_ifname(daemon, ifname_instance)

        mac = vmi.virtual_machine_interface_mac_addresses.mac_address[0]
        Shell.run('ip netns exec ns-%s ifconfig %s hw ether %s' %
                  (daemon, ifname_instance, mac))
        return ifname_master
Exemplo n.º 49
0
    def clear_interfaces(self, nsname):
        output = ""
        try:
            output = Shell.run('ip netns exec %s ip link list' % nsname)
        except Exception as ex:
            logging.error(ex)

        for line in output.split('\n'):
            m = re.match(r'^[\d]+: ([\w]+):', line)
            if m:
                ifname = m.group(1)
                if ifname == 'lo':
                    continue
                Shell.run('ip netns exec %s ip link delete %s' %
                          (nsname, ifname))
Exemplo n.º 50
0
def main():
    try:
        module_dir = os.path.dirname(__file__)
        app_dict = open(os.path.join(module_dir, "app_states/master_state.json")).read()
        app_dict = json.loads(app_dict)
    except Exception:
        return (1, "Could not open file. Traceback: %s" % traceback.format_exc())

    try:
        app = App.create_from_dict(app_dict)
    except Exception:
        return (2, "Could not parse. Traceback: %s" % traceback.format_exc())

    try:
        codes = create_codes(app)
    except Exception:
        return (3, "Could not create app. Traceback: %s" % traceback.format_exc())

    try:
        cc = Coder.create_from_codes(codes)
        tmp_dir = write_to_fs(cc)
    except Exception:
        return (4, "Could not write code. Traceback: %s" % traceback.format_exc())

    # syncdb

    sh = Shell()
    cd = "cd %s" % tmp_dir
    chdir_then = lambda x: "%s ; %s" % (cd, x)

    sh.run(chdir_then('python manage.py syncdb --noinput'))
    errors = sh.errors()
    if len(errors) > 0:
        return (5, repr(errors))

    sh.run(chdir_then('python manage.py runserver'))
    errors = sh.errors()
    if len(errors) > 0:
        return (6, repr(errors))

    sh.run(chdir_then('python manage.py test webapp'))
    errors = sh.errors()
    if len(errors) > 0:
        return (7, repr(errors))
    # runserver
    # run tests

    return (0, "success: %s" % tmp_dir)
Exemplo n.º 51
0
class TestShell(unittest.TestCase):
    def setUp(self):
        from shell import Shell
        self.shell = Shell()

    def test_ls(self):
        output = self.shell.cmd('ls')
Exemplo n.º 52
0
    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD': 'POST',
                     'CONTENT_TYPE': self.headers['Content-Type'],
                     })

        shell = Shell()
        message = shell.execude(form.getvalue('cmd'))
        cwd = shell.pwd
        self.send_response(200)
        self.send_header("Content-type", "text/json")
        self.end_headers()
        s = json.dumps({'result': message, 'cwd': cwd})
        self.wfile.write(bytes(s, 'UTF-8'))
Exemplo n.º 53
0
def getPodInfo(namespace, podName):
    kubeapi = kubelet_get_api()

    data = Shell.run(
        'kubectl --server=%s:8080 get --namespace=%s -o json pod %s' % (
            kubeapi, namespace, podName), True)
    return json.loads(data)
Exemplo n.º 54
0
 def local_address(self):
     output = Shell.run('ip addr show vhost0')
     expr = re.compile(r'inet ((([0-9]{1,3})\.){3}([0-9]{1,3}))/(\d+)')
     m = expr.search(output)
     if not m:
         raise Exception('Unable to determine local IP address')
     return m.group(1)
    def handle(self):
        logger.debug("Connected from %s %u" %(self.client_address))
#        try:
        exit=False
        shellmode=False
        logger.debug("Starting a shell")
        from shell import Shell
        myshell=Shell(self.rfile, self.wfile, self.server.user, self.server.passwd)
        try:
            myshell.cmdloop()
        except:
            ComLog.errorTraceLog(logger)
#        except SSL.ZeroReturnError:
#            pass
        self.request.close()
        logger.debug("Disconnected from %s %u" %(self.client_address))
Exemplo n.º 56
0
    def interface_find_peer_name(self, ifname_instance, nsname):
        # Get ifindex of ifname_instance
        ns_ifindex = Shell.run('ip netns exec %s ethtool -S %s | '
                               'grep peer_ifindex | awk \'{print $2}\'' \
                               % (nsname, ifname_instance))

        ifname = ifindex2name(int(ns_ifindex))
        return ifname
Exemplo n.º 57
0
 def setup_locale(self):
     if 'locale' in self.preferences:
         lang_config = self.root_dir + '/etc/sysconfig/language'
         if os.path.exists(lang_config):
             log.info(
                 'Setting up locale: %s', self.preferences['locale']
             )
             Shell.run_common_function(
                 'baseUpdateSysConfig', [
                     lang_config, 'RC_LANG',
                     self.preferences['locale'].split(',')[0] + '.UTF-8'
                 ]
             )
         else:
             log.warning(
                 'locale setup skipped etc/sysconfig/language not found'
             )
Exemplo n.º 58
0
 def setup_keyboard_map(self):
     if 'keytable' in self.preferences:
         keyboard_config = self.root_dir + '/etc/sysconfig/keyboard'
         if os.path.exists(keyboard_config):
             log.info(
                 'Setting up keytable: %s', self.preferences['keytable']
             )
             Shell.run_common_function(
                 'baseUpdateSysConfig', [
                     keyboard_config, 'KEYTABLE',
                     '"' + self.preferences['keytable'] + '"'
                 ]
             )
         else:
             log.warning(
                 'keyboard setup skipped etc/sysconfig/keyboard not found'
             )