Join Codeheat Contest 2021/22 in Memory of Areeb Jamal

Join the Codeheat Coding Contest 2021/22 in memory of Areeb Jamal and become a codehero. The contest runs until May 2022.

Contributors in the community know Areeb since he started as a FOSSASIA intern. Areeb had become the chief technologist in the organization where he has mentored hundreds of young developers in coding programs. Areeb passed away during the pandemic in India because of a lack of oxygen. He was a wonderful person. All he wanted was to share his knowledge and support others. He will be forever in our hearts and we will always remember him as a genius, kind and generous person. Please watch this video here to learn more about Areeb’s life.

During the contest mentors support contributors on gitter channels and in our monthly “Ask Me Anything” events you can talk to team members.

Codeheat Contest Details

In the contest we will announce winners every two months. All participants with a minimum of five merged PRs in the entire contest time can receive a digital certifcate of participation. Winners will also receive a prize of appreciation.

All issues with the label “codeheat” in any project of FOSSASIA can be taken up in the contest. There are many participating projects, but we have two lead projects. The Open Event Project and the Pocket Science Lab are our focus.

Codeheat Focus Projects

1. The first focus project this year is the Open Event project running the eventyay website. It enables users to run onsite and virtual events entirely with Open Source. Technologies used are Python and Javascript. Please check out the frontend and backend repositories.

2. The second focus project is the Pocket Science Lab project that is now coming with support for Circuitpython and a new hardware version. We are looking for developers who are interested in contributing to the desktop app using web technologies and Electron as well as Android and firmware developers.

Upcoming Codeheat Events

Codeheat “Ask Me Anything” on Wednesday, 24 November, 2021 8:00 PM (IST)

Codeheat “Ask Me Anything” on Wednesday 15 December 2021 8:00 PM (IST)

Codeheat “Ask Me Anything” on Wednesday 19 January 2022 8:00 PM (IST)

Codeheat “Ask Me Anything” on Wednesday 16 February 2022 8:00 PM (IST)

Codeheat “Ask Me Anything” on Wednesday 16 March 2022 8:00 PM (IST)

Codeheat “Ask Me Anything” on Wednesday 20 April 2022 8:00 PM (IST)

Codeheat “Ask Me Anything” on Wednesday 18 May 2022 8:00 PM (IST)

Links

Website: codeheat.org

Codeheat Twitter: twitter.com/codeheat_

FOSSASIA Twitter: twitter.com/fossasia

Codeheat Facebook: facebook.com/codeheat.org

Continue ReadingJoin Codeheat Contest 2021/22 in Memory of Areeb Jamal

Let’s Collaborate on Open Solutions at FOSSASIA

The FOSSASIA Summit 2020 in March already feels like an eternity away. With support from many contributors and sponsors we were able to pull off the event despite all the challenges. Thank you!

It has been impossible for FOSS contributors and Open Source companies since to organize in-person events, meet developers or collaborate on projects face to face.

There is not just a pandemic crisis happening right now, we see a violent political crisis in many regions of the world and also the climate crisis continues to affect people everywhere. These crises show more than ever that – just like in the FOSS community – we need everyone to collaborate on a global scale and to solve problems together with an open on all layers approach.

Below is some information on solutions we are working on at FOSSASIA and how we can team up in the Codeheat coding contest.

Let’s make Virtual Events Use Only FOSS/Open Source!

Currently we are integrating our hosted open source event solution with online video tools such as Jitsi or Big Blue Button. Right now many organizers depend on proprietary tools to run virtual events. Let’s change that. Check out the latest features of Open Event on eventyay.com, have a look at some of the upcoming events and sign up!

Let’s Develop Together and Share our Knowledge in Codeheat

We are running more and more activities online and we are adapting our annual coding contest Codeheat. We support participants by providing “Ask Me Anything” online support sessions, giving out more prizes every two months and extending the overall time of the contest until June 2021. Please join now at codeheat.org or contact us if your company would like to sponsor the program.

Let’s Make Science Truly Open Again with Pocket Science Lab

At FOSSASIA we believe it is only possible to solve our global issues by giving everyone access to open knowledge and tools. For this reason we are working on the miniaturization of science tools by developing the open hardware Pocket Science Lab.

Our goal is to create a science measurement device that is easy to handle, easy to transport, and easy to use. And of course it must fulfill the promise of science to provide every aspect of science openly starting with the hardware and software that collects data.

The PSLab can be connected to a smartphone and extend its capabilities. It enables everyone to collect data through sensors, control robots and to exchange data easily. Currently we are in the final steps of prototyping the next version which will come with an SD Card, on board real time clock, optional WiFi, Bluetooth, or Lora extensions, sleeping mode for datalogging and much more.

To learn more please download and test the project and start contributing to the repositories. Our weekly open hardware meetings take place every Saturday.
 

Continue ReadingLet’s Collaborate on Open Solutions at FOSSASIA

Join Codeheat Coding Contest 2019/20

Master Git, contribute to Open Source, and win a trip to the FOSSASIA Summit Singapore with Codeheat! Codeheat is the annual coding contest for developers to contribute to Free and Open Source software (FOSS) and open hardware projects of FOSSASIA. Join development of real world software applications and win awesome prizes, build up your developer profile, learn new coding skills, collaborate with the community and make new friends from around the world! Sign up now for the fourth edition of Codeheat on the website and follow Codeheat on Twitter.

Start date: September 15, 2019

End date: February 2, 2020

Which Projects Participate

Open Event – Eventyay / Code / Chat

SUSI AI – Website / Code / Chat

Pocket Science Lab (PSLab) – Website / Code / Chat

Phimpme Android – App / Code / Chat

Meilix Linux Distribution – Code / Chat

Voicerepublic – Website / Code / Chat

Badge Magic- App / Code / Chat

Neurolab – Code / Chat

Badgeyay – Website / Code / Chat

How to Join the Contest

  • The contest is open to everyone.
  • Participants can join at any time
  • Register on the site and check out the Frequently Asked Questions for more details.
  • Also join the FOSSASIA Gitter chat and communicate with mentors and follow developers on project specific channels. 

What are the Prizes

  • Winners (3 prizes): Listed on website, certificate, 600SGD travel voucher, 5-night accommodation in Singapore, Tshirt and FOSSASIA limited edition swags. 
  • Finalist (7 prizes): Listed on website, certificate, travel voucher of 100 SGD, Tshirt and FOSSASIA limited edition swags. 
  • Active Contributors (unlimited): Certificate, CodeHeat Tshirt and FOSSASIA limited edition of swags (with at least 10 merged pull requests)
  • Community Participants (unlimited): Digital Certificate of Participation (with at least 5 merged pull requests)

What are the Judging Criteria

Our jury will review the work of the 10 developers who have the highest number of quality contributions during the contest. Contributions include pull requests/code commits, scrum reports, articles, screencasts, community engagement and outreach activities. The mentors will look at the:  

Sustainability, which means that we specifically value contributions that make the project sustainable by building a community where developers collaborate with each other in a friendly way and support the project development through peer reviews, on-boarding new members, and helping fellow contributors. It also means that, while code is the most important success criteria for winning the contest, furthermore we are looking for contributions in other areas to make projects easy to join, to deploy and to use. This includes:

  • creating and enhancing documentation
  • developing how-tos
  • writing technical blog posts
  • sharing work in regular scrum updates to enhance communication
  • organizing local meetups, workshops, presentations 

Quality vs. Quantity: The sheer number of pull requests is not the only criteria for choosing the winners. Quality work is appreciated – some issues are more challenging than others just by their nature (for example, heavy coding versus solving a text typo bug). It is entirely possible that someone who completed 53 issues could be chosen as a winner over someone who completed 88 issues.

How Are the Winners Decided

  • Grand Prize Winners: Three developers will be selected by mentors from the top 10 contributors according to code quality, relevance of commits and contributions that help to bring the project forward.  
  • Finalist Winners: After the grand prize winners are selected, the remaining seven contributors of top the 10 will receive finalist winner prizes.
  • Other contributors who have more than 10 merged pull requests during the contest will receive a Thank you package. Anyone who has 5 pull requests merged will receive a digital certificate.

Links

Website: codeheat.org

Codeheat Twitter: twitter.com/codeheat_

FOSSASIA Twitter: twitter.com/fossasia

Codeheat Facebook: facebook.com/codeheat.org

Continue ReadingJoin Codeheat Coding Contest 2019/20

Join Codeheat Coding Contest 2018/19

Codeheat is a coding contest for developers interested in contributing to Open Source software and hardware projects at FOSSASIA.  Join development of real world software applications, build up your developer profile, learn new new coding skills, collaborate with the community and make new friends from around the world! Sign up for #CodeHeat here now and follow Codeheat on Twitter.

The contest runs until 1st February 2019. Different FOSSASIA projects take part in the Codeheat contest including:

Grand prize winners will be invited to present their work at the FOSSASIA OpenTechSummit in Singapore in March 2019 and will get 600 SGD in travel funding to attend, plus a free speaker ticket and beautiful Swag.

Our jury will choose three winners from the top 10 contributors according to code quality and relevance of commits for the project. The jury also takes other contributions like submitted weekly scrum reports and monthly technical blog posts into account, but of course awesome code is the most important item on the list.

Other participants will have the chance to win Tshirts, Swag and vouchers to attend Open Tech events in the region and will get certificates of participation.

codeheat-logo

Team mentors and jury members from 10 different countries support participants of the contest.

Participants should take the time to read through the contest FAQ and familiarize themselves with the introductory information and Readme.md of each project before starting to work on an issue.

Developers interested in the contest can also contact mentors through project channels on the FOSSASIA Gitter Chat.

Links

Website: codeheat.org

Codeheat Twitter: twitter.com/codeheat_

Codeheat Facebook: facebook.com/codeheat.org

Participating Projects Code Repositories: github.com/fossasia

Continue ReadingJoin Codeheat Coding Contest 2018/19

Badgeyay: Integrating EmberJS Frontend with Flask Backend

Badgeyay is a simple badge generator with a simple web UI that generates a printable badge in PDFs. The project had gone through different cycles starting from a Flask server to a CLI application then a python library and now API Interface for generation of badges.

According to latest changes in the project structure, now the frontend and backend are independent components developed in Ember JS and Flask respectively. Now there is a need to connect the frontend to the backend, which means the user should see the response on the same page without refresh, if the badge generated successfully. AJAX would fit right into the spot. Asynchronous Javascript and XML also known as AJAX, will enable us to perform asynchronous operation on the page without refreshing the page.

We can make an API call to the Server running in backend or deployed on heroku, but the server is not suitable for doing CORS(Cross-Origin Resource Sharing), ability to share the resources on server with the client having different domain names, but as the server and the frontend are not hosted on the same host  so there is a need to enable the server to accept CORS request calls.

Now the challenges were:

  • Enabling Flask Server to accept CORS requests.
  • AJAX query for sending request to the Flask server.

Procedure

  1. Giving the form an id and creating an AJAX request to the Flask server (may be localhost or deployed on heroku).
<form id=”form1″ action=”” method=”post” enctype=”multipart/form-data” onsubmit=”return validate()”>

 

When the generate button is clicked, an AJAX request is made to the server to generate badges and at the same time prevent the page from refreshing. In the AJAX request we set the CORS header to allow the domain.

 

<script type=”text/javascript”>
$(document).ready(function () {
$(‘#form1’).submit(function (event) {
event.preventDefault();
$.ajaxSetup({
headers: {“Access-Control-Allow-Origin”: “*”}
});
$.ajax({
url: “http://badgeyay-api.herokuapp.com/api/v1.0/generate_badges”,
data: $(this).serialize(),
type: ‘POST’,
success: function (data) {…},
error: function (error) {…}
})
});
})
</script>

 

  1. Import the library and enable the API endpoint to accept CORS requests.
from flask_cors import CORS
cors = CORS(app, resources={r”/api/*”: {“origins”: “*”}})

 

  1. Add Logic for appending the download link by extracting the download link from the response and replacing the static text in the template with the download link, also changing the download variable to the filename, by stripping the base url from the download link.
if (data[“response”][0][“type”] === “success”) {
$(‘#success’).css(‘visibility’, ‘visible’);
let link = data[“response”][0][“download_link”];
link = link.replace(“backend/app/”, “http://badgeyay-api.herokuapp.com/”);
$(‘#badge-link’).attr(“href”, link);
link = link.replace(“static/badges/”, “”);
$(‘#badge-link’).attr(“download”, link);
}

 

  1. Output the success on the page.
<div id=”success” style=”visibility: hidden;”>
<div class=”flash-success”>Your badges have been created successfully.</div>
<div class=”text-center”>
<a id=”badge-link” href=”http://badgeyay-api.herokuapp.com/static/badges/{{msg}}-badges.pdf”
class=”btn btn-success”
download=”{{msg}}-badges.pdf”>Download as
PDF</a>
</div>
</div>

 

  1. Frontend and Backend now are connected to each other.The Server now accepts CORS requests and response is generated after the user requests from Frontend.

 

The Pull Request with the above changes is on this Link

Topics Involved

Working on this issue (Link)  involves following topics :

  • Enabling Flask Server for CORS
  • Request Headers
  • AJAX request for CORS.

References

Continue ReadingBadgeyay: Integrating EmberJS Frontend with Flask Backend

Badgeyay: Custom Fonts in generation of badges

Badgeyay is an open source project of FOSSASIA. The main idea for this project is to provide an open-source alternative for badge generation process for any event. It can generate badges according to a predefined config or we can also submit our own custom config for the generation of the badges. We can use custom background, text and other things. One thing that is not present is the choice for choosing a custom font for the badge. I have made a contribution for adding this functionality with selection of some common fonts in the code.

Procedure

  1. Add a Button in index.html for the choice of the font and also preview them at the same time. 
    <label>Choose your font</label>
    <ul style=“list-style-type:none”>
     <li>
        <input type=“radio” name=“fontsource” id=“custfont”> Use Custom font
                        </li>
                        <section id=“custom-font” style=“display: none;”>
        <label for=“inputFile”>Select from following fonts</label>
        <div class=“btn-group”>
           <button type=“button” class=“btn btn-default dropdown-toggle” data-toggle=“dropdown” aria-haspopup=“true” aria-expanded=“false”>
              <span class=“placeholder2”>Select a font</span>
              <span class=“glyphicon glyphicon-chevron-down”></span>
           </button>
           <ul class=“dropdown-menu”>
              {% for i in custom_fonts %}
              <li class=“font-options” style=“font-family:'{{i}}'” data-item=“{{i}}”>{{i}}</li>
              {% endfor %}
           </ul>
        </div>
     </section>
     <input type=“hidden” name=“custfont” value=“”>
    </ul>

     

     

  2. Add javascript for the toggle in the check button and CSS for the Font option button.
.$(“.font-options”).click(function () {
  var i = $(this).data(“item”);
  $(“.placeholder2”).text(i);
  $(“input[name=’custfont’]”).val(i);
});

 

.font-options {
border-bottom: 1px solid darkgray;
padding: 9px;
}

 

  1. Font list is passed in the index page.
CUSTOM_FONTS = [‘monospace’, ‘sans-serif’, ‘sans’, ‘Courier 10 Pitch’, ‘Source Code Pro’]

 

render_template(‘index.html’, default_background=default_background, custom_fonts=CUSTOM_FONTS)

 

  1. Config file for font has been created, so that it can be used by different files.
custom_font = request.form[‘custfont’]
# Custom font is selected for the text
if custom_font != :
  json_str = json.dumps({
      ‘font’: custom_font
  })
  f = open(os.path.join(app.config[‘UPLOAD_FOLDER’], ‘fonts.json’), “w+”)
  f.write(json_str)
  f.close()

 

  1. Font preference is taken from the file at the time of generation of the badge (once only for all the badges in a single run).
font_choice = None
if os.path.isfile(os.path.join(UPLOAD_FOLDER, ‘fonts.json’)):
  DATA = json.load(open(os.path.join(UPLOAD_FOLDER, “fonts.json”)))
  font_choice = DATA[‘font’]

 

  1. Changes in the SVG are made according to the preference for the PDF generation. If the user wants a custom font then it updates the svg using the config else not.
content = CONTENT
if font_choice:
  content = content.replace(“font-family:sans-serif”,
                            “font-family:” + font_choice)
  content = content.replace(“inkscape-font-specification:sans-serif”,
                            “inkscape-font-specification:” + font_choice)
  content = content.replace(“font-family:ubuntu”,
                            “font-family:” + font_choice)
  content = content.replace(“inkscape-font-specification:ubuntu”,
                            “inkscape-font-specification:” + font_choice)

 

  1. Finally the Updated SVG is used for Badge Generation with custom fonts embedded.

Resources

Resources utilised for adding this functionality

  • Fonts in SVG – Link
  • Embed fonts in Inkscape SVG – Link
  • Embed fonts in PDF and SVG – Link

 

Continue ReadingBadgeyay: Custom Fonts in generation of badges

Maintaining Extension State in SUSI.AI Chrome Bot Using Chrome Storage API

SUSI Chrome Bot is a browser action chrome extension which is used to communicate with SUSI AI.The browser action extension in chrome is like any other web app that you visit. It will store all your preferences like theme settings and speech synthesis settings and data till you are interacting with it, but once you close it, it forgets all of your data unless you are saving it in some database or you are using cookies for the session. We want to be able to save the chats and other preferences like theme settings the user makes when interacting with SUSI AI through Susi Chrome Bot. In this blog, we’ll explore Chrome’s chrome.storage API for storing data.

What options do we have for storing data offline?

IndexedDB: IndexedDB is a low-level API for client-side storage of data. IndexedDB allows us to store a large amount of data and works like RDBMS but IndexedDB is javascript based Object-oriented database.

localStorage API: localStorage allows us to store data in key/value pairs which is much more effective than storing data in cookies. localStorage data persists even if the user closes and reopens the browser.

Chrome.storage: Chrome provides us with chrome.storage. It provides the same storage capabilities as localStorage API with some advantages.

For susi_chromebot we will use chrome.storage because of the following advantages it has over the localstorage API:

  1. User data can be automatically synced with Chrome sync if the user is logged in.
  2. The extension’s content scripts can directly access user data without the need for a background page.
  3. A user’s extension settings can be persisted even when using incognito mode.
  4. It’s asynchronous so bulk read and write operations are faster than the serial and blocking localStorage API.
  5. User data can be stored as objects whereas the localStorage API stores data in strings.

Integrating chrome.storage to susi_chromebot for storing chat data

To use chrome.storage we first need to declare the necessary permission in the extension’s manifest file. Add “storage” in the permissions key inside the manifest file.

"permissions": [
         "storage"
       ]

 

We want to store the chat user has made with SUSI. We will use a Javascript object to store the chat data.

var storageObj = {
senderClass: "",
content: ""
};

The storageObj object has two keys namely senderClass and content. The senderClass key represents the sender of the message(user or susi) whereas the content key holds the actual content of the message.

We will use chrome.storage.get and chrome.storage.set methods to store and retrieve data.

var susimessage = newDiv.innerHTML;
storageObj.content = susimessage;
storageObj.senderClass = "susinewmessage";
chrome.storage.sync.get("message",(items) => {
if(items.message){
storageArr = items.message;
}
storageArr.push(storageObj);
chrome.storage.sync.set({"message":storageArr},() => {
console.log("saved");
});
});

 

In the above code snippet, susimessage contains the actual message content sent by the SUSI server. We then set the correct properties of the storageObj object that we declared earlier. Now we can use chrome.storage.set to save the storageObj object but that would overwrite the current data that we have inside chrome’s StorageArea. To prevent the old message data from getting overwritten, we’ll first get all the message content in our storage using chrome.storage.sync.get. Notice how we are passing the “message” string as the first perimeter to the function. This is done because we only want our message content which was saved in the StorageArea. If we pass null instead, it will return all the content inside storageArea. Once we have our messages (which will be an array of objects that we store as storageObj), we will store that into a new array storageArr. We will then push our new storageObj that contains the message and the sender into the array. Finally, we use chrome.storage.sync.set to save the message content in chrome’s StorageArea which can later be retrieved using the “message” key.

storageArr.push(storageObj);
chrome.storage.sync.set({"message":storageArr},() => {
console.log("saved");
});

We use the same procedure to save messages sent by the user.

Note: chrome.storage is not very large, so we need to be careful about what we store or we may run out of storage space. Also, we should not store confidential data in storage since the storage area is not encrypted.

Resources:

Tags:

  • FOSSASIA, codeheat, Chrome extensions, Javascript, Chrome Storage, Chrome Sync, Susi Chrome Bot, SUSI AI, Bot Development
Continue ReadingMaintaining Extension State in SUSI.AI Chrome Bot Using Chrome Storage API

Adding Map Type Response to SUSI.AI Chromebot

SUSI.AI Chromebot has almost all sorts of reply that SUSI.AI Server can generate. But it still missed the Map Type response that was generated by the SUSI.AI Server.

This blog explains how the map type response was added to the chromebot.

Brief Introduction

The original issue was planned by Manish Devgan and Mohit Sharma as an advanced task for Google Code-In 2017. The link to which can be found here: #157

For a long time the issue remained untouched and after GCI got over I assigned the issue to myself as it was a priority issue since MAP type was a major response from the SUSI.AI Server.

How was Map Type response added?

There were a lot of things to be taken in mind before starting working on this issue.

  • Changing code scheme during GCI and other PRs
  • API Response from the SUSI.AI Server
  • Understanding the new codebase that got altered during GCI-17
  • Doing it quick

I will go through all the steps in detail

Changing Code Scheme

The code was altered numerous times with the addition of a number of pull requests during GCI-17 and there were no docstrings for any functions and methods. So I had to figure them out in order to start working on the map type response.

API Response from the SUSI.AI Server

To understand the JSON that server sent, I went to SUSI.AI API and did a simple search for

“Where is Berlin?” and the response generated is given below.

( Since the JSON is very big I am only posting the relevant data for this issue )

 

    "actions": [
      {
        "type": "answer",
        "language": "en",
        "expression": "Berlin (, German: [bɛɐ̯ˈliːn] ( listen)) is the capital and the largest city of Germany as well as one of its 16 constituent states."
      },
      {
        "type": "anchor",
        "link": "https://www.openstreetmap.org/#map=13/52.52436820069531/13.41053001275776",
        "text": "Here is a map",
        "language": "en"
      },
      {
        "type": "map",
        "latitude": "52.52436820069531",
        "longitude": "13.41053001275776",
        "zoom": "13",
        "language": "en"
      }
    ]

 

Here we see and understand that “actions” is an Array of JSONs and the third part has “type” as “map”. This is the relevant information that we require for generating the map-type response.

The important variables in this context are: “latitude” and “longitude”.

Understanding the Codebase

Now I had to figure out the new pattern of adding response types to the SUSI.AI Chromebot.

After having a talk with @ms10398 I figured out the route map.

The above image shows the correct flow of Javascript Code that generated the response. After this, I was good to go and start my work.

Adding the Map-Type Response

To start with I chose “LEAFLET.JS” as the Javascript Library that will be used to create maps.

  • So I added the LEAFLET.JS to the JS folder.
  • Now changes were made to the “index.html” file

 

<link rel=”stylesheet” href=”https://unpkg.com/leaflet@1.3.1/dist/leaflet.css” />

http://”js/leaflet.js”

 

Appropriate CSS was added along with a link to leaflet.js was added.

  • Adding CSS to the “mapClass
.mapClass{

    height : 200px;

    width : 200px;

}

 

  • Generating Maps with dynamic IDs

This part was where I applied brain, as to add the map to any div we required the div to have a proper and unique ID and so a way to generate unique IDs for div without using any external source was to be thought of.

I came with idea of using timestamp, as it will always be unique.

var timeStamp = new Date.now().toString();

 

Then I created the “composeMapReply()” function.

function composeReplyMap(response, action){

    var newDiv = messages.childNodes[messages.childElementCount];

    var mapDiv = document.createElement(“div”);

    var mapDivId = Date.now().toString();

    mapDiv.setAttribute(“id”, mapDivId);

    mapDiv.setAttribute(“class”, “mapClass”);

    newDiv.appendChild(mapDiv);

    messages.appendChild(newDiv);

    var newMap = L.map(mapDivId).setView([Number(action.latitude), Number(action.longitude)], 13);

 L.tileLayer(“https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}”,{

    /*

        This part contains the data for api call.

    */

}).addTo(newMap);

response.isMap = true;

response.newMap = mapDiv;

return response

    

}

 

The complete code can be found: here

At last after adding so many snippets of code we were able to generate the Map-Type response for SUSI.AI Chromebot

GIF

A gif showing the Map-Type response in action.

 

Resources

 

Continue ReadingAdding Map Type Response to SUSI.AI Chromebot

Generating Badges for Manual Data for Pre-Selected Badges

BadgeYay is a Badge Generator developed by FOSSASIA. In recent time there was a BUG that caused the badge generator to throw errors and malfunction while generating the badges.

This error was first reported by me, @gabru-md. And later when everyone seemed to have this bug it was resolved after a complete 48 hour of reverse engineering the code.

What was the Bug?

The bug with the generator was that the server side API did not function well and was not generating badges in cases of Manual Input and Pre-Selected Images.The issue was first made sure and then created on github as Issue number 314 .

Resolving the Bug

Resolving the bug this time was a hard task as the code was not properly maintained due to many PRs being merged and due to this it took me 48 hours to figure out what was wrong with the code.

After like 1 day of reading between the lines it was found out that the bug was caused due to improper “if…else” conditions. There were several  small bugs that arouse when this main bug was being dealt with.

How was it resolved?

Many changes were done to the code to resolve the bug. It was definitely the most time consuming and important fix that I had ever applied to any project.

The only changes were done to the main server file “main.py”.

  • Adding a missing line to the file.
text_on_image = request.form[“text_on_image”]

 

  • Removing unnecessary code for cleaning up the file.
if file.filename == ‘’  and csv ==  ‘’:

    flash(‘Please select a CSV field to upload’)

    return redirect(url_for(‘index’))

 

And

elif:

    if file.find(“png.csv”) != -1:

        if img == ‘’:

            flash(‘{Please upload an image in ...’)   

            return redirect(url_for(‘index’))

    else:

        flash(‘Please upload ...’)

 

  • Adding the relevant code to fix the bug.

 

if img == ‘’:

    img = request.filed[‘image’].filename

    filename = request.files[‘image’].filename + “.csv”

elif csv != ‘’:

Changing filename to “img + .csv” resolved the filename error that caused the badge generator not to recognize the files.

Saving the files to the correct places for the script to recognize them

image.save(os.path.join(app.config[‘UPLOAD_FOLDER’],image.filename))

 

Changing the rest of the code to comply with the changes and make Badgeyay BUG free.

elif eventyay_url != ‘’:

    filename = ‘speaker.png.csv’

    generate_csv_eventyay.tocsv(eventyay_url,filename)

if filename.find(‘png.csv’) != -1:

    if img == ‘’:

        flash(“Please Upload …”)

        return redirect(url_for(‘index’))

else:

    flash(‘Please Upload a CSV …’)

    return redirect(url_for(‘index’))

 

The last change was to change an “if” condition to a relevant one.

if csv == ‘’ and filename == img + ‘.csv’ and eventyay_url == ‘’:

 

All these changes helped resolve one of the major bugs in Badgeyay. With the merging of the associated PR the bug was immediately fixed and Badgeyay was up again.

Challenges

  • Lack of time since service was down for a long time
  • Improper code

 

But I took them as challenges and was able to fix it for once and for all.

Further Improvements

Further Improvements will be leading to a more fast and stable Badgeyay with more user friendly options and an improved UI and stronger UX.

Resources

 

Continue ReadingGenerating Badges for Manual Data for Pre-Selected Badges

Adding Preview Support to BadgeYay!

In an issue it was requested to add a Preview support for BadgeYay, i.e. Badges could be seen before they were generated.

Why Preview Support?

It is a nice question. But Preview support was needed in a badge generator like BadgeYay.

This can be easily answered by an example. Let us suppose that I want to generate hundreds-thousands of badges for a meetup/event that I have organized. But I am confused as to what will look the best on and as badges. So I can just try them all in the Preview section and then choose the one that I like and generate it.

How to add Preview Support?

Adding Preview Support was not an easy task. Although coding it was not the hard part, but thinking of a way that uses less of the server’s support was a thing to take care of.

I had two options to choose from.

Implement Preview Section from backend

This was the idea that first came to my mind when i thought of implementing something like preview section.

It included of generating badges everytime the user wanted a preview and then using the same SVGs generated to show as the preview of badges.

Problems it had

Using Backend to generate badges for every instance would result to a lot of load to the server prior to the actual badge generation. And making it faster and creating less load on server was the main problem to tackle. So I came up with another idea of using frontend to generate Preview(s).

Implementing Preview Section from frontend

This method of generating preview is far more faster and less load heaving to the server.

It uses technologies such as HTML, CSS and Javascript to  generate preview for badges.

The Pull Request for the same is : here

Changes in index.html

  • Adding a button to view preview
<button type=”button” disabled=”disabled” class=”btn btn-block btn-warning” id=”preview-btn”>Preview</button>

 

  • Adding the text areas for badge

Adding appropriate HTML for text areas.

  • Adding Appropriate CSS
.preview-image{

height: 250px;

width: 180px;

margin-left: 80px;

background-size: cover;

padding: 140px 0 0 5px;

text-align: center;

margin-top: 20px;

}

.preview-image-li{

list-style: none;

color: white;

font-size: 15px;

}

#preview-btn{

font-size: 18px;

}

 

  • Adding Javascript code for functionality
function readURL(input){

if(input.files && input.files[0]){

var reader = new FileReader();

reader.onload = function(e){

$(‘#preview’).css(‘background-image’,’url(‘ + e.target.result + ‘)’);

$(‘#preview’).css(background-size’,’cover’);

$(‘#preview-btn’).prop(“disabled”,false);

};

reader.readAsDataURL(input.files[0]);

}

}

 

The above snippet of code adds the image to the background of the preview div and stretches it to occupy full space.

var textValues = $(‘#textArea’).val();

textValues = textValues.split(“/n”)[0].strip(‘,’);

$(‘#preview-li-1’).text(textValue[0]);

$(‘#preview-li-2’).text(textValue[1]);

$(‘#preview-li-3’).text(textValue[2]);

$(‘#preview-li-4’).text(textValue[3]);

The above snippet of code adds the input from the textArea to the appropriate place on the preview badge.

Further Improvements

Adding a real-time preview feature that allows user to see the changes in real-time therefore making the application more flexible and enhancing user experience.

Resources

 

Continue ReadingAdding Preview Support to BadgeYay!