text:
/* crypto/asn1/a_utctm.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 *
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 *
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 *
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdio.h>
#include <time.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include "asn1_locl.h"

int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
{
    static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
    static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
    char *a;
    int n, i, l, o;

    if (d->type != V_ASN1_UTCTIME)
        return (0);
    l = d->length;
    a = (char *)d->data;
    o = 0;

    if (l < 11)
        goto err;
    for (i = 0; i < 6; i++) {
        if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
            i++;
            if (tm)
                tm->tm_sec = 0;
            break;
        }
        if ((a[o] < '0') || (a[o] > '9'))
            goto err;
        n = a[o] - '0';
        if (++o > l)
            goto err;

        if ((a[o] < '0') || (a[o] > '9'))
            goto err;
        n = (n * 10) + a[o] - '0';
        if (++o > l)
            goto err;

        if ((n < min[i]) || (n > max[i]))
            goto err;
        if (tm) {
            switch (i) {
            case 0:
                tm->tm_year = n < 50 ? n + 100 : n;
                break;
            case 1:
                tm->tm_mon = n - 1;
                break;
            case 2:
                tm->tm_mday = n;
                break;
            case 3:
                tm->tm_hour = n;
                break;
            case 4:
                tm->tm_min = n;
                break;
            case 5:
                tm->tm_sec = n;
                break;
            }
        }
    }
    if (a[o] == 'Z')
        o++;
    else if ((a[o] == '+') || (a[o] == '-')) {
        int offsign = a[o] == '-' ? -1 : 1, offset = 0;
        o++;
        if (o + 4 > l)
            goto err;
        for (i = 6; i < 8; i++) {
            if ((a[o] < '0') || (a[o] > '9'))
                goto err;
            n = a[o] - '0';
            o++;
            if ((a[o] < '0') || (a[o] > '9'))
                goto err;
            n = (n * 10) + a[o] - '0';
            if ((n < min[i]) || (n > max[i]))
                goto err;
            if (tm) {
                if (i == 6)
                    offset = n * 3600;
                else if (i == 7)
                    offset += n * 60;
            }
            o++;
        }
        if (offset && !OPENSSL_gmtime_adj(tm, 0, offset * offsign))
            return 0;
    }
    return o == l;
 err:
    return 0;
}

int ASN1_UTCTIME_check(const ASN1_UTCTIME *d)
{
    return asn1_utctime_to_tm(NULL, d);
}

int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str)
{
    ASN1_UTCTIME t;

    t.type = V_ASN1_UTCTIME;
    t.length = strlen(str);
    t.data = (unsigned char *)str;
    if (ASN1_UTCTIME_check(&t)) {
        if (s != NULL) {
            if (!ASN1_STRING_set((ASN1_STRING *)s,
                                 (unsigned char *)str, t.length))
                return 0;
            s->type = V_ASN1_UTCTIME;
        }
        return (1);
    } else
        return (0);
}

ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t)
{
    return ASN1_UTCTIME_adj(s, t, 0, 0);
}

ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
                               int offset_day, long offset_sec)
{
    char *p;
    struct tm *ts;
    struct tm data;
    size_t len = 20;
    int free_s = 0;

    if (s == NULL) {
        s = ASN1_UTCTIME_new();
        if (s == NULL)
            goto err;
        free_s = 1;
    }

    ts = OPENSSL_gmtime(&t, &data);
    if (ts == NULL)
        goto err;

    if (offset_day || offset_sec) {
        if (!OPENSSL_gmtime_adj(ts, offset_day, offset_sec))
            goto err;
    }

    if ((ts->tm_year < 50) || (ts->tm_year >= 150))
        goto err;

    p = (char *)s->data;
    if ((p == NULL) || ((size_t)s->length < len)) {
        p = OPENSSL_malloc(len);
        if (p == NULL) {
            ASN1err(ASN1_F_ASN1_UTCTIME_ADJ, ERR_R_MALLOC_FAILURE);
            goto err;
        }
        OPENSSL_free(s->data);
        s->data = (unsigned char *)p;
    }

    BIO_snprintf(p, len, "%02d%02d%02d%02d%02d%02dZ", ts->tm_year % 100,
                 ts->tm_mon + 1, ts->tm_mday, ts->tm_hour, ts->tm_min,
                 ts->tm_sec);
    s->length = strlen(p);
    s->type = V_ASN1_UTCTIME;
#ifdef CHARSET_EBCDIC_not
    ebcdic2ascii(s->data, s->data, s->length);
#endif
    return (s);
 err:
    if (free_s)
        ASN1_UTCTIME_free(s);
    return NULL;
}

int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t)
{
    struct tm stm, ttm;
    int day, sec;

    if (!asn1_utctime_to_tm(&stm, s))
        return -2;

    if (!OPENSSL_gmtime(&t, &ttm))
        return -2;

    if (!OPENSSL_gmtime_diff(&day, &sec, &ttm, &stm))
        return -2;

    if (day > 0)
        return 1;
    if (day < 0)
        return -1;
    if (sec > 0)
        return 1;
    if (sec < 0)
        return -1;
    return 0;
}


text:
    <markdown>
        ### The column definition object is an array of definition objects
        ### The definition object should have properties shown in the example below:
        {
            columnHeaderDisplayName: 'String', // Not Required if columnHeaderTemplate is specified
            columnHeaderTemplate: 'String', // Not Required if columnHeaderDisplayName is specified.
            displayProperty: 'String || Function', // - Not required if templateUrl is specified - which attribute of the item object to render. In case of function, result of the function (item passed to the function) is printed.
            columnSearchProperty: 'String', // - Options - column search property
            cellFilter: 'String', // - Optional - the filter expression to apply to the displayProperty
            templateUrl: 'String', // - Not required if displayProperty is specified - look at artistPicture.html,
            template: 'String', // - Not required if displayProperty or templateUrl specified. - inline template string
            sortKey: 'String || Function', // - Optional - specified key (in most cases: same as displayProperty) will be used for sorting
            width: 'String' // - Optional - the explicitly specify width of the column. (Ex: '10em', '30px'). If not specified, width is calculated automatically based on content width.
            visible: 'Boolean' // - Optional - hide column by setting this to false
        }
    </markdown>

    <markdown>
        ### You perform actions on table externally. This is how you perform external event:
        $scope.$broadcast('adTableAjaxAction', {
            tableName: 'artistsTableSearch', //Name of the table that you are targeting
            action: function (actions) {
                actions.expandCollapseRow(row); //List of exposed action methods and expected params is listed below
            }
        });

        ### Available action methods

        - expandCollapseRow(row):
            params:
                - row: an integer order of row to be expanded or collapsed
    </markdown>

redpajama_set_name: RedPajamaGithub


text:
#import <XCTestBootstrap/FBApplicationDataPackage.h>
#import <XCTestBootstrap/FBDeviceOperator.h>
#import <XCTestBootstrap/FBDeviceTestPreparationStrategy.h>
#import <XCTestBootstrap/FBProductBundle.h>
#import <XCTestBootstrap/FBSimulatorTestPreparationStrategy.h>
#import <XCTestBootstrap/FBTestBundle.h>
#import <XCTestBootstrap/FBTestConfiguration.h>
#import <XCTestBootstrap/FBTestManager.h>
#import <XCTestBootstrap/FBTestManagerAPIMediator.h>
#import <XCTestBootstrap/FBTestManagerJUnitGenerator.h>
#import <XCTestBootstrap/FBTestManagerProcessInteractionDelegate.h>
#import <XCTestBootstrap/FBTestManagerResult.h>
#import <XCTestBootstrap/FBTestManagerResultSummary.h>
#import <XCTestBootstrap/FBTestManagerTestReporter.h>
#import <XCTestBootstrap/FBTestManagerTestReporterBase.h>
#import <XCTestBootstrap/FBTestManagerTestReporterComposite.h>
#import <XCTestBootstrap/FBTestManagerTestReporterJUnit.h>
#import <XCTestBootstrap/FBTestManagerTestReporterTestCase.h>
#import <XCTestBootstrap/FBTestManagerTestReporterTestCaseFailure.h>
#import <XCTestBootstrap/FBTestManagerTestReporterTestSuite.h>
#import <XCTestBootstrap/FBTestReporterForwarder.h>
#import <XCTestBootstrap/FBTestRunnerConfiguration.h>
#import <XCTestBootstrap/FBXCTestManagerLoggingForwarder.h>
#import <XCTestBootstrap/FBXCTestRunStrategy.h>
#import <XCTestBootstrap/XCTestBootstrapError.h>
#import <XCTestBootstrap/XCTestBootstrapFrameworkLoader.h>


text:
'use strict';

membersApp.controller('EventController', [ '$scope', '$rootScope', 'EventService', function($scope, $rootScope, EventService) {
	var self = this;
	self.events;
	self.eventsFilter;
	self.eventsOriginal;
	self.isLastMonth = true;
	$scope.endDate = new Date();
	$scope.enableLastMonth = true;
	self.highlight = highlight;
	self.remove = remove;
	fetchAllEvents();

	function fetchAllEvents() {
		EventService.fetchAllEvents().then(function(d) {
			self.events = d;
			self.eventsOriginal = d;
		}, function(errorResponse) {
			console.error('Error while fetching Events', errorResponse);
		});
	}

	function highlight(id) {
		EventService.highlight(id).then(fetchAllEvents, function(errorResponse) {
			console.error('Error while highlight Event', errorResponse);
		});
	}

	function remove(id) {
		EventService.remove(id).then(fetchAllEvents, function(errorResponse) {
			console.error('Error while highlight Event', errorResponse);
		});
	}

	$rootScope.$on("fetchAllEvents", function() {
		fetchAllEvents();
	});

	$scope.searchDates = function() {
		if ($scope.endDate != null && $scope.startDate != null) {
			self.events = [];
			for (var i = 0; i < self.eventsOriginal.length; i++) {
				var event = self.eventsOriginal[i];
				if (event.dateEvent > $scope.startDate && event.dateEvent <= $scope.endDate) {
					self.events.push(event);
				} else {
					var index = self.events.indexOf(event);
					self.events.splice(index, 1);
				}
			}
		}
	}

	$scope.lastMonth = function() {
		if (self.isLastMonth) {
			var newEvents = [];
			var newDate = new Date();
			var month = newDate.setMonth(newDate.getMonth() - 1)
			for (var i = 0; i < self.events.length; i++) {
				var event = self.events[i];
				if (event.dateEvent > month) {
					newEvents.push(event);
				}
			}
			self.events = newEvents;
		} else {
			self.events = self.eventsOriginal;
		}
		self.isLastMonth = !self.isLastMonth;
	}
} ]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>9</version>
    </parent>

    <groupId>com.arcbees.gss</groupId>
    <artifactId>gsss</artifactId>
    <version>1.1-SNAPSHOT</version>
    <name>GSS on Steroids</name>

    <properties>
        <!-- client -->
        <gwt.version>2.7.0</gwt.version>

        <maven-release-plugin.version>2.5.1</maven-release-plugin.version>

        <gpg.passphrase>SetAsParam</gpg.passphrase>
        <release.fast>-Dcheckstyle.skip -DskipTests -Dmaven.test.skip</release.fast>
    </properties>

    <repositories>
        <repository>
            <id>sonatype.snapshots</id>
            <name>Sonatype snapshot repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <scm>
        <connection>scm:git:git@github.com:ArcBees/gsss.git</connection>
        <developerConnection>scm:git:git@github.com:ArcBees/gsss.git</developerConnection>
        <url>https://github.com/ArcBees/gsss</url>
      <tag>HEAD</tag>
  </scm>

    <build>
        <resources>
            <resource>
                <directory>${basedir}/src/main/java</directory>
            </resource>
            <resource>
                <directory>${basedir}/src/main/resources</directory>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven-release-plugin.version}</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <useReleaseProfile>false</useReleaseProfile>
                    <releaseProfiles>release</releaseProfiles>
                    <arguments>
                        -Psonatype-oss-release -Prelease -Dgpg.passphrase=${gpg.passphrase} ${release.fast}
                    </arguments>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- Google Web Toolkit dependencies -->
        <dependency>
            <groupId>com.google.gwt</groupId>
            <artifactId>gwt-user</artifactId>
            <version>${gwt.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>


text:
Admin Add movies or actors

                <uib-tabset>
                    <uib-tab>
                        <uib-tab-heading> Movies</uib-tab-heading>

                                <button class="btn btn-primary btn-xs" ng-click="addMovie()">Add Movie</button>

                    </uib-tab>
                    <uib-tab>
                        <uib-tab-heading> Actors</uib-tab-heading>

                                <button class="btn btn-primary btn-xs" ng-click="addActor()">Add Actor</button>

                    </uib-tab>

                </uib-tabset>


text:
<?php

namespace Toyotadjakarta\SlideshowsModule\Test\Unit\Intro;

class IntroPresenterTest extends \TestCase
{

}


text:
import sys
import xlrd
import json

from validate_email import validate_email

debug = None
emails_parsed = 0;

'''
try:
  if sys.argv[1] == '-d':
    debug = True
  else:
    debug = False
except IndexError:
  debug = False
'''
if len(sys.argv) > 1 :
  if sys.argv[1] == '-d':
    debug = True
else:
  debug = False

result_array = []
book = xlrd.open_workbook("file.xls")

sheet_names = book.sheet_names()
sheet_total_pages = book.nsheets;

for i in range(0, sheet_total_pages):
  current_sheet = book.sheet_by_index(i)

  if  current_sheet.name == "PRINCIPAL":
    if debug:
      print (" **---** Ignoring sheet page [%d] **---**" % (i))
  else:
    if debug:
      print ("Parsing sheet page [%d]" % (i))

    num_cols = current_sheet.ncols # Number of columns
    for row_idx in range(6, current_sheet.nrows):    # Iterate through rows (Starting 6st col, not 0, to not read store name and cif)
      if debug:
        print ('Row: %s' % row_idx) # Prints row Number
      for col_idx in range(1, num_cols):  # Iterate through columns
        cell_obj = current_sheet.cell(row_idx, col_idx)  # Get cell object by row, col
        if debug:
          print ('Column: [%s] cell_obj: [%s]' % (col_idx, cell_obj))
        if cell_obj.value: # If cell value (string) is not empty
          email = cell_obj.value
          email = email.lower()
          emails_parsed = emails_parsed + 1
          is_valid = validate_email(email) # We cant validate if email exist (pyDNS is not working anymore)
          if is_valid:
            result_array.append(email)

result_array = list(set(result_array)) # Removing duplicate entries
result_array.sort()

result_json = json.dumps(result_array)

file_ = open('emails.json', 'w')
file_.write(result_json)
file_.close()

print('Parsed %d emails'% emails_parsed)


text:
using base::android::JavaParamRef;

// These functions fulfill the Java to native link between
// PrefetchConfiguration.java and prefetch_prefs.

namespace offline_pages {
namespace android {

JNI_EXPORT jboolean JNI_PrefetchConfiguration_IsPrefetchingEnabled(
    JNIEnv* env,
    const JavaParamRef<jobject>& jkey) {
  ProfileKey* key = ProfileKeyAndroid::FromProfileKeyAndroid(jkey);
  return static_cast<jboolean>(prefetch_prefs::IsEnabled(key->GetPrefs()));
}

JNI_EXPORT jboolean
JNI_PrefetchConfiguration_IsEnabledByServer(JNIEnv* env,
                                            const JavaParamRef<jobject>& jkey) {
  ProfileKey* key = ProfileKeyAndroid::FromProfileKeyAndroid(jkey);
  return static_cast<jboolean>(
      prefetch_prefs::IsEnabledByServer(key->GetPrefs()));
}

JNI_EXPORT jboolean JNI_PrefetchConfiguration_IsForbiddenCheckDue(
    JNIEnv* env,
    const JavaParamRef<jobject>& jkey) {
  ProfileKey* key = ProfileKeyAndroid::FromProfileKeyAndroid(jkey);
  return static_cast<jboolean>(
      prefetch_prefs::IsForbiddenCheckDue(key->GetPrefs()));
}

JNI_EXPORT jboolean JNI_PrefetchConfiguration_IsEnabledByServerUnknown(
    JNIEnv* env,
    const JavaParamRef<jobject>& jkey) {
  ProfileKey* key = ProfileKeyAndroid::FromProfileKeyAndroid(jkey);
  return static_cast<jboolean>(
      prefetch_prefs::IsEnabledByServerUnknown(key->GetPrefs()));
}

JNI_EXPORT void JNI_PrefetchConfiguration_SetPrefetchingEnabledInSettings(
    JNIEnv* env,
    const JavaParamRef<jobject>& jkey,
    jboolean enabled) {
  ProfileKey* key = ProfileKeyAndroid::FromProfileKeyAndroid(jkey);
  prefetch_prefs::SetPrefetchingEnabledInSettings(key->GetPrefs(), enabled);
}

JNI_EXPORT jboolean JNI_PrefetchConfiguration_IsPrefetchingEnabledInSettings(
    JNIEnv* env,
    const JavaParamRef<jobject>& jkey) {
  ProfileKey* key = ProfileKeyAndroid::FromProfileKeyAndroid(jkey);
  return static_cast<jboolean>(
      prefetch_prefs::IsPrefetchingEnabledInSettings(key->GetPrefs()));
}

}  // namespace android
}  // namespace offline_pages


text:
package fr.lteconsulting.hexa.client;

import com.google.gwt.storage.client.Storage;

public class LocalStorage
{
	private final static Storage STORE;

	static
	{
		STORE = Storage.getLocalStorageIfSupported();
	}

	public static boolean isSupported()
	{
		return STORE != null;
	}

	public static int getLength()
	{
		if( STORE == null )
			return -1;
		return STORE.getLength();
	}

	public static void clear()
	{
		if( STORE == null )
			return;

		STORE.clear();
	}
}


text:
<!DOCTYPE HTML>

   <title>Data binding test page using List binding</title>

List data binding test page

ComboBox

DropdownBox

RadioButtonGroup


text:
<?php
if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { 	die('You are not allowed to call this page directly.'); }

function get_v_playlist_data( $playlist_file ) {
	global $wpdb;
	$playlist_content = file_get_contents($playlist_file);

	$playlist_data['title'] = flagGallery::flagGetBetween($playlist_content,'<title><![CDATA[',']]></title>');
	$playlist_data['skin'] = flagGallery::flagGetBetween($playlist_content,'<skin><![CDATA[',']]></skin>');
	$playlist_data['width'] = flagGallery::flagGetBetween($playlist_content,'<width><![CDATA[',']]></width>');
	$playlist_data['height'] = flagGallery::flagGetBetween($playlist_content,'<height><![CDATA[',']]></height>');
	$playlist_data['description'] = flagGallery::flagGetBetween($playlist_content,'<description><![CDATA[',']]></description>');
	preg_match_all( '|<item id="(.*)">|', $playlist_content, $items );
	$playlist_data['items'] = $items[1];
	return $playlist_data;
}

/**
 * Check the playlists directory and retrieve all playlist files with playlist data.
 *
 */
function get_v_playlists($playlist_folder = '') {

	$flag_options = get_option('flag_options');
	$flag_playlists = array ();
	$playlist_root = ABSPATH.$flag_options['galleryPath'].'playlists/video';
	if( !empty($playlist_folder) )
		$playlist_root = $playlist_folder;

	// Files in flagallery/playlists directory
	$playlists_dir = @ opendir( $playlist_root);
	$playlist_files = array();
	if ( $playlists_dir ) {
		while (($file = readdir( $playlists_dir ) ) !== false ) {
			if ( substr($file, 0, 1) == '.' )
				continue;
			if ( substr($file, -4) == '.xml' )
				$playlist_files[] = $file;
		}
	}
	@closedir( $playlists_dir );

	if ( !$playlists_dir || empty($playlist_files) )
		return $flag_playlists;

	foreach ( $playlist_files as $playlist_file ) {
		if ( !is_readable( "$playlist_root/$playlist_file" ) )
			continue;

		$playlist_data = get_v_playlist_data( "$playlist_root/$playlist_file" );

		if ( empty ( $playlist_data['title'] ) )
			continue;

		$flag_playlists[basename( $playlist_file, ".xml" )] = $playlist_data;
	}
	uasort( $flag_playlists, create_function( '$a, $b', 'return strnatcasecmp( $a["title"], $b["title"] );' ));

	return $flag_playlists;
}

function flagSave_vPlaylist($title,$descr,$data,$file='',$skinaction='') {
	global $wpdb;
	if(!trim($title)) {
		$title = 'default';
	}
	$title = htmlspecialchars_decode(stripslashes($title), ENT_QUOTES);
	$descr = htmlspecialchars_decode(stripslashes($descr), ENT_QUOTES);
	if (!$file) {
		$file = sanitize_flagname($title);
	}

	if(!is_array($data))
		$data = explode(',', $data);

	$flag_options = get_option('flag_options');
    $skin = isset($_POST['skinname'])? sanitize_flagname($_POST['skinname']) : 'video_default';
	if(empty($skinaction))
    	$skinaction = isset($_POST['skinaction'])? sanitize_key($_POST['skinaction']) : 'update';
	$skinpath = trailingslashit( $flag_options['skinsDirABS'] ).$skin;
	$playlistPath = ABSPATH.$flag_options['galleryPath'].'playlists/video/'.$file.'.xml';
	$settings = '';
	if( file_exists($playlistPath) && ($skin == $skinaction) ) {
		$settings = file_get_contents($playlistPath);
	} elseif( file_exists($skinpath . "/settings/settings.xml") ) {
		$settings = file_get_contents($skinpath . "/settings/settings.xml");
	} else {
		flagGallery::show_message(__("Can't find skin settings", 'flag'));
		return;
	}
	$properties = flagGallery::flagGetBetween($settings,'<properties>','</properties>');
	if(empty($properties)) {
		flagGallery::show_message(__("Can't find skin settings", 'flag'));
		return;
	}

	if(count($data)) {
		$content = '<gallery>
<properties>'.$properties.'</properties>
<category id="'.$file.'">
	<properties>
		<title><![CDATA['.$title.']]></title>
		<description><![CDATA['.$descr.']]></description>
		<skin><![CDATA['.$skin.']]></skin>
	</properties>
	<items>';

		foreach( (array) $data as $id) {
			$flv = get_post($id);
			if( in_array( $flv->post_mime_type, array('video/x-flv') ) ) {
			    $thumb = get_post_meta($id, 'thumbnail', true);
				$content .= '
		<item id="'.$flv->ID.'">
          <track>'.wp_get_attachment_url($flv->ID).'</track>
          <title><![CDATA['.$flv->post_title.']]></title>
          <description><![CDATA['.$flv->post_content.']]></description>
          <thumbnail>'.$thumb.'</thumbnail>
        </item>';
			}
		}
		$content .= '
	</items>
</category>
</gallery>';
		// Save options
		$flag_options = get_option('flag_options');
		if(wp_mkdir_p(ABSPATH.$flag_options['galleryPath'].'playlists/video/')) {
			if( flagGallery::saveFile($playlistPath,$content,'w') ){
				flagGallery::show_message(__('Playlist Saved Successfully','flag'));
			}
		} else {
			flagGallery::show_message(__('Create directory please:','flag').'"/'.$flag_options['galleryPath'].'playlists/video/"');
		}
	}
}

function flagSave_vPlaylistSkin($file) {
	$file = sanitize_flagname($file);
	$flag_options = get_option('flag_options');
	$playlistPath = ABSPATH.$flag_options['galleryPath'].'playlists/video/'.$file.'.xml';
	// Save options
	$title = esc_html($_POST['playlist_title']);
	$descr = esc_html($_POST['playlist_descr']);
	$items = get_v_playlist_data($playlistPath);
	$data = $items['items'];
	flagSave_vPlaylist($title,$descr,$data,$file,$skinaction='update');
}

function flag_v_playlist_delete($playlist) {
	$playlist = sanitize_flagname($playlist);
	$flag_options = get_option('flag_options');
	$playlistXML = ABSPATH.$flag_options['galleryPath'].'playlists/video/'.$playlist.'.xml';
	if(file_exists($playlistXML)){
		if(unlink($playlistXML)) {
			flagGallery::show_message("'".$playlist.".xml' ".__('deleted','flag'));
		}
	}
}


text:
namespace MultiagentEnvironment
{
    public interface IAbstractAgent
    {

        void Interact(AgentsEnvironment env);

        double X { get; set; }
        double Y { get; set; }
    }
}


text:
/*
 * SplitArcAction.java
 */
package pipe.actions.petrinet;

import pipe.controllers.ArcController;
import uk.ac.imperial.pipe.models.petrinet.Connectable;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;

/**
 * This class is used to split an arc in two at the
 * point the user clicks the mouse button.
 *
 */
@SuppressWarnings("serial")
public class SplitArcAction
        extends javax.swing.AbstractAction {

    /**
     * Arc controller
     */
    private final ArcController<? extends Connectable, ? extends Connectable> arcController;

    /**
     * Point at which to split the arc
     */
    private final Point2D.Double point;

    /**
     *
     * @param arcController arc controller
     * @param mousePoint point at which to split the arc
     */
    public SplitArcAction(ArcController<? extends Connectable, ? extends Connectable> arcController, Point mousePoint) {
        this.arcController = arcController;
        point = new Point2D.Double(mousePoint.getX(), mousePoint.getY());
    }

    /**
     * Adds a new arc path point at the specified location
     * @param arg0 event
     */
    @Override
    public void actionPerformed(ActionEvent arg0) {
        arcController.addPoint(point);
    }

}


text:
using System;
using System.ComponentModel;

namespace Carbonfrost.Commons.PropertyTrees {

    [TypeConverter(typeof(PropertyTreePathConverter))]
    public partial class PropertyTreePath {

        public static PropertyTreePath Parse(string text) {
            PropertyTreePath result;
            Exception ex = _TryParse(text, out result);
            if (ex == null)
                return result;
            else
                throw ex;
        }

        public static bool TryParse(string text, out PropertyTreePath result) {
            return _TryParse(text, out result) == null;
        }

        static Exception _TryParse(string text, out PropertyTreePath result) {
            // TODO Parse paths
            throw new NotImplementedException();
        }

        // TODO Represent property tree paths
    }
}


text:
var Component;
Component = React.createClass({
  displayName: "Component",
  render: function () {
    return null;
  }
});


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Diagnostics
{
    [DataContract]
    internal sealed class DiagnosticDataLocation
    {
        [DataMember(Order = 0)]
        public readonly DocumentId? DocumentId;

        // text can be either given or calculated from original line/column
        [DataMember(Order = 1)]
        public readonly TextSpan? SourceSpan;

        [DataMember(Order = 2)]
        public readonly string? OriginalFilePath;

        [DataMember(Order = 3)]
        public readonly int OriginalStartLine;

        [DataMember(Order = 4)]
        public readonly int OriginalStartColumn;

        [DataMember(Order = 5)]
        public readonly int OriginalEndLine;

        [DataMember(Order = 6)]
        public readonly int OriginalEndColumn;

        /// <summary>
        /// Null if path is not mapped and <see cref="OriginalFilePath"/> contains the actual path.
        /// Note that the value might be a relative path. In that case <see cref="OriginalFilePath"/> should be used
        /// as a base path for path resolution.
        /// </summary>
        [DataMember(Order = 7)]
        public readonly string? MappedFilePath;

        [DataMember(Order = 8)]
        public readonly int MappedStartLine;

        [DataMember(Order = 9)]
        public readonly int MappedStartColumn;

        [DataMember(Order = 10)]
        public readonly int MappedEndLine;

        [DataMember(Order = 11)]
        public readonly int MappedEndColumn;

        public DiagnosticDataLocation(
            DocumentId? documentId = null,
            TextSpan? sourceSpan = null,
            string? originalFilePath = null,
            int originalStartLine = 0,
            int originalStartColumn = 0,
            int originalEndLine = 0,
            int originalEndColumn = 0,
            string? mappedFilePath = null,
            int mappedStartLine = 0,
            int mappedStartColumn = 0,
            int mappedEndLine = 0,
            int mappedEndColumn = 0)
        {
            DocumentId = documentId;
            SourceSpan = sourceSpan;
            MappedFilePath = mappedFilePath;
            MappedStartLine = mappedStartLine;
            MappedStartColumn = mappedStartColumn;
            MappedEndLine = mappedEndLine;
            MappedEndColumn = mappedEndColumn;
            OriginalFilePath = originalFilePath;
            OriginalStartLine = originalStartLine;
            OriginalStartColumn = originalStartColumn;
            OriginalEndLine = originalEndLine;
            OriginalEndColumn = originalEndColumn;
        }

        internal DiagnosticDataLocation WithCalculatedSpan(TextSpan newSourceSpan)
        {
            Contract.ThrowIfTrue(SourceSpan.HasValue);

            return new DiagnosticDataLocation(DocumentId,
                newSourceSpan, OriginalFilePath,
                OriginalStartLine, OriginalStartColumn,
                OriginalEndLine, OriginalEndColumn,
                MappedFilePath, MappedStartLine, MappedStartColumn,
                MappedEndLine, MappedEndColumn);
        }
    }
}


text:
from channels import Group
from channels.sessions import channel_session
from django.contrib.auth.models import User
from authentification.models import Document, Sentence, Word, Locuteur
from backend.models import Historique
import json, re, math

user_room_dict = {}

# Connected to websocket.connect
@channel_session
def ws_connect(message):
    # on accepte la connexion
    message.reply_channel.send({"accept": True})

    # on recupere le nom du groupe en question (exemple: "edit19" -> edition sur le document avec l'id 19),
    room = message.content['path'].split('/', 2 )[2]
    user = message.content['path'].split('/', 2 )[1]  # id de l'utilisateur courant
    document = int(re.search(r'\d+$', room).group())  # id du document

    if room in user_room_dict:
        user_room_dict[room].append(user)
    else:
        user_room_dict[room] = []
        user_room_dict[room].append(user)

    # on enregistre le groupe, l'utilisateur et le document dans la session et on ajoute l'utilisateur au groupe
    message.channel_session['room'] = room
    message.channel_session['user'] = user
    message.channel_session['document'] = document
    Group(room).add(message.reply_channel)

    # on assigne cote serveur chaque sentence au bon correcteur
    # on supprime les doublons car un utilisateur peut etre connecte sur un meme document via plusieurs fenetres
    #user_without_doublon = []
    #for current_user in user_room_dict[message.channel_session['room']]:
        #if not current_user in user_without_doublon:
            #user_without_doublon.append(current_user)

    # on recupere le document, le nombe de ses sentences
    #sentences = Sentence.objects.filter(document__in = [Document.objects.get(id = int(message.channel_session['document']))]).order_by('start_time')
    #nb_sentences_affectee = math.floor(len(sentences) / len(user_without_doublon))
    #reste = len(sentences) % len(user_without_doublon)

    #for j, current_user in enumerate(user_without_doublon):
        #i = 0
        #while i < nb_sentences_affectee:
            #current = nb_sentences_affectee * j + i
            #sentence = sentences[current]
            #sentence.current_correcteur = User.objects.get(id = int(current_user))
            #sentence.save()
            #i += 1

        #if len(user_without_doublon) - 1 == j:
            #i = 1
            #while i <= reste:
                #sentence = sentences[len(sentences) - i]
                #sentence.current_correcteur = User.objects.get(id = int(current_user))
                #sentence.save()
                #i += 1

    # on renvoi dans le groupe de l'utilisateur, la liste des utilisateurs disponibles
    Group(room).send({
        "text": json.dumps({
            'type' : 'connect',
            'repartition' : user_room_dict[room]
        }),
    })

# Connected to websocket.receive
@channel_session
def ws_message(message):
    json_object = json.loads(message.content['text'])
    #json_object['type']  		-> type d'operation (valider, invalider, supprimer, ..., la sentence)
    #json_object['value'] 		-> nouvelle valeur de la sentence
    #json_object['time_start'] 	-> nouveau temps de debut
    #json_object['time_end'] 	-> nouveau temps de fin
    #json_object['user_id'] 	-> id de l'utilisateur qui fait la modification
    #json_object['sentence_id']	-> id de la phrase a modifier

    # permet de savoir si l'utilisateur qui modifie une sentence a le droit de le faire
    #if sentence.current_correcteur.id != json_object['user_id']:
        #return None

    if json_object['type'] != 'insert' and json_object['type'] != 'split':
        sentence = Sentence.objects.get(id = int(json_object['sentence_id']))

    historique = Historique()
    historique.user = User.objects.get(id = int(message.channel_session['user']))
    historique.document = Document.objects.get(id = int(message.channel_session['document']))
    historique.action = message.content['text']
    historique.save()

    # sentence inaudible
    if json_object['type'] == 'inaudible':
        sentence.inaudible = True
        sentence.save()

    # changement de locuteur
    if json_object['type'] == 'locuteur':
        sentence.locuteur = Locuteur.objects.get(id = int(json_object['locuteur_id']))
        sentence.save()

    # checkbox valid sentence
    if json_object['type'] == 'valid':
        sentence.valeur = json_object['value']
        sentence.start_time = json_object['time_start']
        sentence.end_time = json_object['time_end']
        sentence.validated = True
        sentence.save()

    # checkbox invalide sentence
    if json_object['type'] == 'invalid':
        sentence.validated = False
        sentence.save()

    # supprimer une phrase
    if json_object['type'] == 'delete':
        sentence.delete()

    # inserer une phrase
    if json_object['type'] == 'insert':
        document_id = int(re.search(r'\d+$', message.channel_session['room']).group())
        new_sentence = Sentence()
        new_sentence.valeur = ''
        new_sentence.start_time = json_object['time_start']
        new_sentence.end_time = json_object['time_end']
        new_sentence.validated = False
        new_sentence.document = Document.objects.get(id = int(document_id))
        #new_sentence.locuteur = Locuteur.objects.filter(document__in = [Document.objects.get(id = int(document_id))])[0]
        new_sentence.save()
        # on recupere le nouvelle id de la sentence pour le mettre a jours
        json_object['sentence_id'] = new_sentence.id

    # textarea onChange
    if json_object['type'] == 'edit_text':
        sentence.valeur = json_object['value']
        sentence.start_time = json_object['time_start']
        sentence.end_time = json_object['time_end']
        sentence.save()

    # textarea onChange
    if json_object['type'] == 'maj_time':
        sentence.start_time = json_object['time_start']
        sentence.end_time = json_object['time_end']
        sentence.save()

    # split d'une phrase en deux
    if json_object['type'] == 'split':
        document_id = int(re.search(r'\d+$', message.channel_session['room']).group())
        sentence1 = Sentence.objects.get(id = int(json_object['sentence_id1']))
        sentence1.start_time = json_object['time_start1']
        sentence1.end_time = json_object['time_end1']
        sentence1.valeur = json_object['value1']
        sentence1.save()

        sentence2 = Sentence()
        sentence2.valeur = json_object['value2']
        sentence2.start_time = json_object['time_start2']
        sentence2.end_time = json_object['time_end2']
        sentence2.document = Document.objects.get(id = int(document_id))
        #sentence2.locuteur = Locuteur.objects.get(id = int(json_object['locuteur_id']))
        sentence2.save()
        # on recupere le nouvelle id de la sentence pour le mettre a jours
        json_object['sentence_id2'] = sentence2.id

    if json_object['type'] == 'merge':
        sentence_to_remove = Sentence.objects.get(id = int(json_object['to_delete']))
        sentence.start_time = json_object['time_start']
        sentence.end_time = json_object['time_end']
        sentence.valeur = json_object['value']
        sentence.save()
        sentence_to_remove.delete()

    # on renvoi dans le groupe de l'utilisateur, le message qu'on a recus
    Group(message.channel_session['room']).send({
        "text": json.dumps(json_object),
    })

# Connected to websocket.disconnect
@channel_session
def ws_disconnect(message):
    # message.channel_session['user'] --> user de l'utilisateur qui quitte le socket
    # message.channel_session['room'] --> room de l'utilisateur qui quitte le socket
    delete = 0

    for i, val in enumerate(user_room_dict[message.channel_session['room']]):
        if val == message.channel_session['user']:
            delete = i

    user_room_dict[message.channel_session['room']].pop(delete)
    Group(message.channel_session['room']).discard(message.reply_channel)

    # si il n'y a plus personne dans le channel, pas besoin d'envoyer un message
    if len(user_room_dict[message.channel_session['room']]) == 0:
        return None

    # on assigne cote serveur chaque sentence au bon correcteur
    # on supprime les doublons car un utilisateur peut etre connecte sur un meme document via plusieurs fenetres
    #user_without_doublon = []
    #for current_user in user_room_dict[message.channel_session['room']]:
        #if not current_user in user_without_doublon:
            #user_without_doublon.append(current_user)

    # on recupere le document, le nombe de ses sentences
    #sentences = Sentence.objects.filter(document__in = [Document.objects.get(id = int(message.channel_session['document']))]).order_by('start_time')
    #nb_sentences_affectee = math.floor(len(sentences) / len(user_without_doublon))
    #reste = len(sentences) % len(user_without_doublon)

    #for j, current_user in enumerate(user_without_doublon):
        #i = 0
        #while i < nb_sentences_affectee:
            #current = nb_sentences_affectee * j + i
            #sentence = sentences[current]
            #sentence.current_correcteur = User.objects.get(id = int(current_user))
            #sentence.save()
            #i += 1

        #if len(user_without_doublon) - 1 == j:
            #i = 1
            #while i <= reste:
                #sentence = sentences[len(sentences) - i]
                #sentence.current_correcteur = User.objects.get(id = int(current_user))
                #sentence.save()
                #i += 1

    # on renvoi dans le groupe de l'utilisateur, la liste des utilisateurs disponibles
    Group(message.channel_session['room']).send({
        "text": json.dumps({
            'type' : 'disconnect',
            'repartition' : user_room_dict[message.channel_session['room']]
        }),
    })


text:
package org.apache.flex.forks.batik.svggen;

import java.awt.BasicStroke;

import org.apache.flex.forks.batik.ext.awt.g2d.GraphicContext;

/**
 * Utility class that converts a Java BasicStroke object into
 * a set of SVG style attributes
 *
 * @author Vincent Hardy
 * @version $Id: SVGBasicStroke.java 476924 2006-11-19 21:13:26Z dvholten $
 */
public class SVGBasicStroke extends AbstractSVGConverter{
    /**
     * @param generatorContext used by converter to handle precision
     *        or to create elements.
     */
    public SVGBasicStroke(SVGGeneratorContext generatorContext) {
        super(generatorContext);
    }

    /**
     * Converts part or all of the input GraphicContext into
     * a set of attribute/value pairs and related definitions
     *
     * @param gc GraphicContext to be converted
     * @return descriptor of the attributes required to represent
     *         some or all of the GraphicContext state, along
     *         with the related definitions
     * @see org.apache.flex.forks.batik.svggen.SVGDescriptor
     */
    public SVGDescriptor toSVG(GraphicContext gc){
        if(gc.getStroke() instanceof BasicStroke)
            return toSVG((BasicStroke)gc.getStroke());
        else
            return null;
    }

    /**
     * @param stroke BasicStroke to convert to a set of
     *        SVG attributes
     * @return map of attributes describing the stroke
     */
    public final SVGStrokeDescriptor toSVG(BasicStroke stroke)
    {
        // Stroke width
        String strokeWidth = doubleString(stroke.getLineWidth());

        // Cap style
        String capStyle = endCapToSVG(stroke.getEndCap());

        // Join style
        String joinStyle = joinToSVG(stroke.getLineJoin());

        // Miter limit
        String miterLimit = doubleString(stroke.getMiterLimit());

        // Dash array
        float[] array = stroke.getDashArray();
        String dashArray = null;
        if(array != null)
            dashArray = dashArrayToSVG(array);
        else
            dashArray = SVG_NONE_VALUE;

        // Dash offset
        String dashOffset = doubleString(stroke.getDashPhase());

        return new SVGStrokeDescriptor(strokeWidth, capStyle,
                                       joinStyle, miterLimit,
                                       dashArray, dashOffset);
    }

    /**
     * @param dashArray float array to convert to a string
     */
    private final String dashArrayToSVG(float[] dashArray){
        StringBuffer dashArrayBuf = new StringBuffer( dashArray.length * 8 );
        if(dashArray.length > 0)
            dashArrayBuf.append(doubleString(dashArray[0]));

        for(int i=1; i<dashArray.length; i++){
            dashArrayBuf.append(COMMA);
            dashArrayBuf.append(doubleString(dashArray[i]));
        }

        return dashArrayBuf.toString();
    }

    /**
     * @param lineJoin join style
     */
    private static String joinToSVG(int lineJoin){
        switch(lineJoin){
        case BasicStroke.JOIN_BEVEL:
            return SVG_BEVEL_VALUE;
        case BasicStroke.JOIN_ROUND:
            return SVG_ROUND_VALUE;
        case BasicStroke.JOIN_MITER:
        default:
            return SVG_MITER_VALUE;
        }
    }

    /**
     * @param endCap cap style
     */
    private static String endCapToSVG(int endCap){
        switch(endCap){
        case BasicStroke.CAP_BUTT:
            return SVG_BUTT_VALUE;
        case BasicStroke.CAP_ROUND:
            return SVG_ROUND_VALUE;
        default:
        case BasicStroke.CAP_SQUARE:
            return SVG_SQUARE_VALUE;
        }
    }
}


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

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Main xref</title>
<link type="text/css" rel="stylesheet" href="../stylesheet.css" />

View Javadoc

1   package ttetris;
2
3   import ttetris.logiikka.Tetrispeli;
4   import ttetris.ui.Kayttoliittyma;
5
6   public class Main {
7
8       public static void main(String[] args) {
9           Tetrispeli peli = new Tetrispeli();
10          Kayttoliittyma kayttis = new Kayttoliittyma(peli);
11          kayttis.run();
12      }
13  }

Copyright © 2017. All rights reserved.


text:
<!doctype html>

<meta charset="utf-8">

<title>Driver for MPU6050 IMU Sensor, and Pose Estimation with Kalman Filter - Yifan Jiang</title>

<meta property="og:locale" content="en-US">
<meta property="og:site_name" content="Yifan Jiang">
<meta property="og:title" content="Driver for MPU6050 IMU Sensor, and Pose Estimation with Kalman Filter">

  <meta property="og:description" content="MPU6050is a low-cost IMU sensor, which provides 3-axis acceleration and 3-axis angularvelocity measurements (6 DOF in total). This sensor is really handy when itcomes to implementing things like wearable devices and drones. I got anevaluation module of this sensor, and decided to build a very simple interfacefor it using a 8-bit MCU. Source code is available at https://github.com/YifanJiangPolyU/MPU6050">

  <meta property="og:type" content="article">
  <meta property="article:published_time" content="2016-05-10T00:00:00+02:00">

    <link rel="next" href="/post/UAV-Communication-Relay-for-another-UAV/" title="UAV Communication Relay for another UAV">

    <link rel="prev" href="/post/Inverted-Pendulum/" title="Swing-up and Balancing Control of an Inverted Pendulum">

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Yifan Jiang Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

        <button>

</button>

Yifan Jiang

About Me

Posts

Contact Me

Yifan Jiang

    <button class="btn btn--inverse">Follow</button>

 Switzerland

    <meta itemprop="headline" content="Driver for MPU6050 IMU Sensor, and Pose Estimation with Kalman Filter">
    <meta itemprop="description" content="MPU6050is a low-cost IMU sensor, which provides 3-axis acceleration and 3-axis angularvelocity measurements (6 DOF in total). This sensor is really handy when itcomes to implementing things like wearable devices and drones. I got anevaluation module of this sensor, and decided to build a very simple interfacefor it using a 8-bit MCU. Source code is available at https://github.com/YifanJiangPolyU/MPU6050">
    <meta itemprop="datePublished" content="May 10, 2016">

Driver for MPU6050 IMU Sensor, and Pose Estimation with Kalman Filter

  1 minute read

MPU6050
is a low-cost IMU sensor, which provides 3-axis acceleration and 3-axis angular
velocity measurements (6 DOF in total). This sensor is really handy when it
comes to implementing things like wearable devices and drones. I got an
evaluation module of this sensor, and decided to build a very simple interface
for it using a 8-bit MCU. Source code is available at https://github.com/YifanJiangPolyU/MPU6050

A video showing how it works:

MPU6050 has build-in ADC and is capable of outputting readings digitally via a
I2C interface. In this interface, a Arduino Nano, which has a 8MHz 8-bit MCU, is
used as the I2C master. The Arduino reads measurements from MPU6050 cyclically,
and estimates the pose of the sensor, represented as Euler angles, using
a Kalman filter.

The estimated Euler angles are then transmitted to the PC via serial port (i.e.
UART). On the PC side, a python script reads the pose data and visualizes it in
real time.

The current implementation has a number of problems, but improvements are also easy to implement.

The 8-bit MCU is not powerful enough to execute pose estimation.

Delay is sever, because of inadequate processing power of the MCU.

Communication protocol between Arduino and PC is too primitive. Better protocol can be used to enable data integrity checking and miss data detection.

The data acquisition and the Kalman filter run in an infinite loop in main(). A better way would be to make this interrupt-triggered, for a more deterministic sample time.

     Tags:

      Hobby,

      tech

     Categories:

      post

 Updated: <time datetime="2016-05-10T00:00:00+02:00">May 10, 2016</time>

Share on

   Twitter

   Facebook

   Google+

   LinkedIn

      Previous

      Next

Leave a Comment

You May Also Enjoy

Model Predictive Control of a Series Elastic Actuator

  10 minutes read

Recently I had the pleasure to work on what is probably the best-made Series
Elastic Actuator (SEA) module in the world: the ANYdrive. from Robotic Systems
L...

My First Home Made HiFi Audio Decoder and Amplifier

  6 minutes read

Recently I developed my first in-house hi-fi audio decoder + amplifier project. Having tested it with my own ears I was very much surprised by the outstandin...

UAV Communication Relay for another UAV

  12 minutes read

This project is my undergraduate final year project, and I wrote my undergraduate thesis out of it. Hopefully this short article will give you a brief idea a...

Swing-up and Balancing Control of an Inverted Pendulum

  3 minutes read

In this mini project, nonlinear control strategies for the swing-up control of
an inverted pendulum on a cart (i.e. the cart-pole system) is explored. The
co...

Follow:

 Feed

© 2020 Yifan Jiang. Powered by Jekyll & Minimal Mistakes.


text:
package com.gm.lifecycle.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import com.gm.lifecycle.ConfigLifecycle;

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

/**
 * Author     : Gowtham
 * Email      : goutham.gm11@gmail.com
 * Github     : https://github.com/goutham106
 * Created on : 9/18/17.
 * <p>
 * AndroidManifest.xml ManifestLifecycleParser
 */
public final class ManifestLifecycleParser {
    private static final String MODULE_VALUE = "ConfigLifecycle";

    private final Context context;

    public ManifestLifecycleParser(Context context) {
        this.context = context;
    }

    private static ConfigLifecycle parseModule(String className) {
        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Unable to find ConfigLifecycle implementation", e);
        }

        Object lifecycle;
        try {
            lifecycle = clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException("Unable to instantiate ConfigLifecycle implementation for " + clazz, e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Unable to instantiate ConfigLifecycle implementation for " + clazz, e);
        }

        if (!(lifecycle instanceof ConfigLifecycle)) {
            throw new RuntimeException("Expected instanceof ConfigLifecycle, but found: " + lifecycle);
        }
        return (ConfigLifecycle) lifecycle;
    }

    public List<ConfigLifecycle> parse() {
        List<ConfigLifecycle> configLifecycles = new ArrayList<>();
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                for (String key : appInfo.metaData.keySet()) {
                    if (MODULE_VALUE.equals(appInfo.metaData.get(key))) {
                        Log.d("Lifecycle ---> ",
                                String.format("Find ConfigLifecycle in [%s]", key));
                        configLifecycles.add(parseModule(key));
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Unable to find metadata to parse ConfigLifecycle", e);
        }

        return configLifecycles;
    }
}


text:
"""Read and store Gene Ontology's obo file."""
# -*- coding: UTF-8 -*-
from __future__ import print_function
import sys
import os
import re

import collections as cx

GraphEngines = ("pygraphviz", "pydot")

class OBOReader(object):
    """Read goatools.org's obo file. Load into this iterable class.

        Download obo from: http://purl.obolibrary.org/obo/go/go-basic.obo

        >>> reader = OBOReader()
        >>> for rec in reader:
                print rec
    """
    # Revisions by DV Klopfenstein

    def __init__(self, obo_file="go-basic.obo", optional_attrs=None):
        """Read obo file. Load dictionary."""
        self._init_optional_attrs(optional_attrs)
        # True if obo file exists or if a link to an obo file exists.
        if os.path.isfile(obo_file):
            self.obo_file = obo_file
            # GOTerm attributes that are necessary for any operations:
        else:
            raise Exception("download obo file first\n "
                            "[http://purl.obolibrary.org/obo/"
                            "go/go-basic.obo]")

    def __iter__(self):
        """Return one GO Term record at a time from an obo file."""
        # Wait to open file until needed. Automatically close file when done.
        with open(self.obo_file) as fstream:
            rec_curr = None # Stores current GO Term
            for lnum, line in enumerate(fstream):
                # obo lines start with any of: [Term], [Typedef], /^\S+:/, or /^\s*/
                if line[0:6] == "[Term]":
                    rec_curr = self._init_goterm_ref(rec_curr, "Term", lnum)
                elif line[0:9] == "[Typedef]":
                    pass # Original OBOReader did not store these
                elif rec_curr is not None:
                    line = line.rstrip() # chomp
                    if ":" in line:
                        self._add_to_ref(rec_curr, line, lnum)
                    elif line == "":
                        if rec_curr is not None:
                            yield rec_curr
                            rec_curr = None
                    else:
                        self._die("UNEXPECTED LINE CONTENT: {L}".format(L=line), lnum)
            # Return last record, if necessary
            if rec_curr is not None:
                yield rec_curr

    def _init_goterm_ref(self, rec_curr, name, lnum):
        """Initialize new reference and perform checks."""
        if rec_curr is None:
            return GOTerm()
        msg = "PREVIOUS {REC} WAS NOT TERMINATED AS EXPECTED".format(REC=name)
        self._die(msg, lnum)

    def _add_to_ref(self, rec_curr, line, lnum):
        """Add new fields to the current reference."""
        # Examples of record lines containing ':' include:
        #   id: GO:0000002
        #   name: mitochondrial genome maintenance
        #   namespace: biological_process
        #   def: "The maintenance of ...
        #   is_a: GO:0007005 ! mitochondrion organization
        mtch = re.match(r'^(\S+):\s*(\S.*)$', line)
        if mtch:
            field_name = mtch.group(1)
            field_value = mtch.group(2)
            if field_name == "id":
                self._chk_none(rec_curr.id, lnum)
                rec_curr.id = field_value
            if field_name == "alt_id":
                rec_curr.alt_ids.append(field_value)
            elif field_name == "name":
                self._chk_none(rec_curr.name, lnum)
                rec_curr.name = field_value
            elif field_name == "namespace":
                self._chk_none(rec_curr.namespace, lnum)
                rec_curr.namespace = field_value
            elif field_name == "is_a":
                rec_curr._parents.append(field_value.split()[0])
            elif field_name == "is_obsolete" and field_value == "true":
                rec_curr.is_obsolete = True
            elif field_name in self.optional_attrs:
                self.update_rec(rec_curr, field_name, field_value)
        else:
            self._die("UNEXPECTED FIELD CONTENT: {L}\n".format(L=line), lnum)

    def update_rec(self, rec, name, value):
        """Update current GOTerm with optional record."""
        # 'def' is a reserved word in python, do not use it as a Class attr.
        if name == "def":
            name = "defn"
        if hasattr(rec, name):
            if name not in self.attrs_scalar:
                getattr(rec, name).add(value)
            else:
                raise Exception("ATTR({NAME}) ALREADY SET({VAL})".format(
                    NAME=name, VAL=getattr(rec, name)))
        else: # Initialize new GOTerm attr
            if name in self.attrs_scalar:
                setattr(rec, name, value)
            else:
                setattr(rec, name, set([value]))

    def _init_optional_attrs(self, optional_attrs):
        """Prepare to store data from user-desired optional fields.

          Not loading these optional fields by default saves in space and speed.
          But allow the possibility for saving these fields, if the user desires,
            Including:
              comment consider def is_class_level is_metadata_tag is_transitive
              relationship replaced_by subset synonym transitive_over xref
        """
        self.attrs_req = ['id', 'alt_id', 'name', 'namespace', 'is_a', 'is_obsolete']
        self.attrs_scalar = ['comment', 'defn',
                             'is_class_level', 'is_metadata_tag',
                             'is_transitive', 'transitive_over']
        # Allow user to specify either: 'def' or 'defn'
        #   'def' is an obo field name, but 'defn' is legal Python attribute name
        fnc = lambda aopt: aopt if aopt != "defn" else "def"
        if optional_attrs is None:
            optional_attrs = []
        elif isinstance(optional_attrs, str):
            optional_attrs = [fnc(optional_attrs)] if optional_attrs not in self.attrs_req else []
        elif isinstance(optional_attrs, list) or isinstance(optional_attrs, set):
            optional_attrs = set([fnc(f) for f in optional_attrs if f not in self.attrs_req])
        else:
            raise Exception("optional_attrs arg MUST BE A str, list, or set.")
        self.optional_attrs = optional_attrs

    def _die(self, msg, lnum):
        """Raise an Exception if file read is unexpected."""
        raise Exception("**FATAL {FILE}({LNUM}): {MSG}\n".format(
            FILE=self.obo_file, LNUM=lnum, MSG=msg))

    def _chk_none(self, init_val, lnum):
        """Expect these lines to be uninitialized."""
        if init_val is None or init_val is "":
            return
        self._die("FIELD IS ALREADY INITIALIZED", lnum)

class GOTerm:
    """
    GO term, actually contain a lot more properties than interfaced here
    """

    def __init__(self):
        self.id = ""                # GO:NNNNNNN
        self.name = ""              # description
        self.namespace = ""         # BP, CC, MF
        self._parents = []          # is_a basestring of parents
        self.parents = []           # parent records
        self.children = []          # children records
        self.level = None           # shortest distance from root node
        self.depth = None           # longest distance from root node
        self.is_obsolete = False    # is_obsolete
        self.alt_ids = []           # alternative identifiers

    def __str__(self):
        obsolete = "obsolete" if self.is_obsolete else ""
        return "%s\tlevel-%02d\tdepth-%02d\t%s [%s] %s" % (self.id, self.level, self.depth,
                                               self.name, self.namespace, obsolete)

    def __repr__(self):
        """Print GO id and all attributes in GOTerm class."""
        ret = ["GOTerm('{ID}'):".format(ID=self.id)]
        for key, val in self.__dict__.items():
            if isinstance(val, int) or isinstance(val, str):
                ret.append("{K}:{V}".format(K=key, V=val))
            else:
                ret.append("{K}: {V} items".format(K=key, V=len(val)))
                if len(val) < 10:
                    for elem in val:
                        ret.append("  {ELEM}".format(ELEM=elem))
        return "\n  ".join(ret)

    def has_parent(self, term):
        for p in self.parents:
            if p.id == term or p.has_parent(term):
                return True
        return False

    def has_child(self, term):
        for p in self.children:
            if p.id == term or p.has_child(term):
                return True
        return False

    def get_all_parents(self):
        all_parents = set()
        for p in self.parents:
            all_parents.add(p.id)
            all_parents |= p.get_all_parents()
        return all_parents

    def get_all_children(self):
        all_children = set()
        for p in self.children:
            all_children.add(p.id)
            all_children |= p.get_all_children()
        return all_children

    def get_all_parent_edges(self):
        all_parent_edges = set()
        for p in self.parents:
            all_parent_edges.add((self.id, p.id))
            all_parent_edges |= p.get_all_parent_edges()
        return all_parent_edges

    def get_all_child_edges(self):
        all_child_edges = set()
        for p in self.children:
            all_child_edges.add((p.id, self.id))
            all_child_edges |= p.get_all_child_edges()
        return all_child_edges

    def write_hier_rec(self, gos_printed, out=sys.stdout,
                      len_dash=1, max_depth=None, num_child=None, short_prt=False,
                      include_only=None, go_marks=None,
                      depth=1, dp="-"):
        """Write hierarchy for a GO Term record."""
        # Added by DV Klopfenstein
        GO_id = self.id
        # Shortens hierarchy report by only printing the hierarchy
        # for the sub-set of user-specified GO terms which are connected.
        if include_only is not None and GO_id not in include_only:
          return
        nrp = short_prt and GO_id in gos_printed
        if go_marks is not None:
          out.write('{} '.format('>' if GO_id in go_marks else ' '))
        if len_dash is not None:
            # Default character indicating hierarchy level is '-'.
            # '=' is used to indicate a hierarchical path printed in detail previously.
            letter = '-' if not nrp or not self.children else '='
            dp = ''.join([letter]*depth)
            out.write('{DASHES:{N}} '.format(DASHES=dp, N=len_dash))
        if num_child is not None:
            out.write('{N:>5} '.format(N=len(self.get_all_children())))
        out.write('{GO}\tL-{L:>02}\tD-{D:>02}\t{desc}\n'.format(
            GO=self.id, L=self.level, D=self.depth, desc=self.name))
        # Track GOs previously printed only if needed
        if short_prt:
          gos_printed.add(GO_id)
        # Do not print hierarchy below this turn if it has already been printed
        if nrp:
            return
        depth += 1
        if max_depth is not None and depth > max_depth:
            return
        for p in self.children:
            p.write_hier_rec(gos_printed, out, len_dash, max_depth, num_child, short_prt,
                include_only, go_marks,
                depth, dp)

class GODag(dict):

    def __init__(self, obo_file="go-basic.obo", optional_attrs=None):

        self.load_obo_file(obo_file, optional_attrs)

    def load_obo_file(self, obo_file, optional_attrs):

        print("load obo file %s" % obo_file, file=sys.stderr)
        for rec in OBOReader(obo_file, optional_attrs):
            self[rec.id] = rec
            for alt in rec.alt_ids:
                self[alt] = rec

        self.populate_terms()
        print(len(self), "nodes imported", file=sys.stderr)

    def populate_terms(self):

        def _init_level(rec):
            if rec.level is None:
                if not rec.parents:
                    rec.level = 0
                else:
                    rec.level = min(_init_level(rec) for rec in rec.parents) + 1
            return rec.level

        def _init_depth(rec):
            if rec.depth is None:
                if not rec.parents:
                    rec.depth = 0
                else:
                    rec.depth = max(_init_depth(rec) for rec in rec.parents) + 1
            return rec.depth

        # make the parents references to the GO terms
        for rec in self.values():
            rec.parents = [self[x] for x in rec._parents]

        # populate children and levels
        for rec in self.values():
            for p in rec.parents:
                if rec not in p.children:
                    p.children.append(rec)

            if rec.level is None:
                _init_level(rec)

            if rec.depth is None:
                _init_depth(rec)

    def write_dag(self, out=sys.stdout):
        """Write info for all GO Terms in obo file, sorted numerically."""
        for rec_id, rec in sorted(self.items()):
            print(rec, file=out)

    def write_hier_all(self, out=sys.stdout,
                      len_dash=1, max_depth=None, num_child=None, short_prt=False):
        """Write hierarchy for all GO Terms in obo file."""
        # Print: [biological_process, molecular_function, and cellular_component]
        for go_id in ['GO:0008150', 'GO:0003674', 'GO:0005575']:
          self.write_hier(go_id, out, len_dash, max_depth, num_child, short_prt, None)

    def write_hier(self, GO_id, out=sys.stdout,
                       len_dash=1, max_depth=None, num_child=None, short_prt=False,
                       include_only=None, go_marks=None):
        """Write hierarchy for a GO Term."""
        gos_printed = set()
        self[GO_id].write_hier_rec(gos_printed, out, len_dash, max_depth, num_child,
            short_prt, include_only, go_marks)

    def write_summary_cnts(self, GO_ids, out=sys.stdout):
        """Write summary of level and depth counts for specific GO ids."""
        cnts = GODag.get_cnts_levels_depths_recs([self[GO] for GO in GO_ids])
        self._write_summary_cnts(cnts, out)

    def write_summary_cnts_all(self, out=sys.stdout):
        """Write summary of level and depth counts for all active GO Terms."""
        cnts = self.get_cnts_levels_depths_recs(set(self.values()))
        self._write_summary_cnts(cnts, out)

    def write_summary_cnts_rec(self, out=sys.stdout):
        """Write summary of level and depth counts for active GO Terms."""
        cnts = self.get_cnts_levels_depths_recs(recs)
        self._write_summary_cnts(cnts, out)

    def _write_summary_cnts(self, cnts, out=sys.stdout):
        """Write summary of level and depth counts for active GO Terms."""
        # Added by DV Klopfenstein
        # Count level(shortest path to root) and depth(longest path to root)
        # values for all unique GO Terms.
        max_val = max(max(dep for dep in cnts['depth']),
                      max(lev for lev in cnts['level']))
        nss = ['biological_process', 'molecular_function', 'cellular_component']
        out.write('Dep <-Depth Counts->  <-Level Counts->\n')
        out.write('Lev   BP    MF    CC    BP    MF    CC\n')
        out.write('--- ----  ----  ----  ----  ----  ----\n')
        for i in range(max_val+1):
            vals = ['{:>5}'.format(cnts[desc][i][ns]) for desc in cnts for ns in nss]
            out.write('{:>02} {}\n'.format(i, ' '.join(vals)))

    @staticmethod
    def get_cnts_levels_depths_recs(recs):
        """Collect counts of levels and depths in a Group of GO Terms."""
        cnts = cx.defaultdict(lambda: cx.defaultdict(cx.Counter))
        for rec in recs:
            if not rec.is_obsolete:
                cnts['level'][rec.level][rec.namespace] += 1
                cnts['depth'][rec.depth][rec.namespace] += 1
        return cnts

    @staticmethod
    def id2int(GO_id): return int(GO_id.replace("GO:", "", 1))

    def query_term(self, term, verbose=False):
        if term not in self:
            print("Term %s not found!" % term, file=sys.stderr)
            return

        rec = self[term]
        print(rec, file=sys.stderr)
        if verbose:
            print("all parents:", rec.get_all_parents(), file=sys.stderr)
            print("all children:", rec.get_all_children(), file=sys.stderr)
        return rec

    def paths_to_top(self, term):
        """ Returns all possible paths to the root node

            Each path includes the term given. The order of the path is
            top -> bottom, i.e. it starts with the root and ends with the
            given term (inclusively).

            Parameters:
            -----------
            - term:
                the id of the GO term, where the paths begin (i.e. the
                accession 'GO:0003682')

            Returns:
            --------
            - a list of lists of GO Terms
        """
        # error handling consistent with original authors
        if term not in self:
            print("Term %s not found!" % term, file=sys.stderr)
            return

        def _paths_to_top_recursive(rec):
            if rec.level == 0:
                return [[rec]]
            paths = []
            for parent in rec.parents:
                top_paths = _paths_to_top_recursive(parent)
                for top_path in top_paths:
                    top_path.append(rec)
                    paths.append(top_path)
            return paths

        go_term = self[term]
        return _paths_to_top_recursive(go_term)

    def _label_wrap(self, label):
        wrapped_label = r"%s\n%s" % (label,
                                     self[label].name.replace(",", r"\n"))
        return wrapped_label

    def make_graph_pydot(self, recs, nodecolor,
                     edgecolor, dpi,
                     draw_parents=True, draw_children=True):
        """draw AMIGO style network, lineage containing one query record."""
        import pydot
        G = pydot.Dot(graph_type='digraph', dpi="{}".format(dpi)) # Directed Graph
        edgeset = set()
        usr_ids = [rec.id for rec in recs]
        for rec in recs:
            if draw_parents:
                edgeset.update(rec.get_all_parent_edges())
            if draw_children:
                edgeset.update(rec.get_all_child_edges())

        lw = self._label_wrap
        rec_id_set = set([rec_id for endpts in edgeset for rec_id in endpts])
        nodes = {str(ID):pydot.Node(
              lw(ID).replace("GO:",""),  # Node name
              shape="box",
              style="rounded, filled",
              # Highlight query terms in plum:
              fillcolor="beige" if ID not in usr_ids else "plum",
              color=nodecolor)
                for ID in rec_id_set}

        # add nodes explicitly via add_node
        for rec_id, node in nodes.items():
            G.add_node(node)

        for src, target in edgeset:
            # default layout in graphviz is top->bottom, so we invert
            # the direction and plot using dir="back"
            G.add_edge(pydot.Edge(nodes[target], nodes[src],
              shape="normal",
              color=edgecolor,
              label="is_a",
              dir="back"))

        return G

    def make_graph_pygraphviz(self, recs, nodecolor,
                     edgecolor, dpi,
                     draw_parents=True, draw_children=True):
        # draw AMIGO style network, lineage containing one query record
        import pygraphviz as pgv

        G = pgv.AGraph(name="GO tree")
        edgeset = set()
        for rec in recs:
            if draw_parents:
                edgeset.update(rec.get_all_parent_edges())
            if draw_children:
                edgeset.update(rec.get_all_child_edges())

        edgeset = [(self._label_wrap(a), self._label_wrap(b))
                   for (a, b) in edgeset]

        # add nodes explicitly via add_node
        # adding nodes implicitly via add_edge misses nodes
        # without at least one edge
        for rec in recs:
            G.add_node(self._label_wrap(rec.id))

        for src, target in edgeset:
            # default layout in graphviz is top->bottom, so we invert
            # the direction and plot using dir="back"
            G.add_edge(target, src)

        G.graph_attr.update(dpi="%d" % dpi)
        G.node_attr.update(shape="box", style="rounded,filled",
                           fillcolor="beige", color=nodecolor)
        G.edge_attr.update(shape="normal", color=edgecolor,
                           dir="back", label="is_a")
        # highlight the query terms
        for rec in recs:
            try:
                q = G.get_node(self._label_wrap(rec.id))
                q.attr.update(fillcolor="plum")
            except:
                continue

        return G

    def draw_lineage(self, recs, nodecolor="mediumseagreen",
                     edgecolor="lightslateblue", dpi=96,
                     lineage_img="GO_lineage.png", engine="pygraphviz",
                     gml=False, draw_parents=True, draw_children=True):
        assert engine in GraphEngines
        if engine == "pygraphviz":
            G = self.make_graph_pygraphviz(recs, nodecolor, edgecolor, dpi,
                              draw_parents=draw_parents, draw_children=draw_children)
        else:
            G = self.make_graph_pydot(recs, nodecolor, edgecolor, dpi,
                              draw_parents=draw_parents, draw_children=draw_children)

        if gml:
            import networkx as nx  # use networkx to do the conversion
            pf = lineage_img.rsplit(".", 1)[0]
            NG = nx.from_agraph(G) if engine == "pygraphviz" else nx.from_pydot(G)

            del NG.graph['node']
            del NG.graph['edge']
            gmlfile = pf + ".gml"
            nx.write_gml(NG, gmlfile)
            print("GML graph written to {0}".format(gmlfile), file=sys.stderr)

        print(("lineage info for terms %s written to %s" %
                             ([rec.id for rec in recs], lineage_img)), file=sys.stderr)

        if engine == "pygraphviz":
            G.draw(lineage_img, prog="dot")
        else:
            G.write_png(lineage_img)

    def update_association(self, association):
        bad_terms = set()
        for key, terms in list(association.items()):
            parents = set()
            for term in terms:
                try:
                    parents.update(self[term].get_all_parents())
                except:
                    bad_terms.add(term.strip())
            terms.update(parents)
        if bad_terms:
            print("terms not found: %s" % (bad_terms,), file=sys.stderr)


text:
var toLength = require('../internals/to-length');

// `LengthOfArrayLike` abstract operation
// https://tc39.es/ecma262/#sec-lengthofarraylike
module.exports = function (obj) {
  return toLength(obj.length);
};


text: Configuration files for my personal Home Assistant instance


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Novosti Sist. Vyssh. Rast. 10:139. 1973

#### Original name
null

### Remarks
null


text:
using SanicballCore;
using UnityEngine;
using UnityEngine.UI;

namespace Sanicball.UI
{
    public class MainMenuPanel : MonoBehaviour
    {
        [SerializeField]
        private Text versionNameField = null;
        [SerializeField]
        private Text taglineField = null;

        private SlideCanvasGroup activePanel;

        public void SetActivePanel(SlideCanvasGroup panel)
        {
            if (activePanel == null)
            {
                //Opening new panel
                panel.Open();
                activePanel = panel;
            }
            else
            {
                //Changing panel
                if (activePanel != panel)
                {
                    CloseActivePanel();
                    panel.Open();
                    activePanel = panel;
                }
                else
                {
                    //Closing active panel
                    CloseActivePanel();
                }
            }
        }

        public void CloseActivePanel()
        {
            activePanel.Close();
            activePanel = null;
        }

        private void Start()
        {
            versionNameField.text = GameVersion.AS_STRING;
            taglineField.text = GameVersion.TAGLINE;
        }

        private void Update()
        {
            if ((Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(KeyCode.JoystickButton1)) && FindObjectsOfType<Popup>().Length <= 0)
            {
                if (activePanel != null)
                {
                    CloseActivePanel();
                }
                else
                {
                    Application.Quit();
                }
            }
        }
    }
}


text:
using System;
using KayakoRestApi.Controllers;
using KayakoRestApi.Core.Constants;
using KayakoRestApi.Core.Test;
using KayakoRestApi.Net;
using Moq;
using NUnit.Framework;

namespace KayakoRestApi.UnitTests.Core
{
	[TestFixture(Description = "A set of tests testing Api methods around Cusom Fields")]
	public class CoreControllerTests
	{
		private ICoreController _coreController;
		private Mock<IKayakoApiRequest> _kayakoApiRequest;

		private TestData _getTestData;

		[SetUp]
		public void SetUp()
		{
			_kayakoApiRequest = new Mock<IKayakoApiRequest>();
			_coreController = new CoreController(_kayakoApiRequest.Object);

			_getTestData = new TestData("Test");
		}

		[Test]
		public void GetList()
		{
			_kayakoApiRequest.Setup(x => x.ExecuteGet<TestData>(ApiBaseMethods.CoreTest)).Returns(_getTestData);
			var getListResult = _coreController.GetListTest();

			_kayakoApiRequest.Verify(x => x.ExecuteGet<TestData>(ApiBaseMethods.CoreTest), Times.Once());
			Assert.That(getListResult, Is.EqualTo(_getTestData.Data));
		}

		[TestCase(1)]
		[TestCase(2)]
		[TestCase(3)]
		public void Get(int id)
		{
			string apiMethod = String.Format("{0}/{1}", ApiBaseMethods.CoreTest, id);
			_kayakoApiRequest.Setup(x => x.ExecuteGet<TestData>(apiMethod)).Returns(_getTestData);

			var getResult = _coreController.GetTest(id);

			_kayakoApiRequest.Verify(x => x.ExecuteGet<TestData>(apiMethod), Times.Once());
			Assert.That(getResult, Is.EqualTo(_getTestData.Data));
		}

		[TestCase(1)]
		[TestCase(2)]
		[TestCase(3)]
		public void Put(int id)
		{
			string apiMethod = String.Format("{0}/{1}", ApiBaseMethods.CoreTest, id);
			_kayakoApiRequest.Setup(x => x.ExecutePut<TestData>(apiMethod, "")).Returns(_getTestData);

			var putResult = _coreController.PutTest(id);

			_kayakoApiRequest.Verify(x => x.ExecutePut<TestData>(apiMethod, ""), Times.Once());
			Assert.That(putResult, Is.EqualTo(_getTestData.Data));
		}

		[Test]
		public void Post()
		{
			_kayakoApiRequest.Setup(x => x.ExecutePost<TestData>(ApiBaseMethods.CoreTest, "")).Returns(_getTestData);

			var postResult = _coreController.PostTest();

			_kayakoApiRequest.Verify(x => x.ExecutePost<TestData>(ApiBaseMethods.CoreTest, ""), Times.Once());
			Assert.That(postResult, Is.EqualTo(_getTestData.Data));
		}

		[TestCase(1)]
		[TestCase(2)]
		[TestCase(3)]
		public void Delete(int id)
		{
			string apiMethod = String.Format("{0}/{1}", ApiBaseMethods.CoreTest, id);
			_kayakoApiRequest.Setup(x => x.ExecuteDelete(apiMethod)).Returns(true);

			var deleteResult = _coreController.DeleteTest(id);

			_kayakoApiRequest.Verify(x => x.ExecuteDelete(apiMethod), Times.Once());
			Assert.That(deleteResult, Is.EqualTo(true));
		}
	}
}