<commit_before>#!/usr/bin/env python

from __future__ import print_function, unicode_literals, division

import sys
from random import choice as rndchoice
from random import shuffle
from time import sleep
from itertools import cycle

from utils import Dice, TextInput, ujoin, nextval, lasind

size       = 20
num_pieces = 3
blank      = '.'
space      = ' '
quit_key   = 'q'
nl         = '\n'
pause_time = 0.5     # in seconds

players    = 'gb'
ai_players = 'gb'

class Tile(object):
    def __repr__(self):
        return self.char

class Blank(Tile):
    char = blank

class Piece(Tile):
    loc  = -1
    done = False

    def __init__(self, char):
        self.char = char

    def move(self, loc):
        """Move to location `loc`, if moved past the end, set `done` property."""
        track[self.loc] = Blank()
        if loc > len(track) - 1:
            self.done = True
        else:
            if track[loc].char is not blank:
                track[loc].loc = -1     # bump enemy piece back to start
            track[loc] = self
        self.loc = loc

class SimpleRace(object):
    winmsg = "\n'%s' wins the race!"

    def __init__(self):
        """ Create pieces; create list of players with one or the other being the first to move;
            create dice object.
        """
        self.players = [[Piece(p) for _ in range(num_pieces)] for p in players]
        self.dice    = Dice(num=1)      # one 6-sided dice
        shuffle(self.players)

    def draw(self):
        """Display the racing track."""
        print(nl*5 + ujoin(track))

    def valid(self, piece, loc):
        """Valid move: any move that does not land on your other piece (beyond track is ok)."""
        return bool(loc > len(track)-1 or track[loc].char != piece.char)

    def valid_moves(self, player, move):
        """ Valid moves for `player`: return tuples (piece, newloc) for each piece belonging to `player`.

            Note: when more than one piece are at the start, we need to avoid giving the player
            choice between two identical moves, so we need to convert the list of tuples to a dict which
            gets rid of duplicate keys (locations) and then convert back to a list using `items()`
            method.
            We also need to sort `moves` by location because this looks better to the
            user when choices are shown in `get_move()`.
        """
        moves = [(p.loc+move, p) for p in player if not p.done and self.valid(p, p.loc+move)]
        return sorted( dict(moves).items() )

    def is_ai(self, player):
        return bool(player[0].char in ai_players)

    def check_end(self, player):
        """Check if `player` has won the game."""
        if all(piece.done for piece in player):
            self.game_won(player)

    def game_won(self, player):
        self.draw()
        print(self.winmsg % player[0].char)
        sys.exit()

class Test(object):
    self.invalid_move = "Invalid move"

    def offer_choice(self, player, valid_moves):
        return bool(not race.is_ai(player) and len(valid_moves) > 1)

    def run(self):
        """ Run main game loop.

            If more than one valid move is available to the human player, let him make the choice
            with `get_move()`.
        """
        self.textinput = TextInput(board, '%hd')
        player = race.players[0][0].char
        if ai_players and player not in ai_players:
            print("You are playing:", player)

        for player in cycle(race.players):
            race.draw()
            movedist    = race.dice.rollsum()
            valid_moves = race.valid_moves(player, movedist)

            if valid_moves:
                getmove = self.get_move if self.offer_choice(player, valid_moves) else rndchoice
                loc, piece = getmove(valid_moves)
                piece.move(loc)
                race.check_end(player)
            sleep(pause_time)

    def get_move(self, valid_moves):
        """Get player's choice of move options."""
        moves = [space] * 26
        for n, (loc, _) in enumerate(valid_moves):
            moves[loc] = n + 1
        print(ujoin(moves))

        while True:
            move = self.textinput.getinput_val()
            if move <= lasind(valid_moves):
                return valid_moves[move]
            else:
                print(self.invalid_move)

if __name__ == "__main__":
    track = [Blank() for _ in range(size)]
    race  = SimpleRace()
    try: Test().run()
    except KeyboardInterrupt: pass
<commit_msg>updated simplerace<commit_after>#!/usr/bin/env python

from __future__ import print_function, unicode_literals, division

import sys
from random import choice as rndchoice
from random import shuffle
from time import sleep
from itertools import cycle

from utils import Dice, TextInput, ujoin, nextval, lastind, first

size         = 20
num_pieces   = 3
blank        = '.'
space        = ' '
quit_key     = 'q'
nl           = '\n'
pause_time   = 0.5     # in seconds

player_chars = 'gb'
ai_players   = 'b'

class Tile(object):
    def __repr__(self):
        return self.char

class Blank(Tile):
    char = blank

class Piece(Tile):
    loc  = -1
    done = False

    def __init__(self, char):
        self.char = char

    def move(self, loc):
        """Move to location `loc`, if moved past the end, set `done` property."""
        track[self.loc] = Blank()
        if loc > lastind(track):
            self.done = True
        else:
            if track[loc].char is not blank:
                track[loc].loc = -1     # bump enemy piece back to start
            track[loc] = self
        self.loc = loc

class SimpleRace(object):
    winmsg = "\n'%s' wins the race!"

    def __init__(self):
        """ Create pieces; create list of players with one or the other being the first to move;
            create dice object.
        """
        self.dice = Dice(num=1)     # one 6-sided dice
        shuffle(players)

    def draw(self):
        """Display the racing track."""
        print(nl*5 + ujoin(track))

    def valid(self, piece, loc):
        """Valid move: any move that does not land on your other piece (beyond track is ok)."""
        return bool(loc > len(track)-1 or track[loc].char != piece.char)

    def valid_moves(self, player, move):
        """ Valid moves for `player`: return tuples (piece, newloc) for each piece belonging to `player`.

            Note: when more than one piece are at the start, we need to avoid giving the player
            choice between two identical moves, so we need to convert the list of tuples to a dict which
            gets rid of duplicate keys (locations) and then convert back to a list using `items()`
            method.
            We also need to sort `moves` by location because this looks better to the
            user when choices are shown in `get_move()`.
        """
        moves = [(p.loc+move, p) for p in player if not p.done and self.valid(p, p.loc+move)]
        return sorted( dict(moves).items() )

    def check_end(self, player):
        """Check if `player` has won the game."""
        if all(piece.done for piece in player):
            self.game_won(player)

    def game_won(self, player):
        self.draw()
        print(self.winmsg % player.char)
        sys.exit()

class Player(object):
    def __init__(self, char):
        self.char   = char
        self.ai     = char in ai_players
        self.pieces = [Piece(char) for _ in range(num_pieces)]

    def __repr__(self):
        return self.char

    def __iter__(self):
        return iter(self.pieces)

class Test(object):
    def offer_choice(self, player, valid_moves):
        return bool(not player.ai and len(valid_moves) > 1)

    def run(self):
        """ Run main game loop.

            If more than one valid move is available to the human player, let him make the choice
            with `get_move()`.
        """

        self.textinput = TextInput(None, '%hd')
        player = first(players)
        if ai_players and player.char not in ai_players:
            print("You are playing:", player)

        for player in cycle(players):
            race.draw()
            movedist    = race.dice.rollsum()
            valid_moves = race.valid_moves(player, movedist)

            if valid_moves:
                getmove = self.get_move if self.offer_choice(player, valid_moves) else rndchoice
                loc, piece = getmove(valid_moves)
                piece.move(loc)
                race.check_end(player)
            sleep(pause_time)

    def get_move(self, valid_moves):
        """Get player's choice of move options."""
        moves = [space] * 26
        for n, (loc, _) in enumerate(valid_moves):
            moves[loc] = n + 1
        print(ujoin(moves))

        while True:
            move = self.textinput.getinput_val()

            if move <= lastind(valid_moves) : return valid_moves[move]
            else                            : print(self.textinput.invalid_move)

if __name__ == "__main__":
    track   = [Blank() for _ in range(size)]
    players = [Player(c) for c in player_chars]
    race    = SimpleRace()
    try: Test().run()
    except KeyboardInterrupt: pass
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import socket
import struct
import select
import time
import os
import hashlib
import connection_manager

# we import PollingObserver instead of Observer because the deleted event
# is not capturing https://github.com/gorakhargosh/watchdog/issues/46
from watchdog.observers.polling import PollingObserver as Observer
from watchdog.events import FileSystemEventHandler

class DirectoryMonitor(FileSystemEventHandler):
    """
    The DirectoryMonitor for file system events
    like: moved, deleted, created, modified
    """
    def __init__(self, folder_path, event_dispatcher):
        FileSystemEventHandler.__init__(self)
        self.event_dispatcher = event_dispatcher
        self.folder_path = folder_path
        self.folder_watched = self.folder_path.split(os.sep)[-1]
        self.observer = Observer()
        self.observer.schedule(self, path=folder_path, recursive=True)

    def on_any_event(self, event):
        """
        it catpures any filesytem event and redirects it to the event_dispatcher
        """
        def build_data(cmd,e):
            data = {}
            data['cmd'] = cmd
            data['file'] = {
                "filepath": self.relativize_path(e.src_path),
                "mtime": os.path.getmtime(e.src_path),
                "md5": hashlib.md5(e.src_path).hexdigest()
            }
            return data

        if event.is_directory is False:
            e = event

            if e.event_type == 'modified':
                data = build_data('upload', e)

            elif e.event_type == 'created':
                data = build_data('upload', e)

            elif e.event_type == 'moved':
                data = {'cmd':'move'}
                data['file'] = {
                    'src_path': self.relativize_path(e.src_path),
                    'dest_path': self.relativize_path(e.dest_path)}

            elif e.event_type == 'deleted':
                data = {'cmd':'delete'}
                data['file'] = {
                    "filepath": self.relativize_path(e.src_path)}

            self.event_dispatcher(data['cmd'], data['file'])

    def relativize_path(self,path_to_clean):
        """
        This function relativize the path watched by watchdog:
        for example: /home/user/watched/subfolder will be /subfolder
        """
        return path_to_clean.split(self.folder_watched)[-1]

    def start(self):
        """
        starts the observer thread
        """
        self.observer.start()

    def stop(self):
        """
        stops the observer thread
        """
        self.observer.stop()

    def join(self):
        """
        waits for observer execution finalize
        """
        self.observer.join()

class Daemon(object):
    """
    Root of all evil:
    it loads program configurations,
    it starts directory events observations
    it serves command manager
    """

    TIMEOUT = 0.5

    def __init__(self):
        if load_json('config.json'):
            self.cfg = load_json('config.json')
            self.conn_mng = connection_manager.ConnectionManager(self.cfg)
            self.dir_manager = DirectoryMonitor(self.cfg['path'], self.event_dispatcher)
            self.running = 0
        else:
            "No Config File"

    def cmd_dispatcher(self, data):
        """
        It dispatch cmd and args to the api manager object
        """
        cmd = data.keys()[0]  # it will be always one key
        args = data[cmd]  # it will be a dict specifying the args

        print cmd, args

        if cmd == 'shutdown':
            self.shutdown()
        else:
            self.conn_mng.dispatch_request(cmd, args)

    def event_dispatcher(self, cmd, data_file):
        """
        It dispatch the captured events to the api manager object
        """
        self.conn_mng.dispatch_request(cmd, data_file)

    def serve_forever(self):
        """
        it handles the dir manager thread and the server socket together
        """
        backlog = 5
        int_size = struct.calcsize('!i')

        listener_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        listener_socket.bind((self.cfg['host'], self.cfg['port']))
        listener_socket.listen(backlog)
        r_list = [listener_socket]

        self.dir_manager.start()

        self.running = 1
        try:
            while self.running:
                r_ready, w_ready, e_ready = select.select(r_list, [], [], self.TIMEOUT)

                for s in r_ready:

                    if s == listener_socket:
                        # handle the server socket
                        client_socket, client_address = listener_socket.accept()
                        r_list.append(client_socket)
                    else:
                        # handle all other sockets
                        length = s.recv(int_size)
                        if length:
                            length = int(struct.unpack('!i', length)[0])
                            data = json.loads(s.recv(length))
                            self.cmd_dispatcher(data)
                        else:
                            s.close()
                            r_list.remove(s)
        except KeyboardInterrupt:
            self.shutdown()

        self.dir_manager.join()
        listener_socket.close()

    def shutdown(self):
        self.dir_manager.stop()
        self.running = 0

def load_json(conf_path):
    if os.path.isfile(conf_path):
        with open(conf_path,"r") as fo:
            config = json.load(fo)
        return config
    else:
        return False

if __name__ == '__main__':

    daemon = Daemon()
    daemon.serve_forever()
<commit_msg>Exit if config file not exists<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import socket
import struct
import select
import time
import os
import hashlib
import connection_manager

# we import PollingObserver instead of Observer because the deleted event
# is not capturing https://github.com/gorakhargosh/watchdog/issues/46
from watchdog.observers.polling import PollingObserver as Observer
from watchdog.events import FileSystemEventHandler

class DirectoryMonitor(FileSystemEventHandler):
    """
    The DirectoryMonitor for file system events
    like: moved, deleted, created, modified
    """
    def __init__(self, folder_path, event_dispatcher):
        FileSystemEventHandler.__init__(self)
        self.event_dispatcher = event_dispatcher
        self.folder_path = folder_path
        self.folder_watched = self.folder_path.split(os.sep)[-1]
        self.observer = Observer()
        self.observer.schedule(self, path=folder_path, recursive=True)

    def on_any_event(self, event):
        """
        it catpures any filesytem event and redirects it to the event_dispatcher
        """
        def build_data(cmd,e):
            data = {}
            data['cmd'] = cmd
            data['file'] = {
                "filepath": self.relativize_path(e.src_path),
                "mtime": os.path.getmtime(e.src_path),
                "md5": hashlib.md5(e.src_path).hexdigest()
            }
            return data

        if event.is_directory is False:
            e = event

            if e.event_type == 'modified':
                data = build_data('upload', e)

            elif e.event_type == 'created':
                data = build_data('upload', e)

            elif e.event_type == 'moved':
                data = {'cmd':'move'}
                data['file'] = {
                    'src_path': self.relativize_path(e.src_path),
                    'dest_path': self.relativize_path(e.dest_path)}

            elif e.event_type == 'deleted':
                data = {'cmd':'delete'}
                data['file'] = {
                    "filepath": self.relativize_path(e.src_path)}

            self.event_dispatcher(data['cmd'], data['file'])

    def relativize_path(self,path_to_clean):
        """
        This function relativize the path watched by watchdog:
        for example: /home/user/watched/subfolder will be /subfolder
        """
        return path_to_clean.split(self.folder_watched)[-1]

    def start(self):
        """
        starts the observer thread
        """
        self.observer.start()

    def stop(self):
        """
        stops the observer thread
        """
        self.observer.stop()

    def join(self):
        """
        waits for observer execution finalize
        """
        self.observer.join()

class Daemon(object):
    """
    Root of all evil:
    it loads program configurations,
    it starts directory events observations
    it serves command manager
    """

    TIMEOUT = 0.5

    def __init__(self):
        if load_json('config.json'):
            self.cfg = load_json('config.json')
            self.conn_mng = connection_manager.ConnectionManager(self.cfg)
            self.dir_manager = DirectoryMonitor(self.cfg['path'], self.event_dispatcher)
            self.running = 0
        else:
           print "No config File"
           exit()

    def cmd_dispatcher(self, data):
        """
        It dispatch cmd and args to the api manager object
        """
        cmd = data.keys()[0]  # it will be always one key
        args = data[cmd]  # it will be a dict specifying the args

        print cmd, args

        if cmd == 'shutdown':
            self.shutdown()
        else:
            self.conn_mng.dispatch_request(cmd, args)

    def event_dispatcher(self, cmd, data_file):
        """
        It dispatch the captured events to the api manager object
        """
        self.conn_mng.dispatch_request(cmd, data_file)

    def serve_forever(self):
        """
        it handles the dir manager thread and the server socket together
        """
        backlog = 5
        int_size = struct.calcsize('!i')

        listener_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        listener_socket.bind((self.cfg['host'], self.cfg['port']))
        listener_socket.listen(backlog)
        r_list = [listener_socket]

        self.dir_manager.start()

        self.running = 1
        try:
            while self.running:
                r_ready, w_ready, e_ready = select.select(r_list, [], [], self.TIMEOUT)

                for s in r_ready:

                    if s == listener_socket:
                        # handle the server socket
                        client_socket, client_address = listener_socket.accept()
                        r_list.append(client_socket)
                    else:
                        # handle all other sockets
                        length = s.recv(int_size)
                        if length:
                            length = int(struct.unpack('!i', length)[0])
                            data = json.loads(s.recv(length))
                            self.cmd_dispatcher(data)
                        else:
                            s.close()
                            r_list.remove(s)
        except KeyboardInterrupt:
            self.shutdown()

        self.dir_manager.join()
        listener_socket.close()

    def shutdown(self):
        self.dir_manager.stop()
        self.running = 0

def load_json(conf_path):
    if os.path.isfile(conf_path):
        with open(conf_path,"r") as fo:
            config = json.load(fo)
        return config
    else:
        return False

if __name__ == '__main__':

    daemon = Daemon()
    daemon.serve_forever()
<|endoftext|>


<commit_before>"""Generic socket server classes.

This module tries to capture the various aspects of defining a server:

- address family:
        - AF_INET: IP (Internet Protocol) sockets (default)
        - AF_UNIX: Unix domain sockets
        - others, e.g. AF_DECNET are conceivable (see <socket.h>
- socket type:
        - SOCK_STREAM (reliable stream, e.g. TCP)
        - SOCK_DGRAM (datagrams, e.g. UDP)
- client address verification before further looking at the request
        (This is actually a hook for any processing that needs to look
         at the request before anything else, e.g. logging)
- how to handle multiple requests:
        - synchronous (one request is handled at a time)
        - forking (each request is handled by a new process)
        - threading (each request is handled by a new thread)

The classes in this module favor the server type that is simplest to
write: a synchronous TCP/IP server.  This is bad class design, but
save some typing.  (There's also the issue that a deep class hierarchy
slows down method lookups.)

There are four classes in an inheritance diagram that represent
synchronous servers of four types:

        +-----------+        +------------------+
        | TCPServer |------->| UnixStreamServer |
        +-----------+        +------------------+
              |
              v
        +-----------+        +--------------------+
        | UDPServer |------->| UnixDatagramServer |
        +-----------+        +--------------------+

Note that UnixDatagramServer derives from UDPServer, not from
UnixStreamServer -- the only difference between an IP and a Unix
stream server is the address family, which is simply repeated in both
unix server classes.

Forking and threading versions of each type of server can be created
using the ForkingServer and ThreadingServer mix-in classes.  For
instance, a threading UDP server class is created as follows:

        class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass

The Mix-in class must come first, since it overrides a method defined
in UDPServer!

To implement a service, you must derive a class from
BaseRequestHandler and redefine its handle() method.  You can then run
various versions of the service by combining one of the server classes
with your request handler class.

The request handler class must be different for datagram or stream
services.  This can be hidden by using the mix-in request handler
classes StreamRequestHandler or DatagramRequestHandler.

Of course, you still have to use your head!

For instance, it makes no sense to use a forking server if the service
contains state in memory that can be modified by requests (since the
modifications in the child process would never reach the initial state
kept in the parent process and passed to each child).  In this case,
you can use a threading server, but you will probably have to use
locks to avoid two requests that come in nearly simultaneous to apply
conflicting changes to the server state.

On the other hand, if you are building e.g. an HTTP server, where all
data is stored externally (e.g. in the file system), a synchronous
class will essentially render the service "deaf" while one request is
being handled -- which may be for a very long time if a client is slow
to reqd all the data it has requested.  Here a threading or forking
server is appropriate.

In some cases, it may be appropriate to process part of a request
synchronously, but to finish processing in a forked child depending on
the request data.  This can be implemented by using a synchronous
server and doing an explicit fork in the request handler class's
handle() method.

Another approach to handling multiple simultaneous requests in an
environment that supports neither threads nor fork (or where these are
too expensive or inappropriate for the service) is to maintain an
explicit table of partially finished requests and to use select() to
decide which request to work on next (or whether to handle a new
incoming request).  This is particularly important for stream services
where each client can potentially be connected for a long time (if
threads or subprocesses can't be used).

Future work:
- Standard classes for Sun RPC (which uses either UDP or TCP)
- Standard mix-in classes to implement various authentication
  and encryption schemes
- Standard framework for select-based multiplexing

XXX Open problems:
- What to do with out-of-band data?

"""

__version__ = "0.2"

import socket
import sys
import os

class TCPServer:

    """Base class for various socket-based server classes.

    Defaults to synchronous IP stream (i.e., TCP).

    Methods for the caller:

    - __init__(server_address, RequestHandlerClass)
    - serve_forever()
    - handle_request()  # if you don't use serve_forever()
    - fileno() -> int   # for select()

    Methods that may be overridden:

    - server_bind()
    - server_activate()
    - get_request() -> request, client_address
    - verify_request(request, client_address)
    - process_request(request, client_address)
    - handle_error()

    Methods for derived classes:

    - finish_request(request, client_address)

    Class variables that may be overridden by derived classes or
    instances:

    - address_family
    - socket_type
    - request_queue_size (only for stream sockets)

    Instance variables:

    - server_address
    - RequestHandlerClass
    - socket

    """

    address_family = socket.AF_INET

    socket_type = socket.SOCK_STREAM

    request_queue_size = 5

    def __init__(self, server_address, RequestHandlerClass):
        """Constructor.  May be extended, do not override."""
        self.server_address = server_address
        self.RequestHandlerClass = RequestHandlerClass
        self.socket = socket.socket(self.address_family,
                                    self.socket_type)
        self.server_bind()
        self.server_activate()

    def server_bind(self):
        """Called by constructor to bind the socket.

        May be overridden.

        """
        self.socket.bind(self.server_address)

    def server_activate(self):
        """Called by constructor to activate the server.

        May be overridden.

        """
        self.socket.listen(self.request_queue_size)

    def fileno(self):
        """Return socket file number.

        Interface required by select().

        """
        return self.socket.fileno()

    def serve_forever(self):
        """Handle one request at a time until doomsday."""
        while 1:
            self.handle_request()

    # The distinction between handling, getting, processing and
    # finishing a request is fairly arbitrary.  Remember:
    #
    # - handle_request() is the top-level call.  It calls
    #   get_request(), verify_request() and process_request()
    # - get_request() is different for stream or datagram sockets
    # - process_request() is the place that may fork a new process
    #   or create a new thread to finish the request
    # - finish_request() instantiates the request handler class;
    #   this constructor will handle the request all by itself

    def handle_request(self):
        """Handle one request, possibly blocking."""
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)

    def get_request(self):
        """Get the request and client address from the socket.

        May be overridden.

        """
        return self.socket.accept()

    def verify_request(self, request, client_address):
        """Verify the request.  May be overridden.

        Return true if we should proceed with this request.

        """
        return 1

    def process_request(self, request, client_address):
        """Call finish_request.

        Overridden by ForkingMixIn and ThreadingMixIn.

        """
        self.finish_request(request, client_address)

    def finish_request(self, request, client_address):
        """Finish one request by instantiating RequestHandlerClass."""
        self.RequestHandlerClass(request, client_address, self)

    def handle_error(self, request, client_address):
        """Handle an error gracefully.  May be overridden.

        The default is to print a traceback and continue.

        """
        print '-'*40
        print 'Exception happened during processing of request from',
        print client_address
        import traceback
        traceback.print_exc()
        print '-'*40

class UDPServer(TCPServer):

    """UDP server class."""

    socket_type = socket.SOCK_DGRAM

    max_packet_size = 8192

    def get_request(self):
        data, client_addr = self.socket.recvfrom(self.max_packet_size)
        return (data, self.socket), client_addr

    def server_activate(self):
        # No need to call listen() for UDP.
        pass

class ForkingMixIn:

    """Mix-in class to handle each request in a new process."""

    active_children = None
    max_children = 40

    def collect_children(self):
        """Internal routine to wait for died children."""
        while self.active_children:
            if len(self.active_children) < self.max_children:
                options = os.WNOHANG
            else:
                # If the maximum number of children are already
                # running, block while waiting for a child to exit
                options = 0
            try:
                pid, status = os.waitpid(0, options)
            except os.error:
                pid = None
            if not pid: break
            self.active_children.remove(pid)

    def process_request(self, request, client_address):
        """Fork a new subprocess to process the request."""
        self.collect_children()
        pid = os.fork()
        if pid:
            # Parent process
            if self.active_children is None:
                self.active_children = []
            self.active_children.append(pid)
            return
        else:
            # Child process.
            # This must never return, hence os._exit()!
            try:
                self.socket.close()
                self.finish_request(request, client_address)
                os._exit(0)
            except:
                try:
                    self.handle_error(request,
                                      client_address)
                finally:
                    os._exit(1)

class ThreadingMixIn:
    """Mix-in class to handle each request in a new thread."""

    def process_request(self, request, client_address):
        """Start a new thread to process the request."""
        import threading
        t = threading.Thread(target = self.finish_request,
                             args = (request, client_address))
        t.start()

class ForkingUDPServer(ForkingMixIn, UDPServer): pass
class ForkingTCPServer(ForkingMixIn, TCPServer): pass

class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

if hasattr(socket, 'AF_UNIX'):

    class UnixStreamServer(TCPServer):
        address_family = socket.AF_UNIX

    class UnixDatagramServer(UDPServer):
        address_family = socket.AF_UNIX

    class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass

    class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass

class BaseRequestHandler:

    """Base class for request handler classes.

    This class is instantiated for each request to be handled.  The
    constructor sets the instance variables request, client_address
    and server, and then calls the handle() method.  To implement a
    specific service, all you need to do is to derive a class which
    defines a handle() method.

    The handle() method can find the request as self.request, the
    client address as self.client_address, and the server (in case it
    needs access to per-server information) as self.server.  Since a
    separate instance is created for each request, the handle() method
    can define arbitrary other instance variariables.

    """

    def __init__(self, request, client_address, server):
        self.request = request
        self.client_address = client_address
        self.server = server
        try:
            self.setup()
            self.handle()
            self.finish()
        finally:
            sys.exc_traceback = None    # Help garbage collection

    def setup(self):
        pass

    def __del__(self):
        pass

    def handle(self):
        pass

    def finish(self):
        pass

# The following two classes make it possible to use the same service
# class for stream or datagram servers.
# Each class sets up these instance variables:
# - rfile: a file object from which receives the request is read
# - wfile: a file object to which the reply is written
# When the handle() method returns, wfile is flushed properly

class StreamRequestHandler(BaseRequestHandler):

    """Define self.rfile and self.wfile for stream sockets."""

    def setup(self):
        self.connection = self.request
        self.rfile = self.connection.makefile('rb', 0)
        self.wfile = self.connection.makefile('wb', 0)

    def finish(self):
        self.wfile.flush()
        self.wfile.close()
        self.rfile.close()

class DatagramRequestHandler(BaseRequestHandler):

    """Define self.rfile and self.wfile for datagram sockets."""

    def setup(self):
        import StringIO
        self.packet, self.socket = self.request
        self.rfile = StringIO.StringIO(self.packet)
        self.wfile = StringIO.StringIO(self.packet)

    def finish(self):
        self.socket.sendto(self.wfile.getvalue(), self.client_address)
<commit_msg>Add class variable allow_reuse_address in TCPServer -- if nonzero, the server_bind() method calls setsockopt(SOL_SOCKET, SO_REUSEADDR, 1).<commit_after>"""Generic socket server classes.

This module tries to capture the various aspects of defining a server:

- address family:
        - AF_INET: IP (Internet Protocol) sockets (default)
        - AF_UNIX: Unix domain sockets
        - others, e.g. AF_DECNET are conceivable (see <socket.h>
- socket type:
        - SOCK_STREAM (reliable stream, e.g. TCP)
        - SOCK_DGRAM (datagrams, e.g. UDP)
- client address verification before further looking at the request
        (This is actually a hook for any processing that needs to look
         at the request before anything else, e.g. logging)
- how to handle multiple requests:
        - synchronous (one request is handled at a time)
        - forking (each request is handled by a new process)
        - threading (each request is handled by a new thread)

The classes in this module favor the server type that is simplest to
write: a synchronous TCP/IP server.  This is bad class design, but
save some typing.  (There's also the issue that a deep class hierarchy
slows down method lookups.)

There are four classes in an inheritance diagram that represent
synchronous servers of four types:

        +-----------+        +------------------+
        | TCPServer |------->| UnixStreamServer |
        +-----------+        +------------------+
              |
              v
        +-----------+        +--------------------+
        | UDPServer |------->| UnixDatagramServer |
        +-----------+        +--------------------+

Note that UnixDatagramServer derives from UDPServer, not from
UnixStreamServer -- the only difference between an IP and a Unix
stream server is the address family, which is simply repeated in both
unix server classes.

Forking and threading versions of each type of server can be created
using the ForkingServer and ThreadingServer mix-in classes.  For
instance, a threading UDP server class is created as follows:

        class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass

The Mix-in class must come first, since it overrides a method defined
in UDPServer!

To implement a service, you must derive a class from
BaseRequestHandler and redefine its handle() method.  You can then run
various versions of the service by combining one of the server classes
with your request handler class.

The request handler class must be different for datagram or stream
services.  This can be hidden by using the mix-in request handler
classes StreamRequestHandler or DatagramRequestHandler.

Of course, you still have to use your head!

For instance, it makes no sense to use a forking server if the service
contains state in memory that can be modified by requests (since the
modifications in the child process would never reach the initial state
kept in the parent process and passed to each child).  In this case,
you can use a threading server, but you will probably have to use
locks to avoid two requests that come in nearly simultaneous to apply
conflicting changes to the server state.

On the other hand, if you are building e.g. an HTTP server, where all
data is stored externally (e.g. in the file system), a synchronous
class will essentially render the service "deaf" while one request is
being handled -- which may be for a very long time if a client is slow
to reqd all the data it has requested.  Here a threading or forking
server is appropriate.

In some cases, it may be appropriate to process part of a request
synchronously, but to finish processing in a forked child depending on
the request data.  This can be implemented by using a synchronous
server and doing an explicit fork in the request handler class's
handle() method.

Another approach to handling multiple simultaneous requests in an
environment that supports neither threads nor fork (or where these are
too expensive or inappropriate for the service) is to maintain an
explicit table of partially finished requests and to use select() to
decide which request to work on next (or whether to handle a new
incoming request).  This is particularly important for stream services
where each client can potentially be connected for a long time (if
threads or subprocesses can't be used).

Future work:
- Standard classes for Sun RPC (which uses either UDP or TCP)
- Standard mix-in classes to implement various authentication
  and encryption schemes
- Standard framework for select-based multiplexing

XXX Open problems:
- What to do with out-of-band data?

"""

__version__ = "0.2"

import socket
import sys
import os

class TCPServer:

    """Base class for various socket-based server classes.

    Defaults to synchronous IP stream (i.e., TCP).

    Methods for the caller:

    - __init__(server_address, RequestHandlerClass)
    - serve_forever()
    - handle_request()  # if you don't use serve_forever()
    - fileno() -> int   # for select()

    Methods that may be overridden:

    - server_bind()
    - server_activate()
    - get_request() -> request, client_address
    - verify_request(request, client_address)
    - process_request(request, client_address)
    - handle_error()

    Methods for derived classes:

    - finish_request(request, client_address)

    Class variables that may be overridden by derived classes or
    instances:

    - address_family
    - socket_type
    - request_queue_size (only for stream sockets)
    - reuse_address

    Instance variables:

    - server_address
    - RequestHandlerClass
    - socket

    """

    address_family = socket.AF_INET

    socket_type = socket.SOCK_STREAM

    request_queue_size = 5

    allow_reuse_address = 0

    def __init__(self, server_address, RequestHandlerClass):
        """Constructor.  May be extended, do not override."""
        self.server_address = server_address
        self.RequestHandlerClass = RequestHandlerClass
        self.socket = socket.socket(self.address_family,
                                    self.socket_type)
        self.server_bind()
        self.server_activate()

    def server_bind(self):
        """Called by constructor to bind the socket.

        May be overridden.

        """
        if self.allow_reuse_address:
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)

    def server_activate(self):
        """Called by constructor to activate the server.

        May be overridden.

        """
        self.socket.listen(self.request_queue_size)

    def fileno(self):
        """Return socket file number.

        Interface required by select().

        """
        return self.socket.fileno()

    def serve_forever(self):
        """Handle one request at a time until doomsday."""
        while 1:
            self.handle_request()

    # The distinction between handling, getting, processing and
    # finishing a request is fairly arbitrary.  Remember:
    #
    # - handle_request() is the top-level call.  It calls
    #   get_request(), verify_request() and process_request()
    # - get_request() is different for stream or datagram sockets
    # - process_request() is the place that may fork a new process
    #   or create a new thread to finish the request
    # - finish_request() instantiates the request handler class;
    #   this constructor will handle the request all by itself

    def handle_request(self):
        """Handle one request, possibly blocking."""
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)

    def get_request(self):
        """Get the request and client address from the socket.

        May be overridden.

        """
        return self.socket.accept()

    def verify_request(self, request, client_address):
        """Verify the request.  May be overridden.

        Return true if we should proceed with this request.

        """
        return 1

    def process_request(self, request, client_address):
        """Call finish_request.

        Overridden by ForkingMixIn and ThreadingMixIn.

        """
        self.finish_request(request, client_address)

    def finish_request(self, request, client_address):
        """Finish one request by instantiating RequestHandlerClass."""
        self.RequestHandlerClass(request, client_address, self)

    def handle_error(self, request, client_address):
        """Handle an error gracefully.  May be overridden.

        The default is to print a traceback and continue.

        """
        print '-'*40
        print 'Exception happened during processing of request from',
        print client_address
        import traceback
        traceback.print_exc()
        print '-'*40

class UDPServer(TCPServer):

    """UDP server class."""

    socket_type = socket.SOCK_DGRAM

    max_packet_size = 8192

    def get_request(self):
        data, client_addr = self.socket.recvfrom(self.max_packet_size)
        return (data, self.socket), client_addr

    def server_activate(self):
        # No need to call listen() for UDP.
        pass

class ForkingMixIn:

    """Mix-in class to handle each request in a new process."""

    active_children = None
    max_children = 40

    def collect_children(self):
        """Internal routine to wait for died children."""
        while self.active_children:
            if len(self.active_children) < self.max_children:
                options = os.WNOHANG
            else:
                # If the maximum number of children are already
                # running, block while waiting for a child to exit
                options = 0
            try:
                pid, status = os.waitpid(0, options)
            except os.error:
                pid = None
            if not pid: break
            self.active_children.remove(pid)

    def process_request(self, request, client_address):
        """Fork a new subprocess to process the request."""
        self.collect_children()
        pid = os.fork()
        if pid:
            # Parent process
            if self.active_children is None:
                self.active_children = []
            self.active_children.append(pid)
            return
        else:
            # Child process.
            # This must never return, hence os._exit()!
            try:
                self.socket.close()
                self.finish_request(request, client_address)
                os._exit(0)
            except:
                try:
                    self.handle_error(request,
                                      client_address)
                finally:
                    os._exit(1)

class ThreadingMixIn:
    """Mix-in class to handle each request in a new thread."""

    def process_request(self, request, client_address):
        """Start a new thread to process the request."""
        import threading
        t = threading.Thread(target = self.finish_request,
                             args = (request, client_address))
        t.start()

class ForkingUDPServer(ForkingMixIn, UDPServer): pass
class ForkingTCPServer(ForkingMixIn, TCPServer): pass

class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

if hasattr(socket, 'AF_UNIX'):

    class UnixStreamServer(TCPServer):
        address_family = socket.AF_UNIX

    class UnixDatagramServer(UDPServer):
        address_family = socket.AF_UNIX

    class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass

    class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass

class BaseRequestHandler:

    """Base class for request handler classes.

    This class is instantiated for each request to be handled.  The
    constructor sets the instance variables request, client_address
    and server, and then calls the handle() method.  To implement a
    specific service, all you need to do is to derive a class which
    defines a handle() method.

    The handle() method can find the request as self.request, the
    client address as self.client_address, and the server (in case it
    needs access to per-server information) as self.server.  Since a
    separate instance is created for each request, the handle() method
    can define arbitrary other instance variariables.

    """

    def __init__(self, request, client_address, server):
        self.request = request
        self.client_address = client_address
        self.server = server
        try:
            self.setup()
            self.handle()
            self.finish()
        finally:
            sys.exc_traceback = None    # Help garbage collection

    def setup(self):
        pass

    def __del__(self):
        pass

    def handle(self):
        pass

    def finish(self):
        pass

# The following two classes make it possible to use the same service
# class for stream or datagram servers.
# Each class sets up these instance variables:
# - rfile: a file object from which receives the request is read
# - wfile: a file object to which the reply is written
# When the handle() method returns, wfile is flushed properly

class StreamRequestHandler(BaseRequestHandler):

    """Define self.rfile and self.wfile for stream sockets."""

    def setup(self):
        self.connection = self.request
        self.rfile = self.connection.makefile('rb', 0)
        self.wfile = self.connection.makefile('wb', 0)

    def finish(self):
        self.wfile.flush()
        self.wfile.close()
        self.rfile.close()

class DatagramRequestHandler(BaseRequestHandler):

    """Define self.rfile and self.wfile for datagram sockets."""

    def setup(self):
        import StringIO
        self.packet, self.socket = self.request
        self.rfile = StringIO.StringIO(self.packet)
        self.wfile = StringIO.StringIO(self.packet)

    def finish(self):
        self.socket.sendto(self.wfile.getvalue(), self.client_address)
<|endoftext|>


<commit_before>#!/usr/bin/env python
import unittest
import difflib
import sys, os, sublime

"""
Detect SublimeText version to deal w/ v2 vs v3 deltas
"""
version = sublime.version()
print("Testing with SublimeText version: %s" % version)

"""
For plugin helper functions, load them so we can hit functionality
within the plugin
"""
if version < "3000":
    clipboard_diff = sys.modules["clipboard_diff"]
else:
    clipboard_diff = sys.modules["sublime-clipboard-diff.clipboard_diff"]

"""
Python 2 vs Python 3 - Compatibility:
  * reduce() is functools.reduce
"""
try:
    # Python 2
    _reduce = reduce
except NameError:
    # Python 3
    import functools
    _reduce = functools.reduce

class TestSelectionDiffPlugin(unittest.TestCase):
    """
    Unit tests to validate sublime-selection-diff plugin methods
    """

    test_lines_0 = "line 0\nline 1\nline 2"
    test_lines_1 = "line A\nline 1"
    diff_result  = difflib.unified_diff(
                        clipboard_diff.getLinesHelper(test_lines_0),
                        clipboard_diff.getLinesHelper(test_lines_1),
                        "Clipboard", "Selection")

    expected_diff_text = _reduce(lambda acc, x: acc + x, diff_result, "")

    """
    Helper functions
    """
    def runSimpleViewCommand(self, cmd):
        if self.test_view:
            self.test_view.run_command(cmd)

    def insertTextToTestView(self, text):
        self.test_view.run_command("insert", {"characters": text})

    """
    Setup / Teardown
    """
    def setUp(self):
        """
        Common setUp() for TestSelectionDiffPlugin
        """
        self.test_view = sublime.active_window().new_file()
        self.test_view.set_name("Test View")
        self.test_view.set_scratch(True)

    def tearDown(self):
        """
        Common tearDown() for TestSelectionDiffPlugin
        """
        if self.test_view:
            test_window = self.test_view.window()
            test_window.focus_view(self.test_view)
            test_window.run_command("close_file")

    """
    Helper Function Tests:
    """
    def test_get_selection_str(self):
        """
        Validate the selectionToString helper
        """
        self.insertTextToTestView(self.test_lines_0)
        self.runSimpleViewCommand("select_all")

        selection_txt = clipboard_diff.selectionToString(self.test_view)

        self.assertEqual(self.test_lines_0, selection_txt)

    def test_line_helper(self):
        """
        Validates the line helper
        """
        lines = clipboard_diff.getLinesHelper(self.test_lines_0)

        self.assertEqual(len(lines), 3)
        self.assertEqual(lines[0], "line 0\n")
        self.assertEqual(lines[1], "line 1\n")
        self.assertEqual(lines[2], "line 2\n")

    if version < "3000":
        def test_write_to_view(self):
            """
            Validates writing to a view

            This is limited to < ST3 because the edit object is only
            passed into the TextCommand, and view.begin_edit() does
            not exist anymore.
            """
            lines = clipboard_diff.getLinesHelper(self.test_lines_0)
            edit = self.test_view.begin_edit()
            clipboard_diff.writeLinesToViewHelper(self.test_view, edit, lines)
            self.test_view.end_edit(edit)

            self.runSimpleViewCommand("select_all")
            current_selection = self.test_view.sel()
            selected_text = clipboard_diff.selectionToString(self.test_view)

            self.assertEqual(self.test_lines_0 + "\n", selected_text)

    """
    Plugin Tests:
    """
    def test_clipboard_diff(self):
        """
        Validates the `clipboard_diff` command
        """
        self.insertTextToTestView(self.test_lines_0)
        self.runSimpleViewCommand("select_all")
        self.runSimpleViewCommand("clipboard_diff_cut")
        self.insertTextToTestView(self.test_lines_1)
        self.runSimpleViewCommand("select_all")

        self.runSimpleViewCommand("clipboard_diff")
        diff_view = sublime.active_window().active_view()
        diff_text = diff_view.substr(sublime.Region(0, diff_view.size()))
        diff_view.window().run_command("close_file")

        self.assertEqual(self.expected_diff_text, diff_text)<commit_msg>fix bugs w/ test since i removed the cut / copy code, also added a same selection test<commit_after>#!/usr/bin/env python
import unittest
import difflib
import sys, os, sublime

"""
Detect SublimeText version to deal w/ v2 vs v3 deltas
"""
version = sublime.version()
print("Testing with SublimeText version: %s" % version)

"""
For plugin helper functions, load them so we can hit functionality
within the plugin
"""
if version < "3000":
    clipboard_diff = sys.modules["clipboard_diff"]
else:
    clipboard_diff = sys.modules["sublime-clipboard-diff.clipboard_diff"]

"""
Python 2 vs Python 3 - Compatibility:
  * reduce() is functools.reduce
"""
try:
    # Python 2
    _reduce = reduce
except NameError:
    # Python 3
    import functools
    _reduce = functools.reduce

class TestSelectionDiffPlugin(unittest.TestCase):
    """
    Unit tests to validate sublime-selection-diff plugin methods
    """

    test_lines_0 = "line 0\nline 1\nline 2"
    test_lines_1 = "line A\nline 1"
    diff_result  = difflib.unified_diff(
                        clipboard_diff.getLinesHelper(test_lines_0),
                        clipboard_diff.getLinesHelper(test_lines_1),
                        "Clipboard", "Selection")

    expected_diff_text = _reduce(lambda acc, x: acc + x, diff_result, "")

    """
    Helper functions
    """
    def runSimpleViewCommand(self, cmd):
        if self.test_view:
            self.test_view.run_command(cmd)

    def insertTextToTestView(self, text):
        self.test_view.run_command("insert", {"characters": text})

    """
    Setup / Teardown
    """
    def setUp(self):
        """
        Common setUp() for TestSelectionDiffPlugin
        """
        self.test_view = sublime.active_window().new_file()
        self.test_view.set_name("Test View")
        self.test_view.set_scratch(True)

    def tearDown(self):
        """
        Common tearDown() for TestSelectionDiffPlugin
        """
        test_window = self.test_view.window()
        test_window.focus_view(self.test_view)
        test_window.run_command("close_file")

    """
    Helper Function Tests:
    """
    def test_get_selection_str(self):
        """
        Validate the selectionToString helper
        """
        self.insertTextToTestView(self.test_lines_0)
        self.runSimpleViewCommand("select_all")

        selection_txt = clipboard_diff.selectionToString(self.test_view)

        self.assertEqual(self.test_lines_0, selection_txt)

    def test_line_helper(self):
        """
        Validates the line helper
        """
        lines = clipboard_diff.getLinesHelper(self.test_lines_0)

        self.assertEqual(len(lines), 3)
        self.assertEqual(lines[0], "line 0\n")
        self.assertEqual(lines[1], "line 1\n")
        self.assertEqual(lines[2], "line 2\n")

    if version < "3000":
        def test_write_to_view(self):
            """
            Validates writing to a view

            This is limited to < ST3 because the edit object is only
            passed into the TextCommand, and view.begin_edit() does
            not exist anymore.
            """
            lines = clipboard_diff.getLinesHelper(self.test_lines_0)
            edit = self.test_view.begin_edit()
            clipboard_diff.writeLinesToViewHelper(self.test_view, edit, lines)
            self.test_view.end_edit(edit)

            self.runSimpleViewCommand("select_all")
            current_selection = self.test_view.sel()
            selected_text = clipboard_diff.selectionToString(self.test_view)

            self.assertEqual(self.test_lines_0 + "\n", selected_text)

    """
    Plugin Tests:
    """
    def test_clipboard_diff(self):
        """
        Validates the `clipboard_diff` command
        """
        self.insertTextToTestView(self.test_lines_0)
        self.runSimpleViewCommand("select_all")
        self.runSimpleViewCommand("cut")
        self.insertTextToTestView(self.test_lines_1)
        self.runSimpleViewCommand("select_all")

        self.runSimpleViewCommand("clipboard_diff")
        diff_view = sublime.active_window().active_view()
        diff_text = diff_view.substr(sublime.Region(0, diff_view.size()))
        diff_view.window().run_command("close_file")

        self.assertEqual(self.expected_diff_text, diff_text)

    def test_clipboard_diff_same_selection(self):
        """
        Validates the `clipboard_diff` command when run
        with the same selection
        """
        self.insertTextToTestView(self.test_lines_0)
        self.runSimpleViewCommand("select_all")
        self.runSimpleViewCommand("copy")

        self.runSimpleViewCommand("clipboard_diff")
        diff_view = sublime.active_window().active_view()
        diff_text = diff_view.substr(sublime.Region(0, diff_view.size()))
        diff_view.window().run_command("close_file")

        self.assertEqual("", diff_text)
<|endoftext|>


<commit_before>import os
import subprocess
import os.path
import sys
import shutil

if os.name == "nt":
    import _winreg as winreg

tools_dir = os.path.join("..", "tools")
assets_dir = "assets"

action_strings = ["code", "shaders", "models", "textures", "audio", "fonts", "configs"]
action_descriptions = ["generate projects and workspaces",
                       "generate shaders and compile binaries",
                       "make binary mesh and animation files",
                       "compress textures and generate mips",
                       "compress and convert audio to platorm format",
                       "copy fonts to data directory",
                       "copy json configs to data directory"]
execute_actions = []
extra_build_steps = []
build_steps = []

python_exec = ""
shader_options = ""
project_options = ""

platform = ""
ide = ""
renderer = ""
data_dir = ""

premake_exec = os.path.join(tools_dir, "premake","premake5")
shader_script = os.path.join(tools_dir, "build_shaders.py")
textures_script = os.path.join(tools_dir, "build_textures.py")
audio_script = os.path.join(tools_dir, "build_audio.py")
models_script = os.path.join(tools_dir, "build_models.py")

def display_help():
    print("--------pmtech build--------")
    print("run with no arguments for prompted input")
    print("commandline arguments")
    print("\t-platform <osx, win32, ios>")
    print("\t-ide <xcode4, vs2015, v2017>")
    print("\t-renderer <dx11, opengl>")
    print("\t-actions")
    for i in range(0, len(action_strings)):
        print("\t\t" + action_strings[i] + " - " + action_descriptions[ i ])

def parse_args(args):
    global ide
    global renderer
    global platform
    for index in range(0, len(sys.argv)):
        if sys.argv[index] == "-help":
            display_help()
        if sys.argv[index] == "-platform":
            platform = sys.argv[index+1]
            index += 1
        if sys.argv[index] == "-ide":
            ide = sys.argv[index+1]
            index += 1
        if sys.argv[index] == "-renderer":
            ide = sys.argv[index+1]
            index += 1
        elif sys.argv[index] == "-actions":
            for j in range(index+1, len(sys.argv)):
                if "-" not in sys.argv[j]:
                    execute_actions.append(sys.argv[j])
                else:
                    break

def get_platform_info():
    global ide
    global renderer
    global platform
    global python_exec
    global shader_options
    global project_options
    global data_dir

    if os.name == "posix":
        if ide == "":
            ide = "xcode4"
        if renderer == "":
            renderer = "opengl"
        if platform == "":
            platform = "osx"
        python_exec = os.path.join(tools_dir, "bin", "python", "osx", "python3")
    else:
        if ide == "":
            ide = "vs2017"
        if renderer == "":
            renderer = "dx11"
        if platform == "":
            platform = "win32"
        #python_exec = os.path.join(tools_dir, "bin", "python", "win32", "python3")

    extra_target_info = ""
    if platform == "win32":
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Microsoft SDKs\Windows', 0,
                           (winreg.KEY_WOW64_64KEY + winreg.KEY_ALL_ACCESS))
        sdk_ver = winreg.EnumValue(key, 0)
        if len(sdk_ver) >= 0 :
            if sdk_ver[0] == "CurrentVersion":
                extra_target_info += "--sdk_version=" + str(sdk_ver[1])

    if platform == "ios":
        extra_target_info = "--xcode_target=ios"
        extra_build_steps.append(python_exec + " " + os.path.join(tools_dir, "project_ios", "copy_files.py"))
        extra_build_steps.append(python_exec + " " + os.path.join(tools_dir, "project_ios", "set_xcode_target.py"))

    project_options = ide + " --renderer=" + renderer + " " + extra_target_info

    if renderer == "dx11":
        shader_options = "hlsl win32"
    elif renderer == "opengl":
        shader_options = "glsl osx"

    data_dir = os.path.join("bin", platform, "data")

if len(sys.argv) <= 1:
    print("please enter what you want to build")
    print("1. code projects")
    print("2. shaders")
    print("3. models")
    print("4. textures")
    print("5. audio")
    print("6. fonts")
    print("7. configs")
    print("8. all")
    print("0. show full command line options")

    all_value = 8
    input_val = int(input())

    if input_val==0:
        display_help()

    add_all = False

    if input_val == all_value:
        add_all = True

    for index in range(0,all_value-1):
        if input_val-1 == index or add_all:
            execute_actions.append(action_strings[index])
else:
    parse_args(sys.argv)

get_platform_info()

copy_steps = []

for action in execute_actions:
    if action == "code":
        build_steps.append(premake_exec + " " + project_options)
    elif action == "shaders":
        build_steps.append(python_exec + " " + shader_script + " " + shader_options)
    elif action == "models":
        build_steps.append(python_exec + " " + models_script)
    elif action == "textures":
        build_steps.append(python_exec + " " + textures_script)
    elif action == "audio":
        build_steps.append(python_exec + " " + audio_script)
    elif action == "fonts" or action == "configs":
        copy_steps.append(action)

for step in build_steps:
    subprocess.check_call(step, shell=True)

for step in extra_build_steps:
    subprocess.check_call(step, shell=True)

for step in copy_steps:
    dest_dir = os.path.join(data_dir, step)
    if os.path.exists(dest_dir):
        shutil.rmtree(dest_dir)
    print("copying: " + step + " to " + dest_dir)
    shutil.copytree(os.path.join(assets_dir, step), dest_dir)

<commit_msg>skip wireg<commit_after>import os
import subprocess
import os.path
import sys
import shutil

use_win_reg = 0

if os.name == "nt" and use_win_reg == 1:
    import _winreg as winreg

tools_dir = os.path.join("..", "tools")
assets_dir = "assets"

action_strings = ["code", "shaders", "models", "textures", "audio", "fonts", "configs"]
action_descriptions = ["generate projects and workspaces",
                       "generate shaders and compile binaries",
                       "make binary mesh and animation files",
                       "compress textures and generate mips",
                       "compress and convert audio to platorm format",
                       "copy fonts to data directory",
                       "copy json configs to data directory"]
execute_actions = []
extra_build_steps = []
build_steps = []

python_exec = ""
shader_options = ""
project_options = ""

platform = ""
ide = ""
renderer = ""
data_dir = ""

premake_exec = os.path.join(tools_dir, "premake","premake5")
shader_script = os.path.join(tools_dir, "build_shaders.py")
textures_script = os.path.join(tools_dir, "build_textures.py")
audio_script = os.path.join(tools_dir, "build_audio.py")
models_script = os.path.join(tools_dir, "build_models.py")

def display_help():
    print("--------pmtech build--------")
    print("run with no arguments for prompted input")
    print("commandline arguments")
    print("\t-platform <osx, win32, ios>")
    print("\t-ide <xcode4, vs2015, v2017>")
    print("\t-renderer <dx11, opengl>")
    print("\t-actions")
    for i in range(0, len(action_strings)):
        print("\t\t" + action_strings[i] + " - " + action_descriptions[ i ])

def parse_args(args):
    global ide
    global renderer
    global platform
    for index in range(0, len(sys.argv)):
        if sys.argv[index] == "-help":
            display_help()
        if sys.argv[index] == "-platform":
            platform = sys.argv[index+1]
            index += 1
        if sys.argv[index] == "-ide":
            ide = sys.argv[index+1]
            index += 1
        if sys.argv[index] == "-renderer":
            ide = sys.argv[index+1]
            index += 1
        elif sys.argv[index] == "-actions":
            for j in range(index+1, len(sys.argv)):
                if "-" not in sys.argv[j]:
                    execute_actions.append(sys.argv[j])
                else:
                    break

def get_platform_info():
    global ide
    global renderer
    global platform
    global python_exec
    global shader_options
    global project_options
    global data_dir

    if os.name == "posix":
        if ide == "":
            ide = "xcode4"
        if renderer == "":
            renderer = "opengl"
        if platform == "":
            platform = "osx"
        python_exec = os.path.join(tools_dir, "bin", "python", "osx", "python3")
    else:
        if ide == "":
            ide = "vs2017"
        if renderer == "":
            renderer = "dx11"
        if platform == "":
            platform = "win32"
        #python_exec = os.path.join(tools_dir, "bin", "python", "win32", "python3")

    extra_target_info = ""
    if platform == "win32" and use_win_reg:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Microsoft SDKs\Windows', 0,
                           (winreg.KEY_WOW64_64KEY + winreg.KEY_ALL_ACCESS))
        sdk_ver = winreg.EnumValue(key, 0)
        if len(sdk_ver) >= 0 :
            if sdk_ver[0] == "CurrentVersion":
                extra_target_info += "--sdk_version=" + str(sdk_ver[1])

    if platform == "ios":
        extra_target_info = "--xcode_target=ios"
        extra_build_steps.append(python_exec + " " + os.path.join(tools_dir, "project_ios", "copy_files.py"))
        extra_build_steps.append(python_exec + " " + os.path.join(tools_dir, "project_ios", "set_xcode_target.py"))

    project_options = ide + " --renderer=" + renderer + " " + extra_target_info

    if renderer == "dx11":
        shader_options = "hlsl win32"
    elif renderer == "opengl":
        shader_options = "glsl osx"

    data_dir = os.path.join("bin", platform, "data")

if len(sys.argv) <= 1:
    print("please enter what you want to build")
    print("1. code projects")
    print("2. shaders")
    print("3. models")
    print("4. textures")
    print("5. audio")
    print("6. fonts")
    print("7. configs")
    print("8. all")
    print("0. show full command line options")

    all_value = 8
    input_val = int(input())

    if input_val==0:
        display_help()

    add_all = False

    if input_val == all_value:
        add_all = True

    for index in range(0,all_value-1):
        if input_val-1 == index or add_all:
            execute_actions.append(action_strings[index])
else:
    parse_args(sys.argv)

get_platform_info()

copy_steps = []

for action in execute_actions:
    if action == "code":
        build_steps.append(premake_exec + " " + project_options)
    elif action == "shaders":
        build_steps.append(python_exec + " " + shader_script + " " + shader_options)
    elif action == "models":
        build_steps.append(python_exec + " " + models_script)
    elif action == "textures":
        build_steps.append(python_exec + " " + textures_script)
    elif action == "audio":
        build_steps.append(python_exec + " " + audio_script)
    elif action == "fonts" or action == "configs":
        copy_steps.append(action)

for step in build_steps:
    subprocess.check_call(step, shell=True)

for step in extra_build_steps:
    subprocess.check_call(step, shell=True)

for step in copy_steps:
    dest_dir = os.path.join(data_dir, step)
    if os.path.exists(dest_dir):
        shutil.rmtree(dest_dir)
    print("copying: " + step + " to " + dest_dir)
    shutil.copytree(os.path.join(assets_dir, step), dest_dir)

<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''

module: uptimerobot
short_description: Pause and start Uptime Robot monitoring
description:
    - This module will let you start and pause Uptime Robot Monitoring
author: "Nate Kingsley (@nate-kingsley)"
version_added: "1.9"
requirements:
    - Valid Uptime Robot API Key
options:
    state:
        description:
            - Define whether or not the monitor should be running or paused.
        required: true
        choices: [ "started", "paused" ]
    monitorid:
        description:
            - ID of the monitor to check.
        required: true
    apikey:
        description:
            - Uptime Robot API key.
        required: true
notes:
    - Support for adding and removing monitors and alert contacts has not yet been implemented.
'''

EXAMPLES = '''
# Pause the monitor with an ID of 12345.
- uptimerobot:
    monitorid: 12345
    apikey: 12345-1234512345
    state: paused

# Start the monitor with an ID of 12345.
- uptimerobot:
    monitorid: 12345
    apikey: 12345-1234512345
    state: started
'''

import json

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves.urllib.parse import urlencode
from ansible.module_utils.urls import fetch_url

API_BASE = "http://api.uptimerobot.com/"

API_ACTIONS = dict(
    status='getMonitors?',
    editMonitor='editMonitor?'
)

API_FORMAT = 'json'
API_NOJSONCALLBACK = 1
CHANGED_STATE = False
SUPPORTS_CHECK_MODE = False

def checkID(module, params):

    data = urlencode(params)
    full_uri = API_BASE + API_ACTIONS['status'] + data
    req, info = fetch_url(module, full_uri)
    result = req.read()
    jsonresult = json.loads(result)
    req.close()
    return jsonresult

def startMonitor(module, params):

    params['monitorStatus'] = 1
    data = urlencode(params)
    full_uri = API_BASE + API_ACTIONS['editMonitor'] + data
    req, info = fetch_url(module, full_uri)
    result = req.read()
    jsonresult = json.loads(result)
    req.close()
    return jsonresult['stat']

def pauseMonitor(module, params):

    params['monitorStatus'] = 0
    data = urlencode(params)
    full_uri = API_BASE + API_ACTIONS['editMonitor'] + data
    req, info = fetch_url(module, full_uri)
    result = req.read()
    jsonresult = json.loads(result)
    req.close()
    return jsonresult['stat']

def main():

    module = AnsibleModule(
        argument_spec=dict(
            state=dict(required=True, choices=['started', 'paused']),
            apikey=dict(required=True),
            monitorid=dict(required=True)
        ),
        supports_check_mode=SUPPORTS_CHECK_MODE
    )

    params = dict(
        apiKey=module.params['apikey'],
        monitors=module.params['monitorid'],
        monitorID=module.params['monitorid'],
        format=API_FORMAT,
        noJsonCallback=API_NOJSONCALLBACK
    )

    check_result = checkID(module, params)

    if check_result['stat'] != "ok":
        module.fail_json(
            msg="failed",
            result=check_result['message']
        )

    if module.params['state'] == 'started':
        monitor_result = startMonitor(module, params)
    else:
        monitor_result = pauseMonitor(module, params)

    module.exit_json(
        msg="success",
        result=monitor_result
    )

if __name__ == '__main__':
    main()
<commit_msg>Hide apikey from log in uptimerobot (#37342)<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''

module: uptimerobot
short_description: Pause and start Uptime Robot monitoring
description:
    - This module will let you start and pause Uptime Robot Monitoring
author: "Nate Kingsley (@nate-kingsley)"
version_added: "1.9"
requirements:
    - Valid Uptime Robot API Key
options:
    state:
        description:
            - Define whether or not the monitor should be running or paused.
        required: true
        choices: [ "started", "paused" ]
    monitorid:
        description:
            - ID of the monitor to check.
        required: true
    apikey:
        description:
            - Uptime Robot API key.
        required: true
notes:
    - Support for adding and removing monitors and alert contacts has not yet been implemented.
'''

EXAMPLES = '''
# Pause the monitor with an ID of 12345.
- uptimerobot:
    monitorid: 12345
    apikey: 12345-1234512345
    state: paused

# Start the monitor with an ID of 12345.
- uptimerobot:
    monitorid: 12345
    apikey: 12345-1234512345
    state: started
'''

import json

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves.urllib.parse import urlencode
from ansible.module_utils.urls import fetch_url

API_BASE = "http://api.uptimerobot.com/"

API_ACTIONS = dict(
    status='getMonitors?',
    editMonitor='editMonitor?'
)

API_FORMAT = 'json'
API_NOJSONCALLBACK = 1
CHANGED_STATE = False
SUPPORTS_CHECK_MODE = False

def checkID(module, params):

    data = urlencode(params)
    full_uri = API_BASE + API_ACTIONS['status'] + data
    req, info = fetch_url(module, full_uri)
    result = req.read()
    jsonresult = json.loads(result)
    req.close()
    return jsonresult

def startMonitor(module, params):

    params['monitorStatus'] = 1
    data = urlencode(params)
    full_uri = API_BASE + API_ACTIONS['editMonitor'] + data
    req, info = fetch_url(module, full_uri)
    result = req.read()
    jsonresult = json.loads(result)
    req.close()
    return jsonresult['stat']

def pauseMonitor(module, params):

    params['monitorStatus'] = 0
    data = urlencode(params)
    full_uri = API_BASE + API_ACTIONS['editMonitor'] + data
    req, info = fetch_url(module, full_uri)
    result = req.read()
    jsonresult = json.loads(result)
    req.close()
    return jsonresult['stat']

def main():

    module = AnsibleModule(
        argument_spec=dict(
            state=dict(required=True, choices=['started', 'paused']),
            apikey=dict(required=True, no_log=True),
            monitorid=dict(required=True)
        ),
        supports_check_mode=SUPPORTS_CHECK_MODE
    )

    params = dict(
        apiKey=module.params['apikey'],
        monitors=module.params['monitorid'],
        monitorID=module.params['monitorid'],
        format=API_FORMAT,
        noJsonCallback=API_NOJSONCALLBACK
    )

    check_result = checkID(module, params)

    if check_result['stat'] != "ok":
        module.fail_json(
            msg="failed",
            result=check_result['message']
        )

    if module.params['state'] == 'started':
        monitor_result = startMonitor(module, params)
    else:
        monitor_result = pauseMonitor(module, params)

    module.exit_json(
        msg="success",
        result=monitor_result
    )

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


<commit_before>import os
import glob
import time
import RPi.GPIO as GPIO
import json
from datetime import datetime
from firebase import firebase

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

import requests.packages.urllib3

firebase = firebase.FirebaseApplication('https://iot-homebrew.firebaseio.com', None)

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

on_pin = 24
off_pin = 26

GPIO.setmode(GPIO.BOARD)
GPIO.setup(on_pin, GPIO.OUT)
GPIO.setup(off_pin, GPIO.OUT)

override = 0
desired_temp = 0
hysteresis = 0.5
power_is_on = False
get_current_program_interval = 5
current_program = {}
current_step_id = {}

content_type = {'X_CONTENT_TYPE': 'application/json'}

def read_temp_raw():
	f = open(device_file, 'r')
	lines = f.readlines()
	f.close()
	return lines

def power_on():
	print('Virta paalle')
	global power_is_on
	power_is_on = True
	GPIO.output(on_pin, True)
	post_power(power_is_on)

def power_off():
	print('Virta pois')
	global power_is_on
	power_is_on = False
	GPIO.output(on_pin, False)
	post_power(power_is_on)

def read_temp():
	lines = read_temp_raw()

	while lines[0].strip()[-3:] != 'YES':
		time.sleep(0.2)
		lines = read_temp_raw()

	equals_pos = lines[1].find('t=')

	if equals_pos != -1:
		temp_string = lines[1][equals_pos+2:]
		temp = float(temp_string) / 1000.0
		return temp

def post_temp(current_temp):
	global content_type
	temp_info = {"timestamp": time.time(), "temp": current_temp, "desiredTemp": desired_temp, "step": current_step_id}
	firebase.post(url='/Temperatures', data=temp_info, headers=content_type)

def post_power(power):
	global content_type
	json_power = {"timestamp": time.time(), "state": power}
	firebase.post(url='/Power', data=json_power, headers=content_type)

def get_current_program():
	global desired_temp
	global current_program
	current_program = firebase.get('/CurrentStep', None)

def get_override():
	global override
	power = firebase.get('/Power', None)
	override = power["override"]

def get_desired_temp():
	if current_program != None:
		return float(current_program["temp"])
	return 0

GPIO.output(on_pin, False)
GPIO.output(off_pin, False)
power_off()
print('Aloitetaan')
print('Laitefilu: ' + device_file)
loops = 0
while True:

	if loops == 0:
		get_current_program()
		get_override()
		if override == 1:
			power_off()
		elif override == 2:
			power_on()
		else:
			override = 0
		loops = get_current_program_interval
	loops = loops - 1

	current_temp = read_temp()
	desired_temp = get_desired_temp()

	print("desired temp: " + str(desired_temp) + ", current temp: " + str(current_temp))

	post_temp(current_temp)

	if override != 0:
		print("Overrided " + override)
	elif current_temp > (desired_temp - hysteresis) and power_is_on == True:
		power_off()
	elif current_temp < (desired_temp - hysteresis) and power_is_on == False:
		power_on()

	time.sleep(1)
<commit_msg>Casted int to str<commit_after>import os
import glob
import time
import RPi.GPIO as GPIO
import json
from datetime import datetime
from firebase import firebase

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

import requests.packages.urllib3

firebase = firebase.FirebaseApplication('https://iot-homebrew.firebaseio.com', None)

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

on_pin = 24
off_pin = 26

GPIO.setmode(GPIO.BOARD)
GPIO.setup(on_pin, GPIO.OUT)
GPIO.setup(off_pin, GPIO.OUT)

override = 0
desired_temp = 0
hysteresis = 0.5
power_is_on = False
get_current_program_interval = 5
current_program = {}
current_step_id = {}

content_type = {'X_CONTENT_TYPE': 'application/json'}

def read_temp_raw():
	f = open(device_file, 'r')
	lines = f.readlines()
	f.close()
	return lines

def power_on():
	print('Virta paalle')
	global power_is_on
	power_is_on = True
	GPIO.output(on_pin, True)
	post_power(power_is_on)

def power_off():
	print('Virta pois')
	global power_is_on
	power_is_on = False
	GPIO.output(on_pin, False)
	post_power(power_is_on)

def read_temp():
	lines = read_temp_raw()

	while lines[0].strip()[-3:] != 'YES':
		time.sleep(0.2)
		lines = read_temp_raw()

	equals_pos = lines[1].find('t=')

	if equals_pos != -1:
		temp_string = lines[1][equals_pos+2:]
		temp = float(temp_string) / 1000.0
		return temp

def post_temp(current_temp):
	global content_type
	temp_info = {"timestamp": time.time(), "temp": current_temp, "desiredTemp": desired_temp, "step": current_step_id}
	firebase.post(url='/Temperatures', data=temp_info, headers=content_type)

def post_power(power):
	global content_type
	json_power = {"timestamp": time.time(), "state": power}
	firebase.post(url='/Power', data=json_power, headers=content_type)

def get_current_program():
	global desired_temp
	global current_program
	current_program = firebase.get('/CurrentStep', None)

def get_override():
	global override
	power = firebase.get('/Power', None)
	override = power["override"]

def get_desired_temp():
	if current_program != None:
		return float(current_program["temp"])
	return 0

GPIO.output(on_pin, False)
GPIO.output(off_pin, False)
power_off()
print('Aloitetaan')
print('Laitefilu: ' + device_file)
loops = 0
while True:

	if loops == 0:
		get_current_program()
		get_override()
		if override == 1:
			power_off()
		elif override == 2:
			power_on()
		else:
			override = 0
		loops = get_current_program_interval
	loops = loops - 1

	current_temp = read_temp()
	desired_temp = get_desired_temp()

	print("desired temp: " + str(desired_temp) + ", current temp: " + str(current_temp))

	post_temp(current_temp)

	if override != 0:
		print("Overrided " + str(override))
	elif current_temp > (desired_temp - hysteresis) and power_is_on == True:
		power_off()
	elif current_temp < (desired_temp - hysteresis) and power_is_on == False:
		power_on()

	time.sleep(1)
<|endoftext|>


<commit_before>import os, sys

# edit your username below
sys.path.append("/home/{{cookiecutter.helio_user}}/public_html/{{cookiecutter.project_name}}");

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()
def application(environ, start_response):
    environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
    return _application(environ, start_response)
<commit_msg>Edited dispatch.wsgi<commit_after>import os, sys

# edit your username below
sys.path.append("/home/{{cookiecutter.helio_user}}/public_html/{{cookiecutter.project_name}}");

os.environ['DJANGO_SETTINGS_MODULE'] = '{{cookiecutter.project_name}}.settings'

from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()
def application(environ, start_response):
    environ['PATH_INFO'] = environ['SCRIPT_NAME'] + environ['PATH_INFO']
    return _application(environ, start_response)
<|endoftext|>