text:
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
//

#pragma once
#include <algorithm>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include "port/sys_time.h"
#include "rocksdb/env.h"
#include "rocksdb/status.h"

#ifdef USE_HDFS
#include <hdfs.h>

namespace rocksdb {

// Thrown during execution when there is an issue with the supplied
// arguments.
class HdfsUsageException : public std::exception { };

// A simple exception that indicates something went wrong that is not
// recoverable.  The intention is for the message to be printed (with
// nothing else) and the process terminate.
class HdfsFatalException : public std::exception {
public:
  explicit HdfsFatalException(const std::string& s) : what_(s) { }
  virtual ~HdfsFatalException() throw() { }
  virtual const char* what() const throw() {
    return what_.c_str();
  }
private:
  const std::string what_;
};

//
// The HDFS environment for rocksdb. This class overrides all the
// file/dir access methods and delegates the thread-mgmt methods to the
// default posix environment.
//
class HdfsEnv : public Env {

 public:
  explicit HdfsEnv(const std::string& fsname) : fsname_(fsname) {
    posixEnv = Env::Default();
    fileSys_ = connectToPath(fsname_);
  }

  virtual ~HdfsEnv() {
    fprintf(stderr, "Destroying HdfsEnv::Default()\n");
    hdfsDisconnect(fileSys_);
  }

  Status NewSequentialFile(const std::string& fname,
                           std::unique_ptr<SequentialFile>* result,
                           const EnvOptions& options) override;

  Status NewRandomAccessFile(const std::string& fname,
                             std::unique_ptr<RandomAccessFile>* result,
                             const EnvOptions& options) override;

  Status NewWritableFile(const std::string& fname,
                         std::unique_ptr<WritableFile>* result,
                         const EnvOptions& options) override;

  Status NewDirectory(const std::string& name,
                      std::unique_ptr<Directory>* result) override;

  Status FileExists(const std::string& fname) override;

  Status GetChildren(const std::string& path,
                     std::vector<std::string>* result) override;

  Status DeleteFile(const std::string& fname) override;

  Status CreateDir(const std::string& name) override;

  Status CreateDirIfMissing(const std::string& name) override;

  Status DeleteDir(const std::string& name) override;

  Status GetFileSize(const std::string& fname, uint64_t* size) override;

  Status GetFileModificationTime(const std::string& fname,
                                 uint64_t* file_mtime) override;

  Status RenameFile(const std::string& src, const std::string& target) override;

  Status LinkFile(const std::string& /*src*/,
                  const std::string& /*target*/) override {
    return Status::NotSupported(); // not supported
  }

  Status LockFile(const std::string& fname, FileLock** lock) override;

  Status UnlockFile(FileLock* lock) override;

  Status NewLogger(const std::string& fname,
                   std::shared_ptr<Logger>* result) override;

  void Schedule(void (*function)(void* arg), void* arg, Priority pri = LOW,
                void* tag = nullptr,
                void (*unschedFunction)(void* arg) = 0) override {
    posixEnv->Schedule(function, arg, pri, tag, unschedFunction);
  }

  int UnSchedule(void* tag, Priority pri) override {
    return posixEnv->UnSchedule(tag, pri);
  }

  void StartThread(void (*function)(void* arg), void* arg) override {
    posixEnv->StartThread(function, arg);
  }

  void WaitForJoin() override { posixEnv->WaitForJoin(); }

  unsigned int GetThreadPoolQueueLen(Priority pri = LOW) const override {
    return posixEnv->GetThreadPoolQueueLen(pri);
  }

  Status GetTestDirectory(std::string* path) override {
    return posixEnv->GetTestDirectory(path);
  }

  uint64_t NowMicros() override { return posixEnv->NowMicros(); }

  void SleepForMicroseconds(int micros) override {
    posixEnv->SleepForMicroseconds(micros);
  }

  Status GetHostName(char* name, uint64_t len) override {
    return posixEnv->GetHostName(name, len);
  }

  Status GetCurrentTime(int64_t* unix_time) override {
    return posixEnv->GetCurrentTime(unix_time);
  }

  Status GetAbsolutePath(const std::string& db_path,
                         std::string* output_path) override {
    return posixEnv->GetAbsolutePath(db_path, output_path);
  }

  void SetBackgroundThreads(int number, Priority pri = LOW) override {
    posixEnv->SetBackgroundThreads(number, pri);
  }

  int GetBackgroundThreads(Priority pri = LOW) override {
    return posixEnv->GetBackgroundThreads(pri);
  }

  void IncBackgroundThreadsIfNeeded(int number, Priority pri) override {
    posixEnv->IncBackgroundThreadsIfNeeded(number, pri);
  }

  std::string TimeToString(uint64_t number) override {
    return posixEnv->TimeToString(number);
  }

  static uint64_t gettid() {
    assert(sizeof(pthread_t) <= sizeof(uint64_t));
    return (uint64_t)pthread_self();
  }

  uint64_t GetThreadID() const override { return HdfsEnv::gettid(); }

 private:
  std::string fsname_;  // string of the form "hdfs://hostname:port/"
  hdfsFS fileSys_;      //  a single FileSystem object for all files
  Env*  posixEnv;       // This object is derived from Env, but not from
                        // posixEnv. We have posixnv as an encapsulated
                        // object here so that we can use posix timers,
                        // posix threads, etc.

  static const std::string kProto;
  static const std::string pathsep;

  /**
   * If the URI is specified of the form hdfs://server:port/path,
   * then connect to the specified cluster
   * else connect to default.
   */
  hdfsFS connectToPath(const std::string& uri) {
    if (uri.empty()) {
      return nullptr;
    }
    if (uri.find(kProto) != 0) {
      // uri doesn't start with hdfs:// -> use default:0, which is special
      // to libhdfs.
      return hdfsConnectNewInstance("default", 0);
    }
    const std::string hostport = uri.substr(kProto.length());

    std::vector <std::string> parts;
    split(hostport, ':', parts);
    if (parts.size() != 2) {
      throw HdfsFatalException("Bad uri for hdfs " + uri);
    }
    // parts[0] = hosts, parts[1] = port/xxx/yyy
    std::string host(parts[0]);
    std::string remaining(parts[1]);

    int rem = static_cast<int>(remaining.find(pathsep));
    std::string portStr = (rem == 0 ? remaining :
                           remaining.substr(0, rem));

    tPort port;
    port = atoi(portStr.c_str());
    if (port == 0) {
      throw HdfsFatalException("Bad host-port for hdfs " + uri);
    }
    hdfsFS fs = hdfsConnectNewInstance(host.c_str(), port);
    return fs;
  }

  void split(const std::string &s, char delim,
             std::vector<std::string> &elems) {
    elems.clear();
    size_t prev = 0;
    size_t pos = s.find(delim);
    while (pos != std::string::npos) {
      elems.push_back(s.substr(prev, pos));
      prev = pos + 1;
      pos = s.find(delim, prev);
    }
    elems.push_back(s.substr(prev, s.size()));
  }
};

}  // namespace rocksdb

#else // USE_HDFS

namespace rocksdb {

static const Status notsup;

class HdfsEnv : public Env {

 public:
  explicit HdfsEnv(const std::string& /*fsname*/) {
    fprintf(stderr, "You have not build rocksdb with HDFS support\n");
    fprintf(stderr, "Please see hdfs/README for details\n");
    abort();
  }

  virtual ~HdfsEnv() {
  }

  virtual Status NewSequentialFile(const std::string& fname,
                                   std::unique_ptr<SequentialFile>* result,
                                   const EnvOptions& options) override;

  virtual Status NewRandomAccessFile(
      const std::string& /*fname*/,
      std::unique_ptr<RandomAccessFile>* /*result*/,
      const EnvOptions& /*options*/) override {
    return notsup;
  }

  virtual Status NewWritableFile(const std::string& /*fname*/,
                                 std::unique_ptr<WritableFile>* /*result*/,
                                 const EnvOptions& /*options*/) override {
    return notsup;
  }

  virtual Status NewDirectory(const std::string& /*name*/,
                              std::unique_ptr<Directory>* /*result*/) override {
    return notsup;
  }

  virtual Status FileExists(const std::string& /*fname*/) override {
    return notsup;
  }

  virtual Status GetChildren(const std::string& /*path*/,
                             std::vector<std::string>* /*result*/) override {
    return notsup;
  }

  virtual Status DeleteFile(const std::string& /*fname*/) override {
    return notsup;
  }

  virtual Status CreateDir(const std::string& /*name*/) override {
    return notsup;
  }

  virtual Status CreateDirIfMissing(const std::string& /*name*/) override {
    return notsup;
  }

  virtual Status DeleteDir(const std::string& /*name*/) override {
    return notsup;
  }

  virtual Status GetFileSize(const std::string& /*fname*/,
                             uint64_t* /*size*/) override {
    return notsup;
  }

  virtual Status GetFileModificationTime(const std::string& /*fname*/,
                                         uint64_t* /*time*/) override {
    return notsup;
  }

  virtual Status RenameFile(const std::string& /*src*/,
                            const std::string& /*target*/) override {
    return notsup;
  }

  virtual Status LinkFile(const std::string& /*src*/,
                          const std::string& /*target*/) override {
    return notsup;
  }

  virtual Status LockFile(const std::string& /*fname*/,
                          FileLock** /*lock*/) override {
    return notsup;
  }

  virtual Status UnlockFile(FileLock* /*lock*/) override { return notsup; }

  virtual Status NewLogger(const std::string& /*fname*/,
                           std::shared_ptr<Logger>* /*result*/) override {
    return notsup;
  }

  virtual void Schedule(void (* /*function*/)(void* arg), void* /*arg*/,
                        Priority /*pri*/ = LOW, void* /*tag*/ = nullptr,
                        void (* /*unschedFunction*/)(void* arg) = 0) override {}

  virtual int UnSchedule(void* /*tag*/, Priority /*pri*/) override { return 0; }

  virtual void StartThread(void (* /*function*/)(void* arg),
                           void* /*arg*/) override {}

  virtual void WaitForJoin() override {}

  virtual unsigned int GetThreadPoolQueueLen(
      Priority /*pri*/ = LOW) const override {
    return 0;
  }

  virtual Status GetTestDirectory(std::string* /*path*/) override {
    return notsup;
  }

  virtual uint64_t NowMicros() override { return 0; }

  virtual void SleepForMicroseconds(int /*micros*/) override {}

  virtual Status GetHostName(char* /*name*/, uint64_t /*len*/) override {
    return notsup;
  }

  virtual Status GetCurrentTime(int64_t* /*unix_time*/) override {
    return notsup;
  }

  virtual Status GetAbsolutePath(const std::string& /*db_path*/,
                                 std::string* /*outputpath*/) override {
    return notsup;
  }

  virtual void SetBackgroundThreads(int /*number*/,
                                    Priority /*pri*/ = LOW) override {}
  virtual int GetBackgroundThreads(Priority /*pri*/ = LOW) override {
    return 0;
  }
  virtual void IncBackgroundThreadsIfNeeded(int /*number*/,
                                            Priority /*pri*/) override {}
  virtual std::string TimeToString(uint64_t /*number*/) override { return ""; }

  virtual uint64_t GetThreadID() const override {
    return 0;
  }
};
}

#endif // USE_HDFS


text:
package models.entity.group

import java.sql.Date
import play.api.db.slick.Profile

trait GroupComponent { this : Profile =>
  import profile.simple._

  class Groups(tag: Tag) extends Table[(Group)](tag, "GROUPS") {

    def id: Column[Int] = column[Int]("ID", O.PrimaryKey, O.AutoInc)
    def name : Column[String] = column[String]("NAME",O.NotNull)
    def refName : Column[String] = column[String]("REF_NAME",O.NotNull)
    def creationDate : Column[Date] = column[Date]("CREATION_DATE",O.NotNull)
    def updateDate : Column[Date] = column[Date]("MODIFICATION_DATE",O.NotNull)
    def updatingUser : Column[String] = column[String]("UPDATING_USER",O.NotNull)
    def descritpion : Column[String] = column[String]("DESCRIPTION",O.Nullable)
    def applicationId : Column[Int] = column[Int]("APPLICATION_ID",O.NotNull)

    override def * = (id.?,name,refName,creationDate,updateDate,updatingUser,descritpion.?,applicationId) <>(Group.tupled, Group.unapply)

  }

}

case class Group(id : Option[Int],name : String,refName : String,creationDate : Date,updateDate : Date,updatingUser : String,description : Option[String],applicationId : Int)

redpajama_set_name: RedPajamaGithub


text:
/* output_elf.c ELF output driver for vasm */
/* (c) in 2002-2012 by Frank Wille */

#include "vasm.h"
#include "output_elf.h"
#if ELFCPU
static char *copyright="vasm ELF output module 2.1 (c)2002-2012 Frank Wille";
static int be,cpu;
static unsigned elfrelsize,shtreloc;

static struct list shdrlist,symlist,relalist;
static struct StrTabList shstrlist,strlist;

static unsigned symtabidx,strtabidx,shstrtabidx;
static unsigned symindex,shdrindex;
static unsigned stabidx,stabstridx;
static utaddr stabsize,stabstrsize;

static unsigned addString(struct StrTabList *sl,char *s)
{
  struct StrTabNode *sn = mymalloc(sizeof(struct StrTabNode));
  unsigned idx = sl->index;

  sn->str = s;
  addtail(&(sl->l),&(sn->n));
  sl->index += (unsigned)strlen(s) + 1;
  return idx;
}

static void init_lists(void)
{
  initlist(&shdrlist);
  initlist(&symlist);
  initlist(&relalist);
  shstrlist.index = strlist.index = 0;
  initlist(&shstrlist.l);
  initlist(&strlist.l);
  symindex = shdrindex = stabidx = stabstridx = 0;
  addString(&shstrlist,"");  /* first string is always "" */
  symtabidx = addString(&shstrlist,".symtab");
  strtabidx = addString(&shstrlist,".strtab");
  shstrtabidx = addString(&shstrlist,".shstrtab");
  addString(&strlist,"");
}

static struct Shdr32Node *addShdr32(void)
{
  struct Shdr32Node *s = mycalloc(sizeof(struct Shdr32Node));

  addtail(&shdrlist,&(s->n));
  return s;
}

static struct Shdr64Node *addShdr64(void)
{
  struct Shdr64Node *s = mycalloc(sizeof(struct Shdr64Node));

  addtail(&shdrlist,&(s->n));
  return s;
}

static struct Symbol32Node *addSymbol32(char *name)
{
  struct Symbol32Node *sn = mycalloc(sizeof(struct Symbol32Node));

  addtail(&symlist,&(sn->n));
  if (name) {
    sn->name = name;
    setval(be,sn->s.st_name,4,addString(&strlist,name));
  }
  symindex++;
  return sn;
}

static struct Symbol64Node *addSymbol64(char *name)
{
  struct Symbol64Node *sn = mycalloc(sizeof(struct Symbol64Node));

  addtail(&symlist,&(sn->n));
  if (name) {
    sn->name = name;
    setval(be,sn->s.st_name,4,addString(&strlist,name));
  }
  symindex++;
  return sn;
}

static void newSym32(char *name,elfull value,elfull size,uint8_t bind,
                     uint8_t type,unsigned shndx)
{
  struct Symbol32Node *elfsym = addSymbol32(name);

  setval(be,elfsym->s.st_value,4,value);
  setval(be,elfsym->s.st_size,4,size);
  elfsym->s.st_info[0] = ELF32_ST_INFO(bind,type);
  setval(be,elfsym->s.st_shndx,2,shndx);
}

static void newSym64(char *name,elfull value,elfull size,uint8_t bind,
                     uint8_t type,unsigned shndx)
{
  struct Symbol64Node *elfsym = addSymbol64(name);

  setval(be,elfsym->s.st_value,8,value);
  setval(be,elfsym->s.st_size,8,size);
  elfsym->s.st_info[0] = ELF64_ST_INFO(bind,type);
  setval(be,elfsym->s.st_shndx,2,shndx);
}

static void addRel32(elfull o,elfull a,elfull i,elfull r)
{
  if (RELA) {
    struct Rela32Node *rn = mymalloc(sizeof(struct Rela32Node));

    setval(be,rn->r.r_offset,4,o);
    setval(be,rn->r.r_addend,4,a);
    setval(be,rn->r.r_info,4,ELF32_R_INFO(i,r));
    addtail(&relalist,&(rn->n));
  }
  else {
    struct Rel32Node *rn = mymalloc(sizeof(struct Rel32Node));

    setval(be,rn->r.r_offset,4,o);
    setval(be,rn->r.r_info,4,ELF32_R_INFO(i,r));
    addtail(&relalist,&(rn->n));
  }
}

static void addRel64(elfull o,elfull a,elfull i,elfull r)
{
  if (RELA) {
    struct Rela64Node *rn = mymalloc(sizeof(struct Rela64Node));

    setval(be,rn->r.r_offset,8,o);
    setval(be,rn->r.r_addend,8,a);
    setval(be,rn->r.r_info,8,ELF64_R_INFO(i,r));
    addtail(&relalist,&(rn->n));
  }
  else {
    struct Rel64Node *rn = mymalloc(sizeof(struct Rel64Node));

    setval(be,rn->r.r_offset,8,o);
    setval(be,rn->r.r_info,8,ELF64_R_INFO(i,r));
    addtail(&relalist,&(rn->n));
  }
}

static void *makeShdr32(elfull name,elfull type,elfull flags,elfull offset,
                        elfull size,elfull info,elfull align,elfull entsize)
{
  struct Shdr32Node *shn;

  shn = addShdr32();
  setval(be,shn->s.sh_name,4,name);
  setval(be,shn->s.sh_type,4,type);
  setval(be,shn->s.sh_flags,4,flags);
  setval(be,shn->s.sh_offset,4,offset);
  setval(be,shn->s.sh_size,4,size);
  setval(be,shn->s.sh_info,4,info);
  setval(be,shn->s.sh_addralign,4,align);
  setval(be,shn->s.sh_entsize,4,entsize);
  /* @@@ set sh_addr to org? */
  return shn;
}

static void *makeShdr64(elfull name,elfull type,elfull flags,elfull offset,
                        elfull size,elfull info,elfull align,elfull entsize)
{
  struct Shdr64Node *shn;

  shn = addShdr64();
  setval(be,shn->s.sh_name,4,name);
  setval(be,shn->s.sh_type,4,type);
  setval(be,shn->s.sh_flags,8,flags);
  setval(be,shn->s.sh_offset,8,offset);
  setval(be,shn->s.sh_size,8,size);
  setval(be,shn->s.sh_info,4,info);
  setval(be,shn->s.sh_addralign,8,align);
  setval(be,shn->s.sh_entsize,8,entsize);
  /* @@@ set sh_addr to org? */
  return shn;
}

static unsigned findelfsymbol(char *name)
/* find symbol with given name in symlist, return its index */
{
  /* also works for lists with Symbol64Node! */
  struct Symbol32Node *nextsym,*sym = (struct Symbol32Node *)symlist.first;
  unsigned sidx = 0;

  while (nextsym = (struct Symbol32Node *)sym->n.next) {
    if (sym->name)
      if (!strcmp(name,sym->name))
        break;
    ++sidx;
    sym = nextsym;
  }
  return nextsym ? sidx : 0;
}

static void init_ident(unsigned char *id,uint8_t class)
{
  static char elfid[4] = { 0x7f,'E','L','F' };

  memcpy(&id[EI_MAG0],elfid,4);
  id[EI_CLASS] = class;
  id[EI_DATA] = be ? ELFDATA2MSB : ELFDATA2LSB;
  id[EI_VERSION] = EV_CURRENT;
  memset(&id[EI_PAD],0,EI_NIDENT-EI_PAD);
}

static uint32_t get_sec_type(section *s)
/* scan section attributes for type */
{
  char *a = s->attr;

  if (!strncmp(s->name,".note",5))
    return SHT_NOTE;
  else if (!strcmp(s->name,".stabstr"))
    return SHT_STRTAB;

  while (*a) {
    switch (*a++) {
      case 'c':
      case 'd':
        return SHT_PROGBITS;
      case 'u':
        return SHT_NOBITS;
    }
  }
#if 0
  output_error(3,attr);  /* section attributes not suppported */
  return SHT_NULL;
#else
  return SHT_PROGBITS;
#endif
}

static utaddr get_sec_flags(char *a)
/* scan section attributes for flags (read, write, alloc, execute) */
{
  utaddr f = 0;

  while (*a) {
    switch (*a++) {
      case 'a':
        f |= SHF_ALLOC;
        break;
      case 'w':
        f |= SHF_WRITE;
        break;
      case 'x':
        f |= SHF_EXECINSTR;
        break;
    }
  }
  return f;
}

static uint8_t get_sym_info(symbol *s)
/* determine symbol-info: function, object, section, etc. */
{
  switch (TYPE(s)) {
    case TYPE_OBJECT:
      return STT_OBJECT;
    case TYPE_FUNCTION:
      return STT_FUNC;
    case TYPE_SECTION:
      return STT_SECTION;
    case TYPE_FILE:
      return STT_FILE;
  }
  return STT_NOTYPE;
}

static unsigned get_sym_index(symbol *s)
{
  if (s->flags & COMMON)
    return SHN_COMMON;
  if (s->type == IMPORT)
    return SHN_UNDEF;
  if (s->sec)
    return (unsigned)s->sec->idx;
  return SHN_ABS;
}

static utaddr get_reloc_type(rlist **rl,
                             utaddr *roffset,taddr *addend,symbol **refsym)
{
  rlist *rl2;
  utaddr mask,offset;
  int size;
  utaddr t = 0;

  *roffset = 0;
  *addend = 0;
  *refsym = NULL;

#ifdef VASM_CPU_M68K
#include "elf_reloc_68k.h"
#endif

#ifdef VASM_CPU_PPC
#include "elf_reloc_ppc.h"
#endif

#ifdef VASM_CPU_ARM
#include "elf_reloc_arm.h"
#endif

#ifdef VASM_CPU_X86
  if (bytespertaddr == 8) {
#include "elf_reloc_x86_64.h"
  }
  else {
#include "elf_reloc_386.h"
  }
#endif

  if (t)
    *roffset = offset>>3;
  else
    unsupp_reloc_error(*rl);

  return t;
}

static utaddr make_relocs(rlist *rl,utaddr pc,
                          void (*newsym)(char *,elfull,elfull,uint8_t,
                                         uint8_t,unsigned),
                          void (*addrel)(elfull,elfull,elfull,elfull))
/* convert all of an atom's relocations into ELF32/ELF64 relocs */
{
  utaddr ro = 0;

  if (rl) {
    do {
      utaddr rtype,offset;
      taddr addend;
      symbol *refsym;

      if (rtype = get_reloc_type(&rl,&offset,&addend,&refsym)) {

        if (LOCREF(refsym)) {
          /* this is a local relocation */
          addrel(pc+offset,addend,refsym->sec->idx,rtype);
          ro += elfrelsize;
        }
        else if (EXTREF(refsym)) {
          /* this is an external symbol reference */
          unsigned idx = findelfsymbol(refsym->name);

          if (idx == 0) {
            /* create a new symbol, which can be referenced */
            idx = symindex;
            newsym(refsym->name,0,0,STB_GLOBAL,STT_NOTYPE,0);
          }
          addrel(pc+offset,addend,idx,rtype);
          ro += elfrelsize;
        }
        else
          ierror(0);
      }
    }
    while (rl = rl->next);
  }

  return ro;
}

static utaddr prog_sec_hdrs(section *sec,utaddr soffset,
                            void *(*makeshdr)(elfull,elfull,elfull,elfull,
                                              elfull,elfull,elfull,elfull),
                            void (*newsym)(char *,elfull,elfull,
                                           uint8_t,uint8_t,
                                           unsigned))
{
  section *secp;
  void *shn;

  /* generate section headers for program sections */
  for (secp=sec; secp; secp=secp->next) {
    if (get_sec_size(secp)!=0 || (secp->flags & HAS_SYMBOLS)) {
      uint32_t type = get_sec_type(secp);

      secp->idx = ++shdrindex;

      if (!strcmp(secp->name,".stabstr")) {
        stabstridx = shdrindex;
        stabstrsize = get_sec_size(secp);
      }
      else if (!strcmp(secp->name,".stab")) {
        stabidx = shdrindex;
        stabsize = (get_sec_size(secp) / 12) - 1;  /* 12: sizeof(nlist32) */
      }

      shn = makeshdr(addString(&shstrlist,secp->name),
                     type,get_sec_flags(secp->attr),soffset,
                     get_sec_size(secp),0,secp->align,0);

      if (type != SHT_NOBITS)
        soffset += get_sec_size(secp);

      /* add section base symbol */
      newsym(NULL,0,0,STB_LOCAL,STT_SECTION,shdrindex);
    }
    else
      secp->idx = 0;
  }

  return soffset;
}

static unsigned build_symbol_table(symbol *first,
                                   void (*newsym)(char *,elfull,elfull,
                                                  uint8_t,uint8_t,
                                                  unsigned))
{
  symbol *symp;
  unsigned firstglobal;

  /* file name symbol, when defined */
  if (filename)
    newsym(filename,0,0,STB_LOCAL,STT_FILE,SHN_ABS);

  if (!no_symbols)  /* symbols with local binding first */
    for (symp=first; symp; symp=symp->next)
      if (*symp->name!='.' && *symp->name!=' ' && !(symp->flags&VASMINTERN))
        if (symp->type!=IMPORT && !(symp->flags & (EXPORT|WEAK))) {
          if (symp->sec) {
            newsym(symp->name,get_sym_value(symp)-(symp->sec->org),get_sym_size(symp),
                   STB_LOCAL,get_sym_info(symp),get_sym_index(symp));
          } else {
            newsym(symp->name,get_sym_value(symp),get_sym_size(symp),
                   STB_LOCAL,get_sym_info(symp),get_sym_index(symp));
          }
        }

  firstglobal = symindex;  /* now the global and weak symbols */

  for (symp=first; symp; symp=symp->next)
    if (*symp->name != '.'  && !(symp->flags&VASMINTERN))
      if ((symp->type!=IMPORT && (symp->flags & (EXPORT|WEAK))) ||
          (symp->type==IMPORT && (symp->flags & (COMMON|WEAK)))) {
        if (symp->sec) {
          newsym(symp->name,get_sym_value(symp)-(symp->sec->org),get_sym_size(symp),
                 (symp->flags & WEAK) ? STB_WEAK : STB_GLOBAL,
                 get_sym_info(symp),get_sym_index(symp));
        } else {
          newsym(symp->name,get_sym_value(symp),get_sym_size(symp),
                 (symp->flags & WEAK) ? STB_WEAK : STB_GLOBAL,
                 get_sym_info(symp),get_sym_index(symp));
        }
      }

  return firstglobal;
}

static void make_reloc_sections(section *sec,
                                void (*newsym)(char *,elfull,elfull,
                                               uint8_t,uint8_t,
                                               unsigned),
                                void (*addrel)(elfull,elfull,elfull,elfull),
                                void *(*makeshdr)(elfull,elfull,elfull,elfull,
                                                  elfull,elfull,elfull,elfull))
{
  utaddr roffset = 0;
  section *secp;

  /* ".rela.xxx" or ".rel.xxx" relocation sections */
  for (secp=sec; secp; secp=secp->next) {
    if (secp->idx) {
      atom *a;
      utaddr pc=0,npc,basero=roffset;

      for (a=secp->first; a; a=a->next) {
        npc = pcalign(a,pc);
        if (a->type == DATA)
          roffset += make_relocs(a->content.db->relocs,npc,newsym,addrel);
        if (a->type == SPACE)
          roffset += make_relocs(a->content.sb->relocs,npc,newsym,addrel);
        pc = npc + atom_size(a,secp,npc);
      }

      if (basero != roffset) {  /* were there any relocations? */
        /* create .relaXX section header */
        char *sname = mymalloc(strlen(secp->name) + 6);

        if (RELA)
          sprintf(sname,".rela%s",secp->name);
        else
          sprintf(sname,".rel%s",secp->name);

        makeshdr(addString(&shstrlist,sname),shtreloc,0,
                 basero, /* relative offset - will be fixed later! */
                 roffset-basero,secp->idx,bytespertaddr,elfrelsize);
        ++shdrindex;
      }
    }
  }
}

static void write_section_data(FILE *f,section *sec)
{
  section *secp;

  for (secp=sec; secp; secp=secp->next) {
    if (secp->idx && get_sec_type(secp)!=SHT_NOBITS) {
      atom *a;
      utaddr pc=0,npc;

      if (secp->idx == stabidx) {
        /* patch compilation unit header */
        a = secp->first;
        if (a->content.db->size == 12) {
          uint8_t *p = a->content.db->data;

          setval(be,p,4,1);  /* refers to first string from .stabstr */
          setval(be,p+4,4,stabsize);
          setval(be,p+8,4,stabstrsize);
        }
      }

      for (a=secp->first; a; a=a->next) {
        npc = fwpcalign(f,a,secp,pc);

        if (a->type == DATA) {
          fwdata(f,a->content.db->data,a->content.db->size);
        }
        else if (a->type == SPACE) {
          fwsblock(f,a->content.sb);
        }

        pc = npc + atom_size(a,secp,npc);
      }
    }
  }
}

static void write_strtab(FILE *f,struct StrTabList *strl)
{
  struct StrTabNode *stn;

  while (stn = (struct StrTabNode *)remhead(&(strl->l)))
    fwdata(f,stn->str,strlen(stn->str)+1);
}

static void write_ELF64(FILE *f,section *sec,symbol *sym)
{
  struct Elf64_Ehdr header;
  unsigned firstglobal,align1,align2,i;
  utaddr soffset=sizeof(struct Elf64_Ehdr);
  struct Shdr64Node *shn;
  struct Symbol64Node *elfsym;

  elfrelsize = RELA ? sizeof(struct Elf64_Rela) : sizeof(struct Elf64_Rel);

  /* initialize ELF header */
  memset(&header,0,sizeof(struct Elf64_Ehdr));
  init_ident(header.e_ident,ELFCLASS64);
  setval(be,header.e_type,2,ET_REL);
  setval(be,header.e_machine,2,cpu);
  setval(be,header.e_version,4,EV_CURRENT);
  setval(be,header.e_ehsize,2,sizeof(struct Elf64_Ehdr));
  setval(be,header.e_shentsize,2,sizeof(struct Elf64_Shdr));

  init_lists();
  addShdr64();        /* first section header is always zero */
  addSymbol64(NULL);  /* first symbol is empty */

  /* make program section headers, symbols and relocations */
  soffset = prog_sec_hdrs(sec,soffset,makeShdr64,newSym64);
  firstglobal = build_symbol_table(sym,newSym64);
  make_reloc_sections(sec,newSym64,addRel64,makeShdr64);

  /* ".shstrtab" section header string table */
  ++shdrindex;
  makeShdr64(shstrtabidx,SHT_STRTAB,0,
             soffset,shstrlist.index,0,1,0);
  soffset += shstrlist.index;
  align1 = ((soffset + 3) & ~3) - soffset;
  soffset += align1;

  /* set last values in ELF header */
  setval(be,header.e_shoff,8,soffset);  /* remember offset of Shdr table */
  soffset += (shdrindex+3)*sizeof(struct Elf64_Shdr);
  setval(be,header.e_shstrndx,2,shdrindex);
  setval(be,header.e_shnum,2,shdrindex+3);

  /* ".symtab" symbol table */
  ++shdrindex;
  shn = makeShdr64(symtabidx,SHT_SYMTAB,0,soffset,
                   symindex*sizeof(struct Elf64_Sym),
                   firstglobal,8,sizeof(struct Elf64_Sym));
  setval(be,shn->s.sh_link,4,shdrindex+1);  /* associated .strtab section */
  soffset += symindex * sizeof(struct Elf64_Sym);

  /* ".strtab" string table */
  makeShdr64(strtabidx,SHT_STRTAB,0,soffset,strlist.index,0,1,0);
  soffset += strlist.index;
  align2 = ((soffset + 3) & ~3) - soffset;
  soffset += align2;  /* offset for first Reloc-entry */

  /* write ELF header */
  fwdata(f,&header,sizeof(struct Elf64_Ehdr));

  /* write initialized section contents */
  write_section_data(f,sec);

  /* write .shstrtab string table */
  write_strtab(f,&shstrlist);

  /* write section headers */
  for (i=0; i<align1; i++)
    fw8(f,0);
  i = 0;
  while (shn = (struct Shdr64Node *)remhead(&shdrlist)) {
    if (i == stabidx) {
      /* set link to stabstr table for .stab section */
      setval(be,shn->s.sh_link,4,stabstridx);
    }
    if (readval(be,shn->s.sh_type,4) == shtreloc) {
      /* set correct offset and link to symtab */
      setval(be,shn->s.sh_offset,8,readval(be,shn->s.sh_offset,8)+soffset);
      setval(be,shn->s.sh_link,4,shdrindex); /* index of associated symtab */
    }
    fwdata(f,&(shn->s),sizeof(struct Elf64_Shdr));
    i++;
  }

  /* write symbol table */
  while (elfsym = (struct Symbol64Node *)remhead(&symlist))
    fwdata(f,&(elfsym->s),sizeof(struct Elf64_Sym));

  /* write .strtab string table */
  write_strtab(f,&strlist);

  /* write relocations */
  for (i=0; i<align2; i++)
    fw8(f,0);
  if (RELA) {
    struct Rela64Node *rn;

    while (rn = (struct Rela64Node *)remhead(&relalist))
      fwdata(f,&(rn->r),sizeof(struct Elf64_Rela));
  }
  else {
    struct Rel64Node *rn;

    while (rn = (struct Rel64Node *)remhead(&relalist))
      fwdata(f,&(rn->r),sizeof(struct Elf64_Rel));
  }
}

static void write_ELF32(FILE *f,section *sec,symbol *sym)
{
  struct Elf32_Ehdr header;
  unsigned firstglobal,align1,align2,i;
  utaddr soffset=sizeof(struct Elf32_Ehdr);
  struct Shdr32Node *shn;
  struct Symbol32Node *elfsym;

  elfrelsize = RELA ? sizeof(struct Elf32_Rela) : sizeof(struct Elf32_Rel);

  /* initialize ELF header */
  memset(&header,0,sizeof(struct Elf32_Ehdr));
  init_ident(header.e_ident,ELFCLASS32);
  setval(be,header.e_type,2,ET_REL);
  setval(be,header.e_machine,2,cpu);
  setval(be,header.e_version,4,EV_CURRENT);
#ifdef VASM_CPU_ARM
  setval(be,header.e_flags,4,0x04000000);  /* EABI version 4 */
#endif
  setval(be,header.e_ehsize,2,sizeof(struct Elf32_Ehdr));
  setval(be,header.e_shentsize,2,sizeof(struct Elf32_Shdr));

  init_lists();
  addShdr32();        /* first section header is always zero */
  addSymbol32(NULL);  /* first symbol is empty */

  /* make program section headers, symbols and relocations */
  soffset = prog_sec_hdrs(sec,soffset,makeShdr32,newSym32);
  firstglobal = build_symbol_table(sym,newSym32);
  make_reloc_sections(sec,newSym32,addRel32,makeShdr32);

  /* ".shstrtab" section header string table */
  ++shdrindex;
  makeShdr32(shstrtabidx,SHT_STRTAB,0,
             soffset,shstrlist.index,0,1,0);
  soffset += shstrlist.index;
  align1 = ((soffset + 3) & ~3) - soffset;
  soffset += align1;

  /* set last values in ELF header */
  setval(be,header.e_shoff,4,soffset);  /* remember offset of Shdr table */
  soffset += (shdrindex+3)*sizeof(struct Elf32_Shdr);
  setval(be,header.e_shstrndx,2,shdrindex);
  setval(be,header.e_shnum,2,shdrindex+3);

  /* ".symtab" symbol table */
  ++shdrindex;
  shn = makeShdr32(symtabidx,SHT_SYMTAB,0,soffset,
                   symindex*sizeof(struct Elf32_Sym),
                   firstglobal,4,sizeof(struct Elf32_Sym));
  setval(be,shn->s.sh_link,4,shdrindex+1);  /* associated .strtab section */
  soffset += symindex * sizeof(struct Elf32_Sym);

  /* ".strtab" string table */
  makeShdr32(strtabidx,SHT_STRTAB,0,soffset,strlist.index,0,1,0);
  soffset += strlist.index;
  align2 = ((soffset + 3) & ~3) - soffset;
  soffset += align2;  /* offset for first Reloc-entry */

  /* write ELF header */
  fwdata(f,&header,sizeof(struct Elf32_Ehdr));

  /* write initialized section contents */
  write_section_data(f,sec);

  /* write .shstrtab string table */
  write_strtab(f,&shstrlist);

  /* write section headers */
  for (i=0; i<align1; i++)
    fw8(f,0);
  i = 0;
  while (shn = (struct Shdr32Node *)remhead(&shdrlist)) {
    if (i == stabidx) {
      /* set link to stabstr table for .stab section */
      setval(be,shn->s.sh_link,4,stabstridx);
    }
    if (readval(be,shn->s.sh_type,4) == shtreloc) {
      /* set correct offset and link to symtab */
      setval(be,shn->s.sh_offset,4,readval(be,shn->s.sh_offset,4)+soffset);
      setval(be,shn->s.sh_link,4,shdrindex); /* index of associated symtab */
    }
    fwdata(f,&(shn->s),sizeof(struct Elf32_Shdr));
    i++;
  }

  /* write symbol table */
  while (elfsym = (struct Symbol32Node *)remhead(&symlist))
    fwdata(f,&(elfsym->s),sizeof(struct Elf32_Sym));

  /* write .strtab string table */
  write_strtab(f,&strlist);

  /* write relocations */
  for (i=0; i<align2; i++)
    fw8(f,0);
  if (RELA) {
    struct Rela32Node *rn;

    while (rn = (struct Rela32Node *)remhead(&relalist))
      fwdata(f,&(rn->r),sizeof(struct Elf32_Rela));
  }
  else {
    struct Rel32Node *rn;

    while (rn = (struct Rel32Node *)remhead(&relalist))
      fwdata(f,&(rn->r),sizeof(struct Elf32_Rel));
  }
}

static void write_output(FILE *f,section *sec,symbol *sym)
{
  int bits;

  cpu = ELFCPU;    /* cpu ID */
  be = BIGENDIAN;  /* true for big endian */
  bits = bytespertaddr * bitsperbyte;
  shtreloc = RELA ? SHT_RELA : SHT_REL;

  if (bits==32 && cpu!=EM_NONE)
    write_ELF32(f,sec,sym);
  else if (bits==64 && cpu!=EM_NONE)
    write_ELF64(f,sec,sym);
  else
    output_error(1,cpuname);  /* output module doesn't support cpu */
}

static int output_args(char *p)
{
  return 0;
}

int init_output_elf(char **cp,void (**wo)(FILE *,section *,symbol *),
                    int (**oa)(char *))
{
  *cp = copyright;
  *wo = write_output;
  *oa = output_args;
  return 1;
}

#else

int init_output_elf(char **cp,void (**wo)(FILE *,section *,symbol *),
                    int (**oa)(char *))
{
  return 0;
}

#endif


text:
<?php
class controller_admin_config extends ControllerAdminModel {
    function _prehook() {
        parent::_prehook();

        mvc::assign('menu', 'config');
    }

    function list_items() {
        // this is the config we will display
        $configName = filter_get('name', 'string');

        $filters = array();
        $options = array();
        $oConfig = new Config();
        $oConfigCollection = $oConfig->Get($filters, $options);

        $aSortedConfig = $oConfig->sortData($oConfigCollection);

        $Breadcrumbs = Breadcrumbs::getSingleton();
        $Breadcrumbs->Add(__('Config'), MVC_ACTION_URL);
        if ($configName) {
            $Breadcrumbs->Add($configName, CURRENT_URL);
        }

        mvc::assign_by_ref('aConfig', $aSortedConfig);
        mvc::assign('configName', $configName);
    }

    function save_all() {
        $aConfigIds = $_POST['config_ids'];
        $configName = filter_post('configName', 'string');

        try {
            if (!is_array($aConfigIds)) {
                throw new Exception(__('Incorrect input of config ids!'));
            }
            if (!securityCheckToken(filter_post('token', 'string'))) {
                throw new Exception(__('The page delay was too long'));
            }

            db::startTransaction();

            $oConfig = new Config();
            foreach ($aConfigIds as $configId) {
                $configValue = filter_post('config'.$configId, 'clean_html');

                $oItem = new SetterGetter();
                $oItem->setValue($configValue);

                $r = $oConfig->Edit($configId, $oItem);
                if (!$r) {
                    throw new Exception(__('Error while saving one of the config values'));
                }
            }

            db::commitTransaction();

            // clear config values from memcache
            $Memcache = Mcache::getSingleton();
            $Memcache->delete(Config::MEMCACHE_KEY);
        }
        catch (Exception $e) {
            message_set_error($e->getMessage());
            db::rollbackTransaction();
            http_redir(href_admin('config/list_items') . '?name='.$configName);
        }

        message_set(__('All items were saved'));
        http_redir(href_admin('config/list_items') . '?name='.$configName);
    }

    function add() {
        $FV = new FormValidation(array(
            'rules' => array(
                'path'  => 'required',
                'type'  => 'required',
                'value' => ''
            ),
            'messages' => array(
                'path'  => __('Please specify the config path'),
                'type'  => __('Please select a config type')
            )
        ));

        $validateResult = $FV->validate();
        if (isPOST()) {
            try {
                if (!$validateResult) {
                    throw new Exception(__('Please make sure you filled all mandatory values'));
                }
                if (!securityCheckToken(filter_post('token', 'string'))) {
                    throw new Exception(__('The page delay was too long'));
                }

                $path  = filter_post('path', 'clean_html');
                $value = filter_post('value', 'clean_html');
                $type  = filter_post('type', 'string');

                if (count(explode('/', trim($path, '/'))) != 3) {
                    throw new Exception(__('You did not write the config properly'));
                }

                // check if the path exists
                $filters = array('path' => $path);
                $options = array();
                $oConfig = new Config();
                $oConfigCollection = $oConfig->Get($filters, $options);
                if (count($oConfigCollection) > 0) {
                    throw new Exception(__('A config with that path already exists'));
                }

                // add to database
                $oItem = new SetterGetter();
                $oItem->setPath($path);
                $oItem->setValue($value);
                $oItem->setType($type);
                $r = $oConfig->Add($oItem);
                if (!$r) {
                    message_set_error(__('Error while saving to the database'));
                    http_redir(MVC_ACTION_URL);
                }

                message_set(__('Config added successfully'));
                http_redir(MVC_MODULE_URL . '/list_items.html');
            }
            catch (Exception $e) {
                message_set_error($e->getMessage());
            }
        }

        mvc::assign('FV', $FV);
    }

}


text:
class AddBooleanDefaultsToFieldSubscriptionFields < ActiveRecord::Migration
  def self.up
    change_column :service_subscriptions, :update_about_northeast, :boolean, :default => true
    change_column :service_subscriptions, :update_about_northwest, :boolean, :default => true
    change_column :service_subscriptions, :update_about_southside, :boolean, :default => true
    change_column :service_subscriptions, :send_only_on_change, :boolean, :default => true
  end

  def self.down
    change_column :service_subscriptions, :update_about_northeast, :boolean
    change_column :service_subscriptions, :update_about_northwest, :boolean
    change_column :service_subscriptions, :update_about_southside, :boolean
    change_column :service_subscriptions, :send_only_on_change, :boolean
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<Weavers VerifyAssembly='true'>
    <Costura IncludeDebugSymbols='false' />
</Weavers>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;

namespace Log.Visor.Xamarin
{
    public class App : Application
    {
        public App()
        {
            MainPage = new HomePage();
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}


text:
class Salesforce::Solution < Salesforce::SfBase
  set_table_name 'solutions'
end


text:
layout: post
title: "Front-end Web: Sorry, but you can't preview your content"
date: 2013-10-30 16:04
comments: true
categories: tech
---

![](http://farm3.staticflickr.com/2837/10570886836_3ba7832cea_o.png "Front-end's meme")

Kok ga ada yang berubah? Kamu nggak kerja, ya?

Obrolan beberapa hari yang lalu dengan sesama Front-end. Dia bilang, "Front-end itu kerjaannya sering nggak dianggep." :)

~highlander! \o/


text:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use app\components\AccessRule;
use app\models\User;
use app\models\Community;
use app\controllers\WeChatController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * EnterpriseController implements the CRUD actions for Enterprise model.
 */
class CommunityController extends WeChatController
{

    public $layout="main";

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                // We will override the default rule config with the new AccessRule class
                'ruleConfig' => [
                    'class' => AccessRule::className(),
                ],
                //'only' => ['index','create',"update","submit","list","show","showDetail],
                'rules' => [
                    [
                        'actions' => ['show',"show-detail"],
                        'allow' => true,
                        // Allow users, moderators and admins to create
                        'roles' => [
                            "?"
                        ],
                    ],
                    [
                        'actions' => ['index',"create","update","list","delete","submit"],
                        'allow' => true,
                        // Allow moderators and admins to update
                        'roles' => [
                            User::ROLE_ADMIN
                        ],
                    ]
                ],
            ]
        ];
    }

    /**
     * Lists all Enterprise models.
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 显示通知(用户)
     * @return string
     */
    public function actionShow(){

        $this->getOpenId();

        $this->layout="user";

        $query=Community::find();
        $results=$query
            ->joinWith([
                "user"=>function($query){
                    $query->where(["enterprise_id"=>yii::$app->user->getIdentity()->enterprise_id]);
                    //$query->where(["enterprise_id"=>yii::$app->user->getIdentity()?0:1]);
                }
            ])
            ->orderBy([
                'community_id' => SORT_DESC,
            ])
            ->asArray()
            ->all();

        return $this->render("show",[
            "results"=>$results
        ]);
    }
    public function actionShowDetail($id){

        $this->layout="user";

        $model=$this->findModel($id);
        return $this->render("showDetail",[
            "model"=>$model
        ]);
    }

    public function actionList(){
        $params=Yii::$app->request->queryParams;
        $limit=$params["iDisplayLength"];
        $offset=$params["iDisplayStart"];
        $sEcho = $params["sEcho"];
        $query=Community::find();
        $count=$query->count();
        $aaData=$query
            ->asArray()
            ->orderBy([
                'community_id' => SORT_DESC,
            ])
            ->limit($limit)
            ->offset($offset)
            ->all();

        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'success' => true,
            'aaData' => $aaData,
            "iTotalRecords"=>$count,
            "iTotalDisplayRecords"=>$count,
            "sEcho"=>$sEcho
        ];

    }

    public function actionCreate(){
        $model=new Community();
        return $this->render('createOrUpdate',[
            'model' => $model,
        ]);
    }

    public function actionUpdate($id){

        //这样获取会将isNewRecord设置为false
        $model = $this->findModel($id);

        return $this->render('createOrUpdate', [
            'model' => $model,
        ]);
    }

    /**
     *新增和修改提交
     * @return array
     */
    public function actionSubmit(){
        $params=Yii::$app->request->post();

        if(isset($params["community_id"])){
            $model = $this->findModel($params["community_id"]);
        }else{
            $model=new Community();
            $params["create_at"]=date("Y-m-d");
            $params["user_id"]=Yii::$app->user->getId();
        }

        $data=array();

        //yii自动生成的form参数是Enterprise["name"]这种形式,获取后就会是在一个Enterprise中
        $data["Community"]=$params;

        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        if ($model->load($data) && $model->save()) {
            return [
                "success"=>true
            ];
        }else{
            return [
                "success"=>false,
                "error_code"=>1
            ];
        }
    }

    /**
     *由于建立了数据库的外键,这里删除后,所有相关的数据都将删除
     * @param $id
     * @return array
     */
    public function actionDelete($id)
    {

        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        if($this->findModel($id)->delete()){
            return [
                "success"=>true
            ];
        }else{
            return [
                "success"=>false,
                "error_code"=>1
            ];
        }

    }

    protected function findModel($id)
    {
        if (($model = Community::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<?php

namespace mako\tests\integration\database\midgard;

use mako\database\midgard\ORM;
use mako\database\midgard\traits\NullableTrait;
use mako\tests\integration\ORMTestCase;

class NullableTest extends ORMTestCase
{
	/**
	 * Returns a ORM instance.
	 *
	 * @return \mako\database\midgard\ORM
	 */
	protected function getNullable(): ORM
	{
		return new class extends ORM
		{
			use NullableTrait;

			protected $tableName = 'nullables';

			protected $nullable = ['value1'];
		};
	}

	/**
	 *
	 */
	public function testInsert()
	{
		$nullable = $this->getNullable();

		//

		$nullable->value1 = '';

		$nullable->value2 = '';

		$nullable->save();

		//

		$row = $nullable->get($nullable->id);

		$this->assertNull($row->value1);

		$this->assertSame('', $row->value2);
	}

	/**
	 *
	 */
	public function testUpdate()
	{
		$nullable = $this->getNullable();

		//

		$row = $nullable->get(1);

		$row->value1 = 'foobar';

		$row->value2 = 'barfoo';

		$row->save();

		//

		$row = $nullable->get(1);

		$this->assertEquals('foobar', $row->value1);

		$this->assertEquals('barfoo', $row->value2);

		$row->value1 = '';

		$row->value2 = '';

		$row->save();

		//

		$row = $nullable->get(1);

		$this->assertNull($row->value1);

		$this->assertSame('', $row->value2);
	}
}


text:
from __future__ import with_statement
import os
import sys
from collections import namedtuple, defaultdict, Counter
import subprocess
import re
from ansicolor import red, yellow, green, black

def readFileLines(filename):
    with open(filename, encoding="iso-8859-1") as infile:
        return infile.read().split("\n")

def extractToolStatistics(lines):
    """
    From a list of excellon drill lines extract the number of holes for all drill sizes.
    Returns a dict: {drill size: number of holes}
    """
    #Get a tool --> diameter mapping
    tools = extractExcellonTools(lines)
    #Iterate over lines and count holes for each tool
    currentTool = None
    drillCountByDiameter = defaultdict(int)
    toolRegex = re.compile(r"^(T\d+)$")
    drillRegex = re.compile(r"^X[\+-]\d+Y[\+-]\d+$")
    for line in lines:
        if toolRegex.match(line):
            #This line defines a new tool to use
            currentTool = toolRegex.match(line).group(0)
        if drillRegex.match(line):
            drillCountByDiameter[tools[currentTool]] += 1
    return drillCountByDiameter

def extractExcellonTools(lines):
    """
    From a list of excellon lines, extract a dict of tools
    Ignores non-tool-definition lines
    Example: ["foobar", "T01C1.0", "T02C2.2"] -> {"T01": 1.0, "T02": 2.2}
    """
    #Extract those lines that match a regex
    toolDefRegex = re.compile(r"^(T\d+)C([0-9\.]+)$")
    toolDefMatches = [toolDefRegex.match(l) for l in lines if toolDefRegex.match(l)]
    return dict([(t.group(1), float(t.group(2))) for t in toolDefMatches])

def checkExcellonMetric(self, filepath):
    "Check if a given file is a metric excellon file"
    filename = os.path.basename(filepath)
    lines = readFileLines(filepath)
    #Check for excellon header
    if lines[0] != "M48":
        print(red("Can't find Excellon drill header (M48) in %s" % filename, bold="True"))
    #Check for metric dimension: Line like METRIC,0000.00
    if lines[1].partition(",")[0] != "METRIC":
        print(red("Excellon drill program %s does not seem to be metric" % filename, bold="True"))
    #
    # Drill statistics
    #
    toolStats = extractToolStatistics(lines)
    print(black(self.name + ":", bold=True))
    for diameter, numDrills in toolStats.items():
        print("\t%d through holes of diameter %.2fmm" % (numDrills, diameter))
    #Print "None" if there are no holes in this file
    if not toolStats:
        print("\tNone")

#Multimap of allowed layer notes (ExpectedFile.name --> [%LN])
#Built for diptrace. Might need to be adjusted for other EDA tools.
allowedLayerNotes = defaultdict(list)
allowedLayerNotes.update({
    "Top copper layer": ["Top", ['Copper', 'L1', 'Top']],
    "Bottom copper layer": ["Bottom", ['Copper', 'L2', 'Bot']],
    "Solder mask top": ["TopMask", ['Soldermask', 'Top']],
    "Solder mask bottom": ["BotMask", ['Soldermask', 'Bot']],
    "Board outline": ["BoardOutline", ['Profile']],
    "Silk screen top": ["TopSilk", ['Legend', 'Top']],
})

#Gerber aperture
# id: The aperture identifier, e.g. D11
# type: "C"/"R"
# diameter: float, with implicit units
Aperture = namedtuple("Aperture", ["id", "type", "diameter"])

def parseGerberApertures(lines):
    "From a list of gerber lines, parse all embedded apertures"
    apertureRegex = re.compile(r"%AD(D\d+)([CR]),(\d+\.\d+)\*%")
    apertures = []
    #Find lines defining apertures
    for line in lines:
        if apertureRegex.match(line):
            match = apertureRegex.match(line)
            apertures.append(Aperture(match.group(1), match.group(2), float(match.group(3))))
    return apertures

def findAperture(apertures, identifier):
    "Find an aperture in a list of apertures (returns None if not found)"
    for aperture in apertures:
        if aperture.id == identifier: return aperture
    return None

def parseGerberUnit(lines):
    """Returns the extended gerber unit ("mm"/"in") or None if not found"""
    if "%MOIN*%" in lines:
        return "in"
    elif "%MOMM*%" in lines:
        return "mm"
    else: return None

def findCoordinateFormat(lines):
    """
    Try to find a FSLAX line and return the decimal-point factor for coordinates.
    """
    rgx = re.compile(r"\%FSLAX(\d{2})Y(\d{2})\*\%")
    for line in lines:
        m = rgx.match(line)
        if m is not None:
            return 10.**int(m.group(1)[-1]),10.**int(m.group(2)[-1])
    print(red("Could not find coordinate format info %FSLAX. Using default %FSLAX33"))
    return 100000.,100000.

def checkBoardOutline(self, filepath):
    filename = os.path.basename(filepath)
    #Basic gerber checks
    checkGerberFile(self, filepath)
    #Compute board outline
    millLines = readFileLines(filepath)
    # Find factors to get absolute coordinates:
    x_factor, y_factor = findCoordinateFormat(millLines)
    # Initialize X & Y
    x, y = 0, 0
    #We can only interpret the file if coordinates are absolute
    if not "G90*" in millLines:
        print(yellow("Mill coordinates in %s don't seem to be absolute (G90 missing!)" % filename))
        return
    #Determine coordinate units
    unit = parseGerberUnit(millLines)
    if unit is None: #Neither inch nor mm found
        print(yellow("Could not find coordinate units (mm/in) in %s" % filename))
        return
    #Parse the aperture list
    apertures = parseGerberApertures(millLines)
    selectApertureRegex = re.compile(r"(D\d+)\*")
    move2DRegex = re.compile(r"X(-?\d+)Y(-?\d+)D(\d+)\*") #Move (D2) or draw (D1)
    move1DRegex = re.compile(r"([XY])(-?\d+)D(\d+)\*") #With only one coordinate
    #Try to interpret gerber file
    minCoords = (sys.maxsize, sys.maxsize)
    maxCoords = (0, 0)
    lastCoords = (0, 0)
    currentAperture = None
    apertureUseCount = Counter()
    for line in millLines:
        if selectApertureRegex.match(line):
            apertureCode = selectApertureRegex.match(line).group(1)
            currentAperture = findAperture(apertures, apertureCode)
        elif move2DRegex.match(line):
            match = move2DRegex.match(line)
            x = int(match.group(1)) / x_factor
            y = int(match.group(2)) / y_factor
            apertureUseCount[currentAperture] += 1
        elif move1DRegex.match(line):
            match = move1DRegex.match(line)
            apertureUseCount[currentAperture] += 1
            if match.group(1) == "X":
                x = int(match.group(2)) / x_factor
                y = lastCoords[1]
            elif match.group(1) == "Y":
                x = lastCoords[0]
                y = int(match.group(2)) / y_factor
            else: raise Exception("Internal error: Invalid coordinate type in 1D move: %s" % match.group(1))
        else: continue
        #Compute min/max coordinates
        lastCoords = (x, y)
        minCoords = (min(minCoords[0], lastCoords[0]), min(minCoords[1], lastCoords[1]))
        maxCoords = (max(maxCoords[0], lastCoords[0]), max(maxCoords[1], lastCoords[1]))
    #Compute board size (minimum enclosing rectangle)
    boardSize = (maxCoords[0] - minCoords[0], maxCoords[1] - minCoords[1])
    # Compute size of most common aperture
    mostCommonAperture = apertureUseCount.most_common(1)[0][0]
    #   info
    print(black("\tGerber offset: ({1:.2f} {0}, {2:.2f} {0})".format(unit, minCoords[0], minCoords[1])))
    print(black("\tBoard size (minimum rectangle): %.1f %s x %.1f %s" % \
            (boardSize[0], unit, boardSize[1], unit)))
    #print(black("\tBoard outline aperture size: {0:.2f} µm".format(1e3 * mostCommonAperture.diameter), bold=True))

def checkCopperLayer(self, filepath):
    #Basic gerber checks
    checkGerberFile(self, filepath)
    #Check if smallest aperture is < 6mil = 150um
    #NOTE: We currently don't compute the clearance (way too complicated)
    lines = readFileLines(filepath)
    apertures = parseGerberApertures(lines)
    unit = parseGerberUnit(lines)
    limit = 0.125 #TODO use inches if unit == "in"
    if unit == "in": limit = 0.006
    for aperture in apertures:
        if aperture.diameter < limit:
            print(red("Aperture %s (size %.3f %s) is smaller than %.3f %s minimum width" % \
                        (aperture.id, aperture.diameter, unit, limit, unit)))

def checkGerberFile(self, filepath):
    """
    Check if the given file is a RS-274X gerber file
    - Checks for a G04 command at the beginning of the file
    - Checks for a %LN command and verifies it against the filename
    - Checks for a G04 #@! TF.FileFunction command
    """
    filename = os.path.basename(filepath)
    lines = readFileLines(filepath)
    #Find G04 line (i.e. what software created the file)
    if not any(map(lambda l: l.startswith("G04 "), lines)):
        print(red("Couldn't find G04 command (software description) in %s. Probably not a Gerber file." % filename, bold=True))
    #Find %LN line, i.e. what the creating
    # software thinks the current layer is (e.g. "BottomMask")
    layerNoteRegex = re.compile(r"^\%LN([^\*]+)\*%$")
    fileFunctionRegex = re.compile(r"G04 #@! TF\.FileFunction,([^\*]+)\*")
    layerDescription = None
    for line in lines:
        if layerNoteRegex.match(line):
            layerDescription = layerNoteRegex.match(line).group(1)
            break #Expecting only one layer note
        elif fileFunctionRegex.match(line):
            layerDescription = fileFunctionRegex.match(line).group(1)
            layerDescription = layerDescription.split(",")
    #Check if the layer note we found makes sense
    if layerDescription == None: #No %LN line found
        print(yellow("Couldn't find %%LN command or file function command in %s" % filename))
    else: #We found a layer description. Check for sanity
        if isinstance(layerDescription, list): # FileFunction command
            if layerDescription not in allowedLayerNotes[self.name]:
                    print(red("Layer description '%s' in %s does not match any of the expected descriptions: %s" % (layerDescription, filename, allowedLayerNotes[self.name]), bold=True))

        else: # %LN command
            if layerDescription not in allowedLayerNotes[self.name]:
                print(red("Layer description '%s' in %s does not match any of the expected descriptions: %s" % (layerDescription, filename, allowedLayerNotes[self.name]), bold=True))

def extractProjectPrefix(files):
    """
    Extract a common project prefix from all files in a directory
    Fails & exits if no such prefix is found
    Example: [ABC.top, ABC.bot] => "ABC"
    """
    commonprefix = os.path.commonprefix(files)
    if not commonprefix or not commonprefix.endswith("."):
        print(red("Can't extract project name from files: %s" % ", ".join(files), bold=True))
        print(red("Please ensure that all files have a common filename and only differ in their extension!", bold=True))
        print(red("Example: MyBoard.top, MyBoard.bot, ...", bold=True))
        sys.exit(1)
    return commonprefix[:-1] #Strp off dot

def checkFile(directory, expectedFile, projectName):
    "Check if a given expected file exists inside a directory"
    filename = projectName + expectedFile.extension
    filepath = os.path.join(directory, filename)
    if os.path.isfile(filepath):
        print(green("Found %s data %s" % (expectedFile.format, filename)))
        if expectedFile.checkFN is not None:
            expectedFile.checkFN(expectedFile, filepath)
    else:
        print(red("File %s (%s) missing" % (filename, expectedFile.name), bold=True))
        return None
    return filename

ExpectedFile = namedtuple('ExpectedFile', ['extension', 'name', 'format', 'checkFN'])
expectedFiles = [
    #http://www.multi-circuit-boards.eu/support/leiterplatten-daten/gerber-daten.html
    ExpectedFile(".top", "Top copper layer", "RS-274X", checkCopperLayer),
    ExpectedFile(".bot", "Bottom copper layer", "RS-274X", checkCopperLayer),
    ExpectedFile(".smt", "Solder mask top", "RS-274X", checkGerberFile),
    ExpectedFile(".smb", "Solder mask bottom", "RS-274X", checkGerberFile),
    ExpectedFile(".plt", "Silk screen top", "RS-274X", checkGerberFile),
    ExpectedFile(".mil", "Board outline", "RS-274X", checkBoardOutline),
    #Drilling
    ExpectedFile(".pth", "Plated through holes", "Excellon", checkExcellonMetric),
    ExpectedFile(".npth", "Non-plated through holes", "Excellon", checkExcellonMetric),
]

if __name__ == "__main__":
    #Parse commandline arguments
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("directory", help="The directory to scan for project Gerber file")
    parser.add_argument("--gerbv", action="store_true", help="Run gerbv on the files")
    args = parser.parse_args()
    #Perform check
    files = os.listdir(args.directory)
    projectName = extractProjectPrefix(files)
    print(black("Project name: %s" % projectName))
    checkedFiles = [checkFile(args.directory, f, projectName) for f in expectedFiles]
    unknownFiles = set(files) - set(checkedFiles)
    if unknownFiles:
        print(red("Found unknown files: %s" % ",".join(unknownFiles)))
    #Open viewer if enabled
    if args.gerbv:
        filePaths = [os.path.join(args.directory, f) for  f in files]
        subprocess.call(["gerbv"] + filePaths)


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AlbumListActivity">

    <!--<Toolbar-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_alignParentTop="true"-->
        <!--android:id="@+id/toolbar"-->
        <!--android:background="?attr/android:colorPrimary"-->
        <!--/>-->

    <android.support.v7.widget.RecyclerView
        android:id="@+id/album_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


text:
NAME 		:= fivecolors
BIN         := $(NAME)
REPO        := github.com/rjansen/$(NAME)
BUILD       := $(shell git rev-parse --short HEAD)
#VERSION     := $(shell git describe --tags $(shell git rev-list --tags --max-count=1))
MAKEFILE    := $(word $(words $(MAKEFILE_LIST)), $(MAKEFILE_LIST))
BASE_DIR    := $(shell cd $(dir $(MAKEFILE)); pwd)
PKGS        := $(shell go list ./... | grep -v /vendor/)
COVERAGE_FILE   := $(NAME).coverage
COVERAGE_HTML  	:= $(NAME).coverage.html
PKG_COVERAGE   	:= $(NAME).pkg.coverage

ETC_DIR := ./etc
CONF_DIR := $(ETC_DIR)/$(NAME)
CONF_TYPE := yaml

TEST_PKGS :=

ENV ?= local
TEST_PKGS ?=

.PHONY: default
default: build

.PHONY: local
local:
	@echo "Set enviroment to local"
	$(eval ENV = local)

.PHONY: dev
dev:
	@echo "Set enviroment to dev"
	$(eval ENV = dev)

.PHONY: heroku
heroku:
	@echo "Set enviroment to heroku"
	$(eval ENV = heroku)

.PHONY: prod
prod:
	@echo "Set enviroment to prod"
	$(eval ENV = prod)

.PHONY: check_env
check_env:
	@if [ "$(ENV)" == "" ]; then \
	    echo "Env is blank: $(ENV)"; \
	    exit 540; \
	fi

.PHONY: build
build:
	go build $(REPO)

.PHONY: run
run: build
	./$(NAME) -ecf $(CONF_DIR)/$(NAME).$(ENV).$(CONF_TYPE)

pkg_data:
	@echo "Add data pkg for tests"
	$(eval TEST_PKGS += "farm.e-pedion.com/repo/fivecolors/data")

pkg_api:
	@echo "Add api pkg for tests"
	$(eval TEST_PKGS += "farm.e-pedion.com/repo/fivecolors/api")

pkg_test: pkg_data pkg_api
	@echo "TEST_PKGS=$(TEST_PKGS)"

test:
	@if [ "$(TEST_PKGS)" == "" ]; then \
	    echo "Build Without TEST_PKGS" ;\
	    go test farm.e-pedion.com/repo/fivecolors/data farm.e-pedion.com/repo/fivecolors/api ;\
	else \
	    echo "Build With TEST_PKGS=$(TEST_PKGS)" ;\
	    go test $(TEST_PKGS) ;\
	fi


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "args.h"

#include "config.h"
#include "utils.h"

/* Definition of all possible arguments */
ArgHook arg[] = {
   { "d",         0, argSetSearchOnDisk,  infoSetSearchOnDisk },
   { "h",         1, argSetStopHits,      infoSetStopHits },
   { "l",         1, argSetStopLength,    infoSetStopLength },
   { "m",         1, argSetMinWordLength, infoSetMinWordLength },
   { "M",         1, argSetMaxWordLength, infoSetMaxWordLength },
   { "q",         0, argSetQuiet,         infoSetQuiet },
   { "v",         0, argSetVerbose,       infoSetVerbose },
   { "w",         1, argSetStopWord,      infoSetStopWord },
   { "-help",     0, argPrintHelp,        infoPrintHelp },
   { "-version",  0, argPrintVersion,     infoPrintVersion },
   { {0} }
};

/* Makes sure the arguments passed actually make sense */
void argSanityCheck(void) {
   int xWordLen;

   if (minWordLength > maxWordLength) {
      fprintf(stderr, "%s : Minimum word length exceeds maximum word length%s", PROG_NAME, ENDL);
      exit(1);
   }

   if (quiet && verbose) {
      fprintf(stderr, "%s : Only one of -q and -v may be specified%s", PROG_NAME, ENDL);
      exit(1);
   }

   if (stopAfterWord) {
      xWordLen = strlen(xWord);

      if (CheckOnDisk(xWord, xWordLen) == 0) {
	 fprintf(stderr, "%s : Specified word is not in the dictionary%s", PROG_NAME, ENDL);
	 exit(1);
      }
      else if (xWordLen < minWordLength || xWordLen > maxWordLength) {
         fprintf(stderr, "%s : The specified word will never be found%s", PROG_NAME, ENDL);
         exit(1);
      }
   }

   if (stopAfterLength) {
      if (xLength < minWordLength || xLength > maxWordLength) {
         fprintf(stderr, "%s : A word of the specified length will never be found%s", PROG_NAME, ENDL);
         exit(1);
      }
   }
}

/* Goes through and parses all of the arguments.
 * Return value is index at which filenames begin
 * or zero if nothing is left on the command line */
short parseArgs(int argc, char **argv) {
   short i, j, found;
   char *szparam = 0;

   if (argc < MIN_ARGS) {
      fprintf(stderr, "%s : too few arguments%s", PROG_NAME, ENDL);
      exit(1);
   }

   for (i = 1; i < argc; i++) {
      szparam = argv[i];

      /* If the argument starts with a '-' it's a parameter flag */
      if (*szparam != '-') {
         /* Done parsing parameters, before returning do a sanity check */
         argSanityCheck();
         return i;
      }
      else
         szparam++;

      found = 0;
      j = 0;

      /* How dare they!  They didn't pass enough parameters! */
      if (argc < MIN_ARGS + 1) {
         fprintf(stderr, "%s : too few arguments%s", PROG_NAME, ENDL);
         exit(1);
      }

      /* Search for argument hooks */
      while (*arg[j].argName && !found) {
         /* Found one */
         if (strcmp(szparam, arg[j].argName) == 0) {
            if (arg[j].argHasArg) {
               if (i == argc - 1) {
                  fprintf(stderr, "%s : %s parameter is incomplete", PROG_NAME, szparam);
                  exit(1);
               }
               arg[j].argFunc(argv[i+1]);
               i++;
            }
            else
               arg[j].argFunc(0);
            found = 1;
         }

         j++;
      }

      /* If we didn't find the argument we better complain about it! */
      if (!found) {
         fprintf(stderr, "%s : invalid argument -%s%s", PROG_NAME, szparam, ENDL);
         exit(1);
      }
   }

   return 0;
}

/* SetSearchOnDisk argument functions */
void argSetSearchOnDisk(char* szparam) {
   searchOnDisk = 1;
}

void infoSetSearchOnDisk(void) {
   printf("Keep the dictionary on the disk when searching%s", ENDL);
}

/* SetMinWordLength argument functions */
void argSetMinWordLength(char* szparam) {
   minWordLength = atoi(szparam);
   if (minWordLength < DEF_MIN_WORD_LENGTH || minWordLength > DEF_MAX_WORD_LENGTH) {
      fprintf(stderr, "%s : Invalid minimum word length%s", PROG_NAME, ENDL);
      exit(1);
   }
}

void infoSetMinWordLength(void) {
   printf("Sets the minimum word length (default = %d).%s", DEF_MIN_WORD_LENGTH, ENDL);
}

/* SetMaxWordLength argument functions */
void argSetMaxWordLength(char* szparam) {
   maxWordLength = atoi(szparam);
   if (maxWordLength < DEF_MIN_WORD_LENGTH || maxWordLength > DEF_MAX_WORD_LENGTH) {
      fprintf(stderr, "%s : Invalid maximum word length%s", PROG_NAME, ENDL);
      exit(1);
   }
}

void infoSetMaxWordLength(void) {
   printf("Sets the maximum word length (default = %d).%s", DEF_MAX_WORD_LENGTH, ENDL);
}

/* SetStopHits argument functions */
void argSetStopHits(char* szparam) {
   stopAfterHits = 1;

   xHits = atol(szparam);
   if (xHits <= 0) {
      fprintf(stderr, "%s : Invalid value for parameter -h%s", PROG_NAME, ENDL);
      exit(1);
   }
}

void infoSetStopHits(void) {
   printf("Stop after arg words are generated.%s", ENDL);
}

/* SetStopWord argument functions */
void argSetStopWord(char* szparam) {
   short paramLength = strlen(szparam);

   stopAfterWord = 1;
   if (paramLength < DEF_MIN_WORD_LENGTH) {
      fprintf(stderr, "%s : Specified word is too short%s", PROG_NAME, ENDL);
      exit(1);
   }
   else if (paramLength > DEF_MAX_WORD_LENGTH) {
      fprintf(stderr, "%s : Specified word is too long%s", PROG_NAME, ENDL);
      exit(1);
   }

   strcpy(xWord, szparam);
}

void infoSetStopWord(void) {
   printf("Stop after specified word is generated.%s", ENDL);
}

/* SetStopLength argument functions */
void argSetStopLength(char* szparam) {
   stopAfterLength = 1;

   xLength = atoi(szparam);
   if (xLength < DEF_MIN_WORD_LENGTH || xLength > DEF_MAX_WORD_LENGTH) {
      fprintf(stderr, "%s : Specified length is invalid%s", PROG_NAME, ENDL);
      exit(1);
   }
}

void infoSetStopLength(void) {
   printf("Stop after arg length word is found.%s", ENDL);
}

/* SetQuiet argument functions */
void argSetQuiet(char* szparam) {
   quiet = 1;
}

void infoSetQuiet(void) {
   printf("Quiet mode.  Only print words found in the dictionary.%s", ENDL);
}

/* SetVerbose argument functions */
void argSetVerbose(char *szparam) {
   verbose = 1;
}

void infoSetVerbose(void) {
   printf("Verbose mode.  Print all randomly generated strings.%s", ENDL);
}

/* Help argument functions */
void argPrintHelp(char* szparam) {
   unsigned short i, j;

   printf("Usage : %s [options] filename%s%s", PROG_NAME, ENDL, ENDL);
   printf("Displays a list of randomly generated words.%s%s", ENDL, ENDL);

   i = 0;
   while (*arg[i].argName) {
      if (arg[i].argHasArg) {
         printf("  -%s arg", arg[i].argName);
         for (j = 0; j < 12 - strlen(arg[i].argName); j++)
            printf(" ");
      }
      else
         printf("  -%-10s      ", arg[i].argName);
      arg[i].argInfo();
      i++;
   }

   printf("%s", ENDL);
   printf("Send bugs and comments to %s <%s>%s", AUTH_NAME, AUTH_EMAIL, ENDL);

   exit(0);
}

void infoPrintHelp(void) {
   printf("Displays this help message and exits.%s", ENDL);
}

/* Version argument functions */
void argPrintVersion(char* szparam) {
   printf("%s %s.%s%s", PROG_NAME, VER_MAJOR, VER_MINOR, ENDL);
   exit(0);
}

void infoPrintVersion(void) {
   printf("Displays %s's version information and exits.%s", PROG_NAME, ENDL);
}


text:
angular.module('docsTemplateUrlDirective', [])
  .controller('Controller', ['$scope', function($scope) {
    $scope.customer = {
      name: 'Naomi',
      address: '1600 Amphitheatre'
    };
  }])
  .directive('myCustomer', function() {
    return {
      templateUrl: 'my-customer.html'
    };
  });


text:
{% load form_tags %}
{% load widget_tweaks %}

{% if field.is_hidden %}
    {{ field }}
{% else %}
    {% comment %}
        Make the field widget type available to templates so we can mark-up
        checkboxes differently to other widgets.
    {% endcomment %}
    {% annotate_form_field field %}

    {% block control_group %}

            {% block label %}
                {% if not nolabel and field.widget_type != 'CheckboxInput' %}

                        {{ field.label|safe }}
                        {% if field.field.required %} *{% endif %}

                {% endif %}
            {% endblock %}

            {% block controls %}

                    {% block widget %}
                        {% if field.widget_type == 'CheckboxInput' %}

                                {{ field.label|safe }}{% if field.field.required %} *{% endif %}
                                {% render_field field class+="form-control" %}

                        {% else %}
                            {% render_field field class+="form-control" %}
                        {% endif %}
                    {% endblock %}

                    {% block errors %}
                        {% for error in field.errors %}
                             {{ error }}
                        {% endfor %}
                    {% endblock %}

                    {% block help_text %}
                        {% if field.help_text %}

                                {# We allow HTML within form help fields #}
                                {{ field.help_text|safe }}

                        {% endif %}
                    {% endblock %}

            {% endblock %}

    {% endblock %}
{% endif %}


text:
package com.hankcs.demo;

import com.hankcs.hanlp.seg.NShort.NShortSegment;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.Viterbi.ViterbiSegment;

/**
 * N最短路径分词,该分词器比最短路分词器慢,但是效果稍微好一些,对命名实体识别能力更强
 *
 * @author hankcs
 */
public class DemoNShortSegment
{
    public static void main(String[] args)
    {
        Segment nShortSegment = new NShortSegment().enableCustomDictionary(false).enablePlaceRecognize(true).enableOrganizationRecognize(true);
        Segment shortestSegment = new ViterbiSegment().enableCustomDictionary(false).enablePlaceRecognize(true).enableOrganizationRecognize(true);
        String[] testCase = new String[]{
                "今天,刘志军案的关键人物,山西女商人丁书苗在市二中院出庭受审。",
                "江西省监狱管理局与中国太平洋财产保险股份有限公司南昌中心支公司保险合同纠纷案",
                "新北商贸有限公司",
        };
        for (String sentence : testCase)
        {
            System.out.println("N-最短分词:" + nShortSegment.seg(sentence) + "\n最短路分词:" + shortestSegment.seg(sentence));
        }
    }
}


text:
#ifndef __LIST_H__
#define __LIST_H__

/* taken from linux kernel */

#undef offsetof
#ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#else
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#endif

#define container_of(ptr, type, member) ({			\
        const typeof( ((type *)0)->member ) *__mptr = (ptr);	\
        (type *)( (char *)__mptr - offsetof(type,member) );})

struct list_head {
	struct list_head *next, *prev;
};

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
	struct list_head name = LIST_HEAD_INIT(name)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
	list->next = list;
	list->prev = list;
}

#define list_first_entry(ptr, type, member) \
	list_entry((ptr)->next, type, member)

static inline int list_empty(const struct list_head *head)
{
	return head->next == head;
}

#define list_entry(ptr, type, member) \
	container_of(ptr, type, member)

#define list_for_each(pos, head) \
	for (pos = (head)->next; pos != (head); pos = pos->next)

#define list_for_each_entry(pos, head, member)				\
	for (pos = list_entry((head)->next, typeof(*pos), member);	\
	     &pos->member != (head);				 	\
	     pos = list_entry(pos->member.next, typeof(*pos), member))

#define list_for_each_entry_safe(pos, n, head, member)			\
	for (pos = list_entry((head)->next, typeof(*pos), member),	\
		n = list_entry(pos->member.next, typeof(*pos), member);	\
	     &pos->member != (head); 					\
	     pos = n, n = list_entry(n->member.next, typeof(*n), member))

static inline void __list_add(struct list_head *new,
			      struct list_head *prev,
			      struct list_head *next)
{
	next->prev = new;
	new->next = next;
	new->prev = prev;
	prev->next = new;
}

static inline void list_add(struct list_head *new, struct list_head *head)
{
	__list_add(new, head, head->next);
}

static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
	__list_add(new, head->prev, head);
}

static inline void __list_del(struct list_head * prev, struct list_head * next)
{
	next->prev = prev;
	prev->next = next;
}

static inline void list_del(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	entry->next = entry->prev = NULL;
}

static inline void list_del_init(struct list_head *entry)
{
	__list_del(entry->prev, entry->next);
	INIT_LIST_HEAD(entry);
}

static inline void __list_splice(const struct list_head *list,
				 struct list_head *prev,
				 struct list_head *next)
{
	struct list_head *first = list->next;
	struct list_head *last = list->prev;

	first->prev = prev;
	prev->next = first;

	last->next = next;
	next->prev = last;
}

static inline void list_splice_init(struct list_head *list,
				    struct list_head *head)
{
	if (!list_empty(list)) {
		__list_splice(list, head, head->next);
		INIT_LIST_HEAD(list);
	}
}

#endif


text:
package com.eitax.recall.front.domain;

import lombok.Data;

@Data
public class Lambda {
	private String jobId;
	private String awsName;
	private String actionName;
	private String triggerName;
	private String description;
	private String arn;
	private String modalId;
	private String modModalId;
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RuntimePropertyInfo.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implementation of <see cref="IRuntimePropertyInfo" /> for runtime properties.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    using Kephas.Dynamic;
    using Kephas.Logging;
    using Kephas.Reflection;
    using Kephas.Resources;

    /// <summary>
    /// Implementation of <see cref="IRuntimePropertyInfo" /> for runtime properties.
    /// </summary>
    public class RuntimePropertyInfo : RuntimeElementInfoBase, IRuntimePropertyInfo
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimePropertyInfo"/> class.
        /// </summary>
        /// <param name="typeRegistry">The type serviceRegistry.</param>
        /// <param name="propertyInfo">The property information.</param>
        /// <param name="position">Optional. The position.</param>
        /// <param name="logger">Optional. The logger.</param>
        internal RuntimePropertyInfo(IRuntimeTypeRegistry typeRegistry, PropertyInfo propertyInfo, int position = -1, ILogger? logger = null)
            : base(typeRegistry, logger)
        {
            this.PropertyInfo = propertyInfo;
            this.Name = propertyInfo.Name;
            this.FullName = propertyInfo.DeclaringType?.FullName + "." + propertyInfo.Name;
        }

        /// <summary>
        /// Gets the name of the element.
        /// </summary>
        /// <value>
        /// The name of the element.
        /// </value>
        public string Name { get; }

        /// <summary>
        /// Gets the full name of the element.
        /// </summary>
        /// <value>
        /// The full name of the element.
        /// </value>
        public string FullName { get; }

        /// <summary>
        /// Gets the element annotations.
        /// </summary>
        /// <value>
        /// The element annotations.
        /// </value>
        public IEnumerable<object> Annotations => this.PropertyInfo.GetCustomAttributes();

        /// <summary>
        /// Gets the parent element declaring this element.
        /// </summary>
        /// <value>
        /// The declaring element.
        /// </value>
        public IElementInfo DeclaringContainer => this.TypeRegistry.GetTypeInfo(this.PropertyInfo.DeclaringType);

        /// <summary>
        /// Gets the property information.
        /// </summary>
        /// <value>
        /// The property information.
        /// </value>
        public PropertyInfo PropertyInfo { get; }

        /// <summary>
        /// Gets a value indicating whether this property is static.
        /// </summary>
        /// <value>
        /// True if this property is static, false if not.
        /// </value>
        public bool IsStatic => (this.PropertyInfo.GetMethod?.IsStatic ?? false) || (this.PropertyInfo.SetMethod?.IsStatic ?? false);

        /// <summary>
        /// Gets the type of the property.
        /// </summary>
        /// <value>
        /// The type of the property.
        /// </value>
        public IRuntimeTypeInfo ValueType => this.TypeRegistry.GetTypeInfo(this.PropertyInfo.PropertyType);

        /// <summary>
        /// Gets the type of the property.
        /// </summary>
        /// <value>
        /// The type of the property.
        /// </value>
        ITypeInfo IValueElementInfo.ValueType => this.TypeRegistry.GetTypeInfo(this.PropertyInfo.PropertyType);

        /// <summary>
        /// Gets a value indicating whether the property can be written to.
        /// </summary>
        /// <value>
        /// <c>true</c> if the property can be written to; otherwise <c>false</c>.
        /// </value>
        public virtual bool CanWrite => this.PropertyInfo.CanWrite;

        /// <summary>
        /// Gets a value indicating whether the property value can be read.
        /// </summary>
        /// <value>
        /// <c>true</c> if the property value can be read; otherwise <c>false</c>.
        /// </value>
        public virtual bool CanRead => this.PropertyInfo.CanRead;

#if NETSTANDARD2_1
#else
        /// <summary>
        /// Gets the display information.
        /// </summary>
        /// <returns>The display information.</returns>
        public virtual IDisplayInfo? GetDisplayInfo() => ElementInfoHelper.GetDisplayInfo(this);
#endif

        /// <summary>
        /// Gets the underlying member information.
        /// </summary>
        /// <returns>
        /// The underlying member information.
        /// </returns>
        public ICustomAttributeProvider GetUnderlyingElementInfo() => this.PropertyInfo;

        /// <summary>
        /// Sets the specified value.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="value">The value.</param>
        /// <exception cref="MemberAccessException">Property value cannot be set.</exception>
        public virtual void SetValue(object? obj, object? value)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Gets the value from the specified object.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>
        /// The value.
        /// </returns>
        /// <exception cref="MemberAccessException">Property value cannot be get.</exception>
        public virtual object? GetValue(object? obj)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Gets the attribute of the provided type.
        /// </summary>
        /// <typeparam name="TAttribute">Type of the attribute.</typeparam>
        /// <returns>
        /// The attribute of the provided type.
        /// </returns>
        public IEnumerable<TAttribute> GetAttributes<TAttribute>()
            where TAttribute : Attribute
        {
            return this.PropertyInfo.GetCustomAttributes<TAttribute>(inherit: true);
        }

        /// <summary>Returns a string that represents the current object.</summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            return $"{this.PropertyInfo.Name}: {this.PropertyInfo.PropertyType.FullName}";
        }
    }

    /// <summary>
    /// Implementation of <see cref="IRuntimePropertyInfo" /> for typed runtime properties.
    /// </summary>
    /// <typeparam name="T">The container type.</typeparam>
    /// <typeparam name="TMember">The member type.</typeparam>
    public sealed class RuntimePropertyInfo<T, TMember> : RuntimePropertyInfo
    {
        /// <summary>
        /// True if getter computed.
        /// </summary>
        private bool getterComputed = false;

        /// <summary>
        /// The getter.
        /// </summary>
        private Func<T, TMember>? getter;

        /// <summary>
        /// True if setter computed.
        /// </summary>
        private bool setterComputed = false;

        /// <summary>
        /// The setter.
        /// </summary>
        private Action<T, TMember>? setter;

        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimePropertyInfo{T,TMember}"/> class.
        /// </summary>
        /// <param name="typeRegistry">The type serviceRegistry.</param>
        /// <param name="propertyInfo">The property information.</param>
        /// <param name="position">Optional. The position.</param>
        /// <param name="logger">Optional. The logger.</param>
        internal RuntimePropertyInfo(IRuntimeTypeRegistry typeRegistry, PropertyInfo propertyInfo, int position = -1, ILogger? logger = null)
            : base(typeRegistry, propertyInfo, position, logger)
        {
        }

        /// <summary>
        /// Gets a value indicating whether the property value can be read.
        /// </summary>
        /// <value>
        /// <c>true</c> if the property value can be read; otherwise <c>false</c>.
        /// </value>
        public override bool CanRead => this.Getter != null && base.CanRead;

        /// <summary>
        /// Gets a value indicating whether the property can be written to.
        /// </summary>
        /// <value>
        /// <c>true</c> if the property can be written to; otherwise <c>false</c>.
        /// </value>
        public override bool CanWrite => this.Setter != null && base.CanWrite;

        /// <summary>
        /// Gets the getter.
        /// </summary>
        private Func<T, TMember>? Getter
        {
            get
            {
                if (this.getterComputed)
                {
                    return this.getter;
                }

                this.getter = this.ComputeGetter();
                this.getterComputed = true;
                return this.getter;
            }
        }

        /// <summary>
        /// Gets the setter.
        /// </summary>
        private Action<T, TMember>? Setter
        {
            get
            {
                if (this.setterComputed)
                {
                    return this.setter;
                }

                this.setter = this.ComputeSetter();
                this.setterComputed = true;
                return this.setter;
            }
        }

        /// <summary>
        /// Sets the specified value.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="value">The value.</param>
        /// <exception cref="MemberAccessException">Property value cannot be set.</exception>
        public override void SetValue(object? obj, object? value)
        {
            var setDelegate = this.Setter;
            if (setDelegate == null)
            {
                throw new MemberAccessException(string.Format(Strings.RuntimePropertyInfo_SetValue_Exception, this.PropertyInfo.Name, typeof(T)));
            }

            setDelegate((T)obj, (TMember)value);
        }

        /// <summary>
        /// Gets the value from the specified object.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>
        /// The value.
        /// </returns>
        /// <exception cref="MemberAccessException">Property value cannot be get.</exception>
        public override object? GetValue(object? obj)
        {
            var getDelegate = this.Getter;
            if (getDelegate == null)
            {
                throw new MemberAccessException(string.Format(Strings.RuntimePropertyInfo_GetValue_Exception, this.PropertyInfo.Name, typeof(T)));
            }

            return getDelegate((T)obj);
        }

        /// <summary>
        /// Computes the member get delegate.
        /// </summary>
        /// <returns>
        /// The member get delegate.
        /// </returns>
        private Func<T, TMember>? ComputeGetter()
        {
            var mi = this.PropertyInfo.GetMethod;
            if (mi != null && mi.IsPublic)
            {
                try
                {
                    if (mi.IsSecurityTransparent)
                    {
                        return obj => (TMember)mi.Invoke(obj, Array.Empty<object>());
                    }

                    return (Func<T, TMember>)mi.CreateDelegate(typeof(Func<T, TMember>));
                }
                catch (ArgumentException ex)
                {
                    if (this.Logger.IsTraceEnabled())
                    {
                        this.Logger.Trace(ex, "Cannot compute getter delegate for {typeName}.{methodName}, falling back to reflection.", mi.DeclaringType, mi.Name);
                    }

                    return obj => (TMember)mi.Invoke(obj, Array.Empty<object>());
                }
            }

            return null;
        }

        /// <summary>
        /// Computes the member set delegate.
        /// </summary>
        /// <returns>
        /// The member set delegate.
        /// </returns>
        private Action<T, TMember>? ComputeSetter()
        {
            var mi = this.PropertyInfo.SetMethod;
            if (mi != null && mi.IsPublic)
            {
                try
                {
                    if (mi.IsSecurityTransparent)
                    {
                        return (obj, v) => mi.Invoke(obj, new object[] { v });
                    }

                    return (Action<T, TMember>)mi.CreateDelegate(typeof(Action<T, TMember>));
                }
                catch (ArgumentException ex)
                {
                    if (this.Logger.IsTraceEnabled())
                    {
                        this.Logger.Trace(ex, "Cannot compute setter delegate for {typeName}.{methodName}, falling back to reflection.", mi.DeclaringType, mi.Name);
                    }

                    return (obj, v) => mi.Invoke(obj, new object[] { v });
                }
            }

            return null;
        }
    }
}


text:
VERSION=${VERSION:-4.14.1}
MAINTAINER=${MAINTAINER:-OpenNebula Systems <support@opennebula.systems>}
LICENSE=${LICENSE:-Apache 2.0}
PACKAGE_NAME=${PACKAGE_NAME:-one-context}
VENDOR=${VENDOR:-OpenNebula Systems}
DESC="
This package prepares a VM image for OpenNebula:
  * Disables udev net and cd persistent rules
  * Deletes udev net and cd persistent rules
  * Unconfigures the network
  * Adds OpenNebula contextualization scripts to startup
    * Configure network
    * Configure dns (from DNS and ETH*_DNS context variables)
    * Set root authorized keys (from SSH_PUBLIC_KEY and EC2_PUBLIC_KEY)
  * Add onegate tool (NEEDS RUBY AND JSON GEM TO WORK)
  * Resize root filesystem
  * Generate host ssh keys in debian distributions

To get support check the OpenNebula web page:
  http://OpenNebula.org
"
DESCRIPTION=${DESCRIPTION:-$DESC}
PACKAGE_TYPE=${PACKAGE_TYPE:-deb}
URL=${URL:-http://opennebula.org}

[ $PACKAGE_TYPE = rpm ] && PKGARGS="--rpm-os linux"

SCRIPTS_DIR=$PWD
NAME="${PACKAGE_NAME}_${VERSION}.${PACKAGE_TYPE}"
rm $NAME

rm -rf tmp
mkdir tmp
cp -r base/* tmp
cp -r base_$PACKAGE_TYPE/* tmp

for i in $*; do
  cp -r "$i" tmp
done

cd tmp

fpm -n "$PACKAGE_NAME" -t "$PACKAGE_TYPE" $PKGARGS -s dir --vendor "$VENDOR" \
    --license "$LICENSE" --description "$DESCRIPTION" --url "$URL" \
    -m "$MAINTAINER" -v "$VERSION" --after-install $SCRIPTS_DIR/postinstall \
    -a all -p $SCRIPTS_DIR/$NAME *

echo $NAME


text:
(function () {
    'use strict';

    angular.module('demoApp').config(function ($routeProvider) {

        $routeProvider
            // route for the home page
            .when('/', {
                templateUrl: 'demoApp/home/home.template.html',
                controller: 'HomeController'
            })

            // route for the about page
            .when('/movies', {
                templateUrl: 'demoApp/movies/movies.template.html',
                controller: 'MoviesController as vm'
            })

            // route for the contact page
            .when('/bootstrapTutorial', {
                templateUrl: 'demoApp/bootstrapTutorial/bootstrapTutorial.template.html',
                controller: 'BootstrapTutorialController'
            });
    })

})();


text:
NS_ASSUME_NONNULL_BEGIN

@interface PhoneRegionParseInterface : AFHTTPSessionManager

+ (instancetype)sharedClient;

@end

NS_ASSUME_NONNULL_END


text:
using ExpressionBuilder.Parser;

namespace ExpressionBuilder.Fluent
{
	public interface ICodeLine : IParsable
	{
	}
}


text:
Bokeh
=====

  Latest Release

  License

  Build Status

  Conda

  PyPI

Bokeh is a Python interactive visualization library that targets modern
web browsers for presentation. Its goal is to provide elegant, concise
construction of novel graphics in the style of D3.js, but also deliver this
capability with high-performance interactivity over very large or streaming
datasets. Bokeh can help anyone who would like to quickly and easily create
interactive plots, dashboards, and data applications.

Please visit the [Bokeh web page](http://bokeh.pydata.org/en/latest) for more information and full documentation.

To get started quickly, follow the [Quickstart](http://bokeh.pydata.org/en/latest/docs/quickstart.html) in the online documentation, or the QUICKSTART.md located in the top level of the bokeh repository.

Be sure to follow us on Twitter [@bokehplots](http://twitter.com/BokehPlots), as well as on
[Vine](https://vine.co/bokehplots), and [Youtube](https://www.youtube.com/channel/UCK0rSk29mmg4UT4bIOvPYhw)!

Interactive gallery
===================


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="filter_footer_order_type_item_height">50dp</dimen>
</resources>


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.19 at 01:26:29 PM BRT
//

package br.com.dsfnet.nfse.wsnfe2.tp;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for tpTipoRecolhimento.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="tpTipoRecolhimento">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="A"/>
 *     <enumeration value="R"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "tpTipoRecolhimento")
@XmlEnum
public enum TpTipoRecolhimento {

    /**
     * A Recolher.
     *
     */
    A,

    /**
     * Retido na Fonte.
     *
     */
    R;

    public String value() {
        return name();
    }

    public static TpTipoRecolhimento fromValue(String v) {
        return valueOf(v);
    }

}