answer
stringlengths 15
1.25M
|
|---|
using System;
using System.Collections.Generic;
using System.Html;
namespace wwtlib
{
public class PlotTile : Tile
{
bool topDown = true;
protected PositionTexture[] bounds;
protected bool backslash = false;
List<PositionTexture> vertexList = null;
List<Triangle>[] childTriangleList = null;
protected float[] demArray;
protected void <API key>()
{
InitializeGrids();
TopLeft = bounds[0 + 3 * 0].Position.Copy();
BottomRight = bounds[2 + 3 * 2].Position.Copy();
TopRight = bounds[2 + 3 * 0].Position.Copy();
BottomLeft = bounds[0 + 3 * 2].Position.Copy();
CalcSphere();
}
public override void RenderPart(RenderContext renderContext, int part, double opacity, bool combine)
{
if (renderContext.gl != null)
{
//todo draw in WebGL
}
else
{
if (part == 0)
{
foreach(Star star in stars)
{
double radDec = 25 / Math.Pow(1.6, star.Magnitude);
Planets.DrawPointPlanet(renderContext, star.Position, radDec, star.Col, false);
}
}
}
}
WebFile webFile;
public override void RequestImage()
{
if (!Downloading && !ReadyToRender)
{
Downloading = true;
webFile = new WebFile(Util.GetProxiedUrl(this.URL));
webFile.OnStateChange = FileStateChange;
webFile.Send();
}
}
public void FileStateChange()
{
if(webFile.State == StateType.Error)
{
Downloading = false;
ReadyToRender = false;
errored = true;
RequestPending = false;
TileCache.RemoveFromQueue(this.Key, true);
}
else if(webFile.State == StateType.Received)
{
texReady = true;
Downloading = false;
errored = false;
ReadyToRender = texReady && (DemReady || !demTile);
RequestPending = false;
TileCache.RemoveFromQueue(this.Key, true);
LoadData(webFile.GetText());
}
}
List<Star> stars = new List<Star>();
private void LoadData(string data)
{
string[] rows = data.Replace("\r\n","\n").Split("\n");
bool firstRow = true;
PointType type = PointType.Move;
Star star = null;
foreach (string row in rows)
{
if (firstRow)
{
firstRow = false;
continue;
}
if (row.Trim().Length > 5)
{
star = new Star(row);
star.Position = Coordinates.RADecTo3dAu(star.RA, star.Dec, 1);
stars.Add(star);
}
}
}
public override bool IsPointInTile(double lat, double lng)
{
if (Level == 0)
{
return true;
}
if (Level == 1)
{
if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1))
{
return true;
}
if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1))
{
return true;
}
if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0))
{
return true;
}
if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0))
{
return true;
}
return false;
}
if (!this.DemReady || this.DemData == null)
{
return false;
}
Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng);
bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint);
bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint);
bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint);
bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint);
if (top && right && bottom && left)
{
// showSelected = true;
return true;
}
return false; ;
}
private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest)
{
pntA.Normalize();
pntB.Normalize();
Vector3d cross = Vector3d.Cross(pntA, pntB);
double dot = Vector3d.Dot(cross, pntTest);
return dot < 0;
}
private void InitializeGrids()
{
vertexList = new List<PositionTexture>();
childTriangleList = new List<Triangle>[4];
childTriangleList[0] = new List<Triangle>();
childTriangleList[1] = new List<Triangle>();
childTriangleList[2] = new List<Triangle>();
childTriangleList[3] = new List<Triangle>();
bounds = new PositionTexture[9];
if (Level > 0)
{
// Set in constuctor now
//ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null);
if (Parent == null)
{
Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null);
}
PlotTile parent = (PlotTile)Parent;
int xIndex = tileX % 2;
int yIndex = tileY % 2;
if (Level > 1)
{
backslash = parent.backslash;
}
else
{
backslash = xIndex == 1 ^ yIndex == 1;
}
bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy();
bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]);
bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy();
bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]);
if (backslash)
{
bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
}
else
{
bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]);
}
bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy();
bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy();
bounds[0 + 3 * 0].Tu = 0*uvMultiple;
bounds[0 + 3 * 0].Tv = 0 * uvMultiple;
bounds[1 + 3 * 0].Tu = .5f * uvMultiple;
bounds[1 + 3 * 0].Tv = 0 * uvMultiple;
bounds[2 + 3 * 0].Tu = 1 * uvMultiple;
bounds[2 + 3 * 0].Tv = 0 * uvMultiple;
bounds[0 + 3 * 1].Tu = 0 * uvMultiple;
bounds[0 + 3 * 1].Tv = .5f * uvMultiple;
bounds[1 + 3 * 1].Tu = .5f * uvMultiple;
bounds[1 + 3 * 1].Tv = .5f * uvMultiple;
bounds[2 + 3 * 1].Tu = 1 * uvMultiple;
bounds[2 + 3 * 1].Tv = .5f * uvMultiple;
bounds[0 + 3 * 2].Tu = 0 * uvMultiple;
bounds[0 + 3 * 2].Tv = 1 * uvMultiple;
bounds[1 + 3 * 2].Tu = .5f * uvMultiple;
bounds[1 + 3 * 2].Tv = 1 * uvMultiple;
bounds[2 + 3 * 2].Tu = 1 * uvMultiple;
bounds[2 + 3 * 2].Tv = 1 * uvMultiple;
}
else
{
bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0);
bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0);
bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0);
bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f);
bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f);
bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f);
bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1);
bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1);
bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1);
// Setup default matrix of points.
}
}
private PositionTexture Midpoint(PositionTexture <API key>, PositionTexture <API key>)
{
Vector3d a1 = Vector3d.Lerp(<API key>.Position, <API key>.Position, .5f);
Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(<API key>.Tu, <API key>.Tv), Vector2d.Create(<API key>.Tu, <API key>.Tv), .5f);
a1.Normalize();
return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y);
}
int subDivisionLevel = 4;
bool subDivided = false;
public override bool CreateGeometry(RenderContext renderContext)
{
if (GeometryCreated)
{
return true;
}
GeometryCreated = true;
base.CreateGeometry(renderContext);
return true;
}
public PlotTile()
{
}
public static PlotTile Create(int level, int xc, int yc, Imageset dataset, Tile parent)
{
PlotTile temp = new PlotTile();
temp.Parent = parent;
temp.Level = level;
temp.tileX = xc;
temp.tileY = yc;
temp.dataset = dataset;
temp.topDown = !dataset.BottomsUp;
if (temp.tileX != (int)xc)
{
Script.Literal("alert('bad')");
}
//temp.ComputeQuadrant();
if (dataset.MeanRadius != 0)
{
temp.DemScaleFactor = dataset.MeanRadius;
}
else
{
if (dataset.DataSetType == ImageSetType.Earth)
{
temp.DemScaleFactor = 6371000;
}
else
{
temp.DemScaleFactor = 3396010;
}
}
temp.<API key>();
return temp;
}
public override void CleanUp(bool removeFromParent)
{
base.CleanUp(removeFromParent);
if (vertexList != null)
{
vertexList = null;
}
if (childTriangleList != null)
{
childTriangleList = null;
}
subDivided = false;
demArray = null;
}
}
}
|
<?php
declare(strict_types = 1);
namespace Browscap\Cache;
use BrowscapPHP\Cache\<API key>;
use WurflCache\Adapter\AdapterInterface;
final class JsonCache implements <API key>
{
/**
* The cache livetime in seconds.
*
* @var int
*/
public const CACHE_LIVETIME = 315360000; // ~10 years (60 * 60 * 24 * 365 * 10)
/**
* Path to the cache directory
*
* @var \WurflCache\Adapter\AdapterInterface
*/
private $cache;
/**
* Detected browscap version (read from INI file)
*
* @var int
*/
private $version;
/**
* Release date of the Browscap data (read from INI file)
*
* @var string
*/
private $releaseDate;
/**
* Type of the Browscap data (read from INI file)
*
* @var string
*/
private $type;
/**
* Constructor class, checks for the existence of (and loads) the cache and
* if needed updated the definitions
*
* @param \WurflCache\Adapter\AdapterInterface $adapter
* @param int $updateInterval
*/
public function __construct(AdapterInterface $adapter, $updateInterval = self::CACHE_LIVETIME)
{
$this->cache = $adapter;
$this->cache->setExpiration($updateInterval);
}
/**
* Gets the version of the Browscap data
*
* @return int|null
*/
public function getVersion(): ?int
{
if (null === $this->version) {
$success = true;
$version = $this->getItem('browscap.version', false, $success);
if (null !== $version && $success) {
$this->version = (int) $version;
}
}
return $this->version;
}
/**
* Gets the release date of the Browscap data
*
* @return string
*/
public function getReleaseDate(): string
{
if (null === $this->releaseDate) {
$success = true;
$releaseDate = $this->getItem('browscap.releaseDate', false, $success);
if (null !== $releaseDate && $success) {
$this->releaseDate = $releaseDate;
}
}
return $this->releaseDate;
}
/**
* Gets the type of the Browscap data
*
* @return string|null
*/
public function getType(): ?string
{
if (null === $this->type) {
$success = true;
$type = $this->getItem('browscap.type', false, $success);
if (null !== $type && $success) {
$this->type = $type;
}
}
return $this->type;
}
/**
* Get an item.
*
* @param string $cacheId
* @param bool $withVersion
* @param bool|null $success
*
* @return mixed Data on success, null on failure
*/
public function getItem(string $cacheId, bool $withVersion = true, ?bool &$success = null)
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
if (!$this->cache->hasItem($cacheId)) {
$success = false;
return null;
}
$success = null;
$data = $this->cache->getItem($cacheId, $success);
if (!$success) {
$success = false;
return null;
}
if (!property_exists($data, 'content')) {
$success = false;
return null;
}
$success = true;
return $data->content;
}
/**
* save the content into an php file
*
* @param string $cacheId The cache id
* @param mixed $content The content to store
* @param bool $withVersion
*
* @return bool whether the file was correctly written to the disk
*/
public function setItem(string $cacheId, $content, bool $withVersion = true): bool
{
$data = new \stdClass();
// Get the whole PHP code
$data->content = $content;
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
// Save and return
return $this->cache->setItem($cacheId, $data);
}
/**
* Test if an item exists.
*
* @param string $cacheId
* @param bool $withVersion
*
* @return bool
*/
public function hasItem(string $cacheId, bool $withVersion = true): bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->hasItem($cacheId);
}
/**
* Remove an item.
*
* @param string $cacheId
* @param bool $withVersion
*
* @return bool
*/
public function removeItem(string $cacheId, bool $withVersion = true): bool
{
if ($withVersion) {
$cacheId .= '.' . $this->getVersion();
}
return $this->cache->removeItem($cacheId);
}
/**
* Flush the whole storage
*
* @return bool
*/
public function flush(): bool
{
return $this->cache->flush();
}
}
|
(function () {
"use strict";
require('futures/forEachAsync');
var fs = require('fs'),
crypto = require('crypto'),
path = require('path'),
exec = require('child_process').exec,
mime = require('mime'),
FileStat = require('filestat'),
dbaccess = require('../dbaccess'),
utils = require('../utils'),
hashAlgo = "md5";
function readFile(filePath, callback) {
var readStream, hash = crypto.createHash(hashAlgo);
readStream = fs.createReadStream(filePath);
readStream.on('data', function (data) {
hash.update(data);
});
readStream.on('error', function (err) {
console.log("Read Error: " + err.toString());
readStream.destroy();
fs.unlink(filePath);
callback(err);
});
readStream.on('end', function () {
callback(null, hash.digest("hex"));
});
}
function saveToFs(md5, filePath, callback) {
var newPath = utils.hashToPath(md5);
path.exists(newPath, function (exists) {
if (exists) {
fs.move(filePath, newPath, function (err) {
callback(err, newPath);
});
return;
}
exec('mkdir -p ' + newPath, function (err, stdout, stderr) {
var tError;
if (err || stderr) {
console.log("Err: " + (err ? err : "none"));
console.log("stderr: " + (stderr ? stderr : "none"));
tError = {error: err, stderr: stderr, stdout: stdout};
return callback(tError, newPath);
}
console.log("stdout: " + (stdout ? stdout : "none"));
fs.move(filePath, newPath, function (moveErr) {
callback(moveErr, newPath);
});
});
});
}
function addKeysToFileStats(fieldNames, stats) {
var fileStats = [];
stats.forEach(function (item) {
var fileStat = new FileStat();
item.forEach(function (fieldValue, i) {
fileStat[fieldNames[i]] = fieldValue;
});
if (fileStat.path) {
fileStat.type = mime.lookup(fileStat.path);
}
fileStats.push(fileStat);
});
return fileStats;
}
function importFile(fileStat, tmpFile, username, callback) {
var oldPath;
oldPath = tmpFile.path;
readFile(oldPath, function (err, md5) {
if (err) {
fileStat.err = err;
callback(err, fileStat);
return;
}
// if we have an md5sum and they don't match, abandon ship
if (fileStat.md5 && fileStat.md5 !== md5) {
callback("MD5 sums don't match");
return;
}
fileStat.md5 = md5;
fileStat.genTmd5(function (error, tmd5) {
if (!error) {
fileStat.tmd5 = tmd5;
saveToFs(fileStat.md5, oldPath, function (fserr) {
if (fserr) {
// ignoring possible unlink error
fs.unlink(oldPath);
fileStat.err = "File did not save";
} else {
dbaccess.put(fileStat, username);
}
callback(fserr, fileStat);
});
}
});
});
}
function handleUpload(req, res, next) {
if (!req.form) {
return next();
}
req.form.complete(function (err, fields, files) {
var fileStats, bFirst;
fields.statsHeader = JSON.parse(fields.statsHeader);
fields.stats = JSON.parse(fields.stats);
fileStats = addKeysToFileStats(fields.statsHeader, fields.stats);
dbaccess.createViews(req.remoteUser, fileStats);
res.writeHead(200, {'Content-Type': 'application/json'});
// response as array
res.write("[");
bFirst = true;
function handleFileStat(next, fileStat) {
// this callback is synchronous
fileStat.checkMd5(function (qmd5Error, qmd5) {
function finishReq(err) {
console.log(fileStat);
fileStat.err = err;
// we only want to add a comma after the first one
if (!bFirst) {
res.write(",");
}
bFirst = false;
res.write(JSON.stringify(fileStat));
return next();
}
if (qmd5Error) {
return finishReq(qmd5Error);
}
importFile(fileStat, files[qmd5], req.remoteUser, finishReq);
});
}
fileStats.forEachAsync(handleFileStat).then(function () {
// end response array
res.end("]");
});
});
}
module.exports = handleUpload;
}());
|
#!/usr/bin/python
from typing import List, Optional
def bsearch(nums, left, right, res, i, j, target):
while left <= right:
middle = (left + right)
candidate = nums[i] + nums[j] + nums[middle]
if res is None or abs(candidate - target) < abs(res - target):
res = candidate
if candidate == target:
return res
elif candidate > target:
right = middle - 1
else:
left = middle + 1
return res
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> Optional[int]:
res = None
nums = sorted(nums)
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
res = bsearch(nums, j + 1, len(nums) - 1, res, i, j, target)
return res
def main():
sol = Solution()
print(sol.threeSumClosest([-111, -111, 3, 6, 7, 16, 17, 18, 19], 13))
return 0
if __name__ == '__main__':
raise SystemExit(main())
|
package bits;
public class ExclusiveOrOperator implements BinaryOperator
{
@Override
public BitArray combine(BitArray operand1, BitArray operand2) {
if(operand1.size() != operand2.size()) {
throw new <API key>("ExclusiveOrOperator operands must have same size");
}
int size = operand1.size();
BitArray result = new BitArray(size);
for (int i = 0;i < size;i++) {
boolean a = operand1.get(i);
boolean b = operand2.get(i);
result.set(i, a != b );
}
return result;
}
}
|
layout: post
title: "Using the right terms: Method?"
date: 2015-08-05 12:00:00
comments: true
tags: [components, programming, components programming, <API key>, stepanov, knuth, stroustrup, generic, genericprogramming, generic programming, genericity, concepts, math, mathematics, elements, eop, contracts, performance, c++, cpp, c, java, dotnet, c#, csharp, python, ruby, javascript, haskell, dlang, rust, golang, eiffel, templates, metaprogramming, book, fmgp]
(REVISIONISMO)
En esta serie de articulos mi intension es revisar por qué algunos programadores usamos cierta terminologia, ciertas palabras, algunas de las cuales, considero inadecuadas.
En este caso quiero hablar sobre la palabra "method".
Algunos colegas mios, más que nada colegas con background en Java o .Net suelen usar esta palabra, como por ejemplo: "Escribí un método que tome una fecha y retorne un string con el nombre del día".
Yo me pregunto: ¿Por qué decimos "metodo" y no utilizamos otra palabra como "procedimiento", "función", etc?
Cuando yo empecé a programar, casi nadie usaba la palabra "metodo" y de repente ahora es muy común.
Pero, antes de continuar con mi conjetura, me gustaría repasar (muy burdamente) sobre teoría de objetos.
¿Qué es un método?
Cualquier programador Java o C
El estado se almacena en Fields y el comportamiento shown via Métodos.
O sea, un método es un procedimiento, funcion, routine, subroutine, pero que está incluido dentro de una clase en particular.
O sea, un método es una serie de instrucciones, a las que se les pone un nombre.
Java y C
Pero en C++ no se usa el termino Method, sino que al comportamiento de los objetos se los codifica usando Member Functions.
(Al estado de los objetos se lo almacena en Data Members)
C++ es un lenguaje que soporta el paradigma de objetos, pero desde el nacimiento de C++, este no está atado a un solo paradigma.
C++ hereda de C el paradigma de programación estructurada, o sea, C++ es un lenguaje multi-paradigma, por lo tanto, permite la creacion de funciones, tanto dentro de una clase como fuera de ella. A las funciones que son creadas fuera de una clase se las suele llamar Non-Member Functions o Free Functions.
Más allá de esto, el termino "Method" se ha popularizado de tal forma que si dicen "metodo" cualquier programador C++ sabe de que estás hablando.
¿Por qué Java y C# no adoptaron la misma terminologia que C++? (En lo que respecta a comportamiento de objetos)
Bueno, C
(
Al margen: mas alla de que C
- No todos los métodos son virtuales
- In C# a parent and child classes are named Base and Derived clases, respectively (like in C++, see D&E of C++), but in Java are called Super and Sub classes.
)
Eso es dificil de saber, habría que charlar con los creadores del lenguaje para saber el porqué de la nomenclatura.
Para saber que es un método, primero me gustaría explorar distintas fuentes para saber cual es el origen de esa palabra en el ámbito informático.
............................................................
Procedure
Function
Routine
Subroutine
Feature
Method
FORTRAN
FORTRAN was the first high-level programming language and the first high-quality optimizing compiler.
PROGRAM, FUNCTION, SUBROUTINE
Statement function
External function
Subroutine
"Method"
Fortran STANDARs Committee
http:
Fortran 66
ftp://ftp.nag.co.uk/sc22wg5/ARCHIVE/Fortran66.pdf
Fortran 77
ftp://ftp.nag.co.uk/sc22wg5/ARCHIVE/Fortran77.html
Fortran 90
ftp://ftp.nag.co.uk/sc22wg5/N001-N1100/N692.pdf
Fortran 95
ftp://ftp.nag.co.uk/sc22wg5/N1151-N1200/N1191.pdf
Fortran 2003
ftp://ftp.nag.co.uk/sc22wg5/N1601-N1650/N1601.pdf
Fortran 2008 (working)
http://j3-fortran.org/doc/year/10/10-007r1.pdf
http:
Algol
ALGOL (short for ALGOrithmic Language)[1] is a family of imperative computer programming languages, originally developed in the mid-1950s, which greatly influenced many other languages and was the standard method for algorithm description used by the ACM in textbooks and academic sources for more than thirty years.[2]
In the sense that most modern languages are "algol-like",[3] it was arguably the most successful of the four high-level programming languages with which it was roughly contemporary
http:
Simula
Procedure (ALGOL)
function procedure (ALGOL)
Parece que en SIMULA I un objeto (de OOP) es llamado Process
slp-complete.pdf - Chapter 2 - page 10
"It has its own local data and
its own behaviour pattern.
A system may contain several processes with a similar data
structure and the same behaviour pattern. Such processes are
said to belong to the same class, called an activity.""
SIMULA 67
1. 3. 3 Classes
A central new concept in SIMULA 67 is the "object".
An object is a self-contained program (block instance)
having its own local data and actions defined by a
"class declaration". The class declaration defines a
program (data and action) pattern, and objects conforming
to that pattern are said to "belong to the same class".
If no actions are specified in the class declaration,
a class of pure data structures is defined.
Smalltalk
NCITS J20 DRAFT December, 1997 of ANSI Smalltalk Standard revision 1.9
ANSI Smalltalk Standard v1.9 199712 NCITS X3J20 draft (PDF)
A Smalltalk program is a means for describing a dynamic computational process. This section
defines the entities that exist in the computational environment of Smalltalk programs.
A variable is a computational entity that stores a single reference (the value of the variable) to an
object.
A message is a request to perform a designated computation. An object is a computational entity
that is capable of responding to a well defined set of messages. An object may also encapsulate
some (possibly mutable) state.
An object responds to a message by executing a method. Each method is identified by an
associated method selector. A behavior is the set of methods used by an object to respond to
messages.
A method consists of a sequence of expressions. Program execution proceeds by sequentially
evaluating the expressions in one of more methods. There are three types of expressions:
assignments, message sends, and returns.
CLOS
C
C++
n3936.pdf
9.3 Member functions [class.mfct]
1 Functions declared in the definition of a class, excluding those declared with a friend specifier (11.3), are called member functions of that class. A member function may be declared static in which case it is a static member function of its class (9.4); otherwise it is a non-static member function of its class (9.3.1, 9.3.2).
Eiffel
1. ECMA Standard
2. BM - Object Oriented Software Construction vol.2
Eiffel - Object-Oriented Software Construction (2nd Ed) - Bertrand Meyer
Representing a
point in
cartesian
coordinates
Feature: Computation or Memory
This example shows the need for two kinds of feature:
• Some features will be represented by space, that is to say by associating a certain
piece of information with every instance of the class. They will be called attributes.
For points, x and y are attributes in cartesian representation; rho and theta are
attributes in polar representation.
• Some features will be represented by time, that is to say by defining a certain
computation (an algorithm) applicable to all instances of the class. They will be
called routines. For points, rho and theta are routines in cartesian representation; x
and y are routines in polar representation.
A further distinction affects routines (the second of these categories). Some routines
will return a result; they are called functions. Here x and y in polar representation, as well
as rho and theta in cartesian representation, are functions since they return a result, of type
REAL. Routines which do not return a result correspond to the commands of an ADT
specification and are called procedures. For example the class POINT will include
procedures translate, rotate and scale.
Java
Java Language Specification
8.4 Method Declarations
A method declares executable code that can be invoked, passing a fixed number of values as arguments.
227
8.4 Method Declarations
CLASSES
228
MethodDeclaration:
{MethodModifier} MethodHeader MethodBody
MethodHeader:
Result MethodDeclarator [Throws]
TypeParameters {Annotation} Result MethodDeclarator [Throws]
MethodDeclarator:
Identifier ( [FormalParameterList] ) [Dims]
The following production from §4.3 is shown here for convenience:
Dims:
{Annotation} [ ] {{Annotation} [ ]}
The FormalParameterList is described in §8.4.1, the MethodModifier clause in §8.4.3, the TypeParameters clause in §8.4.4, the Result clause in §8.4.5, the Throws clause in §8.4.6, and the MethodBody in §8.4.7.
The Identifier in a MethodDeclarator may be used in a name to refer to the method (§6.5.7.1, §15.12).
It is a compile-time error for the body of a class to declare as members two methods with override-equivalent signatures (§8.4.2).
The scope and shadowing of a method declaration is specified in §6.3 and §6.4.
The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.
Java Tutorials
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
https://docs.oracle.com/javase/tutorial/java/concepts/object.html
C
C# Specification
C# ECMA Standard (ISO Standard)
8.7.3 Methods
A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void), and are either static or non-static. Static methods are accessed through the class. Non-static methods, which are also called instance methods, are accessed through instances of the class. A generic method (§25.6) has a list of one or more type parameters. The example
Python
APPENDIX A - GLOSSARY
method A function which is defined inside a class body. If called as an attribute of an instance of that class, the
method will get the instance object as its first argument (which is usually called self). See function and
nested scope.
function A series of statements which returns some value to a caller. It can also be passed zero or more arguments
which may be used in the execution of the body. See also parameter, method, and the Function definitions
section.
6.1 Expression statements
procedure
(a function that returns no meaningful result; in Python, procedures return the value None).
Knuth - The Art of Computer Programming
- Concrete Mathematics
Elements of Programming
Dijstra ?
Wirth ?
RAE
Britsh
Mathematics
"asymptotic methods"
"repertoire method"
general method
Real Academia Espanola
método.
(Del lat. methŏdus, y este del gr. μέθοδος).
1. m. Modo de decir o hacer con orden.
2. m. Modo de obrar o proceder, hábito o costumbre que cada uno tiene y observa.
3. m. Obra que enseña los elementos de una ciencia o arte.
4. m. Fil. Procedimiento que se sigue en las ciencias para hallar la verdad y enseñarla.
............................................................
{% highlight cpp %}
class employee {
id: natural32
other: natural32
}
class test {
a: natural32 := 0x88FF7799
employees: array<employee> := { {0xA1B2C3D4, 0x11223344},
{0x92817348, 0x96161728},
{0x61592308, 0xa8857472 } }
b: natural32 := 0x12345678
}
//program entry-point
main() {
tc := test{}
// analyze memory here!
}
{% endhighlight %}
The program consists of a main function (entry-point) in which is created an object of type "test".
The test class has three data members (or Fields, in order to use Java/C# jargons):
- a: it is 32-bits natural number (like C/C++'s uint32_t). It is set to 88FF7799 (base16)
- employees: it is a sequence of elements of type "employee".
The employees sequence is filled with three elements.
- b: it is 32-bits natural number. It is set to 12345678 (base16)
The employee class has two data members:
- id: it is 32-bits natural number
- other: it is 32-bits natural number
Note: "array" is a data structure that stores elements contiguosly in memory.
The size of the sequence is dynamic, it is resizable.
Equivalents: C++ std::vector, .Net List<T>, Java ArrayList<T>
For example it is not necessary runtime polymorphism neither runtime type introspection (aka Reflection).
For simplicity all the data members are public.
Now, let's code in real programming languages:
C++ code
{% highlight cpp %}
#include <vector>
using namespace std;
struct employee {
uint32_t id;
uint32_t other;
};
struct test {
uint32_t a {0x88FF7799};
vector<employee> employees { {0xA1B2C3D4, 0x11223344},
{0x92817348, 0x96161728},
{0x61592308, 0xa8857472}};
uint32_t b {0x12345678};
};
int main(int argc, char const* argv[]) {
test t;
// analyze memory here!
return 0;
}
{% endhighlight %}
Java code:
{% highlight cpp %}
import java.util.ArrayList;
class Employee {
public int id;
public int other;
public Employee(int id, int other) {
this.id = id;
this.other = other;
}
}
class Test {
public int a = 0x88FF7799;
public ArrayList<Employee> employees = new ArrayList<Employee>();
public int b = 0x12345678;
public Test() {
employees.add(new Employee(0xA1B2C3D4, 0x11223344));
employees.add(new Employee(0x92817348, 0x96161728));
employees.add(new Employee(0x61592308, 0xa8857472));
}
}
public class MainClass {
public static void main(String args[]) {
Test t = new Test();
// analyze memory here!
}
}
{% endhighlight %}
C# code
{% highlight cpp %}
using System;
using System.Collections.Generic;
internal class Employee
{
public uint Id;
public uint Other;
public Employee(uint id, uint other)
{
Id = id;
Other = other;
}
}
internal class Test
{
public uint A = 0x88FF7799;
public List<Employee> Employees = new List<Employee> {
new Employee(0xA1B2C3D4, 0x11223344),
new Employee(0x92817348, 0x96161728),
new Employee(0x61592308, 0xa8857472) };
public uint B = 0x12345678;
}
class Program
{
static void Main(string[] args)
{
var t = new Test();
// analyze memory here!
}
}
{% endhighlight %}
I tried to write idiomatic code (as possible) in each of the languages.
I am not trying to be OO-purist.
I just tried to write the simplest code to later analyze the memory more easily.
Disclaimer: ....
References:
.Net BCL System.Array class specification:
https://msdn.microsoft.com/en-us/library/system.array%28v=vs.110%29.aspx
.Net BCL System.Array class source code:
http://referencesource.microsoft.com/#mscorlib/system/array.cs,1f52f2a267c6dbe7
.Net BCL System.Collections.Generic.List<T> class specification:
https://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx
.Net BCL System.Collections.Generic.List<T> class source code:
http://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646
Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects
https://msdn.microsoft.com/en-us/magazine/cc163791.aspx
Java ARTICLES
https:
https://wikis.oracle.com/display/HotSpotInternals/CompressedOops
http:
http://mishadoff.com/blog/<API key>/
http://java-performance.info/<API key>/
|
/*"use strict";
var expect = require("expect.js"),
ShellController = require("../lib/shell-controller"),
testView = require("./test-shell-view");
describe("ShellController", function() {
var ctrl;
it("is defined", function() {
expect(ShellController).to.be.an("function");
});
describe("constructor", function() {
before(function() {
ctrl = new ShellController(testView);
});
it("create an object", function() {
expect(ctrl).to.be.an("object");
});
});
describe("on command event", function() {
before(function(done) {
ctrl.events.on("commandExecuted", done);
testView.invokeCommand("ls test/files --color");
});
after(function() {
testView.reset();
});
it("write commands output to view", function() {
var expected =
" <span style=\'color:rgba(170,170,170,255)\'>1.txt<br> 2.txt<br><br><br></span>";
expect(testView.content).to.be.equal(expected);
});
});
describe("findCommandRunner", function() {
var runner;
before(function(done) {
ctrl.findCommandRunner("ls test/files", function(cmdRunner) {
runner = cmdRunner;
done();
});
});
it("return a command runner", function() {
expect(runner.run).to.be.a("function");
});
});
});*/
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Database
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/mydb');
var index = require('./routes/index');
var buyer = require('./routes/buyer');
var seller = require('./routes/seller');
var products = require('./routes/products');
var app = express();
const ObjectID = mongo.ObjectID;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
req.ObjectID = ObjectID;
next();
});
app.use('/', index);
app.use('/buyer', buyer);
app.use('/seller', seller);
app.use('/products', products);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.html', err);
});
module.exports = app;
|
# Smallest Integer
# I worked on this challenge [by myself, with: ].
# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+
# If +list_of_nums+ is empty the method should return nil
# Your Solution Below
def smallest_integer(list_of_nums)
if list_of_nums.empty?
return nil
else
list_of_nums.sort!
return list_of_nums[0]
end
end
|
FactoryGirl.define do
factory :user do
provider 'trello'
uid 'trello-special-uid'
full_name 'Dennis Martinez'
nickname 'dennmart'
oauth_token 'trello-token'
trait :admin do
admin true
end
end
end
|
<!DOCTYPE html>
<html lang="en" ng-app="bookmarkApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bookmark</title>
<link type="text/css" href="app/bootstrap/css/bootstrap.min.css"
rel="stylesheet">
<link type="text/css"
href="app/bootstrap/css/<API key>.min.css" rel="stylesheet">
<link href="app/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" href="app/css/theme.css" rel="stylesheet">
<link type="text/css" href="app/css/ng-table.css" rel="stylesheet">
<link type="text/css" href="app/images/icons/css/font-awesome.css"
rel="stylesheet">
<link type="text/css"
href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600'
rel='stylesheet'>
</head>
<body >
<!-- /navbar -->
<div data-ng-view=""></div>
<script src="app/scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="app/scripts/jquery-ui-1.10.1.custom.min.js" type="text/javascript"></script>
<script src="app/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="app/scripts/angular.min.js"></script>
<script src="app/scripts/angular-route.js"></script>
<script src="app/scripts/angular-resource.min.js"></script>
<script src="app/scripts/angular-resource.min.js.map"></script>
<script src="app/scripts/angular-cookies.min.js"></script>
<script src="app/app.js"></script>
<script src="app/scripts/ng-table.js" type="text/javascript"></script>
<script src="app/bootstrap/js/ui-bootstrap-tpls-0.11.2.js"></script>
<script src="app/directives/commonDirective.js"></script>
<script src="app/controllers/resourceController.js"></script>
<script src="app/controllers/<API key>.js"></script>
<script src="app/services/<API key>.js"></script>
<script src="app/services/resourceService.js"></script>
<script src="app/services/loginService.js"></script>
<script src="app/controllers/userController.js"></script>
<script src="app/services/userservice.js"></script>
<script src="app/services/servicehelper.js"></script>
</body>
|
from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
print 'All subprocesses done.'
"""
Pooljoin()join()close()close()Process
task 0123task 4taskPool44Pool
p = Pool(5)
"""
|
package net.comfreeze.lib;
import android.app.AlarmManager;
import android.app.Application;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.location.LocationManager;
import android.media.AudioManager;
import android.support.v4.content.<API key>;
import android.util.Log;
import net.comfreeze.lib.audio.SoundManager;
import java.io.File;
import java.security.MessageDigest;
import java.security.<API key>;
import java.util.Calendar;
import java.util.TimeZone;
abstract public class CFZApplication extends Application {
public static final String TAG = "CFZApplication";
public static final String PACKAGE = "com.rastermedia";
public static final String KEY_DEBUG = "debug";
public static final String KEY_SYNC_PREFEX = "sync_";
public static SharedPreferences preferences = null;
protected static Context context = null;
protected static CFZApplication instance;
public static <API key> broadcast;
public static boolean silent = true;
@Override
public void onCreate() {
if (!silent)
Log.d(TAG, "Initializing");
instance = this;
setContext();
setPreferences();
broadcast = <API key>.getInstance(context);
super.onCreate();
}
@Override
public void onLowMemory() {
if (!silent)
Log.d(TAG, "Low memory!");
super.onLowMemory();
}
@Override
public void onTerminate() {
unsetContext();
if (!silent)
Log.d(TAG, "Terminating");
super.onTerminate();
}
abstract public void setPreferences();
abstract public void setContext();
abstract public void unsetContext();
abstract public String getProductionKey();
public static CFZApplication getInstance(Class<?> className) {
// log("Returning current application instance");
if (instance == null) {
synchronized (className) {
if (instance == null)
try {
instance = (CFZApplication) className.newInstance();
} catch (<API key> e) {
e.printStackTrace();
} catch (<API key> e) {
e.printStackTrace();
}
}
}
return instance;
}
public void <API key>() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String dir : children) {
if (!dir.equals("lib")) {
deleteDir(new File(appDir, dir));
}
}
}
preferences.edit().clear().commit();
}
private static boolean deleteDir(File dir) {
if (dir != null) {
if (!silent)
Log.d(PACKAGE, "Deleting: " + dir.getAbsolutePath());
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
return false;
}
}
return dir.delete();
}
return false;
}
public static int dipsToPixel(float value, float scale) {
return (int) (value * scale + 0.5f);
}
public static long timezoneOffset() {
Calendar calendar = Calendar.getInstance();
return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
}
public static long timezoneOffset(String timezone) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timezone));
return (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET));
}
public static Resources res() {
return context.getResources();
}
public static LocationManager getLocationManager(Context context) {
return (LocationManager) context.getSystemService(LOCATION_SERVICE);
}
public static AlarmManager getAlarmManager(Context context) {
return (AlarmManager) context.getSystemService(ALARM_SERVICE);
}
public static NotificationManager <API key>(Context context) {
return (NotificationManager) context.getSystemService(<API key>);
}
public static AudioManager getAudioManager(Context context) {
return (AudioManager) context.getSystemService(AUDIO_SERVICE);
}
public static SoundManager getSoundManager(CFZApplication application) {
return (SoundManager) SoundManager.instance(application);
}
public static void setSyncDate(String key, long date) {
preferences.edit().putLong(KEY_SYNC_PREFEX + key, date).commit();
}
public static long getSyncDate(String key) {
return preferences.getLong(KEY_SYNC_PREFEX + key, -1L);
}
public static boolean needSync(String key, long limit) {
return (System.currentTimeMillis() - getSyncDate(key) > limit);
}
public static String hash(final String algorithm, final String s) {
try {
// Create specified hash
MessageDigest digest = java.security.MessageDigest.getInstance(algorithm);
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create hex string
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
} catch (<API key> e) {
e.printStackTrace();
}
return "";
}
public boolean isProduction(Context context) {
boolean result = false;
try {
ComponentName component = new ComponentName(context, instance.getClass());
PackageInfo info = context.getPackageManager().getPackageInfo(component.getPackageName(), PackageManager.GET_SIGNATURES);
Signature[] sigs = info.signatures;
for (int i = 0; i < sigs.length; i++)
if (!silent)
Log.d(TAG, "Signing key: " + sigs[i].toCharsString());
String targetKey = getProductionKey();
if (null == targetKey)
targetKey = "";
if (targetKey.equals(sigs[0].toCharsString())) {
result = true;
if (!silent)
Log.d(TAG, "Signed with production key");
} else {
if (!silent)
Log.d(TAG, "Not signed with production key");
}
} catch (PackageManager.<API key> e) {
if (!silent)
Log.e(TAG, "Package exception", e);
}
return result;
}
public static class LOG {
// Without Throwables
public static void v(String tag, String message) {
if (!silent) Log.v(tag, message);
}
public static void d(String tag, String message) {
if (!silent) Log.d(tag, message);
}
public static void i(String tag, String message) {
if (!silent) Log.i(tag, message);
}
public static void w(String tag, String message) {
if (!silent) Log.w(tag, message);
}
public static void e(String tag, String message) {
if (!silent) Log.e(tag, message);
}
public static void wtf(String tag, String message) {
if (!silent) Log.wtf(tag, message);
}
// With Throwables
public static void v(String tag, String message, Throwable t) {
if (!silent) Log.v(tag, message, t);
}
public static void d(String tag, String message, Throwable t) {
if (!silent) Log.d(tag, message, t);
}
public static void i(String tag, String message, Throwable t) {
if (!silent) Log.i(tag, message, t);
}
public static void w(String tag, String message, Throwable t) {
if (!silent) Log.w(tag, message, t);
}
public static void e(String tag, String message, Throwable t) {
if (!silent) Log.e(tag, message, t);
}
public static void wtf(String tag, String message, Throwable t) {
if (!silent) Log.wtf(tag, message, t);
}
}
}
|
// Generated by class-dump 3.5 (64 bit).
#import "<API key>.h"
@class NSData, <API key>, WFNordicDFUPacketCh;
@interface <API key> : <API key>
{
id <WFNordicDFUDelegate> delegate;
<API key> *dfuControlPointCh;
WFNordicDFUPacketCh *dfuPacketCh;
BOOL bDFUInProgress;
BOOL bStartTransferOnACK;
BOOL bFinishOnACK;
BOOL <API key>;
unsigned long ulImageSize;
unsigned long ulBytesSent;
NSData *firmwareData;
double startTime;
unsigned short usCRC;
unsigned short usProductId;
unsigned int packetIntervalTime;
unsigned char ucMaxRetries;
unsigned char ucRetryCount;
BOOL <API key>;
BOOL <API key>;
BOOL <API key>;
BOOL bAbortImageTransfer;
}
@property(retain, nonatomic) id <WFNordicDFUDelegate> delegate; // @synthesize delegate;
- (void)setMaxRetries:(unsigned char)arg1;
- (void)<API key>:(unsigned int)arg1;
- (BOOL)sendHardReset;
- (BOOL)sendExitDFU;
- (BOOL)sendFirmware:(id)arg1;
- (void)<API key>;
- (void)sendFirmwareImage;
- (void)sendDFUInitParams;
- (BOOL)sendStartDFU;
- (void)restartTransfer;
- (void)delegateFinish:(unsigned char)arg1;
- (void)<API key>:(unsigned long)arg1;
- (void)<API key>:(unsigned char)arg1;
- (void)<API key>:(unsigned char)arg1;
- (void)<API key>:(unsigned char)arg1;
- (void)<API key>:(unsigned char)arg1 imageSize:(unsigned long)arg2;
- (void)reset;
- (id)getData;
- (BOOL)<API key>:(id)arg1 onPeripheral:(id)arg2;
- (void)peripheral:(id)arg1 <API key>:(id)arg2 error:(id)arg3;
- (void)peripheral:(id)arg1 <API key>:(id)arg2 error:(id)arg3;
- (void)peripheral:(id)arg1 <API key>:(id)arg2 error:(id)arg3;
- (void)dealloc;
- (id)init;
@end
|
import {
Camera,
ClampToEdgeWrapping,
DataTexture,
FloatType,
HalfFloatType,
Mesh,
NearestFilter,
PlaneBufferGeometry,
RGBAFormat,
Scene,
ShaderMaterial,
WebGLRenderTarget
} from "./three.module.js";
var <API key> = function ( sizeX, sizeY, renderer ) {
this.variables = [];
this.currentTextureIndex = 0;
var scene = new Scene();
var camera = new Camera();
camera.position.z = 1;
var passThruUniforms = {
passThruTexture: { value: null }
};
var passThruShader = <API key>( <API key>(), passThruUniforms );
var mesh = new Mesh( new PlaneBufferGeometry( 2, 2 ), passThruShader );
scene.add( mesh );
this.addVariable = function ( variableName, <API key>, initialValueTexture ) {
var material = this.<API key>( <API key> );
var variable = {
name: variableName,
initialValueTexture: initialValueTexture,
material: material,
dependencies: null,
renderTargets: [],
wrapS: null,
wrapT: null,
minFilter: NearestFilter,
magFilter: NearestFilter
};
this.variables.push( variable );
return variable;
};
this.<API key> = function ( variable, dependencies ) {
variable.dependencies = dependencies;
};
this.init = function () {
if ( ! renderer.extensions.get( "OES_texture_float" ) &&
! renderer.capabilities.isWebGL2 ) {
return "No OES_texture_float support for float textures.";
}
if ( renderer.capabilities.maxVertexTextures === 0 ) {
return "No support for vertex shader textures.";
}
for ( var i = 0; i < this.variables.length; i ++ ) {
var variable = this.variables[ i ];
// Creates rendertargets and initialize them with input texture
variable.renderTargets[ 0 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
variable.renderTargets[ 1 ] = this.createRenderTarget( sizeX, sizeY, variable.wrapS, variable.wrapT, variable.minFilter, variable.magFilter );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 0 ] );
this.renderTexture( variable.initialValueTexture, variable.renderTargets[ 1 ] );
// Adds dependencies uniforms to the ShaderMaterial
var material = variable.material;
var uniforms = material.uniforms;
if ( variable.dependencies !== null ) {
for ( var d = 0; d < variable.dependencies.length; d ++ ) {
var depVar = variable.dependencies[ d ];
if ( depVar.name !== variable.name ) {
// Checks if variable exists
var found = false;
for ( var j = 0; j < this.variables.length; j ++ ) {
if ( depVar.name === this.variables[ j ].name ) {
found = true;
break;
}
}
if ( ! found ) {
return "Variable dependency not found. Variable=" + variable.name + ", dependency=" + depVar.name;
}
}
uniforms[ depVar.name ] = { value: null };
material.fragmentShader = "\nuniform sampler2D " + depVar.name + ";\n" + material.fragmentShader;
}
}
}
this.currentTextureIndex = 0;
return null;
};
this.compute = function () {
var currentTextureIndex = this.currentTextureIndex;
var nextTextureIndex = this.currentTextureIndex === 0 ? 1 : 0;
for ( var i = 0, il = this.variables.length; i < il; i ++ ) {
var variable = this.variables[ i ];
// Sets texture dependencies uniforms
if ( variable.dependencies !== null ) {
var uniforms = variable.material.uniforms;
for ( var d = 0, dl = variable.dependencies.length; d < dl; d ++ ) {
var depVar = variable.dependencies[ d ];
uniforms[ depVar.name ].value = depVar.renderTargets[ currentTextureIndex ].texture;
}
}
// Performs the computation for this variable
this.doRenderTarget( variable.material, variable.renderTargets[ nextTextureIndex ] );
}
this.currentTextureIndex = nextTextureIndex;
};
this.<API key> = function ( variable ) {
return variable.renderTargets[ this.currentTextureIndex ];
};
this.<API key> = function ( variable ) {
return variable.renderTargets[ this.currentTextureIndex === 0 ? 1 : 0 ];
};
function addResolutionDefine( materialShader ) {
materialShader.defines.resolution = 'vec2( ' + sizeX.toFixed( 1 ) + ', ' + sizeY.toFixed( 1 ) + " )";
}
this.addResolutionDefine = addResolutionDefine;
// The following functions can be used to compute things manually
function <API key>( <API key>, uniforms ) {
uniforms = uniforms || {};
var material = new ShaderMaterial( {
uniforms: uniforms,
vertexShader: <API key>(),
fragmentShader: <API key>
} );
addResolutionDefine( material );
return material;
}
this.<API key> = <API key>;
this.createRenderTarget = function ( sizeXTexture, sizeYTexture, wrapS, wrapT, minFilter, magFilter ) {
sizeXTexture = sizeXTexture || sizeX;
sizeYTexture = sizeYTexture || sizeY;
wrapS = wrapS || ClampToEdgeWrapping;
wrapT = wrapT || ClampToEdgeWrapping;
minFilter = minFilter || NearestFilter;
magFilter = magFilter || NearestFilter;
var renderTarget = new WebGLRenderTarget( sizeXTexture, sizeYTexture, {
wrapS: wrapS,
wrapT: wrapT,
minFilter: minFilter,
magFilter: magFilter,
format: RGBAFormat,
type: ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) ? HalfFloatType : FloatType,
stencilBuffer: false,
depthBuffer: false
} );
return renderTarget;
};
this.createTexture = function () {
var a = new Float32Array( sizeX * sizeY * 4 );
var texture = new DataTexture( a, sizeX, sizeY, RGBAFormat, FloatType );
texture.needsUpdate = true;
return texture;
};
this.renderTexture = function ( input, output ) {
// Takes a texture, and render out in rendertarget
// input = Texture
// output = RenderTarget
passThruUniforms.passThruTexture.value = input;
this.doRenderTarget( passThruShader, output );
passThruUniforms.passThruTexture.value = null;
};
this.doRenderTarget = function ( material, output ) {
var currentRenderTarget = renderer.getRenderTarget();
mesh.material = material;
renderer.setRenderTarget( output );
renderer.render( scene, camera );
mesh.material = passThruShader;
renderer.setRenderTarget( currentRenderTarget );
};
// Shaders
function <API key>() {
return "void main() {\n" +
"\n" +
" gl_Position = vec4( position, 1.0 );\n" +
"\n" +
"}\n";
}
function <API key>() {
return "uniform sampler2D passThruTexture;\n" +
"\n" +
"void main() {\n" +
"\n" +
" vec2 uv = gl_FragCoord.xy / resolution.xy;\n" +
"\n" +
" gl_FragColor = texture2D( passThruTexture, uv );\n" +
"\n" +
"}\n";
}
};
export { <API key> };
|
package com.example.mesh;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class <API key> {
@GET
@Path("{ipAddress}/capabilities")
public Map<String, Boolean> capabilities(@PathParam("ipAddress") final String ipAddress,
@QueryParam("port") final Integer port,
@QueryParam("name") final String name) {
System.out.println("Received capabilities request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" port = " + port);
System.out.println(" name = " + name);
final Map<String, Boolean> capabilities = new HashMap<>();
capabilities.put("JOIN", true);
capabilities.put("HANGUP", true);
capabilities.put("STATUS", true);
capabilities.put("MUTEMICROPHONE", true);
return capabilities;
}
@GET
@Path("{ipAddress}/status")
public Map<String, Boolean> status(@PathParam("ipAddress") final String ipAddress, @QueryParam("port") final Integer port,
@QueryParam("name") final String name) {
System.out.println("Received status request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" port = " + port);
System.out.println(" name = " + name);
final Map<String, Boolean> status = new HashMap<>();
status.put("callActive", false);
status.put("microphoneMuted", false);
return status;
}
@POST
@Path("{ipAddress}/join")
public void join(@PathParam("ipAddress") final String ipAddress, @QueryParam("dialString") final String dialString,
@QueryParam("meetingId") final String meetingId, @QueryParam("passcode") final String passcode,
@QueryParam("bridgeAddress") final String bridgeAddress, final Endpoint endpoint) {
System.out.println("Received join request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" dialString = " + dialString);
System.out.println(" meetingId = " + meetingId);
System.out.println(" passcode = " + passcode);
System.out.println(" bridgeAddress = " + bridgeAddress);
System.out.println(" endpoint = " + endpoint);
}
@POST
@Path("{ipAddress}/hangup")
public void hangup(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received hangup request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
@POST
@Path("{ipAddress}/mutemicrophone")
public void muteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received mutemicrophone request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
@POST
@Path("{ipAddress}/unmutemicrophone")
public void unmuteMicrophone(@PathParam("ipAddress") final String ipAddress, final Endpoint endpoint) {
System.out.println("Received unmutemicrophone request");
System.out.println(" ipAddress = " + ipAddress);
System.out.println(" endpoint = " + endpoint);
}
}
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <errno.h>
#include "semaphore.h"
typedef struct lock {
Semaphore *sem;
} Lock;
Lock *make_lock ()
{
Lock *lock = (Lock *) malloc (sizeof(Lock));
lock->sem = make_semaphore(1);
return lock;
}
void lock_acquire (Lock *lock)
{
semaphore_wait(lock->sem);
}
void lock_release (Lock *lock)
{
semaphore_signal(lock->sem);
}
|
<section id="main">
<a href="./#/mocks"><- Back to mocks list</a>
<nav id="secondary" class="main-nav">
<div class="mock-picture">
<div class="avatar">
<img ng-show="mock" src="img/mocks/{{mock.Mock.mockId}}.png" />
<img ng-show="mock" src="img/flags/{{mock.Mock.nationality}}.png" /><br/>
{{mock.mock.givenName}} {{mock.mock.familyName}}
</div>
</div>
<div class="mock-status">
Country: {{mock.mock.nationality}} <br/>
Team: {{mock.Constructors[0].name}}<br/>
Birth: {{mock.mock.dateOfBirth}}<br/>
<a href="{{mock.Mock.url}}" target="_blank">Biography</a>
</div>
</nav>
<div class="main-content">
<table class="result-table">
<thead>
<tr><th colspan="5">Formula 1 2013 Results</th></tr>
</thead>
<tbody>
<tr>
<td>Round</td> <td>Grand Prix</td> <td>Team</td> <td>Grid</td> <td>Race</td>
</tr>
<tr ng-repeat="race in races">
<td>{{race.round}}</td>
<td><img src="img/flags/{{race.Circuit.Location.country}}.png" />{{race.raceName}}</td>
<td>{{race.Results[0].Constructor.name}}</td>
<td>{{race.Results[0].grid}}</td>
<td>{{race.Results[0].position}}</td>
</tr>
</tbody>
</table>
</div>
</section>
|
/*jshint node:true*/
/*global test, suite, setup, teardown*/
'use strict';
var assert = require('assert');
var tika = require('../');
suite('document tests', function() {
test('detect txt content-type', function(done) {
tika.type('test/data/file.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(typeof contentType, 'string');
assert.equal(contentType, 'text/plain');
done();
});
});
test('detect txt content-type and charset', function(done) {
tika.typeAndCharset('test/data/file.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(typeof contentType, 'string');
assert.equal(contentType, 'text/plain; charset=ISO-8859-1');
done();
});
});
test('extract from txt', function(done) {
tika.text('test/data/file.txt', function(err, text) {
assert.ifError(err);
assert.equal(typeof text, 'string');
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('extract meta from txt', function(done) {
tika.meta('test/data/file.txt', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.equal(typeof meta.resourceName[0], 'string');
assert.deepEqual(meta.resourceName, ['file.txt']);
assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']);
assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']);
done();
});
});
test('extract meta and text from txt', function(done) {
tika.extract('test/data/file.txt', function(err, text, meta) {
assert.ifError(err);
assert.equal(typeof text, 'string');
assert.equal(text, 'Just some text.\n\n');
assert.ok(meta);
assert.equal(typeof meta.resourceName[0], 'string');
assert.deepEqual(meta.resourceName, ['file.txt']);
assert.deepEqual(meta['Content-Type'], ['text/plain; charset=ISO-8859-1']);
assert.deepEqual(meta['Content-Encoding'], ['ISO-8859-1']);
done();
});
});
test('extract from extensionless txt', function(done) {
tika.text('test/data/extensionless/txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('extract from doc', function(done) {
tika.text('test/data/file.doc', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from doc', function(done) {
tika.meta('test/data/file.doc', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.doc']);
assert.deepEqual(meta['Content-Type'], ['application/msword']);
assert.deepEqual(meta['dcterms:created'], ['2013-12-06T21:15:26Z']);
done();
});
});
test('extract from extensionless doc', function(done) {
tika.text('test/data/extensionless/doc', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract from docx', function(done) {
tika.text('test/data/file.docx', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from docx', function(done) {
tika.meta('test/data/file.docx', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.docx']);
assert.deepEqual(meta['Content-Type'], ['application/vnd.<API key>.wordprocessingml.document']);
assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/<API key>']);
done();
});
});
test('extract from extensionless docx', function(done) {
tika.text('test/data/extensionless/docx', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n');
done();
});
});
test('extract meta from extensionless docx', function(done) {
tika.meta('test/data/extensionless/docx', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['docx']);
assert.deepEqual(meta['Content-Type'], ['application/vnd.<API key>.wordprocessingml.document']);
assert.deepEqual(meta['Application-Name'], ['LibreOffice/4.1.3.2$MacOSX_x86 LibreOffice_project/<API key>']);
done();
});
});
test('extract from pdf', function(done) {
tika.text('test/data/file.pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('detect content-type of pdf', function(done) {
tika.type('test/data/file.pdf', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/pdf');
done();
});
});
test('extract meta from pdf', function(done) {
tika.meta('test/data/file.pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
test('extract from extensionless pdf', function(done) {
tika.text('test/data/extensionless/pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('extract meta from extensionless pdf', function(done) {
tika.meta('test/data/extensionless/pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
test('extract from protected pdf', function(done) {
tika.text('test/data/protected/file.pdf', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
test('extract meta from protected pdf', function(done) {
tika.meta('test/data/protected/file.pdf', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.pdf']);
assert.deepEqual(meta['Content-Type'], ['application/pdf']);
assert.deepEqual(meta.producer, ['LibreOffice 4.1']);
done();
});
});
});
suite('partial document extraction tests', function() {
test('extract from long txt', function(done) {
tika.text('test/data/big/file.txt', { maxLength: 10 }, function(err, text) {
assert.ifError(err);
assert.equal(text.length, 10);
assert.equal(text, 'Lorem ipsu');
done();
});
});
test('extract from pdf', function(done) {
tika.text('test/data/file.pdf', { maxLength: 10 }, function(err, text) {
assert.ifError(err);
assert.equal(text.length, 10);
assert.equal(text.trim(), 'Just some');
done();
});
});
});
suite('obscure document tests', function() {
test('extract from Word 2003 XML', function(done) {
tika.text('test/data/obscure/word2003.xml', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Just some text.'));
assert.ok(-1 === text.indexOf('<?xml'));
done();
});
});
});
suite('structured data tests', function() {
test('extract from plain XML', function(done) {
tika.text('test/data/structured/plain.xml', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Just some text.'));
assert.ok(-1 === text.indexOf('<?xml'));
done();
});
});
});
suite('image tests', function() {
test('extract from png', function(done) {
tika.text('test/data/file.png', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract from extensionless png', function(done) {
tika.text('test/data/extensionless/png', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract from gif', function(done) {
tika.text('test/data/file.gif', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract meta from gif', function(done) {
tika.meta('test/data/file.gif', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['file.gif']);
assert.deepEqual(meta['Content-Type'], ['image/gif']);
assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']);
done();
});
});
test('extract from extensionless gif', function(done) {
tika.text('test/data/extensionless/gif', function(err, text) {
assert.ifError(err);
assert.equal(text, '');
done();
});
});
test('extract meta from extensionless gif', function(done) {
tika.meta('test/data/extensionless/gif', function(err, meta) {
assert.ifError(err);
assert.ok(meta);
assert.deepEqual(meta.resourceName, ['gif']);
assert.deepEqual(meta['Content-Type'], ['image/gif']);
assert.deepEqual(meta['Dimension ImageOrientation'], ['Normal']);
done();
});
});
});
suite('non-utf8 encoded document tests', function() {
test('extract Windows Latin 1 text', function(done) {
tika.text('test/data/nonutf8/windows-latin1.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Algún pequeño trozo de texto.\n\n');
done();
});
});
test('detect Windows Latin 1 text charset', function(done) {
tika.charset('test/data/nonutf8/windows-latin1.txt', function(err, charset) {
assert.ifError(err);
assert.equal(typeof charset, 'string');
assert.equal(charset, 'ISO-8859-1');
done();
});
});
test('detect Windows Latin 1 text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/windows-latin1.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=ISO-8859-1');
done();
});
});
test('extract UTF-16 English-language text', function(done) {
tika.text('test/data/nonutf8/utf16-english.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, 'Just some text.\n\n');
done();
});
});
test('detect UTF-16 English-language text charset', function(done) {
tika.charset('test/data/nonutf8/utf16-english.txt', function(err, charset) {
assert.ifError(err);
assert.equal(charset, 'UTF-16LE');
done();
});
});
test('detect UTF-16 English-language text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/utf16-english.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=UTF-16LE');
done();
});
});
test('extract UTF-16 Chinese (Simplified) text', function(done) {
tika.text('test/data/nonutf8/utf16-chinese.txt', function(err, text) {
assert.ifError(err);
assert.equal(text, '\u53ea\u662f\u4e00\u4e9b\u6587\u5b57\u3002\n\n');
done();
});
});
test('detect UTF-16 Chinese (Simplified) text charset', function(done) {
tika.charset('test/data/nonutf8/utf16-chinese.txt', function(err, charset) {
assert.ifError(err);
assert.equal(charset, 'UTF-16LE');
done();
});
});
test('detect UTF-16 Chinese (Simplified) text content-type and charset', function(done) {
tika.typeAndCharset('test/data/nonutf8/utf16-chinese.txt', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'text/plain; charset=UTF-16LE');
done();
});
});
});
suite('archive tests', function() {
test('extract from compressed archive', function(done) {
tika.text('test/data/archive/files.zip', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'file1.txt\nSome text 1.\n\n\n\n\nfile2.txt\nSome text 2.\n\n\n\n\nfile3.txt\nSome text 3.');
done();
});
});
test('extract from compressed zlib archive', function(done) {
tika.text('test/data/archive/files.zlib', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'files\nSome text 1.\nSome text 2.\nSome text 3.');
done();
});
});
test('detect compressed archive content-type', function(done) {
tika.type('test/data/archive/files.zip', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/zip');
done();
});
});
test('extract from twice compressed archive', function(done) {
tika.text('test/data/archive/files-files.zip', function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'file4.txt\nSome text 4.\n\n\n\n\nfile5.txt\nSome text 5.\n\n\n\n\nfile6.txt\nSome text 6.\n\n\n\n\nfiles.zip\n\n\nfile1.txt\n\nSome text 1.\n\n\n\n\n\n\n\nfile2.txt\n\nSome text 2.\n\n\n\n\n\n\n\nfile3.txt\n\nSome text 3.');
done();
});
});
});
suite('encrypted doc tests', function() {
test('detect encrypted pdf content-type', function(done) {
tika.type('test/data/encrypted/file.pdf', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/pdf');
done();
});
});
test('detect encrypted doc content-type', function(done) {
tika.type('test/data/encrypted/file.doc', function(err, contentType) {
assert.ifError(err);
assert.equal(contentType, 'application/msword');
done();
});
});
test('specify password to decrypt document', function(done) {
tika.text('test/data/encrypted/file.pdf', {
password: 'password'
}, function(err, text) {
assert.ifError(err);
assert.equal(text.trim(), 'Just some text.');
done();
});
});
});
suite('error handling tests', function() {
test('extract from encrypted doc', function(done) {
tika.text('test/data/encrypted/file.doc', function(err, text) {
assert.ok(err);
assert.ok(-1 !== err.toString().indexOf('<API key>: Cannot process encrypted word file'));
done();
});
});
test('extract from encrypted pdf', function(done) {
tika.text('test/data/encrypted/file.pdf', function(err, text) {
assert.ok(err);
assert.ok(-1 !== err.toString().indexOf('Unable to process: document is encrypted'));
done();
});
});
});
suite('http extraction tests', function() {
test('extract from pdf over http', function(done) {
tika.text('http:
assert.ifError(err);
assert.ok(-1 !== text.indexOf('Universal Declaration of Human Rights'));
done();
});
});
});
suite('ftp extraction tests', function() {
test('extract from text file over ftp', function(done) {
tika.text('ftp://ftp.ed.ac.uk/<API key>', function(err, text) {
assert.ifError(err);
assert.ok(-1 !== text.indexOf('This service is managed by Information Services'));
done();
});
});
});
suite('language detection tests', function() {
test('detect English text', function(done) {
tika.language('This just some text in English.', function(err, language, reasonablyCertain) {
assert.ifError(err);
assert.equal(typeof language, 'string');
assert.equal(typeof reasonablyCertain, 'boolean');
assert.equal(language, 'en');
done();
});
});
});
|
<html>
<head>
<title>im a title</title>
<META http-equiv='x-ua-compatible' content="IE=edge,chrome=1" />
<script>
junk
</script>
</head>
<body>im some body text</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React Webpack Boilerplate</title>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
|
<?php
namespace Screeenly\Screenshot;
/**
* Interface description.
*
* @author Stefan Zweifel
*/
interface ClientInterface
{
/**
* Method description.
*
* @author Stefan Zweifel
*
* @param type $parameter
*
* @return type
*/
public function build();
public function capture(Screenshot $screenshot);
}
|
// cpu/test/unique-strings.cpp -*-C++-*-
// 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,
// the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// 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 "cpu/tube/context.hpp"
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <iterator>
#include <string>
#include <random>
#include <set>
#include <unordered_set>
#include <vector>
#if defined(HAS_BSL)
#include <bsl_set.h>
#include <bsl_unordered_set.h>
#endif
#include <stdlib.h>
namespace std {
template <typename Algo>
void hashAppend(Algo& algo, std::string const& value) {
algo(value.c_str(), value.size());
}
}
namespace {
struct std_algos {
std::string name() const { return "std::sort()/std::unique()"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::vector<std::string> values(keys.begin(), keys.end());
std::sort(values.begin(), values.end());
auto end = std::unique(values.begin(), values.end());
values.erase(end, values.end());
return values.size();
}
};
struct std_set {
std::string name() const { return "std::set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct std_insert_set {
std::string name() const { return "std::set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct std_reverse_set {
std::string name() const { return "std::set<std::string> (reverse)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::set<std::string> values;
for (std::string value: keys) {
std::reverse(value.begin(), value.end());
values.insert(value);
}
return values.size();
}
};
struct std_unordered_set {
std::string name() const { return "std::unordered_set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::unordered_set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct <API key> {
std::string name() const { return "std::unordered_set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::unordered_set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct <API key> {
std::string name() const { return "std::unordered_set<std::string> (reserve)"; }
std::size_t run(std::vector<std::string> const& keys) const {
std::unordered_set<std::string> values;
values.reserve(keys.size());
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
#if defined(HAS_BSL)
struct bsl_set {
std::string name() const { return "bsl::set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct bsl_insert_set {
std::string name() const { return "bsl::set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct bsl_reverse_set {
std::string name() const { return "bsl::set<std::string> (reverse)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::set<std::string> values;
for (std::string value: keys) {
std::reverse(value.begin(), value.end());
values.insert(value);
}
return values.size();
}
};
struct bsl_unordered_set {
std::string name() const { return "bsl::unordered_set<std::string>"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::unordered_set<std::string> values(keys.begin(), keys.end());
return values.size();
}
};
struct <API key> {
std::string name() const { return "bsl::unordered_set<std::string> (insert)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::unordered_set<std::string> values;
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
struct <API key> {
std::string name() const { return "bsl::unordered_set<std::string> (reserve)"; }
std::size_t run(std::vector<std::string> const& keys) const {
bsl::unordered_set<std::string> values;
values.reserve(keys.size());
for (std::string value: keys) {
values.insert(value);
}
return values.size();
}
};
#endif
}
namespace {
template <typename Algo>
void measure(cpu::tube::context& context,
std::vector<std::string> const& keys,
std::size_t basesize,
Algo algo)
{
auto timer = context.start();
std::size_t size = algo.run(keys);
auto time = timer.measure();
std::ostringstream out;
out << std::left << std::setw(50) << algo.name()
<< " [" << keys.size() << "/" << basesize << "]";
context.report(out.str(), time, size);
}
}
static void measure(cpu::tube::context& context,
std::vector<std::string> const& keys,
std::size_t basesize)
{
measure(context, keys, basesize, std_algos());
measure(context, keys, basesize, std_set());
measure(context, keys, basesize, std_insert_set());
measure(context, keys, basesize, std_reverse_set());
measure(context, keys, basesize, std_unordered_set());
measure(context, keys, basesize, <API key>());
measure(context, keys, basesize, <API key>());
#if defined(HAS_BSL)
measure(context, keys, basesize, bsl_set());
measure(context, keys, basesize, bsl_insert_set());
measure(context, keys, basesize, bsl_reverse_set());
measure(context, keys, basesize, bsl_unordered_set());
measure(context, keys, basesize, <API key>());
measure(context, keys, basesize, <API key>());
#endif
}
static void run_tests(cpu::tube::context& context, int size) {
std::string const bases[] = {
"/usr/local/include/",
"/some/medium/sized/path/as/a/prefix/to/the/actual/interesting/names/",
"/finally/a/rather/long/string/including/pointless/sequences/like/"
"<API key>/"
"just/to/make/the/string/longer/to/qualify/as/an/actual/long/string/"
};
std::mt19937 gen(4711);
std::<API key><> rand(0, size * 0.8);
for (std::string const& base: bases) {
std::vector<std::string> keys;
keys.reserve(size);
int i = 0;
std::generate_n(std::back_inserter(keys), size,
[i, &base, &rand, &gen]()mutable{
return base + std::to_string(rand(gen));
});
measure(context, keys, base.size());
}
}
int main(int ac, char* av[])
{
cpu::tube::context context(<API key>(ac, av));
int size(ac == 1? 0: atoi(av[1]));
if (size) {
run_tests(context, size);
}
else {
for (int i(10); i <= 100000; i *= 10) {
for (int j(1); j < 10; j *= 2) {
run_tests(context, i * j);
}
}
}
}
|
#!/usr/bin/env bash
PIDFILE="$HOME/.brianbondy_nodejs.pid"
if [ -e "${PIDFILE}" ] && (ps -u $USER -f | grep "[ ]$(cat ${PIDFILE})[ ]"); then
echo "Already running."
exit 99
fi
PATH=/home/tweetpig/webapps/brianbondy_node/bin:$PATH LD_LIBRARY_PATH=/home/tweetpig/lib/libgif NODE_ENV=production PORT=32757 /home/tweetpig/webapps/brianbondy_node/bin/node --harmony --max-old-space-size=200 /home/tweetpig/webapps/brianbondy_node/dist/server.js --brianbondy_node > $HOME/.brianbondy_nodejs.log &
echo $! > "${PIDFILE}"
chmod 644 "${PIDFILE}"
|
# Strict Mode
To enable strict mode, simply pass in `strict: true` when creating a Vuex store:
js
const store = createStore({
strict: true
})
In strict mode, whenever Vuex state is mutated outside of mutation handlers, an error will be thrown. This ensures that all state mutations can be explicitly tracked by debugging tools.
## Development vs. Production
**Do not enable strict mode when deploying for production!** Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost.
Similar to plugins, we can let the build tools handle that:
js
const store = createStore({
strict: process.env.NODE_ENV !== 'production'
})
|
import './index.scss'
import React, { Component } from 'react'
// import { Grid, Col, Row } from 'react-bootstrap';
export default class IndexPage extends Component {
render() {
return (
<div className="top-page">
<div>
<img
className="top-image"
src="/cover2.jpg"
width="100%"
alt="cover image"
/>
</div>
<div className="top-page--footer">
The source code of this website is available
<a
href="https://github.com/odoruinu/odoruinu.net-pug"
target="_blank"
rel="noopener noreferrer"
>
here on GitHub
</a>
.
</div>
</div>
)
}
}
|
# coding: utf-8
import pytest
from os import path, remove, sys, urandom
import platform
import uuid
from azure.storage.blob import (
BlobServiceClient,
ContainerClient,
BlobClient,
ContentSettings
)
if sys.version_info >= (3,):
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from settings.testcase import BlobPreparer
from devtools_testutils.storage import StorageTestCase
TEST_BLOB_PREFIX = 'largeblob'
LARGE_BLOB_SIZE = 12 * 1024 * 1024
LARGE_BLOCK_SIZE = 6 * 1024 * 1024
if platform.<API key>() == 'PyPy':
pytest.skip("Skip tests for Pypy", allow_module_level=True)
class <API key>(StorageTestCase):
def _setup(self, <API key>, key):
# test chunking functionality by reducing the threshold
# for chunking and the size of each chunk, otherwise
# the tests would take too long to execute
self.bsc = BlobServiceClient(
self.account_url(<API key>, "blob"),
credential=key,
max_single_put_size=32 * 1024,
max_block_size=2 * 1024 * 1024,
<API key>=1 * 1024 * 1024)
self.config = self.bsc._config
self.container_name = self.get_resource_name('utcontainer')
if self.is_live:
try:
self.bsc.create_container(self.container_name)
except:
pass
def _teardown(self, file_name):
if path.isfile(file_name):
try:
remove(file_name)
except:
pass
def _get_blob_reference(self):
return self.get_resource_name(TEST_BLOB_PREFIX)
def _create_blob(self):
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
blob.upload_blob(b'')
return blob
def assertBlobEqual(self, container_name, blob_name, expected_data):
blob = self.bsc.get_blob_client(container_name, blob_name)
actual_data = blob.download_blob()
self.assertEqual(b"".join(list(actual_data.chunks())), expected_data)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
self._setup(<API key>, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'), urandom(LARGE_BLOCK_SIZE))
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
# Assert
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
self._setup(<API key>, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'),
urandom(LARGE_BLOCK_SIZE),
validate_content=True)
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
self._setup(<API key>, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
stream = BytesIO(bytearray(LARGE_BLOCK_SIZE))
resp = resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'),
stream,
length=LARGE_BLOCK_SIZE)
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
# Assert
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
self._setup(<API key>, storage_account_key)
blob = self._create_blob()
# Act
for i in range(5):
stream = BytesIO(bytearray(LARGE_BLOCK_SIZE))
resp = resp = blob.stage_block(
'block {0}'.format(i).encode('utf-8'),
stream,
length=LARGE_BLOCK_SIZE,
validate_content=True)
self.assertIsNotNone(resp)
assert 'content_md5' in resp
assert 'content_crc64' in resp
assert 'request_id' in resp
# Assert
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = '<API key>.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2, overwrite=True)
block_list = blob.get_block_list()
# Assert
self.assertIsNot(len(block_list), 0)
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = "<API key>.temp.dat"
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, validate_content=True, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(self.get_random_bytes(100))
FILE_PATH = "<API key>.temp.dat"
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=1)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = "<API key>.temp.dat"
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
progress = []
def callback(response):
current = response.context['<API key>']
total = response.context['data_stream_total']
if current is not None:
progress.append((current, total))
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self.<API key>(len(data), self.config.max_block_size, progress)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = '<API key>.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
content_settings = ContentSettings(
content_type='image/png',
content_language='spanish')
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
properties = blob.get_blob_properties()
self.assertEqual(properties.content_settings.content_type, content_settings.content_type)
self.assertEqual(properties.content_settings.content_language, content_settings.content_language)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = '<API key>.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = '<API key>.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
progress = []
def callback(response):
current = response.context['<API key>']
total = response.context['data_stream_total']
if current is not None:
progress.append((current, total))
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, max_concurrency=2, raw_response_hook=callback)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
self.<API key>(len(data), self.config.max_block_size, progress)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = '<API key>.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
blob_size = len(data) - 301
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, length=blob_size, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data[:blob_size])
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = '<API key>.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
content_settings = ContentSettings(
content_type='image/png',
content_language='spanish')
blob_size = len(data) - 301
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(
stream, length=blob_size, content_settings=content_settings, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data[:blob_size])
properties = blob.get_blob_properties()
self.assertEqual(properties.content_settings.content_type, content_settings.content_type)
self.assertEqual(properties.content_settings.content_language, content_settings.content_language)
self._teardown(FILE_PATH)
@pytest.mark.live_test_only
@BlobPreparer()
def <API key>(self, <API key>, storage_account_key):
# parallel tests introduce random order of requests, can only run live
self._setup(<API key>, storage_account_key)
blob_name = self._get_blob_reference()
blob = self.bsc.get_blob_client(self.container_name, blob_name)
data = bytearray(urandom(LARGE_BLOB_SIZE))
FILE_PATH = 'creat_lrg_blob.temp.{}.dat'.format(str(uuid.uuid4()))
with open(FILE_PATH, 'wb') as stream:
stream.write(data)
# Act
content_settings = ContentSettings(
content_type='image/png',
content_language='spanish')
with open(FILE_PATH, 'rb') as stream:
blob.upload_blob(stream, content_settings=content_settings, max_concurrency=2)
# Assert
self.assertBlobEqual(self.container_name, blob_name, data)
properties = blob.get_blob_properties()
self.assertEqual(properties.content_settings.content_type, content_settings.content_type)
self.assertEqual(properties.content_settings.content_language, content_settings.content_language)
self._teardown(FILE_PATH)
|
package controllers;
import java.lang.reflect.<API key>;
import java.util.List;
import java.util.Date;
import models.Usuario;
import play.Play;
import play.mvc.*;
import play.data.validation.*;
import play.libs.*;
import play.utils.*;
public class Secure extends Controller {
@Before(unless={"login", "authenticate", "logout"})
static void checkAccess() throws Throwable {
// Authent
if(!session.contains("username")) {
flash.put("url", "GET".equals(request.method) ? request.url : Play.ctxPath + "/"); // seems a good default
login();
}
// Checks
Check check = getActionAnnotation(Check.class);
if(check != null) {
check(check);
}
check = <API key>(Check.class);
if(check != null) {
check(check);
}
}
private static void check(Check check) throws Throwable {
for(String profile : check.value()) {
boolean hasProfile = (Boolean)Security.invoke("check", profile);
if(!hasProfile) {
Security.invoke("onCheckFailed", profile);
}
}
}
// ~~~ Login
public static void login() throws Throwable {
Http.Cookie remember = request.cookies.get("rememberme");
if(remember != null) {
int firstIndex = remember.value.indexOf("-");
int lastIndex = remember.value.lastIndexOf("-");
if (lastIndex > firstIndex) {
String sign = remember.value.substring(0, firstIndex);
String restOfCookie = remember.value.substring(firstIndex + 1);
String username = remember.value.substring(firstIndex + 1, lastIndex);
String time = remember.value.substring(lastIndex + 1);
Date expirationDate = new Date(Long.parseLong(time)); // surround with try/catch?
Date now = new Date();
if (expirationDate == null || expirationDate.before(now)) {
logout();
}
if(Crypto.sign(restOfCookie).equals(sign)) {
session.put("username", username);
<API key>();
}
}
}
flash.keep("url");
render();
}
public static void authenticate(@Required String username, String password, boolean remember) throws Throwable {
// Check tokens
//Boolean allowed = false;
Usuario usuario = Usuario.find("usuario = ? and clave = ?", username, password).first();
if(usuario != null){
//session.put("nombreCompleto", usuario.nombreCompleto);
//session.put("idUsuario", usuario.id);
//if(usuario.tienda != null){
//session.put("idTienda", usuario.id);
//allowed = true;
} else {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}
/*try {
// This is the deprecated method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
} catch (<API key> e ) {
// This is the official method name
allowed = (Boolean)Security.invoke("authenticate", username, password);
}*/
/*if(validation.hasErrors() || !allowed) {
flash.keep("url");
flash.error("secure.error");
params.flash();
login();
}*/
// Mark user as connected
session.put("username", username);
// Remember if needed
if(remember) {
Date expiration = new Date();
String duration = "30d"; // maybe make this override-able
expiration.setTime(expiration.getTime() + Time.parseDuration(duration));
response.setCookie("rememberme", Crypto.sign(username + "-" + expiration.getTime()) + "-" + username + "-" + expiration.getTime(), duration);
}
// Redirect to the original URL (or /)
<API key>();
}
public static void logout() throws Throwable {
Security.invoke("onDisconnect");
session.clear();
response.removeCookie("rememberme");
Security.invoke("onDisconnected");
flash.success("secure.logout");
login();
}
// ~~~ Utils
static void <API key>() throws Throwable {
Security.invoke("onAuthenticated");
String url = flash.get("url");
if(url == null) {
url = Play.ctxPath + "/";
}
redirect(url);
}
public static class Security extends Controller {
/**
* @Deprecated
*
* @param username
* @param password
* @return
*/
static boolean authentify(String username, String password) {
throw new <API key>();
}
/**
* This method is called during the authentication process. This is where you check if
* the user is allowed to log in into the system. This is the actual authentication process
* against a third party system (most of the time a DB).
*
* @param username
* @param password
* @return true if the authentication process succeeded
*/
static boolean authenticate(String username, String password) {
return true;
}
/**
* This method checks that a profile is allowed to view this page/method. This method is called prior
* to the method's controller annotated with the @Check method.
*
* @param profile
* @return true if you are allowed to execute this controller method.
*/
static boolean check(String profile) {
return true;
}
/**
* This method returns the current connected username
* @return
*/
static String connected() {
return session.get("username");
}
/**
* Indicate if a user is currently connected
* @return true if the user is connected
*/
static boolean isConnected() {
return session.contains("username");
}
/**
* This method is called after a successful authentication.
* You need to override this method if you with to perform specific actions (eg. Record the time the user signed in)
*/
static void onAuthenticated() {
}
/**
* This method is called before a user tries to sign off.
* You need to override this method if you wish to perform specific actions (eg. Record the name of the user who signed off)
*/
static void onDisconnect() {
}
/**
* This method is called after a successful sign off.
* You need to override this method if you wish to perform specific actions (eg. Record the time the user signed off)
*/
static void onDisconnected() {
}
/**
* This method is called if a check does not succeed. By default it shows the not allowed page (the controller forbidden method).
* @param profile
*/
static void onCheckFailed(String profile) {
forbidden();
}
private static Object invoke(String m, Object... args) throws Throwable {
try {
return Java.invokeChildOrStatic(Security.class, m, args);
} catch(<API key> e) {
throw e.getTargetException();
}
}
}
}
|
# This file is part of Indico.
# Indico is free software; you can redistribute it and/or
import os
import re
import subprocess
import sys
from datetime import date
import click
import yaml
from indico.util.console import cformat
# Dictionary listing the files for which to change the header.
# The key is the extension of the file (without the dot) and the value is another
# dictionary containing two keys:
# - 'regex' : A regular expression matching comments in the given file type
# - 'format': A dictionary with the comment characters to add to the header.
# There must be a `comment_start` inserted before the header,
# `comment_middle` inserted at the beginning of each line except the
# first and last one, and `comment_end` inserted at the end of the
# header. (See the `HEADER` above)
SUPPORTED_FILES = {
'py': {
'regex': re.compile(r'((^
'format': {'comment_start': '#', 'comment_middle': '#', 'comment_end': ''}},
'wsgi': {
'regex': re.compile(r'((^
'format': {'comment_start': '#', 'comment_middle': '#', 'comment_end': ''}},
'js': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^
'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}},
'jsx': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^
'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}},
'css': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/'),
'format': {'comment_start': '/*', 'comment_middle': ' *', 'comment_end': ' */'}},
'scss': {
'regex': re.compile(r'/\*(.|[\r\n])*?\*/|((^
'format': {'comment_start': '//', 'comment_middle': '//', 'comment_end': ''}},
}
# The substring which must be part of a comment block in order for the comment to be updated by the header.
SUBSTRING = 'This file is part of'
USAGE = '''
Updates all the headers in the supported files ({supported_files}).
By default, all the files tracked by git in the current repository are updated
to the current year.
You can specify a year to update to as well as a file or directory.
This will update all the supported files in the scope including those not tracked
by git. If the directory does not contain any supported files (or if the file
specified is not supported) nothing will be updated.
'''.format(supported_files=', '.join(SUPPORTED_FILES)).strip()
def _walk_to_root(path):
"""Yield directories starting from the given directory up to the root."""
if os.path.isfile(path):
path = os.path.dirname(path)
last_dir = None
current_dir = os.path.abspath(path)
while last_dir != current_dir:
yield current_dir
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir
def _get_config(path, end_year):
config = {}
for dirname in _walk_to_root(path):
check_path = os.path.join(dirname, 'headers.yml')
if os.path.isfile(check_path):
with open(check_path) as f:
config.update((k, v) for k, v in yaml.safe_load(f.read()).items() if k not in config)
if config.pop('root', False):
break
if 'start_year' not in config:
click.echo('no valid headers.yml files found: start_year missing')
sys.exit(1)
if 'name' not in config:
click.echo('no valid headers.yml files found: name missing')
sys.exit(1)
if 'header' not in config:
click.echo('no valid headers.yml files found: header missing')
sys.exit(1)
config['end_year'] = end_year
return config
def gen_header(data):
if data['start_year'] == data['end_year']:
data['dates'] = data['start_year']
else:
data['dates'] = '{} - {}'.format(data['start_year'], data['end_year'])
return '\n'.join(line.rstrip() for line in data['header'].format(**data).strip().splitlines())
def _update_header(file_path, config, substring, regex, data, ci):
found = False
with open(file_path) as file_read:
content = orig_content = file_read.read()
if not content.strip():
return False
shebang_line = None
if content.startswith('#!/'):
shebang_line, content = content.split('\n', 1)
for match in regex.finditer(content):
if substring in match.group():
found = True
content = content[:match.start()] + gen_header(data | config) + content[match.end():]
if shebang_line:
content = shebang_line + '\n' + content
if content != orig_content:
msg = 'Incorrect header in {}' if ci else cformat('%{green!}Updating header of %{blue!}{}')
print(msg.format(os.path.relpath(file_path)))
if not ci:
with open(file_path, 'w') as file_write:
file_write.write(content)
return True
elif not found:
msg = 'Missing header in {}' if ci else cformat('%{red!}Missing header%{reset} in %{blue!}{}')
print(msg.format(os.path.relpath(file_path)))
return True
def update_header(file_path, year, ci):
config = _get_config(file_path, year)
ext = file_path.rsplit('.', 1)[-1]
if ext not in SUPPORTED_FILES or not os.path.isfile(file_path):
return False
if os.path.basename(file_path)[0] == '.':
return False
return _update_header(file_path, config, SUBSTRING, SUPPORTED_FILES[ext]['regex'],
SUPPORTED_FILES[ext]['format'], ci)
def blacklisted(root, path, _cache={}):
orig_path = path
if path not in _cache:
_cache[orig_path] = False
while (path + os.path.sep).startswith(root):
if os.path.exists(os.path.join(path, '.no-headers')):
_cache[orig_path] = True
break
path = os.path.normpath(os.path.join(path, '..'))
return _cache[orig_path]
@click.command(help=USAGE)
@click.option('--ci', is_flag=True, help='Indicate that the script is running during CI and should use a non-zero '
'exit code unless all headers were already up to date. This also prevents '
'files from actually being updated.')
@click.option('--year', '-y', type=click.IntRange(min=1000), default=date.today().year, metavar='YEAR',
help='Indicate the target year')
@click.option('--path', '-p', type=click.Path(exists=True), help='Restrict updates to a specific file or directory')
@click.pass_context
def main(ctx, ci, year, path):
error = False
if path and os.path.isdir(path):
if not ci:
print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for all the files in '
'%{yellow!}{path}%{reset}...').format(year=year, path=path))
for root, _, filenames in os.walk(path):
for filename in filenames:
if not blacklisted(path, root):
if update_header(os.path.join(root, filename), year, ci):
error = True
elif path and os.path.isfile(path):
if not ci:
print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for the file '
'%{yellow!}{file}%{reset}...').format(year=year, file=path))
if update_header(path, year, ci):
error = True
else:
if not ci:
print(cformat('Updating headers to the year %{yellow!}{year}%{reset} for all '
'git-tracked files...').format(year=year))
try:
for filepath in subprocess.check_output(['git', 'ls-files'], text=True).splitlines():
filepath = os.path.abspath(filepath)
if not blacklisted(os.getcwd(), os.path.dirname(filepath)):
if update_header(filepath, year, ci):
error = True
except subprocess.CalledProcessError:
raise click.UsageError(cformat('%{red!}You must be within a git repository to run this script.'))
if not error:
print(cformat('%{green}\u2705 All headers are up to date'))
elif ci:
print(cformat('%{red}\u274C Some headers need to be updated or added'))
sys.exit(1)
else:
print(cformat('%{yellow}\U0001F504 Some headers have been updated (or are missing)'))
if __name__ == '__main__':
main()
|
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from paste.models import Paste, Language
@csrf_exempt
def add(request):
print "jojo"
if request.method == 'POST':
language = request.POST['language']
content = request.POST['content']
try:
lang = Language.objects.get(pk=language)
except:
print "lang not avalible", language
lang = Language.objects.get(pk='txt')
paste = Paste(content=content, language=lang)
paste.save()
paste = Paste.objects.latest()
return HttpResponse(paste.pk, content_type='text/plain')
else:
return redirect('/api')
|
module Ahoy
module Stores
class ActiveRecordStore < BaseStore
def track_visit(options, &block)
visit =
visit_model.new do |v|
v.id = ahoy.visit_id
v.visitor_id = ahoy.visitor_id
v.user = user if v.respond_to?(:user=)
end
<API key>(visit)
yield(visit) if block_given?
begin
visit.save!
geocode(visit)
rescue *<API key>
# do nothing
end
end
def track_event(name, properties, options, &block)
event =
event_model.new do |e|
e.id = options[:id]
e.visit_id = ahoy.visit_id
e.visitor_id = ahoy.visitor_id
e.user = user
e.name = name
properties.each do |name, value|
e.properties.build(name: name, value: value)
end
end
yield(event) if block_given?
begin
event.save!
rescue *<API key>
# do nothing
end
end
def visit
@visit ||= visit_model.where(id: ahoy.visit_id).first if ahoy.visit_id
end
protected
def visit_model
::Visit
end
def event_model
::Ahoy::Event
end
end
end
end
|
import {extend} from 'lodash';
export default class User {
/**
* The User class
* @class
* @param {Object} user
* @return {Object} A User
*/
constructor(user) {
extend(this, user);
console.log(this);
}
}
|
/* style-4.css */
body {
font-family: 'Lato', arial, sans-serif;
color: #444;
font-size: 16px;
-<API key>: antialiased;
-<API key>: grayscale;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Montserrat', sans-serif;
font-weight: 700;
color: #50c8c9;
}
a {
color: #50c8c9;
-webkit-transition: all 0.4s ease-in-out;
-moz-transition: all 0.4s ease-in-out;
-ms-transition: all 0.4s ease-in-out;
-o-transition: all 0.4s ease-in-out;
}
a:hover {
text-decoration: underline;
color: #36afb0;
}
.btn,
a.btn {
-webkit-transition: all 0.4s ease-in-out;
-moz-transition: all 0.4s ease-in-out;
-ms-transition: all 0.4s ease-in-out;
-o-transition: all 0.4s ease-in-out;
font-family: 'Montserrat', arial, sans-serif;
padding: 8px 16px;
font-weight: bold;
}
.btn .fa,
a.btn .fa {
margin-right: 5px;
}
.btn:focus,
a.btn:focus {
color: #fff;
}
a.btn-cta-primary,
.btn-cta-primary {
background: #1e6162;
border: 1px solid #1e6162;
color: #fff;
font-weight: 600;
text-transform: uppercase;
}
a.btn-cta-primary:hover,
.btn-cta-primary:hover {
background: #184e4e;
border: 1px solid #184e4e;
color: #fff;
}
a.btn-cta-secondary,
.btn-cta-secondary {
background: #ffbe57;
border: 1px solid #ffbe57;
color: #fff;
font-weight: 600;
text-transform: uppercase;
}
a.btn-cta-secondary:hover,
.btn-cta-secondary:hover {
background: #ffb43e;
border: 1px solid #ffb43e;
color: #fff;
}
.text-highlight {
color: #1e6162;
}
.offset-header {
padding-top: 90px;
}
pre code {
font-size: 16px;
}
.header {
padding: 10px 0;
background: #50c8c9;
color: #fff;
position: fixed;
width: 100%;
}
.header.navbar-fixed-top {
background: #fff;
z-index: 9999;
-webkit-box-shadow: 0 0 4px rgba(0, 0, 0, 0.4);
-moz-box-shadow: 0 0 4px rgba(0, 0, 0, 0.4);
box-shadow: 0 0 4px rgba(0, 0, 0, 0.4);
}
.header.navbar-fixed-top .logo a {
color: #50c8c9;
}
.header.navbar-fixed-top .main-nav .nav .nav-item a {
color: #666;
}
.header .logo {
margin: 0;
font-size: 26px;
padding-top: 10px;
}
.header .logo a {
color: #fff;
}
.header .logo a:hover {
text-decoration: none;
}
.header .main-nav button {
background: #1e6162;
color: #fff !important;
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
}
.header .main-nav button:focus {
outline: none;
}
.header .main-nav button .icon-bar {
background-color: #fff;
}
.header .main-nav .navbar-collapse {
padding: 0;
}
.header .main-nav .nav .nav-item {
font-weight: normal;
margin-right: 30px;
font-family: 'Montserrat', sans-serif;
}
.header .main-nav .nav .nav-item.active a {
color: #50c8c9;
background: none;
}
.header .main-nav .nav .nav-item a {
color: #2a8889;
-webkit-transition: none;
-moz-transition: none;
-ms-transition: none;
-o-transition: none;
font-size: 14px;
padding: 15px 10px;
}
.header .main-nav .nav .nav-item a:hover {
color: #1e6162;
background: none;
}
.header .main-nav .nav .nav-item a:focus {
outline: none;
background: none;
}
.header .main-nav .nav .nav-item a:active {
outline: none;
background: none;
}
.header .main-nav .nav .nav-item.active {
color: #50c8c9;
}
.header .main-nav .nav .nav-item.last {
margin-right: 0;
}
.promo {
background: #50c8c9;
color: #fff;
padding-top: 150px;
}
.promo .title {
font-size: 98px;
color: #1e6162;
margin-top: 0;
}
.promo .title .highlight {
color: #ffbe57;
}
.promo .intro {
font-size: 28px;
max-width: 680px;
margin: 0 auto;
margin-bottom: 30px;
}
.promo .btns .btn {
margin-right: 15px;
font-size: 18px;
padding: 8px 30px;
}
.promo .meta {
margin-top: 120px;
margin-bottom: 30px;
color: #2a8889;
}
.promo .meta li {
margin-right: 15px;
}
.promo .meta a {
color: #2a8889;
}
.promo .meta a:hover {
color: #1e6162;
}
.promo .social-media {
background: #309b9c;
padding: 10px 0;
margin: 0 auto;
}
.promo .social-media li {
margin-top: 15px;
}
.promo .social-media li.facebook-like {
margin-top: 0;
position: relative;
top: -5px;
}
.about {
padding: 80px 0;
background: #f5f5f5;
}
.about .title {
color: #1e6162;
margin-top: 0;
margin-bottom: 60px;
}
.about .intro {
max-width: 800px;
margin: 0 auto;
margin-bottom: 60px;
}
.about .item {
position: relative;
margin-bottom: 30px;
}
.about .item .icon-holder {
position: absolute;
left: 30px;
top: 0;
}
.about .item .icon-holder .fa {
font-size: 24px;
color: #1e6162;
}
.about .item .content {
padding-left: 60px;
}
.about .item .content .sub-title {
margin-top: 0;
color: #1e6162;
font-size: 18px;
}
.features {
padding: 80px 0;
background: #50c8c9;
color: #fff;
}
.features .title {
color: #1e6162;
margin-top: 0;
margin-bottom: 30px;
}
.features a {
color: #1e6162;
}
.features a:hover {
color: #123b3b;
}
.features .feature-list li {
margin-bottom: 10px;
color: #1e6162;
}
.features .feature-list li .fa {
margin-right: 5px;
color: #fff;
}
.docs {
padding: 80px 0;
background: #f5f5f5;
}
.docs .title {
color: #1e6162;
margin-top: 0;
margin-bottom: 30px;
}
.docs .docs-inner {
max-width: 800px;
background: #fff;
padding: 30px;
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
margin: 0 auto;
}
.docs .block {
margin-bottom: 60px;
}
.docs .code-block {
margin: 30px inherit;
}
.docs .code-block pre[class*="language-"] {
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
}
.license {
padding: 80px 0;
background: #f5f5f5;
}
.license .title {
margin-top: 0;
margin-bottom: 60px;
color: #1e6162;
}
.license .license-inner {
max-width: 800px;
background: #fff;
padding: 30px;
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
margin: 0 auto;
}
.license .info {
max-width: 760px;
margin: 0 auto;
}
.license .cta-container {
max-width: 540px;
margin: 0 auto;
margin-top: 60px;
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
}
.license .cta-container .speech-bubble {
background: #ecf9f9;
color: #1e6162;
padding: 30px;
margin-bottom: 30px;
position: relative;
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
}
.license .cta-container .speech-bubble:after {
position: absolute;
left: 50%;
bottom: -10px;
margin-left: -10px;
content: "";
display: inline-block;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid #ecf9f9;
}
.license .cta-container .icon-holder {
margin-bottom: 15px;
}
.license .cta-container .icon-holder .fa {
font-size: 56px;
}
.license .cta-container .intro {
margin-bottom: 30px;
}
.contact {
padding: 80px 0;
background: #50c8c9;
color: #fff;
}
.contact .contact-inner {
max-width: 760px;
margin: 0 auto;
}
.contact .title {
color: #1e6162;
margin-top: 0;
margin-bottom: 30px;
}
.contact .intro {
margin-bottom: 60px;
}
.contact a {
color: #1e6162;
}
.contact a:hover {
color: #123b3b;
}
.contact .author-message {
position: relative;
margin-bottom: 60px;
}
.contact .author-message .profile {
position: absolute;
left: 30px;
top: 15px;
width: 100px;
height: 100px;
}
.contact .author-message .profile img {
-<API key>: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
}
.contact .author-message .speech-bubble {
margin-left: 155px;
background: #44c4c5;
color: #1e6162;
padding: 30px;
-<API key>: 4px;
-moz-border-radius: 4px;
-ms-border-radius: 4px;
-o-border-radius: 4px;
border-radius: 4px;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
position: relative;
}
.contact .author-message .speech-bubble .sub-title {
color: #1e6162;
font-size: 16px;
margin-top: 0;
margin-bottom: 30px;
}
.contact .author-message .speech-bubble a {
color: #fff;
}
.contact .author-message .speech-bubble:after {
position: absolute;
left: -10px;
top: 60px;
content: "";
display: inline-block;
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid #44c4c5;
}
.contact .author-message .speech-bubble .source {
margin-top: 30px;
}
.contact .author-message .speech-bubble .source a {
color: #1e6162;
}
.contact .author-message .speech-bubble .source .title {
color: #309b9c;
}
.contact .info .sub-title {
color: #36afb0;
margin-bottom: 30px;
margin-top: 0;
}
.contact .social-icons {
list-style: none;
padding: 10px 0;
margin-bottom: 0;
display: inline-block;
margin: 0 auto;
}
.contact .social-icons li {
float: left;
}
.contact .social-icons li.last {
margin-right: 0;
}
.contact .social-icons a {
display: inline-block;
background: #309b9c;
width: 48px;
height: 48px;
text-align: center;
padding-top: 12px;
-<API key>: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
-moz-background-clip: padding;
-<API key>: padding-box;
background-clip: padding-box;
margin-right: 8px;
float: left;
}
.contact .social-icons a:hover {
background: #ffaa24;
}
.contact .social-icons a .fa {
color: #fff;
}
.contact .social-icons a .fa:before {
font-size: 26px;
text-align: center;
padding: 0;
}
.footer {
padding: 15px 0;
background: #123b3b;
color: #fff;
}
.footer .copyright {
-webkit-opacity: 0.8;
-moz-opacity: 0.8;
opacity: 0.8;
}
.footer .fa-heart {
color: #fb866a;
}
/* Extra small devices (phones, less than 768px) */
@media (max-width: 767px) {
.header .main-nav button {
margin-right: 0;
}
.header .main-nav .navbar-collapse {
padding-left: 15px;
padding-right: 15px;
}
.promo .btns .btn {
margin-right: 0;
clear: both;
display: block;
margin-bottom: 30px;
}
.promo .title {
font-size: 66px;
}
.promo .meta {
margin-top: 60px;
}
.promo .meta li {
float: none;
display: block;
margin-bottom: 5px;
}
.contact .author-message {
text-align: center;
}
.contact .author-message .profile {
position: static;
margin: 0 auto;
margin-bottom: 30px;
}
.contact .author-message .speech-bubble {
margin-left: 0;
}
.contact .author-message .speech-bubble:after {
display: none;
}
.contact .social-icons a {
width: 36px;
height: 36px;
padding-top: 7px;
margin-right: 2px;
}
.contact .social-icons a .fa:before {
font-size: 18px;
}
}
/* Small devices (tablets, 768px and up) */
/* Medium devices (desktops, 992px and up) */
/* Large devices (large desktops, 1200px and up) */
|
using UnityEngine;
using System.Collections;
public class Intro : MonoBehaviour {
public GameObject martin;
public GameObject mrsStrump;
public GameObject strumpFire;
public Sprite sadMartin, slinkton, police, candles, houses, strumps;
public Camera cam;
// Use this for initialization
void Start () {
strumpFire.GetComponent<SpriteRenderer>().enabled = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("space") || Input.GetMouseButtonDown (0))
Application.LoadLevel ("game");
float time = Time.timeSinceLevelLoad;
if (time > 4.0F && time < 4.5F) {
mrsStrump.transform.position = new Vector3(-13, 0, -5);
}
if (time > 4.5F && time < 4.6F) {
mrsStrump.transform.position = new Vector3(-13, -1, -5);
}
if (time > 17.2F && time < 17.7F) {
martin.transform.position = new Vector3(-11, 0, -5);
}
if (time > 17.7F && time < 17.8F) {
martin.transform.position = new Vector3(-11, -1, -5);
}
if (time > 18.5F && time < 18.6F) {
cam.transform.position = new Vector3(-4, 0, -10);
}
if (time > 18.6F && time < 18.7F) {
martin.GetComponent<Rigidbody2D>().velocity = new Vector2(11, 0);
martin.GetComponent<SpriteRenderer>().sprite = sadMartin;
}
if (time > 20.0F && time < 20.1F) {
martin.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 0);
martin.transform.position = new Vector3(5.8F, -2, -5);
}
if (time > 33.0F && time < 33.1F) {
strumpFire.GetComponent<SpriteRenderer>().enabled = true;
}
if (time > 35.0F && time < 35.1F) {
strumpFire.GetComponent<SpriteRenderer>().sprite = slinkton;
}
if (time > 37.7F && time < 37.8F) {
strumpFire.GetComponent<SpriteRenderer>().sprite = police;
}
if (time > 39.2F && time < 39.3F) {
strumpFire.GetComponent<SpriteRenderer>().sprite = candles;
}
if (time > 41.0F && time < 41.1F) {
strumpFire.GetComponent<SpriteRenderer>().sprite = houses;
}
if (time > 42.5F && time < 42.6F) {
strumpFire.GetComponent<SpriteRenderer>().sprite = strumps;
}
if (time > 43.5F && time < 43.6F) {
strumpFire.GetComponent<SpriteRenderer>().enabled = false;
}
if (time > 51.5F)
Application.LoadLevel ("game");
}
}
|
module Parsers
module Edi
class IncomingTransaction
attr_reader :errors
def self.from_etf(etf, i_cache)
<API key> = new(etf)
<API key> = etf.subscriber_loop.policy_loops.first
find_policy = FindPolicy.new(<API key>)
policy = find_policy.by_subkeys({
:eg_id => <API key>.eg_id,
:hios_plan_id => <API key>.hios_id
})
<API key> = PersonLoopValidator.new
etf.people.each do |person_loop|
<API key>.validate(person_loop, <API key>, policy)
end
<API key> = PolicyLoopValidator.new
<API key>.validate(<API key>, <API key>)
<API key>
end
def initialize(etf)
@etf = etf
@errors = []
end
def valid?
@errors.empty?
end
def import
return unless valid?
is_policy_term = false
is_policy_cancel = false
is_non_payment = false
old_npt_flag = @policy.term_for_np
@etf.people.each do |person_loop|
begin
enrollee = @policy.<API key>(person_loop.member_id)
policy_loop = person_loop.policy_loops.first
enrollee.c_id = person_loop.carrier_member_id
enrollee.cp_id = policy_loop.id
if(!@etf.is_shop? && policy_loop.action == :stop )
enrollee.coverage_status = 'inactive'
enrollee.coverage_end = policy_loop.coverage_end
if enrollee.subscriber?
is_non_payment = person_loop.non_payment_change?
if enrollee.coverage_start == enrollee.coverage_end
is_policy_cancel = true
policy_end_date = enrollee.coverage_end
enrollee.policy.aasm_state = "canceled"
enrollee.policy.term_for_np = is_non_payment
enrollee.policy.save
else
is_policy_term = true
policy_end_date = enrollee.coverage_end
enrollee.policy.aasm_state = "terminated"
enrollee.policy.term_for_np = is_non_payment
enrollee.policy.save
end
end
end
rescue Exception
puts @policy.eg_id
puts person_loop.member_id
raise $!
end
end
save_val = @policy.save
unless <API key>?(@policy, is_policy_cancel, is_policy_term, old_npt_flag == is_non_payment)
Observers::PolicyUpdated.notify(@policy)
end
if is_policy_term
# Broadcast the term
reason_headers = if is_non_payment
{:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"}
else
{}
end
Amqp::EventBroadcaster.with_broadcaster do |eb|
eb.broadcast(
{
:routing_key => "info.events.policy.terminated",
:headers => {
:<API key> => @policy.eg_id,
:<API key> => @policy.policy_end.strftime("%Y%m%d"),
:hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids)
}.merge(reason_headers)
},
"")
end
elsif is_policy_cancel
# Broadcast the cancel
reason_headers = if is_non_payment
{:qualifying_reason => "urn:openhbx:terms:v1:benefit_maintenance#non_payment"}
else
{}
end
Amqp::EventBroadcaster.with_broadcaster do |eb|
eb.broadcast(
{
:routing_key => "info.events.policy.canceled",
:headers => {
:<API key> => @policy.eg_id,
:<API key> => @policy.policy_end.strftime("%Y%m%d"),
:hbx_enrollment_ids => JSON.dump(@policy.hbx_enrollment_ids)
}.merge(reason_headers)
},
"")
end
end
save_val
end
def <API key>?(policy, is_cancel, is_term, npt_changed)
return false if is_cancel
return false if npt_changed
return false unless is_term
(policy.policy_end.day == 31) && (policy.policy_end.month == 12)
end
def policy_found(policy)
@policy = policy
end
def <API key>(details)
@errors << "File is a termination, but no or invalid end date is provided for a member: Member #{details[:member_id]}, Coverage End: #{details[:coverage_end_string]}"
end
def <API key>(details)
@errors << "Coverage end before coverage start: Member #{details[:member_id]}, coverage_start: #{details[:coverage_start]}, coverage_end: #{details[:coverage_end]}"
end
def <API key>(details)
@errors << "Cancel/Term issued on 2014 policy. Member #{details[:member_id]}, end date #{details[:date]}"
end
def <API key>(details)
@errors << "Effectuation date mismatch: member #{details[:member_id]}, enrollee start: #{details[:policy]}, effectuation start: #{details[:effectuation]}"
end
def <API key>(details)
@errors << "Could not determine natural policy expiration date: member #{details[:member_id]}"
end
def <API key>(details)
@errors << "Termination date after natural policy expiration: member
end
def policy_not_found(subkeys)
@errors << "Policy not found. Details: #{subkeys}"
end
def plan_found(plan)
@plan = plan
end
def plan_not_found(hios_id)
@errors << "Plan not found. (hios id: #{hios_id})"
end
def carrier_found(carrier)
@carrier = carrier
end
def carrier_not_found(fein)
@errors << "Carrier not found. (fein: #{fein})"
end
def <API key>(id)
end
def <API key>(person_loop)
policy_loop = person_loop.policy_loops.first
if(!policy_loop.canceled?)
@errors << "Missing Carrier Member ID."
end
end
def no_such_member(id)
@errors << "Member not found in policy:
end
def <API key>(id)
end
def <API key>
@errors << "Missing Carrier Policy ID."
end
def policy_id
@policy ? @policy._id : nil
end
def carrier_id
@carrier ? @carrier._id : nil
end
def employer_id
@employer ? @employer._id : nil
end
end
end
end
|
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta content="IE=edge;chrome=1" http-equiv="X-UA-Compatible" />
<title>dognews</title>
<meta content="width=device-width, initial-scale=1" name="viewport" />
<link rel="alternate" type="application/atom+xml" title="Atom Feed" href="/feed.xml" /><!--[if lt IE 9]><script src="../../js/ie8.js" type="text/javascript"></script><![endif]--><link href="../../css/all.css" media="screen" rel="stylesheet" type="text/css" /><script type="text/javascript">
(function(d,e,j,h,f,c,b){d.<API key>=f;d[f]=d[f]||function(){(d[f].q=d[f].q||[]).push(arguments)},d[f].l=1*new Date();c=e.createElement(j),b=e.<API key>(j)[0];c.async=1;c.src=h;b.parentNode.insertBefore(c,b)})(window,document,"script","
</script>
<link href="/favicon.png" rel="icon" type="image/png" />
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle collapsed" data-target=".navbar-ex1-collapse" data-toggle="collapse" type="button"><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="/">dognews</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li>
<a href="/menu1.html"> Über Uns </a>
</li>
<li>
<a href="/menu2.html"> Newsletter! </a>
</li>
<li class="dropdown">
<a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button">Categories <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="/tags/businessidee.html">businessidee (38)</a>
</li>
<li>
<a href="/tags/deutschland.html">deutschland (596)</a>
</li>
<li>
<a href="/tags/erziehung.html">erziehung (35)</a>
</li>
<li>
<a href="/tags/fotografie.html">fotografie (5)</a>
</li>
<li>
<a href="/tags/freizeit.html">freizeit (83)</a>
</li>
<li>
<a href="/tags/gesetz.html">gesetz (38)</a>
</li>
<li>
<a href="/tags/gesundheit.html">gesundheit (116)</a>
</li>
<li>
<a href="/tags/herdenhunde.html">herdenhunde (10)</a>
</li>
<li>
<a href="/tags/hundesachkunde.html">hundesachkunde (13)</a>
</li>
<li>
<a href="/tags/hundesport.html">hundesport (12)</a>
</li>
<li>
<a href="/tags/kinder.html">kinder (9)</a>
</li>
<li>
<a href="/tags/kurioses.html">kurioses (29)</a>
</li>
<li>
<a href="/tags/oesterreich.html">oesterreich (63)</a>
</li>
<li>
<a href="/tags/rassen.html">rassen (8)</a>
</li>
<li>
<a href="/tags/ratgeber.html">ratgeber (161)</a>
</li>
<li>
<a href="/tags/rettungshunde.html">rettungshunde (3)</a>
</li>
<li>
<a href="/tags/schweiz.html">schweiz (99)</a>
</li>
<li>
<a href="/tags/senioren.html">senioren (10)</a>
</li>
<li>
<a href="/tags/stars.html">stars (11)</a>
</li>
<li>
<a href="/tags/urlaub.html">urlaub (39)</a>
</li>
<li>
<a href="/tags/veranstaltung.html">veranstaltung (1)</a>
</li>
<li>
<a href="/tags/wandern.html">wandern (17)</a>
</li>
<li>
<a href="/tags/wissen.html">wissen (200)</a>
</li>
</ul>
</li>
<li class="dropdown">
<a aria-expanded="false" class="dropdown-toggle" data-toggle="dropdown" href="#" role="button">By Year <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="/2017.html">2017 (8)</a>
</li>
<li>
<a href="/2016.html">2016 (55)</a>
</li>
<li>
<a href="/2015.html">2015 (458)</a>
</li>
<li>
<a href="/2014.html">2014 (273)</a>
</li>
</ul>
</li>
<ul class="list-unstyled list-inline nav navbar-nav navbar-right"></ul>
<li><a href="https://twitter.com/cbdognews">
<i class="fa fa-lg fa-inverse fa-twitter-square"></i></a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-lg-9 col-md-9">
<h1>
Archive for Jan 9 2014
</h1>
<ul>
<h2>
<a href="/2014/01/09/<API key>.html">Gelbes Tuch: 'Fass mich nicht an!'</a>
</h2>
<p>
<small class="label label-default">ratgeber</small>
<small class="label label-default">deutschland</small>
</p>
<hr />
<p>
<span class="glyphicon glyphicon-time"></span> Posted on Jan 9
</p>
<hr />
<div class="row">
<div class="article">
<p><dummy> Wenn Kristin Friedrich mit ihrem Schäferhund Wanko unterwegs ist, trägt er jetzt stolz ein gelbes Halstuch. “Es signalisiert, dass der Hund nicht angefasst und nicht bedrängt werden möchte”, erklärt die Beeskower Hundetrainerin und Tierbetreuerin...</dummy></p>
</div>
</div><a class="btn btn-primary" href="/2014/01/09/<API key>.html">Read More<span class="glyphicon <API key>"></span></a>
<hr />
<h2>
<a href="/2014/01/09/<API key>.html">Ehemaliger UBS-Händler gab Finanzkarriere auf – für dies</a>
</h2>
<p>
<small class="label label-default">schweiz</small>
<small class="label label-default">businessidee</small>
</p>
<hr />
<p>
<span class="glyphicon glyphicon-time"></span> Posted on Jan 9
</p>
<hr />
<div class="row">
<div class="article">
<p><dummy> Ex-UBS-Händler gab Finanzkarriere auf – für ein Hunde-Spa
<a href="http:
</div>
</div><a class="btn btn-primary" href="/2014/01/09/<API key>.html">Read More<span class="glyphicon <API key>"></span></a>
<hr />
</ul>
<hr />
<aside>
<h3>
Recent Articles
</h3>
<ol>
<li>
<a href="/2017/12/05/<API key>.html">Nun ist es raus: Hunde sind klüger als Katzen</a> <span>Dec 5</span>
</li>
<li>
<a href="/2017/07/27/<API key>.html">Die Macht der Gerüche</a> <span>Jul 27</span>
</li>
<li>
<a href="/2017/06/21/<API key>.html">Vorsicht giftig! Diese Lebensmittel sollten Hunde nicht fressen</a> <span>Jun 21</span>
</li>
<li>
<a href="/2017/03/27/<API key>.html">Studie: Schäferhunde können Brustkrebs diagnostizieren</a> <span>Mar 27</span>
</li>
<li>
<a href="/2017/03/27/<API key>.html">Atopische Dermatitis: Was tun, wenn es juckt und kratzt? / Allergien belasten das Wohlbefinden ...</a> <span>Mar 27</span>
</li>
<li>
<a href="/2017/02/27/<API key>.html">Tiermedizin - Epilepsie-Gen entdeckt</a> <span>Feb 27</span>
</li>
<li>
<a href="/2017/01/17/<API key>.html">Auch Haustiere frieren | So kommt Bello durch den Winter</a> <span>Jan 17</span>
</li>
<li>
<a href="/2017/01/17/<API key>.html">Hunde sind bei Minusgraden schnell unterkühlt</a> <span>Jan 17</span>
</li>
<li>
<a href="/2016/12/08/<API key>.html">Venedig: Wo die Gondeln Hunde tragen</a> <span>Dec 8</span>
</li>
<li>
<a href="/2016/11/01/<API key>.html">Hunde heulten halbe Stunde vor Erdbeben</a> <span>Nov 1</span>
</li>
</ol>
</aside>
<hr>
<p class="text-center">
©2018 <a href="/">dognews</a> - <a href="/footer1.html">Disclaimer</a><br /><span class="small">Powered by<a href="https://cloudburo.net/docs/products.html"> Cloudburo Curation Engine</a></span>
</p>
</hr>
</div>
<div class="col-lg-3 col-md-3">
<div class="well">
<h4>
Categories
</h4>
<ul class="list-unstyled">
<li>
<a href="/tags/businessidee.html">businessidee</a> (38)
</li>
<li>
<a href="/tags/deutschland.html">deutschland</a> (596)
</li>
<li>
<a href="/tags/erziehung.html">erziehung</a> (35)
</li>
<li>
<a href="/tags/fotografie.html">fotografie</a> (5)
</li>
<li>
<a href="/tags/freizeit.html">freizeit</a> (83)
</li>
<li>
<a href="/tags/gesetz.html">gesetz</a> (38)
</li>
<li>
<a href="/tags/gesundheit.html">gesundheit</a> (116)
</li>
<li>
<a href="/tags/herdenhunde.html">herdenhunde</a> (10)
</li>
<li>
<a href="/tags/hundesachkunde.html">hundesachkunde</a> (13)
</li>
<li>
<a href="/tags/hundesport.html">hundesport</a> (12)
</li>
<li>
<a href="/tags/kinder.html">kinder</a> (9)
</li>
<li>
<a href="/tags/kurioses.html">kurioses</a> (29)
</li>
<li>
<a href="/tags/oesterreich.html">oesterreich</a> (63)
</li>
<li>
<a href="/tags/rassen.html">rassen</a> (8)
</li>
<li>
<a href="/tags/ratgeber.html">ratgeber</a> (161)
</li>
<li>
<a href="/tags/rettungshunde.html">rettungshunde</a> (3)
</li>
<li>
<a href="/tags/schweiz.html">schweiz</a> (99)
</li>
<li>
<a href="/tags/senioren.html">senioren</a> (10)
</li>
<li>
<a href="/tags/stars.html">stars</a> (11)
</li>
<li>
<a href="/tags/urlaub.html">urlaub</a> (39)
</li>
<li>
<a href="/tags/veranstaltung.html">veranstaltung</a> (1)
</li>
<li>
<a href="/tags/wandern.html">wandern</a> (17)
</li>
<li>
<a href="/tags/wissen.html">wissen</a> (200)
</li>
</ul>
</div>
<div class="well">
<h4>
By year
</h4>
<ol>
<li>
<a href="/2017.html">2017</a> (8)
</li>
<li>
<a href="/2016.html">2016</a> (55)
</li>
<li>
<a href="/2015.html">2015</a> (458)
</li>
<li>
<a href="/2014.html">2014</a> (273)
</li>
</ol>
</div>
</div>
</div>
</div>
<script src="../../js/all.js" type="text/javascript"></script>
</body>
</html>
|
geoserver
======
PostGI server and probably more for the Cologne Open Data community.
The goal is to provide a unified, dynamic geodata access point for
some important geographical datasets.
At some point, there might be a tile server or some other visualization
layer as well. We'll see.
## Contents
`postgis`
Scripts to set up a PostGIS environment and import geo data into the system.
|
// EBBannerView+Categories.h
// demo
#import "EBBannerView.h"
#define WEAK_SELF(weakSelf) __weak __typeof(&*self)weakSelf = self;
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
@interface EBBannerView (EBCategory)
+(UIImage*)defaultIcon;
+(NSString*)defaultTitle;
+(NSString*)defaultDate;
+(NSTimeInterval)<API key>;
+(NSTimeInterval)defaultStayTime;
+(UInt32)defaultSoundID;
@end
@interface NSTimer (EBCategory)
+ (NSTimer *)<API key>:(NSTimeInterval)interval block:(void (^)(NSTimer *timer))block repeats:(BOOL)repeats;
@end
@interface UIImage (<API key>)
+(UIColor *)colorAtPoint:(CGPoint)point;
@end
|
exports.<API key> = function (tuples) {
var valueMap = {};
tuples.forEach(function (tuple) {
valueMap['!' + tuple.value0] = tuple.value1;
});
return valueMap;
};
var templatePattern = /\$\{([^}]+)\}/g;
exports._getTemplateVars = function (str) {
return (str.match(templatePattern) || []).map(function (str) {
return str.substring(2, str.length - 1);
});
};
|
#CodeQuiz
_CodeQuiz is a game made with Kivy framework._
_He is a Quiz consists of four options, Ruby, Python, Javascript and C
_Where he will approach curiosities and specificities of each language._
##Install and Run
1.Clone this repo ``` git clone git@github.com:GuiCarneiro/CodeQuiz.git ```
2.Install Kivy on your computer, take a look at their site [Kivy](http://kivy.org)
3.Then run python main.py
##To Play
1. Use the distribution release
2. Double click over the CodeQuiz.exe
OBS:
_Before playing I recommend you to Update the Quiz_
_Use the menu update_
##Collaborate
1. Fork it
2. Create your branch
git checkout -b name-your-feature ```
3. Commit it
git commit -m 'the differece' ```
4. Push it
git push origin name-your-feature ```
5. Create a Pull Request
This projected is licensed under the terms of the MIT license.
|
/**
* @overview
* API handler action creator
* Takes a key-value -pair representing the event to handle as key and its respective
* handler function as the value.
*
* Event-to-URL mapping is done in {@link ApiEventPaths}.
*
* @since 0.2.0
* @version 0.3.0
*/
import { Seq, Map } from 'immutable';
import { createAction } from 'redux-actions';
import { Internal } from '../records';
import { ApiEventPaths } from '../constants';
import * as apiHandlerFns from '../actions/kcsapi';
/**
* Ensure that the action handlers are mapped into {@link ApiHandler} records.
* @type {Immutable.Iterable<any, any>}
* @since 0.2.0
*/
export const handlers = Seq.Keyed(ApiEventPaths)
.flatMap((path, event) =>
Map.of(event, new Internal.ApiHandler({ path, event, handler: apiHandlerFns[event] })));
/**
* A non-`Seq` version of the @see findEventSeq function.
* @param {string} findPath
* @returns {string}
* @since 0.2.0
* @version 0.3.0
*/
export const findEvent = (findPath) => {
const pathRegex = new RegExp(`^${findPath}$`);
return ApiEventPaths.findKey((path) => pathRegex.test(path));
};
/**
* Create a `Seq` of action handlers that is in a usable form for the Redux application.
* @type {Immutable.Iterable<any, any>}
* @since 0.2.0
*/
export const actionHandlers = Seq.Keyed(handlers)
.flatMap((handlerRecord, event) =>
Map.of(event, createAction(event, handlerRecord.handler)));
|
# Fire Keeper
## Introduction
Fire Keeper is a bot designed for the *Praise the Place* Dark Souls Discord server.
Please do not use this bot in your server without adapation of the code, or else things will not work correctly.
|
title: Prepare paperwork
contexts: office365,microsoft365
source: Microsoft public sites
translation: en
tools:
To kick off the employee onboarding checklist, you need to__ prepare the relevant paperwork and information__prior to the employee's first day\. Start by __recording__ the employee's __basic information__ in the__ form fields__below\.
__Employee First Name__
__Employee Last Name__
__Date of Hire__
Date will be set here
__Employee Contact Details__
__Employee Extra Information__
This part of the process is called__ transactional onboarding__ and focuses on completing all the necessary__forms and documents__ so your new employee can __legally start working__\.
Some of the forms you need to prepare are:
- 1
- W\-4
- 2
- I\-9
- 3
- Insurance forms
- 4
- Direct deposit forms
- 5
- The non\-disclosure agreement
However, there are more forms you might need, __specific to your company__\. Good software to use is [Applicant PRO](http:
\(Source: [applicantpro\.com](http:
|
Use [dox](https:
Outputted HTML is by default based on templates and css from [Twitter Bootstrap](twitter.github.com/bootstrap/) and syntax highlighting is done by [Prism.js](http://prismjs.com/).
Doxx was tested with **JavaScript** as well as generated JavaScript from **CoffeeScript**.
## Demo
* [doxx/docs/compile.js](http://fgribreau.github.com/doxx/docs/compile.js.html)
* [doxx/docs/dir.js](http://fgribreau.github.com/doxx/docs/dir.js.html)
* [doxx/docs/parser.js](http://fgribreau.github.com/doxx/docs/parser.js.html)
## Usage
JavaScript JavaDoc style
javascript
/**
* Create an array of all the right files in the source dir
* @param {String} source path
* @param {Object} options
* @param {Function} callback
* @jsFiddle A jsFiddle embed URL
* @return {Array} an array of string path
*/
function collectFiles(source, options, callback) {
}
CoffeeScript JavaDoc style
coffeescript
*
* Create an array of all the right files in the source dir
* @param {String} source path
* @param {Object} options
* @param {Function} callback
* @jsFiddle A jsFiddle embed URL
* @return {Array} an array of string path
collectFiles = (source, options, callback) ->
## Installation
Install the module with: `npm install doxx -g`
## CLI
$ doxx --help
Usage: doxx [options]
Options:
-h, --help output usage information
-V, --version output the version number
-r, --raw output "raw" comments, leaving the markdown intact
-d, --debug output parsed comments for debugging
-t, --title <string> The title for the page produced
-s, --source <source> The folder which should get parsed
-i, --ignore <directories> Comma seperated list of directories to ignore. Default: test,public,static,views,templates
-T, --target <target> The folder which will contain the results. Default: <process.cwd()>/docs
-e, --target_extension <target_extension> Target files extension. Default: html
--template <jade template> The jade template file to use
Examples:
# parse a whole folder
$ doxx --source lib --target docs
# parse a whole folder and use a specific template
$ doxx --template ./view/myowntpl.jade --source lib --target docs
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt).
## Release History
* *0.0.1* - (dox-foundation) Initial release
* *0.2.0* - (dox-foundation) Readable output
* *0.3.0* - (dox-foundation) Support for folder parsing
* *0.4.0* - (dox-foundation) Improved project navigation, major refactor of folder code
* *0.5.0* - Initial release of doxx
* *0.7.0* - Merge pull requests #16 #17 #19 #20
* *0.7.1* - Merge pull request #25 - Add target_extension option
* *0.7.2* - Upgrade dox to ~0.4.4
* *0.7.4* - Merge pull requests #29 #30
## Donate
[Donate Bitcoins](https://coinbase.com/checkouts/<API key>)
Copyright (c) 2013 Francois-Guillaume Ribreau
MIT License
|
<div class="title">
<img class="icon" src="./res/img/interface.svg" />
<p class="interface">IStudentInfo.IYear</p>
</div>
<p>
Describes school year. Contains year id and register id which are needed in order to use the the API.
</p>
<br />
<p class="section-title">Fields</p>
<p>name: <span class="class">string</span> - school year display name, for ex. 2017/2018</p>
<p>id: <span class="class">number</span> - year id</p>
<p>registerId: <span class="class">number</span> - register id</p>
|
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xParentN(e, n)
{
while (e && n--) e = e.parentNode;
return e;
}
|
package org.edtoktay.dynamic.compiler;
/**
* @author deniz.toktay
*
*/
public interface ExampleInterface {
void addObject(String arg1, String arg2);
Object getObject(String arg1);
}
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Navigator,
ScrollView,
ListView,
} from 'react-native'
import NavigationBar from 'react-native-navbar';
var REQUEST_URL = 'https://calm-garden-29993.herokuapp.com/index/groupsinfo/?';
class GroupDetails extends Component {
constructor(props, context) {
super(props, context);
this.state = {
loggedIn: true,
loaded: false,
rando: "a",
};
this.fetchData();
}
backOnePage () {
this.props.navigator.pop();
}
renderRide (ride) {
return (
<View>
<Text style={styles.title}>{ride.title}</Text>
</View>
);
}
componentDidMount () {
this.fetchData();
}
toQueryString(obj) {
return obj ? Object.keys(obj).sort().map(function (key) {
var val = obj[key];
if (Array.isArray(val)) {
return val.sort().map(function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
}).join('&');
}
return encodeURIComponent(key) + '=' + encodeURIComponent(val);
}).join('&') : '';
}
fetchData() {
console.log(this.props.group_info.pk);
fetch(REQUEST_URL + this.toQueryString({"group": this.props.group_info.pk}))
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
this.setState({
group_info: responseData,
loaded: true,
});
})
.done();
}
render () {
if (!this.state.loaded) {
return (<View>
<Text>Loading!</Text>
</View>);
}
else if (this.state.loggedIn) {
console.log(this.props.group_info.fields);
console.log(this.state);
console.log(this.state.group_info[0]);
const backButton = {
title: "Back",
handler: () => this.backOnePage(),
};
return (
<ScrollView>
<NavigationBar
style={{ backgroundColor: "white", }}
leftButton={backButton}
statusBar={{ tintColor: "white", }}
/>
<Text style={styles.headTitle}>
Group Name: {this.state.group_info.name}
</Text>
<Text style={styles.headerOtherText}>Group Leader: {this.state.group_info.admin}</Text>
<Text style={styles.headerOtherText}>{this.state.group_info.users} people in this group.</Text>
</ScrollView>
);
} else {
this.props.navigator.push({id: "LoginPage", name:"Index"})
}
}
}
var styles = StyleSheet.create({
headerOtherText : {
color: 'black',
fontSize: 15 ,
fontWeight: 'normal',
fontFamily: 'Helvetica Neue',
alignSelf: "center",
},
headTitle: {
color: 'black',
fontSize: 30 ,
fontWeight: 'normal',
fontFamily: 'Helvetica Neue',
alignSelf: "center",
},
header: {
marginTop: 20,
flex: 1,
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
},
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff7f50',
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
backgroundColor: '#0000ff',
paddingBottom: 200,
},
});
module.exports = GroupDetails;
|
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>W28677_text</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;">
<div style="float: left;">
<a href="page9.html">«</a>
</div>
<div style="float: right;">
</div>
</div>
<hr/>
<div style="position: absolute; margin-left: 219px; margin-top: 1017px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 302px; margin-top: 1815px;">
<p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 220px; margin-top: 2090px;">
<p class="styleSans8.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Choke manifold minimum 3” 5k </p>
</div>
<div style="position: absolute; margin-left: 577px; margin-top: 54px;">
<p class="styleSans58.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">11” SK psi BOP stack <br/>High Pressure <br/>. . rotating Fill-up line head <br/>- Drillingcmka _ — — <br/>Annular <br/> <br/>Preventer <br/> <br/>I Variable rams - Blind rams - <br/> m Kill line minimum 2" <br/>Drilling Spool <br/>' Spacer spool <br/>4‘ 5000 psi casing head </p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 55px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 165px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 330px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 495px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 660px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 825px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 1155px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 1320px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 1760px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 1925px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 990px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
<div style="position: absolute; margin-left: 2502px; margin-top: 1485px;">
<p class="styleSans12000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>"></p>
</div>
</body>
</html>
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :<API key>, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :<API key>, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :<API key>, :remember_me
cantango_user
end
|
process.stderr.write('Test');
|
# README
SportzBall is a community driven application used to bring people together for
intramural sports. From football to quidditch we want you to SPORTZ!
To set up repository on your local machine clone and set up database (instructions below)
Rails 5.0.1
Ruby ~> 2.3.0
* Configuration
* Database creation and initialization
`rails db:seed`
* To run tests ask Stephen
* Deployment instructions to come
* API setup to come
Contributers
- FinGrayson
- Jefferson-Faseler
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("<API key>", "wellspring.settings")
from django.core.management import <API key>
<API key>(sys.argv)
|
package org.squirrel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.squirrel.managers.PrisonerControllor;
import org.squirrel.managers.inputManager;
import org.squirrel.objects.Player;
import org.squirrel.ui.Hud;
import org.squirrel.world.World;
public class Game extends JPanel implements ActionListener{
private static final long serialVersionUID = -<API key>;
public static String name = JOptionPane.showInputDialog(null,"What is your name?","Welcome to Prison Survival", JOptionPane.QUESTION_MESSAGE);
Timer gameLoop;
Player player;
PrisonerControllor prict;
Hud hud;
World world1;
public Game(){
setFocusable(true);
gameLoop = new Timer(10, this);
gameLoop.start();
player = new Player(300, 300);
prict = new PrisonerControllor();
hud = new Hud();
world1 = new World();
addKeyListener(new inputManager(player));
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
//Camera
int offsetMaxX = 1600 - 800;
int offsetMaxY = 1200 - 600;
int offsetMinX = 0;
int offsetMinY = 0;
int camX = player.getxPos() - 800 /2;
int camY = player.getyPos() - 600 /2;
//if (camX > offsetMaxX){
// camX = offsetMaxX;
//else if (camX < offsetMinX){
// camX = offsetMinX;
//if (camY > offsetMaxY){
// camY = offsetMaxY;
//else if (camY < offsetMinY){
// camY = offsetMinY;
g2d.translate(-camX, -camY);
// Render everything
world1.draw(g2d);
hud.draw(g2d);
prict.draw(g2d);
player.draw(g2d);
g.translate(camX, camY);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
player.update();
hud.update();
prict.update();
world1.update();
repaint();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
|
/* jqModal base Styling courtesy of;
Brice Burgess <bhb@iceburg.net> */
/* The Window's CSS z-index value is respected (takes priority). If none is supplied,
the Window's z-index value will be set to 3000 by default (via jqModal.js). */
.jqmWrap {
display: none;
position: fixed;
top: 20%;
left: 50%;
margin-left: -175px;
width: 350px;
background: #555;
background: rgba(0,0,0,0.3);
border-radius: 5px;
}
.jqmInner {
background: #fff;
color: #333;
border-radius: 3px;
margin: 6px;
padding: 13px;
font:100% Arial,sans-serif;
}
.jqmInner h1,h2,h3 {
margin: 0;
padding: 0;
}
.jqmInner h1 {
font-size: 20px;
font-weight: 700;
}
.jqmInner h2 {
font-size: 12px;
color: #888;
font-weight: 400;
padding: 6px 0 0;
}
.jqmInner h3 {
font-size: 14px;
font-weight: 700;
margin-top: 10px;
padding-top: 13px;
border-top: 1px solid #ddd;
}
.jqmInner h3 a {
color: #47c;
text-decoration: none;
}
.jqmInner h3 a:hover {
color: #47c;
text-decoration: underline;
}
.jqmOverlay { background-color: #000; }
/* Background iframe styling for IE6. Prevents ActiveX bleed-through (<select> form elements, etc.) */
* iframe.jqm {position:absolute;top:0;left:0;z-index:-1;
width: expression(this.parentNode.offsetWidth+'px');
height: expression(this.parentNode.offsetHeight+'px');
}
/* Fixed posistioning emulation for IE6
Star selector used to hide definition from browsers other than IE6
For valid CSS, use a conditional include instead */
* html .jqmWindow {
position: absolute;
top: expression((document.documentElement.scrollTop || document.body.scrollTop) + Math.round(17 * (document.documentElement.offsetHeight || document.body.clientHeight) / 100) + 'px');
}
|
(function () {
'use strict';
angular
.module('app')
.service('<API key>', <API key>);
function <API key>($http, $log, TokenService, UserService, $rootScope) {
this.uploadImage = uploadImage;
/
function uploadImage(formdata, callback) {
let userToken = TokenService.get();
let request = {
method: 'POST',
url: '/api/user/avatar',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Autorization': userToken
},
data: formdata
};
let goodResponse = function successCallback(response) {
let res = response.data;
if (res.success) {
let currentUser = UserService.get();
currentUser.avatarUrl = res.data.avatarUrl;
UserService.save(currentUser);
}
if (callback && typeof callback === 'function') {
callback(res);
}
};
let badResponse = function errorCallback(response) {
$log.debug('Bad, some problems ', response);
if (callback && typeof callback === 'function') {
callback(response);
}
};
$http(request).then(goodResponse, badResponse);
}
}
})();
|
<?php
include 'vendor/autoload.php';
ini_set('error_reporting', E_ALL);
ini_set('display_errors', '1');
ini_set('<API key>', '1');
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>simple-io: 27 s </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.9.0 / simple-io - 1.3.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
simple-io
<small>
1.3.0
<span class="label label-success">27 s </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-01-04 03:17:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-01-04 03:17:13 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.14 <API key> of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 1 Virtual package relying on perl
coq 8.9.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.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Li-yao Xia <lysxia@gmail.com>"
authors: "Li-yao Xia"
homepage: "https://github.com/Lysxia/coq-simple-io"
bug-reports: "https://github.com/Lysxia/coq-simple-io/issues"
license: "MIT"
dev-repo: "git+https://github.com/Lysxia/coq-simple-io.git"
build: [make "build"]
run-test: [make "test"]
install: [make "install"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.13~"}
"coq-ext-lib"
"ocamlbuild" {with-test}
]
tags: [
"date:2020-03-08"
"logpath:SimpleIO"
"keyword:extraction"
"keyword:effects"
]
synopsis: "IO monad for Coq"
description: """
This library provides tools to implement IO programs directly in Coq, in a
similar style to Haskell. Facilities for formal verification are not included.
IO is defined as a parameter with a purely functional interface in Coq,
to be extracted to OCaml. Some wrappers for the basic types and functions in
the OCaml Pervasives module are provided. Users are free to define their own
APIs on top of this IO type."""
url {
src: "https://github.com/Lysxia/coq-simple-io/archive/1.3.0.tar.gz"
checksum: "sha512=bcf7746e7877c4672e509e8c80db28b93cffbb064e114cf4df4465d9be3d55274c84a7406b38eaf510deda8a2574e42f3b40c8f716841bd92557e7b59d86e7cb"
}
</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-simple-io.1.3.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</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>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-simple-io.1.3.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>1 m 13 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-simple-io.1.3.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>27 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 478 K</p>
<ul>
<li>50 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.vo</code></li>
<li>43 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.vo</code></li>
<li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.vo</code></li>
<li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.vo</code></li>
<li>28 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.vo</code></li>
<li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.vo</code></li>
<li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.vo</code></li>
<li>26 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.vo</code></li>
<li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.vo</code></li>
<li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.vo</code></li>
<li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.vo</code></li>
<li>25 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.vo</code></li>
<li>16 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.glob</code></li>
<li>15 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.glob</code></li>
<li>14 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.vo</code></li>
<li>13 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unix.v</code></li>
<li>11 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Stdlib.v</code></li>
<li>10 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.glob</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.glob</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Monad.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.vo</code></li>
<li>4 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.glob</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.glob</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_String.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_RawChar.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.glob</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Unsafe.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.glob</code></li>
<li>2 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Bytes.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Float.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_UnsafeNat.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Exceptions.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Random.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_Sys.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/SimpleIO.v</code></li>
<li>1 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/SimpleIO/IO_StdlibAxioms.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-simple-io.1.3.0</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:
</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>
|
class Sprite(object):
def __init__(self, xPos, yPos):
self.x = xPos
self.y = yPos
self.th = 32
self.tw = 32
def checkCollision(self, otherSprite):
if (self.x < otherSprite.x + otherSprite.tw and otherSprite.x < self.x + self.tw
and self.y < otherSprite.y + otherSprite.th and otherSprite.y < self.y + self.th):
return True
else:
return False
class Actor(Sprite):
def __init__(self, xPos, yPos):
super(Actor, self).__init__(xPos, yPos)
self.speed = 5
self.dy = 0
self.d = 3
self.dir = "right"
# self.newdir = "right"
self.state = "standing"
self.walkR = []
self.walkL = []
def loadPics(self):
self.standing = loadImage("gripe_stand.png")
self.falling = loadImage("grfalling.png")
for i in range(8):
imageName = "gr" + str(i) + ".png"
self.walkR.append(loadImage(imageName))
for i in range(8):
imageName = "gl" + str(i) + ".png"
self.walkL.append(loadImage(imageName))
def checkWall(self, wall):
if wall.state == "hidden":
if (self.x >= wall.x - self.d and
(self.x + 32 <= wall.x + 32 + self.d)):
return False
def move(self):
if self.dir == "right":
if self.state == "walking":
self.im = self.walkR[frameCount % 8]
self.dx = self.speed
elif self.state == "standing":
self.im = self.standing
self.dx = 0
elif self.state == "falling":
self.im = self.falling
self.dx = 0
self.dy = 5
elif self.dir == "left":
if self.state == "walking":
self.im = self.walkL[frameCount % 8]
self.dx = -self.speed
elif self.state == "standing":
self.im = self.standing
self.dx = 0
elif self.state == "falling":
self.im = self.falling
self.dx = 0
self.dy = 5
else:
self.dx = 0
self.x += self.dx
self.y += self.dy
if self.x <= 0:
self.x = 0
if self.x >= 640 - self.tw:
self.x = 640 -self.tw
def display(self):
image(self.im, self.x, self.y)
class Block(Sprite):
def __init__(self, xPos, yPos):
super(Block, self).__init__(xPos, yPos)
self.state = "visible"
def loadPics(self):
self.im = loadImage("block.png")
def display(self):
if self.state == "visible":
image(self.im, self.x, self.y)
|
<?php
namespace Carrot\Docs;
use Exception,
<API key>,
DirectoryIterator;
class Storage
{
/**
* @var string The directory that contains the document files,
* without trailing directory separator.
*/
protected $rootDirectory;
/**
* Constructor.
*
* If no path was given, the root directory will default to:
*
* <code>
* __DIR__ . DIRECTORY_SEPARATOR . 'Files'
* </code>
*
* The directory contains documentation files in HTML format and
* can contain as many folders as you need. You can provide
* 'section.html' file on each directory to be loaded when that
* section is requested.
*
* @param string $rootDirectory The directory that contains the
* document files.
*
*/
public function __construct($rootDirectory = NULL)
{
if ($rootDirectory == NULL)
{
$rootDirectory = __DIR__ . DIRECTORY_SEPARATOR . 'Files';
}
$this->setRootDirectory($rootDirectory);
}
/**
* Set the directory that contains the document files.
*
* @throws <API key> If the root directory given
* is not a valid path or it's not a directory.
* @param string $rootDirectory The directory that contains the
* document files.
*
*/
protected function setRootDirectory($rootDirectory)
{
$<API key> = realpath($rootDirectory);
if ($<API key> == FALSE)
{
throw new <API key>("Storage error in instantiation. The given path '{$rootDirectory}' does not exist.");
}
if (is_dir($<API key>) == FALSE)
{
throw new <API key>("Storage error in instantiation. The given path '{$rootDirectory}' is not directory.");
}
$this->rootDirectory = $<API key>;
}
/**
* Get an instance of page from the given hierarchical path.
*
* The path array contains the hierarchical path to the
* documentation. The array contains item IDs. Example:
*
* <code>
* $path = array(
* '1-introduction',
* '<API key>',
* '<API key>'
* );
* </code>
*
* @param array $pagePathArray The hierarchical path to the
* documentation page to retrieve.
* @return Page|FALSE The documentation page, or FALSE if failed.
*
*/
public function getPage(array $pagePathArray)
{
if (empty($pagePathArray))
{
return $this->getIndexPage();
}
$pageInfo = $this->getPageInfo($pagePathArray);
if (!is_array($pageInfo))
{
return FALSE;
}
return new Page(
$pageInfo['title'],
$pageInfo['content'],
$pageInfo['parentSections'],
$pageInfo['navigation']
);
}
/**
* Get the page containing the index to be returned.
*
* Will try to load the contents of the 'section.html' file in
* the route, if it fails, will simply return an empty body with
* the root navigation.
*
* @return Page
*
*/
public function getIndexPage()
{
$parentSections = array();
$navigation = $this-><API key>($this->rootDirectory, array());
$title = '';
$content = $this-><API key>($this->rootDirectory);
return new Page(
$title,
$content,
$parentSections,
$navigation
);
}
/**
* Get information about the page from the given hierarchical
* path.
*
* Assumes the array is not empty. The structure of the array
* returned is as follows:
*
* <code>
* $pageInfo = array(
* 'parentSections' => $parentSections,
* 'navigation' => $navigation,
* 'title' => $title,
* 'content' => $content
* );
* </code>
*
* The array $parentSections contains the page's parent sections.
* Each section is represented by a {@see NavigationItem}
* instance:
*
* <code>
* $parentSections = array(
* 0 => $sectionA,
* 1 => $sectionB,
* 2 => $sectionC
* ...
* );
* </code>
*
* The array $navigation contains the list of accessible items
* for the current open section, be it a page or another section,
* but with the item ID as the indexes:
*
* <code>
* $navigation = array(
* '1-introduction' => $navItemA,
* '2-autoloading' => $navItemB,
* '<API key>' => $navItemC,
* ...
* );
* </code>
*
* @param array $pagePathArray The hierarchical path to the
* documentation page to retrieve.
*
*/
protected function getPageInfo(array $pagePathArray)
{
$parentSections = array();
$navigation = array();
$title = '';
$content = '';
$directory = $this->rootDirectory;
$segmentsTraversed = array();
$highestLevel = count($pagePathArray) - 1;
foreach ($pagePathArray as $level => $itemID)
{
$isHighestLevel = ($level == $highestLevel);
$availableItems = $this-><API key>(
$directory,
$segmentsTraversed
);
if (!array_key_exists($itemID, $availableItems))
{
return FALSE;
}
$navItem = $availableItems[$itemID];
if ($isHighestLevel)
{
if ($navItem->isSection())
{
$parentSections[] = $navItem;
$segmentsTraversed[] = $itemID;
$directory = $navItem->getRealPath();
$navigation = $this-><API key>(
$directory,
$segmentsTraversed
);
$content = $this-><API key>($directory);
}
else
{
$navigation = $availableItems;
$navigation[$itemID]->markAsCurrent();
$content = $this->getFileContent($navItem->getRealPath());
}
return array(
'parentSections' => $parentSections,
'navigation' => $navigation,
'title' => $navItem->getTitle(),
'content' => $content
);
}
$parentSections[] = $navItem;
$segmentsTraversed[] = $itemID;
$directory = $navItem->getRealPath();
}
}
/**
* Get the list of navigational items from the given directory.
*
* Iterates through the given directory and creates instances of
* {@see NavigationItem} from its contents. Uses the given root
* path segments to construct routing argument arrays of each
* NavigationItem instance.
*
* The root path segments array structure:
*
* <code>
* $rootPathSegments = array(
* '1-Introduction',
* '<API key>'
* );
* </code>
*
* Returns an array containing instances of NavigationItem:
*
* <code>
* $navigationItems = array(
* $navItemA,
* $navItemB,
* $navItemC,
* ...
* );
* </code>
*
* @param string $directory Absolute path to the directory to
* search the files from.
* @param array $rootPathSegments The root path segments leading
* to the given directory, to be used in constructing
* routing arguments on each NavigationItem instances.
* @return array Array containing instances of
* {@see NavigationItem}. Returns an empty array if it
* fails to retrieve data from the directory.
*
*/
protected function <API key>($directory, array $rootPathSegments)
{
$items = array();
try
{
$iterator = new DirectoryIterator($directory);
}
catch (Exception $exception)
{
return $items;
}
foreach ($iterator as $key => $content)
{
$navItem = NULL;
if ($content->isFile())
{
$fileName = $content->getFilename();
$realPath = $content->getPathname();
$navItem = $this-><API key>(
$fileName,
$realPath,
$rootPathSegments
);
}
if ($content->isDir() AND $content->isDot() == FALSE)
{
$fileName = $content->getFilename();
$realPath = $content->getPathname();
$navItem = $this-><API key>(
$fileName,
$realPath,
$rootPathSegments
);
}
if ($navItem instanceof NavigationItem)
{
$items[$navItem->getItemID()] = $navItem;
}
}
return $items;
}
/**
* Get a {@see NavigationItem} instance from the given file name
* and file path.
*
* Only accepts '.html' files with the following pattern as the
* file name:
*
* <code>
* 1. File Name.html
* A. File Name.html
* a. File Name.html
* </code>
*
* @see <API key>()
* @param string $fileName The name of the file.
* @param string $realPath The real path to the file.
* @param array $rootPathSegments The root path segments leading
* to the given file, to be used in constructing routing
* arguments array.
* @return NavigationItem
*
*/
protected function <API key>($fileName, $realPath, array $rootPathSegments)
{
$fileNamePattern = '/^([A-Za-z0-9]+\\. (.+))\.html$/uD';
$<API key> = '/[\\. ]+/u';
if (preg_match($fileNamePattern, $fileName, $matches))
{
$title = $matches[2];
$itemID = preg_replace($<API key>, '-', $matches[1]);
$routingArgs = $rootPathSegments;
$routingArgs[] = $itemID;
return new NavigationItem(
$title,
'doc',
$routingArgs,
$realPath
);
}
}
/**
* Get a {@see NavigationItem} instance from the given directory.
*
* All directory names are accepted.
*
* @see <API key>()
* @param string $fileName The name of the file.
* @param string $realPath The real path to the file.
* @param array $rootPathSegments The root path segments leading
* to the given file, to be used in constructing routing
* arguments array.
* @return NavigationItem
*
*/
protected function <API key>($directoryName, $realPath, array $rootPathSegments)
{
$directoryPattern = '/^([A-Za-z0-9]+\\. (.+))$/uD';
$<API key> = '/[\\. ]+/u';
if (preg_match($directoryPattern, $directoryName, $matches))
{
$title = $matches[2];
$itemID = preg_replace($<API key>, '-', $matches[1]);
$routingArgs = $rootPathSegments;
$routingArgs[] = $itemID;
return new NavigationItem(
$title,
'section',
$routingArgs,
$realPath
);
}
}
/**
* Get the content for section index.
*
* Will try to get an 'section.html' file on the given directory.
* If none found, an empty string will be returned instead.
*
* @param string $directory The physical counterpart of the
* section whose index content we wanted to get, without
* trailing directory separator.
* @return string
*
*/
protected function <API key>($directory)
{
$filePath = $directory . DIRECTORY_SEPARATOR . 'section.html';
return $this->getFilecontent($filePath);
}
/**
* Get the content from the give file.
*
* If the file doesn't exist, will return an empty string
* instead.
*
* @param string $filePath Path to the file to get.
*
*/
protected function getFileContent($filePath)
{
if (!file_exists($filePath))
{
return '';
}
return file_get_contents($filePath);
}
}
|
<div class="panel panel-primary">
<div ng-show="error" class="alert alert-danger">{{ error }}</div>
<div class="panel-heading">
<p class="panel-title">Neuer Gig</p>
</div>
<div class="panel-body">
<form name="addGig" class="form-horizontal" ng-submit="insertGig(gig)">
<fieldset>
<div class="form-group">
<label for="date" class="control-label col-lg-2">Datum:</label>
<div class="col-lg-4">
<input type="date" class="form-control" name="date" ng-model="gig.date" placeholder="yyyy-MM-dd" min="2008-01-01" max="2100-12-31" required />
</div>
</div>
<div class="form-group">
<label for="title" class="control-label col-lg-2">Titel:</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="title" ng-model="gig.title" required />
</div>
</div>
<div class="form-group">
<label for="loc" class="control-label col-lg-2">Location:</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="loc" ng-model="gig.loc" />
</div>
</div>
<div class="form-group">
<label for="status" class="control-label col-lg-2">Status:</label>
<div class="col-lg-4">
<select class="form-control" id="status" ng-model="status">
<option>Angefragt</option>
<option>Gebucht</option>
</select>
</div>
</div>
<div class="form-group">
<label for="contact" class="control-label col-lg-2">Kontakt:</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="contact" ng-model="gig.contact" />
</div>
</div>
<div class="form-group">
<label for="notes" class="control-label col-lg-2">Info:</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="notes" ng-model="gig.notes" />
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default" ng-click="back()">Abbrechen</button>
<button type="submit" class="btn btn-primary">Speichern</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
|
class CreateTeams < ActiveRecord::Migration
def self.up
create_table :teams do |t|
t.string :name
t.string :abbreviation
t.string :hometown
t.timestamps
end
end
def self.down
drop_table :teams
end
end
|
#ifndef X264_VISUALIZE_H
#define X264_VISUALIZE_H
#include "common.h"
void x264_visualize_init( x264_t *h );
void x264_visualize_mb( x264_t *h );
void x264_visualize_show( x264_t *h );
void <API key>( x264_t *h );
#endif
|
angular.module('tips.tips').controller('TipsController', ['$scope', '$routeParams', '$location', 'Global', 'Tips', function ($scope, $routeParams, $location, Global, Tips) {
$scope.global = Global;
$scope.createTip = function () {
var tips = new Tips({
text: this.text,
likes: this.likes,
category: this.category
});
tips.$save(function (response) {
$location.path("/");
});
this.title = "";
};
$scope.showTip = function () {
Tips.query(function (tips) {
$scope.tips = tips;
tips.linkEdit = 'tips/edit/';
// show tips size
function Settings (minLikes, maxLikes) {
var that = this;
that.size = {
min: 26,
max: 300
};
that.maxLikes = maxLikes;
that.minLikes = tips[0].likes;
that.valueOfdivision = (function(){
return (that.size.max - that.size.min)/that.maxLikes
})()
}
function startIsotope(){
var el = $('#isotope-container');
el.isotope({
itemSelector: '.isotope-element',
layoutMode: 'fitRows',
sortBy: 'number',
sortAscending: true,
});
return el;
}
var maxLikes = 0;
var minLikes = 0;
for (var i = 0; i < tips.length; i++) {
if(maxLikes <= tips[i].likes)maxLikes = tips[i].likes;
if(minLikes >= tips[i].likes)minLikes = tips[i].likes;
};
tips.settingsView = new Settings(minLikes, maxLikes);
$scope.$watch('tips', function () {
$scope.$evalAsync(function () {
var isotope = startIsotope();
});
})
});
};
$scope.updateTip = function (tip) {
var tip = new Tips(tip);
tip.$update(tip, function(){
console.log("update updateTip: ", tip._id);
}, function(){
console.warn("error updateTip:", tip._id);
});
};
$scope.getTip = function () {
Tips.query(function (tip) {
$scope.tip = tip;
console.log(tip);
});
};
$scope.editTip = function(tip){
console.log("edit tip");
};
}])
|
# Get Single Promotion
This gets an XML document with the specific promotion by the ID.
## Single Promotion Options
[MadMimi's Promotion Documentation](https://madmimi.com/developer/api/promotions) should give you an idea
of what you need to send to the API. This options object makes some of the methods easier.
Method Reference
`Single::setPromotionId($promotionId)` - Sets the promotion ID to retrieve
## Exceptions
The following exceptions may be thrown throughout the duration of a options object.
- `MadMimi\Exception\<API key>` During options object creation, a value in the array of the constructor argument that's key was not defined as a protected property of this options class
|
# Laravel Favorite (Laravel 5, 6, 7, 8 Package)
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Packagist Downloads][ico-downloads]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-travis]][link-travis]
**Allows Laravel Eloquent models to implement a 'favorite' or 'remember' or 'follow' feature.**
## Index
- [Installation](#installation)
- [Models](#models)
- [Usage](#usage)
- [Testing](#testing)
- [Change log](#change-log)
- [Contributions](#contributions)
- [Pull Requests](#pull-requests)
- [Security](#security)
- [Credits](#credits)
- [License](
## Installation
1) Install the package via Composer
bash
$ composer require christiankuri/laravel-favorite
2) In Laravel >=5.5 this package will automatically get registered. For older versions, update your `config/app.php` by adding an entry for the service provider.
php
'providers' => [
ChristianKuri\LaravelFavorite\<API key>::class,
];
3) Publish the database from the command line:
shell
php artisan vendor:publish --provider="ChristianKuri\LaravelFavorite\<API key>"
4) Migrate the database from the command line:
shell
php artisan migrate
## Models
Your User model should import the `Traits/Favoriteability.php` trait and use it, that trait allows the user to favorite the models.
(see an example below):
php
use ChristianKuri\LaravelFavorite\Traits\Favoriteability;
class User extends Authenticatable
{
use Favoriteability;
}
Your models should import the `Traits/Favoriteable.php` trait and use it, that trait have the methods that you'll use to allow the model be favoriteable.
In all the examples I will use the Post model as the model that is 'Favoriteable', thats for example propuses only.
(see an example below):
php
use ChristianKuri\LaravelFavorite\Traits\Favoriteable;
class Post extends Model
{
use Favoriteable;
}
That's it ... your model is now **"favoriteable"**!
Now the User can favorite models that have the favoriteable trait.
## Usage
The models can be favorited with and without an authenticated user
(see examples below):
Add to favorites and remove from favorites:
If no param is passed in the favorite method, then the model will asume the auth user.
php
$post = Post::find(1);
$post->addFavorite(); // auth user added to favorites this post
$post->removeFavorite(); // auth user removed from favorites this post
$post->toggleFavorite(); // auth user toggles the favorite status from this post
If a param is passed in the favorite method, then the model will asume the user with that id.
php
$post = Post::find(1);
$post->addFavorite(5); // user with that id added to favorites this post
$post->removeFavorite(5); // user with that id removed from favorites this post
$post->toggleFavorite(5); // user with that id toggles the favorite status from this post
The user model can also add to favorites and remove from favrites:
php
$user = User::first();
$post = Post::first();
$user->addFavorite($post); // The user added to favorites this post
$user->removeFavorite($post); // The user removed from favorites this post
$user->toggleFavorite($post); // The user toggles the favorite status from this post
Return the favorite objects for the user:
A user can return the objects he marked as favorite.
You just need to pass the **class** in the `favorite()` method in the `User` model.
php
$user = Auth::user();
$user->favorite(Post::class); // returns a collection with the Posts the User marked as favorite
Return the favorites count from an object:
You can return the favorites count from an object, you just need to return the `favoritesCount` attribute from the model
php
$post = Post::find(1);
$post->favoritesCount; // returns the number of users that have marked as favorite this object.
Return the users who marked this object as favorite
You can return the users who marked this object, you just need to call the `favoritedBy()` method in the object
php
$post = Post::find(1);
$post->favoritedBy(); // returns a collection with the Users that marked the post as favorite.
Check if the user already favorited an object
You can check if the Auth user have already favorited an object, you just need to call the `isFavorited()` method in the object
php
$post = Post::find(1);
$post->isFavorited(); // returns a boolean with true or false.
## Testing
The package have integrated testing, so everytime you make a pull request your code will be tested.
## Change log
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributions
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/ChristianKuri/laravel-favorite).
Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/<API key>.md)** - Check the code style with ``$ composer check-style`` and fix it with ``$ composer fix-style``.
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/<API key>#<API key>) before submitting.
## Security
Please report any issue you find in the issues page.
Pull requests are welcome.
## Credits
- [Christian Kuri][link-author]
- [All Contributors][link-contributors]
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
[ico-version]: https://img.shields.io/packagist/v/ChristianKuri/laravel-favorite.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/<API key>.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/ChristianKuri/laravel-favorite/master.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/ChristianKuri/laravel-favorite.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/ChristianKuri/laravel-favorite.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/ChristianKuri/laravel-favorite.svg?style=flat-square
[link-packagist]: https://packagist.org/packages/ChristianKuri/laravel-favorite
[link-travis]: https://travis-ci.org/ChristianKuri/laravel-favorite
[link-scrutinizer]: https://scrutinizer-ci.com/g/ChristianKuri/laravel-favorite/code-structure
[link-code-quality]: https://scrutinizer-ci.com/g/ChristianKuri/laravel-favorite
[link-downloads]: https://packagist.org/packages/ChristianKuri/laravel-favorite
[link-author]: https://github.com/ChristianKuri
[link-contributors]: ../../contributors
|
package com.xeiam.xchange.cryptotrade.dto;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.<API key>;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.<API key>;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.xeiam.xchange.cryptotrade.dto.<API key>.<API key>;
@JsonDeserialize(using = <API key>.class)
public enum <API key> {
Buy, Sell;
static class <API key> extends JsonDeserializer<<API key>> {
@Override
public <API key> deserialize(final JsonParser jsonParser, final <API key> ctxt) throws IOException, <API key> {
final ObjectCodec oc = jsonParser.getCodec();
final JsonNode node = oc.readTree(jsonParser);
final String orderType = node.asText();
return <API key>.valueOf(orderType);
}
}
}
|
module Mailplug
class Plugin::Example < Mailplug::Middleware
# Message Envelope Methods
def return_path
end
def recipients
end
def message # returns Mail::Message
end
# Hash of state and inter-stack data memo[classname][key]=value
def memo
end
# SMTP State Changes
def open(remote_ip)
end
def helo(server_name)
end
def mail_from(email)
end
def rcpt_to(email)
end
def data
end
def data_line(line)
end
def data_stop
end
def save # false(i don't queue), true (i queued), error msg
end
def quit
end
def close
end
def header(name, value)
end
def abort(code, msg) # Stop it with reason
end
def continue # don't stop
end
def log(msg)
end
def status(number, message, close, waitseconds=0)
end
def service_ready # 220
end
end
end
|
import apiConfig from './MovieDBConfig';
import TmdbApi from 'moviedb-api';
var api = new TmdbApi({
consume: false,
apiKey: apiConfig.apiKey
});
const makeAndList = (list) => {
return list.map(item => item.value).join();
};
export const getGenres = (input='', callback) => {
api.request('/genre/movie/list', 'GET')
.then(res => {
return res.genres.map(item => {
return {label: item.name, value: item.id};
})
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const getKeywords = (input='', callback) => {
api.request('/search/keyword', 'GET', {query: input})
.then(res => {
return res.results.map(item => {
return {label: item.name, value: item.id};
});
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const getActors = (input='', callback) => {
api.request('/search/person', 'GET', {query: input})
.then(res => {
return res.results.map(item => {
return {label: item.name, value: item.id};
});
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const discover = (genres=null, keywords=null, actors, minYear, maxYear, page=1) => {
let g = genres ? makeAndList(genres) : null;
let k = keywords ? makeAndList(keywords) : null;
let a = actors ? makeAndList(actors) : null;
return api.request('/discover/movie', 'GET', {
with_genres: g,
with_keywords: k,
with_cast: a,
"release_date.gte": minYear,
"release_date.lte": maxYear,
page
})
.then(res => res)
};
export const getVideos = (id, language='en') => {
return api.request(`/movie/${id}/videos`, 'GET', {language})
};
export const getMovieKeywords = (id, language='en') => {
return api.request(`/movie/${id}/keywords`, 'GET', {language})
};
export const discoverWithVideo = (genres=null, keywords=null, actors, minYear, maxYear) => {
return discover(genres, keywords, actors, minYear, maxYear)
.then(res => {
return Promise.all(
res.results.map(item => getVideos(item.id)
.then(videos => videos.results[0])
)
).then(list => {
return {
res,
results: res.results.map((item, index) => {
item.youtube = list[index];
return item;
})
}
})
})
};
export const getDetails = (id, language='en') => {
return api.request(`/movie/${id}`, 'GET', {language, append_to_response: "keywords,videos"})
};
|
const excludedTables = ["blacklist", "musicCache", "timedEvents"];
const statPoster = require("../../modules/statPoster.js");
module.exports = async guild => {
let tables = await r.tableList().run();
for(let table of tables) {
let indexes = await r.table(table).indexList().run();
if(~indexes.indexOf("guildID")) r.table(table).getAll(guild.id, { index: "guildID" }).delete().run();
else r.table(table).filter({ guildID: guild.id }).delete().run();
}
if(bot.config.bot.serverChannel) {
let owner = bot.users.get(guild.ownerID);
let botCount = guild.members.filter(member => member.bot).length;
let botPercent = ((botCount / guild.memberCount) * 100).toFixed(2);
let userCount = guild.memberCount - botCount;
let userPercent = ((userCount / guild.memberCount) * 100).toFixed(2);
let content = " LEFT GUILD \n";
content += `Guild: ${guild.name} (${guild.id})\n`;
content += `Owner: ${owner.username}#${owner.discriminator} (${owner.id})\n`;
content += `Members: ${guild.memberCount} **|** `;
content += `Users: ${userCount} (${userPercent}%) **|** `;
content += `Bots: ${botCount} (${botPercent}%)`;
try {
await bot.createMessage(bot.config.bot.serverChannel, content);
} catch(err) {
console.error(`Failed to send message to server log: ${err.message}`);
}
}
statPoster();
};
|
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using IDI.Core.Common.Extensions;
namespace IDI.Core.Localization
{
public abstract class Package
{
public List<PackageItem> Items { get; private set; } = new List<PackageItem>();
public Package(string assemblyName, string packageName)
{
var assembly = Assembly.Load(new AssemblyName(assemblyName));
if (assembly == null)
return;
using (Stream stream = assembly.<API key>(packageName))
{
if (stream == null)
return;
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
this.Items = json.To<List<PackageItem>>();
}
}
}
}
}
|
// UIView+BluredSnapshot.h
// <API key>
#import <UIKit/UIKit.h>
@interface UIView (BluredSnapshot)
-(UIImage *)blurredSnapshot;
@end
|
-- collate4.test
-- execsql {
-- CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT);
-- INSERT INTO collate4t3 VALUES( 'a', 'a' );
-- INSERT INTO collate4t3 VALUES( 'b', 'b' );
-- INSERT INTO collate4t3 VALUES( NULL, NULL );
-- INSERT INTO collate4t3 VALUES( 'B', 'B' );
-- INSERT INTO collate4t3 VALUES( 'A', 'A' );
-- CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE);
CREATE TABLE collate4t3(a COLLATE NOCASE, b COLLATE TEXT);
INSERT INTO collate4t3 VALUES( 'a', 'a' );
INSERT INTO collate4t3 VALUES( 'b', 'b' );
INSERT INTO collate4t3 VALUES( NULL, NULL );
INSERT INTO collate4t3 VALUES( 'B', 'B' );
INSERT INTO collate4t3 VALUES( 'A', 'A' );
CREATE INDEX collate4i2 ON collate4t3(a COLLATE TEXT, b COLLATE NOCASE);
|
import { computed, get } from '@ember/object';
import { getOwner } from '@ember/application';
import { deprecate } from '@ember/debug';
export function ability(abilityName, resourceName) {
deprecate(
'Using ability() computed property is deprecated. Use getters and Can service directly.',
false,
{
for: 'ember-can',
since: {
enabled: '4.0.0',
},
id: 'ember-can.<API key>',
until: '5.0.0',
}
);
resourceName = resourceName || abilityName;
return computed(resourceName, function () {
let canService = getOwner(this).lookup('service:abilities');
return canService.abilityFor(abilityName, get(this, resourceName));
}).readOnly();
}
|
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20140216162246) do
create_table "<API key>", force: true do |t|
t.string "namespace"
t.text "body"
t.string "resource_id", null: false
t.string "resource_type", null: false
t.integer "author_id"
t.string "author_type"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "<API key>", ["author_type", "author_id"], name: "<API key><API key>
add_index "<API key>", ["namespace"], name: "<API key>"
add_index "<API key>", ["resource_type", "resource_id"], name: "<API key>"
create_table "admin_users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "<API key>"
t.datetime "<API key>"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "admin_users", ["email"], name: "<API key>", unique: true
add_index "admin_users", ["<API key>"], name: "<API key>", unique: true
create_table "deposit_addresses", force: true do |t|
t.integer "sponsor_id"
t.integer "project_id"
t.string "bitcoin_address"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "month_donations", limit: 8
t.integer "year_donations", limit: 8
end
add_index "deposit_addresses", ["project_id"], name: "<API key>"
add_index "deposit_addresses", ["sponsor_id"], name: "<API key>"
create_table "deposits", force: true do |t|
t.integer "deposit_address_id"
t.integer "amount", limit: 8
t.string "input_tx"
t.integer "confirmations"
t.string "output_tx"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "deposits", ["deposit_address_id"], name: "<API key>"
create_table "projects", force: true do |t|
t.string "name"
t.text "about"
t.string "url"
t.string "bitcoin_address"
t.datetime "created_at"
t.datetime "updated_at"
t.string "donation_page_url"
t.integer "month_donations", limit: 8
t.datetime "moderated_at"
t.integer "year_donations", limit: 8
end
create_table "sponsors", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "<API key>"
t.datetime "<API key>"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "<API key>"
t.string "unconfirmed_email"
t.datetime "created_at"
t.datetime "updated_at"
t.string "avatar"
t.string "name"
t.string "url"
t.string "location"
t.boolean "private_donations", default: false
t.integer "month_donations", limit: 8
t.integer "year_donations", limit: 8
end
add_index "sponsors", ["confirmation_token"], name: "<API key>", unique: true
add_index "sponsors", ["email"], name: "<API key>", unique: true
add_index "sponsors", ["<API key>"], name: "<API key>", unique: true
end
|
/* global requirejs, require */
/*jslint node: true */
'use strict';
import Ember from 'ember';
import _keys from 'lodash/object/keys';
/*
This function looks through all files that have been loaded by Ember CLI and
finds the ones under /mirage/[factories, fixtures, scenarios, models]/, and exports
a hash containing the names of the files as keys and the data as values.
*/
export default function(prefix) {
let modules = ['factories', 'fixtures', 'scenarios', 'models', 'serializers'];
let mirageModuleRegExp = new RegExp(`^${prefix}/mirage/(${modules.join("|")})`);
let modulesMap = modules.reduce((memo, name) => {
memo[name] = {};
return memo;
}, {});
_keys(requirejs.entries).filter(function(key) {
return mirageModuleRegExp.test(key);
}).forEach(function(moduleName) {
if (moduleName.match('.jshint')) { // ignore autogenerated .jshint files
return;
}
let moduleParts = moduleName.split('/');
let moduleType = moduleParts[moduleParts.length - 2];
let moduleKey = moduleParts[moduleParts.length - 1];
Ember.assert('Subdirectories under ' + moduleType + ' are not supported',
moduleParts[moduleParts.length - 3] === 'mirage');
if (moduleType === 'scenario'){
Ember.assert('Only scenario/default.js is supported at this time.',
moduleKey !== 'default');
}
let module = require(moduleName, null, null, true);
if (!module) { throw new Error(moduleName + ' must export a ' + moduleType); }
let data = module['default'];
modulesMap[moduleType][moduleKey] = data;
});
return modulesMap;
}
|
/* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { <API key> } from './dps-bar-chart.component';
describe('Component: DpsBarChart', () => {
it('should create an instance', () => {
let component = new <API key>();
expect(component).toBeTruthy();
});
});
|
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
?>
<script src="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.js'); ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/plugins/validate/validate.js'); ?>" type="text/javascript"></script>
<link href="<?php echo base_url('assets/plugins/jquery-fancybox/jquery.fancybox.css'); ?>" rel="stylesheet"/>
<form name="setting" class="setting-save" method="POST" action="<?php echo site_url('m_product/admin/setting/save/'.$id); ?>">
<div class="tabpanel" role="tabpanel">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active"><a href="#tab-general" aria-controls="tab-general" role="tab" data-toggle="tab"><?php echo lang('general');?></a></li>
<li role="presentation"><a href="#tab-design" aria-controls="tab-design" role="tab" data-toggle="tab"><?php echo lang('design_options'); ?></a></li>
<li class="button-back pull-right"><a href="javascript:void(0)" onclick="grid.module.setting('m_product')" title="Back to list"><i class="clip-arrow-left-2"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="tab-general">
<div class="form-group">
<label><?php echo lang('title');?><span class="symbol required"></span></label>
<input type="text" class="form-control input-sm validate required" name="title" placeholder="<?php echo lang('title');?>" value="<?php echo $m_product->title; ?>" data-minlength="2" data-maxlength="200" data-msg="<?php echo lang('<API key>');?>">
</div>
<?php
$options = json_decode($m_product->options);
?>
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<label><?php echo lang('<API key>');?></label>
<?php
$show_title = array(
'yes'=>lang('yes'),
'no'=>lang('no'),
);
if(isset($options->show_title))
$default = $options->show_title;
else
$default = '';
echo form_dropdown('options[show_title]', $show_title, $default, 'class="form-control input-sm"');
?>
</div>
<div class="col-sm-6">
<label><?php echo lang('<API key>');?></label>
<?php
$cols = array(
'1'=>1,
'2'=>2,
'3'=>3,
'4'=>4,
'6'=>6,
);
if(isset($options->cols))
$default = $options->cols;
else
$default = '';
echo form_dropdown('options[cols]', $cols, $default, 'class="form-control input-sm"');
?>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6">
<label><?php echo lang('<API key>');?></label>
<?php
$show_product = array(
'lastest'=>lang('<API key>'),
'future'=>lang('<API key>'),
'sale_price'=>lang('<API key>'),
);
if(isset($options->show_product))
$default = $options->show_product;
else
$default = '';
echo form_dropdown('options[show_product]', $show_product, $default, 'class="form-control input-sm"');
?>
</div>
<div class="col-sm-6">
<label><?php echo lang('<API key>');?></label>
<input type="text" name="options[count]" class="form-control input-sm" value="<?php if(isset($options->count) && $options->count != '') echo $options->count; else echo 8; ?>" placeholder="<?php echo lang('<API key>');?>"/>
</div>
</div>
</div>
</div>
<!-- design options -->
<?php
$params = json_decode($m_product->params, true);
?>
<div role="tabpanel" class="tab-pane" id="tab-design">
<div class="design-box">
<div class="design-box-left">
<div class="box-css">
<label><?php echo lang('css');?></label>
<div class="box-margin">
<label><?php echo lang('margin');?></label>
<input type="text" class="box-input" name="params[margin][left]" value="<?php echo setParams($params, 'margin', 'left'); ?>" id="margin-left">
<input type="text" class="box-input" name="params[margin][right]" value="<?php echo setParams($params, 'margin', 'right'); ?>" id="margin-right">
<input type="text" class="box-input" name="params[margin][top]" value="<?php echo setParams($params, 'margin', 'top'); ?>" id="margin-top">
<input type="text" class="box-input" name="params[margin][bottom]" value="<?php echo setParams($params, 'margin', 'bottom'); ?>" id="margin-bottom">
<div class="box-border">
<label><?php echo lang('border');?></label>
<input type="text" class="box-input" name="params[border][left]" value="<?php echo setParams($params, 'border', 'left'); ?>" id="border-left">
<input type="text" class="box-input" name="params[border][right]" value="<?php echo setParams($params, 'border', 'right'); ?>" id="border-right">
<input type="text" class="box-input" name="params[border][top]" value="<?php echo setParams($params, 'border', 'top'); ?>" id="border-top">
<input type="text" class="box-input" name="params[border][bottom]" value="<?php echo setParams($params, 'border', 'bottom'); ?>" id="border-bottom">
<div class="box-padding">
<label><?php echo lang('padding');?></label>
<input type="text" class="box-input" name="params[padding][left]" value="<?php echo setParams($params, 'padding', 'left'); ?>" id="padding-left">
<input type="text" class="box-input" name="params[padding][right]" value="<?php echo setParams($params, 'padding', 'right'); ?>" id="padding-right">
<input type="text" class="box-input" name="params[padding][top]" value="<?php echo setParams($params, 'padding', 'top'); ?>" id="padding-top">
<input type="text" class="box-input" name="params[padding][bottom]" value="<?php echo setParams($params, 'padding', 'bottom'); ?>" id="padding-bottom">
<div class="box-elment">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="design-box-right">
<label><?php echo lang('border');?></label>
<div class="row col-md-12">
<div class="form-group pick-color">
<div class="input-group">
<input type="text" class="form-control color input-sm" name="params[borderColor]" value="<?php echo setParams($params, 'borderColor'); ?>">
<div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div>
</div>
<a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a>
</div>
</div>
<div class="row col-md-12">
<div class="form-group">
<?php $options = array('Defaults', 'Solid','Dotted','Dashed','None','Hidden','Double','Groove','Ridge','Inset','Outset','Initial','Inherit'); ?>
<select class="form-control input-sm" name="params[borderStyle]">
<?php for($i=0; $i<12; $i++){ ?>
<?php $border_style = setParams($params, 'borderStyle');
if($border_style == $options[$i])
$check = 'selected="selected"';
else
$check = '';
?>
<option value="<?php echo $options[$i]; ?>" <?php echo $check;?>><?php echo $options[$i]; ?></option>
<?php } ?>
</select>
</div>
</div>
<label><?php echo lang('background');?></label>
<div class="row col-md-12">
<div class="form-group pick-color">
<div class="input-group">
<input type="text" class="form-control color input-sm" name="params[background][color]" value="<?php echo setParams($params, 'background', 'color'); ?>">
<div class="input-group-addon pick-color-btn"><?php echo lang('select_color');?></div>
</div>
<a href="#" class="btn btn-default btn-sm pick-color-clear"><?php echo lang('clear');?></a>
</div>
</div>
<div class="row col-md-12">
<div class="form-group">
<?php
$image = setParams($params, 'background', 'image');
if($image != '')
{
echo '<div id="gird-box-bg" style="display:inline;">';
echo '<img src="'.base_url($image).'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />';
}else
{
echo '<div id="gird-box-bg" style="display:none;">';
}
?>
<a href="javascript:void(0)" class="gird-box-bg-remove" onclick="gridRemoveImg(this)"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></a>
</div>
<input type="hidden" name="params[background][image]" id="gird-box-bg-img" value="<?php echo $image; ?>">
<a class="gird-box-image" href="javascript:void(0)" onclick="jQuery.fancybox( {href : '<?php echo site_url().'admin/media/modals/productImg/1'; ?>', type: 'iframe'} );"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></a>
</div>
</div>
<div class="row col-md-12">
<div class="form-group">
<?php $options = array('Defaults','Repeat','No repeat'); ?>
<select class="form-control input-sm" name="params[background][style]">
<?php for($i=0; $i<3; $i++){ ?>
<?php $background_style = setParams($params, 'background', 'style');
if($background_style == $options[$i])
$check = 'selected="selected"';
else
$check = '';
?>
<option value="<?php echo $options[$i]; ?>" <?php echo $check; ?>><?php echo $options[$i]; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
function productImg(images)
{
if(images.length > 0)
{
var e = jQuery('#gird-box-bg');
if(e.children('img').length > 0)
e.children('img').attr('src', images[0]);
else
e.append('<img src="'+images[0]+'" class="pull-left box-image" style="width: 80px;" alt="" width="100" />');
e.css('display', 'inline');
var str = images[0];
str = str.replace("<?php echo base_url();?>", "");
jQuery('#gird-box-bg-img').val(str);
jQuery.fancybox.close();
}
}
function gridRemoveImg(e){
var e = jQuery('#gird-box-bg');
e.children('img').remove();
e.css('display', 'none');
jQuery('#gird-box-bg-img').val('');
}
</script>
|
# Botfather configs
[BotFather](https://telegram.me/botfather) allows you to create Telegram bots, and instanciates authentication tokens. But it does more than that. To get the same settings as FiddleGram, follow this:
* Go to Botfather, use `/start` and follow the instructions to create your bot. Put the auth token in `token.js`
* Set up description and about text as you please
* Use /setcommands and give the following block:
start - [language] start a new repl session
stop - stop current repl session
languages - list currently supported languages
version - list bot and languages versions
help - display help
This will enable auto-completion on commands.
All done! Your Fiddlegram is ready to rock.
|
<?php
declare(strict_types=1);
namespace AlphaVantageTest\Api;
use AlphaVantage\Api\ForeignExchange;
class ForeignExchangeTest extends TestCase
{
public function <API key>()
{
$actual = (new ForeignExchange($this->option))-><API key>('BTC', 'CNY');
$this->assertIsArray($actual);
$this->assertCount(1, $actual);
$this->assertArrayHasKey('Realtime Currency Exchange Rate', $actual);
$this->assertNotEmpty($actual['Realtime Currency Exchange Rate']);
$this->assertCount(9, $actual['Realtime Currency Exchange Rate']);
}
}
|
local u = require "lib/util"
local Node = require "lib/espalier/node"
local Section = require "Orbit/section"
local own = require "Orbit/own"
local D = setmetatable({}, { __index = Node })
D.id = "doc"
D.__tostring = function (doc)
local phrase = ""
for _,v in ipairs(doc) do
local repr = tostring(v)
if repr ~= "" and repr ~= "\n" then
phrase = phrase .. repr .. "\n"
end
end
return phrase
end
D.__index = D
D.own = own
function D.dotLabel(doc)
return "doc - " .. tostring(doc.linum)
end
function D.toMarkdown(doc)
local phrase = ""
for _, node in ipairs(doc) do
if node.toMarkdown then
phrase = phrase .. node:toMarkdown()
else
u.freeze("no toMarkdown method for " .. node.id)
end
end
return phrase
end
local d = {}
function D.parentOf(doc, level)
local i = level - 1
local parent = nil
while i >= 0 do
parent = doc.lastOf[i]
if parent then
return parent
else
i = i - 1
end
end
return doc
end
function D.addSection(doc, section, linum, finish)
assert(section.id == "section", "type of putative section is " .. section.id)
assert(section.first, "no first in section at line " .. tostring(linum))
assert(type(finish) == "number", "finish is of type " .. type(finish))
if not doc.latest then
doc[1] = section
else
if linum > 0 then
doc.latest.line_last = linum - 1
doc.latest.last = finish
end
local atLevel = doc.latest.level
if atLevel < section.level then
-- add the section under the latest section
doc.latest:addSection(section, linum, finish)
else
local parent = doc:parentOf(section.level)
if parent.id == "doc" then
if section.level == 1 and doc.latest.level == 1 then
doc[#doc + 1] = section
else
doc.latest:addSection(section, linum, finish)
end
else
parent:addSection(section, linum, finish)
end
end
end
doc.latest = section
doc.lastOf[section.level] = section
return doc
end
function D.addLine(doc, line, linum, finish)
if doc.latest then
doc.latest:addLine(line)
doc.latest.last = finish
else
-- a virtual zero block
doc[1] = Section(0, linum, 1, #line, doc.str)
doc.latest = doc[1]
doc.latest:addLine(line)
doc.latest.last = finish
end
return doc
end
local function new(Doc, str)
local doc = setmetatable({}, D)
doc.str = str
doc.first = 1
doc.last = #str
doc.latest = nil
doc.lines = {}
doc.lastOf = {}
-- for now lets set root to 'false'
doc.root = false
return doc:own(str)
end
setmetatable(D, Node)
d["__call"] = new
return setmetatable({}, d)
|
package com.github.aureliano.evtbridge.output.file;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import org.junit.Test;
import com.github.aureliano.evtbridge.annotation.validation.NotNull;
import com.github.aureliano.evtbridge.annotation.validation.apply.ConstraintViolation;
import com.github.aureliano.evtbridge.annotation.validation.apply.ObjectValidator;
import com.github.aureliano.evtbridge.core.config.OutputConfigTypes;
public class <API key> {
ObjectValidator validator = ObjectValidator.instance();
@Test
public void testGetDefaults() {
FileOutputConfig c = new FileOutputConfig();
assertNull(c.getFile());
assertEquals("UTF-8", c.getEncoding());
assertFalse(c.isAppend());
assertTrue(c.isUseBuffer());
}
@Test
public void testConfiguration() {
FileOutputConfig c = new FileOutputConfig()
.withAppend(true)
.withEncoding("ISO-8859-1")
.withFile("/there/is/not/file");
assertEquals("/there/is/not/file", c.getFile().getPath());
assertEquals("ISO-8859-1", c.getEncoding());
assertTrue(c.isAppend());
}
@Test
public void testClone() {
FileOutputConfig c1 = new FileOutputConfig()
.withAppend(true)
.withUseBuffer(false)
.withEncoding("ISO-8859-1")
.withFile("/there/is/not/file")
.putMetadata("test", "my test");
FileOutputConfig c2 = c1.clone();
assertEquals(c1.getFile(), c2.getFile());
assertEquals(c1.getEncoding(), c2.getEncoding());
assertEquals(c1.isAppend(), c2.isAppend());
assertEquals(c1.isUseBuffer(), c2.isUseBuffer());
assertEquals(c1.getMetadata("test"), c2.getMetadata("test"));
}
@Test
public void testOutputType() {
assertEquals(OutputConfigTypes.FILE_OUTPUT.name(), new FileOutputConfig().id());
}
@Test
public void testValidation() {
FileOutputConfig c = this.<API key>();
assertTrue(this.validator.validate(c).isEmpty());
this._testValidateFile();
}
private void _testValidateFile() {
FileOutputConfig c = new FileOutputConfig();
Set<ConstraintViolation> violations = this.validator.validate(c);
assertTrue(violations.size() == 1);
assertEquals(NotNull.class, violations.iterator().next().getValidator());
}
private FileOutputConfig <API key>() {
return new FileOutputConfig().withFile("/path/to/file");
}
}
|
// THIS CODE IS MACHINE-GENERATED, DO NOT EDIT!
package fallk.jfunktion;
/**
* Represents a predicate (boolean-valued function) of a {@code float}-valued and a generic argument.
* This is the primitive type specialization of
* {@link java.util.function.BiPredicate} for {@code float}/{@code char}.
*
* @see java.util.function.BiPredicate
*/
@FunctionalInterface
public interface <API key><E> {
/**
* Evaluates this predicate on the given arguments.
*
* @param v1 the {@code float} argument
* @param v2 the generic argument
* @return {@code true} if the input arguments match the predicate,
* otherwise {@code false}
*/
boolean apply(float v1, E v2);
}
|
console.log("VS: loading content_script.js..." + new Date());
// Check if the communication between page and background.js has broken.
var last_message_time = new Date().getTime();
new Promise((resolve) => setTimeout(resolve, 1000000)).then(() => {
var now = new Date().getTime();
if (now - last_message_time > 500000) {
sendAlert('Not having message from background for at least 500s, force reloading');
reloadPage();
}
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
// Update timestamp first.
last_message_time = new Date().getTime();
console.log("VS: received data from content_script.js" + new Date());
console.log(request);
var action = request["action"];
takeAction(action, request);
});
var already_logging_in = false;
function takeAction(action, request) {
var url = window.location.href;
console.log("VS: Taking action: " + action + " in " + url);
if (action === ACTION_FOR_HOMEPAGE) {
homePage(request);
} else if (action === <API key>) {
loginPage(request);
} else if (action === <API key>) {
loginPage(request);
} else if (action === <API key>) {
dashboardPage(request);
} else {
// Other cases.
console.log("VS: unknown action:" + new Date());
console.log(action);
return;
}
}
function dashboardPage(request) {
console.log("VS: In dashboard page" + new Date());
//var val = $('[data-reactid=".0.0.3.0.0.0.0.0.1.0.0.1.0"]');
//if (val) {
// var ts = new Date().getTime();
// var amount = val.text();
// if (!amount) {
// console.log("Failed to parse data from html page. " + new Date());
// } else {
// saveGenerationData({'amount': amount, 'time': ts});
//} else {
// sendAlert('Failed to read data from Dashboard page' + window.location.href);
//console.log("VS: setting to reload page in 60s: " + new Date());
//window.setInterval(function() {
console.log("VS: polling account data" + new Date());
$.ajax({url: "/api/fusion/accounts"}).done(function(msg) {
console.log("VS: got account data" + new Date());
var j = msg;
if (typeof(j) === "object" && 'accounts' in j) {
console.log(j['accounts']);
var acct = j['accounts'][0]['account_no'];
var newUrl = '/api/fusion/accounts/' + acct;
console.log("VS: polling account detail data" + new Date());
$.ajax({url: newUrl}).done(function(msg) {
console.log("VS: got account detail data" + new Date());
var j = msg;
if (typeof(j) === "object" && 'energyToday' in j) {
var ts = new Date().getTime();
var amount = j['energyToday'] / 1000.0;
console.log("VS: saveing energy data" + new Date());
saveGenerationData({'time': ts, 'amount': amount});
return;
}
sendAlert("Failed parse detailed account info from AJAX for: " + textStatus);
reloadPage();
}).fail(function(jqXHR, textStatus) {
sendAlert("Request failed for loading detailed account info from AJAX for: " + textStatus);
reloadPage();
});
return;
}
sendAlert('Failed to parse account data');
reloadPage();
}).fail(function(jqXHR, textStatus) {
sendAlert("Request failed for loading accounts AJAX for: " + textStatus);
reloadPage();
});
//}, 60000);
}
function loginPage(request) {
if (request) {
asyncLogin(request);
} else {
chrome.runtime.sendMessage({"action": <API key>});
}
}
function homePage(request) {
var links = $('A');
for (var i in links) {
var link = links[i];
if (link.href == LOGIN_PAGE) {
link.click();
}
}
}
function asyncLogin(request) {
if (already_logging_in) {
console.log("VS: already logging in. This is possible, ignoring.." + new Date());
return;
}
already_logging_in = true;
console.log("VS: gettting new data to login" + new Date());
console.log(request);
context = request['data'];
if ($("INPUT[data-reactid='.0.0.0.0.0.1.1']").val(context.username).length > 0
&& $("INPUT[data-reactid='.0.0.0.0.0.2.0']").val(context.passwd).length > 0) {
$("BUTTON[data-reactid='.0.0.0.0.0.4.0']").click();
new Promise((resolve) => setTimeout(resolve, 100000)).then(() => {
sendAlert('Login failed for username' + context.username + ' and passwd: ' + context.passwd);
});
}
$('.email-input.js-initial-focus').val(context.username);
$('.js-password-field').val(context.passwd);
new Promise((resolve) => setTimeout(resolve, 1500)).then(() => {
$('button.submit').click();
});
}
var action = urlToAction(window.location.href);
console.log("VS: intercepted action:" + action + " at " + new Date());
if (action != '') {
takeAction(action, null);
}
console.log("VS: loaded:" + window.location.href);
console.log("VS: registered on load event here handler in content_script.js" + new Date());
|
Flappy_Flyer
=========
A Flappy Birds clone for iOS.
Raw XCode project along with original artwork.
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Books extends Model
{
protected $table = 'books';
protected $fillable = [
'guid',
'author',
'title',
'description',
'abstract',
'edition',
'publish_date',
'status'];
}
|
namespace gView.Plugins.DbTools.Relates
{
partial class <API key>
{
<summary>
Erforderliche Designervariable.
</summary>
private System.ComponentModel.IContainer components = null;
<summary>
Verwendete Ressourcen bereinigen.
</summary>
<param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Windows Form-Designer generierter Code
<summary>
Erforderliche Methode für die Designerunterstützung.
Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
</summary>
private void InitializeComponent()
{
this.btnRemove = new System.Windows.Forms.Button();
this.btnEdit = new System.Windows.Forms.Button();
this.btnAdd = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.lstRelates = new System.Windows.Forms.ListBox();
this.SuspendLayout();
// btnRemove
this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnRemove.Enabled = false;
this.btnRemove.Location = new System.Drawing.Point(323, 60);
this.btnRemove.Name = "btnRemove";
this.btnRemove.Size = new System.Drawing.Size(125, 23);
this.btnRemove.TabIndex = 9;
this.btnRemove.Text = "Remove";
this.btnRemove.<API key> = true;
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
// btnEdit
this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnEdit.Enabled = false;
this.btnEdit.Location = new System.Drawing.Point(323, 31);
this.btnEdit.Name = "btnEdit";
this.btnEdit.Size = new System.Drawing.Size(125, 23);
this.btnEdit.TabIndex = 8;
this.btnEdit.Text = "Edit...";
this.btnEdit.<API key> = true;
this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click);
// btnAdd
this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAdd.Location = new System.Drawing.Point(323, 2);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(125, 23);
this.btnAdd.TabIndex = 7;
this.btnAdd.Text = "Add...";
this.btnAdd.<API key> = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
// btnClose
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnClose.Location = new System.Drawing.Point(323, 180);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(125, 23);
this.btnClose.TabIndex = 6;
this.btnClose.Text = "Close";
this.btnClose.<API key> = true;
// lstRelates
this.lstRelates.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lstRelates.FormattingEnabled = true;
this.lstRelates.Location = new System.Drawing.Point(2, 2);
this.lstRelates.Name = "lstRelates";
this.lstRelates.Size = new System.Drawing.Size(315, 199);
this.lstRelates.TabIndex = 5;
this.lstRelates.<API key> += new System.EventHandler(this.<API key>);
// TableRelatesDialog
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(450, 206);
this.Controls.Add(this.btnRemove);
this.Controls.Add(this.btnEdit);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.lstRelates);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
this.Name = "TableRelatesDialog";
this.Text = "Relates Dialog";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.Button btnEdit;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.ListBox lstRelates;
}
}
|
<?php
namespace Eloquent\Schemer\Constraint;
interface SchemaInterface extends ConstraintInterface
{
}
|
/* header bar */
.navbar {
margin-bottom:0;
}
/* aside */
.content,aside {
margin-top:20px;
margin-bottom:30px;
margin-left:0px;
margin-right:0px;
}
.home {
background: url(/images/home.jpg) no-repeat center center fixed;
-<API key>: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
aside .nav {
margin-top:10px;
margin-left:10px;
margin-right:10px;
}
/* footer formatting */
footer {
margin-bottom:25px;
}
|
package com.carbon108.tilde;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author K Moroz
* @version 1.0
*/
public class <API key> {
private PrimaryModelFactory factory;
@Before
public void setUp() {
factory = new PrimaryModelFactory();
}
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void <API key>() {
Collection<String> factoryIDs = factory.getIDs();
assertEquals(2, factoryIDs.size());
assertEquals(true, factoryIDs.contains(ModelID.LINEAR));
assertEquals(true, factoryIDs.contains(ModelID.CONSTANT));
// check immutability
exception.expect(<API key>.class);
factoryIDs.add("someString");
}
@Test
public void <API key>() {
TildeModel model1 = factory.make(ModelID.LINEAR);
TildeModel model2 = factory.make(ModelID.CONSTANT);
assertEquals(ModelID.LINEAR, model1.getID());
assertEquals(ModelID.CONSTANT, model2.getID());
}
@Test
public void <API key>() {
TildeModel m1null = factory.make(null);
TildeModel m1blank = factory.make("");
TildeModel m2invalid = factory.make("invalidModelID");
assertTrue(m1null.isNullModel());
assertTrue(m1blank.isNullModel());
assertTrue(m2invalid.isNullModel());
}
@Test
public void makeAll() {
Collection<TildeModel> models = factory.makeAll();
assertEquals(2, models.size());
assertEquals(true, models.contains(new LinearModel()));
assertEquals(true, models.contains(new ConstantModel()));
}
}
|
var <API key> =
[
[ "ParcelsTest", "<API key>.html", "<API key>" ]
];
|
namespace QuanLySinhVien_GUI
{
partial class <API key>
{
<summary>
Required designer variable.
</summary>
private System.ComponentModel.IContainer components = null;
<summary>
Clean up any resources being used.
</summary>
<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
<summary>
Required method for Designer support - do not modify
the contents of this method with the code editor.
</summary>
private void InitializeComponent()
{
System.ComponentModel.<API key> resources = new System.ComponentModel.<API key>(typeof(<API key>));
this.btnThoat = new System.Windows.Forms.Button();
this.cmbMaMH = new System.Windows.Forms.ComboBox();
this.dgvKetQua = new System.Windows.Forms.DataGridView();
this.btnTim = new System.Windows.Forms.Button();
this.txtMaSV = new System.Windows.Forms.TextBox();
this.lblMaMH = new System.Windows.Forms.Label();
this.lblMaSV = new System.Windows.Forms.Label();
this.lblTittle = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).BeginInit();
this.SuspendLayout();
// btnThoat
this.btnThoat.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnThoat.BackgroundImage")));
this.btnThoat.<API key> = System.Windows.Forms.ImageLayout.None;
this.btnThoat.Location = new System.Drawing.Point(580, 418);
this.btnThoat.Name = "btnThoat";
this.btnThoat.Size = new System.Drawing.Size(72, 30);
this.btnThoat.TabIndex = 32;
this.btnThoat.Text = " Thoát";
this.btnThoat.<API key> = true;
// cmbMaMH
this.cmbMaMH.FormattingEnabled = true;
this.cmbMaMH.Location = new System.Drawing.Point(382, 109);
this.cmbMaMH.Name = "cmbMaMH";
this.cmbMaMH.Size = new System.Drawing.Size(121, 21);
this.cmbMaMH.TabIndex = 31;
// dgvKetQua
this.dgvKetQua.AllowUserToAddRows = false;
this.dgvKetQua.<API key> = false;
this.dgvKetQua.<API key> = System.Windows.Forms.<API key>.AutoSize;
this.dgvKetQua.Location = new System.Drawing.Point(96, 183);
this.dgvKetQua.Name = "dgvKetQua";
this.dgvKetQua.ReadOnly = true;
this.dgvKetQua.Size = new System.Drawing.Size(537, 214);
this.dgvKetQua.TabIndex = 30;
// btnTim
this.btnTim.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnTim.BackgroundImage")));
this.btnTim.<API key> = System.Windows.Forms.ImageLayout.None;
this.btnTim.Location = new System.Drawing.Point(580, 105);
this.btnTim.Name = "btnTim";
this.btnTim.Size = new System.Drawing.Size(72, 30);
this.btnTim.TabIndex = 29;
this.btnTim.Text = " Tìm";
this.btnTim.<API key> = true;
// txtMaSV
this.txtMaSV.Location = new System.Drawing.Point(114, 111);
this.txtMaSV.Name = "txtMaSV";
this.txtMaSV.Size = new System.Drawing.Size(125, 20);
this.txtMaSV.TabIndex = 28;
// lblMaMH
this.lblMaMH.AutoSize = true;
this.lblMaMH.Location = new System.Drawing.Point(302, 111);
this.lblMaMH.Name = "lblMaMH";
this.lblMaMH.Size = new System.Drawing.Size(60, 13);
this.lblMaMH.TabIndex = 26;
this.lblMaMH.Text = "Mã Học Kỳ";
// lblMaSV
this.lblMaSV.AutoSize = true;
this.lblMaSV.Location = new System.Drawing.Point(43, 111);
this.lblMaSV.Name = "lblMaSV";
this.lblMaSV.Size = new System.Drawing.Size(39, 13);
this.lblMaSV.TabIndex = 27;
this.lblMaSV.Text = "Mã SV";
// lblTittle
this.lblTittle.AutoSize = true;
this.lblTittle.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTittle.ForeColor = System.Drawing.Color.Red;
this.lblTittle.Location = new System.Drawing.Point(151, 30);
this.lblTittle.Name = "lblTittle";
this.lblTittle.Size = new System.Drawing.Size(408, 31);
this.lblTittle.TabIndex = 25;
this.lblTittle.Text = "Tìm Kiếm Điểm Theo Mã Sinh Viên";
// <API key>
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(695, 479);
this.Controls.Add(this.btnThoat);
this.Controls.Add(this.cmbMaMH);
this.Controls.Add(this.dgvKetQua);
this.Controls.Add(this.btnTim);
this.Controls.Add(this.txtMaSV);
this.Controls.Add(this.lblMaMH);
this.Controls.Add(this.lblMaSV);
this.Controls.Add(this.lblTittle);
this.Name = "<API key>";
this.Text = "TÌM KIẾM ĐIỂM SINH VIÊN";
((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnThoat;
private System.Windows.Forms.ComboBox cmbMaMH;
private System.Windows.Forms.DataGridView dgvKetQua;
private System.Windows.Forms.Button btnTim;
private System.Windows.Forms.TextBox txtMaSV;
private System.Windows.Forms.Label lblMaMH;
private System.Windows.Forms.Label lblMaSV;
private System.Windows.Forms.Label lblTittle;
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cantor: 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.11.2 / cantor - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cantor
<small>
8.9.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-17 11:46:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-17 11:46:38 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-m4 1 Virtual package relying on m4
coq 8.11.2 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.10.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.0 Official release 4.10.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/cantor"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Cantor"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: ordinals"
"keyword: well-foundedness"
"keyword: termination"
"keyword: rpo"
"keyword: Goodstein sequences"
"category: Mathematics/Logic/See also"
"category: Mathematics/Arithmetic and Number Theory/Number theory"
"date: 2006-05-22"
]
authors: [
"Pierre Castéran <pierre.casteran@labri.fr> [http:
"Évelyne Contejean <contejea@lri.fr> [http:
]
bug-reports: "https://github.com/coq-contribs/cantor/issues"
dev-repo: "git+https://github.com/coq-contribs/cantor.git"
synopsis: "On Ordinal Notations"
description: """
This contribution contains data structures for ordinals
less than Gamma0 under Cantor and Veblen normal
forms. Well-foundedness is established thanks to RPO with status for
generic terms. This contribution also includes termination proofs of
Hydra battles and Goodstein sequences as well as a computation of the
length of the Goodstein sequence starting from 4 in base 2.
This work is supported by INRIA-Futurs (Logical project-team), CNRS
and the French ANR via the A3PAT project (http://www3.iie.cnam.fr/~urbain/a3pat/)."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cantor/archive/v8.9.0.tar.gz"
checksum: "md5=<API key>"
}
</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-cantor.8.9.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2).
The following dependencies couldn't be met:
- coq-cantor -> coq < 8.10~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
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-cantor.8.9.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:
</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>
|
#ifndef CHECKQUEUE_H
#define CHECKQUEUE_H
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/condition_variable.hpp>
#include <vector>
#include <algorithm>
template<typename T> class CCheckQueueControl;
/** Queue for verifications that have to be performed.
* The verifications are represented by a type T, which must provide an
* operator(), returning a bool.
*
* One thread (the master) is assumed to push batches of verifications
* onto the queue, where they are processed by N-1 worker threads. When
* the master is done adding work, it temporarily joins the worker pool
* as an N'th worker, until all jobs are done.
*/
template<typename T> class CCheckQueue {
private:
// Mutex to protect the inner state
boost::mutex mutex;
// Worker threads block on this when out of work
boost::condition_variable condWorker;
// Master thread blocks on this when out of work
boost::condition_variable condMaster;
// The queue of elements to be processed.
// As the order of booleans doesn't matter, it is used as a LIFO (stack)
std::vector<T> queue;
// The number of workers (including the master) that are idle.
int nIdle;
// The total number of workers (including the master).
int nTotal;
// The temporary evaluation result.
bool fAllOk;
// Number of verifications that haven't completed yet.
// This includes elements that are not anymore in queue, but still in
// worker's own batches.
unsigned int nTodo;
// Whether we're shutting down.
bool fQuit;
// The maximum number of elements to be processed in one batch
unsigned int nBatchSize;
// Internal function that does bulk of the verification work.
bool Loop(bool fMaster = false) {
boost::condition_variable &cond = fMaster ? condMaster : condWorker;
std::vector<T> vChecks;
vChecks.reserve(nBatchSize);
unsigned int nNow = 0;
bool fOk = true;
do {
{
boost::unique_lock<boost::mutex> lock(mutex);
// first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
if (nNow) {
fAllOk &= fOk;
nTodo -= nNow;
if (nTodo == 0 && !fMaster)
// We processed the last element; inform the master he can exit and return the result
condMaster.notify_one();
} else {
// first iteration
nTotal++;
}
// logically, the do loop starts here
while (queue.empty()) {
if ((fMaster || fQuit) && nTodo == 0) {
nTotal
bool fRet = fAllOk;
// reset the status for new work later
if (fMaster)
fAllOk = true;
// return the current status
return fRet;
}
nIdle++;
cond.wait(lock); // wait
nIdle
}
// Decide how many work units to process now.
// * Do not try to do everything at once, but aim for increasingly smaller batches so
// all workers finish approximately simultaneously.
// * Try to account for idle jobs which will instantly start helping.
// * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
vChecks.resize(nNow);
for (unsigned int i = 0; i < nNow; i++) {
// We want the lock on the mutex to be as short as possible, so swap jobs from the global
// queue to the local batch vector instead of copying.
vChecks[i].swap(queue.back());
queue.pop_back();
}
// Check whether we need to do work at all
fOk = fAllOk;
}
// execute work
BOOST_FOREACH(T &check, vChecks)
if (fOk)
fOk = check();
vChecks.clear();
} while(true);
}
public:
// Create a new check queue
CCheckQueue(unsigned int nBatchSizeIn) :
nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
// Worker thread
void Thread() {
Loop();
}
// Wait until execution finishes, and return whether all evaluations where succesful.
bool Wait() {
return Loop(true);
}
// Add a batch of checks to the queue
void Add(std::vector<T> &vChecks) {
boost::unique_lock<boost::mutex> lock(mutex);
BOOST_FOREACH(T &check, vChecks) {
queue.push_back(T());
check.swap(queue.back());
}
nTodo += vChecks.size();
if (vChecks.size() == 1)
condWorker.notify_one();
else if (vChecks.size() > 1)
condWorker.notify_all();
}
~CCheckQueue() {
}
friend class CCheckQueueControl<T>;
};
/** RAII-style controller object for a CCheckQueue that guarantees the passed
* queue is finished before continuing.
*/
template<typename T> class CCheckQueueControl {
private:
CCheckQueue<T> *pqueue;
bool fDone;
public:
CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
// passed queue is supposed to be unused, or NULL
if (pqueue != NULL) {
assert(pqueue->nTotal == pqueue->nIdle);
assert(pqueue->nTodo == 0);
assert(pqueue->fAllOk == true);
}
}
bool Wait() {
if (pqueue == NULL)
return true;
bool fRet = pqueue->Wait();
fDone = true;
return fRet;
}
void Add(std::vector<T> &vChecks) {
if (pqueue != NULL)
pqueue->Add(vChecks);
}
~CCheckQueueControl() {
if (!fDone)
Wait();
}
};
#endif
|
## Exercises
scheme
;; ======================================================
;; Load definitions and functions from earlier chapters
;; ======================================================
(load "c01s01.scm")
;; ======================================================
**Exercise 1.9** Each of the following two procedures defines a method for adding two positive integers in terms of the procedures inc, which increments its argument by 1, and dec, which decrements its argument by 1.
scheme
(define (+ a b)
(if (= a 0)
b
(inc (+ (dec a) b))))
(define (+ a b)
(if (= a 0)
b
(+ (dec a) (inc b))))
Using the substitution model, illustrate the process generated by each procedure in evaluating (+ 4 5). Are these processes iterative or recursive?
**Exercise 1.10** The following procedure computes a mathematical function called Ackermann's function.
scheme
(define (A x y)
(cond ((= y 0) 0)
((= x 0) (* 2 y))
((= y 1) 2)
(else (A (- x 1)
(A x (- y 1))))))
What are the values of the following expressions?
scheme
(A 1 10)
(A 2 4)
(A 3 3)
Consider the following procedures, where A is the procedure defined above:
scheme
(define (f n) (A 0 n))
(define (g n) (A 1 n))
(define (h n) (A 2 n))
(define (k n) (* 5 n n))
Give concise mathematical definitions for the functions computed by the procedures f, g, and h for positive integer values of n. For example, (k n) computes 5n^2.
scheme
(A 1 10)
; 2^10 because the final argument, (A x (- y 1))
; will evaluate 9 times before y = 1 and the
; function stops at 2
(A 2 4)
; 2^16 because the function first evaluates to (A 1 (A 2 3))
; = (A 1 (A 1 (A 2 2)))
; = (A 1 (A 1 (A 1 (A 2 1))))
; = (A 1 (A 1 (A 1 2)))
; = (A 1 (A 1 (A 0 (A 1 1))))
; = (A 1 (A 1 (A 0 2)))
; = (A 1 (A 1 (2 * 2)))
; = (A 1 (A 1 4))
; = (A 1 (A 0 (A 1 3)))
; = (A 1 (A 0 (A 0 (A 1 2))))
; = (A 1 (A 0 (A 0 (A 1 2))))
; = (A 1 (A 0 (A 0 (A 0 (A 1 1)))))
; = (A 1 (A 0 (A 0 (A 0 2))))
; = (A 1 (A 0 (A 0 (2 * 2))))
; = (A 1 (A 0 (A 0 4)))
; = (A 1 (A 0 (2 * 4)))
; = (A 1 (A 0 8))
; = (A 1 (2 * 8))
; = (A 1 16)
; which as we saw above will evaluate to 2^16
(A 3 3)
; 2^16 because the function first evaluates to (A 2 (A 3 2))
; = (A 2 (A 2 (A 3 1)))
; = (A 2 (A 2 2))
; = (A 2 (A 1 (A 2 1)))
; = (A 2 (A 1 2))
; = (A 2 (A 0 (A 1 1)))
; = (A 2 (A 0 2))
; = (A 2 (2 * 2))
; = (A 2 4)
; which as we saw above will evaluate to 2^16
(define (f n) (A 0 n))
; f(n) = 2*n
(define (g n) (A 1 n))
; g(n) = 2^n
(define (h n) (A 2 n))
; h(n) = 2^(n^2)
**Exercise 1.11** A function f is defined by the rule that f(n) = n if n < 3 and f(n) = f(n-1) + f(n-2) + f(n-3) if n >= 3.
Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.
scheme
; Recursive solution
(define (f n)
(cond ((< n 3) n)
(else (+ (+ (f (- n 1)) (* 2 (f (- n 2))))
(* 3 (f (- n 3)))))))
; Iterative solution
; a <- a + 2*b + 3*c
; b <- a
; c <- b
(define (f n)
(f-iter 2 1 0 n))
(define (f-iter a b c count)
(if (= count 0)
c
(f-iter (+ a (* b 2) (* c 3)) a b (- count 1))))
**Exercise 1.12** The following pattern of numbers is called Pascal's triangle.
Tex
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a procedure that computes elements of Pascal's triangle by means of a recursive process.
scheme
(define (pascal row col)
(cond ((= row 1) 1)
((= row col) 1)
((= col 1) 1)
(else (+ (pascal (- row 1) (- col 1))
(pascal (- row 1) col)))))
(pascal 1 1)
;Value: 1
(pascal 2 1)
;Value: 1
(pascal 2 2)
;Value: 1
(pascal 3 1)
;Value: 1
(pascal 3 2)
;Value: 2
(pascal 3 3)
;Value: 1
(pascal 4 2)
;Value: 3
(pascal 4 3)
;Value: 3
(pascal 5 3)
;Value: 6
**Exercise 1.13** Prove that Fib(n) is the closest integer to (phi^n)/5, where phi = (1 + sqrt(5))/2. Hint: Let psi = (1 - sqrt(5))/2. Use induction and the definition of the Fibonacci numbers (see section 1.2.2) to prove that Fib(n) = (n - n)/5.
Text
Base case: show for n = 0 and n = 1
n=0: Fib(0) = (phi^0 - rho^0)/sqrt(5)
0 = (0 - 0)/sqrt(5)
0 = 0
n=1: Fib(1) = (phi^1 - rho^1)/sqrt(5)
1 = ((1 + sqrt(5))/2 - (1 - sqrt(5))/2)/sqrt(5)
1 = ((2*(sqrt(5)))/2) / sqrt(5)
1 = (sqrt(5)) / sqrt(5)
1 = 1
Induction case: take k >= 1 as given and assume relation is true for all n >= 0
Fib(k + 1) = Fib(k) + Fib(k - 1)
By the induction hypothesis, we have that
Fib(k + 1) = ((phi^(k) - rho^(k))/sqrt(5)) + ((phi^(k - 1) - rho^(k - 1))/sqrt(5))
Fib(k + 1) = ((phi)^(k) + (phi)^(k - 1))/sqrt(5) - ((rho)^(k) + (rho)^(k - 1))/sqrt(5)
Since phi^2 = phi + 1 and rho^2 = rho + 1, we observe that
Fib(k + 1) = (((phi)^(k - 1)(phi + 1)) - ((rho)^(k - 1)(rho + 1)))/sqrt(5)
Fib(k + 1) = (((phi)^(k - 1)(phi^2)) - ((rho)^(k - 1)(rho^2)))/sqrt(5)
Fib(k + 1) = ((phi)^(k + 1) - (rho)^(k + 1))/sqrt(5)
**Exercise 1.14** Draw the tree illustrating the process generated by the count-change procedure of section 1.2.2 in making change for 11 cents. What are the orders of growth of the space and number of steps used by this process as the amount to be changed increases?
**Exercise 1.15** The sine of an angle (specified in radians) can be computed by making use of the approximation sin x ~ x if x is sufficiently small, and the trigonometric identity
sin r = 3 sin r/3 - 4 sin^3 r/3
to reduce the size of the argument of sin. (For purposes of this exercise an angle is considered "sufficiently small" if its magnitude is not greater than 0.1 radians.) These ideas are incorporated in the following procedures:
scheme
(define (cube x) (* x x x))
(define (p x) (- (* 3 x) (* 4 (cube x))))
(define (sine angle)
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
a. How many times is the procedure p applied when (sine 12.15) is evaluated?
> 6
b. What is the order of growth in space and number of steps (as a function of a) used by the process generated by the sine procedure when (sine a) is evaluated?
> n
**Exercise 1.16** Design a procedure that evolves an iterative exponentiation process that uses successive squaring and uses a logarithmic number of steps, as does fast-expt. (Hint: Using the observation that (b^(n/2))^2 = (b^2)^(n/2), keep, along with the exponent n and the base b, an additional state variable a, and define the state transformation in such a way that the product a bn is unchanged from state to state. At the beginning of the process a is taken to be 1, and the answer is given by the value of a at the end of the process. In general, the technique of defining an invariant quantity that remains unchanged from state to state is a powerful way to think about the design of iterative algorithms.)
scheme
; define the iterative algorithm
(define (rapid-expt-iter b n product)
(cond ((= n 0) product)
; use successive squaring for even powers greater than 2
((and (even? n) (> n 2)) (rapid-expt-iter b (/ n 2) (* product (* b b))))
; else use simple iteration
(else (rapid-expt-iter b (- n 1) (* product b)))))
; call iterative algorithm in a shorter-form function which initializes a to be 1
(define (rapid-expt b n)
(rapid-expt-iter b n 1))
; Test some outputs
(rapid-expt 2 4)
; Value: 16
(rapid-expt 3 5)
; Value: 243
**Exercise 1.17** The exponentiation algorithms in this section are based on performing exponentiation by means of repeated multiplication. In a similar way, one can perform integer multiplication by means of repeated addition. The following multiplication procedure (in which it is assumed that our language can only add, not multiply) is analogous to the expt procedure:
scheme
(define (* a b)
(if (= b 0)
0
(+ a (* a (- b 1)))))
This algorithm takes a number of steps that is linear in b. Now suppose we include, together with addition, operations double, which doubles an integer, and halve, which divides an (even) integer by 2. Using these, design a multiplication procedure analogous to fast-expt that uses a logarithmic number of steps.
scheme
; define double
(define (double x) (* x 2))
; define halve
(define (halve x) (/ x 2))
; define the iterative algorithm
(define (rapid-mult-iter a b product)
(cond ((= b 0) product)
; if b can be halved and is greater than 2, halve it and double the product of the multiplication
((and (even? b) (> b 2)) (+ product (double (rapid-mult-iter a (halve b) 0))))
; else use simple iteration
(else (rapid-mult-iter a (- b 1) (+ product a)))))
; call iterative algorithm in a shorter-form function which initializes a to be 1
(define (rapid-mult a b)
(rapid-mult-iter a b 0))
|
# <API key>
A collection of webcomponents, inspired by the design work at http://tympanus.net/codrops/
|
// BallVC.h
// KenshinPro
#import <UIKit/UIKit.h>
<API key>
@interface BallVC : UIViewController
@end
<API key>
|
## Your Names
# 1) Michael Yao
# 2) Benjamin Heidebrink
# We spent [1.25] hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, num_of_ingredients)
library = {"cookie" => 1, "cake" => 5, "pie" => 7}
raise ArgumentError.new("#{item_to_make} is not a valid input") unless library[item_to_make]
# fail ArgumentError, "#{item_to_make} is not a valid input" unless library.key?(item_to_make)
serving_size = library[item_to_make]
<API key> = num_of_ingredients % serving_size
baking_plan = "Calculations complete: Make #{num_of_ingredients / serving_size} of #{item_to_make}"
return baking_plan if <API key>.zero?
baking_plan + ", you have #{<API key>} leftover ingredients. Suggested baking items: #{leftovers(<API key>)}"
end
def leftovers(<API key>)
cakes=<API key>/5
cookies=<API key>%5
"#{cakes} cakes and #{cookies} cookies."
end
p serving_size_calc("pie", 7)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
p serving_size_calc("THIS IS AN ERROR", 5)
# Reflection
# What did you learn about making code readable by working on this challenge?
# It's preeettty important. Also we learned some new methods/syntax to make it more readable and truthy/falsey
# Did you learn any new methods? What did you learn about them?
# .zero? .key? .nil? .values_at
# What did you learn about accessing data in hashes?
# .values_at returns an array, .key checks for keys., if we show one argument it will return an array of hash/key
# What concepts were solidified when working through this challenge?
# refactoring, some syntax
|
import 'css.escape'
import { createFootnote, FootnoteElements } from './footnote'
import { bindScrollHandler } from './scroll'
import { Adapter } from '../core'
import { addClass, removeClass, unmount } from './element'
export const CLASS_CONTENT = 'littlefoot__content'
export const CLASS_WRAPPER = 'littlefoot__wrapper'
export type HTMLAdapterSettings = Readonly<{
allowDuplicates: boolean
<API key>: string
anchorPattern: RegExp
buttonTemplate: string
contentTemplate: string
footnoteSelector: string
numberResetSelector: string
scope: string
}>
type TemplateData = Readonly<{
number: number
id: string
content: string
reference: string
}>
type Original = Readonly<{
reference: HTMLElement
referenceId: string
body: HTMLElement
}>
type OriginalData = Readonly<{
original: Original
data: TemplateData
}>
const CLASS_PRINT_ONLY = 'littlefoot--print'
const CLASS_HOST = 'littlefoot'
const setPrintOnly = (el: Element) => addClass(el, CLASS_PRINT_ONLY)
function queryAll<E extends Element>(
parent: ParentNode,
selector: string
): readonly E[] {
return Array.from(parent.querySelectorAll<E>(selector))
}
function getByClassName<E extends Element>(element: E, className: string): E {
return (
element.querySelector<E>('.' + className) ||
(element.firstElementChild as E | null) ||
element
)
}
function <API key>(html: string): HTMLElement {
const container = document.createElement('div')
container.innerHTML = html
return container.firstElementChild as HTMLElement
}
function children(element: Element, selector: string): readonly Element[] {
return Array.from(element.children).filter(
(child) => child.nodeType !== 8 && child.matches(selector)
)
}
function isDefined<T>(value?: T): value is T {
return value !== undefined
}
function findFootnoteLinks(
document: Document,
pattern: RegExp,
scope: string
): readonly HTMLAnchorElement[] {
return queryAll<HTMLAnchorElement>(document, scope + ' a[href*="#"]').filter(
(link) => (link.href + link.rel).match(pattern)
)
}
function findReference(
document: Document,
allowDuplicates: boolean,
<API key>: string,
footnoteSelector: string
) {
const processed: Element[] = []
return (link: HTMLAnchorElement): Original | undefined => {
// <API key> @typescript-eslint/<API key>
const fragment = link.href.split('
const related = queryAll(document, '#' + CSS.escape(fragment)).find(
(footnote) => allowDuplicates || !processed.includes(footnote)
)
const body = related?.closest<HTMLElement>(footnoteSelector)
if (body) {
processed.push(body)
const reference = link.closest<HTMLElement>(<API key>) || link
const referenceId = reference.id || link.id
return { reference, referenceId, body }
}
}
}
function <API key>(element: HTMLElement): void {
// <API key> @typescript-eslint/<API key>
const container = element.parentElement!
const visibleElements = children(container, `:not(.${CLASS_PRINT_ONLY})`)
const visibleSeparators = visibleElements.filter((el) => el.tagName === 'HR')
if (visibleElements.length === visibleSeparators.length) {
visibleSeparators.concat(container).forEach(setPrintOnly)
<API key>(container)
}
}
function recursiveUnmount(element: HTMLElement) {
// <API key> @typescript-eslint/<API key>
const parent = element.parentElement!
unmount(element)
const html = parent.innerHTML.replace('[]', '').replace(' ', ' ').trim()
if (!html) {
recursiveUnmount(parent)
}
}
function prepareTemplateData(original: Original, idx: number): OriginalData {
const content = <API key>(original.body.outerHTML)
const backlinkSelector = '[href$="#' + original.referenceId + '"]'
queryAll<HTMLElement>(content, backlinkSelector).forEach(recursiveUnmount)
const html = content.innerHTML.trim()
return {
original,
data: {
id: String(idx + 1),
number: idx + 1,
reference: 'lf-' + original.referenceId,
content: html.startsWith('<') ? html : '<p>' + html + '</p>',
},
}
}
const resetNumbers = (resetSelector: string) => {
let current = 0
let previousParent: Element | null = null
return ({ original, data }: OriginalData): OriginalData => {
const parent = original.reference.closest(resetSelector)
current = previousParent === parent ? current + 1 : 1
previousParent = parent
return { original, data: { ...data, number: current } }
}
}
function interpolate(template: string) {
const pattern = /<%=?\s*(\w+?)\s*%>/g
return (replacement: TemplateData) =>
template.replace(pattern, (_, key: keyof TemplateData) =>
String(replacement[key] ?? '')
)
}
function createElements(buttonTemplate: string, popoverTemplate: string) {
const renderButton = interpolate(buttonTemplate)
const renderPopover = interpolate(popoverTemplate)
return ({
original,
data,
}: OriginalData): OriginalData & FootnoteElements => {
const id = data.id
const host = <API key>(
`<span class="${CLASS_HOST}">${renderButton(data)}</span>`
)
const button = host.firstElementChild as HTMLElement
button.setAttribute('aria-expanded', 'false')
button.dataset.footnoteButton = ''
button.dataset.footnoteId = id
const popover = <API key>(renderPopover(data))
popover.dataset.footnotePopover = ''
popover.dataset.footnoteId = id
const wrapper = getByClassName(popover, CLASS_WRAPPER)
const content = getByClassName(popover, CLASS_CONTENT)
bindScrollHandler(content, popover)
return { original, data, id, button, host, popover, content, wrapper }
}
}
function attachFootnote(reference: HTMLElement, host: HTMLElement): void {
reference.<API key>('beforebegin', host)
}
export function setup({
allowDuplicates,
<API key>,
anchorPattern,
buttonTemplate,
contentTemplate,
footnoteSelector,
numberResetSelector,
scope,
}: HTMLAdapterSettings): Adapter<HTMLElement> {
const footnoteElements = findFootnoteLinks(document, anchorPattern, scope)
.map(
findReference(
document,
allowDuplicates,
<API key>,
footnoteSelector
)
)
.filter(isDefined)
.map(prepareTemplateData)
.map(numberResetSelector ? resetNumbers(numberResetSelector) : (i) => i)
.map(createElements(buttonTemplate, contentTemplate))
footnoteElements.forEach(({ original, host }) => {
setPrintOnly(original.reference)
setPrintOnly(original.body)
<API key>(original.body)
attachFootnote(original.reference, host)
})
const footnotes = footnoteElements.map(createFootnote)
return {
footnotes,
unmount() {
footnotes.forEach((footnote) => footnote.destroy())
queryAll(document, '.' + CLASS_PRINT_ONLY).forEach((element) =>
removeClass(element, CLASS_PRINT_ONLY)
)
},
}
}
|
require File.expand_path("spec_helper", File.dirname(File.dirname(__FILE__)))
describe 'response.cache_control' do
it 'sets the Cache-Control header' do
app(:caching) do |r|
response.cache_control :public=>true, :no_cache=>true, :max_age => 60
end
header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public']
end
it 'does not add a Cache-Control header if it would be empty' do
app(:caching) do |r|
response.cache_control({})
end
header('Cache-Control').should == nil
end
end
describe 'response.expires' do
it 'sets the Cache-Control and Expires header' do
app(:caching) do |r|
response.expires 60, :public=>true, :no_cache=>true
end
header('Cache-Control').split(', ').sort.should == ['max-age=60', 'no-cache', 'public']
((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1
end
it 'can be called with only one argument' do
app(:caching) do |r|
response.expires 60
end
header('Cache-Control').split(', ').sort.should == ['max-age=60']
((Time.httpdate(header('Expires')) - Time.now).round - 60).abs.should <= 1
end
end
describe 'response.finish' do
it 'removes Content-Type and Content-Length for 304 responses' do
app(:caching) do |r|
response.status = 304
end
header('Content-Type').should == nil
header('Content-Length').should == nil
end
it 'does not change non-304 responses' do
app(:caching) do |r|
response.status = 200
end
header('Content-Type').should == 'text/html'
header('Content-Length').should == '0'
end
end
describe 'request.last_modified' do
it 'ignores nil' do
app(:caching) do |r|
r.last_modified nil
end
header('Last-Modified').should == nil
end
it 'does not change a status other than 200' do
app(:caching) do |r|
response.status = 201
r.last_modified Time.now
end
status.should == 201
status('<API key>' => 'Sun, 26 Sep 2030 23:43:52 GMT').should == 201
status('<API key>' => 'Sun, 26 Sep 2000 23:43:52 GMT').should == 201
end
end
describe 'request.last_modified' do
def res(a={})
s, h, b = req(a)
h['Last-Modified'].should == @last_modified.httpdate
[s, b.join]
end
before(:all) do
lm = @last_modified = Time.now
app(:caching) do |r|
r.last_modified lm
'ok'
end
end
it 'just sets Last-Modified if no If-Modified-Since header' do
res.should == [200, 'ok']
end
it 'just sets Last-Modified if bogus If-Modified-Since header' do
res('<API key>' => 'a really weird date').should == [200, 'ok']
end
it 'just sets Last-Modified if modified since If-Modified-Since header' do
res('<API key>' => (@last_modified - 1).httpdate).should == [200, 'ok']
end
it 'sets Last-Modified and returns 304 if modified on If-Modified-Since header' do
res('<API key>' => @last_modified.httpdate).should == [304, '']
end
it 'sets Last-Modified and returns 304 if modified before If-Modified-Since header' do
res('<API key>' => (@last_modified + 1).httpdate).should == [304, '']
end
it 'sets Last-Modified if If-None-Match header present' do
res('HTTP_IF_NONE_MATCH' => '*', '<API key>' => (@last_modified + 1).httpdate).should == [200, 'ok']
end
it 'sets Last-Modified if modified before If-Unmodified-Since header' do
res('<API key>' => (@last_modified + 1).httpdate).should == [200, 'ok']
end
it 'sets Last-Modified if modified on If-Unmodified-Since header' do
res('<API key>' => @last_modified.httpdate).should == [200, 'ok']
end
it 'sets Last-Modified and returns 412 if modified after If-Unmodified-Since header' do
res('<API key>' => (@last_modified - 1).httpdate).should == [412, '']
end
end
describe 'request.etag' do
before(:all) do
app(:caching) do |r|
r.is "" do
response.status = r.env['status'] if r.env['status']
etag_opts = {}
etag_opts[:new_resource] = r.env['new_resource'] if r.env.has_key?('new_resource')
etag_opts[:weak] = r.env['weak'] if r.env.has_key?('weak')
r.etag 'foo', etag_opts
'ok'
end
end
end
it 'uses a weak etag with the :weak option' do
header('ETag', 'weak'=>true).should == 'W/"foo"'
end
describe 'for GET requests' do
def res(a={})
s, h, b = req(a)
h['ETag'].should == '"foo"'
[s, b.join]
end
it "sets etag if no If-None-Match" do
res.should == [200, 'ok']
end
it "sets etag and returns 304 if If-None-Match is *" do
res('HTTP_IF_NONE_MATCH' => '*').should == [304, '']
end
it "sets etag and if If-None-Match is * and it is a new resource" do
res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok']
end
it "sets etag and returns 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"').should == [304, '']
end
it "sets etag and returns 304 if If-None-Match includes etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [304, '']
end
it "sets etag if If-None-Match does not include etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok']
end
it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok']
end
it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [304, '']
end
it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [304, '']
end
it "sets etag if If-Match is *" do
res('HTTP_IF_MATCH' => '*').should == [200, 'ok']
end
it "sets etag if If-Match is etag" do
res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok']
end
it "sets etag if If-Match includes etag" do
res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok']
end
it "sets etag and returns 412 if If-Match is * for new resources" do
res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, '']
end
it "sets etag if If-Match does not include etag" do
res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, '']
end
end
describe 'for PUT requests' do
def res(a={})
s, h, b = req(a.merge('REQUEST_METHOD'=>'PUT'))
h['ETag'].should == '"foo"'
[s, b.join]
end
it "sets etag if no If-None-Match" do
res.should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is *" do
res('HTTP_IF_NONE_MATCH' => '*').should == [412, '']
end
it "sets etag and if If-None-Match is * and it is a new resource" do
res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>true).should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, '']
end
it "sets etag and returns 412 if If-None-Match includes etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, '']
end
it "sets etag if If-None-Match does not include etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok']
end
it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok']
end
it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, '']
end
it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, '']
end
it "sets etag if If-Match is *" do
res('HTTP_IF_MATCH' => '*').should == [200, 'ok']
end
it "sets etag if If-Match is etag" do
res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok']
end
it "sets etag if If-Match includes etag" do
res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok']
end
it "sets etag and returns 412 if If-Match is * for new resources" do
res('HTTP_IF_MATCH' => '*', 'new_resource'=>true).should == [412, '']
end
it "sets etag if If-Match does not include etag" do
res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, '']
end
end
describe 'for POST requests' do
def res(a={})
s, h, b = req(a.merge('REQUEST_METHOD'=>'POST'))
h['ETag'].should == '"foo"'
[s, b.join]
end
it "sets etag if no If-None-Match" do
res.should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is * and it is not a new resource" do
res('HTTP_IF_NONE_MATCH' => '*', 'new_resource'=>false).should == [412, '']
end
it "sets etag and if If-None-Match is *" do
res('HTTP_IF_NONE_MATCH' => '*').should == [200, 'ok']
end
it "sets etag and returns 412 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"').should == [412, '']
end
it "sets etag and returns 412 if If-None-Match includes etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "foo"').should == [412, '']
end
it "sets etag if If-None-Match does not include etag" do
res('HTTP_IF_NONE_MATCH' => '"bar", "baz"').should == [200, 'ok']
end
it "sets etag and does not change status code if status code set and not 2xx or 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>499).should == [499, 'ok']
end
it "sets etag and returns 304 if status code set to 2xx if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>201).should == [412, '']
end
it "sets etag and returns 304 if status code is already 304 if If-None-Match is etag" do
res('HTTP_IF_NONE_MATCH' => '"foo"', 'status'=>304).should == [412, '']
end
it "sets etag if If-Match is * and this is not a new resource" do
res('HTTP_IF_MATCH' => '*', 'new_resource'=>false).should == [200, 'ok']
end
it "sets etag if If-Match is etag" do
res('HTTP_IF_MATCH' => '"foo"').should == [200, 'ok']
end
it "sets etag if If-Match includes etag" do
res('HTTP_IF_MATCH' => '"bar", "foo"').should == [200, 'ok']
end
it "sets etag and returns 412 if If-Match is * for new resources" do
res('HTTP_IF_MATCH' => '*').should == [412, '']
end
it "sets etag if If-Match does not include etag" do
res('HTTP_IF_MATCH' => '"bar", "baz"', 'new_resource'=>true).should == [412, '']
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.