text:
#ifndef __cxxtest__ErrorFormatter_h__
#define __cxxtest__ErrorFormatter_h__

//
// The ErrorFormatter is a TestListener that
// prints reports of the errors to an output
// stream.  Since we cannot rely ou the standard
// iostreams, this header defines a base class
// analogout to std::ostream.
//

#include <cxxtest/TestRunner.h>
#include <cxxtest/TestListener.h>
#include <cxxtest/TestTracker.h>
#include <cxxtest/ValueTraits.h>

namespace CxxTest
{
    class OutputStream
    {
    public:
        virtual ~OutputStream() {}
        virtual void flush() {};
        virtual OutputStream &operator<<( unsigned /*number*/ ) { return *this; }
        virtual OutputStream &operator<<( const char * /*string*/ ) { return *this; }

        typedef void (*Manipulator)( OutputStream & );

        virtual OutputStream &operator<<( Manipulator m ) { m( *this ); return *this; }
        static void endl( OutputStream &o ) { (o << "\n").flush(); }
    };

    class ErrorFormatter : public TestListener
    {
    public:
        ErrorFormatter( OutputStream *o, const char *preLine = ":", const char *postLine = "" ) :
            _dotting( true ),
            _reported( false ),
            _verbose( false ),
            _auto( false ),
            _o(o),
            _preLine(preLine),
            _postLine(postLine)
        {
        }

        int run()
        {
            TestRunner::runAllTests( *this );
            return tracker().failedTests();
        }

        void enterWorld( const WorldDescription & /*desc*/ )
        {
            if ( getenv( "TEST" ) || getenv( "SUITE" ) ) {
              (*_o) << "Running tests...";
            } else {
              (*_o) << "Running " << totalTests;
            }
            _o->flush();
            if ( getenv( "VERBOSE" ) ) {
              _verbose = true;
            } else {
              _dotting = true;
            }
            if ( getenv( "AUTO" ) ) {
              _auto = true;
            }
            _reported = false;
        }

        static void totalTests( OutputStream &o )
        {
            char s[WorldDescription::MAX_STRLEN_TOTAL_TESTS];
            const WorldDescription &wd = tracker().world();
            o << wd.strTotalTests( s ) << (wd.numTotalTests() == 1 ? " test" : " tests");
        }

        void enterSuite( const SuiteDescription &d )
        {
          if ( _verbose ) {
            (*_o) << endl << "Suite " << d.suiteName() << endl;
          }
            _reported = false;
        }

        void enterTest( const TestDescription & d)
        {
          if ( _verbose ) {
            ((*_o) << "  " << d.testName() << ": ").flush();
          }

          _reported = false;
        }

        void leaveTest( const TestDescription &d)
        {
          if ( _verbose ) {
            if ( tracker().testFailed() ) {
              (*_o) << "FAIL" << endl;
              if ( _auto ) {
                (*_o) << "--- F " << d.suiteName() << "::" << d.testName() << "::" <<
                  d.file() << "::" << d.line() << endl;
              }
            } else {
              (*_o) << "ok" << endl;
              if ( _auto ) {
                (*_o) << "--- O " << d.suiteName() << "::" << d.testName() << endl;
              }
            }
          } else {
            if ( !tracker().testFailed() ) {
                ((*_o) << ".").flush();
                _dotting = true;
            }
          }
        }

        void leaveWorld( const WorldDescription &desc )
        {
            if ( !tracker().failedTests() ) {
                (*_o) << "OK!" << endl;
                return;
            }
            newLine();
            (*_o) << "Failed " << tracker().failedTests() << " of " << totalTests << endl;
            unsigned numPassed = desc.numTotalTests() - tracker().failedTests();
            (*_o) << "Success rate: " << (numPassed * 100 / desc.numTotalTests()) << "%" << endl;
        }

        void trace( const char *file, unsigned line, const char *expression )
        {
            stop( file, line ) << "Trace: " <<
                expression << endl;
        }

        void warning( const char *file, unsigned line, const char *expression )
        {
            stop( file, line ) << "Warning: " <<
                expression << endl;
        }

        void failedTest( const char *file, unsigned line, const char *expression )
        {
            stop( file, line ) << "Error: Test failed: " <<
                expression << endl;
        }

        void failedAssert( const char *file, unsigned line, const char *expression )
        {
            stop( file, line ) << "Error: Assertion failed: " <<
                expression << endl;
        }

        void failedAssertEquals( const char *file, unsigned line,
                                 const char *xStr, const char *yStr,
                                 const char *x, const char *y )
        {
            stop( file, line ) << "Error: Expected (" <<
                xStr << " == " << yStr << "), found (" <<
                x << " != " << y << ")" << endl;
        }

        void failedAssertSameData( const char *file, unsigned line,
                                   const char *xStr, const char *yStr,
                                   const char *sizeStr, const void *x,
                                   const void *y, unsigned size )
        {
            stop( file, line ) << "Error: Expected " << sizeStr << " (" << size << ") bytes to be equal at (" <<
                xStr << ") and (" << yStr << "), found:" << endl;
            dump( x, size );
            (*_o) << "     differs from" << endl;
            dump( y, size );
        }

        void failedAssertDelta( const char *file, unsigned line,
                                const char *xStr, const char *yStr, const char *dStr,
                                const char *x, const char *y, const char *d )
        {
            stop( file, line ) << "Error: Expected (" <<
                xStr << " == " << yStr << ") up to " << dStr << " (" << d << "), found (" <<
                x << " != " << y << ")" << endl;
        }

        void failedAssertDiffers( const char *file, unsigned line,
                                  const char *xStr, const char *yStr,
                                  const char *value )
        {
            stop( file, line ) << "Error: Expected (" <<
                xStr << " != " << yStr << "), found (" <<
                value << ")" << endl;
        }

        void failedAssertLessThan( const char *file, unsigned line,
                                   const char *xStr, const char *yStr,
                                   const char *x, const char *y )
        {
            stop( file, line ) << "Error: Expected (" <<
                xStr << " < " << yStr << "), found (" <<
                x << " >= " << y << ")" << endl;
        }

        void failedAssertLessThanEquals( const char *file, unsigned line,
                                         const char *xStr, const char *yStr,
                                         const char *x, const char *y )
        {
            stop( file, line ) << "Error: Expected (" <<
                xStr << " <= " << yStr << "), found (" <<
                x << " > " << y << ")" << endl;
        }

        void failedAssertRelation( const char *file, unsigned line,
                                   const char *relation, const char *xStr, const char *yStr,
                                   const char *x, const char *y )
        {
            stop( file, line ) << "Error: Expected " << relation << "( " <<
                xStr << ", " << yStr << " ), found !" << relation << "( " << x << ", " << y << " )" << endl;
        }

        void failedAssertPredicate( const char *file, unsigned line,
                                    const char *predicate, const char *xStr, const char *x )
        {
            stop( file, line ) << "Error: Expected " << predicate << "( " <<
                xStr << " ), found !" << predicate << "( " << x << " )" << endl;
        }

        void failedAssertThrows( const char *file, unsigned line,
                                 const char *expression, const char *type,
                                 bool otherThrown )
        {
            stop( file, line ) << "Error: Expected (" << expression << ") to throw (" <<
                type << ") but it " << (otherThrown ? "threw something else" : "didn't throw") <<
                endl;
        }

        void failedAssertThrowsNot( const char *file, unsigned line, const char *expression )
        {
            stop( file, line ) << "Error: Expected (" << expression << ") not to throw, but it did" <<
                endl;
        }

    protected:
        OutputStream *outputStream() const
        {
            return _o;
        }

    private:
        ErrorFormatter( const ErrorFormatter & );
        ErrorFormatter &operator=( const ErrorFormatter & );

        OutputStream &stop( const char *file, unsigned line )
        {
            newLine();
            reportTest();
            return (*_o) << file << _preLine << line << _postLine << ": ";
        }

        void newLine( void )
        {
            if ( _dotting ) {
                (*_o) << endl;
                _dotting = false;
            }
        }

        void reportTest( void )
        {
            if( _reported )
                return;
            (*_o) << "In " << tracker().suite().suiteName() << "::" << tracker().test().testName() << ":" << endl;
            _reported = true;
        }

        void dump( const void *buffer, unsigned size )
        {
            if ( !buffer )
                dumpNull();
            else
                dumpBuffer( buffer, size );
        }

        void dumpNull()
        {
            (*_o) << "   (null)" << endl;
        }

        void dumpBuffer( const void *buffer, unsigned size )
        {
            unsigned dumpSize = size;
            if ( maxDumpSize() && dumpSize > maxDumpSize() )
                dumpSize = maxDumpSize();

            const unsigned char *p = (const unsigned char *)buffer;
            (*_o) << "   { ";
            for ( unsigned i = 0; i < dumpSize; ++ i )
                (*_o) << byteToHex( *p++ ) << " ";
            if ( dumpSize < size )
                (*_o) << "... ";
            (*_o) << "}" << endl;
        }

        static void endl( OutputStream &o )
        {
            OutputStream::endl( o );
        }

        bool _dotting;
        bool _reported;
        bool _verbose;
        bool _auto;
        OutputStream *_o;
        const char *_preLine;
        const char *_postLine;
    };
};

#endif // __cxxtest__ErrorFormatter_h__


text:
package models

import (
	"crypto/rand"
	"log"
	"math/big"
	"net"

	"github.com/jinzhu/gorm"
	"github.com/oschwald/maxminddb-golang"
)

type mmCity struct {
	GeoPoint mmGeoPoint `maxminddb:"location"`
}

type mmGeoPoint struct {
	Latitude  float64 `maxminddb:"latitude"`
	Longitude float64 `maxminddb:"longitude"`
}

// Result contains the fields for a result object,
// which is a representation of a target in a campaign.
type Result struct {
	Id         int64   `json:"-"`
	CampaignId int64   `json:"-"`
	UserId     int64   `json:"-"`
	RId        string  `json:"id"`
	Email      string  `json:"email"`
	FirstName  string  `json:"first_name"`
	LastName   string  `json:"last_name"`
	Position   string  `json:"position"`
	Status     string  `json:"status" sql:"not null"`
	IP         string  `json:"ip"`
	Latitude   float64 `json:"latitude"`
	Longitude  float64 `json:"longitude"`
}

// UpdateStatus updates the status of the result in the database
func (r *Result) UpdateStatus(s string) error {
	return db.Table("results").Where("id=?", r.Id).Update("status", s).Error
}

// UpdateGeo updates the latitude and longitude of the result in
// the database given an IP address
func (r *Result) UpdateGeo(addr string) error {
	// Open a connection to the maxmind db
	mmdb, err := maxminddb.Open("static/db/geolite2-city.mmdb")
	if err != nil {
		log.Fatal(err)
	}
	defer mmdb.Close()
	ip := net.ParseIP(addr)
	var city mmCity
	// Get the record
	err = mmdb.Lookup(ip, &city)
	if err != nil {
		return err
	}
	// Update the database with the record information
	return db.Table("results").Where("id=?", r.Id).Updates(map[string]interface{}{
		"ip":        addr,
		"latitude":  city.GeoPoint.Latitude,
		"longitude": city.GeoPoint.Longitude,
	}).Error
}

// GenerateId generates a unique key to represent the result
// in the database
func (r *Result) GenerateId() error {
	// Keep trying until we generate a unique key (shouldn't take more than one or two iterations)
	const alphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	k := make([]byte, 7)
	for {
		for i := range k {
			idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(alphaNum))))
			if err != nil {
				return err
			}
			k[i] = alphaNum[idx.Int64()]
		}
		r.RId = string(k)
		err := db.Table("results").Where("r_id=?", r.RId).First(&Result{}).Error
		if err == gorm.ErrRecordNotFound {
			break
		}
	}
	return nil
}

// GetResult returns the Result object from the database
// given the ResultId
func GetResult(rid string) (Result, error) {
	r := Result{}
	err := db.Where("r_id=?", rid).First(&r).Error
	return r, err
}

redpajama_set_name: RedPajamaGithub


text:
require "version"
require "thor/group"

module Mafia
  module Helpers
    def camelize(string)
      string.split(/[\W_]/).map {|c| c.capitalize}.join
    end
  end

  class Generator < Thor::Group
    include Thor::Actions
    include Mafia::Helpers

    argument :name

    def self.source_root
      File.expand_path(File.join(File.dirname(__FILE__), 'mafia/templates'))
    end

    def create_gemspec_file
      opts = {
        :name => name,
        :creator_name => `git config user.name`.chomp,
        :creator_email => `git config user.email`.chomp
      }

      template("gemspec.tt", "#{name}/#{name}.gemspec", opts)
    end

    def create_config_ru_file
      template("config.ru.tt", "#{name}/config.ru")
    end

    def create_version_file
      template("version.rb.tt", "#{name}/lib/version.rb")
    end

    def create_gem_file
      template("gem.rb.tt", "#{name}/lib/#{name}.rb")
    end

    def create_app_file
      template("app.rb.tt", "#{name}/lib/#{name}/app.rb")
    end

    def copy_rakefile
      copy_file("Rakefile", "#{name}/Rakefile")
    end

    def create_gemfile
      template("Gemfile.tt", "#{name}/Gemfile")
    end

    def copy_readme
      template("README.md.tt", "#{name}/README.md")
    end

    def create_empty_files_and_directories
      empty_directory("#{name}/lib/#{name}/public")
      empty_directory("#{name}/lib/#{name}/views")
      empty_directory("#{name}/lib/#{name}/lib")
    end

    def create_bin_file
      if yes? "\n\nCreate a binary to run your application?", :green
        template("bin.tt", "#{name}/bin/#{name}")
        inject_into_file "#{name}/#{name}.gemspec", "\n  s.add_dependency \"thor\"", :after => "s.add_dependency \"sinatra\", \"1.3.1\""
      end
    end

    def create_license
      if yes? "\n\nUse MIT License?", :green

        opts = {
          :name => name,
          :creator_name => `git config user.name`.chomp,
          :creator_email => `git config user.email`.chomp
        }

        template("LICENSE.tt", "#{name}/LICENSE", opts)
      end
    end

    def initalize_git_repo
      target = File.join(Dir.pwd, name)
      say "\n\nInitializating git repo in #{target}", :green
      Dir.chdir(target) {
        run "git init", :verbose => false
        run "git add .", :verbose => false
      }
    end

    def run_bundle_command
      target = File.join(Dir.pwd, name)
      say "\n\nRunning Bundler", :green
      Dir.chdir(target) {
        run "bundle install", :verbose => false
      }
    end

    def show_complete_message
      complete = <<-COMPLETE

Sinatra gem has been generated

For help using sinatra please visit www.sinatrarb.com

COMPLETE

      say complete, :green

    end
  end
end


text:
<?php

namespace app\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Expertise;

/**
 * ExpertiseSearch represents the model behind the search form about `app\models\Expertise`.
 */
class ExpertiseSearch extends Expertise
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'doctor_id', 'specialization_id'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Expertise::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'doctor_id' => $this->doctor_id,
            'specialization_id' => $this->specialization_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        return $dataProvider;
    }
}


text:
package org.apache.solr.response.transform;

import java.util.Set;

import org.apache.lucene.document.Field;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.SchemaField;

/**
 * Used to mark whether a document has been elevated or not
 * @since solr 4.0
 */
public class ElevatedMarkerFactory extends TransformerFactory
{
  @Override
  public DocTransformer create(String field, SolrParams params, SolrQueryRequest req) {
    SchemaField uniqueKeyField = req.getSchema().getUniqueKeyField();
    String idfield = uniqueKeyField.getName();
    return new MarkTransformer(field,idfield, uniqueKeyField.getType());
  }
}

class MarkTransformer extends BaseEditorialTransformer
{

  MarkTransformer(String name, String idFieldName, FieldType ft) {
    super(name, idFieldName, ft);
  }

  @Override
  protected Set<String> getIdSet() {
    return (Set<String>) context.req.getContext().get("BOOSTED");
  }
}


text:
/*

old collision code. this code is deprecated and will eventually be removed
from ODE.

*/

#ifndef _ODE_SPACE_H_
#define _ODE_SPACE_H_

#include "common.h"

#ifdef __cplusplus
extern "C" {
#endif

struct dContactGeom;

typedef void dNearCallback (void *data, dGeomID o1, dGeomID o2);

/* extra information the space needs in every geometry object */

typedef struct dGeomSpaceData {
  dGeomID next;
} dGeomSpaceData;

dSpaceID dSimpleSpaceCreate (int dummy);
dSpaceID dHashSpaceCreate (int dummy);
dSpaceID dQuadTreeSpaceCreate (int dummy, dVector3 Center, dVector3 Extents, int Depth);

void dSpaceDestroy (dSpaceID);
void dSpaceAdd (dSpaceID, dGeomID);
void dSpaceRemove (dSpaceID, dGeomID);
void dSpaceCollide (dSpaceID space, void *data, dNearCallback *callback);
int dSpaceQuery (dSpaceID, dGeomID);

void dHashSpaceSetLevels (dSpaceID space, int minlevel, int maxlevel);

/* @@@ NOT FLEXIBLE ENOUGH
 *
 * generate contacts for those objects in the space that touch each other.
 * an array of contacts is created on the alternative stack using
 * StackAlloc(), and a pointer to the array is returned. the size of the
 * array is returned by the function.
 */
/* int dSpaceCollide (dSpaceID space, dContactGeom **contact_array); */

/* HMMMMM... i dont think so.
 * tell the space that an object has moved, so its representation in the
 * space should be changed.
 */
/* void dSpaceObjectMoved (dSpaceID, dGeomID); */

#ifdef __cplusplus
}
#endif

#endif


text:
/* CSS Theming/Shadows
 *
 * This demo shows how to use CSS shadows.
 */

#include <gtk/gtk.h>

static GtkWidget *window = NULL;

static void
show_parsing_error (GtkCssProvider *provider,
                    GtkCssSection  *section,
                    const GError   *error,
                    GtkTextBuffer  *buffer)
{
  GtkTextIter start, end;
  const char *tag_name;

  gtk_text_buffer_get_iter_at_line_index (buffer,
                                          &start,
                                          gtk_css_section_get_start_line (section),
                                          gtk_css_section_get_start_position (section));
  gtk_text_buffer_get_iter_at_line_index (buffer,
                                          &end,
                                          gtk_css_section_get_end_line (section),
                                          gtk_css_section_get_end_position (section));

  if (g_error_matches (error, GTK_CSS_PROVIDER_ERROR, GTK_CSS_PROVIDER_ERROR_DEPRECATED))
    tag_name = "warning";
  else
    tag_name = "error";

  gtk_text_buffer_apply_tag_by_name (buffer, tag_name, &start, &end);
}

static void
css_text_changed (GtkTextBuffer  *buffer,
                  GtkCssProvider *provider)
{
  GtkTextIter start, end;
  char *text;

  gtk_text_buffer_get_start_iter (buffer, &start);
  gtk_text_buffer_get_end_iter (buffer, &end);
  gtk_text_buffer_remove_all_tags (buffer, &start, &end);

  text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
  gtk_css_provider_load_from_data (provider, text, -1, NULL);
  g_free (text);

  gtk_style_context_reset_widgets (gdk_screen_get_default ());
}

static void
apply_css (GtkWidget *widget, GtkStyleProvider *provider)
{
  gtk_style_context_add_provider (gtk_widget_get_style_context (widget), provider, G_MAXUINT);
  if (GTK_IS_CONTAINER (widget))
    gtk_container_forall (GTK_CONTAINER (widget), (GtkCallback) apply_css, provider);
}

GtkWidget *
create_toolbar (void)
{
  GtkWidget *toolbar;
  GtkToolItem *item;

  toolbar = gtk_toolbar_new ();
  gtk_widget_set_valign (toolbar, GTK_ALIGN_CENTER);

  item = gtk_tool_button_new_from_stock (GTK_STOCK_GO_FORWARD);
  gtk_toolbar_insert (GTK_TOOLBAR (toolbar), item, -1);

  item = gtk_tool_button_new_from_stock (GTK_STOCK_GO_BACK);
  gtk_toolbar_insert (GTK_TOOLBAR (toolbar), item, -1);

  item = gtk_tool_button_new (NULL, "Hello World");
  gtk_tool_item_set_is_important (item, TRUE);
  gtk_toolbar_insert (GTK_TOOLBAR (toolbar), item, -1);

  return toolbar;
}

GtkWidget *
do_css_shadows (GtkWidget *do_widget)
{
  if (!window)
    {
      GtkWidget *paned, *container, *child;
      GtkStyleProvider *provider;
      GtkTextBuffer *text;
      GBytes *bytes;

      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
      gtk_window_set_transient_for (GTK_WINDOW (window), GTK_WINDOW (do_widget));
      gtk_window_set_default_size (GTK_WINDOW (window), 400, 300);
      g_signal_connect (window, "destroy",
                        G_CALLBACK (gtk_widget_destroyed), &window);

      paned = gtk_paned_new (GTK_ORIENTATION_VERTICAL);
      gtk_container_add (GTK_CONTAINER (window), paned);

      child = create_toolbar ();
      gtk_container_add (GTK_CONTAINER (paned), child);

      text = gtk_text_buffer_new (NULL);
      gtk_text_buffer_create_tag (text,
                                  "warning",
                                  "underline", PANGO_UNDERLINE_SINGLE,
                                  NULL);
      gtk_text_buffer_create_tag (text,
                                  "error",
                                  "underline", PANGO_UNDERLINE_ERROR,
                                  NULL);

      provider = GTK_STYLE_PROVIDER (gtk_css_provider_new ());

      container = gtk_scrolled_window_new (NULL, NULL);
      gtk_container_add (GTK_CONTAINER (paned), container);
      child = gtk_text_view_new_with_buffer (text);
      gtk_container_add (GTK_CONTAINER (container), child);
      g_signal_connect (text,
                        "changed",
                        G_CALLBACK (css_text_changed),
                        provider);

      bytes = g_resources_lookup_data ("/css_shadows/gtk.css", 0, NULL);
      gtk_text_buffer_set_text (text, g_bytes_get_data (bytes, NULL), g_bytes_get_size (bytes));

      g_signal_connect (provider,
                        "parsing-error",
                        G_CALLBACK (show_parsing_error),
                        gtk_text_view_get_buffer (GTK_TEXT_VIEW (child)));

      apply_css (window, provider);
    }

  if (!gtk_widget_get_visible (window))
    gtk_widget_show_all (window);
  else
    {
      gtk_widget_destroy (window);
      window = NULL;
    }

  return window;
}


text:
TypeError: Cannot destructure property `readFile` of 'undefined' or 'null'.
    at Object.<anonymous> (/Users/peterjang/.nvm/versions/node/v8.16.0/lib/node_modules/minify/lib/minify.js:5:33)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at uglifyFiles (/Users/peterjang/.nvm/versions/node/v8.16.0/lib/node_modules/minify/bin/minify.js:77:20)
    at minify (/Users/peterjang/.nvm/versions/node/v8.16.0/lib/node_modules/minify/bin/minify.js:56:5)


text:
if [ ! -d "$HOME/.yadr" ]; then
    if [[ "$OSTYPE" == "linux-gnu" ]]; then
      if [ -n "$(command -v yum)" ]; then
        sudo yum remove the-silver-searcher
        sudo yum install -y zsh git curl rake vim ctags tmux the_silver_searcher jq fontconfig
        if [ -n "$(command -v dnf)" ]; then
          sudo dnf install git-delta
        fi
      elif [ -n "$(command -v apt-get)" ]; then
        sudo apt-get install -y zsh git curl rake vim exuberant-ctags tmux silversearcher-ag jq fontconfig #gpg gawk dirmngr
        if [ -n "$(command -v dpkg)" ]; then
          wget https://github.com/dandavison/delta/releases/download/0.12.1/git-delta_0.12.1_amd64.deb -O git-delta.deb
          sudo dpkg -i git-delta.deb
        fi
      else
        echo "Unsupported PKG Manger, you need install: zsh git curl vim exuberant-ctags tmux the_silver_searcher/silversearcher-ag jq fontconfig"
      fi
      git clone https://github.com/asdf-vm/asdf.git ~/.asdf

    elif [[ "$OSTYPE" == "darwin"* ]]; then
        echo "Will install dependencies via Homebrew"
    else
        echo "Unsupported OS: $OSTYPE"
        exit
    fi
    echo "Installing YADR for the first time."
    git clone --depth=1 https://github.com/qianthinking/dotfiles.git "$HOME/.yadr"
    GIT_COMP_VERSION=`git --version | awk '{print $3"\n1.7.11"}' | sort -n | head -n 1`
    echo "git version `git --version`, and $GIT_COMP_VERSION"
    if [[ "$GIT_COMP_VERSION" != "1.7.11" ]]; then
      echo "Set git push.default to matching"
      sed -i 's/upstream/matching/' ~/.yadr/git/gitconfig
    fi
    if [[ "$OSTYPE" == "linux-gnu" ]]; then
      sed -i 's/\(^.*reattach\)/#\1/' ~/.yadr/tmux/tmux.conf
    fi
    cd "$HOME/.yadr"
    [ "$1" = "ask" ] && export ASK="true"
    rake install
else
    echo "YADR is already installed"
fi


text:
package ch.ifocusit.telecom.domain.access;

import ch.ifocusit.livingdoc.annotations.UbiquitousLanguage;
import lombok.Data;

import java.time.Duration;

/**
 * Phone call type access.
 */
@UbiquitousLanguage(id = 500)
@Data
public class CallAccess extends Access {

    /**
     * Phone call duration
     */
    @UbiquitousLanguage(id = 501)
    private Duration duration;
}


text:
package com.github.abel533.echarts.samples.line;

import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Symbol;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.data.LineData;
import com.github.abel533.echarts.json.GsonUtil;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.util.EnhancedOption;
import org.junit.Test;

/**
 * Created by liuzh on 14-8-26.
 */
public class LineTest {

    @Test
    public void test() {
        //例子:http://echarts.baidu.com/doc/example/line.html
        EnhancedOption option = new EnhancedOption();
        option.tooltip().trigger(Trigger.axis);
        option.legend("邮件营销", "联盟广告", "直接访问", "搜索引擎");
        option.toolbox().show(true);
        option.calculable(true);
        option.xAxis(new CategoryAxis().boundaryGap(false).data("周一", "周二", "周三", "周四", "周五", "周六", "周日"));
        option.yAxis(new ValueAxis());
        option.series(new Line().smooth(true).name("邮件营销").stack("总量").symbol(Symbol.none).data(120, 132, 301, 134, new LineData(90, Symbol.droplet, 5), 230, 210));

        //实现不了js的这个效果
        //line.itemStyle.normal.areaStyle = new AreaStyle();
        LineData lineData = new LineData(201, Symbol.star, 15);
        lineData.itemStyle().normal().label().show(true).textStyle().fontSize(20).fontFamily("微软雅黑").fontWeight("bold");
        option.series(new Line().smooth(true).name("联盟广告").stack("总量").symbol("image://http://echarts.baidu.com/doc/asset/ico/favicon.png").symbolSize(8).data(120, 82, lineData, new LineData(134, Symbol.none), 190, new LineData(230, Symbol.emptypin, 8), 110));

       /* line = new Line();
        line.name = "邮件营销";
        line.stack = "总量";
        line.symbol = Symbol.none;
        line.smooth = true;
        //实现不了js的这个效果
        //line.itemStyle.normal.areaStyle = new AreaStyle();
        line.addData(120, 132, 301, 134,new LineData(90,Symbol.droplet,5),230,210);
        option.series.add(line);

        line = new Line();
        line.name = "邮件营销";
        line.stack = "总量";
        line.symbol = Symbol.none;
        line.smooth = true;
        //实现不了js的这个效果
        //line.itemStyle.normal.areaStyle = new AreaStyle();
        line.addData(120, 132, 301, 134,new LineData(90,Symbol.droplet,5),230,210);
        option.series.add(line);*/
        System.out.println(GsonUtil.prettyFormat(option));
        option.exportToHtml("line.html");
        option.view();
    }
}


text:
JSIL.MakeClass("System.Reflection.TypeInfo", "System.RuntimeType", false, [], function ($) {
  $jsilcore.RuntimeTypeInitialized = true;
});


text:
<?php

namespace Google\Service;

use Google\Client;

/**
 * Service definition for HomeGraphService (v1).
 *
 *

 *
 *

 * For more information about this service, see the API
 * Documentation
 *

 *
 * @author Google, Inc.
 */
class HomeGraphService extends \Google\Service
{
  /** Private Service: https://www.googleapis.com/auth/homegraph. */
  const HOMEGRAPH =
      "https://www.googleapis.com/auth/homegraph";

  public $agentUsers;
  public $devices;

  /**
   * Constructs the internal representation of the HomeGraphService service.
   *
   * @param Client|array $clientOrConfig The client used to deliver requests, or a
   *                                     config array to pass to a new Client instance.
   * @param string $rootUrl The root URL used for requests to the service.
   */
  public function __construct($clientOrConfig = [], $rootUrl = null)
  {
    parent::__construct($clientOrConfig);
    $this->rootUrl = $rootUrl ?: 'https://homegraph.googleapis.com/';
    $this->servicePath = '';
    $this->batchPath = 'batch';
    $this->version = 'v1';
    $this->serviceName = 'homegraph';

    $this->agentUsers = new HomeGraphService\Resource\AgentUsers(
        $this,
        $this->serviceName,
        'agentUsers',
        [
          'methods' => [
            'delete' => [
              'path' => 'v1/{+agentUserId}',
              'httpMethod' => 'DELETE',
              'parameters' => [
                'agentUserId' => [
                  'location' => 'path',
                  'type' => 'string',
                  'required' => true,
                ],
                'requestId' => [
                  'location' => 'query',
                  'type' => 'string',
                ],
              ],
            ],
          ]
        ]
    );
    $this->devices = new HomeGraphService\Resource\Devices(
        $this,
        $this->serviceName,
        'devices',
        [
          'methods' => [
            'query' => [
              'path' => 'v1/devices:query',
              'httpMethod' => 'POST',
              'parameters' => [],
            ],'reportStateAndNotification' => [
              'path' => 'v1/devices:reportStateAndNotification',
              'httpMethod' => 'POST',
              'parameters' => [],
            ],'requestSync' => [
              'path' => 'v1/devices:requestSync',
              'httpMethod' => 'POST',
              'parameters' => [],
            ],'sync' => [
              'path' => 'v1/devices:sync',
              'httpMethod' => 'POST',
              'parameters' => [],
            ],
          ]
        ]
    );
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(HomeGraphService::class, 'Google_Service_HomeGraphService');


text:
/** @file
 * Private include file
 *
 * This file is for inclusion from _within_ the library only.
 */

#ifndef _AUBIO__PRIV_H
#define _AUBIO__PRIV_H

/*********************
 *
 * External includes
 *
 */

#if 1 //HAVE_CONFIG_H
#include "config.h"
#endif

#if HAVE_STDLIB_H
#include <stdlib.h>
#endif

#if HAVE_STDIO_H
#include <stdio.h>
#endif

/* must be included before fftw3.h */
#if HAVE_COMPLEX_H
#include <complex.h>
#endif

#if HAVE_FFTW3 || HAVE_FFTW3F
#include <fftw3.h>
#endif

#if HAVE_MATH_H
#include <math.h>
#endif

#if HAVE_STRING_H
#include <string.h>
#endif

#if HAVE_LIMITS_H
#include <limits.h> // for CHAR_BIT, in C99 standard
#endif

#include "types.h"

#define AUBIO_UNSTABLE 1

#include "mathutils.h"

/****
 *
 * SYSTEM INTERFACE
 *
 */

/* Memory management */
#define AUBIO_MALLOC(_n)             malloc(_n)
#define AUBIO_REALLOC(_p,_n)         realloc(_p,_n)
#define AUBIO_NEW(_t)                (_t*)calloc(sizeof(_t), 1)
#define AUBIO_ARRAY(_t,_n)           (_t*)calloc((_n)*sizeof(_t), 1)
#define AUBIO_MEMCPY(_dst,_src,_n)   memcpy(_dst,_src,_n)
#define AUBIO_MEMSET(_dst,_src,_t)   memset(_dst,_src,_t)
#define AUBIO_FREE(_p)               free(_p)

/* file interface */
#define AUBIO_FOPEN(_f,_m)           fopen(_f,_m)
#define AUBIO_FCLOSE(_f)             fclose(_f)
#define AUBIO_FREAD(_p,_s,_n,_f)     fread(_p,_s,_n,_f)
#define AUBIO_FSEEK(_f,_n,_set)      fseek(_f,_n,_set)

/* strings */
#define AUBIO_STRLEN(_s)             strlen(_s)
#define AUBIO_STRCMP(_s,_t)          strcmp(_s,_t)
#define AUBIO_STRNCMP(_s,_t,_n)      strncmp(_s,_t,_n)
#define AUBIO_STRCPY(_dst,_src)      strcpy(_dst,_src)
#define AUBIO_STRCHR(_s,_c)          strchr(_s,_c)
#ifdef strdup
#define AUBIO_STRDUP(s)              strdup(s)
#else
#define AUBIO_STRDUP(s)              AUBIO_STRCPY(AUBIO_MALLOC(AUBIO_STRLEN(s) + 1), s)
#endif

/* Error reporting */
typedef enum {
  AUBIO_OK = 0,
  AUBIO_FAIL = 1
} aubio_status;

#ifdef HAVE_C99_VARARGS_MACROS
#define AUBIO_ERR(...)               fprintf(stderr, "AUBIO ERROR: " __VA_ARGS__)
#define AUBIO_MSG(...)               fprintf(stdout, __VA_ARGS__)
#define AUBIO_DBG(...)               fprintf(stderr, __VA_ARGS__)
#define AUBIO_WRN(...)               fprintf(stderr, "AUBIO WARNING: " __VA_ARGS__)
#else
#define AUBIO_ERR(format, args...)   fprintf(stderr, "AUBIO ERROR: " format , ##args)
#define AUBIO_MSG(format, args...)   fprintf(stdout, format , ##args)
#define AUBIO_DBG(format, args...)   fprintf(stderr, format , ##args)
#define AUBIO_WRN(format, args...)   fprintf(stderr, "AUBIO WARNING: " format, ##args)
#endif

#define AUBIO_ERROR   AUBIO_ERR

#define AUBIO_QUIT(_s)               exit(_s)
#define AUBIO_SPRINTF                sprintf

/* Libc shortcuts */
#define PI         (M_PI)
#define TWO_PI     (PI*2.)

/* aliases to math.h functions */
#if !HAVE_AUBIO_DOUBLE
#define EXP        expf
#define COS        cosf
#define SIN        sinf
#define ABS        fabsf
#define POW        powf
#define SQRT       sqrtf
#define LOG10      log10f
#define LOG        logf
#define FLOOR      floorf
#define CEIL       ceilf
#define ATAN2      atan2f
#else
#define EXP        exp
#define COS        cos
#define SIN        sin
#define ABS        fabs
#define POW        pow
#define SQRT       sqrt
#define LOG10      log10
#define LOG        log
#define FLOOR      floor
#define CEIL       ceil
#define ATAN2      atan2
#endif
#define ROUND(x)   FLOOR(x+.5)

/* aliases to complex.h functions */
#if HAVE_AUBIO_DOUBLE || !defined(HAVE_COMPLEX_H) || defined(WIN32)
/* mingw32 does not know about c*f functions */
#define EXPC      cexp
/** complex = CEXPC(complex) */
#define CEXPC     cexp
/** sample = ARGC(complex) */
#define ARGC      carg
/** sample = ABSC(complex) norm */
#define ABSC      cabs
/** sample = REAL(complex) */
#define REAL      creal
/** sample = IMAG(complex) */
#define IMAG      cimag
#else
/** sample = EXPC(complex) */
#define EXPC      cexpf
/** complex = CEXPC(complex) */
#define CEXPC     cexp
/** sample = ARGC(complex) */
#define ARGC      cargf
/** sample = ABSC(complex) norm */
#define ABSC      cabsf
/** sample = REAL(complex) */
#define REAL      crealf
/** sample = IMAG(complex) */
#define IMAG      cimagf
#endif

/* handy shortcuts */
#define DB2LIN(g) (POW(10.0,(g)*0.05f))
#define LIN2DB(v) (20.0*LOG10(v))
#define SQR(_a)   (_a*_a)

#define MAX(a,b)  ( a > b ? a : b)
#define MIN(a,b)  ( a < b ? a : b)

#define ELEM_SWAP(a,b) { register smpl_t t=(a);(a)=(b);(b)=t; }

#define VERY_SMALL_NUMBER 2.e-42 //1.e-37

/** if ABS(f) < VERY_SMALL_NUMBER, returns 1, else 0 */
#define IS_DENORMAL(f) ABS(f) < VERY_SMALL_NUMBER

/** if ABS(f) < VERY_SMALL_NUMBER, returns 0., else f */
#define KILL_DENORMAL(f)  IS_DENORMAL(f) ? 0. : f

/** if f > VERY_SMALL_NUMBER, returns f, else returns VERY_SMALL_NUMBER */
#define CEIL_DENORMAL(f)  f < VERY_SMALL_NUMBER ? VERY_SMALL_NUMBER : f

#define SAFE_LOG10(f) LOG10(CEIL_DENORMAL(f))
#define SAFE_LOG(f)   LOG(CEIL_DENORMAL(f))

#define UNUSED __attribute__((unused))

#endif /* _AUBIO__PRIV_H */


text:
#ifndef vcl_cerrno_h_
#define vcl_cerrno_h_
/*
  fsm
*/

#include "vcl_compiler.h"

#if !VCL_CXX_HAS_HEADER_CERRNO
# include <errno.h>
#else
# include "iso/vcl_cerrno.h"
#endif

#ifdef linux // bug fix: errno.h erroneously declares __errno_location() as C++
extern "C" inline int* __errno_location__Fv() { return __errno_location(); }
extern "C" inline int* _Z16__errno_locationv() { return __errno_location(); }
#endif

#endif // vcl_cerrno_h_


text:
import { setDayOfYear } from 'date-fns/fp'
export default setDayOfYear


text:
import datetime
import json
import logging
import os
import sys
import uuid

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.template.loader import render_to_string

from lib.py import belay

class FeedData(db.Model):
  title = db.StringProperty()
  name = db.StringProperty()
  location = db.StringProperty()
  client_preimg = db.StringProperty()

class SnapshotData(db.Model):
  snapshot = db.TextProperty()

class ItemData(db.Model):
  when = db.DateTimeProperty(auto_now_add=True);
  body = db.TextProperty(required=True);
  via = db.TextProperty();

  def nicedate(self):
    date = self.when
    today = datetime.datetime.now()
    date_ordinal = date.toordinal()
    today_ordinal = today.toordinal()
    format = ""
    if date_ordinal == today_ordinal:
      format = "today"
    elif date_ordinal == today_ordinal - 1:
      format = "yesterday"
    elif date_ordinal > today_ordinal - 7:
      format = '%a'
    elif date.year == today.year:
      format = '%a, %b %d'
    else:
      format = '%a, %b %d %Y'
    format += ' - %I:%M %p'
    return date.strftime(format)

class GenerateHandler(belay.BcapHandler):
  def post(self):
    feed = FeedData()
    feed.title = self.request.POST['title']
    feed.client_preimg = str(uuid.uuid4())
    feed.put()
    snapshot = SnapshotData(parent=feed)
    snapshot.put()

    response = {
      'launch': self.cap_server.regrant(LaunchHandler, feed),
      'icon': self.server_url("/tool-buzzer.png"),
      'name': feed.title
    }

    self.bcapResponse(response)

class GenerateReaderHandler(belay.CapHandler):
  def get(self):
    feed = self.get_entity()
    response = {
        'launch': self.cap_server.regrant(LaunchReaderHandler, feed),
        'name': 'buzz about ' + feed.title,
        'icon': self.server_url('/tool-buzzer.png')
    };
    self.bcapResponse(response)

class LaunchHandler(belay.CapHandler):
  def get(self):
    feed = self.get_entity()
    snapshot = SnapshotData.all().ancestor(feed).get()

    response = {
      'page': {
        'html': self.server_url('/buzzer-belay.html'),
        'window': { 'width': 300, 'height': 400 }
      },
      'gadget': {
        'html': self.cap_server.regrant(EditorViewHandler, feed).serialize(),
        'scripts': [ self.server_url("/buzzer.js") ]
      },
      'info': {
        'client_preimg': feed.client_preimg,
        'post_cap': self.cap_server.regrant(DataPostHandler, feed),
        'snapshot_cap': self.cap_server.regrant(SnapshotHandler, snapshot),
        'snapshot': snapshot.snapshot,
        'reader_gen_cap': self.cap_server.regrant(GenerateReaderHandler, feed),
        'editor_cap': self.cap_server.regrant(EditorViewHandler, feed),
        'readChitURL': self.server_url("/chit-24.png"),
        'postChitURL': self.server_url("/chit-25.png")
      },
      'attributes': {
        'set': self.cap_server.regrant(SetAttributesHandler, feed)
      }
    }

    self.bcapResponse(response)

class LaunchReaderHandler(belay.CapHandler):
  def get(self):
    feed = self.get_entity()

    response = {
      'page': {
        'html': self.server_url('/buzzer-belay.html'),
        'window': { 'width': 300, 'height': 400 }
      },
      'gadget': {
        'html': self.cap_server.regrant(ReaderViewHandler, feed).serialize(),
        'scripts': [ self.server_url("/buzzer.js") ]
      },
      'info': {
        'client_preimg': str(uuid.uuid4()),
        'editor_cap': self.cap_server.regrant(ReaderViewHandler, feed),
      }
    }

    self.bcapResponse(response)

class ViewHandler(belay.CapHandler):
  def get(self):
    feed = self.get_entity()
    need_profile = feed.title is None
    has_name = feed.name and feed.name != ''
    has_location = feed.location and feed.location != ''

    q = ItemData.all();
    q.ancestor(feed);
    q.order('-when');
    items = q.fetch(10);

    self.render_to_response('buzzer.tmpl',
      { 'css_url': self.server_url('/buzzer.css'),
        'chit_read_url': self.server_url('/chit-24.png'),
        'chit_post_url': self.server_url('/chit-25.png'),
        'post_url': self.cap_server.regrant(DataPostHandler, feed).serialize(),
        'profile_url': self.cap_server.regrant(DataProfileHandler, feed).serialize(),
        'include_post': self.include_post(),
        'need_profile': need_profile,
        'feed': feed,
        'items': items,
        'has_name': has_name,
        'has_location': has_location,
        'has_subtitle': has_name or has_location

      })

  def render_to_response(self, tmpl_filename, dictionary):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
    """Note that this is different than Django's similarly named function"""
    content = render_to_string(tmpl_filename, dictionary)
    # django is misguided here - it doesn't read the file as UTF-8
    self.xhr_content(content, "text/html;charset=UTF-8")

class EditorViewHandler(ViewHandler):
  def include_post(self):
    return True

class ReaderViewHandler(ViewHandler):
  def include_post(self):
    return False

class DataProfileHandler(belay.CapHandler):
  def post(self):
    feed = self.get_entity()

    request = self.bcapRequest()
    feed.title = request.get('title')
    feed.put()

    self.bcapNullResponse()

class DataPostHandler(belay.CapHandler):
  def post(self):
    feed = self.get_entity()

    request = self.bcapRequest()
    v = request.get('body', '')
    if not v:
      self.error(400, "Empty or missing posting body")
      return

    item = ItemData(parent=feed, body=request['body'])
    v = request.get('when', '')
    if v:
      item.when = v
    v = request.get('via', '')
    if v:
      item.via = v
    item.put()

    self.bcapNullResponse()

class SnapshotHandler(belay.CapHandler):
  def get(self):
    self.bcapResponse(self.get_entity().snapshot)

  def put(self):
    v = self.bcapRequest()
    snapshot = self.get_entity()
    snapshot.snapshot = v
    snapshot.put()
    self.bcapNullResponse()

class SetAttributesHandler(belay.CapHandler):
  def put(self):
    feed = self.get_entity()
    request = self.bcapRequest()

    feed.name = request.get('name', '')
    feed.location = request.get('location', '')
    feed.put()

    self.bcapNullResponse()

application = webapp.WSGIApplication(
  [(r'/cap/.*', belay.ProxyHandler),
  ('/generate', GenerateHandler),
  ],
  debug=True)

# Internal Cap Paths
belay.set_handlers(
  '/cap',
  [ ('/belay/launch', LaunchHandler),
    ('/belay/generateReader', GenerateReaderHandler),
    ('/belay/launchReader', LaunchReaderHandler),
    ('/view/editor', EditorViewHandler),
    ('/view/reader', ReaderViewHandler),
    ('/data/profile', DataProfileHandler),
    ('/data/post', DataPostHandler),
    ('/data/snapshot', SnapshotHandler),
    ('/data/attributes', SetAttributesHandler),
  ])


text:
package com.reactnativeamap;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import com.facebook.react.ReactActivity;

public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript.
   * This is used to schedule rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "ReactNativeAmap";
  }

}


text:
Srfax

This is the 'unofficial' SRFax (http://www.srfax.com) API wrapper for ruby.  The API documentation for SRFax can be found at https://www.srfax.com/srf/media/SRFax-REST-API-Documentation.pdf

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'sr_fax'
```

And then execute:

    $ bundle

Or install it yourself using:

    $ gem install sr_fax

## Usage

To get started, simply open the console view and require the SrFax module.  Once you have completed that, enter your account credentials using the SrFax setup block, and then begin to execute calls. All status' returned are simply formatted hashes from the SrFax service.

```ruby

require 'srfax'

SrFax.setup do |config|
  config.defaults[:access_id] = '1234'
  config.defaults[:access_pwd] = 'password'
  config.logger = Rails.logger
end

SrFax.view_inbox
SrFax.view_outbox
SrFax.update_fax_status(descriptor, direction)
SrFax.get_fax(descriptor, direction, {:sMarkasViewed => 'Y'}
```

As an example, here is a sample queue fax call to send a fax

```ruby
SrFax.queue_fax "yourname@yourdomain.com", "SINGLE", "18888888888", {sFileName_1: "file1.txt", sFileContent_1: Base64.encode64("Sample Fax")}
```

The SrFax module currently supports the following functions
  - Sending and receiving faxes
  - Updating flags on the inbox or outbox faxes
  - Deleting faxes from either the inbox or outbox
  - View account usage
  - Download faxes from the inbox or outbox

## Development

After checking out the repo, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/TechCanuck/srfax/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

Licensing: **MIT**
Remember: **'Great opportunities to help others seldom come, but small ones surround us daily' -- Sally Koch**


text:
outputDirectory = 'Engine/Assets/Shaders/Dusk/Debug/'

attributes = {
    'AttributeNormal':   'a_Normal',
    'AttributeTangent':  'a_Tangent',
    'AttributeColor':    'a_Color',
    'AttributeTexCoord1': 'vec4(a_TexCoord1, 0, 1)',
    'AttributeTexCoord2': 'vec4(a_TexCoord2, 0, 1)',
}

ATTRIBUTE_VERTEX = '''
#version 450 core

#include <Dusk/Transform.inc.glsl>
#include <Dusk/VertexAttributes.inc.glsl>

layout(location = 0) out vec4 v_Color;

void main() {
    gl_Position = u_MVP * a_Position;
    v_Color = %s;
}
'''

ATTRIBUTE_FRAGMENT = '''
#version 450 core

layout(location = 0) in vec4 v_Color;

layout(location = 0) out vec4 o_Color;

void main() {
    o_Color = v_Color;
}
'''

filename = outputDirectory + 'Attribute.frag.glsl'
with open(filename, 'wt') as file:
    file.write(ATTRIBUTE_FRAGMENT)

for filename, expr in attributes.items():
    filename = outputDirectory + filename + '.vert.glsl'
    with open(filename, 'wt') as file:
        file.write(ATTRIBUTE_VERTEX % (expr,))

materials = {
    'MaterialBaseColorFactor':      'u_BaseColorFactor',
    'MaterialBaseColorMap':         'texture(u_BaseColorMap, v_TexCoord)',
    'MaterialBaseColor':            'texture(u_BaseColorMap, v_TexCoord) * u_BaseColorFactor',
    'MaterialNormalScale':          'vec4(vec3(u_NormalScale), 1)',
    'MaterialNormalMap':            'vec4(texture(u_NormalMap, v_TexCoord).rgb, 1)',
    'MaterialNormal':               'vec4(texture(u_NormalMap, v_TexCoord).rgb * u_NormalScale, 1)',
    'MaterialMetallicFactor':       'vec4(vec3(u_MetallicFactor), 1)',
    'MaterialMetallicMap':          'vec4(vec3(texture(u_MetallicRoughnessMap, v_TexCoord).b), 1)',
    'MaterialMetallic':             'vec4(vec3(texture(u_MetallicRoughnessMap, v_TexCoord).b * u_MetallicFactor), 1)',
    'MaterialRoughnessFactor':      'vec4(vec3(u_RoughnessFactor), 1)',
    'MaterialRoughnessMap':         'vec4(vec3(texture(u_MetallicRoughnessMap, v_TexCoord).g), 1)',
    'MaterialRoughness':            'vec4(vec3(texture(u_MetallicRoughnessMap, v_TexCoord).g * u_RoughnessFactor), 1)',
    'MaterialEmissiveFactor':       'vec4(u_EmissiveFactor, 1)',
    'MaterialEmissiveMap':          'vec4(texture(u_EmissiveMap, v_TexCoord).rgb, 1)',
    'MaterialEmissive':             'vec4(texture(u_EmissiveMap, v_TexCoord).rgb * u_EmissiveFactor, 1)',
    'MaterialOcclusionStrength':    'vec4(vec3(u_OcclusionStrength), 1)',
    'MaterialOcclusionMap':         'vec4(vec3(texture(u_OcclusionMap, v_TexCoord).r), 1)',
    'MaterialOcclusion':            'vec4(vec3(texture(u_OcclusionMap, v_TexCoord).r) * u_OcclusionStrength, 1)',
}

MATERIAL_VERTEX = '''
#version 450 core

#include <Dusk/Transform.inc.glsl>
#include <Dusk/VertexAttributes.inc.glsl>

layout(location = 0) out vec2 v_TexCoord;

void main() {
    gl_Position = u_MVP * a_Position;
    v_TexCoord = a_TexCoord1;
}
'''

MATERIAL_FRAGMENT = '''
#version 450 core

#include <Dusk/Material.inc.glsl>
#include <Dusk/ColorSpace.inc.glsl>

layout(location = 0) in vec2 v_TexCoord;

layout(location = 0) out vec4 o_Color;

void main()
{
    o_Color = %s;
}
'''

filename = outputDirectory + 'Material.vert.glsl'
with open(filename, 'wt') as file:
    file.write(MATERIAL_VERTEX)

for filename, expr in materials.items():
    filename = outputDirectory + filename + '.frag.glsl'
    with open(filename, 'wt') as file:
        file.write(MATERIAL_FRAGMENT % (expr,))


text:
package com.jpeterson.util.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class RangeTest extends TestCase {
	private Log logger;

	/**
	 * Create the test case
	 *
	 * @param testName
	 *            name of the test case
	 */
	public RangeTest(String testName) {
		super(testName);

		logger = LogFactory.getLog(this.getClass());
		logger.debug("RangeTest");
	}

	/**
	 * @return the suite of tests being tested
	 */
	public static Test suite() {
		return new TestSuite(RangeTest.class);
	}

	/**
	 * Test the setStart() and getStart() methods.
	 */
	public void test_start() {
		Range range = new Range();

		range.setStart(1);

		assertEquals("Unexpected start", 1, range.getStart());
	}

	/**
	 * Test the setEnd() and getEnd() methods.
	 */
	public void test_end() {
		Range range = new Range();

		range.setEnd(4);

		assertEquals("Unexpected start", 4, range.getEnd());
	}

	/**
	 * Test the constructor that takes a start and
	 * end value.
	 */
	public void test_constructorWithStartAndEnd() {
		Range range;

		range = new Range(3, 9);
		assertEquals("Unexpected start", 3, range.getStart());
		assertEquals("Unexpected end", 9, range.getEnd());
	}

	/**
	 * Test the resolve() method.
	 */
	public void test_resolve() {
		Range range;

		// 'open-ended' range
		range = new Range(5);

		assertEquals("Unexpected start", 5, range.getStart());
		assertEquals("Unexpected end", Range.OPEN_ENDED, range.getEnd());

		range.resolve(10);

		assertEquals("Unexpected start", 5, range.getStart());
		assertEquals("Unexpected end", 9, range.getEnd());

		// suffix range
		range = new Range(-10);

		assertEquals("Unexpected start", -10, range.getStart());
		assertEquals("Unexpected end", Range.OPEN_ENDED, range.getEnd());

		range.resolve(100);

		assertEquals("Unexpected start", 90, range.getStart());
		assertEquals("Unexpected end", 99, range.getEnd());

		// already resolved
		range = new Range(2, 4);

		assertEquals("Unexpected start", 2, range.getStart());
		assertEquals("Unexpected end", 4, range.getEnd());

		range.resolve(100);

		assertEquals("Unexpected start", 2, range.getStart());
		assertEquals("Unexpected end", 4, range.getEnd());
	}

	/**
	 * Test the resolve that results in the range being "squeezed".
	 */
	public void test_resolveSqueeze() {
		Range range;

		range = new Range(5, 20);
		range.resolve(10);

		assertEquals("Should have been squeezed", new Range(5, 9), range);
	}

	/**
	 * Test resolving a range that is outside of the absolute length. Should
	 * throw an exception.
	 */
	public void test_resolveIllegalState() {
		Range range;

		range = new Range(20, 30);

		try {
			range.resolve(10);
			fail("Should have thrown an exception");
		} catch (IllegalStateException e) {
			// expected
		}
	}

	/**
	 * Test the getLength() method.
	 */
	public void test_getLength() {
		Range range;

		// 'open-ended' range
		range = new Range(5);

		assertEquals("Unexpected length", -1, range.getLength());

		// suffix range
		range = new Range(-10);

		assertEquals("Unexpected length", -1, range.getLength());

		// already resolved
		range = new Range(2, 4);

		assertEquals("Unexpected length", 3, range.getLength());
	}

	/**
	 * Test the inclues() method.
	 */
	public void test_includes() {
		Range range;

		range = new Range();
		range.setStart(2);
		range.setEnd(4);
		assertFalse("Unexpected value", range.includes(0));
		assertFalse("Unexpected value", range.includes(1));
		assertTrue("Unexpected value", range.includes(2));
		assertTrue("Unexpected value", range.includes(3));
		assertTrue("Unexpected value", range.includes(4));
		assertFalse("Unexpected value", range.includes(5));
		assertFalse("Unexpected value", range.includes(6));

		range = new Range();
		range.setStart(3);
		range.setEnd(3);
		assertFalse("Unexpected value", range.includes(0));
		assertFalse("Unexpected value", range.includes(1));
		assertFalse("Unexpected value", range.includes(2));
		assertTrue("Unexpected value", range.includes(3));
		assertFalse("Unexpected value", range.includes(4));
		assertFalse("Unexpected value", range.includes(5));
		assertFalse("Unexpected value", range.includes(6));
	}

	/**
	 * Test the combinable() method.
	 */
	public void test_combinable() {
		Range r1, r2, r3, r4, r5, r6;

		r1 = new Range();
		r1.setStart(5);
		r1.setEnd(10);

		r2 = new Range();
		r2.setStart(4);
		r2.setEnd(8);

		r3 = new Range();
		r3.setStart(10);
		r3.setEnd(12);

		r4 = new Range();
		r4.setStart(1);
		r4.setEnd(3);

		assertTrue(r1.combinable(r2));
		assertTrue(r1.combinable(r3));
		assertFalse(r1.combinable(r4));

		r5 = new Range(0, 0);
		r6 = new Range(4, 8);

		assertTrue(r4.combinable(r5));
		assertTrue(r4.combinable(r6));
	}

	/**
	 * Test the equals() method.
	 */
	public void test_equals() {
		Range r1, r2, r3, r4, r5;

		r1 = new Range();
		r1.setStart(1);
		r1.setEnd(10);

		r2 = new Range();
		r2.setStart(1);
		r2.setEnd(10);

		r3 = new Range();
		r3.setStart(2);
		r3.setEnd(10);

		r4 = new Range();
		r4.setStart(1);
		r4.setEnd(9);

		r5 = new Range();
		r5.setStart(0);
		r5.setEnd(11);

		assertTrue(r1.equals(r1));
		assertTrue(r1.equals(r2));
		assertTrue(r2.equals(r1));
		assertFalse(r1.equals(null));
		assertFalse(r1.equals("foo"));
		assertFalse(r1.equals(r3));
		assertFalse(r1.equals(r4));
		assertFalse(r1.equals(r5));
	}

	/**
	 * Test the hashCode method.
	 */
	public void test_hashCode() {
		Range r1, r2;

		r1 = new Range();
		r1.setStart(1);
		r1.setEnd(10);

		r2 = new Range();
		r2.setStart(1);
		r2.setEnd(10);

		assertEquals(r1.hashCode(), r1.hashCode());
		assertEquals(r1.hashCode(), r2.hashCode());
	}
}


text:
import numpy as np

from ._trace_object_boundaries_cython import _trace_object_boundaries_cython

def trace_object_boundaries(im_label,
                            conn=4, trace_all=False,
                            x_start=None, y_start=None,
                            max_length=None,
                            simplify_colinear_spurs=True,
                            eps_colinear_area=0.01):
    """Performs exterior boundary tracing of one or more objects in a label
    mask. If a starting point is not provided then a raster scan will be performed
    to identify the starting pixel.

    Parameters
    ----------
    im_label : array_like
        A binary mask image.
    conn : int
        Neighborhood connectivity to evaluate. Valid values are 4 or 8.
        Default value = 4.
    trace_all : bool
        Specify True if you want to trace boundaries of all objects.
        Default = False
    x_start : int
        Starting horizontal coordinate to begin tracing. Default value = None.
    y_start : int
        Starting vertical coordinate to begin tracing. Default value = None.
    max_length : int
        Maximum boundary length to trace before terminating. Default value =
        None.
    simplify_colinear_spurs : bool
        If True colinear streaks/spurs in the object boundary will be
        simplified/removed. Note that if the object boundary is entirely
        colinear then the object itself will be removed. Default = True
    eps_colinear_area : int
        Minimum area of triangle formed by three consecutive points on the
        contour for them to be considered as non-colinear. Default value =
        0.01.

    Notes
    -----
    The Improved Simple Boundary Follower (ISBF) from the reference below is
    used for 4-connected tracing. This algorithm provides accurate tracing with
    competitive execution times. 8-connected tracing is implemented using the
    Moore tracing algorithm.

    Returns
    -------
    X : array_like
        A set of 1D array of horizontal coordinates of contour seed pixels for
        tracing.
    Y : array_like
        A set of 1D array of the vertical coordinates of seed pixels for
        tracing.

    References
    ----------
    .. [#] J. Seo et al "Fast Contour-Tracing Algorithm Based on a Pixel-
       Following Method for Image Sensors" in Sensors,vol.16,no.353,
       doi:10.3390/s16030353, 2016.

    """
    from skimage.measure import regionprops

    if max_length is None:
        max_length = float('inf')

    X = []
    Y = []

    if trace_all:

        rprops = regionprops(im_label)
        numLabels = len(rprops)

        x_start = -1
        y_start = -1

        for i in range(numLabels):

            # get bounds of label mask
            min_row, min_col, max_row, max_col = rprops[i].bbox

            # grab label mask
            lmask = (
                im_label[
                    min_row:max_row, min_col:max_col
                ] == rprops[i].label
            ).astype(np.bool)

            mrows = max_row - min_row + 2
            mcols = max_col - min_col + 2

            mask = np.zeros((mrows, mcols))
            mask[1:mrows-1, 1:mcols-1] = lmask

            by, bx = _trace_object_boundaries_cython(
                np.ascontiguousarray(
                    mask, dtype=np.int), conn, x_start, y_start, max_length
            )

            bx = bx + min_row - 1
            by = by + min_col - 1

            if simplify_colinear_spurs:
                bx, by = _remove_thin_colinear_spurs(bx, by,
                                                     eps_colinear_area)

            if len(bx) > 0:
                X.append(bx)
                Y.append(by)

    else:

        rprops = regionprops(im_label.astype(int))
        numLabels = len(rprops)

        if numLabels > 1:
            raise ValueError("Number of labels should be 1 !!")

        if (x_start is None and y_start is not None) | \
                (x_start is not None and y_start is None):
            raise ValueError("x_start or y_start is not defined !!")

        if x_start is None and y_start is None:
            x_start = -1
            y_start = -1

        by, bx = _trace_object_boundaries_cython(
            np.ascontiguousarray(
                im_label, dtype=np.int), conn, x_start, y_start, max_length
        )

        if simplify_colinear_spurs:
            bx, by = _remove_thin_colinear_spurs(bx, by,
                                                 eps_colinear_area)

        if len(bx) > 0:
            X.append(bx)
            Y.append(by)

    return X, Y

def _remove_thin_colinear_spurs(px, py, eps_colinear_area=0):
    """Simplifies the given list of points by removing colinear spurs
    """

    keep = []  # indices of points to keep

    anchor = -1
    testpos = 0

    while testpos < len(px):

        # get coords of next triplet of points to test
        if testpos == len(px) - 1:
            if not keep:
                break
            nextpos = keep[0]
        else:
            nextpos = testpos + 1

        ind = [anchor, testpos, nextpos]
        x1, x2, x3 = px[ind]
        y1, y2, y3 = py[ind]

        # compute area of triangle formed by triplet
        area = 0.5 * np.linalg.det(
            np.array([[x1, x2, x3], [y1, y2, y3], [1, 1, 1]])
        )

        # if area > cutoff, add testpos to keep and move anchor to testpos
        if abs(area) > eps_colinear_area:

            keep.append(testpos)  # add testpos to keep list
            anchor = testpos      # make testpos the next anchor point
            testpos += 1

        else:

            testpos += 1

    px = px[keep]
    py = py[keep]

    return px, py


text:
<!DOCTYPE html >

          <title>CellSetModelFormat - nablepjt.models.hbase.HBaseModelReadWrite.CellSetModelFormat</title>
          <meta name="description" content="CellSetModelFormat - nablepjt.models.hbase.HBaseModelReadWrite.CellSetModelFormat" />
          <meta name="keywords" content="CellSetModelFormat nablepjt.models.hbase.HBaseModelReadWrite.CellSetModelFormat" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

nablepjt.models.hbase.HBaseModelReadWrite

CellSetModelFormat

        implicit
        object

        CellSetModelFormat extends Format[CellSetModel]

Deprecated

          Linear Supertypes

Format[CellSetModel], Reads[CellSetModel], Writes[CellSetModel], AnyRef, Any

<input id="mbrsel-input" type="text" accesskey="/" />

              Ordering

Alphabetic

By inheritance

                Inherited

CellSetModelFormat

Format

Reads

Writes

AnyRef

Any

Hide All

Show all

            Learn more about member selection

            Visibility

Public

All

Value Members

        final
        def

        !=(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        final
        def

        ##(): Int

Definition Classes

AnyRef → Any

        final
        def

        ==(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        andThen[B](rb: Reads[B])(implicit witness: <:<[CellSetModel, JsValue]): Reads[B]

Definition Classes

Reads

        final
        def

        asInstanceOf[T0]: T0

Definition Classes

Any

        def

        clone(): AnyRef

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        def

        collect[B](error: ValidationError)(f: PartialFunction[CellSetModel, B]): Reads[B]

Definition Classes

Reads

        def

        compose[B <: JsValue](rb: Reads[B]): Reads[CellSetModel]

Definition Classes

Reads

        final
        def

        eq(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        def

        equals(arg0: Any): Boolean

Definition Classes

AnyRef → Any

        def

        filter(error: ValidationError)(f: (CellSetModel) ⇒ Boolean): Reads[CellSetModel]

Definition Classes

Reads

        def

        filter(f: (CellSetModel) ⇒ Boolean): Reads[CellSetModel]

Definition Classes

Reads

        def

        filterNot(error: ValidationError)(f: (CellSetModel) ⇒ Boolean): Reads[CellSetModel]

Definition Classes

Reads

        def

        filterNot(f: (CellSetModel) ⇒ Boolean): Reads[CellSetModel]

Definition Classes

Reads

        def

        finalize(): Unit

Attributes

protected[java.lang]

Definition Classes

AnyRef

Annotations

                @throws(

      classOf[java.lang.Throwable]
    )

        def

        flatMap[B](f: (CellSetModel) ⇒ Reads[B]): Reads[B]

Definition Classes

Reads

        final
        def

        getClass(): Class[_]

Definition Classes

AnyRef → Any

        def

        hashCode(): Int

Definition Classes

AnyRef → Any

        final
        def

        isInstanceOf[T0]: Boolean

Definition Classes

Any

        def

        map[B](f: (CellSetModel) ⇒ B): Reads[B]

Definition Classes

Reads

        final
        def

        ne(arg0: AnyRef): Boolean

Definition Classes

AnyRef

        final
        def

        notify(): Unit

Definition Classes

AnyRef

        final
        def

        notifyAll(): Unit

Definition Classes

AnyRef

        def

        orElse(v: Reads[CellSetModel]): Reads[CellSetModel]

Definition Classes

Reads

        def

        reads(json: JsValue): JsResult[CellSetModel]

Definition Classes

CellSetModelFormat → Reads

        final
        def

        synchronized[T0](arg0: ⇒ T0): T0

Definition Classes

AnyRef

        def

        toString(): String

Definition Classes

AnyRef → Any

        def

        transform(transformer: Writes[JsValue]): Writes[CellSetModel]

Definition Classes

Writes

        def

        transform(transformer: (JsValue) ⇒ JsValue): Writes[CellSetModel]

Definition Classes

Writes

        final
        def

        wait(): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long, arg1: Int): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        final
        def

        wait(arg0: Long): Unit

Definition Classes

AnyRef

Annotations

                @throws(

      ...
    )

        def

        writes(o: CellSetModel): JsValue

Definition Classes

CellSetModelFormat → Writes

Inherited from Format[CellSetModel]

Inherited from Reads[CellSetModel]

Inherited from Writes[CellSetModel]

Inherited from AnyRef

Inherited from Any

Ungrouped


text: CKEDITOR.plugins.setLang("showblocks","id",{toolbar:"Perlihatkan Blok"});


text:
/**
 * HTML5的上传处理类
 * @param {Object} options 配置
 */
function Html5Uploader (options) {

    var self   = this,

        /**
         * 上传文件对象
         * @type {Object}
         */
        _file  = null,

        /**
         * Uploader状态
         * @type {Number}
         */
        status = 0,

        /**
         * XMLHttpRequest
         * @type {XMLHttpRequest}
         */
        xhr    = null,

        /**
         * 文件信息
         * @type {Object}
         */
        info   = {
            name: null,
            size: null,
            time: null,
            start: null,
            end: null,
            token: null
        };

    /**
     * 配置信息
     * @type {Object}
     */
    this.options = options;

    /**
     * 设置文件 相当于初始化
     * @param {File} file 上传文件
     */
    this.setFile = function(file) {

        self.abort();
        status = 0;
        _file  = file;
        info   = {
            name: _file.name,
            size: _file.size,
            time: Math.ceil(_file.lastModifiedDate.getTime() / 1000),
            start: null,
            end: null,
            token: null
        };
    }

    /**
     * 获取文件对象
     * @return {File|Bool} 文件信息
     */
    this.getFile = function() {

        if(_file === null || !(_file instanceof File)) {
            self.emit('error', ['', 301]);
            return false;
        } else return _file;
    }

    /**
     * 设置文件信息
     * @param {String} name 键
     * @param {String|Number} val 值
     */
    this.setInfo = function(name, val) {
        info[name] = val;
    }

    /**
     * 获取文件信息
     * @param  {String} name 所需键
     * @return {String|Number} 返回值
     */
    this.getInfo = function(name) {
        if(typeof name === 'undefined') return info;
        else return info[name];
    }

    /**
     * 设置XMLHttpRequest对象
     * @param {XMLHttpRequest} x
     */
    this.setXHR = function(x) {
        xhr = x;
    }

    /**
     * 获取XMLHttpRequest对象
     * @return {XMLHttpRequest}
     */
    this.getXHR = function() {
        return xhr;
    }

    /**
     * 获取状态
     * @return {Number} 状态值
     */
    this.getStatus = function() {
        return +status;
    }

    this.getTokenInfo = function() {

        if(self.getInfo('name') === null) {
            self.emit('error', ['', 301]);
            return false;
        }

        var data = {
            name: self.getInfo('name'),
            size: self.getInfo('size'),
            time: self.getInfo('time')
        };

        $.ajax({
            url: self.options.tokenUrl,
            type: 'GET',
            data: data,
            dataType: 'json',
            cache: false
        }).fail(function(jqXHR, textStatus, errorThrown) {
            self.emit('error', ['', 201]);
        }).done(function(data, textStatus, jqXHR) {
            self.emit('fetchTokenComplete', [data]);
        });
    }

    this.upload = function() {

        var token = self.getInfo('token'),
            file  = self.getFile();

        if($.trim(token) === '') {
            self.emit('error', ['', 201]);
            return false;
        }

        var xhr = $.ajaxSettings.xhr();

        $(xhr.upload).bind('progress', function(e) {
            self.emit('progress', [e.originalEvent.loaded, +self.getInfo('size')]);
        });

        var param = $.param({
            token: token,
            start: 0,
            end: self.getInfo('size')
        });

        self.setXHR(xhr);

        $.ajax({
            url: [self.options.uploadUrl, param].join('?'),
            type: 'POST',
            dataType: 'json',
            data: file,
            processData: false,
            contentType: file.type,
            xhr: function() {
                return xhr;
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            self.emit('error', ['', 201]);
        }).done(function(data, textStatus, jqXHR) {
            self.emit('complete', [self.getInfo('token')]);
        });

        file = undefined;

    }

    this.multiChunkUpload = function() {

        if(self.getStatus() === 2) {
            self.emit('progress', [+self.getInfo('size'), +self.getInfo('size')]);
            self.emit('complete', [self.getInfo('token')]);
            return;
        }

        var start = self.getInfo('start'),
            end   = self.getInfo('end'),
            token = self.getInfo('token'),
            file  = self.getFile();

        if($.trim(token) === '') {
            self.emit('error', ['', 201]);
            return false;
        }

        var slice = file.slice || file.webkitSlice || file.mozSlice,
            blob  = slice.call(file, start, end, file.type),
            xhr   = $.ajaxSettings.xhr();

        $(xhr.upload).bind('progress', function(e) {
            self.emit('progress', [ +start + e.originalEvent.loaded, +self.getInfo('size')]);
        });

        var param = $.param({
            token: token,
            start: start,
            end: end
        });

        self.setXHR(xhr);

        $.ajax({
            url: [self.options.uploadUrl, param].join('?'),
            type: 'POST',
            dataType: 'json',
            data: blob,
            processData: false,
            contentType: blob.type,
            xhr: function() {
                return xhr;
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            self.emit('error', ['', 201]);
        }).done(function(data, textStatus, jqXHR) {
            self.emit('uploadChunkFinished', [data]);
        });

        blob = undefined;
    }

    this.addEventListener('fetchTokenComplete', function(data) {

        var range = data.range.split('-');

        status = data.status;

        self.setInfo('token', data.token);
        self.setInfo('start', range[0]);
        self.setInfo('end', range[1]);

        this.multiChunkUpload();
    });

    this.addEventListener('uploadChunkFinished', function(data) {

        status = data.status;
        var range = data.range.split('-');
        self.setInfo('start', range[0]);
        self.setInfo('end', range[1]);

        if(self.getStatus() === 2) {
            self.emit('complete', [self.getInfo('token')]);
        } else {
            self.multiChunkUpload();
        }

    });

    this.abort = function() {
        var xhr = self.getXHR();
        if(xhr) xhr.abort();
    }

    this.reset = function() {
        this.abort();
        _file  = null,
        status = 0,
        xhr    = null,
        info   = {
            name: null,
            size: null,
            time: null,
            start: null,
            end: null,
            token: null
        };
    }

}

Html5Uploader.prototype = EventDispatcher.prototype;
Html5Uploader.prototype.constructor = Html5Uploader;

function FlashUploader(options, id) {

    var getFlash = function() {
        return document[id] || window[id] || document.getElementById(id);
    }

    this.upload = function() {
        getFlash().upload();
    }

    this.abort = function() {
        getFlash().abort();
    }

    this.reset = function() {
        getFlash().reset();
    }

}
FlashUploader.prototype = EventDispatcher.prototype;
FlashUploader.prototype.constructor = FlashUploader;


text:
package com.github.nrudenko.dora.query;

public interface ISql {

    String toSql();
}


text:
package com.java110.user.smo.impl;

import com.java110.core.base.smo.BaseServiceSMO;
import com.java110.dto.PageDto;
import com.java110.dto.owner.OwnerCarDto;
import com.java110.dto.user.UserDto;
import com.java110.entity.assetImport.ImportCustomCreateFeeDto;
import com.java110.entity.assetImport.ImportRoomFee;
import com.java110.intf.user.IOwnerCarInnerServiceSMO;
import com.java110.intf.user.IUserInnerServiceSMO;
import com.java110.user.dao.IOwnerCarServiceDao;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName FloorInnerServiceSMOImpl
 * @Description 车辆管理内部服务实现类
 * @Author wuxw
 * @Date 2019/4/24 9:20
 * @Version 1.0
 * add by wuxw 2019/4/24
 **/
@RestController
public class OwnerCarInnerServiceSMOImpl extends BaseServiceSMO implements IOwnerCarInnerServiceSMO {

    @Autowired
    private IOwnerCarServiceDao ownerCarServiceDaoImpl;

    @Autowired
    private IUserInnerServiceSMO userInnerServiceSMOImpl;

    @Override
    public List<OwnerCarDto> queryOwnerCars(@RequestBody OwnerCarDto ownerCarDto) {

        //校验是否传了 分页信息

        int page = ownerCarDto.getPage();

        if (page != PageDto.DEFAULT_PAGE) {
            ownerCarDto.setPage((page - 1) * ownerCarDto.getRow());
        }

        List<OwnerCarDto> ownerCars = BeanConvertUtil.covertBeanList(ownerCarServiceDaoImpl.getOwnerCarInfo(BeanConvertUtil.beanCovertMap(ownerCarDto)), OwnerCarDto.class);

        return ownerCars;
    }

    /**
     * 从用户列表中查询用户,将用户中的信息 刷新到 floor对象中
     *
     * @param ownerCar 小区车辆管理信息
     * @param users    用户列表
     */
    private void refreshOwnerCar(OwnerCarDto ownerCar, List<UserDto> users) {
        for (UserDto user : users) {
            if (ownerCar.getUserId().equals(user.getUserId())) {
                BeanConvertUtil.covertBean(user, ownerCar);
            }
        }
    }

    /**
     * 获取批量userId
     *
     * @param ownerCars 小区楼信息
     * @return 批量userIds 信息
     */
    private String[] getUserIds(List<OwnerCarDto> ownerCars) {
        List<String> userIds = new ArrayList<String>();
        for (OwnerCarDto ownerCar : ownerCars) {
            userIds.add(ownerCar.getUserId());
        }

        return userIds.toArray(new String[userIds.size()]);
    }

    @Override
    public int queryOwnerCarsCount(@RequestBody OwnerCarDto ownerCarDto) {
        return ownerCarServiceDaoImpl.queryOwnerCarsCount(BeanConvertUtil.beanCovertMap(ownerCarDto));
    }

    @Override
    public List<ImportRoomFee> freshCarIds(@RequestBody List<ImportRoomFee> tmpImportCarFees) {
        List<String> carNums = new ArrayList<>();
        for (ImportRoomFee importRoomFee : tmpImportCarFees) {
            if (StringUtil.isEmpty(importRoomFee.getCarNum())) {
                continue;
            }
            carNums.add(importRoomFee.getCarNum());
        }

        if (carNums.size() < 1) {
            return tmpImportCarFees;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("carNums", carNums.toArray(new String[carNums.size()]));
        info.put("communityId", tmpImportCarFees.get(0).getCommunityId());
        info.put("statusCd", "0");
        List<OwnerCarDto> ownerCarDtos = BeanConvertUtil.covertBeanList(ownerCarServiceDaoImpl.getOwnerCarInfo(info), OwnerCarDto.class);

        for (OwnerCarDto ownerCarDto : ownerCarDtos) {
            for (ImportRoomFee importRoomFee : tmpImportCarFees) {
                if (ownerCarDto.getCarNum().equals(importRoomFee.getCarNum())) {
                    importRoomFee.setCarId(ownerCarDto.getCarId());
                    importRoomFee.setOwnerId(ownerCarDto.getOwnerId());
                    importRoomFee.setOwnerName(ownerCarDto.getOwnerName());
                    importRoomFee.setOwnerLink(ownerCarDto.getLink());
                }
            }
        }
        return tmpImportCarFees;
    }

    public List<ImportCustomCreateFeeDto> freshCarIdsByImportCustomCreateFee(@RequestBody List<ImportCustomCreateFeeDto> tmpImportCarFees){
        List<String> carNums = new ArrayList<>();
        for (ImportCustomCreateFeeDto importRoomFee : tmpImportCarFees) {
            if (StringUtil.isEmpty(importRoomFee.getCarNum())) {
                continue;
            }
            carNums.add(importRoomFee.getCarNum());
        }

        if (carNums.size() < 1) {
            return tmpImportCarFees;
        }
        Map<String, Object> info = new HashMap<>();
        info.put("carNums", carNums.toArray(new String[carNums.size()]));
        info.put("communityId", tmpImportCarFees.get(0).getCommunityId());
        info.put("statusCd", "0");
        List<OwnerCarDto> ownerCarDtos = BeanConvertUtil.covertBeanList(ownerCarServiceDaoImpl.getOwnerCarInfo(info), OwnerCarDto.class);

        for (OwnerCarDto ownerCarDto : ownerCarDtos) {
            for (ImportCustomCreateFeeDto importRoomFee : tmpImportCarFees) {
                if (ownerCarDto.getCarNum().equals(importRoomFee.getCarNum())) {
                    importRoomFee.setPayObjId(ownerCarDto.getCarId());
                    importRoomFee.setOwnerId(ownerCarDto.getOwnerId());
                    importRoomFee.setOwnerName(ownerCarDto.getOwnerName());
                    importRoomFee.setOwnerLink(ownerCarDto.getLink());
                }
            }
        }
        return tmpImportCarFees;
    }

    @Override
    public long queryOwnerParkingSpaceCount(@RequestBody OwnerCarDto ownerCarDto) {
        return ownerCarServiceDaoImpl.queryOwnerParkingSpaceCount(BeanConvertUtil.beanCovertMap(ownerCarDto));
    }

    public IOwnerCarServiceDao getOwnerCarServiceDaoImpl() {
        return ownerCarServiceDaoImpl;
    }

    public void setOwnerCarServiceDaoImpl(IOwnerCarServiceDao ownerCarServiceDaoImpl) {
        this.ownerCarServiceDaoImpl = ownerCarServiceDaoImpl;
    }

    public IUserInnerServiceSMO getUserInnerServiceSMOImpl() {
        return userInnerServiceSMOImpl;
    }

    public void setUserInnerServiceSMOImpl(IUserInnerServiceSMO userInnerServiceSMOImpl) {
        this.userInnerServiceSMOImpl = userInnerServiceSMOImpl;
    }
}


text:
import { createApiService,
    CheckboxPage,
    LocalStorageUtil,
    LoginPage,
    UploadActions,
    UserModel,
    UsersActions,
    ViewerPage
} from '@alfresco/adf-testing';
import { MetadataViewPage } from '../../core/pages/metadata-view.page';
import { NavigationBarPage } from '../../core/pages/navigation-bar.page';
import { FileModel } from '../../models/ACS/file.model';
import { browser } from 'protractor';
import { ContentServicesPage } from '../../core/pages/content-services.page';
import { CustomModelApi, NodesApi } from '@alfresco/js-api';

describe('Aspect oriented config', () => {

    const loginPage = new LoginPage();
    const viewerPage = new ViewerPage();
    const metadataViewPage = new MetadataViewPage();
    const navigationBarPage = new NavigationBarPage();
    const contentServicesPage = new ContentServicesPage();
    const modelOneName = 'modelOne', emptyAspectName = 'emptyAspect';
    const defaultModel = 'cm', defaultEmptyPropertiesAspect = 'taggable', aspectName = 'Taggable';

    const apiService = createApiService();
    const usersActions = new UsersActions(apiService);
    const nodesApi = new NodesApi(apiService.getInstance());
    const customModelApi = new CustomModelApi(apiService.getInstance());

    let acsUser: UserModel;

    const pngFileModel = new FileModel({
        name: browser.params.resources.Files.ADF_DOCUMENTS.PNG.file_name,
        location: browser.params.resources.Files.ADF_DOCUMENTS.PNG.file_path
    });
    let uploadActions;

    beforeAll(async () => {
        uploadActions = new UploadActions(apiService);

        await apiService.loginWithProfile('admin');

        try {
            await customModelApi.createCustomModel('ACTIVE', modelOneName, modelOneName, modelOneName, modelOneName);
        } catch (e) {
        }

        try {
            await customModelApi.createCustomAspect(modelOneName, emptyAspectName, null, emptyAspectName, emptyAspectName);
        } catch (e) {
        }

        acsUser = await usersActions.createUser();

        await apiService.login(acsUser.username, acsUser.password);

        const uploadedFile = await uploadActions.uploadFile(pngFileModel.location, pngFileModel.name, '-my-');

        await loginPage.login(acsUser.username, acsUser.password);

        const aspects = await nodesApi.getNode(uploadedFile.entry.id);

        aspects.entry.aspectNames.push(modelOneName.concat(':', emptyAspectName));

        aspects.entry.aspectNames.push(defaultModel.concat(':', defaultEmptyPropertiesAspect));

        await nodesApi.updateNode(uploadedFile.entry.id, { aspectNames: aspects.entry.aspectNames });
   });

    afterAll(async () => {
        await navigationBarPage.clickLogoutButton();
    });

    afterEach(async () => {
        await viewerPage.clickCloseButton();
        await contentServicesPage.checkAcsContainer();
   });

    it('[C261117] Should be possible restrict the display properties of one an aspect', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', JSON.stringify({
            presets: {
                default: [
                    {
                        title: 'IMAGE',
                        items: [
                            {
                                aspect: 'exif:exif',
                                properties: [
                                    'exif:pixelXDimension',
                                    'exif:pixelYDimension',
                                    'exif:isoSpeedRatings'
                                ]
                            }
                        ]
                    }
                ]
            }
        }));

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();
        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.clickMetadataGroup('IMAGE');
        await metadataViewPage.checkPropertyIsVisible('properties.exif:pixelXDimension', 'textitem');
        await metadataViewPage.checkPropertyIsVisible('properties.exif:pixelYDimension', 'textitem');
        await metadataViewPage.checkPropertyIsNotVisible('properties.exif:isoSpeedRatings', 'textitem');

        await metadataViewPage.editIconClick();

        await metadataViewPage.checkPropertyIsVisible('properties.exif:isoSpeedRatings', 'textitem');
    });

    it('[C260185] Should ignore not existing aspect when present in the configuration', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', JSON.stringify({
            presets: {
                default: {
                    'exif:exif': '*',
                    'cm:versionable': '*',
                    'not:exists': '*'
                }
            }
        }));

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();
        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsPresent('EXIF');
        await metadataViewPage.checkMetadataGroupIsPresent('properties');
        await metadataViewPage.checkMetadataGroupIsPresent('Versionable');
        await metadataViewPage.checkMetadataGroupIsNotPresent('exists');
    });

    it('[C260183] Should show all the aspect if the content-metadata configuration is NOT provided', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', '{}');

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();
        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsPresent('EXIF');
        await metadataViewPage.checkMetadataGroupIsPresent('properties');
        await metadataViewPage.checkMetadataGroupIsPresent('Versionable');
    });

    it('[C260182] Should show all the aspects if the default configuration contains the star symbol', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', JSON.stringify({
            presets: {
                default: '*'
            }
        }));

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();
        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsPresent('EXIF');
        await metadataViewPage.checkMetadataGroupIsPresent('properties');
        await metadataViewPage.checkMetadataGroupIsPresent('Versionable');
    });

    it('[C268899] Should be possible use a Translation key as Title of a metadata group', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', '{' +
            '  "presets": {' +
            '    "default": [' +
            '      {' +
            '        "title": "GROUP-TITLE1-TRANSLATION-KEY",' +
            '        "items": [' +
            '          {' +
            '            "aspect": "exif:exif",' +
            '            "properties": "*"' +
            '          }' +
            '        ]' +
            '      },' +
            '      {' +
            '        "title": "GROUP-TITLE2-TRANSLATION-KEY",' +
            '        "items": [' +
            '          {' +
            '            "aspect": "exif:exif",' +
            '            "properties": "*"' +
            '          }' +
            '        ]' +
            '      }' +
            '    ]' +
            '  }' +
            '}');

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();

        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsPresent('GROUP-TITLE1-TRANSLATION-KEY');
        await metadataViewPage.checkMetadataGroupIsPresent('GROUP-TITLE2-TRANSLATION-KEY');

        await expect(await metadataViewPage.getMetadataGroupTitle('GROUP-TITLE1-TRANSLATION-KEY')).toBe('CUSTOM TITLE TRANSLATION ONE');
        await expect(await metadataViewPage.getMetadataGroupTitle('GROUP-TITLE2-TRANSLATION-KEY')).toBe('CUSTOM TITLE TRANSLATION TWO');
   });

    it('[C279968] Should be possible use a custom preset', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', '{' +
            '    "presets": {' +
            '        "custom-preset": {' +
            '            "exif:exif": "*",' +
            '            "cm:versionable": "*"' +
            '        }' +
            '    }' +
            '}');

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();

        await CheckboxPage.check(metadataViewPage.presetSwitch);

        await metadataViewPage.enterPresetText('custom-preset');

        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsPresent('properties');
        await metadataViewPage.checkMetadataGroupIsPresent('Versionable');
    });

    it('[C299186] The aspect without properties is not displayed', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', '{' +
            '    "presets": { "' + modelOneName +
            '       ": { "' + modelOneName + ':' + emptyAspectName +
            '            ":"*"' +
            '        }' +
            '    }' +
            '}');

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();

        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsNotPresent(emptyAspectName);
    });

    it('[C299187] The aspect with empty properties is displayed when edit', async () => {
        await LocalStorageUtil.setConfigField('content-metadata', '{' +
            '    "presets": { "' + defaultModel +
            '       ": { "' + defaultModel + ':' + defaultEmptyPropertiesAspect +
            '            ":"*"' +
            '        }' +
            '    }' +
            '}');

        await navigationBarPage.navigateToContentServices();

        await viewerPage.viewFile(pngFileModel.name);
        await viewerPage.clickInfoButton();
        await viewerPage.checkInfoSideBarIsDisplayed();
        await metadataViewPage.clickOnPropertiesTab();

        await metadataViewPage.informationButtonIsDisplayed();
        await metadataViewPage.clickOnInformationButton();

        await metadataViewPage.checkMetadataGroupIsNotPresent(aspectName);

        await metadataViewPage.editIconClick();

        await metadataViewPage.checkMetadataGroupIsPresent(aspectName);
    });
});


text:
from click.testing import CliRunner
from vl import __version__ as vl_version
from vl.cli.main import run

def test_run():
    runner = CliRunner()
    result = runner.invoke(run, ['--version'])
    assert result.exit_code == 0
    assert result.output == 'version %s\n' % vl_version


text:
/**
 * Display the details of the user with the given email.
 *
 * @param email
 * @param $this = jQuery object of selected table item
 */
function viewUserDetails(email, $this) {

    getUsers(
        success = function (user) {
            populateUserDetails(user, email, $this);
        },
        error = function (response) {
            handleApiError(response);
        },
        email
    );

    var isAdmin, isEditor;
    function populateUserDetails(user, email, $this) {
        getUserPermission(
            function (permission) {
                isAdmin = permission.admin;
                isEditor = permission.editor;

                addPermissionToJSON(user);

                var showPanelOptions = {
                    html: window.templates.userDetails(user)
                };
                showPanel($this, showPanelOptions);

                $('.btn-user-change-password').click(function () {
                    var currentPasswordRequired = false;

                    if (email == Florence.Authentication.loggedInEmail()) {
                        currentPasswordRequired = true;
                    }

                    viewChangePassword(email, currentPasswordRequired);
                });

                $('.btn-user-delete').click(function () {
                    swal({
                        title: "Confirm deletion",
                        text: "Please enter the email address of the user you want to delete",
                        type: "input",
                        inputPlaceHolder: "Email address",
                        showCancelButton: true,
                        closeOnConfirm: false,
                        confirmButtonText: "Delete",
                        animation: "slide-from-top"
                    }, function (result) {
                        console.log(result);
                        if (result) {
                            if (result === email) {
                                swal({
                                    title: "User deleted",
                                    text: "This user has been deleted",
                                    type: "success",
                                    timer: 2000
                                });
                                deleteUser(email);
                            } else {
                                sweetAlert("Oops!", 'The email you entered did not match the user you want to delete.')
                            }
                        }
                    });
                });

                $('.btn-user-cancel').click(function () {
                    hidePanel({});
                });
            },
            function (error) {handleApiError(error);},
            email
        );

    }

    /*
     * Add permissions object to JSON so accessible to handlebars template
     * @param user - JSON object
     */
    function addPermissionToJSON (user) {
        user['permission'] = permissionStr(isAdmin, isEditor);
    }

    /*
     * Logic to work out user role
     * @param isAdmin - true/false
     * @param isEditor - true/false
     * @return the user's role as string
     */
    function permissionStr (isAdmin, isEditor) {
        var permissionStr;
        if (!isAdmin && !isEditor) {permissionStr = 'viewer';}
        if (isEditor) {permissionStr = 'publisher';}
        if (isAdmin) {permissionStr = "admin";}

        return permissionStr;
    }
}