Exemple #1
0
def consumer_acquisition_report(request, stype):
    """
    Generates a report showing monthly consumer sign-ups for the MediaPartner
    """
    site = get_current_site(request)
    partner_site = SiteConsumerStats(site=site)

    graph = Flot()
    graph.add_time_series(partner_site.get_series(stype)['series'],
            "My Site",
            lines={'show': True})
    return render_to_response('media_partner/consumer_acquisition.html',
            {'graph': graph,
             'graph_title': stype.replace('-', ' ').capitalize(),
             'js_flot': True},
            context_instance=RequestContext(request))
Exemple #2
0
def monthly_expenses_vs_quota(request):
    """
     return flot data/options for the expenses of all months with their quota
    """
    graph = Flot()
    user_profile = request.user.get_profile()
    quotas = user_profile.quotas.all()
    num_months = quotas.count()
    
    used_quota_datas = []
    quota_datas = []
    
#    date0 = quotas[num_months-1].date - datetime.timedelta(days=30)
#    used_quota_datas.append([date0, float(user_profile.used_monthly_quota(num_months-1))])
#    quota_datas.append([date0, float(quotas[num_months-1].quota)])
    

    for i in xrange(0,num_months):
        quota = quotas[num_months-1-i]             
        used_quota = float(user_profile.used_monthly_quota(num_months-1-i))   
        xaxis = quota.date
        
        quota_datas.append([xaxis,float(quota.quota)])
        used_quota_datas.append([xaxis,used_quota])

        
    dateN1 = quotas[0].date + datetime.timedelta(days=30)
    used_quota_datas.append([dateN1, float(user_profile.used_monthly_quota(0))])
    quota_datas.append([dateN1, float(quotas[0].quota)])
    
    
    graph.add_lines(used_quota_datas, label="Expenses",**{"fill":True,"steps":True})
    graph.add_lines(quota_datas, label="Quota",**{"steps":True})
    
    graph = add_axis_label(graph,"x","Months")
    graph = add_axis_label(graph,"y","Amount ($)")
    graph._options['xaxis'].update({"minTickSize": [1, "month"]})
    
#    #show a month before
#    date0 = quotas[num_months-1].date - datetime.timedelta(days=30)
#    graph._options['xaxis'].update({"min": time.mktime(date0.timetuple())*1000 })
    
    
    content = "{\"datas\": %(DATAS)s, \"options\": %(OPTS)s }" % {"DATAS":graph.series_json, "OPTS":graph.options_json}
    return HttpResponse(content, mimetype="application/json")
Exemple #3
0
def test_flot(request):
    "testing flot ajax"
    
    m1 = datetime.date.today()
    m0 = m1 - datetime.timedelta(days=30)
    m2 = m1+datetime.timedelta(days=30)
    m3 = m2+datetime.timedelta(days=30)
    graph = Flot()
    graph.add_lines([(m1, 1), (m2, 2), (m3, 3)], label="func a",**{"fill":True})
#    graph.add_bars([(1, 1), (2, 1), (3, 3)], label="func b")
    graph = add_axis_label(graph,"x","Label x")
    graph = add_axis_label(graph,"y","Label y")
    graph._options['xaxis'].update({"minTickSize": [1, "month"]})
    
#    graph._options['xaxis'].update({"min": time.mktime(m0.timetuple())*100 })
#    graph._options['xaxis'].update({"min": 1354154400000 })
    
    
    
    content = "{\"datas\": %(DATAS)s, \"options\": %(OPTS)s }" % {"DATAS":graph.series_json, "OPTS":graph.options_json}
    return HttpResponse(content, mimetype="application/json")
Exemple #4
0
def test_flot(request):
    "testing flot ajax"

    m1 = datetime.date.today()
    m0 = m1 - datetime.timedelta(days=30)
    m2 = m1 + datetime.timedelta(days=30)
    m3 = m2 + datetime.timedelta(days=30)
    graph = Flot()
    graph.add_lines([(m1, 1), (m2, 2), (m3, 3)],
                    label="func a",
                    **{"fill": True})
    #    graph.add_bars([(1, 1), (2, 1), (3, 3)], label="func b")
    graph = add_axis_label(graph, "x", "Label x")
    graph = add_axis_label(graph, "y", "Label y")
    graph._options['xaxis'].update({"minTickSize": [1, "month"]})

    #    graph._options['xaxis'].update({"min": time.mktime(m0.timetuple())*100 })
    #    graph._options['xaxis'].update({"min": 1354154400000 })

    content = "{\"datas\": %(DATAS)s, \"options\": %(OPTS)s }" % {
        "DATAS": graph.series_json,
        "OPTS": graph.options_json
    }
    return HttpResponse(content, mimetype="application/json")
Exemple #5
0
def monthly_expenses_vs_quota(request):
    """
     return flot data/options for the expenses of all months with their quota
    """
    graph = Flot()
    user_profile = request.user.get_profile()
    quotas = user_profile.quotas.all()
    num_months = quotas.count()

    used_quota_datas = []
    quota_datas = []

    #    date0 = quotas[num_months-1].date - datetime.timedelta(days=30)
    #    used_quota_datas.append([date0, float(user_profile.used_monthly_quota(num_months-1))])
    #    quota_datas.append([date0, float(quotas[num_months-1].quota)])

    for i in xrange(0, num_months):
        quota = quotas[num_months - 1 - i]
        used_quota = float(user_profile.used_monthly_quota(num_months - 1 - i))
        xaxis = quota.date

        quota_datas.append([xaxis, float(quota.quota)])
        used_quota_datas.append([xaxis, used_quota])

    dateN1 = quotas[0].date + datetime.timedelta(days=30)
    used_quota_datas.append(
        [dateN1, float(user_profile.used_monthly_quota(0))])
    quota_datas.append([dateN1, float(quotas[0].quota)])

    graph.add_lines(used_quota_datas,
                    label="Expenses",
                    **{
                        "fill": True,
                        "steps": True
                    })
    graph.add_lines(quota_datas, label="Quota", **{"steps": True})

    graph = add_axis_label(graph, "x", "Months")
    graph = add_axis_label(graph, "y", "Amount ($)")
    graph._options['xaxis'].update({"minTickSize": [1, "month"]})

    #    #show a month before
    #    date0 = quotas[num_months-1].date - datetime.timedelta(days=30)
    #    graph._options['xaxis'].update({"min": time.mktime(date0.timetuple())*1000 })

    content = "{\"datas\": %(DATAS)s, \"options\": %(OPTS)s }" % {
        "DATAS": graph.series_json,
        "OPTS": graph.options_json
    }
    return HttpResponse(content, mimetype="application/json")
 def setUp(self):
     self.flot = Flot()
class TestFlot(unittest.TestCase):

    def setUp(self):
        self.flot = Flot()

    def check_add_series(self, raw, label=None):
        count = len(self.flot._series)
        self.flot.add_series(raw, label)
        self.assertEqual(count+1, len(self.flot._series))
        series = self.flot._series[count]
        self.assertEqual(raw, series['data'])
        if label:
            self.assertEqual(label, series['label'])
        else:
            self.assertFalse('label' in series)

    def test_initial_state(self):
        "make sure internal structures initialize properly"
        self.assertEqual(self.flot._series, [])
        self.assertEqual(self.flot._options, {})

    def test_basic_add_series(self):
        "make sure a series can be added with no label or options"
        self.check_add_series(S1)

    def test_reject_empty_series(self):
        """don't accept empty series"""
        self.assertRaises(MissingDataException, self.flot.add_series, [])
        self.assertEqual(len(self.flot._series), 0)

    def test_add_series_with_label(self):
        """make sure a label can be associated with a series"""
        self.flot.add_series(S1, "as_arg")
        self.flot._series = []
        self.flot.add_series(S1, label="as_kwarg")

    def test_reject_duplicate_label(self):
        "make sure a series is not added if it has a duplicate label"
        self.check_add_series(S1, "label1")
        self.assertRaises(DuplicateLabelException, self.flot.add_series, S1, "label1")

    def test_add_multiple_series(self):
        "make sure multiple series can be added"
        self.check_add_series(S1)
        self.check_add_series(S1)

    def test_add_line_types(self):
        "test the line type shortcuts"
        for stype in ('bars', 'line', 'points'):
            getattr(self.flot, 'add_%s' %stype)(S1)
            self.assertEqual(self.flot._series[0][stype], {'show': True})
            self.flot._series = []

    def test_add_bars(self):
        "test the shortcut for adding a series as bars"
        series = {'data': ((0,0), ) + S1, 
                  "bars": {"barWidth": 0.75, "show": True}}
        self.flot.add_bars(((0,0), ) + S1)
        self.assertEqual(self.flot._series[0]['bars'], {'show': True})
        self.assertEqual(json.dumps([series]), self.flot.series_json)

    def test_series_json(self):
        "make sure conversion to JSON works for simple series"
        self.assertEqual("[]", self.flot.series_json)
        series = {'data': S1}
        self.flot.add_series(S1)
        self.assertEqual(json.dumps([series]), self.flot.series_json)

    def test_series_with_label_json(self):
        "make sure series with label converts to JSON properly"
        series = {'data': S1, 'label': 'label1'}
        self.flot.add_series(S1, 'label1')
        self.assertEqual(json.dumps([series]), self.flot.series_json)

    def test_add_time_series(self):
        """
        make sure adding time series works properly:

        * conversion to JS timestamp
        * time series mode added to options
        """
        time_series = [(date(2010, 3, 14) - timedelta(days=i), i) \
                        for i in range(5)]
        self.flot.add_time_series(time_series)
        self.assertEqual(self.flot._series[0]['data'],
            [(1268553600000.0, 0),
            (1268467200000.0, 1),
            (1268380800000.0, 2),
            (1268294400000.0, 3),
            (1268208000000.0, 4)])
        self.assertEqual(self.flot._options['xaxis'],
                {'mode': 'time'})

    def test_empty_options_json(self):
        "make sure conversion to JSON works for default options"
        self.assertEqual("{}", self.flot.options_json)

    def test_options(self):
        "make sure options are applied correctly for a Flot subclass" 
        class MyFlot(Flot):
            options = FAKE_NESTED_OPTIONS

        f = MyFlot()
        self.assertEqual(f._options, FAKE_NESTED_OPTIONS)
        self.assertEqual(f.options_json,
                json.dumps(FAKE_NESTED_OPTIONS))

    def test_options_inheritance(self):
        "make sure options in an inheritance chain are applied correctly"
        class MyFlot(Flot):
            options = FAKE_NESTED_OPTIONS

        class AnotherFlot(MyFlot):
            options = {
                'level1': {
                    'd': 4,
                    'level2': {
                        'a': 10}}}

        f = AnotherFlot()
        self.assertEqual(f._options,
                {'level1': {'d': 4, 'level2': {'a':10, 'level3': {'b':2}}}, 'c':3})
        #TODO will the dumped dict string match work across platforms?
        self.assertEqual(f.options_json,
                 '{"level1": {"level2": {"a": 10, "level3": {"b": 2}}, "d": 4}, "c": 3}')
 def setUp(self):
     self.flot = Flot()
class TestFlot(unittest.TestCase):
    def setUp(self):
        self.flot = Flot()

    def check_add_series(self, raw, label=None):
        count = len(self.flot._series)
        self.flot.add_series(raw, label)
        self.assertEqual(count + 1, len(self.flot._series))
        series = self.flot._series[count]
        self.assertEqual(raw, series['data'])
        if label:
            self.assertEqual(label, series['label'])
        else:
            self.assertFalse('label' in series)

    def test_initial_state(self):
        "make sure internal structures initialize properly"
        self.assertEqual(self.flot._series, [])
        self.assertEqual(self.flot._options, {})

    def test_basic_add_series(self):
        "make sure a series can be added with no label or options"
        self.check_add_series(S1)

    def test_reject_empty_series(self):
        """don't accept empty series"""
        self.assertRaises(MissingDataException, self.flot.add_series, [])
        self.assertEqual(len(self.flot._series), 0)

    def test_add_series_with_label(self):
        """make sure a label can be associated with a series"""
        self.flot.add_series(S1, "as_arg")
        self.flot._series = []
        self.flot.add_series(S1, label="as_kwarg")

    def test_reject_duplicate_label(self):
        "make sure a series is not added if it has a duplicate label"
        self.check_add_series(S1, "label1")
        self.assertRaises(DuplicateLabelException, self.flot.add_series, S1,
                          "label1")

    def test_add_multiple_series(self):
        "make sure multiple series can be added"
        self.check_add_series(S1)
        self.check_add_series(S1)

    def test_add_line_types(self):
        "test the line type shortcuts"
        for stype in ('bars', 'line', 'points'):
            getattr(self.flot, 'add_%s' % stype)(S1)
            self.assertEqual(self.flot._series[0][stype], {'show': True})
            self.flot._series = []

    def test_add_bars(self):
        "test the shortcut for adding a series as bars"
        series = {
            'data': ((0, 0), ) + S1,
            "bars": {
                "barWidth": 0.75,
                "show": True
            }
        }
        self.flot.add_bars(((0, 0), ) + S1)
        self.assertEqual(self.flot._series[0]['bars'], {'show': True})
        self.assertEqual(json.dumps([series]), self.flot.series_json)

    def test_series_json(self):
        "make sure conversion to JSON works for simple series"
        self.assertEqual("[]", self.flot.series_json)
        series = {'data': S1}
        self.flot.add_series(S1)
        self.assertEqual(json.dumps([series]), self.flot.series_json)

    def test_series_with_label_json(self):
        "make sure series with label converts to JSON properly"
        series = {'data': S1, 'label': 'label1'}
        self.flot.add_series(S1, 'label1')
        self.assertEqual(json.dumps([series]), self.flot.series_json)

    def test_add_time_series(self):
        """
        make sure adding time series works properly:

        * conversion to JS timestamp
        * time series mode added to options
        """
        time_series = [(date(2010, 3, 14) - timedelta(days=i), i) \
                        for i in range(5)]
        self.flot.add_series(time_series)
        self.assertEqual(self.flot._series[0]['data'], [(1268553600000.0, 0),
                                                        (1268467200000.0, 1),
                                                        (1268380800000.0, 2),
                                                        (1268294400000.0, 3),
                                                        (1268208000000.0, 4)])
        self.assertEqual(self.flot._options['xaxis'], {'mode': 'time'})

    def test_bogus_call(self):
        """make sure explicit and dynamic instance methods work, and that
        bogus attribute access fails as expected"""
        self.assertRaises(AttributeError, lambda: self.flot.add_shrimp)
        self.assertRaises(AttributeError, lambda: self.flot.minus_bars)
        self.assertRaises(AttributeError, lambda: self.flot.asdf)
        self.assertTrue(isinstance(self.flot.add_bars, partial))
        self.assertTrue(isinstance(self.flot.add_line, partial))
        self.assertTrue(isinstance(self.flot.add_points, partial))
        self.assertTrue(isinstance(self.flot.add_series, MethodType))

    def test_empty_options_json(self):
        "make sure conversion to JSON works for default options"
        self.assertEqual("{}", self.flot.options_json)

    def test_options(self):
        "make sure options are applied correctly for a Flot subclass"

        class MyFlot(Flot):
            options = FAKE_NESTED_OPTIONS

        f = MyFlot()
        self.assertEqual(f._options, FAKE_NESTED_OPTIONS)
        self.assertEqual(f.options_json, json.dumps(FAKE_NESTED_OPTIONS))

    def test_options_inheritance(self):
        "make sure options in an inheritance chain are applied correctly"

        class MyFlot(Flot):
            options = FAKE_NESTED_OPTIONS

        class AnotherFlot(MyFlot):
            options = {'level1': {'d': 4, 'level2': {'a': 10}}}

        f = AnotherFlot()
        self.assertEqual(f._options, {
            'level1': {
                'd': 4,
                'level2': {
                    'a': 10,
                    'level3': {
                        'b': 2
                    }
                }
            },
            'c': 3
        })
        #TODO will the dumped dict string match work across platforms?
        self.assertEqual(
            f.options_json,
            '{"level1": {"level2": {"a": 10, "level3": {"b": 2}}, "d": 4}, "c": 3}'
        )