Example #1
0
    def setUp(self):
        self.game = Game(3, 3, 3)

        self.cell1 = Cell(1, 3, 0)
        self.cell2 = Cell(2, 1, 0)
        self.cell3 = Cell(1, 1, 1)
        self.cell4 = Cell(2, 2, 0)
Example #2
0
    def setUp(self):

        self.cell1 = Cell(1, 1, 0)
        self.cell2 = Cell(1, 1, 1)

        self.line = Line([
            self.cell1,
            self.cell2
        ], 1)
 def setUp(self):
     self.player_one = Player("Gosho", 50, 2, 16)
     self.player_two = Player("Misho", 50, 2, 16)
     self.player_three = Player("Misho", 20, 2, 16)
     self.player_four = Player("Misho", 0, 2, 16)
     self.cards = [GoodCard(), BadCard(), TripCard()]
     self.field = [[{
         1: Cell(0, 0, self.cards)
     }, {
         2: Cell(0, 1, self.cards)
     }]]
     self.levels = {"SMALL": (1, 2), "MEDIUM": (2, 3), "LARGE": (3, 4)}
Example #4
0
    def setData(self, index, data, role=None):
        row, column = index.row(), index.column()
        cell = Cell.get(row, column)
        if not cell:
            if data:
                cell = Cell(row, column)
                cell.data = data
                self.headerDataChanged.emit(Qt.Horizontal, column,
                                            Qt.DisplayRole)
                ColList.List.reset()
        else:
            cell.data = data

        return True
Example #5
0
    def RPC__Worksheet__fork(self, origin_uuid, folder_uuid):
        """Create an exact copy of a worksheet from an origin. """
        try:
            origin = Worksheet.objects.get(uuid=origin_uuid)
        except Worksheet.DoesNotExist:
            self.return_api_error('origin-does-not-exist')
            return

        if origin.published is None:
            self.return_api_error('origin-is-not-published')
            return

        try:
            folder = Folder.objects.get(uuid=folder_uuid)
        except Folder.DoesNotExist:
            self.return_api_error('folder-does-not-exist')
            return

        worksheet = Worksheet(
            user=self.user,
            name=origin.name,
            description=origin.description,
            engine=origin.engine,
            origin=origin,
            folder=folder)
        worksheet.save()

        order = []

        for uuid in origin.get_order():
            try:
                base = Cell.objects.get(uuid=uuid)
            except Cell.DoesNotExist:
                pass
            else:
                cell = Cell(user=self.user,
                            type=base.type,
                            parent=base.parent,
                            content=base.content,
                            worksheet=worksheet)
                order.append(cell.uuid)
                cell.save()

        worksheet.set_order(order)
        worksheet.save()

        self.return_api_result({
            'uuid': worksheet.uuid,
            'name': worksheet.name,
        })
Example #6
0
def csv_convert_obj(path):
    _list = list()
    with open(path) as f:
        _csv = csv.reader(f, delimiter=';')
        if os.path.basename(path).lower().startswith('cell-'):
            for row in _csv:
                if list(row).__len__() == 5:
                    _list.append(Cell(row[1], row[2], row[3], row[4]))
        elif os.path.basename(path).lower().startswith('element-'):
            for row in _csv:
                if list(row).__len__() == 7:
                    _list.append(
                        Element(row[1], row[2], row[3], row[4], row[5],
                                row[6]))
        elif os.path.basename(path).lower().startswith('dimension-'):
            for row in _csv:
                if list(row).__len__() == 4:
                    _list.append(Dimension(row[1], row[2], row[3]))
        elif os.path.basename(path).lower().startswith('cube-'):
            for row in _csv:
                if list(row).__len__() == 5:
                    _list.append(Cube(row[1], row[2], row[3], row[4]))
        elif os.path.basename(path).lower().startswith('database-'):
            for row in _csv:
                if list(row).__len__() == 3:
                    _list.append(Database(row[1], row[2]))
    return _list
Example #7
0
def update_matrix(df_fut, df_opt, df_undrl):
    # combining tables fut and opt
    df_fut['type'] = 'F'
    df_opt['type'] = 'O'
    df_futopt_grouped = pd.concat([df_fut, df_opt]).groupby(["lasttrademonth", "assetcode"])

    # cell - max OI_RUB for coloring the cell
    cell_max_OI_rub = df_futopt_grouped['oi_rub'].sum().max()
    d_colors = get_colors()
    n_colors = len(d_colors)

    # cleaning cells table
    db.session.query(Cell).delete()

    # filling cells
    for name, group in df_futopt_grouped:
        cell_OI_rub = group['oi_rub'].sum()
        cell_type = set(group['type'].unique())
        db_cell = Cell(underlying=name[1], year_month=name[0],
                       color=d_colors[round_up_log(cell_OI_rub, cell_max_OI_rub, n_colors)],
                       label=" ".join(sorted([e for e in cell_type])),
                       date_created=datetime.utcnow())
        db.session.add(db_cell)

    db.session.commit()
    return 'd'
Example #8
0
 def set_board(self):
     for row in range(self._game._rows):
         rowCells = []
         for col in range(self._game._cols):
             rowCells.append(Cell())
         self._game._board.append(rowCells)
     self._create_mines()
     self._init_cell()
Example #9
0
class TestsCellModel(TestCase):

    """
    Test Cell model and its methods
    """

    def setUp(self):
        self.cell = Cell(1, 1, 1)

    def test_can_create_a_valid_cell(self):
        self.assertIsInstance(self.cell, Cell)

    def test_can_return_a_formatted_repr_for_object(self):
        self.assertEqual(self.cell.__repr__(), "Cell (1 1 1)")

    def test_can_return_a_formatted_str_for_object(self):
        self.assertEqual(self.cell.__str__(), "Cell (1 1 1)")
Example #10
0
    def test_model_cell(self):
        """
        Test cell model works
        """
        cell = Cell()
        self.assertEqual(cell._isMine, False)
        self.assertEqual(cell._isRevealed, False)
        self.assertEqual(cell._isRevealed, False)
        self.assertEqual(cell._minesAround, 0)

        cell._isMine = True
        cell._isRevealed = True
        cell._isFlagged = True
        cell._minesAround = 8
        self.assertEqual(cell._isMine, True)
        self.assertEqual(cell._isRevealed, True)
        self.assertEqual(cell._isFlagged, True)
        self.assertEqual(cell._minesAround, 8)
Example #11
0
def insert_row(calendar, current_user, date):
    row = CalendarRow(parent=calendar.key)
    row.put()

    cell_keys = []
    for i in range(len(calendar.column_names)):
        cell = Cell(parent=row.key)
        cell.put()
        cell_keys.append(cell.key)

    date_cell = DateCell(parent=row.key, date=date)
    date_cell.put()

    row.cell_keys = cell_keys
    row.date_cell = date_cell.key
    row.put()
    calendar.row_keys.append(row.key)
    calendar.put()
Example #12
0
    def execute(self):
        old_new_values = OldNewValue.all()
        # onv = old new value
        for onv in old_new_values.values():

            if onv.type == OldNewValue.SingleValue \
                    or onv.type == OldNewValue.Range:

                for cell in Cell.get_by_value(onv.old1):
                    cell.data = onv.new
Example #13
0
    def data(self, index, role=None):
        # logger.debug("index={}, role={}".format(QModelIndex, role))
        row, column = index.row(), index.column()
        if role == Qt.DisplayRole:
            cell = Cell.get(row, column)
            return cell.data if cell else None

        if role == Qt.EditRole:
            cell = Cell.get(row, column)
            return str(cell.data) if cell else None

        if role == Qt.SizeHintRole:
            return CellModel.CellSize

        if role == Qt.TextAlignmentRole:
            column = Column.get(column)
            if column:
                if column.type.type == DataType.Numeric:
                    return CellModel.NumericCellAlign
Example #14
0
def parse_dim(dim_file, num_cells):
    with open(dim_file) as dim:
        core = Core(numberify(dim.readline().split()))

        cells = []
        for i in range(num_cells):
            cell = Cell(i+1, floatify(dim.readline().split(",")))
            cells.append(cell)

        return core, cells
def create_cell():
    form = CellForm()
    if form.validate_on_submit():
        if Cell.query.filter_by(name=form.name.data).first():
            flash('A cell with this name already exists.', 'danger')
            return render_template('cell.html',
                                   action=url_for('nbg.create_cell'),
                                   form=form)
        cell = Cell(form.name.data, CellType(form.cell_type.data),
                    form.source.data)
        cell.collapsed = form.collapsed.data
        cell.set_metadata(form.cell_metadata.data)
        db.session.add(cell)
        db.session.commit()
        flash('Cell created', 'success')
        return redirect(url_for('nbg.list_cells'))
    return render_template('cell.html',
                           action=url_for('nbg.create_cell'),
                           form=form)
Example #16
0
def cells20():
    row = [None]*10
    rows = [row[:] for i in range(10)] 
    
    cells = Cell.all().filter('enabled =', True).order('ctime').fetch(1000)
    for cell in cells:
        rows[cell.y][cell.x] = cell
    
    return render_template('cells20.html',
      rows=rows,
    )
Example #17
0
def cell_update(x, y):
    c = Cell.at_position(x, y)
    if c.is_initialized():
        return make_response("Cell already initialized.")
    c.title = request.values.get("title", c.title)
    c.description = request.values.get("description", c.description)
    c.link = request.values.get("link", c.link)
    if c.link and not "://" in c.link:
        c.link = "http://" + c.link
    c.put()
    return make_response("Updated.")
Example #18
0
def initialize_pcf_cell():
    from app import models
    from models import Pcf, Cell

    from datetime import date
    today = date.today()
    # print("today ", today)
    t_date = today.strftime("%Y/%m/%d")

    import pandas as pd

    file = 'CG.xlsx'

    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data',
                        file)

    # Load spreadsheet
    xl = pd.ExcelFile(path)

    # Load a sheet into a DataFrame by name: df1
    df1 = xl.parse('Sheet1')

    cells = df1.iloc[:, 0].tolist()
    pcfs = df1.iloc[:, 1].tolist()

    d = {}
    for i in pcfs:
        d[i] = []

    for i in range(len(cells)):
        d[pcfs[i]].append(cells[i])

    # print(d)

    pcf_list = list(d.keys())
    pcf_id = {}

    for pcf in pcf_list:
        pcf_item = Pcf(pcf=pcf, entry_date=t_date)
        db.session.add(pcf_item)
        db.session.flush()
        # print(pcf_item.id)
        pcf_id[pcf] = pcf_item.id

    for pcf in pcf_list:

        pcells = d[pcf]
        # print(pcells)
        for pc in pcells:
            cell_item = Cell(pcf_id=pcf_id[pcf], cell=pc, entry_date=t_date)
            db.session.add(cell_item)

    db.session.commit()
Example #19
0
    def test_can_add_a_cell_to_a_line(self):

        """
        Test can add a cell to a line and increment count for line cells
        """

        cells_count = len(self.line.cells)

        self.line.add(Cell(1, 1, 2))

        self.assertEqual(cells_count + 1, len(self.line.cells))
        self.assertEqual(self.line.cells_count, len(self.line.cells))
Example #20
0
    def create(self, request):
        cell = Cell(owner=request.user)
        form = CellCreateForm(request.user, request.POST, instance=cell)
        if not form.is_valid():
            raise APIBadRequest(form.errors)

        form.save()

        rev = form.instance.cellrevision_set.all()[0]
        rev.resource = form.cleaned_data['resource']
        rev.save()

        return form.instance
Example #21
0
    def RPC__Worksheet__sync(self, uuid, force=False):
        """Synchronize a worksheet with its origin. """
        try:
            worksheet = Worksheet.objects.get(uuid=uuid)
        except Worksheet.DoesNotExist:
            self.return_api_error('does-not-exist')
            return

        if worksheet.origin is None:
            self.return_api_error('does-not-have-origin')
            return

        if not force and worksheet.modified > worksheet.created:
            self.return_api_error('worksheet-was-modified')
            return

        Cell.objects.filter(worksheet=worksheet).delete()

        order = []

        for uuid in worksheet.origin.get_order():
            try:
                base = Cell.objects.get(uuid=uuid)
            except Cell.DoesNotExist:
                pass
            else:
                cell = Cell(user=self.user,
                            type=base.type,
                            parent=base.parent,
                            content=base.content,
                            worksheet=worksheet)
                order.append(cell.uuid)
                cell.save()

        worksheet.set_order(order)
        worksheet.save()

        self.return_api_result()
Example #22
0
def cell_budget(x, y):
    c = Cell.at_position(x, y)
    budget = c.get_bitcoin_budget()
    
    render_bitcoin_budget = get_template_attribute('macros.html', 'render_bitcoin_budget')
    
    logging.info(repr(str(render_bitcoin_budget(c))))
    
    body = json.dumps({
        'budget': budget,
        'html': str(render_bitcoin_budget(c)),
    }, indent=4)

    response = make_response(body)
    response.headers['Content-Type'] = 'text/plain'
    return response
Example #23
0
def update():
    """ Update the global statistics.
    """

    from models import Cell

    stats = get()
    cursor = None
    
    results = {
        'total_cell_count': 0,
        'active_cell_count': 0,
        'initialized_cell_count': 0,
        'nonemptybudget_cell_count': 0,
        
        'total_bitcoin': 0,
        
        'biggest_budget': 0,
        'biggest_budget_cell': None,
    }
    while True:
        query = Cell.all()
        if cursor:
            query.with_cursor(cursor)
        cells = query.fetch(1000)
        if not cells:
            break
        
        cursor = query.cursor()
        
        for cell in cells:
            results['total_cell_count'] += 1
            if cell.enabled:
                results['active_cell_count'] += 1
            if cell.is_initialized():
                results['initialized_cell_count'] += 1
            if cell.bitcoin_budget:
                results['nonemptybudget_cell_count'] += 1
                results['total_bitcoin'] += cell.bitcoin_budget
                
            if cell.bitcoin_budget > results['biggest_budget']:
                results['biggest_budget'] = cell.bitcoin_budget
                results['biggest_budget_cell'] = db.Blob(model_to_protobuf(cell))
                
    for k,v in results.items():
        setattr(stats, k, v)
    stats.put()
Example #24
0
def addMapWithCells(db, mapData, zonesRadius, cellList):
	map_ = Map(id=mapData[0], name=mapData[1], maxX=mapData[2], maxY=mapData[3])
	db.session.add(map_)
	db.session.flush()

	for i in range(0, len(cellList)):
		for j in range(0, len(cellList[0])):
			if cellList[i][j] == 0:
				continue

			r = 0 if (cellList[i][j] == -1 or cellList[i][j] == 0) else zonesRadius[cellList[i][j]]
			cell = Cell(map=mapData[0], value=cellList[i][j], radius=r, posX=j, posY=i)
			db.session.add(cell)
			db.session.flush()

	db.session.commit()

	print ('Added map {0}'.format(mapData[1]))
Example #25
0
def cell_activity():
    from flask import json
    
    cursor = request.values.get("cursor")
    if cursor == 'latest':
        cursor = memcache.get("ACTIVITY_CURSOR", "")
    query = Cell.activity(cursor=cursor)
    cells = query.fetch(100)
    cursor = query.cursor()
    memcache.set("ACTIVITY_CURSOR", cursor)
    
    body = json.dumps({
        'cursor': cursor,
        'cells': [c.to_dict() for c in cells],
    }, indent=4)

    response = make_response(body)
    response.headers['Content-Type'] = 'text/plain'
    return response
Example #26
0
    def RPC__Worksheet__save(self, uuid, cells):
        """Store cells (and their order) associated with a worksheet. """
        try:
            worksheet = Worksheet.objects.get(user=self.user, uuid=uuid)
        except Worksheet.DoesNotExist:
            self.return_api_error('does-not-exist')
        else:
            order = []

            for data in cells:
                uuid = data['uuid']
                type = data['type']
                content = data['content']

                try:
                    cell = Cell.objects.get(user=self.user, uuid=uuid)
                except Cell.DoesNotExist:
                    cell = Cell(uuid=uuid,
                                user=self.user,
                                worksheet=worksheet,
                                content=content,
                                type=type)
                else:
                    cell.content = content
                    cell.type = type

                order.append(uuid)
                cell.save()

            worksheet.set_order(order)
            worksheet.save()

            uuids = set(order)

            for cell in Cell.objects.filter(user=self.user, worksheet=worksheet):
                if cell.uuid not in uuids:
                    cell.delete()

            self.return_api_result()
Example #27
0
    def test_can_return_matching_lines_for_cell(self):

        """
        Test can return a matching line for a cell
        """

        line = Line([
            self.cell1,
        ], 1)

        line2 = Line([
            self.cell3
        ], 1)

        self.game.lines = [line, line2]

        cell = Cell(1, 2, 1)

        matches = self.game.get_matching_lines_for_cell(cell)

        self.assertEqual(len(matches), 2)
    def handle_cell(self, blob_info):
        from models import Cell
        
        x = int(self.request.params['x'])
        y = int(self.request.params['y'])

        cell = Cell.at_position(x, y)
        
        if cell.is_initialized():
            raise Exception("Cell (%s,%s) already initialized." % (x, y))
        
        old_image = cell.image
        cell.image = blob_info.key()
        cell.image_url = images.get_serving_url(str(blob_info.key()))
        cell.put()
        if old_image:
            old_image.delete()
            
        taskqueue.add(url="/macro/update_row_cache", params={'y': y}, method="GET")
        
        self.redirect('/')
Example #29
0
    def execute(self):
        query = Query(select=self.input.toPlainText())
        query.execute()
        if query.error == Query.NoError:
            var_name = self.target.text().strip()
            column = None
            new_column = False
            if var_name:
                logger.debug("var_name={}".format(var_name))
                column = Column.get_by_name(var_name)

            if not column:
                column = Column(Column.count(), name=var_name)
                new_column = True

            logger.debug("new_column={}".format(new_column))

            for row, data in query.result.items():
                if new_column:
                    Cell(row, column.id, data=data)
                else:
                    cell = Cell.get(row, column.id)
                    cell.data = data
Example #30
0
    def test_model_cell(self):
        """
        Test cell model works
        """
        cell = Cell()
        self.assertEqual(cell._isMine, False)
        self.assertEqual(cell._isRevealed, False)
        self.assertEqual(cell._isRevealed, False)
        self.assertEqual(cell._minesAround, 0)

        cell._isMine = True
        cell._isRevealed = True
        cell._isFlagged = True
        cell._minesAround = 8
        self.assertEqual(cell._isMine, True)
        self.assertEqual(cell._isRevealed, True)
        self.assertEqual(cell._isFlagged, True)
        self.assertEqual(cell._minesAround, 8)
Example #31
0
def pixels():
    cells = Cell.all().filter('enabled =', True).order('-bitcoin_budget').fetch(1000)
    return render_template('pixels.html', cells=cells)
Example #32
0
 def setUp(self):
     self.cell = Cell(1, 1, 1)
Example #33
0
	def test_cell_dies_method(self):
		cell = Cell(0, 0, True)
		cell.dies()
		self.assertFalse(cell.is_alive())
Example #34
0
	def test_toggle_state_method(self):
		cell = Cell(0, 0)
		self.assertFalse(cell.is_alive())
		cell.toggle_state()
		self.assertTrue(cell.is_alive())
Example #35
0
	def test_cell_enliven_method(self):
		cell = Cell(0, 0)
		cell.enliven()
		self.assertTrue(cell.is_alive())
Example #36
0
 def before_execution(self):
     if not self.has_error():
         Cell.insert()
Example #37
0
    def test_cell_neighbors_is_empty_on_creation(self):
        from models import Cell
        cells = Cell()

        self.assertListEqual(cells.neighbors, [])
Example #38
0
type_list = ['Tumorous', 'Red', 'White']
nano_virus = Virus()

cell_objects = {}
distance_cells = []

tumorous_cells = []
red_cells = []
white_cells = []

count_1 = count_2 = count_3 = 0
i = 100

while i > 0:
    cell_objects[i] = Cell()
    rand_prop = numpy.random.choice(numpy.arange(1, 4), p=[0.05, 0.25, 0.70])
    cell_objects[i].set_type(type_list[rand_prop - 1])
    i = i - 1


def calculate_distance(cell1, cell2):
    distance = sqrt((cell1.get_x() - cell2.get_x())**2 +
                    (cell1.get_y() - cell2.get_y())**2 +
                    (cell1.get_z() - cell2.get_z())**2)
    return distance


def locate_cell_by_type(cell_objects):
    c = len(cell_objects)
    for cels in range(1, 101):
 def test_initial_values_Cell(self):
     cards = [BadCard(), GoodCard(), TripCard()]
     obj_1 = Cell(1, 2, cards)
     assert obj_1.row == 1
     assert obj_1.col == 2
     assert obj_1.cards == cards
 def test_no_value(self):
     with pytest.raises(Exception) as e_info:
         obj = Cell()
Example #41
0
def cell(x, y):
    c = Cell.at_position(x, y)        
    return redirect(c.get_image_url())