Recherche avancée

Médias (91)

Autres articles (53)

  • Publier sur MédiaSpip

    13 juin 2013

    Puis-je poster des contenus à partir d’une tablette Ipad ?
    Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir

  • Les autorisations surchargées par les plugins

    27 avril 2010, par

    Mediaspip core
    autoriser_auteur_modifier() afin que les visiteurs soient capables de modifier leurs informations sur la page d’auteurs

  • D’autres logiciels intéressants

    12 avril 2011, par

    On ne revendique pas d’être les seuls à faire ce que l’on fait ... et on ne revendique surtout pas d’être les meilleurs non plus ... Ce que l’on fait, on essaie juste de le faire bien, et de mieux en mieux...
    La liste suivante correspond à des logiciels qui tendent peu ou prou à faire comme MediaSPIP ou que MediaSPIP tente peu ou prou à faire pareil, peu importe ...
    On ne les connais pas, on ne les a pas essayé, mais vous pouvez peut être y jeter un coup d’oeil.
    Videopress
    Site Internet : (...)

Sur d’autres sites (7567)

  • Homepage Design : Best Practices & Examples

    5 octobre 2022, par Erin

    Did you know users spend about 50 milliseconds deciding if they like your website’s homepage design or not ?

    With billions of websites and scrolling often done on the go, you have to make a strong first impression because the chances for a once-over are slim. 

    Learn how to design magnetically-appealing website homepages from this guide. 

    What is a homepage in web design ?

    Homepage is the front page of your website — a destination where users land when typing your website URL address. It’s located at the root of the website’s domain (e.g., matomo.org) or a subdomain (e.g., university.webflow.com).

    Design-wise a homepage has two goals :

    • Explain the purpose of the website and present overview information 
    • Provide top-level navigation to lower-level web pages (e.g., blog, sales pages, etc.) 

    Separately, a homepage is also the place where users will return each time they’ll feel stuck and want to start anew. Thus, your homepage website design should provide obvious navigation paths to other website areas.

    6 Must-Know Website Homepage Design Best Practices

    Behind every winning homepage design stands a detailed customer journey map. 

    A customer journey is a schematic representation of how site visitors will move around your website to accomplish various goals. 

    A good customer journey map lists different actions a user will take after landing on your website (e.g., browse product pages, save items to a wishlist, register an account, etc.) — and it does so for different audience segments

    Your homepage design should help users move from the first step on their journey (e.g., learning about your website) to the final one (e.g., converting to a paid customer). At the same time, your homepage should serve the needs of both new and returning visitors — prospects who may be at a different stage of their journey (e.g., consideration). 

    With the above in mind, let’s take a look at several website homepage design ideas and the reasons why they work. 

    1. Use Familiar Design Elements

    Whether you’re designing a new website or refreshing an old one, it’s always tempting to go “out of the box” — use horizontal scrolling, skip header navigation or include arty animations. 

    Bold design choices work for some brands, mainly those who aren’t using their website as a primary sales channel (e.g., luxury brands). 

    But unfamiliar design patterns can also intimidate a lot of shoppers. In one observational study, people were asked to guess where specific content (e.g., information on international calls) would be placed on a telecom website. 75% of users picked the same location. This means two things :

    • People already have expectations of where specific website information is typically placed 
    • Yet, one in four users struggles to identify the right areas even within standard website layouts

    So why make the job harder for them ? As UX consultant Peter Ramsey rightfully notes : 

    The truth is : designing the best experience isn’t about being unique, it’s about being easy. And guess what feels really easy to use ? Things that feel familiar.

    Therefore, analyse other homepage layout designs in your industry. Pay attention to the number and type of homepage screens and approaches to designing header/footer navigation. 

    Take some of those ideas as your “base”. Then make your homepage design on-brand with unique typography, icons, visuals and other graphic design elements.

    Take a cue from ICAM — a steel manufacturing company. Their niche isn’t typically exciting. Yet, their homepage design stops you in your tracks and tinkers your curiosity to discover more (even if you aren’t shopping for metalware). 

    ICAM homepage example

    The interesting part is that ICAM uses a rather standard homepage layout. You have a hero image in the first screen, followed by a multi-column layout of their industry expertise and an overview of manufacturers. 

    But this homepage design feels fresh because the company uses plenty of white space, bold typography and vibrant visuals. Also, they delay the creative twist (horizontal scrolling area) to the bottom of the homepage, meaning that it’s less likely to intimidate less confident web users. 

    2. Decide On The Optimal Homepage Layout 

    In web design, a homepage layout is your approach to visually organising different information on the screen. 

    Observant folks will notice that good homepage designs often have the same layout. For example, include a split-view “hero” screen with a call to action on the left and visuals (photo or video) on the left. 

    Ecommerce Homepage Design Example
    SOURCE : shopify.com / SOURCE : squareup.com

    The reason for using similar layouts for website homepage design isn’t a lack of creativity. On the contrary, some layouts have become the “best practice” because they :

    • Offer a great user experience (UX) and don’t confuse first-time visitors 
    • Feel familiar and create a pleasurable sense of deja-vu among users 
    • Have proven to drive higher conversion rates through benchmarks and tests 

    Popular types of website homepage layouts : 

    • Single column – a classic option of presenting main content in a single, vertical column. Good choice for blogs, personal websites and simple corporate sites. 
    • Split screen layout divides the page in two equal areas with different information present. Works best for Ecommerce homepages (e.g., to separate different types of garments) or SaaS websites, offering two product types (e.g., a free personal product version and a business edition). 
    • Asymmetrical layout assumes dividing your homepage into areas of different size and styles. Asymmetry helps create specific focal points for users to draw their attention to the most prominent information. 
    • Grid of cards layout helps present a lot of information in a more digestible manner by breaking down bigger bulks of text into smaller cards — a graphic element, featuring an image and some texts. By tapping a card, users can then access extra content. 
    • Boxes are visually similar to cards, but can be of varying shape. For example, you can have a bigger header-width box area, followed by four smaller boxes within it. Both of these website layouts work well for Ecommerce. 
    • Featured image layout gives visuals (photos and videos) the most prominent placement on the homepage, with texts and other graphic design elements serving a secondary purpose. 
    • F-pattern layout is based on the standard eye movement most people have when reading content on the website. Eye tracking studies found that we usually pay the most attention to information atop of the page (header area), then scan horizontally before dripping down to the next vertical line until we find content that captures our attention. 

    User behaviour analytics (UBA) tools are the best way to determine what type of layout will work for your homepage. 

    For example, you can use Matomo Heatmaps and Session Recording to observe how users navigate your homepage, which areas or links they click and what blockers they face during navigation.

    Matomo Heatmaps

    Matomo can capture accurate behavioural insights because we track relative positions to elements within your websites. This approach allows us to provide accurate data for users with different browsers, operating systems, zoom-in levels and fonts. 

    The best part ? You can collect behavioural data from up to 100 different user segments to understand how different audience cohorts engage with your product.

    3. Include a One-Sentence Tagline

    A tagline is a one-line summary of what your company does and what its unique sales proposition (USP) is. It should be short, catchy and distinguish you from competitors.

    A modern homepage design practice is to include a call to action in the first screen. Why ? Because you then instantly communicate or remind of your value proposition to every user — and provide them with an easy way to convert whenever they are ready to do business with you. 

    Here’s how three companies with a similar product, a project management app, differentiate themselves through homepage taglines. 

    Monday.com positions itself as an operating system (OS) for work. 

    monday.com homepage

    Basecamp emphasises its product simplicity and openly says that they are different from other overly-complex software. 

    Asana, in turn, addresses a familiar user pain point (siloed communication) that it attempts to fix with its product. 

    asana.com homepage

    Coming up with the perfect homepage tagline is a big task. You may have plenty of ideas, but little confidence in what version will stick. 

    The best approach ? Let a series of A/B tests decide. You can test a roaster of homepage slogans on a rotating bi-weekly/monthly schedule and track how copy changes affect conversion rates. 

    With Matomo A/B test feature, you can create, track and manage all experiments straight from your web analytics app — and get consolidated reports on total page visitors and conversion rates per each tested variation. 

    Matomo A/B Test feature

    Beyond slogans, you can also run A/B tests to validate submission form placements, button texts or the entire page layout. 

    For instance, you can benchmark how your new homepage design performs compared to the old version with a subset of users before making it publicly available. 

    4. Highlight The Main Tasks For The User

    Though casual browsing is a thing, most of us head to specific websites with a clear agenda — find information, compare prices, obtain services, etc. 

    Thus, your homepage should provide clear starting points for users’ main tasks (those you’ve also identified as conversion goals on your customer journey maps !).

    These tasks can include : 

    • Account registration 
    • Product demo request 
    • Newsletter sign-up 

    The best website homepage designs organically guide users through a set number of common tasks, one screen at a time. 

    Let’s analyse Sable homepage design. The company offers a no-fee bank account and a credit card product for soon-to-be US transplants. The main task a user has : Decide if they want to try Sable and hopefully open an account with them. 

    Sable Example Homepage

    This mono-purpose page focuses on persuading a prospect that Sable is right for them. 

    The first screen hosts the main CTA with an animated drop-down arrow to keep scrolling. This is likely aimed at first-time visitors that just landed on the page from an online ad or social media post. 

    The second screen serves the main pitch — no-fee, no-hassle access to a US banking account that also helps you build your credit score. 

    The third screen encourages users to learn more about Sable Credit — the flagship product. For the sceptics, the fourth screen offers several more reasons to sign up for the credit product. 

    Then Sable moves on to pitching its second offering — a no-fee debit card with a cashback. Once again, the follow-up screen sweetens the deal by bringing up other perks (higher cashback for popular services like Amazon) and overcoming objections (no SSN required and multi-language support available). 

    The sequence ends with side-by-side product comparison and some extra social proof. 

    In Sable’s case, each homepage screen has a clear purpose and is designed to facilitate one specific user action — account opening. 

    For multi-product companies, the above strategy works great for designing individual landing pages. 

    5. Design Proper Navigation Paths

    All websites have two areas reserved for navigation : 

    • Header menu 
    • Footer menu 

    Designing an effective header menu is more important since it’s the primary tool visitors will use to discover other pages. 

    Your header menu can be :

    • Sticky — always visible as the person keeps scrolling. 
    • Static — e.g., a hidden drop-down menu. 

    If you go for a static header and have a longer homepage layout (e.g., 5+ screens), you also need to add extra navigation elements somewhere mid-page. Or else users might not figure out where to go next and merely bounce off. 

    You can do this by : 

    • Promoting other areas of your website (e.g., sub-category pages) by linking out to them 
    • Adding a carousel of “recent posts”, “recommended reads” and “latest products” 
    • Using buttons and CTAs to direct users towards specific actions (e.g., account registration) or assets (free eBook)

    For instance, cosmetics brand Typology doesn’t have a sticky header on the homepage. Instead, they prompt discovery by promoting different product categories (best sellers, bundles, latest arrivals) and their free skin diagnostic quiz — a great engagement mechanism to retain first time users.

    Typology Homepage Example

    Once the user scrolls down to the bottom of the page, they should have an extra set of navigational options — aka footer links. 

    Again, these help steer the visitor towards discovering more content without scrolling back up to the top of your homepage. 

    Nielsen Norman Group says that people mostly use footers as :

    • A second chance to be convinced — after reading the entire homepage, the user is ready to give your product a go.
    • The last resort for hard-to-find content that’s not displayed in global header navigation (e.g., Terms and Conditions or shipping information pages).

    As a rule of thumb, you should designate the following information to the footer : 

    • Utility links (Contact page, Terms & Conditions, Privacy Policy, etc.) 
    • Secondary-task links (e.g., Career page, Investor Details, Media contacts, etc.) 
    • Brands within the organisation (if you operate several) 
    • Customer engagement link (email newsletters and social media buttons)

    The key is to keep the area compact — not more than one standard user screen resolution of 1280×720. 

    6. Show Users What’s Clickable (Or Not) 

    A homepage invites your site visitors on a journey. But if they don’t know which elements to click, they aren’t going to get anywhere.

    Good homepage design makes it obvious which page elements are clickable, i.e., can take the user to a new page or another segment of the homepage. 

    Here are several must-know homepage design tips for better on-page navigation : 

    • Use colour and underline or bold to highlight clickable words. Alternatively, you can change the browser cursor from a standard arrow into another element (e.g., a larger dot or a pointy finger) to indicate when the cursor hovers over a clickable website area. 
    • Make descriptive button texts that imply what will happen when a user clicks the page. Instead of using abstract and generic button texts like “see more” or “learn more”, try a more vibrant language like “dive in” for clicking through to a spa page. 
    • Use a unified hover area to show how different homepage design elements represent a single path or multiple navigation paths. When multiple items are encapsulated in one visual element (e.g., a box), users may be reluctant to click the image because they aren’t sure if it’s one large hit area leading to a single page or if there are multiple hit areas, leading to different pages. 

    Homepage of BEAUSiTE — a whimsical hotel in the Swiss Alps – embodies all of the above design principles. They change the cursor style whenever you scroll into a hit area, use emotive and creative micro-copy for all button texts and clearly distinguish between different homepage elements.

    Beausite Homepage Example

    How to Make Your Homepage Design Even More Impactful ? 

    Website homepage design is roughly 20% of pure design work and 80% of behind-the-scenes research. 

    To design a high-performing homepage you need to have data-backed answers to the following questions : 

    • Who are your primary and secondary target audiences ? 
    • Which tasks (1 to 4) you’d want to help them solve through your homepage ?

    You can get the answers to both questions from your web analytics data by using audience segmentation and page transition (behaviour flow) reports in Matomo. 

    Based on these, you can determine common user journeys and tasks people look to accomplish when visiting your website. Next, you can collect even more data with UBA tools  like heatmaps and user session recordings. Then translated the observed patterns into working homepage design ideas. 

    Improve your homepage design and conversion rates with Matomo. Start your free 21-day trial now ! 

  • Data Privacy in Business : A Risk Leading to Major Opportunities

    9 août 2022, par Erin — Privacy

    Data privacy in business is a contentious issue. 

    Claims that “big data is the new oil of the digital economy” and strong links between “data-driven personalisation and customer experience” encourage leaders to set up massive data collection programmes.

    However, many of these conversations downplay the magnitude of security, compliance and ethical risks companies face when betting too much on customer data collection. 

    In this post, we discuss the double-edged nature of privacy issues in business — the risk-ridden and the opportunity-driven. ​​

    3 Major Risks of Ignoring Data Privacy in Business

    As the old adage goes : Just because everyone else is doing it doesn’t make it right.

    Easy data accessibility and ubiquity of analytics tools make data consumer collection and processing sound like a “given”. But the decision to do so opens your business to a spectrum of risks. 

    1. Compliance and Legal Risks 

    Data collection and customer privacy are protected by a host of international laws including GDPR, CCPA, and regional regulations. Only 15% of countries (mostly developing ones) don’t have dedicated laws for protecting consumer privacy. 

    State of global data protection legislature via The UN

    Global legislature includes provisions on : 

    • Collectible data types
    • Allowed uses of obtained data 
    • Consent to data collection and online tracking 
    • Rights to request data removal 

    Personally identifiable information (PII) processing is prohibited or strictly regulated in most jurisdictions. Yet businesses repeatedly circumnavigate existing rules and break them on occasion.

    In Australia, for example, only 2% of brands use logos, icons or messages to transparently call out online tracking, data sharing or other specific uses of data at the sign-up stage. In Europe, around half of small businesses are still not fully GDPR-compliant — and Big Tech companies like Google, Amazon and Facebook can’t get a grip on their data collection practices even when pressed with horrendous fines. 

    Although the media mostly reports on compliance fines for “big names”, smaller businesses are increasingly receiving more scrutiny. 

    As Max Schrems, an Austrian privacy activist and founder of noyb NGO, explained in a Matomo webinar :

    “In Austria, my home country, there are a lot of €5,000 fines going out there as well [to smaller businesses]. Most of the time, they are just not reported. They just happen below the surface. [GDPR fines] are already a reality.”​

    In April 2022, the EU Court of Justice ruled that consumer groups can autonomously sue businesses for breaches of data protection — and nonprofit organisations like noyb enable more people to do so. 

    Finally, new data privacy legislation is underway across the globe. In the US, Colorado, Connecticut, Virginia and Utah have data protection acts at different stages of approval. South African authorities are working on the Protection of Personal Information Act (POPI) act and Brazil is working on a local General Data Protection Law (LGPD).

    Re-thinking your stance on user privacy and data protection now can significantly reduce the compliance burden in the future. 

    2. Security Risks 

    Data collection also mandates data protection for businesses. Yet, many organisations focus on the former and forget about the latter. 

    Lenient attitudes to consumer data protection resulted in a major spike in data breaches.

    Check Point research found that cyberattacks increased 50% year-over-year, with each organisation facing 925 cyberattacks per week globally.

    Many of these attacks end up being successful due to poor data security in place. As a result, billions of stolen consumer records become publicly available or get sold on dark web marketplaces.

    What’s even more troublesome is that stolen consumer records are often purchased by marketing firms or companies, specialising in spam campaigns. Buyers can also use stolen emails to distribute malware, stage phishing and other social engineering attacks – and harvest even more data for sale. 

    One business’s negligence creates a snowball effect of negative changes down the line with customers carrying the brunt of it all. 

    In 2020, hackers successfully targeted a Finnish psychotherapy practice. They managed to steal hundreds of patient records — and then demanded a ransom both from the firm and its patients for not exposing information about their mental health issues. Many patients refused to pay hackers and some 300 records ended up being posted online as Associated Press reported.

    Not only did the practice have to deal with the cyber-breach aftermath, but it also faced vocal regulatory and patient criticisms for failing to properly protect such sensitive information.

    Security negligence can carry both direct (heavy data breach fines) and indirect losses in the form of reputational damages. An overwhelming 90% of consumers say they wouldn’t buy from a business if it doesn’t adequately protect their data. This brings us to the last point. 

    3. Reputational Risks 

    Trust is the new currency. Data negligence and consumer privacy violations are the two fastest ways to lose it. 

    Globally, consumers are concerned about how businesses collect, use, and protect their data. 

    Consumer data sharing attitudes
    • According to Forrester, 47% of UK adults actively limit the amount of data they share with websites and apps. 49% of Italians express willingness to ask companies to delete their personal data. 36% of Germans use privacy and security tools to minimise online tracking of their activities. 
    • A GDMA survey also notes that globally, 82% of consumers want more control over their personal information, shared with companies. 77% also expect brands to be transparent about how their data is collected and used. 

    When businesses fail to hold their end of the bargain — collect just the right amount of data and use it with integrity — consumers are fast to cut ties. 

    Once the information about privacy violations becomes public, companies lose : 

    • Brand equity 
    • Market share 
    • Competitive positioning 

    An AON report estimates that post-data breach companies can lose as much as 25% of their initial value. In some cases, the losses can be even higher. 

    In 2015, British telecom TalkTalk suffered from a major data breach. Over 150,000 customer records were stolen by hackers. To contain the issue, TalkTalk had to throw between $60-$70 million into containment efforts. Still, they lost over 100,000 customers in a matter of months and one-third of their company value, equivalent to $1.4 billion, by the end of the year. 

    Fresher data from Infosys gives the following maximum cost estimates of brand damage, companies could experience after a data breach (accidental or malicious).

    Estimated cost of brand damage due to a data breach

    3 Major Advantages of Privacy in Business 

    Despite all the industry mishaps, a reassuring 77% of CEOs now recognise that their companies must fundamentally change their approaches to customer engagement, in particular when it comes to ensuring data privacy. 

    Many organisations take proactive steps to cultivate a privacy-centred culture and implement transparent data collection policies. 

    Here’s why gaining the “privacy advantage” pays off.

    1. Market Competitiveness 

    There’s a reason why privacy-focused companies are booming. 

    Consumers’ mounting concerns and frustrations over the lack of online privacy, prompt many to look for alternative privacy-centred products and services

    The following B2C and B2B products are moving from the industry margins to the mainstream : 

    Across the board, consumers express greater trust towards companies, protective of their privacy : 

    And as we well know : trust translates to higher engagement, loyalty, and – ultimately revenue. 

    By embedding privacy into the core of your product, you give users more reasons to select, stay and support your business. 

    2. Higher Operational Efficiency

    Customer data protection isn’t just a policy – it’s a culture of collecting “just enough” data, protecting it and using it responsibly. 

    Sadly, that’s the area where most organisations trail behind. At present, some 90% of businesses admit to having amassed massive data silos. 

    Siloed data is expensive to maintain and operationalise. Moreover, when left unattended, it can evolve into a pressing compliance issue. 

    A recently leaked document from Facebook says the company has no idea where all of its first-party, third-party and sensitive categories data goes or how it is processed. Because of this, Facebook struggles to achieve GDPR compliance and remains under regulatory pressure. 

    Similarly, Google Analytics is riddled with privacy issues. Other company products were found to be collecting and operationalising consumer data without users’ knowledge or consent. Again, this creates valid grounds for regulatory investigations. 

    Smaller companies have a better chance of making things right at the onset. 

    By curbing customer data collection, you can : 

    • Reduce data hosting and Cloud computation costs (aka trim your Cloud bill) 
    • Improve data security practices (since you would have fewer assets to protect) 
    • Make your staff more productive by consolidating essential data and making it easy and safe to access

    Privacy-mindful companies also have an easier time when it comes to compliance and can meet new data regulations faster. 

    3. Better Marketing Campaigns 

    The biggest counter-argument to reducing customer data collection is marketing. 

    How can we effectively sell our products if we know nothing about our customers ? – your team might be asking. 

    This might sound counterintuitive, but minimising data collection and usage can lead to better marketing outcomes. 

    Limiting the types of data that can be used encourages your people to become more creative and productive by focusing on fewer metrics that are more important.

    Think of it this way : Every other business uses the same targeting parameters on Facebook or Google for running paid ad campaigns on Facebook. As a result, we see ads everywhere — and people grow unresponsive to them or choose to limit exposure by using ad blocking software, private browsers and VPNs. Your ad budgets get wasted on chasing mirage metrics instead of actual prospects. 

    Case in point : In 2017 Marc Pritchard of Procter & Gamble decided to first cut the company’s digital advertising budget by 6% (or $200 million). Unilever made an even bolder move and reduced its ad budget by 30% in 2018. 

    Guess what happened ?

    P&G saw a 7.5% increase in organic sales and Unilever had a 3.8% gain as HBR reports. So how come both companies became more successful by spending less on advertising ? 

    They found that overexposure to online ads led to diminishing returns and annoyances among loyal customers. By minimising ad exposure and adopting alternative marketing strategies, the two companies managed to market better to new and existing customers. 

    The takeaway : There are more ways to engage consumers aside from pestering them with repetitive retargeting messages or creepy personalisation. 

    You can collect first-party data with consent to incrementally improve your product — and educate them on the benefits of your solution in transparent terms.

    Final Thoughts 

    The definitive advantage of privacy is consumers’ trust. 

    You can’t buy it, you can’t fake it, you can only cultivate it by aligning your external appearances with internal practices. 

    Because when you fail to address privacy internally, your mishaps will quickly become apparent either as social media call-outs or worse — as a security incident, a data breach or a legal investigation. 

    By choosing to treat consumer data with respect, you build an extra layer of protection around your business, plus draw in some banging benefits too. 

    Get one step closer to becoming a privacy-centred company by choosing Matomo as your web analytics solution. We offer robust privacy controls for ensuring ethical, compliant, privacy-friendly and secure website tracking. 

  • Trying to get the current FPS and Frametime value into Matplotlib title

    16 juin 2022, par TiSoBr

    I try to turn an exported CSV with benchmark logs into an animated graph. Works so far, but I can't get the Titles on top of both plots with their current FPS and frametime in ms values animated.

    


    Thats the output I'm getting. Looks like he simply stores all values in there instead of updating them ?

    


    Screengrab of cli output
Screengrab of the final output (inverted)

    


    from __future__ import division
import sys, getopt
import time
import matplotlib
import numpy as np
import subprocess
import math
import re
import argparse
import os
import glob

import matplotlib.animation as animation
import matplotlib.pyplot as plt


def check_pos(arg):
    ivalue = int(arg)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError("%s Not a valid positive integer value" % arg)
    return True
    
def moving_average(x, w):
    return np.convolve(x, np.ones(w), 'valid') / w
    

parser = argparse.ArgumentParser(
    description = "Example Usage python frame_scan.py -i mangohud -c '#fff' -o mymov",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-i", "--input", help = "Input data set from mangohud", required = True, nargs='+', type=argparse.FileType('r'), default=sys.stdin)
parser.add_argument("-o", "--output", help = "Output file name", required = True, type=str, default = "")
parser.add_argument("-r", "--framerate", help = "Set the desired framerate", required = False, type=float, default = 60)
parser.add_argument("-c", "--colors", help = "Colors for the line graphs; must be in quotes", required = True, type=str, nargs='+', default = 60)
parser.add_argument("--fpslength", help = "Configures how long the data will be shown on the FPS graph", required = False, type=float, default = 5)
parser.add_argument("--fpsthickness", help = "Changes the line width for the FPS graph", required = False, type=float, default = 3)
parser.add_argument("--frametimelength", help = "Configures how long the data will be shown on the frametime graph", required = False, type=float, default = 2.5)
parser.add_argument("--frametimethickness", help = "Changes the line width for the frametime graph", required = False, type=float, default = 1.5)
parser.add_argument("--graphcolor", help = "Changes all of the line colors on the graph; expects hex value", required = False, default = '#FFF')
parser.add_argument("--graphthicknes", help = "Changes the line width of the graph", required = False, type=float, default = 1)
parser.add_argument("-ts","--textsize", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 23)
parser.add_argument("-fsM","--fpsmax", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 180)
parser.add_argument("-fsm","--fpsmin", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 0)
parser.add_argument("-fss","--fpsstep", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 30)
parser.add_argument("-ftM","--frametimemax", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 50)
parser.add_argument("-ftm","--frametimemin", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 0)
parser.add_argument("-fts","--frametimestep", help = "Changes the the size of numbers marking the ticks", required = False, type=float, default = 10)

arg = parser.parse_args()
status = False


if arg.input:
    status = True
if arg.output:
    status = True
if arg.framerate:
    status = check_pos(arg.framerate)
if arg.fpslength:
    status = check_pos(arg.fpslength)
if arg.fpsthickness:
    status = check_pos(arg.fpsthickness)
if arg.frametimelength:
    status = check_pos(arg.frametimelength)
if arg.frametimethickness:
    status = check_pos(arg.frametimethickness)
if arg.colors:
    if len(arg.output) != len(arg.colors):
        for i in arg.colors:
            if re.match(r"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", i):
                status = True
            else:
                print('{} : Isn\'t a valid hex value!'.format(i))
                status = False
    else:
        print('You must have the same amount of colors as files in input!')
        status = False
if arg.graphcolor:
    if re.match(r"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", arg.graphcolor):
        status = True
    else:
        print('{} : Isn\'t a vaild hex value!'.format(arg.graphcolor))
        status = False
if arg.graphthicknes:
    status = check_pos(arg.graphthicknes)
if arg.textsize:
    status = check_pos(arg.textsize)
if not status:
    print("For a list of arguments try -h or --help") 
    exit()


# Empty output folder
files = glob.glob('/output/*')
for f in files:
    os.remove(f)


# We need to know the longest recording out of all inputs so we know when to stop the video
longest_data = 0

# Format the raw data into a list of tuples (fps, frame time in ms, time from start in micro seconds)
# The first three lines of our data are setup so we ignore them
data_formated = []
for li, i in enumerate(arg.input):
    t = 0
    sublist = []
    for line in i.readlines()[3:]:
        x = line[:-1].split(',')
        fps = float(x[0])
        frametime = int(x[1])/1000 # convert from microseconds to milliseconds
        elapsed = int(x[11])/1000 # convert from nanosecond to microseconds
        data = (fps, frametime, elapsed)
        sublist.append(data)
    # Compare last entry of each list with the 
    if sublist[-1][2] >= longest_data:
        longest_data = sublist[-1][2]
    data_formated.append(sublist)


max_blocksize = max(arg.fpslength, arg.frametimelength) * arg.framerate
blockSize = arg.framerate * arg.fpslength


# Get step time in microseconds
step = (1/arg.framerate) * 1000000 # 1000000 is one second in microseconds
frame_size_fps = (arg.fpslength * arg.framerate) * step
frame_size_frametime = (arg.frametimelength * arg.framerate) * step


# Total frames will have to be updated for more then one source
total_frames = int(int(longest_data) / step)


if True: # Gonna be honest, this only exists so I can collapse this block of code

    # Sets up our figures to be next to each other (horizontally) and with a ratio 3:1 to each other
    fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})

    # Size of whole output 1920x360 1080/3=360
    fig.set_size_inches(19.20, 3.6)

    # Make the background transparent
    fig.patch.set_alpha(0)


    # Loop through all active axes; saves a lot of lines in ax1.do_thing(x) ax2.do_thing(x)
    for axes in fig.axes:

        # Set all splines to the same color and width
        for loc, spine in axes.spines.items():
            axes.spines[loc].set_color(arg.graphcolor)
            axes.spines[loc].set_linewidth(arg.graphthicknes)

        # Make sure we don't render any data points as this will be our background
        axes.set_xlim(-(max_blocksize * step), 0)
        

        # Make both plots transparent as well as the background
        axes.patch.set_alpha(.5)
        axes.patch.set_color('#020202')

        # Change the Y axis info to be on the right side
        axes.yaxis.set_label_position("right")
        axes.yaxis.tick_right()

        # Add the white lines across the graphs; the location of the lines are based off set_{}ticks
        axes.grid(alpha=.8, b=True, which='both', axis='y', color=arg.graphcolor, linewidth=arg.graphthicknes)

        # Remove X axis info
        axes.set_xticks([])

    # Add a another Y axis so ticks are on both sides
    tmp_ax1 = ax1.secondary_yaxis("left")
    tmp_ax2 = ax2.secondary_yaxis("left")

    # Set both to the same values
    ax1.set_yticks(np.arange(arg.fpsmin, arg.fpsmax + 1, step=arg.fpsstep))
    ax2.set_yticks(np.arange(arg.frametimemin, arg.frametimemax + 1, step=arg.frametimestep))
    tmp_ax1.set_yticks(np.arange(arg.fpsmin , arg.fpsmax + 1, step=arg.fpsstep))
    tmp_ax2.set_yticks(np.arange(arg.frametimemin, arg.frametimemax + 1, step=arg.frametimestep))

    # Change the "ticks" to be white and correct size also change font size
    ax1.tick_params(axis='y', color=arg.graphcolor ,width=arg.graphthicknes, length=16, labelsize=arg.textsize, labelcolor=arg.graphcolor)
    ax2.tick_params(axis='y', color=arg.graphcolor ,width=arg.graphthicknes, length=16, labelsize=arg.textsize, labelcolor=arg.graphcolor)
    tmp_ax1.tick_params(axis='y', color=arg.graphcolor ,width=arg.graphthicknes, length=8, labelsize=0) # Label size of 0 disables the fps/frame numbers
    tmp_ax2.tick_params(axis='y', color=arg.graphcolor ,width=arg.graphthicknes, length=8, labelsize=0)


    # Limits Y scale
    ax1.set_ylim(arg.fpsmin,arg.fpsmax + 1)
    ax2.set_ylim(arg.frametimemin,arg.frametimemax + 1)

    # Add an empty plot
    line = ax1.plot([], lw=arg.fpsthickness)
    line2 = ax2.plot([], lw=arg.frametimethickness)

    # Sets all the data for our benchmark
    for benchmarks, color in zip(data_formated, arg.colors):
        y = moving_average([x[0] for x in benchmarks], 25)
        y2 = [x[1] for x in benchmarks]
        x = [x[2] for x in benchmarks]
        line += ax1.plot(x[12:-12],y, c=color, lw=arg.fpsthickness)
        line2 += ax2.step(x,y2, c=color, lw=arg.fpsthickness)
    
    # Add titles with values
    ax1.set_title("Avg. frames per second: {}".format(y2), color=arg.graphcolor, fontsize=20, fontweight='bold', loc='left')
    ax2.set_title("Frametime in ms: {}".format(y2), color=arg.graphcolor, fontsize=20, fontweight='bold', loc='left')  

    # Removes unwanted white space; also controls the space between the two graphs
    plt.tight_layout(pad=0, h_pad=0, w_pad=2.5)
    
    fig.canvas.draw()

    # Cache the background
    axbackground = fig.canvas.copy_from_bbox(ax1.bbox)
    ax2background = fig.canvas.copy_from_bbox(ax2.bbox)


# Create a ffmpeg instance as a subprocess we will pipe the finished frame into ffmpeg
# encoded in Apple QuickTime (qtrle) for small(ish) file size and alpha support
# There are free and opensource types that will also do this but with much larger sizes
canvas_width, canvas_height = fig.canvas.get_width_height()
outf = '{}.mov'.format(arg.output)
cmdstring = ('ffmpeg',
                '-stats', '-hide_banner', '-loglevel', 'error', # Makes ffmpeg less annoying / to much console output
                '-y', '-r', '60', # set the fps of the video
                '-s', '%dx%d' % (canvas_width, canvas_height), # size of image string
                '-pix_fmt', 'argb', # format cant be changed since this is what  `fig.canvas.tostring_argb()` outputs
                '-f', 'rawvideo',  '-i', '-', # tell ffmpeg to expect raw video from the pipe
                '-vcodec', 'qtrle', outf) # output encoding must support alpha channel
pipe = subprocess.Popen(cmdstring, stdin=subprocess.PIPE)

def render_frame(frame : int):

    # Set the bounds of the graph for each frame to render the correct data
    start = (frame * step) - frame_size_fps
    end = start + frame_size_fps
    ax1.set_xlim(start,end)
     
     
    start = (frame * step) - frame_size_frametime
    end = start + frame_size_frametime
    ax2.set_xlim(start,end)
    

    # Restore background
    fig.canvas.restore_region(axbackground)
    fig.canvas.restore_region(ax2background)

    # Redraw just the points will only draw points with in `axes.set_xlim`
    for i in line:
        ax1.draw_artist(i)
        
    for i in line2:
        ax2.draw_artist(i)

    # Fill in the axes rectangle
    fig.canvas.blit(ax1.bbox)
    fig.canvas.blit(ax2.bbox)
    
    fig.canvas.flush_events()

    # Converts the finished frame to ARGB
    string = fig.canvas.tostring_argb()
    return string




#import multiprocessing
#p = multiprocessing.Pool()
#for i, _ in enumerate(p.imap(render_frame, range(0, int(total_frames + max_blocksize))), 20):
#    pipe.stdin.write(_)
#    sys.stderr.write('\rdone {0:%}'.format(i/(total_frames + max_blocksize)))
#p.close()

#Signle Threaded not much slower then multi-threading
if __name__ == "__main__":
    for i , _ in enumerate(range(0, int(total_frames + max_blocksize))):
        render_frame(_)
        pipe.stdin.write(render_frame(_))
        sys.stderr.write('\rdone {0:%}'.format(i/(total_frames + max_blocksize)))