text:
"""A scanner for the pycompiler project.
"""
import sys, os, string, shutil
parent_dir = os.path.abspath( os.path.join(__file__, '../..') )
if not parent_dir in sys.path:
    sys.path.append(parent_dir)

__all__ = ['Scanner', 'alphanum', 'special']

from globals import *
from util import *

whitespace = string.whitespace
letters = string.ascii_letters
digits = string.digits
alphanum = letters + digits
special = sorted( [ch for ch in set(string.printable) -
                                set(alphanum).union( set(string.whitespace) )] )

class Scanner:
    def __init__(self, srcfile=None,
                    tokfile='tokfile',
                    **kwargs):
        """@param srcfile: will only read srcfile
        @param tokfile: scan will create or overwrite this file
        """
        self.srcfile = srcfile
        self.tokfile_path = tokfile
        self.tokfile = None
        self.reserved = ['declare', 'put', 'get', 'stop', 'goto', 'if', 'then', 'end', 'do',]

    def scan(self):
        """Scans the sourcefile and produces the tokenfile."""
        self.tokfile = open(self.tokfile_path, 'w')
        word = ''
        for line in open(self.srcfile):
            for ch in line:
                if ch in alphanum:
                    word += ch
                else:
                    if word:
                        try:
                            self.print_tok('$int', int(word))
                        except ValueError:
                            if word in self.reserved:
                                self.print_tok('$' + word)
                            else:
                                self.print_tok('$id', word)
                    if ch in special:
                        self.print_tok(ch)
                    word = ''
        self.tokfile.close()

    def print_tok(self, name, value=None):
        """Print name and value or '' with lineseps to tokenfile."""
        val = '' if value == None else value
        tokstring = '%s%s%s' % (name, os.linesep, val)
        print >> self.tokfile, tokstring

    def tokfile_equiv_w_cpp_scanner(self):
        """Runs scan and runs the platform dependent executable for the cpp scanner from cs4110
        on the same sourcefile.
        @return: true if tokenfiles produced are equivalent
        """
        self.scan()
        tokfile = os.path.join(tempdir, 'tokfile')
        Scanner.run_cpp_scanner(self.srcfile, tokfile)
        ours = open(self.tokfile_path).read()
        theirs = open(tokfile).read()
        return ours == theirs

    @staticmethod
    def run_cpp_scanner(srcfile, tokfile):
        """Runs the platform dependent executable for the cpp scanner from cs4110 on srcfile
        and copies resulting token file to tokfile.
        """
        path = resourcedir
        shutil.copyfile(srcfile, os.path.join(path, 'srcfile'))
        #open(os.path.join(path, 'srcfile'), 'w').write(open(srcfile).read())

        if sys.platform[:3] == 'win':
            print 'need win exe'
        elif sys.platform[:5] == 'linux':
            exec_name = 'cpp_scanner_ubuntu'
            cmd = 'cd %s; ./%s; cd -' % (path, exec_name)
            os.popen(cmd)

        shutil.copyfile(os.path.join(path, 'tokfile'), tokfile)
        #open(tokfile, 'w').write( open(os.path.join(path, 'tokfile')).read() )

if __name__ == '__main__':
    scanner = Scanner(srcfile='srcfile',
                      tokfile='tokfile')
    scanner.scan()


text:
package com.ceco.marshmallow.gravitybox.quicksettings;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import de.robv.android.xposed.XposedHelpers;

/**
 * Generic invocation handler for handling tile's DetailAdapter interface proxy calls
 * Registered callback handles method calls defined on the interface
 */
public class QsDetailAdapterProxy implements InvocationHandler {

    public static final String IFACE_DETAIL_ADAPTER = BaseTile.CLASS_BASE_TILE+".DetailAdapter";

    public interface Callback {
        int getTitle();
        Boolean getToggleState();
        View createDetailView(Context context, View convertView, ViewGroup parent) throws Throwable;
        Intent getSettingsIntent();
        void setToggleState(boolean state);
    }

    private Callback mCallback;

    private QsDetailAdapterProxy() { /* must be created via createProxy */ };

    private QsDetailAdapterProxy(Callback cb) {
        mCallback = cb;
    }

    public static Object createProxy(ClassLoader cl, Callback cb) {
        if (cb == null)
            throw new IllegalArgumentException("Callback cannot be null");

        return Proxy.newProxyInstance(cl,
                new Class<?>[] { XposedHelpers.findClass(IFACE_DETAIL_ADAPTER, cl) },
                new QsDetailAdapterProxy(cb));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("getTitle")) {
            return mCallback.getTitle();
        } else if (method.getName().equals("getToggleState")) {
            return mCallback.getToggleState();
        } else if (method.getName().equals("getSettingsIntent")) {
            return mCallback.getSettingsIntent();
        } else if (method.getName().equals("setToggleState")) {
            mCallback.setToggleState((boolean)args[0]);
            return null;
        } else if (method.getName().equals("getMetricsCategory")) {
            return 111;
        } else if (method.getName().equals("createDetailView")) {
            return mCallback.createDetailView((Context)args[0], (View)args[1], (ViewGroup)args[2]);
        } else {
            return null;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
D.import_port_flavour('dom-on-click', {
  dir: 'in',
  settings: [
    {
      key: 'thing',
      desc: 'A dom selector for binding',
      type: 'selector'
    },
    {
      key: 'parent',
      desc: 'A dom element contain thing. Defaults to document.',
      type: 'id'
    },
  ],
  outside_add: function() {
    var self = this
    D.track_event('click', this.settings.thing, this.settings.parent, function(value) {self.enter(value)})
  }
})


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Validation extends CI_Controller {

	public function __construct()
    {
        parent::__construct();
        // $this->form_validation->set_error_delimiters('
×', '
');
    }

	public function send_message()
	{
		$this->form_validation->set_rules('name','Nama','xss_clean|trim|required');
		$this->form_validation->set_rules('email','Email','xss_clean|trim|required|valid_email');
		$this->form_validation->set_rules('subject','Topik','xss_clean|trim|required');
		$this->form_validation->set_rules('message','Aspirasi','xss_clean|trim|required');

		$name 		= $this->input->post('name');
		$email 		= $this->input->post('email');
		$subject 	= $this->input->post('subject');
		$message 	= $this->input->post('message');
		$attachment = $this->input->post('attachment');

		if($this->form_validation->run() === FALSE)
		{
			$msg['err_msg'] = validation_errors();
			$repopulate = array(
				'name' => $name,
				'email' => $email,
				'subject' => $subject,
				'message' => $message
			);
			$this->session->set_flashdata($repopulate);

		}
		else
		{
			$hash = preg_replace('/[^0-9]+/', '', md5(uniqid(time(), true)), 10);
			$filename = url_title(date('dmy').'-'.$name, 'dash', TRUE);
			$file = array();
			if (!empty($_FILES['attachment']['name'])) {
       			$files = $_FILES['attachment'];
            	foreach($files['name'] as $k => $v) {
					$_FILES['attachment']['name']     = $files['name'][$k];
					$_FILES['attachment']['type']     = $files['type'][$k];
					$_FILES['attachment']['tmp_name'] = $files['tmp_name'][$k];
					$_FILES['attachment']['error']    = $files['error'][$k];
					$_FILES['attachment']['size']     = $files['size'][$k];
					// chmod($path = ,0755);
					$config['upload_path'] 		= './assets/uploaded_files/attachments';
					$config['allowed_types'] 	= 'jpg|jpeg|pdf|png|doc|docx|xls|xlsx|ppt|pptx|txt|rtf|rar|zip';
					$config['max_size'] 		= 2048;
					$config['overwrite']		= FALSE;
	                $config['file_name'] 		= $filename;
	                $config['max_filename_increment'] = 50;

					$this->upload->initialize($config);
					if ($this->upload->do_upload('attachment')) {
						$data = $this->upload->data();
						chmod($data['full_path'], 0755);
						$file[$k] =  $data['file_name'];
					} else {
						$msg['err_msg'] = $this->upload->display_errors();
					}
				}
			}

			$data = array(
				'name' => $name,
				'email' => $email,
				'subject' => $subject,
				'message' => $message,
				'attachments' => implode(",", $file),
				'hash' => $hash,
				'status' => 'not read yet',
				'tipe' => 'msg'
			);
			$inserted = $this->messages_model->makeMessage($data);
			if ($inserted === TRUE) {
				$msg['scss_msg'] = "We've received your message. Thanks for participating actively to make better Undip.";
			} else {
				foreach ($file as $f) {
					$myfile = $f;
					unlink('./assets/uploaded_files/attachments/'.$myfile);
				}

				$msg['err_msg'] = "An error occurred. Please try again. If error still occurs, please contact us";
			}
		}

		$this->session->set_flashdata($msg);
		redirect('kotak-saran');

	}
	public function create_post(){

		$this->form_validation->set_rules('title','Title','xss_clean|trim|required');
		$this->form_validation->set_rules('body','Post Body','xss_clean|trim|required');

        $title = $this->input->post('title');
        $body = $this->input->post('body');
        $post_category = $this->input->post('category');
        $post_images = $this->input->post('user_file');

        if($post_category == null){
            $post_category = 0;
        }

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'title' => $title,
                'body' => $body
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
            $hash = md5(uniqid(time(), true));
            $slug = url_title($title, 'dash', true);
            $images = array();
            $filename = date('dmy')."-".$slug;

            if (!empty($_FILES['user_file']['name'])) {
       			$files = $_FILES['user_file'];
            	foreach($files['name'] as $k => $v) {
					$_FILES['user_file']['name']     = $files['name'][$k];
					$_FILES['user_file']['type']     = $files['type'][$k];
					$_FILES['user_file']['tmp_name'] = $files['tmp_name'][$k];
					$_FILES['user_file']['error']    = $files['error'][$k];
					$_FILES['user_file']['size']     = $files['size'][$k];

					$config['upload_path']      = './assets/images/post';
	                $config['allowed_types']    = 'jpg|jpeg|png';
	                $config['max_size']         = 50120;
	                $config['overwrite']        = FALSE;
	                $config['file_name']        = $filename;
	                $config['max_filename_increment'] = 50;

					$this->upload->initialize($config);
					if ($this->upload->do_upload('user_file')) {
						$data = $this->upload->data();
						$images[$k] = $data['file_name'];
					} else {
						$msg['err_msg'] = $this->upload->display_errors();
					}
				}
            }

            if (!empty($post_category)) {
                $data = array(
                    'title' => $title,
                    'slug' => $slug,
                    'body' => $body,
                    'category' => implode(",",$post_category),
                    'image' => implode(",",$images),
                    'hash' => $hash,
                    'author' =>$this->session->userdata('user_id')
                );
            } else {
                $data = array(
                    'title' => $title,
                    'slug' => $slug,
                    'body' => $body,
                    'category' =>$post_category,
                    'image' => implode(",",$images),
                    'hash' => $hash,
                    'author' =>$this->session->userdata('user_id')
                );
            }

            $inserted = $this->post_model->createPost($data);

            if ($inserted === TRUE) {
                $msg['scss_msg'] = "Success creating new post";
            } else {
                foreach ($images as $ui) {
                    $img = $ui;
                    unlink('./assets/images/post/'.$img);
                }

                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        redirect('post');
    }
    public function do_updatePost($id){
        $this->form_validation->set_rules('title','Title','xss_clean|trim|required');
        $this->form_validation->set_rules('body','Post Body','xss_clean|trim|required');

        $title = $this->input->post('title');
        $body = $this->input->post('body');
        $post_category = $this->input->post('category');
        $post_images = $this->input->post('user_file');

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'title' => $title,
                'body' => $body
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
            $hash = md5(uniqid(time(), true));
            $slug = url_title($title, 'dash', true);
            $images = array();
            $filename = date('dmy')."-".$slug;

            if (!empty($_FILES['user_file']['name'])) {
                $files = $_FILES['user_file'];
                foreach($files['name'] as $k => $v) {
                    $_FILES['user_file']['name']     = $files['name'][$k];
                    $_FILES['user_file']['type']     = $files['type'][$k];
                    $_FILES['user_file']['tmp_name'] = $files['tmp_name'][$k];
                    $_FILES['user_file']['error']    = $files['error'][$k];
                    $_FILES['user_file']['size']     = $files['size'][$k];

                    $config['upload_path']      = './assets/images/post';
                    $config['allowed_types']    = 'jpg|jpeg|png';
                    $config['max_size']         = 50120;
                    $config['overwrite']        = FALSE;
                    $config['file_name']        = $filename;
                    $config['max_filename_increment'] = 50;

                    $this->upload->initialize($config);
                    if ($this->upload->do_upload('user_file')) {
                        $data = $this->upload->data();
                        $images[$k] = $data['file_name'];
                    } else {
                        $msg['err_msg'] = $this->upload->display_errors();
                    }
                }
            }

            if (!empty($post_category) && !empty($images)) {
                $data = array(
                    'title' => $title,
                    'slug' => $slug,
                    'body' => $body,
                    'category' => implode(",",$post_category),
                    'image' => implode(",",$images),
                    'hash' => $hash,
                    'author' =>$this->session->userdata('user_id')
                );
            } else if (!empty($post_category) && empty($images)) {
                $data = array(
                    'title' => $title,
                    'slug' => $slug,
                    'body' => $body,
                    'category' => implode(",",$post_category),
                    'author' =>$this->session->userdata('user_id')
                );
            } else if (!empty($images) && empty($post_category)) {
                $data = array(
                    'title' => $title,
                    'slug' => $slug,
                    'body' => $body,
                    'image' => implode(",",$images),
                    'author' =>$this->session->userdata('user_id')
                );
            } else{
                $data = array(
                    'title' => $title,
                    'slug' => $slug,
                    'body' => $body,
                    'author' =>$this->session->userdata('user_id')
                );
            }

            $inserted = $this->post_model->doUpdatePost($id,$data);

            if ($inserted === TRUE) {
                $msg['scss_msg'] = "Success Update post";
            } else {
                foreach ($images as $ui) {
                    $img = $ui;
                    unlink('./assets/images/post/'.$img);
                }

                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        if($this->session->userdata('user_id') == 'admin'){
            redirect('post');
        }else{
            redirect('post-user');
        }
    }
    public function new_comment($slug,$id){
    	$this->form_validation->set_rules('nama','Nama','xss_clean|trim');
		$this->form_validation->set_rules('email','Email','xss_clean|trim|valid_email');
		$this->form_validation->set_rules('comment','comment','xss_clean|trim');

			if($this->form_validation->run()==false){
				$msg['err_msg'] = "An error occurred. Please try again.";
			}else{
				$hash = md5(uniqid(time(), true));
				$data = array(
					'nama'=>$this->input->post('nama'),
					'email'=>$this->input->post('email'),
					'comment'=>$this->input->post('comment'),
					'hash'=>$hash,
                    'belong_to'=>$this->input->post('id_author'),
					'hash_post'=>$id,
					'hapus'=>0
					);
				$query = $this->comment_model->input_post($data);
				$msg['scss_msg'] = "Success add new comment";

			}
		$this->session->set_flashdata($msg);
		redirect($this->input->server('HTTP_REFERER'));
    }

    public function update_page($id)
    {
    	$this->form_validation->set_rules('title','Title','xss_clean|trim');
		$this->form_validation->set_rules('desc','Description','xss_clean|trim');

        // $id = $this->input->post('id');
        $title = $this->input->post('title');
        $desc = $this->input->post('desc');

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'title' => $title,
                'desc' => $decs
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
        	$data = array(
                'title' => $title,
                'description' => $desc
            );
            $inserted = $this->pages_model->updatePage($id, $data);

            if ($inserted === TRUE) {
                $msg['scss_msg'] = "Success update page Beranda";
            } else {
                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        redirect('page/edit/'.$id);
    }

    public function reply_comment($hash){
    	$this->form_validation->set_rules('reply','Reply','xss_clean|trim');

    	if($this->form_validation->run() == FALSE)
    	{
            $msg['err_msg'] =  "An error occurred. Please try again.";
	    }
	    else
	    {
			$idComment = $hash;
			$data = array('id_comment'=>$idComment,'reply'=>$this->input->post('reply'));
			$inserted = $this->comment_model->ReplyComment($data);

			if ($inserted === TRUE) {$msg['scss_msg'] = "Success Reply Comment";}
			else {$msg['err_msg'] = "An error occurred. Please try again.";}
		}
			$this->session->set_flashdata($msg);
            redirect($this->input->server('HTTP_REFERER'));
    }

    public function doUpdate_Reply($id){
      $this->form_validation->set_rules('reply', 'Content', 'trim|xss_clean');
      if($this->form_validation->run()==false){
        $msg['err_msg'] =  "An error occurred. Please try again.";
      }else{
        $data = array('reply'=>$this->input->post('reply'));
        $inserted = $this->comment_model->UpdateReplyComment($data,$id);
        if ($inserted === TRUE) {
          $msg['scss_msg'] = "Success Update Reply Comment";
        }
        else {
          $msg['err_msg'] = "An error occurred. Please try again.";
        }
      }
      $this->session->set_flashdata($msg);
          if($this->session->userdata('role') == "admin"){
            redirect('AllReply/');
          }else{
            redirect('AllReply_user/');
          }

    }
    public function add_category(){

        $this->form_validation->set_rules('nama', 'Kategori', 'trim|xss_clean');
          if($this->form_validation->run()==false){
            $msg['err_msg'] =  "An error occurred. Please try again.";
          }else{
            $data = array('name'=>$this->input->post('nama'));
            $inserted = $this->category_model->addCategory($data);
            if ($inserted === TRUE) {
              $msg['scss_msg'] = "Success Update Reply Comment";
            }
            else {
              $msg['err_msg'] = "An error occurred. Please try again.";
            }
          }
          $this->session->set_flashdata($msg);redirect('viewCategory');
    }
    public function Update_Kategori($id){

        $this->form_validation->set_rules('nama', 'Kategori', 'trim|xss_clean');
          if($this->form_validation->run()==false){
            $msg['err_msg'] =  "An error occurred. Please try again.";
          }else{
            $data = array('name'=>$this->input->post('nama'));
            $inserted = $this->category_model->updateCategory($id,$data);
            if ($inserted === TRUE) {
              $msg['scss_msg'] = "Success Update Reply Comment";
            }
            else {
              $msg['err_msg'] = "An error occurred. Please try again.";
            }
          }
          $this->session->set_flashdata($msg);redirect('viewCategory');
    }
    public function tambah_PK($id){
        $this->form_validation->set_rules('nomor', 'Kategori', 'trim|xss_clean');
        $this->form_validation->set_rules('jenis_kegiatan', 'Kategori', 'trim|xss_clean');
          if($this->form_validation->run()==false){
            $msg['err_msg'] =  "An error occurred. Please try again.";
          }else{
            $data = array('judul_program'=>$this->input->post('judul'),'jenis_kegiatan'=>$this->input->post('aspirasi'));
            $inserted = $this->proker_model->addProker($data);
            if ($inserted === TRUE) {
              $msg['scss_msg'] = "Success Add Proker";
            }
            else {
              $msg['err_msg'] = "An error occurred. Please try again.";
            }
          }
          $this->session->set_flashdata($msg);
          redirect($this->input->server('HTTP_REFERER'));
    }
    public function update_proker($id)
    {
        $this->form_validation->set_rules('judul_program', 'Judul', 'trim|xss_clean');
        $this->form_validation->set_rules('jenis_kegiatan', 'Jenis Kegiatan', 'trim|xss_clean');
          if($this->form_validation->run()==false){
            $msg['err_msg'] =  "An error occurred. Please try again.";
          }else{
            $data = array('judul_program'=>$this->input->post('judul_program'),'jenis_kegiatan'=>$this->input->post('jenis_kegiatan'));
            $inserted = $this->proker_model->UpdateProker($id,$data);
            if ($inserted === TRUE) {
              $msg['scss_msg'] = "Success Update Proker";
            }
            else {
              $msg['err_msg'] = "An error occurred. Please try again.";
            }
          }
          $this->session->set_flashdata($msg);
          redirect($this->input->server('HTTP_REFERER'));
    }
    public function StatusUpdate($id){
        $this->form_validation->set_rules('status','Status','trim|xss_clean');

        if($this->form_validation->run()==false){
               $msg['err_msg'] = validation_errors();
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
        }else{
            $return = $this->users_model->UpdateStatus($id);
            if($return == true){
                $msg['err_msg'] = "Success Update Status";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }else{
                $msg['err_msg'] = "An error occurred. Please try again.";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }
        }
    }

    public function kelolaPersonalia($aksi,$ka)
    {
    	$this->form_validation->set_rules('nama','Nama','xss_clean|trim');
		$this->form_validation->set_rules('jabatan','Jabatan','xss_clean|trim');
		$this->form_validation->set_rules('unsur','Unsur','xss_clean|trim');
		$this->form_validation->set_rules('email','Email','xss_clean|trim');
        $this->form_validation->set_rules('tahun','Tahun','xss_clean|trim');
        $this->form_validation->set_rules('alamat','Alamat','xss_clean|trim');
        $this->form_validation->set_rules('bio','Bio','xss_clean|trim');
		$this->form_validation->set_rules('telp','No. Telp','xss_clean|trim');
		$this->form_validation->set_rules('fb','Akun Facebook','xss_clean|trim');
		$this->form_validation->set_rules('twit','Akun Twitter','xss_clean|trim');
		$this->form_validation->set_rules('ig','Akun Instagram','xss_clean|trim');

        $id = $this->input->post('id') ;
        $nama = $this->input->post('nama');
        $jabatan = $this->input->post('jabatan');
        $unsur = $this->input->post('unsur');
        $email = $this->input->post('email');
        $telp = $this->input->post('telp');
        $bio = $this->input->post('bio');
        $fb = $this->input->post('fb');
        $tahun = $this->input->post('tahun');
        $alamat = $this->input->post('alamat');
        $twit = $this->input->post('twit');
        $ig = $this->input->post('ig');
        $is_ka = ($ka == 1) ? 'yes' : 'no';

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'nama' => $nama,
                'jabatan' => $jabatan,
                'unsur' => $unsur,
                'email' => $email,
                'telp' => $telp,
                'fb' => $fb,
                'twit' => $twit,
                'ig' => $ig
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
			$filename = url_title(time().'-'.$nama, 'dash', TRUE);
			$foto = '';
			$full_path = '';
			if (!empty($_FILES['fotopersonalia']['name'])) {
				// chmod($path = ,0755);
				$config['upload_path'] 		= './assets/images/personalia';
				$config['allowed_types'] 	= 'jpg|jpeg|png';
				$config['max_size'] 		= 2048;
				$config['overwrite']		= FALSE;
                $config['file_name'] 		= $filename;
                $config['max_filename_increment'] = 50;

				$this->upload->initialize($config);
				if ($this->upload->do_upload('fotopersonalia')) {
					$data = $this->upload->data();
					chmod($data['full_path'], 0755);
					$foto .=  $data['file_name'];
					$full_path .= $data['full_path'];
				} else {
					unlink($full_path);
					$msg['err_msg'] = $this->upload->display_errors();
				}
			}

        	$dataAdd = array(
                'nama' => $nama,
                'jabatan' => $jabatan,
                'unsur' => $unsur,
                'email' => $email,
                'telp' => $telp,
                'facebook' => $fb,
                'twitter' => $twit,
                'tahun'=>$tahun,
                'alamat'=>$alamat,
                'bio'=>$bio,
                'instagram' => $ig,
                'is_ka' => $is_ka,
                'foto' => $foto
            );

            $dataUpdate = array(
                'nama' => $nama,
                'jabatan' => $jabatan,
                'unsur' => $unsur,
                'email' => $email,
                'tahun'=>$tahun,
                'alamat'=>$alamat,
                'telp' => $telp,
                'bio'=>$bio,
                'facebook' => $fb,
                'twitter' => $twit,
                'instagram' => $ig,
                'is_ka' => $is_ka
            );

            $data = (!empty($foto)) ? $dataAdd : $dataUpdate;

            $inserted = ($aksi === 'add') ? $this->personalia_model->addPersonalia($data) : $this->personalia_model->updatePersonalia($id, $data);

            if ($inserted === TRUE) {
            	$p = ($is_ka == 'yes') ? 'Komite Audit' : 'Personalia';
                $msg['scss_msg'] = "Success update page ".$p;
            } else {
                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        redirect($this->input->server('HTTP_REFERER'));
    }

    public function kelolaSKP($aksi, $kategori)
    {
    	$this->form_validation->set_rules('nomor','Nomor','xss_clean|trim');
		$this->form_validation->set_rules('tanggal','Tanggal','xss_clean|trim');
		$this->form_validation->set_rules('tentang','Tentang','xss_clean|trim');

        $id = $this->input->post('id') ;
        $nomor = $this->input->post('nomor');
        $tanggal = $this->input->post('tanggal');
        $tentang = $this->input->post('tentang');

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'nomor' => $nomor,
                'tanggal' => $tanggal,
                'tentang' => $tentang
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
			$filename = url_title($kategori.'-'.$nomor.'-'.$tentang, 'dash', TRUE);
			$file = '';
			$full_path = '';
			if (!empty($_FILES['fileskp']['name'])) {
				// chmod($path = ,0755);
				$config['upload_path'] 		= './assets/uploaded_files/skp';
				$config['allowed_types'] 	= 'pdf';
				$config['max_size'] 		= 5120 * 5;
				$config['overwrite']		= FALSE;
                $config['file_name'] 		= $filename;
                $config['max_filename_increment'] = 50;

				$this->upload->initialize($config);
				if ($this->upload->do_upload('fileskp')) {
					$data = $this->upload->data();
					chmod($data['full_path'], 0755);
					$file .=  $data['file_name'];
					$full_path .= $data['full_path'];
				} else {
					unlink($full_path);
					$msg['err_msg'] = $this->upload->display_errors();
				}
			}

        	$dataAdd = array(
                'nomor' => $nomor,
                'tanggal' => $tanggal,
                'tentang' => $tentang,
                'file' => $file,
                'kategori' => $kategori
            );

            $dataUpdate = array(
                'nomor' => $nomor,
                'tanggal' => $tanggal,
                'tentang' => $tentang,
                'kategori' => $kategori
            );

            $data = (!empty($file)) ? $dataAdd : $dataUpdate;

            $inserted = ($aksi === 'add') ? $this->skp_model->addSKP($data) : $this->skp_model->updateSKP($id, $data);

            if ($inserted === TRUE) {
                $msg['scss_msg'] = "Success update page $kategori";
            } else {
                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        redirect($this->input->server('HTTP_REFERER'));
    }

    public function kelolaProker($aksi)
    {
        $this->form_validation->set_rules('judul','Judul Program','xss_clean|trim');
        $this->form_validation->set_rules('jenis_kegiatan','Jenis Kegiatan','xss_clean|trim');

        $id = $this->input->post('id');
        $judul = $this->input->post('judul');
        $jenis_kegiatan = $this->input->post('jenis_kegiatan');

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'judul' => $judul,
                'jenis_kegiatan' => $jenis_kegiatan
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
            $data = array(
                'judul_program' => $judul,
                'jenis_kegiatan' => $jenis_kegiatan
            );

            $inserted = ($aksi === 'add') ? $this->proker_model->addProker($data) : $this->proker_model->updateProker($id, $data);

            if ($inserted === TRUE) {
                $msg['scss_msg'] = "Success update page";
            } else {
                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        redirect($this->input->server('HTTP_REFERER'));
    }

    public function kelolaFK()
    {
        $this->form_validation->set_rules('fungsi','Fungsi','xss_clean|trim');
        $this->form_validation->set_rules('kewenangan','Kewenangan','xss_clean|trim');

        $id = $this->input->post('id');
        $fungsi = $this->input->post('fungsi');
        $kewenangan = $this->input->post('kewenangan');

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'kewenangan' => $kewenangan,
                'fungsi' => $fungsi
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
            $data = array(
                'fungsi' => $fungsi,
                'kewenangan' => $kewenangan
            );

            $updated = $this->fk_model->update($id, $data);

            if ($updated === TRUE) {
                $msg['scss_msg'] = "Success update page Penjelasan Umum";
            } else {
                $msg['err_msg'] = "An error occurred. Please try again.";
            }
        }

        $this->session->set_flashdata($msg);
        redirect($this->input->server('HTTP_REFERER'));
    }
    public function ValidationUser(){
        $this->form_validation->set_rules('username','Username','xss_clean|trim|is_unique[user.username]');
        $this->form_validation->set_rules('password','Password','xss_clean|trim|min_length[5]|alpha_numeric');
        $this->form_validation->set_rules('password2','Re-Type Password','xss_clean|trim|matches[password]');
        $this->form_validation->set_rules('role','Role','xss_clean|trim');

        if($this->form_validation->run() == false)
        {
            $msg['err_msg'] = validation_errors();
            $this->session->set_flashdata($msg);
            redirect($this->input->server('HTTP_REFERER'));
        }
        else
        {

            $return = $this->users_model->AddUser();
            if($return == true){
                $msg['err_msg'] = "Success Add New User";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }else{
                $msg['err_msg'] = "An error occurred. Please try again.";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }

        }
    }
    public function VUserUpdate($id){
        $this->form_validation->set_rules('username1','Old Username','xss_clean|trim');
        $this->form_validation->set_rules('username2','New Username','xss_clean|trim|is_unique[user.username]');
        $this->form_validation->set_rules('password','Password','xss_clean|trim');

        if($this->form_validation->run() == false)
        {
            $msg['err_msg'] = validation_errors();
            $this->session->set_flashdata($msg);
            redirect($this->input->server('HTTP_REFERER'));
        }
        else
        {
            $return = $this->users_model->UserUpdate($id);
            if($return == true){
                $msg['err_msg'] = "Success Update User";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }else{
                $msg['err_msg'] = "An error occurred. Please try again.";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }

        }
    }
    public function VpassUpdate($id){
        $this->form_validation->set_rules('password1','Old Username','xss_clean|trim');
        $this->form_validation->set_rules('password2','New Username','xss_clean|trim|matches[password1]');

        if($this->form_validation->run()==false){
            $msg['err_msg'] = validation_errors();
            $this->session->set_flashdata($msg);
            redirect($this->input->server('HTTP_REFERER'));
        }else{
            $return = $this->users_model->passUpdate($id);
            if($return == true){
                $msg['err_msg'] = "Success Update Password";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }else{
                $msg['err_msg'] = "An error occurred. Please try again.";
                $this->session->set_flashdata($msg);
                redirect($this->input->server('HTTP_REFERER'));
            }
        }

    }

    public function reply_message()
    {

        $this->form_validation->set_rules('email','Email','xss_clean|trim|valid_email');
        $this->form_validation->set_rules('msgReply','Pesan Balasan','xss_clean|trim|required');

        $id         = $this->input->post('msgId');
        $nama       = $this->input->post('msgTarget');
        $email      = $this->input->post('email');
        $message    = $this->input->post('msgReply');
        $attachment = $this->input->post('replyMsgAttch');

        if($this->form_validation->run() === FALSE)
        {
            $msg['err_msg'] = validation_errors();
            $repopulate = array(
                'email' => $email,
                'msgReply' => $message
            );
            $this->session->set_flashdata($repopulate);
        }
        else
        {
            $hash = preg_replace('/[^0-9]+/', '', md5(uniqid(time(), true)), 10);
            $filename = url_title(date('dmy').'-'.$nama, 'dash', TRUE);
            $file = array();

            if (!empty($_FILES['replyMsgAttch']['name'])) {
                $files = $_FILES['replyMsgAttch'];
                foreach($files['name'] as $k => $v) {
                    $_FILES['replyMsgAttch']['name']     = $files['name'][$k];
                    $_FILES['replyMsgAttch']['type']     = $files['type'][$k];
                    $_FILES['replyMsgAttch']['tmp_name'] = $files['tmp_name'][$k];
                    $_FILES['replyMsgAttch']['error']    = $files['error'][$k];
                    $_FILES['replyMsgAttch']['size']     = $files['size'][$k];

                    $config['upload_path']      = './assets/uploaded_files/attachments';
                    $config['allowed_types']    = 'jpg|jpeg|pdf|png|doc|docx|xls|xlsx|ppt|pptx|txt|rtf|rar|zip';
                    $config['max_size']         = 2048;
                    $config['overwrite']        = FALSE;
                    $config['file_name']        = $filename;
                    $config['max_filename_increment'] = 50;

                    $file_to_attach = $_FILES['replyMsgAttch']['tmp_name'];
                    $filename = $_FILES['replyMsgAttch']['name'];
                    //die(var_dump($filename));

                    $this->upload->initialize($config);
                    if ($this->upload->do_upload('replyMsgAttch')) {
                        $data = $this->upload->data();
                        chmod($data['full_path'], 0755);
                        $file[$k] =  $data['file_name'];

                    } else {
                        $msg['err_msg'] = $this->upload->display_errors();
                    }
                }
            }

            $data = array(
                'name' => $nama,
                'email' => $email,
                'subject' => 'Reply Message id'.$id,
                'message' => $message,
                'attachments' => implode(",", $file),
                'hash' => $hash,
                'status' => 'not read yet',
                'tipe' => 'reply'
            );

            $inserted = $this->messages_model->makeMessage($data);

            if ($inserted === TRUE) {

            include "classes/class.phpmailer.php";
            $mail = new PHPMailer;
            $mail->SMTPSecure = 'ssl';
            $mail->Host = "smtp.gmail.com"; //host masing2 provider email
            $mail->SMTPDebug = 2;
            $mail->Port = 465;
            $mail->SMTPAuth = true;
            $mail->Username = "theoafnt@gmail.com"; //user email
            $mail->Password = "passwordbuatminiatur"; //password email
            $mail->SetFrom("admin@mwa.undip.ac.id","Balasan Email Aspirasi Dari MWA"); //set email pengirim
            $mail->Subject = "Balasan Email Aspirasi"; //subyek email
            $mail->AddAddress($email);  //tujuan email
            $mail->MsgHTML($message,'non Reply');

            //     $file_to_attach = $_FILES['replyMsgAttch']['tmp_name'] ;
            //     $filename=$_FILES['replyMsgAttch']['name'];
            //      $mail->AddAttachment( $file_to_attach , $filename );

                if ($mail->Send()) {
                    $msg['scss_msg'] = "Pesan balasan terkirim ke $email";
                } else {
                    // $msg['err_msg'] = "Gagal mengirim pesan balasan. Pesan disimpan ke dalam database.";
                    $msg['err_msg'] = $this->email->print_debugger();
                }
            } else {
                foreach ($file as $f) {
                    $myfile = $f;
                    unlink('./assets/uploaded_files/attachments/'.$myfile);
                }

                $msg['err_msg'] = "An error occurred. Please try again. If error still occurs, please contact us";
            }
        }

        $this->session->set_flashdata($msg);
        redirect($this->input->server('HTTP_REFERER'));

    }

}


text:
<?php

namespace App\Common\Models\Company\Mysql;

use App\Common\Models\Base\Mysql\Base;

class Team extends Base
{

    /**
     * 公司-团队管理
     * This model is mapped to the table icompany_team
     */
    public function getSource()
    {
        return 'icompany_team';
    }
}


text:
package com.intellij.ide.highlighter.custom.tokens;

import com.intellij.psi.CustomHighlighterTokenType;
import com.intellij.psi.tree.IElementType;

/**
 * @author dsl
 */
public class IdentifierParser extends TokenParser {
  public IdentifierParser() {
  }

  @Override
  public boolean hasToken(int position) {
    if (!Character.isJavaIdentifierStart(myBuffer.charAt(position))) return false;
    final int start = position;
    for (position++; position < myEndOffset; position++) {
      final char c = myBuffer.charAt(position);
      if (!isIdentifierPart(c)) break;
    }
    IElementType tokenType = CustomHighlighterTokenType.IDENTIFIER;
    myTokenInfo.updateData(start, position, tokenType);
    return true;
  }

  protected boolean isIdentifierPart(final char c) {
    return Character.isJavaIdentifierPart(c) || c == '-';
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>

    <title>Midokura Docs: Getting Started</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

<link href="_static/css/bootstrap.min.css" rel="stylesheet">

<link href="_static/css/native.css" rel="stylesheet">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,700' rel='stylesheet' type='text/css'>

<link href="_static/css/combined.css" rel="stylesheet">
<link href="_static/css/styles.css" rel="stylesheet">

      <button class="navbar-toggle" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" type="button">
        Toggle navigation

      </button>

          OSS Docs

          MEM Docs

Getting Started

updated: 2016-08-15 19:38

Contents

Getting Started

Neutron topology

Getting Started¶

Neutron topology¶

This section discusses the Neutron entities that Raven creates when it spawns
(in case they don’t exist).

When you configured Kuryr-Kubernetes, you did see the following section:

[k8s]

#
# From kuryr
#

# (string value)
#api_root = http://localhost:8080

# Subnet pool used to grab ranges of IPs for each new K8s namespace. Pod IPs
# will be inside those ranges (string value)
cluster_subnet_pool = 192.168.0.0/16

# Network range of the Floating IPs used when creating services with externalIP
# access. (string value)
cluster_external_subnet = 172.16.0.0/16

# Range of IPs used as K8s ClusterIPs. It must match with Kubernetes
# SERVICE_CLUSTER_IP_RANGE (string value)
cluster_service_subnet = 10.0.0.0/24

These values define basically the range of IPs of the Pods, the externalIPs and the
VIPs of the Kubernetes entities.

cluster_subnet_pool: You’ll see in more detail in the
namespaces section, but basically it defines the Neutron subnetpool from
where we will pick the namespaces’ networks. The network names will be based
on namespaces names.

cluster_external_subnet: public services can define
externalIPs addresses to let external access to Kubernetes services. This
option define what’s the range of these externalIPs. The network name will be
(not configurable yet) raven-default-external-net

cluster_service_subnet: This is the range of VIPs that K8s gives
to services. This value MUST MATCH with Kubernetes configuration option
SERVICE_CLUSTER_IP_RANGE when is deployed. The network name will be (not
configurable yet) raven-default-service

As network topology, this is traduced to:

`</span>raven-default-external-net<span class="sb">`
------------+---------------
            |
            |
+-----------+-------------+
|   raven-default-router  |
+--+----------+--------+--+
   |          |        |           net-1 (range taken from `</span>cluster_subnet_pool<span class="sb">`)
   |          |   +----+----------------------------------------------------------+
   |          |
   |          |       net-2 (range taken from `</span>cluster_subnet_pool<span class="sb">`)
   |     +----+-----------------------------------------------------------------+
   |
   |      `</span>raven-default-service<span class="sb">`
---+------------------------------------------------------------------+

Or, if you prefer to see it on Neutron commands:

happyuser@kuryr:~ > neutron net-list -c name -c subnets
+----------------------------+-----------------------------------------------------+
| name                       | subnets                                             |
+----------------------------+-----------------------------------------------------+
| default                    | 29f5df27-427e-4282-8fb1-b8b64a152575 192.168.0.0/24 |
| raven-default-service      | 1610fb22-d8e1-4de9-8896-adc542699157 10.0.0.0/24    |
| raven-default-external-net | 1f2a9589-2b7b-444e-a6cc-a9fb88f4f75c 172.16.0.0/16  |
+----------------------------+-----------------------------------------------------+
happyuser@kuryr:~ > neutron router-list -c name
+----------------------+
| name                 |
+----------------------+
| raven-default-router |
+----------------------+
happyuser@kuryr:~ > neutron router-port-list raven-default-router -c fixed_ips
+------------------------------------------------------------------------------------+
| fixed_ips                                                                          |
+------------------------------------------------------------------------------------+
| {"subnet_id": "29f5df27-427e-4282-8fb1-b8b64a152575", "ip_address": "192.168.0.1"} |
| {"subnet_id": "1f2a9589-2b7b-444e-a6cc-a9fb88f4f75c", "ip_address": "172.16.0.2"}  |
| {"subnet_id": "1610fb22-d8e1-4de9-8896-adc542699157", "ip_address": "10.0.0.1"}    |
+------------------------------------------------------------------------------------+
happyuser@kuryr:~ > neutron subnet-list -c name -c cidr
+-------------------------------+----------------+
| name                          | cidr           |
+-------------------------------+----------------+
| default-subnet                | 192.168.0.0/24 |
| raven-default-10.0.0.0/24     | 10.0.0.0/24    |
| raven-default-external-subnet | 172.16.0.0/16  |
+-------------------------------+----------------+

All this topology will not be created if it is created already with the same
names. As pointed out on limitations section, there is no way to reuse any
current network or subnet right now.

You could, though, give access to already created networks (that probably will have Virtual
Machines running on it) by adding a router interface attaching that network to the
raven-default-router manually.

updated: 2016-08-15 19:38

 Except where otherwise noted, this document is licensed under
 Creative Commons
 Attribution 3.0 License. See all
 OpenStack Legal Documents.

     Search

    <button onclick="location.href='/'" class="btn docs-sidebar-home" data-toggle="tooltip" data-placement="top" title="Docs Home"></button>
    <button href="#" type="button" data-toggle="dropdown" class="btn docs-sidebar-release-select">Midonet Documentation</button>

Guides

Midonet RDO Mitaka

Midonet Ubuntu Mitaka

Midonet RDO Liberty

Midonet Ubuntu Liberty

Midonet Reference Architecture

Midonet Operations Guide

Contents

Current Limitations

Getting Started

Neutron topology

Pods

Namespaces

Services

Map to Neutron Security Groups

OpenStack

Projects

OpenStack Security

Common Questions

Blog

News

Community

User Groups

Events

Jobs

Companies

Contribute

Documentation

OpenStack Manuals

Getting Started

API Documentation

Wiki

Branding & Legal

Logos & Guidelines

Trademark Policy

Privacy Policy

OpenStack CLA

Stay In Touch

          The OpenStack project is provided under the
          Apache 2.0 license. Openstack.org is powered by
          Rackspace Cloud Computing.


text:
package org.datadog.jenkins.plugins.datadog.publishers;

import hudson.Extension;
import hudson.model.Computer;
import hudson.model.PeriodicWork;
import jenkins.model.Jenkins;
import org.datadog.jenkins.plugins.datadog.DatadogClient;
import org.datadog.jenkins.plugins.datadog.DatadogUtilities;
import org.datadog.jenkins.plugins.datadog.clients.ClientFactory;
import org.datadog.jenkins.plugins.datadog.util.TagsUtil;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * This class registers a {@link PeriodicWork} with Jenkins to run periodically in order to enable
 * us to compute metrics related to nodes and executors.
 */
@Extension
public class DatadogComputerPublisher extends PeriodicWork {

    private static final Logger logger = Logger.getLogger(DatadogComputerPublisher.class.getName());

    private static final long RECURRENCE_PERIOD = TimeUnit.MINUTES.toMillis(1);

    @Override
    public long getRecurrencePeriod() {
        return RECURRENCE_PERIOD;
    }

    @Override
    protected void doRun() throws Exception {
        try {
            logger.fine("doRun called: Computing Node metrics");

            // Get Datadog Client Instance
            DatadogClient client = ClientFactory.getClient();
            String hostname = DatadogUtilities.getHostname("null");

            long nodeCount = 0;
            long nodeOffline = 0;
            long nodeOnline = 0;
            Computer[] computers = Jenkins.getInstance().getComputers();
            final Map<String, Set<String>> globalTags = DatadogUtilities.getTagsFromGlobalTags();
            for (Computer computer : computers) {
                nodeCount++;
                if (computer.isOffline()) {
                    nodeOffline++;
                }
                if (computer.isOnline()) {
                    nodeOnline++;
                }

                int executorCount = computer.countExecutors();
                int inUse = computer.countBusy();
                int free = computer.countIdle();

                Map<String, Set<String>> tags = TagsUtil.merge(
                        DatadogUtilities.getComputerTags(computer), globalTags);
                client.gauge("jenkins.executor.count", executorCount, hostname, tags);
                client.gauge("jenkins.executor.in_use", inUse, hostname, tags);
                client.gauge("jenkins.executor.free", free, hostname, tags);
            }
            client.gauge("jenkins.node.count", nodeCount, hostname, globalTags);
            client.gauge("jenkins.node.offline", nodeOffline, hostname, globalTags);
            client.gauge("jenkins.node.online", nodeOnline, hostname, globalTags);

        } catch (Exception e) {
            logger.warning("Unexpected exception occurred - " + e.getMessage());
        }

    }

}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.autofill_assistant.user_data;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.Callback;
import org.chromium.components.autofill_assistant.AssistantTextUtils;
import org.chromium.components.autofill_assistant.R;

/**
 * A section to display a text string.
 *
 * This section properly handles embedded links of the form <link0>some text</link0>.
 */
public class AssistantInfoSection {
    private final Context mContext;
    private final TextView mView;
    @Nullable
    private Callback<Integer> mListener;

    AssistantInfoSection(Context context, ViewGroup parent) {
        mContext = context;
        mView = new TextView(context);
        ApiCompatibilityUtils.setTextAppearance(mView, R.style.TextAppearance_TextSmall_Secondary);

        int horizontalMargin = context.getResources().getDimensionPixelSize(
                R.dimen.autofill_assistant_bottombar_horizontal_spacing);
        parent.addView(mView,
                new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        setHorizontalMargins(mView, horizontalMargin, horizontalMargin);
    }

    void setListener(Callback<Integer> listener) {
        mListener = listener;
    }

    View getView() {
        return mView;
    }

    void setText(String text) {
        if (TextUtils.isEmpty(text)) {
            mView.setVisibility(View.GONE);
        } else {
            AssistantTextUtils.applyVisualAppearanceTags(mView, text, this::onLinkClicked);
            mView.setVisibility(View.VISIBLE);
        }
    }

    private void setHorizontalMargins(View view, int marginStart, int marginEnd) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        lp.setMarginStart(marginStart);
        lp.setMarginEnd(marginEnd);
        view.setLayoutParams(lp);
    }

    public void setPaddings(int topPadding, int bottomPadding) {
        mView.setPadding(
                mView.getPaddingLeft(), topPadding, mView.getPaddingRight(), bottomPadding);
    }

    public void setCenter(boolean center) {
        mView.setGravity(center ? Gravity.CENTER_HORIZONTAL : (Gravity.TOP | Gravity.START));
    }

    private void onLinkClicked(int link) {
        if (mListener != null) {
            mListener.onResult(link);
        }
    }
}


text:
class 'GameGrid' (GameComponent)
local tuple = require 'tuple'

function GameGrid:__init()
    GameComponent.__init(self)
    LuaDebug.Log('GameGrid:__init() called!')

    -- Serialisation properties
    self:serialiseField('defaultTileset', 'TileDef')
    self:serialiseField('targetTileset', 'TileDef')
    self:serialiseField('shader', 'ShaderDef')
    self:serialiseField('size', 'Vec2i')
    self:serialiseField('depth', 'number')
    self:serialiseField('workBotAnimationSet', 'AnimationSetDef')
    self:serialiseField('workBotMiningAnimSet', 'AnimationSetDef')

    self.selectedTiles = {}

    self._botManager = GetBotManager();
end

function GameGrid:setup()
    LuaDebug.Log('GameGrid:setup()')
    local renderer = self.gameObject.renderer;
    renderer.transform.localPosition.z = self.depth;
    -- Create the batched mesh
    -- The materials are handled by the batched mesh so
    -- we don't have to set self.gameObject.renderer.material
    local batchedMesh = BatchedMesh()
    renderer.mesh = batchedMesh

    local frameWidth = self.defaultTileset:getFrameWidth()
    local frameHeight = self.defaultTileset:getFrameHeight()

    self.tiles = {}

    for x = 0 , self.size.x do
        for y = 0, self.size.y do
            local tile = GameObject()

            tile.renderer.transform.localPosition = Vec3f(
                x * frameWidth,
                y * frameHeight,
                self.depth
            )

            local passibility = self:GetPassibility(x, y, self.size.x, self.size.y)
            self:SetupTile(tile, passibility, self.defaultTileset)
            tile.renderer:batch(batchedMesh)
            self.tiles[x..y] = tile

            AddGameObject(tile)
        end
    end

end

function GameGrid:update(deltaTime)

end

function GameGrid:keyUp(keyEvent)
    -- Filter out every key but m
    -- TODO: Make this key configurable (under confirm action?)
    local doMine =          keyEvent:getCode() == config['KEY_MineTile'] or
                            keyEvent:getCode() == config['KEY_InstantMineTile']
    local doInstantMine =   keyEvent:getCode() == config['KEY_InstantMineTile']
    local doWorkBotSpawn =  keyEvent:getCode() == config['KEY_SpawnWorkBot']

    local frameWidth = self.defaultTileset:getFrameWidth()
    local frameHeight = self.defaultTileset:getFrameHeight()

    if (doMine) then
        for id, tile in pairs(self.selectedTiles) do
            local tilePos = tile.renderer.transform.localPosition
            local coord = Vec2i(tilePos.x / frameWidth, tilePos.y / frameHeight)
            if doInstantMine then
                 -- Instant mine so you can create test maps without bots
                local sprite = GetComponentFromType(self.tiles[coord.x..coord.y], 'Sprite')
                sprite:setSpriteTexture(self.targetTileset)
                self:FixTileFrames(coord)
                self._botManager:addCoord(coord)
            else
                -- Create mining job (requires bots)
                local job = MiningJob(self, coord, self.defaultTileset, self.targetTileset)
                RegisterJob(job)
            end
            RemoveGameObject(tile) -- Remove selection gameobject
        end
    end

    if (doWorkBotSpawn) then
        for id, tile in pairs(self.selectedTiles) do
            local tilePos = tile.renderer.transform.localPosition
            local coord = Vec2i(tilePos.x / frameWidth, tilePos.y / frameHeight)
            -- TODO: Don't spawn bot onto unpassable tiles (rock)
            -- TODO: Wrap up this logic in some sort of factory method/etc

            local workBotGo = GameObject()
            local workBotComp = WorkBot(self, coord, self.workBotMiningAnimSet)
            local workBotAnim = AnimatedSprite()
            LuaDebug.Log('self.workBotAnimationSet == nil: ' .. tostring(self.workBotAnimationSet == nil))
            LuaDebug.Log('typename: ' .. class_info(self.workBotAnimationSet).name)
            workBotAnim:setAnimationSet(self.workBotAnimationSet)
            workBotAnim:setAnimationName('idle')

            workBotGo:addComponent(workBotAnim)
            workBotGo:addComponent(workBotComp)
            AddGameObject(workBotGo)

            self._botManager:addBot(workBotComp)
            RemoveGameObject(tile)
        end

    end

    self.selectedTiles = {} -- Deselect all
end

function GameGrid:SetupTile(tile, passibility, texture)

    local texFrame = texture:getFrameFromPassibility(passibility)
    local sprite = Sprite(texture, texFrame)
    tile:addComponent(sprite)

end

function GameGrid:GetPassibility(x, y, maxX, maxY)
    local passibility = Passibility()

    if x == 0 then
      passibility:setFlag(Passibility.West)
    end
    if y == 0 then
      passibility:setFlag(Passibility.North)
    end
    if x == maxX then
      passibility:setFlag(Passibility.East)
    end
    if y == maxY then
      passibility:setFlag(Passibility.South)
    end
    -- All others are set to none
    if passibility:getInternalValue() == 0  then
      passibility:setFlag(Passibility.None)
    end

    return passibility;

end

function GameGrid:FixTileFrames(point)
    self:FixTileFrame(point);
    self:FixTileFrame(Vec2i(point.x - 1, point.y))
    self:FixTileFrame(Vec2i(point.x, point.y - 1))
    self:FixTileFrame(Vec2i(point.x + 1, point.y))
    self:FixTileFrame(Vec2i(point.x, point.y + 1))

end

function GameGrid:FixTileFrame(point)

    if not self:PointInRange(point) or not self:TileIsPassable(point) then
        return
    end

    --LuaDebug.Log('GameGrid:FixTileFrame: point: ' .. point.x .. ',' .. point.y)

    local p = Passibility()
    local checks = {
        tuple(-1, 0, Passibility.West),
        tuple(0, -1, Passibility.North),
        tuple(1, 0, Passibility.East),
        tuple(0, 1, Passibility.South)
    }

    for i, check in ipairs(checks) do
        local checkPoint = Vec2i(point.x + check[1], point.y + check[2])
        if self:PointInRange(checkPoint) and self:TileIsPassable(checkPoint) then
            p:setFlag(check[3])
        end
    end

    local tile = self.tiles[point.x..point.y]
    local sprite = GetComponentFromType(tile, 'Sprite')
    local texture = sprite:getSpriteTexture()
    local texFrame = texture:getFrameFromPassibility(p)
    sprite:setSpriteFrame(texFrame)

    --self:SetupTile(tile, p)
    --tile.renderer:invalidateBatch()
end

function GameGrid:TileIsPassable(point)
    local tile = self.tiles[point.x..point.y]
    local sprite = GetComponentFromType(tile, 'Sprite')
    local texture = sprite:getSpriteTexture()
    return tile and texture:getCanWalk()
end

function GameGrid:PointInRange(point)
    return point.x >= 0 and point.x <= self.size.x and point.y > 0 and point.y < self.size.y;
end


text:
/*
 *
 * CoachDashboard
 *
 */

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {Tabs, Tab} from 'material-ui/Tabs';
import CoachTeamPage from '../../containers/CoachTeamPage';
import CoachInvitePage from '../../containers/CoachInvitePage';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';

export class CoachTeam extends React.Component { // eslint-disable-line react/prefer-stateless-function
  render() {
    return (
      <div>
        {this.props.TeamsList && <CoachTeamPage TeamsList={this.props.TeamsList} />}
      </div>
    );
  }
}

const coachTeamQuery = gql`query coachTeamQuery ($userId: ID){
   allTeams(filter: {
      coach: {
        user:{
          id: $userId
        }
    }
  }
   ) {
    id
    name
    atheletTeams{
      athlete{ id user{ id email firstName lastName } }
      status
      athleteMessage
    }
    season
    ageGroup
    totalNumberOfAthelets
    createdAt
    sport { id name }
    coach { id user { id email firstName lastName }}
    manager { id user { id email firstName lastName }}
  }
}`

const coachQueryData = compose(
  graphql(coachTeamQuery , {name: 'TeamsList'}, {
  options: (props) => ({ variables: { userId: props.userId } })
}))(CoachTeam);

export default coachQueryData;


text:
require 'spec_helper'

describe StageConfigLoader do

  before(:all) do
    @klass = Class.new(AdminController) do
      cattr_accessor :filter_names
      attr_accessor :pipeline, :stage, :params

      self.filter_names = []

      def self.before_filter filter_name, *args
        filter_names << filter_name
      end

      include StageConfigLoader

      load_stage_except_for
    end
  end

  before(:each) do
    @controller = @klass.new
    @controller.pipeline = PipelineConfigMother.createPipelineConfig("foo-pipeline", "bar-stage", ["baz-job", "quux-job"].to_java(java.lang.String))
  end

  it "should load stage if exists" do
    @controller.params = {:pipeline_name => "foo-pipeline", :stage_name => "bar-stage"}
    @controller.stage.should be_nil
    @controller.send(@klass.filter_names.last).should == true
    @controller.stage.name().should == CaseInsensitiveString.new("bar-stage")
  end

  it "should render error when no stage exists" do
    @controller.params = {:pipeline_name => "foo-pipeline", :stage_name => "quux-stage"}
    @controller.stage.should be_nil

    @controller.should_receive_render_with({:template => "shared/config_error.html", :layout => "application", :status => 404})

    @controller.send(@klass.filter_names.last).should == false

    @controller.instance_variable_get('@message').should == "No stage named 'quux-stage' exists for pipeline 'foo-pipeline'."
    @controller.stage.should be_nil
  end

  it "should hookup load_pipeline before load_stage" do
    @klass.filter_names.should == [:load_pipeline, :load_pause_info, :load_stage]
  end
end


text:
'use strict';

var stringify = function (V) {
    var circ = [];

    var core = function (V) {
        if ((typeof V === 'number') || (typeof V === 'boolean')) {
            return V;
        }

        if (V === null) {
            return 'null';
        }

        if (V === undefined) {
            return 'undefined';
        }

        if (V instanceof Date) {
            return 'new Date(' + V.toISOString() + ')';
        }

        if (Array.isArray(V)) {
            return '[' + V.map(function (v) {
                return core(v);
            }).join(',') + ']';
        }

        if (V === Object(V)) {
            if (circ.indexOf(V) > -1) {
                return '"[CIRCULAR!]"';
            }

            circ.push(V);

            return '{' + Object.keys(V).map(function (k) {
                return core(k) + ':' + core(V[k]);
            }).join(',') + '}';
        }

        return JSON.stringify(V);
    };

    return core(V);
};

/**
 * FluxexObject is an object can be serialized and be constructed with the serialized status.
 * @class
 * @param {Object=} state - Serialized state
 */
var FluxexObject = function FluxexObject(state) {
    var copy = {};

    if ((state !== null) && ('object' === typeof state)) {
        this._context = state;
    } else {
        this._context = {};
    }

    if ('function' === typeof this.initialize) {
        Object.assign(copy, state);
        this.initialize();
        Object.assign(this._context, copy);
    }

};

Object.assign(FluxexObject.prototype,
/** @lends FluxexObject# */
{
    /**
     * Get a value or an object by name
     * @param {String} name - a simple key name
     * @return {Object|Number|String|Null} the value
     */
    _get: function (name) {
        return this._context[name];
    },

    /**
     * Restore the FluxexObject status by provided status object
     * @param {Object} state - the status to restore
     */
    _restore: function (state) {
        this._context = state;
    },

    /**
     * Set value by name
     * @param {String} name - a simple key name or json path
     * @return {FluxexObject} Self
     */
    _set: function (name, value) {
        this._context[name] = value;
        return this;
    },

    /**
     * Get serialized state
     * @return {String} A JSON string of current status
     */
    toString: function () {
        return stringify(this._context);
    }
});

module.exports = FluxexObject;


text:
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=140)

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=140)

    body = models.TextField()
    excerpt = models.CharField(max_length=200, blank=True)

    time_modified = models.DateTimeField()
    time_created = models.DateTimeField()

    is_published = models.BooleanField(default=False)
    hash = models.CharField(max_length=32)

    category = models.ForeignKey(Category)

    author = models.ForeignKey(User)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('detail', args=[self.hash])

    def get_edit_url(self):
        return reverse('update', args=[self.hash])

    def get_delete_url(self):
        return reverse('delete', args=[self.hash])


text:
package templates;

import org.junit.*;
import org.junit.runners.MethodSorters;

import static org.junit.Assert.assertEquals;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestKlasesSagatave {

//	private static Variable variable = null;

    @BeforeClass
    //Before even start testing do some preparations!
    public static void initTestPreConditions() {

    }

    @AfterClass
    //After all tests perform actions that cleans everything up!
    public static void finalizeTestConditions() {

    }

    @Before
    //Before every test do initial setup!
    public void setUpForEachTest() {

    }

    @After
    //After every test tear down this mess!
    public void tearDownForEachTest() {

    }

    @Test
    public void test01NameOfTest() {
        assertEquals(val, variable);
    }
}


text:
function LoadTweenMax() {
    if (typeof jQuery === 'undefined') {
        setTimeout(LoadTweenMax, 250);
    } else {
        $(function () {
            if (typeof window.tweenmax_loaded === 'undefined') {
                $('body').append("<script src='//cdnjs.cloudflare.com/ajax/libs/gsap/1.9.2/TweenMax.min.js'></script>");
                $('body').append("<script src='https://jsonce.azurewebsites.net/TweenMax-SVGAnimation.js'></script>");
                window.tweenmax_loaded = true;
            }
        })
    }
}

LoadTweenMax();


text:
<?php

namespace lo\modules\noty\assets;

use yii\web\AssetBundle;

/**
 * Class BootstrapNotifyAsset
 * @package lo\modules\noty\layers
 */
class BootstrapNotifyAsset extends AssetBundle
{
    /** @var string  */
    public $sourcePath = '@bower/remarkable-bootstrap-notify';

    /** @var array $js */
    public $js = [
        'bootstrap-notify.min.js'
    ];

    /** @var array $depends */
    public $depends = [
        'yii\bootstrap\BootstrapPluginAsset',
    ];
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bulletin of the Faculty of Agriculture, Yamaguchi University 26: 91 (1975)

#### Original name
Microthyriella disseminata I. Hino & Katum.

### Remarks
null


text:
package org.apache.ignite.ml.pipeline;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.ml.IgniteModel;
import org.apache.ignite.ml.dataset.DatasetBuilder;
import org.apache.ignite.ml.dataset.impl.cache.CacheBasedDatasetBuilder;
import org.apache.ignite.ml.dataset.impl.local.LocalDatasetBuilder;
import org.apache.ignite.ml.environment.LearningEnvironmentBuilder;
import org.apache.ignite.ml.math.functions.IgniteBiFunction;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.preprocessing.PreprocessingTrainer;
import org.apache.ignite.ml.trainers.DatasetTrainer;

/**
 * A simple pipeline, which acts as a global trainer which produce a Pipeline Model.
 * A Pipeline consists of a sequence of stages, each of which is either a Preprocessing Stage or a Trainer.
 * When {@code fit()} method is called, the stages are executed in order.
 *
 * @param <K> Type of a key in {@code upstream} data.
 * @param <V> Type of a value in {@code upstream} data.
 * @param <R> Type of a result in {@code upstream} feature extractor.
 */
public class Pipeline<K, V, R> {
    /** Feature extractor. */
    private IgniteBiFunction<K, V, R> finalFeatureExtractor;

    /** Label extractor. */
    private IgniteBiFunction<K, V, Double> lbExtractor;

    /** Preprocessor stages. */
    private List<PreprocessingTrainer> preprocessors = new ArrayList<>();

    /** Final trainer stage. */
    private DatasetTrainer finalStage;

    /** Learning environment builder. */
    private LearningEnvironmentBuilder envBuilder = LearningEnvironmentBuilder.defaultBuilder();

    /**
     * Adds feature extractor as a zero stage.
     *
     * @param featureExtractor The parameter value.
     * @return The updated Pipeline.
     */
    public Pipeline<K, V, R> addFeatureExtractor(IgniteBiFunction<K, V, R> featureExtractor) {
        this.finalFeatureExtractor = featureExtractor;
        return this;
    }

    /**
     * Adds a label extractor for the produced model.
     *
     * @param lbExtractor The parameter value.
     * @return The updated Pipeline.
     */
    public Pipeline<K, V, R> addLabelExtractor(IgniteBiFunction<K, V, Double> lbExtractor) {
        this.lbExtractor = lbExtractor;
        return this;
    }

    /**
     * Adds a preprocessor.
     *
     * @param preprocessor The parameter value.
     * @return The updated Pipeline.
     */
    public Pipeline<K, V, R> addPreprocessor(PreprocessingTrainer preprocessor) {
        preprocessors.add(preprocessor);
        return this;
    }

    /**
     * Adds a trainer.
     *
     * @param trainer The parameter value.
     * @return The updated Pipeline.
     */
    public Pipeline<K, V, R> addTrainer(DatasetTrainer trainer) {
        this.finalStage = trainer;
        return this;
    }

    /**
     * Fits the pipeline to the input cache.
     *
     * @param ignite Ignite instance.
     * @param cache Ignite cache with {@code upstream} data.
     * @return The fitted model based on chain of preprocessors and final trainer.
     */
    public PipelineMdl<K, V> fit(Ignite ignite, IgniteCache<K, V> cache) {
        DatasetBuilder datasetBuilder = new CacheBasedDatasetBuilder<>(ignite, cache);
        return fit(datasetBuilder);
    }

    /**
     * Set learning environment builder.
     *
     * @param envBuilder Learning environment builder.
     */
    public void setEnvironmentBuilder(LearningEnvironmentBuilder envBuilder) {
        this.envBuilder = envBuilder;
    }

    /**
     * Fits the pipeline to the input mock data.
     *
     * @param data Data.
     * @param parts Number of partitions.
     * @return The fitted model based on chain of preprocessors and final trainer.
     */
    public PipelineMdl<K, V> fit(Map<K, V> data, int parts) {
        DatasetBuilder datasetBuilder = new LocalDatasetBuilder<>(data, parts);
        return fit(datasetBuilder);
    }

    /** Fits the pipeline to the input dataset builder. */
    private PipelineMdl<K, V> fit(DatasetBuilder datasetBuilder) {
        assert lbExtractor != null;
        assert finalFeatureExtractor != null;

        if (finalStage == null)
            throw new IllegalStateException("The Pipeline should be finished with the Training Stage.");

        preprocessors.forEach(e -> {

            finalFeatureExtractor = e.fit(
                envBuilder,
                datasetBuilder,
                finalFeatureExtractor
            );
        });

        IgniteModel<Vector, Double> internalMdl = finalStage
            .fit(
                datasetBuilder,
                finalFeatureExtractor,
                lbExtractor
            );

        return new PipelineMdl<K, V>()
            .withFeatureExtractor(finalFeatureExtractor)
            .withLabelExtractor(lbExtractor)
            .withInternalMdl(internalMdl);
    }
}


text:
/**
 * @file ARUPDATER_Manager.h
 * @brief libARUpdater Manager header file.
 * @date 07/01/2014
 * @author david.flattin.ext@parrot.com
 **/

#ifndef _ARUPDATER_MANAGER_H_
#define _ARUPDATER_MANAGER_H_

#include <libARUpdater/ARUPDATER_Error.h>
#include <libARDataTransfer/ARDataTransfer.h>
#include <libARDataTransfer/ARDATATRANSFER_Uploader.h>
#include <libARDiscovery/ARDISCOVERY_Discovery.h>

#define ARUPDATER_MANAGER_DEVICE_STRING_MAX_SIZE        10
#define ARUPDATER_MANAGER_FOLDER_SEPARATOR              "/"
#define ARUPDATER_MANAGER_PLF_FOLDER                    "plfFolder/"
#define ARUPDATER_MANAGER_PLF_EXTENSION                 ".plf"
#define ARUPDATER_MANAGER_TAR_EXTENSION                 ".tar"
#define ARUPDATER_MANAGER_GZ_EXTENSION                  ".gz"

/**
 * @brief Manager structure
 * @see ARUPDATER_Manager_New ()
 */
typedef struct ARUPDATER_Manager_t ARUPDATER_Manager_t;

/**
 * @brief Create a new ARUpdater Manager
 * @warning This function allocates memory
 * @param[out] error A pointer on the error output. Can be null
 * @return Pointer on the new ARUpdater Manager
 * @see ARUPDATER_Manager_Delete ()
 */
ARUPDATER_Manager_t* ARUPDATER_Manager_New(eARUPDATER_ERROR *error);

/**
 * @brief Delete an ARUpdater Manager
 * @warning This function frees memory
 * @param manager The address of the pointer on the ARUpdater Manager
 * @see ARUPDATER_Manager_New ()
 */
void ARUPDATER_Manager_Delete (ARUPDATER_Manager_t **managerPtrAddr);

/**
 * @brief get the version of a given plf file
 * @param manager : pointer on the manager
 * @param[in] product : product type to be tested
 * @param[in] remoteVersion : the remote version to be compared with local one
 * @param[in] rootFolder : root folder of the local plf.
 * @param[out] localVersionBuffer : out buffer that will contain the version of the local plf
 * @param[in] bufferSize : The size of the localVersionBuffer
 * @param[out] error : ARUPDATER_OK if operation went well, the description of the error otherwise. Can be null
 * @return 1 if the product plf is at the same version (or more recent) as the local plf
 */
int ARUPDATER_Manager_PlfVersionIsUpToDate(ARUPDATER_Manager_t *manager, eARDISCOVERY_PRODUCT product, const char *remoteVersion, const char *rootFolder, char *localVersionBuffer, size_t bufferSize, eARUPDATER_ERROR *error);

#endif /* _ARUPDATER_MANAGER_H_ */


text:
'use strict';

var VersionChecker = require('ember-cli-version-checker');
var hasBeenWarned = false;

module.exports = {
  name: require('./package').name,
  included() {
    this._super.included.apply(this, arguments);

    this._ensureThisImport();

    var checker = new VersionChecker(this);
    var emberVersion = checker.forEmber();

    if (emberVersion.lt('2.3.0')) {
      this.import('vendor/install-getowner-polyfill.js');
    } else if (this.parent === this.project && !hasBeenWarned){
      console.warn('ember-getowner-polyfill is not required for Ember 2.3.0 and later, please remove from your `package.json`.');
      hasBeenWarned = true;
    }
  },

  _ensureThisImport() {
    if (!this.import) {
      this._findHost = function findHostShim() {
        var current = this;
        var app;
        do {
          app = current.app || app;
        } while (current.parent.parent && (current = current.parent));
        return app;
      };
      this.import = function importShim(asset, options) {
        var app = this._findHost();
        app.import(asset, options);
      };
    }
  },

  treeForVendor(rawVendorTree) {
    let babelAddon = this.addons.find(
      addon => addon.name === 'ember-cli-babel'
    );

    let transpiledVendorTree = babelAddon.transpileTree(rawVendorTree, {
      babel: this.options.babel,

      'ember-cli-babel': {
        compileModules: false,
      },
    });

    return transpiledVendorTree;
  },
};


text:
/**
 * Base class for viewers visualizaing expression of a set of genes from various aspects
 *
 * The descendant classes should override:
 * 1. getSubmtrixParams - to set params for get_submatrix_stat method from the KBaseFeatureValues service
 * 2. buildWidget - to create a custom visuzualization
 *
 *
 *
 *
 * Pavel Novichkov <psnovichkov@lbl.gov>
 * @public
 */

define([
    'kbwidget',
    'bootstrap',
    'jquery',
    'kbaseAuthenticatedWidget',
    'kbaseTabs',
    'narrativeConfig',
    'kb_common/jsonRpc/dynamicServiceClient',
    'kb_common/jsonRpc/genericClient',
    // Loaded for effect
    'jquery-dataTables',
    'kbaseFeatureValues-client-api',
], (
    KBWidget,
    bootstrap,
    $,
    kbaseAuthenticatedWidget,
    kbaseTabs,
    Config,
    DynamicServiceClient,
    ServiceClient
) => {
    'use strict';

    return KBWidget({
        name: 'kbaseExpressionGenesetBaseWidget',
        parent: kbaseAuthenticatedWidget,
        version: '1.0.0',
        options: {
            workspaceID: null,
            expressionMatrixID: null,
            geneIds: null,
            input_featureset: null,
            loadingImage: 'static/kbase/images/ajax-loader.gif',
        },
        // Prefix for all div ids
        pref: null,
        // KBaseFeatureValue client
        featureValueClient: null,
        // Matrix set stat
        submatrixStat: null,
        init: function (options) {
            this._super(options);
            this.pref = this.uuid();

            // Create a message pane
            this.$messagePane = $('
').addClass('kbwidget-message-pane kbwidget-hide-message');
            this.$elem.append(this.$messagePane);

            return this;
        },
        loggedInCallback: function (event, auth) {
            this.featureValues = new DynamicServiceClient({
                module: 'KBaseFeatureValues',
                url: Config.url('service_wizard'),
                token: auth.token,
            });
            this.ws = new ServiceClient({
                module: 'Workspace',
                url: Config.url('workspace'),
                token: auth.token,
            });

            // Let's go...
            this.loadAndRender();
            return this;
        },
        loggedOutCallback: function () {
            this.isLoggedIn = false;
            return this;
        },
        setTestParameters: function () {
            this.options.workspaceID = '645';
            this.options.expressionMatrixID = '9';
            this.options.geneIds =
                'VNG0001H,VNG0002G,VNG0003C,VNG0006G,VNG0013C,VNG0014C,VNG0361C,VNG0518H,VNG0868H,VNG0289H,VNG0852C';
        },
        // To be overriden to specify additional parameters
        getSubmtrixParams: function () {
            const self = this;
            self.setTestParameters();
            let features = [];
            if (self.options.geneIds) {
                features = $.map(self.options.geneIds.split(','), $.trim);
            }
            return {
                input_data: self.options.workspaceID + '/' + self.options.expressionMatrixID,
                row_ids: features,
                // specify your additional parameters
            };
        },
        loadAndRender: function () {
            const self = this;
            self.loading(true);

            function getSubmatrixStatsAndRender() {
                const smParams = self.getSubmtrixParams();

                // some parameter checking
                if (!smParams.row_ids || smParams.row_ids.length === 0) {
                    self.clientError(
                        'No Features or FeatureSet selected.  Please include at least one Feature from the data.'
                    );
                    return;
                }
                self.featureValues
                    .callFunc('get_submatrix_stat', [smParams])
                    .spread((data) => {
                        self.submatrixStat = data;
                        self.render();
                        self.loading(false);
                    })
                    .catch((error) => {
                        self.clientError(error);
                    });
            }

            // if a feature set is defined, use it.
            if (self.options.featureset) {
                self.ws
                    .callFunc('get_objects', [
                        [
                            {
                                ref: self.options.workspaceID + '/' + self.options.featureset,
                            },
                        ],
                    ])
                    .spread((fdata) => {
                        const fs = fdata[0].data;
                        if (!self.options.geneIds) {
                            self.options.geneIds = '';
                        }

                        for (const fid in fs.elements) {
                            if (fs.elements.hasOwnProperty(fid)) {
                                if (self.options.geneIds) {
                                    self.options.geneIds += ',';
                                }
                                self.options.geneIds += fid;
                                //        for now we ignore which genome it came from, just use the ids
                                //        for (var k=0; k<fs.elements[fid].length; k++) {
                                //            var gid = fs.elements[fid][k];
                                //        }
                            }
                        }
                        getSubmatrixStatsAndRender();
                    })
                    .catch((error) => {
                        self.clientError(error);
                    });
            } else {
                getSubmatrixStatsAndRender();
            }
        },
        render: function () {
            const $overviewContainer = $('
');
            this.$elem.append($overviewContainer);
            this.buildOverviewDiv($overviewContainer);

            // Separator
            this.$elem.append($('

'));

            const $vizContainer = $('
');
            this.$elem.append($vizContainer);
            this.buildWidget($vizContainer);
        },
        buildOverviewDiv: function ($containerDiv) {
            const self = this;
            const pref = this.pref;

            const $overviewSwitch = $('').html('[Show/Hide Selected Features]');
            $containerDiv.append($overviewSwitch);

            const $overvewContainer = $('
');
            $containerDiv.append($overvewContainer);

            const geneData = self.buildGenesTableData();
            const iDisplayLength = 10;
            let style = 'lftip';
            if (geneData.length <= iDisplayLength) {
                style = 'fti';
            }

            $overvewContainer.append(
                $(
                    '
\

'
                ).dataTable({
                    sDom: style,
                    iDisplayLength: iDisplayLength,
                    aaData: geneData,
                    aoColumns: [
                        { sTitle: 'Name', mData: 'id' },
                        { sTitle: 'Function', mData: 'function' },
                        { sTitle: 'Min', mData: 'min' },
                        { sTitle: 'Max', mData: 'max' },
                        { sTitle: 'Avg', mData: 'avg' },
                        { sTitle: 'Std', mData: 'std' },
                        { sTitle: 'Missing', mData: 'missing_values' },
                    ],
                    oLanguage: {
                        sEmptyTable: 'No genes found!',
                        sSearch: 'Search: ',
                    },
                })
            );

            $overviewSwitch.click(() => {
                $overvewContainer.toggle();
            });
        },
        buildGenesTableData: function () {
            const submatrixStat = this.submatrixStat;
            const tableData = [];
            const stat = submatrixStat.row_set_stats;
            for (let i = 0; i < submatrixStat.row_descriptors.length; i++) {
                const desc = submatrixStat.row_descriptors[i];

                const gene_function = desc.properties['function'];
                tableData.push({
                    index: desc.index,
                    id: desc.id,
                    name: desc.name ? desc.name : ' ',
                    function: gene_function ? gene_function : ' ',
                    min: stat.mins[i] ? stat.mins[i].toFixed(2) : null,
                    max: stat.maxs[i] ? stat.maxs[i].toFixed(2) : null,
                    avg: stat.avgs[i] ? stat.avgs[i].toFixed(2) : null,
                    std: stat.stds[i] ? stat.stds[i].toFixed(2) : null,
                    missing_values: stat.missing_values[i],
                });
            }
            return tableData;
        },
        // To be overriden
        buildWidget: null,

        makeRow: function (name, value) {
            const $row = $('
')
                .append($('').css('width', '20%').append(name))
                .append($('').append(value));
            return $row;
        },
        loading: function (isLoading) {
            if (isLoading) this.showMessage("");
            else this.hideMessage();
        },
        showMessage: function (message) {
            const span = $('').append(message);

            this.$messagePane.append(span);
            this.$messagePane.show();
        },
        hideMessage: function () {
            this.$messagePane.hide();
            this.$messagePane.empty();
        },
        clientError: function (error) {
            this.loading(false);
            let errString = 'Unknown error.';
            console.error(error);
            if (typeof error === 'string') errString = error;
            else if (error.error && error.error.message) errString = error.error.message;
            else if (error.error && error.error.error && typeof error.error.error === 'string') {
                errString = error.error.error;
                if (
                    errString.indexOf('java.lang.NullPointerException') > -1 &&
                    errString.indexOf('buildIndeces(KBaseFeatureValuesImpl.java:708)') > -1
                ) {
                    // this is a null pointer due to an unknown feature ID.  TODO: handle this gracefully
                    errString = 'Feature IDs not found.

';
                    errString +=
                        'Currently all Features included in a FeatureSet must be present' +
                        ' in the Expression Data Matrix.  Please rebuild the FeatureSet ' +
                        'so that it only includes these features.  This is a known issue ' +
                        'and will be fixed shortly.';
                }
            }

            const $errorDiv = $('
')
                .addClass('alert alert-danger')
                .append('Error:')
                .append('
' + errString);
            this.$elem.empty();
            this.$elem.append($errorDiv);
        },
        uuid: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
                const r = (Math.random() * 16) | 0,
                    v = c == 'x' ? r : (r & 0x3) | 0x8;
                return v.toString(16);
            });
        },
        buildObjectIdentity: function (workspaceID, objectID, objectVer, wsRef) {
            const obj = {};
            if (wsRef) {
                obj['ref'] = wsRef;
            } else {
                if (/^\d+$/.exec(workspaceID)) obj['wsid'] = workspaceID;
                else obj['workspace'] = workspaceID;

                // same for the id
                if (/^\d+$/.exec(objectID)) obj['objid'] = objectID;
                else obj['name'] = objectID;

                if (objectVer) obj['ver'] = objectVer;
            }
            return obj;
        },
    });
});


text:
package org.broadinstitute.hellbender.tools.copynumber.utils.annotatedinterval;

import org.broadinstitute.hellbender.GATKBaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;

public class SimpleAnnotatedIntervalWriterUnitTest extends GATKBaseTest {

    private static final File TEST_FILE_NO_SAMHEADER = new File(toolsTestDir,
            "copynumber/utils/combine-segment-breakpoints-no-samheader.seg");
    private static final File TEST_FILE = new File(toolsTestDir,
            "copynumber/utils/combine-segment-breakpoints.seg");
    private static final File TEST_FILE_OLD_HEADER = new File(toolsTestDir,
            "copynumber/utils/annotatedinterval/simple-annotated-interval-writer-replacement-header-comments.seg");
    private static final File TEST_FILE_OLD_HEADER_CONFIG = new File(toolsTestDir,
            "copynumber/utils/annotatedinterval/old-header.config");

    @Test
    public void testNoSamFileHeaderWithComments() throws IOException {
        final File outputFile = File.createTempFile("simpleannotatedintervalwriter_no_samheader", ".seg");
        final AnnotatedIntervalCollection collection = AnnotatedIntervalCollection.create(TEST_FILE_NO_SAMHEADER.toPath(), null);

        final SimpleAnnotatedIntervalWriter writer = new SimpleAnnotatedIntervalWriter(outputFile);
        writer.writeHeader(AnnotatedIntervalCodec.createHeaderForWriter(collection.getAnnotations(), collection.getSamFileHeader()));
        collection.getRecords().forEach(r -> writer.add(r));
        writer.close();

        final AnnotatedIntervalCollection testCollection = AnnotatedIntervalCollection.create(outputFile.toPath(), null);

        // Reminder: In this case, the output will have additional comments for the header
        Assert.assertEquals(testCollection.getComments().subList(0,2), collection.getComments());
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.CONTIG_COL_COMMENT + "CONTIG")));
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.START_COL_COMMENT + "START")));
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.END_COL_COMMENT + "END")));
        Assert.assertEquals(testCollection.getRecords(), collection.getRecords());
        Assert.assertEquals(testCollection.getSamFileHeader(), collection.getSamFileHeader());
        Assert.assertEquals(testCollection.getAnnotations(), collection.getAnnotations());
    }

    @Test
    public void testRoundTrip() throws IOException {
        final File outputFile = File.createTempFile("simpleannotatedintervalwriter_", ".seg");
        final AnnotatedIntervalCollection collection = AnnotatedIntervalCollection.create(TEST_FILE.toPath(), null);

        final SimpleAnnotatedIntervalWriter writer = new SimpleAnnotatedIntervalWriter(outputFile);

        writer.writeHeader(AnnotatedIntervalCodec.createHeaderForWriter(collection.getAnnotations(), collection.getSamFileHeader()));
        collection.getRecords().forEach(r -> writer.add(r));
        writer.close();

        final AnnotatedIntervalCollection testCollection = AnnotatedIntervalCollection.create(outputFile.toPath(), null);

        // Reminder: In this case, the output will have additional comments for the header.  The input had none.
        Assert.assertEquals(testCollection.getComments().size(), 3);
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.CONTIG_COL_COMMENT + "CONTIG")));
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.START_COL_COMMENT + "START")));
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.END_COL_COMMENT + "END")));
        Assert.assertEquals(testCollection.getRecords(), collection.getRecords());
        Assert.assertEquals(testCollection.getSamFileHeader(), collection.getSamFileHeader());
        Assert.assertEquals(testCollection.getAnnotations(), collection.getAnnotations());
    }

    @Test
    public void testRoundTripWithReplacementHeader() throws IOException {
        // Tests that we can read a file with a non-standard header (specified by a config file) and that we can output
        //  with the default headers (input headers would then not match output headers).
        //  Also, tests that the structured comments get replaced with the new value.
        final File outputFile = File.createTempFile("simpleannotatedintervalwriter_", ".seg");
        final AnnotatedIntervalCollection collection = AnnotatedIntervalCollection.create(TEST_FILE_OLD_HEADER.toPath(),
                TEST_FILE_OLD_HEADER_CONFIG.toPath(),null);

        final String newContigColumn = "CONTIG";
        final String newStartColumn = "START";
        final String newEndColumn = "END";

        try (final SimpleAnnotatedIntervalWriter writer = new SimpleAnnotatedIntervalWriter(outputFile)) {
            writer.writeHeader(AnnotatedIntervalCodec.createHeaderForWriter(collection.getAnnotations(), collection.getSamFileHeader()));
            collection.getRecords().forEach(r -> writer.add(r));
        }

        final AnnotatedIntervalCollection testCollection = AnnotatedIntervalCollection.create(outputFile.toPath(), null);

        // Reminder: In this case, the output will have additional comments for the header.  The input had none.
        Assert.assertEquals(testCollection.getComments().size(), 1+3);
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.CONTIG_COL_COMMENT + newContigColumn)));
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.START_COL_COMMENT + newStartColumn)));
        Assert.assertTrue(testCollection.getComments().stream().anyMatch(c -> c.equals(AnnotatedIntervalCodec.END_COL_COMMENT + newEndColumn)));
        Assert.assertEquals(testCollection.getRecords(), collection.getRecords());
        Assert.assertEquals(testCollection.getSamFileHeader(), collection.getSamFileHeader());
        Assert.assertEquals(testCollection.getAnnotations(), collection.getAnnotations());
    }
}