code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<?php
namespace App\Project\File\Types;
/**
* Type類別型 interface
*/
interface TypeInterface
{
/**
* 所有Type 必須能夠取得子關聯
*
* EX: MemberType 可以取得 children (members)
* @return Relation
*/
public function children();
/**
* 所有Type 必須能夠將子類型,與自己關聯
*
* EX: MemberType 可以 addChild (member)
*/
public function addChild($child);
}
| g9308370/PMBook | app/Project/File/Types/TypeInterface.php | PHP | mit | 453 |
Dummy::Application.routes.draw do
get '/:controller(/:action(/:id))'
get '/favicon.ico' => 'capybara#favicon'
end
| rails/pjax_rails | test/dummy/config/routes.rb | Ruby | mit | 118 |
use MooseX::Declare;
# ABSTRACT: list the continents
class Planet::Earth::Countries::App::Command::Continents extends MooseX::App::Cmd::Command {
use Planet::Earth;
use Data::Printer;
method execute {
my $e = Planet::Earth->new;
my $continents = $e->continents;
p $continents;
return $continents;
}
}
| displague/moose-demo | Planet/Earth/Countries/App/Command/Continents.pm | Perl | mit | 329 |
---
layout: publications
title: "Multiple languages in AngularJS"
categories: publications
modified: 2015-01-24T11:57:41-04:00
toc: false
comments: true
image:
feature: AngularJS.jpg
teaser: AngularJS.jpg
---
in work .... | ivanproskuryakov/ivanproskuryakov.github.io | _inwork/2015-2-17-Multiple-languages-in-AngularJS.md | Markdown | mit | 226 |
"""
Base storages can store, integers, strings, and byte strings
"""
from bitarray import bitarray
import pytest
from bigsi.tests.base import get_test_storages
def get_storages():
return get_test_storages()
def test_get_set():
for storage in get_storages():
storage.delete_all()
storage["test"] = b"123"
assert storage["test"] == b"123"
storage.delete_all()
def test_get_set_integer():
for storage in get_storages():
storage.delete_all()
storage.set_integer("test", 112)
assert storage.get_integer("test") == 112
storage.delete_all()
def test_get_set_string():
for storage in get_storages():
storage.delete_all()
storage.set_string("test", "abc")
assert storage.get_string("test") == "abc"
storage.delete_all()
def test_get_set_bitarray():
ba = bitarray("110101111010")
for storage in get_storages():
storage.delete_all()
storage.set_bitarray("test", ba)
assert storage.get_bitarray("test")[:12] == ba
assert storage.get_bit("test", 1) == True
assert storage.get_bit("test", 2) == False
storage.set_bit("test", 0, 0)
assert storage.get_bitarray("test")[:12] == bitarray("010101111010")
assert storage.get_bit("test", 0) == False
storage.delete_all()
def test_increment():
for storage in get_storages():
storage.delete_all()
assert storage.incr("testinc") == 1
assert storage.incr("testinc") == 2
def test_delete():
for storage in get_storages():
storage.set_string("test", "1231")
assert storage.get_string("test") == "1231"
storage.delete_all()
with pytest.raises(BaseException):
storage.get_string("test") == None
storage.delete_all()
| Phelimb/cbg | bigsi/tests/storage/test_storage.py | Python | mit | 1,829 |
/* Copyright John Reid 2007
*/
#include "bio-pch.h"
#include "bio/defs.h"
#include "bio/biobase_db.h"
#include "bio/biobase_data_traits.h"
USING_BIO_NS
using namespace boost;
using namespace boost::archive;
using namespace std;
BIO_NS_START
namespace detail {
bool
never_parse( Database type )
{
switch( type )
{
case AFFY_PROBE_DB:
case BKL_DB:
case RSNP_DB:
case UNKNOWN_DB:
return true;
default:
return false;
}
}
} //namespace detail
AlignDesc::AlignDesc()
: positive_orientation( true )
{
}
bool
Site::parse_db_type( Database type )
{
if( detail::never_parse( type ) ) { return false; }
return false;
}
bool
Gene::parse_db_type( Database type )
{
if( detail::never_parse( type ) ) { return false; }
return true;
}
bool
Factor::parse_db_type( Database type )
{
if( detail::never_parse( type ) ) { return false; }
return true;
}
bool
Evidence::parse_db_type( Database type )
{
if( detail::never_parse( type ) ) { return false; }
return true;
}
int Site::get_transfac_gene_accession() const
{
static const std::string tag = "Gene:";
static const std::string dot = ".";
//find the gene tag in description
std::string::size_type pos = description.find( tag );
if ( std::string::npos == pos )
{
return -1;
}
pos += tag.size();
//ignore white space
while ( ' ' == description[ pos ] )
{
++pos;
}
//the dot at the end of the text of the link to the gene table
std::string::size_type end = description.find( dot, pos );
//the text of the link to the gene table
const std::string gene_link = description.substr( pos, end - pos );
//parse the text
const TableLink link = parse_table_link_accession_number( gene_link );
if ( GENE_DATA != link.table_id )
{
return -1;
}
return link.entry_idx;
}
BIO_NS_END
| JohnReid/biopsy | C++/src/bio/lib/biobase_db.cpp | C++ | mit | 1,786 |
<?php
namespace phpdotnet\phd;
class Package_IDE_SQLite extends Package_IDE_Base {
private $sql = array();
private $db = null;
public function __construct() {
$this->registerFormatName('IDE-SQLite');
$this->setExt(Config::ext() === null ? ".sqlite" : Config::ext());
}
public function INIT($value) {
$this->loadVersionInfo();
$this->createDatabase();
}
public function FINALIZE($value) {
$this->db->exec('BEGIN TRANSACTION; ' . join(' ', $this->sql) . ' COMMIT');
if ($this->db->lastErrorCode()) {
trigger_error($this->db->lastErrorMsg(), E_USER_WARNING);
}
}
public function writeChunk () {
if (!isset($this->cchunk['funcname'][0])) {
return;
}
if (false !== strpos($this->cchunk['funcname'][0], ' ')) {
return;
}
$this->function['version'] = $this->versionInfo($this->cchunk['funcname'][0]);
foreach ($this->cchunk['funcname'] as $funcname) {
$this->function['name'] = $funcname;
$this->parseFunction();
}
}
public function parseFunction() {
$sql = sprintf("INSERT INTO functions (name, purpose, manual_id, version, return_type, return_description, errors) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s');",
$this->db->escapeString($this->function['name']),
$this->db->escapeString($this->function['purpose']),
$this->db->escapeString($this->function['manualid']),
$this->db->escapeString($this->function['version']),
$this->db->escapeString($this->function['return']['type'] ?? ''),
$this->db->escapeString($this->function['return']['description'] ?? ''),
$this->db->escapeString($this->function['errors'] ?? '')
);
foreach ((array)$this->function['params'] as $param) {
$sql .= sprintf("INSERT INTO params (function_name, name, type, description, optional, initializer) VALUES ('%s', '%s', '%s', '%s', '%s', '%s');",
$this->db->escapeString($this->function['name']),
$this->db->escapeString($param['name']),
$this->db->escapeString($param['type']),
$this->db->escapeString(isset($param['description']) ? $param['description'] : ''),
$this->db->escapeString($param['optional'] === 'true' ? 1 : 0),
$this->db->escapeString(isset($param['initializer']) ? $param['initializer'] : '')
);
}
foreach ((array)$this->function['notes'] as $entry) {
$sql .= sprintf("INSERT INTO notes (function_name, type, description) VALUES ('%s', '%s', '%s');",
$this->db->escapeString($this->function['name']),
$this->db->escapeString($entry['type']),
$this->db->escapeString($entry['description'])
);
}
foreach ((array)$this->function['changelog'] as $entry) {
$sql .= sprintf("INSERT INTO changelogs (function_name, version, change) VALUES ('%s', '%s', '%s');",
$this->db->escapeString($this->function['name']),
$this->db->escapeString($entry['version']),
$this->db->escapeString($entry['change'])
);
}
foreach ((array)$this->function['seealso'] as $entry) {
$sql .= sprintf("INSERT INTO seealso (function_name, name, type) VALUES ('%s', '%s', '%s');",
$this->db->escapeString($this->function['name']),
$this->db->escapeString($entry['name']),
$this->db->escapeString($entry['type'])
);
}
$this->sql[] = $sql;
}
public function createDatabase() {
$db = new \SQLite3(Config::output_dir() . strtolower($this->getFormatName()) . $this->getExt());
$db->exec('DROP TABLE IF EXISTS functions');
$db->exec('DROP TABLE IF EXISTS params');
$db->exec('DROP TABLE IF EXISTS notes');
$db->exec('DROP TABLE IF EXISTS seealso');
$db->exec('DROP TABLE IF EXISTS changelogs');
$db->exec('PRAGMA default_synchronous=OFF');
$db->exec('PRAGMA count_changes=OFF');
$db->exec('PRAGMA cache_size=100000');
$db->exec($this->createSQL());
$this->db = $db;
}
public function createSQL() {
return <<<SQL
CREATE TABLE functions (
name TEXT,
purpose TEXT,
manual_id TEXT,
version TEXT,
return_type TEXT,
return_description TEXT,
errors TEXT
);
CREATE TABLE params (
function_name TEXT,
name TEXT,
type TEXT,
description TEXT,
optional INTEGER,
initializer TEXT
);
CREATE TABLE notes (
function_name TEXT,
type TEXT,
description TEXT
);
CREATE TABLE seealso (
function_name TEXT,
name TEXT,
type TEXT,
description TEXT
);
CREATE TABLE changelogs (
function_name TEXT,
version TEXT,
change TEXT
);
SQL;
}
}
/*
* vim600: sw=4 ts=4 syntax=php et
* vim<600: sw=4 ts=4
*/
| php/phd | phpdotnet/phd/Package/IDE/SQLite.php | PHP | mit | 5,088 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>V8 API Reference Guide for node.js v0.11.9: Namespace Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">V8 API Reference Guide for node.js v0.11.9
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="namespaces.html"><span>Namespace List</span></a></li>
<li class="current"><a href="namespacemembers.html"><span>Namespace Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li class="current"><a href="namespacemembers.html"><span>All</span></a></li>
<li><a href="namespacemembers_func.html"><span>Functions</span></a></li>
<li><a href="namespacemembers_type.html"><span>Typedefs</span></a></li>
<li><a href="namespacemembers_enum.html"><span>Enumerations</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<div class="textblock">Here is a list of all documented namespace members with links to the namespaces they belong to:</div><ul>
<li>AccessControl
: <a class="el" href="namespacev8.html#a31d8355cb043d7d2dda3f4a52760b64e">v8</a>
</li>
<li>AccessorGetterCallback
: <a class="el" href="namespacev8.html#a722613c87061708a4f1aa050d095f868">v8</a>
</li>
<li>AccessType
: <a class="el" href="namespacev8.html#add8bef6469c5b94706584124e610046c">v8</a>
</li>
<li>AllowCodeGenerationFromStringsCallback
: <a class="el" href="namespacev8.html#a521d909ec201742a1cb35d50a8e2a3c2">v8</a>
</li>
<li>ConfigureResourceConstraintsForCurrentPlatform()
: <a class="el" href="namespacev8.html#a19e20f71bd0c06e31b37fa8b67a36ce0">v8</a>
</li>
<li>EntropySource
: <a class="el" href="namespacev8.html#ab699f4bbbb56350e6e915682e420fcdc">v8</a>
</li>
<li>FunctionEntryHook
: <a class="el" href="namespacev8.html#aaf07fb6bb13f295da3c6568938b7dec5">v8</a>
</li>
<li>GCType
: <a class="el" href="namespacev8.html#ac109d6f27e0c0f9ef4e98bcf7a806cf2">v8</a>
</li>
<li>IndexedPropertyDeleterCallback
: <a class="el" href="namespacev8.html#a53863728de14cde48dd6543207b2f2da">v8</a>
</li>
<li>IndexedPropertyEnumeratorCallback
: <a class="el" href="namespacev8.html#adbb0a6d5537371953f9ba807d4f6275e">v8</a>
</li>
<li>IndexedPropertyGetterCallback
: <a class="el" href="namespacev8.html#a48e7816ba64447bf32a25d194588daaf">v8</a>
</li>
<li>IndexedPropertyQueryCallback
: <a class="el" href="namespacev8.html#a980b62c33eb664783e61e25c3b27f9ee">v8</a>
</li>
<li>IndexedPropertySetterCallback
: <a class="el" href="namespacev8.html#a4ac7cc6185ebc8b6a199f9fa8e6bf5c3">v8</a>
</li>
<li>IndexedSecurityCallback
: <a class="el" href="namespacev8.html#aebbcc7837753e51112d944ad96520da1">v8</a>
</li>
<li>JitCodeEventHandler
: <a class="el" href="namespacev8.html#a39243bc91e63d64d111452fdb98c4733">v8</a>
</li>
<li>JitCodeEventOptions
: <a class="el" href="namespacev8.html#a06f34fa4fa4cfc8518366808d1d461c1">v8</a>
</li>
<li>NamedPropertyDeleterCallback
: <a class="el" href="namespacev8.html#aaba861076c5b111912cfa0791d348437">v8</a>
</li>
<li>NamedPropertyEnumeratorCallback
: <a class="el" href="namespacev8.html#a5f6f16818a9cddacadbfe6d90ca3a6b1">v8</a>
</li>
<li>NamedPropertyGetterCallback
: <a class="el" href="namespacev8.html#a50cae386a68bf9ff23d02aa1161face4">v8</a>
</li>
<li>NamedPropertyQueryCallback
: <a class="el" href="namespacev8.html#ac135beae5f0c8b290255accb438f990e">v8</a>
</li>
<li>NamedPropertySetterCallback
: <a class="el" href="namespacev8.html#a9587769513971dc7cb301b740d9e66b6">v8</a>
</li>
<li>NamedSecurityCallback
: <a class="el" href="namespacev8.html#ab5cafda0c556bba990c660ce9c904e0d">v8</a>
</li>
<li>ReturnAddressLocationResolver
: <a class="el" href="namespacev8.html#a8ce54c75241be41ff6a25e9944eefd2a">v8</a>
</li>
<li>SetDefaultResourceConstraintsForCurrentPlatform()
: <a class="el" href="namespacev8.html#a2ed25f92f343806b1230763d2786aeef">v8</a>
</li>
<li>SetResourceConstraints()
: <a class="el" href="namespacev8.html#a9b221aaf88ecee02285c08edaada9c8f">v8</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Aug 11 2015 23:46:16 for V8 API Reference Guide for node.js v0.11.9 by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| v8-dox/v8-dox.github.io | b73967e/html/namespacemembers.html | HTML | mit | 7,287 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sqlalchemy as sa
from hyputils.memex.db import Base
from hyputils.memex.db import mixins
from hyputils.memex import pubid
ORGANIZATION_DEFAULT_PUBID = "__default__"
ORGANIZATION_NAME_MIN_CHARS = 1
ORGANIZATION_NAME_MAX_CHARS = 25
class Organization(Base, mixins.Timestamps):
__tablename__ = "organization"
id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)
# We don't expose the integer PK to the world, so we generate a short
# random string to use as the publicly visible ID.
pubid = sa.Column(sa.Text(), default=pubid.generate, unique=True, nullable=False)
name = sa.Column(sa.UnicodeText(), nullable=False, index=True)
logo = sa.Column(sa.UnicodeText())
authority = sa.Column(sa.UnicodeText(), nullable=False)
@sa.orm.validates("name")
def validate_name(self, key, name):
if not (
ORGANIZATION_NAME_MIN_CHARS <= len(name) <= ORGANIZATION_NAME_MAX_CHARS
):
raise ValueError(
"name must be between {min} and {max} characters long".format(
min=ORGANIZATION_NAME_MIN_CHARS, max=ORGANIZATION_NAME_MAX_CHARS
)
)
return name
def __repr__(self):
return "<Organization: %s>" % self.pubid
@classmethod
def default(cls, session):
return session.query(cls).filter_by(pubid=ORGANIZATION_DEFAULT_PUBID).one()
| tgbugs/hypush | hyputils/memex/models/organization.py | Python | mit | 1,477 |
<!DOCTYPE html>
<html lang="ko-kr">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="generator" content="Hugo 0.15" />
<title>#Ludens</title>
<meta property="og:site_name" content="#Ludens" />
<meta property="og:locale" content="ko-kr" />
<meta property="og:url" content="http://ludens.kr/tags/charlie-bit-my-finger/" />
<meta property="fb:pages" content="1707155736233413"/>
<meta property="fb:admins" content="100001662925065"/>
<meta property="fb:app_id" content="326482430777833"/>
<meta property="fb:article_style" content="default" />
<meta name="twitter:site" content="@ludensk" />
<meta name="twitter:creator" content="@ludensk" />
<meta name="google-site-verification" content="RPY_1Z0am0hoduGzENYtuwF3BBoE0x5l3UxhUplLWPU" />
<meta name="naver-site-verification" content="f84c50bc744edf7a543994325914265117555d53" />
<meta name="p:domain_verify" content="381496f2247c95edc614061bacd92e08" />
<meta name="msvalidate.01" content="9137E6F3A8C1C4AE6DC4809DEDB06FD9" />
<meta property="og:title" content="Charlie Bit My Finger" />
<meta property="og:type" content="website" />
<meta name="description" content="페이스북부터 심리학 그리고 워드프레스까지 온갖 잡지식을 가끔씩 끄적이고 있습니다." />
<meta name="twitter:card" content="summary" />
<link rel="author" href="humans.txt" />
<link rel="me" href="https://twitter.com/ludensk" />
<link rel="me" href="https://google.com/+ludensk" />
<link rel="me" href="https://github.com/ludens" />
<link rel="pingback" href="https://webmention.io/ludens.kr/xmlrpc" />
<link rel="webmention" href="https://webmention.io/ludens.kr/webmention" />
<link href="https://plus.google.com/+ludensk" rel="publisher">
<link rel="canonical" href="http://ludens.kr/tags/charlie-bit-my-finger/" />
<link rel="alternate" type="application/rss+xml" title="#Ludens" href="http://ludens.kr/rss/" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="#Ludens">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#111111">
<meta name="msapplication-navbutton-color" content="#111111">
<meta name="msapplication-TileColor" content="#111111">
<meta name="application-name" content="#Ludens">
<meta name="msapplication-tooltip" content="페이스북부터 심리학 그리고 워드프레스까지 온갖 잡지식을 가끔씩 끄적이고 있습니다.">
<meta name="msapplication-starturl" content="/">
<meta http-equiv="cleartype" content="on">
<meta name="msapplication-tap-highlight" content="no">
<link rel="apple-touch-icon" sizes="57x57" href="http://ludens.kr/favicon/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="http://ludens.kr/favicon/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="http://ludens.kr/favicon/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="http://ludens.kr/favicon/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="http://ludens.kr/favicon/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="http://ludens.kr/favicon/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="http://ludens.kr/favicon/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="http://ludens.kr/favicon/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="http://ludens.kr/favicon/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-194x194.png" sizes="194x194">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="http://ludens.kr/favicon/manifest.json">
<link rel="mask-icon" href="http://ludens.kr/favicon/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
<link rel="stylesheet" href="http://ludens.kr/css/pure/pure-min.css" />
<link rel="stylesheet" href="http://ludens.kr/css/pure/grids-responsive-min.css" />
<link rel='stylesheet' href='http://ludens.kr/font/fonts.css'>
<link rel="stylesheet" href="http://ludens.kr/font/font-awesome.min.css">
<link rel="stylesheet" href="http://ludens.kr/css/style.css"/>
<script src="http://ludens.kr/js/jquery-2.2.1.min.js"></script>
</head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '326482430777833',
xfbml : true,
version : 'v2.6'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/ko_KR/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<header class="pure-g">
<div class="pure-u-1 pure-u-sm-1-3 center">
<h1><a href="http://ludens.kr">#LUDENS</a></h1>
</div>
<nav class="pure-u-1 pure-u-sm-2-3 center">
<a href="http://ludens.kr/" class="home" title="Home">HOME</a>
<a href="http://ludens.kr/categories/" class="category" title="Category">CATEGORY</a>
<a href="http://ludens.kr/post/" class="archive" title="Archive">ARCHIVE</a>
<a href="http://ludens.kr/tags/" class="tag" title="Tag">TAG</a>
<a href="http://ludens.kr/guestbook/" class="guestbook" title="Guestbook">GUESTBOOK</a>
</nav>
</header>
<main class="list mainWrap">
<h2 class="ellipsis"><small>Posts about </small>Charlie Bit My Finger</h2>
<h3 id="2013">2013</h3>
<div class="pure-g">
<div class="pure-u-1 pure-u-sm-1-2">
<a href="http://ludens.kr/post/5-common-characteristics-of-viral-videos/" class="cover" style="background-image: url('/images/old/cfile2.uf.0334113851061E74185CD8.png');"></a>
<div class="category ubuntu300 grey">
<a class="grey" href="http://ludens.kr/categories/marketing" title="marketing">marketing</a>
at <time datetime="28 Jan 2013 17:00">2013/1/28</time>
</div>
<h3 class="ellipsis margintop0"><a href="http://ludens.kr/post/5-common-characteristics-of-viral-videos/" title="성공하는 바이럴 영상들의 5가지 공통점">성공하는 바이럴 영상들의 5가지 공통점</a></h3>
</div>
</div>
</main>
<footer>
<div class="footerWrap pure-g">
<div class="pure-u-1 pure-u-md-2-5 copyright center">
ⓒ 2016 Ludens | Published with <a class="black dotline" href="http://gohugo.io" target="_blank" rel="nofollow">Hugo</a>
</div>
<nav class="pure-u-1 pure-u-md-3-5 center">
<a href="https://twitter.com/ludensk" class="twitter" title="Twitter"><i class='fa fa-twitter-square'></i></a>
<a href="https://fb.com/ludensk" class="facebook" title="Facebook"><i class='fa fa-facebook-square'></i></a>
<a href="https://instagr.am/ludensk" class="instagram" title="Instagram"><i class='fa fa-instagram'></i></a>
<a href="https://pinterest.com/ludensk" class="pinterest" title="Pinterest"><i class='fa fa-pinterest-square'></i></a>
<a href="https://www.youtube.com/user/ludensk" class="youtube" title="YouTube"><i class='fa fa-youtube-square'></i></a>
<a href="https://ludensk.tumblr.com" class="tumblr" title="Tumblr"><i class='fa fa-tumblr-square'></i></a>
<a href="https://linkedin.com/in/ludensk" class="linkedin" title="LinkedIn"><i class='fa fa-linkedin-square'></i></a>
<a href="https://github.com/ludens" class="github" title="GitHub"><i class='fa fa-github-square'></i></a>
<a href="http://ludens.kr/rss/" class="rss" title="RSS"><i class='fa fa-rss-square'></i></a>
</nav>
</div>
</footer>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-29269230-1', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script>
<script type="text/javascript">
if(!wcs_add) var wcs_add = {};
wcs_add["wa"] = "123cefa73667c5c";
wcs_do();
</script>
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','//connect.facebook.net/en_US/fbevents.js');
fbq('init','1143503702345044');
fbq('track',"PageView");
</script>
<noscript><img height="1" width="1" style="display:none" src="//www.facebook.com/tr?id=1143503702345044&ev=PageView&noscript=1" /></noscript>
<script src="//twemoji.maxcdn.com/twemoji.min.js"></script>
<script>var emoji=document.getElementsByClassName("emoji");twemoji.parse(emoji[0],{size:16});</script>
<script src="http://ludens.kr/js/jquery.keep-ratio.min.js"></script>
<script type="text/javascript">
$(function() {
$('.kofic-poster').keepRatio({ ratio: 27/40, calculate: 'height' });
$('.articleWrap .cover, .post_latest .cover,.articleWrap header figure').keepRatio({ ratio: 12/5, calculate: 'height' });
if ($(window).width() >= 568) {
$('.futher .cover,.error .cover,.post_two .cover,.list .cover').keepRatio({ ratio: 4/3, calculate: 'height' });
$('.categories .cover').keepRatio({ ratio: 1/1, calculate: 'height' });
}
else {
$('.futher .cover,.error .cover,.post_two .cover,.list .cover,.categories .cover').keepRatio({ ratio: 12/5, calculate: 'height' });
}
});
</script>
</body>
</html> | ludens/ludens.kr | tags/charlie-bit-my-finger/index.html | HTML | mit | 10,675 |
/*
VRT - Copyright © 2014 Odd Marthon Lende
All Rights Reserved
*/
define([
'd3'
, 'lib/adapters/adapter'
, 'lib/api'
], function (d3, Adapter, vrt) {
function Manual (options) {
options = options || {};
Adapter.call(this, options);
this.name = "manual";
}
Manual.prototype = Object.create(Adapter.prototype);
return Manual;
}) | oddmarthon-lende/vrt | lib/adapters/manual.adapter.js | JavaScript | mit | 434 |
using EventService.Data;
using EventService.Data.Model;
using EventService.Features.Core;
using MediatR;
using System;
using System.Threading.Tasks;
using System.Data.Entity;
using static EventService.Features.Geolocation.GetLongLatCoordinatesQuery;
using EventService.Features.Locations;
namespace EventService.Features.Events
{
public class AddOrUpdateEventCommand
{
public class AddOrUpdateEventRequest : IRequest<AddOrUpdateEventResponse>
{
public EventApiModel Event { get; set; }
public Guid TenantUniqueId { get; set; }
}
public class AddOrUpdateEventResponse { }
public class AddOrUpdateEventHandler : IAsyncRequestHandler<AddOrUpdateEventRequest, AddOrUpdateEventResponse>
{
public AddOrUpdateEventHandler(EventServiceContext context, ICache cache, IMediator mediator)
{
_context = context;
_cache = cache;
_mediator = mediator;
}
public async Task<AddOrUpdateEventResponse> Handle(AddOrUpdateEventRequest request)
{
var entity = await _context.Events
.Include(x => x.Tenant)
.Include(x=>x.EventLocation)
.SingleOrDefaultAsync(x => x.Id == request.Event.Id && x.Tenant.UniqueId == request.TenantUniqueId);
var tenant = await _context.Tenants.SingleOrDefaultAsync(x => x.UniqueId == request.TenantUniqueId);
if (entity == null) {
_context.Events.Add(entity = new Event() { TenantId = tenant.Id });
}
entity.EventLocation = entity.EventLocation ?? new EventLocation() { TenantId = tenant.Id };
var longLatResponse = await _mediator.Send(new GetLongLatCoordinatesRequest() { Address = $"{request.Event.EventLocation.Address},{request.Event.EventLocation.City},{request.Event.EventLocation.Province},{request.Event.EventLocation.PostalCode}" });
request.Event.EventLocation.Longitude = longLatResponse.Longitude;
request.Event.EventLocation.Latitude = longLatResponse.Latitude;
entity.Name = request.Event.Name;
entity.Url = request.Event.Url;
entity.DisplayName = request.Event.DisplayName;
entity.Description = request.Event.Description;
entity.Abstract = request.Event.Abstract;
entity.Start = request.Event.Start;
entity.End = request.Event.End;
entity.ImageUrl = request.Event.ImageUrl;
request.Event.EventLocation.ToLocation(entity.EventLocation);
await _context.SaveChangesAsync();
return new AddOrUpdateEventResponse();
}
protected readonly EventServiceContext _context;
protected readonly ICache _cache;
protected readonly IMediator _mediator;
}
}
}
| QuinntyneBrown/EventService | src/EventService/Features/Events/AddOrUpdateEventCommand.cs | C# | mit | 3,055 |
/*
* Copyright (c) 2016 Samuel Marchildon-Lavoie
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.djxy.multiscripts.scripts.lua;
import io.github.djxy.multiscripts.objects.ArrayObject;
import io.github.djxy.multiscripts.objects.MapObject;
import io.github.djxy.multiscripts.objects.Value;
import org.luaj.vm2.LuaInteger;
import org.luaj.vm2.LuaValue;
/**
* Created by Samuel on 2016-11-07.
*/
public class LuaArray extends LuaMap {
private final ArrayObject arrayObject;
public LuaArray(Value value) {
super(value);
this.arrayObject = (ArrayObject) value.get();
}
@Override
public LuaValue rawget(LuaValue luaValue) {
if(luaValue.isint())
return Util.toLuaValue(arrayObject.get(luaValue.checkint()));
if(luaValue.checkjstring().equals("length"))
return LuaInteger.valueOf(arrayObject.size());
return super.rawget(luaValue);
}
@Override
public void rawset(LuaValue luaValue, LuaValue luaValue1) {
if(luaValue.isint()) {
if (luaValue1.equals(LuaValue.NIL))
arrayObject.remove(luaValue.checkint());
else
arrayObject.add(luaValue.checkint(), Util.toValue(luaValue1));
}
else
super.rawset(luaValue, luaValue1);
}
}
| djxy/MultiScripts | src/main/java/io/github/djxy/multiscripts/scripts/lua/LuaArray.java | Java | mit | 2,327 |
using UnityEngine;
using System.Collections;
public class CameraRotate : MonoBehaviour {
private float mouseX;
public float rotateSpeed = 10.0f;
public float moveSpeed = 1.0f;
void LateUpdate()
{
HandleMouseRotation();
mouseX = Input.mousePosition.x;
}
public void HandleMouseRotation()
{
if (Input.GetMouseButton(1))
{
//horizontal rotation
if(Input.mousePosition.x != mouseX)
{
float cameraRotationY = (Input.mousePosition.x - mouseX) * rotateSpeed * Time.deltaTime;
this.transform.Rotate(0, cameraRotationY, 0);
}
}
}
}
| lethosor/armok-vision | Assets/CameraScripts/CameraRotate.cs | C# | mit | 691 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pokemon Example</title>
<script type="text/javascript" src="../libraries/d3.min.js"></script>
<script type="text/javascript" src="../libraries/d3-scale-chromatic.min.js"></script>
<style>
body {
font-family: "Open Sans";
font-size: 14px;
}
svg text {
font-family: "Open Sans";
font-size: 14px;
}
#tooltip {
position: absolute;
visibility: hidden;
background: white;
font-size: 12px;
padding: 5px 15px
}
.container {
display: flex;
}
.headline-container {
display: flex;
}
#selection {
padding: 0px 5px;
}
#remove-selection {
padding: 0px 3px;
visibility: hidden;
cursor: pointer;
background: #b46d6d;
}
</style>
</head>
<body>
<div id="tooltip"></div>
<div class="container">
<div>
<div>Pokemon Type Matrix</div>
<div class="type-container" id="type-viz"></div>
</div>
<div>
<div class="headline-container">
<div>Pokemon Scatterplot -</div>
<div id="selection">all types visible</div>
<div id="remove-selection">remove all</div>
</div>
<div class="poke-container" id="poke-viz"></div>
</div>
</div>
<script type="text/javascript">
window.onload = function () {
var pokemon_data;
var margin = {top: 20, left: 100, bottom: 60, right: 10};
var marginSp = {top: 20, left: 50, bottom: 50, right: 10};
var width = 650 * 0.9 - margin.left - margin.right;
var widthSp = 650 * 0.9 - marginSp.left - marginSp.right;
var height = 450 * 0.9 - margin.top - margin.bottom;
var tooltip = d3.select('#tooltip');
var selectionName = d3.select('#selection');
var removeSelection = d3.select('#remove-selection')
.on('click', function () {
selectionName.html('all types visible');
d3.select(this).style('visibility', 'hidden');
updatePokemonViz(pokemon_data);
});
var svgType = d3.select('#type-viz')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var r = d3.scaleLinear()
.range([1, 10]);
var yAxis = d3.axisLeft(y),
xAxis = d3.axisBottom(x);
var svgPoke = d3.select('#poke-viz')
.append('svg')
.attr('width', widthSp + marginSp.left + marginSp.right)
.attr('height', height + marginSp.top + marginSp.bottom);
var g = svgPoke.append('g')
.attr('transform', 'translate(' + marginSp.left + ',' + marginSp.top + ')');
var gy = g.append('g')
.attr('class', 'y-axis')
.call(yAxis);
var gx = g.append('g')
.attr('class', 'x-axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
d3.csv('Pokemon.csv'
, function (d) {
var type2 = d['Type 2'];
if (type2 === "") {
type2 = 'Unknown';
}
return {
id: d['#'],
name: d['Name'],
generation: d['Generation'],
type_1: d['Type 1'],
type_2: type2,
hp: +d['HP'],
attack: +d['Attack'],
defense: +d['Defense']
}
}
, function (error, da) {
var helperType = {};
var type1 = [], type2 = [];
pokemon_data = da;
pokemon_data.forEach(function (d) {
if (helperType[d.type_1] === undefined) {
type1.push(d.type_1);
helperType[d.type_1] = {count: 0};
}
helperType[d.type_1].count = helperType[d.type_1].count + 1;
if (helperType[d.type_1][d.type_2] === undefined) {
helperType[d.type_1][d.type_2] = {count: 0};
}
helperType[d.type_1][d.type_2].count = helperType[d.type_1][d.type_2].count + 1;
});
type1.sort();
type1.map(function (d) {
type2.push(d);
});
type2.push('Unknown');
var typematrix = [];
var max = -1e10;
// console.log(helperType)
for (var key in helperType) {
for (var k in helperType[key]) {
if (k !== 'count') {
typematrix.push({type_1: key, type_2: k, count: helperType[key][k].count})
if (max < helperType[key][k].count) max = helperType[key][k].count;
}
}
}
drawTypeMatrix(typematrix, type1, type2, svgType);
updatePokemonViz(pokemon_data);
});
//ab hier wird die achse genutzt.
function drawTypeMatrix(data, type1, type2, svg) {
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.2)
.domain(type2.map(function (d) {
return d;
}));
var y = d3.scaleBand()
.range([height, 0])
.padding(0.2)
.domain(type1.map(function (d) {
return d;
}));
var color = d3.scaleThreshold()
.domain([1, 3, 6, 8, 12, 25, 35, 45])
.range(d3.schemePurples[9]);
svg.append('g')
.call(d3.axisLeft(y));
svg.append('text')
.attr('x', -margin.left)
.attr('y', 0)
.attr("font-weight", "bold")
.attr('font-size', 16)
.text("Type 1");
svg.append('text')
.attr('x', -margin.left * 0.5)
.attr('y', height + margin.bottom * 0.5)
.attr("font-weight", "bold")
.attr('font-size', 16)
.text("Type 2");
svg.append('g')
.attr('class', 'x-matrix')
.attr('transform', 'translate(0,' + height + ')')
.call(d3.axisBottom(x))
.selectAll('text')
.attr('transform', 'rotate(-45)')
.style('text-anchor', 'end');
svg.selectAll('.histo')
.data(data)
.enter().append('rect')
.attr('class', 'histo')
.attr('y', function (d) {
return y(d.type_1);
})
.attr('x', function (d) {
return x(d.type_2);
})
.attr('width', x.bandwidth())
.attr('height', y.bandwidth())
.style('fill', function (d) {
return color(d.count);
})
.on('mouseenter', function (d) {
svg.select('.' + d.type_1 + '_' + d.type_2)
.style('visibility', 'visible');
})
.on('mouseout', function (d) {
svg.select('.' + d.type_1 + '_' + d.type_2)
.style('visibility', 'hidden');
})
.on('click', function (d) {
var ar = reduceData(pokemon_data, d.type_1, d.type_2);
selectionName.html('Type ' + d.type_1 + ' & ' + d.type_2 + ' selected');
removeSelection.style('visibility', 'visible');
updatePokemonViz(ar);
});
svg.selectAll('.histo-count')
.data(data)
.enter().append('text')
.attr('class', function (d) {
return 'histo-count ' + d.type_1 + '_' + d.type_2;
})
.attr('y', function (d) {
return y(d.type_1) + y.bandwidth() * 0.9;
})
.attr('x', function (d) {
return x(d.type_2) + x.bandwidth() * 0.5;
})
.style('text-anchor', 'middle')
.style('cursor', 'pointer')
.style('fill', function (d) {
if (d.count > 30) {
return '#fff'
} else {
return '#000'
}
})
.style('visibility', 'hidden')
.text(function (d) {
return d.count;
})
.on('mouseenter', function (d) {
d3.select(this)
.style('visibility', 'visible');
// d3.selectAll('.dot')
// .style('opacity', 0.1)
// d3.selectAll('.types_'+d.type_1+'_'+d.type_2)
// .style('opacity', 1)
})
.on('mouseout', function () {
d3.select(this)
.style('visibility', 'hidden');
// d3.selectAll('.dot')
// .style('opacity', 0.5)
})
.on('click', function (d) {
var ar = reduceData(pokemon_data, d.type_1, d.type_2);
selectionName.html('Type ' + d.type_1 + ' & ' + d.type_2 + ' selected');
removeSelection.style('visibility', 'visible');
updatePokemonViz(ar);
});
}
function updatePokemonViz(data) {
x.domain([d3.min(data, function (d) {
return d.attack * 0.9;
}), d3.max(data, function (d) {
return d.attack * 1.1;
})]);
y.domain([d3.min(data, function (d) {
return d.defense * 0.9;
}), d3.max(data, function (d) {
return d.defense * 1.1;
})]);
r.domain([d3.min(data, function (d) {
return d.hp * 0.9;
}), d3.max(data, function (d) {
return d.hp * 1.1;
})]);
gy.transition()
.duration(1500)
.call(yAxis);
gx.transition()
.duration(1500)
.call(xAxis);
var dots = g.selectAll('.dot')
.data(data);
dots.exit().remove();
dots.enter().append('circle')
.style('fill', 'rgba(63, 0, 125, 0.5)')
.merge(dots)
.attr('class', function(d){
return 'dot types_'+d.type_1+'_'+d.type_2;
})
.transition()
.duration(1500)
.attr('r', function (d) {
return r(d.hp);
})
.attr('cy', function (d) {
return y(d.defense);
})
.attr('cx', function (d) {
return x(d.attack);
})
}
function reduceData(data, type1, type2) {
var array = [];
data.forEach(function (d) {
if (d.type_1 === type1 && d.type_2 === type2) {
array.push(d);
}
});
return array;
}
};
</script>
</body>
</html> | drensove/workspace2017-d3-js | W09_coordinated_views/index.html | HTML | mit | 8,821 |
import numpy as np
import pygame
import src.camera.modes.Follow as Follow
import src.camera.modes.Static as Static
import src.camera.modes.Tile as Tile
modes = {
"Static": Static.get_bounding_box,
"Follow": Follow.get_bounding_box,
"Tile": Tile.get_bounding_box
}
class Camera:
def __init__(self, screen):
self.screen = screen
self.level = None
self.target = None
self.settings = None
def set_settings(self, settings):
self.settings = settings
def set_level(self, level):
self.level = level
self.target = None
def get_bounding_box(self):
if self.target is None and "target" in self.settings:
self.target = self.level.get_entities(self.settings["target"])[0]
return modes[self.settings["mode"]](self.settings, self.screen, self.level, self.target)
def render_background(self, background, bounding_box=None):
parallax_amount = 0
try:
parallax_amount = float(self.settings['backgroundparallaxamount'])
except KeyError:
pass
if background is None:
return
if bounding_box is None:
bounding_box = self.get_bounding_box()
screen_size = np.array(self.screen.get_size())
parallax_scale_factor = (1 + parallax_amount / 100)
size = parallax_scale_factor * np.array(screen_size)
bounding_box_center = np.mean((bounding_box.x_interval, bounding_box.y_interval), 1)
screen_size_in_blocks = screen_size / (bounding_box.block_width, bounding_box.block_height)
level_size_in_blocks = self.level.map_shape[::-1]
parallax_padding = size - size / parallax_scale_factor
pos = -0.5 * (bounding_box_center / np.max((level_size_in_blocks, screen_size_in_blocks))) * parallax_padding
sprite = pygame.transform.scale(background, size.astype(int))
self.screen.blit(sprite, pos)
# pre-compute and reuse bounding_box for performance gain
def render(self, renderable, bounding_box=None):
if bounding_box is None:
bounding_box = self.get_bounding_box()
x, _ = bounding_box.x_interval
y, _ = bounding_box.y_interval
pos = ((renderable.x - x) * bounding_box.block_width, (renderable.y - y) * bounding_box.block_height)
size = (int(renderable.width * bounding_box.block_width), int(renderable.height * bounding_box.block_height))
renderable.draw(self.screen, pos, size)
def clear(self):
self.screen.fill((100, 100, 100))
| cthit/CodeIT | src/camera/Camera.py | Python | mit | 2,564 |
// Manipulating JavaScript Objects
// I worked on this challenge: [by myself, with: ]
// There is a section below where you will write your code.
// DO NOT ALTER THIS OBJECT BY ADDING ANYTHING WITHIN THE CURLY BRACES!
var terah = {
name: "Terah",
age: 32,
height: 66,
weight: 130,
hairColor: "brown",
eyeColor: "brown"
}
// __________________________________________
// Write your code below.
adam = {
name: "Adam",
};
terah.spouse = adam;
terah.weight = 125;
delete terah.eyeColor;
adam.spouse = terah;
terah.children = new Object();
terah.children.carson = new Object();
terah.children.carson.name = "Carson";
terah.children.carter = new Object();
terah.children.carter.name = "Carter";
terah.children.colton = new Object();
terah.children.colton.name = "Colton";
adam.children = terah.children;
// __________________________________________
// Reflection: Use the reflection guidelines
// What tests did you have trouble passing? What did you do to make it pass? Why did that work?
// The three-level-nested object is the one I had trouble passing. For one thing I didn't understand out to structure it when reading the instruction.
// Also the property assignment was a bit confusing after the object is three-level nested.
// I read the code for testing and understood the structure. Then simply used the dot notation to do property assignment.
// How difficult was it to add and delete properties outside of the object itself?
// It is very simple. To add simply use assignment. To remove, use "delete" function.
// What did you learn about manipulating objects in this challenge?
// Objects can be nested and correlated in a very complex way.
// Objects can be treated as class and are quite volatile.
// __________________________________________
// Driver Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(adam instanceof Object),
"The value of adam should be an Object.",
"1. "
)
assert(
(adam.name === "Adam"),
"The value of the adam name property should be 'Adam'.",
"2. "
)
assert(
terah.spouse === adam,
"terah should have a spouse property with the value of the object adam.",
"3. "
)
assert(
terah.weight === 125,
"The terah weight property should be 125.",
"4. "
)
assert(
terah.eyeColor === undefined || null,
"The terah eyeColor property should be deleted.",
"5. "
)
assert(
terah.spouse.spouse === terah,
"Terah's spouse's spouse property should refer back to the terah object.",
"6. "
)
assert(
(terah.children instanceof Object),
"The value of the terah children property should be defined as an Object.",
"7. "
)
assert(
(terah.children.carson instanceof Object),
"carson should be defined as an object and assigned as a child of Terah",
"8. "
)
assert(
terah.children.carson.name === "Carson",
"Terah's children should include an object called carson which has a name property equal to 'Carson'.",
"9. "
)
assert(
(terah.children.carter instanceof Object),
"carter should be defined as an object and assigned as a child of Terah",
"10. "
)
assert(
terah.children.carter.name === "Carter",
"Terah's children should include an object called carter which has a name property equal to 'Carter'.",
"11. "
)
assert(
(terah.children.colton instanceof Object),
"colton should be defined as an object and assigned as a child of Terah",
"12. "
)
assert(
terah.children.colton.name === "Colton",
"Terah's children should include an object called colton which has a name property equal to 'Colton'.",
"13. "
)
assert(
adam.children === terah.children,
"The value of the adam children property should be equal to the value of the terah children property",
"14. "
)
console.log("\nHere is your final terah object:")
console.log(terah) | nathanluo112/phase-0 | week-7/manipulating_objects.js | JavaScript | mit | 3,971 |
<?php
namespace Site\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ModuleCommentCommentsType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('img', 'text', array(
'required' => true,
'label' => 'backend.module_comment_comments.img'
))
->add('file', 'file', array(
'required' => true,
'label' => 'backend.module_comment_comments.file'
))
->add('text', 'textarea', array(
'required' => true,
'label' => 'backend.module_comment_comments.text',
"attr" => array(
"class" => "ckeditor"
)
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Site\MainBundle\Entity\ModuleCommentComments',
'translation_domain' => 'menu',
'csrf_protection' => false
));
}
/**
* @return string
*/
public function getName()
{
return '';
}
}
| olegfox/landing | src/Site/MainBundle/Form/ModuleCommentCommentsType.php | PHP | mit | 1,494 |
# frozen_string_literal: true
class CreateComments < ActiveRecord::Migration[4.2]
def change
create_table :comments do |t|
t.text :content
t.integer :user_id
t.string :commentable_type
t.integer :commentable_id
t.timestamps
end
end
end
| BlueRidgeLabs/kimball | db/migrate/20130423195105_create_comments.rb | Ruby | mit | 280 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.6.0_18) on Thu Dec 18 17:18:13 PST 2014 -->
<title>BasicComboPopup.ItemHandler (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.swing.plaf.basic.BasicComboPopup.ItemHandler class">
<meta name="keywords" content="itemStateChanged()">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="BasicComboPopup.ItemHandler (Java Platform SE 7 )";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/BasicComboPopup.ItemHandler.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.InvocationMouseMotionHandler.html" title="class in javax.swing.plaf.basic"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.ListDataHandler.html" title="class in javax.swing.plaf.basic"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/swing/plaf/basic/BasicComboPopup.ItemHandler.html" target="_top">Frames</a></li>
<li><a href="BasicComboPopup.ItemHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">javax.swing.plaf.basic</div>
<h2 title="Class BasicComboPopup.ItemHandler" class="title">Class BasicComboPopup.ItemHandler</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li><a href="../../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</a></li>
<li>
<ul class="inheritance">
<li>javax.swing.plaf.basic.BasicComboPopup.ItemHandler</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../java/awt/event/ItemListener.html" title="interface in java.awt.event">ItemListener</a>, <a href="../../../../java/util/EventListener.html" title="interface in java.util">EventListener</a></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.html" title="class in javax.swing.plaf.basic">BasicComboPopup</a></dd>
</dl>
<hr>
<br>
<pre>protected class <span class="strong">BasicComboPopup.ItemHandler</span>
extends <a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a>
implements <a href="../../../../java/awt/event/ItemListener.html" title="interface in java.awt.event">ItemListener</a></pre>
<div class="block">This listener watches for changes to the selection in the
combo box.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier</th>
<th class="colLast" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected </code></td>
<td class="colLast"><code><strong><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.ItemHandler.html#BasicComboPopup.ItemHandler()">BasicComboPopup.ItemHandler</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.ItemHandler.html#itemStateChanged(java.awt.event.ItemEvent)">itemStateChanged</a></strong>(<a href="../../../../java/awt/event/ItemEvent.html" title="class in java.awt.event">ItemEvent</a> e)</code>
<div class="block">Invoked when an item has been selected or deselected by the user.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.<a href="../../../../java/lang/Object.html" title="class in java.lang">Object</a></h3>
<code><a href="../../../../java/lang/Object.html#clone()">clone</a>, <a href="../../../../java/lang/Object.html#equals(java.lang.Object)">equals</a>, <a href="../../../../java/lang/Object.html#finalize()">finalize</a>, <a href="../../../../java/lang/Object.html#getClass()">getClass</a>, <a href="../../../../java/lang/Object.html#hashCode()">hashCode</a>, <a href="../../../../java/lang/Object.html#notify()">notify</a>, <a href="../../../../java/lang/Object.html#notifyAll()">notifyAll</a>, <a href="../../../../java/lang/Object.html#toString()">toString</a>, <a href="../../../../java/lang/Object.html#wait()">wait</a>, <a href="../../../../java/lang/Object.html#wait(long)">wait</a>, <a href="../../../../java/lang/Object.html#wait(long,%20int)">wait</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="BasicComboPopup.ItemHandler()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>BasicComboPopup.ItemHandler</h4>
<pre>protected BasicComboPopup.ItemHandler()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="itemStateChanged(java.awt.event.ItemEvent)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>itemStateChanged</h4>
<pre>public void itemStateChanged(<a href="../../../../java/awt/event/ItemEvent.html" title="class in java.awt.event">ItemEvent</a> e)</pre>
<div class="block"><strong>Description copied from interface: <code><a href="../../../../java/awt/event/ItemListener.html#itemStateChanged(java.awt.event.ItemEvent)">ItemListener</a></code></strong></div>
<div class="block">Invoked when an item has been selected or deselected by the user.
The code written for this method performs the operations
that need to occur when an item is selected (or deselected).</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../java/awt/event/ItemListener.html#itemStateChanged(java.awt.event.ItemEvent)">itemStateChanged</a></code> in interface <code><a href="../../../../java/awt/event/ItemListener.html" title="interface in java.awt.event">ItemListener</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/BasicComboPopup.ItemHandler.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><strong>Java™ Platform<br>Standard Ed. 7</strong></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.InvocationMouseMotionHandler.html" title="class in javax.swing.plaf.basic"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../javax/swing/plaf/basic/BasicComboPopup.ListDataHandler.html" title="class in javax.swing.plaf.basic"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/swing/plaf/basic/BasicComboPopup.ItemHandler.html" target="_top">Frames</a></li>
<li><a href="BasicComboPopup.ItemHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://docs.oracle.com/javase/7/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> <a href="../../../../../legal/cpyr.html">Copyright</a> © 1993, 2015, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
| fbiville/annotation-processing-ftw | doc/java/jdk7/javax/swing/plaf/basic/BasicComboPopup.ItemHandler.html | HTML | mit | 12,364 |
# audio-tagger
Javascript application for audio tagging and management for Community
Radio
Features:
Get audio files from Server
Api request returns a collection of urls for mp3 files
Api should allow to post uploads
more on that here: https://github.com/janastu/da-server
HTML5 audio player to load and play audio
Add tags to the Audio file - Should include text and non-text input(at this
time thinking about emoji).
Tag Management:
Set Tags: A set of pre-defined tags, whose definition should help in
workflow management.
Suggested Tags: Community suggested tags
Social Networking features like, unline and share audio.
Installation
Python virtualenv requires
Install dependencies
python setup.py install
SwtStore is used for User authentication and Tag, feedback storing
Check out on how to set up the store,
https://github.com/janastu/swtstore
copy sampleConfig.py to config.py
and fill all the details
python servers/audioApp.py
Need help with documentation, testing!
| janastu/audio-tagger | README.md | Markdown | mit | 985 |
// Inspiration from XQuery, https://github.com/nkallen/jquery-database , and http://www.sitepen.com/blog/2008/07/16/jsonquery-data-querying-beyond-jsonpath/
// I also came across http://plugins.jquery.com/project/jLINQ (and http://www.hugoware.net/Projects/jLinq ) and http://jsinq.codeplex.com/ after starting this work
// Flower is inspired by the FLWOR expressions of XQuery (For, Let, Where, Order by, Return)
// Methods are prefixed by '$' to avoid use of JavaScript keywords (e.g., for, let, return)
// (JS-pre-declared) Variables could be implementable without need for "this." in subsequent methods by using eval() and strings, but less JS-like (and may as well do XQuery parser in that case) and also less secure
// Fix: only accept where, order by, and return if a let or for has been called, and require where, order by, and return in that order
function JQFlower (opts) {
if (!(this instanceof JQFlower)) {
return new JQFlower(opts);
}
this.depth = 0;
this.forMap = {children:{}};
if (opts) {
this.$declaration(opts);
}
}
// Allows invoking on an explicit function separately though it is unnecessary
// as this function is also auto-invoked by the constructor
JQFlower.prototype.$declaration = function (opts) {
/* for (var opt in opts) {
} */
return this;
};
JQFlower.prototype.$ = JQFlower.prototype.$wrapper = function () {
return this;
};
JQFlower.prototype.$for = function (query) {
for (var key in query) {
query = query[key];
break;
}
this.key = key;
this.query = query;
this.vrs = '';
if (typeof query === 'function') {
query.call(this); // Continue the FLWOR chain asynchronously
}
};
JQFlower.prototype.$at = function (vrs) {
return this;
};
JQFlower.prototype.$let = function (vrs) {
if (typeof vrs === 'function') {
vrs = vrs();
}
for (var p in vrs) {
this.vrs += 'var ' + p + '=' + vrs[p] + ';';
}
return this;
};
JQFlower.prototype.$where = function (__clause__) {
// Fix: filter down this.key
eval(this.vrs);
this.nodes = this.nodes.querySelectorAll(__clause__);
return this;
};
JQFlower.prototype.$orderBy = function (order) {
// Fix: order this.key
eval(this.vrs);
return this;
};
JQFlower.prototype.$return = function (cb) {
if (typeof cb === 'function') {
var scope = {};
scope[this.key] = document.querySelectorAll(this.query);
return cb.call(scope);
}
var nodes = document.querySelectorAll(this.query);
for (var i=0; i < nodes.length; i++) {
eval('var '+this.key + '= nodes[i];' +this.vrs + ';' + cb);
}
};
// Branch off into domain-specific functions (and associated with constant strings?)
// Fix: define this on JQFlower, unless a 'global' declaration is made
// Make JSON-specific ones, jQuery-specific (e.g., filter()), etc.
// XQuery-like element converter
function string (el) {
if (el.length) {
var content = '';
for (var i = 0; i < el.length; i++) {
content += el[i].textContent;
}
return content;
}
return el.textContent;
}
// For users who don't want jQuery
var $in = function queryAll (node, selector) {
if (selector) {
return [].slice.call(node.querySelectorAll(this.query));
}
else {
return [].slice.call(document.querySelectorAll(this.query));
}
};
var queryAll = $in;
| brettz9/jhtml | SAJJ/js-xquery-xsl/jqflower.js | JavaScript | mit | 3,443 |
package main
import "fmt"
import "math/cmplx"
var c, python, java bool
func add (x int, y int) int {
return x + y
}
func divide (divr int, divd int) (quot int, rem int) {
quot = divd / divr
rem = divd % divr
useless := 1
useless = useless + 16
fmt.Println(useless)
return
}
func swap (a string, b string) (string, string) {
return b, a
}
func main () {
var i int
var c_128 complex128
const t_or_f = true
u_64 := 1
c_128 = cmplx.Sqrt(-5 + 12i)
fmt.Println("Hello World")
a, b := swap("Hello", "World")
fmt.Println(a, b)
fmt.Println(add(5, 2))
fmt.Println(divide(5, 2))
fmt.Println(i, c, python, java)
//Printf
fmt.Printf("Type : %T Value: %v\n", i, i)
fmt.Printf("Type : %T Value: %v\n", u_64, u_64)
fmt.Printf("Type : %T Value: %v\n", c_128, c_128)
fmt.Printf("Type : %T Value: %v\n", t_or_f, t_or_f)
}
| rishdas/golang-pract | functions/functions.go | GO | mit | 838 |
<!DOCTYPE html><html lang="en"><head><title>src/nor</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../"><meta name="groc-document-path" content="src/nor"><meta name="groc-project-path" content="src/nor.js"><link rel="stylesheet" type="text/css" media="all" href="../assets/style.css"><script type="text/javascript" src="../assets/behavior.js"></script><body><div id="meta"><div class="file-path">src/nor.js</div></div><div id="document"><div class="segment"><div class="comments "><div class="wrapper"><p>Copyright 2015-2018 FormBucket LLC</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">import</span> not <span class="hljs-keyword">from</span> <span class="hljs-string">"./not"</span>;
<span class="hljs-keyword">import</span> or <span class="hljs-keyword">from</span> <span class="hljs-string">"./or"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nor</span>(<span class="hljs-params">...args</span>) </span>{
<span class="hljs-keyword">return</span> not(or(...args));
}</div></div></div></div></body></html> | FunctionFoundry/functionfoundry | docs/code/src/nor.html | HTML | mit | 1,369 |
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
class StatisticsController extends Controller {
public function home() {
$uId = Auth::id();
return view('statistics.home', compact($uId));
}
}
| arminnh/Programming-project-databases | htdocs/app/Http/Controllers/StatisticsController.php | PHP | mit | 308 |
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_time_zone
protected
def set_time_zone
Time.zone = "America/Boise"
end
end
| blowmage/pairwithme | app/controllers/application_controller.rb | Ruby | mit | 183 |
package com.github.joelgodofwar.sps.api;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Usage:
* <li>String msg = Ansi.Red.and(Ansi.BgYellow).format("Hello %s", name)</li>
* <li>String msg = Ansi.Blink.colorize("BOOM!")</li>
*
* Or, if you are adverse to that, you can use the constants directly:
* <li>String msg = new Ansi(Ansi.ITALIC, Ansi.GREEN).format("Green money")</li>
* Or, even:
* <li>String msg = Ansi.BLUE + "scientific"</li>
*
* NOTE: Nothing stops you from combining multiple FG colors or BG colors,
* but only the last one will display.
*
* @author dain
*
*/
public final class Ansi {
// Color code strings from:
// http://www.topmudsites.com/forums/mud-coding/413-java-ansi.html
public static final String RESET = "\u001B[0m";
public static final String HIGH_INTENSITY = "\u001B[1m";
public static final String LOW_INTENSITY = "\u001B[2m";
public static final String HighIntensity = HIGH_INTENSITY;
public static final String BOLD = HighIntensity;
public static final Ansi LowIntensity = new Ansi(LOW_INTENSITY);
public static final Ansi Normal = LowIntensity;
public static final String ITALIC = "\u001B[3m";
public static final String UNDERLINE = "\u001B[4m";
public static final String BLINK = "\u001B[5m";
public static final String RAPID_BLINK = "\u001B[6m";
public static final String REVERSE_VIDEO = "\u001B[7m";
public static final String INVISIBLE_TEXT = "\u001B[8m";
public static final String BLACK = BOLD + "\u001B[30m";
public static final String RED = BOLD + "\u001B[31m";
public static final String GREEN = BOLD + "\u001B[32m";
public static final String YELLOW = BOLD + "\u001B[33m";
public static final String BLUE = BOLD + "\u001B[34m";
public static final String MAGENTA = BOLD + "\u001B[35m";
public static final String CYAN = BOLD + "\u001B[36m";
public static final String WHITE = BOLD + "\u001B[37m";
public static final String DARK_BLACK = "\u001B[30m";
public static final String DARK_RED = "\u001B[31m";
public static final String DARK_GREEN = "\u001B[32m";
public static final String DARK_YELLOW = "\u001B[33m";
public static final String DARK_BLUE = "\u001B[34m";
public static final String DARK_MAGENTA = "\u001B[35m";
public static final String DARK_CYAN = "\u001B[36m";
public static final String DARK_WHITE = "\u001B[37m";
public static final String BACKGROUND_BLACK = "\u001B[40m";
public static final String BACKGROUND_RED = "\u001B[41m";
public static final String BACKGROUND_GREEN = "\u001B[42m";
public static final String BACKGROUND_YELLOW = "\u001B[43m";
public static final String BACKGROUND_BLUE = "\u001B[44m";
public static final String BACKGROUND_MAGENTA = "\u001B[45m";
public static final String BACKGROUND_CYAN = "\u001B[46m";
public static final String BACKGROUND_WHITE = "\u001B[47m";
final private String[] codes;
final private String codes_str;
public Ansi(String... codes) {
this.codes = codes;
String _codes_str = "";
for (String code : codes) {
_codes_str += code;
}
codes_str = _codes_str;
}
public Ansi and(Ansi other) {
List<String> both = new ArrayList<String>();
Collections.addAll(both, codes);
Collections.addAll(both, other.codes);
return new Ansi(both.toArray(new String[] {}));
}
public String colorize(String original) {
return codes_str + original + RESET;
}
public String format(String template, Object... args) {
return colorize(String.format(template, args));
}
} | JoelGodOfwar/SinglePlayerSleep | 1.13_2.13.45.D3/src/main/java/com/github/joelgodofwar/sps/api/Ansi.java | Java | mit | 3,573 |
{
callback({
timeRemaining() {
return Infinity;
}
});
}
| stas-vilchik/bdd-ml | data/6181.js | JavaScript | mit | 74 |
# 6.1.0
allows transforms to be ignored throughout the entire bundle
https://github.com/substack/node-browserify/pull/945
# 6.0.3
fixes a bug where module insert-module-globals would trigger too soon and
conflict with other transforms
https://github.com/substack/node-browserify/issues/867
https://github.com/substack/node-browserify/issues/895
https://github.com/substack/node-browserify/issues/855
# 6.0.2
upgrades process to 0.8.0
https://github.com/substack/node-browserify/pull/906
# 6.0.1
respects opts.expose in require()
https://github.com/substack/node-browserify/pull/907
# 6.0.0
resolves source map maths relative to the base url. This should help with more
reproducible builds.
https://github.com/substack/node-browserify/pull/923
# 5.13.1
bails early if opts.basedir is not the correct type
https://github.com/substack/node-browserify/pull/927
# 5.13.0
exposes global browserify options to transforms under opts._flags
https://github.com/substack/node-browserify/pull/910
# 5.12.2
fixes the array form of b.external()
https://github.com/substack/node-browserify/issues/930
# 5.12.1
dedupe deps when fullPaths is on
https://github.com/substack/node-browserify/pull/917
and fixes the crypto tests
# 5.12.0
adds back the array form for add() and require(), with extra places to add
options
# 5.11.2
fixes ignore for relative paths
in https://github.com/substack/node-browserify/issues/896
# 5.11.1
fixes exports across resets, which caused issues for watchify with exports
https://github.com/substack/node-browserify/pull/892
# 5.11.0
adds an implicit dependency on the original module during dedupe
https://github.com/substack/node-browserify/pull/880
# 5.10.1
fixes the command-line client to properly ignore paths that don't match a glob
https://github.com/substack/node-browserify/pull/866
# 5.10.0
adds back support for `.external(b)` on a browserify instance `b`
that was dropped on the v5 refactor
# 5.9.3
buffers the record pipeline phase to start outputting after the first tick
so that user plugins can capture and modify recorder output
# 5.9.2
fixes a bug with using --ignore to exclude node_modules packages on the command-line
https://github.com/substack/node-browserify/pull/845
# 5.9.1
improves the detection for --ignore
# 5.9.0
fixes bug with builtins that load json files (the 'constants' module),
new 'json' pipeline label
https://github.com/substack/module-deps/issues/46
# 5.8.0
allow optional extensions in bin/args
# 5.7.0
re-instates transforms after a reset and fixes exposing the transform events
properly
# 5.6.1
makes stream entry files deterministic
# 5.6.0
adds 'package' events from module-deps when a package.json file is read
# 5.5.0
adds back the `'bundle'` event and copies over options correctly to reset()
# 5.4.2
adds a note about derequire in standalone mode to the readme
# 5.4.1
fixes an error with basedir resolving plugins from names
# 5.4.0
also allows opts.plugin from the constructor like transform
# 5.3.0
passes `.file` on stream inputs through to transforms
https://github.com/substack/node-browserify/issues/744
# 5.2.1
sets require() for streams to not just be entry files
# 5.2.0
upgrades crypto-browserify to v3
# 5.1.1
updates --list to always print file paths
# 5.1.0
adds back `.plugin()` which was mistakenly omitted
# 5.0.8
fixes using debug and standalone at the same time
https://github.com/substack/node-browserify/issues/750
# 5.0.7
fixes command-line versions of -u and -x
https://github.com/substack/node-browserify/issues/821
# 5.0.6
test for --bare
# 5.0.5
fix for detectGlobals, --bare
https://github.com/substack/node-browserify/issues/803
# 5.0.4
fixes --no-bundle-external with globals
https://github.com/substack/node-browserify/issues/828
# 5.0.3
upgrades insert-module-globals to fix
https://github.com/substack/node-browserify/issues/834
# 5.0.2
fixes the changelog link https://github.com/substack/node-browserify/pull/835
# 5.0.1
adds an untracked test
# 5.0.0
At a glance:
* extensible internal labeled-stream-splicer pipeline
* bundle() - no longer accepts `opts`, callback gets a buffer
* b.deps(), b.pack(), opts.pack, opts.deps are gone
* can call bundle() multiple times on the same instance
* a better --noparse matcher
* id labeling integer index based instead of hash based
* derequire removed for performance reasons
* .external(bundle) has been removed (for now)
* semicolon at end of output
* hashing is gone so `expose: true` or explicit expose id is required for doing
multi-export bundles
In more depth: [doc/changelog/5_0.markdown](doc/changelog/5_0.markdown).
# 4.2.3
reverts 4.2.2 due to breaking some existing use-cases
# 4.2.2
fixes a bug applying transforms to symlinked files by resolving the realpath
first https://github.com/substack/node-browserify/pull/831
# 4.2.1
SECURITY NOTICE
Make sure your installation of browserify is using [email protected] or
later. there was a security vulnerability where a malicious file could
execute code when browserified.
The vulnerability involves breaking out of `Function()`, which was used to
check syntax for more informative errors. In node 0.10, `Function()` seems
to be implemented in terms of `eval()`, so malicious code can execute even
if the function returned by `Function()` was never called. node 0.11 does
not appear to be vulnerable.
Thanks to Cal Leeming [[email protected]]
for discovering and disclosing this bug!
# 4.2.0
upgrades http-browserify, crypto-browserify, and sets more versions to float
with ^ semvers
# 4.1.11
fixes a bug with transform argument handling https://github.com/substack/node-browserify/pull/795
# 4.1.10
upgrades browser-resolve to get opts.path fixes https://github.com/defunctzombie/node-browser-resolve/pull/43
# 4.1.9
upgrades resolve to fix relative NODE_PATH paths https://github.com/substack/node-resolve/pull/46
# 4.1.8
bumps the module-deps version to get an ordering bugfix https://github.com/substack/module-deps/pull/39 https://github.com/substack/node-browserify/pull/774
# 4.1.7
fixes ignoreMissing when set in the constructor https://github.com/substack/node-browserify/pull/785
# 4.1.6
emits the 'id' event on the correct instance https://github.com/substack/node-browserify/pull/780
# 4.1.5
added this document
# 4.1.4
fixes a bug in `ie<=8` support for querystring https://github.com/substack/node-browserify/issues/764
# 4.1.2
upgrades umd to fix some issues with --standalone https://github.com/substack/node-browserify/pull/714
# 4.1.1
makes deps() behave more like bundle() https://github.com/substack/node-browserify/issues/757 and fixes global transform precedence https://github.com/substack/node-browserify/issues/759
# 4.1.0
upgrades the version of buffer to ^2.3.0
# 4.0
4.0 is hot off the presses. See [doc/changelog/4_0.markdown].
# 3.46.1
fixes a bug exposing the host path of the process module in the bundle output https://github.com/substack/insert-module-globals/pull/32
# 3.46.0
allows array arguments in b.require(), b.add(), and b.external() https://github.com/substack/node-browserify/pull/742 from @spacepluk
# 3.45.0
renders complete stack traces where before they were getting truncated https://github.com/substack/node-browserify/pull/741 patch from @secoif
# 3.44.2
slims down the dependency payload by 20M https://github.com/substack/node-browserify/pull/736
# 3.44.1
fixes the recursion error many people were getting https://github.com/substack/node-browserify/pull/713 Thanks to @MattMcKegg for isolating the bug!
# 3.44.0
upgrades module-deps to 1.10.0 to make all the packageFilter dir argument pathways are consistent
# 3.43.0
lets b.transform(opts, t) args to be swapped around since opts is more common as a last argument
# 3.42.0
passes through the dir parameter in opts.packageFilter from module-deps 1.10.0 https://github.com/substack/node-browserify/pull/731
# 3.41.0
has an option to disable external files, making it easier to run bundles in node for code coverage https://github.com/substack/node-browserify/pull/672
# 3.40.4
makes --list work again https://github.com/substack/node-browserify/pull/727
# 3.40.3
merges a patch for piping via stdin and --require at the same time https://github.com/substack/node-browserify/pull/728
# 3.40.2
upgrades module-deps to fix --list for $NODE_PATH https://github.com/substack/node-browserify/issues/726
# 3.40.1
upgrades module-deps to get this packageTransform bugfix https://github.com/substack/module-deps/pull/32
# 3.40.0
modifies the behavior of opts.builtins to be more useful and intuitive https://github.com/substack/node-browserify/pull/717
# 3.39.0
adds a zlib that has parity with node https://github.com/substack/node-browserify/pull/721
# 3.38.0
upgrades derequire which uses esprima-fb https://github.com/substack/node-browserify/pull/710
# 3.37.2
adds 'close' events back to the bundle stream. This should fix some issues with watchify.
# 3.37.1
fixes a bug with through being required in the bin/cmd.js instead of through2
# 3.37.0
also reverts that require('process') thing which was mistakenly briefly put in the builtins list
# 3.37.0
gives streams2 semantics for bundle() https://github.com/substack/node-browserify/pull/646
# 3.36.1
fixes a dumb bug with ^ for versions that don't work in old npm clients
# 3.36.0
adds require('process') and removes the path resolution for process out of insert-module-globals
# 3.35.0
adds an empty tls stub to the builtins list https://github.com/substack/node-browserify/issues/703
# 3.34.0
fixes a bug with transforms not being applied in deps() https://github.com/substack/node-browserify/pull/708
# 3.33.1
fixes a bug with options in --global-transform on the command-line https://github.com/substack/node-browserify/pull/705
# 3.33.0
fixes parsing errors while maintaining es6 support by switching to esprima-fb https://github.com/substack/node-browserify/issues/698
# 3.32.1
should be easier to shinkwrap and install on windows https://github.com/substack/node-browserify/pull/684
# 3.32.0
adds --full-path and opts.fullPath to always expand ids to full paths https://github.com/substack/node-browserify/pull/668#issuecomment-36586786
# 3.31.2
fixes a bug in the subarg argument parsing for multiple transforms https://github.com/substack/node-browserify/issues/678
# 3.31.1
uses process.cwd() as the default rebase target instead of commondir https://github.com/substack/node-browserify/pull/669#issuecomment-36078282
# 3.31.0
merges https://github.com/substack/node-browserify/pull/669 which should help with more deterministic builds across systems
# 3.30.4
fixes parsing the --insert-global-vars argument properly https://github.com/substack/node-browserify/pull/674
# 3.30.3
fixes exclude globbing in the arg parser https://github.com/substack/node-browserify/pull/676
# 3.30.2
included a fix for --no-builtins for non-wrapped modules https://github.com/substack/node-browserify/pull/666
# 3.30.1
upgrades buffer for a utf8 fix https://github.com/substack/node-browserify/pull/656
# 3.30.0
adds globs for -u, -i, and -x https://github.com/substack/node-browserify/issues/654
# 3.29.1
adds relatively-resolved paths to ignored and excluded files
# 3.29.0
upgrades http-browserify to 1.3.1
# 3.28.2
now always includes the full package.json content in the 'package' event
# 3.28.1
fixes a bug with stream entry order https://github.com/substack/node-browserify/pull/643
# 3.28.0
adds plugins for doing super fancy things like factored bundle output https://github.com/substack/node-browserify#plugins
# 3.27.1
fixes a bug resolving transform modules when browserify is under a symlink
# 3.27.0
adds transform configuration in the package.json browserify.transform field https://github.com/substack/module-deps#packagejson-transformkey
# 3.26.0
you can pass arguments to transforms https://github.com/substack/node-browserify/blob/master/bin/advanced.txt#L67-L77
# 3.25.2
fixes a bug where the transform event didn't fire while IO was pending
# 3.25.1
fixes the transform docs
# 3.25.0
adds 'bundle' and 'transform' events https://github.com/substack/node-browserify#bonbundle-function-bundle-
# 3.24.11
upgrades derequire to 0.6.0. That should be the last piece needed for full es6 syntax support.
# 3.24.10
expands the documentation for the package.json browser and browserify.transform fields https://github.com/substack/node-browserify#packagejson
# 3.24.9
fixes generator syntax and other es6-isms in browserify https://github.com/substack/node-browserify/issues/614
# 3.24.7
fixes noParse, which had accidentally been disabled in the insert-module-global changes and also closes https://github.com/substack/node-browserify/issues/504
# 3.24.6
similar to 3.24.5, 3.24.6 fixes some error reporting propagation from the browserify command
# 3.24.3
fixes how require('buffer').Buffer wasn't the same as implicit Buffer https://github.com/substack/node-browserify/issues/612
# 3.24.2
fixes where the output stream didn't emit "close" in standalone mode https://github.com/substack/node-browserify/pull/608
# 3.24.1
fixes an issue where --standalone combined with expose caused a syntax error https://github.com/substack/node-browserify/issues/489
# 3.24.0
removes require() calls from --standalone so you can require() a standalone bundle again
# 3.23.0
merges this tiny fix returning `this` in noParse() https://github.com/substack/node-browserify/pull/592
# 3.22.0
merges https://github.com/substack/node-browserify/pull/587 which changes the source map prefix from //@ to //#
# 3.21.0
standardizes the module missing error formats to have filename, parent, and type === 'not found' fields
# 3.20.1
has a fix for the case where stdin is implicitly treated as the input stream instead of a file
# 3.20.0
3.20.0 is out: parity with how $NODE_PATH works in node https://github.com/substack/node-browserify/issues/593
# 3.19.1
restores support for node 0.8 by upgrading concat-stream
# 3.0
See [doc/changelog/3_0.markdown](doc/changelog/3_0.markdown).
| zedam/portfolio | node_modules/browserify/changelog.markdown | Markdown | mit | 14,200 |
module Comparisons.Fauxter where
import Control.Category hiding ((>>>), (<<<))
import Control.Applicative
import Prelude hiding ((.), id)
import Melchior.Control
import Melchior.Data.String
import Melchior.Dom
import Melchior.Dom.Events
import Melchior.Dom.Html
import Melchior.Dom.Selectors
import Melchior.Remote.Json
import Melchior.Remote.XHR
import Melchior.Sink
import Melchior.Time
main :: IO ()
main = runDom setupFauxter
setupFauxter :: [Element] -> Dom ()
setupFauxter html = do
initialiseTabs html
container <- Dom $ assuredly $ select (byId "container" . from) html
append container (request GET "/next" $ every second :: Signal Fauxt)
initialiseTabs html = do
links <- Dom $ select (byClass "link" . from) html
clicks <- sequence $ clickListener "innerHTML" <$> links
sequence $ (\click -> return $ (rmClassFromParentSiblings >>> addClassTo >>> (hideSiblings &&& showCurrent)) click) <$> clicks
data Fauxt = Fauxt { author :: String, body :: String }
instance JsonSerialisable Fauxt where
fromJson Nothing = Fauxt "" ""
fromJson (Just x) = Fauxt (def $ getJsonString "author" x) (def $ getJsonString "body" x)
where def Nothing = ""
def (Just x) = x
instance Renderable Fauxt where
render x = stringToJSString $ "<div class='row-fluid marketing'><h4>"++(author x)++"</h4><p>"++(body x)++"</p></div>"
addClassTo :: SF (IO JSString) (IO JSString)
addClassTo s = addSingle <$> s
where addSingle = (\x -> do { cls <- x; elems <- select ((byClass $ jsStringToString cls) . from) root;
return $ map (\y -> addClass "active" $ parentOf y) elems; return cls })
rmClassFromParentSiblings :: Signal (JSString) -> Signal (IO JSString)
rmClassFromParentSiblings s = rmSingle <$> s
where rmSingle = (\x -> do { elems <- select ((byClass $ jsStringToString x) . from) root;
return $ map (\y -> (removeClass "active") y ) $ concatMap (\x -> siblings $ parentOf x) elems; return x })
clickListener s e = createEventedSignalOf (Of $ stringToJSString "jsstring") e (MouseEvt ClickEvt) s
applyById op s = (\x -> x >>= \idS -> op <$> select ((byId $ jsStringToString idS) . from) root) <$> s
hideSiblings = applyById (\e -> UHC.Base.head <$> (\y -> map (addClass "hidden") y) <$> (siblings <$> e))
showCurrent = applyById (\e -> removeClass "hidden" <$> e) | kjgorman/melchior | comparison/fauxter/resources/melchior/application.hs | Haskell | mit | 2,417 |
## A nodejs wrapper for nexmo API
## Installation
```sh
$ meteor add calvert:simple-nexmo
```
## Initialize
After you've installed, you can initial the package by following way:
```js
var nexmo = new Nexmo({
apiKey: 'YOUR_API_KEY',
apiSecret: 'YOUR_API_SECRET',
baseUrl: 'API_BASE_URL',
useSSL: true,
debug: false
});
```
`apiKey`、`apiSecret`: **Required.** You can find them in "API Settings" in [Nexmo Dashboard](https://dashboard.nexmo.com/private/dashboard)
`baseUrl`: **Optional.** Set to rest-sandbox.nexmo.com to test in sandbox (Default: rest.nexmo.com)
`useSSL`: **Optional.** Set to true to use HTTP protocol instead HTTPS (Default: true)
`debug` : **Optional.** Set to true to see debug informations (Default: false)
## Usage
For more information please refer to [simple-nexmo](https://github.com/CalvertYang/simple-nexmo).
## The MIT License (MIT)
> Copyright © 2014 Calvert Yang
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

| CalvertYang/meteor-simple-nexmo | README.md | Markdown | mit | 2,048 |
---
layout: post
title: "简单文字换行算法"
tags: [HTML, JavaScript]
---
很多情况下,平台只支持单行文本的渲染(如HTML5 Canvas),这时就需要手动按照一定的规则对文本进行换行处理。
具体规则如下:
## 1、分组
该过程稍类似于词法分析过程和LL(1)语法分析过程,每次读取一个字符(每个汉字算一个字符),根据当前字符和上一个字符的类型,决定将该字符插入到上一个字符所在组的末尾,还是新建一个组并将该字符插入到新建的分组中。
以下情况当前字符将被添加到上一个字符所在的组中:
* 上一个字符是不能出现在行尾的标点。
* 当前字符是不能出现在行首的标点。
* 当前字符是空白字符(如半角空格、全角空格、tab字符)。
* 当前字符是字母/数字,且上一个字符也是字母/数字。
一般情况下,以下标点是不能出现在行首的(Word中称为“后置标点”):
>!),.:;?]}¨·ˇˉ―‖’”…∶、。〃々〉》」』】〕〗!"'),.:;?]`|}~¢
以下标点是不能出现在行尾的(Word中称为“前置标点”):
>([{·‘“〈《「『【〔〖(.[{£¥
举个例子:对以下文本进行分组
> HTML5的canvas元素使用JavaScript在网页上绘制图像,画布是一个矩形区域。
分组后的结果如下:
`HTML5` `的` `canvas` `元` `素` `使` `用` `JavaScript` `在` `网` `页` `上` `绘` `制` `图` `像,` `画` `布` `是` `一` `个` `矩` `形` `区` `域。`
英文单词被单独归为一组,逗号和句号被放到前一个字符所在的分组中。
后续操作需要对各个分组的宽度进行测量,一般使用平台提供的相关接口(对于HTML5 Canvas,则是`context.measureText()`)。
## 2、拆分超长组
如果某些组去掉尾部空格后的宽度仍然超过了容器宽度,则需要对该组进行强制拆分,否则会导致内容出界、内容显示不全,甚至系统崩溃。
拆分过程如下:
1. 去掉待拆分的组尾部的空格。
2. 从待拆分的组的开头取出字符,并添加到新分组中,直到新分组的宽度超过容器宽度。
3. 把新分组中最后一个字符取出,放回待拆分组的开头。然后把新分组放到待拆分组之前。
4. 重复步骤2、3,直到待拆分组的宽度小于容器宽度。
## 3、确定最终换行结果
1. 取出一个分组,确定当前分组的宽度是否超过当前行的剩余宽度。
2. 如果当前分组的内容是换行符,则另起一行作为当前行并转步骤1。
3. 如果当前分组的宽度大于当前行剩余宽度,则去掉尾部空格后再测量宽度。如果仍然大于当前行剩余宽度,则另起一行作为当前行。
4. 将该分组放到当前行中,当前行剩余宽度减去当前分组的宽度。
5. 重复步骤1-4,直到所有分组都处理完。
## 4、渲染
将分好行的文本按行进行渲染,此时可自行控制行高,以及对齐方式。
## 运用条件
该文字换行算法仅适用于英语、法语、德语等使用拉丁字母的文字,俄语等使用西里尔字母的文字,以及中日韩文字。
| frank-deng/frank-deng.github.io | _posts/2019-07-28-line-folding.md | Markdown | mit | 3,269 |
package OOD.Question8_10;
import java.util.LinkedList;
public class Hash<K, V> {
private final int MAX_SIZE = 5;
LinkedList<Cell<K, V>>[] items;
public Hash() {
items = (LinkedList<Cell<K, V>>[]) new LinkedList[MAX_SIZE];
}
public int hashCodeOfKey(K key) {
return key.toString().length() % items.length;
}
public void put(K key, V value) {
int x = hashCodeOfKey(key);
if (items[x] == null) {
items[x] = new LinkedList<Cell<K, V>>();
}
LinkedList<Cell<K, V>> collided = items[x];
for (Cell<K, V> c : collided) {
if (c.equivalent(key)) {
collided.remove(c);
break;
}
}
Cell<K, V> cell = new Cell<K, V>(key, value);
collided.add(cell);
}
public V get(K key) {
int x = hashCodeOfKey(key);
if (items[x] == null) {
return null;
}
LinkedList<Cell<K, V>> collided = items[x];
for (Cell<K, V> c : collided) {
if (c.equivalent(key)) {
return c.getValue();
}
}
return null;
}
public void debugPrintHash() {
for (int i = 0; i < items.length; i++) {
System.out.print(i + ": ");
LinkedList<Cell<K, V>> list = items[i];
if (list != null) {
for (Cell<K, V> cell : list) {
System.out.print(cell.toString() + ", ");
}
}
System.out.println("");
}
}
}
| Ernestyj/JStudy | src/main/java/OOD/Question8_10/Hash.java | Java | mit | 1,323 |
THEME = theme.sed
FILTER = sed -f mixins.sed | sed -f $(THEME)
install: ~/.nano/syntax.nanorc
install-separate: $(addprefix ~/.nano/syntax/, $(wildcard *.nanorc))
~/.nano/syntax.nanorc: *.nanorc mixins/*.nanorc $(THEME) | ~/.nano/
@cat *.nanorc | $(FILTER) > $@
@grep '^include $@' ~/.nanorc >/dev/null 2>&1 || \
echo 'include $@' >> ~/.nanorc
@echo 'Installed: $@'
~/.nano/syntax/%.nanorc: %.nanorc mixins/*.nanorc $(THEME) | ~/.nano/syntax/
@cat $< | $(FILTER) > $@
@echo 'Installed: $@'
~/.nano/ ~/.nano/syntax/:
@mkdir -p $@
ifeq ($(shell test -f ~/.nanotheme && echo 1),1)
THEME = ~/.nanotheme
endif
# Remove "header" directives if not supported (introduced in nano 2.1.6)
NANOVER = $(shell nano -V | sed -n 's/^.* version \([0-9\.]*\).*/\1/p')
ifeq ($(shell printf "2.1.5\n$(NANOVER)" | sort -nr | head -1),2.1.5)
FILTER += | sed -e '/^header/d'
endif
ifdef TEXT
FILTER += | sed -e 's|^color \(bright\)\{0,1\}black|color \1$(TEXT)|'
endif
ifdef BSDREGEX
FILTER += | sed -e 's|\\<|[[:<:]]|g;s|\\>|[[:>:]]|g'
endif
.PHONY: install install-separate ~/.nano/syntax.nanorc
| mbacho/configfiles | nano/nanorc/nanorc_nanorc/Makefile | Makefile | mit | 1,104 |
<?php
/* Cachekey: cache/stash_default/doctrine/[concrete\core\entity\attribute\setkey$set@[annot]][1]/ */
/* Type: array */
/* Expiration: 2017-03-24T13:47:52+01:00 */
$loaded = true;
$expiration = 1490359672;
$data = array();
/* Child Type: array */
$data['return'] = unserialize(base64_decode('YTozOntpOjA7TzoyMzoiRG9jdHJpbmVcT1JNXE1hcHBpbmdcSWQiOjA6e31pOjE7TzozMDoiRG9jdHJpbmVcT1JNXE1hcHBpbmdcTWFueVRvT25lIjo0OntzOjEyOiJ0YXJnZXRFbnRpdHkiO3M6MzU6IlxDb25jcmV0ZVxDb3JlXEVudGl0eVxBdHRyaWJ1dGVcU2V0IjtzOjc6ImNhc2NhZGUiO047czo1OiJmZXRjaCI7czo0OiJMQVpZIjtzOjEwOiJpbnZlcnNlZEJ5IjtOO31pOjI7TzozMToiRG9jdHJpbmVcT1JNXE1hcHBpbmdcSm9pbkNvbHVtbiI6Nzp7czo0OiJuYW1lIjtzOjQ6ImFzSUQiO3M6MjA6InJlZmVyZW5jZWRDb2x1bW5OYW1lIjtzOjQ6ImFzSUQiO3M6NjoidW5pcXVlIjtiOjA7czo4OiJudWxsYWJsZSI7YjoxO3M6ODoib25EZWxldGUiO047czoxNjoiY29sdW1uRGVmaW5pdGlvbiI7TjtzOjk6ImZpZWxkTmFtZSI7Tjt9fQ=='));
/* Child Type: integer */
$data['createdOn'] = 1489961899;
| drago2308/WaniKani-Classroom | application/files/cache/0fea6a13c52b4d47/25368f24b045ca84/38a865804f8fdcb6/57cd99682e939275/2ddb27c5cdf0b672/745d4c64665be841/49873f75e230b2f4/671517ea8523dd59.php | PHP | mit | 928 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
<link rel="stylesheet" href="css/css.css" type="text/css"/>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div id="app" class="container"></div>
<script src="build.js"></script>
</body>
</html> | xsi640/react_note | work/index.html | HTML | mit | 433 |
import React, {
Component,
PropTypes
} from 'react-native'
/*
^ there is a new format they said (new RN 0.25.1)
where the import is like -->
````
import React, { Component } from 'react'
import {
PropTypes,
StyleSheet,
Dimensions,
Text,
TextInput,
View,
TouchableHighlight
} from 'react-native'
````
(https://github.com/facebook/react-native/releases/tag/v0.25.1)
*/
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Bubble from '../components/Bubble'
import Chat from '../components/Chat'
import ChatCell from '../components/ChatCell'
import AnimatedTextInput from '../components/AnimatedTextInput'
import * as MessageActions from '../actions/message'
import * as ConversationActions from '../actions/conversation'
const mapStateToProps = state => ({
messages: state.message,
conversation: state.conversation
})
function mapDispatchToProps(dispatch) {
return bindActionCreators(Object.assign({}, MessageActions, ConversationActions), dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Chat)
| project-xband/android | src/containers/ChatContainer.js | JavaScript | mit | 1,131 |
class AddOptoutBeforeToPhones < ActiveRecord::Migration
def self.up
add_column :phones, :optout_before, :datetime
end
def self.down
remove_column :phones, :optout_before
end
end
| CarouselSMS/RecessApp | db/migrate/20090501105935_add_optout_before_to_phones.rb | Ruby | mit | 195 |
require 'test_helper'
class UserPageTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| jphacks/KS_1602 | test/models/user_page_test.rb | Ruby | mit | 122 |
{{ template "header.html" . }}
<script src="//cdn.ckeditor.com/4.9.2/standard/ckeditor.js"></script>
<h3>Edit shop category</h3>
<hr>
{{ if .validationError }}
<div class="alert alert-danger" role="alert">
<strong>Error!</strong> {{ .validationError }}
</div>
{{ end }}
<form action="{{ url "subtopic" "admin" "shop" "category" "edit" }}" method="post">
<input type="hidden" name="_csrf" value="{{ .csrfToken }}">
<input type="hidden" name="id" value="{{ .id }}">
<div class="form-group">
<input type="text" class="form-control" name="title" placeholder="Title" {{ if .title }} value="{{ .title }}"{{ end }}>
</div>
<div class="form-group">
<textarea id ="category-text" class="form-control" rows="8" name="text" placeholder="Message" spellcheck="true">{{ .text }}</textarea>
</div>
<button type="submit" class="btn btn-primary" name="action" value="add">Submit</button>
<a class="btn btn-warning" href="{{ url "subtopic" "admin" "shop" }}">Cancel</a>
</form>
{{ template "footer.html" . }}
<script nonce={{ .nonce }}>
CKEDITOR.replace('article-text', {
extraPlugins: 'uploadimage',
imageUploadUrl: '/subtopic/admin/ckeditor/image/upload?_csrf={{ .csrfToken }}',
});
</script> | Raggaer/castro | pages/admin/shop/category/edit/shopcategoryedit.html | HTML | mit | 1,213 |
<?php
namespace Micro\Container;
class Container implements ContainerInterface
{
/**
* @var array
*/
protected $services = [];
/**
* @var array
*/
protected $resolved = [];
/**
* @var array
*/
protected $aliases = [];
/**
* @var object
*/
protected $binder;
/**
* @var array of bindings
*/
protected $bindings = [];
/**
* @var array of resolved bindings
*/
protected $ranBinders = [];
/**
* @param array $config
* @param boolean $useAsDefault
*/
public function __construct(array $config = [], $useAsDefault = \true)
{
if ($useAsDefault === \true) {
SharedContainer::setInstance($this);
}
$this->configure($config);
}
/**
* @param array $config
*/
public function configure(array $config)
{
if (isset($config['services'])) {
foreach ($config['services'] as $id => $service) {
$this->set($id, $service);
}
}
if (isset($config['aliases'])) {
foreach ($config['aliases'] as $alias => $service) {
$this->alias($alias, $service);
}
}
}
/**
* (non-PHPdoc)
* @see \Micro\Container\ContainerInterface::get()
*/
public function get($service)
{
if (isset($this->aliases[$service])) {
$service = $this->resolveAlias($service);
}
// call resolved
if (isset($this->resolved[$service]) || \array_key_exists($service, $this->resolved)) {
return $this->resolved[$service];
}
if (!isset($this->services[$service])
&& !\array_key_exists($service, $this->services)
&& isset($this->bindings[$service])
&& !isset($this->ranBinders[$this->bindings[$service]])
&& $this->binder !== \null
) {
$this->ranBinders[$method = $this->bindings[$service]] = \true;
$this->binder->$method();
if (isset($this->resolved[$service]) || \array_key_exists($service, $this->resolved)) {
return $this->resolved[$service];
}
}
if (!isset($this->services[$service]) && !\array_key_exists($service, $this->services)) {
throw new \InvalidArgumentException(sprintf('[' . __METHOD__ . '] Service "%s" not found!', $service), 500);
}
$result = $this->services[$service];
if ($result instanceof \Closure) {
$result = $result($this);
}
if (\is_string($result) && \class_exists($result, \true)) {
$result = new $result;
}
if ($result instanceof ContainerFactoryInterface) {
$result = $result->create($this, $service);
}
if ($result instanceof ContainerAwareInterface) {
$result->setContainer($this);
}
$this->resolved[$service] = $result;
return $result;
}
/**
* (non-PHPdoc)
* @see \Micro\Container\ContainerInterface::set()
*/
public function set($service, $callback, $override = \true)
{
if (isset($this->resolved[$service]) || \array_key_exists($service, $this->resolved)) {
throw new \InvalidArgumentException(sprintf('[' . __METHOD__ . '] Service "%s" is resolved!', $service), 500);
}
if ((isset($this->services[$service]) || \array_key_exists($service, $this->services)) && $override === \false) {
return $this;
}
$this->services[$service] = $callback;
return $this;
}
/**
* (non-PHPdoc)
* @see \Micro\Container\ContainerInterface::has()
*/
public function has($service)
{
if (isset($this->aliases[$service])) {
$service = $this->resolveAlias($service);
}
return isset($this->services[$service]);
}
/**
* @param string $alias
* @param string $service
* @return Container
*/
public function alias($alias, $service)
{
$this->aliases[$alias] = $service;
return $this;
}
/**
* @param sring $alias
* @throws \Exception
* @return string
*/
public function resolveAlias($alias)
{
$stack = [];
while (isset($this->aliases[$alias])) {
if (isset($stack[$alias])) {
throw new \Exception(sprintf(
'Circular alias reference: %s -> %s',
implode(' -> ', $stack),
$alias
));
}
$stack[$alias] = $alias;
$alias = $this->aliases[$alias];
}
return $alias;
}
public function setBindings($binder, array $bindings)
{
$this->binder = $binder;
$this->bindings = $bindings;
}
/**
* (non-PHPdoc)
* @see ArrayAccess::offsetGet()
*/
public function offsetGet($offset)
{
return $this->get($offset);
}
/**
* (non-PHPdoc)
* @see ArrayAccess::offsetSet()
*/
public function offsetSet($offset, $value)
{
return $this->set($offset, $value);
}
/**
* (non-PHPdoc)
* @see ArrayAccess::offsetExists()
*/
public function offsetExists($offset)
{
return $this->has($offset);
}
/**
* (non-PHPdoc)
* @see ArrayAccess::offsetUnset()
*/
public function offsetUnset($offset)
{
}
} | control-corp/micro | library/Micro/src/Container/Container.php | PHP | mit | 5,548 |
/* GIO - GLib Input, Output and Streaming Library
*
* Copyright (C) 2006-2007 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* Author: Alexander Larsson <[email protected]>
*/
#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
#error "Only <gio/gio.h> can be included directly."
#endif
#ifndef __G_IO_ERROR_H__
#define __G_IO_ERROR_H__
#include <glib.h>
#include <gio/gioenums.h>
G_BEGIN_DECLS
/**
* G_IO_ERROR:
*
* Error domain for GIO. Errors in this domain will be from the #GIOErrorEnum enumeration.
* See #GError for more information on error domains.
**/
#define G_IO_ERROR g_io_error_quark()
GQuark g_io_error_quark (void);
GIOErrorEnum g_io_error_from_errno (gint err_no);
#ifdef G_OS_WIN32
GIOErrorEnum g_io_error_from_win32_error (gint error_code);
#endif
G_END_DECLS
#endif /* __G_IO_ERROR_H__ */
| neohung/smallgame | src/gtk/include/win32/glib-2.0/gio/gioerror.h | C | mit | 1,613 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>zfc: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.0 / zfc - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
zfc
<small>
8.6.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-07-31 07:04:33 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-31 07:04:33 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.12 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.7.0 Formal proof management system.
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/zfc"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ZFC"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: Set Theory" "keyword: Zermelo-Fraenkel" "keyword: Calculus of Inductive Constructions" "category: Mathematics/Logic/Set theory" ]
authors: [ "Benjamin Werner" ]
bug-reports: "https://github.com/coq-contribs/zfc/issues"
dev-repo: "git+https://github.com/coq-contribs/zfc.git"
synopsis: "An encoding of Zermelo-Fraenkel Set Theory in Coq"
description: """
The encoding of Zermelo-Fraenkel Set Theory is largely inspired by
Peter Aczel's work dating back to the eighties. A type Ens is defined,
which represents sets. Two predicates IN and EQ stand for membership
and extensional equality between sets. The axioms of ZFC are then
proved and thus appear as theorems in the development.
A main motivation for this work is the comparison of the respective
expressive power of Coq and ZFC.
A non-computational type-theoretical axiom of choice is necessary to
prove the replacement schemata and the set-theoretical AC.
The main difference between this work and Peter Aczel's is that
propositions are defined on the impredicative level Prop. Since the
definition of Ens is, however, still unchanged, I also added most of
Peter Aczel's definition. The main advantage of Aczel's approach is a
more constructive vision of the existential quantifier (which gives
the set-theoretical axiom of choice for free)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/zfc/archive/v8.6.0.tar.gz"
checksum: "md5=52b0642ce8dd701ba162e7068779384f"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-zfc.8.6.0 coq.8.7.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.0).
The following dependencies couldn't be met:
- coq-zfc -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-zfc.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.05.0-2.0.6/released/8.7.0/zfc/8.6.0.html | HTML | mit | 7,842 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>paradoxes: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">dev / paradoxes - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
paradoxes
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-01-23 14:46:44 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-23 14:46:44 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 3 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 2.9.1 Fast, portable, and opinionated build system
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/paradoxes"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Paradoxes"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:reynolds paradox" "keyword:burali forti paradox" "keyword:diaconescu paradox" "keyword:set theory" "keyword:system u" "keyword:inconsistency" "keyword:hurkens paradox" "category:Mathematics/Logic/Foundations" ]
authors: [ "Bruno Barras <>" "Benjamin Werner <>" "Hugo Herbelin <>" "Thierry Coquand <>" ]
bug-reports: "https://github.com/coq-contribs/paradoxes/issues"
dev-repo: "git+https://github.com/coq-contribs/paradoxes.git"
synopsis: "Paradoxes in Set Theory and Type Theory"
description: """
A formalisation of Burali-Forti paradox in system U (the
existence of an ordinal of ordinals is inconsistent), of Diaconescu
paradox (axiom of choice implies excluded-middle), of Reynolds paradox
(there is no set-theoretic model of system F) and Hurkens paradox in
system U (adapted by H. Geuvers to show the inconsistency of
Excluded-Middle in impredicative-Set Calculus of Inductive Constructions)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/paradoxes/archive/v8.5.0.tar.gz"
checksum: "md5=09cae5a778b3cee470f9dc71b5baface"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-paradoxes.8.5.0 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq-paradoxes -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-paradoxes.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| coq-bench/coq-bench.github.io | clean/Linux-x86_64-4.09.1-2.0.6/extra-dev/dev/paradoxes/8.5.0.html | HTML | mit | 7,542 |
import * as React from 'react-native'
const { Alert, Component, StyleSheet, Text, View, TextInput, Image, ScrollView } = React
import * as stateActions from '../../native/actions'
const bindActionCreators = require('redux').bindActionCreators
const connect = require('react-redux').connect
const Button = require('apsl-react-native-button')
const settings = require('../../../config/settings')
@connect(
undefined,
(dispatch) => ({actions: bindActionCreators(stateActions, dispatch)})
)
export default class LoginRender extends Component<any, any> {
constructor(props, context) {
super(props, context)
this.state = {email: '', password: ''}
}
public render() {
return (
<Image
style={styles.container}
source={require('../../../public/nativeBG.jpg')} >
<ScrollView style={styles.inputs}>
<View style={styles.inputContainer}>
<TextInput
style={styles.input}
placeholder='Email'
placeholderTextColor='#BBB'
autoCapitalize='none'
autoCorrect={false}
keyboardType='email-address'
onChangeText={(text) => this.setState({email: text})}
value={this.state.email}
/>
<TextInput
style={styles.input}
placeholder='Password'
placeholderTextColor='#BBB'
password={true}
secureTextEntry={true}
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
/>
<Button
style={styles.buttonStyle} textStyle={styles.textStyle}
onPress={this.logIn.bind(this)}>
LOGIN
</Button>
</View>
<Text style={styles.extraText} onPress={() => this.props.actions.navigatePush('SignUp')}>
Not a member?
</Text>
</ScrollView>
</Image>
)
}
private async logIn() {
if (this.state.email && this.state.password) {
const formData = new FormData()
formData.append('email', this.state.email)
formData.append('password', this.state.password)
formData.append('rememberMe', 'true')
this.props.actions.startMainTransition()
try {
const response = await fetch(`http://${settings.hostname}:${settings.serverPort}/login`, {
method: 'POST',
body: formData,
credentials: 'same-origin'
})
if (response.status !== 200 && response.statusText !== 'OK') {
throw new Error('Invalid credentials.')
}
this.props.actions.setAsAuthenticated()
} catch (e) {
if (e && e.message === 'Network request failed') { this.props.actions.setAsOffline() }
Alert.alert(e.message)
}
this.props.actions.finishMainTransition()
} else { Alert.alert('Invalid credentials.') }
}
}
const styles = StyleSheet.create({
buttonStyle: {
marginTop: 10,
height: 40,
borderColor: '#4CAF50',
borderRadius: 3,
backgroundColor: '#00C853'
},
textStyle: { color: '#fff', fontWeight: 'bold', fontSize: 14},
inputUsername: { marginLeft: 15, width: 20, height: 20 },
extraText: { color: '#fff', textAlign: 'center', backgroundColor: 'transparent', paddingBottom: 20},
container: { flex: 1, width: null, height: null },
inputs: { paddingTop: 80 },
input: {
height: 40,
fontSize: 14,
color: '#444',
borderRadius: 3,
backgroundColor: '#DDD',
padding: 10,
marginBottom: 5,
marginTop: 5,
},
inputContainer: {
backgroundColor: '#fff',
borderRadius: 5,
padding: 10,
margin: 20,
borderWidth: 0,
}
})
| rodrigopivi/PlayApp | src/components/Login/LoginRender.native.tsx | TypeScript | mit | 4,425 |
<?php
/* SensioDistributionBundle:Configurator/Step:secret.html.twig */
class __TwigTemplate_2fd458a4b6c65ab8cf05afd50a94aa088d113fb3b96c70ad737aa9b08dfd30c8 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("SensioDistributionBundle::Configurator/layout.html.twig");
$this->blocks = array(
'title' => array($this, 'block_title'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "SensioDistributionBundle::Configurator/layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = array())
{
echo "Symfony - Configure global Secret";
}
// line 5
public function block_content($context, array $blocks = array())
{
// line 6
echo " ";
$this->env->getExtension('form')->renderer->setTheme((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), array(0 => "SensioDistributionBundle::Configurator/form.html.twig"));
// line 7
echo "
<div class=\"step\">
";
// line 9
$this->env->loadTemplate("SensioDistributionBundle::Configurator/steps.html.twig")->display(array_merge($context, array("index" => (isset($context["index"]) ? $context["index"] : $this->getContext($context, "index")), "count" => (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))));
// line 10
echo "
<h1>Global Secret</h1>
<p>Configure the global secret for your website:</p>
<div class=\"symfony-form-errors\">
";
// line 15
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors');
echo "
</div>
<form action=\"";
// line 17
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_configurator_step", array("index" => (isset($context["index"]) ? $context["index"] : $this->getContext($context, "index")))), "html", null, true);
echo " \" method=\"POST\">
<div class=\"symfony-form-row\">
";
// line 19
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "secret", array()), 'label');
echo "
<div class=\"symfony-form-field\">
";
// line 21
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "secret", array()), 'widget');
echo "
<a href=\"#\" onclick=\"generateSecret(); return false;\" class=\"sf-button\">
<span class=\"border-l\">
<span class=\"border-r\">
<span class=\"btn-bg\">Generate</span>
</span>
</span>
</a>
<div class=\"symfony-form-errors\">
";
// line 30
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "secret", array()), 'errors');
echo "
</div>
</div>
</div>
";
// line 35
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'rest');
echo "
<div class=\"symfony-form-footer\">
<p>
<button type=\"submit\" class=\"sf-button\">
<span class=\"border-l\">
<span class=\"border-r\">
<span class=\"btn-bg\">NEXT STEP</span>
</span>
</span>
</button>
</p>
<p>* mandatory fields</p>
</div>
</form>
<script type=\"text/javascript\">
function generateSecret()
{
var result = '';
for (i=0; i < 32; i++) {
result += Math.round(Math.random()*16).toString(16);
}
document.getElementById('distributionbundle_secret_step_secret').value = result;
}
</script>
</div>
";
}
public function getTemplateName()
{
return "SensioDistributionBundle:Configurator/Step:secret.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 89 => 35, 81 => 30, 69 => 21, 64 => 19, 59 => 17, 54 => 15, 47 => 10, 45 => 9, 41 => 7, 38 => 6, 35 => 5, 29 => 3,);
}
}
| clemsonmatt/Wedding | app/cache/dev/twig/2f/d4/58a4b6c65ab8cf05afd50a94aa088d113fb3b96c70ad737aa9b08dfd30c8.php | PHP | mit | 5,412 |
<!DOCTYPE html>
<html>
<head>
<!-- <script src="../node_modules/scram-engine/filesystem-config.js"></script> -->
<link rel="import" href="components/pg-app/pg-app.html">
</head>
<body>
<script>
console.log("Hello World!");
</script>
<pg-app></pg-app>
</body>
</html>
| scramjs/playground | src/index.html | HTML | mit | 329 |
require 'test_helper'
class CrmEmailTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| pranab/crm_email | test/crm_email_test.rb | Ruby | mit | 155 |
---
layout: category
title: "DevOps"
slug: devops
permalink: /category/devops/
--- | Winbobob/winbobob.github.io | source/categories/category-devops.html | HTML | mit | 82 |
/**
* Copyright (c) 2015 Christopher M. Baker
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var when = require('when');
var aws = require('aws-sdk');
/**
* Creates a trampoline function that forwards arguments to this function.
*
* @returns {function} The trampoline function.
*
*/
Function.prototype.curry = function() {
var fun = this;
var args = [].slice.call(arguments, 0);
return function() {
return fun.apply(this, args.concat([].slice.call(arguments, 0)));
};
};
/**
* Creates a new fluent dynamo instance.
*
* @param {object} AWS The Amazon SDK (optional).
* @returns {object} The fluent dynamo instance.
*
*/
var fluent = module.exports = function(AWS) {
var options = { };
AWS = AWS || aws;
return {
withAccessKeyId: withAccessKeyId.curry(options),
withEndpoint: withEndpoint.curry(options),
withRegion: withRegion.curry(options),
withSecretAccessKey: withSecretAccessKey.curry(options),
createTable: createTable.curry(AWS, options),
deleteTable: deleteTable.curry(AWS, options),
putItem: putItem.curry(AWS, options),
updateItem: updateItem.curry(AWS, options),
deleteItem: deleteItem.curry(AWS, options),
query: query.curry(AWS, options)
};
};
/**
* Sets the access key id for the connection.
*
* @param {object} options The dynamo configuration options.
* @param {string} value The access key id.
* @returns {object} The fluent dynamo instance.
*
*/
function withAccessKeyId(options, value) {
options.accessKeyId = value;
return this;
}
/**
* Sets the endpoint for the connection.
*
* @param {object} options The dynamo configuration options.
* @param {string} value The endpoint.
* @returns {object} The fluent dynamo instance.
*
*/
function withEndpoint(options, value) {
options.endpoint = value;
return this;
}
/**
* Sets the region for the connection.
*
* @param {object} options The dynamo configuration options.
* @param {string} value The region.
* @returns {object} The fluent dynamo instance.
*
*/
function withRegion(options, value) {
options.region = value;
return this;
}
/**
* Sets the secret access key for the connection.
*
* @param {object} options The dynamo configuration options.
* @param {string} value The secrety access key.
* @returns {object} The fluent dynamo instance.
*
*/
function withSecretAccessKey(options, value) {
options.secretAccessKey = value;
return this;
}
/**
* Sends the request to the endpoint.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} method The dynamo method name to invoke.
* @param {object} request The method request to send.
* @returns {Promise} A promise for the response.
*
*/
function send(AWS, options, method, request) {
return when().then(function() {
return when.promise(function(resolve, reject) {
var dynamo = new AWS.DynamoDB(options);
dynamo[method](request, function(error, response) {
if (error) reject(error);
else resolve(response);
});
});
});
}
/**
* Creates a table in dynamo.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} table The name of the table.
* @returns {Promise} A promise for the create table response.
*
*/
function createTable(AWS, options, table) {
var attributes = [ ];
var keys = [ ];
var request = {
AttributeDefinitions: attributes,
KeySchema: keys,
ProvisionedThroughput: { },
TableName: table
};
return {
__proto__: send(AWS, options, 'createTable', request),
withHashKey: withHashKey.curry(attributes, keys),
withRangeKey: withRangeKey.curry(attributes, keys),
withReadCapacity: withReadCapacity.curry(request),
withWriteCapacity: withWriteCapacity.curry(request),
withGlobalSecondaryIndex: withGlobalSecondaryIndex.curry(request),
withLocalSecondaryIndex: withLocalSecondaryIndex.curry(request)
};
}
/**
* Deletes a table in dynamo.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} table The name of the table.
* @returns {Promise} A promise for the create table response.
*
*/
function deleteTable(AWS, options, table) {
var attributes = [ ];
var keys = [ ];
var request = {
TableName: table
};
return {
__proto__: send(AWS, options, 'deleteTable', request)
};
}
/**
* Sets the hash key for the table or index.
*
* @param {array} attributes The attribute definitions.
* @param {array} keys The key schema.
* @param {string} name The name of the hash key.
* @returns {object} The hash key configuration.
*
*/
function withHashKey(attributes, keys, name) {
withKey(keys, 'HASH', name);
return withAttribute.call(this, attributes, name);
}
/**
* Sets the range key for the table or index.
*
* @param {array} attributes The attribute definitions.
* @param {array} keys The key schema.
* @param {string} name The name of the range key.
* @returns {object} The range key configuration.
*
*/
function withRangeKey(attributes, keys, name) {
withKey(keys, 'RANGE', name);
return withAttribute.call(this, attributes, name);
}
/**
* Creates a key in the schema.
*
* @param {array} keys The key schema.
* @param {string} type The key type.
* @param {string} name The name of the key.
* @returns {object} The key configuration.
*
*/
function withKey(keys, type, name) {
keys.push({
AttributeName: name,
KeyType: type
});
return this;
}
/**
* Creates an attribute type configuration.
*
* @param {object} attribute The attribute definition.
* @returns {object} The attribute type configuration.
*
*/
function withType(attribute) {
function asType(type) {
attribute.AttributeType = type;
return this;
}
return {
asType: asType.bind(this),
asString: asType.bind(this, 'S'),
asNumber: asType.bind(this, 'N')
};
}
/**
* Creates an attribute definition.
*
* @param {array} attributes The attribute definitions.
* @param {string} name The name of the attribute.
* @returns {object} The attribute type configuration.
*
*/
function withAttribute(attributes, name) {
for (var i = 0; i < attributes.length; i++) {
if (attributes[i].AttributeName == name) {
return withType.call(this, attributes[i]);
}
}
var attribute = {
AttributeName: name
};
attributes.push(attribute);
return withType.call(this, attribute);
}
/**
* Sets the read capacity for the table or index.
*
* @param {object} request The create table request.
* @param {number} units The read capacity units.
* @returns {Promise} A promise for the create table response.
*
*/
function withReadCapacity(request, units) {
request.ProvisionedThroughput.ReadCapacityUnits = units;
return this;
}
/**
* Sets the write capacity for the table or index.
*
* @param {object} request The create table request.
* @param {number} units The write capacity units.
* @returns {Promise} A promise for the create table response.
*
*/
function withWriteCapacity(request, units) {
request.ProvisionedThroughput.WriteCapacityUnits = units;
return this;
}
/**
* Creates a global secondary index for the table.
*
* @param {object} request The create table request.
* @param {string} name The name of the index.
* @returns {object} The index configuration.
*
*/
function withGlobalSecondaryIndex(request, name) {
var keys = [ ];
var attributes = request.AttributeDefinitions;
var index = {
IndexName: name,
KeySchema: keys,
Projection: { },
ProvisionedThroughput: { }
};
request.GlobalSecondaryIndexes = request.GlobalSecondaryIndexes || [ ];
request.GlobalSecondaryIndexes.push(index);
return {
__proto__: withProjection.call(this, index),
withHashKey: withHashKey.curry(attributes, keys),
withRangeKey: withRangeKey.curry(attributes, keys),
withReadCapacity: withReadCapacity.curry(index),
withWriteCapacity: withWriteCapacity.curry(index)
};
}
/**
* Creates a local secondary index for the table.
*
* @param {object} request The create table request.
* @param {string} name The name of the index.
* @returns {object} The index configuration.
*
*/
function withLocalSecondaryIndex(request, name) {
var keys = [ ];
var attributes = request.AttributeDefinitions;
var index = {
IndexName: name,
KeySchema: keys,
Projection: { }
};
request.LocalSecondaryIndexes = request.LocalSecondaryIndexes || [ ];
request.LocalSecondaryIndexes.push(index);
return {
__proto__: withProjection.call(this, index),
withHashKey: withHashKey.curry(attributes, keys),
withRangeKey: withRangeKey.curry(attributes, keys)
};
}
/**
* Sets the projection for the index.
*
* @param {object} index The index definition.
* @returns {object} The projection configuration.
*
*/
function withProjection(index) {
function project(type) {
index.Projection.ProjectionType = type;
return this;
}
return {
withProjection: project.bind(this),
withAllAttributesProjection: project.bind(this, 'ALL'),
withKeysOnlyProjection: project.bind(this, 'KEYS_ONLY')
};
}
/**
* Creates a new item or replaces an existing item in the table.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} table The name of the table.
* @returns {Promise} A promise for the put item response.
*
*/
function putItem(AWS, options, table) {
var request = {
Item: { },
TableName: table
};
return {
__proto__: send(AWS, options, 'putItem', request),
withAttribute: withAttributeNameAndValue.curry(request.Item),
withCondition: withCondition.curry(request)
};
}
/**
* Creates an item with a value.
*
* @param {object} attributes The collection to append to.
* @param {string} name The name of the attribute.
* @returns {object} The attribute value configuration.
*
*/
function withAttributeNameAndValue(attributes, name) {
function asValue(type, value) {
var attribute = attributes[name] = { };
attribute[type] = value.toString();
return this;
}
return {
asValue: asValue.bind(this),
asString: asValue.bind(this, 'S'),
asNumber: asValue.bind(this, 'N')
};
}
/**
* Creates a condition on an attribute.
*
* @param {object} request The put item request.
* @param {string} name The name of the attribute.
* @returns {object} The condition configuration.
*
*/
function withCondition(request, name) {
function isOperation(operator, type, value) {
var key = ':v' + Object.keys(request.ExpressionAttributeValues).length;
var attribute = request.ExpressionAttributeValues[key] = { };
attribute[type] = value.toString();
if (request.ConditionExpression) {
request.ConditionExpression += ' and ';
}
request.ConditionExpression += name + ' ' + operator + ' ' + key;
return this;
}
request.ConditionExpression = request.ConditionExpression || '';
request.ExpressionAttributeValues = request.ExpressionAttributeValues || { };
return {
isOperation: isOperation.bind(this),
isLessThan: isOperation.bind(this, '<'),
isLessThanNumber: isOperation.bind(this, '<', 'N'),
isLessThanOrEqualTo: isOperation.bind(this, '<='),
isLessThanOrEqualToNumber: isOperation.bind(this, '<=', 'N'),
isGreaterThan: isOperation.bind(this, '>'),
isGreaterThanNumber: isOperation.bind(this, '>', 'N'),
isGreaterThanOrEqualTo: isOperation.bind(this, '>='),
isGreaterThanOrEqualToNumber: isOperation.bind(this, '>=', 'N'),
isEqualTo: isOperation.bind(this, '='),
isEqualToString: isOperation.bind(this, '=', 'S'),
isEqualToNumber: isOperation.bind(this, '=', 'N'),
isNotEqualTo: isOperation.bind(this, '<>'),
isNotEqualToString: isOperation.bind(this, '<>', 'S'),
isNotEqualToNumber: isOperation.bind(this, '<>', 'N')
};
}
/**
* Deletes an item from a table.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} table The name of the table.
* @returns {Promise} A promise for the delete item response.
*
*/
function deleteItem(AWS, options, table) {
var request = {
Key: { },
TableName: table
};
return {
__proto__: send(AWS, options, 'deleteItem', request),
withHashKey: withAttributeNameAndValue.curry(request.Key),
withRangeKey: withAttributeNameAndValue.curry(request.Key)
};
}
/**
* Finds an item in a table.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} table The name of the table.
* @returns {Promise} A promise for the query item response.
*
*/
function query(AWS, options, table) {
var items = [ ];
var request = {
KeyConditions: { },
TableName: table
};
return {
__proto__: queryAndAggregate(AWS, options, items, request),
withIndex: withIndex.curry(request),
withConsistentRead: withConsistentRead.curry(request),
withCondition: withQueryCondition.curry(request.KeyConditions)
};
}
/**
* Sets the index name.
*
* @param {object} request The method request to send.
* @param {string} name The name of the index.
* @returns {Promise} A promise for the query item response.
*
*/
function withIndex(request, name) {
request.IndexName = name;
return this;
}
/**
* Parses the value of a typed attribute.
*
* @param {object} attribute The attribute to parse.
* @returns {object} The parsed attribute value.
*
*/
function parseAttribute(attribute) {
for (var type in attribute) {
var value = attribute[type];
if (type == 'N') {
value = parseFloat(value);
}
return value;
}
}
/**
* Parses a dynamo item.
*
* @param {object} item The item to parse.
* @returns {object} The parsed item.
*
*/
function parseItem(item) {
var parsed = { };
for (var attribute in item) {
parsed[attribute] = parseAttribute(item[attribute]);
}
return parsed;
}
/**
* Searches for items in a table and aggregates partial content.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {array} items The collection to add items to.
* @param {object} request The method request to send.
* @returns {Promise} A promise for the query response.
*
*/
function queryAndAggregate(AWS, options, items, request) {
return send(AWS, options, 'query', request)
.then(function(response) {
response.Items.forEach(function(item) {
items.push(parseItem(item));
});
if (response.LastEvaluatedKey) {
request.ExclusiveStartKey = response.LastEvaluatedKey;
return queryAndAggregate(AWS, options, items, request);
}
return items;
});
}
/**
* Sets the query options to enable consistent reads.
*
* @returns {Promise} A promise for the query response.
*
*/
function withConsistentRead(request) {
request.ConsistentRead = true;
return this;
}
/**
* Creates a query condition used for searching.
*
* @param {object} conditions The query conditions.
* @param {string} name The name of the attribute.
* @returns {object} The query condition configuration.
*
*/
function withQueryCondition(conditions, name) {
function isOperation(operator, type, value) {
var attribute = { };
attribute[type] = value.toString();
conditions[name] = {
AttributeValueList: [ attribute ],
ComparisonOperator: operator
};
return this;
}
return {
isOperation: isOperation.bind(this),
isLessThan: isOperation.bind(this, 'LT'),
isLessThanNumber: isOperation.bind(this, 'LT', 'N'),
isLessThanOrEqualTo: isOperation.bind(this, 'LE'),
isLessThanOrEqualToNumber: isOperation.bind(this, 'LE', 'N'),
isGreaterThan: isOperation.bind(this, 'GT'),
isGreaterThanNumber: isOperation.bind(this, 'GT', 'N'),
isGreaterThanOrEqualTo: isOperation.bind(this, 'GE'),
isGreaterThanOrEqualToNumber: isOperation.bind(this, 'GE', 'N'),
isEqualTo: isOperation.bind(this, 'EQ'),
isEqualToString: isOperation.bind(this, 'EQ', 'S'),
isEqualToNumber: isOperation.bind(this, 'EQ', 'N'),
beginsWith: isOperation.bind(this, 'BEGINS_WITH'),
beginsWithString: isOperation.bind(this, 'BEGINS_WITH', 'S')
};
}
/**
* Updates an existing item in the table.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {string} table The name of the table.
* @returns {Promise} A promise for the update item response.
*
*/
function updateItem(AWS, options, table) {
var request = {
Key: { },
TableName: table
};
return {
__proto__: updateAndReturn(AWS, options, request),
withHashKey: withAttributeNameAndValue.curry(request.Key),
withRangeKey: withAttributeNameAndValue.curry(request.Key),
withCondition: withCondition.curry(request),
withSetExpression: withSetExpression.curry(request),
withRemoveExpression: withRemoveExpression.curry(request),
withNoReturnValues: withReturnValues.curry(request, 'NONE'),
withAllNewReturnValues: withReturnValues.curry(request, 'ALL_NEW'),
withAllOldReturnValues: withReturnValues.curry(request, 'ALL_OLD'),
withUpdatedOldReturnValues: withReturnValues.curry(request, 'UPDATED_OLD'),
withUpdatedNewReturnValues: withReturnValues.curry(request, 'UPDATED_NEW')
};
}
/**
* Updates an item by setting an attribute.
*
* @param {object} request The put item request.
* @param {string} name The name of the attribute.
* @returns {object} The update configuration.
*
*/
function withSetExpression(request, name) {
function asValue(type, value) {
var key = ':v' + Object.keys(request.ExpressionAttributeValues).length;
var attribute = request.ExpressionAttributeValues[key] = { };
attribute[type] = value.toString();
if (request.UpdateExpression) {
request.UpdateExpression += ' ';
}
request.UpdateExpression += 'set ' + name + ' = ' + key;
return this;
}
request.UpdateExpression = request.UpdateExpression || '';
request.ExpressionAttributeValues = request.ExpressionAttributeValues || { };
return {
asValue: asValue.bind(this),
asString: asValue.bind(this, 'S'),
asNumber: asValue.bind(this, 'N')
};
}
/**
* Updates an item by removing an attribute.
*
* @param {object} request The put item request.
* @param {string} name The name of the attribute.
* @returns {object} The update configuration.
*
*/
function withRemoveExpression(request, name) {
if (request.UpdateExpression) {
request.UpdateExpression += ' ';
}
else {
request.UpdateExpression = '';
}
request.UpdateExpression += 'remove ' + name;
return this;
}
/**
* Sets the return values for the update.
*
* @param {object} request The put item request.
* @param {string} type The return values.
* @returns {Promise} A promise for the update item response.
*
*/
function withReturnValues(request, type) {
request.ReturnValues = type;
return this;
}
/**
* Updates an item in the database and returns the values.
*
* @param {object} AWS The Amazon SDK.
* @param {object} options The dynamo configuration options.
* @param {object} request The method request to send.
* @returns {Promise} A promise for the update item response.
*
*/
function updateAndReturn(AWS, options, request) {
return send(AWS, options, 'updateItem', request)
.then(function(response) {
return parseItem(response.Attributes || { });
});
}
| bakerface/fluent-dynamo | lib/fluent.js | JavaScript | mit | 20,676 |
import React, {PropTypes, Component} from 'react';
class TestComponent extends Component {
render() {
return (
<div>
1123123123123123 hahaha small test
</div>
);
}
}
export default TestComponent;
| ssmlee04/electron-react-flux-es6-boiletplate | src/system/components/TestComponent.js | JavaScript | mit | 228 |
---
layout: post
title: DNE 56 - Data Science
home-title: "Data Science"
type: "Pauta"
cast: 267220053-devnaestrada-devnaestrada-56-data-science.mp3
cast-length: "64768108"
cast-time: "00:44:55"
description: "Hoje @raymonsanches conversa com um pouco com @raonyguimaraes, @lerrua e Carlos Baia para falar um pouco sobre esse hype, esse termo tão utilizado que é o DataScience. Venha embarcar conosco nessa aventura para tentar entender um pouco desse grande universo."
soundcloud-id: "267220053"
soundcloud-post-image: "000165645277-x4ginr"
lybsyn-id: "5634220"
sponsors: ["revelo"]
participants:
-
name: Fellipe Azambuja
twitter: femontanha
-
name: Ramon Sanches
twitter: raymonsanches
-
name: Raony Guimaraes
twitter: raonyguimaraes
-
name: Igor Leroy
twitter: lerrua
links:
-
name: "Twitter Raony Guimaraes"
url: "http://twitter.com/raonyguimaraes"
-
name: "Twitter Igor Leroy"
url: "http://twitter.com/lerrua"
-
name: "IBM Watsom"
url: "https://www.youtube.com/watch?v=_Xcmh1LQB9I"
-
name: "The Talking Machines"
url: "http://www.thetalkingmachines.com/blog/"
-
name: "The Data Lake Model is a Powerhouse for Invention"
url: "http://radar.oreilly.com/2015/01/the-data-lake-model-is-a-powerhouse-for-invention.html"
-
name: "Primeiros Passos com Data Science"
url: "http://www.lerrua.com/blog/2016/03/08/primeiros-passos-com-data-science"
-
name: "Awesome DataScience"
url: "https://github.com/okulbilisim/awesome-datascience"
-
name: "Machine Learning"
url: "http://carlosbaia.com/2016/04/22/machine-learning"
---
Hoje @raymonsanches conversa com um pouco com @raonyguimaraes, @lerrua e Carlos Baia para falar um pouco sobre esse hype, esse termo tão utilizado que é o DataScience. Venha embarcar conosco nessa aventura para tentar entender um pouco desse grande universo.
{% include modules/post-extras.html %}
| devnaestrada/devnaestrada.com.br | _posts/2016/2016-06-03-data-science.md | Markdown | mit | 1,942 |
<?php
namespace Blogger\BlogBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Blogger\BlogBundle\Entity\User;
class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;
/**
* {@inheritDoc}
*/
public function setContainer(ContainerInterface $container = null)
{
var_dump('getting container here');
$this->container = $container;
}
/**
* {@inheritDoc}
*/
public function load(ObjectManager $manager)
{
$user1 = new User();
$user1 ->setUsername("daniel");
$user1 ->setSalt(md5(uniqid()));
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user1);
$user1 ->setPassword($encoder->encodePassword('12345', $user1 ->getSalt()));
$user1 ->setEmail("[email protected]");
$manager->persist($user1);
$user2 = new User();
$user2 ->setUsername("rui");
$user2 ->setSalt(md5(uniqid()));
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user2);
$user2 ->setPassword($encoder->encodePassword('12345', $user2 ->getSalt()));
$user2 ->setEmail("[email protected]");
$manager->persist($user2);
$user3 = new User();
$user3 ->setUsername("ricardo");
$user3 ->setSalt(md5(uniqid()));
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user3);
$user3 ->setPassword($encoder->encodePassword('12345', $user3 ->getSalt()));
$user3 ->setEmail("[email protected]");
$manager->persist($user3);
$manager->flush();
}
} | jpcarvalho1992/symblog | src/Blogger/BlogBundle/DataFixtures/ORM/LoadUserData.php | PHP | mit | 1,866 |
# AutoDI
Have a question? [](https://gitter.im/AutoDIContainer/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[](https://www.nuget.org/packages/AutoDI/)
[](https://www.nuget.org/packages/AutoDI.Build/)
[](https://www.nuget.org/packages/AutoDI.AspNetCore/)

AutoDI is both a dependency injection container and a framework to simplify working with dependency injection (DI). It is built on top of the [Microsoft.Extensions.DependencyInjection.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection.Abstractions/) library, and it works very similar to [the way ASP.NET Core handles dependency injection](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection).
AutoDI delivers delivers two excellent features:
1. It is built on [Microsoft.Extensions.DependencyInjection.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection.Abstractions/) library to bring the same flavor of dependency injection enjoyed on ASP.NET Core to other platforms (.NET Framework, WPF, Xamarin, UWP, etc).
2. It generates container registrations _at compile time_ using conventions (of course you can also add more at run-time as well).
See the [wiki](https://github.com/Keboo/AutoDI/wiki) for more details or check out the [Quick Start](https://github.com/Keboo/AutoDI/wiki/Quick-Start) page to get up and running fast.
## Why do I need this?
The goal of this library is to make dependency injection as simple as adding a NuGet package.
In addition to standard constructor dependency injection, it also allows optional constructor parameters that will be resolved when the constructor is invoked.
In a typical DI setup, you can often find objects needing to take in dependencies that the object itself is not using, but needs them to pass into some other object. The bigger and deeper the object model gets, the worse this becomes.
As a specific example, imagine you are inside of class `Foo` and wish to create an instance of `Bar`, but `Bar` has a dependency on `IService`.
In many cases, one of several options can be used:
* Pass a facade to either the DI container or a factory that can create a `Bar`
* Add a dependency on `Foo` to take in an `IService` so that when it needs to create a `Bar` it can simply pass the instance to `Bar`'s constructor.
Though both these options work, they add additional effort. After all, in many cases, when we want a `Bar` we simply call `new Bar();`. AutoDI lets you write exactly that, and moves the dependency resolution inside of `Bar`'s constructor.
This dependency resolution is then forwarded to the DI container to resolve it.
## Does it work with <my favorite DI container / framework>?
Probably.
Take a look at the [AutoDI.Examples](https://github.com/Keboo/AutoDI.Examples) repository for samples. There are examples of adding support for other DI containers as well as simple examples for most frameworks.
*Don't see your favorite listed? I accept PRs.*
### Icon
<img src="https://raw.github.com/Keboo/AutoDI/master/Icons/needle.png" width="64">
[Needle](https://materialdesignicons.com/icon/needle) designed by [Austin Andrews](https://thenounproject.com/prosymbols/) from [Material Design Icons](https://materialdesignicons.com/)
| Keboo/AutoDI | README.md | Markdown | mit | 3,782 |
# Vive Grip Extensions
Event messaging is a powerful tool in Vive Grip that lets you extend and modify fundamental aspects of Vive Grip. In fact, everything that Vive Grip does from grabbing to highlighting occurs through these methods.
The methods are called on the acting controller, its children, and the scene objects involved. The scripts mentioned here are on the right controller's Grip Point in the demo scene. You can enable them in the Inspector to try them out with that controller.
## How do I extend...
### Grabbing
- `ViveGripGrabStart(ViveGrip_GripPoint gripPoint)`
- `ViveGripGrabStop(ViveGrip_GripPoint gripPoint)`
This is sent whenever an object is grabbed or released. `ViveGripExample_ExtendGrab` uses this to enable a toggling grab. If the grip is started and released within the threshold, I manually toggle the grab so that the object isn't dropped.
### Highlighting
- `ViveGripHighlightStart(ViveGrip_GripPoint gripPoint)`
- `ViveGripHighlightStop(ViveGrip_GripPoint gripPoint)`
This is sent whenever object highlighting starts or stops. `ViveGripExample_ExtendHighlight` uses this to highlight the controller as well as the object. It simply captures the base color on starting and lightens it when the controller highlights an object. Note that `ViveGripHighlightStop` is called when the object is grabbed.
Another option would be to manually add `ViveGrip_Highlighter` as it leverages these methods to do the default highlighting for objects. However, it doesn't play nice with the way I fade the example hands in and out. It may be useful to try this in your scene if the conditions are right.
### Touching
- `ViveGripTouchStart(ViveGrip_GripPoint gripPoint)`
- `ViveGripTouchStop(ViveGrip_GripPoint gripPoint)`
This is similar to highlighting but doesn't change when objects are grabbed.
### Interacting
- `ViveGripInteractStart(ViveGrip_GripPoint gripPoint)`
- `ViveGripInteractStop(ViveGrip_GripPoint gripPoint)`
Vive Grip doesn't do anything before sending these messages. You have full control over what happens when using the interaction button.
| vr-sils/pokemon-demo | Assets/ViveGrip/Examples/EXTENSIONS.md | Markdown | mit | 2,096 |
////////////////////////////////////////////////////////////////////////////////
// Entity.cpp
// Furiosity
//
// Created by Bojan Endrovski on 9/13/13.
// Copyright (c) 2013 Bojan Endrovski. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#include "Entity.h"
using namespace Furiosity;
using namespace std;
using namespace tinyxml2;
int Entity::nextValidID = 1;
////////////////////////////////////////////////////////////////////////////////
// Ctor
////////////////////////////////////////////////////////////////////////////////
Entity::Entity() :type(default_entity_type), tag(false)
{
SetID(nextValidID);
}
////////////////////////////////////////////////////////////////////////////////
// Ctor
////////////////////////////////////////////////////////////////////////////////
Entity::Entity(uint ID)
: type(default_entity_type),
tag(false)
{
SetID(ID);
}
////////////////////////////////////////////////////////////////////////////////
// Ctor from xml stettings, this need to point inside the element and
// not on it's root. This alows for the ctor to be used for settings and
// streaming at the same time.
////////////////////////////////////////////////////////////////////////////////
Entity::Entity(const XMLElement* settings)
: type(default_entity_type),
tag(false)
{
// ID
// Handle id - used for streaming a level with hardcoded ID
const char* pID = settings->Attribute("ID");
if (pID)
SetID(atoi(pID));
else
SetID(nextValidID);
// Name
// Set the name for this entity
//string tName(settings->Attribute("name"));
const char* pName = settings->Attribute("name");
if (pName)
name = string(pName);
else
name = "Unknown";
// Type
// Set type - A hacky short cut!
// !!! Do this only if you know what are you doing as it does no checks against
// the world types which are usefull for collision and casting !!!
const char* pType = settings->Attribute("type");
if(pType)
type = atoi(pType);
}
////////////////////////////////////////////////////////////////////////////////
// SetID
// This must be called within each constructor to make sure the ID is set
// correctly. It verifies that the value passed to the method is greater
// or equal to the next valid ID, before setting the ID and incrementing
// the next valid ID
////////////////////////////////////////////////////////////////////////////////
void Entity::SetID(uint val)
{
// Make sure the val is equal to or greater than the next available ID
assert( (val >= nextValidID) );
_ID = val;
nextValidID = _ID + 1;
} | enci/Furiosity | Furiosity/Core/Entity.cpp | C++ | mit | 2,760 |
/**
* @file Automatically generated by barrelsby.
*/
export * from './api.model';
export * from './public-error.model';
export * from './pull-request.model';
export * from './repo.model';
export * from './user.model';
| Kibibit/achievibit | server/src/models/index.ts | TypeScript | mit | 221 |
package gannoy
import "testing"
func TestFreePopEmpty(t *testing.T) {
free := newFree()
id, err := free.pop()
if id != -1 {
t.Errorf("Free pop with empty list should return -1, but %d.", id)
}
if err == nil {
t.Errorf("Free pop with empty list should return error.")
}
}
func TestFreePop(t *testing.T) {
free := newFree()
free.push(1)
free.push(2)
id, err := free.pop()
if id != 2 {
t.Errorf("Free pop should return 2, but %d.", id)
}
if err != nil {
t.Errorf("Free pop should not return error.")
}
}
| monochromegane/gannoy | free_test.go | GO | mit | 527 |
import Test from '../helpers/test';
import itsInvalid from '../itsInvalid';
import itsValid from '../itsValid';
const validData = {
'http://www.example.com': 'test',
};
export default (test: Test) => {
itsInvalid(10, 'not an object', test);
itsInvalid({
http: 'test'
}, 'containing invalid keys', test);
itsValid(validData, test);
};
| LearningLocker/xapi-validation | src/tests/maps/extensions.ts | TypeScript | mit | 350 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class C_RKH extends CI_Controller {
public function index()
{
}
public function lihatJenjang(){
$data = array(
'jenjang' => $this->e_kelompokbelajar->getKelBelajarAll(),
);
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_daftar_jenjang', $data);
}
public function lihatTemaSubtema($id_kel_belajar){
$data = array(
'temasub' => $this->e_tema->getTemaSubRKH($id_kel_belajar) ,
'tahun' => $this->e_tema->getTA() ,
'id_kel_belajar' => $id_kel_belajar ,
);
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_daftar_temasub', $data);
}
public function gantiTA(){
$tahun = $this->input->post('tahun_ajaran');
$id_kel_belajar = $this->input->post('id_kel_belajar');
if ($tahun == "all") {
$this->lihatTemaSubtema($id_kel_belajar);
}
else{
$data = array(
'temasub' => $this->e_tema->getTemaSubtemaTA($tahun, $id_kel_belajar) ,
'tahun' => $this->e_tema->getTA() ,
'id_kel_belajar' => $id_kel_belajar ,
);
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_daftar_temasub', $data);
}
}
public function lihatMinggu($id_subtema){
$data = array(
'hari' => $this->e_subtema->getTemaSubtemaHari($id_subtema),
);
$array = array(
'id_subtema' => $id_subtema
);
$this->session->set_userdata( $array );
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_daftar_hari', $data);
}
public function lihatHari($id_hari){
$data = array(
'detail' => $this->e_hari->getHariDetailHari($id_hari),
'tanggal' => $this->e_hari->getTanggalDetailHari($id_hari),
);
if ($data['detail']) { //ada data
$array = array(
'data_hari' => 1,
'id_hari' => $id_hari
);
$this->session->set_userdata( $array );
$check_tgl = $this->cekTanggalSekarang($data['tanggal']);
if ($check_tgl) { //jika sudah melewati
$array = array(
'aut_hari' => 0
);
$this->session->set_userdata( $array );
}else{ //jika belum melewati
$array = array(
'aut_hari' => 1
);
$this->session->set_userdata( $array );
}
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_data_hari', $data);
}else{
$array = array(
'data_hari' => 0,
'id_hari' => $id_hari
);
$this->session->set_userdata( $array );
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_data_hari');
}
}
public function cekTanggalSekarang($tanggal){
$tanggal_now = date('Y-m-d');
if ($tanggal < $tanggal_now) {
return true;
}else{
return false;
}
}
public function buatDetilHari($id_hari){
$data = array(
'jeniskeg' => $this->e_jeniskeg->getJenisKegAll() ,
'subtema' => $this->e_hari->getSubtemaHari($id_hari) ,
'indikator' => $this->e_indisub->getIndikatorSubtema($this->session->userdata('id_subtema')) ,
'id_hari' => $id_hari ,
);
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_tambah_detilhari', $data);
}
public function tambahDetilHari(){
$this->e_detilhari->setIdHari($this->input->post('id_hari'));
$this->e_detilhari->setIdJenisKeg($this->input->post('id_jenis_keg'));
$this->e_detilhari->setUrutan($this->input->post('urutan'));
$this->e_detilhari->setKegiatan($this->input->post('kegiatan'));
$this->e_detilhari->setMedia($this->input->post('media'));
$this->e_detilhari->setDurasi($this->input->post('durasi'));
$this->e_detilhari->tambahDetilHari();
$id_detilhari = $this->e_detilhari->getIdDetilHari();
$this->e_indisub->setIdDetilhari($id_detilhari);
$this->e_indisub->updateIndiSub($this->input->post('id_indisub'));
$this->session->set_flashdata('info', 'Detil kegiatan telah ditambahkan');
redirect('c_RKH/lihatHari/'.$this->session->userdata('id_hari'),'refresh');
}
public function gantiDetilHari($id_detilhari){
$data = array(
'jeniskeg' => $this->e_jeniskeg->getJenisKegAll() ,
'subtema' => $this->e_hari->getSubtemaHari($this->session->userdata('id_hari')) ,
'indikator' => $this->e_indisub->getIndikatorSubtema($this->session->userdata('id_subtema')) ,
'detilhari' => $this->e_detilhari->getDetilHariIndiSub($id_detilhari) ,
'id_detilhari' => $id_detilhari
);
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_ganti_detilhari', $data);
}
public function perbaruiDetilHari(){
$this->e_detilhari->setIdJenisKeg($this->input->post('id_jenis_keg'));
$this->e_detilhari->setUrutan($this->input->post('urutan'));
$this->e_detilhari->setKegiatan($this->input->post('kegiatan'));
$this->e_detilhari->setMedia($this->input->post('media'));
$this->e_detilhari->setDurasi($this->input->post('durasi'));
$this->e_detilhari->updateDetilHari($this->input->post('id_detilhari'));
if ($this->input->post('id_indisub') != $this->input->post('id_indisub_lama')) {
$this->e_indisub->nullDetilhari($this->input->post('id_detilhari'));
$this->e_indisub->setIdDetilhari($this->input->post('id_detilhari'));
$this->e_indisub->updateIndiSub($this->input->post('id_indisub'));
}
$this->session->set_flashdata('info', 'Detil kegiatan telah dirubah');
redirect('c_RKH/lihatHari/'.$this->session->userdata('id_hari'),'refresh');
}
public function konfirmasiHapus($id_detilhari){
$data = array(
'id_detilhari' => $id_detilhari
);
$this->load->view('header');
$this->load->view('html_head');
$this->load->view('content/kurikulum/v_hapus_detilhari', $data);
}
public function hapusDetilHari($id_detilhari){
$this->e_indisub->nullDetilhari($id_detilhari);
$this->e_detilhari->deleteDetilHari($id_detilhari);
$this->session->set_flashdata('info', 'Detil hari telah dihapus');
redirect('c_RKH/lihatHari/'.$this->session->userdata('id_hari'),'refresh');
}
public function batalHapus(){
$this->session->set_flashdata('calm', 'Tidak jadi dihapus');
redirect('c_RKH/lihatHari/'.$this->session->userdata('id_hari'),'refresh');
}
}
/* End of file c_RKH.php */
/* Location: ./application/controllers/c_RKH.php */ | agungsurya03/SIMPI | application/controllers/c_RKH.php | PHP | mit | 6,409 |
.center-wrapper{
margin-left: 2px;
margin-right: 2px;
}
.flange-wrapper{
margin: 0 10px 0 10px;
}
.days-fieldset .ui-controlgroup-controls {
width: 100%;
text-align:center;
margin:0 auto;
}
.days-fieldset .ui-controlgroup-controls .ui-select {
width: 14.2857%;
}
.days-label-wrapper {
width:82%;
height: 10px;
margin:0 auto;
text-align: justify;
-ms-text-justify: distribute-all-lines;
text-justify: distribute-all-lines;
}
.days-label-wrapper div {
width: auto;
height: 10px;
display: inline-block;
*display: inline;
zoom: 1
}
.stretcher {
width: 100%;
display: inline-block;
font-size: 0;
line-height: 0;
}
.checkbox-area {
width:95%;
margin:0 auto;
}
.checkbox-area .ui-select,
.checkbox-area .ui-checkbox,
.checkbox-area .check-label {
/*background-color: red;*/
vertical-align: middle;
}
/*
.checkbox-area .ui-checkbox {
background-color: red;
}
*/
/*inline for custom values menu-------------------------*/
.deduct-inline .wrapper {
float: left;
width: 100%;
}
.deduct-inline .wrapper .content {
margin: 0 105px 0 110px;
}
/* for custom day boxes*/
.deduct-inline .wrapper .left-cont {
margin-left: 60px;
margin-right: 5px;
float:left;
width: 60px;
}
.deduct-inline .wrapper .cent-cont {
margin-right: 5px;
float:left;
width: 60px;
}
.deduct-inline .wrapper .right-cont {
float:left;
width: 60px;
}
.deduct-inline .left {
float: left;
width: 105px;
margin-left:-100%;
}
.deduct-inline .text {
padding-top:0.7em;
padding-bottom:0.7em;
display: block;
font-size: 16px;
}
.deduct-inline .right {
float: left;
width: 100px;
margin-left: -100px;
}
.deduct-inline .footer {
clear: left;
}
/*for apply button in collapsibles-----------------*/
.apply-inline .text {
float: left;
}
.apply-inline .right {
float: right;
}
.apply-inline .footer {
clear: left;
}
/*preset buttons--------------*/
.preset-inline .wrapper {
float: left;
width: 98%;
margin: auto;
}
.preset-inline .preset-but {
float: left;
width: 85px;
margin-left:5px;
}
/* loa inline -----------------------*/
.loa-inline .wrapper{
float: left;
width: 100%;
}
.loa-inline .left {
float: left;
margin: 0 5px 0 5px;
width: 100px;
}
.loa-inline .footer {
clear: left;
}
.boltpat-inline .wrapper .content {
margin-top: 13px;
}
.boltpat-inline .right {
margin-top: 10px;
}
| ataboo/BMToolbox | assets/www/css/ata.bmtoolbox.css | CSS | mit | 2,436 |
'use strict';
var landing = {
controller : function () {
console.log('helo');
},
view : function () {
return '';
}
};
module.exports = landing;
| sslash/feedr | app/assets/scripts/landing/landing.js | JavaScript | mit | 180 |
---
layout: page
title: Austin Davila's 66th Birthday
date: 2016-05-24
author: Patrick Pena
tags: weekly links, java
status: published
summary: Quisque malesuada turpis dui, quis sodales ex consequat non. Nulla.
banner: images/banner/meeting-01.jpg
booking:
startDate: 09/10/2017
endDate: 09/15/2017
ctyhocn: CHILOHX
groupCode: AD6B
published: true
---
Suspendisse a venenatis ligula, sed sollicitudin velit. Aliquam posuere nibh ut scelerisque lacinia. In condimentum nunc sed porta fermentum. Suspendisse ultrices accumsan turpis. Duis efficitur mollis facilisis. Donec sed elementum orci, sit amet elementum dolor. Donec eu metus dolor. Mauris vehicula diam velit, ut volutpat quam molestie nec. Donec convallis ligula vitae lobortis sagittis. Integer ac turpis eu turpis sollicitudin aliquam vitae a nisl. Donec sit amet lobortis nisi. Pellentesque condimentum tellus mi, nec placerat nulla gravida eu. Fusce tristique, felis et iaculis varius, turpis diam hendrerit justo, at mattis orci nunc ut enim.
Suspendisse a laoreet sem. Sed massa eros, vehicula quis egestas ac, fermentum in purus. Nullam vulputate mollis ante vitae mollis. Cras ut libero at libero aliquam tempor ac a nisl. Vivamus placerat velit nec lorem lacinia, scelerisque ultricies sem pharetra. Curabitur at dolor tincidunt, consequat metus ac, gravida mi. Nulla pellentesque porta dignissim. In hac habitasse platea dictumst. Aliquam auctor dapibus nisi, eget posuere tellus congue sed. Aliquam erat volutpat. Sed elementum metus at ullamcorper varius. Ut sit amet commodo justo. Donec sollicitudin eros id molestie egestas. Aliquam gravida elementum malesuada. Proin aliquam odio felis, eget dapibus elit pulvinar id.
1 Quisque nec metus ornare mi gravida dictum
1 Etiam nec neque suscipit, tincidunt massa quis, tempor lorem
1 Phasellus a enim non felis iaculis ultrices id eu lorem
1 Integer nec neque et magna eleifend molestie
1 Vestibulum placerat mi id augue luctus ornare
1 Curabitur pulvinar felis in tempor suscipit.
Donec id tempus turpis. Integer et orci vel odio feugiat tincidunt. Cras sodales fringilla semper. Maecenas non metus turpis. Donec hendrerit viverra auctor. Quisque ipsum eros, dapibus quis auctor non, porttitor sit amet tellus. Suspendisse purus ex, consequat et arcu a, fermentum luctus quam. Sed eu pharetra ligula. Duis risus lorem, laoreet in est non, dignissim varius sem. Suspendisse semper augue enim, et dapibus leo euismod vitae. Maecenas nulla elit, volutpat sed aliquam vitae, ullamcorper et nibh. Vestibulum commodo luctus tincidunt. Phasellus mattis eu sem nec malesuada. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Duis non ligula nec lorem porttitor maximus. Praesent eget porta dolor. Aenean pulvinar facilisis neque. Sed commodo pharetra metus sed condimentum. In euismod tempor metus, pretium vestibulum odio. Nulla elit est, viverra ac rutrum et, faucibus et nisl. Nunc et pulvinar mauris. Cras interdum euismod sapien, efficitur congue libero cursus id. Nunc aliquam sodales ex, vitae commodo felis. Sed eleifend tempor orci quis cursus.
| KlishGroup/prose-pogs | pogs/C/CHILOHX/AD6B/index.md | Markdown | mit | 3,113 |
@charset "utf-8";
/* Text CSS Document */
body
{
color: #353535;
font-family: "Crimson Text", Verdana, Arial, Helvetica, sans-serif;
font-size: 1em;
line-height: 1;
}
footer
{
color: #858585;
}
a
{
color: #000000;
}
a:hover
{
color: #C80815;
text-decoration: none;
}
h1, h2, h3, h4, h5, h6
{
color: #C80815;
font-family: "Neuton";
font-weight: normal;
margin-bottom: 0.25em;
}
h1
{
font-size: 2.5em;
}
h2
{
font-size: 2em;
}
h3
{
font-size: 1.875em;
}
h4
{
font-size: 1.75em;
}
h5
{
font-size: 1.625em;
}
h6
{
font-size: 1.438em;
}
p
{
font-size: 1.125em;
margin-bottom: 1em;
}
form > p
{
color: #C80815;
margin-top: 0.5em;
margin-bottom: 0.5em;
}
.hymntext
{
color: #000000;
font-size: 1em;
}
.centerText
{
text-align: center;
}
.smallText
{
font-size: 0.80em;
}
.largeText
{
font-size: 1.438em;
}
a.smallText
{
color: #DAA520;
font-weight: bold;
}
a.smallText:hover
{
color: #FFCC00;
}
a.darkLink
{
color: #C04000;
}
a.darkLink:hover
{
color: #FF7F00;
}
.author
{
color: #858585;
font-style: italic;
text-align: right;
}
.colorRed
{
color: #C80815;
}
a.iconFont
{
font-family: "IconFont";
color: #999999;
}
a.iconFont:hover
{
color: #666666;
}
a.iconFont:active
{
color: #333333;
} | joelabr/Online-Psalmboken | css/text.css | CSS | mit | 1,293 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# See http://stackoverflow.com/questions/4764932/in-python-how-do-i-read-the-exif-data-for-an-image/4765242#4765242
import PIL.Image as pil_img # PIL.Image is a module not a class...
import PIL.ExifTags as pil_exif_tags # PIL.ExifTags is a module not a class...
import sys
def main():
"""Main function"""
try:
filename = sys.argv[1]
except IndexError:
print("Usage: {} FILENAME".format(sys.argv[0]))
sys.exit(1)
img = pil_img.open(filename)
# Print the image's EXIF metadata dictionary indexed by EXIF numeric tags
exif_data_num_dict = img._getexif()
print(exif_data_num_dict)
# Print the image's EXIF metadata dictionary indexed by EXIF tag name strings
exif_data_str_dict = {pil_exif_tags.TAGS[k]: v for k, v in exif_data_num_dict.items() if k in pil_exif_tags.TAGS}
print(exif_data_str_dict)
if __name__ == '__main__':
main()
| jeremiedecock/snippets | python/pillow/exif_get_all_tags_values.py | Python | mit | 2,081 |
Queues = new Mongo.Collection('queues');
Tracks = new Mongo.Collection('tracks');
| evntq/evntq-meteor | lib/collection.js | JavaScript | mit | 82 |
# AoikKarrigellStart
Start code for Karrigell.
Tested working with:
- Python: 3.4
Karrigell does not support Py2.
- Karrigell: 4.3.10
## How to use
### Install Karrigell
Karrigell is not installable via pip.
Download **Karrigell-4.3.10.gz** from [here](http://code.google.com/p/karrigell/downloads/list).
Unzip it.
Go to the dir containing **setup.py**.
Run
```
python setup.py install
```
### Clone this repo
Clone this repo to local.
### Run
Go to the local repo dir.
The program entry point is [src/aoikkarrigellstart/main.py](/src/aoikkarrigellstart/main.py).
Run
```
python src/aoikkarrigellstart/main.py
```
- Use **-w** to specify using wsgiref server instead of Karrigell's.
- Use **-o** and **-p** to specify binding host and port.
Open **http://127.0.0.1:8000/** in your browser.
| AoiKuiyuyou/AoikKarrigellStart | README.md | Markdown | mit | 808 |
<?php
namespace Opifer\EavBundle\Model;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
class AttributeManager
{
/** @var EntityManager */
protected $em;
/** @var string */
protected $class;
/**
* Constructor
*
* @param EntityManagerInterface $em
* @param $class
*
* @throws \Exception If the passed classname does not implement AttributeInterface
*/
public function __construct(EntityManagerInterface $em, $class)
{
if (!is_subclass_of($class, 'Opifer\EavBundle\Model\AttributeInterface')) {
throw new \Exception($class.' must implement Opifer\EavBundle\Model\AttributeInterface');
}
$this->em = $em;
$this->class = $class;
}
/**
* Get class
*
* @return string
*/
public function getClass()
{
return $this->class;
}
/**
* Create a new attribute instance
*
* @return AttributeInterface
*/
public function create()
{
$class = $this->getClass();
$attribute = new $class();
return $attribute;
}
/**
* Save attribute
*
* @param AttributeInterface $attribute
*
* @return AttributeInterface
*/
public function save(AttributeInterface $attribute)
{
$this->em->persist($attribute);
$this->em->flush();
return $attribute;
}
/**
* Get repository
*
* @return \Doctrine\ORM\EntityRepository
*/
public function getRepository()
{
return $this->em->getRepository($this->getClass());
}
}
| Opifer/Cms | src/EavBundle/Model/AttributeManager.php | PHP | mit | 1,661 |
<?php
namespace SiteBundle\Repository;
/**
* ProductSpecRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ProductSpecRepository extends \Doctrine\ORM\EntityRepository
{
}
| firestorm23/gyrolab-ste | src/SiteBundle/Repository/ProductSpecRepository.php | PHP | mit | 246 |
package io.sniffy;
import com.codahale.metrics.Timer;
import io.qameta.allure.Feature;
import io.sniffy.configuration.SniffyConfiguration;
import org.junit.Before;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.*;
public class SniffyTest extends BaseTest {
@Before
public void clearSpies() {
Sniffy.registeredSpies.clear();
Sniffy.currentThreadSpies.clear();
}
@Test
public void hasSpiesFromOtherThreads() throws Exception {
try (@SuppressWarnings("unused") Spy spy = Sniffy.spy()) {
AtomicBoolean hasSpies = new AtomicBoolean();
Thread thread = new Thread(() -> hasSpies.set(Sniffy.hasSpies()));
thread.start();
thread.join();
assertTrue(hasSpies.get());
}
}
@Test
public void hasNotSpiesFromOtherThreads() throws Exception {
try (@SuppressWarnings("unused") CurrentThreadSpy spy = Sniffy.spyCurrentThread()) {
AtomicBoolean hasSpies = new AtomicBoolean();
Thread thread = new Thread(() -> hasSpies.set(Sniffy.hasSpies()));
thread.start();
thread.join();
assertFalse(hasSpies.get());
}
}
@Test
public void testCurrentThreadSpy() throws Exception {
CurrentThreadSpy spy = Sniffy.spyCurrentThread();
executeStatements(2);
executeStatementsInOtherThread(3);
assertEquals(2, spy.executedStatements());
assertEquals(1, spy.getExecutedStatements().size());
assertEquals(2, spy.getExecutedStatements().values().iterator().next().queries.get());
}
@Test
@Feature("issues/292")
public void testGlobalSqlStatsDisabled() throws Exception {
int topSqlCapacity = SniffyConfiguration.INSTANCE.getTopSqlCapacity();
try {
Sniffy.getGlobalSqlStats().clear();
SniffyConfiguration.INSTANCE.setTopSqlCapacity(0);
executeStatements(3);
assertTrue(Sniffy.getGlobalSqlStats().isEmpty());
} finally {
SniffyConfiguration.INSTANCE.setTopSqlCapacity(topSqlCapacity);
}
}
@Test
@Feature("issues/292")
public void testGetGlobalSqlStats() throws Exception {
Sniffy.getGlobalSqlStats().clear();
executeStatements(3);
ConcurrentMap<String, Timer> globalSqlStats = Sniffy.getGlobalSqlStats();
assertEquals(1, globalSqlStats.size());
Map.Entry<String, Timer> entry = globalSqlStats.entrySet().iterator().next();
assertEquals("SELECT 1 FROM DUAL", entry.getKey());
assertEquals(3, entry.getValue().getCount());
}
@Test
@Feature("issues/292")
public void testLruGlobalSqlStats() throws Exception {
Sniffy.getGlobalSqlStats().clear();
for (int i = 0; i < Sniffy.TOP_SQL_CAPACITY; i++) {
executeSelectStatements(i, 2 + i % 100);
}
assertEquals(Sniffy.TOP_SQL_CAPACITY, Sniffy.getGlobalSqlStats().size());
assertNotNull(Sniffy.getGlobalSqlStats().get(String.format("SELECT %d FROM DUAL", 0)));
executeSelectStatements(Sniffy.TOP_SQL_CAPACITY + 1000, 1);
assertEquals(Sniffy.TOP_SQL_CAPACITY, Sniffy.getGlobalSqlStats().size());
assertTrue(Sniffy.getGlobalSqlStats().containsKey(String.format("SELECT %d FROM DUAL", Sniffy.TOP_SQL_CAPACITY + 1000)));
assertTrue(Sniffy.getGlobalSqlStats().containsKey(String.format("SELECT %d FROM DUAL", 0)));
assertFalse(Sniffy.getGlobalSqlStats().containsKey(String.format("SELECT %d FROM DUAL", 1)));
}
private void executeSelectStatements(int index, int count) throws SQLException {
try (Connection connection = openConnection();
Statement statement = connection.createStatement()) {
for (int i = 0; i < count; i++) {
statement.execute(String.format("SELECT %d FROM DUAL", index));
}
}
}
} | sniffy/sniffy | sniffy-core/src/test/java/io/sniffy/SniffyTest.java | Java | mit | 4,141 |
//
// пример порогового преобразования над RGB-картинкой
// cvThreshold() и cvAdaptiveThreshold()
//
// http://robocraft.ru/blog/computervision/375.html
//
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
IplImage *image=0, *gray=0, *dst=0, *dst2=0;
IplImage* r=0, *g=0, *b=0; // для хранения отдельных слоёв RGB-изображения
// имя картинки задаётся первым параметром
const char* filename = argc >= 2 ? argv[1] : "../tests/rectangle_5_1_6.jpg";
// получаем картинку
image = cvLoadImage(filename, 1);
printf("[i] image: %s\n", filename);
assert( image != 0 );
// покажем изображение
cvNamedWindow( "original", 1 );
cvShowImage( "original", image );
// картинка для хранения изображения в градациях серого
gray = cvCreateImage(cvGetSize(image), image->depth, 1);
// преобразуем картинку в градации серого
cvConvertImage(image, gray, CV_BGR2GRAY);
// покажем серую картинку
cvNamedWindow( "gray", 1 );
cvShowImage( "gray", gray );
dst = cvCreateImage( cvGetSize(gray), IPL_DEPTH_8U, 1);
dst2 = cvCreateImage( cvGetSize(gray), IPL_DEPTH_8U, 1);
// пороговые преобразования над картинкой в градациях серого
cvThreshold(gray, dst, 50, 250, CV_THRESH_BINARY);
cvAdaptiveThreshold(gray, dst2, 250, CV_ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY, 7, 1);
// показываем результаты
cvNamedWindow( "cvThreshold", 1 );
cvShowImage( "cvThreshold", dst);
cvNamedWindow( "cvAdaptiveThreshold", 1 );
cvShowImage( "cvAdaptiveThreshold", dst2);
//=======================================================
//
// проведём пороговое преобразование над RGB-картинкой
//
r = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
g = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
b = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
// разбиваем на отдельные слои
cvSplit(image, b, g, r, 0);
// картинка для хранения промежуточных результатов
IplImage* temp = cvCreateImage( cvGetSize(image), IPL_DEPTH_8U, 1 );
// складываем картинки с одинаковым весом
cvAddWeighted( r, 1.0/3.0, g, 1.0/3.0, 0.0, temp );
cvAddWeighted( temp, 2.0/3.0, b, 1.0/3.0, 0.0, temp );
// выполняем пороговое преобразование
cvThreshold(temp, dst, 50, 250, CV_THRESH_BINARY);
cvReleaseImage(&temp);
// показываем результат
cvNamedWindow( "RGB cvThreshold", 1 );
cvShowImage( "RGB cvThreshold", dst);
//
// попробуем пороговое преобразование над отдельными слоями
//
IplImage* t1, *t2, *t3; // для промежуточного хранения
t1 = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
t2 = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
t3 = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
// выполняем пороговое преобразование
cvThreshold(r, t1, 50, 250, CV_THRESH_BINARY);
cvThreshold(g, t2, 50, 250, CV_THRESH_BINARY);
cvThreshold(b, t3, 50, 250, CV_THRESH_BINARY);
// складываем результаты
cvMerge(t3, t2, t1, 0, image);
cvNamedWindow( "RGB cvThreshold 2", 1 );
cvShowImage( "RGB cvThreshold 2", image);
cvReleaseImage(&t1); cvReleaseImage(&t2); cvReleaseImage(&t3);
//=======================================================
// ждём нажатия клавиши
cvWaitKey(0);
// освобождаем ресурсы
cvReleaseImage(& image);
cvReleaseImage(&gray);
cvReleaseImage(&dst);
cvReleaseImage(&dst2);
cvReleaseImage(&r); cvReleaseImage(&g); cvReleaseImage(&b);
// удаляем окна
cvDestroyAllWindows();
return 0;
} | Ralor/PatternRecognizer | usedsnippets/treshold_layers.cpp | C++ | mit | 4,760 |
<?php
namespace ApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use AssureurBundle\Entity\Devis;
use AssureurBundle\Form\Type\DevisType;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
class DevisController extends Controller{
/**
* @ApiDoc(
* section="Devis",
* description="Create a new Object",
* input="AssureurBundle\Form\Type\DevisType",
* output="AssureurBundle\Entity\Devis"
* )
* @param Request $request
* @Rest\View(statusCode=Response::HTTP_CREATED)
* @Rest\Post("/devis/add")
* @return Accident
*/
public function postDevisAction(Request $request){
$devis = new Devis();
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(DevisType::class,$devis);
$form->submit($request->request->get($form->getName()));
if($form->isSubmitted())
{
$dossierId = $request->request->get($form->getName())['dossier'];
$dossier = $this->getDoctrine()->getRepository('AssureurBundle:Dossier')->find($dossierId);
if(empty($dossier)){
return new JsonResponse(['message' => 'not found'],404);
}
$file = $request->files->get($form->getName())['url'];
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$file->move($this->getParameter('photo_directory') . '/devis/', $fileName);
$fullUrl = '/uploads/photo/devis/' . $fileName;
$devis->setUrl($fullUrl);
$devis->setDossier($dossier);
$em->persist($devis);
$em->flush();
return $devis;
}
else{
return $form->getErrors();
}
}
/**
* @ApiDoc(
* section="Devis",
* description="Edit Object via Post(file upload)",
* input="AssureurBundle\Form\Type\DevisType",
* output="AssureurBundle\Entity\Devis",
* requirements={
* {
* "name"="id",
* "dataType"="integer",
* "requirement"="\d+",
* "description"="Devis Id"
* }
* }
* )
* @param Request $request
* @Rest\View(statusCode=Response::HTTP_ACCEPTED)
* @Rest\Post("/devis/edit/{id}")
* @return Accident
*/
public function postDevisEditAction(Request $request,$id){
$em = $this->getDoctrine()->getManager();
$devisToEdit = $em->getRepository('AssureurBundle:Devis')->findOneBy(array('deleted' => false,'id' => $id));
if(empty($devisToEdit))
{
return new JsonResponse(['message' => 'not found'],404);
}
$devis = new Devis() ;
$form = $this->createForm(DevisType::class,$devis);
$form->submit($request->request->get($form->getName()));
if($form->isSubmitted())
{
$dossierId = $request->request->get($form->getName())['dossier'];
$dossier = $this->getDoctrine()->getRepository('AssureurBundle:Dossier')->find($dossierId);
if(empty($dossier)){
return new JsonResponse(['message' => 'not found'],404);
}
$file = $request->files->get('devis')['url'];
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$file->move($this->getParameter('photo_directory') . '/devis/', $fileName);
$fullUrl = '/uploads/photo/devis/' . $fileName;
$devisToEdit->setUrl($fullUrl);
$devisToEdit->setDossier($dossier);
$em->flush();
return $devisToEdit;
}
else{
return $form->getErrors();
}
}
/**
*
* @ApiDoc(
* section="Devis",
* description="Delete Object",
* requirements={
* {
* "name"="id",
* "dataType"="integer",
* "requirement"="\d+",
* "description"="Devis ID"
* }
* }
* )
* @Rest\View
* @Rest\Delete("/devis/delete/{id}")
* @return JsonResponse
*/
public function deleteDevisAction($id){
$em = $this->getDoctrine()->getManager();
$devis= $em->getRepository('AssureurBundle:Devis')->findOneBy(array('deleted' => false,'id' => $id));
if(empty($devis))
{
return new JsonResponse(['message' => 'not found'],404);
}
$devis->setDeleted(true);
$em->flush();
return new JsonResponse(['message' => 'deleted'],Response::HTTP_NO_CONTENT);
}
/**
* @ApiDoc(
* section="Devis",
* description="Get Object By Dossier ID",
* requirements={
* {
* "name"="dossierId",
* "dataType"="integer",
* "requirement"="\d+",
* "description"="Dossier ID"
* }
* }
* )
* @Rest\View
* @Rest\Get("/devis/dossier/{dossierId}")
*/
public function getDevisByDossierIdAction($dossierId){
$em = $this->getDoctrine()->getManager();
$devis= $em->getRepository('AssureurBundle:Devis')->findBy(array('deleted' => false,'dossier' => $dossierId));
if(empty($devis))
{
return new JsonResponse(['message' => 'not found'],404);
}
return $devis;
}
} | lmomar/ensurance2 | src/ApiBundle/Controller/DevisController.php | PHP | mit | 5,682 |
<?php namespace Benhawker\Pipedrive\Library;
use Benhawker\Pipedrive\Exceptions\PipedriveMissingFieldError;
/**
* Pipedrive Deals Methods
*
* DealFields represent the near-complete schema for a Deal in the context of the company of the authorized user.
* Each company can have a different schema for their Deals, with various custom fields. In the context of using
* DealFiels as a schema for defining the data fields of a Deal, it must be kept in mind that some types of
* custom fields can have additional data fields which are not separate DealFields per se. Such is the case with
* monetary, daterange and timerange fields – each of these fields will have one additional data field in addition
* to the one presented in the context of DealFields. For example, if there is a monetary field with the key
* 'ffk9s9' stored on the account, 'ffk9s9' would hold the numeric value of the field, and 'ffk9s9_currency'
* would hold the ISO currency code that goes along with the numeric value. To find out which data fields are
* available, fetch one Deal and list its keys.
*
*/
class DealFields
{
/**
* Hold the pipedrive cURL session
* @var Curl Object
*/
protected $curl;
/**
* Initialise the object load master class
*/
public function __construct(\Benhawker\Pipedrive\Pipedrive $master)
{
//associate curl class
$this->curl = $master->curl();
}
/**
* Adds a dealField
*
* @param array $data deal field detials
* @return array returns detials of the deal field
*/
public function add(array $data)
{
//if there is no name set throw error as it is a required field
if (!isset($data['name'])) {
throw new PipedriveMissingFieldError('You must include a "name" field when inserting a dealField');
}
return $this->curl->post('dealFields', $data);
}
}
| henrikroosmann/pipedrive-api-php | src/Benhawker/Pipedrive/Library/DealFields.php | PHP | mit | 1,917 |
<?php
namespace Mapping\Fixture;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Sluggable {
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(name="title", type="string", length=64)
*/
private $title;
/**
* @ORM\Column(name="code", type="string", length=16)
*/
private $code;
/**
* @Gedmo\Slug(handlers={
* @Gedmo\SlugHandler(class="Gedmo\Sluggable\Handler\TreeSlugHandler", options={
* @Gedmo\SlugHandlerOption(name="parentRelationField", value="parent"),
* @Gedmo\SlugHandlerOption(name="separator", value="/")
* }),
* @Gedmo\SlugHandler(class="Gedmo\Sluggable\Handler\RelativeSlugHandler", options={
* @Gedmo\SlugHandlerOption(name="relationField", value="user"),
* @Gedmo\SlugHandlerOption(name="relationSlugField", value="slug"),
* @Gedmo\SlugHandlerOption(name="separator", value="/")
* })
* }, separator="-", updatable=false, fields={"title", "code"})
* @ORM\Column(name="slug", type="string", length=64, unique=true)
*/
private $slug;
/**
* @ORM\ManyToOne(targetEntity="Sluggable")
*/
private $parent;
/**
* @ORM\ManyToOne(targetEntity="User")
*/
private $user;
public function getId()
{
return $this->id;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setCode($code)
{
$this->code = $code;
}
public function getCode()
{
return $this->code;
}
public function getSlug()
{
return $this->slug;
}
}
| vlefrere/ProjetBDD | vendor/gedmo/doctrine-extensions/tests/Gedmo/Mapping/Fixture/Sluggable.php | PHP | mit | 1,807 |
"""
This module tests for compability with Ethereum's Smart Contracts.
"""
"""
import os
import pytest
from pyethereum import tester
import serpent
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
logger = logging.getLogger()
# customize VM log output to your needs
# hint: use 'py.test' with the '-s' option to dump logs to the console
pblogger = tester.pb.pblogger
pblogger.log_pre_state = True # dump storage at account before execution
pblogger.log_post_state = True # dump storage at account after execution
pblogger.log_block = False # dump block after TX was applied
pblogger.log_memory = False # dump memory before each op
pblogger.log_stack = True # dump stack before each op
pblogger.log_op = True # log op, gas, stack before each op
pblogger.log_apply_op = True # log op, gas, stack before each op
pblogger.log_json = False # generate machine readable output
gasprice = 0
startgas = 10000
"""
### Counterparty compatibility ###
import server
from dogepartylib.lib import (util, config, database)
from dogepartylib.lib.messages import execute
from dogepartylib.lib.messages.scriptlib import (blocks, rlp, processblock)
import subprocess # Serpent is Python 3‐incompatible.
import binascii
import os
import sys
import logging
logger = logging.getLogger(__name__)
import tempfile
CURR_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(CURR_DIR, '..')))
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
TIMESTAMP = 1410973349
tx_index = 1
class serpent(object):
def compile(code):
evmcode = subprocess.check_output(['serpent', 'compile', code])
evmcode = evmcode[:-1] # Strip newline.
return binascii.unhexlify(bytes(evmcode))
def encode_datalist(vals):
def enc(n):
if type(n) == int:
return n.to_bytes(32, byteorder='big')
elif type(n) == str and len(n) == 40:
return b'\x00' * 12 + binascii.unhexlify(n)
elif type(n) == str:
return b'\x00' * (32 - len(n)) + n.encode('utf-8') # TODO: ugly (and multi‐byte characters)
elif n is True:
return 1
elif n is False or n is None:
return 0
def henc(n):
return util.hexlify(enc(n))
if isinstance(vals, (tuple, list)):
return ''.join(map(henc, vals))
elif vals == '':
return b''
else:
assert False
# Assume you're getting in numbers or 0x...
# return ''.join(map(enc, list(map(numberize, vals.split(' ')))))
class tester(object):
gas_limit = 100000
class serpent(object):
def compile_lll(lll_code):
code = subprocess.check_output(['serpent', 'compile_lll', lll_code])
code = code[:-1] # Strip newline.
return binascii.unhexlify(bytes(code))
class state(object):
# N/A
def mine (self, n, coinbase):
global TIMESTAMP
TIMESTAMP += 50000
def snapshot(self):
cursor = db.cursor()
name = 'xyz'
cursor.execute('''SAVEPOINT {}'''.format(name))
return name
def revert(self, name):
cursor = db.cursor()
cursor.execute('''ROLLBACK TO SAVEPOINT {}'''.format(name))
def create_contract(self, code, endowment=0, sender=''):
if not sender:
sender = '82a978b3f5962a5b0957d9ee9eef472ee55b42f1' # PyEthereum uses ECDSA to derive this string from `sender = 0`.
util.credit(db, sender, config.XDP, max(endowment*2, 100000000), action='unit test', event='facefeed')
success, data = tester.state.do_send(self, sender, '', endowment, data=code)
contract_id = data
return contract_id
def evm(self, evmcode, endowment=0, sender=''):
# Publish code.
contract_id = tester.state.create_contract(self, evmcode, endowment=endowment, sender=sender)
# Return contract_id.
return contract_id
def contract(self, code, sender='', endowment=0):
# Compile fake code.
if code:
evmcode = serpent.compile(code)
else:
evmcode = b''
return tester.state.evm(self, evmcode, endowment=endowment, sender=sender)
def do_send (self, sender, to, value, data=[]):
global tx_index
if not sender:
sender = util.contract_sha3('foo'.encode('utf-8'))
# Construct `tx`.
tx = { 'source': sender,
'block_index': 0,
'tx_hash': '{}{}'.format(to, tx_index),
'block_time': TIMESTAMP,
'tx_index': tx_index
}
tx_index += 1
tx_obj = execute.Transaction(tx, to, 1, tester.gas_limit, value, data)
# Force block init.
def fake_block_init(self, db):
self.db = db
self.timestamp = TIMESTAMP
self.number = 9001
self.prevhash = 'facefeed'
self.difficulty = 1337
return
blocks.Block.__init__ = fake_block_init
block_obj = blocks.Block(db)
# Run.
processblock.MULTIPLIER_CONSTANT_FACTOR = 1
success, output, gas_remained = processblock.apply_transaction(db, tx_obj, block_obj)
# Decode, return result.
return success, output
def send (self, sender, to, value, data=[]):
# print('tuple', sender, to, value, data)
# Encode data.
data = serpent.encode_datalist(data)
data = binascii.unhexlify(data)
# Execute contract.
# print('qux', data, type(data))
util.credit(db, sender, config.XDP, value + 100000000, action='unit test', event='facefeed')
success, output = tester.state.do_send(self, sender, to, value, data=data)
if output:
return rlp.decode_datalist(bytes(output))
else:
return []
class block(object):
def to_dict():
return True # NOTE: Not applicable.
def set_code(contract_id, code):
cursor = db.cursor()
bindings = {'block_index': 0, 'code': code, 'contract_id': contract_id}
sql='''update contracts set code = :code where contract_id = :contract_id'''
cursor.execute(sql, bindings)
cursor.close()
def get_storage_data(contract_id, key):
block = blocks.Block(db)
return block.get_storage_data(contract_id, key)
def get_balance(address):
block = blocks.Block(db)
return block.get_balance(address)
tester.k0 = '82a978b3f5962a5b0957d9ee9eef472ee55b42f1'
tester.k1 = '7d577a597b2742b498cb5cf0c26cdcd726d39e6e'
tester.k2 = '82a978b3f5962a5b0957d9ee9eef472ee55b42f1'
tester.a0 = '82a978b3f5962a5b0957d9ee9eef472ee55b42f1'
tester.a1 = 'dceceaf3fc5c0a63d195d69b1a90011b7b19650d'
tester.a2 = 'dceceaf3fc5c0a63d195d69b1a90011b7b19650d'
tester.a3 = '598443f1880ef585b21f1d7585bd0577402861e5'
def setup_function(function):
server.initialise(database_file=tempfile.gettempdir()+'/counterparty.unittest.db',
rpc_port=9999, rpc_password='pass',
backend_password='pass',
testnet=True, testcoin=False)
try:
os.remove(config.DATABASE)
except:
pass
# Connect to database.
global db
db = database.get_connection(read_only=False, foreign_keys=False)
from dogepartylib.lib import blocks
blocks.initialise(db)
def teardown_function(function):
global db
del db
os.remove(config.DATABASE)
### Counterparty compatibility ###
# Test EVM contracts
serpent_code = 'return(msg.data[0] ^ msg.data[1])'
evm_code = serpent.compile(serpent_code)
def test_evm():
s = tester.state()
c = s.evm(evm_code)
o = s.send(tester.k0, c, 0, [2, 5])
assert o == [32]
# Test serpent compilation of variables using _with_, doing a simple
# arithmetic calculation 20 * 30 + 10 = 610
sixten_code =\
'''
(with 'x 10
(with 'y 20
(with 'z 30
(seq
(set 'a (add (mul (get 'y) (get 'z)) (get 'x)))
(return (ref 'a) 32)
)
)
)
)
'''
def test_sixten():
s = tester.state()
c = s.contract('')
s.block.set_code(c, tester.serpent.compile_lll(sixten_code))
o1 = s.send(tester.k0, c, 0, [])
assert o1 == [610]
# Test Serpent's import mechanism
mul2_code = \
'''
return(msg.data[0]*2)
'''
filename = "mul2_qwertyuioplkjhgfdsa.se"
returnten_code = \
'''
x = create("%s")
return(call(x, 5))
''' % filename
def test_returnten():
s = tester.state()
open(filename, 'w').write(mul2_code)
c = s.contract(returnten_code)
o1 = s.send(tester.k0, c, 0, [])
os.remove(filename)
assert o1 == [10]
# Test a simple namecoin implementation
namecoin_code =\
'''
if !contract.storage[msg.data[0]]:
contract.storage[msg.data[0]] = msg.data[1]
return(1)
else:
return(0)
'''
def test_namecoin():
s = tester.state()
c = s.contract(namecoin_code)
o1 = s.send(tester.k0, c, 0, ['"george"', 45])
assert o1 == [1]
o2 = s.send(tester.k0, c, 0, ['"george"', 20])
assert o2 == [0]
o3 = s.send(tester.k0, c, 0, ['"harry"', 60])
assert o3 == [1]
assert s.block.to_dict()
# Test a simple currency implementation
currency_code = '''
init:
contract.storage[msg.sender] = 1000
code:
if msg.datasize == 1:
addr = msg.data[0]
return(contract.storage[addr])
else:
from = msg.sender
fromvalue = contract.storage[from]
to = msg.data[0]
value = msg.data[1]
if fromvalue >= value:
contract.storage[from] = fromvalue - value
contract.storage[to] = contract.storage[to] + value
return(1)
else:
return(0)
'''
def test_currency():
s = tester.state()
c = s.contract(currency_code, sender=tester.k0)
o1 = s.send(tester.k0, c, 0, [tester.a2, 200])
assert o1 == [1]
o2 = s.send(tester.k0, c, 0, [tester.a2, 900])
assert o2 == [0]
o3 = s.send(tester.k0, c, 0, [tester.a0])
assert o3 == [800]
o4 = s.send(tester.k0, c, 0, [tester.a2])
assert o4 == [200]
# Test a data feed
data_feed_code = '''
if !contract.storage[1000]:
contract.storage[1000] = 1
contract.storage[1001] = msg.sender
return(20)
elif msg.datasize == 2:
if msg.sender == contract.storage[1001]:
contract.storage[msg.data[0]] = msg.data[1]
return(1)
else:
return(0)
else:
return(contract.storage[msg.data[0]])
'''
def test_data_feeds():
s = tester.state()
c = s.contract(data_feed_code, sender=tester.k0)
o1 = s.send(tester.k0, c, 0)
assert o1 == [20]
o2 = s.send(tester.k0, c, 0, [500])
assert o2 == [0]
o3 = s.send(tester.k0, c, 0, [500, 19])
assert o3 == [1]
o4 = s.send(tester.k0, c, 0, [500])
assert o4 == [19]
o5 = s.send(tester.k1, c, 0, [500, 726])
assert o5 == [0]
o6 = s.send(tester.k0, c, 0, [500, 726])
assert o6 == [1]
return s, c
# Test an example hedging contract, using the data feed. This tests
# contracts calling other contracts
hedge_code = '''
if !contract.storage[1000]:
contract.storage[1000] = msg.sender
contract.storage[1002] = msg.value
contract.storage[1003] = msg.data[0]
contract.storage[1004] = msg.data[1]
return(1)
elif !contract.storage[1001]:
ethvalue = contract.storage[1002]
if msg.value >= ethvalue:
contract.storage[1001] = msg.sender
c = call(contract.storage[1003],[contract.storage[1004]],1)
othervalue = ethvalue * c
contract.storage[1005] = othervalue
contract.storage[1006] = block.timestamp + 500
return([2,othervalue],2)
else:
othervalue = contract.storage[1005]
ethvalue = othervalue / call(contract.storage[1003],contract.storage[1004])
if ethvalue >= contract.balance:
send(contract.storage[1000],contract.balance)
return(3)
elif block.timestamp > contract.storage[1006]:
send(contract.storage[1001],contract.balance - ethvalue)
send(contract.storage[1000],ethvalue)
return(4)
else:
return(5)
'''
def test_hedge():
s, c = test_data_feeds()
c2 = s.contract(hedge_code, sender=tester.k0)
# Have the first party register, sending 10^16 wei and
# asking for a hedge using currency code 500
o1 = s.send(tester.k0, c2, 10**16, [c, 500])
assert o1 == [1]
# Have the second party register. It should receive the
# amount of units of the second currency that it is
# entitled to. Note that from the previous test this is
# set to 726
o2 = s.send(tester.k2, c2, 10**16)
assert o2 == [2, 7260000000000000000]
snapshot = s.snapshot()
# Set the price of the asset down to 300 wei
o3 = s.send(tester.k0, c, 0, [500, 300])
assert o3 == [1]
# Finalize the contract. Expect code 3, meaning a margin call
o4 = s.send(tester.k0, c2, 0)
assert o4 == [3]
s.revert(snapshot)
# Don't change the price. Finalize, and expect code 5, meaning
# the time has not expired yet
o5 = s.send(tester.k0, c2, 0)
assert o5 == [5]
s.mine(100, tester.a3)
# Mine ten blocks, and try. Expect code 4, meaning a normal execution
# where both get their share
o6 = s.send(tester.k0, c2, 0)
assert o6 == [4]
# Test the LIFO nature of call and the FIFO nature of post
arither_code = '''
init:
contract.storage[0] = 10
code:
if msg.data[0] == 0:
contract.storage[0] += 1
elif msg.data[0] == 1:
contract.storage[0] *= 10
call(contract.address, 0)
contract.storage[0] *= 10
elif msg.data[0] == 2:
contract.storage[0] *= 10
postcall(tx.gas / 2, contract.address, 0)
contract.storage[0] *= 10
elif msg.data[0] == 3:
return(contract.storage[0])
'''
def test_post():
s = tester.state()
c = s.contract(arither_code)
s.send(tester.k0, c, 0, [1])
o2 = s.send(tester.k0, c, 0, [3])
assert o2 == [1010]
c = s.contract(arither_code)
s.send(tester.k0, c, 0, [2])
o2 = s.send(tester.k0, c, 0, [3])
assert o2 == [1001]
# Test suicides and suicide reverts
suicider_code = '''
if msg.data[0] == 0:
contract.storage[15] = 40
call(contract.address, 3)
i = 0
while i < msg.data[1]:
i += 1
elif msg.data[0] == 1:
contract.storage[15] = 20
msg(tx.gas - 100, contract.address, 0, [0, msg.data[1]], 2)
elif msg.data[0] == 2:
return(10)
elif msg.data[0] == 3:
suicide(0)
elif msg.data[0] == 4:
return(contract.storage[15])
'''
def test_suicider():
s = tester.state()
c = s.contract(suicider_code)
prev_gas_limit = tester.gas_limit
tester.gas_limit = 4000
# Run normally: suicide processes, so the attempt to ping the
# contract fails
s.send(tester.k0, c, 0, [1, 10])
o2 = s.send(tester.k0, c, 0, [2])
assert o2 == []
c = s.contract(suicider_code)
# Run the suicider in such a way that it suicides in a sub-call,
# then runs out of gas, leading to a revert of the suicide and the
# storage mutation
s.send(tester.k0, c, 0, [1, 4000])
# Check that the suicide got reverted
o2 = s.send(tester.k0, c, 0, [2])
assert o2 == [10]
# Check that the storage op got reverted
o3 = s.send(tester.k0, c, 0, [4])
assert o3 == [20]
tester.gas_limit = prev_gas_limit
# Test reverts
reverter_code = '''
if msg.data[0] == 0:
msg(1000, contract.address, 0, 1)
msg(1000, contract.address, 0, 2)
elif msg.data[0] == 1:
send(1, 9)
contract.storage[8080] = 4040
contract.storage[160160] = 2020
elif msg.data[0] == 2:
send(2, 9)
contract.storage[8081] = 4039
contract.storage[160161] = 2019
call(contract.address, 2)
contract.storage["waste_some_gas"] = 0
'''
def test_reverter():
s = tester.state()
c = s.contract(reverter_code, endowment=10**15)
s.send(tester.k0, c, 0, [0])
assert s.block.get_storage_data(c, 8080) == 4040
assert s.block.get_balance('0'*39+'1') == 9
assert s.block.get_storage_data(c, 8081) == 0
assert s.block.get_balance('0'*39+'2') == 0
# Test stateless contracts
add1_code = \
'''
contract.storage[1] += msg.data[0]
'''
filename2 = "stateless_qwertyuioplkjhgfdsa.se"
stateless_test_code = \
'''
x = create("%s")
call(x, 6)
call_stateless(x, 4)
call_stateless(x, 60)
call(x, 40)
return(contract.storage[1])
''' % filename2
def test_stateless():
s = tester.state()
open(filename2, 'w').write(add1_code)
c = s.contract(stateless_test_code)
o1 = s.send(tester.k0, c, 0, [])
os.remove(filename2)
assert o1 == [64]
# https://github.com/ethereum/serpent/issues/8
array_code = '''
a = array(1)
a[0] = 1
return(a, 1)
'''
def test_array():
s = tester.state()
c = s.contract(array_code)
assert [1] == s.send(tester.k0, c, 0, [])
array_code2 = '''
a = array(1)
something = 2
a[0] = 1
return(a, 1)
'''
def test_array2():
s = tester.state()
c = s.contract(array_code2)
assert [1] == s.send(tester.k0, c, 0, [])
array_code3="""
a = array(3)
return(a, 3)
"""
def test_array3():
s = tester.state()
c = s.contract(array_code3)
assert [0,0,0] == s.send(tester.k0, c, 0, [])
| coinwarp/dogeparty-lib | dogepartylib/test/contracts_test.py | Python | mit | 17,873 |
{% extends "layout.html" %} {% block page_title %} Advance payment {% endblock %} {% block content %}
<main id="content" role="main">
<!-- alpha banner -->
<div class="phase-banner-beta">
<p>
<strong class="phase-tag">BETA</strong>
<span>This is a new service – your <a href="../../feedback">feedback</a> will help us to improve it.</span>
</p>
</div>
<!-- main content starts -->
<a href="../land-compensation" class="link-back" style="margin-bottom:0">Back</a>
<h1 class="heading-large" style="margin-top:20px">
Advance payment
</h1>
<div class="grid-row">
<div class="column-two-thirds">
<form action="../what-does-charge-do" method="GET">
<fieldset>
<legend>
<h2 class="heading-medium">What is the amount of advance payment?</h2>
</legend>
<span class="form-hint">For example, 100000</span>
<div class="form-group">
<label class="form-label-bold" for="compensation-amount">
</label>
<span class="bold-small">£ </span>
<input class="form-control form-control-1-4" type="text" name="amount" id="compensation-amount">
</div>
</fieldset>
<fieldset>
<legend>
<h2 class="heading-medium">What is the percentage of agreed or estimated compensation</h2>
</legend>
<span class="form-hint">This is the % of the agreed or estimated compensation. For example, 90</span>
<div class="form-group">
<label class="form-label-bold" for="compensation-amount">
</label>
<input class="form-control form-control-1-8" type="text" name="percentage" id="percentage-compensation"><span class="bold-small"> %</span>
</div>
</fieldset>
</form>
<p>
<a class="button" id="amountLandCompensationBtn" role="button" href="land-ownership">Continue</a>
</p>
</div>
</div>
</main>
<script>
var editCheck = sessionStorage.getItem('editing');
if (editCheck === 'true') {
document.getElementById('amountLandCompensationBtn').setAttribute('href', 'charge-summary-new');
}
document.getElementById('amountLandCompensationBtn').onclick = function() {
sessionStorage.setItem('landCompAmountGiven', 'true');
var landCompAmount = document.getElementById('compensation-amount').value;
sessionStorage.setItem('landCompAmount', landCompAmount);
var percentageOfAmount = document.getElementById('percentage').value;
sessionStorage.setItem('percentageOfAmount', percentageOfAmount);
}
</script>
{% endblock %} | LandRegistry/llc-prototype | app/views/add_charge/v4-9-3/amount-of-compensation.html | HTML | mit | 3,071 |
file preempt-sched.elf
target remote localhost:8282
load
break main
| dmcniven/preemptive-scheduler | gdb_startup.cmd | Batchfile | mit | 68 |
require 'integration_helper'
class Debian6BootstrapTest < IntegrationTest
def user
"admin"
end
def image_id
"ami-4d20a724"
end
def prepare_server
# Do nothing as `solo bootstrap` will do everything
end
include Apache2Bootstrap
end
| outsmartin/ispconfig3 | vendor/bundler/ruby/2.0.0/gems/knife-solo-0.2.0/test/integration/debian6_bootstrap_test.rb | Ruby | mit | 261 |
## MIPS 汇编器
### 常量/类型定义
我们先定义了一些常量。其中 `CMD_ID` 保存了 I 型和 R 型指令的 OpCode 或 R 型指令的功能码,`REGS` 则保存了各个寄存器的名字:
```ruby
CMD_ID = {
nop: 0x0,
lw: 0x23, sw: 0x2b,
lui: 0x0f,
add: 0x20, addu: 0x21, sub: 0x22, subu: 0x23, and: 0x24, or: 0x25, xor: 0x26, nor: 0x27, slt: 0x2a,
addi: 0x08, addiu: 0x09, andi: 0x0c, slti: 0x0a, sltiu: 0x0b,
sll: 0x0, srl: 0x02, sra: 0x03,
beq: 0x4, bne: 0x5,
blez: 0x6, bgtz: 0x7, bgez: 0x1,
j: 0x02, jal: 0x03,
jr: 0x08,
jalr: 0x09
}
REGS = %w(zero at v0 v1 a0 a1 a2 a3 t0 t1 t2 t3 t4 t5 t6 t7
s0 s1 s2 s3 s4 s5 s6 s7 t8 t9 k0 k1 gp sp fp ra)
```
然后,我们定义了 `MIPSSyntaxError`,用来充当解析错误时抛出的异常:
```ruby
# Represent a MIPS syntax error
class MIPSSyntaxError < StandardError
end
```
然后我们便可以定义 `Assembler` 类了。在我们的设计中,`Assembler` 类需要保存以下几个状态:
* `symbol_table`: 符号表,用来保存源代码中出现的标签,以及他们所对应的地址。
* `current_addr`: 当前地址,用来记录当前解析的语句所处的地址。
```ruby
def initialize
@symbol_table = {}
@current_addr = 0x0
end
```
### 汇编器实现
而汇编的思路也很简单。首先,我们扫描一遍 MIPS 源代码,在解析语法的同时保存出现的标签和其所在的地址。然后,我们再依次对解析过的各个语句进行汇编。其中,我们采用正则表达式来匹配标签和汇编指令。对于不符合语法的语句,我们直接抛出 `MIPSSyntaxError` 异常。
```ruby
def assembly(src)
cmds = []
# Read tags.
src.each_line do |line|
fail MIPSSyntaxError, "#{line}: Syntax error." unless /^\s*((?<tag>[a-zA-Z]\w*)\s*:\s*)?((?<cmd>[a-z]+)\s*((?<arg1>\$?\w+)\s*(,\s*((?<arg2>\$?\w+)|((?<offset>\d+)\(\s*(?<arg2>\$\w+)\s*\)))\s*(,\s*(?<arg3>\$?\w+)\s*)?)?)?)?(#.*)?$/ =~ line
read_tag tag
if cmd
cmds << [cmd, arg1, arg2, arg3, offset]
@current_addr += 4
end
end
# Parse commands.
@current_addr = 0
result = []
cmds.each do |cmd|
line_result = parse(*cmd)
result << line_result if line_result
@current_addr += 4
end
result
end
def self.assembly(src)
new.assembly(src)
end
```
然后我们开始具体实现解析。首先是对标签的解析。我们先在符号表中查找,如果发现相同标签就抛出异常。若没有,我们则将当前标签和当前地址加入到符号表中。
```ruby
def read_tag(tag)
return if tag.nil? # No tag.
if @symbol_table.include? tag
fail MIPSSyntaxError, "Redeclaration of tag `#{tag}`"
else
@symbol_table[tag] = @current_addr
end
end
```
紧接着,我们来对指令进行解析。注意到尽管 R 型,I 型和 J 型指令内部的结构不同,每种指令内部格式确是一样的,我们首先定义 `type_r`, `type_i` 和 `type_j` 函数,用来构建三种指令:
```ruby
def type_r(rs, rt, rd, shamt, funct)
rs << 21 | rt << 16 | rd << 11 | shamt << 6 | funct
end
def type_i(opcode, rs, rt, imm)
# Notice immi could be negative.
opcode << 26 | rs << 21 | rt << 16 | (imm & ((1 << 16) - 1))
end
def type_j(opcode, target)
opcode << 26 | (target >> 2 & ((1 << 26) - 1))
end
```
同时,我们构造一些辅助函数,来解析指令中的各个部分,包括:寄存器,整数,绝对地址,相对地址:
```ruby
def reg(arg)
name = arg[1..-1]
if arg =~ /^\$([12]?[0-9])|(3[01])$/
name.to_i
elsif (index = REGS.index(name))
index
else
fail MIPSSyntaxError, "#{arg}: Invalid register name"
end
end
def int(arg)
if /^0[xX](?<hex>\h+)$/ =~ arg
hex.to_i(16)
else
arg.to_i
end
end
def absolute_addr(tag)
addr = @symbol_table[tag]
fail MIPSSyntaxError, "#{tag}: Tag not found" if addr.nil?
addr
end
def relative_addr(tag)
addr = @symbol_table[tag]
fail MIPSSyntaxError, "#{tag}: Tag not found" if addr.nil?
(addr - @current_addr) / 4 - 1
end
```
最后,我们根据指令的类型,将指令的不同部分解析为不同类型,并用指令所属类型对应的函数构建指令:
```ruby
def parse(cmd, arg1, arg2, arg3, offset)
return if cmd.nil? # No command
cmd = cmd.to_sym
cmd_id = CMD_ID[cmd]
begin
case cmd
when :nop
0x0
when :lw, :sw
type_i(cmd_id, reg(arg2), reg(arg1), offset.to_i)
when :lui
type_i(cmd_id, 0, reg(arg1), int(arg2))
when :add, :addu, :sub, :subu, :and, :or, :xor, :nor, :slt
type_r(reg(arg2), reg(arg3), reg(arg1), 0, cmd_id)
when :addi, :addiu, :andi, :slti, :sltiu
type_i(cmd_id, reg(arg2), reg(arg1), int(arg3))
when :sll, :srl, :sra
type_r(0, reg(arg2), reg(arg1), int(arg3), cmd_id)
when :beq, :bne
type_i(cmd_id, reg(arg1), reg(arg2), relative_addr(arg3))
when :blez, :bgtz, :bgez
type_i(cmd_id, reg(arg1), (cmd == :bgez ? 1 : 0), relative_addr(arg2))
when :j, :jal
type_j(cmd_id, absolute_addr(arg1))
when :jr
type_r(reg(arg1), 0, 0, 0, cmd_id)
when :jalr
type_r(reg(arg2), 0, reg(arg1), 0, cmd_id)
else
fail MIPSSyntaxError, "#{cmd}: Unknown command"
end
rescue # Got error while parsing.
raise MIPSSyntaxError, "#{cmd}: Syntax error"
end
end
```
这样,我们就实现了一个基础的 MIPS 汇编器。
### 自动代码生成
为了简化我们的工作,我们希望实现这样的效果:我们每次修改 MIPS 代码之后,只需要运行 `rake` 指令,便能生成更新后的 `rom.v` 文件。为了达到这个目标,我们首先实现一个命令行程序,用来从 `.asm` 文件生成 `.v` 文件:
```ruby
require "mips"
code_head = <<EOS
`timescale 1ns/1ps
module ROM(addr, data);
input [31 :0] addr;
output [31:0] data;
localparam ROM_SIZE = 32;
reg [31:0] dat _DATA[ROM_SIZE-1:0];
always@(*)
case(addr[9:2]) // Address Must Be Word Aligned.
EOS
code_tail = <<EOS
default: data <= 32'h0800_0000;
endcase
endmodule
EOS
exit if ARGV.size != 2
fin = ARGV.first
result = MIPS::Assembler.assembly(File.read(fin))
fout = File.open(ARGV.last, "w")
fout.puts code_head
result.each_with_index do |line, index|
fout.puts " #{index}: data <= 32'h#{line.to_s(16).rjust(8, '0')};"
end
fout.puts code_tail
```
然后,我们在 `Rakefile` 中添加如下条目,在测试之后进行代码生成:
```ruby
task :gen_code => :test do
system "ruby", "-Ilib", "bin/assembly.rb", "test/gcd.asm", "test/rom.v"
end
```
这样,我们就完成了自动代码生成的工作。
| DigitalLogicSummerTerm2015/mips-assembler | report.md | Markdown | mit | 6,642 |
@pushd %~dp0
%windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe "StockportWebappTests_UI.csproj"
@if ERRORLEVEL 1 goto end
@cd ..\..\packages\SpecRun.Runner.*\tools
SpecRun.exe run Default.srprofile "/baseFolder:%~dp0\bin\Debug" /log:specrun.log /toolIntegration:TeamCity
:end
@popd
| smbc-digital/iag-webapp | test/StockportWebappTests_UI/runtests.cmd | Batchfile | mit | 294 |
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
import debug from '../../../debug';
import debugs from '../../debugs';
import utils from '../../helpers';
import helpers from '../helpers';
import withSimplifyResaga from '../withSimplifyResaga';
describe('withSimplifyResaga()', () => {
const MockComponent = () => <div>Hello</div>;
const requiredProps = {
setValue: jest.fn(), setValueWithFunc: jest.fn(), beforeDispatch: jest.fn(),
};
const config = {};
let rendered;
let instance;
beforeAll(() => {
Enzyme.configure({ adapter: new Adapter() });
});
beforeEach(() => {
utils.subscribeValue = jest.fn(() => jest.fn());
utils.connect = jest.fn(() => (a) => a);
const Wrapped = withSimplifyResaga(config)(MockComponent);
rendered = shallow(<Wrapped {...requiredProps} />);
instance = rendered.instance();
});
afterEach(() => jest.clearAllMocks());
describe('Smoke tests', () => {
it('should exists', () => {
expect(withSimplifyResaga).toBeDefined();
});
it('should render without exploding', () => {
expect(rendered.length).toBe(1);
});
});
describe('utils.connect', () => {
const dispatchFn = jest.fn();
let mapDispatch;
beforeEach(() => {
expect(utils.connect).toBeCalled();
expect(utils.connect.mock.calls.length).toBe(1);
expect(utils.connect.mock.calls[0].length).toBe(2);
const args = utils.connect.mock.calls[0];
expect(typeof args[0]).toBe('function');
expect(typeof args[1]).toBe('function');
mapDispatch = args[1](dispatchFn);
});
it('mapState should call utils.subscribeValue', () => {
expect(utils.subscribeValue).toBeCalled();
});
it('setValue', () => {
mapDispatch.setValue(1);
expect(dispatchFn).toBeCalled();
});
it('setValueWithFunc', () => {
mapDispatch.setValueWithFunc(1);
expect(dispatchFn).toBeCalled();
});
it('beforeDispatch', () => {
mapDispatch.beforeDispatch();
expect(dispatchFn).toBeCalled();
});
});
describe('componentWillReceiveProps', () => {
it('should NOT call debug', () => {
debug.on = jest.fn(() => false);
debugs.componentWillReceiveProps = jest.fn();
instance.componentWillReceiveProps();
expect(debugs.componentWillReceiveProps).not.toBeCalled();
});
it('should call debug', () => {
helpers.componentWillReceiveProps = jest.fn(() => 123);
debug.on = jest.fn(() => true);
debugs.componentWillReceiveProps = jest.fn();
instance.componentWillReceiveProps();
expect(debugs.componentWillReceiveProps).toBeCalled();
});
it('should pass prop.id', () => {
rendered.setProps({ id: 111 });
helpers.componentWillReceiveProps = jest.fn(() => 123);
debug.on = jest.fn(() => true);
debugs.componentWillReceiveProps = jest.fn();
instance.componentWillReceiveProps();
expect(debugs.componentWillReceiveProps).toBeCalled();
});
});
describe('componentWillUpdate', () => {
it('helpers.getValuesChanged true', () => {
helpers.getValuesChanged = jest.fn(() => ({ hi: 999 }));
instance.values = { hi: 998 };
instance.componentWillUpdate();
expect(instance.values).toEqual({ hi: 999 });
});
it('helpers.getValuesChanged false', () => {
helpers.getValuesChanged = jest.fn(() => false);
instance.values = { hi: 998 };
instance.componentWillUpdate();
expect(instance.values).toEqual({ hi: 998 });
});
});
describe('setValue', () => {
it('should call setValue', () => {
helpers.setValue = jest.fn();
instance.setValue();
expect(helpers.setValue).toBeCalled();
});
});
describe('dispatchTo', () => {
it('should call dispatchTo', () => {
helpers.dispatchTo = jest.fn();
instance.dispatchTo();
expect(helpers.dispatchTo).toBeCalled();
});
});
});
| quandhz/resaga | lib/internal/hoc/__tests__/withSimplifyResaga.test.js | JavaScript | mit | 4,019 |
window.app = window.app || {};
var app = window.app;
/**
* Control Creado para darle un like a la denuncia
*/
app.ExternalWMS = function(opt_options) {
var options = opt_options || {},
button = document.createElement('button'),
element = document.createElement('div'),
this_ = this,
parser = new ol.format.WMSCapabilities(),
multiselect = function(opciones){
return '<div class="container-fluid text-center"><div class="row">' +
'<div class="col-xs-5">' +
'<select name="from[]" id="multiselect" class="form-control" size="8" multiple="multiple">' +
opciones +
'</select>' +
'</div>' +
'<div class="col-xs-2">' +
'<button type="button" id="multiselect_rightAll" class="btn btn-block"><i class="glyphicon glyphicon-forward"></i></button>' +
'<button type="button" id="multiselect_rightSelected" class="btn btn-block"><i class="glyphicon glyphicon-chevron-right"></i></button>' +
'<button type="button" id="multiselect_leftSelected" class="btn btn-block"><i class="glyphicon glyphicon-chevron-left"></i></button>' +
'<button type="button" id="multiselect_leftAll" class="btn btn-block"><i class="glyphicon glyphicon-backward"></i></button>' +
'</div>' +
'<div class="col-xs-5">' +
'<select name="to[]" id="multiselect_to" class="form-control" size="8" multiple="multiple"></select>' +
'</div></div>' +
'<button id="add_capas" class="btn btn-success col-lg-12" style="margin-top: 5px">AÑADIR CAPAS</button>' +
'</div>'
},
message = '<div class="container-fluid"><p> Pega aquí el link hacia el servidor externo</p><input placeholder="ej: http://www.dominio.es/geoserver/wms" class="form-control col-lg-12" id="input_ext" class="col-lg-12" type="text"></input><button id="btn_ext" style="min-width : 100%" class="col-lg-12 btn btn-success">CONECTAR CON EL SERVIDOR</button></div>',
dialog_ = function() {
var dialog = new BootstrapDialog({
title : 'Añade un servidor WMS externo',
message : message,
autodestroy : true,
onshow : function(dialog){
dialog.getModalHeader().replaceWith($('<div class="row" style="margin: 0px; padding-top: 5px; border-top-left-radius: 10px; border-top-right-radius: 10px; background: url('http://www.batlleiroig.com/wp-content/uploads/247_parc_central_st_cugat_8.jpg'); background-size: cover; background-repeat: no-repeat;">' +
'<div class="bootstrap-dialog-close-button">' +
'<button class="close" style="color : #fff; margin-right : 10px;">X</button>' +
'</div>' +
'<div class="col-xs-6" style="text-align: center; color: #fff; font-weight : bold;">' +
'<i class="fa fa-external-link" style="font-size : 60px; color : #00bbff; text-shadow: 2px 2px #fff;"></i>' +
'<h4 style="padding : 2px; color : #00bbff; background : rgba(0,0,0,0.7); border-radius : 15px;"> Añade un Servidor WMS externo</h4>' +
'</div>' +
'</div>'));
dialog.getModalDialog().find('.close').click(function(){dialog.close()});
dialog.getModalBody().parent().css('border-radius', '15px');
dialog.getModalBody().css('padding-top', '10px');
},
onshown : function(d){
$(dialog.getModalBody()).find('#btn_ext').click(function(e){
var wms_ext = $(dialog.getModalBody()).find('#input_ext').val();
var regex = new RegExp(/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/);
wms_ext = wms_ext.split('?')[0];
console.log(wms_ext.match(regex));
if(!wms_ext.match(regex))
return BootstrapDialog.show({
title : 'Error',
message : 'Debe introducir una URL válida',
onshow : function(dialog){$(dialog.getModalHeader()).css('background', 'rgb(200,50,50)')}
});
var xhr = new XMLHttpRequest();
var url = wms_ext + '?request=GetCapabilities&service=WMS&version=1.3.0';
var params = {url : url, method : 'GET'};
xhr.open('GET', "/xhr?" + $.param(params), true);
//xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.onload = function(){
//console.log(xhr.responseText);
try {
var json_cap = parser.read(xhr.responseText);
//console.log(json_cap);
var opts = '';
json_cap.Capability.Layer.Layer.forEach(function(layer){
console.log(layer);
// TODO --> Mostrar capas en un recuadro, decirle al usuario que
// elija las que quiera y cargarlas como un grupo de capas
opts += '<option value="' + layer.Name + '">' + layer.Name + '</option>';
});
//dialog.setData('url', url);
$(dialog.getModalBody()).empty().append($(multiselect(opts)));
$(dialog.getModalBody()).find('#multiselect').multiselect({
keepRenderingSort : true,
});
$(dialog.getModalBody()).find('button').css('min-width', '0px');
$(dialog.getModalBody()).find('#add_capas').click(function(){
var layers = [];
$('#multiselect_to > option').each(function(){
console.log($(this).val());
layers.push(new ol.layer.Tile({
title: $(this).val(),
visible: true,
source: new ol.source.TileWMS({
//crossOrigin: 'anonymous', // So important maniguiiiiii
url: wms_ext,
params: {
'FORMAT': 'image/png',
VERSION : '1.1.0',
LAYERS: $(this).val(),
STYLES: '',
}
})
}));
}); // multiselect option each
map.addLayer(new ol.layer.Group({
title : wms_ext,
layers : layers
}));
d.close();
}); // add capas click
} catch (e) {
BootstrapDialog.show({
title : 'Error',
message : 'Error conectando al Servidor externo: \n' + e,
onshow : function(dialog){
$(dialog.getModalHeader()).css('background', 'rgb(200,50,50)');
}
});
}
};
xhr.send();
});
}
});
dialog.open();
};
function external_wms (){
dialog_();
};
button.innerHTML = '<i class="fa fa-external-link"></i>';
button.addEventListener('click', external_wms, false);
element.setAttribute('data-toggle', 'left');
element.setAttribute('title', 'WMS Externo');
element.setAttribute('data-content', 'Añade capas de un servidor WMS externo');
element.className = 'external_wms ol-unselectable ol-control';
element.appendChild(button);
ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(app.ExternalWMS, ol.control.Control); | joseahr/informaTorrent-Node.JS | public/javascripts/openlayers/controles/external_wms.js | JavaScript | mit | 7,290 |
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/7.0.67
* Generated at: 2015-12-23 08:29:09 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.naming.*;
public final class e2end_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
public Connection getConnection() throws Exception {
//DataSource datasource = (DataSource) new InitialContext().lookup("java:/comp/env/jdbc/hsql");
//return datasource.getConnection();
return DriverManager.getConnection("jdbc:hsqldb:mydatabase","sa","");
}
Random rand = new Random();
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("<html>\n");
out.write("<body>\n");
Thread.sleep(rand.nextInt(1000));
Connection conn = getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from scouter");
while (rs.next()) {
String id = rs.getString(1);
String name = rs.getString(2);
out.println(id + " " + name + "<br>");
}
rs.close();
stmt.close();
conn.commit();
conn.close();
out.write("\t\n");
out.write("This is e2end.jsp\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| scouter-project/scouter-demo | demo-env1/apache-tomcat-7.0.67/work/Catalina/localhost/jpetstore/org/apache/jsp/e2end_jsp.java | Java | mit | 4,587 |
<?php
session_start();
$link=mysqli_connect("localhost","root","opom2317") or die ("Unable to connect".
mysqli_error($link));
$q=mysqli_select_db($link,"permohonan");
$sv = $_SESSION['id_user'];
$query="SELECT * FROM supervisor WHERE sv_username='$sv'";
$result = mysqli_query($link,$query) or die('Query failed. ' . mysqli_error($link));
$q=mysqli_query($link,$query);
while( $row = mysqli_fetch_assoc($result) )
{
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>OFFICE MANAGEMENT SYSTEM</title>
<!-- Bootstrap Core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="svhome.php">Supervisor Page</a>
</div>
<!-- Top Menu Items -->
<ul class="nav navbar-right top-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-fw fa-user"></i> <?php echo $row['name']; ?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="svdisplaybiodata.php"><i class="fa fa-fw fa-user"></i> Profile</a>
</li>
<li>
<a href="svchgpass.php"><i class="fa fa-fw fa-gear"></i> Settings</a>
</li>
<li class="divider"></li>
<li>
<a href="../logout.php"><i class=fa fa-sign-out fa-fw"></i> Log Out</a>
</li>
</ul>
</li>
</ul>
<?php
}
?>
<!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav side-nav">
<li class="active">
<a href="svhome.php"><i class="fa fa-fw fa-dashboard"></i> Dashboard</a>
</li>
<li>
<a href="javascript:;" data-toggle="collapse" data-target="#demo"><i class="fa fa-fw fa-edit"></i> Office Leave <i class="fa fa-fw fa-caret-down"></i></a>
<ul id="demo" class="collapse">
<li>
<a href="svofficeleave.php">Office Leave Form</a>
</li>
<li>
<a href="svstatusofficeleave.php">Status </a>
</li>
<li>
<a href="svofficeleaverecords.php">View Records</a>
</ul>
</li>
<li>
<a href="javascript:;" data-toggle="collapse" data-target="#demo1"><i class="fa fa-fw fa-edit"></i> Leave <i class="fa fa-fw fa-caret-down"></i></a>
<ul id="demo1" class="collapse">
<li>
<a href="svleave.php">Leave</a>
</li>
<li>
<a href="svstatusleave.php">Status </a>
</li>
<li>
<a href="svleaverecords.php">View Records</a>
</ul>
</li>
<li>
<a href="javascript:;" data-toggle="collapse" data-target="#demo2"><i class="fa fa-fw fa-edit"></i> Application <i class="fa fa-fw fa-caret-down"></i></a>
<ul id="demo2" class="collapse">
<li>
<a href="svappofficeleave.php">Validate Office Leave Form</a>
</li>
<li>
<a href="svappleave.php">Validate Leave Form </a>
</li>
</ul>
</li>
<li>
<a href="svcalendar.php"><i class="fa fa-fw fa-calendar"></i> Calendar</a>
</li>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
<?php
$link=mysqli_connect("localhost","root","opom2317") or die ("Unable to connect".
mysqli_error($link));
$q=mysqli_select_db($link,"permohonan");
$staff = $_SESSION['id_user'];
$name = $_SESSION['user_name'];
$query="SELECT * FROM request WHERE role='staff' AND status = 0";
$result = mysqli_query($link,$query) or die('Query failed. ' . mysqli_error($link));
$q=mysqli_query($link,$query);
$num_rows= mysqli_num_rows($q);
?>
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
Office Leave
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="svhome.php">Dashboard</a>
</li>
<li class="active">
<i class="fa fa-table"></i> Validation
</li>
</ol>
</div>
</div>
<!-- /.row -->
<div class="row">
<!--<div class="col-lg-6">-->
</center>
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th><center>Name</center></th>
<th><center>Department</center></th>
<th><center>Status</center></th>
<th><center>Action</center></th>
</tr>
</thead
<?php
while($row=mysqli_fetch_array($result))
{
?>
<tbody>
<tr align="center">
<td><?php echo $row['name'];?></td>
<td><?php echo $row['department'];?></td>
<td> <?php
if ( $row['status'] == "0") {
echo "Pending";
} else {
echo "Approved";
}
?></td>
<td><a href="applicationstaffformsv.php?no=<?php echo $row['no'];?>"><img src="../css/img/pencil.png" style="30" width="30"/> </a>
</tr>
<?php
}
mysqli_close($link);
?>
</tbody>
</table>
</div>
</div>
<br>
<br>
<br>
<br>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="../js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="../js/bootstrap.min.js"></script>
</body>
</html>
| wanaimannnn/fyp | supervisor/svappofficeleave.php | PHP | mit | 9,603 |
import React from "react";
export default class extends React.Component {
render() {
const arrayIdentifier = ["good", "luck"];
return (
<div className={this.props.isOpen ? "yup" : arrayIdentifier.join(" ")}>
Base test.
</div>
);
}
};
| walmartreact/babel-plugin-react-cssmoduleify | test/fixtures/jsx/binary-expression/actual.js | JavaScript | mit | 273 |
/*
* Copyright (c) 2009-2010 Secure Endpoints Inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "khmapp.h"
static const wchar_t * _exp_env_vars[] = {
L"TMP",
L"TEMP",
L"APPDATA",
L"USERPROFILE",
L"ALLUSERSPROFILE",
L"SystemRoot"
#if 0
/* Replacing this is not typically useful */
L"SystemDrive"
#endif
};
const int _n_exp_env_vars = ARRAYLENGTH(_exp_env_vars);
static int
check_and_replace_env_prefix(wchar_t * s, size_t cb_s, const wchar_t * env) {
wchar_t evalue[MAX_PATH];
DWORD len;
size_t sz;
evalue[0] = L'\0';
len = GetEnvironmentVariable(env, evalue, ARRAYLENGTH(evalue));
if (len > ARRAYLENGTH(evalue) || len == 0)
return 0;
if (_wcsnicmp(s, evalue, len))
return 0;
if (SUCCEEDED(StringCbPrintf(evalue, sizeof(evalue), L"%%%s%%%s",
env, s + len)) &&
SUCCEEDED(StringCbLength(evalue, sizeof(evalue), &sz)) &&
sz <= cb_s) {
StringCbCopy(s, cb_s, evalue);
}
return 1;
}
/* We use this instead of PathUnexpandEnvStrings() because that API
doesn't take process TMP and TEMP. The string is modified
in-place. The usual case is to call it with a buffer big enough to
hold MAX_PATH characters. */
void
unexpand_env_var_prefix(wchar_t * s, size_t cb_s) {
int i;
for (i=0; i < _n_exp_env_vars; i++) {
if (check_and_replace_env_prefix(s, cb_s, _exp_env_vars[i]))
return;
}
}
| secure-endpoints/netidmgr | ui/envvar.c | C | mit | 2,521 |
package com.fly.firefly.ui.activity.BookingFlight;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import com.fly.firefly.AnalyticsApplication;
import com.fly.firefly.MainFragmentActivity;
import com.fly.firefly.R;
import com.fly.firefly.ui.activity.FragmentContainerActivity;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import butterknife.ButterKnife;
//import android.view.WindowManager;
public class FlightSummaryActivity2 extends MainFragmentActivity implements FragmentContainerActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.inject(this);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.main_content, FlightSummaryFragment.newInstance()).commit();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public int getFragmentContainerId() {
return R.id.main_content;
}
}
| zatyabdullah/Fy | rhymecity/src/main/java/com/fly/firefly/ui/activity/BookingFlight/FlightSummaryActivity2.java | Java | mit | 1,215 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Dec 03 19:50:50 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>net.sourceforge.pmd.cpd (PMD Core 5.2.2 Test API)</title>
<meta name="date" content="2014-12-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../net/sourceforge/pmd/cpd/package-summary.html" target="classFrame">net.sourceforge.pmd.cpd</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AnyTokenizerTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">AnyTokenizerTest</a></li>
<li><a href="CpddummyLanguage.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">CpddummyLanguage</a></li>
<li><a href="CPDTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">CPDTest</a></li>
<li><a href="FileReporterTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">FileReporterTest</a></li>
<li><a href="LanguageFactoryTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">LanguageFactoryTest</a></li>
<li><a href="MatchTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">MatchTest</a></li>
<li><a href="SourceCodeTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">SourceCodeTest</a></li>
<li><a href="TokenEntryTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">TokenEntryTest</a></li>
<li><a href="XMLRendererTest.html" title="class in net.sourceforge.pmd.cpd" target="classFrame">XMLRendererTest</a></li>
</ul>
</div>
</body>
</html>
| byronka/xenos | utils/pmd-bin-5.2.2/docs/pmd-core/testapidocs/net/sourceforge/pmd/cpd/package-frame.html | HTML | mit | 1,821 |
package com.panzareon.spellcircles.spell.parts;
import com.panzareon.spellcircles.exception.MissingAuraException;
import com.panzareon.spellcircles.spell.SpellPart;
import com.panzareon.spellcircles.spell.SpellPartValue;
import com.panzareon.spellcircles.spell.SpellReturnTypes;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.math.Vec3d;
public class SpellPartSlowness extends SpellPart
{
private final float AuraUse = 1.0f;
@Override
public String getSpellName() {
return "SNDGB";
}
@Override
public String getSpellId() {
return "slowness";
}
@Override
public int getNrOfChildren() {
return 3;
}
@Override
public SpellReturnTypes[] getReturnValueTypes() {
return new SpellReturnTypes[]{SpellReturnTypes.ACTION};
}
@Override
protected SpellPartValue cast(SpellPartValue[] childValues) throws MissingAuraException {
int nr = childValues[0].getEntityLength();
int nr2 = childValues[1].getNumberLength();
int nr3 = childValues[2].getNumberLength();
if(nr > 0 && nr2 > 0 && nr3 > 0)
{
if(nr < nr2)
nr = nr2;
if(nr < nr3)
nr = nr3;
Vec3d castPos = environ.getCastPosition();
float auraMultiplier;
float slowStrength;
EntityLivingBase target;
int effectDuration;
for(int i = 0; i < nr; i++)
{
slowStrength = (float) Math.floor(childValues[1].getNumber(i));
target = (EntityLivingBase) childValues[0].getEntity(i);
effectDuration = (int)(childValues[2].getNumber(i) * 20);
if(target == null || slowStrength <= 0 || effectDuration < 20)
continue;
if(slowStrength > 5)
slowStrength = 5;
//calculate Aura expense
auraMultiplier = (float) castPos.squareDistanceTo(target.getPositionVector());
if(environ.useAura((int) ((AuraUse + auraMultiplier)*slowStrength*effectDuration), environ.strength))
{
target.addPotionEffect(new PotionEffect(Potion.getPotionFromResourceLocation("slowness"), effectDuration, (int) slowStrength));
}
else
{
throw new MissingAuraException(this);
}
}
}
return new SpellPartValue();
}
@Override
public SpellReturnTypes getChildType(int childId)
{
if(childId == 0)
{
return SpellReturnTypes.ENTITY;
}
else if(childId == 1)
{
return SpellReturnTypes.NUMBER;
}
else if(childId == 2)
{
return SpellReturnTypes.NUMBER;
}
return super.getChildType(childId);
}
}
| Panzareon/SpellCircles | src/main/java/com/panzareon/spellcircles/spell/parts/SpellPartSlowness.java | Java | mit | 3,004 |
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var draws = require('../../app/controllers/draws.server.controller');
// Draws Routes
app.route('/draws')
.get(draws.list)
.post(users.requiresLogin, draws.create);
app.route('/draws/:drawId')
.get(draws.read)
.put(users.requiresLogin, draws.hasAuthorization, draws.update)
.delete(users.requiresLogin, draws.hasAuthorization, draws.delete);
// Finish by binding the Draw middleware
app.param('drawId', draws.drawByID);
};
| Karmacons/nhcgala | app/routes/draws.server.routes.js | JavaScript | mit | 561 |
/**
* Copyright © 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved.
*/
package com.beiyelin.shop.modules.shop.utils;
import com.beiyelin.shop.modules.shop.entity.ShopCategory;
import com.beiyelin.shop.modules.shop.service.ShopCategoryService;
import com.google.common.collect.Lists;
import com.beiyelin.shop.common.utils.CacheUtils;
import com.beiyelin.shop.common.utils.SpringContextHolder;
import org.springframework.ui.Model;
import javax.servlet.ServletContext;
import java.util.List;
import java.util.Map;
/**
* 内容管理工具类
* @author Tony Wong
* @version 2013-5-29
*/
public class ShopCategoryUtils {
private static ShopCategoryService categoryService = SpringContextHolder.getBean(ShopCategoryService.class);
private static ServletContext context = SpringContextHolder.getBean(ServletContext.class);
/** cache name and keys **/
public static final String CACHE_NAME = "ShopCategory";
public static final String CK_Category = "Category_";
public static final String CK_findFirstList = "findFirstList";
public static final String CK_getFirstSortCategory = "getFirstSortCategory";
//每次目录或产品的修改都要清空这个缓存
public static final String CK_findFirstListWithProduct4App = "findFirstListWithProduct4App";
public static ShopCategory getCategory(String categoryId) {
String key = CK_Category + categoryId;
ShopCategory category = (ShopCategory) getCache(key);
if (category == null) {
category = categoryService.get(categoryId);
putCache(key, category);
}
return category;
}
/**
* 获得第一级目录列表
*/
public static List<ShopCategory> findFirstList(){
String key = CK_findFirstList;
List<ShopCategory> list = (List<ShopCategory>) getCache(key);
if (list == null){
list = categoryService.findFirstList();
putCache(key, list);
}
return list;
}
/**
* 取得排列第一的目录
*/
public static ShopCategory getFirstSortCategory() {
String key = CK_getFirstSortCategory;
ShopCategory category = (ShopCategory) getCache(key);
if (category == null) {
category = categoryService.getFirstSortCategory();
putCache(key, category);
}
return category;
}
/*====================== for app ========================*/
/**
* 获得第一级目录列表和对应的产品列表
* @return [{
* id:""
* name:""
* productList:[{
* id:""
* name:""
* imageSmall:""
* },...]
* },...]
*/
public static List<Map<String, Object>> findFirstListWithProduct4App() {
List<Map<String, Object>> list = categoryService.findFirstListWithProduct4App();
return list;
}
// ============== Shop Category Cache ==============
public static Object getCache(String key) {
return CacheUtils.get(CACHE_NAME, key);
}
public static void putCache(String key, Object value) {
CacheUtils.put(CACHE_NAME, key, value);
}
public static void removeCache(String key) {
CacheUtils.remove(CACHE_NAME, key);
}
public static void removeAllCache() {
CacheUtils.removeAll(CACHE_NAME);
}
/**
* 每次目录或产品的修改都要清空这个缓存
*/
public static void removeCache4_findFirstListWithProduct4App() {
CacheUtils.remove(CACHE_NAME, CK_findFirstListWithProduct4App);
}
} | newmann/backstone | src/main/java/com/beiyelin/shop/modules/shop/utils/ShopCategoryUtils.java | Java | mit | 3,490 |
<div class="row">
<div id="like" class="jumbotron col-md-12" >
<div ng-if="!isRecommendationExist">
No more recommendations for you! Please come back again!
</div>
<div class="col-md-12 like-picture-container" ng-if="isRecommendationExist">
<div id="like-picture-container">
<img id="like-picture-image" ng-src="{{likees[currentLikeeIndex].image}}">
</div>
</div>
<div class="col-md-12" id="like-profile" ng-if="isRecommendationExist">
{{likees[currentLikeeIndex].first_name}}, {{likees[currentLikeeIndex].age}}
</div>
<div class="col-md-3 btn btn-danger" id="button-dislike" ng-if="isRecommendationExist" ng-click="postNewLike(false)">
Dislike
</div>
<div class="col-md-offset-6 col-md-3 btn btn-success" id="button-like" ng-if="isRecommendationExist" ng-click="postNewLike(true)">
Like
</div>
</div>
</div>
| cs411sp15vmnjhtdw/MeetU | meetu/static/views/like/_like_tools.html | HTML | mit | 918 |
'''
following: https://github.com/jorditorresBCN/LibroTensorFlow <- doesn't work due to breaking changes
This scripts loads already extracted data from "bio_select_variables" and finds linear regression between number of select variables and execution time
'''
import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from bio_select_variables import *
# plt.rcParams['font.family'] = 'serif'
# plt.rcParams['font.serif'] = 'Ubuntu'
# plt.rcParams['font.monospace'] = 'Ubuntu Mono'
# plt.rcParams['font.size'] = 10
# plt.rcParams['axes.labelsize'] = 10
# plt.rcParams['axes.labelweight'] = 'bold'
# plt.rcParams['xtick.labelsize'] = 8
# plt.rcParams['ytick.labelsize'] = 8
# plt.rcParams['legend.fontsize'] = 10
# plt.rcParams['figure.titlesize'] = 12
rng = np.random
# Parameters
learning_rate = 0.01
epochs = 1000
#Set training arrays
train_X = np.array([])
train_Y = np.array([])
# Set model weights
W = tf.Variable(rng.randn(), name="weight", dtype=tf.float64)
b = tf.Variable(rng.randn(), name="bias", dtype=tf.float64)
n_samples = 0
#load BioPortal data and append training vectors
def load_bio_data():
db = readout_feature()
global train_X
global train_Y
global n_samples
#load in first 2000 datapoints
for entry in (line for i, line in enumerate(db) if i<=2000):
entry = re.split(r'[\t|\n]', entry)
try:
#first try at taking out outliers, plot is unreadable otherwise
#TODO - find better solution
if 0 < float(entry[1]) and float(entry[1]) < 10 and float(entry[0])<7:
# print(entry)
train_X = np.append(train_X,float(entry[0]))
train_Y = np.append(train_Y,float(entry[1]))
n_samples += 1
except ValueError,e:
print ("error",e,"on line",entry)
return db
def load_dbpedia_data():
def linear_model():
# Construct a linear model
return tf.add(tf.mul(train_X, W), b)
def train_linear_model(data):
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
pred = linear_model()
# # Mean squared error
# cost = tf.reduce_sum(tf.pow(pred-Y, 2))/(2*len(data))
cost = tf.reduce_mean(tf.square(pred - train_Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train = optimizer.minimize(cost)
for epoch in range(epochs):
sess.run(train)
print(epoch, sess.run(W), sess.run(b))
print(epoch, sess.run(cost))
print(len(data))
#Graphic display
plt.plot(train_X, train_Y, 'ro')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), linestyle="-")
plt.xlabel('SELECT variables')
plt.ylabel('Execution time')
plt.xticks([1,2,3,4])
plt.xlim(0.97,4.03)
# plt.ylim(-0.1,10.1)
plt.legend()
plt.show()
def main():
data = load_db_data()
train_linear_model(data)
if __name__ == '__main__':
main() | derdav3/tf-sparql | data/BioPortal/bio_select_linear_regression.py | Python | mit | 3,051 |
"""empty message
Revision ID: f6eab383c7de
Revises: None
Create Date: 2016-07-22 11:01:28.783123
"""
# revision identifiers, used by Alembic.
revision = 'f6eab383c7de'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('book',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=True),
sa.Column('author', sa.String(), nullable=True),
sa.Column('publisher', sa.String(), nullable=True),
sa.Column('genter', sa.String(), nullable=True),
sa.Column('isbn', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('borrow',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('id_lender', sa.Integer(), nullable=False),
sa.Column('id_borrowe', sa.Integer(), nullable=False),
sa.Column('id_book', sa.Integer(), nullable=False),
sa.Column('final_date', sa.Date(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('password', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=True),
sa.Column('cpf', sa.String(), nullable=True),
sa.Column('gender', sa.String(), nullable=True),
sa.Column('birtday', sa.Date(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('user')
op.drop_table('borrow')
op.drop_table('book')
### end Alembic commands ###
| leonardowolf/bookfree | migrations/versions/f6eab383c7de_.py | Python | mit | 1,752 |
function solution(num) {
for (let i = 1; i <= num; i++) {
if (i % 2 !== 0)
console.log(i);
}
}
solution(7); | George221b/SoftUni-Tasks | JSFundamentals/02.ExpressionsConditionalStatementsAndLoops/16.OddNumbers1toN.js | JavaScript | mit | 136 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PropertyInsurance.API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PropertyInsurance.API")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("16f6315b-06a4-427c-8615-28a292b4cfef")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| TBag/canviz | Cloud/PropertyInsurance.API/Properties/AssemblyInfo.cs | C# | mit | 1,373 |
//Write a program for generating and printing all subsets of k strings from given set of strings.
// Example: s = {test, rock, fun}, k=2
// (test rock), (test fun), (rock fun)
namespace DSA_Recursion_Homework
{
using System;
public class AllSubsetsOfKStrings
{
//static void Main()
//{
// //Console.Write("Enter n: ");
// //int n = int.Parse(Console.ReadLine());
// //Console.Write("Enter k: ");
// //int k = int.Parse(Console.ReadLine());
// //string[] set = new string[n];
// //for (int i = 0; i < n; i++)
// //{
// // Console.Write("Enter {0} element: ",i+1);
// // set[i] = Console.ReadLine();
// //}
// int n = 3;
// int k = 2;
// var set = new string[] { "test", "rock", "fun" };
// string[] stringToPrint = new string[k];
// Combos(0, n, 0, set, stringToPrint);
//}
private static void Combos(int index, int n, int start, string[] set, string[] stringToPrint)
{
if (index >= stringToPrint.Length)
{
Console.WriteLine("( " + string.Join(",", stringToPrint) + " )");
}
else
{
for (int i = start; i < n; i++)
{
stringToPrint[index] = set[i];
Combos(index + 1, n, i + 1, set, stringToPrint);
}
}
}
}
} | kaizer04/Telerik-Academy-2013-2014 | DSA/DSA-Recursion-Homework/DSA-Recursion-Homework/06.AllSubsetsOfKStrings.cs | C# | mit | 1,518 |
module SimpleMigrator
VERSION = "0.0.3"
end
| jesjos/simple_migrator | lib/simple_migrator/version.rb | Ruby | mit | 46 |
#include "defs.h"
void transitive_closure(unsigned *R, int n)
{
register int rowsize;
register unsigned mask;
register unsigned *rowj;
register unsigned *rp;
register unsigned *rend;
register unsigned *ccol;
register unsigned *relend;
register unsigned *cword;
register unsigned *rowi;
rowsize = WORDSIZE(n);
relend = R + n*rowsize;
cword = R;
mask = 1;
rowi = R;
while (rowi < relend)
{
ccol = cword;
rowj = R;
while (rowj < relend)
{
if (*ccol & mask)
{
rp = rowi;
rend = rowj + rowsize;
while (rowj < rend)
*rowj++ |= *rp++;
}
else
{
rowj += rowsize;
}
ccol += rowsize;
}
mask <<= 1;
if (mask == 0)
{
mask = 1;
cword++;
}
rowi += rowsize;
}
}
void reflexive_transitive_closure(unsigned *R, int n)
{
register int rowsize;
register unsigned mask;
register unsigned *rp;
register unsigned *relend;
transitive_closure(R, n);
rowsize = WORDSIZE(n);
relend = R + n*rowsize;
mask = 1;
rp = R;
while (rp < relend)
{
*rp |= mask;
mask <<= 1;
if (mask == 0)
{
mask = 1;
rp++;
}
rp += rowsize;
}
}
| satya-das/cppparser | third_party/btyacc_tp/btyacc/warshall.c | C | mit | 1,203 |
/*
* This is the source code of Telegram for Android v. 1.4.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package com.yahala.ui.Views;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import com.yahala.android.OSUtilities;
import com.yahala.messenger.R;
import com.yahala.objects.MessageObject;
import com.yahala.ui.Rows.BaseCell;
import com.yahala.xmpp.FileLoader;
import com.yahala.android.MediaController;
import java.io.File;
public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate, MediaController.FileDownloadProgressListener {
private boolean wasLayout = false;
protected MessageObject currentMessageObject;
private static Drawable backgroundMediaDrawableIn;
private static Drawable[][] statesDrawable = new Drawable[8][2];
private static TextPaint timePaint;
private SeekBar seekBar;
private ProgressView progressView;
private int seekBarX;
private int seekBarY;
private int buttonState = 0;
private int buttonX;
private int buttonY;
private int buttonPressed = 0;
private StaticLayout timeLayout;
private int timeX;
int timeWidth = 0;
private String lastTimeString = null;
private int TAG;
public PopupAudioView(Context context) {
super(context);
if (backgroundMediaDrawableIn == null) {
backgroundMediaDrawableIn = getResources().getDrawable(R.drawable.msg_in_photo);
statesDrawable[0][0] = getResources().getDrawable(R.drawable.play1);
statesDrawable[0][1] = getResources().getDrawable(R.drawable.play1_pressed);
statesDrawable[1][0] = getResources().getDrawable(R.drawable.pause1);
statesDrawable[1][1] = getResources().getDrawable(R.drawable.pause1_pressed);
statesDrawable[2][0] = getResources().getDrawable(R.drawable.audioload1);
statesDrawable[2][1] = getResources().getDrawable(R.drawable.audioload1_pressed);
statesDrawable[3][0] = getResources().getDrawable(R.drawable.audiocancel1);
statesDrawable[3][1] = getResources().getDrawable(R.drawable.audiocancel1_pressed);
statesDrawable[4][0] = getResources().getDrawable(R.drawable.play2);
statesDrawable[4][1] = getResources().getDrawable(R.drawable.play2_pressed);
statesDrawable[5][0] = getResources().getDrawable(R.drawable.pause2);
statesDrawable[5][1] = getResources().getDrawable(R.drawable.pause2_pressed);
statesDrawable[6][0] = getResources().getDrawable(R.drawable.audioload2);
statesDrawable[6][1] = getResources().getDrawable(R.drawable.audioload2_pressed);
statesDrawable[7][0] = getResources().getDrawable(R.drawable.audiocancel2);
statesDrawable[7][1] = getResources().getDrawable(R.drawable.audiocancel2_pressed);
timePaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaint.setTextSize(OSUtilities.dp(16));
}
TAG = MediaController.getInstance().generateObserverTag();
seekBar = new SeekBar(getContext());
seekBar.delegate = this;
progressView = new ProgressView();
}
public void setMessageObject(MessageObject messageObject) {
if (currentMessageObject != messageObject) {
String jid = messageObject.messageOwner.getJid();
seekBar.type = 1;
progressView.setProgressColors(0xffd9e2eb, 0xff86c5f8);
currentMessageObject = messageObject;
wasLayout = false;
/*if (currentMessageObject.messageOwner.id < 0 && currentMessageObject.messageOwner.getSend_state() != XMPPManager.MESSAGE_SEND_STATE_SEND_ERROR && currentMessageObject.messageOwner.getSend_state() != XMPPManager.MESSAGE_SEND_STATE_SENT) {
if (MessagesController.getInstance().sendingMessages.get(currentMessageObject.messageOwner.id) == null) {
currentMessageObject.messageOwner.send_state = MessagesController.MESSAGE_SEND_STATE_SEND_ERROR;
}
}*/
requestLayout();
}
updateButtonState();
}
public final MessageObject getMessageObject() {
return currentMessageObject;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
setMeasuredDimension(width, OSUtilities.dp(56));
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (currentMessageObject == null) {
super.onLayout(changed, left, top, right, bottom);
return;
}
seekBarX = OSUtilities.dp(40);
buttonX = OSUtilities.dp(10);
timeX = getMeasuredWidth() - timeWidth - OSUtilities.dp(16);
seekBar.width = getMeasuredWidth() - OSUtilities.dp(56) - timeWidth;
seekBar.height = OSUtilities.dp(30);
progressView.width = getMeasuredWidth() - OSUtilities.dp(80) - timeWidth;
progressView.height = OSUtilities.dp(30);
seekBarY = OSUtilities.dp(13);
buttonY = OSUtilities.dp(10);
updateProgress();
if (changed || !wasLayout) {
wasLayout = true;
}
}
@Override
protected void onDraw(Canvas canvas) {
if (currentMessageObject == null) {
return;
}
if (!wasLayout) {
requestLayout();
return;
}
setDrawableBounds(backgroundMediaDrawableIn, 0, 0, getMeasuredWidth(), getMeasuredHeight());
backgroundMediaDrawableIn.draw(canvas);
if (currentMessageObject == null) {
return;
}
canvas.save();
if (buttonState == 0 || buttonState == 1) {
canvas.translate(seekBarX, seekBarY);
seekBar.draw(canvas);
} else {
canvas.translate(seekBarX + OSUtilities.dp(12), seekBarY);
progressView.draw(canvas);
}
canvas.restore();
int state = buttonState + 4;
timePaint.setColor(0xffa1aab3);
Drawable buttonDrawable = statesDrawable[state][buttonPressed];
int side = OSUtilities.dp(36);
int x = (side - buttonDrawable.getIntrinsicWidth()) / 2;
int y = (side - buttonDrawable.getIntrinsicHeight()) / 2;
setDrawableBounds(buttonDrawable, x + buttonX, y + buttonY);
buttonDrawable.draw(canvas);
canvas.save();
canvas.translate(timeX, OSUtilities.dp(18));
timeLayout.draw(canvas);
canvas.restore();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
MediaController.getInstance().removeLoadingFileObserver(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
boolean result = seekBar.onTouch(event.getAction(), event.getX() - seekBarX, event.getY() - seekBarY);
if (result) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
}
invalidate();
} else {
int side = OSUtilities.dp(36);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side) {
buttonPressed = 1;
invalidate();
result = true;
}
} else if (buttonPressed == 1) {
if (event.getAction() == MotionEvent.ACTION_UP) {
buttonPressed = 0;
playSoundEffect(SoundEffectConstants.CLICK);
didPressedButton();
invalidate();
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
buttonPressed = 0;
invalidate();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (!(x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side)) {
buttonPressed = 0;
invalidate();
}
}
}
if (!result) {
result = super.onTouchEvent(event);
}
}
return result;
}
private void didPressedButton() {
if (buttonState == 0) {
boolean result = MediaController.getInstance().playAudio(currentMessageObject);
if (result) {
buttonState = 1;
invalidate();
}
} else if (buttonState == 1) {
boolean result = MediaController.getInstance().pauseAudio(currentMessageObject);
if (result) {
buttonState = 0;
invalidate();
}
} else if (buttonState == 2) {
FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.tl_message.media.audio);
buttonState = 3;
invalidate();
} else if (buttonState == 3) {
FileLoader.getInstance().cancelLoadFile(null, null, null, currentMessageObject.messageOwner.tl_message.media.audio);
buttonState = 2;
invalidate();
}
}
public void updateProgress() {
if (currentMessageObject == null) {
return;
}
if (!seekBar.isDragging()) {
seekBar.setProgress(currentMessageObject.audioProgress);
}
int duration = 0;
if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) {
duration = currentMessageObject.messageOwner.tl_message.media.audio.duration;
} else {
duration = currentMessageObject.audioProgressSec;
}
String timeString = String.format("%02d:%02d", duration / 60, duration % 60);
if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) {
timeWidth = (int) Math.ceil(timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
invalidate();
}
public void downloadAudioIfNeed() {
if (buttonState == 2) {
FileLoader.getInstance().loadFile(null, null, null, currentMessageObject.messageOwner.tl_message.media.audio);
buttonState = 3;
invalidate();
}
}
public void updateButtonState() {
String fileName = currentMessageObject.getFileName();
File cacheFile = new File(OSUtilities.getCacheDir(), fileName);
if (cacheFile.exists()) {
MediaController.getInstance().removeLoadingFileObserver(this);
boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject);
if (!playing || playing && MediaController.getInstance().isAudioPaused()) {
buttonState = 0;
} else {
buttonState = 1;
}
progressView.setProgress(0);
} else {
MediaController.getInstance().addLoadingFileObserver(fileName, this);
if (!FileLoader.getInstance().isLoadingFile(fileName)) {
buttonState = 2;
progressView.setProgress(0);
} else {
buttonState = 3;
Float progress = FileLoader.getInstance().fileProgresses.get(fileName);
if (progress != null) {
progressView.setProgress(progress);
} else {
progressView.setProgress(0);
}
}
}
updateProgress();
}
@Override
public void onFailedDownload(String fileName) {
updateButtonState();
}
@Override
public void onSuccessDownload(String fileName) {
updateButtonState();
}
@Override
public void onProgressDownload(String fileName, float progress) {
progressView.setProgress(progress);
invalidate();
}
@Override
public void onProgressUpload(String fileName, float progress, boolean isEncrypted) {
}
@Override
public int getObserverTag() {
return TAG;
}
@Override
public void onSeekBarDrag(float progress) {
if (currentMessageObject == null) {
return;
}
currentMessageObject.audioProgress = progress;
MediaController.getInstance().seekToProgress(currentMessageObject, progress);
}
}
| wmhameed/Yahala-Messenger | app/src/main/java/com/yahala/ui/Views/PopupAudioView.java | Java | mit | 13,053 |