text:
package com.github.kmbulebu.dsc.it100;

import com.github.kmbulebu.dsc.it100.commands.read.BaudRateSetCommand;
import com.github.kmbulebu.dsc.it100.commands.read.ReadCommand;
import com.github.kmbulebu.dsc.it100.commands.util.Key;
import com.github.kmbulebu.dsc.it100.commands.write.BaudRateChangeCommand;
import com.github.kmbulebu.dsc.it100.commands.write.KeyPressCommand;
import com.github.kmbulebu.dsc.it100.commands.write.WriteCommand;
import rx.Observable;
import rx.functions.Action1;

import java.util.Scanner;

import static com.github.kmbulebu.dsc.it100.commands.write.BaudRateChangeCommand.BaudRate.BAUD_115200;

public class VirtualKeypadExample {

	public static void main(String... args) throws Exception {
		final Scanner scanner = new Scanner(System.in);
		System.out.print("Connect using socket or serial port?(s/p): ");
		String command = scanner.nextLine();
		ConfigurationBuilder cb = new ConfigurationBuilder();
		String baud = null;
		if ("s".equalsIgnoreCase(command)) {
			System.out.print("Using socket. Insert host and port (host:port): ");
			command = scanner.nextLine();
			String[] socket = command.split(":");
			cb.withRemoteSocket(socket[0], Integer.parseInt(socket[1]));
		} else {
			System.out.print("Using serial port. Insert file name and baud rate (file baud): ");
			command = scanner.nextLine();
			String[] socket = command.split(" ");
			baud = socket[1];
			cb.withSerialPort(socket[0], Integer.parseInt(socket[1]));
		}

		final IT100 it100 = new IT100(cb.build());

		try {
			// Start communicating with IT-100.
			it100.connect();

			final Observable<ReadCommand> readObservable = it100.getReadObservable();

			//Write out responses
			readObservable.subscribe(new Action1<ReadCommand>() {

				@Override
				public void call(ReadCommand t1) {
					System.out.println("Received message: " + t1.toString());
				}

			});

			it100.getWriteObservable().subscribe(new Action1<WriteCommand>() {

				@Override
				public void call(WriteCommand t1) {
					System.out.println("Sent message: " + t1.toString());
				}

			});

			//Virtual keypad needs higher baud rate than 9600
			readObservable.ofType(BaudRateSetCommand.class).subscribe(new Action1<BaudRateSetCommand>() {

				@Override
				public void call(BaudRateSetCommand t1) {
					System.out.println("Baud rate successfully set to " + t1.getBaudRateCode());
					System.out.println("Run the program again with the new baud rate");
					System.exit(0);
				}

			});

			if ("9600".equals(baud)) {
				it100.send(new BaudRateChangeCommand(BAUD_115200));
			} else {
				readCommand(scanner, it100);
				System.out.println("Quitting");
				System.exit(0);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			scanner.close();
			it100.disconnect();
		}
	}

	private static void readCommand(Scanner scanner, IT100 it100) {
		System.out.print("Insert command (or q to quit):");
		String command = scanner.nextLine();

		if (command.equals("q")) {
			return;
		}
		char unknownChar = 0;
		for (char c : command.toCharArray()) {
			Key key = Key.fromAsciiChar(c);
			if (key == null) {
				unknownChar = c;
				break;
			}
		}
		if (unknownChar != 0) {
			System.out.printf("Unknown character %c\n", unknownChar);
		} else {
			for (char c : command.toCharArray()) {
				Key key = Key.fromAsciiChar(c);
				it100.send(new KeyPressCommand(key));
				it100.send(new KeyPressCommand(Key.BREAK));
			}
		}
		readCommand(scanner, it100);
	}
}


text:
module.exports = function (config) {
  config.set({
    files: [
      './components/angular/angular.js',
      './components/angular-mocks/angular-mocks.js',
      './test/*.js',
      './src/index.js'
    ],

    browsers: ['PhantomJS'],
    frameworks: ['mocha', 'chai', 'sinon'],

    autoWatch: true
  });
};

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\UserBundle\Admin ;

use Symfony\Bundle\FrameworkBundle\Controller\Controller ;
use Symfony\Component\HttpFoundation\Request ;
use App\AdminBundle\Compiler\Cache\ActionCache ;
use Symfony\Component\Form\Form ;

use Symfony\Component\Security\Core\SecurityContext;

abstract class UserAdmin extends \App\AdminBundle\Compiler\Cache\AdminCache {

    public function adjustFormOptions($object, $property, array & $options){
        if( $property === 'id_card' ) {
            $options['constraints'][] = new \App\UserBundle\Form\Constraints\IdCard(array(
                    'message'  =>
                        $this->trans('app_user.form.id_card.error', array(), $this->tr_domain ) ,
                )) ;
        }
    }

    public function setUserRegistration(\App\UserBundle\Entity\User $user, \Symfony\Component\HttpFoundation\Request $request) {
        $group_admin  = $this->admin_loader->getAdminByName('app_group') ;

        $group  = $group_admin->getRepository()->findOneBy( array('default_group'=>true)) ;
        if( !$group ) {
            throw new \Exception('need create default group');
        }
        $user->setUserGroup($group) ;

        $log    = new \App\UserBundle\Entity\UserLog() ;
        $log->setUser($user) ;
        $log->setType( \App\UserBundle\Entity\UserLog::TYPE_USER_REG ) ;
        $log_admin  = $this->admin_loader->getAdminByClass($log) ;
        $log_admin->initByRequest($log, $request) ;
        $this->getManager()->persist( $log ) ;
    }

    public function addMember(\App\UserBundle\Entity\User $user, \Symfony\Component\HttpFoundation\Request $request){
        $group_admin  = $this->admin_loader->getAdminByName('app_group') ;

        $group  = $group_admin->getRepository()->findOneBy( array('trust_group'=>true) ) ;
        if( !$group ) {
            throw new \Exception('need create trust group');
        }
        $user->setUserGroup($group) ;
        $em = $this->getManager() ;
        $em->persist( $user ) ;

        $log    = new \App\UserBundle\Entity\UserLog() ;
        $log->setUser($user) ;
        $log->setType( \App\UserBundle\Entity\UserLog::TYPE_USER_BANK ) ;
        $log_admin  = $this->admin_loader->getAdminByClass($log) ;
        $log_admin->initByRequest($log, $request) ;
        $em->persist( $log ) ;
    }

    public function getLoginForm(\Symfony\Component\HttpFoundation\Request $request = null, array $options = array(), $with_title = true ) {

        if( $request ) {
            if ( $request->attributes->has(SecurityContext::AUTHENTICATION_ERROR) ) {
                $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
            } else {
                $error = $request->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
                $request->getSession()->set( SecurityContext::AUTHENTICATION_ERROR , null ) ;
            }
        } else {
            $error  = null ;
        }

        $tr = $this->container->get('translator') ;
        $app_domain  = $this->container->getParameter('app.admin.domain') ;

        $form_options   = array(
        ) ;

        if( $with_title ) {
            $form_options['label']  = 'app.login.label' ;
            $form_options['translation_domain']  = $app_domain;
        } else {
            $form_options['label_render']  = false  ;
        }

        \Dev::merge( $form_options, $options ) ;

        $builder = $this->container->get('form.factory')->createNamedBuilder('login', 'form', null, $form_options ) ;

        $router  = $this->container->get('router') ;
        $session  = $this->container->get('session') ;

        $builder
                    ->add('username', 'text', array(
                        'label' => 'app.login.username.label' ,
                        'translation_domain' => $app_domain ,
                        'data'  => $session->get(SecurityContext::LAST_USERNAME) ,
                        // 'horizontal_input_wrapper_class' => 'col-xs-6',
                        'input_width'   => 46 ,
                        'attr' => array(
                            'placeholder' => 'app.login.username.placeholder' ,
                        )
                    ) )
                    ->add('password', 'password', array(
                        'label'  => 'app.login.password.label' ,
                        'translation_domain' => $app_domain ,
                        'input_width'   => 46 ,
                        // 'horizontal_input_wrapper_class' => 'col-xs-6',
                        'attr' => array(

                        )
                    ) )

                    ->add('captcha', 'appcaptcha', array(
                        'label' => 'app.form.captcha.label' ,
                        'translation_domain' => $app_domain ,
                    ))

                    ->add('remembme', 'appcheckbox', array(
                        'label_render' => false ,
                        'translation_domain' => $app_domain ,
                        'required'  => false ,
                        'value_text'  =>'app.login.remembme.label' ,
                        'inline_help' => $tr->trans('app.login.remembme.resetting' ,  array(
                            '%url%' => $router->generate('fos_user_resetting_request') ,
                        ), $app_domain) ,
                    ))
                ;

        $form     = $builder->getForm() ;

        if( $error ) {
            if( $error instanceof \Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException ) {
                $_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.crsf', array(), $app_domain ) ) ;
                $form->addError( $_error  ) ;
            } else if ( $error instanceof \App\UserBundle\Exception\CaptchaException ) {
                $_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.captcha' , array(), $app_domain ) ) ;
                $form->get('captcha')->addError( $_error ) ;
            } else if( $error instanceof \Symfony\Component\Security\Core\Exception\BadCredentialsException ) {
                $_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.credentials' , array(), $app_domain ) ) ;
                $form->get('username')->addError( $_error ) ;
            } else if( $error instanceof \Symfony\Component\Security\Core\Exception\DisabledException ) {
                $_error = new \Symfony\Component\Form\FormError( $tr->trans('app.login.error.disabled' , array(), $app_domain ) ) ;
                $form->get('username')->addError( $_error ) ;
            } else {
                $_error = new \Symfony\Component\Form\FormError( $error->getMessage() ) ;
                if( $this->container->getParameter('kernel.debug') ) {
                    \Dev::dump(  $error ) ;
                }
                $form->get('username')->addError( $_error ) ;
            }
        }

        return $form ;
    }

    public function getLoginErrors() {
        $tr = $this->container->get('translator') ;
        $app_domain  = $this->container->getParameter('app.admin.domain') ;
        return array(
            'captchaexception'  => $tr->trans('app.login.error.captcha' , array(), $app_domain ) ,
            'badcredentialsexception'  => $tr->trans('app.login.error.credentials' , array(), $app_domain ) ,
            'disabledexception'  => $tr->trans('app.login.error.disabled', array(), $app_domain ) ,
            'invalidcsrftokenexception'  => $tr->trans('app.login.error.crsf', array(), $app_domain ) ,
        );
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.revelc.code.formatter;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.maven.plugin.logging.Log;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.text.edits.MalformedTreeException;

import net.revelc.code.formatter.css.CssFormatter;
import net.revelc.code.formatter.html.HTMLFormatter;
import net.revelc.code.formatter.xml.XMLFormatter;

/**
 * The Class AbstractCacheableFormatter.
 */
public abstract class AbstractCacheableFormatter {

    /** The log. */
    protected Log log;

    /** The encoding. */
    protected Charset encoding;

    /**
     * Inits the AbstractCacheableFormatter.
     *
     * @param options
     *            the options
     * @param cfg
     *            the cfg
     */
    protected abstract void init(Map<String, String> options, ConfigurationSource cfg);

    /**
     * Inits the cfg.
     *
     * @param cfg
     *            the cfg
     */
    protected void initCfg(final ConfigurationSource cfg) {
        this.log = cfg.getLog();
        this.encoding = cfg.getEncoding();
    }

    /**
     * Format file.
     *
     * @param file
     *            the file
     * @param originalCode
     *            the original code
     * @param ending
     *            the ending
     *
     * @return the string
     */
    public String formatFile(final File file, final String originalCode, final LineEnding ending) {
        try {
            this.log.debug("Processing file: " + file + " with line ending: " + ending);
            var formatterLineEnding = ending;
            // if the line ending is set as KEEP we have to determine the current line ending of the file
            // and let the formatter use this one. Otherwise it would likely fall back to current system line separator
            if (formatterLineEnding == LineEnding.KEEP) {
                formatterLineEnding = LineEnding.determineLineEnding(originalCode);
                this.log.debug("Determined line ending: " + formatterLineEnding + " to keep for file: " + file);
            }
            var formattedCode = this.doFormat(originalCode, formatterLineEnding);

            if (formattedCode == null) {
                this.log.debug("Nothing formatted. Try to fix line endings.");
                formattedCode = AbstractCacheableFormatter.fixLineEnding(originalCode, ending);
            } else if (this instanceof CssFormatter || this instanceof HTMLFormatter || this instanceof XMLFormatter) {
                this.log.debug("Formatted but line endings not supported by tooling. Try to fix line endings.");
                formattedCode = AbstractCacheableFormatter.fixLineEnding(formattedCode, ending);
            }

            if (formattedCode == null) {
                this.log.debug("Equal code. Not writing result to file.");
                return originalCode;
            }

            this.log.debug("Line endings fixed");

            return formattedCode;
        } catch (IOException | MalformedTreeException | BadLocationException e) {
            this.log.warn(e);
            return null;
        }
    }

    /**
     * Fix line ending.
     *
     * @param code
     *            the code
     * @param ending
     *            the ending
     *
     * @return the string
     */
    private static String fixLineEnding(String code, final LineEnding ending) {
        if (ending == LineEnding.KEEP) {
            return null;
        }

        // Normalize all line endings
        code = code.replace(LineEnding.CRLF.getChars(), LineEnding.LF.getChars());
        code = code.replace(LineEnding.CR.getChars(), LineEnding.LF.getChars());

        // Replace line endings with chosen style
        return code.replace(LineEnding.LF.getChars(), ending.getChars());
    }

    /**
     * Do format.
     *
     * notice that when calling this function, {@code ending} here MUST equals lineending in config when
     * {@link #init(Map, ConfigurationSource)} init.
     *
     * @param code
     *            the code
     * @param ending
     *            the ending
     *
     * @return the string
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws BadLocationException
     *             the bad location exception
     */
    protected abstract String doFormat(String code, LineEnding ending) throws IOException, BadLocationException;

}


text:
<?php

if ( ! isset($CFG) ) return; // Only from within tsugi.php

use \Tsugi\Util\U;
use \Tsugi\Core\LTIX;
use \Tsugi\Google\GoogleClassroom;

require_once("util.php");

$request_headers = apache_request_headers();
$agent = U::get($request_headers,'User-Agent');
if ( isset($CFG->logo_url) && $agent && stripos($agent,'Google Web Preview') !== false ) {
    echo('logo_url.'">'."\n");
    return;
}

// TODO: Make the session be based on resource_link_id
session_start();

// Lets be really picky about the path...
$path = U::parse_rest_path();
if ( count($path) != 3 ) {
    $_SESSION['error'] = 'Invalid resource id format';
    header('Location: '.$CFG->apphome);
    return;
}
$pieces = explode(':',$path[2]);
if ( count($pieces) != 4 || strlen($pieces[1]) != 6 || strlen($pieces[3]) != 6
     || ! is_numeric($pieces[0]) || ! is_numeric($pieces[2]) ) {
    $_SESSION['error'] = 'Invalid resource id format';
    header('Location: '.$CFG->apphome);
    return;
}

$gc_course = $pieces[0];
$user_mini_sig = $pieces[1];
$link_id = $pieces[2];
$link_mini_sig = $pieces[3];

$context_url = $gc_course . ':' . $user_mini_sig;
$context_key = 'gclass:' . $context_url;
$context_sha256 = lti_sha256($context_key);

if ( ! isset($_SESSION['id']) ) {
    $_SESSION['login_return'] = $path[0].'/'.$path[1].'/'.$path[2];
    header('Location: '.$CFG->wwwroot.'/login');
    return;
}

$user_id = $_SESSION['id'];
$user_email = $_SESSION['email'];
$user_displayname = $_SESSION['displayname'];
$user_key = $_SESSION['user_key'];
$user_avatar = U::get($_SESSION,'avatar', null);

$PDOX = LTIX::getConnection();

// Load up the stuff course / link stuff / big inner join

$sql = "SELECT gc_secret, O.user_id AS owner_id, O.email AS owner_email,
        role, role_override,
        C.context_id AS context_id, C.title AS context_title,
        L.path AS path, link_key, L.link_id as link_id, L.title AS link_title,
        result_id, gc_submit_id,
        M.json AS membership_json,
        K.key_id AS key_id, K.secret AS key_secret, K.key_key AS key_key
    FROM {$CFG->dbprefix}lti_context AS C
    JOIN {$CFG->dbprefix}lti_user AS O
        ON C.user_id = O.user_id
    JOIN {$CFG->dbprefix}lti_link AS L
        ON C.context_id = L.context_id
    JOIN {$CFG->dbprefix}lti_key AS K
        ON C.key_id = K.key_id
    LEFT JOIN {$CFG->dbprefix}lti_result AS R
        ON L.link_id = R.link_id AND R.user_id = :UID
    LEFT JOIN {$CFG->dbprefix}lti_membership AS M
        ON C.context_id = M.context_id AND M.user_id = :UID
    WHERE context_sha256 = :context_sha256 AND context_key = :context_key
    AND L.link_id = :LID
    LIMIT 1";

$row = $PDOX->rowDie($sql,
    array(
        ':context_sha256' => $context_sha256,
        ':context_key' => $context_key,
        ':UID' => $user_id,
        ':LID' => $link_id )
);

if ( ! $row ) {
    $_SESSION['error'] = 'Could not lookup resource id';
    header('Location: '.$CFG->apphome);
    return;
}

$gc_secret = $row['gc_secret'];
$path = $row['path'];
$owner_id = $row['owner_id'];
$gc_coursework = $row['link_key'];
$owner_email = $row['owner_email'];
$context_id = $row['context_id'];
$context_title = $row['context_title'];
$key_id = $row['key_id'];
$key_key = $row['key_key'];
$key_secret = $row['key_key'];
$gc_submit_id = $row['gc_submit_id'];
$result_id = $row['result_id'];
$link_title = $row['link_title'];
$role = $row['role'];
$membership_json = $row['membership_json'];
if ( $row['role_override'] > $row['role'] ) {
    $role = $row['role_override'];
}

// Do some validation...
$plain = $CFG->google_classroom_secret.$gc_course.$owner_id.$CFG->google_classroom_secret;
$user_mini_check = lti_sha256($plain);
$user_mini_check = substr($user_mini_check,0,6);

$plain = $gc_secret.$context_url.$link_id.$gc_secret;
$link_mini_check = lti_sha256($plain);
$link_mini_check = substr($link_mini_check,0,6);

if ( $link_mini_check != $link_mini_sig || $user_mini_check != $user_mini_sig ) {
    $_SESSION['error'] = 'Could not validate resource id';
    header('Location: '.$CFG->apphome);
    return;
}

// Try access token from session when LTIX adds it.
$accessTokenStr = GoogleClassroom::retrieve_instructor_token($owner_id);
if ( ! $accessTokenStr ) {
    $_SESSION['error'] = 'Classroom connection not set up, see your instructor';
    header('Location: '.$CFG->apphome);
    return;
}

// Get the API client and construct the service object.
$client = GoogleClassroom::getClient($accessTokenStr, $owner_id);
if ( ! $client ) {
    $_SESSION['error'] = 'Classroom connection failed';
    error_log('Classroom connection failed id='.$owner_id);
    error_log($accessTokenStr);
    header('Location: '.$CFG->apphome);
    return;
}

// Lets talk to Google
$service = new Google_Service_Classroom($client);

$student_id = false;
// If we have a membership record...
if ( $role != null ) {
    if ( $role <= LTIX::ROLE_LEARNER && strlen($membership_json) > 0 ) {
        $mj = json_decode($membership_json, true);
        $student_id = U::get($mj, 'student_id');
	if ( ! $student_id ) error_log('Could not restore student_id');
    }
// Make a membership record
} else {
    if ( $user_email == $owner_email ) $role = LTIX::ROLE_INSTRUCTOR;

    // Check if the current user is a student...
    if ( ! $role ) {
        // TODO: Look into using the APIs to do this.
        $access_token_data = $client->getAccessToken();
        $access_token = $access_token_data['access_token'];

        $membership_info_url = "https://classroom.googleapis.com/v1/courses/".$gc_course.
            "/students/".$_SESSION['email']."?alt=json&access_token=" .  $access_token;

        $response = \Tsugi\Util\Net::doGet($membership_info_url);
        $membership = json_decode($response);

        /* Not a student:
        object(stdClass)#27 (1) {
        ["error"]=>
            object(stdClass)#26 (3) {
            ["code"]=>
            int(404)
            ["message"]=>
            string(31) "Requested entity was not found."
            ["status"]=>
            string(9) "NOT_FOUND"
            }
        }

        Student:
        object(stdClass)#24 (3) {
        ["courseId"]=>
        string(10) "9523923149"
        ["userId"]=>
        string(21) "100516595241762316861"
        ["profile"]=>
        ...
        }
        */

        // If the current user is a student we are golden
        if ( isset($membership->courseId) ) {
            $role = LTIX::ROLE_LEARNER;
        } else {
            $_SESSION['error'] = 'You are not enrolled in this class';
            error_log('Classroom connection failed id='.$owner_id);
            error_log($accessTokenStr);
            header('Location: '.$CFG->apphome);
            return;
        }

        if ( isset($membership->userId) ) {
            $student_id = $membership->userId;
        } else {
            $_SESSION['error'] = 'You are do not have a studentId in this class';
            error_log('Classroom connection failed id='.$owner_id);
            error_log($accessTokenStr);
            header('Location: '.$CFG->apphome);
            return;
        }

        // Insert the membership record
        $json = new \stdClass();
        $json->student_id = $student_id;
        $json = json_encode($json);

        $sql = "INSERT INTO {$CFG->dbprefix}lti_membership
            ( context_id, user_id, role, json, created_at, updated_at ) VALUES
            ( :context_id, :user_id, :role, :json, NOW(), NOW() )
            ON DUPLICATE KEY UPDATE role=:role, updated_at=NOW()";
        $PDOX->queryDie($sql, array(
            ':context_id' => $context_id,
            ':user_id' => $user_id,
            ':json' => $json,
            ':role' => $role));
    }
}

// Make sure we have a submit_id in the database
if ( $student_id && $gc_submit_id === null ) {
    try {
        // Get the student's submission...
        $studentSubmissions = $service->courses_courseWork_studentSubmissions;

        // Submissions associated with this courseWork for this student
        $retval = $studentSubmissions->listCoursesCourseWorkStudentSubmissions(
            $gc_course, $gc_coursework, array('userId' => $student_id));
        // var_dump($retval);

        // Grab the first submission
        $submissions = $retval->studentSubmissions;
        $first = $submissions[0];
        // var_dump($first);
        $gc_submit_id = $first->id;
    } catch (Exception $e) {
        $_SESSION['error'] = 'Could not retrieve submission for this assignment.';
        error_log('Could not retrieve submission for this assignment id='.$owner_id);
        error_log($accessTokenStr);
        header('Location: '.$CFG->apphome);
        return;
    }
}

// Insert the result record if necessary (learner and instructor)
if ( $result_id == null || $row['gc_submit_id'] === null ) {
    $sql = "INSERT INTO {$CFG->dbprefix}lti_result
        ( link_id, user_id, gc_submit_id, created_at, updated_at ) VALUES
        ( :link_id, :user_id, :GCS, NOW(), NOW() )
        ON DUPLICATE KEY UPDATE gc_submit_id=:GCS, updated_at=NOW()";
    $PDOX->queryDie($sql, array(
        ':link_id' => $link_id,
        ':user_id' => $user_id,
        ':GCS' => $gc_submit_id));
    $result_id = $PDOX->lastInsertId();
    error_log('New student='.$user_id.' context='.$context_id.' owner='.$user_email);
}

// Set up the LTI launch information

$lti = array();
$lti['key_id'] = $key_id;
$lti['key_key'] = $key_key;

if ( strlen($key_secret) ) {
    $lti['secret'] = LTIX::encrypt_secret($key_secret);
}

$lti['user_id'] = $user_id;
$lti['user_key'] = $user_key;
$lti['user_email'] = $user_email;
$lti['user_displayname'] = $user_displayname;
if ( strlen($user_avatar) ) {
    $lti['user_image'] = $user_avatar;
}
$lti['role'] = $role;

$lti['context_id'] = $context_id;
$lti['context_key'] = $context_key;
$lti['context_title'] = $context_title;

$lti['link_id'] = $link_id;
$lti['link_title'] = $link_title;

$lti['result_id'] = $result_id;

// Grades will do this:
// $retval = $studentSubmissions->patch($gc_course, $gc_coursework, $gc_submit_id, $sub, $opt);
$lti['gc_owner_id'] = $owner_id;
$lti['gc_course'] = $gc_course;
$lti['gc_coursework'] = $gc_coursework;
$lti['gc_submit_id'] = $gc_submit_id;

// Set that data in the session.
$_SESSION['lti'] = $lti;

// Record their log in if this is the first for a session
$start_time = U::get($_SESSION, 'tsugi_permanent_start_time', false);
if ( $start_time === false ) {
    LTIX::noteLoggedIn($lti);
    $_SESSION['tsugi_permanent_start_time'] = time();
}

$launch = U::add_url_parm($path, 'PHPSESSID', session_id());

if ( ! U::get($_GET,'debug') ) {
    header('Location: '.$launch);
    return;
}
?>
<a href="<?= $launch ?>" target="_blank"><?= $launch ?>

LTI:
<?php
print_r($lti);
?>
Row:
<?php
print_r($row);
?>
Path:
<?php
print_r($path);
?>

Post:
<?php
print_r($_POST);
?>

Get:
<?php
print_r($_GET);


text:
package com.github.badoualy.telegram.tl.api;

import com.github.badoualy.telegram.tl.TLContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;

/**
 * @author Yannick Badoual yann.badoual@gmail.com
 * @see http://github.com/badoualy/kotlogram
 */
public class TLChatParticipantAdmin extends TLAbsChatParticipant {

    public static final int CONSTRUCTOR_ID = 0xe2d6e436;

    protected int inviterId;

    protected int date;

    private final String _constructor = "chatParticipantAdmin#e2d6e436";

    public TLChatParticipantAdmin() {
    }

    public TLChatParticipantAdmin(int userId, int inviterId, int date) {
        this.userId = userId;
        this.inviterId = inviterId;
        this.date = date;
    }

    @Override
    public void serializeBody(OutputStream stream) throws IOException {
        writeInt(userId, stream);
        writeInt(inviterId, stream);
        writeInt(date, stream);
    }

    @Override
    @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
    public void deserializeBody(InputStream stream, TLContext context) throws IOException {
        userId = readInt(stream);
        inviterId = readInt(stream);
        date = readInt(stream);
    }

    @Override
    public int computeSerializedSize() {
        int size = SIZE_CONSTRUCTOR_ID;
        size += SIZE_INT32;
        size += SIZE_INT32;
        size += SIZE_INT32;
        return size;
    }

    @Override
    public String toString() {
        return _constructor;
    }

    @Override
    public int getConstructorId() {
        return CONSTRUCTOR_ID;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getInviterId() {
        return inviterId;
    }

    public void setInviterId(int inviterId) {
        this.inviterId = inviterId;
    }

    public int getDate() {
        return date;
    }

    public void setDate(int date) {
        this.date = date;
    }
}


text:
require 'helper'

class TestSanitizer < Minitest::Unit::TestCase

  def test_special_cases
    items = [nil, '', '      ']
    Scrapouille::Sanitizer.clean!(items)
    assert_equal [nil, '', ''], items
  end

  def test_squeeze_and_strip_whitespaces
    items = ['1  2    3 4  ', '   a b c d ']
    Scrapouille::Sanitizer.clean!(items)
    assert_equal ['1 2 3 4', 'a b c d'], items
  end

  def test_replace_html_non_breaking_spaces_by_whitespaces
    with_html_nbsp = 'B. Firat F'
    refute with_html_nbsp.ascii_only?
    items = [with_html_nbsp]
    Scrapouille::Sanitizer.clean!(items)
    assert_equal ['B. Firat F'], items, 'Should have removed   (\u00A0) char'
    assert items.first.ascii_only?
  end

end


text:
package controllers

import (
	"bytes"
	ctx "context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	c "github.com/opensds/opensds/pkg/context"
	"github.com/opensds/opensds/pkg/db"
	"github.com/opensds/opensds/pkg/model"
	pb "github.com/opensds/opensds/pkg/model/proto"
	. "github.com/opensds/opensds/testutils/collection"
	ctrtest "github.com/opensds/opensds/testutils/controller/testing"
	dbtest "github.com/opensds/opensds/testutils/db/testing"
)

////////////////////////////////////////////////////////////////////////////////
//                      Prepare for mock server                               //
////////////////////////////////////////////////////////////////////////////////
func init() {
	beego.Router("/v1beta/file/shares", NewFakeFileSharePortal(),
		"post:CreateFileShare;get:ListFileShares")
	beego.Router("/v1beta/file/shares/:fileshareId", NewFakeFileSharePortal(),
		"get:GetFileShare;put:UpdateFileShare;delete:DeleteFileShare")

	beego.Router("/v1beta/file/snapshots", &FileShareSnapshotPortal{},
		"post:CreateFileShareSnapshot;get:ListFileShareSnapshots")
	beego.Router("/v1beta/file/snapshots/:snapshotId", &FileShareSnapshotPortal{},
		"get:GetFileShareSnapshot;put:UpdateFileShareSnapshot;delete:DeleteFileShareSnapshot")

}

func NewFakeFileSharePortal() *FileSharePortal {
	mockClient := new(ctrtest.Client)

	mockClient.On("Connect", "localhost:50049").Return(nil)
	mockClient.On("Close").Return(nil)
	mockClient.On("CreateFileShare", ctx.Background(), &pb.CreateFileShareOpts{
		Context: c.NewAdminContext().ToJson(),
	}).Return(&pb.GenericResponse{}, nil)
	mockClient.On("DeleteFileShare", ctx.Background(), &pb.DeleteFileShareOpts{
		Context: c.NewAdminContext().ToJson(),
	}).Return(&pb.GenericResponse{}, nil)

	return &FileSharePortal{
		CtrClient: mockClient,
	}
}

////////////////////////////////////////////////////////////////////////////////
//                            Tests for FileShare                             //
////////////////////////////////////////////////////////////////////////////////

var (
	fakeFileShare = &model.FileShareSpec{
		BaseModel: &model.BaseModel{
			Id:        "f4a5e666-c669-4c64-a2a1-8f9ecd560c78",
			CreatedAt: "2017-10-24T16:21:32",
		},
		Name:             "fake FileShare",
		Description:      "fake FileShare",
		Size:             99,
		AvailabilityZone: "unknown",
		Status:           "available",
		PoolId:           "831fa5fb-17cf-4410-bec6-1f4b06208eef",
		ProfileId:        "d3a109ff-3e51-4625-9054-32604c79fa90",
	}
	fakeFileShares = []*model.FileShareSpec{fakeFileShare}
)

func TestListFileShares(t *testing.T) {

	t.Run("Should return 200 if everything works well", func(t *testing.T) {
		var sampleFileShares = []*model.FileShareSpec{&SampleFileShares[0], &SampleFileShares[1]}
		mockClient := new(dbtest.Client)
		m := map[string][]string{
			"offset":  {"0"},
			"limit":   {"1"},
			"sortDir": {"asc"},
			"sortKey": {"name"},
		}
		mockClient.On("ListFileSharesWithFilter", c.NewAdminContext(), m).Return(sampleFileShares, nil)
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/shares?offset=0&limit=1&sortDir=asc&sortKey=name", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)

		var output []*model.FileShareSpec
		json.Unmarshal(w.Body.Bytes(), &output)
		assertTestResult(t, w.Code, 200)
		assertTestResult(t, output, sampleFileShares)
	})

	t.Run("Should return 500 if list file share with bad request", func(t *testing.T) {
		mockClient := new(dbtest.Client)
		m := map[string][]string{
			"offset":  {"0"},
			"limit":   {"1"},
			"sortDir": {"asc"},
			"sortKey": {"name"},
		}
		mockClient.On("ListFileSharesWithFilter", c.NewAdminContext(), m).Return(nil, errors.New("db error"))
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/shares?offset=0&limit=1&sortDir=asc&sortKey=name", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		assertTestResult(t, w.Code, 500)
	})
}

func TestGetFileShare(t *testing.T) {

	t.Run("Should return 200 if everything works well", func(t *testing.T) {
		mockClient := new(dbtest.Client)
		mockClient.On("GetFileShare", c.NewAdminContext(), "bd5b12a8-a101-11e7-941e-d77981b584d8").Return(&SampleFileShares[0], nil)
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/shares/bd5b12a8-a101-11e7-941e-d77981b584d8", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)

		var output model.FileShareSpec
		json.Unmarshal(w.Body.Bytes(), &output)
		assertTestResult(t, &output, &SampleFileShares[0])
	})

	t.Run("Should return 404 if get file share replication with bad request", func(t *testing.T) {
		mockClient := new(dbtest.Client)
		mockClient.On("GetFileShare", c.NewAdminContext(), "bd5b12a8-a101-11e7-941e-d77981b584d8").Return(nil, errors.New("db error"))
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/shares/bd5b12a8-a101-11e7-941e-d77981b584d8", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		assertTestResult(t, w.Code, 404)
	})
}

func TestUpdateFileShare(t *testing.T) {
	var jsonStr = []byte(`{
		"id": "bd5b12a8-a101-11e7-941e-d77981b584d8",
		"name":"fake FileShare",
		"description":"fake Fileshare"
	}`)
	var expectedJson = []byte(`{
		"id": "bd5b12a8-a101-11e7-941e-d77981b584d8",
		"name": "fake FileShare",
		"description": "fake FileShare",
		"size": 1,
		"status": "available",
		"poolId": "084bf71e-a102-11e7-88a8-e31fe6d52248",
		"profileId": "1106b972-66ef-11e7-b172-db03f3689c9c"
	}`)
	var expected model.FileShareSpec
	json.Unmarshal(expectedJson, &expected)

	t.Run("Should return 200 if everything works well", func(t *testing.T) {
		fileshare := model.FileShareSpec{BaseModel: &model.BaseModel{}}
		json.NewDecoder(bytes.NewBuffer(jsonStr)).Decode(&fileshare)
		mockClient := new(dbtest.Client)
		mockClient.On("UpdateFileShare", c.NewAdminContext(), &fileshare).Return(&expected, nil)
		db.C = mockClient

		r, _ := http.NewRequest("PUT", "/v1beta/file/shares/bd5b12a8-a101-11e7-941e-d77981b584d8", bytes.NewBuffer(jsonStr))
		w := httptest.NewRecorder()
		r.Header.Set("Content-Type", "application/JSON")
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		var output model.FileShareSpec
		json.Unmarshal(w.Body.Bytes(), &output)
		assertTestResult(t, w.Code, 200)
		assertTestResult(t, &output, &expected)
	})

	t.Run("Should return 500 if update file share with bad request", func(t *testing.T) {
		fileshare := model.FileShareSpec{BaseModel: &model.BaseModel{}}
		json.NewDecoder(bytes.NewBuffer(jsonStr)).Decode(&fileshare)
		mockClient := new(dbtest.Client)
		mockClient.On("UpdateFileShare", c.NewAdminContext(), &fileshare).Return(nil, errors.New("db error"))
		db.C = mockClient

		r, _ := http.NewRequest("PUT", "/v1beta/file/shares/bd5b12a8-a101-11e7-941e-d77981b584d8", bytes.NewBuffer(jsonStr))
		w := httptest.NewRecorder()
		r.Header.Set("Content-Type", "application/JSON")
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		assertTestResult(t, w.Code, 500)
	})
}

////////////////////////////////////////////////////////////////////////////////
//                      Tests for fileshare snapshot                          //
////////////////////////////////////////////////////////////////////////////////

func TestListFileShareSnapshots(t *testing.T) {

	t.Run("Should return 200 if everything works well", func(t *testing.T) {
		var sampleSnapshots = []*model.FileShareSnapshotSpec{&SampleFileShareSnapshots[0], &SampleFileShareSnapshots[1]}
		mockClient := new(dbtest.Client)
		m := map[string][]string{
			"offset":  {"0"},
			"limit":   {"1"},
			"sortDir": {"asc"},
			"sortKey": {"name"},
		}
		mockClient.On("ListFileShareSnapshotsWithFilter", c.NewAdminContext(), m).Return(sampleSnapshots, nil)
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/snapshots?offset=0&limit=1&sortDir=asc&sortKey=name", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)

		var output []*model.FileShareSnapshotSpec
		json.Unmarshal(w.Body.Bytes(), &output)
		assertTestResult(t, w.Code, 200)
		assertTestResult(t, output, sampleSnapshots)
	})

	t.Run("Should return 500 if list fileshare snapshots with bad request", func(t *testing.T) {
		mockClient := new(dbtest.Client)
		m := map[string][]string{
			"offset":  {"0"},
			"limit":   {"1"},
			"sortDir": {"asc"},
			"sortKey": {"name"},
		}
		mockClient.On("ListFileShareSnapshotsWithFilter", c.NewAdminContext(), m).Return(nil, errors.New("db error"))
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/snapshots?offset=0&limit=1&sortDir=asc&sortKey=name", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		assertTestResult(t, w.Code, 500)
	})
}

func TestGetFileShareSnapshot(t *testing.T) {

	t.Run("Should return 200 if everything works well", func(t *testing.T) {
		mockClient := new(dbtest.Client)
		mockClient.On("GetFileShareSnapshot", c.NewAdminContext(), "3769855c-a102-11e7-b772-17b880d2f537").Return(&SampleFileShareSnapshots[0], nil)
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/snapshots/3769855c-a102-11e7-b772-17b880d2f537", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		var output model.FileShareSnapshotSpec
		json.Unmarshal(w.Body.Bytes(), &output)
		assertTestResult(t, w.Code, 200)
		assertTestResult(t, &output, &SampleFileShareSnapshots[0])
	})

	t.Run("Should return 404 if get fileshare group with bad request", func(t *testing.T) {
		mockClient := new(dbtest.Client)
		mockClient.On("GetFileShareSnapshot", c.NewAdminContext(), "3769855c-a102-11e7-b772-17b880d2f537").Return(nil, errors.New("db error"))
		db.C = mockClient

		r, _ := http.NewRequest("GET", "/v1beta/file/snapshots/3769855c-a102-11e7-b772-17b880d2f537", nil)
		w := httptest.NewRecorder()
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		assertTestResult(t, w.Code, 404)
	})
}

func TestUpdateFileShareSnapshot(t *testing.T) {
	var jsonStr = []byte(`{
		"id": "3769855c-a102-11e7-b772-17b880d2f537",
		"name":"fake snapshot",
		"description":"fake snapshot"
	}`)
	var expectedJson = []byte(`{
		"id": "3769855c-a102-11e7-b772-17b880d2f537",
		"name": "fake snapshot",
		"description": "fake snapshot",
		"size": 1,
		"status": "available",
		"fileshareId": "bd5b12a8-a101-11e7-941e-d77981b584d8"
	}`)
	var expected model.FileShareSnapshotSpec
	json.Unmarshal(expectedJson, &expected)

	t.Run("Should return 200 if everything works well", func(t *testing.T) {
		snapshot := model.FileShareSnapshotSpec{BaseModel: &model.BaseModel{}}
		json.NewDecoder(bytes.NewBuffer(jsonStr)).Decode(&snapshot)
		mockClient := new(dbtest.Client)
		mockClient.On("UpdateFileShareSnapshot", c.NewAdminContext(), snapshot.Id, &snapshot).
			Return(&expected, nil)
		db.C = mockClient

		r, _ := http.NewRequest("PUT", "/v1beta/file/snapshots/3769855c-a102-11e7-b772-17b880d2f537", bytes.NewBuffer(jsonStr))
		w := httptest.NewRecorder()
		r.Header.Set("Content-Type", "application/JSON")
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		var output model.FileShareSnapshotSpec
		json.Unmarshal(w.Body.Bytes(), &output)
		assertTestResult(t, w.Code, 200)
		assertTestResult(t, &output, &expected)
	})

	t.Run("Should return 500 if update fileshare snapshot with bad request", func(t *testing.T) {
		snapshot := model.FileShareSnapshotSpec{BaseModel: &model.BaseModel{}}
		json.NewDecoder(bytes.NewBuffer(jsonStr)).Decode(&snapshot)
		mockClient := new(dbtest.Client)
		mockClient.On("UpdateFileShareSnapshot", c.NewAdminContext(), snapshot.Id, &snapshot).
			Return(nil, errors.New("db error"))
		db.C = mockClient

		r, _ := http.NewRequest("PUT", "/v1beta/file/snapshots/3769855c-a102-11e7-b772-17b880d2f537", bytes.NewBuffer(jsonStr))
		w := httptest.NewRecorder()
		r.Header.Set("Content-Type", "application/JSON")
		beego.InsertFilter("*", beego.BeforeExec, func(httpCtx *context.Context) {
			httpCtx.Input.SetData("context", c.NewAdminContext())
		})
		beego.BeeApp.Handlers.ServeHTTP(w, r)
		assertTestResult(t, w.Code, 500)
	})
}


text:
//----------------------------------------------------------------------------//
//                                                                            //
// Z80 Emulator CP/M 2.2 libabry (c) 2017 Søren Amtorp                        //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
//----------------------------------------------------------------------------//
//
// BdosEmulator
//

using System;
using Z80lib;
using Z80cpm22.Device;

namespace Z80cpm22.BdosEmulator
{
    public class BdosEmulator
    {
        IBox vBox;
        Bios vBios;
        Bdos vBdos;
        ICharDevice vConsole;

        public Bios Bios
        {
            get
            {
                return vBios;
            }
        }
        public Bdos Bdos
        {
            get
            {
                return vBdos;
            }
        }
        public ICharDevice Console
        {
            get
            {
                return vConsole;
            }
        }
        public IBox Box
        {
            get
            {
                return vBox;
            }
        }

        public BdosEmulator(IBox pBox, ICharDevice pConsole)
        {
            vBox = pBox;
            vConsole = pConsole;
            vBios = new Bios(this);
            vBdos = new Bdos(this);
        }

        public void MountDrive(int pDriveNo, string pPath)
        {
            vBdos.MountDrive(pDriveNo, pPath);
        }

        public void UnmountDrive(int pDriveNo)
        {
            vBdos.UnmountDrive(pDriveNo);
        }
    }
}


text:
from setuptools import setup

setup(
    name="python-goclio",
    packages=['goclio'],
    version='0.0.1',
    author="Ross Crawford-d'Heureuse",
    license="MIT",
    author_email="ross@lawpal.com",
    url="https://github.com/rosscdh/python-goclio",
    description="A python module for using the goclio api",
    zip_safe=False,
    include_package_data=True,
    install_requires = [
        'requests',
        'requests-oauth2',
    ]
)


text:
SUP - Simply Use Parse
===
I developed this application as an exercise to learn more about [Parse](http://parse.com) by implementing the basic functionality behind the popular [Yo app](https://play.google.com/store/apps/details?id=com.justyo).

With this application you can do the following:

1. Create an account
2. Sign into your account
3. Add a friend(s)
4. Send push notification to your friend(s)

Building
===
To build and run this application on your device, follow these steps:

1. Clone this repo

        git clone git@github.com:michaelcarrano/sup.git

2. Import project into [Android Studio](https://developer.android.com/sdk/installing/studio.html)
3. Create an account at [Parse](http://parse.com)
4. Create a Parse app and configure the push notification settings.
5. Add your [App ID](https://github.com/michaelcarrano/sup/blob/master/android/app/src/main/java/com/michaelcarrano/sup/App.java#L13) and [Client Key](https://github.com/michaelcarrano/sup/blob/master/android/app/src/main/java/com/michaelcarrano/sup/App.java#L15)

Contributing
===
Feel free to open a pull request with any bug fixes or new functionality.

It would be awesome if people are interested in contributing this same application but for a different platform such as iOS or Windows Phone.

Download
===
You can download this application from Google Play - [https://play.google.com/store/apps/details?id=com.michaelcarrano.sup](https://play.google.com/store/apps/details?id=com.michaelcarrano.sup)

License
===

    Copyright 2013 Michael Carrano

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text: Simple .NET C# app to transform a XML based in a XSL and generate a text output


text:
from app.users.decorator import handle_user_cookie as user_handler
del decorator


text:
package ch5_exrcise;

/**
 * Exercise 5.33
 *
 * (Perfect number) A positive integer is called a perfect number if it is equal to the
 * sum of all of its positive divisors, excluding itself. For example, 6 is the first
 * perfect number because 6 = 3 + 2 + 1 . The next is 28 = 14 + 7 + 4 + 2 + 1 .
 * There are four perfect numbers less than 10,000. Write a program to find all these four
 * numbers.
 *
 * @author g3rs0n
 *
 */

public class PerfectNumber {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int sum = 0; int max = 10000;

		for (int i = 2; i <= max; i++) {
			//System.out.println("# " + i);
			for (int j = 1; j <= max - 1; j++) {
				//To print divisors
				if (i % j == 0 && i != j) {
					//System.out.println(j);
					sum += j;
				}
				//System.out.println(sum);
			}
			//System.out.println(sum);

			if (sum == i) {System.out.println(i);}

			sum = 0;
		}

	}

}


text:
using ::std::cout;
using ::std::endl;
using ::std::string;
using ::std::vector;
using ::zippylog::device::Server;
using ::zippylog::device::ServerStartParams;

#ifdef LINUX
static volatile sig_atomic_t active = 1;

void signal_handler(int signo)
{
    active = 0;

    signal(signo, SIG_DFL);
}
#endif

int main(int argc, const char * const argv[])
{
    if (argc < 2) {
        cout << "Usage: zippylogd /path/to/config/file" << endl;
        return 1;
    }

#ifdef LINUX
    // TODO this signal handling is horribly naive
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
#endif

    try {
        ::zippylog::initialize_library();

        ServerStartParams config;
        string error;

        if (!Server::ParseConfig(argv[1], config, error)) {
            cout << "Error loading config file: " << error << endl;
            return 1;
        }

        Server server(config);

#ifdef LINUX
        server.RunAsync();
        while (active) pause();
#elif WINDOWS
        server.Run();
#else
#error "not implemented on this platform"
#endif
    }
    catch (::std::exception e) {
        cout << "Exception: " << e.what() << endl;
        return 1;
    }

    ::zippylog::shutdown_library();

    return 0;
}


text:
package org.jenkinsci.plugins.jenkinsreviewbot;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import hudson.Extension;
import hudson.Launcher;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.*;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import org.jenkinsci.plugins.jenkinsreviewbot.util.Review;
import org.kohsuke.stapler.DataBoundConstructor;

import javax.annotation.Nullable;
import java.util.*;

/**
 * User: ymeymann
 * Date: 9/3/13 1:12 AM
 */
public class ReviewboardPollingBuilder extends Builder {

  private final String reviewbotJobName;
  private final String checkBackPeriod;
  private final int reviewbotRepoId;
  private boolean restrictByUser = true;
  private Set<String> processedReviews = new HashSet<String>();
  private final boolean disableAdvanceNotice;
  private Map<String, Date> processedReviewDates = new HashMap<String, Date>();

  @DataBoundConstructor
  public ReviewboardPollingBuilder(String reviewbotJobName, String checkBackPeriod,
                                   String reviewbotRepoId, boolean restrictByUser, boolean disableAdvanceNotice) {
    this.reviewbotRepoId = reviewbotRepoId == null || reviewbotRepoId.isEmpty() ? -1 : Integer.parseInt(reviewbotRepoId);
    this.restrictByUser = restrictByUser;
    this.reviewbotJobName = reviewbotJobName;
    this.checkBackPeriod = checkBackPeriod;
    this.disableAdvanceNotice = disableAdvanceNotice;
  }

  public String getReviewbotJobName() {
    return reviewbotJobName;
  }

  public String getCheckBackPeriod() {
    return checkBackPeriod;
  }

  public int getReviewbotRepoId() { return reviewbotRepoId; }

  public boolean getRestrictByUser() { return restrictByUser; }

  public boolean getDisableAdvanceNotice() { return disableAdvanceNotice; }

  public String getJenkinsUser() { return ReviewboardNotifier.DESCRIPTOR.getReviewboardUsername(); }

  private Set<Review.Slim> getRichProcessedReviews() {
    if (processedReviews == null) return Collections.emptySet();
    HashSet<Review.Slim> res = new HashSet<Review.Slim>();
    for (String r: processedReviews) {
      res.add(new Review.Slim(r, processedReviewDates == null ? null : processedReviewDates.get(r)));
    }
    return res;
  }

  private void updateProcessed(Collection<Review.Slim> reviews) {
    processedReviews = new HashSet<String>(Collections2.transform(reviews, new Function<Review.Slim, String>() {
      public String apply(@Nullable Review.Slim input) { return input.getUrl(); }
    }));
    if (processedReviewDates == null) { processedReviewDates = new HashMap<String, Date>(); }
    else { processedReviewDates.clear(); }
    for (Review.Slim r: reviews) {
      if (r.getLastUpdate() != null) processedReviewDates.put(r.getUrl(), r.getLastUpdate());
    }
  }

  @Override
  public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
    listener.getLogger().println("Looking for reviews that need building...");
    long period = checkBackPeriod != null && !checkBackPeriod.isEmpty() ? Long.parseLong(checkBackPeriod) : 1L;
    listener.getLogger().println("Going to check reviews updated during last " + period + " hour(s): ");
    ReviewboardConnection con = ReviewboardConnection.fromConfiguration();
    try {
      listener.getLogger().println("Query: " + con.getPendingReviewsUrl(restrictByUser, reviewbotRepoId));
      Collection<Review.Slim> reviews = ReviewboardOps.getInstance().getPendingReviews(con, period, restrictByUser, reviewbotRepoId);
      listener.getLogger().println("Got " + reviews.size() + " reviews");
      Set<Review.Slim> unprocessedReviews = new HashSet<Review.Slim>(reviews);
      if (processedReviews != null) { //apparently, it is null when de-serialized from previous version of plugin... DUH!
        Set<Review.Slim> richProcessed = getRichProcessedReviews();
        unprocessedReviews.removeAll(richProcessed);
      }
      listener.getLogger().println("After removing previously processed, left with " + unprocessedReviews.size() + " reviews");
      updateProcessed(reviews);
      if (unprocessedReviews.isEmpty()) return true;
      Cause cause = new Cause.UpstreamCause((Run<?,?>)build); //TODO not sure what should be put here
      listener.getLogger().println("Setting cause to this build");
      Jenkins jenkins = Jenkins.getInstance();
      AbstractProject project = jenkins.getItem(reviewbotJobName, jenkins, AbstractProject.class);
      if (project == null) {
        listener.getLogger().println("ERROR: Job named " + reviewbotJobName + " not found");
        return false;
      }
      listener.getLogger().println("Found job " + reviewbotJobName);
      for (Review.Slim review : unprocessedReviews) {
        listener.getLogger().println(review.getUrl());
        if (!disableAdvanceNotice) ReviewboardOps.getInstance().postComment(con, review.getUrl(), Messages.ReviewboardPollingBuilder_Notice(), false, false);
        project.scheduleBuild2(project.getQuietPeriod(),
            cause,
            new ParametersAction(new ReviewboardParameterValue("review.url", review.getUrl())));
      }
      return true;
    } catch (Exception e) {
      e.printStackTrace(listener.getLogger());
      return false;
    }
  }

  @Override
  public DescriptorImpl getDescriptor() {
    return (DescriptorImpl) super.getDescriptor();
  }

  @Extension
  public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {

    private Map<String, Integer> repositories = Collections.emptyMap();

    public DescriptorImpl() {
      load();
    }

    private Map<String, Integer> loadRepositories() {
      try {
        return ReviewboardOps.getInstance().getRepositories();
      } catch (Exception e) {
        // TODO how do we properly log this?
        e.printStackTrace();
        return Collections.emptyMap();
      }
    }

    @Override
    public String getDisplayName() {
      return Messages.ReviewboardBuilder_DisplayName();
    }

    @Override
    public boolean isApplicable(Class type) {
      return true;
    }

    public ListBoxModel doFillReviewbotJobNameItems() {
      ListBoxModel items = new ListBoxModel();
      for (AbstractProject project: Jenkins.getInstance().getAllItems(AbstractProject.class)) {
        items.add(project.getName());
      }
      return items;
    }

    public ListBoxModel doFillReviewbotRepoIdItems() {
      // populate list of repositories with (name, id)
      ListBoxModel items = new ListBoxModel();
      // select option to allow polling requests for all repositories
      items.add("-- any --", "-1");
      Map<String, Integer> localRepositories = this.repositories;
      boolean disableCache = ReviewboardNotifier.DESCRIPTOR.getDisableRepoCache();
      //if no repositories or caching disabled - try to load them again
      if (localRepositories.isEmpty() || disableCache) {
        localRepositories = loadRepositories();
      }
      //cache repository list
      repositories = localRepositories;
      // select options to filter by repository id.
      for (Map.Entry<String, Integer> e: localRepositories.entrySet()) {
        items.add(e.getKey(), e.getValue().toString());
      }
      return items;
    }

    @Initializer(before= InitMilestone.PLUGINS_STARTED)
    public static void addAliases() {
      Items.XSTREAM2.addCompatibilityAlias(
          "org.jenkinsci.plugins.jenkinsreviewbot.RevieboardPollingBuilder", ReviewboardPollingBuilder.class);
    }
  }

}


text:
package com.google.javascript.jscomp;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import com.google.common.base.Optional;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Converts async functions to valid ES6 generator functions code.
 *
 *
This pass must run before the passes that transpile let declarations, arrow functions, and
 * generators.
 *
 *
An async function, foo(a, b), will be rewritten as:
 *
 *
 {@code
 * function foo(a, b) {
 *   let $jscomp$async$arguments = arguments;
 *   let $jscomp$async$this = this;
 *   function* $jscomp$async$generator() {
 *     // original body of foo() with:
 *     // - await (x) replaced with yield (x)
 *     // - arguments replaced with $jscomp$async$arguments
 *     // - this replaced with $jscomp$async$this
 *   }
 *   return $jscomp.executeAsyncGenerator($jscomp$async$generator());
 * }}

 */
public final class RewriteAsyncFunctions implements NodeTraversal.Callback, HotSwapCompilerPass {

  private static final String ASYNC_GENERATOR_NAME = "$jscomp$async$generator";
  private static final String ASYNC_ARGUMENTS = "$jscomp$async$arguments";
  private static final String ASYNC_THIS = "$jscomp$async$this";

  /**
   * Keeps track of whether we're examining nodes within an async function & what changes are needed
   * for the function currently in context.
   */
  private static final class LexicalContext {
    final Optional<Node> function; // absent for top level
    final LexicalContext thisAndArgumentsContext;
    boolean mustAddAsyncThisVariable = false;
    boolean mustAddAsyncArgumentsVariable = false;

    /** Creates root-level context. */
    LexicalContext() {
      this.function = Optional.absent();
      this.thisAndArgumentsContext = this;
    }

    LexicalContext(LexicalContext outer, Node function) {
      this.function = Optional.of(function);
      // An arrow function shares 'this' and 'arguments' with its outer scope.
      this.thisAndArgumentsContext =
          function.isArrowFunction() ? outer.thisAndArgumentsContext : this;
    }

    boolean isAsyncContext() {
      return function.isPresent() && function.get().isAsyncFunction();
    }

    boolean mustReplaceThisAndArguments() {
      return isAsyncContext() || thisAndArgumentsContext.isAsyncContext();
    }

    void recordAsyncThisReplacementWasDone() {
      if (thisAndArgumentsContext.isAsyncContext()) {
        thisAndArgumentsContext.mustAddAsyncThisVariable = true;
      } else {
        // The current context is an async arrow function within a non-async function,
        // so it must define its own replacement variable.
        checkState(isAsyncContext());
        mustAddAsyncThisVariable = true;
      }
    }

    void recordAsyncArgumentsReplacementWasDone() {
      if (thisAndArgumentsContext.isAsyncContext()) {
        thisAndArgumentsContext.mustAddAsyncArgumentsVariable = true;
      } else {
        // The current context is an async arrow function within a non-async function,
        // so it must define its own replacement variable.
        checkState(isAsyncContext());
        mustAddAsyncArgumentsVariable = true;
      }
    }
  }

  private final Deque<LexicalContext> contextStack;
  private final AbstractCompiler compiler;

  public RewriteAsyncFunctions(AbstractCompiler compiler) {
    checkNotNull(compiler);
    this.compiler = compiler;
    this.contextStack = new ArrayDeque<>();
    this.contextStack.addFirst(new LexicalContext());
  }

  @Override
  public void process(Node externs, Node root) {
    TranspilationPasses.processTranspile(compiler, root, this);
  }

  @Override
  public void hotSwapScript(Node scriptRoot, Node originalRoot) {
    TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, this);
  }

  @Override
  public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) {
    if (n.isFunction()) {
      contextStack.addFirst(new LexicalContext(contextStack.getFirst(), n));
      if (n.isAsyncFunction()) {
        compiler.ensureLibraryInjected("es6/execute_async_generator", /* force */ false);
      }
    }
    return true;
  }

  @Override
  public void visit(NodeTraversal t, Node n, Node parent) {
    LexicalContext context = contextStack.getFirst();

    if (n.isFunction()) {
      checkState(
          context.function.isPresent() && context.function.get() == n,
          "unexpected function context:\nexpected: %s\nactual: %s",
          n,
          context.function);
      contextStack.removeFirst();
    }
    switch (n.getToken()) {
      case FUNCTION:
        if (context.isAsyncContext()) {
          convertAsyncFunction(context);
        }
        break;

      case NAME:
        if (context.mustReplaceThisAndArguments() && n.matchesQualifiedName("arguments")) {
          n.setString(ASYNC_ARGUMENTS);
          context.recordAsyncArgumentsReplacementWasDone();
        }
        break;

      case THIS:
        if (context.mustReplaceThisAndArguments()) {
          parent.replaceChild(n, IR.name(ASYNC_THIS).useSourceInfoIfMissingFrom(n));
          context.recordAsyncThisReplacementWasDone();
        }
        break;

      case AWAIT:
        checkState(context.isAsyncContext(), "await found within non-async function body");
        checkState(n.hasOneChild(), "await should have 1 operand, but has %s", n.getChildCount());
        // Awaits become yields in the converted async function's inner generator function.
        parent.replaceChild(n, IR.yield(n.removeFirstChild()).useSourceInfoIfMissingFrom(n));
        break;

      default:
        break;
    }
  }

  private void convertAsyncFunction(LexicalContext functionContext) {
    Node originalFunction = functionContext.function.get();
    originalFunction.setIsAsyncFunction(false);
    Node originalBody = originalFunction.getLastChild();
    Node newBody = IR.block().useSourceInfoIfMissingFrom(originalBody);
    originalFunction.replaceChild(originalBody, newBody);

    if (functionContext.mustAddAsyncThisVariable) {
      newBody.addChildToBack(IR.constNode(IR.name(ASYNC_THIS), IR.thisNode()));
    }
    if (functionContext.mustAddAsyncArgumentsVariable) {
      newBody.addChildToBack(IR.constNode(IR.name(ASYNC_ARGUMENTS), IR.name("arguments")));
    }

    // Normalize arrow function short body to block body
    if (!originalBody.isNormalBlock()) {
      originalBody = IR.block(IR.returnNode(originalBody)).useSourceInfoFromForTree(originalBody);
    }
    // NOTE: visit() will already have made appropriate replacements in originalBody so it may
    // be used as the generator function body.
    Node newFunctionName = IR.name(ASYNC_GENERATOR_NAME);
    Node originalName = originalFunction.getFirstChild();
    // Use the source info from the function name. Without this line, we would use the source info
    // from originalBody for the name node near the end of this method.
    newFunctionName.useSourceInfoIfMissingFromForTree(originalName);
    Node generatorFunction = IR.function(newFunctionName, IR.paramList(), originalBody);
    compiler.reportChangeToChangeScope(generatorFunction);
    generatorFunction.setIsGeneratorFunction(true);
    // function* $jscomp$async$generator() { ... }
    newBody.addChildToBack(generatorFunction);

    // return $jscomp.executeAsyncGenerator($jscomp$async$generator());
    Node executeAsyncGenerator = IR.getprop(IR.name("$jscomp"), IR.string("executeAsyncGenerator"));
    newBody.addChildToBack(
        IR.returnNode(
            IR.call(executeAsyncGenerator, NodeUtil.newCallNode(IR.name(ASYNC_GENERATOR_NAME)))));

    newBody.useSourceInfoIfMissingFromForTree(originalBody);
    compiler.reportChangeToEnclosingScope(newBody);
  }
}


text:
pub mod lstd;
pub mod mc;
pub mod td;

// TODO:
// Implement the algorithms discussed in https://arxiv.org/pdf/1304.3999.pdf


text:
namespace Flepper.QueryBuilder
{
    internal partial class QueryBuilder : IFromCommand
    {
        public IFromCommand FromCommand(string schema, string table)
        {
            Command.AppendFormat("FROM [{0}].[{1}] ", schema, table);
            return this;
        }

        public IFromCommand FromCommand(string table)
        {
            Command.AppendFormat("FROM [{0}] ", table);
            return this;
        }
    }
}


text:
import os
import platform

def get_docker_fs(base_path):
    fs_types = ['aufs', 'devicemapper']
    for fs_type in fs_types:
        if os.path.exists(os.path.join(base_path, fs_type)):
            return fs_type
    return 'unknown'

def get_sys_info():
    system = {
              'hostname' : platform.node(),
              'system'  : platform.system(),
              'machine' : platform.machine(),
              'architecture' : platform.architecture(),
              'release' : platform.release(),
              'dist' : platform.dist(),
              'python' : platform.python_version()
              }
    return system


text:
package repositories

import (
	"log"

	"cjdavis.me/elysium/db"
	"cjdavis.me/elysium/library"
)

type AuthorRepository struct {
}

func NewAuthorRepository() *AuthorRepository {
	return &AuthorRepository{}
}

func (self *AuthorRepository) GetAllAuthors() ([]library.Author, error) {
	authors := []library.Author{}

	rows, err := db.AppDB().Query(`
SELECT id, first_name, last_name
FROM author
`)
	if err != nil {
		return authors, err
	}
	defer rows.Close()

	for rows.Next() {
		author := library.Author{}
		err := rows.Scan(&author.ID, &author.FirstName, &author.LastName)
		if err != nil {
			log.Println("Error scanning authors: ", err)
			continue
		}

		authors = append(authors, author)
	}

	err = rows.Err()
	if err != nil {
		log.Println("Error scanning authors: ", err)
	}

	return authors, err
}


text:
#region Copyright

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Kodestruct.Loads.ASCE7.Lateral.Wind.StructureParameters
{
    /// <summary>
    /// Interaction logic for Kodestruct.Loads.ASCE7.Lateral.Wind.StructureParameters.WindDirectionalityCaseIdSelectionView.xaml
    /// </summary>
    public partial class WindDirectionalityCaseIdSelectionView: UserControl
    {
        public WindDirectionalityCaseIdSelectionView()
        {
            InitializeComponent();
        }
    }
}


text:
/*
 * InputOutputOJ.java
 * -- documented
 *
 * methods to load and save project and results
 */
package oj.io;

import java.util.logging.Level;
import java.util.logging.Logger;
import ij.IJ;
import ij.Prefs;
import ij.gui.GenericDialog;
import ij.io.OpenDialog;
import ij.plugin.frame.Editor;
import java.awt.Color;
import java.awt.Font;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.CharArrayReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import oj.OJ;
import oj.gui.menuactions.ProjectActionsOJ;
import oj.gui.results.ProjectResultsOJ;
import oj.gui.settings.ProjectSettingsOJ;
import oj.util.UtilsOJ;
import oj.project.*;
import oj.io.spi.IIOProviderOJ;
import oj.io.spi.IOFactoryOJ;
import oj.macros.EmbeddedMacrosOJ;
import oj.project.results.ColumnsOJ;
import static oj.util.UtilsOJ.showInFinderOrExplorer;

public class InputOutputOJ {

	private static String currentDirectory = "";

	/**
	 * @return directory containing the ojj file
	 */
	public static String getCurrentDirectory() {
		return currentDirectory;
	}

	/**
	 * directory containing the ojj file
	 */
	public static void setCurrentDirectory(String directory) {
		currentDirectory = directory;
	}

	/**
	 * Save embedded macros with project name and txt in project folder and
	 * "double-click" it there
	 */
	public static void exportEmbeddedMacros() {//23-12-2017
		String text = OJ.getData().getLinkedMacroText();
		Editor ed = OJ.editor;
		if (ed != null) {
			text = ed.getText();
		}
		String txtName = OJ.getData().getName() + ".txt";
		String path = getCurrentDirectory() + txtName;
		File f = new File(path);
		if (f.exists() && !f.canWrite()) {
			IJ.showMessage("Editor", "Unable to save because file is write-protected. \n \n" + path);
			return;
		}
		char[] chars = new char[text.length()];
		text.getChars(0, text.length(), chars, 0);
		try {
			BufferedReader br = new BufferedReader(new CharArrayReader(chars));
			BufferedWriter bw = new BufferedWriter(new FileWriter(path));
			while (true) {
				String s = br.readLine();
				if (s == null) {
					break;
				}
				bw.write(s, 0, s.length());
				bw.newLine();
			}
			bw.close();
			IJ.showStatus(text.length() + " chars saved to " + path);

			showInFinderOrExplorer(OJ.getData().getDirectory(), txtName);

			//IJ.runMacro("exec('open', getArgument())", path);
		} catch (IOException e) {
		}
	}

	static String ago(File file) {
		String date = "";
		if (!file.exists()) {
			return date;
		}
		long now = new Date().getTime();
		long modified = file.lastModified();
		long mSecs = now - modified;
		double minutes = ((double) (mSecs)) / 1000 / 60;
		String ago = "  (" + IJ.d2s(minutes, 1) + " minutes ago)";
		if (minutes > 99) {
			ago = "  (" + IJ.d2s(minutes / 60, 1) + " hours ago)";
		}
		if (minutes > 48 * 60) {
			ago = "  (" + IJ.d2s(minutes / 60 / 24, 0) + " days ago)";
		}
		date += (new Date(file.lastModified())).toString() + ago;
		return date;
	}

	/**
	 * Load text file (project name + .txt from project folder and install it as
	 * embedded macros.
	 */
	public static void replaceEmbeddedMacros(boolean withAltKey) {//23-12-2017

		String dir = getCurrentDirectory();
		String fName = OJ.getData().getName() + ".txt";
		String xPath = dir + fName;//exchangePath
		File xFile = new File(xPath);//exchangeFile
		String newMacroText = "";
		boolean xExists = xFile.exists();
		boolean fromOjj = false;
		boolean fromTxt = false;

		if (withAltKey) {
			if (!xExists) {
				IJ.showMessage("Alt key was down, but 'Exchange file' does not exist");
				return;
			}
			newMacroText = IJ.openAsString(xPath);
		}

		if (!withAltKey) {
			String multiLinePath = xPath;
			if (multiLinePath.length() > 80) {
				multiLinePath = multiLinePath.replace("/", "/\n");
			}
			if (!withAltKey) {
				int index = 0;
				Color color = Color.decode("#aa0000");
				if (xExists) {
					index = 1;
					color = Color.decode("#008800");

				}
				GenericDialog gd = new GenericDialog("Replace embedded macro text");
				String[] radios = ("From any .txt or .ojj file;From 'Exchange File' *").split(";");
				gd.addRadioButtonGroup("\nReplace and install embedded macros :", radios, 2, 1, radios[index]);
				int sizeEmbeddedMacros = OJ.getData().getLinkedMacroText().length();

				String msg2 = "";
				if (xExists) {
					msg2 += "\n *'Exchange File' exists:\n";

				} else {
					msg2 += "\n *'Exchange File' does not exist:";
				}
				msg2 += "\n " + multiLinePath;

				if (xExists) {
					msg2 += "\n \nModified:  " + ago(xFile);
					msg2 += "\nSize (bytes): " + xFile.length();;

				}

				gd.addMessage(msg2, Font.decode("Arial-12"), color);

				gd.addMessage("\nEmbedded macros:\nSize (bytes): " + sizeEmbeddedMacros, Font.decode("Arial-12"));

				String msg4 = "\n \n* Note: ";
				msg4 += "\n 'Exchange File' has same name and location as ";
				msg4 += "\n the .ojj project file, but extension is .txt instead .ojj ";
				msg4 += "\n \n It simplifies the installation of embedded macros that were ";
				msg4 += "\n edited elsewhere, but has no function otherwise";
				msg4 += "\n \n This dialog is skipped when the Alt key was down";
				gd.addMessage(msg4, Font.decode("Arial-12"));
				gd.showDialog();
				if (gd.wasCanceled()) {
					return;
				}
				String radioStr = gd.getNextRadioButton();
				if (radioStr.equals(radios[0])) {

					boolean savedFC = Prefs.useJFileChooser;
					if(IJ.isMacOSX())
						Prefs.useJFileChooser = true;
					String fromPath = IJ.getFilePath("Choose .txt or .ojj file to replace embedded macros");
					Prefs.useJFileChooser = savedFC;//15.10.2019
					if(fromPath == null){
						IJ.showStatus("Nothing was imported");
						return;
					}
					int separatorIndex = fromPath.lastIndexOf(File.separator);
					int len = fromPath.length();
					String name = fromPath.substring(separatorIndex + 1, len);
					String projectDir = fromPath.substring(0, separatorIndex);

					if (fromPath.toLowerCase().endsWith(".txt")) {
						xPath = fromPath;
						fromTxt = true;
						newMacroText = IJ.openAsString(xPath);

					} else if (fromPath.toLowerCase().endsWith(".ojj")) {
						newMacroText = extractEmbeddedMacros(projectDir, name);
						fromOjj = true;
					} else {
						IJ.showMessage("Extension must be  '.txt' or '.ojj' :   \nYou chose:\n \n" + fromPath);
					}

				}
				if (radioStr.equals(radios[1])) {
					newMacroText = IJ.openAsString(xPath);
				}
			}
		}

		if (!xExists && !fromOjj && !fromTxt) {
			IJ.showMessage("Cancelled");
			return;
		}

		OJ.getData().setLinkedMacroText(newMacroText);
		EmbeddedMacrosOJ.getInstance().doInstall(newMacroText);
		Editor ed = OJ.editor;
		if (ed != null) {
			ed.getTextArea().setText(newMacroText);
			ed.getTextArea().setSelectionEnd(0);//13.10.2019
			ed.getTextArea().setSelectionStart(0);
			ed.getTextArea().setCaretPosition(0);
			EmbeddedMacrosOJ.getInstance().setEditorUnchanged(ed);//29.3.2021
		}
		int nMacros = OJ.getData().getMacroSet().getMacrosCount();
		IJ.selectWindow("ImageJ");
		IJ.showStatus("*** Installed " + nMacros + " Embedded Macros");
	}
//

//usually there is already a project file that now needs to be overwritten.
//If old project file does not exist, then a warning is issued:
//e.g. the old project file may have been moved or trashed in the Finder.
//now the user can save it under this or a different name.
	/**
	 * saves the project in an .ojj file. old version: xml text is saved
	 * uncompressed new version: binary and macro are put in a compressed zip
	 * archive
	 *
	 * @return true if successful
	 */
	public boolean saveProject(DataOJ data, boolean itsBinary) {
		ij.IJ.showStatus("Saving ObjectJ project...");
		if ((data.getDirectory() != null) && (data.getFilename() != null) && (new File(data.getDirectory(), data.getFilename()).exists())) {
			OJ.getImageProcessor().updateImagesProperties();//verify scaling and stackdimensions when opening and saving a project 16.5.2020
			File f = new File(data.getDirectory(), data.getName() + FileFilterOJ.objectJFileFilter().getExtension());

			if (!oj.OJ.loadedAsBinary) {
				boolean flag = ij.IJ.showMessageWithCancel("Saving Project", "Project file was loaded in XML format, and will now be saved in the newer Binary format.");
				if (!flag) {
					return false;
				}
				oj.OJ.loadedAsBinary = true;
			}
			if (f.exists()&& f.canWrite()) {
				boolean useBinary = OJ.saveAsBinary;//10.4.2010
				return saveProject(data, data.getDirectory(), data.getFilename(), useBinary);
			} else {

			    if(f.exists() && !f.canWrite())
				ij.IJ.showMessage("Cannot overwrite project file");
				boolean pathMayChange = false;
				return saveProjectAs(data, itsBinary, pathMayChange);//, true
			}
		} else {
			boolean pathMayChange = true;
			IJ.showMessage("Couldn't relocate project file on disk");
			return saveProjectAs(data, itsBinary, pathMayChange);//, true
		}
	}

		public boolean saveProjectNew(DataOJ data, boolean itsBinary) {
		ij.IJ.showStatus("Saving ObjectJ project...");
		if ((data.getDirectory() != null) && (data.getFilename() != null) && (new File(data.getDirectory(), data.getFilename()).exists())) {
			File f = new File(data.getDirectory(), data.getName() + FileFilterOJ.objectJFileFilter().getExtension());

			if (!oj.OJ.loadedAsBinary) {
				boolean flag = ij.IJ.showMessageWithCancel("Saving Project", "Project file was loaded in XML format, and will now be saved in the newer Binary format.");
				if (!flag) {
					return false;
				}
				oj.OJ.loadedAsBinary = true;
			}
			if (f.exists() && f.canWrite()) {
				boolean useBinary = true;
				return saveProject(data, data.getDirectory(), data.getFilename(), useBinary);
			} else {
			    if(ij.IJ.showMessageWithCancel("Error","Cannot save project file here, save elsewhere?")){
				boolean pathMayChange = false;
				return saveProjectAs(data, itsBinary, pathMayChange);//, true
			    }
			    return false;
			}
		} else {
			boolean pathMayChange = true;
			IJ.showMessage("Couldn't relocate project file on disk");
			return saveProjectAs(data, itsBinary, pathMayChange);//, true
		}
	}

	/**
	 * Saves a copy of current project for backup
	 */
	public boolean saveACopy(DataOJ data) {
		boolean ok = true;
		String tmpName = data.getName();
		String tmpDir = data.getDirectory();
		String tmpFileName = data.getFilename();
		String fName = data.getName();
		if (fName.length() < 20) {
			fName += "-Copy";
		}
		fName += ".ojj";
		String fNameNoExtension = "";
		String dir = "";
		SaveDialogOJ sd = new SaveDialogOJ("Save a copy of project ...", fName, FileFilterOJ.objectJFileFilter());
		if (sd.isApproved()) {
			try {
				fName = sd.getFilename();
				dir = sd.getDirectory();
				int index = fName.lastIndexOf(".");
				fNameNoExtension = fName;
				if (index > 0) {
					fNameNoExtension = fName.substring(0, index);
				}

			} catch (Exception e) {
				IJ.error("error 5456");
				ok = false;
			}
			if (ok) {
				try {
					data.setName(fNameNoExtension);
					IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject");
					ioProvider.saveProject(data, dir, fName);

				} catch (Exception e) {
					IJ.error("error 9843");
					ok = false;
				}
			}
		}
		//data.setImages(tmpImages);
		//data.setCells(tmpCells);
		data.setName(tmpName);
		data.setDirectory(tmpDir);
		data.setFilename(tmpFileName);
		return ok;
	}

	/**
	 * Sets Images and Cells temporarily to zero and saves an empty copy, so it
	 * can be used for a similar experiment. All other information is retained:
	 * macros, object defs, column defs. Caution: unlinked columns are not
	 * emptied.
	 */
	public boolean saveEmptyProject(DataOJ data) {
		boolean ok = true;
		CellsOJ tmpCells = data.getCells();
		ImagesOJ tmpImages = data.getImages();
		String tmpName = data.getName();
		String tmpDir = data.getDirectory();
		String tmpFileName = data.getFilename();
		data.setCells(new CellsOJ());
		data.setImages(new ImagesOJ());
		String fName = "Untitled.ojj";
		String fNameNoExtension = "";
		String dir = "";
		SaveDialogOJ sd = new SaveDialogOJ("Save empty copy ...", fName, FileFilterOJ.objectJFileFilter());
		if (sd.isApproved()) {
			try {
				fName = sd.getFilename();
				dir = sd.getDirectory();
				int index = fName.lastIndexOf(".");
				fNameNoExtension = fName;
				if (index > 0) {
					fNameNoExtension = fName.substring(0, index);
				}

			} catch (Exception e) {
				IJ.error("error 9895");
				ok = false;
			}
			if (ok) {
				try {
					data.setName(fNameNoExtension);
					IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject");
					ioProvider.saveProject(data, dir, fName);

				} catch (Exception e) {
					IJ.error("error 8871");
					ok = false;
				}
			}
		}
		data.setImages(tmpImages);
		data.setCells(tmpCells);
		data.setName(tmpName);
		data.setDirectory(tmpDir);
		data.setFilename(tmpFileName);
		return ok;
	}

	/**
	 * will only be used in the new zipped version which contains the macro
	 */
	//public boolean saveProjectAs(DataOJ data, boolean itsBinary, boolean saveACopy/*, boolean withContent*/) {
	public boolean saveProjectAs(DataOJ data, boolean itsBinary, boolean pathMayChange) {

		boolean ok = false;

		if (data != null) {
			String oldDir = data.getDirectory();
			String oldFileName = data.getFilename();
			String oldProjectName = data.getName();

			String newDir = "";
			String newFileName = "";
			String newProjectName = "";

			String defaultName = data.getName();
			if ((data.getFilename() != null) && (!data.getFilename().equals(""))) {
				int index = data.getFilename().lastIndexOf(".");
				if (index > 0) {
					defaultName = data.getFilename().substring(0, index);
				}
			} else {
				defaultName = "Untitled";
			}
			SaveDialogOJ sd;
			if (itsBinary) {
				sd = new SaveDialogOJ("Save project ...", defaultName, FileFilterOJ.objectJFileFilter());
			} else {
				sd = new SaveDialogOJ("Save project ...", defaultName, FileFilterOJ.xmlFileFilter());
			}
			if (sd.isApproved()) {
				try {
					newFileName = sd.getFilename();
					newDir = sd.getDirectory();
					int index = sd.getFilename().lastIndexOf(".");
					if (index > 0) {
						newProjectName = sd.getFilename().substring(0, index);
					}

					data.setName(newProjectName);
					ok = saveProject(data, sd.getDirectory(), sd.getFilename(), itsBinary);//30.9.2010

				} catch (Exception e) {
					IJ.error("OJ_Prefs.txt contains binary=true?");
					ok = false;
				}
			} else {
				ok = false;
			}

			if (!pathMayChange) {
				data.setDirectory(oldDir);
				data.setFilename(oldFileName);
				data.setName(oldProjectName);
			} else {
				data.setDirectory(newDir);
				data.setFilename(newFileName);
				data.setName(newProjectName);
			}
		}
		OJ.isProjectOpen = true;//4.10.2010
		return ok;

	}

	/**
	 * saves current project under same name. depending on flag "asBinary",
	 * selects either "xmlstream" or "javaobject" provider, then calls that
	 * provider's "saveProject()" method. Before saving, killBadCells() removes
	 * cells with zero ytems, and ytems with zero points
	 *
	 * @return true if successful
	 */
	private boolean saveProject(DataOJ data, String directory, String filename, boolean asBinary) {
		//asBinary = false;
		int error = 6004;
		if (data != null) {
			data.getCells().killBadCells();

			data.setDescription(data.xmlComment);

		}
		try {
			data.setFilename(filename);
			data.setDirectory(directory);
			error = 6005;
			data.getResults().recalculate();
			error = 6006;
			data.updateChangeDate();
			if (asBinary) {
				IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject");
				ioProvider.saveProject(data, directory, filename);
				return true;
			} else {
				error = 6007;
				IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("xmlstream");
				error = 6008;
				ioProvider.saveProject(data, directory, filename);
				return true;
			}
		} catch (Exception e) {
			IJ.error("error = " + error + ":  " + e.getMessage());
			return false;
		}
	}

	/**
	 * Called by ResultActionsOJ to save results as text
	 */
	public void saveResultsAsText(String txt, String defaultName) {
		DataOJ data = oj.OJ.getData();
		if (data != null) {
			OpenDialog.setDefaultDirectory(data.getDirectory());//26.8.2010
		}
		SaveDialogOJ sd = new SaveDialogOJ("Save results ...", defaultName, FileFilterOJ.objectResultTextFileFilter());
		if (sd.isApproved()) {
			try {
				FileWriter fos = new FileWriter(new File(sd.getDirectory(), sd.getFilename()));
				PrintWriter out = new PrintWriter(fos);
				out.println(txt);
				out.close();
			} catch (Exception e) {
				IJ.error("error 3365: " + e.getMessage());
			}

		}
	}

	/**
	 * Asks to load a project
	 */
	public DataOJ loadProjectWithDialog() {
		OpenDialogOJ od = new OpenDialogOJ("Open ObjectJ project ...", FileFilterOJ.objectJFileFilter());
		if (od.isApproved()) {
			return loadAProject(od.getDirectory(), od.getFilename());
		} else {
			return null;
		}

	}

	public static String extractEmbeddedMacros(String directory, String filename) {
		String macros = null;
		String theType = UtilsOJ.getFileType(directory, filename);
		try {
			if (theType.startsWith("isZipped")) {
				IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject");
				macros = ioProvider.extractMacros(directory, filename);
			}
		} catch (ProjectIOExceptionOJ ex) {
			Logger.getLogger(InputOutputOJ.class.getName()).log(Level.SEVERE, null, ex);
			IJ.showMessage(ex.getMessage());
			return null;
		}
		return macros;
	}

	/**
	 * Depending on file type, selects either the "xmlstream" or the "javaobject
	 * provider, then calls that provider's "loadProject" method.
	 *
	 * @return dataOJ or null
	 */
	public DataOJ loadAProject(String directory, String filename) {

		ProjectSettingsOJ.close();//23-3-2020
		DataOJ dataOj = null;
		OJ.editor = null;
		ProjectResultsOJ.kill();//18.11.2018
		//OJ.doubleBuffered = false; //10.2.2011
		String theType = UtilsOJ.getFileType(directory, filename);
		try {
			if (theType.startsWith("isZipped")) {
				IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("javaobject");
				dataOj = ioProvider.loadProject(directory, filename);
				oj.OJ.loadedAsBinary = true;
				OJ.isProjectOpen = true;
			} else {
				IIOProviderOJ ioProvider = IOFactoryOJ.getFactory().getProvider("xmlstream");
				if (ioProvider.isValidData(directory, filename)) {
					IJ.showStatus("Please wait while loading project file ...");
					dataOj = ioProvider.loadProject(directory, filename);
					oj.OJ.loadedAsBinary = false;
					OJ.isProjectOpen = true;
				}
			}
		} catch (ProjectIOExceptionOJ ex) {
			Logger.getLogger(InputOutputOJ.class.getName()).log(Level.SEVERE, null, ex);
			IJ.showMessage(ex.getMessage());
			return null;
		}

		if (dataOj != null) {//repair if z=0
			int nCells = dataOj.getCells().getCellsCount();
			int hits = 0;
			boolean repairFlag = false;
			for (int pass = 1; pass <= 2; pass++) {
				for (int jj = 0; jj < nCells; jj++) {
					CellOJ cell = dataOj.getCells().getCellByIndex(jj);
					int nYtems = cell.getYtemsCount();
					for (int ytm = 0; ytm < nYtems; ytm++) {
						YtemOJ ytem = cell.getYtemByIndex(ytm);
						int slice = ytem.getStackIndex();
						for (int ll = 0; ll < ytem.getLocationsCount(); ll++) {
							double z = ytem.getLocation(ll).z;
							if (z == 0.0) {
								hits++;
								if (repairFlag) {
									ytem.getLocation(ll).z = slice;
								}
							}
						}
					}
				}
				if (pass == 1 && hits > 0) {
					repairFlag = ij.IJ.showMessageWithCancel("", "Found coordinates z==0; Repair?\n (you should click \"OK\")");
				}
			}
		}

		try {
			dataOj.getResults().getColumns().fixColumnsOrder();//2.2.2014

		} catch (Exception e) {
			IJ.showMessage("Exception 1878: " + e.toString());
		}
		ColumnsOJ columns = dataOj.getResults().getColumns();
		String titles[] = columns.columnNamesToArray();
		int max = titles.length;
		int nUnlinked = 0;
			for (int jj = max - 1; jj >= 0; jj--) {
			if (titles[jj].startsWith("_")){
				columns.removeColumnByIndex(jj);
				nUnlinked++;
				if(nUnlinked == 1){
					IJ.log("\\Clear");
					IJ.log("--- Unlinked columns: ---");
				}
				IJ.log(titles[jj]);
			}

		}
		if(nUnlinked > 0){
		    //IJ.runMacro("waitForUser;");

			String msg = "This project file contains unlinked results";
			msg +="\nwhich are not supported after ObjectJ version 1.04w";

			msg += "\n \nFor keeping this project file untouched,";
			msg +="\nclick 'OK' and choose  'ObjectJ>Project>Close Project'";
			msg +="\n \nOtherwise continue without unlinked results";

			String version = "ObjectJ " + OJ.releaseVersion;
			IJ.showMessage(version, msg);
		}
		dataOj.setChanged(false);
		return dataOj;
	}

	/**
	 *
	 * Special exception object for project IO doesn't do anything special
	 */
	public static class ProjectIOExceptionOJ extends Exception {

		public ProjectIOExceptionOJ(String message) {
			super(message);
		}
	}

}


text:
package archive

import (
	"context"
	"fmt"
	"runtime"

	"go-common/app/interface/main/app-player/conf"
	"go-common/app/interface/main/app-player/model/archive"
	arcrpc "go-common/app/service/main/archive/api"
	"go-common/library/cache/memcache"
	"go-common/library/log"
)

// Dao is archive dao.
type Dao struct {
	// memcache
	arcMc *memcache.Pool
	// chan
	mCh chan func()
	// rpc
	arcRPC arcrpc.ArchiveClient
}

// New new a archive dao.
func New(c *conf.Config) (d *Dao) {
	d = &Dao{
		// memcache
		arcMc: memcache.NewPool(c.Memcache),
		// mc proc
		mCh: make(chan func(), 1024),
	}
	var err error
	d.arcRPC, err = arcrpc.NewClient(c.ArchiveClient)
	if err != nil {
		panic(fmt.Sprintf("archive NewClient error(%v)", err))
	}
	for i := 0; i < runtime.NumCPU(); i++ {
		go d.cacheproc()
	}
	return
}

// Ping ping check memcache connection
func (d *Dao) Ping(c context.Context) (err error) {
	return d.pingMC(c)
}

// addCache add archive to mc or redis
func (d *Dao) addCache(f func()) {
	select {
	case d.mCh <- f:
	default:
		log.Warn("cacheproc chan full")
	}
}

// cacheproc write memcache and stat redis use goroutine
func (d *Dao) cacheproc() {
	for {
		f, ok := <-d.mCh
		if !ok {
			return
		}
		f()
	}
}

// ArchiveCache is
func (d *Dao) ArchiveCache(c context.Context, aid int64) (arc *archive.Info, err error) {
	if arc, err = d.archiveCache(c, aid); err != nil {
		log.Error("%+v", err)
		err = nil
	}
	if arc != nil {
		return
	}
	var (
		view *arcrpc.ViewReply
		cids []int64
	)
	if view, err = d.arcRPC.View(c, &arcrpc.ViewRequest{Aid: aid}); err != nil {
		log.Error("d.arcRPC.View3(%d) error(%+v)", aid, err)
		return
	}
	for _, p := range view.Pages {
		cids = append(cids, p.Cid)
	}
	arc = &archive.Info{
		Aid:       view.Arc.Aid,
		State:     view.Arc.State,
		Mid:       view.Arc.Author.Mid,
		Cids:      cids,
		Attribute: view.Arc.Attribute,
	}
	d.addCache(func() {
		d.addArchiveCache(context.Background(), aid, arc)
	})
	return
}

// Views is
func (d *Dao) Views(c context.Context, aids []int64) (arcs map[int64]*archive.Info, err error) {
	var reply *arcrpc.ViewsReply
	if reply, err = d.arcRPC.Views(c, &arcrpc.ViewsRequest{Aids: aids}); err != nil {
		return
	}
	arcs = make(map[int64]*archive.Info)
	for _, v := range reply.Views {
		var (
			info = new(archive.Info)
			cids []int64
		)
		info.Aid = v.Arc.Aid
		info.State = v.Arc.State
		info.Mid = v.Arc.Author.Mid
		info.Attribute = v.Arc.Attribute
		for _, p := range v.Pages {
			cids = append(cids, p.Cid)
		}
		info.Cids = cids
		arcs[info.Aid] = info
	}
	return
}


text:
@interface GUCFilterCollectionViewController : UICollectionViewController

@end


text:
import logging
import unittest
from retrying import retry

from google.cloud.logging import DESCENDING
import google.cloud.logging

import test_util

class TestCustomLogging(unittest.TestCase):
    def __init__(self, url, methodName='runTest'):
        self._url = url + test_util.CUSTOM_LOGGING_ENDPOINT
        super(TestCustomLogging, self).__init__()

    def runTest(self):
        logging.debug('Posting to endpoint: {0}'.format(self._url))

        payloads = test_util.generate_logging_payloads()
        for payload in payloads:
            _, response_code = test_util.post(self._url, payload)
            if response_code != 0:
                self.fail('Error encountered inside '
                          'sample application!')

            client = google.cloud.logging.Client()
            log_name = payload.get('log_name')
            token = payload.get('token')
            level = payload.get('level')

            logging.info('log name is {0}, '
                         'token is {1}, '
                         'level is {2}'.format(log_name, token, level))

            project_id = test_util.project_id()

            FILTER = 'logName = ' \
                     '"projects/{0}/logs/{1}" ' \
                     'AND (textPayload:{2} OR jsonPayload.message:*) ' \
                     'AND severity = "{3}"'.format(project_id,
                                                   log_name,
                                                   test_util.LOGGING_PREFIX,
                                                   level)

            logging.info('logging filter: {0}'.format(FILTER))

            self.assertTrue(
                self._read_log(client, token, FILTER),
                'Log entry not found for posted token!')

    @retry(wait_fixed=4000, stop_max_attempt_number=8)
    def _read_log(self, client, token, FILTER):
        iterator = client.list_entries(filter_=FILTER,
                                       order_by=DESCENDING,
                                       page_size=10)
        first_page = next(iterator.pages)
        # Only check the first page
        for entry in first_page:
            logging.debug(entry.payload)
            if (token in entry.payload or
                    isinstance(entry.payload, dict) and
                    token in entry.payload.get('message')):
                logging.info('Token {0} found in '
                             'Stackdriver logs!'.format(token))
                return True
        raise Exception('Log entry not found for posted token!')