Subscribe

Tag: GSoC17

Open-Event Front-end uses Ember data for handling Open Event Orga API which abides by JSON API specs. It allows the user to manage the event using the event panel of that event. This panel lets us create or update sessions & speakers. Each speaker must be associated with a session, therefore we save the session before saving the speaker.In this blog we will see how to Implement the session & speaker creation via event panel. Lets see how we implemented it?

Passing the session & speaker models to the formOn the session & speaker creation page we need to render the forms using the custom form API and create new speaker and session entity. We create a speaker object here and we pass in the relationships for event and the user to it, likewise we create the session object and pass the event relationship to it.These objects along with form which contains all the fields of the custom form, tracks which is a list of all the tracks & sessionTypes which is a list of all the session types of the event is passed in the model.

We bind the speaker & session object to the template which has contains the session-speaker component for form validation. The request is only made if the form gets validated.

Saving the data

In Open Event API each speaker must be associated with a session, i.e we must define a session relationship for the speaker. To accomplish this we first save the session into the server and once it has been successfully saved we pass the session as a relation to the speaker object.

this.get('model.session').save().then(session=>{letspeaker=this.get('model.speaker');speaker.set('session',session);speaker.save().then(()=>{this.get('notify').success(this.l10n.t('Your session has been saved'));this.transitionToRoute('events.view.sessions',this.get('model.event.id'));});})

We save the objects using the save method. After the speakers and sessions are save successfully we notify the user by showing a success message via the notify service.

Thank you for reading the blog, you can check the source code for the example here.

An Android application often includes settings that allow the user to modify features of the app. For example, SUSI Android app allows users to specify whether they want to use in built mic to give speech input or not. Different settings in SUSI Android app and their purpose are given below

Setting

Purpose

Enter As Send

It allows users to specify whether they want to use enter key to send message or to add new line.

Mic Input

It allows users to specify whether they want to use in built mic to give speech input or not.

Speech Always

It allows users to specify whether they want voice output in case of speech input or not.

Speech Output

It allows users to specify whether they want speech output irrespective of input type or not.

Language

It allows users to set different query language.

Reset Password

It allows users to change password.

Select Server

It allows users to specify whether they want to use custom server or not.

Android provides a powerful framework, Preference framework, that allows us to define the way we want preferences. In this blog post, I will show you how Settings UI is created using Preference framework and Kotlin in SUSI Android.

Advantages of using Preference are:

It has own UI so we don‘t have to develop our own UI for it

It stores the string into the SharedPreferences so we don’t need to manage the values in SharedPreference.

First, we will add the dependency in build.gradle(project) file as shown below.

compile ‘com.takisoft.fix:preference-v7:25.4.0.3’

To create the custom style for our Settings Activity screen we can set

android:theme=“@style/PreferencesThemeLight”

as the base theme and can apply various other modifications and colour over this. By default, it has the usual Day and Night theme with NoActionBar extension.

Layout Design

I used PreferenceScreen as the main container to create UI of Settings and filled it with the other components. Different components used are following:

SwitchPreferenceCompat: This gives us the Switch Preference which we can use to toggle between two different modes in the setting.

<com.takisoft.fix.support.v7.preference.SwitchPreferenceCompat

android:defaultValue=”true”

PreferenceCategory: It is used for grouping the preference. For example, Chat Settings, Mic Settings, Speech Settings etc are different groups in settings.

ListPreference: This preference display list of values and help in selecting one.For example in setLanguage option ListPreference is used to show a list of query language. List of query language is provided via xml file array.xml (res/values). Attribute android:entries point to arrays languagentries and android:entryValue holds the corresponding value defined for each of the languages.

<ListPreference

android:title=“@string/Language”android:key=“Lang_Select”

android:entries=“@array/languagentries”

android:entryValues=“@array/languagentry”

</ListPreference>

Implementation in SUSI Android

All the logic related to Preferences and their action is written in ChatSettingsFragment class. ChatSettingsFragment extends PreferenceFragmentCompat class.

class ChatSettingsFragment:PreferenceFragmentCompat()

Fragment populate the preferences when created. addPreferencesFromResource method is used to inflate view from xml.

Open Event Organizer is a client side application of Open Event API Server created for event organizers and entry managers. The app maintains a local database and syncs it with the server when required. I will be talking about handling data requests in the app in this blog.

The app uses ReactiveX for all the background tasks including data accessing. When a user requests any data, there are two possible ways the app can perform. The one where app fetches the data directly from the local database maintained and another where it requests data from the server. The app has to decide one of the ways. In the Organizer app, AbstractObservableBuilder class takes care of this. The relevant code is:

finalclassAbstractObservableBuilder<T>{privatefinalIUtilModelutilModel;privatebooleanreload;privateObservable<T>diskObservable;privateObservable<T>networkObservable;......@NonNullprivateCallable<Observable<T>>getReloadCallable(){return()->{if(reload)returnObservable.empty();elsereturndiskObservable.doOnNext(item->Timber.d("Loaded %s From Disk on Thread %s",item.getClass(),Thread.currentThread().getName()));};}@NonNullprivateObservable<T>getConnectionObservable(){if(utilModel.isConnected())returnnetworkObservable.doOnNext(item->Timber.d("Loaded %s From Network on Thread %s",item.getClass(),Thread.currentThread().getName()));elsereturnObservable.error(newThrowable(Constants.NO_NETWORK));}@NonNullprivate<V>ObservableTransformer<V,V>applySchedulers(){returnobservable->observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());}@NonNullpublicObservable<T>build(){if(diskObservable==null||networkObservable==null)thrownewIllegalStateException("Network or Disk observable not provided");returnObservable.defer(getReloadCallable()).switchIfEmpty(getConnectionObservable()).toList().flatMap(items->diskObservable.toList()).flattenAsObservable(items->items).compose(applySchedulers());}}

DiskObservable is a data request to the local database and networkObservable is a data request to the server. The build function decides which one to use and returns a correct observable accordingly. The class object takes a boolean field reload which is used to decide which observable to subscribe. If reload is true, that means the user wants data from the server, hence networkObservable is returned to subscribe. Also switchIfEmpty in the build method checks whether the data fetched using diskObservable is empty, if found empty it switches the observable to the networkObservable to subscribe.

This class object is used for every data access in the app. For example, this is a code snippet of the gettEvents method in EventRepository class.

When you build an Android app, you must consider about users for whom you are building an app. It may be possible that you users are from the different region. To support the most users your app should show text in locale language so that user can use your app easily. Our app SUSI Android is also targeting users from different regions. Internationalization is a way that ensures our app can be adapted to various languages without requiring any change to source code. This also allows projects to collaborate with non-coders more easily and plugin translation tools like Weblate.

Benefits of using Internationalization are:

It reduces the time for localization i.e it will localize your app automatically.

It helps us to keep and maintain only single source code for different regions.

To achieve Internationalization in Android app you must follow below steps:

Move all the required contents of your app’s user interface into the resource file.

We need to create separate directories for different locale because to show locale specific content, Android check specific folder i.e res/<resource type>-(language code) like res/values-de and show content from that folder. That’s why we need to move all the required content into resource file so that each required content can be shown in the specific locale.

How Internationalization is implemented in SUSI Android

In SUSI Android there is not any locale specific image but only string. So I created only locale specific value resource folder to add locale specific strings. To create locale specific values folder I follow the above-mentioned rule i.e <resource type>-(language code).

After that, I added specific language string in the respective folder.

Instead of hard-coded strings, we used strings from string.xml file so that it will change automatically according to the region.

android:text=“@string/reset”

and

showToast(getString(R.string.wrong_password))

In absence of resource directory for any specific locale, Android use default resource directory.

Integrate Weblate in SUSI Android

Weblate is a web based translation tool. The best part of Weblate is its tight version control integration which makes it easy for translators to contribute because translator does not need to fork your repo and send pull request for each change but Weblate handle this part i.e translator translate strings of the project in Weblate site and Weblate will send pull request for those changes.

Weblate can host your free software projects for free but it depends on them. Here is the link of SUSI Android project hosted on Weblate. If your project is good then they can host your project for free. But for that, you have to apply from this link and select ask for hosting. Now fill up form as shown in below picture.

Once your project is hosted on Weblate, they will email you about it. After that, you have to integrate Weblate in your project so that Weblate can automatically push translated strings to your project and also Weblate get notify about changes in your repository. Here is the link on how to add Weblate service and Weblate user to your project.

If it is not possible to host your project on Weblate for free then you can host it by own. You can follow below steps:

First, we deploy Weblate on our localhost using the installation guide given on Weblate site. I install Weblate from git. I cloned latest source code using Git

git clone https://github.com/WeblateOrg/weblate.git

Now change directory to where you cloned weblate source code and install all the required dependencies and optional dependencies using code

pip install -r requirements.txt

and

pip install -r requirements-optional.txt

After doing that we copy weblate/settings_example.py to weblate/settings.py. Then we configure settings.py and use the following command to migrate the settings.

./manage.py migrate

Now create an admin using following command.

./manage.py createadmin

After that add a project from your Admin dashboard (Web translations-> Projects-> Add Project) by filling all details.

Once the project is added, we add the component (Web translations-> Components-> Add Component) to link our Translation files.

To change any translation we make changes and push it to the repository where our SSH key generated from Weblate is added. A full guide to do that is mentioned in this link.

Sometimes we need to store information on the device locally so that we can use information offline and also query data faster. Initially, SQLite was only option to store information on the device. But working with SQLite is difficult sometimes and also it makes code difficult to understand. Also, SQL queries take a long time. But now we have realm a better alternative of SQLite. The Realm is a lightweight mobile database and better substitute of SQLite. The Realm has own C++ core and store data in a universal, table-based format by a C++ core. This allows Realm to allow data access from multiple languages as well as a range of queries. In this blog post, I will show you why we used Realm and how we save data in SUSI Android using Realm.

“How about performance? Well, we’re glad you asked 🙂 For all the API goodness & development productivity we give you, we’re still up to 100x faster than some SQLite ORMs and on average ~10x faster than raw SQLite and common ORMs for typical operations.” (compare: https://blog.realm.io/realm-for-android/)

Advantages of Realm over SQLite are following:

It is faster than SQLite as explained on the Realmblog. One of the reasons realm is faster than SQLite is, the traditional SQLite + ORM abstraction is leaky because ORM simply converts Objects and their methods into SQL statements. Realm, on the other hand, is anobject database, meaning your objects directly reflect your database.

It is easier to use as it uses objects for storing data. When we use SQLite we need boilerplate code to convert values to and from the database, setting up mappings between classes and tables, fields and columns, foreign keys, etc. Whereas in Realm data is directly exposed as objects and can be queried without any conversion.

Prerequisites

To include this library in your project you need

Android studio version 1.5.1 or higher.

JDK version 7.0 or higher.

Android API level 9 or higher.

How to use realm in Android

To use Realm in your project we must add the dependency of the library in build.gradle(project) file

Field in the model class uses to define columns. For eg. ‘name’ is a column name. Method like setName() use to save data and getName() use to retrieve saved data.

Now create an instance of the Realm in the activity where you want to use it. It will be used to read data from the Realm and write data to the Realm.

Realm realm = Realm.getInstance(this);

Before you start a new transaction you must call beginTransaction(). It will open database.

realm.beginTransaction();

To write data to the Realm you need to create an instance of the model class. createObject used to create an instance of RealmObject class. Our model class is RealmObject type so we use createObject() to create an instance of the model class.

Person person = realm.createObject(Person.class);

Write data to realm.

person.setName(“MSDHONI”);

And after it you must call commitTransaction(). commitTransaction() use to end transaction.

realm.commitTransaction();

Reading data from Realm is easier than writing data to it. You need to create an instance of the Realm.

Realm realm = Realm.getInstance(this);

To create query use where the method and pass the class of object you want to query. After creating query you can fetch all data using findAll() method.

But, what if the user wanted to group certain questions under a specific category. There was no solution in the FAQ API for that. So a new API, FAQ-Types was created.

Why make a separate API for it?

Another question that arose while designing the FAQ-Types API was whether it was necessary to add a separate API for it or not. Consider that a type attribute was simply added to the FAQ API itself. It would mean the client would have to specify the type of the FAQ record every time a new record is being created for the same. This would mean trusting that the user will always enter the same spelling for questions falling under the same type. The user cannot be trusted on this front. Thus the separate API made sure that the types remain controlled and multiple entries for the same type are not there.

Helps in handling large number of records:

Another concern was what if there were a large number of FAQ records under the same FAQ-Type. Entering the type for each of those questions would be cumbersome for the user. The FAQ-Type would also overcome this problem

Meilix is the repository which uses build script to generate community version of lubuntu as LXQT Desktop. Meilix-Generator is the webapp which uses Meilix to generate ISO and deploy it on Meilix Github Release. Then the webapp mail the link of the ISO to the user.
Increasing number of ISO will increase the number of releases which results in dirty looking of Meilix repository. So we need to delete older releases after certain interval of time to make the repository release page looks good and decrease unwanted space.
This releases_maintainer.sh script will do this work for us.

#!/usr/bin/env bashset-eecho"This is a script to delete obsolete meilix iso builds by Abishek V Ashok"echo"You have to add an authorization token to make it functional."# jq is the JSON parser we will be usingsudoapt-get-yinstalljq# Storing the response to a variable for future usageresponse=`curl https://api.github.com/repos/fossasia/meilix/releases | jq '.[] | .id, .published_at'`index=1# when index is odd, $i contains id and when it is even $i contains published_datedelete=0# Should we delete the release?current_year=`date +%Y`# Current year eg) 2001current_month=`date +%m`# Current month eg) 2current_day=`date +%d`# Current date eg) 24foriin$response;doif[$((index%2))-eq0];then# We get the published_date of the release as $i's value herepublished_year=${i:1:4}published_month=${i:6:2}published_day=${i:9:2}if[$published_year-lt$current_year];thenlet"delete=1"elseif[$published_month-lt$current_month];thenlet"delete=1"elseif[$((current_day-$published_day))-gt10];thenlet"delete=1"fififielse# We get the id of the release as $i`s value hereif[$delete-eq1];thencurl-XDELETE-H"Authorization: token $KEY"https://api.github.com/repos/fossasia/meilix/releases/$ilet"delete=0"fifilet"index+=1"done

This code uses Github API to curl the Meilix releases. Github API is very useful in providing lots of information but here we are only concerned with the release date and time of the build.
Then we setup a condition if that satisfies then the release will automatically will get deleted.

For taking care of the authentication, a token has been uploaded to the Travis settings of Meilix of FOSSASIA.

The personal token has been generated by a user with write access to the repository with repo scope token.

This sort out the issue of having bulk of releases in the Meilix repository of FOSSASIA.

The Open Event System allows usage of discount codes with tickets and events. This blogpost describes what types of discount codes are present and what endpoints can be used to fetch and update details.

In Open Event API Server, each event can have two types of discount codes. One is ‘event’ discount code, while the other is ‘ticket’ discount code. As the name suggests, the event discount code is an event level discount code and the ticket discount code is ticket level.

Now each event can have only one ‘event’ discount code and is accessible only to the server admin. The Open Event server admin can create, view and update the ‘event’ discount code for an event. The event discount code followsDiscountCodeEvent Schema. This schema is inherited from the parent class DiscountCodeSchemaPublic. To save the unique discount code associated with an event, the event model’s discount_code_id field is used.

The ‘ticket’ discount is accessible by the event organizer and co-organizer. Each event can have any number of ‘ticket’ discount codes. This follows the DiscountCodeTicket schema, which is also inherited from the same base class ofDiscountCodeSchemaPublic. The use of the schema is decided based on the value of the field ‘used_for’ which can have the value either ‘events’ or ‘tickets’. Both the schemas have different relationships with events and marketer respectively.

We have the following endpoints for Discount Code events and tickets:‘/events/<int:event_id>/discount-code’‘/events/<int:event_id>/discount-codes’

The first endpoint is based on the DiscountCodeDetail class. It returns the detail of one discount code which in this case is the event discount code associated with the event.

The second endpoint is based on the DiscountCodeList class which returns a list of discount codes associated with an event. Note that this list also includes the ‘event’ discount code, apart from all the ticket discount codes.

Since each discount code belongs to an event(either directly or through the ticket), the factory for this has event as related factory, but to check for /events/<int:event_id>/discount-codeendpoint we first need the event and then pass the discount code id to be 1 for dredd to check this. Hence, event is not included as a related factory, but added as a different object every time a discount code object is to be used.

Note that it will only be set in the context of function decorated by jwt_required(). The problem with the current_identity proxy when using jwt_required is that the token has to be active, the identity of an expired token cannot be fetched by this function.

So why not write a function on our own to do the same. A JWT token is divided into three segments. JSON Web Tokens consist of three parts separated by dots (.), which are:

Header

Payload

Signature

The first step would be to get the payload, that can be done as follows:

token_second_segment=_default_request_handler().split('.')[1]

The payload obtained above would still be in form of JSON, it can be converted into a dict as follows:

payload=json.loads(token_second_segment.decode('base64'))

The identity can now be found in the payload as payload[‘identity’]. We can get the actual user from the paylaod as follows:

defget_identity():""" To be used only if identity for expired tokens is required, otherwise use current_identity from flask_jwt :return: """token_second_segment=_default_request_handler().split('.')[1]missing_padding=len(token_second_segment)%4payload=json.loads(token_second_segment.decode('base64'))user=jwt_identity(payload)returnuser

But after using this function for sometime, you will notice that for certain tokens, the system will raise an error saying that the JWT token is missing padding. The JWT payload is base64 encoded, and it requires the payload string to be a multiple of four. If the string is not a multiple of four, the remaining spaces can pe padded with extra =(equal to) signs. And since Python 2.7’s .decode doesn’t do that by default, we can accomplish that as follows:

missing_padding=len(token_second_segment)%4# ensures the string is correctly padded to be a multiple of 4ifmissing_padding!=0:token_second_segment+=b'='*(4-missing_padding)

SUSI Linux has an assistant user interface to answer your queries. You may ask queries and SUSI answers interactively using a host of skills which range from entertainment, knowledge, media to science, technology and sports. While SUSI is finding the answer to the query, it makes sense to add some animations depicting the process. The UI for SUSI Linux app is wholly made using GTK+ 3 using PyGObject (PyGTK). Thus, I needed to find a way create animations in GTK+.

Animations in most frameworks are generally created using repetitive drawing after an interval which leads to the effect of an object’s movement. Thus, basic need was to find a way to draw a custom object in GTK+. Reading the documentation of the GTK+, I realized that this could be done with a GTKDrawingArea.

GTKDrawingArea defines an area on which application developers can do the drawing on their own. GTK itself does not provide Canvas and related object to draw the shapes. For that, we need to use Cairo graphics library. Cairo is an open source graphics library with support for multiple window systems. It can run on a variety of backends, though here, we are not concerned about them.

Cairo can be accessed in Python using Pycairo. Pycairo is a set of Python 2 & 3 bindings for the cairo graphics library. Resources for usage of Pycairo for animations with GTK+ 3 are very less thus I will try to explain it in this blog in detail. We will start by creating an Animator class extending the GTK DrawingArea class.

In the above code stub, we created the Animator class extending the GTK.DrawingArea. Animator class is meant to be an abstract class for the other animators. We defined the size request of the area we want and connected the “draw” signal to the do_drawing method. On notable thing to note here is that, we have “draw” signal on GTK+ 3 while on GTK+2 we have “on_expose” signal. On the creation of the widget, draw signal is fired. In the handler do_drawing method, we receive widget and ctx. Here ctx is the Cairo context. We can perform our drawing with the help of the of Cairo context. We further call the draw method passing the context, width and height of the widget. On notable thing here is that, even though we requested for a size for the widget, allocated size might be different depending upon a number of factors. Thus, drawing must be done according to allocated area instead of the absolute area.

The draw is an abstract method. All the animators must override this method to implement custom drawing on the widget area. Lastly, we add a timeout based call to tick method. This is what drives the animation. This is done with the help of GLib.timeout_add(). Here the first argument is the time in milliseconds after which callback should be fired and second argument is the callback that should be fired. We are calling tick method in the class. It is required for the method to return True if successful for proper functioning. We call queue_draw method from within the tick method. queue_draw leads to invalidation of current area and again generates the draw signal.

Now that we know how the core of the animation will work, let us define some cool animations for the Listening phase of the application. We define the Listening Animator for the same.

In this we are drawing some lines with round cap to create an effect like below.

Since, the lines must move we are using trigonometric functions to create sinusoidal movement with some phase difference between adjacent lines. To set color of the brush, we use set_source_rgb method. We may then move the pointer to desired position, draw lines or other shapes. Then, we can either fill the shape or draw strokes using the relevant methods. The full list of methods can be accessed here in the official documentation.After creating the widget, it can be easily added to the UI depending on the type of the container, generally by add method. You may access the full code of SUSI Linux repository to learn more about the usage in SUSI Linux App. The final result can be seen in the following video.