code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
#include "XmlSerializer.h"
namespace dnc {
namespace Xml {
XmlSerializer::XmlSerializer() {}
XmlSerializer::~XmlSerializer() {}
std::string XmlSerializer::ToString() {
return std::string("System.Xml.XmlSerializer");
}
std::string XmlSerializer::GetTypeString() {
return std::string("XmlSerializer");
}
String XmlSerializer::ToXml(Serializable* obj, Collections::Generic::List<unsigned long long>& _childPtrs) {
unsigned long long hash = 0;
String res;
size_t len;
//Serializable* seri = nullptr;
/*if(std::is_same<T, Serializable*>::value) {
seri = (Serializable*) obj;
} else {
seri = static_cast<Serializable*>(&obj);
}*/
len = obj->AttrLen();
res = "<" + obj->Name() + " ID=\"" + obj->getHashCode() + "\">";
for(size_t i = 0; i < len; i++) {
SerializableAttribute& t = obj->Attribute(i);
// Get Values
String attrName = t.AttributeName();
Object& val = t.Member();
// Check Serializable
Serializable* child = dynamic_cast<Serializable*>(&val);
if(child == nullptr) {
// Just serialize
res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">";
res += val.ToString();
res += "</" + attrName + ">";
} else {
// Is Serializable
hash = child->getHashCode();
if(_childPtrs.Contains(hash)) {
// Just add a reference
res += "<" + attrName + " ref=\"" + hash + "\"/>";
} else {
// Call serialize
_childPtrs.Add(hash);
res += "<" + attrName + " type=\"" + val.GetTypeString() + "\">";
res += ToXml(child, _childPtrs);
res += "</" + attrName + ">";
}
}
}
res += "</" + obj->Name() + ">\r\n";
return res;
}
}
} | OperationDarkside/ProjectDNC | DNC/XmlSerializer.cpp | C++ | gpl-3.0 | 1,718 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>AgeDetectedIssueCodeのJavaクラス。
*
* <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
* <p>
* <pre>
* <simpleType name="AgeDetectedIssueCode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="AGE"/>
* <enumeration value="DOSEHINDA"/>
* <enumeration value="DOSELINDA"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "AgeDetectedIssueCode")
@XmlEnum
public enum AgeDetectedIssueCode {
AGE,
DOSEHINDA,
DOSELINDA;
public String value() {
return name();
}
public static AgeDetectedIssueCode fromValue(String v) {
return valueOf(v);
}
}
| ricecakesoftware/CommunityMedicalLink | ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/AgeDetectedIssueCode.java | Java | gpl-3.0 | 913 |
---
title: Puppet ça pête !
author: Deimos
type: post
date: 2010-06-24T14:50:45+00:00
url: /2010/06/24/puppet-ca-pete/
image: /images/Puppet-short.png
thumbnailImage: /thumbnails/Puppet-short.png
thumbnailImagePosition: left
categories:
- Developement
- Hi-Tech
- Linux
- OpenBSD
- Solaris
tags:
- Developement
- Hi-Tech
- Linux
- OpenBSD
- Solaris
---

Et bah voilà ! Ca y est je vais passer mon puppet en prod au taf. Franchement c'est vraiment bien. Très long à mettre en place mais pour après arrêter les taches répétitives sur les serveurs ! Ça vaut le coup surtout si on a une belle ferme de machines.
J'ai donc prévu [une petite doc](http://wiki.deimos.fr/Puppet_:_Solution_de_gestion_de_fichier_de_configuration) à cet effet pour ceux que ça intéresse. J'ai été aidé de Luc (un presta qui depuis a fait quelques commentaires sur le blog) et ai enrichi un peu le tout.
Avec les besoins de ma boite, j'ai du développer un petit truc permettant de faire du push "easy" avec Puppet. J'ai donc développé [puppet_push](http://www.deimos.fr/gitweb/?p=puppet_push.git;a=tree) qui est encore en phase bêta mais qui fonctionne plutôt pas mal pour le moment.
Hier j'ai eu quelques mails houleux avec Nico (un mec du GCU) se plaignant de ne pas assez le citer lorsque je lui prenais des infos sur son blog. Donc on va la faire officielle : MERCI NICO !
| deimosfr/blog | content/post/2010-06-24-puppet-ca-pete.md | Markdown | gpl-3.0 | 1,444 |
<?php
/**
* @package Arastta eCommerce
* @copyright Copyright (C) 2015 Arastta Association. All rights reserved. (arastta.org)
* @license GNU General Public License version 3; see LICENSE.txt
*/
// Heading
$_['heading_title'] = 'Produktegenskaper - Grupper';
// Text
$_['text_success'] = 'Endringer ble vellykket lagret.';
$_['text_list'] = 'Liste';
$_['text_add'] = 'Legg til';
$_['text_edit'] = 'Endre';
// Column
$_['column_name'] = 'Navn';
$_['column_sort_order'] = 'Sortering';
$_['column_action'] = 'Valg';
// Entry
$_['entry_name'] = 'Navn';
$_['entry_sort_order'] = 'Sortering';
// Error
$_['error_permission'] = 'Du har ikke rettigheter til å utføre valgte handling.';
$_['error_name'] = 'Navn må inneholde mellom 3 og 64 tegn.';
$_['error_attribute'] = 'Denne gruppen kan ikke slettes ettersom den er tilknyttet %s produktegenskaper.';
$_['error_product'] = 'Denne gruppen kan ikke slettes ettersom den er tilknyttet %s produkter.'; | interspiresource/interspire | admin/language/nb-NO/catalog/attribute_group.php | PHP | gpl-3.0 | 1,022 |
code --install-extension brian-anders.sublime-duplicate-text
code --install-extension britesnow.vscode-toggle-quotes
code --install-extension dbaeumer.vscode-eslint
code --install-extension dinhlife.gruvbox
code --install-extension eamodio.gitlens
code --install-extension editorconfig.editorconfig
code --install-extension esbenp.prettier-vscode
code --install-extension malmaud.tmux
code --install-extension marp-team.marp-vscode
code --install-extension mikestead.dotenv
code --install-extension pnp.polacode
code --install-extension sleistner.vscode-fileutils
code --install-extension wmaurer.change-case
| huntie/dotfiles | vscode/install.sh | Shell | gpl-3.0 | 609 |
<?php
/**
* @package Joomla.Platform
* @subpackage Data
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* JDataSet is a collection class that allows the developer to operate on a set of JData objects as if they were in a
* typical PHP array.
*
* @since 12.3
*/
class JDataSet implements JDataDumpable, ArrayAccess, Countable, Iterator
{
/**
* The current position of the iterator.
*
* @var integer
* @since 12.3
*/
private $_current = false;
/**
* The iterator objects.
*
* @var array
* @since 12.3
*/
private $_objects = array();
/**
* The class constructor.
*
* @param array $objects An array of JData objects to bind to the data set.
*
* @since 12.3
* @throws InvalidArgumentException if an object is not an instance of JData.
*/
public function __construct(array $objects = array())
{
// Set the objects.
$this->_initialise($objects);
}
/**
* The magic call method is used to call object methods using the iterator.
*
* Example: $array = $objectList->foo('bar');
*
* The object list will iterate over its objects and see if each object has a callable 'foo' method.
* If so, it will pass the argument list and assemble any return values. If an object does not have
* a callable method no return value is recorded.
* The keys of the objects and the result array are maintained.
*
* @param string $method The name of the method called.
* @param array $arguments The arguments of the method called.
*
* @return array An array of values returned by the methods called on the objects in the data set.
*
* @since 12.3
*/
public function __call($method, $arguments = array())
{
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $key => $object)
{
// Create the object callback.
$callback = array($object, $method);
// Check if the callback is callable.
if (is_callable($callback))
{
// Call the method for the object.
$return[$key] = call_user_func_array($callback, $arguments);
}
}
return $return;
}
/**
* The magic get method is used to get a list of properties from the objects in the data set.
*
* Example: $array = $dataSet->foo;
*
* This will return a column of the values of the 'foo' property in all the objects
* (or values determined by custom property setters in the individual JData's).
* The result array will contain an entry for each object in the list (compared to __call which may not).
* The keys of the objects and the result array are maintained.
*
* @param string $property The name of the data property.
*
* @return array An associative array of the values.
*
* @since 12.3
*/
public function __get($property)
{
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $key => $object)
{
// Get the property.
$return[$key] = $object->$property;
}
return $return;
}
/**
* The magic isset method is used to check the state of an object property using the iterator.
*
* Example: $array = isset($objectList->foo);
*
* @param string $property The name of the property.
*
* @return boolean True if the property is set in any of the objects in the data set.
*
* @since 12.3
*/
public function __isset($property)
{
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $object)
{
// Check the property.
$return[] = isset($object->$property);
}
return in_array(true, $return, true) ? true : false;
}
/**
* The magic set method is used to set an object property using the iterator.
*
* Example: $objectList->foo = 'bar';
*
* This will set the 'foo' property to 'bar' in all of the objects
* (or a value determined by custom property setters in the JData).
*
* @param string $property The name of the property.
* @param mixed $value The value to give the data property.
*
* @return void
*
* @since 12.3
*/
public function __set($property, $value)
{
// Iterate through the objects.
foreach ($this->_objects as $object)
{
// Set the property.
$object->$property = $value;
}
}
/**
* The magic unset method is used to unset an object property using the iterator.
*
* Example: unset($objectList->foo);
*
* This will unset all of the 'foo' properties in the list of JData's.
*
* @param string $property The name of the property.
*
* @return void
*
* @since 12.3
*/
public function __unset($property)
{
// Iterate through the objects.
foreach ($this->_objects as $object)
{
unset($object->$property);
}
}
/**
* Gets the number of data objects in the set.
*
* @return integer The number of objects.
*
* @since 12.3
*/
public function count()
{
return count($this->_objects);
}
/**
* Clears the objects in the data set.
*
* @return JDataSet Returns itself to allow chaining.
*
* @since 12.3
*/
public function clear()
{
$this->_objects = array();
$this->rewind();
return $this;
}
/**
* Get the current data object in the set.
*
* @return JData The current object, or false if the array is empty or the pointer is beyond the end of the elements.
*
* @since 12.3
*/
public function current()
{
return is_scalar($this->_current) ? $this->_objects[$this->_current] : false;
}
/**
* Dumps the data object in the set, recursively if appropriate.
*
* @param integer $depth The maximum depth of recursion (default = 3).
* For example, a depth of 0 will return a stdClass with all the properties in native
* form. A depth of 1 will recurse into the first level of properties only.
* @param SplObjectStorage $dumped An array of already serialized objects that is used to avoid infinite loops.
*
* @return array An associative array of the date objects in the set, dumped as a simple PHP stdClass object.
*
* @see JData::dump()
* @since 12.3
*/
public function dump($depth = 3, SplObjectStorage $dumped = null)
{
// Check if we should initialise the recursion tracker.
if ($dumped === null)
{
$dumped = new SplObjectStorage;
}
// Add this object to the dumped stack.
$dumped->attach($this);
$objects = array();
// Make sure that we have not reached our maximum depth.
if ($depth > 0)
{
// Handle JSON serialization recursively.
foreach ($this->_objects as $key => $object)
{
$objects[$key] = $object->dump($depth, $dumped);
}
}
return $objects;
}
/**
* Gets the data set in a form that can be serialised to JSON format.
*
* Note that this method will not return an associative array, otherwise it would be encoded into an object.
* JSON decoders do not consistently maintain the order of associative keys, whereas they do maintain the order of arrays.
*
* @param mixed $serialized An array of objects that have already been serialized that is used to infinite loops
* (null on first call).
*
* @return array An array that can be serialised by json_encode().
*
* @since 12.3
*/
public function jsonSerialize($serialized = null)
{
// Check if we should initialise the recursion tracker.
if ($serialized === null)
{
$serialized = array();
}
// Add this object to the serialized stack.
$serialized[] = spl_object_hash($this);
$return = array();
// Iterate through the objects.
foreach ($this->_objects as $object)
{
// Call the method for the object.
$return[] = $object->jsonSerialize($serialized);
}
return $return;
}
/**
* Gets the key of the current object in the iterator.
*
* @return scalar The object key on success; null on failure.
*
* @since 12.3
*/
public function key()
{
return $this->_current;
}
/**
* Gets the array of keys for all the objects in the iterator (emulates array_keys).
*
* @return array The array of keys
*
* @since 12.3
*/
public function keys()
{
return array_keys($this->_objects);
}
/**
* Advances the iterator to the next object in the iterator.
*
* @return void
*
* @since 12.3
*/
public function next()
{
// Get the object offsets.
$keys = $this->keys();
// Check if _current has been set to false but offsetUnset.
if ($this->_current === false && isset($keys[0]))
{
// This is a special case where offsetUnset was used in a foreach loop and the first element was unset.
$this->_current = $keys[0];
}
else
{
// Get the current key.
$position = array_search($this->_current, $keys);
// Check if there is an object after the current object.
if ($position !== false && isset($keys[$position + 1]))
{
// Get the next id.
$this->_current = $keys[$position + 1];
}
else
{
// That was the last object or the internal properties have become corrupted.
$this->_current = null;
}
}
}
/**
* Checks whether an offset exists in the iterator.
*
* @param mixed $offset The object offset.
*
* @return boolean True if the object exists, false otherwise.
*
* @since 12.3
*/
public function offsetExists($offset)
{
return isset($this->_objects[$offset]);
}
/**
* Gets an offset in the iterator.
*
* @param mixed $offset The object offset.
*
* @return JData The object if it exists, null otherwise.
*
* @since 12.3
*/
public function offsetGet($offset)
{
return isset($this->_objects[$offset]) ? $this->_objects[$offset] : null;
}
/**
* Sets an offset in the iterator.
*
* @param mixed $offset The object offset.
* @param JData $object The object object.
*
* @return void
*
* @since 12.3
* @throws InvalidArgumentException if an object is not an instance of JData.
*/
public function offsetSet($offset, $object)
{
// Check if the object is a JData object.
if (!($object instanceof JData))
{
throw new InvalidArgumentException(sprintf('%s("%s", *%s*)', __METHOD__, $offset, gettype($object)));
}
// Set the offset.
$this->_objects[$offset] = $object;
}
/**
* Unsets an offset in the iterator.
*
* @param mixed $offset The object offset.
*
* @return void
*
* @since 12.3
*/
public function offsetUnset($offset)
{
if (!$this->offsetExists($offset))
{
// Do nothing if the offset does not exist.
return;
}
// Check for special handling of unsetting the current position.
if ($offset == $this->_current)
{
// Get the current position.
$keys = $this->keys();
$position = array_search($this->_current, $keys);
// Check if there is an object before the current object.
if ($position > 0)
{
// Move the current position back one.
$this->_current = $keys[$position - 1];
}
else
{
// We are at the start of the keys AND let's assume we are in a foreach loop and `next` is going to be called.
$this->_current = false;
}
}
unset($this->_objects[$offset]);
}
/**
* Rewinds the iterator to the first object.
*
* @return void
*
* @since 12.3
*/
public function rewind()
{
// Set the current position to the first object.
if (empty($this->_objects))
{
$this->_current = false;
}
else
{
$keys = $this->keys();
$this->_current = array_shift($keys);
}
}
/**
* Validates the iterator.
*
* @return boolean True if valid, false otherwise.
*
* @since 12.3
*/
public function valid()
{
// Check the current position.
if (!is_scalar($this->_current) || !isset($this->_objects[$this->_current]))
{
return false;
}
return true;
}
/**
* Initialises the list with an array of objects.
*
* @param array $input An array of objects.
*
* @return void
*
* @since 12.3
* @throws InvalidArgumentException if an object is not an instance of JData.
*/
private function _initialise(array $input = array())
{
foreach ($input as $key => $object)
{
if (!is_null($object))
{
$this->offsetSet($key, $object);
}
}
$this->rewind();
}
}
| MasiaArmato/coplux | libraries/joomla/data/set.php | PHP | gpl-3.0 | 12,869 |
package medium_challenges;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class BenderSolution {
public static void main(String args[]) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int R = in.nextInt();
int C = in.nextInt();
in.nextLine();
List<Node> teleports = new ArrayList<>();
Node start = null;
// Create (x,y) map and store starting point
char[][] map = new char[C][R];
for (int y = 0; y < R; y++) {
String row = in.nextLine();
for (int x = 0; x < C; x++){
char item = row.charAt(x);
map[x][y] = item;
if (item == '@') {
start = new Node(x,y);
}
if (item == 'T') {
teleports.add(new Node(x,y));
}
}
}
// Create new robot with map
Bender bender = new Bender(start, map, teleports);
// Limit iterations
boolean circular = false;
final int MAX_ITERATIONS = 200;
// Collect all moves.
List<String> moves = new ArrayList<>();
while (bender.alive && !circular) {
moves.add(bender.move());
circular = moves.size() > MAX_ITERATIONS;
}
// Output Result
if (circular) System.out.println("LOOP");
else {
for (String s: moves) System.out.println(s);
}
}
/** Simple object to store coordinate pair */
private static class Node {
final int x, y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
/** Object to store state and behavior of Bender */
private static class Bender {
Node position;
char[][] map;
boolean directionToggle;
boolean alive;
Direction facing;
boolean beerToggle;
List<Node> teleports;
/** Direction enum includes the ability to find next node based on direction Bender is facing.
*/
private enum Direction {
SOUTH(0, 1), EAST(1, 0), NORTH(0, -1), WEST(-1, 0);
private int dx;
private int dy;
Direction (int dx, int dy) {
this.dx = dx;
this.dy = dy;
}
public Node newNode(Node original) {
return new Node(original.x + dx, original.y + dy);
}
public Direction nextDirection(boolean toggle) {
if (toggle) {
switch (this) {
case SOUTH: return EAST;
case EAST: return NORTH;
default: return WEST;
}
} else {
switch (this) {
case WEST: return NORTH;
case NORTH: return EAST;
default: return SOUTH;
}
}
}
}
public Bender(Node start, char[][] map, List<Node> teleports) {
this.position = start;
this.map = map;
this.alive = true;
this.facing = Direction.SOUTH;
this.directionToggle = true;
this.beerToggle = false;
this.teleports = teleports;
}
/** Updates the state of bender.
Returns direction of the move.
*/
public String move() {
char currentContent = map[position.x][position.y];
// Check for Teleporters
if (currentContent == 'T') {
position = (teleports.get(0).equals(position)) ? teleports.get(1) : teleports.get(0);
}
// Check for immediate move command
if ((""+currentContent).matches("[NESW]")) {
switch (currentContent) {
case 'N': facing = Direction.NORTH; position = facing.newNode(position); return Direction.NORTH.toString();
case 'W': facing = Direction.WEST; position = facing.newNode(position); return Direction.WEST.toString();
case 'S': facing = Direction.SOUTH; position = facing.newNode(position); return Direction.SOUTH.toString();
default: facing = Direction.EAST; position = facing.newNode(position); return Direction.EAST.toString();
}
}
// Check for inversion
if (currentContent == 'I') {
directionToggle = !directionToggle;
}
// Check for beer
if (currentContent == 'B') {
beerToggle = !beerToggle;
}
// Trial next possibility
Node trial = facing.newNode(position);
char content = map[trial.x][trial.y];
// Check if Bender dies
if (content == '$') {
alive = false;
return facing.toString();
}
// Check for beer power to remove X barrier
if (beerToggle && content == 'X') {
content = ' ';
map[trial.x][trial.y] = ' ';
}
// Check for Obstacles
boolean initialCheck = true;
while (content == 'X' || content == '#') {
// Check for obstacles
if (content == 'X' || content == '#') {
if (initialCheck) {
facing = directionToggle ? Direction.SOUTH : Direction.WEST;
initialCheck = false;
} else {
facing = facing.nextDirection(directionToggle);
}
}
// Update position and facing
trial = facing.newNode(position);
content = map[trial.x][trial.y];
}
// If we made it to this point, it's okay to move bender
position = facing.newNode(position);
if (content == '$') alive = false;
return facing.toString();
}
}
} | workwelldone/bright-eyes | src/medium_challenges/BenderSolution.java | Java | gpl-3.0 | 5,937 |
package me.zsj.moment.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
/**
* @author zsj
*/
public class CircleTransform extends BitmapTransformation {
public CircleTransform(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squared.recycle();
return result;
}
@Override public String getId() {
return getClass().getName();
}
}
| Assassinss/Moment | app/src/main/java/me/zsj/moment/utils/CircleTransform.java | Java | gpl-3.0 | 1,691 |
/*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OUTDOOR_PVP_HP_
#define OUTDOOR_PVP_HP_
#include "OutdoorPvP.h"
#define OutdoorPvPHPBuffZonesNum 6
// HP, citadel, ramparts, blood furnace, shattered halls, mag's lair
const uint32 OutdoorPvPHPBuffZones[OutdoorPvPHPBuffZonesNum] = { 3483, 3563, 3562, 3713, 3714, 3836 };
enum OutdoorPvPHPSpells
{
AlliancePlayerKillReward = 32155,
HordePlayerKillReward = 32158,
AllianceBuff = 32071,
HordeBuff = 32049
};
enum OutdoorPvPHPTowerType
{
HP_TOWER_BROKEN_HILL = 0,
HP_TOWER_OVERLOOK = 1,
HP_TOWER_STADIUM = 2,
HP_TOWER_NUM = 3
};
const uint32 HP_CREDITMARKER[HP_TOWER_NUM] = {19032, 19028, 19029};
const uint32 HP_CapturePointEvent_Enter[HP_TOWER_NUM] = {11404, 11396, 11388};
const uint32 HP_CapturePointEvent_Leave[HP_TOWER_NUM] = {11403, 11395, 11387};
enum OutdoorPvPHPWorldStates
{
HP_UI_TOWER_DISPLAY_A = 0x9ba,
HP_UI_TOWER_DISPLAY_H = 0x9b9,
HP_UI_TOWER_COUNT_H = 0x9ae,
HP_UI_TOWER_COUNT_A = 0x9ac,
HP_UI_TOWER_SLIDER_N = 2475,
HP_UI_TOWER_SLIDER_POS = 2474,
HP_UI_TOWER_SLIDER_DISPLAY = 2473
};
const uint32 HP_MAP_N[HP_TOWER_NUM] = {0x9b5, 0x9b2, 0x9a8};
const uint32 HP_MAP_A[HP_TOWER_NUM] = {0x9b3, 0x9b0, 0x9a7};
const uint32 HP_MAP_H[HP_TOWER_NUM] = {0x9b4, 0x9b1, 0x9a6};
const uint32 HP_TowerArtKit_A[HP_TOWER_NUM] = {65, 62, 67};
const uint32 HP_TowerArtKit_H[HP_TOWER_NUM] = {64, 61, 68};
const uint32 HP_TowerArtKit_N[HP_TOWER_NUM] = {66, 63, 69};
const go_type HPCapturePoints[HP_TOWER_NUM] =
{
{182175, 530, -471.462f, 3451.09f, 34.6432f, 0.174533f, 0.0f, 0.0f, 0.087156f, 0.996195f}, // 0 - Broken Hill
{182174, 530, -184.889f, 3476.93f, 38.205f, -0.017453f, 0.0f, 0.0f, 0.008727f, -0.999962f}, // 1 - Overlook
{182173, 530, -290.016f, 3702.42f, 56.6729f, 0.034907f, 0.0f, 0.0f, 0.017452f, 0.999848f} // 2 - Stadium
};
const go_type HPTowerFlags[HP_TOWER_NUM] =
{
{183514, 530, -467.078f, 3528.17f, 64.7121f, 3.14159f, 0.0f, 0.0f, 1.0f, 0.0f}, // 0 broken hill
{182525, 530, -187.887f, 3459.38f, 60.0403f, -3.12414f, 0.0f, 0.0f, 0.999962f, -0.008727f}, // 1 overlook
{183515, 530, -289.610f, 3696.83f, 75.9447f, 3.12414f, 0.0f, 0.0f, 0.999962f, 0.008727f} // 2 stadium
};
class OPvPCapturePointHP : public OPvPCapturePoint
{
public:
OPvPCapturePointHP(OutdoorPvP* pvp, OutdoorPvPHPTowerType type);
void ChangeState();
void SendChangePhase();
void FillInitialWorldStates(WorldPacket & data);
// used when player is activated/inactivated in the area
bool HandlePlayerEnter(Player* player);
void HandlePlayerLeave(Player* player);
private:
OutdoorPvPHPTowerType m_TowerType;
};
class OutdoorPvPHP : public OutdoorPvP
{
public:
OutdoorPvPHP();
bool SetupOutdoorPvP();
void HandlePlayerEnterZone(Player* player, uint32 zone);
void HandlePlayerLeaveZone(Player* player, uint32 zone);
bool Update(uint32 diff);
void FillInitialWorldStates(WorldPacket &data);
void SendRemoveWorldStates(Player* player);
void HandleKillImpl(Player* player, Unit* killed);
uint32 GetAllianceTowersControlled() const;
void SetAllianceTowersControlled(uint32 count);
uint32 GetHordeTowersControlled() const;
void SetHordeTowersControlled(uint32 count);
private:
// how many towers are controlled
uint32 m_AllianceTowersControlled;
uint32 m_HordeTowersControlled;
};
#endif
| Sworken/RagSWC | src/server/scripts/OutdoorPvP/OutdoorPvPHP.h | C | gpl-3.0 | 4,238 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>reordc_c</TITLE>
</HEAD>
<BODY style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);">
<A name="TOP"></A>
<table style="text-align: left; margin-left: auto; margin-right: auto; width: 800px;"
border="0" cellpadding="5" cellspacing="2">
<tbody>
<tr>
<td style="background-color: rgb(153, 153, 153); vertical-align: middle; text-align: center;">
<div align="right">
<small><small><a href="index.html">Index Page</a></small></small>
</div>
<b>reordc_c</b> </td>
</tr>
<tr>
<td style="vertical-align: top;">
<small><div align="center">
<A HREF="index.html#A">A</A>
<A HREF="index.html#B">B</A>
<A HREF="index.html#C">C</A>
<A HREF="index.html#D">D</A>
<A HREF="index.html#E">E</A>
<A HREF="index.html#F">F</A>
<A HREF="index.html#G">G</A>
<A HREF="index.html#H">H</A>
<A HREF="index.html#I">I</A>
<A HREF="index.html#J">J</A>
<A HREF="index.html#K">K</A>
<A HREF="index.html#L">L</A>
<A HREF="index.html#M">M</A>
<A HREF="index.html#N">N</A>
<A HREF="index.html#O">O</A>
<A HREF="index.html#P">P</A>
<A HREF="index.html#Q">Q</A>
<A HREF="index.html#R">R</A>
<A HREF="index.html#S">S</A>
<A HREF="index.html#T">T</A>
<A HREF="index.html#U">U</A>
<A HREF="index.html#V">V</A>
<A HREF="index.html#W">W</A>
<A HREF="index.html#X">X</A>
</div></small>
<br>
<table style="text-align: left; width: 60%; margin-left: auto; margin-right: auto;"
border="0" cellspacing="2" cellpadding="2">
<tbody>
<tr>
<td style="width: 33%; text-align: center;">
<small>
<a href="#Procedure">Procedure<br></a>
<a href="#Abstract">Abstract<br></a>
<a href="#Required_Reading">Required_Reading<br></a>
<a href="#Keywords">Keywords<br></a>
<a href="#Brief_I/O">Brief_I/O<br></a>
<a href="#Detailed_Input">Detailed_Input<br></a>
</small>
</td>
<td style="vertical-align: top; width: 33%; text-align: center;">
<small> <a href="#Detailed_Output">Detailed_Output<br></a>
<a href="#Parameters">Parameters<br></a>
<a href="#Exceptions">Exceptions<br></a>
<a href="#Files">Files<br></a>
<a href="#Particulars">Particulars<br></a>
<a href="#Examples">Examples<br></a>
</small>
</td>
<td style="vertical-align: top; width: 33%; text-align: center;">
<small> <a href="#Restrictions">Restrictions<br></a>
<a href="#Literature_References">Literature_References<br></a>
<a href="#Author_and_Institution">Author_and_Institution<br></a>
<a href="#Version">Version<br></a>
<a href="#Index_Entries">Index_Entries<br></a>
</small>
</td>
</tr>
</tbody>
</table>
<h4><a name="Procedure">Procedure</a></h4>
<PRE>
void reordc_c ( ConstSpiceInt * iorder,
SpiceInt ndim,
SpiceInt lenvals,
void * array )
</PRE>
<h4><a name="Abstract">Abstract</a></h4>
<PRE>
Re-order the elements of an array of character strings
according to a given order vector.
</PRE>
<h4><a name="Required_Reading">Required_Reading</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Keywords">Keywords</a></h4>
<PRE>
ARRAY, SORT
</PRE>
<h4><a name="Brief_I/O">Brief_I/O</a></h4>
<PRE>
VARIABLE I/O DESCRIPTION
-------- --- --------------------------------------------------
iorder I Order vector to be used to re-order array.
ndim I Dimension of array.
lenvals I String length.
array I/O Array to be re-ordered.
</PRE>
<h4><a name="Detailed_Input">Detailed_Input</a></h4>
<PRE>
iorder is the order vector to be used to re-order the input
array. The first element of iorder is the index of
the first item of the re-ordered array, and so on.
Note that the order imposed by <b>reordc_c</b> is not the
same order that would be imposed by a sorting
routine. In general, the order vector will have
been created (by one of the order routines) for
a related array, as illustrated in the example below.
The elements of iorder range from zero to ndim-1.
ndim is the number of elements in the input array.
lenvals is the declared length of the strings in the input
string array, including null terminators. The input
array should be declared with dimension
[ndim][lenvals]
array on input, is an array containing some number of
elements in unspecified order.
</PRE>
<h4><a name="Detailed_Output">Detailed_Output</a></h4>
<PRE>
array on output, is the same array, with the elements
in re-ordered as specified by iorder.
</PRE>
<h4><a name="Parameters">Parameters</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Exceptions">Exceptions</a></h4>
<PRE>
1) If the input string array pointer is null, the error
SPICE(NULLPOINTER) will be signaled.
2) If the input array string's length is less than 2, the error
SPICE(STRINGTOOSHORT) will be signaled.
3) If memory cannot be allocated to create a Fortran-style version of
the input order vector, the error SPICE(MALLOCFAILED) is signaled.
4) If ndim < 2, this routine executes a no-op. This case is
not an error.
</PRE>
<h4><a name="Files">Files</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Particulars">Particulars</a></h4>
<PRE>
<b>reordc_c</b> uses a cyclical algorithm to re-order the elements of
the array in place. After re-ordering, element iorder[0] of
the input array is the first element of the output array,
element iorder[1] of the input array is the second element of
the output array, and so on.
The order vector used by <b>reordc_c</b> is typically created for
a related array by one of the order*_c routines, as shown in
the example below.
</PRE>
<h4><a name="Examples">Examples</a></h4>
<PRE>
In the following example, the order*_c and reord*_c routines are
used to sort four related arrays (containing the names,
masses, integer ID codes, and visual magnitudes for a group
of satellites). This is representative of the typical use of
these routines.
#include "SpiceUsr.h"
.
.
.
/.
Sort the object arrays by name.
./
<a href="orderc_c.html">orderc_c</a> ( namlen, names, n, iorder );
<b>reordc_c</b> ( iorder, n, namlen, names );
<a href="reordd_c.html">reordd_c</a> ( iorder, n, masses );
<a href="reordi_c.html">reordi_c</a> ( iorder, n, codes );
<a href="reordd_c.html">reordd_c</a> ( iorder, n, vmags );
</PRE>
<h4><a name="Restrictions">Restrictions</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Literature_References">Literature_References</a></h4>
<PRE>
None.
</PRE>
<h4><a name="Author_and_Institution">Author_and_Institution</a></h4>
<PRE>
N.J. Bachman (JPL)
W.L. Taber (JPL)
I.M. Underwood (JPL)
</PRE>
<h4><a name="Version">Version</a></h4>
<PRE>
-CSPICE Version 1.0.0, 10-JUL-2002 (NJB) (WLT) (IMU)
</PRE>
<h4><a name="Index_Entries">Index_Entries</a></h4>
<PRE>
reorder a character array
</PRE>
</td>
</tr>
</tbody>
</table>
<pre>Tue Jul 15 14:31:41 2014</pre>
</body>
</html>
| seap-udea/GravRay | util/doc/cspice/reordc_c.html | HTML | gpl-3.0 | 7,956 |
/*
Rocrail - Model Railroad Software
Copyright (C) 2002-2014 Rob Versluis, Rocrail.net
This program is free software; you can redistribute it and/or
as published by the Free Software Foundation; either version 2
modify it under the terms of the GNU General Public License
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef __bidibidentdlg__
#define __bidibidentdlg__
/**
@file
Subclass of BidibIdentDlgGen, which is generated by wxFormBuilder.
*/
#include "bidibidendlggen.h"
#include "rocs/public/node.h"
#include "rocs/public/list.h"
#include "rocs/public/map.h"
#include "rocs/public/mutex.h"
//// end generated include
/** Implementing BidibIdentDlgGen */
class BidibIdentDlg : public BidibIdentDlgGen
{
iONode node;
iONode bidibnode;
iOList nodeList;
iOMap nodeMap;
iOMap nodePathMap;
iONode m_SelectedBidibNode;
iONode m_ProductsNode;
iOMap m_ProductsMap;
int macro;
int macroline;
int macrosize;
int macrolevel;
int macroparam;
bool macrosave;
bool macroapply;
int configL;
int configR;
int configV;
int configS;
int uid;
char* www;
iOMutex servoSetMutex;
bool eventUpdate;
wxTreeItemId findTreeItem( const wxTreeItemId& root, const wxString& text);
int getLevel(const char* path, int* n, int* o, int* p, char** key, char** parentkey);
wxTreeItemId addTreeChild( const wxTreeItemId& root, iONode bidibnode);
void handleFeature(iONode node);
void clearFeatureList();
void handleMacro(iONode node);
void handleAccessory(iONode node);
iONode findNodeByUID( const char* uid);
protected:
// Handlers for BidibIdentDlgGen events.
void onClose( wxCloseEvent& event );
void onCancel( wxCommandEvent& event );
void onOK( wxCommandEvent& event );
void onHelp( wxCommandEvent& event );
void onTreeSelChanged( wxTreeEvent& event );
void onBeginDrag( wxTreeEvent& event );
void onItemActivated( wxTreeEvent& event );
void onItemRightClick( wxTreeEvent& event );
void onMenu( wxCommandEvent& event );
void onFeatureSelect( wxCommandEvent& event );
void onFeaturesGet( wxCommandEvent& event );
void onFeatureSet( wxCommandEvent& event );
void onServoLeft( wxScrollEvent& event );
void onServoRight( wxScrollEvent& event );
void onServoSpeed( wxScrollEvent& event );
void onServoPort( wxSpinEvent& event );
void onServoLeftTest( wxCommandEvent& event );
void onServoRightTest( wxCommandEvent& event );
void onServoGet( wxCommandEvent& event );
void onPortSet( wxCommandEvent& event );
void onConfigL( wxSpinEvent& event );
void onConfigR( wxSpinEvent& event );
void onConfigV( wxSpinEvent& event );
void onConfigS( wxSpinEvent& event );
void onServoReserved( wxScrollEvent& event );
void onPortType( wxCommandEvent& event );
void onConfigLtxt( wxCommandEvent& event );
void onConfigRtxt( wxCommandEvent& event );
void onConfigVtxt( wxCommandEvent& event );
void onConfigStxt( wxCommandEvent& event );
void onSelectUpdateFile( wxCommandEvent& event );
void onUpdateStart( wxCommandEvent& event );
void onServoSet(bool overwrite=false);
void onPageChanged( wxNotebookEvent& event );
void onMacroList( wxCommandEvent& event );
void onMacroLineSelected( wxGridEvent& event );
void onMacroApply( wxCommandEvent& event );
void onMacroReload( wxCommandEvent& event );
void onMacroSave( wxCommandEvent& event );
void onMacroEveryMinute( wxCommandEvent& event );
void onMacroExport( wxCommandEvent& event );
void onMacroImport( wxCommandEvent& event );
void onMacroSaveMacro( wxCommandEvent& event );
void onMacroDeleteMacro( wxCommandEvent& event );
void onMacroRestoreMacro( wxCommandEvent& event );
void onMacroTest( wxCommandEvent& event );
void onVendorCVEnable( wxCommandEvent& event );
void onVendorCVDisable( wxCommandEvent& event );
void onVendorCVGet( wxCommandEvent& event );
void onVendorCVSet( wxCommandEvent& event );
void onAccessoryOnTest( wxCommandEvent& event );
void onAccessoryOffTest( wxCommandEvent& event );
void onAccessoryReadOptions( wxCommandEvent& event );
void onAccessoryWriteOptions( wxCommandEvent& event );
void onAccessoryReadMacroMap( wxCommandEvent& event );
void onAccessoryWriteMacroMap( wxCommandEvent& event );
void onLeftLogo( wxMouseEvent& event );
void onProductName( wxMouseEvent& event );
int getProductID(int uid);
void onReport( wxCommandEvent& event );
void onUsernameSet( wxCommandEvent& event );
public:
/** Constructor */
BidibIdentDlg( wxWindow* parent );
//// end generated class members
BidibIdentDlg( wxWindow* parent, iONode node );
~BidibIdentDlg();
void event(iONode node);
void initLabels();
void initValues();
void initProducts();
const char* GetProductName(int vid, int pid, char** www);
};
#endif // __bidibidentdlg__
| KlausMerkert/FreeRail | rocview/dialogs/decoders/bidibidentdlg.h | C | gpl-3.0 | 5,389 |
package clientdata.visitors;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.HashMap;
import java.util.Map;
import org.apache.mina.core.buffer.IoBuffer;
import clientdata.VisitorInterface;
public class SlotDefinitionVisitor implements VisitorInterface {
public static class SlotDefinition {
public String slotName;
public byte global;
public byte canMod;
public byte exclusive;
public String hardpointName;
public int unk1;
}
public SlotDefinitionVisitor() {
definitions = new HashMap<String, SlotDefinition>();
}
private Map<String, SlotDefinition> definitions;
public Map<String, SlotDefinition> getDefinitions() {
return definitions;
}
@Override
public void parseData(String nodename, IoBuffer data, int depth, int size) throws Exception {
if(nodename.endsWith("DATA")) {
CharsetDecoder cd = Charset.forName("US-ASCII").newDecoder();
while(data.hasRemaining()) {
SlotDefinition next = new SlotDefinition();
next.slotName = data.getString(cd);
cd.reset();
next.global = data.get();
next.canMod = data.get();
next.exclusive = data.get();
next.hardpointName = data.getString(cd);
cd.reset();
next.unk1 = data.getInt();
definitions.put(next.slotName, next);
}
}
}
@Override
public void notifyFolder(String nodeName, int depth) throws Exception {}
}
| swgopenge/openge | src/clientdata/visitors/SlotDefinitionVisitor.java | Java | gpl-3.0 | 1,410 |
package fr.eurecom.senml.entity;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
@PersistenceCapable
public class ContactTest {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String firstName;
@Persistent
private String lastName;
@Persistent
private String email;
public ContactTest(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getEmail() {return email;}
public Key getKey() {return key;}
}
| mspublic/openair4G-mirror | targets/PROJECTS/SPECTRA/DEMO_SPECTRA/spectra_demo_src/CRM/server-gae/restlet/src/fr/eurecom/senml/entity/ContactTest.java | Java | gpl-3.0 | 917 |
<ion-header>
<ion-navbar color="secondary">
<button ion-button menuToggle>
<ion-icon color="primary" name="menu"></ion-icon>
</button>
<ion-title color="primary">Gourmet Calculator</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="calc">
<form #calcForm="ngForm" (ngSubmit)="onSubmit()">
<ion-item padding-top class="noBg">
<ion-label color="secondary" stacked class="amountLabel">Enter the amount (x100) <span padding-left class="preview" [hidden]="!amount>0 || calcForm.form.invalid" stacked>{{amount/100 | currency:currency:true:'1.2'}}</span></ion-label>
<!-- better tel because it allows to set maxlength -->
<ion-input type="tel" pattern="[0-9]+" placeholder="2500" maxlength="4" name="amount" required [(ngModel)]="amount" (ngModelChange)="amountChange($event)" [disabled]="gotResults"></ion-input>
</ion-item>
<ion-item text-center class="noBg" [hidden]="gotResults">
<button type="submit" ion-button large [outline]="calcForm.form.invalid" [disabled]="calcForm.form.invalid || isLoading" color="light">
<ion-icon padding-right name="calculator" [hidden]="isLoading" ></ion-icon>
<ion-spinner padding-right [hidden]="!isLoading" ></ion-spinner>
Calc
</button>
</ion-item>
</form>
<div padding *ngIf="gotResults">
<ion-list-header no-margin class="noBg">
Option 1 <ion-icon name="arrow-down" color="warning"></ion-icon>
</ion-list-header>
<ion-item padding class="semiBg calcResults">
<ion-label no-margin color="secondary" stacked>{{results.Option1Ticket1}} x {{ticket1/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="secondary" stacked>{{results.Option1Ticket2}} x {{ticket2/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="light" stacked>To pay: {{results.Option1Cash/100 | currency:currency:true:'1.2'}}</ion-label>
</ion-item>
<ion-list-header no-margin class="noBg">
Option 2 <ion-icon name="arrow-up" color="warning"></ion-icon>
</ion-list-header>
<ion-item padding class="semiBg calcResults">
<ion-label no-margin color="secondary" stacked>{{results.Option2Ticket1}} x {{ticket1/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="secondary" stacked>{{results.Option2Ticket2}} x {{ticket2/100 | currency:currency:true:'1.2'}}</ion-label>
<ion-label color="light" stacked>To receive: {{results.Option2Cash/100 | currency:currency:true:'1.2'}}</ion-label>
</ion-item>
<ion-item text-center padding-top class="noBg">
<button ion-button large outline (click)="reset()" [disabled]="calcForm.form.invalid" color="light">
<ion-icon padding-right name="refresh"></ion-icon> Reset
</button>
</ion-item>
</div>
<div padding *ngIf="gotFacts && !gotResults">
<ion-list-header no-margin class="noBg">
<ion-icon padding-right name="bulb" color="warning"></ion-icon> Did you know?
</ion-list-header>
<ion-item padding class="semiBg" text-wrap>
{{fact}}
</ion-item>
</div>
</ion-content>
| GitFranzis/gourmet-calculator | src/pages/calculator/calculator.html | HTML | gpl-3.0 | 3,024 |
class CustomUrl < ActiveRecord::Base
belongs_to :media_resource
belongs_to :creator, class_name: 'User', foreign_key: :creator_id
belongs_to :updator, class_name: 'User', foreign_key: :updator_id
default_scope lambda{order(id: :asc)}
end
| zhdk/madek | app/models/custom_url.rb | Ruby | gpl-3.0 | 247 |
package me.anthonybruno.soccerSim.team.member;
import me.anthonybruno.soccerSim.models.Range;
/**
* Player is a class that contains information about a player.
*/
public class Player extends TeamMember {
private final Range shotRange;
private final int goal;
/**
* Creates a new player with a name, shot range (how likely a shot will be attributed to the player) and a goal
* rating (how likely they are to score a goal).
*
* @param name The name of the player
* @param shotRange Shot range of player. Defines how likely a shot on goal will be attributed to this player (see
* rule files for more information. Is the maximum value when lower and upper bounds given by the
* rules.
* @param goal How likely a shot from the player will go in. When shot is taken, a number from 1-10 is generated.
* If the generated number is above or equal to goal rating, the player scores.
*/
public Player(String name, Range shotRange, int goal, int multiplier) {
super(name, multiplier);
this.shotRange = shotRange;
this.goal = goal;
}
/**
* Returns the shot range of player.
*
* @return the player's shot range.
*/
public Range getShotRange() {
return shotRange;
}
/**
* Returns the goal rating of the player.
*
* @return the player's goal range.
*/
public int getGoal() {
return goal;
}
}
| AussieGuy0/soccerSim | src/main/java/me/anthonybruno/soccerSim/team/member/Player.java | Java | gpl-3.0 | 1,523 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Newtonsoft.Json;
using SmartStore.Core.Infrastructure;
namespace SmartStore.Collections
{
public abstract class TreeNodeBase<T> where T : TreeNodeBase<T>
{
private T _parent;
private List<T> _children = new List<T>();
private int? _depth = null;
private int _index = -1;
protected object _id;
private IDictionary<object, TreeNodeBase<T>> _idNodeMap;
protected IDictionary<string, object> _metadata;
private readonly static ContextState<Dictionary<string, object>> _contextState = new ContextState<Dictionary<string, object>>("TreeNodeBase.ThreadMetadata");
public TreeNodeBase()
{
}
#region Id
public object Id
{
get
{
return _id;
}
set
{
_id = value;
if (_parent != null)
{
var map = GetIdNodeMap();
if (_id != null && map.ContainsKey(_id))
{
// Remove old id from map
map.Remove(_id);
}
if (value != null)
{
map[value] = this;
}
}
}
}
public T SelectNodeById(object id)
{
if (id == null || IsLeaf)
return null;
var map = GetIdNodeMap();
var node = (T)map?.Get(id);
if (node != null && !this.IsAncestorOfOrSelf(node))
{
// Found node is NOT a child of this node
return null;
}
return node;
}
private IDictionary<object, TreeNodeBase<T>> GetIdNodeMap()
{
var map = this.Root._idNodeMap;
if (map == null)
{
map = this.Root._idNodeMap = new Dictionary<object, TreeNodeBase<T>>();
}
return map;
}
#endregion
#region Metadata
public IDictionary<string, object> Metadata
{
get
{
return _metadata ?? (_metadata = new Dictionary<string, object>());
}
set
{
_metadata = value;
}
}
public void SetMetadata(string key, object value)
{
Guard.NotEmpty(key, nameof(key));
Metadata[key] = value;
}
public void SetThreadMetadata(string key, object value)
{
Guard.NotEmpty(key, nameof(key));
var state = _contextState.GetState();
if (state == null)
{
state = new Dictionary<string, object>();
_contextState.SetState(state);
}
state[GetContextKey(this, key)] = value;
}
public TMetadata GetMetadata<TMetadata>(string key, bool recursive = true)
{
Guard.NotEmpty(key, nameof(key));
object metadata;
if (!recursive)
{
return TryGetMetadataForNode(this, key, out metadata) ? (TMetadata)metadata : default(TMetadata);
}
// recursively search for the metadata value in current node and ancestors
var current = this;
while (!TryGetMetadataForNode(current, key, out metadata))
{
current = current.Parent;
if (current == null)
break;
}
if (metadata != null)
{
return (TMetadata)metadata;
}
return default(TMetadata);
}
private bool TryGetMetadataForNode(TreeNodeBase<T> node, string key, out object metadata)
{
metadata = null;
var state = _contextState.GetState();
if (state != null)
{
var contextKey = GetContextKey(node, key);
if (state.ContainsKey(contextKey))
{
metadata = state[contextKey];
return true;
}
}
if (node._metadata != null && node._metadata.ContainsKey(key))
{
metadata = node._metadata[key];
return true;
}
return false;
}
private static string GetContextKey(TreeNodeBase<T> node, string key)
{
return node.GetHashCode().ToString() + key;
}
#endregion
private List<T> ChildrenInternal
{
get
{
if (_children == null)
{
_children = new List<T>();
}
return _children;
}
}
private void AddChild(T node, bool clone, bool append = true)
{
var newNode = node;
if (clone)
{
newNode = node.Clone(true);
}
newNode.AttachTo((T)this, append ? (int?)null : 0);
}
private void AttachTo(T newParent, int? index)
{
Guard.NotNull(newParent, nameof(newParent));
var prevParent = _parent;
if (_parent != null)
{
// Detach from parent
_parent.Remove((T)this);
}
if (index == null)
{
newParent.ChildrenInternal.Add((T)this);
_index = newParent.ChildrenInternal.Count - 1;
}
else
{
newParent.ChildrenInternal.Insert(index.Value, (T)this);
_index = index.Value;
FixIndexes(newParent._children, _index + 1, 1);
}
_parent = newParent;
FixIdNodeMap(prevParent, newParent);
}
/// <summary>
/// Responsible for propagating node ids when detaching/attaching nodes
/// </summary>
private void FixIdNodeMap(T prevParent, T newParent)
{
ICollection<TreeNodeBase<T>> keyedNodes = null;
if (prevParent != null)
{
// A node is moved. We need to detach first.
keyedNodes = new List<TreeNodeBase<T>>();
// Detach ids from prev map
var prevMap = prevParent.GetIdNodeMap();
Traverse(x =>
{
// Collect all child node's ids
if (x._id != null)
{
keyedNodes.Add(x);
if (prevMap.ContainsKey(x._id))
{
// Remove from map
prevMap.Remove(x._id);
}
}
}, true);
}
if (keyedNodes == null && _idNodeMap != null)
{
// An orphan/root node is attached
keyedNodes = _idNodeMap.Values;
}
if (newParent != null)
{
// Get new *root map
var map = newParent.GetIdNodeMap();
// Merge *this map with *root map
if (keyedNodes != null)
{
foreach (var node in keyedNodes)
{
map[node._id] = node;
}
// Get rid of *this map after memorizing keyed nodes
if (_idNodeMap != null)
{
_idNodeMap.Clear();
_idNodeMap = null;
}
}
if (prevParent == null && _id != null)
{
// When *this was a root, but is keyed, then *this id
// was most likely missing in the prev id-node-map.
map[_id] = (T)this;
}
}
}
[JsonIgnore]
public T Parent
{
get
{
return _parent;
}
}
public T this[int i]
{
get
{
return _children?[i];
}
}
public IReadOnlyList<T> Children
{
get
{
return ChildrenInternal;
}
}
[JsonIgnore]
public IEnumerable<T> LeafNodes
{
get
{
return _children != null
? _children.Where(x => x.IsLeaf)
: Enumerable.Empty<T>();
}
}
[JsonIgnore]
public IEnumerable<T> NonLeafNodes
{
get
{
return _children != null
? _children.Where(x => !x.IsLeaf)
: Enumerable.Empty<T>();
}
}
[JsonIgnore]
public T FirstChild
{
get
{
return _children?.FirstOrDefault();
}
}
[JsonIgnore]
public T LastChild
{
get
{
return _children?.LastOrDefault();
}
}
[JsonIgnore]
public bool IsLeaf
{
get
{
return _children == null || _children.Count == 0;
}
}
[JsonIgnore]
public bool HasChildren
{
get
{
return _children == null || _children.Count > 0;
}
}
[JsonIgnore]
public bool IsRoot
{
get
{
return _parent == null;
}
}
[JsonIgnore]
public int Index
{
get
{
return _index;
}
}
/// <summary>
/// Root starts with 0
/// </summary>
[JsonIgnore]
public int Depth
{
get
{
if (!_depth.HasValue)
{
var node = this;
int depth = 0;
while (node != null && !node.IsRoot)
{
depth++;
node = node.Parent;
}
_depth = depth;
}
return _depth.Value;
}
}
[JsonIgnore]
public T Root
{
get
{
var root = this;
while (root._parent != null)
{
root = root._parent;
}
return (T)root;
}
}
[JsonIgnore]
public T First
{
get
{
return _parent?._children?.FirstOrDefault();
}
}
[JsonIgnore]
public T Last
{
get
{
return _parent?._children?.LastOrDefault();
}
}
[JsonIgnore]
public T Next
{
get
{
return _parent?._children?.ElementAtOrDefault(_index + 1);
}
}
[JsonIgnore]
public T Previous
{
get
{
return _parent?._children?.ElementAtOrDefault(_index - 1);
}
}
public bool IsDescendantOf(T node)
{
var parent = _parent;
while (parent != null)
{
if (parent == node)
{
return true;
}
parent = parent._parent;
}
return false;
}
public bool IsDescendantOfOrSelf(T node)
{
if (node == (T)this)
return true;
return IsDescendantOf(node);
}
public bool IsAncestorOf(T node)
{
return node.IsDescendantOf((T)this);
}
public bool IsAncestorOfOrSelf(T node)
{
if (node == (T)this)
return true;
return node.IsDescendantOf((T)this);
}
[JsonIgnore]
public IEnumerable<T> Trail
{
get
{
var trail = new List<T>();
var node = (T)this;
do
{
trail.Insert(0, node);
node = node._parent;
} while (node != null);
return trail;
}
}
/// <summary>
/// Gets the first element that matches the predicate by testing the node itself
/// and traversing up through its ancestors in the tree.
/// </summary>
/// <param name="predicate">predicate</param>
/// <returns>The closest node</returns>
public T Closest(Expression<Func<T, bool>> predicate)
{
Guard.NotNull(predicate, nameof(predicate));
var test = predicate.Compile();
if (test((T)this))
{
return (T)this;
}
var parent = _parent;
while (parent != null)
{
if (test(parent))
{
return parent;
}
parent = parent._parent;
}
return null;
}
public T Append(T value)
{
this.AddChild(value, false, true);
return value;
}
public void AppendRange(IEnumerable<T> values)
{
values.Each(x => Append(x));
}
public void AppendChildrenOf(T node)
{
if (node?._children != null)
{
node._children.Each(x => this.AddChild(x, true, true));
}
}
public T Prepend(T value)
{
this.AddChild(value, false, false);
return value;
}
public void InsertAfter(int index)
{
var refNode = _children?.ElementAtOrDefault(index);
if (refNode != null)
{
InsertAfter(refNode);
}
throw new ArgumentOutOfRangeException(nameof(index));
}
public void InsertAfter(T refNode)
{
this.Insert(refNode, true);
}
public void InsertBefore(int index)
{
var refNode = _children?.ElementAtOrDefault(index);
if (refNode != null)
{
InsertBefore(refNode);
}
throw new ArgumentOutOfRangeException(nameof(index));
}
public void InsertBefore(T refNode)
{
this.Insert(refNode, false);
}
private void Insert(T refNode, bool after)
{
Guard.NotNull(refNode, nameof(refNode));
var refParent = refNode._parent;
if (refParent == null)
{
throw Error.Argument("refNode", "The reference node cannot be a root node and must be attached to the tree.");
}
AttachTo(refParent, refNode._index + (after ? 1 : 0));
}
public T SelectNode(Expression<Func<T, bool>> predicate, bool includeSelf = false)
{
Guard.NotNull(predicate, nameof(predicate));
return this.FlattenNodes(predicate, includeSelf).FirstOrDefault();
}
/// <summary>
/// Selects all nodes (recursively) witch match the given <c>predicate</c>
/// </summary>
/// <param name="predicate">The predicate to match against</param>
/// <returns>A readonly collection of node matches</returns>
public IEnumerable<T> SelectNodes(Expression<Func<T, bool>> predicate, bool includeSelf = false)
{
Guard.NotNull(predicate, nameof(predicate));
return this.FlattenNodes(predicate, includeSelf);
}
private void FixIndexes(IList<T> list, int startIndex, int summand = 1)
{
if (startIndex < 0 || startIndex >= list.Count)
return;
for (var i = startIndex; i < list.Count; i++)
{
list[i]._index += summand;
}
}
public void Remove(T node)
{
Guard.NotNull(node, nameof(node));
if (!node.IsRoot)
{
var list = node._parent?._children;
if (list.Remove(node))
{
node.FixIdNodeMap(node._parent, null);
FixIndexes(list, node._index, -1);
node._index = -1;
node._parent = null;
node.Traverse(x => x._depth = null, true);
}
}
}
public void Clear()
{
Traverse(x => x._depth = null, false);
if (_children != null)
{
_children.Clear();
}
FixIdNodeMap(_parent, null);
}
public void Traverse(Action<T> action, bool includeSelf = false)
{
Guard.NotNull(action, nameof(action));
if (includeSelf)
action((T)this);
if (_children != null)
{
foreach (var child in _children)
child.Traverse(action, true);
}
}
public void TraverseParents(Action<T> action, bool includeSelf = false)
{
Guard.NotNull(action, nameof(action));
if (includeSelf)
action((T)this);
var parent = _parent;
while (parent != null)
{
action(parent);
parent = parent._parent;
}
}
public IEnumerable<T> FlattenNodes(bool includeSelf = true)
{
return this.FlattenNodes(null, includeSelf);
}
protected IEnumerable<T> FlattenNodes(Expression<Func<T, bool>> predicate, bool includeSelf = true)
{
IEnumerable<T> list;
if (includeSelf)
{
list = new[] { (T)this };
}
else
{
list = Enumerable.Empty<T>();
}
if (_children == null)
return list;
var result = list.Union(_children.SelectMany(x => x.FlattenNodes()));
if (predicate != null)
{
result = result.Where(predicate.Compile());
}
return result;
}
public T Clone()
{
return Clone(true);
}
public virtual T Clone(bool deep)
{
var clone = CreateInstance();
if (deep)
{
clone.AppendChildrenOf((T)this);
}
return clone;
}
protected abstract T CreateInstance();
}
}
| smartstoreag/SmartStoreNET | src/Libraries/SmartStore.Core/Collections/TreeNodeBase.cs | C# | gpl-3.0 | 13,704 |
package vizardous.delegate.dataFilter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import vizardous.util.Converter;
/**
* Filter class that provides filter functionality for data structures with comparable content
*
* @author Johannes Seiffarth <[email protected]>
*/
public class ComparableFilter {
/**
* Filters a map. All values (not keys!) that equal kick will be removed
* @param map to filter
* @param kick Value to kick out
*/
public static <T extends Comparable<T>, K> void filter(Map<K,T> map, T kick) {
Set<Map.Entry<K, T>> entrySet = map.entrySet();
for(Iterator<Map.Entry<K,T>> it = entrySet.iterator(); it.hasNext();) {
Map.Entry<K, T> entry = it.next();
if(entry.getValue().equals(kick))
it.remove();
}
}
/**
* Filters a list. All values that equal kick will be removed
* @param list to filter
* @param kick Value to kick out
* @return a reference to list (no new list!)
*/
public static <T extends Comparable<T>> List<T> filter(List<T> list, T kick) {
for(Iterator<T> it = list.iterator(); it.hasNext();) {
T val = it.next();
if(val.equals(kick))
it.remove();
}
return list;
}
/**
* Filters a double array. All values that equal kick will be removed
* @param data array to filter
* @param kick Value to kick out
* @return a new filtered array
*/
public static double[] filter(double[] data, double kick) {
LinkedList<Double> list = new LinkedList<Double>();
for(double value : data) {
if(value != kick)
list.add(value);
}
return Converter.listToArray(list);
}
}
| modsim/vizardous | src/main/java/vizardous/delegate/dataFilter/ComparableFilter.java | Java | gpl-3.0 | 1,741 |
/*++
Copyright (c) 2008 Microsoft Corporation
Module Name:
ast_smt_pp.h
Abstract:
Pretty printer of AST formulas as SMT benchmarks.
Author:
Nikolaj Bjorner 2008-04-09.
Revision History:
--*/
#ifndef _AST_SMT_PP_H_
#define _AST_SMT_PP_H_
#include"ast.h"
#include<string>
#include"map.h"
class smt_renaming {
typedef map<symbol, symbol, symbol_hash_proc, symbol_eq_proc> symbol2symbol;
symbol2symbol m_translate;
symbol2symbol m_rev_translate;
symbol fix_symbol(symbol s, int k);
bool is_legal(char c);
bool is_special(char const* s);
bool is_numerical(char const* s);
bool all_is_legal(char const* s);
public:
smt_renaming();
symbol get_symbol(symbol s0);
symbol operator()(symbol const & s) { return get_symbol(s); }
};
class ast_smt_pp {
public:
class is_declared {
public:
virtual bool operator()(func_decl* d) const { return false; }
virtual bool operator()(sort* s) const { return false; }
};
private:
ast_manager& m_manager;
expr_ref_vector m_assumptions;
expr_ref_vector m_assumptions_star;
symbol m_benchmark_name;
symbol m_source_info;
symbol m_status;
symbol m_category;
symbol m_logic;
std::string m_attributes;
family_id m_dt_fid;
is_declared m_is_declared_default;
is_declared* m_is_declared;
bool m_simplify_implies;
public:
ast_smt_pp(ast_manager& m);
void set_benchmark_name(const char* bn) { if (bn) m_benchmark_name = bn; }
void set_source_info(const char* si) { if (si) m_source_info = si; }
void set_status(const char* s) { if (s) m_status = s; }
void set_category(const char* c) { if (c) m_category = c; }
void set_logic(const char* l) { if (l) m_logic = l; }
void add_attributes(const char* s) { if (s) m_attributes += s; }
void add_assumption(expr* n) { m_assumptions.push_back(n); }
void add_assumption_star(expr* n) { m_assumptions_star.push_back(n); }
void set_simplify_implies(bool f) { m_simplify_implies = f; }
void set_is_declared(is_declared* id) { m_is_declared = id; }
void display(std::ostream& strm, expr* n);
void display_smt2(std::ostream& strm, expr* n);
void display_expr(std::ostream& strm, expr* n);
void display_expr_smt2(std::ostream& strm, expr* n, unsigned indent = 0, unsigned num_var_names = 0, char const* const* var_names = 0);
};
struct mk_smt_pp {
expr * m_expr;
ast_manager& m_manager;
unsigned m_indent;
unsigned m_num_var_names;
char const* const* m_var_names;
mk_smt_pp(expr* e, ast_manager & m, unsigned indent = 0, unsigned num_var_names = 0, char const* const* var_names = 0) :
m_expr(e), m_manager(m), m_indent(indent), m_num_var_names(num_var_names), m_var_names(var_names) {}
};
inline std::ostream& operator<<(std::ostream& out, const mk_smt_pp & p) {
ast_smt_pp pp(p.m_manager);
pp.display_expr_smt2(out, p.m_expr, p.m_indent, p.m_num_var_names, p.m_var_names);
return out;
}
#endif
| cs-au-dk/Artemis | contrib/Z3/lib/ast_smt_pp.h | C | gpl-3.0 | 3,147 |
#!/bin/bash
set -e
echo "$(whoami)"
if [ "$(whoami)" == "root" ]; then
chown -R scrapy:scrapy /home/scrapy/backup
chown --dereference scrapy "/proc/$$/fd/1" "/proc/$$/fd/2" || :
exec gosu scrapy "$@"
fi | IDEES-Rouen/Flight-Scrapping | flight/docker-entrypoint.sh | Shell | gpl-3.0 | 215 |
<!DOCTYPE html>
<html>
<head>
<title>!AntiShout demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="/">
<p>
<label>Type: text</label>
<input type="text" placeholder="Try me">
</p>
<p>
<label>Textarea</label>
<textarea placeholder="And me too"></textarea>
</p>
<div class="message"></div>
<button type="submit" disabled>send</button>
</form>
<!-- load scripts -->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
<script src="antishout.js"></script>
<!-- antishout init -->
<script>
$(function(){
$('form').antishout();
});
</script>
</body>
</html>
| npsr/antishout.js | example.html | HTML | gpl-3.0 | 987 |
# Tutorials
## Table of contents
- [Make a server from scratch](https://github.com/Komrod/web-servo/blob/master/tutorials.md#make-a-server-from-scratch)
- [Create a HTTPS server](https://github.com/Komrod/web-servo/blob/master/tutorials.md#make-a-https-server)
## Make a server from scratch
Assuming you start from nothing, install Node (https://nodejs.org/en/download/) and open a console. Then create a directory for your project and install the web-servo module:
```
mkdir myProject
cd myProject
npm install web-servo
```
Create the script "server.js" to launch the server in "myProject/":
```
require('web-servo').start();
```
If you run the server now, it will show an error because the configuration is not set in the script and the server is supposed to use the file "config.json" that doesn't exist yet. It is also recommanded to create the WWW root directory and log directory so everything works fine.
```
mkdir www
mkdir log
```
Now create "config.json" in "myProject/":
```
{
"server": {
"port": "9000",
"dir": "www/"
},
"log": {
"access": {
"enabled": true,
"path": "log/access.log",
"console": true
},
"error": {
"enabled": true,
"path": "log/error.log",
"console": true,
"debug": true
}
}
}
```
In this file, we defined the server to run on port 9000 and the WWW directory to "www/". I also add the log parameters to show access and errors in the console.
If you omit a parameter in this file, it will take the default value. For example, the default page is set by default to "index.html".
Now launch the server and it should run properly:
```
node server.js
```
The console will output:
```
Using config file "C:\Users\me\git\myProject\config.json"
Using WWW directory "C:\Users\me\git\myProject\www"
Server listening on: http://localhost:9000
```
Create a simple "index.html" file and put it in "myProject/www/":
```
<!doctype html>
<html>
<head>
<title>Hello world!</title>
</head>
<body>
This is the Hello world page!
</body>
</html>
```
Now open a browser and request http://localhost:9000/ you should see the Hello world page. You can now build a whole website inside the WWW directory with images, CSS, JS ...
## Make a HTTPS server
You can run a web server over HTTPS protocol. You will need the SSL key file and the SSL certificate file.
If you want to run your server locally, you can generate those files on your computer with some commands, it will require OpenSSL installed.
### Generate local SSL files by script
There is a shell script in the root directory that can do it for you. How to use it :
```
./generateSSL.sh example/ssl/ example
```
This will generate the files in the "example/ssl/" directory.
After succefull execution, the generated files are "example/ssl/example.key" and "example/ssl/example.crt".
### Generate local SSL files manually
You can generate manually those files by typing the commands yourself. You can go to the directory you want to create the SSL files "example.crt" and "example.key".
```
cd example/ssl/
openssl genrsa -des3 -passout pass:x -out example.pass.key 2048
openssl rsa -passin pass:x -in example.pass.key -out example.key
```
You must know your local hostname or else your certificate will not work.
```
hostname
```
Your host name is the response to field Common Name (CN or FQDN).
```
openssl x509 -req -days 365 -in example.csr -signkey example.key -out example.crt
```
Cleanup temporary files.
```
rm example.pass.key example.csr
```
If everything runs properly, you now have the 2 files "example.crt" and "example.key". They are ready to use with the example HTTPS server. They must be in the directory "example/ssl/".
If you use them in another project, you can also rename them.
### Configure the server
You now have the 2 SSL files. You need to configure the files in the config file of Web-servo, it may looks like this (in config.json):
```
{
"server": {
"port": "443",
"ssl": {
"enabled": true,
"key": "ssl/example.key",
"cert": "ssl/example.crt"
}
}
}
```
If you are using the example server, the config file is already ready in "example/config_https.json".
Then, you have to run your server with a simple line in a node script.
```
require('web-servo').start();
```
The script is also ready in "example/server_https.js". You can run "node example/server_https.js".
Executing the example HTTPS server will have this result :
```
Using config file "C:\Users\PR033\git\web-servo\example\config_https.json"
Using WWW directory "C:\Users\PR033\git\web-servo\example\www"
Server listening on: https://localhost:443
```
### Finally
You can now access the server on https://localhost/. If you are using a locally generated certificate, you may have a warning because your certificate is not validated by a trusted source. But it will run properly.
Way to disable the warning:
- [For Internet Explorer](https://www.poweradmin.com/help/sslhints/ie.aspx)
- [For Chrome](https://support.google.com/chrome/answer/99020)
- [For Firefox](http://ccm.net/faq/14655-firefox-disable-warning-when-accessing-secured-sites)
If your certificate files are invalid or corrupted, there might be no errors while running the server but your browser will prevent you to process the requests.
| Komrod/web-servo | tutorials.md | Markdown | gpl-3.0 | 5,390 |
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: ../pdfreporter-core/src/org/oss/pdfreporter/crosstabs/fill/calculation/BucketingServiceContext.java
//
#include "J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext")
#ifdef RESTRICT_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext
#define INCLUDE_ALL_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext 0
#else
#define INCLUDE_ALL_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext 1
#endif
#undef RESTRICT_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext
#if !defined (OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext_) && (INCLUDE_ALL_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext || defined(INCLUDE_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext))
#define OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext_
@class IOSObjectArray;
@protocol OrgOssPdfreporterEngineFillJRFillExpressionEvaluator;
@protocol OrgOssPdfreporterEngineJRExpression;
@protocol OrgOssPdfreporterEngineJasperReportsContext;
@protocol OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext < NSObject, JavaObject >
- (id<OrgOssPdfreporterEngineJasperReportsContext>)getJasperReportsContext;
- (id<OrgOssPdfreporterEngineFillJRFillExpressionEvaluator>)getExpressionEvaluator;
- (id)evaluateMeasuresExpressionWithOrgOssPdfreporterEngineJRExpression:(id<OrgOssPdfreporterEngineJRExpression>)expression
withOrgOssPdfreporterCrosstabsFillCalculationMeasureDefinition_MeasureValueArray:(IOSObjectArray *)measureValues;
@end
J2OBJC_EMPTY_STATIC_INIT(OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext)
J2OBJC_TYPE_LITERAL_HEADER(OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext)
#endif
#pragma pop_macro("INCLUDE_ALL_OrgOssPdfreporterCrosstabsFillCalculationBucketingServiceContext")
| OpenSoftwareSolutions/PDFReporterKit | PDFReporterKit/Sources/org/oss/pdfreporter/crosstabs/fill/calculation/BucketingServiceContext.h | C | gpl-3.0 | 1,963 |
<?php
return array(
'title' => 'Publicaciones',
'parent' => 'Contenido',
'name' => 'publicación|publicaciones',
'table' =>
array(
'id' => 'ID',
'action' => 'Acción',
'title' => 'Título',
'category_id' => 'Categoría',
'author_id' => 'Autor',
'url_alias' => 'Alias de la URL',
'author_alias' => 'Alias del autor',
'image_file' => 'Imagen',
'description' => 'Descripción',
'content' => 'Contenido',
'created_at' => 'Creado',
'status' => 'Estado',
),
);
| systemson/BlankBoard | resources/lang/es/articles.php | PHP | gpl-3.0 | 516 |
package com.albion.common.graph.algorithms;
import com.albion.common.graph.core.v1.Edge;
import com.albion.common.graph.core.v1.Graph;
import com.albion.common.graph.core.v1.Vertex;
import java.util.ArrayList;
import java.util.List;
public class BreathFirstSearch {
public static Vertex locate(Graph graph, Integer source, Integer target){
List<Vertex> queue = new ArrayList<>();
Vertex root = graph.getVertex(source);
queue.add(root);
while(!queue.isEmpty()){
Vertex v = queue.remove(0);
if(v.getId() == target.intValue()){
v.setVisited(true);
return v;
}
List<Edge> edgeList = v.getEdgeList();
for(Edge edge : edgeList){
int vertexId = edge.getY();
Vertex w = graph.getVerticesMap().get(vertexId);
if(w.isVisited() == false){
w.setVisited(true);
queue.add(w);
}
}
}
return null;
}
}
| KyleLearnedThis/data-structures | src/main/java/com/albion/common/graph/algorithms/BreathFirstSearch.java | Java | gpl-3.0 | 868 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Athame.PluginAPI.Service
{
/// <summary>
/// Represents a collection of items that are retrieved as pages from a service.
/// </summary>
/// <typeparam name="T">The type of each item.</typeparam>
public abstract class PagedMethod<T> : PagedList<T>
{
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="itemsPerPage">The amount of items per page to load.</param>
protected PagedMethod(int itemsPerPage)
{
ItemsPerPage = itemsPerPage;
}
/// <summary>
/// Retrieves the next page asynchronously and appends the result to <see cref="AllItems"/>.
/// </summary>
/// <returns>The next page's contents.</returns>
public abstract Task<IList<T>> GetNextPageAsync();
/// <summary>
/// Retrieves each page sequentially until there are none left.
/// </summary>
public virtual async Task LoadAllPagesAsync()
{
while (HasMoreItems)
{
await GetNextPageAsync();
}
}
}
}
| svbnet/Athame | Athame.PluginAPI/Service/PagedMethod.cs | C# | gpl-3.0 | 1,242 |
namespace Animals.Animals
{
public class Kitten : Cat
{
public Kitten(string name, int age) : base(name, age, "Female")
{
}
public override string ProduceSound()
{
return "Meow";
}
}
}
| martinmladenov/SoftUni-Solutions | CSharp OOP Basics/Exercises/04. Inheritance - Exercise/Animals/Animals/Kitten.cs | C# | gpl-3.0 | 261 |
URLDetector
===========
URLDetector is an objc program that can find all parts in a string that might refer to an URL.
| beanandbean/URLDetector | README.md | Markdown | gpl-3.0 | 120 |
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Platform-specific code for FreeBSD goes here. For the POSIX-compatible
// parts, the implementation is in platform-posix.cc.
#include <osconfig.h>
#ifdef FreeBSD
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/ucontext.h>
#include <stdlib.h>
#include <sys/types.h> // mmap & munmap
#include <sys/mman.h> // mmap & munmap
#include <sys/stat.h> // open
#include <sys/fcntl.h> // open
#include <unistd.h> // getpagesize
// If you don't have execinfo.h then you need devel/libexecinfo from ports.
#include <strings.h> // index
#include <errno.h>
#include <stdarg.h>
#include <limits.h>
#undef MAP_TYPE
#include "v8.h"
#include "v8threads.h"
#include "platform.h"
namespace v8 {
namespace internal {
const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
if (std::isnan(time)) return "";
time_t tv = static_cast<time_t>(std::floor(time/msPerSecond));
struct tm* t = localtime(&tv);
if (NULL == t) return "";
return t->tm_zone;
}
double OS::LocalTimeOffset(TimezoneCache* cache) {
time_t tv = time(NULL);
struct tm* t = localtime(&tv);
// tm_gmtoff includes any daylight savings offset, so subtract it.
return static_cast<double>(t->tm_gmtoff * msPerSecond -
(t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
}
void* OS::Allocate(const size_t requested,
size_t* allocated,
bool executable) {
const size_t msize = RoundUp(requested, getpagesize());
int prot = PROT_READ | PROT_WRITE | (executable ? PROT_EXEC : 0);
void* mbase = mmap(NULL, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
if (mbase == MAP_FAILED) {
LOG(Isolate::Current(), StringEvent("OS::Allocate", "mmap failed"));
return NULL;
}
*allocated = msize;
return mbase;
}
class PosixMemoryMappedFile : public OS::MemoryMappedFile {
public:
PosixMemoryMappedFile(FILE* file, void* memory, int size)
: file_(file), memory_(memory), size_(size) { }
virtual ~PosixMemoryMappedFile();
virtual void* memory() { return memory_; }
virtual int size() { return size_; }
private:
FILE* file_;
void* memory_;
int size_;
};
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
FILE* file = fopen(name, "r+");
if (file == NULL) return NULL;
fseek(file, 0, SEEK_END);
int size = ftell(file);
void* memory =
mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
return new PosixMemoryMappedFile(file, memory, size);
}
OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
void* initial) {
FILE* file = fopen(name, "w+");
if (file == NULL) return NULL;
int result = fwrite(initial, size, 1, file);
if (result < 1) {
fclose(file);
return NULL;
}
void* memory =
mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
return new PosixMemoryMappedFile(file, memory, size);
}
PosixMemoryMappedFile::~PosixMemoryMappedFile() {
if (memory_) munmap(memory_, size_);
fclose(file_);
}
static unsigned StringToLong(char* buffer) {
return static_cast<unsigned>(strtol(buffer, NULL, 16)); // NOLINT
}
void OS::LogSharedLibraryAddresses(Isolate* isolate) {
static const int MAP_LENGTH = 1024;
int fd = open("/proc/self/maps", O_RDONLY);
if (fd < 0) return;
while (true) {
char addr_buffer[11];
addr_buffer[0] = '0';
addr_buffer[1] = 'x';
addr_buffer[10] = 0;
int result = read(fd, addr_buffer + 2, 8);
if (result < 8) break;
unsigned start = StringToLong(addr_buffer);
result = read(fd, addr_buffer + 2, 1);
if (result < 1) break;
if (addr_buffer[2] != '-') break;
result = read(fd, addr_buffer + 2, 8);
if (result < 8) break;
unsigned end = StringToLong(addr_buffer);
char buffer[MAP_LENGTH];
int bytes_read = -1;
do {
bytes_read++;
if (bytes_read >= MAP_LENGTH - 1)
break;
result = read(fd, buffer + bytes_read, 1);
if (result < 1) break;
} while (buffer[bytes_read] != '\n');
buffer[bytes_read] = 0;
// Ignore mappings that are not executable.
if (buffer[3] != 'x') continue;
char* start_of_path = index(buffer, '/');
// There may be no filename in this line. Skip to next.
if (start_of_path == NULL) continue;
buffer[bytes_read] = 0;
LOG(isolate, SharedLibraryEvent(start_of_path, start, end));
}
close(fd);
}
void OS::SignalCodeMovingGC() {
}
// Constants used for mmap.
static const int kMmapFd = -1;
static const int kMmapFdOffset = 0;
VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
VirtualMemory::VirtualMemory(size_t size)
: address_(ReserveRegion(size)), size_(size) { }
VirtualMemory::VirtualMemory(size_t size, size_t alignment)
: address_(NULL), size_(0) {
ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
size_t request_size = RoundUp(size + alignment,
static_cast<intptr_t>(OS::AllocateAlignment()));
void* reservation = mmap(OS::GetRandomMmapAddr(),
request_size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
kMmapFd,
kMmapFdOffset);
if (reservation == MAP_FAILED) return;
Address base = static_cast<Address>(reservation);
Address aligned_base = RoundUp(base, alignment);
ASSERT_LE(base, aligned_base);
// Unmap extra memory reserved before and after the desired block.
if (aligned_base != base) {
size_t prefix_size = static_cast<size_t>(aligned_base - base);
OS::Free(base, prefix_size);
request_size -= prefix_size;
}
size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
ASSERT_LE(aligned_size, request_size);
if (aligned_size != request_size) {
size_t suffix_size = request_size - aligned_size;
OS::Free(aligned_base + aligned_size, suffix_size);
request_size -= suffix_size;
}
ASSERT(aligned_size == request_size);
address_ = static_cast<void*>(aligned_base);
size_ = aligned_size;
}
VirtualMemory::~VirtualMemory() {
if (IsReserved()) {
bool result = ReleaseRegion(address(), size());
ASSERT(result);
USE(result);
}
}
bool VirtualMemory::IsReserved() {
return address_ != NULL;
}
void VirtualMemory::Reset() {
address_ = NULL;
size_ = 0;
}
bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
return CommitRegion(address, size, is_executable);
}
bool VirtualMemory::Uncommit(void* address, size_t size) {
return UncommitRegion(address, size);
}
bool VirtualMemory::Guard(void* address) {
OS::Guard(address, OS::CommitPageSize());
return true;
}
void* VirtualMemory::ReserveRegion(size_t size) {
void* result = mmap(OS::GetRandomMmapAddr(),
size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
kMmapFd,
kMmapFdOffset);
if (result == MAP_FAILED) return NULL;
return result;
}
bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
if (MAP_FAILED == mmap(base,
size,
prot,
MAP_PRIVATE | MAP_ANON | MAP_FIXED,
kMmapFd,
kMmapFdOffset)) {
return false;
}
return true;
}
bool VirtualMemory::UncommitRegion(void* base, size_t size) {
return mmap(base,
size,
PROT_NONE,
MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
kMmapFd,
kMmapFdOffset) != MAP_FAILED;
}
bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
return munmap(base, size) == 0;
}
bool VirtualMemory::HasLazyCommits() {
// TODO(alph): implement for the platform.
return false;
}
} } // namespace v8::internal
#endif
| jiachenning/fibjs | vender/src/v8/src/platform-freebsd.cc | C++ | gpl-3.0 | 8,266 |
#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
with Page (self.canvas) as pg:
for obj in self.objects:
coords = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_type, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()
| clearclaw/xxpaper | xxpaper/contents.py | Python | gpl-3.0 | 590 |
class CfgWeapons {
// Base classes
class ItemCore;
class H_HelmetB;
class H_Cap_red;
class H_Bandanna_khk;
class rhs_booniehat2_marpatd;
// RHSSAF
class rhssaf_helmet_base : H_HelmetB{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m59_85_nocamo : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m59_85_oakleaf : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_olive_nocamo : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_olive_nocamo_black_ess : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_olive_nocamo_black_ess_bare: rhssaf_helmet_m97_olive_nocamo_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_black_nocamo : rhssaf_helmet_m97_olive_nocamo{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_black_nocamo_black_ess : rhssaf_helmet_m97_olive_nocamo_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_black_nocamo_black_ess_bare: rhssaf_helmet_m97_olive_nocamo_black_ess_bare{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_woodland : rhssaf_helmet_base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_digital : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_md2camo : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_oakleaf : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_nostrap_blue : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_nostrap_blue_tan_ess : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_nostrap_blue_tan_ess_bare : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_woodland_black_ess : rhssaf_helmet_m97_olive_nocamo_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_digital_black_ess : rhssaf_helmet_m97_woodland_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_md2camo_black_ess : rhssaf_helmet_m97_woodland_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_oakleaf_black_ess : rhssaf_helmet_m97_woodland_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_woodland_black_ess_bare: rhssaf_helmet_m97_woodland_black_ess{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_digital_black_ess_bare : rhssaf_helmet_m97_woodland_black_ess_bare{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_md2camo_black_ess_bare : rhssaf_helmet_m97_woodland_black_ess_bare{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_oakleaf_black_ess_bare : rhssaf_helmet_m97_woodland_black_ess_bare{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_veil_Base : rhssaf_helmet_m97_woodland{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_veil_woodland : rhssaf_helmet_m97_veil_Base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_veil_digital : rhssaf_helmet_m97_veil_Base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_veil_md2camo : rhssaf_helmet_m97_veil_Base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_helmet_m97_veil_oakleaf : rhssaf_helmet_m97_veil_Base{
rgoc_canAcceptNVG = 1;
};
class rhssaf_beret_green : rhssaf_helmet_base{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_red : rhssaf_beret_green{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_para : rhssaf_beret_green{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_black : rhssaf_beret_green{
rgoc_canAcceptNVG = 0;
};
class rhssaf_beret_blue_un : rhssaf_helmet_base{
rgoc_canAcceptNVG = 0;
};
class rhssaf_booniehat_digital: rhs_booniehat2_marpatd{
rgoc_canAcceptNVG = 0;
};
class rhssaf_booniehat_md2camo: rhs_booniehat2_marpatd{
rgoc_canAcceptNVG = 0;
};
class rhssaf_booniehat_woodland: rhs_booniehat2_marpatd{
rgoc_canAcceptNVG = 0;
};
class rhssaf_bandana_digital: H_Bandanna_khk{
rgoc_canAcceptNVG = 0;
};
class rhssaf_bandana_digital_desert: rhssaf_bandana_digital{
rgoc_canAcceptNVG = 0;
};
class rhssaf_bandana_oakleaf: rhssaf_bandana_digital{
rgoc_canAcceptNVG = 0;
};
class rhssaf_bandana_smb: rhssaf_bandana_digital{
rgoc_canAcceptNVG = 0;
};
class rhssaf_bandana_md2camo: rhssaf_bandana_digital{
rgoc_canAcceptNVG = 0;
};
}; | finesseseth/SOCOMD | rgoc_rhssaf_compat/CfgWeapons.hpp | C++ | gpl-3.0 | 4,218 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package services;
import FareCalculator.Calculate;
import java.util.ArrayList;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.lang.ClassNotFoundException;
import java.net.URI;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import localstorage.FaresType;
/**
*
* @author peppa
*/
@Path("/")
public class calculatorService {
@Context
private UriInfo context;
public calculatorService(){
}
@GET
@Path("/calculate")
@Produces({"application/xml"})
public Response fareCalculator(@DefaultValue("TK") @QueryParam("carrier") String carrier,
@DefaultValue("2012-01-01") @QueryParam("date") String date,
@DefaultValue("ADB") @QueryParam("origCode") String origCode,
@DefaultValue("ESB") @QueryParam("destCode") String destCode,
@DefaultValue("Economy") @QueryParam("fareClass") String fareClass) {
Calculate cal = new Calculate();
FaresType fare = cal.fareCalculate(carrier, date, origCode, destCode, fareClass);
return Response.ok(new JAXBElement<FaresType>(new QName("faresType"), FaresType.class, fare)).build();
}
}
| ecemandirac/FlightTracker | Fare_Module/src/java/services/calculatorService.java | Java | gpl-3.0 | 1,825 |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Globalization
Imports System.Resources
Imports System.Windows
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("Viewport Reporting for Revit 2015")>
<Assembly: AssemblyDescription("Viewport Reporting for Revit 2015")>
<Assembly: AssemblyCompany("Case Design, Inc.")>
<Assembly: AssemblyProduct("Viewport Reporting for Revit 2015")>
<Assembly: AssemblyCopyright("Copyright @ Case Design, Inc. 2014")>
<Assembly: AssemblyTrademark("Case Design, Inc.")>
<Assembly: ComVisible(false)>
'In order to begin building localizable applications, set
'<UICulture>CultureYouAreCodingWith</UICulture> in your .vbproj file
'inside a <PropertyGroup>. For example, if you are using US english
'in your source files, set the <UICulture> to "en-US". Then uncomment the
'NeutralResourceLanguage attribute below. Update the "en-US" in the line
'below to match the UICulture setting in the project file.
'<Assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)>
'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found.
'1st parameter: where theme specific resource dictionaries are located
'(used if a resource is not found in the page,
' or application resource dictionaries)
'2nd parameter: where the generic resource dictionary is located
'(used if a resource is not found in the page,
'app, and any theme specific resource dictionaries)
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("c93af61b-e349-4300-985b-fc4a99f2897a")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("2014.6.2.0")>
<Assembly: AssemblyFileVersion("2014.6.2.0")>
| kmorin/case-apps | 2015/Case.ViewportReporting/Case.ViewportReporting/My Project/AssemblyInfo.vb | Visual Basic | gpl-3.0 | 2,384 |
package xyw.ning.juicer.poco.model;
import xyw.ning.juicer.base.NoProguard;
/**
* Created by Ning-win on 2016/7/30.
*/
public class Size implements NoProguard {
public String url;
public long width;
public long height;
}
| ningshu/Juicer | app/src/main/java/xyw/ning/juicer/poco/model/Size.java | Java | gpl-3.0 | 237 |
#include <gtest/gtest.h>
#include "math/integr/WeightedIntegral.h"
#include "math/integr/IntegrationDensities.h"
#include <stdexcept>
#include <cmath>
class WeightedIntegralTest: public testing::Test
{
};
TEST_F(WeightedIntegralTest,Test)
{
rql::integr::WeightedIntegral wi(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Constant(1.0));
const double integral = wi.integrate<double(*)(double)>(cos);
const double sin1 = sin(1.0);
ASSERT_NEAR(sin1, integral, 1E-5);
rql::integr::WeightedIntegral ws(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Sine(2.0));
const double integral2 = ws.integrate<double(*)(double)>(cos);
const double cos1 = cos(1.0);
const double expected2 = (1-pow(cos1, 3))*2.0/3;
ASSERT_NEAR(expected2, integral2, 1E-8);
rql::integr::WeightedIntegral wc(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Cosine(2.0));
const double integral3 = wc.integrate<double(*)(double)>(sin);
const double expected3 = (3*cos1 - cos(3.0)-2)/6.0;
ASSERT_NEAR(expected3, integral3, 1E-8);
}
double constant_one(double x)
{
return 1;
}
double linear(double x)
{
return x;
}
TEST_F(WeightedIntegralTest,Sine)
{
rql::integr::WeightedIntegral wu(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Constant(1.0));
const double integral_u = wu.integrate<double(*)(double)>(sin);
ASSERT_NEAR(1 - cos(1.0), integral_u, 1E-5) << "unity";
rql::integr::WeightedIntegral ws(rql::integr::WeightedIntegral::gen_xs(0, 1, 100), rql::integr::IntegrationDensities::Sine(1.0));
const double integral_s = ws.integrate(constant_one);
ASSERT_NEAR(1 - cos(1.0), integral_s, 1E-10) << "sine_weight";
const double integral_linear = ws.integrate(linear);
ASSERT_NEAR(sin(1.0) - cos(1.0), integral_linear, 1E-10);
}
| rilwen/open-quantum-systems | math-test/integr/WeightedIntegralTest.cpp | C++ | gpl-3.0 | 1,913 |
/********************************************************************
* a A
* AM\/MA
* (MA:MMD
* :: VD
* :: º
* ::
* :: ** .A$MMMMND AMMMD AMMM6 MMMM MMMM6
+ 6::Z. TMMM MMMMMMMMMDA VMMMD AMMM6 MMMMMMMMM6
* 6M:AMMJMMOD V MMMA VMMMD AMMM6 MMMMMMM6
* :: TMMTMC ___MMMM VMMMMMMM6 MMMM
* MMM TMMMTTM, AMMMMMMMM VMMMMM6 MMMM
* :: MM TMMTMMMD MMMMMMMMMM MMMMMM MMMM
* :: MMMTTMMM6 MMMMMMMMMMM AMMMMMMD MMMM
* :. MMMMMM6 MMMM MMMM AMMMMMMMMD MMMM
* TTMMT MMMM MMMM AMMM6 MMMMD MMMM
* TMMMM8 MMMMMMMMMMM AMMM6 MMMMD MMMM
* TMMMMMM$ MMMM6 MMMM AMMM6 MMMMD MMMM
* TMMM MMMM
* TMMM .MMM
* TMM .MMD ARBITRARY·······XML········RENDERING
* TMM MMA ====================================
* TMN MM
* MN ZM
* MM,
*
*
* AUTHORS: see AUTHORS file
*
* COPYRIGHT: ©2019 - All Rights Reserved
*
* LICENSE: see LICENSE file
*
* WEB: http://axrproject.org
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS"
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR
* FITNESS FOR A PARTICULAR PURPOSE.
*
********************************************************************/
#ifndef HSSEVENTSELECTOR_H
#define HSSEVENTSELECTOR_H
#include "HSSNameSelector.h"
namespace AXR
{
/**
* @brief The special object \@event in HSS.
*
* Used in selector chains, returns a special object that contains
* information about an event.
*/
class AXR_API HSSEventSelector : public HSSNameSelector
{
public:
/**
* Creates a new instance of a event selector.
*/
HSSEventSelector(AXRController * controller);
/**
* Clones an instance of HSSEventSelector and gives a shared pointer of the
* newly instanciated object.
* @return A shared pointer to the new HSSEventSelector
*/
QSharedPointer<HSSEventSelector> clone() const;
//see HSSNameSelector.h for the documentation of this method
AXRString getElementName();
//see HSSParserNode.h for the documentation of this method
virtual AXRString toString();
//see HSSParserNode.h for the documentation of this method
AXRString stringRep();
QSharedPointer<HSSSelection> filterSelection(QSharedPointer<HSSSelection> scope, QSharedPointer<HSSDisplayObject> thisObj, bool processing, bool subscribingToNotifications);
private:
virtual QSharedPointer<HSSClonable> cloneImpl() const;
};
}
#endif
| axr/core | src/core/hss/values/selectors/HSSEventSelector.h | C | gpl-3.0 | 2,991 |
/*
* Copyright (C) 2014 Matej Kormuth <http://matejkormuth.eu>
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package ts3bot.helpers;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Helper for testing method signatures.
*/
public final class MethodSignatureTester {
// Object methods.
private static final List<MethodSignature> objectMethodSignatures = new ArrayList<MethodSignatureTester.MethodSignature>();
static {
for (Method m : Object.class.getDeclaredMethods()) {
objectMethodSignatures.add(new MethodSignature(m.getName(),
m.getParameterTypes()));
}
}
/**
* Checks whether specified interface declares all of public methods implementation class declares.
*
* @param impl
* implementation class
* @param interf
* interface class
* @throws RuntimeException
* When interface does not declare public method implementation class does
*/
public static final void hasInterfAllImplPublicMethods(final Class<?> impl,
final Class<?> interf) {
List<MethodSignature> interfMethodSignatures = new ArrayList<MethodSignature>(
100);
// Generate interface method signatures.
for (Method m : interf.getDeclaredMethods()) {
// Interface has only public abstract methods.
interfMethodSignatures.add(new MethodSignature(m.getName(),
m.getParameterTypes()));
}
for (Method m : impl.getDeclaredMethods()) {
// Checking only public methods.
MethodSignature ms;
if (Modifier.isPublic(m.getModifiers())) {
// Build method signature.
ms = new MethodSignature(m.getName(), m.getParameterTypes());
// Don't check methods derived from Object.
if (!objectMethodSignatures.contains(ms)) {
// Check if interface declares it.
if (!interfMethodSignatures.contains(ms)) { throw new RuntimeException(
"Interface '" + interf.getName()
+ "' does not declare method " + ms.toString()
+ " implemented in class '" + impl.getName() + "'!"); }
}
}
}
}
/**
* Class that specified method signature in Java.
*/
private static class MethodSignature {
private final String name;
private final Class<?>[] params;
public MethodSignature(final String name, final Class<?>[] params) {
this.name = name;
this.params = params;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result
+ ((this.params == null) ? 0 : this.params.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
MethodSignature other = (MethodSignature) obj;
if (this.name == null) {
if (other.name != null)
return false;
}
else if (!this.name.equals(other.name))
return false;
if (this.params == null) {
if (other.params != null)
return false;
}
else if (this.params.length != other.params.length)
return false;
for (int i = 0; i < this.params.length; i++) {
if (!this.params[i].equals(other.params[i])) { return false; }
}
return true;
}
@Override
public String toString() {
return "MethodSignature [name=" + this.name + ", params="
+ Arrays.toString(this.params) + "]";
}
}
}
| dobrakmato/Sergius | src/test/java/ts3bot/helpers/MethodSignatureTester.java | Java | gpl-3.0 | 4,969 |
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6" > <![endif]-->
<!--[if IE 7]> <html class="no-js ie7" > <![endif]-->
<!--[if IE 8]> <html class="no-js ie8" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="generator" content="pandoc" />
<meta name="description" content="Responsive Web Design" />
<meta name="author" content="Adolfo Sanz De Diego" />
<title>Responsive Web Design</title>
<!-- deck core css -->
<link rel="stylesheet" href="../lib/deck.js-master/core/deck.core.css">
<!-- deck extensions css -->
<link rel="stylesheet" href="../lib/deck.js-master/extensions/goto/deck.goto.css">
<link rel="stylesheet" href="../lib/deck.js-master/extensions/menu/deck.menu.css">
<link rel="stylesheet" href="../lib/deck.js-master/extensions/navigation/deck.navigation.css">
<link rel="stylesheet" href="../lib/deck.js-master/extensions/scale/deck.scale.css">
<link rel="stylesheet" href="../lib/deck.js-master/extensions/status/deck.status.css">
<!-- deck slide theme css -->
<link rel="stylesheet" href="../lib/deck.js-master/themes/style/web-2.0.css">
<!--
<link rel="stylesheet" href="../lib/deck.js-master/themes/style/neon.css">
<link rel="stylesheet" href="../lib/deck.js-master/themes/style/swiss.css">
<link rel="stylesheet" href="../lib/deck.js-master/themes/style/web-2.0.css">
-->
<!-- deck slide transition css -->
<link rel="stylesheet" href="../lib/deck.js-transition-cube-master/cube.css">
<!--
<link rel="stylesheet" href="../lib/deck.js-transition-cube-master/cube.css">
<link rel="stylesheet" href="../lib/deck.js-master/themes/transition/fade.css">
<link rel="stylesheet" href="../lib/deck.js-master/themes/transition/horizontal-slide.css">
<link rel="stylesheet" href="../lib/deck.js-master/themes/transition/vertical-slide.css">
-->
<!-- custom css just for this page -->
<style>
figcaption {
display: none;
visibility:hidden;
}
#titlepage, #documentauthor, #documentdate {
text-align: center;
}
#titlepage {
font-size: 5.25em;
padding-top: 15%;
}
#documentauthor {
font-size: 2.25em;
}
#documentdate {
font-size: 1.25em;
}
</style>
<!-- modernizr deck js -->
<script src="../lib/deck.js-master/modernizr.custom.js"></script>
</head>
<body class="deck-container">
<section class="slide">
<h2 id="titlepage">Responsive Web Design</h2>
<h3 id="documentauthor">Adolfo Sanz De Diego</h3>
<h4 id="documentdate">Septiembre 2014</h4>
</section>
<section id="el-autor" class="titleslide slide level1"><h1><span class="header-section-number">1</span> El autor</h1></section><section id="adolfo-sanz-de-diego" class="slide level2">
<h2><span class="header-section-number">1.1</span> Adolfo Sanz De Diego</h2>
<ul>
<li><p><strong>Antiguo programador web JEE (6 años)</strong></p></li>
<li><p>Hoy en día:</p>
<ul>
<li><strong>Profesor de FP (6 años)</strong>:
<ul>
<li>Hardware, Sistemas Operativos</li>
<li>Redes, Programación</li>
</ul></li>
<li><strong>Formador Freelance (3 años)</strong>:
<ul>
<li>Java, Android</li>
<li>JavaScript, jQuery</li>
<li>JSF, Spring, Hibernate</li>
<li>Groovy & Grails</li>
</ul></li>
</ul></li>
</ul>
</section><section id="algunos-proyectos" class="slide level2">
<h2><span class="header-section-number">1.2</span> Algunos proyectos</h2>
<ul>
<li><p>Fundador y/o creador:</p>
<ul>
<li><strong>Hackathon Lovers</strong>: <a href="http://hackathonlovers.com">http://hackathonlovers.com</a></li>
<li><strong>Tweets Sentiment</strong>: <a href="http://tweetssentiment.com">http://tweetssentiment.com</a></li>
<li><strong>MarkdownSlides</strong>: <a href="https://github.com/asanzdiego/markdownslides">https://github.com/asanzdiego/markdownslides</a></li>
</ul></li>
<li><p>Co-fundador y/o co-creador:</p>
<ul>
<li><strong>PeliTweets</strong>: <a href="http://pelitweets.com">http://pelitweets.com</a></li>
<li><strong>Password Manager Generator</strong>: <a href="http://pasmangen.github.io">http://pasmangen.github.io</a></li>
</ul></li>
</ul>
</section><section id="donde-encontrarme" class="slide level2">
<h2><span class="header-section-number">1.3</span> ¿Donde encontrarme?</h2>
<ul>
<li><p>Mi nick: <strong>asanzdiego</strong></p>
<ul>
<li>AboutMe: <a href="http://about.me/asanzdiego">http://about.me/asanzdiego</a></li>
<li>GitHub: <a href="http://github.com/asanzdiego">http://github.com/asanzdiego</a></li>
<li>Twitter: <a href="http://twitter.com/asanzdiego">http://twitter.com/asanzdiego</a></li>
<li>Blog: <a href="http://asanzdiego.blogspot.com.es">http://asanzdiego.blogspot.com.es</a></li>
<li>LinkedIn: <a href="http://www.linkedin.com/in/asanzdiego">http://www.linkedin.com/in/asanzdiego</a></li>
<li>Google+: <a href="http://plus.google.com/+AdolfoSanzDeDiego">http://plus.google.com/+AdolfoSanzDeDiego</a></li>
</ul></li>
</ul>
</section>
<section id="introducción" class="titleslide slide level1"><h1><span class="header-section-number">2</span> Introducción</h1></section><section id="esto-no-es-la-web" class="slide level2">
<h2><span class="header-section-number">2.1</span> Esto no es la web</h2>
<figure>
<img src="../img/brad_frost_1.png" alt="Esto no es la web. Fuente: bradfostweb.com" /><figcaption>Esto no es la web. Fuente: bradfostweb.com</figcaption>
</figure>
</section><section id="esto-es-la-web" class="slide level2">
<h2><span class="header-section-number">2.2</span> Esto es la web</h2>
<figure>
<img src="../img/brad_frost_2.png" alt="Esto es la web. Fuente: bradfostweb.com" /><figcaption>Esto es la web. Fuente: bradfostweb.com</figcaption>
</figure>
</section><section id="será-esto-la-web" class="slide level2">
<h2><span class="header-section-number">2.3</span> ¿Será esto la web?</h2>
<figure>
<img src="../img/brad_frost_3.png" alt="¿Será esto la web?. Fuente: bradfostweb.com" /><figcaption>¿Será esto la web?. Fuente: bradfostweb.com</figcaption>
</figure>
</section><section id="estadísticas" class="slide level2">
<h2><span class="header-section-number">2.4</span> Estadísticas</h2>
<figure>
<img src="../img/StatCounter-resolution-ww-monthly-200903-201408.jpeg" alt="Estadísticas. Fuente: gs.statcounter.com" /><figcaption>Estadísticas. Fuente: gs.statcounter.com</figcaption>
</figure>
</section><section id="el-desarrollador" class="slide level2">
<h2><span class="header-section-number">2.5</span> El desarrollador</h2>
<figure>
<img src="../img/globalmoxie.png" alt="El desarrollador atual. Fuente: globalmoxie.com" /><figcaption>El desarrollador atual. Fuente: globalmoxie.com</figcaption>
</figure>
</section><section id="responsive-web-design" class="slide level2">
<h2><span class="header-section-number">2.6</span> Responsive Web Design</h2>
<figure>
<img src="../img/rwd.png" alt="Responsive Web Design. Fuente: flickr.com/photos/zergev/" /><figcaption>Responsive Web Design. Fuente: flickr.com/photos/zergev/</figcaption>
</figure>
</section><section id="content-is-like-water" class="slide level2">
<h2><span class="header-section-number">2.7</span> Content is like water</h2>
<figure>
<img src="../img/content-is-like-water.jpg" alt="Content is like water. Fuente: fr.wikipedia.org/wiki/Site_web_adaptatif" /><figcaption>Content is like water. Fuente: fr.wikipedia.org/wiki/Site_web_adaptatif</figcaption>
</figure>
</section><section id="graceful-degradation" class="slide level2">
<h2><span class="header-section-number">2.8</span> Graceful degradation</h2>
<ul>
<li>Se <strong>desarrolla para los últimos navegadores</strong>, con la posibilidad de que funcione en navegadores antiguos.</li>
</ul>
<figure>
<img src="../img/responsive-design-graceful-degradation.png" alt="Graceful degradation. Fuente: bradfostweb.com" /><figcaption>Graceful degradation. Fuente: bradfostweb.com</figcaption>
</figure>
</section><section id="progessive-enhancement" class="slide level2">
<h2><span class="header-section-number">2.9</span> Progessive enhancement</h2>
<ul>
<li>Se <strong>desarrolla una versión básica</strong> completamente operativa, con la posibilidad de ir añadiendo mejoras para los últimos navegadores.</li>
</ul>
<figure>
<img src="../img/responsive-design-progressive-enhancement.png" alt="Progressive enhancement. Fuente: bradfostweb.com" /><figcaption>Progressive enhancement. Fuente: bradfostweb.com</figcaption>
</figure>
</section><section id="beneficios-i" class="slide level2">
<h2><span class="header-section-number">2.10</span> Beneficios (I)</h2>
<ul>
<li><p><strong>Reducción de costos</strong>. Pues no hay que hacer varias versiones de una misma página.</p></li>
<li><p><strong>Eficiencia en la actualización</strong>. El sitio solo se debe actualizar una vez y se ve reflejada en todas las plataformas.</p></li>
<li><p><strong>Mejora la usabilidad</strong>. El usuario va a tener experiencias de usuario parecidas independientemente del dispositivo que esté usando en cada momento</p></li>
</ul>
</section><section id="beneficios-ii" class="slide level2">
<h2><span class="header-section-number">2.11</span> Beneficios (II)</h2>
<ul>
<li><p><strong>Mejora el SEO</strong>. Según las Guidelines de Google el tener una web que se vea correctamente en móviles es un factor que tienen en cuenta a la hora de elaborar los rankings.</p></li>
<li><p><strong>Impacto en el visitante</strong>. Esta tecnología por ser nueva genera impacto en las personas que la vean en acción, lo que permitirá asociar a la marca con creatividad e innovación.</p></li>
</ul>
</section>
<section id="ejemplos" class="titleslide slide level1"><h1><span class="header-section-number">3</span> Ejemplos</h1></section><section id="matt-kersley" class="slide level2">
<h2><span class="header-section-number">3.1</span> Matt Kersley</h2>
<ul>
<li>Página de testeo de Matt Kersley
<ul>
<li><a href="http://mattkersley.com/responsive">http://mattkersley.com/responsive</a></li>
</ul></li>
</ul>
</section><section id="dconstruct-2011" class="slide level2">
<h2><span class="header-section-number">3.2</span> dConstruct 2011</h2>
<ul>
<li><a href="http://2011.dconstruct.org">http://2011.dconstruct.org</a></li>
</ul>
<figure>
<img src="../img/dConstruct-2011-ejemplo-de-Responsive-Web-Design.jpg" alt="Ejemplo RWD: dConstruct 2011. Fuente:ecbloguer.com" /><figcaption>Ejemplo RWD: dConstruct 2011. Fuente:ecbloguer.com</figcaption>
</figure>
</section><section id="boston-globe" class="slide level2">
<h2><span class="header-section-number">3.3</span> Boston Globe</h2>
<ul>
<li><a href="http://www.bostonglobe.com">http://www.bostonglobe.com</a></li>
</ul>
<figure>
<img src="../img/Boston-Globe-ejemplo-de-Responsive-Web-Design.jpg" alt="Ejemplo RWD: Boston Globe. Fuente:ecbloguer.com" /><figcaption>Ejemplo RWD: Boston Globe. Fuente:ecbloguer.com</figcaption>
</figure>
</section><section id="food-sense" class="slide level2">
<h2><span class="header-section-number">3.4</span> Food Sense</h2>
<ul>
<li><a href="http://foodsense.is">http://foodsense.is</a></li>
</ul>
<figure>
<img src="../img/Food-Sense-ejemplo-de-Responsive-Web-Design.jpg" alt="Ejemplo RWD: Food Sense. Fuente:ecbloguer.com" /><figcaption>Ejemplo RWD: Food Sense. Fuente:ecbloguer.com</figcaption>
</figure>
</section><section id="deren-keskin" class="slide level2">
<h2><span class="header-section-number">3.5</span> Deren Keskin</h2>
<ul>
<li><a href="http://www.deren.me">http://www.deren.me</a></li>
</ul>
<figure>
<img src="../img/Deren-Keskin-ejemplo-de-Responsive-Web-Design.jpg" alt="Ejemplo RWD: Deren Keskin. Fuente:ecbloguer.com" /><figcaption>Ejemplo RWD: Deren Keskin. Fuente:ecbloguer.com</figcaption>
</figure>
</section>
<section id="diseño-fluido" class="titleslide slide level1"><h1><span class="header-section-number">4</span> Diseño fluido</h1></section><section id="de-px-a-em" class="slide level2">
<h2><span class="header-section-number">4.1</span> De PX a EM</h2>
<ul>
<li><p>Formula: <strong>target ÷ context = result</strong></p>
<ul>
<li>target - font-size que tenemos en píxeles</li>
<li>context - font-size base (por defecto 16px en la mayoría de los navegadores)</li>
<li>result - resultado que obtenemos en em</li>
</ul></li>
<li><p>Es recomendable indicar el cálculo realizado junto a la regla de CSS.</p></li>
</ul>
</section><section id="on-line" class="slide level2">
<h2><span class="header-section-number">4.2</span> On Line</h2>
<ul>
<li><a href="http://pxtoem.com">http://pxtoem.com</a></li>
</ul>
<figure>
<img src="../img/pxtoem.png" alt="px to em. Fuente:pxtoem.com" /><figcaption>px to em. Fuente:pxtoem.com</figcaption>
</figure>
</section><section id="ejemplo" class="slide level2">
<h2><span class="header-section-number">4.3</span> Ejemplo</h2>
<ul>
<li>Ejemplo para poner 13px por defecto y luego 18px para h1 en em:</li>
</ul>
<pre><code>body {
font: 13px;
}
h1 {
font-size: 1.3846 em;
/* 18px/13px = 1.3846em */
}</code></pre>
</section><section id="em-se-hereda" class="slide level2">
<h2><span class="header-section-number">4.4</span> EM se hereda</h2>
<ul>
<li><p>Importante: <strong>las medidas em se heredan</strong>, es decir, un elemento dentro de un elemento tomará como referencia el superior para calcular cuánto es un em.</p></li>
<li><p>Por ejemplo, si tenemos una caja donde hemos definido una fuente como 0.5em y dentro de esa caja otra con una fuente 0.25em, esta última fuente tendrá 1/4 de tamaño respecto a la 1/2 de tamaño de la fuente general.</p></li>
</ul>
</section><section id="de-px-a" class="slide level2">
<h2><span class="header-section-number">4.5</span> De PX a %</h2>
<figure>
<img src="../img/porcentajes.jpg" alt="Cálculo porcentajes. Fuente:aloud.es" /><figcaption>Cálculo porcentajes. Fuente:aloud.es</figcaption>
</figure>
</section>
<section id="sistema-de-rejilla" class="titleslide slide level1"><h1><span class="header-section-number">5</span> Sistema de rejilla</h1></section><section id="ejemplo-1" class="slide level2">
<h2><span class="header-section-number">5.1</span> Ejemplo</h2>
<ul>
<li>1 columna para xs (<768px)</li>
<li>2 columnas para sm (≥768px)</li>
<li>3 columnas para md (≥992px)</li>
<li>4 columnas para lg (≥1200px)</li>
</ul>
</section><section id="uso-de-clases" class="slide level2">
<h2><span class="header-section-number">5.2</span> Uso de clases</h2>
<ul>
<li>Uso de clases en el HTML como <strong>Bootstrap</strong>
<ul>
<li><a href="http://getbootstrap.com/css">http://getbootstrap.com/css</a></li>
</ul></li>
</ul>
</section><section id="ejemplo-bootstrap" class="slide level2">
<h2><span class="header-section-number">5.3</span> Ejemplo Bootstrap</h2>
<pre><code><div class="row">
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">1</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">2</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">3</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-3">4</div>
</div></code></pre>
</section><section id="semántico" class="slide level2">
<h2><span class="header-section-number">5.4</span> Semántico</h2>
<ul>
<li><strong>The Semantic Grid System</strong>: Mediante layouts, y sin necesidad de usar clases en HTML.
<ul>
<li><a href="http://semantic.gs">http://semantic.gs</a></li>
</ul></li>
</ul>
</section><section id="ejemplo-semantic.gs-html" class="slide level2">
<h2><span class="header-section-number">5.5</span> Ejemplo semantic.gs (HTML)</h2>
<pre><code><header>...</header>
<article>...</article>
<aside>...</aside></code></pre>
</section><section id="ejemplo-semantic.gs-css" class="slide level2">
<h2><span class="header-section-number">5.6</span> Ejemplo semantic.gs (CSS)</h2>
<pre><code>@column-width: 60;
@gutter-width: 20;
@columns: 12;
header { .column(12); }
article { .column(9); }
aside { .column(3); }
@media (max-device-width: 960px) {
article { .column(12); }
aside { .column(12); }
}</code></pre>
</section>
<section id="imágenes-fluidas" class="titleslide slide level1"><h1><span class="header-section-number">6</span> Imágenes fluidas</h1></section><section id="tamaño-máximo" class="slide level2">
<h2><span class="header-section-number">6.1</span> Tamaño máximo</h2>
<ul>
<li>Fijar un <strong>tamaño máximo</strong> (si la imagen no llega, se queda con su tamaño):</li>
</ul>
<pre><code>img {
max-width:400px;
}</code></pre>
</section><section id="ancho-del-contenedor-i" class="slide level2">
<h2><span class="header-section-number">6.2</span> Ancho del contenedor (I)</h2>
<ul>
<li>Ocupar el <strong>ancho del contenedor</strong> (si la imagen no llega, se deforma):</li>
</ul>
<pre><code>img {
width:100%;
}</code></pre>
</section><section id="ancho-del-contenedor-ii" class="slide level2">
<h2><span class="header-section-number">6.3</span> Ancho del contenedor (II)</h2>
<ul>
<li>Ocupar el <strong>ancho del contenedor</strong> (si la imagen no llega, se queda con su tamaño):</li>
</ul>
<pre><code>img {
max-width:100%;
}</code></pre>
</section><section id="ancho-del-contenedor-iii" class="slide level2">
<h2><span class="header-section-number">6.4</span> Ancho del contenedor (III)</h2>
<ul>
<li>Ocupar el <strong>ancho del contenedor hasta un máximo</strong> (si la imagen no llega, se deforma):</li>
</ul>
<pre><code>img {
width:100%;
max-width:400px;
}</code></pre>
</section><section id="backgrounds" class="slide level2">
<h2><span class="header-section-number">6.5</span> Backgrounds</h2>
<ul>
<li>Para los background usar <strong>cover</strong></li>
</ul>
<pre><code>.background-fluid {
width: 100%;
background-image:
url(img/water.jpg);
background-size: cover;
}</code></pre>
</section>
<section id="viewport" class="titleslide slide level1"><h1><span class="header-section-number">7</span> Viewport</h1></section><section id="orígenes" class="slide level2">
<h2><span class="header-section-number">7.1</span> Orígenes</h2>
<ul>
<li><p>La etiqueta meta para el viewport fue <strong>introducida por Apple</strong> en Safari para móviles en el año 2007, para ayudar a los desarrolladores a mejorar la presentación de sus aplicaciones web en un iPhone.</p></li>
<li><p>Hoy en día ha sido <strong>ampliamente adoptada por el resto de navegadores móviles</strong>, convirtiéndose en un estándar de facto.</p></li>
</ul>
</section><section id="qué-nos-permite" class="slide level2">
<h2><span class="header-section-number">7.2</span> ¿Qué nos permite?</h2>
<ul>
<li>La etiqueta viewport nos permite definir el <strong>ancho, alto y escala del área</strong> usada por el navegador para mostrar contenido.</li>
</ul>
</section><section id="tamaño" class="slide level2">
<h2><span class="header-section-number">7.3</span> Tamaño</h2>
<ul>
<li><p>Al fijar el ancho (width) o alto (height) del viewport, <strong>podemos usar un número fijo de pixeles</strong> (ej: 320px, 480px, etc) <strong>o usar dos constantes, device-width y device-height</strong> respectivamente.</p></li>
<li><p>Se considera una <strong>buena práctica configurar el viewport con device-width y device-height</strong>, en lugar de utilizar un ancho o alto fijo.</p></li>
</ul>
</section><section id="escala" class="slide level2">
<h2><span class="header-section-number">7.4</span> Escala</h2>
<ul>
<li><p>La propiedad <strong>initial-scale</strong> controla el nivel de zoom inicial al cargarse la página.</p></li>
<li><p>Las propiedades <strong>maximum-scale, minimum-scale</strong> controlan el nivel máximo y mínimo de zoom que se le va a permitir usar al usuario.</p></li>
<li><p>La propiedad <strong>user-scalable [yes|no]</strong> controlan si el usuario puede o no hacer zoom sobre la página.</p></li>
</ul>
</section><section id="accesibilidad" class="slide level2">
<h2><span class="header-section-number">7.5</span> Accesibilidad</h2>
<ul>
<li>Es una <strong>buena práctica de accesibilidad no bloquear las opciones de zoom</strong> al usuario.</li>
</ul>
</section><section id="ejemplo-2" class="slide level2">
<h2><span class="header-section-number">7.6</span> Ejemplo</h2>
<ul>
<li>Un ejemplo adaptable y accesible sería:</li>
</ul>
<pre><code><meta name="viewport"
content="width=device-width,
initial-scale=1,
user-scalable=yes"></code></pre>
</section>
<section id="media-queries" class="titleslide slide level1"><h1><span class="header-section-number">8</span> Media Queries</h1></section><section id="qué-son" class="slide level2">
<h2><span class="header-section-number">8.1</span> ¿Qué son?</h2>
<p>Un Media Query <strong>no sólo nos permite seleccionar el tipo de medio</strong> (all, braille, print, proyection, screen, tty, tv, etc.), <strong>sino además consultar otras características</strong> sobre el dispositivo que esta mostrando la página.</p>
</section><section id="ejemplo-3" class="slide level2">
<h2><span class="header-section-number">8.2</span> Ejemplo</h2>
<ul>
<li><strong>Ejemplo</strong>: aplicar distintas reglas CSS cuando el área de visualización sea mayor que 480px.</li>
</ul>
</section><section id="distintos-css" class="slide level2">
<h2><span class="header-section-number">8.3</span> Distintos CSS</h2>
<ul>
<li>Solución 1: <strong>cargar distintas CSS</strong>:</li>
</ul>
<pre><code><link rel="stylesheet"
type="text/css"
media="all and (min-width: 480px)"
href="tablet.css" />
<!-- tablet.css es un CSS con reglas para cuando el área de visualización sea mayor que 480px --></code></pre>
</section><section id="mismo-css" class="slide level2">
<h2><span class="header-section-number">8.4</span> Mismo CSS</h2>
<ul>
<li>Solución 2: <strong>definir distintas propiedades dentro del mismo CSS</strong>:</li>
</ul>
<pre><code>@media all and (min-width: 480px) {
/* aquí poner las reglas CSS
para cuando el área de visualización
sea mayor que 480px*/
}</code></pre>
</section><section id="importar-css" class="slide level2">
<h2><span class="header-section-number">8.5</span> Importar CSS</h2>
<ul>
<li>Solución 3: <strong>importar distintas hojas de estilo dentro del mismo CSS</strong>:</li>
</ul>
<pre><code>@import url("tablet.css")
all and (min-width: 480px);
/* tablet.css es un CSS con reglas
para cuando el área de visualización
sea mayor que 480px */
}</code></pre>
</section><section id="operador-and" class="slide level2">
<h2><span class="header-section-number">8.6</span> Operador and</h2>
<ul>
<li>Es usado para combinar múltiples media features en un sólo Media Query, <strong>requiriendo que cada función devuelve true</strong> para que el Query también lo sea.</li>
</ul>
</section><section id="ejemplo-and" class="slide level2">
<h2><span class="header-section-number">8.7</span> Ejemplo and</h2>
<pre><code>@media tv
and (min-width: 700px)
and (orientation: landscape) {
/* reglas que queremos que
se apliquen para televisiones
con áreas de visualización
mayores de 700px siempre que
la pantalla esté en
modo landscape */
}</code></pre>
</section><section id="operador-or" class="slide level2">
<h2><span class="header-section-number">8.8</span> Operador 'or'</h2>
<ul>
<li><p>Se pueden combinar múltiples Media Queries <strong>separados por comas</strong> en una lista, de tal forma que si alguna de las Media Queries devuelve true, todo la sentencia devolverá true.</p></li>
<li><p>Esto es <strong>equivalente a un operador or</strong>.</p></li>
<li><p>Cada Media Query separado por comas en la lista se trata individualmente.</p></li>
</ul>
</section><section id="ejemplo-or" class="slide level2">
<h2><span class="header-section-number">8.9</span> Ejemplo 'or'</h2>
<pre><code>@media tv,
(min-width: 700px),
(orientation: landscape) {
/* reglas que queremos que
se apliquen para televisiones,
o para dispositivos con áreas
de visualización mayores
de 700px, o cuando la pantalla
está en modo landscape */
}</code></pre>
</section><section id="operador-not" class="slide level2">
<h2><span class="header-section-number">8.10</span> Operador not</h2>
<ul>
<li><p>Se utiliza para <strong>negar un Media Query completo</strong>.</p></li>
<li><p>No se puede negar una característica individualmente, si no solamente el Media Query completo.</p></li>
</ul>
</section><section id="ejemplo-not-i" class="slide level2">
<h2><span class="header-section-number">8.11</span> Ejemplo not (I)</h2>
<pre><code>@media not tv and max-width(800px),
not screen and max-width(400px) {
/* reglas que queremos que
se apliquen para dispositivos
que no sean ni televisiones
con áreas de visualización
menores de 800px, ni pantallas
con áreas de visualización
menores de 400px */
}</code></pre>
</section><section id="ejemplo-not-ii" class="slide level2">
<h2><span class="header-section-number">8.12</span> Ejemplo not (II)</h2>
<ul>
<li>El anterior ejemplo sería equivalente a:</li>
</ul>
<pre><code>@media not (tv and max-width(800px)),
not (screen and max-width(400px)) {
...
}</code></pre>
</section><section id="características-i" class="slide level2">
<h2><span class="header-section-number">8.13</span> Características (I)</h2>
<ul>
<li><p>Características que hacen referencia al <strong>área de visualización</strong>:</p>
<ul>
<li><strong>width</strong></li>
<li><strong>height</strong></li>
<li><strong>aspect-ratio</strong> [4/3 | 16/9 | ...]</li>
<li><strong>orientation</strong> [portrait | landscape]</li>
</ul></li>
</ul>
</section><section id="características-ii" class="slide level2">
<h2><span class="header-section-number">8.14</span> Características (II)</h2>
<ul>
<li><p>Características que hacen referencia a la <strong>pantalla del dispositivo</strong>:</p>
<ul>
<li><strong>device-width</strong></li>
<li><strong>device-height</strong></li>
<li><strong>device-aspect-ratio</strong> [4/3 | 16/9 | ...]</li>
</ul></li>
</ul>
</section><section id="características-iii" class="slide level2">
<h2><span class="header-section-number">8.15</span> Características (III)</h2>
<ul>
<li><p><strong>Otras</strong> características:</p>
<ul>
<li><strong>color</strong>: El número de bits de profundidad de color</li>
<li><strong>monocrome</strong>: El número de bits de profundidad de color, en dispotivos monocromáticos</li>
<li><strong>resolution</strong>: Densidad de pixels en el dispositivo, medido en dpi</li>
</ul></li>
</ul>
</section><section id="min--y-max-" class="slide level2">
<h2><span class="header-section-number">8.16</span> Min- y Max-</h2>
<ul>
<li><p>A casi todas las características se les puede adjuntar los <strong>prefijos min- y max-</strong></p></li>
<li><p>De hecho lo habitual es usar dichos prefijos.</p></li>
</ul>
</section>
<section id="metodologías" class="titleslide slide level1"><h1><span class="header-section-number">9</span> Metodologías</h1></section><section id="desktop-vs-mobile" class="slide level2">
<h2><span class="header-section-number">9.1</span> Desktop VS Mobile</h2>
<figure>
<img src="../img/desktop-first-vs-mobile-first.png" alt="Desktop first VS Mobile first. Fuente: brettjankord.com" /><figcaption>Desktop first VS Mobile first. Fuente: brettjankord.com</figcaption>
</figure>
</section><section id="desktop-first" class="slide level2">
<h2><span class="header-section-number">9.2</span> Desktop First</h2>
<ul>
<li>Consiste en <strong>desarrollar para pantallas grandes</strong> y posteriormente adaptar el diseño a pantallas pequeñas.</li>
</ul>
</section><section id="df-utiliza-max-width" class="slide level2">
<h2><span class="header-section-number">9.3</span> DF: utiliza max-width</h2>
<ul>
<li>Normalmente los Media Queries utilizan <strong>max-width</strong>, simplificando y ajustando para las pantallas más pequeñas.</li>
</ul>
<pre><code>@media all and (max-width: 320px) {
/* Estilos para anchos
menores a 320px */
}
@media all and (max-width: 768px) {
/* Estilos para anchos
menores a 768px */
}</code></pre>
</section><section id="df-problemas" class="slide level2">
<h2><span class="header-section-number">9.4</span> DF: problemas</h2>
<ul>
<li><p>Los Media Query <strong>no están soportados por todos los móviles</strong>.</p></li>
<li><p>La <strong>versión móvil termina siendo una versión descafeinada</strong> de la web original.</p></li>
</ul>
</section><section id="mobile-first" class="slide level2">
<h2><span class="header-section-number">9.5</span> Mobile first</h2>
<ul>
<li>Consiste en <strong>desarrollar para pantallas pequeñas</strong> y posteriormente adaptar el diseño a pantallas grandes.</li>
</ul>
</section><section id="mf-utiliza-min-width" class="slide level2">
<h2><span class="header-section-number">9.6</span> MF: utiliza min-width</h2>
<ul>
<li>Ahora los Media Queries utilizan <strong>min-width</strong>, para ajustar el diseño a medida que aumenta el tamaño de pantalla.</li>
</ul>
<pre><code>@media all and (min-width: 320px) {
/* Estilos para anchos
superiores a 320px */
}
@media all and (min-width: 768px) {
/* Estilos para anchos
superiores a 768px */
}</code></pre>
</section><section id="mf-ventajas" class="slide level2">
<h2><span class="header-section-number">9.7</span> MF: ventajas</h2>
<ul>
<li><p>Funciona en <strong>móviles y/o navegadores antiguos</strong> que no soportan los Media Queries.</p></li>
<li><p>Normalmente la <strong>hoja de estilos resultante suele ser más sencilla</strong> que usando la otra vía.</p></li>
<li><p>Empezar por el móvil nos servirá para <strong>determinar de una manera más clara cual es el contenido realmente importante</strong> de nuestra web.</p></li>
</ul>
</section><section id="puntos-de-rotura-i" class="slide level2">
<h2><span class="header-section-number">9.8</span> Puntos de rotura (I)</h2>
<ul>
<li>Normalmente:
<ul>
<li>320px para el móvil,</li>
<li>768px para el tablet,</li>
<li>1024px para el portatil,</li>
<li>1200px para el sobremesa.</li>
</ul></li>
</ul>
</section><section id="puntos-de-rotura-ii" class="slide level2">
<h2><span class="header-section-number">9.9</span> Puntos de rotura (II)</h2>
<ul>
<li><p>Lo mejor sería que los puntos de rotura que aplicamos en los Media Query, fueran <strong>en función de nuestro contenido</strong>, en vez de en función del tamaño del dispositivo más vendido.</p></li>
<li><p>La manera de hacerlo: <strong>ir cambiando poco a poco el ancho del navegador y donde la web se rompa</strong>, aplicar un Media Query.</p></li>
</ul>
</section>
<section id="acerca-de" class="titleslide slide level1"><h1><span class="header-section-number">10</span> Acerca de</h1></section><section id="licencia" class="slide level2">
<h2><span class="header-section-number">10.1</span> Licencia</h2>
<ul>
<li>Estas <strong>transparencias</strong> están hechas con:
<ul>
<li>MarkdownSlides: <a href="https://github.com/asanzdiego/markdownslides">https://github.com/asanzdiego/markdownslides</a></li>
</ul></li>
<li>Estas <strong>transparencias</strong> están bajo una licencia Creative Commons Reconocimiento-CompartirIgual 3.0:
<ul>
<li><a href="http://creativecommons.org/licenses/by-sa/3.0/es">http://creativecommons.org/licenses/by-sa/3.0/es</a></li>
</ul></li>
</ul>
</section><section id="fuentes" class="slide level2">
<h2><span class="header-section-number">10.2</span> Fuentes</h2>
<ul>
<li>Transparencias:
<ul>
<li><a href="https://github.com/asanzdiego/curso-interfaces-web-2014/tree/master/03-rwd/slides">https://github.com/asanzdiego/curso-interfaces-web-2014/tree/master/03-rwd/slides</a></li>
</ul></li>
<li>Código:
<ul>
<li><a href="https://github.com/asanzdiego/curso-interfaces-web-2014/tree/master/03-rwd/src">https://github.com/asanzdiego/curso-interfaces-web-2014/tree/master/03-rwd/src</a></li>
</ul></li>
</ul>
</section><section id="bibliografía-i" class="slide level2">
<h2><span class="header-section-number">10.3</span> Bibliografía (I)</h2>
<ul>
<li>Responsive Web Design
<ul>
<li><a href="http://www.arkaitzgarro.com/responsive-web-design/index.html">http://www.arkaitzgarro.com/responsive-web-design/index.html</a></li>
</ul></li>
<li>Introducción al Diseño Web Adaptable o Responsive Web Design
<ul>
<li><a href="http://www.emenia.es/diseno-web-adaptable-o-responsive-web-design">http://www.emenia.es/diseno-web-adaptable-o-responsive-web-design</a></li>
</ul></li>
<li>Tutorial: Responsive Web Design
<ul>
<li><a href="http://www.mmfilesi.com/blog/tutorial-responsive-web-design-i">http://www.mmfilesi.com/blog/tutorial-responsive-web-design-i</a></li>
</ul></li>
</ul>
</section><section id="bibliografía-ii" class="slide level2">
<h2><span class="header-section-number">10.4</span> Bibliografía (II)</h2>
<ul>
<li>Tutorial: Transforma tu web en Responsive Design
<ul>
<li><a href="http://blog.ikhuerta.com/transforma-tu-web-en-responsive-design">http://blog.ikhuerta.com/transforma-tu-web-en-responsive-design</a></li>
</ul></li>
<li>Curso responsive web design - Redradix School
<ul>
<li><a href="http://www.slideshare.net/Redradix/curso-responsive-web-design-redradix-school">http://www.slideshare.net/Redradix/curso-responsive-web-design-redradix-school</a></li>
</ul></li>
<li>Todo lo que necesita saber sobre Responsive Web Design
<ul>
<li><a href="http://www.ecbloguer.com/marketingdigital/?p=2635">http://www.ecbloguer.com/marketingdigital/?p=2635</a></li>
</ul></li>
</ul>
</section><section id="bibliografía-iii" class="slide level2">
<h2><span class="header-section-number">10.5</span> Bibliografía (III)</h2>
<ul>
<li>Diseño web fluido y plantilla fluida con HTML5 y CSS3
<ul>
<li><a href="http://www.aloud.es/diseno-web-fluido-y-plantilla-fluida">http://www.aloud.es/diseno-web-fluido-y-plantilla-fluida</a></li>
</ul></li>
<li>Beneficios del Responsive Web Design en SEO
<ul>
<li><a href="http://madridnyc.com/blog/2013/01/29/beneficios-del-responsive-web-design-en-seo">http://madridnyc.com/blog/2013/01/29/beneficios-del-responsive-web-design-en-seo</a></li>
</ul></li>
<li>Responsive Web Design Testing Tool
<ul>
<li><a href="http://mattkersley.com/responsive">http://mattkersley.com/responsive</a></li>
</ul></li>
</ul>
</section><section id="bibliografía-iv" class="slide level2">
<h2><span class="header-section-number">10.6</span> Bibliografía (IV)</h2>
<ul>
<li>Responsive Web Design
<ul>
<li><a href="http://www.ricardocastillo.com/rwd.pdf">http://www.ricardocastillo.com/rwd.pdf</a></li>
</ul></li>
<li>Responsive Design y accesibilidad. Buenas y malas prácticas. Errores comunes.
<ul>
<li><a href="http://olgacarreras.blogspot.com.es/2014/01/responsive-design-y-accesibilidad.html">http://olgacarreras.blogspot.com.es/2014/01/responsive-design-y-accesibilidad.html</a></li>
</ul></li>
<li>Diseño web adaptativo: mejores prácticas
<ul>
<li><a href="http://www.emenia.es/diseno-web-adaptativo-mejores-practicas">http://www.emenia.es/diseno-web-adaptativo-mejores-practicas</a></li>
</ul></li>
</ul>
</section><section id="bibliografía-v" class="slide level2">
<h2><span class="header-section-number">10.7</span> Bibliografía (V)</h2>
<ul>
<li>Traducción de "Responsive Web Design" de "A List Apart"
<ul>
<li><a href="http://diseñowebresponsivo.com.ar">http://diseñowebresponsivo.com.ar</a></li>
</ul></li>
<li>Responsive Design Exercise
<ul>
<li><a href="http://blog.garciaechegaray.com/2013/11/29/responsive-design-exercise.html">http://blog.garciaechegaray.com/2013/11/29/responsive-design-exercise.html</a></li>
</ul></li>
</ul>
</section><section id="bibliografía-vi" class="slide level2">
<h2><span class="header-section-number">10.8</span> Bibliografía (VI)</h2>
<ul>
<li>Estadísticas de StatCounter
<ul>
<li><a href="http://gs.statcounter.com">http://gs.statcounter.com</a></li>
</ul></li>
<li>Página de testeo de Matt Kersley
<ul>
<li><a href="http://mattkersley.com/responsive">http://mattkersley.com/responsive</a></li>
</ul></li>
</ul>
</section>
<!--footer id="footer">
<h4 class="author"> Adolfo Sanz De Diego - Septiembre 2014</h4>
</footer-->
<!-- deck goto extension html -->
<form action="." method="get" class="goto-form">
<label for="goto-slide">Go to slide:</label>
<input type="text" name="slidenum" id="goto-slide" list="goto-datalist">
<datalist id="goto-datalist"></datalist>
<input type="submit" value="Go">
</form>
<!-- deck navigation extension html -->
<div aria-role="navigation">
<a href="#" class="deck-prev-link" title="Previous">←</a>
<a href="#" class="deck-next-link" title="Next">→</a>
</div>
<!-- deck status extension html -->
<p class="deck-status" aria-role="status">
<span class="deck-status-current"></span>
/
<span class="deck-status-total"></span>
</p>
<!-- jquery -->
<script src="../lib/deck.js-master/jquery.min.js"></script>
<!-- deck core js -->
<script src="../lib/deck.js-master/core/deck.core.js"></script>
<!-- deck extension js -->
<script src="../lib/deck.js-master/extensions/goto/deck.goto.js"></script>
<script src="../lib/deck.js-master/extensions/menu/deck.menu.js"></script>
<script src="../lib/deck.js-master/extensions/navigation/deck.navigation.js"></script>
<script src="../lib/deck.js-master/extensions/scale/deck.scale.js"></script>
<script src="../lib/deck.js-master/extensions/status/deck.status.js"></script>
<!--script src="../lib/deck.search.js-master/search/deck.search.js"></script-->
<!-- Initialize the deck. -->
<script>
$(function() {
$.deck('.slide');
});
</script>
</body>
</html>
| asanzdiego/curso-interfaces-web-2014 | 03-rwd/slides/export/rwd-deck-slides.html | HTML | gpl-3.0 | 37,701 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Abide.HaloLibrary.Halo2.Retail.Tag.Generated
{
using System;
using Abide.HaloLibrary;
using Abide.HaloLibrary.Halo2.Retail.Tag;
/// <summary>
/// Represents the generated weapon_shared_interface_struct_block tag block.
/// </summary>
public sealed class WeaponSharedInterfaceStructBlock : Block
{
/// <summary>
/// Initializes a new instance of the <see cref="WeaponSharedInterfaceStructBlock"/> class.
/// </summary>
public WeaponSharedInterfaceStructBlock()
{
this.Fields.Add(new PadField("", 16));
}
/// <summary>
/// Gets and returns the name of the weapon_shared_interface_struct_block tag block.
/// </summary>
public override string BlockName
{
get
{
return "weapon_shared_interface_struct_block";
}
}
/// <summary>
/// Gets and returns the display name of the weapon_shared_interface_struct_block tag block.
/// </summary>
public override string DisplayName
{
get
{
return "weapon_shared_interface_struct";
}
}
/// <summary>
/// Gets and returns the maximum number of elements allowed of the weapon_shared_interface_struct_block tag block.
/// </summary>
public override int MaximumElementCount
{
get
{
return 1;
}
}
/// <summary>
/// Gets and returns the alignment of the weapon_shared_interface_struct_block tag block.
/// </summary>
public override int Alignment
{
get
{
return 4;
}
}
}
}
| MikeMatt16/Abide | Abide Tag Definitions/Generated/Library/WeaponSharedInterfaceStructBlock.Generated.cs | C# | gpl-3.0 | 2,208 |
<?php
require('../../php/bdd.php');
$bdd->query('DELETE FROM general WHERE 1');
$reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)');
$reqe->execute(array(
"label" => 'titre_accueil',
"text" => $_POST['title']
));
$reqe->CloseCursor();
$reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)');
$reqe->execute(array(
"label" => 'text_accueil',
"text" => $_POST['text']
));
$reqe->CloseCursor();
$reqe = $bdd->prepare('INSERT INTO general (name, text, date) VALUES (:label, :text, 0)');
$reqe->execute(array(
"label" => 'foot_accueil',
"text" => $_POST['foot']
));
$reqe->CloseCursor();
echo "Effectué !";
?> | atomgenie/B2cave | b2cave/b2cave/admin/php/modif_general.php | PHP | gpl-3.0 | 703 |
Get required packages
=====================
``` r
library(devtools)
install.packages('tm')
install.packages("SnowballC")
devtools::install_github("cran/wordcloud")
```
Setup corpus
============
- Around here I became frustrated with the CamlCase inconsistencies. Oh well.
- The recursive argument doesn't seem to work, either. Something to investigate.
``` r
suppressPackageStartupMessages(library(tm))
project_dir <- "~/projects/9999-99-99_master_text_miner"
setwd(project_dir)
org_dir <- "~/projects/9999-99-99_master_text_miner/data"
org_dir_source <- DirSource(org_dir, recursive = FALSE)
agenda_corpus <- VCorpus(x=org_dir_source,
readerControl=
list(reader = reader(org_dir_source),
language = "en"))
```
Inspect the corpus
==================
- Structure of the corpus object
``` r
typeof(agenda_corpus)
str(agenda_corpus[1])
```
## [1] "list"
## List of 1
## $ computing.org:List of 2
## ..$ content: chr [1:4509] "* Document appearance and settings" "#+LINK: google http://www.google.com/search?q=%s" "#+TAGS: install(i) sysupdate(s) bug(b) config(c) laptop(l) desktop(d)" "#+DRAWERS: CODE HIDDEN" ...
## ..$ meta :List of 7
## .. ..$ author : chr(0)
## .. ..$ datetimestamp: POSIXlt[1:1], format: "2014-10-02 10:34:03"
## .. ..$ description : chr(0)
## .. ..$ heading : chr(0)
## .. ..$ id : chr "computing.org"
## .. ..$ language : chr "en"
## .. ..$ origin : chr(0)
## .. ..- attr(*, "class")= chr "TextDocumentMeta"
## ..- attr(*, "class")= chr [1:2] "PlainTextDocument" "TextDocument"
## - attr(*, "class")= chr [1:2] "VCorpus" "Corpus"
``` r
inspect(agenda_corpus[c(1, 4, 5)])
```
Tranformations and filtering
============================
- It is important to remove some content, such as punctuation, letter case, certain words, etc.
- what transformations are available?
``` r
getTransformations()
```
## [1] "removeNumbers" "removePunctuation" "removeWords"
## [4] "stemDocument" "stripWhitespace"
- Makes sense, except stem. [What's that?](http://en.wikipedia.org/wiki/Stemming). Oh, so reduce a compound or derivative words to their base. So, e.g. "computing", "computers", "computation", etc may be identified as "compute". Not a great example, since compute and computer are rather different. Digress.
- Undigress, that highlights that one should be familiar with the stemming algorithm. I'll assume it's OK for this exercise.
``` r
suppressPackageStartupMessages(library(SnowballC))
lapply(agenda_corpus, nchar)[[1]]
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(removeWords),
stopwords())
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(removePunctuation))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(removeNumbers))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(stripWhitespace))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(stemDocument))
lapply(agenda_corpus, nchar)[[1]]
```
## content meta
## 173970 272
## content meta
## 103882 272
- the transformations working, but removeWords with the org agenda terms wasn't working. A hack is implemented below for wordcloud.
- future project, pertaining to org specifically, is add custom transformations, e.g. DONE, TODO, NEXT etc
Create document term matrix
===========================
- Here's how to imagine a document term matrix
| doc | word1 | word2 | ... | wordN |
|----------|--------|--------|-----|--------|
| doc1.txt | freq11 | freq12 | ... | freq1N |
| doc2.txt | freq21 | freq22 | ... | freq2N |
| .... | ... | ..... | ... | ..... |
| docn.txt | freqn1 | freqn2 | ... | freqnN |
``` r
org_doc_term_matrix <- DocumentTermMatrix(agenda_corpus)
str(org_doc_term_matrix)
inspect(org_doc_term_matrix[, 1:10])
```
## List of 6
## $ i : int [1:13751] 1 1 1 1 1 1 1 1 1 1 ...
## $ j : int [1:13751] 9 10 14 15 24 26 27 28 40 41 ...
## $ v : num [1:13751] 6 1 1 1 2 7 2 1 2 3 ...
## $ nrow : int 7
## $ ncol : int 9126
## $ dimnames:List of 2
## ..$ Docs : chr [1:7] "computing.org" "fynanse.org" "personal.org" "physical.org" ...
## ..$ Terms: chr [1:9126] "aabout" "aac" "aacount" "aal" ...
## - attr(*, "class")= chr [1:2] "DocumentTermMatrix" "simple_triplet_matrix"
## - attr(*, "weighting")= chr [1:2] "term frequency" "tf"
## <<DocumentTermMatrix (documents: 7, terms: 10)>>
## Non-/sparse entries: 12/58
## Sparsity : 83%
## Maximal term length: 7
## Weighting : term frequency (tf)
##
## Terms
## Docs aabout aac aacount aal aaltiv aas abbrev abcd able
## computing.org 0 0 0 0 0 0 0 0 6
## fynanse.org 0 0 0 0 0 0 0 0 0
## personal.org 0 0 0 0 0 0 0 0 0
## physical.org 0 0 0 0 0 1 0 0 1
## professional.org 0 1 0 20 1 0 1 1 4
## reading.org 0 0 0 0 0 0 0 0 0
## website.org 1 0 1 0 0 0 0 0 0
## Terms
## Docs abort
## computing.org 1
## fynanse.org 0
## personal.org 0
## physical.org 0
## professional.org 0
## reading.org 0
## website.org 0
- hmm, would be nice to see most frequent terms.
Examine document term matrix
============================
``` r
org_term_freq <- colSums(as.matrix(org_doc_term_matrix))
org_term_order <- order(org_term_freq)
org_term_freq[tail(org_term_order, n=25L)]
```
## data get also make add see use
## 143 143 145 145 146 164 166
## check cancelled can sat sun thu scheduled
## 175 202 226 299 316 335 346
## wed fri mon tue next closed logbook
## 399 422 537 558 653 752 1046
## todo end state done
## 1055 1186 1693 2143
- the org mode todo items are common. Blimey, ive done a lot.
- It might be intersting to remove them, but it also indicates the actionability of my work. Identify tasks and execute.
- more examining reveals many other semi-useless words in top 50+ words
``` r
findFreqTerms(org_doc_term_matrix, lowfreq=1000)
```
## [1] "done" "end" "logbook" "state" "todo"
``` r
findFreqTerms(org_doc_term_matrix, lowfreq=100)
```
## [1] "add" "air" "also" "broker" "can"
## [6] "cancelled" "check" "closed" "create" "data"
## [11] "deal" "done" "edm" "end" "fri"
## [16] "get" "git" "just" "logbook" "loss"
## [21] "make" "mon" "need" "new" "next"
## [26] "one" "peril" "results" "right" "rms"
## [31] "run" "sat" "scheduled" "see" "setup"
## [36] "state" "sun" "thu" "todo" "tue"
## [41] "use" "waiting" "wed" "will" "work"
- can also examine word associations, plot associations, which I will omit here.
Plot wordcloud
==============
- I had issues isntalling wordcloud. Github worked, my cran mirror (Rstudio) didn't.
- There's a hack in here to plot only some of the words, since omitting the org bulk words via removeWords didn't work. I heard there's a bug with removeWords if they're at the start of a line, which the org state words usually are.
``` r
library("wordcloud")
set.seed(1945)
wordcloud(names(org_term_freq), org_term_freq,
min.freq=40,
colors=brewer.pal(6,"Dark2"))
```

``` r
org_term_freq[tail(org_term_order, n=25L)]
```
## data get also make add see use
## 143 143 145 145 146 164 166
## check cancelled can sat sun thu scheduled
## 175 202 226 299 316 335 346
## wed fri mon tue next closed logbook
## 399 422 537 558 653 752 1046
## todo end state done
## 1055 1186 1693 2143
``` r
all_terms <- length(org_term_freq)
omit_last <- 25
wordcloud(names(org_term_freq[head(org_term_order,
n=all_terms-omit_last)]),
org_term_freq[head(org_term_order,
n=all_terms-omit_last)],
min.freq=15,
colors=brewer.pal(5,"Dark2"))
```

Finally, make wordclouds for individual org agenda files
========================================================
- I've omitted some of the plots for brevity.
``` r
setwd("data")
org_dirs <- dir()[!grepl(".org",dir())]
org_dirs
corp_to_wordcloud <- function(top_dir){
dir_source <- DirSource(top_dir)
agenda_corpus <- VCorpus(x=dir_source,
readerControl=
list(reader = reader(dir_source),
language = "en"))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(removeWords),
stopwords())
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(removePunctuation))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(removeNumbers))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(stripWhitespace))
agenda_corpus <- tm_map(agenda_corpus,
content_transformer(stemDocument))
org_doc_term_matrix <- DocumentTermMatrix(agenda_corpus)
org_term_freq <- colSums(as.matrix(org_doc_term_matrix))
org_term_order <- order(org_term_freq)
set.seed(1945)
all_terms <- length(org_term_freq)
omit_last <- 15
wordcloud(names(org_term_freq[head(org_term_order,
n=all_terms-omit_last)]),
org_term_freq[head(org_term_order,
n=all_terms-omit_last)],
min.freq=15,
colors=brewer.pal(5,"Dark2"), main=dir_source)
}
lapply(org_dirs, corp_to_wordcloud)
```
      
## [1] "computing" "fynanse" "personal" "physical"
## [5] "professional" "reading" "website"
## [[1]]
## NULL
##
## [[2]]
## NULL
##
## [[3]]
## NULL
##
## [[4]]
## NULL
##
## [[5]]
## NULL
##
## [[6]]
## NULL
##
## [[7]]
## NULL
Next time
=========
- Try python's nltk
- I think some normalization of the word frequencies against a null case (some generic books, dictionary, i don't know what) might be more interesting
- Trim terms using in inflection points on the ordered terms vs frequency relationship
- Animate the wordclouds of the individual org agenda files
References
==========
- <http://onepager.togaware.com/TextMiningO.pdf>
- <http://cran.r-project.org/web/packages/tm/vignettes/tm.pdf>
| jo-tham/org_text_miner | analysis.md | Markdown | gpl-3.0 | 12,738 |
#ifndef TOKENS_H
#define TOKENS_H
#define NUMBER 256
#define SYMBOL 257
#endif
| wellingtondellamura/compilers-codes-samples | translators/simple-postfix-translator/postfix_lex/tokens.h | C | gpl-3.0 | 81 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Newegg.Oversea.Silverlight.Controls;
using Newegg.Oversea.Silverlight.ControlPanel.Core.Base;
using ECCentral.Portal.UI.MKT.Models;
using ECCentral.Portal.UI.MKT.UserControls.Keywords;
using Newegg.Oversea.Silverlight.Controls.Components;
using ECCentral.Portal.UI.MKT.Facades;
using ECCentral.Portal.Basic.Utilities;
using ECCentral.QueryFilter.MKT;
using ECCentral.BizEntity.MKT;
using ECCentral.Portal.Basic;
using ECCentral.BizEntity.Common;
using ECCentral.BizEntity.Enum.Resources;
using Newegg.Oversea.Silverlight.ControlPanel.Core;
using ECCentral.Portal.UI.MKT.Resources;
using Newegg.Oversea.Silverlight.Utilities.Validation;
namespace ECCentral.Portal.UI.MKT.Views
{
[View(IsSingleton = true, SingletonType = SingletonTypes.Url)]
public partial class HotKeywords : PageBase
{
private HotKeywordsQueryFacade facade;
private HotKeywordsQueryFilter filter;
private List<HotKeywordsVM> gridVM;
private HotKeywordsQueryVM queryVM;
private HotKeywordsQueryFilter filterVM;
public HotKeywords()
{
InitializeComponent();
}
/// <summary>
/// 数据全部导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void QueryResultGrid_ExportAllClick(object sender, EventArgs e)
{
if (filterVM == null || this.QueryResultGrid.TotalCount < 1)
{
Window.Alert(ResKeywords.Information_ExportFailed);
return;
}
ColumnSet col = new ColumnSet(this.QueryResultGrid);
filter = queryVM.ConvertVM<HotKeywordsQueryVM, HotKeywordsQueryFilter>();
filter.PageInfo = new ECCentral.QueryFilter.Common.PagingInfo()
{
PageSize = ConstValue.MaxRowCountLimit,
PageIndex = 0,
SortBy = string.Empty
};
facade.ExportExcelFile(filterVM, new ColumnSet[] { col });
}
public override void OnPageLoad(object sender, EventArgs e)
{
facade = new HotKeywordsQueryFacade(this);
filter = new HotKeywordsQueryFilter();
queryVM = new HotKeywordsQueryVM();
queryVM.CompanyCode = CPApplication.Current.CompanyCode;
queryVM.ChannelID = "1";
QuerySection.DataContext = queryVM;
facade.GetHotKeywordsEditUserList(CPApplication.Current.CompanyCode, (s, args) =>
{
if (args.FaultsHandle())
return;
BindEditUserList(args.Result);
});
base.OnPageLoad(sender, e);
}
private void BindEditUserList(List<UserInfo> userList)
{
if (userList == null)
{
userList = new List<UserInfo>();
}
userList.Insert(0, new UserInfo { SysNo = null, UserName = ResCommonEnum.Enum_All });
comEditUser.ItemsSource = userList;
}
private void QueryResultGrid_LoadingDataSource(object sender, Newegg.Oversea.Silverlight.Controls.Data.LoadingDataEventArgs e)
{
facade.QueryHotKeywords(QueryResultGrid.QueryCriteria as HotKeywordsQueryFilter, e.PageSize, e.PageIndex, e.SortField, (s, args) =>
{
if (args.FaultsHandle())
return;
gridVM = DynamicConverter<HotKeywordsVM>.ConvertToVMList<List<HotKeywordsVM>>(args.Result.Rows);
QueryResultGrid.ItemsSource = gridVM;
QueryResultGrid.TotalCount = args.Result.TotalCount;
if (gridVM != null)
{
btnVoidItem.IsEnabled = true;
btnAvailableItem.IsEnabled = true;
}
else
{
btnVoidItem.IsEnabled = false;
btnAvailableItem.IsEnabled = false;
}
});
}
/// <summary>
/// 预览
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void hlViewItem_Click(object sender, RoutedEventArgs e)
{
HotKeywordsVM vm = QueryResultGrid.SelectedItem as HotKeywordsVM;
HotKeywordsVM vmItem = gridVM.SingleOrDefault(a => a.SysNo.Value == vm.SysNo.Value);
HotSearchKeyWords item = EntityConvertorExtensions.ConvertVM<HotKeywordsVM, HotSearchKeyWords>(vmItem, (v, t) =>
{
t.Keywords = new BizEntity.LanguageContent(ConstValue.BizLanguageCode, v.Keywords);
});
UCViewHotSearchKeywords usercontrol = new UCViewHotSearchKeywords();
usercontrol.Model = item;
usercontrol.Dialog = Window.ShowDialog(ResKeywords.Title_ReviewHotKeywords, usercontrol, OnMaintainDialogResult);
}
private void btnNewItem_Click(object sender, RoutedEventArgs e)
{
UCAddHotKeywords usercontrol = new UCAddHotKeywords();
usercontrol.Dialog = Window.ShowDialog(ResKeywords.Title_NewHotKeywords, usercontrol, OnMaintainDialogResult);
}
private void OnMaintainDialogResult(object sender, ResultEventArgs args)
{
if (args.DialogResult == DialogResultType.OK)
{
filter = queryVM.ConvertVM<HotKeywordsQueryVM, HotKeywordsQueryFilter>();
filter.PageType = ucPageType.PageType;
filter.PageID = ucPageType.PageID;
filterVM = Newegg.Oversea.Silverlight.Utilities.UtilityHelper.DeepClone<HotKeywordsQueryFilter>(filter);
QueryResultGrid.QueryCriteria = this.filter;
QueryResultGrid.Bind();
}
}
/// <summary>
/// 屏蔽
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnVoidItem_Click(object sender, RoutedEventArgs e)
{
List<int> invalidSysNo = new List<int>();
gridVM.ForEach(item =>
{
if (item.IsChecked == true)
invalidSysNo.Add(item.SysNo.Value);
});
if (invalidSysNo.Count > 0)
facade.BatchSetHotKeywordsInvalid(invalidSysNo, (obj, args) =>
{
if (args.FaultsHandle())
return;
QueryResultGrid.Bind();
Window.Alert(ResKeywords.Information_OperateSuccessful, MessageType.Information);
});
else
Window.Alert(ResKeywords.Information_MoreThanOneRecord, MessageType.Error);
}
/// <summary>
/// 编辑
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void hlEdit_Click(object sender, RoutedEventArgs e)
{
HotKeywordsVM item = this.QueryResultGrid.SelectedItem as HotKeywordsVM;
UCAddHotKeywords usercontrol = new UCAddHotKeywords();
//usercontrol.SysNo = item.SysNo.Value;
usercontrol.VM = gridVM.Single(a => a.SysNo.Value == item.SysNo.Value);//item;
usercontrol.Dialog = Window.ShowDialog(ResKeywords.Title_EditHotKeywords, usercontrol, OnMaintainDialogResult);
}
private void Button_Search_Click(object sender, RoutedEventArgs e)
{
if (ValidationManager.Validate(this.QuerySection))
{
filter = queryVM.ConvertVM<HotKeywordsQueryVM, HotKeywordsQueryFilter>();
filter.PageType = ucPageType.PageType;
filter.PageID = ucPageType.PageID;
filterVM = Newegg.Oversea.Silverlight.Utilities.UtilityHelper.DeepClone<HotKeywordsQueryFilter>(filter);
QueryResultGrid.QueryCriteria = this.filter;
QueryResultGrid.Bind();
}
}
private void ckbSelectRow_Click(object sender, RoutedEventArgs e)
{
var checkBoxAll = sender as CheckBox;
if (gridVM == null || checkBoxAll == null)
return;
gridVM.ForEach(item =>
{
item.IsChecked = checkBoxAll.IsChecked ?? false;
});
}
/// <summary>
/// 有效
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAvailableItem_Click(object sender, RoutedEventArgs e)
{
List<int> invalidSysNo = new List<int>();
gridVM.ForEach(item =>
{
if (item.IsChecked == true)
invalidSysNo.Add(item.SysNo.Value);
});
if (invalidSysNo.Count > 0)
facade.BatchSetHotKeywordsAvailable(invalidSysNo, (obj, args) =>
{
if (args.FaultsHandle())
return;
QueryResultGrid.Bind();
Window.Alert(ResKeywords.Information_OperateSuccessful, MessageType.Information);
});
else
Window.Alert(ResKeywords.Information_MoreThanOneRecord, MessageType.Error);
}
}
}
| ZeroOne71/ql | 02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.MKT/Views/HotKeywords.xaml.cs | C# | gpl-3.0 | 9,684 |
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class SelectOnInput : MonoBehaviour {
public EventSystem eventSystem;
public GameObject selectedObject;
private bool buttonSelected;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetAxisRaw("Vertical") != 0 && buttonSelected == false)
{
eventSystem.SetSelectedGameObject(selectedObject);
buttonSelected = true;
}
}
private void OnDisable()
{
buttonSelected = false;
}
}
| TheMrNomis/T-racing | Assets/Scripts/UI/SelectOnInput.cs | C# | gpl-3.0 | 617 |
package org.anddev.amatidev.pvb;
import java.util.LinkedList;
import org.amatidev.util.AdEnviroment;
import org.amatidev.util.AdPrefs;
import org.anddev.amatidev.pvb.bug.BugBeetle;
import org.anddev.amatidev.pvb.card.Card;
import org.anddev.amatidev.pvb.card.CardTomato;
import org.anddev.amatidev.pvb.obj.Dialog;
import org.anddev.amatidev.pvb.plant.Plant;
import org.anddev.amatidev.pvb.singleton.GameData;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.Text;
public class Tutorial extends MainGame {
private Sprite mArrow;
private int mTutorialStep = 1;
@Override
public void createScene() {
// sfondo e tabellone
Sprite back = new Sprite(0, 0, GameData.getInstance().mBackground);
Sprite table = new Sprite(0, 0, GameData.getInstance().mTable);
getChild(BACKGROUND_LAYER).attachChild(back);
getChild(BACKGROUND_LAYER).attachChild(table);
Sprite seed = new Sprite(25, 14, GameData.getInstance().mSeed);
table.attachChild(seed);
GameData.getInstance().mMySeed.setParent(null);
table.attachChild(GameData.getInstance().mMySeed);
// field position
for (int i = 0; i < FIELDS; i++) {
int x = i % 9;
int y = (int)(i / 9);
Rectangle field = new Rectangle(0, 0, 68, 74);
field.setColor(0f, 0f, 0f);
if (i % 2 == 0)
field.setAlpha(0.05f);
else
field.setAlpha(0.08f);
field.setPosition(42 + x * 71, 96 + y * 77);
getChild(GAME_LAYER).attachChild(field);
registerTouchArea(field);
}
}
protected void initLevel() {
// contatori per individuare se in una riga c'e' un nemico
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "enemy_killed");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count96.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count173.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count250.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count327.0");
AdPrefs.resetAccessCount(AdEnviroment.getInstance().getContext(), "count404.0");
GameData.getInstance().mMySeed.resetScore();
LinkedList<Card> cards = GameData.getInstance().mCards;
cards.clear();
cards.add(new CardTomato());
// TUTORIAL
this.mArrow = new Sprite(106, 95, GameData.getInstance().mArrow);
this.mArrow.setColor(1f, 0.4f, 0.4f);
this.mArrow.registerEntityModifier(
new LoopEntityModifier(
null,
-1,
null,
new SequenceEntityModifier(
new ScaleModifier(0.5f, 1f, 1.2f),
new ScaleModifier(0.5f, 1.2f, 1f)
)
)
);
getChild(GUI_LAYER).attachChild(this.mArrow);
AdEnviroment.getInstance().showMessage("Select a card to use");
AdEnviroment.getInstance().showMessage("Each card has a recharge time and price");
}
@Override
public void startScene() {
initLevel();
// add card
LinkedList<Card> cards = GameData.getInstance().mCards;
int start_x = 106;
for (int i = 0; i < cards.size(); i++) {
Card c = cards.get(i);
c.setPosition(start_x + i * 69, 7);
getChild(BACKGROUND_LAYER).attachChild(c);
}
Text skip = new Text(0, 0, GameData.getInstance().mFontTutorial, "Skip");
skip.setColor(1.0f, 0.3f, 0.3f);
skip.setPosition(37, 360);
getChild(GUI_LAYER).attachChild(skip);
registerTouchArea(skip);
}
public void checkLevelFinish() {
if (this.mGameOver == false && this.mLevelFinish == false) {
registerUpdateHandler(new TimerHandler(2f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
if (Tutorial.this.mTutorialStep == 4) {
final Sprite e = new Sprite(12, 25, GameData.getInstance().mSeed);
IEntity field = getChild(GAME_LAYER).getChild(12);
if (field.getChildCount() == 0)
field.attachChild(e);
Tutorial.this.mTutorialStep++;
Tutorial.this.mArrow.setPosition(310, 135);
Tutorial.this.mArrow.setRotation(-132f);
AdEnviroment.getInstance().showMessage("Pick the seeds producing the field to increase the stock");
}
}
}));
}
}
private void levelFinish() {
if (this.mGameOver == false && this.mLevelFinish == false) {
Dialog dialog = new Dialog("Tutorial\nComplete");
getChild(GUI2_LAYER).attachChild(dialog);
clearScene();
registerUpdateHandler(new TimerHandler(6, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
AdEnviroment.getInstance().nextScene();
}
}));
this.mLevelFinish = true;
GameData.getInstance().mMyScore.resetScore();
}
}
@Override
public void manageAreaTouch(ITouchArea pTouchArea) {
if (pTouchArea instanceof Card) {
GameData.getInstance().mSoundCard.play();
this.mSelect = ((Card) pTouchArea).makeSelect();
// TUTORIAL
if (this.mTutorialStep == 1) {
this.mTutorialStep++;
this.mArrow.setPosition(595, 203);
this.mArrow.setRotation(132f);
AdEnviroment.getInstance().showMessage("If bugs incoming, try to kill them by planting");
BugBeetle e = new BugBeetle(250f);
getChild(GAME_LAYER).attachChild(e);
registerUpdateHandler(new TimerHandler(6f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
Tutorial.this.mTutorialStep++;
Tutorial.this.mArrow.setPosition(100, 203);
Tutorial.this.mArrow.setRotation(-132f);
AdEnviroment.getInstance().showMessage("If you have enough seeds you can plant");
}
}));
}
} else {
IEntity field = (IEntity) pTouchArea;
if (field.getChildCount() == 1 && !(field.getFirstChild() instanceof Plant)) {
GameData.getInstance().mSoundSeed.play();
GameData.getInstance().mMySeed.addScore(1);
AdEnviroment.getInstance().safeDetachEntity(field.getFirstChild());
if (this.mTutorialStep == 5) {
this.mTutorialStep++;
this.mArrow.setPosition(17, 95);
this.mArrow.setRotation(0f);
AdEnviroment.getInstance().showMessage("Seeds stock are increased to +1");
AdEnviroment.getInstance().showMessage("Kill bugs to complete levels and obtain score and new plants");
registerUpdateHandler(new TimerHandler(9f, false, new ITimerCallback() {
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
AdEnviroment.getInstance().getEngine().runOnUpdateThread(new Runnable() {
@Override
public void run() {
Tutorial.this.levelFinish();
}
});
}
}));
}
} else if (field instanceof Text) {
GameData.getInstance().mSoundMenu.play();
AdEnviroment.getInstance().nextScene();
} else {
if (this.mSelect != null && this.mSelect.isReady() && field.getChildCount() == 0 && this.mTutorialStep >= 3 && field.getY() == 250.0f) {
if (GameData.getInstance().mMySeed.getScore() >= this.mSelect.getPrice()) {
GameData.getInstance().mMySeed.addScore(-this.mSelect.getPrice());
this.mSelect.startRecharge();
field.attachChild(this.mSelect.getPlant());
// TUTORIAL
if (this.mTutorialStep == 3) {
this.mTutorialStep++;
this.mArrow.setPosition(17, 95);
this.mArrow.setRotation(0f);
AdEnviroment.getInstance().showMessage("Seeds stock are decreased because you bought a plant");
}
}
}
}
}
}
}
| amatig/PlantsVsBugs | src/org/anddev/amatidev/pvb/Tutorial.java | Java | gpl-3.0 | 7,881 |
<html>
<body>
<table border="0" cellspacing="0" cellpadding="0" align="LEFT">
<tr>
<td><img src="file:///I:/Monografia/2. Diagramas BPMN/3. Generados/Añadir Escuela a proyectos-1.0_0_0.png"/></td>
</tr>
</table>
</body>
</html> | Thealexander/Sarglass | Documentacion/2. Diagramas BPMN/2. Generados/Añadir Escuela a proyectos-1.0.html | HTML | gpl-3.0 | 229 |
## Introduction
<b>vedgTools/QtWidgetsUtilities</b> is a general-purpose C++ library, which
depends on QtCore and QtWidgets/QtGui libraries. Both Qt4 and Qt5 are supported.
It also depends on vedgTools/CMakeModules and vedgTools/QtCoreUtilities
libraries, which are present as submodules in this git repository.
## License
Copyright (C) 2014 Igor Kushnir <igorkuo AT Google mail>
vedgTools/QtWidgetsUtilities is licensed under the <b>GNU GPLv3+</b> license,
a copy of which can be found in the `COPYING` file.
vedgTools/QtWidgetsUtilities is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
vedgTools/QtWidgetsUtilities is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
vedgTools/QtWidgetsUtilities. If not, see <http://www.gnu.org/licenses/>.
| vedgy/QtWidgetsUtilities | README.md | Markdown | gpl-3.0 | 1,175 |
-----------------------------------------
-- Spell: Protect
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local power = 15;
local duration = 1800;
duration = calculateDurationForLvl(duration, 7, target:getMainLvl());
if (caster:hasStatusEffect(EFFECT_PERPETUANCE)) then
duration = duration * 2;
end
local typeEffect = EFFECT_PROTECT;
local subPower = 0;
if ((caster:getID() == target:getID()) and target:getEffectsCount(EFFECT_TELLUS) >= 1) then
power = power * 1.25;
subPower = 10;
end
power, duration = applyEmbolden(caster, power, duration);
if (target:addStatusEffect(typeEffect, power, 0, duration, 0, subPower)) then
spell:setMsg(230);
else
spell:setMsg(75); -- no effect
end
return typeEffect;
end;
| Vadavim/jsr-darkstar | scripts/globals/spells/protect.lua | Lua | gpl-3.0 | 1,084 |
/*
==============================================================================
This file is part of the JUCE examples.
Copyright (c) 2017 - ROLI Ltd.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
/*******************************************************************************
The block below describes the properties of this PIP. A PIP is a short snippet
of code that can be read by the Projucer and used to generate a JUCE project.
BEGIN_JUCE_PIP_METADATA
name: OpenGLAppDemo
version: 1.0.0
vendor: JUCE
website: http://juce.com
description: Simple OpenGL application.
dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
juce_gui_basics, juce_gui_extra, juce_opengl
exporters: xcode_mac, vs2017, xcode_iphone
moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
type: Component
mainClass: OpenGLAppDemo
useLocalCopy: 1
END_JUCE_PIP_METADATA
*******************************************************************************/
#pragma once
#include "../Assets/DemoUtilities.h"
#include "../Assets/WavefrontObjParser.h"
//==============================================================================
/*
This component lives inside our window, and this is where you should put all
your controls and content.
*/
class OpenGLAppDemo : public OpenGLAppComponent
{
public:
//==============================================================================
OpenGLAppDemo()
{
setSize (800, 600);
}
~OpenGLAppDemo()
{
shutdownOpenGL();
}
void initialise() override
{
createShaders();
}
void shutdown() override
{
shader .reset();
shape .reset();
attributes.reset();
uniforms .reset();
}
Matrix3D<float> getProjectionMatrix() const
{
auto w = 1.0f / (0.5f + 0.1f);
auto h = w * getLocalBounds().toFloat().getAspectRatio (false);
return Matrix3D<float>::fromFrustum (-w, w, -h, h, 4.0f, 30.0f);
}
Matrix3D<float> getViewMatrix() const
{
Matrix3D<float> viewMatrix ({ 0.0f, 0.0f, -10.0f });
Matrix3D<float> rotationMatrix = viewMatrix.rotation ({ -0.3f, 5.0f * std::sin (getFrameCounter() * 0.01f), 0.0f });
return rotationMatrix * viewMatrix;
}
void render() override
{
jassert (OpenGLHelpers::isContextActive());
auto desktopScale = (float) openGLContext.getRenderingScale();
OpenGLHelpers::clear (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glViewport (0, 0, roundToInt (desktopScale * getWidth()), roundToInt (desktopScale * getHeight()));
shader->use();
if (uniforms->projectionMatrix.get() != nullptr)
uniforms->projectionMatrix->setMatrix4 (getProjectionMatrix().mat, 1, false);
if (uniforms->viewMatrix.get() != nullptr)
uniforms->viewMatrix->setMatrix4 (getViewMatrix().mat, 1, false);
shape->draw (openGLContext, *attributes);
// Reset the element buffers so child Components draw correctly
openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0);
}
void paint (Graphics& g) override
{
// You can add your component specific drawing code here!
// This will draw over the top of the openGL background.
g.setColour (getLookAndFeel().findColour (Label::textColourId));
g.setFont (20);
g.drawText ("OpenGL Example", 25, 20, 300, 30, Justification::left);
g.drawLine (20, 20, 170, 20);
g.drawLine (20, 50, 170, 50);
}
void resized() override
{
// This is called when this component is resized.
// If you add any child components, this is where you should
// update their positions.
}
void createShaders()
{
vertexShader =
"attribute vec4 position;\n"
"attribute vec4 sourceColour;\n"
"attribute vec2 textureCoordIn;\n"
"\n"
"uniform mat4 projectionMatrix;\n"
"uniform mat4 viewMatrix;\n"
"\n"
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
"\n"
"void main()\n"
"{\n"
" destinationColour = sourceColour;\n"
" textureCoordOut = textureCoordIn;\n"
" gl_Position = projectionMatrix * viewMatrix * position;\n"
"}\n";
fragmentShader =
#if JUCE_OPENGL_ES
"varying lowp vec4 destinationColour;\n"
"varying lowp vec2 textureCoordOut;\n"
#else
"varying vec4 destinationColour;\n"
"varying vec2 textureCoordOut;\n"
#endif
"\n"
"void main()\n"
"{\n"
#if JUCE_OPENGL_ES
" lowp vec4 colour = vec4(0.95, 0.57, 0.03, 0.7);\n"
#else
" vec4 colour = vec4(0.95, 0.57, 0.03, 0.7);\n"
#endif
" gl_FragColor = colour;\n"
"}\n";
std::unique_ptr<OpenGLShaderProgram> newShader (new OpenGLShaderProgram (openGLContext));
String statusText;
if (newShader->addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (vertexShader))
&& newShader->addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (fragmentShader))
&& newShader->link())
{
shape .reset();
attributes.reset();
uniforms .reset();
shader.reset (newShader.release());
shader->use();
shape .reset (new Shape (openGLContext));
attributes.reset (new Attributes (openGLContext, *shader));
uniforms .reset (new Uniforms (openGLContext, *shader));
statusText = "GLSL: v" + String (OpenGLShaderProgram::getLanguageVersion(), 2);
}
else
{
statusText = newShader->getLastError();
}
}
private:
//==============================================================================
struct Vertex
{
float position[3];
float normal[3];
float colour[4];
float texCoord[2];
};
//==============================================================================
// This class just manages the attributes that the shaders use.
struct Attributes
{
Attributes (OpenGLContext& openGLContext, OpenGLShaderProgram& shaderProgram)
{
position .reset (createAttribute (openGLContext, shaderProgram, "position"));
normal .reset (createAttribute (openGLContext, shaderProgram, "normal"));
sourceColour .reset (createAttribute (openGLContext, shaderProgram, "sourceColour"));
textureCoordIn.reset (createAttribute (openGLContext, shaderProgram, "textureCoordIn"));
}
void enable (OpenGLContext& glContext)
{
if (position.get() != nullptr)
{
glContext.extensions.glVertexAttribPointer (position->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), nullptr);
glContext.extensions.glEnableVertexAttribArray (position->attributeID);
}
if (normal.get() != nullptr)
{
glContext.extensions.glVertexAttribPointer (normal->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 3));
glContext.extensions.glEnableVertexAttribArray (normal->attributeID);
}
if (sourceColour.get() != nullptr)
{
glContext.extensions.glVertexAttribPointer (sourceColour->attributeID, 4, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 6));
glContext.extensions.glEnableVertexAttribArray (sourceColour->attributeID);
}
if (textureCoordIn.get() != nullptr)
{
glContext.extensions.glVertexAttribPointer (textureCoordIn->attributeID, 2, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 10));
glContext.extensions.glEnableVertexAttribArray (textureCoordIn->attributeID);
}
}
void disable (OpenGLContext& glContext)
{
if (position.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (position->attributeID);
if (normal.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (normal->attributeID);
if (sourceColour.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (sourceColour->attributeID);
if (textureCoordIn.get() != nullptr) glContext.extensions.glDisableVertexAttribArray (textureCoordIn->attributeID);
}
std::unique_ptr<OpenGLShaderProgram::Attribute> position, normal, sourceColour, textureCoordIn;
private:
static OpenGLShaderProgram::Attribute* createAttribute (OpenGLContext& openGLContext,
OpenGLShaderProgram& shader,
const char* attributeName)
{
if (openGLContext.extensions.glGetAttribLocation (shader.getProgramID(), attributeName) < 0)
return nullptr;
return new OpenGLShaderProgram::Attribute (shader, attributeName);
}
};
//==============================================================================
// This class just manages the uniform values that the demo shaders use.
struct Uniforms
{
Uniforms (OpenGLContext& openGLContext, OpenGLShaderProgram& shaderProgram)
{
projectionMatrix.reset (createUniform (openGLContext, shaderProgram, "projectionMatrix"));
viewMatrix .reset (createUniform (openGLContext, shaderProgram, "viewMatrix"));
}
std::unique_ptr<OpenGLShaderProgram::Uniform> projectionMatrix, viewMatrix;
private:
static OpenGLShaderProgram::Uniform* createUniform (OpenGLContext& openGLContext,
OpenGLShaderProgram& shaderProgram,
const char* uniformName)
{
if (openGLContext.extensions.glGetUniformLocation (shaderProgram.getProgramID(), uniformName) < 0)
return nullptr;
return new OpenGLShaderProgram::Uniform (shaderProgram, uniformName);
}
};
//==============================================================================
/** This loads a 3D model from an OBJ file and converts it into some vertex buffers
that we can draw.
*/
struct Shape
{
Shape (OpenGLContext& glContext)
{
if (shapeFile.load (loadEntireAssetIntoString ("teapot.obj")).wasOk())
for (auto* shapeVertices : shapeFile.shapes)
vertexBuffers.add (new VertexBuffer (glContext, *shapeVertices));
}
void draw (OpenGLContext& glContext, Attributes& glAttributes)
{
for (auto* vertexBuffer : vertexBuffers)
{
vertexBuffer->bind();
glAttributes.enable (glContext);
glDrawElements (GL_TRIANGLES, vertexBuffer->numIndices, GL_UNSIGNED_INT, nullptr);
glAttributes.disable (glContext);
}
}
private:
struct VertexBuffer
{
VertexBuffer (OpenGLContext& context, WavefrontObjFile::Shape& aShape) : openGLContext (context)
{
numIndices = aShape.mesh.indices.size();
openGLContext.extensions.glGenBuffers (1, &vertexBuffer);
openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
Array<Vertex> vertices;
createVertexListFromMesh (aShape.mesh, vertices, Colours::green);
openGLContext.extensions.glBufferData (GL_ARRAY_BUFFER,
static_cast<GLsizeiptr> (static_cast<size_t> (vertices.size()) * sizeof (Vertex)),
vertices.getRawDataPointer(), GL_STATIC_DRAW);
openGLContext.extensions.glGenBuffers (1, &indexBuffer);
openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
openGLContext.extensions.glBufferData (GL_ELEMENT_ARRAY_BUFFER,
static_cast<GLsizeiptr> (static_cast<size_t> (numIndices) * sizeof (juce::uint32)),
aShape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW);
}
~VertexBuffer()
{
openGLContext.extensions.glDeleteBuffers (1, &vertexBuffer);
openGLContext.extensions.glDeleteBuffers (1, &indexBuffer);
}
void bind()
{
openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
}
GLuint vertexBuffer, indexBuffer;
int numIndices;
OpenGLContext& openGLContext;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VertexBuffer)
};
WavefrontObjFile shapeFile;
OwnedArray<VertexBuffer> vertexBuffers;
static void createVertexListFromMesh (const WavefrontObjFile::Mesh& mesh, Array<Vertex>& list, Colour colour)
{
auto scale = 0.2f;
WavefrontObjFile::TextureCoord defaultTexCoord { 0.5f, 0.5f };
WavefrontObjFile::Vertex defaultNormal { 0.5f, 0.5f, 0.5f };
for (auto i = 0; i < mesh.vertices.size(); ++i)
{
const auto& v = mesh.vertices.getReference (i);
const auto& n = i < mesh.normals.size() ? mesh.normals.getReference (i) : defaultNormal;
const auto& tc = i < mesh.textureCoords.size() ? mesh.textureCoords.getReference (i) : defaultTexCoord;
list.add ({ { scale * v.x, scale * v.y, scale * v.z, },
{ scale * n.x, scale * n.y, scale * n.z, },
{ colour.getFloatRed(), colour.getFloatGreen(), colour.getFloatBlue(), colour.getFloatAlpha() },
{ tc.x, tc.y } });
}
}
};
const char* vertexShader;
const char* fragmentShader;
std::unique_ptr<OpenGLShaderProgram> shader;
std::unique_ptr<Shape> shape;
std::unique_ptr<Attributes> attributes;
std::unique_ptr<Uniforms> uniforms;
String newVertexShader, newFragmentShader;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLAppDemo)
};
| COx2/JUCE_JAPAN_DEMO | 2018/JUCE/examples/GUI/OpenGLAppDemo.h | C | gpl-3.0 | 15,810 |
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Grakn is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*/
package ai.grakn.engine.backgroundtasks.config;
/**
* <p>
* Class containing strings that describe the Kafka queues and groups
* </p>
*
* @author Denis Lobanov, alexandraorth
*/
public interface KafkaTerms {
String TASK_RUNNER_GROUP = "task-runners";
String SCHEDULERS_GROUP = "schedulers";
String WORK_QUEUE_TOPIC = "work-queue";
String NEW_TASKS_TOPIC = "new-tasks";
String LOG_TOPIC = "logs";
}
| mikonapoli/grakn | grakn-engine/src/main/java/ai/grakn/engine/backgroundtasks/config/KafkaTerms.java | Java | gpl-3.0 | 1,152 |
use sha1::{Sha1, Digest};
use std::fs;
let mut file = fs::File::open(&path)?;
let hash = Sha1::digest_reader(&mut file)?; | MediaKraken/MediaKraken_Deployment | source_rust/mk_lib_hash/src/mk_lib_hash_md5.rs | Rust | gpl-3.0 | 122 |
abstract class Adjunction[F[_], U[_]](
implicit val F: Functor[F],
val U: Representable[U]
){
def unit[A](a: A): U[F[A]]
def counit[A](a: F[U[A]]): A
}
| hmemcpy/milewski-ctfp-pdf | src/content/3.2/code/scala/snippet04.scala | Scala | gpl-3.0 | 161 |
function HistoryAssistant() {
}
HistoryAssistant.prototype.setup = function() {
this.appMenuModel = {
visible: true,
items: [
{ label: $L("About"), command: 'about' },
{ label: $L("Help"), command: 'tutorial' },
]
};
this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems: true}, this.appMenuModel);
var attributes = {};
this.model = {
//backgroundImage : 'images/glacier.png',
background: 'black',
onLeftFunction : this.wentLeft.bind(this),
onRightFunction : this.wentRight.bind(this)
}
this.controller.setupWidget('historydiv', attributes, this.model);
this.myPhotoDivElement = $('historydiv');
this.timestamp = new Date().getTime();
var env = Mojo.Environment.DeviceInfo;
if (env.screenHeight <= 400)
this.myPhotoDivElement.style.height = "372px";
}
HistoryAssistant.prototype.wentLeft = function(event){
this.timestamp = this.timestamp - (1000*60*60*24);
var timenow = new Date(this.timestamp);
var timenowstring = "";
var Ayear = timenow.getUTCFullYear();
var Amonth = timenow.getUTCMonth()+1;
if(Amonth.toString().length < 2)
Amonth = "0" + Amonth;
var Aday = timenow.getUTCDate();
if(Aday.toString().length < 2)
Aday = "0" + Aday;
/*var Ahours = timenow.getUTCHours();
if(Ahours.toString().length < 2)
Ahours = "0" + Ahours;*/
Ahours = "00";
if (this.timestamp > 1276146000000) {
if (this.timestamp > 1276146000000 + (1000 * 60 * 60 * 24)) {
this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png");
}
this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png");
this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png");
}
$('text').innerHTML = "<center>Histoy Of Pixels - " + Ayear + " / " + Amonth + " / " + Aday + "</center>";
}
HistoryAssistant.prototype.wentRight = function(event){
this.timestamp = this.timestamp + (1000*60*60*24);
var timenow = new Date(this.timestamp);
var timenowstring = "";
var Ayear = timenow.getUTCFullYear();
var Amonth = timenow.getUTCMonth()+1;
if(Amonth.toString().length < 2)
Amonth = "0" + Amonth;
var Aday = timenow.getUTCDate();
if(Aday.toString().length < 2)
Aday = "0" + Aday;
/*var Ahours = timenow.getUTCHours();
if(Ahours.toString().length < 2)
Ahours = "0" + Ahours;*/
Ahours = "00";
if (this.timestamp < new Date().getTime()) {
this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday - 1) + Ahours + ".png");
this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png");
if (this.timestamp + (1000*60*60*24) < new Date().getTime()) {
this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday + 1) + Ahours + ".png");
}
}
$('text').innerHTML = "<center>Histoy Of Pixels - " + Ayear + " / " + Amonth + " / " + Aday + "</center>";
}
HistoryAssistant.prototype.activate = function(event) {
var timenow = new Date(this.timestamp);
var timenowstring = "";
var Ayear = timenow.getUTCFullYear();
var Amonth = timenow.getUTCMonth()+1;
if(Amonth.toString().length < 2)
Amonth = "0" + Amonth;
var Aday = timenow.getUTCDate();
if(Aday.toString().length < 2)
Aday = "0" + Aday;
/*var Ahours = timenow.getUTCHours();
if(Ahours.toString().length < 2)
Ahours = "0" + Ahours;*/
Ahours = "00";
this.myPhotoDivElement.mojo.leftUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday-1) + Ahours + ".png");
this.myPhotoDivElement.mojo.centerUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday) + Ahours + ".png");
//this.myPhotoDivElement.mojo.rightUrlProvided("http://100ps.omoco.de/100pixels/history/" + Ayear + Amonth + (Aday+1) + Ahours + ".png");
$('text').innerHTML = "<center>Histoy Of Pixels - " + Ayear + " / " + Amonth + " / " + Aday + "</center>";
}
HistoryAssistant.prototype.deactivate = function(event) {
}
HistoryAssistant.prototype.cleanup = function(event) {
}
HistoryAssistant.prototype.handleCommand = function(event){
if(event.type == Mojo.Event.command) {
switch (event.command) {
case 'about':
Mojo.Controller.stageController.pushScene("about");
break;
case 'tutorial':
this.controller.showAlertDialog({
onChoose: function(value) {},
title:"Help",
message:"This is the history of all pixels user have every created. Every night there is made a new snapshot.<br><br>Flip the image left or right to go through the history. Zoom into the image for more details.",
allowHTMLMessage: true,
choices:[ {label:'OK', value:'OK', type:'color'} ]
});
break;
}
}
} | sebastianha/webos-app_de.omoco.100pixels | app/assistants/history-assistant.js | JavaScript | gpl-3.0 | 4,982 |
# -*- coding: utf-8 -*-
import logging
from pprint import pformat
from time import clock, sleep
try:
import unittest2 as unittest
except ImportError:
import unittest
import config
from event_stack import TimeOutReached
from database_reception import Database_Reception
from static_agent_pools import Receptionists, Customers
logging.basicConfig (level = logging.INFO)
class Test_Case (unittest.TestCase):
Caller = None
Receptionist = None
Receptionist_2 = None
Callee = None
Reception_Database = None
Reception = None
Start_Time = None
Next_Step = 1
def Preconditions (self, Reception):
self.Start_Time = clock ()
self.Next_Step = 1
self.Log ("Incoming calls test case: Setting up preconditions...")
self.Log ("Requesting a customer (caller)...")
self.Caller = Customers.request ()
self.Log ("Requesting a receptionist...")
self.Receptionist = Receptionists.request ()
self.Log ("Requesting a second receptionist...")
self.Receptionist_2 = Receptionists.request ()
self.Log ("Requesting a customer (callee)...")
self.Callee = Customers.request ()
self.Log ("Select which reception to test...")
self.Reception = Reception
self.Log ("Select a reception database connection...")
self.Reception_Database = Database_Reception (uri = config.reception_server_uri,
authtoken = self.Receptionist.call_control.authtoken)
def Postprocessing (self):
self.Log ("Incoming calls test case: Cleaning up after test...")
if not self.Caller is None:
self.Caller.release ()
if not self.Receptionist is None:
self.Receptionist.release ()
if not self.Receptionist_2 is None:
self.Receptionist_2.release ()
if not self.Callee is None:
self.Callee.release ()
def Step (self,
Message,
Delay_In_Seconds = 0.0):
if self.Next_Step is None:
self.Next_Step = 1
if self.Start_Time is None:
self.Start_Time = clock ()
logging.info ("Step " + str (self.Next_Step) + ": " + Message)
sleep (Delay_In_Seconds)
self.Next_Step += 1
def Log (self,
Message,
Delay_In_Seconds = 0.0):
if self.Next_Step is None:
self.Next_Step = 1
if self.Start_Time is None:
self.Start_Time = clock ()
logging.info (" " + str (self.Next_Step - 1) + ": " + Message)
sleep (Delay_In_Seconds)
def Caller_Places_Call (self, Number):
self.Step (Message = "Caller places call to " + str (Number) + "...")
self.Log (Message = "Dialling through caller agent...")
self.Caller.dial (Number)
def Receptionist_Places_Call (self, Number):
self.Step (Message = "Receptionist places call to " + str (Number) + "...")
self.Log (Message = "Dialling through receptionist agent...")
self.Receptionist.dial (Number)
def Caller_Hears_Dialtone (self):
self.Step (Message = "Caller hears dial-tone...")
self.Log (Message = "Caller agent waits for dial-tone...")
self.Caller.sip_phone.Wait_For_Dialtone ()
def Receptionist_Hears_Dialtone (self):
self.Step (Message = "Receptionist hears dial-tone...")
self.Log (Message = "Receptionist agent waits for dial-tone...")
self.Receptionist.sip_phone.Wait_For_Dialtone ()
def Call_Announced (self):
self.Step (Message = "Receptionist's client waits for 'call_offer'...")
try:
self.Receptionist.event_stack.WaitFor ("call_offer")
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("Call offer didn't arrive from Call-Flow-Control.")
if not self.Receptionist.event_stack.stack_contains (event_type="call_offer",
destination=self.Reception):
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived call offer was not for the expected reception (destination).")
return self.Receptionist.event_stack.Get_Latest_Event (Event_Type="call_offer", Destination=self.Reception)['call']['id'],\
self.Receptionist.event_stack.Get_Latest_Event (Event_Type="call_offer", Destination=self.Reception)['call']['reception_id']
def Call_Announced_As_Locked (self, Call_ID):
self.Step (Message = "Call-Flow-Control sends out 'call_lock'...")
try:
self.Receptionist.event_stack.WaitFor (event_type = "call_lock",
call_id = Call_ID,
timeout = 20.0)
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("No 'call_lock' event arrived from Call-Flow-Control.")
if not self.Receptionist.event_stack.stack_contains (event_type = "call_lock",
destination = self.Reception,
call_id = Call_ID):
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived 'call_lock' event was not for the expected reception (destination).")
def Call_Announced_As_Unlocked (self, Call_ID):
self.Step (Message = "Call-Flow-Control sends out 'call_unlock'...")
try:
self.Receptionist.event_stack.WaitFor (event_type = "call_unlock",
call_id = Call_ID)
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("No 'call_unlock' event arrived from Call-Flow-Control.")
if not self.Receptionist.event_stack.stack_contains (event_type = "call_unlock",
destination = self.Reception,
call_id = Call_ID):
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived 'call_unlock' event was not for the expected reception (destination).")
def Request_Information (self, Reception_ID):
self.Step (Message = "Requesting (updated) information about reception " + str (Reception_ID))
Data_On_Reception = self.Reception_Database.Single (Reception_ID)
self.Step (Message = "Received information on reception " + str (Reception_ID))
return Data_On_Reception
def Offer_To_Pick_Up_Call (self, Call_Flow_Control, Call_ID):
self.Step (Message = "Client offers to answer call...")
try:
Call_Flow_Control.PickupCall (call_id = Call_ID)
except:
self.Log (Message = "Pick-up call returned an error of some kind.")
def Call_Allocation_Acknowledgement (self, Call_ID, Receptionist_ID):
self.Step (Message = "Receptionist's client waits for 'call_pickup'...")
try:
self.Receptionist.event_stack.WaitFor (event_type = "call_pickup",
call_id = Call_ID)
except TimeOutReached:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("No 'call_pickup' event arrived from Call-Flow-Control.")
try:
Event = self.Receptionist.event_stack.Get_Latest_Event (Event_Type = "call_pickup",
Call_ID = Call_ID)
except:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("Could not extract the received 'call_pickup' event from the Call-Flow-Control client.")
try:
if not Event['call']['assigned_to'] == Receptionist_ID:
logging.critical (self.Receptionist.event_stack.dump_stack ())
self.fail ("The arrived 'call_pickup' event was for " + str (Event['call']['assigned_to']) + ", and not for " + str (Receptionist_ID) + " as expected.")
except:
logging.critical (self.Receptionist.event_stack.dump_stack ())
raise
self.Log (Message = "Call picked up: " + pformat (Event))
return Event
def Receptionist_Answers (self, Call_Information, Reception_Information, After_Greeting_Played):
self.Step (Message = "Receptionist answers...")
if Call_Information['call']['greeting_played']:
try:
self.Log (Message = "Receptionist says '" + Reception_Information['short_greeting'] + "'.")
except:
self.fail ("Reception information missing 'short_greeting'.")
else:
try:
self.Log (Message = "Receptionist says '" + Reception_Information['greeting'] + "'.")
except:
self.fail ("Reception information missing 'greeting'.")
if After_Greeting_Played:
if not Call_Information['call']['greeting_played']:
self.fail ("It appears that the receptionist didn't wait long enough to allow the caller to hear the recorded message.")
else:
if Call_Information['call']['greeting_played']:
self.fail ("It appears that the receptionist waited too long, and allowed the caller to hear the recorded message.")
| AdaHeads/Coverage_Tests | disabled_tests/incoming_calls.py | Python | gpl-3.0 | 9,794 |
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction data structure.
use std::ops::Deref;
use rlp::*;
use util::sha3::Hashable;
use util::{H256, Address, U256, Bytes, HeapSizeOf};
use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError};
use error::*;
use evm::Schedule;
use header::BlockNumber;
use ethjson;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
/// Transaction action type.
pub enum Action {
/// Create creates new contract.
Create,
/// Calls contract at given address.
/// In the case of a transfer, this is the receiver's address.'
Call(Address),
}
impl Default for Action {
fn default() -> Action { Action::Create }
}
impl Decodable for Action {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let rlp = decoder.as_rlp();
if rlp.is_empty() {
Ok(Action::Create)
} else {
Ok(Action::Call(rlp.as_val()?))
}
}
}
/// Transaction activation condition.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub enum Condition {
/// Valid at this block number or later.
Number(BlockNumber),
/// Valid at this unix time or later.
Timestamp(u64),
}
/// A set of information describing an externally-originating message call
/// or contract creation operation.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct Transaction {
/// Nonce.
pub nonce: U256,
/// Gas price.
pub gas_price: U256,
/// Gas paid up front for transaction execution.
pub gas: U256,
/// Action, can be either call or contract create.
pub action: Action,
/// Transfered value.
pub value: U256,
/// Transaction data.
pub data: Bytes,
}
impl Transaction {
/// Append object with a without signature into RLP stream
pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream, network_id: Option<u64>) {
s.begin_list(if network_id.is_none() { 6 } else { 9 });
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas);
match self.action {
Action::Create => s.append_empty_data(),
Action::Call(ref to) => s.append(to)
};
s.append(&self.value);
s.append(&self.data);
if let Some(n) = network_id {
s.append(&n);
s.append(&0u8);
s.append(&0u8);
}
}
}
impl HeapSizeOf for Transaction {
fn heap_size_of_children(&self) -> usize {
self.data.heap_size_of_children()
}
}
impl From<ethjson::state::Transaction> for SignedTransaction {
fn from(t: ethjson::state::Transaction) -> Self {
let to: Option<ethjson::hash::Address> = t.to.into();
let secret = Secret::from_slice(&t.secret.0).expect("Valid secret expected.");
Transaction {
nonce: t.nonce.into(),
gas_price: t.gas_price.into(),
gas: t.gas_limit.into(),
action: match to {
Some(to) => Action::Call(to.into()),
None => Action::Create
},
value: t.value.into(),
data: t.data.into(),
}.sign(&secret, None)
}
}
impl From<ethjson::transaction::Transaction> for UnverifiedTransaction {
fn from(t: ethjson::transaction::Transaction) -> Self {
let to: Option<ethjson::hash::Address> = t.to.into();
UnverifiedTransaction {
unsigned: Transaction {
nonce: t.nonce.into(),
gas_price: t.gas_price.into(),
gas: t.gas_limit.into(),
action: match to {
Some(to) => Action::Call(to.into()),
None => Action::Create
},
value: t.value.into(),
data: t.data.into(),
},
r: t.r.into(),
s: t.s.into(),
v: t.v.into(),
hash: 0.into(),
}.compute_hash()
}
}
impl Transaction {
/// The message hash of the transaction.
pub fn hash(&self, network_id: Option<u64>) -> H256 {
let mut stream = RlpStream::new();
self.rlp_append_unsigned_transaction(&mut stream, network_id);
stream.as_raw().sha3()
}
/// Signs the transaction as coming from `sender`.
pub fn sign(self, secret: &Secret, network_id: Option<u64>) -> SignedTransaction {
let sig = ::ethkey::sign(secret, &self.hash(network_id))
.expect("data is valid and context has signing capabilities; qed");
SignedTransaction::new(self.with_signature(sig, network_id))
.expect("secret is valid so it's recoverable")
}
/// Signs the transaction with signature.
pub fn with_signature(self, sig: Signature, network_id: Option<u64>) -> UnverifiedTransaction {
UnverifiedTransaction {
unsigned: self,
r: sig.r().into(),
s: sig.s().into(),
v: sig.v() as u64 + if let Some(n) = network_id { 35 + n * 2 } else { 27 },
hash: 0.into(),
}.compute_hash()
}
/// Useful for test incorrectly signed transactions.
#[cfg(test)]
pub fn invalid_sign(self) -> UnverifiedTransaction {
UnverifiedTransaction {
unsigned: self,
r: U256::default(),
s: U256::default(),
v: 0,
hash: 0.into(),
}.compute_hash()
}
/// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned.
pub fn fake_sign(self, from: Address) -> SignedTransaction {
SignedTransaction {
transaction: UnverifiedTransaction {
unsigned: self,
r: U256::default(),
s: U256::default(),
v: 0,
hash: 0.into(),
}.compute_hash(),
sender: from,
public: Public::default(),
}
}
/// Get the transaction cost in gas for the given params.
pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 {
data.iter().fold(
(if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64,
|g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64
)
}
/// Get the transaction cost in gas for this transaction.
pub fn gas_required(&self, schedule: &Schedule) -> u64 {
Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule)
}
}
/// Signed transaction information.
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct UnverifiedTransaction {
/// Plain Transaction.
unsigned: Transaction,
/// The V field of the signature; the LS bit described which half of the curve our point falls
/// in. The MS bits describe which network this transaction is for. If 27/28, its for all networks.
v: u64,
/// The R field of the signature; helps describe the point on the curve.
r: U256,
/// The S field of the signature; helps describe the point on the curve.
s: U256,
/// Hash of the transaction
hash: H256,
}
impl Deref for UnverifiedTransaction {
type Target = Transaction;
fn deref(&self) -> &Self::Target {
&self.unsigned
}
}
impl Decodable for UnverifiedTransaction {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder {
let d = decoder.as_rlp();
if d.item_count() != 9 {
return Err(DecoderError::RlpIncorrectListLen);
}
let hash = decoder.as_raw().sha3();
Ok(UnverifiedTransaction {
unsigned: Transaction {
nonce: d.val_at(0)?,
gas_price: d.val_at(1)?,
gas: d.val_at(2)?,
action: d.val_at(3)?,
value: d.val_at(4)?,
data: d.val_at(5)?,
},
v: d.val_at(6)?,
r: d.val_at(7)?,
s: d.val_at(8)?,
hash: hash,
})
}
}
impl Encodable for UnverifiedTransaction {
fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) }
}
impl UnverifiedTransaction {
/// Used to compute hash of created transactions
fn compute_hash(mut self) -> UnverifiedTransaction {
let hash = (&*self.rlp_bytes()).sha3();
self.hash = hash;
self
}
/// Append object with a signature into RLP stream
fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) {
s.begin_list(9);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas);
match self.action {
Action::Create => s.append_empty_data(),
Action::Call(ref to) => s.append(to)
};
s.append(&self.value);
s.append(&self.data);
s.append(&self.v);
s.append(&self.r);
s.append(&self.s);
}
/// Reference to unsigned part of this transaction.
pub fn as_unsigned(&self) -> &Transaction {
&self.unsigned
}
/// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid.
pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } }
/// The `v` value that appears in the RLP.
pub fn original_v(&self) -> u64 { self.v }
/// The network ID, or `None` if this is a global transaction.
pub fn network_id(&self) -> Option<u64> {
match self.v {
v if v > 36 => Some((v - 35) / 2),
_ => None,
}
}
/// Construct a signature object from the sig.
pub fn signature(&self) -> Signature {
Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v())
}
/// Checks whether the signature has a low 's' value.
pub fn check_low_s(&self) -> Result<(), Error> {
if !self.signature().is_low_s() {
Err(EthkeyError::InvalidSignature.into())
} else {
Ok(())
}
}
/// Get the hash of this header (sha3 of the RLP).
pub fn hash(&self) -> H256 {
self.hash
}
/// Recovers the public key of the sender.
pub fn recover_public(&self) -> Result<Public, Error> {
Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?)
}
/// Do basic validation, checking for valid signature and minimum gas,
// TODO: consider use in block validation.
#[cfg(test)]
#[cfg(feature = "json-tests")]
pub fn validate(self, schedule: &Schedule, require_low: bool, allow_network_id_of_one: bool) -> Result<UnverifiedTransaction, Error> {
if require_low && !self.signature().is_low_s() {
return Err(EthkeyError::InvalidSignature.into())
}
match self.network_id() {
None => {},
Some(1) if allow_network_id_of_one => {},
_ => return Err(TransactionError::InvalidNetworkId.into()),
}
self.recover_public()?;
if self.gas < U256::from(self.gas_required(&schedule)) {
Err(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}).into())
} else {
Ok(self)
}
}
}
/// A `UnverifiedTransaction` with successfully recovered `sender`.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SignedTransaction {
transaction: UnverifiedTransaction,
sender: Address,
public: Public,
}
impl HeapSizeOf for SignedTransaction {
fn heap_size_of_children(&self) -> usize {
self.transaction.unsigned.heap_size_of_children()
}
}
impl Encodable for SignedTransaction {
fn rlp_append(&self, s: &mut RlpStream) { self.transaction.rlp_append_sealed_transaction(s) }
}
impl Deref for SignedTransaction {
type Target = UnverifiedTransaction;
fn deref(&self) -> &Self::Target {
&self.transaction
}
}
impl From<SignedTransaction> for UnverifiedTransaction {
fn from(tx: SignedTransaction) -> Self {
tx.transaction
}
}
impl SignedTransaction {
/// Try to verify transaction and recover sender.
pub fn new(transaction: UnverifiedTransaction) -> Result<Self, Error> {
let public = transaction.recover_public()?;
let sender = public_to_address(&public);
Ok(SignedTransaction {
transaction: transaction,
sender: sender,
public: public,
})
}
/// Returns transaction sender.
pub fn sender(&self) -> Address {
self.sender
}
/// Returns a public key of the sender.
pub fn public_key(&self) -> Public {
self.public
}
}
/// Signed Transaction that is a part of canon blockchain.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct LocalizedTransaction {
/// Signed part.
pub signed: UnverifiedTransaction,
/// Block number.
pub block_number: BlockNumber,
/// Block hash.
pub block_hash: H256,
/// Transaction index within block.
pub transaction_index: usize,
/// Cached sender
pub cached_sender: Option<Address>,
}
impl LocalizedTransaction {
/// Returns transaction sender.
/// Panics if `LocalizedTransaction` is constructed using invalid `UnverifiedTransaction`.
pub fn sender(&mut self) -> Address {
if let Some(sender) = self.cached_sender {
return sender;
}
let sender = public_to_address(&self.recover_public()
.expect("LocalizedTransaction is always constructed from transaction from blockchain; Blockchain only stores verified transactions; qed"));
self.cached_sender = Some(sender);
sender
}
}
impl Deref for LocalizedTransaction {
type Target = UnverifiedTransaction;
fn deref(&self) -> &Self::Target {
&self.signed
}
}
/// Queued transaction with additional information.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", binary)]
pub struct PendingTransaction {
/// Signed transaction data.
pub transaction: SignedTransaction,
/// To be activated at this condition. `None` for immediately.
pub condition: Option<Condition>,
}
impl PendingTransaction {
/// Create a new pending transaction from signed transaction.
pub fn new(signed: SignedTransaction, condition: Option<Condition>) -> Self {
PendingTransaction {
transaction: signed,
condition: condition,
}
}
}
impl Deref for PendingTransaction {
type Target = SignedTransaction;
fn deref(&self) -> &SignedTransaction { &self.transaction }
}
impl From<SignedTransaction> for PendingTransaction {
fn from(t: SignedTransaction) -> Self {
PendingTransaction {
transaction: t,
condition: None,
}
}
}
#[test]
fn sender_test() {
let t: UnverifiedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
assert_eq!(t.data, b"");
assert_eq!(t.gas, U256::from(0x5208u64));
assert_eq!(t.gas_price, U256::from(0x01u64));
assert_eq!(t.nonce, U256::from(0x00u64));
if let Action::Call(ref to) = t.action {
assert_eq!(*to, "095e7baea6a6c7c4c2dfeb977efac326af552d87".into());
} else { panic!(); }
assert_eq!(t.value, U256::from(0x0au64));
assert_eq!(public_to_address(&t.recover_public().unwrap()), "0f65fe9276bc9a24ae7083ae28e2660ef72df99e".into());
assert_eq!(t.network_id(), None);
}
#[test]
fn signing() {
use ethkey::{Random, Generator};
let key = Random.generate().unwrap();
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.sign(&key.secret(), None);
assert_eq!(Address::from(key.public().sha3()), t.sender());
assert_eq!(t.network_id(), None);
}
#[test]
fn fake_signing() {
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.fake_sign(Address::from(0x69));
assert_eq!(Address::from(0x69), t.sender());
assert_eq!(t.network_id(), None);
let t = t.clone();
assert_eq!(Address::from(0x69), t.sender());
assert_eq!(t.network_id(), None);
}
#[test]
fn should_recover_from_network_specific_signing() {
use ethkey::{Random, Generator};
let key = Random.generate().unwrap();
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.sign(&key.secret(), Some(69));
assert_eq!(Address::from(key.public().sha3()), t.sender());
assert_eq!(t.network_id(), Some(69));
}
#[test]
fn should_agree_with_vitalik() {
use rustc_serialize::hex::FromHex;
let test_vector = |tx_data: &str, address: &'static str| {
let signed = decode(&FromHex::from_hex(tx_data).unwrap());
let signed = SignedTransaction::new(signed).unwrap();
assert_eq!(signed.sender(), address.into());
flushln!("networkid: {:?}", signed.network_id());
};
test_vector("f864808504a817c800825208943535353535353535353535353535353535353535808025a0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116da0044852b2a670ade5407e78fb2863c51de9fcb96542a07186fe3aeda6bb8a116d", "0xf0f6f18bca1b28cd68e4357452947e021241e9ce");
test_vector("f864018504a817c80182a410943535353535353535353535353535353535353535018025a0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bcaa0489efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6", "0x23ef145a395ea3fa3deb533b8a9e1b4c6c25d112");
test_vector("f864028504a817c80282f618943535353535353535353535353535353535353535088025a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5a02d7c5bef027816a800da1736444fb58a807ef4c9603b7848673f7e3a68eb14a5", "0x2e485e0c23b4c3c542628a5f672eeab0ad4888be");
test_vector("f865038504a817c803830148209435353535353535353535353535353535353535351b8025a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4e0a02a80e1ef1d7842f27f2e6be0972bb708b9a135c38860dbe73c27c3486c34f4de", "0x82a88539669a3fd524d669e858935de5e5410cf0");
test_vector("f865048504a817c80483019a28943535353535353535353535353535353535353535408025a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c063a013600b294191fc92924bb3ce4b969c1e7e2bab8f4c93c3fc6d0a51733df3c060", "0xf9358f2538fd5ccfeb848b64a96b743fcc930554");
test_vector("f865058504a817c8058301ec309435353535353535353535353535353535353535357d8025a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1a04eebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "0xa8f7aba377317440bc5b26198a363ad22af1f3a4");
test_vector("f866068504a817c80683023e3894353535353535353535353535353535353535353581d88025a06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2fa06455bf8ea6e7463a1046a0b52804526e119b4bf5136279614e0b1e8e296a4e2d", "0xf1f571dc362a0e5b2696b8e775f8491d3e50de35");
test_vector("f867078504a817c807830290409435353535353535353535353535353535353535358201578025a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021a052f1a9b320cab38e5da8a8f97989383aab0a49165fc91c737310e4f7e9821021", "0xd37922162ab7cea97c97a87551ed02c9a38b7332");
test_vector("f867088504a817c8088302e2489435353535353535353535353535353535353535358202008025a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c12a064b1702d9298fee62dfeccc57d322a463ad55ca201256d01f62b45b2e1c21c10", "0x9bddad43f934d313c2b79ca28a432dd2b7281029");
test_vector("f867098504a817c809830334509435353535353535353535353535353535353535358202d98025a052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afba052f8f61201b2b11a78d6e866abc9c3db2ae8631fa656bfe5cb53668255367afb", "0x3c24d7329e92f84f08556ceb6df1cdb0104ca49f");
}
| BSDStudios/parity | ethcore/src/types/transaction.rs | Rust | gpl-3.0 | 18,976 |
#pragma once
#include <ros/assert.h>
#include <iostream>
#include <eigen3/Eigen/Dense>
#include "../utility/utility.h"
#include "../parameters.h"
#include "integration_base.h"
#include <ceres/ceres.h>
class IMUFactor : public ceres::SizedCostFunction<15, 7, 9, 7, 9>
{
public:
IMUFactor() = delete;
IMUFactor(IntegrationBase* _pre_integration):pre_integration(_pre_integration)
{
}
virtual bool Evaluate(double const *const *parameters, double *residuals, double **jacobians) const
{
Eigen::Vector3d Pi(parameters[0][0], parameters[0][1], parameters[0][2]);
Eigen::Quaterniond Qi(parameters[0][6], parameters[0][3], parameters[0][4], parameters[0][5]);
Eigen::Vector3d Vi(parameters[1][0], parameters[1][1], parameters[1][2]);
Eigen::Vector3d Bai(parameters[1][3], parameters[1][4], parameters[1][5]);
Eigen::Vector3d Bgi(parameters[1][6], parameters[1][7], parameters[1][8]);
Eigen::Vector3d Pj(parameters[2][0], parameters[2][1], parameters[2][2]);
Eigen::Quaterniond Qj(parameters[2][6], parameters[2][3], parameters[2][4], parameters[2][5]);
Eigen::Vector3d Vj(parameters[3][0], parameters[3][1], parameters[3][2]);
Eigen::Vector3d Baj(parameters[3][3], parameters[3][4], parameters[3][5]);
Eigen::Vector3d Bgj(parameters[3][6], parameters[3][7], parameters[3][8]);
//Eigen::Matrix<double, 15, 15> Fd;
//Eigen::Matrix<double, 15, 12> Gd;
//Eigen::Vector3d pPj = Pi + Vi * sum_t - 0.5 * g * sum_t * sum_t + corrected_delta_p;
//Eigen::Quaterniond pQj = Qi * delta_q;
//Eigen::Vector3d pVj = Vi - g * sum_t + corrected_delta_v;
//Eigen::Vector3d pBaj = Bai;
//Eigen::Vector3d pBgj = Bgi;
//Vi + Qi * delta_v - g * sum_dt = Vj;
//Qi * delta_q = Qj;
//delta_p = Qi.inverse() * (0.5 * g * sum_dt * sum_dt + Pj - Pi);
//delta_v = Qi.inverse() * (g * sum_dt + Vj - Vi);
//delta_q = Qi.inverse() * Qj;
#if 0
if ((Bai - pre_integration->linearized_ba).norm() > 0.10 ||
(Bgi - pre_integration->linearized_bg).norm() > 0.01)
{
pre_integration->repropagate(Bai, Bgi);
}
#endif
Eigen::Map<Eigen::Matrix<double, 15, 1>> residual(residuals);
residual = pre_integration->evaluate(Pi, Qi, Vi, Bai, Bgi,
Pj, Qj, Vj, Baj, Bgj);
Eigen::Matrix<double, 15, 15> sqrt_info = Eigen::LLT<Eigen::Matrix<double, 15, 15>>(pre_integration->covariance.inverse()).matrixL().transpose();
//sqrt_info.setIdentity();
residual = sqrt_info * residual;
if (jacobians)
{
double sum_dt = pre_integration->sum_dt;
Eigen::Matrix3d dp_dba = pre_integration->jacobian.template block<3, 3>(O_P, O_BA);
Eigen::Matrix3d dp_dbg = pre_integration->jacobian.template block<3, 3>(O_P, O_BG);
Eigen::Matrix3d dq_dbg = pre_integration->jacobian.template block<3, 3>(O_R, O_BG);
Eigen::Matrix3d dv_dba = pre_integration->jacobian.template block<3, 3>(O_V, O_BA);
Eigen::Matrix3d dv_dbg = pre_integration->jacobian.template block<3, 3>(O_V, O_BG);
if (pre_integration->jacobian.maxCoeff() > 1e8 || pre_integration->jacobian.minCoeff() < -1e8)
{
ROS_WARN("numerical unstable in preintegration");
//std::cout << pre_integration->jacobian << std::endl;
/// ROS_BREAK();
}
if (jacobians[0])
{
Eigen::Map<Eigen::Matrix<double, 15, 7, Eigen::RowMajor>> jacobian_pose_i(jacobians[0]);
jacobian_pose_i.setZero();
jacobian_pose_i.block<3, 3>(O_P, O_P) = -Qi.inverse().toRotationMatrix();
jacobian_pose_i.block<3, 3>(O_P, O_R) = Utility::skewSymmetric(Qi.inverse() * (0.5 * G * sum_dt * sum_dt + Pj - Pi - Vi * sum_dt));
#if 0
jacobian_pose_i.block<3, 3>(O_R, O_R) = -(Qj.inverse() * Qi).toRotationMatrix();
#else
Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg));
jacobian_pose_i.block<3, 3>(O_R, O_R) = -(Utility::Qleft(Qj.inverse() * Qi) * Utility::Qright(corrected_delta_q)).bottomRightCorner<3, 3>();
#endif
jacobian_pose_i.block<3, 3>(O_V, O_R) = Utility::skewSymmetric(Qi.inverse() * (G * sum_dt + Vj - Vi));
jacobian_pose_i = sqrt_info * jacobian_pose_i;
if (jacobian_pose_i.maxCoeff() > 1e8 || jacobian_pose_i.minCoeff() < -1e8)
{
ROS_WARN("numerical unstable in preintegration");
//std::cout << sqrt_info << std::endl;
//ROS_BREAK();
}
}
if (jacobians[1])
{
Eigen::Map<Eigen::Matrix<double, 15, 9, Eigen::RowMajor>> jacobian_speedbias_i(jacobians[1]);
jacobian_speedbias_i.setZero();
jacobian_speedbias_i.block<3, 3>(O_P, O_V - O_V) = -Qi.inverse().toRotationMatrix() * sum_dt;
jacobian_speedbias_i.block<3, 3>(O_P, O_BA - O_V) = -dp_dba;
jacobian_speedbias_i.block<3, 3>(O_P, O_BG - O_V) = -dp_dbg;
#if 0
jacobian_speedbias_i.block<3, 3>(O_R, O_BG - O_V) = -dq_dbg;
#else
//Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg));
//jacobian_speedbias_i.block<3, 3>(O_R, O_BG - O_V) = -Utility::Qleft(Qj.inverse() * Qi * corrected_delta_q).bottomRightCorner<3, 3>() * dq_dbg;
jacobian_speedbias_i.block<3, 3>(O_R, O_BG - O_V) = -Utility::Qleft(Qj.inverse() * Qi * pre_integration->delta_q).bottomRightCorner<3, 3>() * dq_dbg;
#endif
jacobian_speedbias_i.block<3, 3>(O_V, O_V - O_V) = -Qi.inverse().toRotationMatrix();
jacobian_speedbias_i.block<3, 3>(O_V, O_BA - O_V) = -dv_dba;
jacobian_speedbias_i.block<3, 3>(O_V, O_BG - O_V) = -dv_dbg;
jacobian_speedbias_i.block<3, 3>(O_BA, O_BA - O_V) = -Eigen::Matrix3d::Identity();
jacobian_speedbias_i.block<3, 3>(O_BG, O_BG - O_V) = -Eigen::Matrix3d::Identity();
jacobian_speedbias_i = sqrt_info * jacobian_speedbias_i;
//ROS_ASSERT(fabs(jacobian_speedbias_i.maxCoeff()) < 1e8);
//ROS_ASSERT(fabs(jacobian_speedbias_i.minCoeff()) < 1e8);
}
if (jacobians[2])
{
Eigen::Map<Eigen::Matrix<double, 15, 7, Eigen::RowMajor>> jacobian_pose_j(jacobians[2]);
jacobian_pose_j.setZero();
jacobian_pose_j.block<3, 3>(O_P, O_P) = Qi.inverse().toRotationMatrix();
#if 0
jacobian_pose_j.block<3, 3>(O_R, O_R) = Eigen::Matrix3d::Identity();
#else
Eigen::Quaterniond corrected_delta_q = pre_integration->delta_q * Utility::deltaQ(dq_dbg * (Bgi - pre_integration->linearized_bg));
jacobian_pose_j.block<3, 3>(O_R, O_R) = Utility::Qleft(corrected_delta_q.inverse() * Qi.inverse() * Qj).bottomRightCorner<3, 3>();
#endif
jacobian_pose_j = sqrt_info * jacobian_pose_j;
//ROS_ASSERT(fabs(jacobian_pose_j.maxCoeff()) < 1e8);
//ROS_ASSERT(fabs(jacobian_pose_j.minCoeff()) < 1e8);
}
if (jacobians[3])
{
Eigen::Map<Eigen::Matrix<double, 15, 9, Eigen::RowMajor>> jacobian_speedbias_j(jacobians[3]);
jacobian_speedbias_j.setZero();
jacobian_speedbias_j.block<3, 3>(O_V, O_V - O_V) = Qi.inverse().toRotationMatrix();
jacobian_speedbias_j.block<3, 3>(O_BA, O_BA - O_V) = Eigen::Matrix3d::Identity();
jacobian_speedbias_j.block<3, 3>(O_BG, O_BG - O_V) = Eigen::Matrix3d::Identity();
jacobian_speedbias_j = sqrt_info * jacobian_speedbias_j;
//ROS_ASSERT(fabs(jacobian_speedbias_j.maxCoeff()) < 1e8);
//ROS_ASSERT(fabs(jacobian_speedbias_j.minCoeff()) < 1e8);
}
}
return true;
}
//bool Evaluate_Direct(double const *const *parameters, Eigen::Matrix<double, 15, 1> &residuals, Eigen::Matrix<double, 15, 30> &jacobians);
//void checkCorrection();
//void checkTransition();
//void checkJacobian(double **parameters);
IntegrationBase* pre_integration;
};
| HKUST-Aerial-Robotics/VINS-Mono | vins_estimator/src/factor/imu_factor.h | C | gpl-3.0 | 8,487 |
/*!
* \file GPS_L1_CA.h
* \brief Defines system parameters for GPS L1 C/A signal and NAV data
* \author Javier Arribas, 2011. jarribas(at)cttc.es
*
* -------------------------------------------------------------------------
*
* Copyright (C) 2010-2015 (see AUTHORS file for a list of contributors)
*
* GNSS-SDR is a software defined Global Navigation
* Satellite Systems receiver
*
* This file is part of GNSS-SDR.
*
* GNSS-SDR is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GNSS-SDR is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNSS-SDR. If not, see <http://www.gnu.org/licenses/>.
*
* -------------------------------------------------------------------------
*/
#ifndef GNSS_SDR_GPS_L1_CA_H_
#define GNSS_SDR_GPS_L1_CA_H_
#include <vector>
#include <utility> // std::pair
#include "MATH_CONSTANTS.h"
#include "gnss_frequencies.h"
#define GPS_L1_CA_CN0_ESTIMATION_SAMPLES 20
#define GPS_L1_CA_MINIMUM_VALID_CN0 25
#define GPS_L1_CA_MAXIMUM_LOCK_FAIL_COUNTER 50
#define GPS_L1_CA_CARRIER_LOCK_THRESHOLD 0.85
// Physical constants
const double GPS_C_m_s = SPEED_OF_LIGHT; //!< The speed of light, [m/s]
const double GPS_C_m_ms = 299792.4580; //!< The speed of light, [m/ms]
const double GPS_PI = 3.1415926535898; //!< Pi as defined in IS-GPS-200E
const double GPS_TWO_PI = 6.283185307179586;//!< 2Pi as defined in IS-GPS-200E
const double OMEGA_EARTH_DOT = DEFAULT_OMEGA_EARTH_DOT; //!< Earth rotation rate, [rad/s]
const double GM = 3.986005e14; //!< Universal gravitational constant times the mass of the Earth, [m^3/s^2]
const double F = -4.442807633e-10; //!< Constant, [s/(m)^(1/2)]
// carrier and code frequencies
const double GPS_L1_FREQ_HZ = FREQ1; //!< L1 [Hz]
const double GPS_L1_CA_CODE_RATE_HZ = 1.023e6; //!< GPS L1 C/A code rate [chips/s]
const double GPS_L1_CA_CODE_LENGTH_CHIPS = 1023.0; //!< GPS L1 C/A code length [chips]
const double GPS_L1_CA_CODE_PERIOD = 0.001; //!< GPS L1 C/A code period [seconds]
const double GPS_L1_CA_CHIP_PERIOD = 9.7752e-07; //!< GPS L1 C/A chip period [seconds]
/*!
* \brief Maximum Time-Of-Arrival (TOA) difference between satellites for a receiver operated on Earth surface is 20 ms
*
* According to the GPS orbit model described in [1] Pag. 32.
* It should be taken into account to set the buffer size for the PRN start timestamp in the pseudoranges block.
* [1] J. Bao-Yen Tsui, Fundamentals of Global Positioning System Receivers. A Software Approach, John Wiley & Sons,
* Inc., Hoboken, NJ, 2nd edition, 2005.
*/
const double MAX_TOA_DELAY_MS = 20;
//#define NAVIGATION_SOLUTION_RATE_MS 1000 // this cannot go here
const double GPS_STARTOFFSET_ms = 68.802; //[ms] Initial sign. travel time (this cannot go here)
// OBSERVABLE HISTORY DEEP FOR INTERPOLATION
const int GPS_L1_CA_HISTORY_DEEP = 500;
// NAVIGATION MESSAGE DEMODULATION AND DECODING
#define GPS_PREAMBLE {1, 0, 0, 0, 1, 0, 1, 1}
const int GPS_CA_PREAMBLE_LENGTH_BITS = 8;
const int GPS_CA_PREAMBLE_LENGTH_SYMBOLS = 160;
const double GPS_CA_PREAMBLE_DURATION_S = 0.160;
const int GPS_CA_TELEMETRY_RATE_BITS_SECOND = 50; //!< NAV message bit rate [bits/s]
const int GPS_CA_TELEMETRY_SYMBOLS_PER_BIT = 20;
const int GPS_CA_TELEMETRY_RATE_SYMBOLS_SECOND = GPS_CA_TELEMETRY_RATE_BITS_SECOND*GPS_CA_TELEMETRY_SYMBOLS_PER_BIT; //!< NAV message bit rate [symbols/s]
const int GPS_WORD_LENGTH = 4; //!< CRC + GPS WORD (-2 -1 0 ... 29) Bits = 4 bytes
const int GPS_SUBFRAME_LENGTH = 40; //!< GPS_WORD_LENGTH x 10 = 40 bytes
const int GPS_SUBFRAME_BITS = 300; //!< Number of bits per subframe in the NAV message [bits]
const int GPS_SUBFRAME_SECONDS = 6; //!< Subframe duration [seconds]
const int GPS_SUBFRAME_MS = 6000; //!< Subframe duration [seconds]
const int GPS_WORD_BITS = 30; //!< Number of bits per word in the NAV message [bits]
// GPS NAVIGATION MESSAGE STRUCTURE
// NAVIGATION MESSAGE FIELDS POSITIONS (from IS-GPS-200E Appendix II)
// SUBFRAME 1-5 (TLM and HOW)
const std::vector<std::pair<int,int> > TOW( { {31,17} } );
const std::vector<std::pair<int,int> > INTEGRITY_STATUS_FLAG({{23,1}});
const std::vector<std::pair<int,int> > ALERT_FLAG({{48,1}});
const std::vector<std::pair<int,int> > ANTI_SPOOFING_FLAG({{49,1}});
const std::vector<std::pair<int,int> > SUBFRAME_ID({{50,3}});
// SUBFRAME 1
const std::vector<std::pair<int,int>> GPS_WEEK({{61,10}});
const std::vector<std::pair<int,int>> CA_OR_P_ON_L2({{71,2}}); //*
const std::vector<std::pair<int,int>> SV_ACCURACY({{73,4}});
const std::vector<std::pair<int,int>> SV_HEALTH ({{77,6}});
const std::vector<std::pair<int,int>> L2_P_DATA_FLAG ({{91,1}});
const std::vector<std::pair<int,int>> T_GD({{197,8}});
const double T_GD_LSB = TWO_N31;
const std::vector<std::pair<int,int>> IODC({{83,2},{211,8}});
const std::vector<std::pair<int,int>> T_OC({{219,16}});
const double T_OC_LSB = TWO_P4;
const std::vector<std::pair<int,int>> A_F2({{241,8}});
const double A_F2_LSB = TWO_N55;
const std::vector<std::pair<int,int>> A_F1({{249,16}});
const double A_F1_LSB = TWO_N43;
const std::vector<std::pair<int,int>> A_F0({{271,22}});
const double A_F0_LSB = TWO_N31;
// SUBFRAME 2
const std::vector<std::pair<int,int>> IODE_SF2({{61,8}});
const std::vector<std::pair<int,int>> C_RS({{69,16}});
const double C_RS_LSB = TWO_N5;
const std::vector<std::pair<int,int>> DELTA_N({{91,16}});
const double DELTA_N_LSB = PI_TWO_N43;
const std::vector<std::pair<int,int>> M_0({{107,8},{121,24}});
const double M_0_LSB = PI_TWO_N31;
const std::vector<std::pair<int,int>> C_UC({{151,16}});
const double C_UC_LSB = TWO_N29;
const std::vector<std::pair<int,int>> E({{167,8},{181,24}});
const double E_LSB = TWO_N33;
const std::vector<std::pair<int,int>> C_US({{211,16}});
const double C_US_LSB = TWO_N29;
const std::vector<std::pair<int,int>> SQRT_A({{227,8},{241,24}});
const double SQRT_A_LSB = TWO_N19;
const std::vector<std::pair<int,int>> T_OE({{271,16}});
const double T_OE_LSB = TWO_P4;
const std::vector<std::pair<int,int>> FIT_INTERVAL_FLAG({{271,1}});
const std::vector<std::pair<int,int>> AODO({{272,5}});
const int AODO_LSB = 900;
// SUBFRAME 3
const std::vector<std::pair<int,int>> C_IC({{61,16}});
const double C_IC_LSB = TWO_N29;
const std::vector<std::pair<int,int>> OMEGA_0({{77,8},{91,24}});
const double OMEGA_0_LSB = PI_TWO_N31;
const std::vector<std::pair<int,int>> C_IS({{121,16}});
const double C_IS_LSB = TWO_N29;
const std::vector<std::pair<int,int>> I_0({{137,8},{151,24}});
const double I_0_LSB = PI_TWO_N31;
const std::vector<std::pair<int,int>> C_RC({{181,16}});
const double C_RC_LSB = TWO_N5;
const std::vector<std::pair<int,int>> OMEGA({{197,8},{211,24}});
const double OMEGA_LSB = PI_TWO_N31;
const std::vector<std::pair<int,int>> OMEGA_DOT({{241,24}});
const double OMEGA_DOT_LSB = PI_TWO_N43;
const std::vector<std::pair<int,int>> IODE_SF3({{271,8}});
const std::vector<std::pair<int,int>> I_DOT({{279,14}});
const double I_DOT_LSB = PI_TWO_N43;
// SUBFRAME 4-5
const std::vector<std::pair<int,int>> SV_DATA_ID({{61,2}});
const std::vector<std::pair<int,int>> SV_PAGE({{63,6}});
// SUBFRAME 4
//! \todo read all pages of subframe 4
// Page 18 - Ionospheric and UTC data
const std::vector<std::pair<int,int>> ALPHA_0({{69,8}});
const double ALPHA_0_LSB = TWO_N30;
const std::vector<std::pair<int,int>> ALPHA_1({{77,8}});
const double ALPHA_1_LSB = TWO_N27;
const std::vector<std::pair<int,int>> ALPHA_2({{91,8}});
const double ALPHA_2_LSB = TWO_N24;
const std::vector<std::pair<int,int>> ALPHA_3({{99,8}});
const double ALPHA_3_LSB = TWO_N24;
const std::vector<std::pair<int,int>> BETA_0({{107,8}});
const double BETA_0_LSB = TWO_P11;
const std::vector<std::pair<int,int>> BETA_1({{121,8}});
const double BETA_1_LSB = TWO_P14;
const std::vector<std::pair<int,int>> BETA_2({{129,8}});
const double BETA_2_LSB = TWO_P16;
const std::vector<std::pair<int,int>> BETA_3({{137,8}});
const double BETA_3_LSB = TWO_P16;
const std::vector<std::pair<int,int>> A_1({{151,24}});
const double A_1_LSB = TWO_N50;
const std::vector<std::pair<int,int>> A_0({{181,24},{211,8}});
const double A_0_LSB = TWO_N30;
const std::vector<std::pair<int,int>> T_OT({{219,8}});
const double T_OT_LSB = TWO_P12;
const std::vector<std::pair<int,int>> WN_T({{227,8}});
const double WN_T_LSB = 1;
const std::vector<std::pair<int,int>> DELTAT_LS({{241,8}});
const double DELTAT_LS_LSB = 1;
const std::vector<std::pair<int,int>> WN_LSF({{249,8}});
const double WN_LSF_LSB = 1;
const std::vector<std::pair<int,int>> DN({{257,8}});
const double DN_LSB = 1;
const std::vector<std::pair<int,int>> DELTAT_LSF({{271,8}});
const double DELTAT_LSF_LSB = 1;
// Page 25 - Antispoofing, SV config and SV health (PRN 25 -32)
const std::vector<std::pair<int,int>> HEALTH_SV25({{229,6}});
const std::vector<std::pair<int,int>> HEALTH_SV26({{241,6}});
const std::vector<std::pair<int,int>> HEALTH_SV27({{247,6}});
const std::vector<std::pair<int,int>> HEALTH_SV28({{253,6}});
const std::vector<std::pair<int,int>> HEALTH_SV29({{259,6}});
const std::vector<std::pair<int,int>> HEALTH_SV30({{271,6}});
const std::vector<std::pair<int,int>> HEALTH_SV31({{277,6}});
const std::vector<std::pair<int,int>> HEALTH_SV32({{283,6}});
// SUBFRAME 5
//! \todo read all pages of subframe 5
// page 25 - Health (PRN 1 - 24)
const std::vector<std::pair<int,int>> T_OA({{69,8}});
const double T_OA_LSB = TWO_P12;
const std::vector<std::pair<int,int>> WN_A({{77,8}});
const std::vector<std::pair<int,int>> HEALTH_SV1({{91,6}});
const std::vector<std::pair<int,int>> HEALTH_SV2({{97,6}});
const std::vector<std::pair<int,int>> HEALTH_SV3({{103,6}});
const std::vector<std::pair<int,int>> HEALTH_SV4({{109,6}});
const std::vector<std::pair<int,int>> HEALTH_SV5({{121,6}});
const std::vector<std::pair<int,int>> HEALTH_SV6({{127,6}});
const std::vector<std::pair<int,int>> HEALTH_SV7({{133,6}});
const std::vector<std::pair<int,int>> HEALTH_SV8({{139,6}});
const std::vector<std::pair<int,int>> HEALTH_SV9({{151,6}});
const std::vector<std::pair<int,int>> HEALTH_SV10({{157,6}});
const std::vector<std::pair<int,int>> HEALTH_SV11({{163,6}});
const std::vector<std::pair<int,int>> HEALTH_SV12({{169,6}});
const std::vector<std::pair<int,int>> HEALTH_SV13({{181,6}});
const std::vector<std::pair<int,int>> HEALTH_SV14({{187,6}});
const std::vector<std::pair<int,int>> HEALTH_SV15({{193,6}});
const std::vector<std::pair<int,int>> HEALTH_SV16({{199,6}});
const std::vector<std::pair<int,int>> HEALTH_SV17({{211,6}});
const std::vector<std::pair<int,int>> HEALTH_SV18({{217,6}});
const std::vector<std::pair<int,int>> HEALTH_SV19({{223,6}});
const std::vector<std::pair<int,int>> HEALTH_SV20({{229,6}});
const std::vector<std::pair<int,int>> HEALTH_SV21({{241,6}});
const std::vector<std::pair<int,int>> HEALTH_SV22({{247,6}});
const std::vector<std::pair<int,int>> HEALTH_SV23({{253,6}});
const std::vector<std::pair<int,int>> HEALTH_SV24({{259,6}});
#endif /* GNSS_SDR_GPS_L1_CA_H_ */
| luis-esteve/gnss-sdr | src/core/system_parameters/GPS_L1_CA.h | C | gpl-3.0 | 11,551 |
/* Copyright 2016 Devon Call, Zeke Hunter-Green, Paige Ormiston, Joe Renner, Jesse Sliter
This file is part of Myrge.
Myrge is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Myrge is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Myrge. If not, see <http://www.gnu.org/licenses/>. */
app.controller('NavCtrl', [
'$scope',
'$state',
'auth',
function($scope, $state, auth){
$scope.isLoggedIn = auth.isLoggedIn;
$scope.currentUser = auth.currentUser;
$scope.logOut = auth.logOut;
$scope.loggedin = auth.isLoggedIn();
if($scope.loggedin){
auth.validate(auth.getToken()).success(function(data){
if(!data.valid){
auth.logOut();
$state.go("login");
}
});
}
}]);
| Decision-Maker/sp | public/javascripts/Controllers/navController.js | JavaScript | gpl-3.0 | 1,136 |
# Topydo - A todo.txt client written in Python.
# Copyright (C) 2014 - 2015 Bram Schoenmakers <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
This module provides the Todo class.
"""
from datetime import date
from topydo.lib.Config import config
from topydo.lib.TodoBase import TodoBase
from topydo.lib.Utils import date_string_to_date
class Todo(TodoBase):
"""
This class adds common functionality with respect to dates to the Todo
base class, mainly by interpreting the start and due dates of task.
"""
def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {}
def get_date(self, p_tag):
""" Given a date tag, return a date object. """
string = self.tag_value(p_tag)
result = None
try:
result = date_string_to_date(string) if string else None
except ValueError:
pass
return result
def start_date(self):
""" Returns a date object of the todo's start date. """
return self.get_date(config().tag_start())
def due_date(self):
""" Returns a date object of the todo's due date. """
return self.get_date(config().tag_due())
def is_active(self):
"""
Returns True when the start date is today or in the past and the
task has not yet been completed.
"""
start = self.start_date()
return not self.is_completed() and (not start or start <= date.today())
def is_overdue(self):
"""
Returns True when the due date is in the past and the task has not
yet been completed.
"""
return not self.is_completed() and self.days_till_due() < 0
def days_till_due(self):
"""
Returns the number of days till the due date. Returns a negative number
of days when the due date is in the past.
Returns 0 when the task has no due date.
"""
due = self.due_date()
if due:
diff = due - date.today()
return diff.days
return 0
def length(self):
"""
Returns the length (in days) of the task, by considering the start date
and the due date. When there is no start date, its creation date is
used. Returns 0 when one of these dates is missing.
"""
start = self.start_date() or self.creation_date()
due = self.due_date()
if start and due and start < due:
diff = due - start
return diff.days
else:
return 0
| bram85/topydo | topydo/lib/Todo.py | Python | gpl-3.0 | 3,165 |
/* Copyright (c) Colorado School of Mines, 1996.*/
/* All rights reserved. */
/* segy.h - include file for SEGY traces
*
* declarations for:
* typedef struct {} segy - the trace identification header
* typedef struct {} bhed - binary header
*
* Note:
* If header words are added, run the makefile in this directory
* to recreate hdr.h.
*
* Reference:
* K. M. Barry, D. A. Cavers and C. W. Kneale, "Special Report:
* Recommended Standards for Digital Tape Formats",
* Geophysics, vol. 40, no. 2 (April 1975), P. 344-352.
*
* $Author: koehn $
* $Source: /home/tbohlen/CVSROOT/DENISE/src/segy.h,v $
* $Revision: 1.1.1.1 $ ; $Date: 2007/11/21 22:44:52 $
*/
#ifndef SEGY_H
#define SEGY_H
#define SU_NFLTS 32768 /* Arbitrary limit on data array size */
/* TYPEDEFS */
#ifdef _CRAY
typedef struct { /* segy - trace identification header */
signed tracl :32; /* trace sequence number within line */
signed tracr :32; /* trace sequence number within reel */
signed fldr :32; /* field record number */
signed tracf :32; /* trace number within field record */
signed ep :32; /* energy source point number */
signed cdp :32; /* CDP ensemble number */
signed cdpt :32; /* trace number within CDP ensemble */
signed trid :16; /* trace identification code:
1 = seismic data
2 = dead
3 = dummy
4 = time break
5 = uphole
6 = sweep
7 = timing
8 = water break
9---, N = optional use (N = 32,767)
Following are CWP id flags:
9 = autocorrelation
10 = Fourier transformed - no packing
xr[0],xi[0], ..., xr[N-1],xi[N-1]
11 = Fourier transformed - unpacked Nyquist
xr[0],xi[0],...,xr[N/2],xi[N/2]
12 = Fourier transformed - packed Nyquist
even N:
xr[0],xr[N/2],xr[1],xi[1], ...,
xr[N/2 -1],xi[N/2 -1]
(note the exceptional second entry)
odd N:
xr[0],xr[(N-1)/2],xr[1],xi[1], ...,
xr[(N-1)/2 -1],xi[(N-1)/2 -1],xi[(N-1)/2]
(note the exceptional second & last entries)
13 = Complex signal in the time domain
xr[0],xi[0], ..., xr[N-1],xi[N-1]
14 = Fourier transformed - amplitude/phase
a[0],p[0], ..., a[N-1],p[N-1]
15 = Complex time signal - amplitude/phase
a[0],p[0], ..., a[N-1],p[N-1]
16 = Real part of complex trace from 0 to Nyquist
17 = Imag part of complex trace from 0 to Nyquist
18 = Amplitude of complex trace from 0 to Nyquist
19 = Phase of complex trace from 0 to Nyquist
21 = Wavenumber time domain (k-t)
22 = Wavenumber frequency (k-omega)
23 = Envelope of the complex time trace
24 = Phase of the complex time trace
25 = Frequency of the complex time trace
30 = Depth-Range (z-x) traces
101 = Seismic data packed to bytes (by supack1)
102 = Seismic data packed to 2 bytes (by supack2)
*/
signed nvs :16; /* number of vertically summed traces (see vscode
in bhed structure) */
signed nhs :16; /* number of horizontally summed traces (see vscode
in bhed structure) */
signed duse :16; /* data use:
1 = production
2 = test */
signed offset :32; /* distance from source point to receiver
group (negative if opposite to direction
in which the line was shot) */
signed gelev :32; /* receiver group elevation from sea level
(above sea level is positive) */
signed selev :32; /* source elevation from sea level
(above sea level is positive) */
signed sdepth :32; /* source depth (positive) */
signed gdel :32; /* datum elevation at receiver group */
signed sdel :32; /* datum elevation at source */
signed swdep :32; /* water depth at source */
signed gwdep :32; /* water depth at receiver group */
signed scalel :16; /* scale factor for previous 7 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
signed scalco :16; /* scale factor for next 4 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
signed sx :32; /* X source coordinate */
signed sy :32; /* Y source coordinate */
signed gx :32; /* X group coordinate */
signed gy :32; /* Y group coordinate */
signed counit :16; /* coordinate units code:
for previous four entries
1 = length (meters or feet)
2 = seconds of arc (in this case, the
X values are longitude and the Y values
are latitude, a positive value designates
the number of seconds east of Greenwich
or north of the equator */
signed wevel :16; /* weathering velocity */
signed swevel :16; /* subweathering velocity */
signed sut :16; /* uphole time at source */
signed gut :16; /* uphole time at receiver group */
signed sstat :16; /* source static correction */
signed gstat :16; /* group static correction */
signed tstat :16; /* total static applied */
signed laga :16; /* lag time A, time in ms between end of 240-
byte trace identification header and time
break, positive if time break occurs after
end of header, time break is defined as
the initiation pulse which maybe recorded
on an auxiliary trace or as otherwise
specified by the recording system */
signed lagb :16; /* lag time B, time in ms between the time break
and the initiation time of the energy source,
may be positive or negative */
signed delrt :16; /* delay recording time, time in ms between
initiation time of energy source and time
when recording of data samples begins
(for deep water work if recording does not
start at zero time) */
signed muts :16; /* mute time--start */
signed mute :16; /* mute time--end */
unsigned ns :16; /* number of samples in this trace */
unsigned dt :16; /* sample interval; in micro-seconds */
signed gain :16; /* gain type of field instruments code:
1 = fixed
2 = binary
3 = floating point
4 ---- N = optional use */
signed igc :16; /* instrument gain constant */
signed igi :16; /* instrument early or initial gain */
signed corr :16; /* correlated:
1 = no
2 = yes */
signed sfs :16; /* sweep frequency at start */
signed sfe :16; /* sweep frequency at end */
signed slen :16; /* sweep length in ms */
signed styp :16; /* sweep type code:
1 = linear
2 = cos-squared
3 = other */
signed stas :16; /* sweep trace length at start in ms */
signed stae :16; /* sweep trace length at end in ms */
signed tatyp :16; /* taper type: 1=linear, 2=cos^2, 3=other */
signed afilf :16; /* alias filter frequency if used */
signed afils :16; /* alias filter slope */
signed nofilf :16; /* notch filter frequency if used */
signed nofils :16; /* notch filter slope */
signed lcf :16; /* low cut frequency if used */
signed hcf :16; /* high cut frequncy if used */
signed lcs :16; /* low cut slope */
signed hcs :16; /* high cut slope */
signed year :16; /* year data recorded */
signed day :16; /* day of year */
signed hour :16; /* hour of day (24 hour clock) */
signed minute :16; /* minute of hour */
signed sec :16; /* second of minute */
signed timbas :16; /* time basis code:
1 = local
2 = GMT
3 = other */
signed trwf :16; /* trace weighting factor, defined as 1/2^N
volts for the least sigificant bit */
signed grnors :16; /* geophone group number of roll switch
position one */
signed grnofr :16; /* geophone group number of trace one within
original field record */
signed grnlof :16; /* geophone group number of last trace within
original field record */
signed gaps :16; /* gap size (total number of groups dropped) */
signed otrav :16; /* overtravel taper code:
1 = down (or behind)
2 = up (or ahead) */
/* local assignments */
/* signed pad :32; */ /* double word alignment for Cray 64-bit floats */
float d1; /* sample spacing for non-seismic data */
float f1; /* first sample location for non-seismic data */
float d2; /* sample spacing between traces */
float f2; /* first trace location */
float ungpow; /* negative of power used for dynamic
range compression */
float unscale; /* reciprocal of scaling factor to normalize
range */
signed ntr :32; /* number of traces */
signed mark :16; /* mark selected traces */
signed unass :16; /* unassigned values */
float data[SU_NFLTS];
} segy;
typedef struct { /* bhed - binary header */
int jobid :32; /* job identification number */
int lino :32; /* line number (only one line per reel) */
int reno :32; /* reel number */
short ntrpr :16; /* number of data traces per record */
short nart :16; /* number of auxiliary traces per record */
short hdt :16; /* sample interval in micro secs for this reel */
short dto :16; /* same for original field recording */
short hns :16; /* number of samples per trace for this reel */
short nso :16; /* same for original field recording */
short format :16; /* data sample format code:
1 = floating point (4 bytes)
2 = fixed point (4 bytes)
3 = fixed point (2 bytes)
4 = fixed point w/gain code (4 bytes) */
short fold :16; /* CDP fold expected per CDP ensemble */
short tsort :16; /* trace sorting code:
1 = as recorded (no sorting)
2 = CDP ensemble
3 = single fold continuous profile
4 = horizontally stacked */
short vscode :16; /* vertical sum code:
1 = no sum
2 = two sum ...
N = N sum (N = 32,767) */
short hsfs :16; /* sweep frequency at start */
short hsfe :16; /* sweep frequency at end */
short hslen :16; /* sweep length (ms) */
short hstyp :16; /* sweep type code:
1 = linear
2 = parabolic
3 = exponential
4 = other */
short schn :16; /* trace number of sweep channel */
short hstas :16; /* sweep trace taper length at start if
tapered (the taper starts at zero time
and is effective for this length) */
short hstae :16; /* sweep trace taper length at end (the ending
taper starts at sweep length minus the taper
length at end) */
short htatyp :16; /* sweep trace taper type code:
1 = linear
2 = cos-squared
3 = other */
short hcorr :16; /* correlated data traces code:
1 = no
2 = yes */
short bgrcv :16; /* binary gain recovered code:
1 = yes
2 = no */
short rcvm :16; /* amplitude recovery method code:
1 = none
2 = spherical divergence
3 = AGC
4 = other */
short mfeet :16; /* measurement system code:
1 = meters
2 = feet */
short polyt :16; /* impulse signal polarity code:
1 = increase in pressure or upward
geophone case movement gives
negative number on tape
2 = increase in pressure or upward
geophone case movement gives
positive number on tape */
short vpol :16; /* vibratory polarity code:
code seismic signal lags pilot by
1 337.5 to 22.5 degrees
2 22.5 to 67.5 degrees
3 67.5 to 112.5 degrees
4 112.5 to 157.5 degrees
5 157.5 to 202.5 degrees
6 202.5 to 247.5 degrees
7 247.5 to 292.5 degrees
8 293.5 to 337.5 degrees */
signed pad :32; /* double word alignment pad */
double hunass[21]; /* unassigned, double is portable! */
} bhed;
#else /* bit fields may not be portable! */
typedef struct { /* segy - trace identification header */
int tracl ; /* trace sequence number within line */
int tracr ; /* trace sequence number within reel */
int fldr ; /* field record number */
int tracf ; /* trace number within field record */
int ep ; /* energy source point number */
int cdp ; /* CDP ensemble number */
int cdpt ; /* trace number within CDP ensemble */
short trid ; /* trace identification code:
1 = seismic data
2 = dead
3 = dummy
4 = time break
5 = uphole
6 = sweep
7 = timing
8 = water break
9---, N = optional use (N = 32,767)
Following are CWP id flags:
9 = autocorrelation
10 = Fourier transformed - no packing
xr[0],xi[0], ..., xr[N-1],xi[N-1]
11 = Fourier transformed - unpacked Nyquist
xr[0],xi[0],...,xr[N/2],xi[N/2]
12 = Fourier transformed - packed Nyquist
even N:
xr[0],xr[N/2],xr[1],xi[1], ...,
xr[N/2 -1],xi[N/2 -1]
(note the exceptional second entry)
odd N:
xr[0],xr[(N-1)/2],xr[1],xi[1], ...,
xr[(N-1)/2 -1],xi[(N-1)/2 -1],xi[(N-1)/2]
(note the exceptional second & last entries)
13 = Complex signal in the time domain
xr[0],xi[0], ..., xr[N-1],xi[N-1]
14 = Fourier transformed - amplitude/phase
a[0],p[0], ..., a[N-1],p[N-1]
15 = Complex time signal - amplitude/phase
a[0],p[0], ..., a[N-1],p[N-1]
16 = Real part of complex trace from 0 to Nyquist
17 = Imag part of complex trace from 0 to Nyquist
18 = Amplitude of complex trace from 0 to Nyquist
19 = Phase of complex trace from 0 to Nyquist
21 = Wavenumber time domain (k-t)
22 = Wavenumber frequency (k-omega)
23 = Envelope of the complex time trace
24 = Phase of the complex time trace
25 = Frequency of the complex time trace
30 = Depth-Range (z-x) traces
101 = Seismic data packed to bytes (by supack1)
102 = Seismic data packed to 2 bytes (by supack2)
*/
short nvs ; /* number of vertically summed traces (see vscode
in bhed structure) */
short nhs ; /* number of horizontally summed traces (see vscode
in bhed structure) */
short duse ; /* data use:
1 = production
2 = test */
int offset ; /* distance from source point to receiver
group (negative if opposite to direction
in which the line was shot) */
int gelev ; /* receiver group elevation from sea level
(above sea level is positive) */
int selev ; /* source elevation from sea level
(above sea level is positive) */
int sdepth ; /* source depth (positive) */
int gdel ; /* datum elevation at receiver group */
int sdel ; /* datum elevation at source */
int swdep ; /* water depth at source */
int gwdep ; /* water depth at receiver group */
short scalel ; /* scale factor for previous 7 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
short scalco ; /* scale factor for next 4 entries
with value plus or minus 10 to the
power 0, 1, 2, 3, or 4 (if positive,
multiply, if negative divide) */
int sx ; /* X source coordinate */
int sy ; /* Y source coordinate */
int gx ; /* X group coordinate */
int gy ; /* Y group coordinate */
short counit ; /* coordinate units code:
for previous four entries
1 = length (meters or feet)
2 = seconds of arc (in this case, the
X values are longitude and the Y values
are latitude, a positive value designates
the number of seconds east of Greenwich
or north of the equator */
short wevel ; /* weathering velocity */
short swevel ; /* subweathering velocity */
short sut ; /* uphole time at source */
short gut ; /* uphole time at receiver group */
short sstat ; /* source static correction */
short gstat ; /* group static correction */
short tstat ; /* total static applied */
short laga ; /* lag time A, time in ms between end of 240-
byte trace identification header and time
break, positive if time break occurs after
end of header, time break is defined as
the initiation pulse which maybe recorded
on an auxiliary trace or as otherwise
specified by the recording system */
short lagb ; /* lag time B, time in ms between the time break
and the initiation time of the energy source,
may be positive or negative */
short delrt ; /* delay recording time, time in ms between
initiation time of energy source and time
when recording of data samples begins
(for deep water work if recording does not
start at zero time) */
short muts ; /* mute time--start */
short mute ; /* mute time--end */
unsigned short ns ; /* number of samples in this trace */
unsigned short dt ; /* sample interval; in micro-seconds */
short gain ; /* gain type of field instruments code:
1 = fixed
2 = binary
3 = floating point
4 ---- N = optional use */
short igc ; /* instrument gain constant */
short igi ; /* instrument early or initial gain */
short corr ; /* correlated:
1 = no
2 = yes */
short sfs ; /* sweep frequency at start */
short sfe ; /* sweep frequency at end */
short slen ; /* sweep length in ms */
short styp ; /* sweep type code:
1 = linear
2 = cos-squared
3 = other */
short stas ; /* sweep trace length at start in ms */
short stae ; /* sweep trace length at end in ms */
short tatyp ; /* taper type: 1=linear, 2=cos^2, 3=other */
short afilf ; /* alias filter frequency if used */
short afils ; /* alias filter slope */
short nofilf ; /* notch filter frequency if used */
short nofils ; /* notch filter slope */
short lcf ; /* low cut frequency if used */
short hcf ; /* high cut frequncy if used */
short lcs ; /* low cut slope */
short hcs ; /* high cut slope */
short year ; /* year data recorded */
short day ; /* day of year */
short hour ; /* hour of day (24 hour clock) */
short minute ; /* minute of hour */
short sec ; /* second of minute */
short timbas ; /* time basis code:
1 = local
2 = GMT
3 = other */
short trwf ; /* trace weighting factor, defined as 1/2^N
volts for the least sigificant bit */
short grnors ; /* geophone group number of roll switch
position one */
short grnofr ; /* geophone group number of trace one within
original field record */
short grnlof ; /* geophone group number of last trace within
original field record */
short gaps ; /* gap size (total number of groups dropped) */
short otrav ; /* overtravel taper code:
1 = down (or behind)
2 = up (or ahead) */
/* local assignments */
float d1; /* sample spacing for non-seismic data */
float f1; /* first sample location for non-seismic data */
float d2; /* sample spacing between traces */
float f2; /* first trace location */
float ungpow; /* negative of power used for dynamic
range compression */
float unscale; /* reciprocal of scaling factor to normalize
range */
int ntr ; /* number of traces */
short mark ; /* mark selected traces */
short unass[15]; /* unassigned values */
float data[SU_NFLTS];
} segy;
typedef struct { /* bhed - binary header */
int jobid ; /* job identification number */
int lino ; /* line number (only one line per reel) */
int reno ; /* reel number */
short ntrpr ; /* number of data traces per record */
short nart ; /* number of auxiliary traces per record */
short hdt ; /* sample interval in micro secs for this reel */
short dto ; /* same for original field recording */
short hns ; /* number of samples per trace for this reel */
short nso ; /* same for original field recording */
short format ; /* data sample format code:
1 = floating point (4 bytes)
2 = fixed point (4 bytes)
3 = fixed point (2 bytes)
4 = fixed point w/gain code (4 bytes) */
short fold ; /* CDP fold expected per CDP ensemble */
short tsort ; /* trace sorting code:
1 = as recorded (no sorting)
2 = CDP ensemble
3 = single fold continuous profile
4 = horizontally stacked */
short vscode ; /* vertical sum code:
1 = no sum
2 = two sum ...
N = N sum (N = 32,767) */
short hsfs ; /* sweep frequency at start */
short hsfe ; /* sweep frequency at end */
short hslen ; /* sweep length (ms) */
short hstyp ; /* sweep type code:
1 = linear
2 = parabolic
3 = exponential
4 = other */
short schn ; /* trace number of sweep channel */
short hstas ; /* sweep trace taper length at start if
tapered (the taper starts at zero time
and is effective for this length) */
short hstae ; /* sweep trace taper length at end (the ending
taper starts at sweep length minus the taper
length at end) */
short htatyp ; /* sweep trace taper type code:
1 = linear
2 = cos-squared
3 = other */
short hcorr ; /* correlated data traces code:
1 = no
2 = yes */
short bgrcv ; /* binary gain recovered code:
1 = yes
2 = no */
short rcvm ; /* amplitude recovery method code:
1 = none
2 = spherical divergence
3 = AGC
4 = other */
short mfeet ; /* measurement system code:
1 = meters
2 = feet */
short polyt ; /* impulse signal polarity code:
1 = increase in pressure or upward
geophone case movement gives
negative number on tape
2 = increase in pressure or upward
geophone case movement gives
positive number on tape */
short vpol ; /* vibratory polarity code:
code seismic signal lags pilot by
1 337.5 to 22.5 degrees
2 22.5 to 67.5 degrees
3 67.5 to 112.5 degrees
4 112.5 to 157.5 degrees
5 157.5 to 202.5 degrees
6 202.5 to 247.5 degrees
7 247.5 to 292.5 degrees
8 293.5 to 337.5 degrees */
char pad[4] ; /* double word alignment pad */
int hunass[42]; /* unassigned */
} bhed;
#endif /* end of ifdef CRAY, the bit fields are not portable */
/* DEFINES */
#define gettr(x) fgettr(stdin, (x))
#define vgettr(x) fvgettr(stdin, (x))
#define puttr(x) fputtr(stdout, (x))
#define gettra(x, y) fgettra(stdin, (x), (y))
/* The following refer to the trid field in segy.h */
/* CHARPACK represents byte packed seismic data from supack1 */
#define CHARPACK 101
/* SHORTPACK represents 2 byte packed seismic data from supack2 */
#define SHORTPACK 102
/* TREAL represents real time traces */
#define TREAL 1
/* TDEAD represents dead time traces */
#define TDEAD 2
/* TDUMMY represents dummy time traces */
#define TDUMMY 3
/* TBREAK represents time break traces */
#define TBREAK 4
/* UPHOLE represents uphole traces */
#define UPHOLE 5
/* SWEEP represents sweep traces */
#define SWEEP 6
/* TIMING represents timing traces */
#define TIMING 7
/* WBREAK represents timing traces */
#define WBREAK 8
/* TCMPLX represents complex time traces */
#define TCMPLX 13
/* TAMPH represents time domain data in amplitude/phase form */
#define TAMPH 15
/* FPACK represents packed frequency domain data */
#define FPACK 12
/* FUNPACKNYQ represents complex frequency domain data */
#define FUNPACKNYQ 11
/* FCMPLX represents complex frequency domain data */
#define FCMPLX 10
/* FAMPH represents freq domain data in amplitude/phase form */
#define FAMPH 14
/* REALPART represents the real part of a trace to Nyquist */
#define REALPART 16
/* IMAGPART represents the imaginary part of a trace to Nyquist */
#define IMAGPART 17
/* AMPLITUDE represents the amplitude of a trace to Nyquist */
#define AMPLITUDE 18
/* PHASE represents the phase of a trace to Nyquist */
#define PHASE 19
/* KT represents wavenumber-time domain data */
#define KT 21
/* KOMEGA represents wavenumber-frequency domain data */
#define KOMEGA 22
/* ENVELOPE represents the envelope of the complex time trace */
#define ENVELOPE 23
/* INSTPHASE represents the phase of the complex time trace */
#define INSTPHASE 24
/* INSTFREQ represents the frequency of the complex time trace */
#define INSTFREQ 25
/* DEPTH represents traces in depth-range (z-x) */
#define TRID_DEPTH 30
#define ISSEISMIC(id) ( (id)==0 || (id)==TREAL || (id)==TDEAD || (id)==TDUMMY )
/* FUNCTION PROTOTYPES */
#ifdef __cplusplus /* if C++, specify external linkage to C functions */
extern "C" {
#endif
int fgettr(FILE *fp, segy *tp);
int fvgettr(FILE *fp, segy *tp);
void fputtr(FILE *fp, segy *tp);
int fgettra(FILE *fp, segy *tp, int itr);
/* hdrpkge */
/* void gethval(const segy *tp, int index, Value *valp);
void puthval(segy *tp, int index, Value *valp);
void getbhval(const bhed *bhp, int index, Value *valp);
void putbhval(bhed *bhp, int index, Value *valp);
void gethdval(const segy *tp, char *key, Value *valp);
void puthdval(segy *tp, char *key, Value *valp);
char *hdtype(const char *key);
char *getkey(const int index);
int getindex(const char *key);
void swaphval(segy *tp, int index);
void swapbhval(bhed *bhp, int index);
void printheader(const segy *tp); */
void tabplot(segy *tp, int itmin, int itmax);
#ifdef __cplusplus /* if C++, end external linkage specification */
}
#endif
#endif
| daniel-koehn/GERMAINE | include/segy.h | C | gpl-3.0 | 25,371 |
/*
* File: tstGenericDBObject.cpp
* Author: volker
*
* Created on March 2, 2014, 3:46 PM
*/
#include <QString>
#include "tstScore.h"
#include "Score.h"
using namespace QTournament;
//----------------------------------------------------------------------------
void tstScore::testGameScore_IsValidScore()
{
printStartMsg("tstScore::testGameScore_IsValidScore");
int tstScore[][3] = {
{-1, 10, 0},
{21, -6, 0},
{29, 31, 0},
{32, 10, 0},
{21, 21, 0},
{12, 12, 0},
{30, 29, 1},
{29, 30, 1},
{20, 21, 0},
{21, 20, 0},
{13, 21, 1},
{21, 0, 1},
{23, 21, 1},
{28, 26, 1},
{28, 3, 0},
};
for (auto score : tstScore)
{
bool expectedResult = (score[2] == 1);
// test the static function isValidScore()
CPPUNIT_ASSERT(GameScore::isValidScore(score[0], score[1]) == expectedResult);
// test the factory function fromScore()
auto g = GameScore::fromScore(score[0], score[1]);
CPPUNIT_ASSERT((g == nullptr) == !expectedResult);
if (expectedResult)
{
auto sc = g->getScore();
CPPUNIT_ASSERT(get<0>(sc) == score[0]);
CPPUNIT_ASSERT(get<1>(sc) == score[1]);
}
// test the factory function fromString()
QString s = QString::number(score[0]) + ":" + QString::number(score[1]);
g = GameScore::fromString(s);
CPPUNIT_ASSERT((g == nullptr) == !expectedResult);
if (expectedResult)
{
auto sc = g->getScore();
CPPUNIT_ASSERT(get<0>(sc) == score[0]);
CPPUNIT_ASSERT(get<1>(sc) == score[1]);
}
}
printEndMsg();
}
//----------------------------------------------------------------------------
void tstScore::testGameScore_ToString()
{
printStartMsg("tstScore::testGameScore_ToString");
auto gs = GameScore::fromScore(12, 21);
CPPUNIT_ASSERT(gs->toString() == "12:21");
gs = GameScore::fromScore(21, 0);
CPPUNIT_ASSERT(gs->toString() == "21:0");
printEndMsg();
}
//----------------------------------------------------------------------------
void tstScore::testGameScore_GetWinner()
{
printStartMsg("tstScore::testGameScore_GetWinner");
int tstScore[][3] = {
{30, 29, 1},
{29, 30, 2},
{13, 21, 2},
{21, 0, 1},
{23, 21, 1},
{28, 26, 1},
};
for (auto score : tstScore)
{
auto gs = GameScore::fromScore(score[0], score[1]);
CPPUNIT_ASSERT(gs->getWinner() == score[2]);
int loser = (score[2] == 1) ? 2 : 1;
CPPUNIT_ASSERT(gs->getLoser() == loser);
}
printEndMsg();
}
//----------------------------------------------------------------------------
//------------------MatchScore------------------------------------------------
//----------------------------------------------------------------------------
void tstScore::testMatchScore_FactoryFuncs_ToString()
{
constexpr int MAX_NUM_GAMES = 5;
printStartMsg("tstScore::testMatchScore_FactoryFuncs_ToString");
int gameScore[][2] = {
{30, 29}, // 0
{29, 30}, // 1
{13, 21}, // 2
{21, 0}, // 3
{21, 18}, // 4
{23, 21}, // 5
{28, 26}, // 6
};
int gameCombinations[][MAX_NUM_GAMES + 5] = {
// game1, game2, game3, game4, game5, numWinGames, allowDraw, isValid, winner, loser
// +0 , +1 , +2 , +3 , +4
{0, 1, -1, -1, -1, 2, 0, 0, -1, -1}, // invalid draw
{0, 0, -1, -1, -1, 2, 0, 1, 1, 2}, // two games, player 1 wins
{2, 4, 2, 2, -1, 2, 0, 0, -1, -1}, // four games but only two win games ==> invalid
{2, 4, 2, 2, -1, 3, 0, 1, 2, 1}, // four games, three win games ==> valid
{2, 4, 4, 2, 2, 3, 0, 1, 2, 1}, // five games, three win games ==> valid
{2, 4, 4, -1, -1, 3, 0, 0, -1, -1}, // three games, three win games ==> invalid
{2, 4, 4, -1, -1, 2, 0, 1, 1, 2}, // three games, two win games ==> valid
{2, 4, 4, -1, -1, 3, 1, 0, -1, -1}, // three games, three win games, draw allowed ==> invalid
{2, 4, -1, -1, -1, 2, 1, 1, 0, 0}, // two games, two win games, draw allowed ==> valid
{2, 4, 2, 4, -1, 3, 1, 1, 0, 0}, // four games, three win games, draw allowed ==> valid
};
for (auto combi : gameCombinations)
{
GameScoreList gsl;
QString scoreString;
for (int gameCount = 0; gameCount < MAX_NUM_GAMES; ++gameCount)
{
if (combi[gameCount] != -1)
{
auto game = GameScore::fromScore(gameScore[combi[gameCount]][0], gameScore[combi[gameCount]][1]);
CPPUNIT_ASSERT(game != nullptr);
gsl.append(*game);
scoreString += game->toString() + ",";
}
}
scoreString = scoreString.left(scoreString.length() - 1);
int numWinGames = combi[MAX_NUM_GAMES];
bool allowDraw = (combi[MAX_NUM_GAMES+1] == 1);
bool isValidMatch = (combi[MAX_NUM_GAMES+2] == 1);
// test the factory function fromGameScoreList()
auto match = MatchScore::fromGameScoreList(gsl, numWinGames, allowDraw);
if (!isValidMatch)
{
CPPUNIT_ASSERT(match == nullptr);
continue;
}
CPPUNIT_ASSERT(match != nullptr);
// test the factory function fromString()
auto match1 = MatchScore::fromString(scoreString, numWinGames, allowDraw);
if (!isValidMatch)
{
CPPUNIT_ASSERT(match1 == nullptr);
continue;
}
CPPUNIT_ASSERT(match1 != nullptr);
// test the static isValidScore() function
CPPUNIT_ASSERT(MatchScore::isValidScore(gsl, numWinGames, allowDraw) == isValidMatch);
// test the toString() function
CPPUNIT_ASSERT(match->toString() == scoreString);
CPPUNIT_ASSERT(match1->toString() == scoreString);
}
printEndMsg();
}
//----------------------------------------------------------------------------
void tstScore::testMatchScore_GetWinner_GetLoser()
{
constexpr int MAX_NUM_GAMES = 5;
printStartMsg("tstScore::testMatchScore_GetWinner_GetLoser");
int gameScore[][2] = {
{30, 29}, // 0
{29, 30}, // 1
{13, 21}, // 2
{21, 0}, // 3
{21, 18}, // 4
{23, 21}, // 5
{28, 26}, // 6
};
int gameCombinations[][MAX_NUM_GAMES + 5] = {
// game1, game2, game3, game4, game5, numWinGames, allowDraw, isValid, winner, loser
// +0 , +1 , +2 , +3 , +4
{0, 0, -1, -1, -1, 2, 0, 1, 1, 2}, // two games, player 1 wins
{2, 4, 2, 2, -1, 3, 0, 1, 2, 1}, // four games, three win games ==> valid
{2, 4, 4, 2, 2, 3, 0, 1, 2, 1}, // five games, three win games ==> valid
{2, 4, 4, -1, -1, 2, 0, 1, 1, 2}, // three games, two win games ==> valid
{2, 4, -1, -1, -1, 2, 1, 1, 0, 0}, // two games, two win games, draw allowed ==> valid
{2, 4, 2, 4, -1, 3, 1, 1, 0, 0}, // four games, three win games, draw allowed ==> valid
};
for (auto combi : gameCombinations)
{
GameScoreList gsl;
for (int gameCount = 0; gameCount < MAX_NUM_GAMES; ++gameCount)
{
if (combi[gameCount] != -1)
{
auto game = GameScore::fromScore(gameScore[combi[gameCount]][0], gameScore[combi[gameCount]][1]);
CPPUNIT_ASSERT(game != nullptr);
gsl.append(*game);
}
}
int numWinGames = combi[MAX_NUM_GAMES];
bool allowDraw = (combi[MAX_NUM_GAMES+1] == 1);
auto match = MatchScore::fromGameScoreList(gsl, numWinGames, allowDraw);
CPPUNIT_ASSERT(match != nullptr);
// test getWinner() and getLoser()
CPPUNIT_ASSERT(match->getWinner() == combi[MAX_NUM_GAMES+3]);
CPPUNIT_ASSERT(match->getLoser() == combi[MAX_NUM_GAMES+4]);
}
printEndMsg();
}
//----------------------------------------------------------------------------
void tstScore::testRandomMatchGeneration()
{
constexpr int MATCH_COUNT = 1000;
constexpr double PROBABILITY_MARGIN = 0.05;
printStartMsg("tstScore::testRandomMatchGeneration");
// a lambda as a match generator
auto matchGenerator = [](int count, int numWinGames, bool drawAllowed) {
MatchScoreList result;
for (int i=0; i < count; ++i)
{
result.append(*(MatchScore::genRandomScore(numWinGames, drawAllowed)));
}
return result;
};
// a lambda to compare an actual count with an expected count
// including a margin
auto isCountInRange = [](int expected, int actual, double margin) {
int absMargin = static_cast<int>(expected * margin);
int minCount = expected - absMargin;
int maxCount = expected + absMargin;
return ((actual <= maxCount) && (actual >= minCount));
};
// Generate matches with 2 win games and no draw
MatchScoreList msl = matchGenerator(MATCH_COUNT, 2, false);
CPPUNIT_ASSERT(msl.count() == MATCH_COUNT);
// gather some statistics
int p1Wins = 0;
int p2Wins = 0;
int gamesCount = 0;
int gamesBeyond21 = 0;
for (MatchScore ms : msl)
{
if (ms.getWinner() == 1) ++p1Wins;
if (ms.getWinner() == 2) ++p2Wins;
int cnt = ms.getNumGames();
for (int i=0; i < cnt; ++i)
{
++gamesCount;
auto gs = ms.getGame(i);
if (gs->getWinnerScore() > 21) ++gamesBeyond21;
}
CPPUNIT_ASSERT(ms.isValidScore(2, false));
}
// make sure that wins are equally distributed among players
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT / 2, p1Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT / 2, p2Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(gamesCount * 0.3, gamesBeyond21, PROBABILITY_MARGIN));
// Generate matches with 3 win games and draw
msl.clear();
msl = matchGenerator(MATCH_COUNT, 3, true);
CPPUNIT_ASSERT(msl.count() == MATCH_COUNT);
// gather some statistics
p1Wins = 0;
p2Wins = 0;
int draws = 0;
gamesCount = 0;
gamesBeyond21 = 0;
for (MatchScore ms : msl)
{
if (ms.getWinner() == 0) ++draws;
if (ms.getWinner() == 1) ++p1Wins;
if (ms.getWinner() == 2) ++p2Wins;
int cnt = ms.getNumGames();
for (int i=0; i < cnt; ++i)
{
++gamesCount;
auto gs = ms.getGame(i);
if (gs->getWinnerScore() > 21) ++gamesBeyond21;
}
if (ms.getWinner() == 0)
{
CPPUNIT_ASSERT(ms.getNumGames() == 4); // 4 = (numWinGames - 1) * 2
}
CPPUNIT_ASSERT(ms.isValidScore(3, true));
}
// make sure that wins are equally distributed among players
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.3, draws, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.35, p1Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(MATCH_COUNT * 0.35, p2Wins, PROBABILITY_MARGIN));
CPPUNIT_ASSERT(isCountInRange(gamesCount * 0.3, gamesBeyond21, PROBABILITY_MARGIN));
printEndMsg();
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
| Foorgol/QTournament | tests_deprecated/tstScore.cpp | C++ | gpl-3.0 | 11,604 |
CC = gcc
CFLAGS = -g -Wall -Werror -D_GNU_SOURCE -I../include
LDFLAGS = -ljson-c
HEADERS = ../include/json.h ../include/error.h ../include/account.h ../include/util.h
SRC = assignfee.c ../lib/json.c ../lib/account.c ../lib/error.c ../lib/util.c
assignfee: $(SRC) $(HEADERS)
$(CC) $(CFLAGS) $(LDFLAGS) $(SRC) -o$@
clean:
rm -f assignfee
.PHONY: clean
| nonnakip/nastyfans-suite | assignfee/Makefile | Makefile | gpl-3.0 | 355 |
import java.util.Scanner;
public class FeetMeters {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Number of feet: ");
float feet = keyboard.nextInt();
float foottometers = (float) .305;
System.out.println("");
System.out.print("Number of meters: ");
float meters = (float) .305 * feet;
System.out.println(meters);
}
}
| semiconductor7/java-101 | Projects_import/Project1/src/FeetMeters.java | Java | gpl-3.0 | 467 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Web service functions relating to point grades and grading.
*
* @package core_grades
* @copyright 2019 Andrew Nicols <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
declare(strict_types = 1);
namespace core_grades\grades\grader\gradingpanel\point\external;
use coding_exception;
use context;
use core_user;
use core_grades\component_gradeitem as gradeitem;
use core_grades\component_gradeitems;
use external_api;
use external_function_parameters;
use external_multiple_structure;
use external_single_structure;
use external_value;
use external_warnings;
use moodle_exception;
use required_capability_exception;
/**
* External grading panel point API
*
* @package core_grades
* @copyright 2019 Andrew Nicols <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class store extends external_api {
/**
* Describes the parameters for fetching the grading panel for a simple grade.
*
* @return external_function_parameters
* @since Moodle 3.8
*/
public static function execute_parameters(): external_function_parameters {
return new external_function_parameters ([
'component' => new external_value(
PARAM_ALPHANUMEXT,
'The name of the component',
VALUE_REQUIRED
),
'contextid' => new external_value(
PARAM_INT,
'The ID of the context being graded',
VALUE_REQUIRED
),
'itemname' => new external_value(
PARAM_ALPHANUM,
'The grade item itemname being graded',
VALUE_REQUIRED
),
'gradeduserid' => new external_value(
PARAM_INT,
'The ID of the user show',
VALUE_REQUIRED
),
'notifyuser' => new external_value(
PARAM_BOOL,
'Wheteher to notify the user or not',
VALUE_DEFAULT,
false
),
'formdata' => new external_value(
PARAM_RAW,
'The serialised form data representing the grade',
VALUE_REQUIRED
),
]);
}
/**
* Fetch the data required to build a grading panel for a simple grade.
*
* @param string $component
* @param int $contextid
* @param string $itemname
* @param int $gradeduserid
* @param bool $notifyuser
* @param string $formdata
* @return array
* @throws \dml_exception
* @throws \invalid_parameter_exception
* @throws \restricted_context_exception
* @throws coding_exception
* @throws moodle_exception
* @since Moodle 3.8
*/
public static function execute(string $component, int $contextid, string $itemname, int $gradeduserid,
bool $notifyuser, string $formdata): array {
global $USER;
[
'component' => $component,
'contextid' => $contextid,
'itemname' => $itemname,
'gradeduserid' => $gradeduserid,
'notifyuser' => $notifyuser,
'formdata' => $formdata,
] = self::validate_parameters(self::execute_parameters(), [
'component' => $component,
'contextid' => $contextid,
'itemname' => $itemname,
'gradeduserid' => $gradeduserid,
'notifyuser' => $notifyuser,
'formdata' => $formdata,
]);
// Validate the context.
$context = context::instance_by_id($contextid);
self::validate_context($context);
// Validate that the supplied itemname is a gradable item.
if (!component_gradeitems::is_valid_itemname($component, $itemname)) {
throw new coding_exception("The '{$itemname}' item is not valid for the '{$component}' component");
}
// Fetch the gradeitem instance.
$gradeitem = gradeitem::instance($component, $context, $itemname);
// Validate that this gradeitem is actually enabled.
if (!$gradeitem->is_grading_enabled()) {
throw new moodle_exception("Grading is not enabled for {$itemname} in this context");
}
// Fetch the record for the graded user.
$gradeduser = \core_user::get_user($gradeduserid);
// Require that this user can save grades.
$gradeitem->require_user_can_grade($gradeduser, $USER);
if (!$gradeitem->is_using_direct_grading()) {
throw new moodle_exception("The {$itemname} item in {$component}/{$contextid} is not configured for direct grading");
}
// Parse the serialised string into an object.
$data = [];
parse_str($formdata, $data);
// Grade.
$gradeitem->store_grade_from_formdata($gradeduser, $USER, (object) $data);
$hasgrade = $gradeitem->user_has_grade($gradeduser);
// Notify.
if ($notifyuser) {
// Send notification.
$gradeitem->send_student_notification($gradeduser, $USER);
}
// Fetch the updated grade back out.
$grade = $gradeitem->get_grade_for_user($gradeduser, $USER);
return fetch::get_fetch_data($grade, $hasgrade, 0);
}
/**
* Describes the data returned from the external function.
*
* @return external_single_structure
* @since Moodle 3.8
*/
public static function execute_returns(): external_single_structure {
return fetch::execute_returns();
}
}
| dustinbrisebois/moodle | grade/classes/grades/grader/gradingpanel/point/external/store.php | PHP | gpl-3.0 | 6,329 |
from pupa.scrape import Jurisdiction, Organization
from .bills import MNBillScraper
from .committees import MNCommitteeScraper
from .people import MNPersonScraper
from .vote_events import MNVoteScraper
from .events import MNEventScraper
from .common import url_xpath
"""
Minnesota legislative data can be found at the Office of the Revisor
of Statutes:
https://www.revisor.mn.gov/
Votes:
There are not detailed vote data for Senate votes, simply yes and no counts.
Bill pages have vote counts and links to House details, so it makes more
sense to get vote data from the bill pages.
"""
class Minnesota(Jurisdiction):
division_id = "ocd-division/country:us/state:mn"
classification = "government"
name = "Minnesota"
url = "http://state.mn.us/"
check_sessions = True
scrapers = {
"bills": MNBillScraper,
"committees": MNCommitteeScraper,
"people": MNPersonScraper,
"vote_events": MNVoteScraper,
"events": MNEventScraper,
}
parties = [{'name': 'Republican'},
{'name': 'Democratic-Farmer-Labor'}]
legislative_sessions = [
{
'_scraped_name': '86th Legislature, 2009-2010',
'classification': 'primary',
'identifier': '2009-2010',
'name': '2009-2010 Regular Session'
},
{
'_scraped_name': '86th Legislature, 2010 1st Special Session',
'classification': 'special',
'identifier': '2010 1st Special Session',
'name': '2010, 1st Special Session'
},
{
'_scraped_name': '86th Legislature, 2010 2nd Special Session',
'classification': 'special',
'identifier': '2010 2nd Special Session',
'name': '2010, 2nd Special Session'
},
{
'_scraped_name': '87th Legislature, 2011-2012',
'classification': 'primary',
'identifier': '2011-2012',
'name': '2011-2012 Regular Session'
},
{
'_scraped_name': '87th Legislature, 2011 1st Special Session',
'classification': 'special',
'identifier': '2011s1',
'name': '2011, 1st Special Session'
},
{
'_scraped_name': '87th Legislature, 2012 1st Special Session',
'classification': 'special',
'identifier': '2012s1',
'name': '2012, 1st Special Session'
},
{
'_scraped_name': '88th Legislature, 2013-2014',
'classification': 'primary',
'identifier': '2013-2014',
'name': '2013-2014 Regular Session'
},
{
'_scraped_name': '88th Legislature, 2013 1st Special Session',
'classification': 'special',
'identifier': '2013s1',
'name': '2013, 1st Special Session'
},
{
'_scraped_name': '89th Legislature, 2015-2016',
'classification': 'primary',
'identifier': '2015-2016',
'name': '2015-2016 Regular Session'
},
{
'_scraped_name': '89th Legislature, 2015 1st Special Session',
'classification': 'special',
'identifier': '2015s1',
'name': '2015, 1st Special Session'
},
{
'_scraped_name': '90th Legislature, 2017-2018',
'classification': 'primary',
'identifier': '2017-2018',
'name': '2017-2018 Regular Session'
},
]
ignored_scraped_sessions = [
'85th Legislature, 2007-2008',
'85th Legislature, 2007 1st Special Session',
'84th Legislature, 2005-2006',
'84th Legislature, 2005 1st Special Session',
'83rd Legislature, 2003-2004',
'83rd Legislature, 2003 1st Special Session',
'82nd Legislature, 2001-2002',
'82nd Legislature, 2002 1st Special Session',
'82nd Legislature, 2001 1st Special Session',
'81st Legislature, 1999-2000',
'80th Legislature, 1997-1998',
'80th Legislature, 1998 1st Special Session',
'80th Legislature, 1997 3rd Special Session',
'80th Legislature, 1997 2nd Special Session',
'80th Legislature, 1997 1st Special Session',
'79th Legislature, 1995-1996',
'79th Legislature, 1995 1st Special Session',
'89th Legislature, 2015-2016',
]
def get_organizations(self):
legis = Organization('Minnesota Legislature', classification='legislature')
upper = Organization('Minnesota Senate', classification='upper',
parent_id=legis._id)
lower = Organization('Minnesota House of Representatives',
classification='lower', parent_id=legis._id)
for n in range(1, 68):
upper.add_post(label=str(n), role='Senator',
division_id='ocd-division/country:us/state:mn/sldu:{}'.format(n))
lower.add_post(label=str(n) + 'A', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}a'.format(n))
lower.add_post(label=str(n) + 'B', role='Representative',
division_id='ocd-division/country:us/state:mn/sldl:{}b'.format(n))
yield legis
yield upper
yield lower
def get_session_list(self):
return url_xpath('https://www.revisor.mn.gov/revisor/pages/'
'search_status/status_search.php?body=House',
'//select[@name="session"]/option/text()')
| cliftonmcintosh/openstates | openstates/mn/__init__.py | Python | gpl-3.0 | 5,612 |
<?php
namespace Test\FlexiPeeHP;
use FlexiPeeHP\Nastaveni;
/**
* Generated by PHPUnit_SkeletonGenerator on 2016-04-27 at 17:32:11.
*/
class NastaveniTest extends FlexiBeeROTest
{
/**
* @var Nastaveni
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp(): void
{
$this->object = new Nastaveni();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown(): void
{
}
/**
* @covers FlexiPeeHP\Nastaveni::getFlexiData
*/
public function testGetFlexiData()
{
if ($this->object->url == 'https://demo.flexibee.eu') {
$this->markTestSkipped('Public demo site does not allow read here');
} else {
$flexidata = $this->object->getFlexiData();
$this->assertArrayHasKey(0, $flexidata);
$this->assertArrayHasKey('id', $flexidata[0]);
$filtrered = $this->object->getFlexiData(null,
key($flexidata[0])." = ".current($flexidata[0]));
$this->assertArrayHasKey(0, $filtrered);
$this->assertArrayHasKey('id', $filtrered[0]);
}
}
}
| Spoje-NET/FlexiPeeHP | testing/src/FlexiPeeHP/NastaveniTest.php | PHP | gpl-3.0 | 1,380 |
#pragma once
#include <fstream>
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include "jw.hpp"
namespace Zee {
class Report {
public:
Report(std::string title, std::string rowTitle)
: title_(title), rowTitle_(rowTitle) {
rowSize_ = rowTitle_.size();
}
void addColumn(std::string colName, std::string texName = "") {
columns_.push_back(colName);
if (!texName.empty())
columnsTex_.push_back(texName);
else
columnsTex_.push_back(colName);
columnWidth_[colName] = colName.size();
}
void addRow(std::string row) {
entries_[row] = std::map<std::string, std::string>();
if (row.size() > rowSize_) {
rowSize_ = row.size();
}
}
template <typename T>
void addResult(std::string row, std::string column, T result) {
if (entries_.find(row) == entries_.end()) {
JWLogError << "Trying to add result to non-existing row" << endLog;
return;
}
std::stringstream ss;
ss << std::fixed << std::setprecision(1) << result;
entries_[row][column] = ss.str();
entriesTex_[row][column] = ss.str();
if (ss.str().size() > columnWidth_[column]) {
columnWidth_[column] = ss.str().size();
}
}
void addResult(std::string row, std::string column, std::string result,
std::string texResult) {
addResult(row, column, result);
entriesTex_[row][column] = texResult;
}
void print() {
JWLogResult << title_ << endLog;
unsigned int lineSize = rowSize_ + 4;
for (auto col : columnWidth_) {
lineSize += col.second + 2;
}
std::string hline = "";
for (unsigned int i = 0; i < lineSize; ++i) hline.push_back('-');
auto addElement = [](int width, std::stringstream& result,
std::string entry) {
result << std::left << std::setprecision(1) << std::setw(width)
<< std::setfill(' ') << entry;
};
std::stringstream ss;
addElement(rowSize_ + 2, ss, rowTitle_);
ss << "| ";
for (auto& col : columns_) addElement(columnWidth_[col] + 2, ss, col);
JWLogInfo << hline << endLog;
JWLogInfo << ss.str() << endLog;
JWLogInfo << hline << endLog;
for (auto& rowCols : entries_) {
std::stringstream rowSs;
addElement(rowSize_ + 2, rowSs, rowCols.first);
rowSs << "| ";
for (auto& col : columns_) {
addElement(columnWidth_[col] + 2, rowSs, rowCols.second[col]);
}
JWLogInfo << rowSs.str() << endLog;
}
JWLogInfo << hline << endLog;
}
void saveToCSV();
void readFromCSV();
void saveToTex(std::string filename) {
auto replaceTex = [](std::string entry) {
std::string texEntry = entry;
auto pos = entry.find("+-");
if (pos != std::string::npos) {
texEntry =
texEntry.substr(0, pos) + "\\pm" + texEntry.substr(pos + 2);
}
pos = entry.find("%");
if (pos != std::string::npos) {
texEntry =
texEntry.substr(0, pos) + "\\%" + texEntry.substr(pos + 1);
}
return texEntry;
};
std::ofstream fout(filename);
fout << "\\begin{table}" << std::endl;
fout << "\\centering" << std::endl;
fout << "\\begin{tabular}{|l|";
for (unsigned int i = 0; i < columns_.size(); ++i) {
fout << "l";
fout << ((i < (columns_.size() - 1)) ? " " : "|}");
}
fout << std::endl << "\\hline" << std::endl;
fout << "\\textbf{" << rowTitle_ << "} & ";
for (unsigned int i = 0; i < columns_.size(); ++i) {
fout << "$" << columnsTex_[i] << "$";
fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\");
}
fout << std::endl;
fout << "\\hline" << std::endl;
for (auto& rowCols : entriesTex_) {
fout << "\\verb|" << rowCols.first << "| & ";
for (unsigned int i = 0; i < columns_.size(); ++i) {
fout << "$" << replaceTex(rowCols.second[columns_[i]]) << "$";
fout << ((i < (columns_.size() - 1)) ? " & " : "\\\\");
}
fout << std::endl;
}
fout << "\\hline" << std::endl;
fout << "\\end{tabular}" << std::endl;
;
fout << "\\caption{\\ldots}" << std::endl;
fout << "\\end{table}" << std::endl;
}
private:
std::string title_;
std::string rowTitle_;
std::map<std::string, std::map<std::string, std::string>> entries_;
std::map<std::string, std::map<std::string, std::string>> entriesTex_;
std::vector<std::string> columns_;
std::vector<std::string> columnsTex_;
std::map<std::string, unsigned int> columnWidth_;
unsigned int rowSize_;
};
} // namespace Zee
| jwbuurlage/Zee | include/util/report.hpp | C++ | gpl-3.0 | 5,111 |
package ProxyPattern;
public class GumballMachineTestDrive {
public static void main(String[] args) {
int count = 0;
if (args .length < 2) {
System.out.println("GumballMachine <name> <inventory>");
System.exit(1);
}
count = Integer.parseInt(args[1]);
GumballMachine gumballMachine = new GumballMachine(args[0], count);
GumballMonitor monitor = new GumballMonitor(gumballMachine);
monitor.report();
}
}
| ohgood/Head-First-Design-Patterns | ProxyPattern/GumballMachineTestDrive.java | Java | gpl-3.0 | 425 |
<?php
/**
* OpenSKOS
*
* LICENSE
*
* This source file is subject to the GPLv3 license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.gnu.org/licenses/gpl-3.0.txt
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category OpenSKOS
* @package OpenSKOS
* @copyright Copyright (c) 2011 Pictura Database Publishing. (http://www.pictura-dp.nl)
* @author Mark Lindeman
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
*/
class OpenSKOS_Solr_Document implements Countable, ArrayAccess, Iterator
{
protected $fieldnames = array();
protected $data = array();
protected $position = 0;
public function __set($fieldname, $value)
{
//this differs from self::offsetSet:
// - if a field has been set before, make this field multiValued
$offsetExists = $this->offsetExists($fieldname);
$value = !is_array($value) ? array($value) : $value;
if (!$offsetExists) {
$this->fieldnames[] = $fieldname;
$this->data[$fieldname] = $value;
} else {
if (is_array($this->data[$fieldname])) {
$this->data[$fieldname] = array_merge($this->data[$fieldname], $value);
} else {
$this->data[$fieldname] = array_merge(array($this->data[$fieldname]), $value);
}
}
}
public function offsetSet($fieldname, $value) {
$newField = false;
if (!$this->offsetExists($fieldname)) {
$this->fieldnames[] = $fieldname;
$newField = true;
}
if (!is_array($value)) {
if (false === $newField) {
$this->data[$fieldname][] = $value;
} else {
$this->data[$fieldname] = array($value);
}
} else {
if (false === $newField) {
$this->data[$fieldname] = $this->data[$fieldname] + $value;
} else {
$this->data[$fieldname] = $value;
}
}
}
public function offsetExists($fieldname) {
return in_array($fieldname, $this->fieldnames);
}
public function offsetUnset($fieldname) {
if (!$this->offsetExists($fieldname)) {
trigger_error('Undefined index: '.$fieldname, E_USER_NOTICE);
return;
}
unset ( $this->data[$fieldname]);
$ix = array_search($fieldname, $this->fieldnames);
unset($this->fieldnames[$ix]);
$fieldnames = array();
foreach ($this->fieldnames as $fieldname) $fieldnames[] = $fieldname;
$this->fieldnames = $fieldnames;
$this->rewind();
}
public function offsetGet($fieldname) {
return $this->offsetExists($fieldname) ? $this->data [$fieldname] : null;
}
public function count()
{
return count($this->fieldnames);
}
public function rewind() {
$this->position = 0;
}
public function current() {
return $this->data[$this->fieldnames[$this->position]];
}
public function key() {
return $this->fieldnames[$this->position];
}
public function next() {
++$this->position;
}
public function valid() {
return isset($this->data[$this->fieldnames[$this->position]]);
}
public function toArray()
{
return $this->data;
}
/**
* @return OpenSKOS_Solr
*/
protected function solr()
{
return Zend_Registry::get('OpenSKOS_Solr');
}
public function save($commit = null)
{
$this->solr()->add(new OpenSKOS_Solr_Documents($this), $commit);
return $this;
}
/**
* Registers the notation of the document in the database, or generates one if the document does not have notation.
*
* @return OpenSKOS_Solr
*/
public function registerOrGenerateNotation()
{
if ((isset($this->data['class']) && $this->data['class'] == 'Concept')
|| (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept')) {
$currentNotation = '';
if (isset($this->data['notation']) && isset($this->data['notation'][0])) {
$currentNotation = $this->data['notation'][0];
}
if (empty($currentNotation)) {
$this->fieldnames[] = 'notation';
$this->data['notation'] = array(OpenSKOS_Db_Table_Notations::getNext());
// Adds the notation to the xml. At the end just before </rdf:Description>
$closingTag = '</rdf:Description>';
$notationTag = '<skos:notation>' . $this->data['notation'][0] . '</skos:notation>';
$xml = $this->data['xml'];
$xml = str_replace($closingTag, $notationTag . $closingTag, $xml);
$this->data['xml'] = $xml;
} else {
if ( ! OpenSKOS_Db_Table_Notations::isRegistered($currentNotation)) {
// If we do not have the notation registered - register it.
OpenSKOS_Db_Table_Notations::register($currentNotation);
}
}
}
return $this;
}
/**
* Generates uri if it can. Alters the document to put it in, also alters the xml to put rdf:about
* @param OpenSKOS_Db_Table_Row_Collection $collection From where to get the basic uri.
* @throws OpenSKOS_Rdf_Parser_Exception
*/
public function autoGenerateUri(OpenSKOS_Db_Table_Row_Collection $collection)
{
if (!((isset($this->data['class']) && $this->data['class'] == 'Concept')
|| (isset($this->data['class'][0]) && $this->data['class'][0] == 'Concept'))) {
throw new OpenSKOS_Rdf_Parser_Exception(
'Auto generate uri is for concepts only. Not working for concept schemas.'
);
}
if ($collection === null) {
throw new OpenSKOS_Rdf_Parser_Exception(
'Auto generate uri is set to true, but collection is not provided.'
);
}
$baseUri = $collection->getConceptsBaseUri();
if (empty($baseUri)) {
throw new OpenSKOS_Rdf_Parser_Exception(
'Auto generate uri is set to true, but collection is not provided.'
);
}
if (!preg_match('/\/$/', $baseUri) && !preg_match('/=$/', $baseUri)) {
$baseUri .= '/';
}
$this->registerOrGenerateNotation();
$uri = $baseUri . $this->data['notation'][0];
// Write in the xml.
if (strpos($this->data['xml'][0], 'rdf:about') !== false) {
throw new OpenSKOS_Rdf_Parser_Exception(
'Can not auto generate uri if rdf about is set.'
);
}
$this->data['xml'] = str_replace(
'<rdf:Description',
'<rdf:Description rdf:about="' . $uri . '"',
$this->data['xml']
);
$this->uri = $uri;
}
/**
*
* @throws OpenSKOS_Rdf_Parser_Exception
*/
public function updateStatusInGeneratedXml()
{
if (isset($this->data['status']) && isset($this->data['status'][0])) {
$statusTag = '<openskos:status>' . $this->data['status'][0] . '</openskos:status>';
if (strpos($this->data['xml'][0], 'openskos:status') === false) {
// Adds the status to the xml. At the end just before </rdf:Description>
$closingTag = '</rdf:Description>';
$xml = $this->data['xml'];
$xml = str_replace($closingTag, $statusTag . $closingTag, $xml);
$this->data['xml'] = $xml;
} else {
$xml = $this->data['xml'];
$xml = preg_replace('/<openskos:status>.*<\/openskos:status>/i', $statusTag, $xml);
$this->data['xml'] = $xml;
}
}
}
public function __toString()
{
$doc = new DOMDocument();
$doc->loadXML('<doc/>');
foreach ($this->fieldnames as $fieldname) {
foreach ($this->data[$fieldname] as $value) {
$node = $doc->documentElement->appendChild($doc->createElement('field'));
$htmlSafeValue = htmlspecialchars($value);
if ($htmlSafeValue == $value) {
$node->appendChild($doc->createTextNode($htmlSafeValue));
} else {
$node->appendChild($doc->createCDataSection($value));
}
$node->setAttribute('name', $fieldname);
}
}
return $doc->saveXml($doc->documentElement);
}
} | olhsha/OpenSKOS2tempMeertens | library/OpenSKOS/Solr/Document.php | PHP | gpl-3.0 | 8,418 |
#ifndef SQLCONNECTDIALOG_H
#define SQLCONNECTDIALOG_H
#include <QDialog>
#include <QtSql>
namespace Ui {
class SQLConnectDialog;
}
class SQLConnectDialog : public QDialog
{
Q_OBJECT
public:
explicit SQLConnectDialog(QWidget *parent = 0);
~SQLConnectDialog();
QSqlDatabase connect(QSqlDatabase db);
private slots:
void on_ConnectButton_clicked();
private:
Ui::SQLConnectDialog *ui;
QSqlDatabase tmp;
};
#endif // SQLCONNECTDIALOG_H
| kin63camapa/convertor | sqlconnectdialog.h | C | gpl-3.0 | 466 |
// This code is part of the CPCC-NG project.
//
// Copyright (c) 2009-2016 Clemens Krainer <[email protected]>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
package cpcc.demo.setup.builder;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.tuple.Pair;
import cpcc.core.entities.SensorDefinition;
import cpcc.core.entities.SensorType;
import cpcc.core.entities.SensorVisibility;
import cpcc.core.entities.TopicCategory;
/**
* Sensor Constants implementation.
*/
public final class SensorConstants
{
private static final String SENSOR_MSGS_NAV_SAT_FIX = "sensor_msgs/NavSatFix";
private static final String SENSOR_MSGS_IMAGE = "sensor_msgs/Image";
private static final String STD_MSGS_FLOAT32 = "std_msgs/Float32";
private static final Date now = new Date();
private static final SensorDefinition[] SENSOR_DEFINITIONS = {
new SensorDefinitionBuilder()
.setId(1)
.setDescription("Altimeter")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.ALTIMETER)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(2)
.setDescription("Area of Operations")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.AREA_OF_OPERATIONS)
.setVisibility(SensorVisibility.PRIVILEGED_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(3)
.setDescription("Barometer")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.BAROMETER)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(4)
.setDescription("Battery")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.BATTERY)
.setVisibility(SensorVisibility.PRIVILEGED_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(5)
.setDescription("Belly Mounted Camera 640x480")
.setLastUpdate(now)
.setMessageType(SENSOR_MSGS_IMAGE)
.setParameters("width=640 height=480 yaw=0 down=1.571 alignment=''north''")
.setType(SensorType.CAMERA)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
// new SensorDefinitionBuilder()
// .setId(6)
// .setDescription("FPV Camera 640x480")
// .setLastUpdate(now)
// .setMessageType("sensor_msgs/Image")
// .setParameters("width=640 height=480 yaw=0 down=0 alignment=''heading''")
// .setType(SensorType.CAMERA)
// .setVisibility(SensorVisibility.ALL_VV)
// .setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(7)
.setDescription("CO2")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.CO2)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(9)
.setDescription("GPS")
.setLastUpdate(now)
.setMessageType(SENSOR_MSGS_NAV_SAT_FIX)
.setParameters(null)
.setType(SensorType.GPS)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(10)
.setDescription("Hardware")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.HARDWARE)
.setVisibility(SensorVisibility.PRIVILEGED_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(11)
.setDescription("NOx")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.NOX)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build(),
new SensorDefinitionBuilder()
.setId(12)
.setDescription("Thermometer")
.setLastUpdate(now)
.setMessageType(STD_MSGS_FLOAT32)
.setParameters(null)
.setType(SensorType.THERMOMETER)
.setVisibility(SensorVisibility.ALL_VV)
.setDeleted(false).build()
};
public static final Map<TopicCategory, SensorType> TOPIC_SENSOR_MAP = Collections.unmodifiableMap(Stream
.of(Pair.of(TopicCategory.ALTITUDE_OVER_GROUND, SensorType.ALTIMETER),
Pair.of(TopicCategory.CAMERA, SensorType.CAMERA),
Pair.of(TopicCategory.CAMERA_INFO, SensorType.CAMERA),
Pair.of(TopicCategory.GPS_POSITION_PROVIDER, SensorType.GPS))
.collect(Collectors.toMap(Pair::getLeft, Pair::getRight)));
private SensorConstants()
{
// Intentionally empty.
}
/**
* @param type the required sensor types.
* @return all sensor definitions specified in type.
*/
public static List<SensorDefinition> byType(SensorType... type)
{
Set<SensorType> types = Stream.of(type).collect(Collectors.toSet());
return Stream.of(SENSOR_DEFINITIONS).filter(x -> types.contains(x.getType())).collect(Collectors.toList());
}
/**
* @return all sensor definitions.
*/
public static List<SensorDefinition> all()
{
return Arrays.asList(SENSOR_DEFINITIONS);
}
}
| cksystemsgroup/cpcc | cpcc-demo/src/main/java/cpcc/demo/setup/builder/SensorConstants.java | Java | gpl-3.0 | 6,792 |
<?php
namespace App\Console\Commands;
use App\App;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Imperium\File\File;
class Venus extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:secure';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Configure app';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$db = database_path('venus');
if (!File::exist($db))
{
if (File::create($db))
{
File::copy('.env.example', '.env');
Artisan::call('key:generate');
}
}
return App::cryptEnv();
}
}
| fumseck/aphrodite | app/Console/Commands/Venus.php | PHP | gpl-3.0 | 1,016 |
/*
* Decompiled with CFR 0_114.
*
* Could not load the following classes:
* com.stimulsoft.base.drawing.StiBrush
* com.stimulsoft.base.drawing.StiColor
* com.stimulsoft.base.drawing.StiSolidBrush
* com.stimulsoft.base.drawing.enums.StiPenStyle
* com.stimulsoft.base.serializing.annotations.StiDefaulValue
* com.stimulsoft.base.serializing.annotations.StiSerializable
*/
package com.stimulsoft.report.chart.view.series.radar;
import com.stimulsoft.base.drawing.StiBrush;
import com.stimulsoft.base.drawing.StiColor;
import com.stimulsoft.base.drawing.StiSolidBrush;
import com.stimulsoft.base.drawing.enums.StiPenStyle;
import com.stimulsoft.base.serializing.annotations.StiDefaulValue;
import com.stimulsoft.base.serializing.annotations.StiSerializable;
import com.stimulsoft.report.chart.core.series.StiSeriesCoreXF;
import com.stimulsoft.report.chart.core.series.radar.StiRadarAreaSeriesCoreXF;
import com.stimulsoft.report.chart.interfaces.series.IStiSeries;
import com.stimulsoft.report.chart.interfaces.series.radar.IStiRadarAreaSeries;
import com.stimulsoft.report.chart.view.areas.radar.StiRadarAreaArea;
import com.stimulsoft.report.chart.view.series.radar.StiRadarSeries;
public class StiRadarAreaSeries
extends StiRadarSeries
implements IStiRadarAreaSeries {
private StiColor lineColor = StiColor.Black;
private StiPenStyle lineStyle = StiPenStyle.Solid;
private boolean lighting = true;
private float lineWidth = 2.0f;
private StiBrush brush = new StiSolidBrush(StiColor.Gainsboro);
@StiSerializable
public StiColor getLineColor() {
return this.lineColor;
}
public void setLineColor(StiColor stiColor) {
this.lineColor = stiColor;
}
@StiDefaulValue(value="Solid")
@StiSerializable
public StiPenStyle getLineStyle() {
return this.lineStyle;
}
public void setLineStyle(StiPenStyle stiPenStyle) {
this.lineStyle = stiPenStyle;
}
@StiDefaulValue(value="true")
@StiSerializable
public boolean getLighting() {
return this.lighting;
}
public void setLighting(boolean bl) {
this.lighting = bl;
}
@StiDefaulValue(value="2.0")
@StiSerializable
public float getLineWidth() {
return this.lineWidth;
}
public void setLineWidth(float f) {
if (f > 0.0f) {
this.lineWidth = f;
}
}
@StiSerializable(shortName="bh")
public final StiBrush getBrush() {
return this.brush;
}
public final void setBrush(StiBrush stiBrush) {
this.brush = stiBrush;
}
public Class GetDefaultAreaType() {
return StiRadarAreaArea.class;
}
public StiRadarAreaSeries() {
this.setCore(new StiRadarAreaSeriesCoreXF(this));
}
}
| talek69/curso | stimulsoft/src/com/stimulsoft/report/chart/view/series/radar/StiRadarAreaSeries.java | Java | gpl-3.0 | 2,787 |
/*
Copyright (C) 2011-2017 Michael Goffioul
This file is part of Octave.
Octave is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
Octave is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with Octave; see the file COPYING. If not, see
<http://www.gnu.org/licenses/>.
*/
#if ! defined (octave_PushButtonControl_h)
#define octave_PushButtonControl_h 1
#include "ButtonControl.h"
class QPushButton;
namespace QtHandles
{
class PushButtonControl : public ButtonControl
{
public:
PushButtonControl (const graphics_object& go, QPushButton* btn);
~PushButtonControl (void);
static PushButtonControl* create (const graphics_object& go);
protected:
void update (int pId);
};
}
#endif
| xmjiao/octave-debian | libgui/graphics/PushButtonControl.h | C | gpl-3.0 | 1,136 |
package com.base.engine.math;
public class Vector2f
{
private float x, y;
public Vector2f(float x, float y)
{
this.x = x;
this.y = y;
}
public Vector2f normalized()
{
float len = length();
float x_ = x / len;
float y_ = y / len;
return new Vector2f(x_, y_);
}
public float length()
{
return (float)Math.sqrt(x * x + y * y);
}
public Vector2f add(Vector2f r)
{
return new Vector2f(x + r.getX(), y + r.getY());
}
public Vector2f add(float r)
{
return new Vector2f(x + r, y + r);
}
public Vector2f sub(Vector2f r)
{
return new Vector2f(x - r.getX(), y - r.getY());
}
public Vector2f sub(float r)
{
return new Vector2f(x - r, y - r);
}
public Vector2f mul(Vector2f r)
{
return new Vector2f(x * r.getX(), y * r.getY());
}
public Vector2f mul(float r)
{
return new Vector2f(x * r, y * r);
}
public Vector2f div(Vector2f r)
{
return new Vector2f(x / r.getX(), y / r.getY());
}
public Vector2f div(float r)
{
return new Vector2f(x / r, y / r);
}
public Vector2f abs()
{
return new Vector2f(Math.abs(x), Math.abs(y));
}
@Override
public String toString()
{
return "(" + x + ", " + y + ")";
}
public float getX()
{
return this.x;
}
public void setX(float x)
{
this.x = x;
}
public float getY()
{
return this.y;
}
public void setY(float y)
{
this.y = y;
}
}
| mattparizeau/2DGameEngine | ge_common/com/base/engine/math/Vector2f.java | Java | gpl-3.0 | 1,731 |
/*
* Twidere - Twitter client for Android
*
* Copyright (C) 2012 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mariotaku.twidere.util;
import java.io.File;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
public final class EnvironmentAccessor {
public static File getExternalCacheDir(final Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO)
return GetExternalCacheDirAccessorFroyo.getExternalCacheDir(context);
final File ext_storage_dir = Environment.getExternalStorageDirectory();
if (ext_storage_dir != null && ext_storage_dir.isDirectory()) {
final String ext_cache_path = ext_storage_dir.getAbsolutePath() + "/Android/data/"
+ context.getPackageName() + "/cache/";
final File ext_cache_dir = new File(ext_cache_path);
if (ext_cache_dir.isDirectory() || ext_cache_dir.mkdirs()) return ext_cache_dir;
}
return null;
}
@TargetApi(Build.VERSION_CODES.FROYO)
private static class GetExternalCacheDirAccessorFroyo {
@TargetApi(Build.VERSION_CODES.FROYO)
private static File getExternalCacheDir(final Context context) {
return context.getExternalCacheDir();
}
}
}
| gen4young/twidere | src/org/mariotaku/twidere/util/EnvironmentAccessor.java | Java | gpl-3.0 | 1,877 |
#include "toString.h"
vector<string> splitString(string s, char c) {
stringstream ss(s);
string token;
vector<string> res;
while (std::getline(ss, token, c)) res.push_back(token);
return res;
}
string toString(string s) { return s; }
string toString(bool b) { stringstream ss; ss << b; return ss.str(); }
string toString(int i) { stringstream ss; ss << i; return ss.str(); }
string toString(size_t i) { stringstream ss; ss << i; return ss.str(); }
string toString(unsigned int i) { stringstream ss; ss << i; return ss.str(); }
string toString(float f) { stringstream ss; ss << f; return ss.str(); }
string toString(double f) { stringstream ss; ss << f; return ss.str(); }
string toString(OSG::Vec2f v) {
stringstream ss;
ss << v[0] << " " << v[1];
return ss.str();
}
string toString(OSG::Pnt3f v) { return toString(OSG::Vec3f(v)); }
string toString(OSG::Vec3f v) {
stringstream ss;
ss << v[0] << " " << v[1] << " " << v[2];
return ss.str();
}
string toString(OSG::Vec4f v) {
stringstream ss;
ss << v[0] << " " << v[1] << " " << v[2] << " " << v[3];
return ss.str();
}
string toString(OSG::Vec3i v) {
stringstream ss;
ss << v[0] << " " << v[1] << " " << v[2];
return ss.str();
}
bool toBool(string s) {
stringstream ss;
ss << s;
bool b;
ss >> b;
return b;
}
int toInt(string s) {
stringstream ss;
ss << s;
int i;
ss >> i;
return i;
}
float toFloat(string s) {
stringstream ss;
ss << s;
float i;
ss >> i;
return i;
}
OSG::Vec2f toVec2f(string s) {
OSG::Vec2f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
return v;
}
OSG::Vec3f toVec3f(string s) {
OSG::Vec3f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
return v;
}
OSG::Vec4f toVec4f(string s) {
OSG::Vec4f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
ss >> v[3];
return v;
}
OSG::Pnt3f toPnt3f(string s) {
OSG::Pnt3f v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
return v;
}
OSG::Vec3i toVec3i(string s) {
OSG::Vec3i v;
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
return v;
}
void toValue(string s, string& s2) {
s2 = s;
}
void toValue(string s, bool& b) {
stringstream ss(s);
ss >> b;
}
void toValue(string s, int& i) {
stringstream ss(s);
ss >> i;
}
void toValue(string s, float& f) {
stringstream ss(s);
ss >> f;
}
void toValue(string s, OSG::Vec2f& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
}
void toValue(string s, OSG::Vec3f& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
}
void toValue(string s, OSG::Vec4f& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
ss >> v[3];
}
void toValue(string s, OSG::Vec3i& v) {
stringstream ss(s);
ss >> v[0];
ss >> v[1];
ss >> v[2];
}
| infobeisel/polyvr | src/core/utils/toString.cpp | C++ | gpl-3.0 | 2,978 |
<!DOCTYPE html><html><head><link rel="canonical" href="http://raph.es/blog/2011/06/mapping-network-drives-for-teamcity-build-agents/"/><meta http-equiv="content-type" content="text/html; charset=utf-8" /><meta http-equiv="refresh" content="0;url=http://raph.es/blog/2011/06/mapping-network-drives-for-teamcity-build-agents/" /></head></html> | galaktor/galaktor.github.io | 2011/06/mapping-network-drives-for-teamcity.html | HTML | gpl-3.0 | 341 |
<?php
class NivelSni extends AppModel {
var $name = 'NivelSni';
var $displayField = 'nombre';
var $validate = array(
'nombre' => array(
'minlength' => array(
'rule' => array('minlength', 1),
'message' => 'Valor muy pequeño.',
'allowEmpty' => false
),
),
'descripcion' => array(
'minlength' => array(
'rule' => array('minlength',1),
'message' => 'Ingrese una descripción mas detallada.',
'allowEmpty' => false
),
),
);
var $hasMany = array(
'DatosProfesionales' => array(
'className' => 'DatosProfesionales',
'foreignKey' => 'nivel_sni_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
| esteban-uo/-Grafo-Red-Social-de-Investigadores | app/models/nivel_sni.php | PHP | gpl-3.0 | 803 |
'''
Copyright 2015
This file is part of Orbach.
Orbach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Orbach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Orbach. If not, see <http://www.gnu.org/licenses/>.
'''
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from orbach.core import views
router = DefaultRouter()
router.register(r'galleries', views.GalleryViewSet)
router.register(r'image_files', views.ImageFileViewSet)
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
| awood/orbach | orbach/core/urls.py | Python | gpl-3.0 | 1,005 |
public class Silver extends Piece {
public Silver(int owner) {
super(owner);
setSymbol("S");
setType("Silver");
}
public boolean canMove(Square from, Square to, Board b) {
if(promoted) {
//Gold movement code
if((Math.abs(from.getR() - to.getR()) <= 1 &&
(Math.abs(from.getC() - to.getC()) <= 1))) {
if(owner == 1) {
//If Piece is moving backwards check for diagonal
if(from.getR() - to.getR() == 1) {
if(from.getC() != to.getC()) {
return false;
}
}
} else if(owner == 2) {
//If Piece is moving backwards check for diagonal
if(from.getR() - to.getR() == -1) {
if(from.getC() != to.getC()) {
return false;
}
}
}
if(to.getPiece() != null) {
if(from.getPiece().getOwner() == to.getPiece().getOwner()) {
return false;
}
}
return true;
}
return false;
}
if((Math.abs(from.getR() - to.getR()) <= 1 &&
(Math.abs(from.getC() - to.getC()) <= 1))) {
if(owner == 1) {
//If Piece is moving backwards p1
if(from.getR() - to.getR() == 1) {
if(from.getC() == to.getC()) {
return false;
}
}
} else if(owner == 2) {
//If Piece is moving backwards p2
if(from.getR() - to.getR() == -1) {
if(from.getC() == to.getC()) {
return false;
}
}
}
//moving sideways
if(from.getR() == to.getR()) {
return false;
}
if(to.getPiece() != null) {
if(from.getPiece().getOwner() == to.getPiece().getOwner()) {
return false;
}
}
return true;
}
return false;
}
}
| dma-gh/Shogi-Game | src/Silver.java | Java | gpl-3.0 | 1,589 |
/*
* This file is part of the OTHERobjects Content Management System.
*
* Copyright 2007-2009 OTHER works Limited.
*
* OTHERobjects is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OTHERobjects is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OTHERobjects. If not, see <http://www.gnu.org/licenses/>.
*/
package org.otherobjects.cms.tools;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import javax.annotation.Resource;
import org.otherobjects.cms.model.User;
import org.otherobjects.cms.model.UserDao;
import org.otherobjects.cms.views.Tool;
import org.springframework.stereotype.Component;
/**
* Generates URL to Gravatar images based on user email address.
*
* <p>For more info on Gravatars see <a href="http://en.gravatar.com/">http://en.gravatar.com/</a>. Details of
* the algorithm are available at <a href="http://en.gravatar.com/site/implement/url">http://en.gravatar.com/site/implement/url</a>.
*
* @author rich
*/
@Component
@Tool
public class GravatarTool
{
private static final String GRAVATAR_SERVER = "http://www.gravatar.com/avatar/";
private static final String GRAVATAR_SECURE_SERVER = "https://secure.gravatar.com/avatar/";
@Resource
protected UserDao userDao;
/**
* Generates url of Gravatar image for provided user. Username must be valid.
*
* @param username the username for the required user
* @param size width in pixels of required image
* @return the url to the image
*/
public String getUrl(String username, int size, boolean ssl)
{
return getUrl(username, size, null, ssl);
}
/**
* Generates url of Gravatar image for provided user. Username must be valid.
* If the user does not have a Gravatar image then the provided placeholder image url
* is returned.
*
* @param username the username for the required user
* @param size width in pixels of required image
* @param placeholder the url of image to use when no Gravatar is available
* @return the url to the image
*/
public String getUrl(String username, int size, String placeholder, boolean ssl)
{
User user = (User) userDao.loadUserByUsername(username);
return getUrlForEmail(user.getEmail(), size, null, ssl);
}
/**
* Generates url of Gravatar image for provided user. The email address does not
* need to be for a user in OTHERobjects.
*
* If the user does not have a Gravatar image then the provided placeholder image url
* is returned (provide a null placeholder to use the default Gravatar one).
*
* @param email the email address for the required user
* @param size width in pixels of required image
* @param placeholder the url of image to use when no Gravatar is available
* @param ssl whether or not to get an image from a secure Gravatar url
* @return the url to the image
*/
public String getUrlForEmail(String email, int size, String placeholder, boolean ssl)
{
StringBuffer url = new StringBuffer(ssl ? GRAVATAR_SECURE_SERVER : GRAVATAR_SERVER);
// Add image name
url.append(md5Hex(email));
url.append(".jpg");
// Add options
StringBuffer options = new StringBuffer();
if (size > 0)
{
options.append("s=" + size);
}
try
{
if (placeholder != null)
{
if (options.length() > 0)
{
options.append("&");
}
options.append("d=" + URLEncoder.encode(placeholder, "UTF-8"));
}
}
catch (UnsupportedEncodingException e)
{
// Ignore -- UTF-8 must be supported
}
if (options.length() > 0)
{
url.append("?" + options.toString());
}
return url.toString();
}
public String getUrlForEmail(String email, int size, String placeholder)
{
return getUrlForEmail(email, size, placeholder, false);
}
private static String hex(byte[] array)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i)
{
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
}
private static String md5Hex(String message)
{
try
{
MessageDigest md = MessageDigest.getInstance("MD5");
return hex(md.digest(message.getBytes("CP1252")));
}
catch (Exception e)
{
// Ignore
}
return null;
}
}
| 0x006EA1E5/oo6 | src/main/java/org/otherobjects/cms/tools/GravatarTool.java | Java | gpl-3.0 | 5,206 |
package com.baobaotao.transaction.nestcall;
public class BaseService {
}
| puliuyinyi/test | src/main/java/com/baobaotao/transaction/nestcall/BaseService.java | Java | gpl-3.0 | 75 |
import kivy
kivy.require('1.9.1')
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.metrics import dp
from kivy.app import Builder
from kivy.properties import StringProperty, ObjectProperty
from kivy.clock import Clock
from kivy.metrics import sp
from kivy.metrics import dp
from iconbutton import IconButton
__all__ = ('alertPopup, confirmPopup, okPopup, editor_popup')
Builder.load_string('''
<ConfirmPopup>:
cols:1
Label:
text: root.text
GridLayout:
cols: 2
size_hint_y: None
height: '44sp'
spacing: '5sp'
IconButton:
text: u'\uf00c'
on_press: root.dispatch('on_answer', True)
IconButton:
text: u'\uf00d'
color: ColorScheme.get_primary()
on_release: root.dispatch('on_answer', False)
<OkPopup>:
cols:1
Label:
text: root.text
GridLayout:
cols: 2
size_hint_y: None
height: '44sp'
spacing: '5sp'
IconButton:
text: u'\uf00c'
on_press: root.dispatch('on_answer', True)
<EditorPopup>:
id: editor_popup
cols:1
BoxLayout:
id: content
GridLayout:
id: buttons
cols: 2
size_hint_y: None
height: '44sp'
spacing: '5sp'
IconButton:
text: u'\uf00c'
on_press: root.dispatch('on_answer', True)
IconButton:
text: u'\uf00d'
color: ColorScheme.get_primary()
on_release: root.dispatch('on_answer', False)
''')
def alertPopup(title, msg):
popup = Popup(title = title,
content=Label(text = msg),
size_hint=(None, None), size=(dp(600), dp(200)))
popup.open()
def confirmPopup(title, msg, answerCallback):
content = ConfirmPopup(text=msg)
content.bind(on_answer=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(None, None),
size=(dp(600),dp(200)),
auto_dismiss= False)
popup.open()
return popup
class ConfirmPopup(GridLayout):
text = StringProperty()
def __init__(self,**kwargs):
self.register_event_type('on_answer')
super(ConfirmPopup,self).__init__(**kwargs)
def on_answer(self, *args):
pass
def editor_popup(title, content, answerCallback):
content = EditorPopup(content=content)
content.bind(on_answer=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(0.7, 0.8),
auto_dismiss= False,
title_size=sp(18))
popup.open()
return popup
class EditorPopup(GridLayout):
content = ObjectProperty(None)
def __init__(self,**kwargs):
self.register_event_type('on_answer')
super(EditorPopup,self).__init__(**kwargs)
def on_content(self, instance, value):
Clock.schedule_once(lambda dt: self.ids.content.add_widget(value))
def on_answer(self, *args):
pass
def okPopup(title, msg, answerCallback):
content = OkPopup(text=msg)
content.bind(on_ok=answerCallback)
popup = Popup(title=title,
content=content,
size_hint=(None, None),
size=(dp(600),dp(200)),
auto_dismiss= False)
popup.open()
return popup
class OkPopup(GridLayout):
text = StringProperty()
def __init__(self,**kwargs):
self.register_event_type('on_ok')
super(OkPopup,self).__init__(**kwargs)
def on_ok(self, *args):
pass | ddimensia/RaceCapture_App | autosportlabs/racecapture/views/util/alertview.py | Python | gpl-3.0 | 3,843 |
class CheckBase(object):
"""
Base class for checks.
"""
hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A list of strings."""
def execute(self, hook):
"""
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
"""
pass
| lddubeau/glerbl | glerbl/check/__init__.py | Python | gpl-3.0 | 461 |
<?php
/* Copyright (C) 2003-2006 Rodolphe Quiedeville <[email protected]>
* Copyright (C) 2004-2011 Laurent Destailleur <[email protected]>
* Copyright (C) 2005-2009 Regis Houssin <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* \file htdocs/product/stock/index.php
* \ingroup stock
* \brief Home page of stock area
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
$langs->load("stocks");
// Security check
$result=restrictedArea($user,'stock');
/*
* View
*/
$help_url='EN:Module_Stocks_En|FR:Module_Stock|ES:Módulo_Stocks';
llxHeader("",$langs->trans("Stocks"),$help_url);
print_fiche_titre($langs->trans("StocksArea"));
//print '<table border="0" width="100%" class="notopnoleftnoright">';
//print '<tr><td valign="top" width="30%" class="notopnoleft">';
print '<div class="fichecenter"><div class="fichethirdleft">';
/*
* Zone recherche entrepot
*/
print '<form method="post" action="'.DOL_URL_ROOT.'/product/stock/liste.php">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<table class="noborder nohover" width="100%">';
print "<tr class=\"liste_titre\">";
print '<td colspan="3">'.$langs->trans("Search").'</td></tr>';
print "<tr ".$bc[false]."><td>";
print $langs->trans("Ref").':</td><td><input class="flat" type="text" size="18" name="sref"></td><td rowspan="2"><input type="submit" value="'.$langs->trans("Search").'" class="button"></td></tr>';
print "<tr ".$bc[false]."><td>".$langs->trans("Other").':</td><td><input type="text" name="sall" class="flat" size="18"></td>';
print "</table></form><br>";
$sql = "SELECT e.label, e.rowid, e.statut";
$sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e";
$sql.= " WHERE e.statut in (0,1)";
$sql.= " AND e.entity = ".$conf->entity;
$sql.= $db->order('e.statut','DESC');
$sql.= $db->plimit(15, 0);
$result = $db->query($sql);
if ($result)
{
$num = $db->num_rows($result);
$i = 0;
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Warehouses").'</td></tr>';
if ($num)
{
$entrepot=new Entrepot($db);
$var=True;
while ($i < $num)
{
$objp = $db->fetch_object($result);
$var=!$var;
print "<tr $bc[$var]>";
print "<td><a href=\"fiche.php?id=$objp->rowid\">".img_object($langs->trans("ShowStock"),"stock")." ".$objp->label."</a></td>\n";
print '<td align="right">'.$entrepot->LibStatut($objp->statut,5).'</td>';
print "</tr>\n";
$i++;
}
$db->free($result);
}
print "</table>";
}
else
{
dol_print_error($db);
}
//print '</td><td valign="top" width="70%" class="notopnoleftnoright">';
print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
// Last movements
$max=10;
$sql = "SELECT p.rowid, p.label as produit,";
$sql.= " e.label as stock, e.rowid as entrepot_id,";
$sql.= " m.value, m.datem";
$sql.= " FROM ".MAIN_DB_PREFIX."entrepot as e";
$sql.= ", ".MAIN_DB_PREFIX."stock_mouvement as m";
$sql.= ", ".MAIN_DB_PREFIX."product as p";
$sql.= " WHERE m.fk_product = p.rowid";
$sql.= " AND m.fk_entrepot = e.rowid";
$sql.= " AND e.entity = ".$conf->entity;
if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) $sql.= " AND p.fk_product_type = 0";
$sql.= $db->order("datem","DESC");
$sql.= $db->plimit($max,0);
dol_syslog("Index:list stock movements sql=".$sql, LOG_DEBUG);
$resql = $db->query($sql);
if ($resql)
{
$num = $db->num_rows($resql);
print '<table class="noborder" width="100%">';
print "<tr class=\"liste_titre\">";
print '<td>'.$langs->trans("LastMovements",min($num,$max)).'</td>';
print '<td>'.$langs->trans("Product").'</td>';
print '<td>'.$langs->trans("Warehouse").'</td>';
print '<td align="right"><a href="'.DOL_URL_ROOT.'/product/stock/mouvement.php">'.$langs->trans("FullList").'</a></td>';
print "</tr>\n";
$var=True;
$i=0;
while ($i < min($num,$max))
{
$objp = $db->fetch_object($resql);
$var=!$var;
print "<tr $bc[$var]>";
print '<td>'.dol_print_date($db->jdate($objp->datem),'dayhour').'</td>';
print "<td><a href=\"../fiche.php?id=$objp->rowid\">";
print img_object($langs->trans("ShowProduct"),"product").' '.$objp->produit;
print "</a></td>\n";
print '<td><a href="fiche.php?id='.$objp->entrepot_id.'">';
print img_object($langs->trans("ShowWarehouse"),"stock").' '.$objp->stock;
print "</a></td>\n";
print '<td align="right">';
if ($objp->value > 0) print '+';
print $objp->value.'</td>';
print "</tr>\n";
$i++;
}
$db->free($resql);
print "</table>";
}
//print '</td></tr></table>';
print '</div></div></div>';
llxFooter();
$db->close();
?>
| jcntux/Dolibarr | htdocs/product/stock/index.php | PHP | gpl-3.0 | 5,429 |
<?php
require_once ('getConnection.php');
$stmt = $connect -> stmt_init();
$query = "SELECT c_token FROM t_course WHERE c_id = ?";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!($stmt -> bind_param("d", $_POST["course"]))) {
echo "Bind failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
if (!($result = $stmt -> get_result())) {
echo "Result failed: (" . $connect -> errno . ") " . $connect -> error;
}
while ($row = $result -> fetch_array(MYSQLI_NUM)) {
$course_token = $row[0];
}
$stmt -> close();
$stmt = $connect -> stmt_init();
$query = "SELECT p_token FROM t_prof WHERE p_id = ?";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!($stmt -> bind_param("d", $_POST['prof']))) {
echo "Bind failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
if (!($result = $stmt -> get_result())) {
echo "Result failed: (" . $connect -> errno . ") " . $connect -> error;
}
while ($row = $result -> fetch_array(MYSQLI_NUM)) {
$prof_token = $row[0];
}
$stmt -> close();
for ($i = 1; $i <= $_POST['count_tan']; $i++) {
do {
$stmt = $connect -> stmt_init();
$query = "SELECT t_tan FROM t_tan";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
if (!($result = $stmt -> get_result())) {
echo "Result failed: (" . $connect -> errno . ") " . $connect -> error;
}
while ($row = $result -> fetch_array(MYSQLI_NUM)) {
$generated_tans[] = $row[0];
}
$stmt -> close();
$tan_pruef = generate($prof_token, $course_token);
if (!empty($generated_tans)) {
$pruef = in_array($tan_pruef, $generated_tans);
} else {
$pruef = false;
}
} while ($pruef);
$tan[] = $tan_pruef;
}
echo "<h1>generated TANs</h1>";
echo "\n";
foreach ($tan as $t) {
$stmt = $connect -> stmt_init();
$query = "INSERT into t_tan(t_course, t_prof,t_tan) VALUES(?,?,?)";
if (!($stmt -> prepare($query))) {
echo "Prepare failed: " . $connect -> errno . $connect -> error;
}
if (!($stmt -> bind_param("dds", $_POST['course'], $_POST['prof'], $t))) {
echo "Bind failed: " . $connect -> errno . $connect -> error;
}
if (!$stmt -> execute()) {
echo "Execute failed: (" . $connect -> errno . ") " . $connect -> error;
}
$stmt -> close();
echo '<p>' . $t . '</p>';
echo "\n";
}
unset($_POST);
echo '<a href="admin_tan.html"><img src="../images/buttons/button_back.jpg" alt="back" id="button" width = 300 height = 150/></a>';
echo "\n";
mysqli_close($connect);
function generate($token1, $token2) {
$token = rand(100000, 999999);
$TAN = $token1 . $token . $token2;
return $TAN;
};
?> | Babbafett/evaluate_your_prof | php/generateTAN.php | PHP | gpl-3.0 | 2,980 |
/*
This project is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Deviation is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Deviation. If not, see <http://www.gnu.org/licenses/>.
*/
#define OVERRIDE_PLACEMENT
#include "common.h"
#include "pages.h"
#include "gui/gui.h"
#include "config/model.h"
#include "config/ini.h"
#include <stdlib.h>
enum {
LABELNUM_X = 0,
LABELNUM_WIDTH = 16,
LABEL_X = 17,
LABEL_WIDTH = 0,
};
#include "../128x64x1/model_loadsave.c"
| Chen-Leon/DeviationX | src/pages/text/model_loadsave.c | C | gpl-3.0 | 943 |
/*
Copyright (C) 2013 Jason Gowan
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gowan.plugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.viewers.IStructuredSelection;
public class SelectionToICompilationUnitList implements List<ICompilationUnit> {
private List<ICompilationUnit> list;
public SelectionToICompilationUnitList(IStructuredSelection selection){
List<ICompilationUnit> localList = new ArrayList<ICompilationUnit>();
List<Object> selectionList = selection.toList();
for (Object object : selectionList) {
localList.addAll( delegate(object) );
}
this.list = localList;
}
protected List<ICompilationUnit> delegate(Object selected){
List<ICompilationUnit> compilationUnits = new ArrayList<ICompilationUnit>();
if( selected instanceof ICompilationUnit ){
compilationUnits.add((ICompilationUnit)selected);
}else if ( selected instanceof IPackageFragment){
compilationUnits.addAll(get((IPackageFragment)selected));
}else if( selected instanceof IPackageFragmentRoot){
compilationUnits.addAll(get((IPackageFragmentRoot)selected));
}else if( selected instanceof IJavaProject){
compilationUnits.addAll(get((IJavaProject)selected));
}
return compilationUnits;
}
protected List<ICompilationUnit> get(IJavaProject selected) {
List<ICompilationUnit> result = new ArrayList<ICompilationUnit>();
IPackageFragmentRoot[] packageRoots;
try {
packageRoots = selected.getAllPackageFragmentRoots();
for(int i=0; i<packageRoots.length; i++){
result.addAll(get(packageRoots[i]));
}
} catch (JavaModelException e) {
e.printStackTrace();
}
return result;
}
protected List<ICompilationUnit> get(IPackageFragment frag){
List<ICompilationUnit> result = new ArrayList<ICompilationUnit>();
try {
result = Arrays.asList(frag.getCompilationUnits());
} catch (JavaModelException e) {
e.printStackTrace();
}
return result;
}
protected List<ICompilationUnit> get(IPackageFragmentRoot root){
List<ICompilationUnit> result = new ArrayList<ICompilationUnit>();
try {
for (IJavaElement frag : Arrays.asList(root.getChildren())) {
if( frag instanceof IPackageFragment ){
result.addAll(get((IPackageFragment) frag));
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}
return result;
}
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public boolean contains(Object o) {
return list.contains(o);
}
@Override
public Iterator<ICompilationUnit> iterator() {
return list.iterator();
}
@Override
public Object[] toArray() {
return list.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return list.toArray(a);
}
@Override
public boolean add(ICompilationUnit e) {
return list.add(e);
}
@Override
public boolean remove(Object o) {
return list.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return list.contains(c);
}
@Override
public boolean addAll(Collection<? extends ICompilationUnit> c) {
return list.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends ICompilationUnit> c) {
return list.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return list.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return list.retainAll(c);
}
@Override
public void clear() {
list.clear();
}
@Override
public ICompilationUnit get(int index) {
return list.get(index);
}
@Override
public ICompilationUnit set(int index, ICompilationUnit element) {
return list.set(index, element);
}
@Override
public void add(int index, ICompilationUnit element) {
list.add(index, element);
}
@Override
public ICompilationUnit remove(int index) {
return list.remove(index);
}
@Override
public int indexOf(Object o) {
return list.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return list.lastIndexOf(o);
}
@Override
public ListIterator<ICompilationUnit> listIterator() {
return list.listIterator();
}
@Override
public ListIterator<ICompilationUnit> listIterator(int index) {
return list.listIterator(index);
}
@Override
public List<ICompilationUnit> subList(int fromIndex, int toIndex) {
return list.subList(fromIndex, toIndex);
}
}
| jesg/junit3Tojunit4 | src/com/gowan/plugin/SelectionToICompilationUnitList.java | Java | gpl-3.0 | 5,321 |
<?php
namespace DB;
final class mPDO {
private $connection = null;
private $statement = null;
public function __construct($hostname, $username, $password, $database, $port = '3306') {
try {
$dsn = "mysql:host={$hostname};port={$port};dbname={$database};charset=UTF8";
$options = array(
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_TIMEOUT => 15,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION );
$this->connection = new \PDO($dsn, $username, $password, $options);
} catch (\PDOException $e) {
throw new \Exception('Failed to connect to database. Reason: \'' . $e->getMessage() . '\'');
}
$this->connection->exec("SET NAMES 'utf8'");
$this->connection->exec("SET CHARACTER SET utf8");
$this->connection->exec("SET CHARACTER_SET_CONNECTION=utf8");
$this->connection->exec("SET SQL_MODE = ''");
$this->rowCount = 0;
}
public function prepare($sql) {
$this->statement = $this->connection->prepare($sql);
}
public function bindParam($parameter, $variable, $data_type = \PDO::PARAM_STR, $length = 0) {
if ($length) {
$this->statement->bindParam($parameter, $variable, $data_type, $length);
} else {
$this->statement->bindParam($parameter, $variable, $data_type);
}
}
public function execute() {
try {
if ($this->statement && $this->statement->execute()) {
$data = array();
while ($row = $this->statement->fetch(\PDO::FETCH_ASSOC)) {
$data[] = $row;
}
$result = new \stdClass();
$result->row = (isset($data[0])) ? $data[0] : array();
$result->rows = $data;
$result->num_rows = $this->statement->rowCount();
}
} catch (\PDOException $e) {
throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode());
}
}
public function query($sql, $params = array()) {
$this->statement = $this->connection->prepare($sql);
$result = false;
try {
if ($this->statement && $this->statement->execute($params)) {
$data = array();
$this->rowCount = $this->statement->rowCount();
if ($this->rowCount > 0) {
try {
$data = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
} catch (\Exception $ex) {
}
}
// free up resources
$this->statement->closeCursor();
$this->statement = null;
$result = new \stdClass();
$result->row = (isset($data[0]) ? $data[0] : array());
$result->rows = $data;
$result->num_rows = $this->rowCount;
}
} catch (\PDOException $e) {
throw new \Exception('Error: ' . $e->getMessage() . ' Error Code : ' . $e->getCode() . ' <br />' . $sql);
}
if ($result) {
return $result;
} else {
$result = new \stdClass();
$result->row = array();
$result->rows = array();
$result->num_rows = 0;
return $result;
}
}
public function escape($value) {
return str_replace(array( "\\", "\0", "\n", "\r", "\x1a", "'", '"' ), array(
"\\\\",
"\\0", "\\n", "\\r", "\Z", "\'", '\"' ), $value);
}
public function countAffected() {
if ($this->statement) {
return $this->statement->rowCount();
} else {
return $this->rowCount;
}
}
public function getLastId() {
return $this->connection->lastInsertId();
}
public function isConnected() {
if ($this->connection) {
return true;
} else {
return false;
}
}
public function __destruct() {
$this->connection = null;
}
} | Copona/copona | system/library/db/mpdo.php | PHP | gpl-3.0 | 4,141 |
/**
* copyright
* Inubit AG
* Schoeneberger Ufer 89
* 10785 Berlin
* Germany
*/
package com.inubit.research.textToProcess.textModel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Rectangle2D;
import net.frapu.code.visualization.ProcessNode;
import net.frapu.code.visualization.ProcessUtils;
import net.frapu.code.visualization.ProcessUtils.Orientation;
/**
* @author ff
*
*/
public class WordNode extends ProcessNode {
/**
*
*/
public static final Color HIGHLIGHT_COLOR = new Color(255,255,224);
private static final int PADDING = 3; //pixels
/**
*
*/
public WordNode(String word) {
setText(word.replaceAll("\\/", "/"));
setBackground(Color.WHITE);
}
/**
*
*/
public WordNode() {
// TODO Auto-generated constructor stub
}
@Override
protected Shape getOutlineShape() {
Rectangle2D outline = new Rectangle2D.Float(getPos().x - (getSize().width / 2),
getPos().y - (getSize().height / 2), getSize().width, getSize().height);
return outline;
}
@Override
protected void paintInternal(Graphics g) {
Graphics2D _g = (Graphics2D) g;
Shape _s = getOutlineShape();
if(isSelected()) {
_g.setColor(WordNode.HIGHLIGHT_COLOR);
}else {
_g.setColor(getBackground());
_g.setStroke(ProcessUtils.defaultStroke);
}
_g.fill(_s);
_g.setColor(Color.LIGHT_GRAY);
_g.draw(_s);
_g.setColor(Color.BLACK);
if(getText() == null) {
ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, "Word", Orientation.CENTER);
}else {
ProcessUtils.drawText(_g, getPos().x, getPos().y, getSize().width, getText(), Orientation.CENTER);
}
}
@Override
public void setSize(int w, int h) {
return;
}
@Override
public void setPos(int x, int y) {
return;
}
/**
* @return
*/
public String getWord() {
return getText();
}
/**
* @param stringBounds
*/
public void setBounds(Rectangle2D b) {
super.setSize((int)b.getWidth() + 2* PADDING, (int)b.getHeight() + 2* PADDING);
}
/**
* @param _wx
* @param y
*/
public void setLocation(int x, int y) {
super.setPos(x,y);
}
@Override
public String toString() {
return "WordNode ("+getText()+")";
}
}
| FabianFriedrich/Text2Process | src/com/inubit/research/textToProcess/textModel/WordNode.java | Java | gpl-3.0 | 2,249 |
<?php
/*
* $result->groups
* $result->auditories
* $result->lectors
* $result->calendars
*/
?>
<h1>Додати календар</h1>
<div class="uk-margin">
<div class="uk-form">
<?php
if(mysqli_num_rows($result->groups) > 0){
echo '<select>';
while($row = mysqli_fetch_assoc($result->groups)) {
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
echo '</select>';
}
?>
<?php
if(mysqli_num_rows($result->auditories) > 0){
echo '<select>';
while($row = mysqli_fetch_assoc($result->auditories)) {
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
echo '</select>';
}
?>
<?php
if(mysqli_num_rows($result->lectors) > 0){
echo '<select>';
while($row = mysqli_fetch_assoc($result->lectors)) {
echo '<option value="'.$row->id.'">'.$row->name.'</option>';
}
echo '</select>';
}
?>
</div>
</div>
| nemishkor/npu-calendars | application/views/calendar_add_view.php | PHP | gpl-3.0 | 905 |
<?php
/*
Scripts and styles options
*/
/**
* Renders the Scripts and styles options section.
*/
function electric_thop_render_scripts_section(){
echo "<p>" . __('You are not forced to use everything that the theme includes. If you are not going to use a feature (because you don\'t like it or because you prefer a different solution, just uncheck it. You will save some kb to load.','electric') . "</p>" ;
echo "<p>" . __('If you use these styles/scripts they will be loaded individually. If you want to boost performance, you can combine them into a single file using a plugin (W3 Total Cache is suggested, but you can use any option or do it manually)','electric') . "</p>" ;
}
/**
* Renders the Icon Fonts checkbox setting field.
*/
function electric_sfield_use_icon_fonts() {
$options = electric_thop_get_options();
?>
<label for="use-icon-fonts" class="description">
<input type="checkbox" name="electric_theme_options[use_icon_fonts]" id="use-icon-fonts" <?php checked('on', $options['use_icon_fonts']); ?> />
<?php _e('Check this if you want to use the icon font.', 'electric'); ?>
</label>
<p class="description"><?php _e('You can customize the icons uploading the file electric/fonts/fonts/electric.dev.svg to <a href="http://icomoon.io">icomoon.io</a>.', 'electric'); ?></p>
<?php
}
/**
* Renders the Google Fonts checkbox setting field.
*/
function electric_sfield_use_google_fonts() {
$options = electric_thop_get_options();
?>
<label for="use-google-fonts" class="description">
<input type="checkbox" name="electric_theme_options[use_google_fonts]" id="use-google-fonts" <?php checked('on', $options['use_google_fonts']); ?> />
<?php _e('Check this if you want to use fonts from Google Web Fonts', 'electric'); ?>
</label>
<p class="description"><?php _e('Allows you to use fonts from <a href="http://www.google.com/webfonts">Google Web Fonts</a>', 'electric') ?></p>
<?php
}
/**
* Renders the Google Fonts Family input setting field.
*/
function electric_sfield_google_fonts_choice() {
$options = electric_thop_get_options();
?>
<input type="text" name="electric_theme_options[google_fonts_choice]" id="google-fonts-choice" value="<?php echo esc_attr($options['google_fonts_choice']); ?>" />
<label class="description" for="google-fonts-choice"><?php _e('Your font family choice', 'electric'); ?></label>
<p class="description"><?php _e('If you want to use a different set than the default (Comfortaa + Open Sans):', 'electric') ?></p>
<ol class="description">
<li><?php _e('Choose the font(s) you like and click "Use"', 'electric') ?></li>
<li><?php _e('Choose the style(s) you want and character set(s) at point 1 and 2', 'electric') ?></li>
<li><?php _e('Copy the code at the "Standard" tab at point 3 ', 'electric') ?></li>
</ol>
<?php
}
/**
* Renders the tooltip checkbox setting field.
*/
function electric_sfield_use_tooltip_js() {
$options = electric_thop_get_options();
?>
<label for="use-tooltip-js" class="description">
<input type="checkbox" name="electric_theme_options[use_tooltip_js]" id="use-tooltip-js" <?php checked('on', $options['use_tooltip_js']); ?> />
<?php _e('Uncheck this if you don\'t want to load the Tooltip script', 'electric'); ?>
</label>
<p class="description"><?php _e('This script is used to display a tooltip in the menus and in the availability widget.
If you don\'t want them, don\'t include the plugin and save some kb', 'electric') ?></p>
<p class="description"><?php _e('More info about this tooltip <a href="http://jquerytools.org/demos/tooltip/index.html">here</a>', 'electric') ?></p>
<?php
}
| cmoralesweb/electric-theme | wp-content/themes/electric/inc/theme-options/scripts.php | PHP | gpl-3.0 | 3,745 |
#ifndef __PROCESSOR_H__
#define __PROCESSOR_H__
#include <gctypes.h>
#include "asm.h"
#define __stringify(rn) #rn
#define ATTRIBUTE_ALIGN(v) __attribute__((aligned(v)))
// courtesy of Marcan
#define STACK_ALIGN(type, name, cnt, alignment) u8 _al__##name[((sizeof(type)*(cnt)) + (alignment) + (((sizeof(type)*(cnt))%(alignment)) > 0 ? ((alignment) - ((sizeof(type)*(cnt))%(alignment))) : 0))]; \
type *name = (type*)(((u32)(_al__##name)) + ((alignment) - (((u32)(_al__##name))&((alignment)-1))))
#define _sync() asm volatile("sync")
#define _nop() asm volatile("nop")
#define ppcsync() asm volatile("sc")
#define ppchalt() ({ \
asm volatile("sync"); \
while(1) { \
asm volatile("nop"); \
asm volatile("li 3,0"); \
asm volatile("nop"); \
} \
})
#define mfpvr() ({register u32 _rval; \
asm volatile("mfpvr %0" : "=r"(_rval)); _rval;})
#define mfdcr(_rn) ({register u32 _rval; \
asm volatile("mfdcr %0," __stringify(_rn) \
: "=r" (_rval)); _rval;})
#define mtdcr(rn, val) asm volatile("mtdcr " __stringify(rn) ",%0" : : "r" (val))
#define mfmsr() ({register u32 _rval; \
asm volatile("mfmsr %0" : "=r" (_rval)); _rval;})
#define mtmsr(val) asm volatile("mtmsr %0" : : "r" (val))
#define mfdec() ({register u32 _rval; \
asm volatile("mfdec %0" : "=r" (_rval)); _rval;})
#define mtdec(_val) asm volatile("mtdec %0" : : "r" (_val))
#define mfspr(_rn) \
({ register u32 _rval = 0; \
asm volatile("mfspr %0," __stringify(_rn) \
: "=r" (_rval));\
_rval; \
})
#define mtspr(_rn, _val) asm volatile("mtspr " __stringify(_rn) ",%0" : : "r" (_val))
#define mfwpar() mfspr(WPAR)
#define mtwpar(_val) mtspr(WPAR,_val)
#define mfmmcr0() mfspr(MMCR0)
#define mtmmcr0(_val) mtspr(MMCR0,_val)
#define mfmmcr1() mfspr(MMCR1)
#define mtmmcr1(_val) mtspr(MMCR1,_val)
#define mfpmc1() mfspr(PMC1)
#define mtpmc1(_val) mtspr(PMC1,_val)
#define mfpmc2() mfspr(PMC2)
#define mtpmc2(_val) mtspr(PMC2,_val)
#define mfpmc3() mfspr(PMC3)
#define mtpmc3(_val) mtspr(PMC3,_val)
#define mfpmc4() mfspr(PMC4)
#define mtpmc4(_val) mtspr(PMC4,_val)
#define mfhid0() mfspr(HID0)
#define mthid0(_val) mtspr(HID0,_val)
#define mfhid1() mfspr(HID1)
#define mthid1(_val) mtspr(HID1,_val)
#define mfhid2() mfspr(HID2)
#define mthid2(_val) mtspr(HID2,_val)
#define mfhid4() mfspr(HID4)
#define mthid4(_val) mtspr(HID4,_val)
#define __lhbrx(base,index) \
({ register u16 res; \
__asm__ volatile ("lhbrx %0,%1,%2" : "=r"(res) : "b%"(index), "r"(base) : "memory"); \
res; })
#define __lwbrx(base,index) \
({ register u32 res; \
__asm__ volatile ("lwbrx %0,%1,%2" : "=r"(res) : "b%"(index), "r"(base) : "memory"); \
res; })
#define __sthbrx(base,index,value) \
__asm__ volatile ("sthbrx %0,%1,%2" : : "r"(value), "b%"(index), "r"(base) : "memory")
#define __stwbrx(base,index,value) \
__asm__ volatile ("stwbrx %0,%1,%2" : : "r"(value), "b%"(index), "r"(base) : "memory")
#define cntlzw(_val) ({register u32 _rval; \
asm volatile("cntlzw %0, %1" : "=r"((_rval)) : "r"((_val))); _rval;})
#define _CPU_MSR_GET( _msr_value ) \
do { \
_msr_value = 0; \
asm volatile ("mfmsr %0" : "=&r" ((_msr_value)) : "0" ((_msr_value))); \
} while (0)
#define _CPU_MSR_SET( _msr_value ) \
{ asm volatile ("mtmsr %0" : "=&r" ((_msr_value)) : "0" ((_msr_value))); }
#define _CPU_ISR_Enable() \
{ register u32 _val = 0; \
__asm__ __volatile__ ( \
"mfmsr %0\n" \
"ori %0,%0,0x8000\n" \
"mtmsr %0" \
: "=&r" ((_val)) : "0" ((_val)) \
); \
}
#define _CPU_ISR_Disable( _isr_cookie ) \
{ register u32 _disable_mask = 0; \
_isr_cookie = 0; \
__asm__ __volatile__ ( \
"mfmsr %0\n" \
"rlwinm %1,%0,0,17,15\n" \
"mtmsr %1\n" \
"extrwi %0,%0,1,16" \
: "=&r" ((_isr_cookie)), "=&r" ((_disable_mask)) \
: "0" ((_isr_cookie)), "1" ((_disable_mask)) \
); \
}
#define _CPU_ISR_Restore( _isr_cookie ) \
{ register u32 _enable_mask = 0; \
__asm__ __volatile__ ( \
" cmpwi %0,0\n" \
" beq 1f\n" \
" mfmsr %1\n" \
" ori %1,%1,0x8000\n" \
" mtmsr %1\n" \
"1:" \
: "=r"((_isr_cookie)),"=&r" ((_enable_mask)) \
: "0"((_isr_cookie)),"1" ((_enable_mask)) \
); \
}
#define _CPU_ISR_Flash( _isr_cookie ) \
{ register u32 _flash_mask = 0; \
__asm__ __volatile__ ( \
" cmpwi %0,0\n" \
" beq 1f\n" \
" mfmsr %1\n" \
" ori %1,%1,0x8000\n" \
" mtmsr %1\n" \
" rlwinm %1,%1,0,17,15\n" \
" mtmsr %1\n" \
"1:" \
: "=r" ((_isr_cookie)), "=&r" ((_flash_mask)) \
: "0" ((_isr_cookie)), "1" ((_flash_mask)) \
); \
}
#define _CPU_FPR_Enable() \
{ register u32 _val = 0; \
asm volatile ("mfmsr %0; ori %0,%0,0x2000; mtmsr %0" : \
"=&r" (_val) : "0" (_val));\
}
#define _CPU_FPR_Disable() \
{ register u32 _val = 0; \
asm volatile ("mfmsr %0; rlwinm %0,%0,0,19,17; mtmsr %0" : \
"=&r" (_val) : "0" (_val));\
}
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
static inline u16 bswap16(u16 val)
{
u16 tmp = val;
return __lhbrx(&tmp,0);
}
static inline u32 bswap32(u32 val)
{
u32 tmp = val;
return __lwbrx(&tmp,0);
}
static inline u64 bswap64(u64 val)
{
union ullc {
u64 ull;
u32 ul[2];
} outv;
u64 tmp = val;
outv.ul[0] = __lwbrx(&tmp,4);
outv.ul[1] = __lwbrx(&tmp,0);
return outv.ull;
}
// Basic I/O
static inline u32 read32(u32 addr)
{
u32 x;
asm volatile("lwz %0,0(%1) ; sync" : "=r"(x) : "b"(0xc0000000 | addr));
return x;
}
static inline void write32(u32 addr, u32 x)
{
asm("stw %0,0(%1) ; eieio" : : "r"(x), "b"(0xc0000000 | addr));
}
static inline void mask32(u32 addr, u32 clear, u32 set)
{
write32(addr, (read32(addr)&(~clear)) | set);
}
static inline u16 read16(u32 addr)
{
u16 x;
asm volatile("lhz %0,0(%1) ; sync" : "=r"(x) : "b"(0xc0000000 | addr));
return x;
}
static inline void write16(u32 addr, u16 x)
{
asm("sth %0,0(%1) ; eieio" : : "r"(x), "b"(0xc0000000 | addr));
}
static inline u8 read8(u32 addr)
{
u8 x;
asm volatile("lbz %0,0(%1) ; sync" : "=r"(x) : "b"(0xc0000000 | addr));
return x;
}
static inline void write8(u32 addr, u8 x)
{
asm("stb %0,0(%1) ; eieio" : : "r"(x), "b"(0xc0000000 | addr));
}
static inline void writef32(u32 addr, f32 x)
{
asm("stfs %0,0(%1) ; eieio" : : "f"(x), "b"(0xc0000000 | addr));
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
| MbCrew/wiicraft-code | libogc/include/ogc/machine/processor.h | C | gpl-3.0 | 6,592 |
'use strict';
angular.module('ldrWebApp')
/**
* @name pageSkipper
* @param config
* @param pages
* @type element
* @description Skip to page directive
* @requires $scope
*/
.directive('pageSkipper', function () {
return {
restrict: 'E',
templateUrl: 'components/page-skipper/page-skipper.template.html',
scope: {'config': '=', 'pages': '='},
controller: function ($scope) {
/**
* @name pageSkipper#generateArray
* @param {Number} start
* @param {Number} end
* @description generate an array in form {start} to {end}
* @returns {Array}
*/
function generateArray(start, end) {
var list = [];
for (var i = start; i <= end; i++) {
list.push(i);
}
return list;
}
/**
* @name pageSkipper#skipToPage
* @param {Number} item
* @description get the desired page
* @return {Undefined}
*/
$scope.skipToPage = function (item) {
$scope.config.page = (item === undefined) ? 1 : item;
};
$scope.selectedPage = 1;
$scope.pagesList = generateArray(1, $scope.pages);
}
};
});
| qualitance/ldir-web | client/components/page-skipper/page-skipper.directive.js | JavaScript | gpl-3.0 | 1,522 |
odoo.define('point_of_sale.DB', function (require) {
"use strict";
var core = require('web.core');
var utils = require('web.utils');
/* The PosDB holds reference to data that is either
* - static: does not change between pos reloads
* - persistent : must stay between reloads ( orders )
*/
var PosDB = core.Class.extend({
name: 'openerp_pos_db', //the prefix of the localstorage data
limit: 100, // the maximum number of results returned by a search
init: function(options){
options = options || {};
this.name = options.name || this.name;
this.limit = options.limit || this.limit;
if (options.uuid) {
this.name = this.name + '_' + options.uuid;
}
//cache the data in memory to avoid roundtrips to the localstorage
this.cache = {};
this.product_by_id = {};
this.product_by_barcode = {};
this.product_by_category_id = {};
this.product_packaging_by_barcode = {};
this.partner_sorted = [];
this.partner_by_id = {};
this.partner_by_barcode = {};
this.partner_search_string = "";
this.partner_write_date = null;
this.category_by_id = {};
this.root_category_id = 0;
this.category_products = {};
this.category_ancestors = {};
this.category_childs = {};
this.category_parent = {};
this.category_search_string = {};
},
/**
* sets an uuid to prevent conflict in locally stored data between multiple PoS Configs. By
* using the uuid of the config the local storage from other configs will not get effected nor
* loaded in sessions that don't belong to them.
*
* @param {string} uuid Unique identifier of the PoS Config linked to the current session.
*/
set_uuid: function(uuid){
this.name = this.name + '_' + uuid;
},
/* returns the category object from its id. If you pass a list of id as parameters, you get
* a list of category objects.
*/
get_category_by_id: function(categ_id){
if(categ_id instanceof Array){
var list = [];
for(var i = 0, len = categ_id.length; i < len; i++){
var cat = this.category_by_id[categ_id[i]];
if(cat){
list.push(cat);
}else{
console.error("get_category_by_id: no category has id:",categ_id[i]);
}
}
return list;
}else{
return this.category_by_id[categ_id];
}
},
/* returns a list of the category's child categories ids, or an empty list
* if a category has no childs */
get_category_childs_ids: function(categ_id){
return this.category_childs[categ_id] || [];
},
/* returns a list of all ancestors (parent, grand-parent, etc) categories ids
* starting from the root category to the direct parent */
get_category_ancestors_ids: function(categ_id){
return this.category_ancestors[categ_id] || [];
},
/* returns the parent category's id of a category, or the root_category_id if no parent.
* the root category is parent of itself. */
get_category_parent_id: function(categ_id){
return this.category_parent[categ_id] || this.root_category_id;
},
/* adds categories definitions to the database. categories is a list of categories objects as
* returned by the openerp server. Categories must be inserted before the products or the
* product/ categories association may (will) not work properly */
add_categories: function(categories){
var self = this;
if(!this.category_by_id[this.root_category_id]){
this.category_by_id[this.root_category_id] = {
id : this.root_category_id,
name : 'Root',
};
}
categories.forEach(function(cat){
self.category_by_id[cat.id] = cat;
});
categories.forEach(function(cat){
var parent_id = cat.parent_id[0];
if(!(parent_id && self.category_by_id[parent_id])){
parent_id = self.root_category_id;
}
self.category_parent[cat.id] = parent_id;
if(!self.category_childs[parent_id]){
self.category_childs[parent_id] = [];
}
self.category_childs[parent_id].push(cat.id);
});
function make_ancestors(cat_id, ancestors){
self.category_ancestors[cat_id] = ancestors;
ancestors = ancestors.slice(0);
ancestors.push(cat_id);
var childs = self.category_childs[cat_id] || [];
for(var i=0, len = childs.length; i < len; i++){
make_ancestors(childs[i], ancestors);
}
}
make_ancestors(this.root_category_id, []);
},
category_contains: function(categ_id, product_id) {
var product = this.product_by_id[product_id];
if (product) {
var cid = product.pos_categ_id[0];
while (cid && cid !== categ_id){
cid = this.category_parent[cid];
}
return !!cid;
}
return false;
},
/* loads a record store from the database. returns default if nothing is found */
load: function(store,deft){
if(this.cache[store] !== undefined){
return this.cache[store];
}
var data = localStorage[this.name + '_' + store];
if(data !== undefined && data !== ""){
data = JSON.parse(data);
this.cache[store] = data;
return data;
}else{
return deft;
}
},
/* saves a record store to the database */
save: function(store,data){
localStorage[this.name + '_' + store] = JSON.stringify(data);
this.cache[store] = data;
},
_product_search_string: function(product){
var str = product.display_name;
if (product.barcode) {
str += '|' + product.barcode;
}
if (product.default_code) {
str += '|' + product.default_code;
}
if (product.description) {
str += '|' + product.description;
}
if (product.description_sale) {
str += '|' + product.description_sale;
}
str = product.id + ':' + str.replace(/:/g,'') + '\n';
return str;
},
add_products: function(products){
var stored_categories = this.product_by_category_id;
if(!products instanceof Array){
products = [products];
}
for(var i = 0, len = products.length; i < len; i++){
var product = products[i];
if (product.id in this.product_by_id) continue;
if (product.available_in_pos){
var search_string = utils.unaccent(this._product_search_string(product));
var categ_id = product.pos_categ_id ? product.pos_categ_id[0] : this.root_category_id;
product.product_tmpl_id = product.product_tmpl_id[0];
if(!stored_categories[categ_id]){
stored_categories[categ_id] = [];
}
stored_categories[categ_id].push(product.id);
if(this.category_search_string[categ_id] === undefined){
this.category_search_string[categ_id] = '';
}
this.category_search_string[categ_id] += search_string;
var ancestors = this.get_category_ancestors_ids(categ_id) || [];
for(var j = 0, jlen = ancestors.length; j < jlen; j++){
var ancestor = ancestors[j];
if(! stored_categories[ancestor]){
stored_categories[ancestor] = [];
}
stored_categories[ancestor].push(product.id);
if( this.category_search_string[ancestor] === undefined){
this.category_search_string[ancestor] = '';
}
this.category_search_string[ancestor] += search_string;
}
}
this.product_by_id[product.id] = product;
if(product.barcode){
this.product_by_barcode[product.barcode] = product;
}
}
},
add_packagings: function(product_packagings){
var self = this;
_.map(product_packagings, function (product_packaging) {
if (_.find(self.product_by_id, {'id': product_packaging.product_id[0]})) {
self.product_packaging_by_barcode[product_packaging.barcode] = product_packaging;
}
});
},
_partner_search_string: function(partner){
var str = partner.name || '';
if(partner.barcode){
str += '|' + partner.barcode;
}
if(partner.address){
str += '|' + partner.address;
}
if(partner.phone){
str += '|' + partner.phone.split(' ').join('');
}
if(partner.mobile){
str += '|' + partner.mobile.split(' ').join('');
}
if(partner.email){
str += '|' + partner.email;
}
if(partner.vat){
str += '|' + partner.vat;
}
str = '' + partner.id + ':' + str.replace(':', '').replace(/\n/g, ' ') + '\n';
return str;
},
add_partners: function(partners){
var updated_count = 0;
var new_write_date = '';
var partner;
for(var i = 0, len = partners.length; i < len; i++){
partner = partners[i];
var local_partner_date = (this.partner_write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z');
var dist_partner_date = (partner.write_date || '').replace(/^(\d{4}-\d{2}-\d{2}) ((\d{2}:?){3})$/, '$1T$2Z');
if ( this.partner_write_date &&
this.partner_by_id[partner.id] &&
new Date(local_partner_date).getTime() + 1000 >=
new Date(dist_partner_date).getTime() ) {
// FIXME: The write_date is stored with milisec precision in the database
// but the dates we get back are only precise to the second. This means when
// you read partners modified strictly after time X, you get back partners that were
// modified X - 1 sec ago.
continue;
} else if ( new_write_date < partner.write_date ) {
new_write_date = partner.write_date;
}
if (!this.partner_by_id[partner.id]) {
this.partner_sorted.push(partner.id);
}
this.partner_by_id[partner.id] = partner;
updated_count += 1;
}
this.partner_write_date = new_write_date || this.partner_write_date;
if (updated_count) {
// If there were updates, we need to completely
// rebuild the search string and the barcode indexing
this.partner_search_string = "";
this.partner_by_barcode = {};
for (var id in this.partner_by_id) {
partner = this.partner_by_id[id];
if(partner.barcode){
this.partner_by_barcode[partner.barcode] = partner;
}
partner.address = (partner.street ? partner.street + ', ': '') +
(partner.zip ? partner.zip + ', ': '') +
(partner.city ? partner.city + ', ': '') +
(partner.state_id ? partner.state_id[1] + ', ': '') +
(partner.country_id ? partner.country_id[1]: '');
this.partner_search_string += this._partner_search_string(partner);
}
this.partner_search_string = utils.unaccent(this.partner_search_string);
}
return updated_count;
},
get_partner_write_date: function(){
return this.partner_write_date || "1970-01-01 00:00:00";
},
get_partner_by_id: function(id){
return this.partner_by_id[id];
},
get_partner_by_barcode: function(barcode){
return this.partner_by_barcode[barcode];
},
get_partners_sorted: function(max_count){
max_count = max_count ? Math.min(this.partner_sorted.length, max_count) : this.partner_sorted.length;
var partners = [];
for (var i = 0; i < max_count; i++) {
partners.push(this.partner_by_id[this.partner_sorted[i]]);
}
return partners;
},
search_partner: function(query){
try {
query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.');
query = query.replace(/ /g,'.+');
var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi");
}catch(e){
return [];
}
var results = [];
for(var i = 0; i < this.limit; i++){
var r = re.exec(this.partner_search_string);
if(r){
var id = Number(r[1]);
results.push(this.get_partner_by_id(id));
}else{
break;
}
}
return results;
},
/* removes all the data from the database. TODO : being able to selectively remove data */
clear: function(){
for(var i = 0, len = arguments.length; i < len; i++){
localStorage.removeItem(this.name + '_' + arguments[i]);
}
},
/* this internal methods returns the count of properties in an object. */
_count_props : function(obj){
var count = 0;
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
count++;
}
}
return count;
},
get_product_by_id: function(id){
return this.product_by_id[id];
},
get_product_by_barcode: function(barcode){
if(this.product_by_barcode[barcode]){
return this.product_by_barcode[barcode];
} else if (this.product_packaging_by_barcode[barcode]) {
return this.product_by_id[this.product_packaging_by_barcode[barcode].product_id[0]];
}
return undefined;
},
get_product_by_category: function(category_id){
var product_ids = this.product_by_category_id[category_id];
var list = [];
if (product_ids) {
for (var i = 0, len = Math.min(product_ids.length, this.limit); i < len; i++) {
const product = this.product_by_id[product_ids[i]];
if (!(product.active && product.available_in_pos)) continue;
list.push(product);
}
}
return list;
},
/* returns a list of products with :
* - a category that is or is a child of category_id,
* - a name, package or barcode containing the query (case insensitive)
*/
search_product_in_category: function(category_id, query){
try {
query = query.replace(/[\[\]\(\)\+\*\?\.\-\!\&\^\$\|\~\_\{\}\:\,\\\/]/g,'.');
query = query.replace(/ /g,'.+');
var re = RegExp("([0-9]+):.*?"+utils.unaccent(query),"gi");
}catch(e){
return [];
}
var results = [];
for(var i = 0; i < this.limit; i++){
var r = re.exec(this.category_search_string[category_id]);
if(r){
var id = Number(r[1]);
const product = this.get_product_by_id(id);
if (!(product.active && product.available_in_pos)) continue;
results.push(product);
}else{
break;
}
}
return results;
},
/* from a product id, and a list of category ids, returns
* true if the product belongs to one of the provided category
* or one of its child categories.
*/
is_product_in_category: function(category_ids, product_id) {
if (!(category_ids instanceof Array)) {
category_ids = [category_ids];
}
var cat = this.get_product_by_id(product_id).pos_categ_id[0];
while (cat) {
for (var i = 0; i < category_ids.length; i++) {
if (cat == category_ids[i]) { // The == is important, ids may be strings
return true;
}
}
cat = this.get_category_parent_id(cat);
}
return false;
},
/* paid orders */
add_order: function(order){
var order_id = order.uid;
var orders = this.load('orders',[]);
// if the order was already stored, we overwrite its data
for(var i = 0, len = orders.length; i < len; i++){
if(orders[i].id === order_id){
orders[i].data = order;
this.save('orders',orders);
return order_id;
}
}
// Only necessary when we store a new, validated order. Orders
// that where already stored should already have been removed.
this.remove_unpaid_order(order);
orders.push({id: order_id, data: order});
this.save('orders',orders);
return order_id;
},
remove_order: function(order_id){
var orders = this.load('orders',[]);
orders = _.filter(orders, function(order){
return order.id !== order_id;
});
this.save('orders',orders);
},
remove_all_orders: function(){
this.save('orders',[]);
},
get_orders: function(){
return this.load('orders',[]);
},
get_order: function(order_id){
var orders = this.get_orders();
for(var i = 0, len = orders.length; i < len; i++){
if(orders[i].id === order_id){
return orders[i];
}
}
return undefined;
},
/* working orders */
save_unpaid_order: function(order){
var order_id = order.uid;
var orders = this.load('unpaid_orders',[]);
var serialized = order.export_as_JSON();
for (var i = 0; i < orders.length; i++) {
if (orders[i].id === order_id){
orders[i].data = serialized;
this.save('unpaid_orders',orders);
return order_id;
}
}
orders.push({id: order_id, data: serialized});
this.save('unpaid_orders',orders);
return order_id;
},
remove_unpaid_order: function(order){
var orders = this.load('unpaid_orders',[]);
orders = _.filter(orders, function(o){
return o.id !== order.uid;
});
this.save('unpaid_orders',orders);
},
remove_all_unpaid_orders: function(){
this.save('unpaid_orders',[]);
},
get_unpaid_orders: function(){
var saved = this.load('unpaid_orders',[]);
var orders = [];
for (var i = 0; i < saved.length; i++) {
orders.push(saved[i].data);
}
return orders;
},
/**
* Return the orders with requested ids if they are unpaid.
* @param {array<number>} ids order_ids.
* @return {array<object>} list of orders.
*/
get_unpaid_orders_to_sync: function(ids){
var saved = this.load('unpaid_orders',[]);
var orders = [];
saved.forEach(function(o) {
if (ids.includes(o.id)){
orders.push(o);
}
});
return orders;
},
/**
* Add a given order to the orders to be removed from the server.
*
* If an order is removed from a table it also has to be removed from the server to prevent it from reapearing
* after syncing. This function will add the server_id of the order to a list of orders still to be removed.
* @param {object} order object.
*/
set_order_to_remove_from_server: function(order){
if (order.server_id !== undefined) {
var to_remove = this.load('unpaid_orders_to_remove',[]);
to_remove.push(order.server_id);
this.save('unpaid_orders_to_remove', to_remove);
}
},
/**
* Get a list of server_ids of orders to be removed.
* @return {array<number>} list of server_ids.
*/
get_ids_to_remove_from_server: function(){
return this.load('unpaid_orders_to_remove',[]);
},
/**
* Remove server_ids from the list of orders to be removed.
* @param {array<number>} ids
*/
set_ids_removed_from_server: function(ids){
var to_remove = this.load('unpaid_orders_to_remove',[]);
to_remove = _.filter(to_remove, function(id){
return !ids.includes(id);
});
this.save('unpaid_orders_to_remove', to_remove);
},
set_cashier: function(cashier) {
// Always update if the user is the same as before
this.save('cashier', cashier || null);
},
get_cashier: function() {
return this.load('cashier');
}
});
return PosDB;
});
| jeremiahyan/odoo | addons/point_of_sale/static/src/js/db.js | JavaScript | gpl-3.0 | 21,089 |
<div class="container">
<div class="row jumbotron indexBKGD">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">
<div class="row">
<div class="col-12 col-sm-12 col-lg-12" style="text-align: center;">
<div class="panel panel-default">
<div class="panel-body">
<h2 style="text-align: center;"><strong>Nathaniel Buechler</strong></h2>
<h6 style="text-align: center;"><i>Multifaceted Specialist</i></h6>
<h6 style="text-align: center;">
<a class="btn btn-default" href="https://github.com/nbuechler"><i class="fa fa-2x fa-github"></i></a>
<a class="btn btn-default" href="https://www.linkedin.com/in/nathaniel-buechler"><i class="fa fa-2x fa-linkedin-square"></i></a>
<a class="btn btn-default" href="mailto:[email protected]?Subject=Hello%20Nathaniel"><i class="fa fa-2x fa-envelope"></i></a>
<a class="btn btn-default" href="/resume/Nathaniel_Buechler-Sr_UX_Engineer.pdf"><i class="fa fa-2x fa-file-text"></i></a>
</h6>
<hr></hr>
<h6 class="well" style="text-align: center;">
<i>Where is my attention?</i><br></br>
My talents as a Full-Stack JavaScript Engineer combined with my Python experience allow me to actively experiment with basic ML, AC, NLP, IoT, and microservices to solve real problems.
</h6>
<h6 style="text-align: center;">
I'm passionate about connecting many different themes with many "lenses" of knowledge.
If you would like to learn more about me, below you will see a few different clickable icons to spark your interest about my interests. Please, enjoy my website!
</h6>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-lg-5 mobile" style="text-align: center; padding-bottom: 5%; padding-top: 6%;">
<a href="http://nathanielbuechler.com/"><img style="height: 220px; cursor: default;" onclick="alert('You found the secret!!')" src="images/default-hex.png" alt="Nathaniel" /></a>
</div>
<div class="col-xs-12 mobile" id="roleBarMobile">
<div class="hextopshift">
<a ui-sref="artist"><img class="roleIcon-hex" src="images/web-rdy_icons/artist-hex.png" alt="artist" /></a>
<a ui-sref="painter"><img class="roleIcon-hex" src="images/web-rdy_icons/painter-hex.png" alt="painter" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="photographer"><img class="roleIcon-hex" src="images/web-rdy_icons/photographer-hex.png" alt="photographer" /></a>
</div>
<div class="hextopshift">
<a ui-sref="graphic-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/graphic-designer-hex.png" alt="graphic-designer" /></a>
<a ui-sref="sound-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/sound-designer-hex.png" alt="sound-designer" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="musician"><img class="roleIcon-hex" src="images/web-rdy_icons/musician-hex.png" alt="musician" /></a>
</div>
<div class="hextopshift">
<a ui-sref="journalist"><img class="roleIcon-hex" src="images/web-rdy_icons/journalist-hex.png" alt="journalist" /></a>
<a ui-sref="world-historian"><img class="roleIcon-hex" src="images/web-rdy_icons/world-historian-hex.png" alt="world historian" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="political-economist"><img class="roleIcon-hex" src="images/web-rdy_icons/political-economist-hex.png" alt="political economist" /></a>
</div>
<div class="hextopshift">
<a ui-sref="social-activist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-activist-hex.png" alt="social activist" /></a>
<a ui-sref="social-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-scientist-hex.png" alt="social_scientist" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="comparative-institutionalist"><img class="roleIcon-hex" src="images/web-rdy_icons/comparative-institutionalist-hex.png" alt="comparative institutionalist"/></a>
</div>
<div class="hextopshift">
<a ui-sref="cultural-anthropologist"><img class="roleIcon-hex" src="images/web-rdy_icons/cultural-anthropologist-hex.png" alt="cultural_anthropologist" /></a>
<a ui-sref="linguist"><img class="roleIcon-hex" src="images/web-rdy_icons/linguist-hex.png" alt="linguist" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="computer-programmer"><img class="roleIcon-hex" src="images/web-rdy_icons/computer-programmer-hex.png" alt="computer_programmer" /></a>
</div>
<div class="hextopshift">
<a ui-sref="back-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/back-end-developer-hex.png" alt="back-end developer"/></a>
<a ui-sref="front-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/front-end-developer-hex.png" alt="front-end developer" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="natural-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/natural-scientist-hex.png" alt="natural_scientist" /></a>
</div>
<div class="hextopshift">
<a ui-sref="engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/engineer-hex.png" alt="engineer" /></a>
<a ui-sref="biologist"><img class="roleIcon-hex" src="images/web-rdy_icons/biologist-hex.png" alt="biologist" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="affective-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/affective-engineer-hex.png" alt="affective-engineer"/></a>
</div>
<div class="hextopshift">
<a ui-sref="software-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/software-engineer-hex.png" alt="software-engineer" /></a>
<a ui-sref="botanist"><img class="roleIcon-hex" src="images/web-rdy_icons/botanist-hex.png" alt="botanist" /></a>
</div>
<!--
<div class="hextopshift hexrightshift">
<a ui-sref="hardware-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/hardware-engineer-hex.png" alt="hardware-engineer" /></a>
<a ui-sref="chemist"><img class="roleIcon-hex" src="images/web-rdy_icons/chemist-hex.png" alt="chemist" /></a>
</div>
-->
</div>
<!-- Mobile above, desktop below -->
<div class="col-sm-12 col-lg-5 desktop" style="text-align: center; padding-bottom: 5%; padding-top: 6%;">
<a href="http://nathanielbuechler.com/"><img style="height: 320px; cursor: default;" onclick="alert('You found the secret!!')" src="images/default-hex.png" alt="Nathaniel" /></a>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-7 desktop" id="roleBarDesktop">
<div class="hextopshift">
<a ui-sref="artist"><img class="roleIcon-hex" src="images/web-rdy_icons/artist-hex.png" alt="artist" /></a>
<a ui-sref="painter"><img class="roleIcon-hex" src="images/web-rdy_icons/painter-hex.png" alt="painter" /></a>
<a ui-sref="photographer"><img class="roleIcon-hex" src="images/web-rdy_icons/photographer-hex.png" alt="photographer" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="graphic-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/graphic-designer-hex.png" alt="graphic-designer" /></a>
<a ui-sref="sound-designer"><img class="roleIcon-hex" src="images/web-rdy_icons/sound-designer-hex.png" alt="sound-designer" /></a>
</div>
<div class="hextopshift">
<a ui-sref="musician"><img class="roleIcon-hex" src="images/web-rdy_icons/musician-hex.png" alt="musician" /></a>
<a ui-sref="journalist"><img class="roleIcon-hex" src="images/web-rdy_icons/journalist-hex.png" alt="journalist" /></a>
<a ui-sref="world-historian"><img class="roleIcon-hex" src="images/web-rdy_icons/world-historian-hex.png" alt="world historian" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="political-economist"><img class="roleIcon-hex" src="images/web-rdy_icons/political-economist-hex.png" alt="political economist" /></a>
<a ui-sref="social-activist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-activist-hex.png" alt="social activist" /></a>
</div>
<div class="hextopshift">
<a ui-sref="social-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/social-scientist-hex.png" alt="social_scientist" /></a>
<a ui-sref="comparative-institutionalist"><img class="roleIcon-hex" src="images/web-rdy_icons/comparative-institutionalist-hex.png" alt="comparative institutionalist"/></a>
<a ui-sref="cultural-anthropologist"><img class="roleIcon-hex" src="images/web-rdy_icons/cultural-anthropologist-hex.png" alt="cultural_anthropologist" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="linguist"><img class="roleIcon-hex" src="images/web-rdy_icons/linguist-hex.png" alt="linguist" /></a>
<a ui-sref="computer-programmer"><img class="roleIcon-hex" src="images/web-rdy_icons/computer-programmer-hex.png" alt="computer_programmer" /></a>
</div>
<div class="hextopshift">
<a ui-sref="back-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/back-end-developer-hex.png" alt="back-end developer"/></a>
<a ui-sref="front-end-developer"><img class="roleIcon-hex" src="images/web-rdy_icons/front-end-developer-hex.png" alt="front-end developer" /></a>
<a ui-sref="natural-scientist"><img class="roleIcon-hex" src="images/web-rdy_icons/natural-scientist-hex.png" alt="natural_scientist" /></a>
</div>
<div class="hextopshift hexrightshift">
<a ui-sref="engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/engineer-hex.png" alt="engineer" /></a>
<a ui-sref="biologist"><img class="roleIcon-hex" src="images/web-rdy_icons/biologist-hex.png" alt="biologist" /></a>
</div>
<div class="hextopshift">
<a ui-sref="affective-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/affective-engineer-hex.png" alt="affective-engineer"/></a>
<a ui-sref="software-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/software-engineer-hex.png" alt="software-engineer" /></a>
<a ui-sref="botanist"><img class="roleIcon-hex" src="images/web-rdy_icons/botanist-hex.png" alt="botanist" /></a>
</div>
<!--
<div class="hextopshift hexrightshift">
<a ui-sref="hardware-engineer"><img class="roleIcon-hex" src="images/web-rdy_icons/hardware-engineer-hex.png" alt="hardware-engineer" /></a>
<a ui-sref="chemist"><img class="roleIcon-hex" src="images/web-rdy_icons/chemist-hex.png" alt="chemist" /></a>
</div>
-->
</div>
</div>
<br></br>
<div class="row">
<div class="col-12 col-sm-12 col-lg-12" style="text-align: center;">
<div class="panel panel-default">
<div class="panel-body">
<h2 style="text-align: center;"><strong>>30 Seconds</strong></h2>
<h6 style="text-align: center;"><i>About Me</i></h6>
<hr></hr>
<h6 style="text-align: center;">
A dream job would be working on trying to solve societal and institutional problems. For more information on that, consider reading <i><a style="color: #A1A1A1;" href="https://books.google.com/books/about/Philosophy_and_the_Social_Problem_Schola.html?id=pw48rgEACAAJ&hl=en">'Philosophy and the Social Problem'</a></i> by Will Durant. It's available for free on Google Books. If your familiar with some of these ideas, then you might become more aware of some of my personal motivations. If you aren't familiar, I can summarize my goals by stating that I'm interested in working on software that improves the emotional intelligence of people.
</h6>
<hr></hr>
<h6 style="text-align: center;">
In a technology sense, my latest intrigue is focused on the field of <i><a style="color: #A1A1A1;" href="https://en.wikipedia.org/wiki/Affective_computing">Affective Computing.</a></i> I'm learning Tensorflow and other machine learning tools as a way to get a working knowledge. Additionally, I am interested in more conventional programming languages, but my main expertise is actually in JavaScript. I have been considering the next wave of JavaScript, and React.js is where I am focusing my time.
</h6>
<hr></hr>
<h6 style="text-align: center;">
As for other technologies, I prefer using Flask and configuration based frameworks, but I am additionally looking into polyglot programming and polyglot persistence as it pertains to microservices. If you want more information on that, Google <i><a style="color: #A1A1A1;" href="http://lmgtfy.com/?q=Netflix+microservices">'Netflix microservices'</a></i> and the first few articles do a good job of explaining the concept. I try to continue learning tools and tech, so as time goes on, my interests will change.
</h6>
<hr></hr>
<h6 style="text-align: center;">
Lastly, I had some experience watching others program with iOS and Android, and I'm continuing to pay attention to the intersection of mobile and cloud computing. This is one area which is very nebulous to me, but I would be interested in discovering more about the 'Internet of Things' ecosystem. I've made a plan to begin experimenting with a Raspberry Pi, but haven't been able to do much with it.
</h6>
<hr></hr>
<h6>
<h5 class="well" style="text-align: center;"><strong>Still Interested?</strong> <a class="btn btn-md btn-default" href="/resume/Nathaniel_Buechler-Sr_UX_Engineer.pdf" style="color: white; margin: 10px;">Download my Résumé</a></h5>
</h6>
</div>
</div>
</div>
</div>
</div><!--/span-->
</div><!--/row-->
</div><!--/container-->
<div class="row jumbotron mainBKGD">
<div class="container">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Role Perspective</div>
<div class="panel-body">
<div id="roleFocus" class="well col-lg-3 col-md-12 col-sm-12" style="text-align: center; height: 420px">
<div style='margin-top: 80px'><span><img height="150" src="images/default-hex.png" alt="Nathaniel" /><br><h6 class="well">Multifaceted Specialist</h6></div>
</div>
<div class="col-lg-9 col-md-12 col-sm-12 content canvasHolderBkgd">
<div id="roleChart" style="font: white; text-align: center;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div ng-controller="homeController">
<div ui-view="artist"></div>
<div ui-view="social-scientist"></div>
<div ui-view="computer-programmer"></div>
<div ui-view="natural-scientist"></div>
<div ui-view="engineer"></div>
</div>
<div class="row jumbotron mainBKGD">
<div class="container">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Skill Perspective</div>
<div class="panel-body">
<div id="skillFocus" class="well col-lg-3 col-md-12 col-sm-12" style="text-align: center; height: 460px">
<div style='margin-top: 80px'><span><img height="150" src="images/default-hex.png" alt="Nathaniel" /><br><h6 class="well">Multifaceted Specialist</h6></div>
</div>
<div class="col-lg-9 col-md-12 col-sm-12 content canvasHolderBkgd">
<div id="navSunBurst" style="font: white; text-align: center;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row jumbotron mainBKGD">
<div class="container">
<div class="col-xs-12">
<div class="row">
<div class="col-12 col-sm-12 col-lg-12" style="text-align: center;">
<div class="panel panel-default">
<div class="panel-body">
<h2 style="text-align: center;"><strong>Software Documentation</strong></h2>
<h6 style="text-align: center;"><i>Project Notes from Nathaniel Buechler</i></h6>
<hr></hr>
<div class="well">
<div class="row">
<h6>Maybe one day, someone else will want to use some of my code, and I want to make it easier for them. Also, I want to make it easier for myself to use as a reference in the distant future.</h6>
<h6>Over 25 repositories are show on this site, but some of the projects more documented due to their importance and complexity. My hope is that this documentation makes it easier for you to understand the projects that I have created.</h6>
</div>
</div>
<hr></hr>
<h5 class="well" style="text-align: center;">
<a href="http://nathanielbuechler.io/" class="btn btn-default">
<i class="fa fa-book fa-2x"
aria-hidden="true"
style="vertical-align: middle;"></i>
<span style="display: inline-block; vertical-align: middle;">
View the project documentation
</span>
</a>
</h5>
</div>
</div>
</div>
</div>
</div><!--/span-->
</div><!--/row-->
</div><!--/container-->
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">
<div class="row">
<div class="col-12 col-sm-12 col-lg-12" style="text-align: center;">
<div class="panel panel-default">
<div class="panel-body">
<h2 style="text-align: center;"><strong>Recap</strong></h2>
<h6 style="text-align: center;"><i>Roles of this Multifaceted Specialist</i></h6>
<hr></hr>
<div class="well">
<div class="row">
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="affective-engineer">Affective Engineer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="artist">Artist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="back-end-developer">Back-End Developer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="biologist">Biologist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="botanist">Botanist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="comparative-institutionalist">Comparative Institutionalist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="computer-programmer">Computer Programmer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="cultural-anthropologist">Cultural Anthropologist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="engineer">Engineer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="front-end-developer">Front-End Developer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="graphic-designer">Graphic Designer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="journalist">Journalist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="linguist">Linguist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="musician">Musician</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="natural-scientist">Natural Scientist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="painter">Painter</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="photographer">Photographer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="political-economist">Political Economist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="social-activist">Social Activist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="social-scientist">Social Scientist</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="software-engineer">Software Engineer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="sound-designer">Sound Designer</a>
<a class="col-xs-12 col-sm-12 col-md-6 col-lg-3" style="text-align: center; color: white;" ui-sref="world-historian">World Historian</a>
</div>
</div>
<hr></hr>
<h5 class="well" style="text-align: center;">
<a class="btn btn-default" href="https://github.com/nbuechler"><i class="fa fa-2x fa-github"></i></a>
<a class="btn btn-default" href="https://www.linkedin.com/in/nathaniel-buechler-87a29226"><i class="fa fa-2x fa-linkedin-square"></i></a>
<a class="btn btn-default" href="mailto:[email protected]?Subject=Hello%20Nathaniel"><i class="fa fa-2x fa-envelope"></i></a>
<a class="btn btn-default" href="/resume/Nathaniel_Buechler-Sr_Software_Engineer.pdf"><i class="fa fa-2x fa-file-text"></i></a>
</h5>
</div>
</div>
</div>
</div>
</div><!--/span-->
</div><!--/row-->
</div><!--/container-->
<!--d3, application JavaScript Files-->
<script type="text/javascript" src="js/d3-charts/roleTimeline.js"></script>
<script type="text/javascript" src="js/d3-charts/skillBurst.js"></script>
| nbuechler/nb.com-v8 | views/home.html | HTML | gpl-3.0 | 23,965 |
.PHONY: all help build run builddocker rundocker kill rm-image rm clean enter logs
all: help
help:
@echo ""
@echo "-- Help Menu"
@echo "" This is merely a base image for usage read the README file
@echo "" 1. make run - build and run docker container
@echo "" 2. make build - build docker container
@echo "" 3. make clean - kill and remove docker container
@echo "" 4. make enter - execute an interactive bash in docker container
@echo "" 3. make logs - follow the logs of docker container
build: NAME TAG builddocker
# run a plain container
run: TZ PORT LOGDIR DATADIR rundocker
prod: run
temp: init
init: DATADIR TZ PORT config pull initdocker
auto: init next
initdocker:
$(eval TMP := $(shell mktemp -d --suffix=DOCKERTMP))
$(eval NAME := $(shell cat NAME))
$(eval PORT := $(shell cat PORT))
$(eval TAG := $(shell cat TAG))
$(eval DOMOTICZ_OPTS := $(shell cat DOMOTICZ_OPTS))
$(eval TZ := $(shell cat TZ))
chmod 777 $(TMP)
@docker run --name=$(NAME)-init \
--cidfile="cid" \
-e TZ=$(TZ) \
-e DOMOTICZ_OPTS=$(DOMOTICZ_OPTS) \
-v $(TMP):/tmp \
--device=/dev/ttyUSB0 \
--device=/dev/pts/0 \
--privileged \
--device=/dev/ttyUSB0 \
--device=/dev/pts/0 \
-d \
-p $(PORT):8080 \
-t $(TAG)
debugdocker:
$(eval TMP := $(shell mktemp -d --suffix=DOCKERTMP))
$(eval NAME := $(shell cat NAME))
$(eval PORT := $(shell cat PORT))
$(eval TAG := $(shell cat TAG))
$(eval DOMOTICZ_OPTS := $(shell cat DOMOTICZ_OPTS))
$(eval TZ := $(shell cat TZ))
chmod 777 $(TMP)
@docker run --name=$(NAME)-init \
--cidfile="cid" \
-e TZ=$(TZ) \
-e DOMOTICZ_OPTS=$(DOMOTICZ_OPTS) \
-v $(TMP):/tmp \
--privileged \
--device=/dev/ttyUSB0 \
--device=/dev/pts/0 \
-d \
-p $(PORT):8080 \
-t $(TAG) /bin/bash
rundocker:
$(eval TMP := $(shell mktemp -d --suffix=DOCKERTMP))
$(eval NAME := $(shell cat NAME))
$(eval TZ := $(shell cat TZ))
$(eval DOMOTICZ_OPTS := $(shell cat DOMOTICZ_OPTS))
$(eval DATADIR := $(shell cat DATADIR))
$(eval LOGDIR := $(shell cat LOGDIR))
$(eval PORT := $(shell cat PORT))
$(eval TAG := $(shell cat TAG))
chmod 777 $(TMP)
@docker run --name=$(NAME) \
--cidfile="cid" \
-v $(TMP):/tmp \
-e TZ=$(TZ) \
-e DOMOTICZ_OPTS=$(DOMOTICZ_OPTS) \
--privileged \
-d \
--device=/dev/ttyUSB0 \
--device=/dev/pts/0 \
-p $(PORT):8080 \
-v $(DATADIR)/config:/config \
-v $(LOGDIR)/log:/log \
-t $(TAG)
builddocker:
docker build -t `cat TAG` .
kill:
-@docker kill `cat cid`
rm-image:
-@docker rm `cat cid`
-@rm cid
rm: kill rm-image
clean: rm
enter:
docker exec -i -t `cat cid` /bin/bash
logs:
docker logs -f `cat cid`
rmall: rm
config: datadir/domoticz.db
datadir/domoticz.db:
tar jxvf domoticz.db.tz2
mkdir -p datadir
mv domoticz.db datadir/
TZ:
@while [ -z "$$TZ" ]; do \
read -r -p "Enter the timezone you wish to associate with this container [America/Denver]: " TZ; echo "$$TZ">>TZ; cat TZ; \
done ;
DOMOTICZ_OPTS:
@while [ -z "$$DOMOTICZ_OPTS" ]; do \
read -r -p "Enter the domoticz options you wish to associate with this container: " DOMOTICZ_OPTS; echo "$$DOMOTICZ_OPTS">>DOMOTICZ_OPTS; cat DOMOTICZ_OPTS; \
done ;
PORT:
@while [ -z "$$PORT" ]; do \
read -r -p "Enter the port you wish to associate with this container [PORT]: " PORT; echo "$$PORT">>PORT; cat PORT; \
done ;
LOGDIR:
@while [ -z "$$LOGDIR" ]; do \
read -r -p "Enter the datadir you wish to associate with this container (i.e. /exports/mkdomoticz) [LOGDIR]: " LOGDIR; echo "$$LOGDIR">>LOGDIR; cat LOGDIR; \
done ;
DATADIR:
@while [ -z "$$DATADIR" ]; do \
read -r -p "Enter the datadir you wish to associate with this container (i.e. /exports/mkdomoticz) [DATADIR]: " DATADIR; echo "$$DATADIR">>DATADIR; cat DATADIR; \
done ;
REGISTRY:
@while [ -z "$$REGISTRY" ]; do \
read -r -p "Enter the registry you wish to associate with this container [REGISTRY]: " REGISTRY; echo "$$REGISTRY">>REGISTRY; cat REGISTRY; \
done ;
REGISTRY_PORT:
@while [ -z "$$REGISTRY_PORT" ]; do \
read -r -p "Enter the port of the registry you wish to associate with this container, usually 5000 [REGISTRY_PORT]: " REGISTRY_PORT; echo "$$REGISTRY_PORT">>REGISTRY_PORT; cat REGISTRY_PORT; \
done ;
grab: DATADIR GRABDATADIR
GRABDATADIR:
-@mkdir -p datadir/domoticz
docker cp `cat cid`:/config - |sudo tar -C datadir/ -pxf -
push: TAG REGISTRY REGISTRY_PORT
$(eval TAG := $(shell cat TAG))
$(eval REGISTRY := $(shell cat REGISTRY))
$(eval REGISTRY_PORT := $(shell cat REGISTRY_PORT))
docker tag $(TAG) $(REGISTRY):$(REGISTRY_PORT)/$(TAG)
docker push $(REGISTRY):$(REGISTRY_PORT)/$(TAG)
pull:
docker pull `cat TAG`
next: waitforport grab clean place run
place:
$(eval DATADIR := $(shell cat DATADIR))
mkdir -p $(DATADIR)
sudo mv datadir $(DATADIR)/
echo "$(DATADIR)/datadir" > DATADIR
sync
@echo "Moved datadir to $(DATADIR)"
waitforport:
$(eval PORT := $(shell cat PORT))
@echo "Waiting for port to become available"
@while ! curl --output /dev/null --silent --head --fail http://127.0.0.1:$(PORT); do sleep 10 && echo -n .; done;
@echo "check port $(PORT), it appears that now it is up!"
| joshuacox/mkdomoticz | Makefile | Makefile | gpl-3.0 | 5,104 |
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="assets/style.css"></link>
</head>
<body>
<div class="content">
<h1><a href="page_rationale.html"><span class="mute">wi</span><span class="bright">doh</span></a></h1>
<ul class="menu">
<li><a href="list_persons.html">People</a></li>
<li><a href="list_projects.html">Projects</a></li>
<li><a href="page_rationale.html">Rationale</a></li>
<li><a href="page_index.html">About</a></li>
</ul>
<div class="page">
<div>
<h2>2008-11-17</h2>
<p>
<p><a href="project_bjax.html">BJax - javascript for managers</a></p>
<p><a href="project_geodevice.html">Geographical Tracking Device</a></p>
<p><a href="project_hillsearch.html">Paragliding Hill Gazetteer</a></p>
<p><a href="project_trainclock.html">Train Clock</a></p>
</p>
</div>
<div>
<h2>2008-11-10</h2>
<p>
<p><a href="project_foleyfeet.html">Foley Footsteps</a></p>
<p><a href="project_onepixelwebcam.html">One Pixel Webcam</a></p>
<p><a href="project_semaphoresms.html">Semaphore to SMS Gateway</a></p>
<p><a href="project_trainmodelling.html">Statistical Distributions of Train Delays</a></p>
</p>
</div>
</div>
<div class="menu">
<div>
<h2>Widoh Projects</h2>
<p>Whatever the technology project, the more playful the better. No business cases required.</p>
</div>
</div>
<div class="footer">
CSS copyright: © 2008, Cefn Hoile, inspired by Adam Particka's orangray.
</div>
</div>
</body>
</html> | cefn/allyourx | allyourx/xq/result/list_projects.html | HTML | gpl-3.0 | 2,095 |
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//
// BSRunKeeperLoginSegue.h
// BeSport Mobile
//
// Created by François-Xavier Thomas on 5/18/12.
// Copyright (c) 2012 BeSport. All rights reserved.
//
#import "BSLoginSegue.h"
@interface BSRunKeeperLoginSegue : BSLoginSegue
@end
| besport/BSLoginServices | Vendor/BSLoginServices/BSRunKeeperLoginSegue.h | C | gpl-3.0 | 917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.