November 9, 2018 ademcan No comments

How to create a react-native bridge library for iOS

React-Native allows user to create bridges to access native code from JavaScript. Once you have created your own bridges you might want to share them with the community. This article will explain in a few simple steps how to do so.

1. Create a new project with react-native-create-library

Open your terminal and run

react-native-create-library --package-identifier org.domain --platforms android,ios native-bridge

This will create a new project name react-native-native-bridge with all the required files in there.

2. Implement your bridge

Open the Xcode project located in the react-native-native-bridge/ios folder and edit the RNNativeBridge.m file to add your bridge functions accordingly. Here is a simple example that will return “Hello from Xcode!” when called in React-Native

RCT_EXPORT_METHOD(greetings: (RCTResponseSenderBlock)callback){
    callback(@[[NSNull null], @"Hello from Xcode!" ]);
}

If you are not familiar with native modules, go check the great documentation here.

3. Create a new npm package and publish it

Now that our hyper sophisticated bridge library is ready😉, we will propose it as an npm package on npmjs. You first need to create a new account on npmjs if you don’t have one yet. You can run

npm whoami

to check if you are logged in or not. If not, just run

npm adduser

and follow the instructions. Update the package.json file accordingly and run

npm publish

The new package will now be available to the community via the npm command and you can also see it at https://npmjs.com/package/react-native-native-bridge. You can refer to the documentation if you need any help.

4. Create a new React-Native demo app and use the package

Let’s create a new React Native project to test the npm package. Open your terminal and run

react-native init nativeBridgeTest

Install the react-native-native-bridge package and link it

npm install react-native-native-bridge
react-native link react-native-native-bridge

Open the App.js file of your React Native project and edit as follow

import RNNative Bridge from react-native-native-bridge
...
// create a new function in the App class
greetings = () => {
    RNNativeBridge.greetings( (err, res) => {
        console.log(res); 
    });
}
...
// Add a button in the render() function that will call the native function when clicked
<Button title="Greetings" onPress={this.greetings} />

This should print “Hello from Xcode!” in the logs.

Sources:
Creating a React Native Bridge Library

August 3, 2018 ademcan No comments

How to convert a NSData hexstring to a NSString in Objective-C

At the QRL we are dealing a lot with hexstrings. Several of our API functions return results in hexstring format and it is sometimes important to be able to reuse them for another call. Here is how to convert a hexstring you received as NSData object (and looks like <24501f40 6cf57975 676b6d34 95d4cd7d 14541ddd 4d44fa4a f08e6faf 9d15252b>) to a string (in our case “24501f406cf57975676b6d3495d4cd7d14541ddd4d44fa4af08e6faf9d15252b”):

NSData *data = YOUR_NSDATA_HEXSTRING;
// we first need to get the length of our hexstring
// data.lenght returns the lenght in bytes, so we *2 to get as hexstring
NSUInteger capacity = data.length * 2;
// Create a new NSMutableString with the correct lenght
NSMutableString *mutableString = [NSMutableString stringWithCapacity:capacity];
// get the bytes of data to be able to loop through it
const unsigned char *buf = (const unsigned char*) [data bytes];

NSInteger t;
for (t=0; t<data.length; ++t) {
  NSLog(@"GLYPH at t : %c", buf[t]);
  NSLog(@"DECIMAL at t  : %lu", (NSUInteger)buf[t]);
  // "%02X" will append a 0 if the value is less than 2 digits (i.e. 4 becomes 04)
  [mutableString appendFormat:@"%02X", (NSUInteger)buf[t]];
}
NSLog(@"Hexstring: %@", mutableString);
// save as NSString
NSString * hexstring =mutableString;

You can check the decimal, hex and corresponding glyph here.

sources
SO question
String Format Specifiers [Apple dev]
Bits and Bytes

July 3, 2018 ademcan No comments

How to call native Java functions from JavaScript for a React Native app (Android)

React Native is a great framework to develop mobile apps for iOS and Android with the help of JavaScript. However, at some point of your project you might need to call native functions. In React Native, invoking a native function is called bridging. In this article, I will explain how to implement a bridge communication between Java and JavaScript for your React Native based Android app.

1. Create a new react-native project or open an existing one

To create a new react-native project, open your terminal and enter the following command:

react-native init HelloWorld

This will create a new react-native app called HelloWorld with the corresponding android/ and ios/ folders containing your mobile app’s codes for the different platforms.

2. Open the project on Android Studio

Launch Android Studio and select File -> New -> Import Project… then select the HelloWorld/android folder to import to Android Studio. Your Android Studio Project window should look like this :

3. Create a new Java module

The first step to be able to use Java native code from react-native is to create a new Java module that extends the ReactContextBaseJavaModule class. To do so on the 1:Project pane of Android Studio right click on the com.helloworld folder and select New -> Java Class as shown below.

In the new window enter the following information and click OK:

Important note: in this tutorial, we will be using a callback so that your Java function can send some parameters back to JavaScript. Alternatively, one could also use a Promise (see here) or nothing at all if the main point is just to call a Java class without information going back and forth.
The newly create HelloWorldModule.java will open. You can remove the content of the file and add the following code:

package com.helloworld;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.uimanager.IllegalViewOperationException;

public class HelloWorldModule extends ReactContextBaseJavaModule {

    public HelloWorldModule(ReactApplicationContext reactContext) {
        super(reactContext); //required by React Native
    }

    @Override
    //getName is required to define the name of the module represented in JavaScript
    public String getName() { 
        return "HelloWorld";
    }

    @ReactMethod
    public void sayHi(Callback errorCallback, Callback successCallback) {
        try {
            System.out.println("Greetings from Java");
            successCallback.invoke("Callback : Greetings from Java");
        } catch (IllegalViewOperationException e) {
            errorCallback.invoke(e.getMessage());
        }
    }
}

4. Register the new Java module

Once your module is implemented, you need to register it. For the registration, you will need to create a new package. Create a new Java Class as you did earlier and call it HelloWorldPackage. Copy and paste the following code to your HelloWorldPackage.java file.

package com.helloworld;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.helloworld.HelloWorldModule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HelloWorldPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        //this is where you register the module
        modules.add(new HelloWorldModule(reactContext));
        return modules;
    }
}

5. Register the new Java package

Finally, you need to properly register the new package. Open the MainApplication.java and modify it as follow

package com.helloworld;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new HelloWorldPackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

We are simply adding the new HelloWorldPackage() code at line 26, the rest is unchanged.

6. Edit JavaScript code

It is now time to implement the JavaScript side of the app. We will create a simple TouchableOpacity element and call the native Java function on press of this element. Open the HelloWorld/App.js file with your favorite text editor and change it as below:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';

// We are importing the native Java module here
import {NativeModules} from 'react-native';
var HelloWorld = NativeModules.HelloWorld;

type Props = {};
export default class App extends Component<Props> {

  // async function to call the Java native method
  async sayHiFromJava() {
    HelloWorld.sayHi( (err) => {console.log(err)}, (msg) => {console.log(msg)} );
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={ this.sayHiFromJava }>
              <Text>Invoke native Java code</Text>
         </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

7. Start the Android Virtual Device and run the app

On Android Studio click the small AVD manager icon () and start (or create a new one if you don’t have any existing one) your AVD. Then on your terminal enter the following command:

react-native run-android

You should see the following on your Android emulator

8. Invoke the sayHi() Java function from JavaScript

Open the 6:Logcat window of Android Studio to see the Logs and press the “Invoke native java code” button in the emulator. This action will call the native Java function and should indicate the following output in your logs:

I hope this tutorial was clear, let me know how it went for you in the comments😊

Sources:
https://facebook.github.io/react-native/docs/native-modules-android
https://blog.botreetechnologies.com/how-to-build-a-react-native-android-bridge-4166e114a990
https://www.dailydrip.com/topics/react-native/drips/using-android-native-modules.html

January 17, 2018 ademcan No comments

How I implemented canSnippet’s newsletter campaign with MailChimp

“An email subscriber is worth 100x twitter or LinkedIn followers or whatever other stuff is out there. An email = a real channel” Andrew Chen

    A newsletter is an essential part of your online business/blog/project. It helps you reach your auditors more easily and keep them informed about any update regarding your project. I recently implemented a newsletter for canSnippet, my snippet management tool. I have already heard a lot about MailChimp and as it is the most commonly used service (and you can create a free account for small projects) I decided to go with it. I had some difficulties to create my first campaign (I didn’t even know what that meant at the time) so I wanted to share some essential points to help you in the creation of your first newsletter.
    There are 4 easy steps to follow for implementing a newsletter with MailChimp (without counting the fact that you already have a MailChimp account…).

1. Create a List

    This list will contain all the email addresses related to your project. You can have different lists for different projects. Connect to your MailChimp account and click on the Lists button on the top menu.

    Click the Create list button and confirm the creation of a new list. Fill the form with all the required information (you can see an example below).

Click Save to create your first list.

2. Design your forms

    Every event can be linked to a form, be it signup, unsubscibe… You can design all of these forms one by one and with great details. After creating your first list, you can click on the Signup forms tab and select General forms.
    For this simple example of a newsletter, all the forms that we will use are located under General forms except for the “Subscribe” form that will be located under Embedded forms.
There are 5 forms that are useful in case of a newsletter implementation. You can see the details of the required forms in the image below.

Click the image to see the full resolution PDF

You can select every form one by one and modify them as you like. I find the default forms already pretty good, I just added the logo and name of canSnippet on the header for additional personalisation.

3. Creating your first campaign

    You can now create your first Campaign that will correspond to your Welcome message. You can actually implement the Welcome message already in the Signup forms section, under Final Welcome email and tick the Send a final welcome email. Alternatively, you can create a Campaign and send a more personalized email every time a new user subscribes to your newsletter. That’s what we will do now, you can also refer to this approach next time you will create a Campaign.

Go to Campaigns and click Create Campaign, click Create an Email and give a name to your campaign.

Select Automated as we want the email to be sent every time a new user registers to our newsletter and select Welcome new subscribers.

In the next step just select the list we created earlier (so-called newsletter).
The final window corresponds to the heart of your campaign and will contain all the required information.
To send an automatic email every time an event is detected you need to adjust the trigger. Click Edit trigger and on the Delay section click on the drop-down menu and select Immediately and click Update Trigger.

4. Design your Welcome email

    Click Design Email and fill the form as you wish with the Email subject and Preview Text (optional) information. Then, select a template and start designing your welcome email. That’s where all the craziness starts as you can do everything you want. For a welcome email you can just start with a Basic – 1 Column layout and modify the text accordingly by adding an image for example. Then you can simply click Save and Close and click Save and Continue once you are done.

Click Next and review your workflow. If there is any issue, MailChimp will let you know. Finally, click Start workflow and confirm.

That’s it, you are done, enjoy your newsletter and share as much as you can✨

November 24, 2017 ademcan 9 comments

Upload/download images to/from AWS S3 in React-Native: a step-by-step guide

I recently struggled a lot to be able to upload/download images to/from AWS S3 in my React Native iOS app. I wanted to allow users to upload images to S3 and access some of the images from other users… I have a server running on Express (nodejs) and here is how I solved my problem.

1. Create an IAM user

Go to the IAM section on your AWS dashboard, select the Users category from the left side menu and press the Add user button.
1.1 Enter a username (test_user in this example) and select the access type Programmatic access, click Next:Permissions.

1.2 Leave this section as is and click Next:Review.

1.3 Finalize the creation of the user by clicking the Create user button.

1.4 Your new IAM user is created, click the Download .csv button and keep the file somewhere safe as it contains the Secret Access Key of your user. We will need this information later to create pre-signed URLs.

2. Create an AWS S3 bucket

Go to the S3 section on your AWS dashboard and click the + Create bucket button.
2.1 Enter a name for your bucket (test-bucket-tutorial in this example), the name has to be unique. Click Next.

2.2 Leave the default parameters in the Set properties section and click Next (you can always change them later)

2.3 Same for Set permissions, leave the default parameters and click Next

2.4 Review and click Create bucket

2.5 Go to your freshly created bucket and click + Create folder . Name your new folder images.

3. Create policy for your IAM user

So far we created our IAM user and our S3 bucket with an images folder. We now need to give permissions to our IAM user to access the S3 test-bucket-tutorial/images folder.
3.1 Go to your IAM section on your AWS dashboard and click the Policies section.

3.2 Click Create policy and select the JSON tab, then copy-paste the text below on the text input.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:ListBucket"],
      "Resource": ["arn:aws:s3:::test-bucket-tutorial/images"]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject",
        "s3:GetObjectAcl",
        "s3:GetObjectVersion",
        "s3:PutObjectAcl",
        "s3:PutObjectVersionAcl"
      ],
      "Resource": ["arn:aws:s3:::test-bucket-tutorial/images/*"]
    }
  ]
}

It should look like the picture below:

3.3 Click Review policy, give a name to your policy (test-bucket-tutorial-policy in this example) and click Create policy

4. Attach policy to your IAM user

Now we need to attach the policy to the user.
4.1 On the Policies section, select our freshly created policy.

4.2 Go to the Attached entities tab and click Attach

4.3 Select the IAM user that we created at Step1 and click Attach policy

Now the user has the permissions (listed in the policy) to access the test-bucket-tutorial/images folder in your S3 bucket.

5. Generating pre-signed URL on the server side

Pre-signed URLs allow you to create a unique URL based on the credentials that you will provide and to safely use this URL on your client-side (without providing the Secret Access Key). As written earlier, I am using expressjs as a back-end, however the code below can easily be adapted to other alternatives.
5.1 Install the node aws-sdk package.

npm install aws-sdk

5.2 Copy-paste the following code to your main javascript code when running your server, this will output the generated pre-signed URL to the console.

var AWS = require('aws-sdk');
var s3 = new AWS.S3({accessKeyId:'XXXXXXXXXXXX', secretAccessKey:'YYYYYYYYYYYY', region:'REGION'});

var params = {Bucket: 'test-bucket-tutorial', Key: 'images/myimage.jpg', ContentType: 'image/jpeg'};
s3.getSignedUrl('putObject', params, function (err, url) {
    console.log('Your generated pre-signed URL is', url);
});
  • Replace XXXXXXXXXXXX by your user’s Access Key ID that you can find on the csv file previously downloaded (Step 1.4)
  • Replace YYYYYYYYYYYY by your user’s Secret Access Key that you can find on the csv file previously downloaded
  • Replace REGION by the region of your AWS S3 bucket, you can find this information here

6. Upload images to S3 from the client-side

My client-side is implemented in React-Native. To allow the user to select a picture and send it to our S3 bucket we will use the ImagePickerIOS component (which is not very highly documented…). Put the code below on your RN app wherever you want it to be run.

ImagePickerIOS.openSelectDialog({}, imageUri => {
    const xhr = new XMLHttpRequest()
    xhr.open('PUT', presignedUrl)
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
            console.log('Image successfully uploaded to S3')
        } else {
            console.log('Error while sending the image to S3')
        }
    }
}
xhr.setRequestHeader('Content-Type', 'image/jpeg')
xhr.send({ uri: imageUri, type: 'image/jpeg', name: 'myimage.jpg'})
}, error => console.log(error));

I adapted the original code that I found in this very helpful article. Change the presignedUrl value with the pre-signed URL that you generated on your server (Step 5.2).

7. Downloading images from the client-side

If you want to download some images to your client app, you need to follow a similar approach with some slight changes:

  • remove the ContentType attribute from the params array
  • use the getObject method instead of putObject

The code will then look like:

var params = {Bucket: 'test-bucket-tutorial', Key: 'images/myimage.jpg'};
s3.getSignedUrl('getObject', params, function (err, url) {
    console.log('Your generated pre-signed URL is', url);
});

This code will generate a unique URL to access your image.
Check the AWS.S3 Documentation page if you want to learn more about the different methods that are available.

8. A concrete example

I personally use these examples in my own project as follow :
1 – The user selects a photo from the Gallery
2 – The RN app sends a request to my Express server with the name (and ID) of the user as the image filename
3 – The nodejs server generates the pre-signed URL adapted to the image filename using the AWS SDK
4 – The server sends the generated pre-signed URL to the RN app
5 – The RN app performs a HTTP request with the pre-signed URL to upload the image to S3

Let me know how it goes for you in the comments 🙂

August 10, 2017 ademcan No comments

How to get a specific sequence (chromosome, start, end) from the command line?

In several of my projects, I have to focus on specific regions of a genome, let’s say while looking for binding peaks. It is quite common to download a full genome as a fasta file, or each chromosome separately from Ensembl or NCBI. However, it is difficult to get a specific region of a genome (chromosome, start, end). I didn’t find any easy solution for it so far. Therefore, I focused on using tools available directly from NCBI, the e-utilities.

To get a specific region of the genome one needs to know the GI identifier of the chromosome of interest. Let’s say we are interested in sequences from chromosome 2L of Drosophila melanogaster. The first step is to search for it on the Nucleotide database of NCBI.

Here, we have to note the GI identifier (667674288)

Then, the command to run is

efetch -db=nuccore -format=fasta -id=667674288 -seq_start=12200 -seq_stop=13000

This will return the sequence of chromosome 2L between positions 12200 and 13000 in fasta format as follow:

>AE014134.6:12000-12200 Drosophila melanogaster chromosome 2L
ATTTCATATGTATTCACAACTTCATCACATGCGTAGGTTTCCTTATTATTCTCTGCATCATTTTCTTCCA
ACACAGACTCTTCATTTTCTAATGGTTCTACTGGAACAACGCCAGTGGGTTGCACGACTCTGGACGTGGC
TAAAGCAATACGCTGCAGTTCAGAAGAAGACATCATATACAGTGCTTCTCCAGAGTTTGTA

This command gets really handy when working with multiple regions. One could save all the regions of interest in a tab separated file with one column containing the start position and the other the end positions such as:

12000    12200
13500    13700

and then use awk to get the sequences for all those regions and save it as a fasta file:

awk '{ system("efetch -db=nuccore -format=fasta -id=667674288 -seq_start="$1" -seq_stop="$2" ") }' dmel_chr2L_peaks.txt > dmel_chr2L_peaks.fasta

Enjoy and let me know if you have any alternative solution for this problem.

June 17, 2017 ademcan 6 comments

How to submit an Electron app to the mac appstore?

 

1- Create a Bundle ID for your app

The very first step to be able to send a mac app to the appStore is to create a unique Bundle ID for it:

  • go to your Apple Developer Account
  • click Certificates, IDs & Profiles
  • select macOS in the top-left dropdown list
  • click on App IDs under the Identifiers menu
  • click the + sign on the upper-right part of the screen
  • give a description to your app, choose Explicit App ID and enter a Bundle ID (usually something like com.domain.appname)
  • click Continue and then Register

 

2- Create your developer certificates

You need two types of certificate as a developer to submit an app to the mac appStore:

  • click Certificates, IDs & Profiles
  • select macOS in the top-left dropdown list
  • click on All under the Certificates menu
  • click the + sign on the upper-right part of the screen
  • in the Production section choose Mac App Store
  • in the next page select Mac App Distribution, click Continue
  • create your Certificate Signing Request as indicated, click Continue
  • load your CSR file and download the generated certificate

In addition to the Mac App Distribution certificate, one also need a Mac Installer Distribution certificate. You need to perform the same steps as previously and select Mac Installer Distribution on step 5.
All your certificates should be ready now.
 

3- Package your Electron app

It is now time to prepare your app for the submission. You  first need to install electron-packager. This module will be helpful to create the .app and package everything we need. To install :

npm install electron-packager -g

And then run:

electron-packager . --appname=appName --app-bundle-id=com.domain.appname --version=ELECTRON_VERSION --overwrite --platform=mas --arch=x64 --icon=../appName.icns --prune --out=mas-build --ignore --app-version=1.0.0 --ignore=.+.o$

Change ELECTRON_VERSION to the correct version of Electron installed in your machine (run “electron -v” if you are not sure).
This will create your appName.app in a new folder named mas-build. This is usually enough if you want to distribute your app. However, a few more steps are required to submit it properly to the appStore.
As you can see, you also need the .icns file with the requested icon format. You can check here to see how to prepare the perfect .icns.
 

4- Sign your app

You need then to sign your app, so everybody knows it’s coming from a trustworthy developer 😉
The codesign command already exists by default on mac, you will use it to sign your app. Run the following command by properly adding the name of your certificate and the correct path to your appName.app.

codesign --deep --verbose --force --sign "3rd Party Mac Developer Application: $$$$$ (£££££)" PATH_TO/appName.app
codesign --verify -vvvv PATH_TO/appName.app

 

5-Prepare additional files

5.a- Update the Info.plist

Your app is now signed. The next step is to find your appName.app, right-click and select Show Package Contents.
Go to the Contents folder and open the Info.plist file with a text editor (not Xcode).
Add the following code

<key>ElectronTeamID</key>
<pre><string>TEAM_ID</string>

Just before

...
<code><span class="nt"></dict></span>
<span class="nt"></plist>

Here you need to replace TEAM_ID with your teamID, you can find it on your Apple developer account (click Membership then you’ll see a row named Team ID).
 

5.b- Add child.plist and parent.plist

Create the two following files with the corresponding content:

  • child.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.inherit</key>
    <true/>
  </dict>
</plist>
  • parent.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>com.apple.security.app-sandbox</key>
    <true/>
    <key>com.apple.security.application-groups</key>
    <string>TEAM_ID.your.bundle.id</string>
  </dict>
</plist>

Replace TEAM_ID by your Team ID and your.bundle.id by the unique Bundle ID of your app (we previoudly used com.domain.appname).
 

6- Create a .pkg of your app

Create a new file and name it packageAppStore.sh with the following content.

#!/bin/bash

# Name of your app.
APP="YourApp"
# The path of your app to sign.
APP_PATH="/path/to/YourApp.app"
# The path to the location you want to put the signed package.
RESULT_PATH="~/Desktop/$APP.pkg"
# The name of certificates you requested.
APP_KEY="3rd Party Mac Developer Application: Company Name (APPIDENTITY)"
INSTALLER_KEY="3rd Party Mac Developer Installer: Company Name (APPIDENTITY)"
# The path of your plist files.
CHILD_PLIST="/path/to/child.plist"
PARENT_PLIST="/path/to/parent.plist"

FRAMEWORKS_PATH="$APP_PATH/Contents/Frameworks"

codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Electron Framework"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework/Versions/A/Libraries/libnode.dylib"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/Electron Framework.framework"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper.app/Contents/MacOS/$APP Helper"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper.app/"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper EH.app/Contents/MacOS/$APP Helper EH"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper EH.app/"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper NP.app/Contents/MacOS/$APP Helper NP"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$FRAMEWORKS_PATH/$APP Helper NP.app/"
codesign -s "$APP_KEY" -f --entitlements "$CHILD_PLIST" "$APP_PATH/Contents/MacOS/$APP"
codesign -s "$APP_KEY" -f --entitlements "$PARENT_PLIST" "$APP_PATH"

productbuild --component "$APP_PATH" /Applications --sign "$INSTALLER_KEY" "$RESULT_PATH"

You need to do some changes on this file on the first lines:

  • l4: change YourApp.app by the name of your app (with the .app extension), in our case appName.app
  • l6: change /path/to/YourApp.app to the path to your appName.app
  • l8: change ~/Desktop/$APP.pkg to the directory where you want to save your final .pkg, don’t modify the $APP.pkg part
  • l10 and l11: Enter the corresponding names of your two certificates
  • l13: change /path/to/child.plist to the path to your child.plist file
  • l14: change /path/to/parent.plist to the path to your parent.plist file

Finally, run the following command to generate your appName.pkg :

./packageAppStore.sh

 

7- Launch Application Loader and load the .pkg

If you already installed Xcode, you should also have an application called Application Loader. Launch Application Loader and login with your account. You might need to get an app specific password, for this connect to appleid.apple.com and click Generate Passwords… on the APP-SPECIFIC-PASSWORDS section. Enter a Label (for example Application Loader) and copy paste the code to the Application Loader app.
Click Choose and select the freshly generate appName.pkg. This should automatically identify your app based on the Bundle ID.
Finish the whole process of uploading your app.
 

8- Complete your app information

You app build should be available on your iTunesConnect account soon. In the meantime, you need to complete the information about your app. Once done, you can select the build that you want to upload to the appStore and click Submit.
 

9- Some potential issues

If you submitted the .pkg file but it does not appear on itunesConnect, check your email. If you received something like:

Invalid Signature – The executable at path appName.app/Contents/Resources/app/node_modules/robotjs/build/Release/robotjs.node has following signing error(s): code object is not signed at all In architecture: x86_64 . Refer to the Code Signing and Application Sandboxing Guide at http://developer.apple.com/library/mac/#documentation/Security/Conceptual/CodeSigningGuide/AboutCS/AboutCS.html and Technical Note 2206 at https://developer.apple.com/library/mac/technotes/tn2206/_index.html for more information.

You need to sign the different modules mentioned in this email. For that, just do as follow for each module:

electron-osx-sign appName.app appName.app/Contents/Resources/app/node_modules/robotjs/build/Release/robotjs.node

Voilà 🙂 You can now enjoy some coffee while waiting for the review. Congratulations!

Source: https://electron.atom.io/docs/tutorial/mac-app-store-submission-guide/

June 12, 2017 ademcan No comments

How to draw a Venn diagram in R?

The topic of today is about Venn diagrams, see here for a detailed defition. I will quickly show you how to draw a Venn diagram composed of three distinct datasets in R.

For this purpose you will need the VennDiagram package. Start R and install the required package as follow:

install.packages('VennDiagram')
library(VennDiagram)

The main command to draw your Venn diagram is:

draw.triple.venn(area1 = 3472, area2 = 3528, area3 = 3492, n12 = 3176, n23 = 3323, n13 = 3182, n123 = 3096, category = c("sample1", "sample2", "sample3"), lty = "blank", fill = c("skyblue", "pink1", "mediumorchid") , cex=2, cat.cex=2, cat.fontfamily = rep("serif", 3))

The resulting Venn diagram will look like :

The explanation of the different numbers (area1, area2, area3, n12, n23, n13 and n123) are represented in the figures below:

June 7, 2017 ademcan No comments

How to launch a job on SGE based clusters ?

As bioinformaticians, we often have to deal with computer clusters. There are different computer cluster systems available such as SGE, LSF… Although the main idea is the same, the commands used to submit a job might be slightly different. In this article I will quickly show how to submit a job to an SGE (Sun Grid Engine) based cluster.

There are two main commands that are very useful :

  • qsub: to submit a job to the cluster
  • qstat: to check the jobs you submitted to the cluster

There are two ways to submit a job to a cluster:

1 – Submission via a script

An example of a script is shown below, let’s call the script file jobscript.sh. In this case, it is essential to specify all the parameters as header of the script.

#!/bin/bash
#$ -N jobName
#$ -q jobQueue
#$ -o /path_to/jobs.out
#$ -e /path_to/jobs.err
cd /folder
$YOUR_COMMAND

Here, we are starting a job with the following parameters:

  • -N: name of the job
  • -q: queue on which to run the job
  • -o: path to the output file
  • -e: path to the error file
  • The rest of the script correspond to the commands we want to run

Some additional helpful headers are as follow:

  • -pe smp 8: number of threads to use for the job (here 8)
  • -cwd: start the job on current working directory
  • -M: email address (to get notifications about the job status)
  • -m [b,e,a,s,n]: status to be notified about (beginning, end, aborted, suspended, no mail)

For more information see: http://gridscheduler.sourceforge.net/htmlman/htmlman1/qsub.html

To start your job, you need to run

qsub jobscript.sh

2 – Direct submission from the command line

There is an alternative way to submit a job from the command line.


qsub -N jobName -q jobQueue -o /path_to/jobs.out -e /path_to/jobs.err [ENTER]

cd /folder [ENTER]

$YOUR_COMMAND [Ctrl+D]

This way the job will be submitted as soon as you press Ctrl+D. You can use several commands by pressing ENTER to separate each of them and start the job by pressing Ctrl+D after the last command.