text:
{-# LANGUAGE DeriveDataTypeable #-}

module Cassandra.Schema
       ( CType (..)
       , PrimaryKey (..)
       , UDT (..)
       , Table (..)
       , View (..)
       , Field
       , Schema (..)
       , HasName (..)
       , HasFields (..)
       , parseSchema
       , checkSchema
       , pkGetPartitionKeys
       , pkGetClusterKeys
       , pkToList
       , ctypeToCql )
       where

import Data.Generics
import Text.ParserCombinators.Parsec
import qualified Text.Parsec.Token as P
import Control.Monad
import Data.Monoid
import Data.Either
import Data.List
import Data.Maybe

import Debug.Trace

data CType =
    CType String
  | CList CType
  deriving (Show, Data, Typeable)

data PrimaryKey = PKTupled [String] [String] | PKSingle String [String]
                deriving (Show, Data, Typeable)

pkGetPartitionKeys :: PrimaryKey -> [String]
pkGetPartitionKeys (PKSingle x _) = [x]
pkGetPartitionKeys (PKTupled xs _) = xs

pkGetClusterKeys :: PrimaryKey -> [String]
pkGetClusterKeys (PKSingle _ xs) = xs
pkGetClusterKeys (PKTupled _ xs) = xs

pkToList :: PrimaryKey -> [String]
pkToList pk = pkGetPartitionKeys pk ++ pkGetClusterKeys pk

type Field = (String, CType)

class HasFields t where
  getFields :: t -> [Field]

class HasName t where
  getName :: t -> String

data UDT =
  UDT String [Field]
  deriving (Show, Data, Typeable)

data Table = Table
  { tableName     :: String
  , tablePk       :: PrimaryKey
  , tableFields   :: [Field]
  } deriving (Show, Data, Typeable)

data View = View
  { viewName :: String
  , viewTable :: String
  , viewFields :: [String]
  } deriving (Show, Data, Typeable)

type TypeSyn = (String, String)
type TypeMap = (String, String)

data Schema = Schema
  { schemaUDTs  :: [UDT]
  , schemaTables :: [Table]
  , schemaTypeSyns :: [TypeSyn]
  , schemaTypeMaps :: [TypeMap]
  , schemaViews :: [View]
  } deriving (Show, Data, Typeable)

udtSchema     t = Schema [t] [] [] [] []
tableSchema   t = Schema [] [t] [] [] []
typesynSchema t = Schema [] [] [t] [] []
typemapSchema t = Schema [] [] [] [t] []
viewSchema    t = Schema [] [] [] [] [t]

instance Monoid Schema where
  mappend (Schema a0 a1 a2 a3 a4) (Schema b0 b1 b2 b3 b4) =
    Schema (a0 <> b0) (a1 <> b1) (a2 <> b2) (a3 <> b3) (a4 <> b4)
  mempty = Schema [] [] [] [] []

instance HasFields Table where
  getFields = tableFields

instance HasFields UDT where
  getFields (UDT _ fields) = fields

instance HasName Table where
  getName = tableName

instance HasName UDT where
  getName (UDT name _) = name

cqlDef = P.LanguageDef
  { P.commentStart = "/*"
  , P.commentEnd = "*/"
  , P.commentLine = "--"
  , P.nestedComments = False
  , P.identStart = letter <|> char '_'
  , P.identLetter = alphaNum <|> char '_'
  , P.opStart = char '+'
  , P.opLetter = char '+'
  , P.reservedNames = ["table", "udt", "end"]
  , P.reservedOpNames = []
  , P.caseSensitive = False
  }

lexer = P.makeTokenParser cqlDef

parens     = P.parens     lexer
braces     = P.braces     lexer
identifier = P.identifier lexer
reserved   = P.reserved   lexer
symbol     = P.reserved   lexer
angles     = P.angles     lexer
comma      = P.comma      lexer
commaSep   = P.commaSep   lexer
whitespace = P.whiteSpace lexer

schema :: CharParser st Schema
schema = do
  whitespace
  elems <- many schemaElement
  return $ mconcat elems

cassandraType :: CharParser st CType
cassandraType =
  (try (CList <$> (symbol "list" >> angles cassandraType))) <|>
  (CType <$> identifier)

ctypeToCql :: CType -> String
ctypeToCql (CType s) = s
ctypeToCql (CList t) = "list" ++ ('<' : ctypeToCql t ++ ">")

field :: CharParser st Field
field = do
  id <- identifier
  typ <- cassandraType
  return (id, typ)

partitionKey :: CharParser st (Either [String] String)
partitionKey =
  parens (Left <$> commaSep identifier) <|>
  Right <$> identifier

primaryKey :: CharParser st PrimaryKey
primaryKey = do
  partKey <- partitionKey
  rest <- option [] $ do
    comma
    commaSep identifier
  return $ case partKey of
    Left k -> PKTupled k rest
    Right k -> PKSingle k rest

table :: CharParser st Table
table = do
  reserved "table"
  tableName <- identifier
  pk <- parens primaryKey
  fields <- many1 field
  reserved "end"
  return $ Table tableName pk fields

aTable = tableSchema <$> table

udt :: CharParser st UDT
udt = do
  reserved "udt"
  name <- identifier
  fields <- many1 field
  reserved "end"
  return $ UDT name fields

aUdt = udtSchema <$> udt

typesyn :: CharParser st TypeSyn
typesyn = do
  reserved "typesyn"
  newName <- identifier
  otherName <- identifier
  return $ (newName, otherName)

aTypesyn = typesynSchema <$> typesyn

typemap :: CharParser st TypeMap
typemap = do
  reserved "typemap"
  cqlName <- identifier
  haskellName <- identifier
  return $ (cqlName, haskellName)

aTypemap = typemapSchema <$> typemap

view :: CharParser st View
view = do
  reserved "view"
  viewName <- identifier
  tableName <- parens identifier
  theFields <- many1 identifier
  reserved "end"
  return $ View viewName tableName theFields

aView = viewSchema <$> view

schemaElement :: CharParser st Schema
schemaElement = aTable <|> aUdt <|> aTypesyn <|> aTypemap <|> aView

testTable = unlines
  [ "typesyn user_id int"
  , "typemap user_id UserId"
  , ""
  , "table user (user_id)"
  , "  user_id uuid"
  , "  name text"
  , "end"
  , ""
  , "udt my_udt"
  , "  udt_field tt"
  , "end"
  , "table other ((other_id, asd), two)"
  , "  other_id uuid"
  , "  other_name text"
  , "end"
  , "view user_view (user) user_id end"
  ]

testInput = "(a, x), b, c"

testParser p s = runParser p () "" s

test = testParser schema testTable

parseSchema :: Monad m => (String, Int, Int) -> String -> m Schema
parseSchema (file, line, col) s =
    case runParser p () "" s of
      Left err  -> fail $ show err
      Right r   -> return r
  where
    p = do pos <- getPosition
           setPosition $
             flip setSourceName file $
             flip setSourceLine line $
             flip setSourceColumn col $
             pos
           result <- schema
           eof
           return result

checkSchema :: Schema -> Either String ()
checkSchema (Schema udts tables typeSyns typeMaps views) = return ()
  --   typeNames <- mapM checkType udts
  --   tableNames <- mapM (checkTable typeNames) tables
  --   checkNoDuplicateTables tableNames
  --   return ()
  -- where checkTable :: [String] -> Table -> Either String String
  --       checkTable typeNames (Table name pk fields) = do
  --         let fieldNames = map fst fields
  --         unless (nub fieldNames == fieldNames) $
  --           Left ("Repeated field name in table " ++ name)

  --         let allPkParts = case pk of
  --               PKSingle x xs -> x : xs
  --               PKTupled xs ys -> xs ++ ys

  --         unless (all (`elem` fieldNames) allPkParts) $
  --           Left ("Undefined field used as primary key in table " ++ name)

  --         let getUDT (_, CCustom t) = Just t
  --             getUDT _ = Nothing

  --             udtsUsed = mapMaybe getUDT fields

  --         let undefinedNames =
  --               filter (not . (`elem` typeNames)) udtsUsed
  --         unless (null undefinedNames) $
  --           Left ("Undefined udts in table "
  --                 ++ name ++ ": " ++ show undefinedNames)

  --         return name

  --       checkType (UDT name fields) = do
  --         let fieldNames = map fst fields
  --         unless (nub fieldNames == fieldNames) $
  --           Left ("Repeated field name in type " ++ name)

  --         return name

  --       checkNoDuplicateTables tableNames = do
  --         let duplicates = filter ((>1) . length) . group . sort $ tableNames
  --         unless (null duplicates) $
  --           Left ("Duplicate table names found: " ++ show duplicates)


text:
using namespace llvm;
using namespace clang;

template <unsigned Kind>
const StringRef getNameImpl(CodeCompletionResult Result);

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Declaration>(CodeCompletionResult Result) {
  auto declaration = Result.Declaration;
  if (!declaration->getIdentifier()) return "";
  return declaration->getIdentifier()->getName();
}

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Keyword>(CodeCompletionResult Result) {
  return Result.Keyword;
}

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Macro>(CodeCompletionResult Result) {
  return Result.Macro->getName();
}

template <>
const StringRef getNameImpl<CodeCompletionResult::RK_Pattern>(CodeCompletionResult Result) {
  return Result.Pattern->getAsString();
}

const StringRef getName(CodeCompletionResult Result) {
  switch (Result.Kind) {
  case CodeCompletionResult::RK_Declaration:
    return getNameImpl<CodeCompletionResult::RK_Declaration>(Result);
  case CodeCompletionResult::RK_Keyword:
    return getNameImpl<CodeCompletionResult::RK_Keyword>(Result);
  case CodeCompletionResult::RK_Macro:
    return getNameImpl<CodeCompletionResult::RK_Macro>(Result);
  case CodeCompletionResult::RK_Pattern:
    return getNameImpl<CodeCompletionResult::RK_Pattern>(Result);
  }
  llvm_unreachable("Unknown code completion result Kind.");
}

bool isCompletionAvailable(CodeCompletionResult Result) {
  return Result.Availability == CXAvailability_Available ||
    Result.Availability == CXAvailability_Deprecated;
}

bool CompletionPrinter::isResultFilteredOut(StringRef Filter,
                                            CodeCompletionResult Result) {
  return !isCompletionAvailable(Result) && getName(Result).startswith(Filter);
}

class CompletionCandidate {
public:
  template <class T>
  using PlaceholdersTy = llvm::SmallVector<T, 4>;
  struct Postcompletion {
    std::string PlaceholdersText;
    PlaceholdersTy<unsigned> Positions;
  };
  void setTypedText(const char *value) { addStringValue(TypedText, value); }
  void setResultType(const char *value) { addStringValue(ResultType, value); }
  void setBriefComment(const char *value) { addStringValue(BriefComment, value); }
  void addArgumentToSignature(const char *value) {
    auto sizeBefore = PostcompletionInfo.PlaceholdersText.size();
    addToSignature(value);
    auto sizeAfter = PostcompletionInfo.PlaceholdersText.size();
    if (sizeAfter != sizeBefore)
      addPlaceholderRange(sizeBefore, sizeAfter);
  }
  void addTypedTextToSignature(const char *value) {
    addToSignature(value);
  }
  void addToPostcompletion(const char* value) {
    addStringValue(PostcompletionInfo.PlaceholdersText, value);
  }
  void setPriority(unsigned value) { Priority = value; }
  void addPlaceholderRange(unsigned begin, unsigned end) {
    PostcompletionInfo.Positions.push_back(begin);
    PostcompletionInfo.Positions.push_back(end);
  }

  const std::string &getTypedText() { return TypedText; }
  const std::string &getResultType() { return ResultType; }
  const std::string &getBriefComment() { return BriefComment; }
  const std::string &getSignature() { return Signature; }
  const Postcompletion &getPostcompletion() { return PostcompletionInfo; }
  unsigned getPriority() { return Priority; }
  unsigned getAnnotation() { return TypedText.size(); }
  static CompletionCandidate createOutOf(CodeCompletionString &CCS);
private:
  void addToSignature(const char *value) {
    addStringValue(Signature, value);
    if (TypedTextSet) addToPostcompletion(value);
    TypedTextSet = true;
  }
  void addStringValue(std::string &dst, const char *src) {
    if (src) dst += src;
  }

  bool TypedTextSet = false;
  std::string TypedText      = "",
              ResultType     = "",
              BriefComment   = "",
              Signature      = "";
  unsigned Priority = 0, Annotation = 0;
  Postcompletion PostcompletionInfo;
};

void print(llvm::raw_ostream &OS, const std::string &value) {
  OS << "\"" << value << "\"" << " ";
}

void print(llvm::raw_ostream &OS, unsigned value) {
  OS << value << " ";
}

CompletionCandidate CompletionCandidate::createOutOf(CodeCompletionString &CCS) {
  CompletionCandidate result;
  result.setTypedText(CCS.getTypedText());
  result.setPriority(CCS.getPriority());
  result.setBriefComment(CCS.getBriefComment());
  for (auto chunk : CCS) {
    switch (chunk.Kind) {
    case CodeCompletionString::CK_ResultType:
      result.setResultType(chunk.Text);
      break;
    case CodeCompletionString::CK_Optional:
      break;
    case CodeCompletionString::CK_Placeholder:
      result.addArgumentToSignature(chunk.Text);
      break;
    default:
      result.addTypedTextToSignature(chunk.Text);
    }
  }
  return std::move(result);
}

namespace print {
  auto adapt(const std::string &value) {
    return wrap(value);
  }

  auto adapt(unsigned value) {
    return boost::lexical_cast<std::string>(value);
  }

  template <class Ty>
  auto adapt(const CompletionCandidate::PlaceholdersTy<Ty> &value) {
      CompletionCandidate::PlaceholdersTy<std::string> adaptedValue;
      boost::range::transform(value, std::back_inserter(adaptedValue),
                              [](auto x) { return adapt(x); });
      return boost::algorithm::join(adaptedValue, " ");
  }

  void print(llvm::raw_ostream &OS, const CompletionCandidate::Postcompletion &arg) {
    OS << "(" << adapt(arg.PlaceholdersText);
    auto positions = adapt(arg.Positions);
    OS << (!positions.empty() ? " " : "") << positions << ")";
  }

  template <class ProcessedArgTy, class ...ArgsTy>
  void print(llvm::raw_ostream &OS, ProcessedArgTy arg, ArgsTy... args) {
    OS << adapt(arg) << " ";
    print(OS, args...);
  }
}
llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, CompletionCandidate &candidate) {
  print::print(OS, candidate.getTypedText(),
               candidate.getPriority(),
               candidate.getResultType(),
               candidate.getBriefComment(),
               candidate.getSignature(),
               candidate.getAnnotation(),
               candidate.getPostcompletion());
  return OS;
}

void
CompletionPrinter::ProcessCodeCompleteResults(Sema &SemaRef,
                                              CodeCompletionContext Context,
                                              CodeCompletionResult *Results,
                                              unsigned NumResults) {
  std::stable_sort(Results, Results + NumResults);

  // Print the results.
  OS << "(\n";
  for (unsigned I = 0; I != NumResults; ++I) {
    CompletionCandidate candidate;
    if (CodeCompletionString *CCS
        = Results[I].CreateCodeCompletionString(SemaRef, Context,
                                                    getAllocator(),
                                                    CCTUInfo,
                                                    includeBriefComments())) {
      candidate = CompletionCandidate::createOutOf(*CCS);
    }
  OS << "(" << candidate << ")\n";
  }
  OS << ")\n";
}

static std::string getOverloadAsString(const CodeCompletionString &CCS) {
  std::string Result;
  llvm::raw_string_ostream OS(Result);

  for (auto &C : CCS) {
    switch (C.Kind) {
    case CodeCompletionString::CK_Informative:
    case CodeCompletionString::CK_ResultType:
      OS << "[#" << C.Text << "#]";
      break;

    case CodeCompletionString::CK_CurrentParameter:
      OS << "<#" << C.Text << "#>";
      break;

    default: OS << C.Text; break;
    }
  }
  return OS.str();
}

void
CompletionPrinter::ProcessOverloadCandidates(Sema &SemaRef,
                                             unsigned CurrentArg,
                                             OverloadCandidate *Candidates,
                                             unsigned NumCandidates) {
  for (unsigned I = 0; I != NumCandidates; ++I) {
    if (CodeCompletionString *CCS
          = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
                                                getAllocator(), CCTUInfo,
                                                includeBriefComments())) {
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.jmnarloch.spring.cloud.feign;

import com.github.jmnarloch.spring.cloud.feign.app.client.InvoiceClient;
import com.github.jmnarloch.spring.cloud.feign.app.domain.Invoice;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Tests the response compression.
 *
 * @author Jakub Narloch
 */
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
@SpringApplicationConfiguration(classes = {FeignAcceptEncodingTest.Application.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class FeignAcceptEncodingTest {

    @Autowired
    private InvoiceClient invoiceClient;

    @Test
    public void compressedResponse() {

        // when
        final ResponseEntity<List<Invoice>> invoices = invoiceClient.getInvoices();

        // then
        assertNotNull(invoices);
        assertEquals(HttpStatus.OK, invoices.getStatusCode());
        assertNotNull(invoices.getBody());
        assertEquals(100, invoices.getBody().size());

    }

    @EnableFeignAcceptGzipEncoding
    @EnableFeignClients
    @RibbonClient(name = "local", configuration = LocalRibbonClientConfiguration.class)
    @ComponentScan("com.github.jmnarloch.spring.cloud.feign.app")
    @EnableAutoConfiguration
    @Configuration
    public static class Application {
    }

    @Configuration
    static class LocalRibbonClientConfiguration {

        @Value("${local.server.port}")
        private int port = 0;

        @Bean
        public ILoadBalancer ribbonLoadBalancer() {
            BaseLoadBalancer balancer = new BaseLoadBalancer();
            balancer.setServersList(Collections.singletonList(new Server("localhost", this.port)));
            return balancer;
        }
    }
}


text:
'use strict';

angular.module('groups').run(['Menus',
 function (Menus) {
        // Set top bar menu items
        Menus.addMenuItem('topbar', 'Groups', 'groups', 'dropdown', '/groups(/create)?');
        Menus.addSubMenuItem('topbar', 'groups', 'List Groups', 'groups');
        Menus.addSubMenuItem('topbar', 'groups', 'New Group', 'groups/create');
 }
]);


text:
#ifndef __DEV_DISP_H__
#define __DEV_DISP_H__

#include "de/bsp_display.h"
#if defined(SUPPORT_HDMI)
#include "../hdmi/drv_hdmi_i.h"
#endif

#if defined(SUPPORT_TV)
#include "tv/drv_tv_i.h"
#endif

#ifdef CONFIG_ION_SUNXI
#define FB_RESERVED_MEM
#endif

typedef enum
{
	DISPLAY_NORMAL = 0,
	DISPLAY_LIGHT_SLEEP = 1,
	DISPLAY_DEEP_SLEEP = 2,
}disp_standby_flags;

struct info_mm
{
	void *info_base;	/* Virtual address */
	uintptr_t mem_start;	/* Start of frame buffer mem */
				/* (physical address) */
	u32 mem_len;			/* Length of frame buffer mem */
};

struct proc_list
{
	void (*proc)(u32 screen_id);
	struct list_head list;
};

struct ioctl_list
{
	unsigned int cmd;
	int (*func)(unsigned int cmd, unsigned long arg);
	struct list_head list;
};

struct standby_cb_list
{
	int (*suspend)(void);
	int (*resume)(void);
	struct list_head list;
};

typedef struct
{
	bool                  b_init;
	enum disp_init_mode        disp_mode;//0:single screen0(fb0); 1:single screen1(fb0); 2:single screen2(fb0)

	//for screen0/1/2
	enum disp_output_type      output_type[3];
	unsigned int          output_mode[3];

	//for fb0/1/2
	unsigned int          buffer_num[3];
	enum disp_pixel_format     format[3];
	unsigned int          fb_width[3];
	unsigned int          fb_height[3];
}disp_init_para;

typedef struct
{
	struct device           *dev;
	uintptr_t               reg_base[DISP_MOD_NUM];
	u32                     irq_no[DISP_MOD_NUM];
	struct clk              *mclk[DISP_MOD_NUM];

	disp_init_para          disp_init;
	struct disp_manager     *mgr[DEVICE_NUM];

	struct proc_list        sync_proc_list;
	struct proc_list        sync_finish_proc_list;
	struct ioctl_list       ioctl_extend_list;
	struct standby_cb_list  stb_cb_list;
	struct mutex            mlock;
	struct work_struct      resume_work[3];
	struct work_struct      start_work;

	u32    		              exit_mode;//0:clean all  1:disable interrupt
	bool			              b_lcd_enabled[3];
	bool                    inited;//indicate driver if init
	disp_bsp_init_para      para;
#if defined(CONFIG_ION_SUNXI)
	struct ion_client *client;
	struct ion_handle *handle;
#endif
}disp_drv_info;

struct sunxi_disp_mod {
	disp_mod_id id;
	char name[32];
};

struct __fb_addr_para
{
	uintptr_t fb_paddr;
	int fb_size;
};

#define DISP_RESOURCE(res_name, res_start, res_end, res_flags) \
{\
	.start = (int __force)res_start, \
	.end = (int __force)res_end, \
	.flags = res_flags, \
	.name = #res_name \
},

typedef struct bmp_color_table_entry {
	u8	blue;
	u8	green;
	u8	red;
	u8	reserved;
} __attribute__ ((packed)) bmp_color_table_entry_t;

typedef struct bmp_header {
	/* Header */
	char signature[2];
	u32	file_size;
	u32	reserved;
	u32	data_offset;
	/* InfoHeader */
	u32	size;
	u32	width;
	u32	height;
	u16	planes;
	u16	bit_count;
	u32	compression;
	u32	image_size;
	u32	x_pixels_per_m;
	u32	y_pixels_per_m;
	u32	colors_used;
	u32	colors_important;
	/* ColorTable */

} __attribute__ ((packed)) bmp_header_t;

typedef struct bmp_image {
	bmp_header_t header;
	/* We use a zero sized array just as a placeholder for variable
	   sized array */
	bmp_color_table_entry_t color_table[0];
} bmp_image_t;

typedef struct
{
	int x;
	int y;
	int bit;
	void *buffer;
}
sunxi_bmp_store_t;

//int disp_open(struct inode *inode, struct file *file);
//int disp_release(struct inode *inode, struct file *file);
//ssize_t disp_read(struct file *file, char __user *buf, size_t count, loff_t *ppos);
//ssize_t disp_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos);
//int disp_mmap(struct file *file, struct vm_area_struct * vma);
//long disp_ioctl(struct file *file, unsigned int cmd, unsigned long arg);

s32 disp_create_heap(u32 pHeapHead, u32 pHeapHeadPhy, u32 nHeapSize);
void *disp_malloc(u32 num_bytes, void *phy_addr);
void  disp_free(void *virt_addr, void* phy_addr, u32 num_bytes);

extern s32 disp_register_sync_proc(void (*proc)(u32));
extern s32 disp_unregister_sync_proc(void (*proc)(u32));
extern s32 disp_register_sync_finish_proc(void (*proc)(u32));
extern s32 disp_unregister_sync_finish_proc(void (*proc)(u32));
extern s32 disp_register_ioctl_func(unsigned int cmd, int (*proc)(unsigned int cmd, unsigned long arg));
extern s32 disp_unregister_ioctl_func(unsigned int cmd);
extern s32 disp_register_standby_func(int (*suspend)(void), int (*resume)(void));
extern s32 disp_unregister_standby_func(int (*suspend)(void), int (*resume)(void));
extern s32 composer_init(disp_drv_info *psg_disp_drv);
extern unsigned int composer_dump(char* buf);
extern s32 disp_tv_register(struct disp_tv_func * func);
extern s32 disp_set_hdmi_detect(bool hpd);

extern disp_drv_info    g_disp_drv;

extern int sunxi_disp_get_source_ops(struct sunxi_disp_source_ops *src_ops);
extern s32 disp_lcd_open(u32 sel);
extern s32 disp_lcd_close(u32 sel);
#if defined(__LINUX_PLAT__)
extern s32 fb_init(struct platform_device *pdev);
extern s32 fb_exit(void);
#endif
extern int lcd_init(void);

s32 disp_set_hdmi_func(struct disp_device_func * func);
#if defined(__LINUX_PLAT__)
s32 sunxi_get_fb_addr_para(struct __fb_addr_para *fb_addr_para);
s32 fb_draw_colorbar(char* base, u32 width, u32 height, struct fb_var_screeninfo *var);
s32 fb_draw_gray_pictures(char* base, u32 width, u32 height, struct fb_var_screeninfo *var);
s32 drv_disp_vsync_event(u32 sel);
#endif
void DRV_disp_int_process(u32 sel);
s32 Display_set_fb_timming(u32 sel);
unsigned int disp_boot_para_parse(void);
int disp_get_parameter_for_cmdlind(char *cmdline, char *name, char *value);

#endif


text:
<?php
namespace Ncaneldiee\Rajaongkir;

class International extends Domestic
{
    /**
     * Default account type.
     *
     * @var string
     */
    protected $account_type = 'basic';

    /**
     * API version.
     *
     * @var string
     */
    protected $api_version = 'v2';

    /**
     * Courier list.
     *
     * @var array
     */
    protected $courier = [
        'basic' => [
            'pos' => 'POS Indonesia (POS)',
            'tiki' => 'Citra Van Titipan Kilat (TIKI)',
        ],
        'pro' => [
            'expedito' => 'Expedito Global Indonesia (EXPEDITO)',
            'jne' => 'Jalur Nugraha Ekakurir (JNE)',
            'slis' => 'Solusi Ekspres (SLIS)',
        ],
        'starter' => [],
    ];

    /**
     * Constructor.
     *
     * @param  string  $account_key
     * @param  string|null  $account_type
     * @return void
     */
    public function __construct($account_key, $account_type = null)
    {
        parent::__construct($account_key, $account_type);
    }

    /**
     * Get shipping cost and delivery time.
     *
     * @param  int  $origin
     * @param  int  $destination
     * @param  int|array  $shipment
     * @param  string  $courier
     * @return object
     */
    public function cost($origin, $destination, $shipment, $courier = null)
    {
        $courier = mb_strtolower($courier);

        $parameter = $this->shipment($shipment);
        $parameter['origin'] = $origin;
        $parameter['destination'] = $destination;
        $parameter['courier'] = $courier ?: implode(':', array_keys($this->courier));

        return $this->request($this->api_version . '/internationalCost', $parameter, 'POST');
    }

    /**
     * Get a list or detail of the destination country.
     *
     * @param  int|null  $id
     * @return object
     */
    public function destination($id = null)
    {
        return $this->request($this->api_version . '/internationalDestination', [
            'id' => $id,
        ]);
    }

    /**
     * Get a list or detail of the origin city.
     *
     * @param  int|null  $province
     * @param  int|null  $id
     * @return object
     */
    public function origin($province = null, $id = null)
    {
        return $this->request($this->api_version . '/internationalOrigin', [
            'province' => $province,
            'id' => $id,
        ]);
    }
}


text:
import requests
import json
import os

from posixpath import join as urljoin
from requests_oauthlib import OAuth1Session
import xmltodict

CLIENT_ID = os.getenv('GOODREADS_CLIENT_ID')
CLIENT_SECRET = os.getenv('GOODREADS_CLIENT_SECRET')

# credentials stored to home folder
OAUTH_TOKEN_JSON = os.getenv('GOODREADS_OAUTH_TOKEN_JSON',
                             os.path.expanduser('~/.goodreads.json'))

# these variables take precedence over the .goodreads.json
# this is to simplify travis-ci testing
RESOURCE_OWNER_KEY = os.getenv('GOODREADS_RESOURCE_OWNER_KEY')
RESOURCE_OWNER_SECRET = os.getenv('GOODREADS_RESOURCE_OWNER_SECRET')

req_token_url = 'https://www.goodreads.com/oauth/request_token'
authorize_url = 'https://www.goodreads.com/oauth/authorize'
access_token_url = 'https://www.goodreads.com/oauth/access_token'

class GoodreadsClient(object):
    def __init__(self):
        """Authenticate user with saved credentials.

        GoodreadsClient.authorize_access()
        must be called the very first time
        """

        # load credentials
        if RESOURCE_OWNER_KEY and RESOURCE_OWNER_SECRET:
            access_token = {
                'oauth_token': os.getenv('GOODREAD_RESOURCE_OWNER_KEY'),
                'oauth_token_secret': os.getenv('GOODREAD_RESOURCE_OWNER_SECRET')
            }
        else:
            with open(OAUTH_TOKEN_JSON, 'r') as fp:
                access_token = json.load(fp)

        self.session = OAuth1Session(
            CLIENT_ID,
            client_secret=CLIENT_SECRET,
            resource_owner_key=access_token['oauth_token'],
            resource_owner_secret=access_token['oauth_token_secret'])

        self.user = self.auth_user

    @staticmethod
    def authorize_access():
        """Authorize the app on Goodreads to access user data.

        Run this once before doing anything else.
        """

        goodreads = OAuth1Session(CLIENT_ID, client_secret=CLIENT_SECRET)
        oauth_token = goodreads.fetch_request_token(req_token_url)
        authorization_url = goodreads.authorization_url(authorize_url)

        raw_input("""Visit the following link to approve the app:
        -----------------------------------------------------
        {}
        -----------------------------------------------------
        Press Return when done
        """.format(authorization_url))

        # fetch oauth access token
        # the verifier needs somevalue, probably any will do
        access_token = goodreads.fetch_access_token(access_token_url,
                                                    verifier=u'y')

        with open(OAUTH_TOKEN_JSON, 'w') as fp:
            json.dump(access_token, fp)

        return access_token

    @staticmethod
    def parse_response(goodreads_response):
        return xmltodict.parse(goodreads_response.content)['GoodreadsResponse']

    def get(self, what, **params):
        """Calling the API"""
        url = urljoin('https://goodreads.com', what)
        return self.session.get(url, params=params)

    @property
    def auth_user(self):
        user_req = self.get('api/auth_user')
        user = GoodreadsClient.parse_response(user_req)['user']
        return user

    @property
    def owned_books(self):
        books_req = self.get(
            'owned_books/user',
            id=self.user['@id'],
            format='xml')
        parsed = GoodreadsClient.parse_response(books_req)
        return parsed['owned_books']['owned_book']

    @property
    def user_shelves(self):
        shelves_req = self.get('shelf/list.xml', user_id=self.user['@id'])
        user_shelves = GoodreadsClient.parse_response(
            shelves_req)['shelves']['user_shelf']
        return user_shelves


text:
namespace tensorflow {

namespace {

const ::google::protobuf::Descriptor* TensorDescription_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
  TensorDescription_reflection_ = NULL;

}  // namespace

void protobuf_AssignDesc_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto() {
  protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto();
  const ::google::protobuf::FileDescriptor* file =
    ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
      "tensorflow/core/framework/tensor_description.proto");
  GOOGLE_CHECK(file != NULL);
  TensorDescription_descriptor_ = file->message_type(0);
  static const int TensorDescription_offsets_[3] = {
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorDescription, dtype_),
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorDescription, shape_),
    GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorDescription, allocation_description_),
  };
  TensorDescription_reflection_ =
    ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
      TensorDescription_descriptor_,
      TensorDescription::default_instance_,
      TensorDescription_offsets_,
      -1,
      -1,
      -1,
      sizeof(TensorDescription),
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorDescription, _internal_metadata_),
      GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TensorDescription, _is_default_instance_));
}

namespace {

GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
  ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
                 &protobuf_AssignDesc_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto);
}

void protobuf_RegisterTypes(const ::std::string&) {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
      TensorDescription_descriptor_, &TensorDescription::default_instance());
}

}  // namespace

void protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto() {
  delete TensorDescription::default_instance_;
  delete TensorDescription_reflection_;
}

void protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto() {
  static bool already_here = false;
  if (already_here) return;
  already_here = true;
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  ::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftypes_2eproto();
  ::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftensor_5fshape_2eproto();
  ::tensorflow::protobuf_AddDesc_tensorflow_2fcore_2fframework_2fallocation_5fdescription_2eproto();
  ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
    "\n2tensorflow/core/framework/tensor_descr"
    "iption.proto\022\ntensorflow\032%tensorflow/cor"
    "e/framework/types.proto\032,tensorflow/core"
    "/framework/tensor_shape.proto\0326tensorflo"
    "w/core/framework/allocation_description."
    "proto\"\250\001\n\021TensorDescription\022#\n\005dtype\030\001 \001"
    "(\0162\024.tensorflow.DataType\022+\n\005shape\030\002 \001(\0132"
    "\034.tensorflow.TensorShapeProto\022A\n\026allocat"
    "ion_description\030\004 \001(\0132!.tensorflow.Alloc"
    "ationDescriptionB8\n\030org.tensorflow.frame"
    "workB\027TensorDescriptionProtosP\001\370\001\001b\006prot"
    "o3", 442);
  ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
    "tensorflow/core/framework/tensor_description.proto", &protobuf_RegisterTypes);
  TensorDescription::default_instance_ = new TensorDescription();
  TensorDescription::default_instance_->InitAsDefaultInstance();
  ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto);
}

// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto {
  StaticDescriptorInitializer_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto() {
    protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto();
  }
} static_descriptor_initializer_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto_;

namespace {

static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD;
static void MergeFromFail(int line) {
  GOOGLE_CHECK(false) << __FILE__ << ":" << line;
}

}  // namespace

// ===================================================================

void TensorDescription::_slow_mutable_shape() {
  shape_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorShapeProto >(
      GetArenaNoVirtual());
}
::tensorflow::TensorShapeProto* TensorDescription::_slow_release_shape() {
  if (shape_ == NULL) {
    return NULL;
  } else {
    ::tensorflow::TensorShapeProto* temp = new ::tensorflow::TensorShapeProto;
    temp->MergeFrom(*shape_);
    shape_ = NULL;
    return temp;
  }
}
::tensorflow::TensorShapeProto* TensorDescription::unsafe_arena_release_shape() {
  // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorDescription.shape)

  ::tensorflow::TensorShapeProto* temp = shape_;
  shape_ = NULL;
  return temp;
}
void TensorDescription::_slow_set_allocated_shape(
    ::google::protobuf::Arena* message_arena, ::tensorflow::TensorShapeProto** shape) {
    if (message_arena != NULL &&
        ::google::protobuf::Arena::GetArena(*shape) == NULL) {
      message_arena->Own(*shape);
    } else if (message_arena !=
               ::google::protobuf::Arena::GetArena(*shape)) {
      ::tensorflow::TensorShapeProto* new_shape =
            ::google::protobuf::Arena::CreateMessage< ::tensorflow::TensorShapeProto >(
            message_arena);
      new_shape->CopyFrom(**shape);
      *shape = new_shape;
    }
}
void TensorDescription::unsafe_arena_set_allocated_shape(
    ::tensorflow::TensorShapeProto* shape) {
  if (GetArenaNoVirtual() == NULL) {
    delete shape_;
  }
  shape_ = shape;
  if (shape) {

  } else {

  }
  // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorDescription.shape)
}
void TensorDescription::_slow_mutable_allocation_description() {
  allocation_description_ = ::google::protobuf::Arena::CreateMessage< ::tensorflow::AllocationDescription >(
      GetArenaNoVirtual());
}
::tensorflow::AllocationDescription* TensorDescription::_slow_release_allocation_description() {
  if (allocation_description_ == NULL) {
    return NULL;
  } else {
    ::tensorflow::AllocationDescription* temp = new ::tensorflow::AllocationDescription;
    temp->MergeFrom(*allocation_description_);
    allocation_description_ = NULL;
    return temp;
  }
}
::tensorflow::AllocationDescription* TensorDescription::unsafe_arena_release_allocation_description() {
  // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.TensorDescription.allocation_description)

  ::tensorflow::AllocationDescription* temp = allocation_description_;
  allocation_description_ = NULL;
  return temp;
}
void TensorDescription::_slow_set_allocated_allocation_description(
    ::google::protobuf::Arena* message_arena, ::tensorflow::AllocationDescription** allocation_description) {
    if (message_arena != NULL &&
        ::google::protobuf::Arena::GetArena(*allocation_description) == NULL) {
      message_arena->Own(*allocation_description);
    } else if (message_arena !=
               ::google::protobuf::Arena::GetArena(*allocation_description)) {
      ::tensorflow::AllocationDescription* new_allocation_description =
            ::google::protobuf::Arena::CreateMessage< ::tensorflow::AllocationDescription >(
            message_arena);
      new_allocation_description->CopyFrom(**allocation_description);
      *allocation_description = new_allocation_description;
    }
}
void TensorDescription::unsafe_arena_set_allocated_allocation_description(
    ::tensorflow::AllocationDescription* allocation_description) {
  if (GetArenaNoVirtual() == NULL) {
    delete allocation_description_;
  }
  allocation_description_ = allocation_description;
  if (allocation_description) {

  } else {

  }
  // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.TensorDescription.allocation_description)
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int TensorDescription::kDtypeFieldNumber;
const int TensorDescription::kShapeFieldNumber;
const int TensorDescription::kAllocationDescriptionFieldNumber;
#endif  // !defined(_MSC_VER) || _MSC_VER >= 1900

TensorDescription::TensorDescription()
  : ::google::protobuf::Message(), _internal_metadata_(NULL) {
  SharedCtor();
  // @@protoc_insertion_point(constructor:tensorflow.TensorDescription)
}

TensorDescription::TensorDescription(::google::protobuf::Arena* arena)
  : ::google::protobuf::Message(),
  _internal_metadata_(arena) {
  SharedCtor();
  RegisterArenaDtor(arena);
  // @@protoc_insertion_point(arena_constructor:tensorflow.TensorDescription)
}

void TensorDescription::InitAsDefaultInstance() {
  _is_default_instance_ = true;
  shape_ = const_cast< ::tensorflow::TensorShapeProto*>(&::tensorflow::TensorShapeProto::default_instance());
  allocation_description_ = const_cast< ::tensorflow::AllocationDescription*>(&::tensorflow::AllocationDescription::default_instance());
}

TensorDescription::TensorDescription(const TensorDescription& from)
  : ::google::protobuf::Message(),
    _internal_metadata_(NULL) {
  SharedCtor();
  MergeFrom(from);
  // @@protoc_insertion_point(copy_constructor:tensorflow.TensorDescription)
}

void TensorDescription::SharedCtor() {
    _is_default_instance_ = false;
  _cached_size_ = 0;
  dtype_ = 0;
  shape_ = NULL;
  allocation_description_ = NULL;
}

TensorDescription::~TensorDescription() {
  // @@protoc_insertion_point(destructor:tensorflow.TensorDescription)
  SharedDtor();
}

void TensorDescription::SharedDtor() {
  if (GetArenaNoVirtual() != NULL) {
    return;
  }

  if (this != default_instance_) {
    delete shape_;
    delete allocation_description_;
  }
}

void TensorDescription::ArenaDtor(void* object) {
  TensorDescription* _this = reinterpret_cast< TensorDescription* >(object);
  (void)_this;
}
void TensorDescription::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void TensorDescription::SetCachedSize(int size) const {
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* TensorDescription::descriptor() {
  protobuf_AssignDescriptorsOnce();
  return TensorDescription_descriptor_;
}

const TensorDescription& TensorDescription::default_instance() {
  if (default_instance_ == NULL) protobuf_AddDesc_tensorflow_2fcore_2fframework_2ftensor_5fdescription_2eproto();
  return *default_instance_;
}

TensorDescription* TensorDescription::default_instance_ = NULL;

TensorDescription* TensorDescription::New(::google::protobuf::Arena* arena) const {
  return ::google::protobuf::Arena::CreateMessage<TensorDescription>(arena);
}

void TensorDescription::Clear() {
// @@protoc_insertion_point(message_clear_start:tensorflow.TensorDescription)
  dtype_ = 0;
  if (GetArenaNoVirtual() == NULL && shape_ != NULL) delete shape_;
  shape_ = NULL;
  if (GetArenaNoVirtual() == NULL && allocation_description_ != NULL) delete allocation_description_;
  allocation_description_ = NULL;
}

bool TensorDescription::MergePartialFromCodedStream(
    ::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
  ::google::protobuf::uint32 tag;
  // @@protoc_insertion_point(parse_start:tensorflow.TensorDescription)
  for (;;) {
    ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
    tag = p.first;
    if (!p.second) goto handle_unusual;
    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
      // optional .tensorflow.DataType dtype = 1;
      case 1: {
        if (tag == 8) {
          int value;
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
                 input, &value)));
          set_dtype(static_cast< ::tensorflow::DataType >(value));
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(18)) goto parse_shape;
        break;
      }

      // optional .tensorflow.TensorShapeProto shape = 2;
      case 2: {
        if (tag == 18) {
         parse_shape:
          DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
               input, mutable_shape()));
        } else {
          goto handle_unusual;
        }
        if (input->ExpectTag(34)) goto parse_allocation_description;
        break;
      }

      // optional .tensorflow.AllocationDescription allocation_description = 4;
      case 4: {
        if (tag == 34) {
         parse_allocation_description:
          DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
               input, mutable_allocation_description()));
        } else {
          goto handle_unusual;
        }
        if (input->ExpectAtEnd()) goto success;
        break;
      }

      default: {
      handle_unusual:
        if (tag == 0 ||
            ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
            ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
          goto success;
        }
        DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
        break;
      }
    }
  }
success:
  // @@protoc_insertion_point(parse_success:tensorflow.TensorDescription)
  return true;
failure:
  // @@protoc_insertion_point(parse_failure:tensorflow.TensorDescription)
  return false;
#undef DO_
}

void TensorDescription::SerializeWithCachedSizes(
    ::google::protobuf::io::CodedOutputStream* output) const {
  // @@protoc_insertion_point(serialize_start:tensorflow.TensorDescription)
  // optional .tensorflow.DataType dtype = 1;
  if (this->dtype() != 0) {
    ::google::protobuf::internal::WireFormatLite::WriteEnum(
      1, this->dtype(), output);
  }

  // optional .tensorflow.TensorShapeProto shape = 2;
  if (this->has_shape()) {
    ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
      2, *this->shape_, output);
  }

  // optional .tensorflow.AllocationDescription allocation_description = 4;
  if (this->has_allocation_description()) {
    ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
      4, *this->allocation_description_, output);
  }

  // @@protoc_insertion_point(serialize_end:tensorflow.TensorDescription)
}

::google::protobuf::uint8* TensorDescription::SerializeWithCachedSizesToArray(
    ::google::protobuf::uint8* target) const {
  // @@protoc_insertion_point(serialize_to_array_start:tensorflow.TensorDescription)
  // optional .tensorflow.DataType dtype = 1;
  if (this->dtype() != 0) {
    target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
      1, this->dtype(), target);
  }

  // optional .tensorflow.TensorShapeProto shape = 2;
  if (this->has_shape()) {
    target = ::google::protobuf::internal::WireFormatLite::
      WriteMessageNoVirtualToArray(
        2, *this->shape_, target);
  }

  // optional .tensorflow.AllocationDescription allocation_description = 4;
  if (this->has_allocation_description()) {
    target = ::google::protobuf::internal::WireFormatLite::
      WriteMessageNoVirtualToArray(
        4, *this->allocation_description_, target);
  }

  // @@protoc_insertion_point(serialize_to_array_end:tensorflow.TensorDescription)
  return target;
}

int TensorDescription::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:tensorflow.TensorDescription)
  int total_size = 0;

  // optional .tensorflow.DataType dtype = 1;
  if (this->dtype() != 0) {
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::EnumSize(this->dtype());
  }

  // optional .tensorflow.TensorShapeProto shape = 2;
  if (this->has_shape()) {
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
        *this->shape_);
  }

  // optional .tensorflow.AllocationDescription allocation_description = 4;
  if (this->has_allocation_description()) {
    total_size += 1 +
      ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
        *this->allocation_description_);
  }

  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = total_size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
  return total_size;
}

void TensorDescription::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:tensorflow.TensorDescription)
  if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
  const TensorDescription* source =
      ::google::protobuf::internal::DynamicCastToGenerated<const TensorDescription>(
          &from);
  if (source == NULL) {
  // @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.TensorDescription)
    ::google::protobuf::internal::ReflectionOps::Merge(from, this);
  } else {
  // @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.TensorDescription)
    MergeFrom(*source);
  }
}

void TensorDescription::MergeFrom(const TensorDescription& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.TensorDescription)
  if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
  if (from.dtype() != 0) {
    set_dtype(from.dtype());
  }
  if (from.has_shape()) {
    mutable_shape()->::tensorflow::TensorShapeProto::MergeFrom(from.shape());
  }
  if (from.has_allocation_description()) {
    mutable_allocation_description()->::tensorflow::AllocationDescription::MergeFrom(from.allocation_description());
  }
}

void TensorDescription::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:tensorflow.TensorDescription)
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

void TensorDescription::CopyFrom(const TensorDescription& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.TensorDescription)
  if (&from == this) return;
  Clear();
  MergeFrom(from);
}

bool TensorDescription::IsInitialized() const {

  return true;
}

void TensorDescription::Swap(TensorDescription* other) {
  if (other == this) return;
  if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
    InternalSwap(other);
  } else {
    TensorDescription temp;
    temp.MergeFrom(*this);
    CopyFrom(*other);
    other->CopyFrom(temp);
  }
}
void TensorDescription::UnsafeArenaSwap(TensorDescription* other) {
  if (other == this) return;
  GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
  InternalSwap(other);
}
void TensorDescription::InternalSwap(TensorDescription* other) {
  std::swap(dtype_, other->dtype_);
  std::swap(shape_, other->shape_);
  std::swap(allocation_description_, other->allocation_description_);
  _internal_metadata_.Swap(&other->_internal_metadata_);
  std::swap(_cached_size_, other->_cached_size_);
}

::google::protobuf::Metadata TensorDescription::GetMetadata() const {
  protobuf_AssignDescriptorsOnce();
  ::google::protobuf::Metadata metadata;
  metadata.descriptor = TensorDescription_descriptor_;
  metadata.reflection = TensorDescription_reflection_;
  return metadata;
}

#if PROTOBUF_INLINE_NOT_IN_HEADERS
// TensorDescription

// optional .tensorflow.DataType dtype = 1;
void TensorDescription::clear_dtype() {
  dtype_ = 0;
}
 ::tensorflow::DataType TensorDescription::dtype() const {
  // @@protoc_insertion_point(field_get:tensorflow.TensorDescription.dtype)
  return static_cast< ::tensorflow::DataType >(dtype_);
}
 void TensorDescription::set_dtype(::tensorflow::DataType value) {

  dtype_ = value;
  // @@protoc_insertion_point(field_set:tensorflow.TensorDescription.dtype)
}

// optional .tensorflow.TensorShapeProto shape = 2;
bool TensorDescription::has_shape() const {
  return !_is_default_instance_ && shape_ != NULL;
}
void TensorDescription::clear_shape() {
  if (GetArenaNoVirtual() == NULL && shape_ != NULL) delete shape_;
  shape_ = NULL;
}
const ::tensorflow::TensorShapeProto& TensorDescription::shape() const {
  // @@protoc_insertion_point(field_get:tensorflow.TensorDescription.shape)
  return shape_ != NULL ? *shape_ : *default_instance_->shape_;
}
::tensorflow::TensorShapeProto* TensorDescription::mutable_shape() {

  if (shape_ == NULL) {
    _slow_mutable_shape();
  }
  // @@protoc_insertion_point(field_mutable:tensorflow.TensorDescription.shape)
  return shape_;
}
::tensorflow::TensorShapeProto* TensorDescription::release_shape() {
  // @@protoc_insertion_point(field_release:tensorflow.TensorDescription.shape)

  if (GetArenaNoVirtual() != NULL) {
    return _slow_release_shape();
  } else {
    ::tensorflow::TensorShapeProto* temp = shape_;
    shape_ = NULL;
    return temp;
  }
}
 void TensorDescription::set_allocated_shape(::tensorflow::TensorShapeProto* shape) {
  ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
  if (message_arena == NULL) {
    delete shape_;
  }
  if (shape != NULL) {
    _slow_set_allocated_shape(message_arena, &shape);
  }
  shape_ = shape;
  if (shape) {

  } else {

  }
  // @@protoc_insertion_point(field_set_allocated:tensorflow.TensorDescription.shape)
}

// optional .tensorflow.AllocationDescription allocation_description = 4;
bool TensorDescription::has_allocation_description() const {
  return !_is_default_instance_ && allocation_description_ != NULL;
}
void TensorDescription::clear_allocation_description() {
  if (GetArenaNoVirtual() == NULL && allocation_description_ != NULL) delete allocation_description_;
  allocation_description_ = NULL;
}
const ::tensorflow::AllocationDescription& TensorDescription::allocation_description() const {
  // @@protoc_insertion_point(field_get:tensorflow.TensorDescription.allocation_description)
  return allocation_description_ != NULL ? *allocation_description_ : *default_instance_->allocation_description_;
}
::tensorflow::AllocationDescription* TensorDescription::mutable_allocation_description() {

  if (allocation_description_ == NULL) {
    _slow_mutable_allocation_description();
  }
  // @@protoc_insertion_point(field_mutable:tensorflow.TensorDescription.allocation_description)
  return allocation_description_;
}
::tensorflow::AllocationDescription* TensorDescription::release_allocation_description() {
  // @@protoc_insertion_point(field_release:tensorflow.TensorDescription.allocation_description)

  if (GetArenaNoVirtual() != NULL) {
    return _slow_release_allocation_description();
  } else {
    ::tensorflow::AllocationDescription* temp = allocation_description_;
    allocation_description_ = NULL;
    return temp;
  }
}
 void TensorDescription::set_allocated_allocation_description(::tensorflow::AllocationDescription* allocation_description) {
  ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
  if (message_arena == NULL) {
    delete allocation_description_;
  }
  if (allocation_description != NULL) {
    _slow_set_allocated_allocation_description(message_arena, &allocation_description);
  }
  allocation_description_ = allocation_description;
  if (allocation_description) {

  } else {

  }
  // @@protoc_insertion_point(field_set_allocated:tensorflow.TensorDescription.allocation_description)
}

#endif  // PROTOBUF_INLINE_NOT_IN_HEADERS

// @@protoc_insertion_point(namespace_scope)

}  // namespace tensorflow

// @@protoc_insertion_point(global_scope)


text:
namespace mojo {
namespace platform {

// An interface for an abstract "thread". Implementations are typically not
// thread-safe and should be used only on the thread it was created on.
class Thread {
 public:
  // Note: If "started", the thread must be joined (i.e., |Stop()| must be
  // called) before destruction.
  virtual ~Thread() {}

  // Requests that the thread stop (if applicable) and joins it.
  virtual void Stop() = 0;

 protected:
  Thread() {}

 private:
  MOJO_DISALLOW_COPY_AND_ASSIGN(Thread);
};

}  // namespace platform
}  // namespace mojo

#endif  // MOJO_EDK_PLATFORM_THREAD_H_


text:
//
// General:
//      This file is part of .NET Bridge
//
// Copyright:
//      2010 Jonathan Shore
//      2017 Jonathan Shore and Contributors
//
// License:
//      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.
//

using System;

namespace bridge.common.time
{

	/// <summary>
	/// date/time info generator
	/// </summary>
	public class ZDateTimeInfoGenerator
	{
		public ZDateTimeInfoGenerator (ZTimeZone zone)
		{
			_zone = zone;
			_zone_offset = (long)zone.BaseUtcOffset.TotalMilliseconds;
		}

		// Functions

		/// <summary>
		/// Date / time information for clock
		/// </summary>
		public ZDateTimeInfo DateAndTimeFor (long clock)
		{
			// if entered a new year need to recompute DST
			if (clock > _year_end || clock < _year_start)
				NewDST (new DateTime(clock * 10000L + 621355968000000000L, DateTimeKind.Utc));

			var dstadj = (clock < _DST_start || clock > _DST_end) ? 0 : _DST_offset;
			var adjclock = clock + _zone_offset + dstadj;

			var timepart = (int)(adjclock % (24L*3600L*1000L));

			var hour = timepart / (3600*1000);
			var min = (timepart % (3600*1000)) / 60000;
			var sec = (timepart % 60000) / 1000;
			var ms = timepart % 1000;

			// determine new date if clock does not fall within day range
			var netclock = adjclock * 10000L + 621355968000000000L;
			if (netclock < _day_start || netclock > _day_end)
 				NewYMD (netclock);

			return new ZDateTimeInfo (_year, _month, _day, hour, min, sec, ms);
		}

		/// <summary>
		/// Date / time information for clock
		/// </summary>
		public ZDateTimeInfo DateFor (long clock)
		{
			// if entered a new year need to recompute DST
			if (clock > _year_end || clock < _year_start)
				NewDST (new DateTime(clock * 10000L + 621355968000000000L, DateTimeKind.Utc));

			var dstadj = (clock < _DST_start || clock > _DST_end) ? 0 : _DST_offset;
			var adjclock = clock + _zone_offset + dstadj;
			var netclock = adjclock * 10000L + 621355968000000000L;

			// determine new date if clock does not fall within day range
			if (netclock < _day_start || netclock > _day_end)
 				NewYMD (netclock);

			return new ZDateTimeInfo (_year, _month, _day);
		}

		/// <summary>
		/// Date / time information for clock
		/// </summary>
		public ZTime TimeFor (long clock)
		{
			// if entered a new year need to recompute DST
			if (clock > _year_end || clock < _year_start)
				NewDST (new DateTime(clock * 10000L + 621355968000000000L, DateTimeKind.Utc));

			var dstadj = (clock < _DST_start || clock > _DST_end) ? 0 : _DST_offset;
			var adjclock = clock + _zone_offset + dstadj;

			var netclock = adjclock * 10000L + 621355968000000000L;
			var timepart = (int)((netclock % TicksPerDay) / 10000L);

			var hour = timepart / (3600*1000);
			var min = (timepart % (3600*1000)) / 60000;
			var sec = (timepart % 60000) / 1000;
			var ms = timepart % 1000;

			return new ZTime (hour,min,sec,ms);
		}

		// Implementation: DST

		private void NewYMD (long netclock)
		{
			// n = number of days since 1/1/0001
            int n = (int)(netclock / TicksPerDay);
            // y400 = number of whole 400-year periods since 1/1/0001
            int y400 = n / DaysPer400Years;
            // n = day number within 400-year period
            n -= y400 * DaysPer400Years;
            // y100 = number of whole 100-year periods within 400-year period
            int y100 = n / DaysPer100Years;
            // Last 100-year period has an extra day, so decrement result if 4
            if (y100 == 4) y100 = 3;
            // n = day number within 100-year period
            n -= y100 * DaysPer100Years;
            // y4 = number of whole 4-year periods within 100-year period
            int y4 = n / DaysPer4Years;
            // n = day number within 4-year period
            n -= y4 * DaysPer4Years;
            // y1 = number of whole years within 4-year period
            int y1 = n / DaysPerYear;
            // Last year has an extra day, so decrement result if 4
            if (y1 == 4) y1 = 3;
            _year = y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;

            // n = day number within year
            n -= y1 * DaysPerYear;

			// Leap year calculation looks different from IsLeapYear since y1, y4, and y100 are relative to year 1, not year 0
            bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
            int[] days = leapYear? DaysToMonth366: DaysToMonth365;

			// All months have less than 32 days, so n >> 5 is a good conservative estimate for the month
            var month = n >> 5 + 1;
            // m = 1-based month number
            while (n >= days[month]) month++;
			_month = month;

            // Return 1-based day-of-month
            _day = n - days[month - 1] + 1;

			// setup day window
			_day_start = (netclock / TicksPerDay) * TicksPerDay;
			_day_end = (_day_start + TicksPerDay - 1);
		}

		private void NewDST (DateTime time)
		{
			var rule = GetApplicableRule (_zone, time);
			var year = time.Year;
			var utcoffset = _zone.Underlier.BaseUtcOffset;

			if (rule != null)
			{
				var Rstart = rule.DaylightTransitionStart;
				var Rend = rule.DaylightTransitionEnd;

				DateTime DST_start = TransitionPoint (
					Rstart, year);
				DateTime DST_end = TransitionPoint (
					Rend,
					year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));

				DST_start -= utcoffset;
				DST_end -= (utcoffset + rule.DaylightDelta);

				_DST_start = (DST_start.Ticks - 621355968000000000L) / 10000L;
				_DST_end = (DST_end.Ticks - 621355968000000000L) / 10000L;
				_DST_offset = (long)rule.DaylightDelta.TotalMilliseconds;

				DateTime ystart = new DateTime(year, 1, 1, 0,0,0,0, DateTimeKind.Utc) - utcoffset;
				DateTime yend = new DateTime(year, 12, 31, 23,59,59,999, DateTimeKind.Utc) - utcoffset;

				_year_start = (ystart.Ticks - 621355968000000000L) / 10000L;
				_year_end = (yend.Ticks - 621355968000000000L) / 10000L;
			}
			else
			{
				_DST_start = long.MaxValue;
				_DST_end = 0;
				_DST_offset = 0;

				DateTime ystart = new DateTime(year, 1, 1, 0,0,0,0, DateTimeKind.Utc) - utcoffset;
				DateTime yend = new DateTime(year, 12, 31, 23,59,59,999, DateTimeKind.Utc) - utcoffset;

				_year_start = (ystart.Ticks - 621355968000000000L) / 10000L;
				_year_end = (yend.Ticks - 621355968000000000L) / 10000L;

			}
		}

		private TimeZoneInfo.AdjustmentRule GetApplicableRule (ZTimeZone ourzone, DateTime time)
		{
			TimeZoneInfo zone = ourzone.Underlier;
			if (zone == TimeZoneInfo.Utc)
				return null;

			var Tclock = time.Ticks + zone.BaseUtcOffset.Ticks;

			// use local to avoid another thread changing reference during test
			var srule = _rule;
			if (srule != null && IsAppropriateRule (srule, Tclock))
				return srule;

			var rulelist = zone.GetAdjustmentRules();
			foreach (var rule in rulelist)
			{
				if (IsAppropriateRule (rule, Tclock))
					return _rule = rule;
			}

			return null;
		}

		private bool IsAppropriateRule (TimeZoneInfo.AdjustmentRule rule, long Tclock)
		{
			if (rule.DateStart.Ticks > Tclock)
				return false;
			if (rule.DateEnd.Ticks >= Tclock)
				return true;
			else
				return false;
		}

		private DateTime TransitionPoint (TimeZoneInfo.TransitionTime transition, int year)
		{
			if (transition.IsFixedDateRule)
				return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;

			DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
			DayOfWeek target = transition.DayOfWeek;

			// locate first dayofweek
			int dayadjust = (first > target) ? (7 - (int)first + 1) : ((int)target - (int)first + 1);
			// roll to the nth
			int day = dayadjust + (transition.Week - 1) * 7;
			if (day >  DateTime.DaysInMonth (year, transition.Month))
				day -= 7;

			return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
		}

		// Constants

		private const int 				dp400 = 146097;
		private const int				dp100 = 36524;
		private const int				dp4 = 1461;

		// Number of 100ns ticks per time unit
        private const long 				TicksPerMillisecond = 10000;
        private const long 				TicksPerSecond = TicksPerMillisecond * 1000;
        private const long 				TicksPerMinute = TicksPerSecond * 60;
        private const long 				TicksPerHour = TicksPerMinute * 60;
        private const long 				TicksPerDay = TicksPerHour * 24;

        // Number of milliseconds per time unit
        private const int 				MillisPerSecond = 1000;
        private const int 				MillisPerMinute = MillisPerSecond * 60;
        private const int 				MillisPerHour = MillisPerMinute * 60;
        private const int 				MillisPerDay = MillisPerHour * 24;

        // Number of days in a non-leap year
        private const int 				DaysPerYear = 365;
        // Number of days in 4 years
        private const int 				DaysPer4Years = DaysPerYear * 4 + 1;
        // Number of days in 100 years
        private const int 				DaysPer100Years = DaysPer4Years * 25 - 1;
        // Number of days in 400 years
        private const int 				DaysPer400Years = DaysPer100Years * 4 + 1;

        // Number of days from 1/1/0001 to 12/31/1600
        private const int 				DaysTo1601 = DaysPer400Years * 4;
        // Number of days from 1/1/0001 to 12/30/1899
        private const int 				DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;
        // Number of days from 1/1/0001 to 12/31/9999
        private const int 				DaysTo10000 = DaysPer400Years * 25 - 366;

        private const long 				FileTimeOffset = DaysTo1601 * TicksPerDay;
        private const long 				DoubleDateOffset = DaysTo1899 * TicksPerDay;

		// The minimum OA date is 0100/01/01 & the maximum OA date is 9999/12/31
        private const long 				OADateMinAsTicks = (DaysPer100Years - DaysPerYear) * TicksPerDay;
        // All OA dates must be greater than (not >=) OADateMinAsDouble
        private const double 			OADateMinAsDouble = -657435.0;
        // All OA dates must be less than (not <=) OADateMaxAsDouble
        private const double 			OADateMaxAsDouble = 2958466.0;

        private static readonly int[] DaysToMonth365 =
			{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
        private static readonly int[] DaysToMonth366 =
			{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };

		// Variables

		private TimeZoneInfo.AdjustmentRule 	_rule;
		private ZTimeZone						_zone;
		private long							_zone_offset;

		private long							_year_start;
		private long							_year_end;
		private long							_day_start;
		private long							_day_end;

		private long							_DST_start;
		private long							_DST_end;
		private long							_DST_offset;

		private int								_year;
		private int								_month;
		private int								_day;
	}

}


text:
/**
 * Support for building Spring Boot applications using Ant.
 */
package org.springframework.boot.ant;


text:
function [J] = costFunctionJ (X, y, theta)
  % X is the design matrix
  % y is a column vector
  % theta is a column vector

  m = size(X, 1);
  predictions = X * theta;
  sqrErrors = (predictions - y) .^ 2; % squared errors

  J = 1/(2*m) * sum(sqrErrors);
  return;

endfunction


text:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'gwt-numpicker',
    templateUrl: './numpicker.component.html'
})
export class NumPickerComponent implements OnInit {
    @Input() min = 0;
    @Input() max = 10;
    @Input() step = 1;
    @Input() value = 0;
    @Output() valueChanged = new EventEmitter<number>();

    availValues: number[];

    ngOnInit(): void {
        this.refresh();
    }

    selectValue(value: number): void {
        this.value = value;
        this.valueChanged.emit(value);
    }

    private refresh(): void {
        this.availValues = [];

        for (let i = this.min; i <= this.max; i += this.step) {
            this.availValues.push(i);
        }
    }
}


text:
void class_model::set_observer(interface_observer *observer){

  // メンバにセット.
  observer_ = observer; // observer_にobserverをセット.
  observer_->set_subject(this); // observer_->set_subjectで自身(this)をセットすることでobserver_のサブジェクトになる.

}

// メンバ関数notify
void class_model::notify(){

  // notifyが呼ばれた.
  std::cout << "class_model::notify()" << std::endl; // "class_model::notify()"と出力.

  // observer_に通知.
  observer_->changed();

}


text:
import os
import sys
import commands

from gettext import gettext as _
from plugins.plugin import Plugin

from TurtleArt.tapalette import make_palette
from TurtleArt.tapalette import palette_name_to_index
from TurtleArt.tapalette import palette_blocks
from TurtleArt.tapalette import special_block_colors
from TurtleArt.talogo import logoerror
from TurtleArt.taprimitive import Primitive, ArgSlot
from TurtleArt.tatype import TYPE_INT, TYPE_FLOAT, TYPE_STRING, TYPE_NUMBER

sys.path.insert(0, os.path.abspath('./plugins/rodi'))
import pyfirmata

VALUE = {_('HIGH'): 1, _('LOW'): 0}
MODE = {_('INPUT'): pyfirmata.INPUT, _('OUTPUT'): pyfirmata.OUTPUT,
        _('PWM'): pyfirmata.PWM, _('SERVO'): pyfirmata.SERVO}

MAX_SPEED = 90
LEFT_SENSOR = 3
RIGHT_SENSOR = 0
BATTERY_MON = 1
DISTANCE_SENSOR = 2
LEFT_SERVO = 5
RIGHT_SERVO = 6
BUZZER = 9

COLOR_NOTPRESENT = ["#A0A0A0","#808080"]
COLOR_PRESENT = ["#6A8DF6","#5A7DE6"]

ERROR = _('ERROR: Check the connection with the robot.')
ERROR_SPEED = _('ERROR: The speed must be a value between 0 and %d' %(MAX_SPEED))
ERROR_SPEED_ABS = _('ERROR: The speed must be a value between -%(max)d and %(max)d') % {'max': MAX_SPEED}

class Rodi(Plugin):

    def __init__(self, parent):
        Plugin.__init__(self);
        self.tw = parent
        self._baud = 57600
        self.active_rodi = 0
        self._rodis = []
        self._rodis_it = []
        self._rodis_pines = []
        self.actualSpeed = [50, 50]

    def setup(self):
        """ Setup is called once, when the Turtle Window is created. """
        palette = make_palette('rodi', COLOR_NOTPRESENT,
                             _('Palette for Rodi bots using Arduino'))

        palette.add_block('refresh_Rodi',
                     style='basic-style',
                     label=_('refresh Rodi'),
                     prim_name='refresh_Rodi',
                     help_string=_('refresh the state of the Rodi palette and blocks'))
        self.tw.lc.def_prim('refresh_Rodi', 0,
            Primitive(self.refresh_Rodi))
        special_block_colors['refresh_Rodi'] = COLOR_PRESENT[:]

        palette.add_block('select_Rodi',
                          style='basic-style-1arg',
                          default = 1,
                          label=_('Rodi'),
                          help_string=_('set current Rodi robot'),
                          prim_name = 'select_Rodi')
        self.tw.lc.def_prim('select_Rodi', 1,
            Primitive(self.select_Rodi, arg_descs=[ArgSlot(TYPE_NUMBER)]))

        palette.add_block('count_Rodi',
                          style='box-style',
                          label=_('number of Rodis'),
                          help_string=_('number of Rodi robots'),
                          prim_name = 'count_Rodi')
        self.tw.lc.def_prim('count_Rodi', 0,
            Primitive(self.count_Rodi, TYPE_INT))

        palette.add_block('name_Rodi',
                  style='number-style-1arg',
                  label=_('Rodi name'),
                  default=[1],
                  help_string=_('Get the name of a Rodi robot'),
                  prim_name='name_Rodi')
        self.tw.lc.def_prim('name_Rodi', 1,
            Primitive(self.name_Rodi, TYPE_STRING, [ArgSlot(TYPE_NUMBER)]))

        palette.add_block('move_Rodi',
                     style='basic-style-2arg',
                     label=[_('move Rodi'), _('left'), _('right')],
                     prim_name='move_Rodi',
                     default=[50, 50],
                     help_string=_('moves the Rodi motors at the specified speed'))
        self.tw.lc.def_prim('move_Rodi', 2,
            Primitive(self.move_Rodi, arg_descs=[ArgSlot(TYPE_NUMBER), ArgSlot(TYPE_NUMBER)]))
        special_block_colors['move_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('stop_Rodi',
                     style='basic-style',
                     label=_('stop Rodi'),
                     prim_name='stop_Rodi',
                     help_string=_('stop the Rodi robot'))
        self.tw.lc.def_prim('stop_Rodi', 0,
            Primitive(self.stop_Rodi))
        special_block_colors['stop_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('forward_Rodi',
                     style='basic-style',
                     label=_('forward Rodi'),
                     prim_name='forward_Rodi',
                     help_string=_('move the Rodi robot forward'))
        self.tw.lc.def_prim('forward_Rodi', 0,
            Primitive(self.forward_Rodi))
        special_block_colors['forward_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('left_Rodi',
                     style='basic-style',
                     label=_('left Rodi'),
                     prim_name='left_Rodi',
                     help_string=_('turn the Rodi robot at left'))
        self.tw.lc.def_prim('left_Rodi', 0,
            Primitive(self.left_Rodi))
        special_block_colors['left_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('right_Rodi',
                     style='basic-style',
                     label=_('right Rodi'),
                     prim_name='right_Rodi',
                     help_string=_('turn the Rodi robot at right'))
        self.tw.lc.def_prim('right_Rodi', 0,
            Primitive(self.right_Rodi))
        special_block_colors['right_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('backward_Rodi',
                     style='basic-style',
                     label=_('backward Rodi'),
                     prim_name='backward_Rodi',
                     help_string=_('move the Rodi robot backward'))
        self.tw.lc.def_prim('backward_Rodi', 0,
            Primitive(self.backward_Rodi))
        special_block_colors['backward_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('distanced_Rodi',
                     style='box-style',
                     label=_('distance Rodi'),
                     prim_name='distance_Rodi',
                     help_string=_('returns the distance as a value between 0 and 1'))
        self.tw.lc.def_prim('distance_Rodi', 0,
            Primitive(self.distance_Rodi, TYPE_FLOAT))
        special_block_colors['distance_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('left_sensor_Rodi',
                     style='box-style',
                     label=_('left sensor Rodi'),
                     prim_name='left_sensor_Rodi',
                     help_string=_('returns the left line sensor as a value between 0 and 1'))
        self.tw.lc.def_prim('left_sensor_Rodi', 0,
            Primitive(self.left_sensor_Rodi, TYPE_FLOAT))
        special_block_colors['left_sensor_Rodi'] = COLOR_NOTPRESENT[:]

        palette.add_block('right_sensor_Rodi',
                     style='box-style',
                     label=_('right sensor Rodi'),
                     prim_name='right_sensor_Rodi',
                     help_string=_('returns the right line sensor as a value between 0 and 1'))
        self.tw.lc.def_prim('right_sensor_Rodi', 0,
            Primitive(self.right_sensor_Rodi, TYPE_FLOAT))
        special_block_colors['right_sensor_Rodi'] = COLOR_NOTPRESENT[:]

    ############################## Turtle signals ##############################

    def stop(self):
        self.stopRodis()

    def quit(self):
        self.closeRodis()

    ############################ Select functions ##############################

    def select_Rodi(self, i):
        n = len(self._rodis)
        try:
            i = int(i)
        except:
            raise logoerror(_('The device must be an integer'))
        i = i - 1
        if (i < n) and (i >= 0):
            self.active_arduino = i
        else:
            raise logoerror(_('Not found Rodi %s') % (i + 1))

    def count_Rodi(self):
        return len(self._rodis)

    def name_Rodi(self, i):
        n = len(self._rodis)
        try:
            i = int(i)
        except:
            raise logoerror(_('The device must be an integer'))
        i = i - 1
        if (i < n) and (i >= 0):
            a = self._arduinos[i]
            return a.name
        else:
            raise logoerror(_('Not found Rodi %s') % (i + 1))

    ############################## Refresh process #############################

    def _check_init(self):
        n = len(self._rodis)
        if (self.active_rodi > n) or (self.active_rodi < 0):
            raise logoerror(_('Not found Rodi %s') % (self.active_rodi + 1))

    def change_color_blocks(self):
        if len(self._rodis) > 0:
            rodi_present = True
        else:
            rodi_present = False
        index = palette_name_to_index('rodi')
        if index is not None:
            rodi_blocks = palette_blocks[index]
            for block in self.tw.block_list.list:
                if block.type in ['proto', 'block']:
                    if block.name in rodi_blocks:
                        if (rodi_present) or (block.name == 'refresh_Rodi'):
                            special_block_colors[block.name] = COLOR_PRESENT[:]
                        else:
                            special_block_colors[block.name] = COLOR_NOTPRESENT[:]
                        block.refresh()
            self.tw.regenerate_palette(index)

    def refresh_Rodi(self):
        #Close actual Rodis
        self.closeRodis()

        #Search for new Rodis
        #status,output_usb = commands.getstatusoutput("ls /dev/ | grep ttyUSB")
        #output_usb_parsed = output_usb.split('\n')
        #status,output_acm = commands.getstatusoutput("ls /dev/ | grep ttyACM")
        #output_acm_parsed = output_acm.split('\n')

        # add rfcomm to the list of rodis
        status,output_rfc = commands.getstatusoutput("ls /dev/ | grep rfcomm")
        output_rfc_parsed = output_rfc.split('\n')

        #output = output_usb_parsed
        #output.extend(output_acm_parsed)
        output = output_rfc_parsed

        for dev in output:
            if not(dev == ''):
                n = '/dev/%s' % dev
                try:
                    r = pyfirmata.Arduino(n, baudrate=self._baud)
                    it = pyfirmata.util.Iterator(r)
                    it.start()
                    self._rodis.append(r)
                    self._rodis_it.append(it)
                except:
                    raise logoerror(_('Error loading %s board') % n)

        self.change_color_blocks()

    ############################ Movement calls ################################

    def set_vels(self, left, right):
        try:
            r = self._rodis[self.active_rodi]
            #lMode = r.digital[LEFT_SERVO]._get_mode()
            #rMode = r.digital[RIGHT_SERVO]._get_mode()
            if left == 0:
                r.digital[LEFT_SERVO]._set_mode(MODE['OUTPUT'])
            else:
                r.digital[LEFT_SERVO]._set_mode(MODE['SERVO'])
                r.digital[LEFT_SERVO].write(MAX_SPEED + left)

            if right == 0:
                r.digital[RIGHT_SERVO]._set_mode(MODE['OUTPUT'])
            else:
                r.digital[RIGHT_SERVO]._set_mode(MODE['SERVO'])
                r.digital[RIGHT_SERVO].write(MAX_SPEED - right)
        except:
            raise logoerror(ERROR)

    def move_Rodi(self, left, right):
        try:
            left = int(left)
        except:
            left = 0
        if (left < -MAX_SPEED) or (left > MAX_SPEED):
            raise logoerror(ERROR_SPEED_ABS)
        try:
            right = int(right)
        except:
            right = 0
        if (right < -MAX_SPEED) or (right > MAX_SPEED):
            raise logoerror(ERROR_SPEED_ABS)
        self.set_vels(left, right)

    def forward_Rodi(self):
        self.set_vels(self.actualSpeed[0], self.actualSpeed[1])

    def backward_Rodi(self):
        self.set_vels(-self.actualSpeed[0], -self.actualSpeed[1])

    def left_Rodi(self):
        self.set_vels(-self.actualSpeed[0], self.actualSpeed[1])

    def right_Rodi(self):
        self.set_vels(self.actualSpeed[0], -self.actualSpeed[1])

    def stop_Rodi(self):
        self.set_vels(0, 0)

    ################################ Sensors calls ################################

    def distance_Rodi(self):
        res = -1
        try:
            r = self._rodis[self.active_rodi]
            r.analog[DISTANCE_SENSOR].enable_reporting()
            r.pass_time(0.05)
            res = r.analog[DISTANCE_SENSOR].read()
            r.analog[DISTANCE_SENSOR].disable_reporting()
        except:
            pass
        return res

    def left_sensor_Rodi(self):
        res = -1
        try:
            r = self._rodis[self.active_rodi]
            r.analog[LEFT_SENSOR].enable_reporting()
            r.pass_time(0.05)
            res = r.analog[LEFT_SENSOR].read()
            r.analog[LEFT_SENSOR].disable_reporting()
        except:
            pass
        return res

    def right_sensor_Rodi(self):
        res = -1
        try:
            r = self._rodis[self.active_rodi]
            r.analog[RIGHT_SENSOR].enable_reporting()
            r.pass_time(0.05)
            res = r.analog[RIGHT_SENSOR].read()
            r.analog[RIGHT_SENSOR].disable_reporting()
        except:
            pass
        return res

    def closeRodis(self):
        for dev in self._rodis:
            try:
                dev.exit()
            except:
                pass
        self._rodis = []
        self._rodis_it = []

    def stopRodis(self):
        for dev in self._rodis:
            try:
                dev.digital[LEFT_SERVO]._set_mode(MODE['OUTPUT'])
                dev.digital[RIGHT_SERVO]._set_mode(MODE['OUTPUT'])
            except:
                pass


text:
GO111MODULE=on

install:
	@go get

gen_examples: install
	@protoc --go_out=./_examples/ --gohttp_out=./_examples/ --go_opt=paths=source_relative -I_examples ./_examples/*.proto

gen_pb:
	@protoc --go_out=./testdata/ --gohttp_out=./testdata/ --go_opt=paths=source_relative -I testdata ./testdata/**/*.proto

test: test_examples
	@go test ./...

test_examples:
	@cd _examples && go test

run_examples:
	@cd _examples && go run main.go greeter.pb.go greeter.http.go

curl_google_option_proto:
	@curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/annotations.proto > _examples/google/api/annotations.proto
	@curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/annotations.proto > testdata/google/api/annotations.proto
	@curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/http.proto > _examples/google/api/http.proto
	@curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/api/http.proto > testdata/google/api/http.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/any.proto> _examples/google/protobuf/any.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/any.proto> testdata/google/protobuf/any.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/api.proto> _examples/google/protobuf/api.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/api.proto> testdata/google/protobuf/api.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/duration.proto> _examples/google/protobuf/duration.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/duration.proto> testdata/google/protobuf/duration.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/empty.proto> _examples/google/protobuf/empty.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/empty.proto> testdata/google/protobuf/empty.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/field_mask.proto> _examples/google/protobuf/field_mask.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/field_mask.proto> testdata/google/protobuf/field_mask.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/source_context.proto> _examples/google/protobuf/source_context.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/source_context.proto> testdata/google/protobuf/source_context.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/struct.proto> _examples/google/protobuf/struct.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/struct.proto> testdata/google/protobuf/struct.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/timestamp.proto> _examples/google/protobuf/timestamp.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/timestamp.proto> testdata/google/protobuf/timestamp.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/type.proto> _examples/google/protobuf/type.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/type.proto> testdata/google/protobuf/type.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/wrappers.proto> _examples/google/protobuf/wrappers.proto
	@curl https://raw.githubusercontent.com/protocolbuffers/protobuf/master/src/google/protobuf/wrappers.proto> testdata/google/protobuf/wrappers.proto


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>PinkWink</title>
    <meta name="description" content="Robot, Data Science, AI, Engineer" />

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

    <link rel="shortcut icon" href="/assets/images/favicon.ico" >

    <link rel="stylesheet" type="text/css" href="/assets/css/screen.css" />
    <link rel="stylesheet" type="text/css"
          href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
    <link rel="stylesheet" type="text/css" href="/assets/css/syntax.css" />

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css">

        <link rel="canonical" href="https://pinkwink.github.io///tag/Control/" />
    <meta name="referrer" content="origin" />
    <link rel="next" href="/page2/" />

    <meta property="og:site_name" content="PinkWink" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="PinkWink" />
    <meta property="og:description" content="Robot, Data Science, AI, Engineer" />
    <meta property="og:url" content="https://pinkwink.github.io///tag/Control/" />
    <meta property="og:image" content="/assets/images/cover2.jpg" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="PinkWink" />
    <meta name="twitter:description" content="Robot, Data Science, AI, Engineer" />
    <meta name="twitter:url" content="https://pinkwink.github.io///tag/Control/" />
    <meta name="twitter:image:src" content="/assets/images/cover2.jpg" />

    <meta name="generator" content="Jekyll 3.0.0" />
    <link rel="alternate" type="application/rss+xml" title="PinkWink" href="/feed.xml" />

Menu

        Close

Home

About

Robot

Data Science

Control

Total Posts

    Subscribe

            Menu

Control

			    A 1-post collection

     Page 1 of 1

Two-Rotor System Controller Design using T-S Fuzzy Model

The original of this post is PinkWink. Some of the contents have been revised while moving the post written in Korean. Two-Rotor (VTOL) System When the... »

            PinkWink

                on

                       Control

            <time class="post-date" datetime="2017-11-02">02 Nov 2017</time>

     Page 1 of 1

PinkWink © 2017

Proudly published with Jekyll using Jasper