code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
namespace Delr3ves\RestApiBundle\Tests\Unit\Unmarshalling;
use Delr3ves\RestApiBundle\Unmarshalling\ContentTypeUtils;
use Delr3ves\RestApiBundle\Unmarshalling\FormatNotSupportedException;
class ContentTypeUtilsTest extends \PHPUnit_Framework_TestCase {
/**
* @var ContentTypeUtils
*/
protected $contentTypeUtils;
public function setUp() {
$this->contentTypeUtils = new ContentTypeUtils();
}
/**
* @dataProvider getValidNormalizedContentTypeProvider
*/
public function testNormalizeContentTypeShouldReturnType($providedContentType, $expectedType) {
$normalizedFormat = $this->contentTypeUtils->normalize($providedContentType);
$this->assertThat($normalizedFormat, $this->equalTo($expectedType));
}
/**
* @expectedException Delr3ves\RestApiBundle\Unmarshalling\FormatNotSupportedException
*/
public function testNormalizeContentTypeShouldThrowException() {
$this->contentTypeUtils->normalize('invalidContentType');
}
/**
* @dataProvider getValidAcceptContentTypeProvider
*/
public function testGetAcceptContentTypeShouldReturnType($providedContentType, $expectedType) {
$normalizedFormat = $this->contentTypeUtils->findAcceptType($providedContentType);
$this->assertThat($normalizedFormat, $this->equalTo($expectedType));
}
public static function getValidNormalizedContentTypeProvider() {
return array(
array(ContentTypeUtils::SIMPLE_JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::SIMPLE_XML_FORMAT, ContentTypeUtils::XML_FORMAT),
array(ContentTypeUtils::XML_FORMAT, ContentTypeUtils::XML_FORMAT),
);
}
public static function getValidAcceptContentTypeProvider() {
return array(
array("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "application/xml"),
array(ContentTypeUtils::SIMPLE_JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::JSON_FORMAT, ContentTypeUtils::JSON_FORMAT),
array(ContentTypeUtils::SIMPLE_XML_FORMAT, ContentTypeUtils::XML_FORMAT),
array(ContentTypeUtils::XML_FORMAT, ContentTypeUtils::XML_FORMAT),
);
}
}
| delr3ves/SymfonyRestApiBundle | Tests/Unit/Unmarshalling/ContentTypeUtilsTest.php | PHP | mit | 2,368 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dona.Forms.Dependencies
{
public interface INetworkInformation
{
string GetNetworkOperatorName();
}
}
| MartinGian/dona | Portable/Dependencies/INetworkInformation.cs | C# | mit | 252 |
<!DOCTYPE html>
<!--[if IE 6]> <html id="ie ie67 ie6" dir="ltr" lang="en-US"> <![endif]-->
<!--[if IE 7]> <html id="ie ie67 ie7" dir="ltr" lang="en-US"> <![endif]-->
<!--[if IE 8]> <html id="ie ie678 ie8" dir="ltr" lang="en-US"> <![endif]-->
<!--[if !(IE 6) | !(IE 7) | !(IE 8) ]><!--> <html dir="ltr" lang="en-US"> <!--<![endif]-->
<head>
<title>Crossings Community Church</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
</head>
<body>
<div id="container">
<div id="header">
<!-- <h1><a href="http://crossingscommunity.com/"><span class="hide">Crossings Community Church</span></a></h1> -->
</div>
<div id="nav">
<ul>
<li id="about"><a href="/about.php">About Crossings</a></li>
<li id="sermons"><a href="sermons/">Sermons</a></li>
<li id="sermons"><a href="songs.php">Songs</a></li>
<li id="critter"><a href="critter-crossings.php">Critter Crossings</a></li>
<li id="members"><a href="members.php">Members</a></li>
<li id="week"><a href="restofweek.php">Rest of Week</a></li>
<li id="contact"><a href="contact.php">Contact Us</a></li>
</ul>
</div>
<div id="content">
<div id="content-contain">
<object type="text/html" data="ccc-rss.html">
<div id="right-col" class="column">
<h2>What's Happening</h2>
<div class="block">
<p class="quiet">Meeting Wednesdays and Fridays</p>
<h4>Bible Study</h4>
<p>Watch your email for which group you'll be in.</p>
</div>
<div class="block">
<p class="quiet">October 23-26, 2008</p>
<h4>Annual Crossings Retreat</h4>
<p>Stay tuned for details!</p>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
1 West Campbell Avenue, Campbell, CA 95008 - Sundays @ 10am. Join us for set-up and fellowship @ 9am
</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-2468518-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
| Southbay-CityChurch/crossings-community | index2.php | PHP | mit | 2,438 |
#!/usr/bin/php -q
<?php
/*
The MIT License (MIT)
Copyright (c) 2015 Gary Smart www.smart-itc.com.au
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Parts of this script were inspired from jared@osTicket.com / ntozier@osTicket / tmib.net (http://tmib.net/using-osticket-1812-api)
*/
$settings = array(
'dbHost' => 'localhost',
'dbTable' => 'ost.ost_faq', // Database.Table where FAQs are stored.
'dbUser' => 'root',
'dbPass' => '',
'categoryId' => 16, // The Category ID where Automator tickete FAQs are kept
'topicId' => 8, // Created tickets are assigned to this topic.
'subjectPrefix' => '[',
'subjectSuffix' => ']',
'reporterEmail' => 'automator@domain.com',
'reporterName' => 'Automator',
'apiURL' => 'http://ost.domain.com/api/http.php/tickets.json',
'apiKey' => 'your-api-key'
);
if (!isset($settings)) {
die ('$settings is not set. Aborting.');
}
$period = isset($argv[1]) ? $argv[1] : "daily";
$tks = findTicketsToCreate($period);
foreach($tks as $t) {
createTicket($t->subject, $t->message);
}
// $period to match FAQ Question field.
function findTicketsToCreate($period = "daily") {
global $settings;
$link = mysql_connect($settings['dbHost'], $settings['dbUser'], $settings['dbPass']);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql_query = "select faq_id, answer from " . $settings['dbTable'] . " WHERE category_id=" . $settings['categoryId'] . " AND UPPER(question) LIKE UPPER('%$period%')";
$sql_result = mysql_query($sql_query, $link);
$rowsFound = false;
$results = array();
while ($row = mysql_fetch_array($sql_result,MYSQL_ASSOC)) {
$rowsFound = true;
$lines = explode("\n", trim(br2nl($row['answer']))) ;
foreach($lines as $line) {
$line = trim($line);
// Skip empty lines or lines starting with a comment (-- or #)
if (empty($line) || (strpos($line, "--") === 0) || (strpos($line, "#") === 0)) {
continue;
}
$subject = $line;
$message = null;
if (strpos($line, "|") !== FALSE) {
list($subject, $message) = explode("|", $line);
}
$subject = decode($subject);
$message = decode($message);
if (empty($message)) {
$message = $subject;
}
$tmp = new stdClass();
$tmp->faqId = $row['faq_id'];
$tmp->subject = $subject;
$tmp->message = $message . "\n\nPeriod: $period";
$results[] = $tmp;
}
}
mysql_free_result($sql_result);
mysql_close($link);
if (!$rowsFound) {
$msg = "Automator called for Period '$period' but found no tickets to create";
echo $msg . "\n";
createTicket($msg);
}
return $results;
} // findTicketsToCreate()
function createTicket($subject, $message = null) {
global $settings;
$topicId = $settings['topicId'];
$reporterEmail = $settings['reporterEmail'];
$reporterName = $settings['reporterName'];
$reporterIP = gethostbyname(gethostname());
if (empty($subject)) {
echo ("No Subject provided. Not creating ticket.\n");
return false;
};
if (empty($message)) {
$message = $subject;
}
$subject = $settings['subjectPrefix'] . $subject . $settings['subjectSuffix'];
$data = array(
'name' => $reporterName,
'email' => $reporterEmail,
'phone' => '',
'subject' => $subject,
'message' => $message,
'ip' => $reporterIP,
'topicId' => $topicId
);
function_exists('curl_version') or die('CURL support required');
function_exists('json_encode') or die('JSON support required');
set_time_limit(30);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $settings['apiURL']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_USERAGENT, 'osTicket API Client v1.8');
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Expect:', 'X-API-Key: '.$settings['apiKey']));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result=curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code != 201) {
echo "Unable to create ticket with subject $subject: " .$result . "\n";
return false;
}
$ticketId = (int)$result;
echo "Ticket '$subject' created with id $ticketId\n";
return $ticketId;
} // createTicket()
function br2nl($string) {
return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
}
function decode($s) {
if (empty($s)) {
return $s;
}
$s = str_ireplace(" ", " ", $s);
return trim($s);
}
| garyns/osTicket-extensions | automator/createTicketPeriod.php | PHP | mit | 5,765 |
<?php
namespace Recurrence\Validator;
use Recurrence\Model\Frequency;
use Recurrence\Model\Recurrence;
use Recurrence\Constraint\ProviderConstraint\EndOfMonthConstraint;
use Recurrence\Model\Exception\InvalidRecurrenceException;
/**
* Class RecurrenceValidator
* @package Recurrence\Validator
*/
class RecurrenceValidator
{
/**
* @param Recurrence $recurrence
* @throws InvalidRecurrenceException
* @return bool
*/
public static function validate(Recurrence $recurrence)
{
if (!$recurrence->getFrequency()) {
throw new InvalidRecurrenceException('Frequency is required');
}
if ($recurrence->hasCount() && $recurrence->getPeriodEndAt()) {
throw new InvalidRecurrenceException('Recurrence cannot have [COUNT] and [UNTIL] option at the same time');
}
if (!$recurrence->hasCount() && !$recurrence->getPeriodEndAt()) {
throw new InvalidRecurrenceException('Recurrence required [COUNT] or [UNTIL] option');
}
if ($recurrence->hasConstraint(EndOfMonthConstraint::class) && (string) $recurrence->getFrequency() != Frequency::FREQUENCY_MONTHLY) {
throw new InvalidRecurrenceException('End of month constraint can be applied only with monthly frequency');
}
return true;
}
}
| Samffy/recurrence | src/Recurrence/Validator/RecurrenceValidator.php | PHP | mit | 1,331 |
import React from 'react';
import Tap from '../hahoo/Tap';
class BtnUpLevel extends React.Component {
static propTypes = {
onItemClick: React.PropTypes.func
}
state = {}
render() {
const { onItemClick, ...rest } = this.props;
return (<Tap
onTap={onItemClick}
className="btn btn-default"
{...rest}
><i className="fa fa-arrow-circle-up fa-fw" /> 上级</Tap>);
}
}
export default BtnUpLevel;
| hahoocn/hahoo-admin | src/components/Btns/BtnUpLevel.js | JavaScript | mit | 439 |
package org.openforis.collect.web.manager;
import java.util.HashMap;
import java.util.Map;
import org.openforis.collect.manager.CachedRecordProvider;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectRecord.Step;
import org.openforis.collect.model.CollectSurvey;
public class SessionRecordProvider extends CachedRecordProvider {
private CachedRecordProvider delegate;
private Map<Integer, CollectRecord> recordsPreviewBySurvey = new HashMap<Integer, CollectRecord>();
public SessionRecordProvider(CachedRecordProvider cachedRecordProvider) {
super(null);
this.delegate = cachedRecordProvider;
}
@Override
public CollectRecord provide(CollectSurvey survey, Integer recordId, Step recordStep) {
if (recordId == null) {
// Preview record
return this.recordsPreviewBySurvey.get(survey.getId());
} else {
return delegate.provide(survey, recordId, recordStep);
}
}
public void putRecord(CollectRecord record) {
if (record.isPreview()) {
this.recordsPreviewBySurvey.put(record.getSurvey().getId(), record);
} else {
delegate.putRecord(record);
}
}
@Override
public void clearRecords(int surveyId) {
delegate.clearRecords(surveyId);
this.recordsPreviewBySurvey.remove(surveyId);
}
}
| openforis/collect | collect-server/src/main/java/org/openforis/collect/web/manager/SessionRecordProvider.java | Java | mit | 1,273 |
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
var _graphqlRelay = require("graphql-relay");
var _EnsayoType = _interopRequireDefault(require("./EnsayoType"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _default =
(0, _graphqlRelay.connectionDefinitions)({
name: 'Ensayos',
nodeType: _EnsayoType.default });exports.default = _default;
//# sourceMappingURL=EnsayosConnection.js.map | codefoundries/UniversalRelayBoilerplate | deployment/units/rb-example-ensayo-server/graphql/type/EnsayosConnection.js | JavaScript | mit | 494 |
<?php
class Controller
{
private $project;
private $request;
private $response;
private $user;
private $template_engine;
public function __construct(BaseProject $project, Request $request=null)
{
$this->project = $project;
$this->request = $request;
}
public function getActionName($action)
{
return $action . 'Action';
}
public function action($action, $parameters=null)
{
$method = $this->getActionName($action);
if (!method_exists($this, $method))
throw new NotFoundException('Action not found: ' . $method);
$response = $this->getResponse();
if ($this->preExecute()===false) return $response;
$actionResult = $this->$method($parameters);
if ($actionResult) $response->setContent($actionResult);
$this->postExecute();
return $response;
}
public function preExecute(){}
public function postExecute(){}
public function getRequest()
{
if (!$this->request)
$this->request = new Request();
return $this->request;
}
public function getRequestParameter($parameter)
{
return $this->getRequest()->getParameter($parameter);
}
public function getResponse()
{
if (!$this->response)
$this->response = new Response();
return $this->response;
}
public function getTemplateDirectories()
{
return $this->getProject()->getTemplateDirectories();
}
public function prepareTemplateEngine()
{
$loader = new sfTemplateLoaderFilesystem($this->getTemplateDirectories());
$template_engine = new TemplateEngine($loader);
$helperSet = new sfTemplateHelperSet(array(new sfTemplateHelperAssets(), new sfTemplateHelperJavascripts(), new sfTemplateHelperStylesheets(), new ProjectHelper($this->getProject()), new RoutingHelper($this->getRequest()), new UserHelper($this->getUser())));
$template_engine->setHelperSet($helperSet);
return $template_engine;
}
public function getTemplateEngine()
{
if (!$this->template_engine){
$this->template_engine = $this->prepareTemplateEngine();
}
return $this->template_engine;
}
public function getTemplateVariables()
{
return array();
}
public function getProject()
{
return $this->project;
}
public function getUser()
{
if (!$this->user){
$this->user = new User();
}
return $this->user;
}
public function isAuthenticated()
{
return $this->getUser()->isAuthenticated();
}
public function getProjectName()
{
return $this->getProject()->getName();
}
public function render($template, $vars=array())
{
//TODO: check:
$vars = array_merge($vars, $this->getTemplateVariables());
$this->getTemplateEngine()->setParameters($vars);
return $this->getTemplateEngine()->render($template, $vars);
}
public function forward($controller_name, $action_name)
{
$current_controller = get_class($this);
if ($current_controller == $controller_name.'Controller'){
$action = $action_name . 'Action';
return $this->$action();
}
//TODO: needs fixing - since the new controller works in its own domain and doesn't effect the current User or Response.
return $this->getProject()->loadAction($controller_name, $action_name, $this->request);
}
public function redirect($url, $status=302)
{
$response = $this->getResponse();
$response->setStatusCode($status);
$response->setHeader('Location', $this->getRequest()->getScriptName() .$url);
}
public function getPagesCacheManager()
{
return $this->getProject()->getPagesCacheManager();
}
public function getSiteConfiguration()
{
return $this->getProject()->getSiteConfiguration();
}
}
?> | iamkoby/muesli | Muesli/Lib/Muesli/Controller/Controller.php | PHP | mit | 3,549 |
class AddObserveIdFromPeriods < ActiveRecord::Migration
def change
add_reference :periods, :user, index: true
end
end
| gurujowa/rails-simple-crm | db/old_migrate/2014/20140512073938_add_observe_id_from_periods.rb | Ruby | mit | 126 |
namespace GridCity.Fields.Buildings {
using System;
using System.Collections.Generic;
using People;
internal class WorkBuilding : OccupationalBuilding {
//---------------------------------------------------------------------
// Constructors
//---------------------------------------------------------------------
public WorkBuilding(string name, Utility.GlobalCoordinate pos, Pathfinding.BaseNodeLayout layout, Orientation_CW orientation, Dictionary<Resident.Type, uint> jobs, Tuple<uint, uint> size) : base(name, pos, layout, orientation, jobs, size) {
}
}
}
| gartenriese2/GridCity | GridCity/Fields/Buildings/WorkBuilding.cs | C# | mit | 626 |
<?php use_stylesheets_for_form($form) ?>
<?php use_javascripts_for_form($form) ?>
<div class="sf_admin_form">
<?php echo form_tag_for($form, '@jt_users') ?>
<?php echo $form->renderHiddenFields(false) ?>
<?php if ($form->hasGlobalErrors()): ?>
<?php echo $form->renderGlobalErrors() ?>
<?php endif; ?>
<?php foreach ($configuration->getFormFields($form, $form->isNew() ? 'new' : 'edit') as $fieldset => $fields): ?>
<?php include_partial('jt_users/form_fieldset', array('jtusers' => $jtusers, 'form' => $form, 'fields' => $fields, 'fieldset' => $fieldset)) ?>
<?php endforeach; ?>
<?php include_partial('jt_users/form_actions', array('jtusers' => $jtusers, 'form' => $form, 'configuration' => $configuration, 'helper' => $helper)) ?>
</form>
</div>
| jtarleton/jt-web | cache/front/dev/modules/autoJt_users/templates/_form.php | PHP | mit | 793 |
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def rssToEstimatedDistance(rss):
freq = 2462 # freq of WiFi channel 6
origDBm = -20 # estimate this value
loss = abs(origDBm - rss)
dist = 10 ** ( ( loss + 27.55 - 20 * math.log10(freq) ) / 20 )
return dist
def trilaterate(inSources, rss):
distances = []
distances.append( rssToEstimatedDistance(rss[0]) )
distances.append( rssToEstimatedDistance(rss[1]) )
distances.append( rssToEstimatedDistance(rss[2]) )
# find the three intersection points
tp1 = _findEqualPerp(inSources[0], inSources[1], distances[0], distances[1])
tp2 = _findEqualPerp(inSources[0], inSources[2], distances[0], distances[2])
tp3 = _findEqualPerp(inSources[1], inSources[2], distances[1], distances[2])
p = Point( (tp1.x + tp2.x + tp3.x) / 3, (tp1.y + tp2.y + tp3.y) / 3 )
return p
def _findEqualPerp(p1, p2, r1, r2):
# swap points if p2 is behind p2
if p2.x < p1.x:
temp = p2
p2 = p1
p1 = temp
# compute the equation for the line
deltaX = p2.x - p1.x
deltaY = p2.y - p1.y
if deltaX == 0:
slope = 999999999
else:
slope = deltaY / deltaX
intercept = p2.y - slope * p2.x
# compute the constant multiplier
lineLen = math.sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)
c = lineLen / (r1 + r2)
posOnLine = c * r1
angle = math.atan(slope)
touchingPoint = Point(math.cos(angle) * posOnLine + p1.x, math.sin(angle) * posOnLine + p1.y)
return touchingPoint
# test program
def main():
a = Point(1, 6)
b = Point(2, 3)
c = Point(5, 7)
t = trilaterate([a,b,c], [2,3,5])
print(t.x)
print(t.y)
if __name__ == '__main__':
main()
| DepthDeluxe/dot11sniffer | app/Trilateration_Colin.py | Python | mit | 1,799 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitfbfcde531df662d1e2394a96c22298b7::getLoader();
| bssamkah/agance | vendor/autoload.php | PHP | mit | 183 |
package _04MordorsCrueltyPlan;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Wizard {
private static final Map<String, Integer> FOODS = new HashMap<String, Integer>() {{
put("cram", 2);
put("lembas", 3);
put("apple", 1);
put("melon", 1);
put("honeycake", 5);
put("mushrooms", -10);
}};
public int getHappinessIndex() {
return this.happinessIndex;
}
private int happinessIndex;
public void setHappinessIndex(List<String> foods) {
foods.forEach(this::eatFood);
}
public String getMood() {
if (this.happinessIndex < -5) {
return "Angry";
} else if (this.happinessIndex <= 0) {
return "Sad";
} else if (this.happinessIndex <= 15) {
return "Happy";
} else {
return "JavaScript";
}
}
private void eatFood(String food) {
String foodLowerName = food.toLowerCase();
if (FOODS.containsKey(foodLowerName)) {
this.happinessIndex += FOODS.get(foodLowerName);
} else {
this.happinessIndex -= 1;
}
}
}
| yangra/SoftUni | JavaFundamentals/JavaOOPBasic/03.InheritanceExercise/src/_04MordorsCrueltyPlan/Wizard.java | Java | mit | 1,184 |
import { Behavior } from '@aelea/core'
import { $text, component, style } from '@aelea/dom'
import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components'
import { pallete } from '@aelea/ui-components-theme'
import { at, debounce, empty, join, map, merge, now, snapshot, startWith, switchLatest } from '@most/core'
import { Stream } from '@most/types'
function filterArrayByText(array: string[], filter: string) {
const filterLowercase = filter.toLocaleLowerCase()
return array.filter(id =>
id.indexOf(filterLowercase) > -1
)
}
const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)(
$text(style({ color: pallete.foreground }))(label),
$text(value)
)
export const $VirtualScrollExample = component((
[scrollRequest, scrollRequestTether]: Behavior<ScrollRequest, ScrollRequest>,
[delayResponse, delayResponseTether]: Behavior<string, number>,
[filter, filterTether]: Behavior<string, string>,
) => {
const PAGE_SIZE = 25
const TOTAL_ITEMS = 1000
const formatNumber = Intl.NumberFormat().format
const initialDelayResponse = now(1600)
const delayWithInitial = merge(initialDelayResponse, delayResponse)
let i = 0
const $item = $text(style({ padding: '3px 10px' }))
const stubbedData = Array(TOTAL_ITEMS).fill(null).map(() =>
`item: ${Math.random().toString(36).substring(7)} ${formatNumber(++i)}`
)
const dataSourceFilter = (filter: string) => join(
snapshot((delay, requestNumber): Stream<ScrollResponse> => {
const pageStart = requestNumber * PAGE_SIZE
const pageEnd = pageStart + PAGE_SIZE
const filteredItems = filterArrayByText(stubbedData, filter)
const $items = filteredItems.slice(pageStart, pageEnd).map(id => {
return $item(id)
})
return at(delay, { $items: $items, offset: 0, pageSize: PAGE_SIZE })
}, delayWithInitial, scrollRequest)
)
const filterText = startWith('', filter)
const debouncedFilterText = debounce(300, filterText)
return [
$column(layoutSheet.spacingBig)(
$text(`High performance dynamically loaded list based on Intersection Observer Web API. this example shows a very common pagination and REST like fetching asynchnously more pages`),
$row(layoutSheet.spacingBig)(
$label('Page: ', map(l => String(l), scrollRequest)),
$label(`Page Size:`, String(PAGE_SIZE)),
$label(`Total Items:`, String(TOTAL_ITEMS)),
),
$row(layoutSheet.spacingBig)(
$TextField({
label: 'Filter',
value: empty(),
hint: 'Remove any items that does not match filter and debounce changes by 300ms to prevert spamming',
containerOp: layoutSheet.flex
})({
change: filterTether()
}),
$TextField({
label: 'Delay Response(ms)',
value: initialDelayResponse,
hint: 'Emulate the duration of a datasource response, show a stubbed $node instead',
containerOp: layoutSheet.flex
})({
change: delayResponseTether(
map(Number)
)
}),
),
$seperator,
$card(style({ padding: 0 }))(
switchLatest(
map(searchText =>
$VirtualScroll({
dataSource: dataSourceFilter(searchText),
containerOps: style({ padding: '8px', maxHeight: '400px' })
})({
scrollIndex: scrollRequestTether(),
})
, debouncedFilterText)
)
)
)
]
})
| nissoh/fufu | website/src/pages/examples/virtual-scroll/$VirtualScrollExample.ts | TypeScript | mit | 3,616 |
/**
* Lawnchair!
* ---
* clientside json store
*
*/
var Lawnchair = function () {
// lawnchair requires json
if (!JSON) throw 'JSON unavailable! Include http://www.json.org/json2.js to fix.'
// options are optional; callback is not
if (arguments.length <= 2 && arguments.length > 0) {
var callback = (typeof arguments[0] === 'function') ? arguments[0] : arguments[1]
, options = (typeof arguments[0] === 'function') ? {} : arguments[0]
} else {
throw 'Incorrect # of ctor args!'
}
if (typeof callback !== 'function') throw 'No callback was provided';
// default configuration
this.record = options.record || 'record' // default for records
this.name = options.name || 'records' // default name for underlying store
// mixin first valid adapter
var adapter
// if the adapter is passed in we try to load that only
if (options.adapter) {
adapter = Lawnchair.adapters[Lawnchair.adapters.indexOf(options.adapter)]
adapter = adapter.valid() ? adapter : undefined
// otherwise find the first valid adapter for this env
} else {
for (var i = 0, l = Lawnchair.adapters.length; i < l; i++) {
adapter = Lawnchair.adapters[i].valid() ? Lawnchair.adapters[i] : undefined
if (adapter) break
}
}
// we have failed
if (!adapter) throw 'No valid adapter.'
// yay! mixin the adapter
for (var j in adapter) {
this[j] = adapter[j]
}
// call init for each mixed in plugin
for (var i = 0, l = Lawnchair.plugins.length; i < l; i++)
Lawnchair.plugins[i].call(this)
// init the adapter
this.init(options, callback)
}
Lawnchair.adapters = []
/**
* queues an adapter for mixin
* ===
* - ensures an adapter conforms to a specific interface
*
*/
Lawnchair.adapter = function (id, obj) {
// add the adapter id to the adapter obj
// ugly here for a cleaner dsl for implementing adapters
obj['adapter'] = id
// methods required to implement a lawnchair adapter
var implementing = 'adapter valid init keys save batch get exists all remove nuke'.split(' ')
// mix in the adapter
for (var i in obj) if (implementing.indexOf(i) === -1) throw 'Invalid adapter! Nonstandard method: ' + i
// if we made it this far the adapter interface is valid
Lawnchair.adapters.push(obj)
}
Lawnchair.plugins = []
/**
* generic shallow extension for plugins
* ===
* - if an init method is found it registers it to be called when the lawnchair is inited
* - yes we could use hasOwnProp but nobody here is an asshole
*/
Lawnchair.plugin = function (obj) {
for (var i in obj)
i === 'init' ? Lawnchair.plugins.push(obj[i]) : this.prototype[i] = obj[i]
}
/**
* helpers
*
*/
Lawnchair.prototype = {
isArray: Array.isArray || function(o) { return Object.prototype.toString.call(o) === '[object Array]' },
// awesome shorthand callbacks as strings. this is shameless theft from dojo.
lambda: function (callback) {
return this.fn(this.record, callback)
},
// first stab at named parameters for terse callbacks; dojo: first != best // ;D
fn: function (name, callback) {
return typeof callback == 'string' ? new Function(name, callback) : callback
},
// returns a unique identifier (by way of Backbone.localStorage.js)
// TODO investigate smaller UUIDs to cut on storage cost
uuid: function () {
var S4 = function () {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
},
// a classic iterator
each: function (callback) {
var cb = this.lambda(callback)
// iterate from chain
if (this.__results) {
for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i)
}
// otherwise iterate the entire collection
else {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i)
})
}
return this
}
// --
};
Lawnchair.adapter('webkit-sqlite', (function () {
// private methods
var fail = function (e, i) { console.log('error in sqlite adaptor!', e, i) }
, now = function () { return new Date() } // FIXME need to use better date fn
// not entirely sure if this is needed...
if (!Function.prototype.bind) {
Function.prototype.bind = function( obj ) {
var slice = [].slice
, args = slice.call(arguments, 1)
, self = this
, nop = function () {}
, bound = function () {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)))
}
nop.prototype = self.prototype
bound.prototype = new nop()
return bound
}
}
// public methods
return {
valid: function() { return !!(window.openDatabase) },
init: function (options, callback) {
var that = this
, cb = that.fn(that.name, callback)
, create = "CREATE TABLE IF NOT EXISTS " + this.name + " (id NVARCHAR(32) UNIQUE PRIMARY KEY, value TEXT, timestamp REAL)"
, win = cb.bind(this)
// open a connection and create the db if it doesn't exist
this.db = openDatabase(this.name, '1.0.0', this.name, 65536)
this.db.transaction(function (t) {
t.executeSql(create, [], win, fail)
})
},
keys: function (callback) {
var cb = this.lambda(callback)
, that = this
, keys = "SELECT id FROM " + this.name + " ORDER BY timestamp DESC"
this.db.transaction(function(t) {
var win = function (xxx, results) {
if (results.rows.length == 0 ) {
cb.call(that, [])
} else {
var r = [];
for (var i = 0, l = results.rows.length; i < l; i++) {
r.push(results.rows.item(i).id);
}
cb.call(that, r)
}
}
t.executeSql(keys, [], win, fail)
})
return this
},
// you think thats air you're breathing now?
save: function (obj, callback) {
var that = this
, id = obj.key || that.uuid()
, ins = "INSERT INTO " + this.name + " (value, timestamp, id) VALUES (?,?,?)"
, up = "UPDATE " + this.name + " SET value=?, timestamp=? WHERE id=?"
, win = function () { if (callback) { obj.key = id; that.lambda(callback).call(that, obj) }}
, val = [now(), id]
// existential
that.exists(obj.key, function(exists) {
// transactions are like condoms
that.db.transaction(function(t) {
// TODO move timestamp to a plugin
var insert = function (obj) {
val.unshift(JSON.stringify(obj))
t.executeSql(ins, val, win, fail)
}
// TODO move timestamp to a plugin
var update = function (obj) {
delete(obj.key)
val.unshift(JSON.stringify(obj))
t.executeSql(up, val, win, fail)
}
// pretty
exists ? update(obj) : insert(obj)
})
});
return this
},
// FIXME this should be a batch insert / just getting the test to pass...
batch: function (objs, cb) {
var results = []
, done = false
, that = this
var updateProgress = function(obj) {
results.push(obj)
done = results.length === objs.length
}
var checkProgress = setInterval(function() {
if (done) {
if (cb) that.lambda(cb).call(that, results)
clearInterval(checkProgress)
}
}, 200)
for (var i = 0, l = objs.length; i < l; i++)
this.save(objs[i], updateProgress)
return this
},
get: function (keyOrArray, cb) {
var that = this
, sql = ''
// batch selects support
if (this.isArray(keyOrArray)) {
sql = 'SELECT id, value FROM ' + this.name + " WHERE id IN ('" + keyOrArray.join("','") + "')"
} else {
sql = 'SELECT id, value FROM ' + this.name + " WHERE id = '" + keyOrArray + "'"
}
// FIXME
// will always loop the results but cleans it up if not a batch return at the end..
// in other words, this could be faster
var win = function (xxx, results) {
var o = null
, r = []
if (results.rows.length) {
for (var i = 0, l = results.rows.length; i < l; i++) {
o = JSON.parse(results.rows.item(i).value)
o.key = results.rows.item(i).id
r.push(o)
}
}
if (!that.isArray(keyOrArray)) r = r.length ? r[0] : null
if (cb) that.lambda(cb).call(that, r)
}
this.db.transaction(function(t){ t.executeSql(sql, [], win, fail) })
return this
},
exists: function (key, cb) {
var is = "SELECT * FROM " + this.name + " WHERE id = ?"
, that = this
, win = function(xxx, results) { if (cb) that.fn('exists', cb).call(that, (results.rows.length > 0)) }
this.db.transaction(function(t){ t.executeSql(is, [key], win, fail) })
return this
},
all: function (callback) {
var that = this
, all = "SELECT * FROM " + this.name
, r = []
, cb = this.fn(this.name, callback) || undefined
, win = function (xxx, results) {
if (results.rows.length != 0) {
for (var i = 0, l = results.rows.length; i < l; i++) {
var obj = JSON.parse(results.rows.item(i).value)
obj.key = results.rows.item(i).id
r.push(obj)
}
}
if (cb) cb.call(that, r)
}
this.db.transaction(function (t) {
t.executeSql(all, [], win, fail)
})
return this
},
remove: function (keyOrObj, cb) {
var that = this
, key = typeof keyOrObj === 'string' ? keyOrObj : keyOrObj.key
, del = "DELETE FROM " + this.name + " WHERE id = ?"
, win = function () { if (cb) that.lambda(cb).call(that) }
this.db.transaction( function (t) {
t.executeSql(del, [key], win, fail);
});
return this;
},
nuke: function (cb) {
var nuke = "DELETE FROM " + this.name
, that = this
, win = cb ? function() { that.lambda(cb).call(that) } : function(){}
this.db.transaction(function (t) {
t.executeSql(nuke, [], win, fail)
})
return this
}
//////
}})())
| d2s/lawnchair | test/lib/lawnchair.js | JavaScript | mit | 10,887 |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("HealthMonitoring.AcceptanceTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HealthMonitoring.AcceptanceTests")]
[assembly: AssemblyCopyright("Copyright © Wonga")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("8d2cfa8a-f44f-4de2-98bc-b19eb496f003")]
[assembly: AssemblyVersion("3.9.0.0")]
[assembly: AssemblyFileVersion("3.9.0.0")]
| Suremaker/HealthMonitoring | HealthMonitoring.AcceptanceTests/Properties/AssemblyInfo.cs | C# | mit | 586 |
module Hanami
module Utils
# HTML escape utilities
#
# Based on OWASP research and OWASP ESAPI code
#
# @since 0.4.0
#
# @see https://www.owasp.org
# @see https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
# @see https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
# @see https://www.owasp.org/index.php/ESAPI
# @see https://github.com/ESAPI/esapi-java-legacy
module Escape
# Hex base for base 10 integer conversion
#
# @since 0.4.0
# @api private
#
# @see http://www.ruby-doc.org/core/Fixnum.html#method-i-to_s
HEX_BASE = 16
# Limit for non printable chars
#
# @since 0.4.0
# @api private
LOW_HEX_CODE_LIMIT = 0xff
# Replacement hex for non printable characters
#
# @since 0.4.0
# @api private
REPLACEMENT_HEX = "fffd".freeze
# Low hex codes lookup table
#
# @since 0.4.0
# @api private
HEX_CODES = (0..255).each_with_object({}) do |c, codes|
if (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A)
codes[c] = nil
else
codes[c] = c.to_s(HEX_BASE)
end
end.freeze
# Non printable chars
#
# This is a Hash instead of a Set, to make lookup faster.
#
# @since 0.4.0
# @api private
#
# @see https://gist.github.com/jodosha/ac5dd54416de744b9600
NON_PRINTABLE_CHARS = {
0x0 => true, 0x1 => true, 0x2 => true, 0x3 => true, 0x4 => true,
0x5 => true, 0x6 => true, 0x7 => true, 0x8 => true, 0x11 => true,
0x12 => true, 0x14 => true, 0x15 => true, 0x16 => true, 0x17 => true,
0x18 => true, 0x19 => true, 0x1a => true, 0x1b => true, 0x1c => true,
0x1d => true, 0x1e => true, 0x1f => true, 0x7f => true, 0x80 => true,
0x81 => true, 0x82 => true, 0x83 => true, 0x84 => true, 0x85 => true,
0x86 => true, 0x87 => true, 0x88 => true, 0x89 => true, 0x8a => true,
0x8b => true, 0x8c => true, 0x8d => true, 0x8e => true, 0x8f => true,
0x90 => true, 0x91 => true, 0x92 => true, 0x93 => true, 0x94 => true,
0x95 => true, 0x96 => true, 0x97 => true, 0x98 => true, 0x99 => true,
0x9a => true, 0x9b => true, 0x9c => true, 0x9d => true, 0x9e => true,
0x9f => true
}.freeze
# Lookup table for HTML escape
#
# @since 0.4.0
# @api private
#
# @see Hanami::Utils::Escape.html
HTML_CHARS = {
'&' => '&',
'<' => '<',
'>' => '>',
'"' => '"',
"'" => ''',
'/' => '/'
}.freeze
# Lookup table for safe chars for HTML attributes.
#
# This is a Hash instead of a Set, to make lookup faster.
#
# @since 0.4.0
# @api private
#
# @see Lookup::Utils::Escape.html_attribute
# @see https://gist.github.com/jodosha/ac5dd54416de744b9600
HTML_ATTRIBUTE_SAFE_CHARS = {
',' => true, '.' => true, '-' => true, '_' => true
}.freeze
# Lookup table for HTML attribute escape
#
# @since 0.4.0
# @api private
#
# @see Hanami::Utils::Escape.html_attribute
HTML_ENTITIES = {
34 => 'quot', # quotation mark
38 => 'amp', # ampersand
60 => 'lt', # less-than sign
62 => 'gt', # greater-than sign
160 => 'nbsp', # no-break space
161 => 'iexcl', # inverted exclamation mark
162 => 'cent', # cent sign
163 => 'pound', # pound sign
164 => 'curren', # currency sign
165 => 'yen', # yen sign
166 => 'brvbar', # broken bar
167 => 'sect', # section sign
168 => 'uml', # diaeresis
169 => 'copy', # copyright sign
170 => 'ordf', # feminine ordinal indicator
171 => 'laquo', # left-pointing double angle quotation mark
172 => 'not', # not sign
173 => 'shy', # soft hyphen
174 => 'reg', # registered sign
175 => 'macr', # macron
176 => 'deg', # degree sign
177 => 'plusmn', # plus-minus sign
178 => 'sup2', # superscript two
179 => 'sup3', # superscript three
180 => 'acute', # acute accent
181 => 'micro', # micro sign
182 => 'para', # pilcrow sign
183 => 'middot', # middle dot
184 => 'cedil', # cedilla
185 => 'sup1', # superscript one
186 => 'ordm', # masculine ordinal indicator
187 => 'raquo', # right-pointing double angle quotation mark
188 => 'frac14', # vulgar fraction one quarter
189 => 'frac12', # vulgar fraction one half
190 => 'frac34', # vulgar fraction three quarters
191 => 'iquest', # inverted question mark
192 => 'Agrave', # Latin capital letter a with grave
193 => 'Aacute', # Latin capital letter a with acute
194 => 'Acirc', # Latin capital letter a with circumflex
195 => 'Atilde', # Latin capital letter a with tilde
196 => 'Auml', # Latin capital letter a with diaeresis
197 => 'Aring', # Latin capital letter a with ring above
198 => 'AElig', # Latin capital letter ae
199 => 'Ccedil', # Latin capital letter c with cedilla
200 => 'Egrave', # Latin capital letter e with grave
201 => 'Eacute', # Latin capital letter e with acute
202 => 'Ecirc', # Latin capital letter e with circumflex
203 => 'Euml', # Latin capital letter e with diaeresis
204 => 'Igrave', # Latin capital letter i with grave
205 => 'Iacute', # Latin capital letter i with acute
206 => 'Icirc', # Latin capital letter i with circumflex
207 => 'Iuml', # Latin capital letter i with diaeresis
208 => 'ETH', # Latin capital letter eth
209 => 'Ntilde', # Latin capital letter n with tilde
210 => 'Ograve', # Latin capital letter o with grave
211 => 'Oacute', # Latin capital letter o with acute
212 => 'Ocirc', # Latin capital letter o with circumflex
213 => 'Otilde', # Latin capital letter o with tilde
214 => 'Ouml', # Latin capital letter o with diaeresis
215 => 'times', # multiplication sign
216 => 'Oslash', # Latin capital letter o with stroke
217 => 'Ugrave', # Latin capital letter u with grave
218 => 'Uacute', # Latin capital letter u with acute
219 => 'Ucirc', # Latin capital letter u with circumflex
220 => 'Uuml', # Latin capital letter u with diaeresis
221 => 'Yacute', # Latin capital letter y with acute
222 => 'THORN', # Latin capital letter thorn
223 => 'szlig', # Latin small letter sharp sXCOMMAX German Eszett
224 => 'agrave', # Latin small letter a with grave
225 => 'aacute', # Latin small letter a with acute
226 => 'acirc', # Latin small letter a with circumflex
227 => 'atilde', # Latin small letter a with tilde
228 => 'auml', # Latin small letter a with diaeresis
229 => 'aring', # Latin small letter a with ring above
230 => 'aelig', # Latin lowercase ligature ae
231 => 'ccedil', # Latin small letter c with cedilla
232 => 'egrave', # Latin small letter e with grave
233 => 'eacute', # Latin small letter e with acute
234 => 'ecirc', # Latin small letter e with circumflex
235 => 'euml', # Latin small letter e with diaeresis
236 => 'igrave', # Latin small letter i with grave
237 => 'iacute', # Latin small letter i with acute
238 => 'icirc', # Latin small letter i with circumflex
239 => 'iuml', # Latin small letter i with diaeresis
240 => 'eth', # Latin small letter eth
241 => 'ntilde', # Latin small letter n with tilde
242 => 'ograve', # Latin small letter o with grave
243 => 'oacute', # Latin small letter o with acute
244 => 'ocirc', # Latin small letter o with circumflex
245 => 'otilde', # Latin small letter o with tilde
246 => 'ouml', # Latin small letter o with diaeresis
247 => 'divide', # division sign
248 => 'oslash', # Latin small letter o with stroke
249 => 'ugrave', # Latin small letter u with grave
250 => 'uacute', # Latin small letter u with acute
251 => 'ucirc', # Latin small letter u with circumflex
252 => 'uuml', # Latin small letter u with diaeresis
253 => 'yacute', # Latin small letter y with acute
254 => 'thorn', # Latin small letter thorn
255 => 'yuml', # Latin small letter y with diaeresis
338 => 'OElig', # Latin capital ligature oe
339 => 'oelig', # Latin small ligature oe
352 => 'Scaron', # Latin capital letter s with caron
353 => 'scaron', # Latin small letter s with caron
376 => 'Yuml', # Latin capital letter y with diaeresis
402 => 'fnof', # Latin small letter f with hook
710 => 'circ', # modifier letter circumflex accent
732 => 'tilde', # small tilde
913 => 'Alpha', # Greek capital letter alpha
914 => 'Beta', # Greek capital letter beta
915 => 'Gamma', # Greek capital letter gamma
916 => 'Delta', # Greek capital letter delta
917 => 'Epsilon', # Greek capital letter epsilon
918 => 'Zeta', # Greek capital letter zeta
919 => 'Eta', # Greek capital letter eta
920 => 'Theta', # Greek capital letter theta
921 => 'Iota', # Greek capital letter iota
922 => 'Kappa', # Greek capital letter kappa
923 => 'Lambda', # Greek capital letter lambda
924 => 'Mu', # Greek capital letter mu
925 => 'Nu', # Greek capital letter nu
926 => 'Xi', # Greek capital letter xi
927 => 'Omicron', # Greek capital letter omicron
928 => 'Pi', # Greek capital letter pi
929 => 'Rho', # Greek capital letter rho
931 => 'Sigma', # Greek capital letter sigma
932 => 'Tau', # Greek capital letter tau
933 => 'Upsilon', # Greek capital letter upsilon
934 => 'Phi', # Greek capital letter phi
935 => 'Chi', # Greek capital letter chi
936 => 'Psi', # Greek capital letter psi
937 => 'Omega', # Greek capital letter omega
945 => 'alpha', # Greek small letter alpha
946 => 'beta', # Greek small letter beta
947 => 'gamma', # Greek small letter gamma
948 => 'delta', # Greek small letter delta
949 => 'epsilon', # Greek small letter epsilon
950 => 'zeta', # Greek small letter zeta
951 => 'eta', # Greek small letter eta
952 => 'theta', # Greek small letter theta
953 => 'iota', # Greek small letter iota
954 => 'kappa', # Greek small letter kappa
955 => 'lambda', # Greek small letter lambda
956 => 'mu', # Greek small letter mu
957 => 'nu', # Greek small letter nu
958 => 'xi', # Greek small letter xi
959 => 'omicron', # Greek small letter omicron
960 => 'pi', # Greek small letter pi
961 => 'rho', # Greek small letter rho
962 => 'sigmaf', # Greek small letter final sigma
963 => 'sigma', # Greek small letter sigma
964 => 'tau', # Greek small letter tau
965 => 'upsilon', # Greek small letter upsilon
966 => 'phi', # Greek small letter phi
967 => 'chi', # Greek small letter chi
968 => 'psi', # Greek small letter psi
969 => 'omega', # Greek small letter omega
977 => 'thetasym', # Greek theta symbol
978 => 'upsih', # Greek upsilon with hook symbol
982 => 'piv', # Greek pi symbol
8194 => 'ensp', # en space
8195 => 'emsp', # em space
8201 => 'thinsp', # thin space
8204 => 'zwnj', # zero width non-joiner
8205 => 'zwj', # zero width joiner
8206 => 'lrm', # left-to-right mark
8207 => 'rlm', # right-to-left mark
8211 => 'ndash', # en dash
8212 => 'mdash', # em dash
8216 => 'lsquo', # left single quotation mark
8217 => 'rsquo', # right single quotation mark
8218 => 'sbquo', # single low-9 quotation mark
8220 => 'ldquo', # left double quotation mark
8221 => 'rdquo', # right double quotation mark
8222 => 'bdquo', # double low-9 quotation mark
8224 => 'dagger', # dagger
8225 => 'Dagger', # double dagger
8226 => 'bull', # bullet
8230 => 'hellip', # horizontal ellipsis
8240 => 'permil', # per mille sign
8242 => 'prime', # prime
8243 => 'Prime', # double prime
8249 => 'lsaquo', # single left-pointing angle quotation mark
8250 => 'rsaquo', # single right-pointing angle quotation mark
8254 => 'oline', # overline
8260 => 'frasl', # fraction slash
8364 => 'euro', # euro sign
8465 => 'image', # black-letter capital i
8472 => 'weierp', # script capital pXCOMMAX Weierstrass p
8476 => 'real', # black-letter capital r
8482 => 'trade', # trademark sign
8501 => 'alefsym', # alef symbol
8592 => 'larr', # leftwards arrow
8593 => 'uarr', # upwards arrow
8594 => 'rarr', # rightwards arrow
8595 => 'darr', # downwards arrow
8596 => 'harr', # left right arrow
8629 => 'crarr', # downwards arrow with corner leftwards
8656 => 'lArr', # leftwards double arrow
8657 => 'uArr', # upwards double arrow
8658 => 'rArr', # rightwards double arrow
8659 => 'dArr', # downwards double arrow
8660 => 'hArr', # left right double arrow
8704 => 'forall', # for all
8706 => 'part', # partial differential
8707 => 'exist', # there exists
8709 => 'empty', # empty set
8711 => 'nabla', # nabla
8712 => 'isin', # element of
8713 => 'notin', # not an element of
8715 => 'ni', # contains as member
8719 => 'prod', # n-ary product
8721 => 'sum', # n-ary summation
8722 => 'minus', # minus sign
8727 => 'lowast', # asterisk operator
8730 => 'radic', # square root
8733 => 'prop', # proportional to
8734 => 'infin', # infinity
8736 => 'ang', # angle
8743 => 'and', # logical and
8744 => 'or', # logical or
8745 => 'cap', # intersection
8746 => 'cup', # union
8747 => 'int', # integral
8756 => 'there4', # therefore
8764 => 'sim', # tilde operator
8773 => 'cong', # congruent to
8776 => 'asymp', # almost equal to
8800 => 'ne', # not equal to
8801 => 'equiv', # identical toXCOMMAX equivalent to
8804 => 'le', # less-than or equal to
8805 => 'ge', # greater-than or equal to
8834 => 'sub', # subset of
8835 => 'sup', # superset of
8836 => 'nsub', # not a subset of
8838 => 'sube', # subset of or equal to
8839 => 'supe', # superset of or equal to
8853 => 'oplus', # circled plus
8855 => 'otimes', # circled times
8869 => 'perp', # up tack
8901 => 'sdot', # dot operator
8968 => 'lceil', # left ceiling
8969 => 'rceil', # right ceiling
8970 => 'lfloor', # left floor
8971 => 'rfloor', # right floor
9001 => 'lang', # left-pointing angle bracket
9002 => 'rang', # right-pointing angle bracket
9674 => 'loz', # lozenge
9824 => 'spades', # black spade suit
9827 => 'clubs', # black club suit
9829 => 'hearts', # black heart suit
9830 => 'diams', # black diamond suit
}.freeze
# Allowed URL schemes
#
# @since 0.4.0
# @api private
#
# @see Hanami::Utils::Escape.url
DEFAULT_URL_SCHEMES = ['http', 'https', 'mailto'].freeze
# The output of an escape.
#
# It's marked with this special class for two reasons:
#
# * Don't double escape the same string (this is for `Hanami::Helpers` compatibility)
# * Leave open the possibility to developers to mark a string as safe with an higher API (eg. `#raw` in `Hanami::View` or `Hanami::Helpers`)
#
# @since 0.4.0
# @api private
class SafeString < ::String
# @return [SafeString] the duped string
#
# @since 0.4.0
# @api private
#
# @see http://www.ruby-doc.org/core/String.html#method-i-to_s
def to_s
dup
end
# Encode the string the given encoding
#
# @return [SafeString] an encoded SafeString
#
# @since 0.4.0
# @api private
#
# @see http://www.ruby-doc.org/core/String.html#method-i-encode
def encode(*args)
self.class.new super
end
end
# Escape HTML contents
#
# This MUST be used only for tag contents.
# Please use `html_attribute` for escaping HTML attributes.
#
# @param input [String] the input
#
# @return [String] the escaped string
#
# @since 0.4.0
#
# @see https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet OWASP XSS Cheat Sheet Rule #1
#
# @example Good practice
# <div><%= Hanami::Utils::Escape.html('<script>alert(1);</script>') %></div>
# <div><script>alert(1);</script></div>
#
# @example Bad practice
# # WRONG Use Escape.html_attribute
# <a title="<%= Hanami::Utils::Escape.html('...') %>">link</a>
def self.html(input)
input = encode(input)
return input if input.is_a?(SafeString)
result = SafeString.new
input.each_char do |chr|
result << HTML_CHARS.fetch(chr, chr)
end
result
end
# Escape HTML attributes
#
# This can be used both for HTML attributes and contents.
# Please note that this is more computational expensive.
# If you need to escape only HTML contents, please use `.html`.
#
# @param input [String] the input
#
# @return [String] the escaped string
#
# @since 0.4.0
#
# @see https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet OWASP XSS Cheat Sheet Rule #2
#
# @example Good practice
# <a title="<%= Hanami::Utils::Escape.html_attribute('...') %>">link</a>
#
# @example Good but expensive practice
# # Alternatively you can use Escape.html
# <p><%= Hanami::Utils::Escape.html_attribute('...') %></p>
def self.html_attribute(input)
input = encode(input)
return input if input.is_a?(SafeString)
result = SafeString.new
input.each_char do |chr|
result << encode_char(chr, HTML_ATTRIBUTE_SAFE_CHARS)
end
result
end
# Escape URL for HTML attributes (href, src, etc..).
#
# It extracts from the given input the first valid URL that matches the
# whitelisted schemes (default: http, https and mailto).
#
# It's possible to pass a second optional argument to specify different
# schemes.
#
# @param input [String] the input
# @param schemes [Array<String>] an array of whitelisted schemes
#
# @return [String] the escaped string
#
# @since 0.4.0
#
# @see Hanami::Utils::Escape::DEFAULT_URL_SCHEMES
# @see http://www.ruby-doc.org/stdlib/libdoc/uri/rdoc/URI.html#method-c-extract
#
# @example Basic usage
# <%
# good_input = "http://hanamirb.org"
# evil_input = "javascript:alert('xss')"
#
# escaped_good_input = Hanami::Utils::Escape.url(good_input) # => "http://hanamirb.org"
# escaped_evil_input = Hanami::Utils::Escape.url(evil_input) # => ""
# %>
#
# <a href="<%= escaped_good_input %>">personal website</a>
# <a href="<%= escaped_evil_input %>">personal website</a>
#
# @example Custom scheme
# <%
# schemes = ['ftp', 'ftps']
#
# accepted = "ftps://ftp.example.org"
# rejected = "http://www.example.org"
#
# escaped_accepted = Hanami::Utils::Escape.url(accepted) # => "ftps://ftp.example.org"
# escaped_rejected = Hanami::Utils::Escape.url(rejected) # => ""
# %>
#
# <a href="<%= escaped_accepted %>">FTP</a>
# <a href="<%= escaped_rejected %>">FTP</a>
def self.url(input, schemes = DEFAULT_URL_SCHEMES)
input = encode(input)
return input if input.is_a?(SafeString)
SafeString.new(
URI::Parser.new.extract(
URI.decode_www_form_component(input),
schemes
).first.to_s
)
end
private
# Encode the given string into UTF-8
#
# @param input [String] the input
#
# @return [String] an UTF-8 encoded string
#
# @since 0.4.0
# @api private
def self.encode(input)
return '' if input.nil?
input.to_s.encode(Encoding::UTF_8)
rescue Encoding::UndefinedConversionError
input.dup.force_encoding(Encoding::UTF_8)
end
# Encode the given UTF-8 char.
#
# @param char [String] an UTF-8 char
# @param safe_chars [Hash] a table of safe chars
#
# @return [String] an HTML encoded string
#
# @since 0.4.0
# @api private
def self.encode_char(char, safe_chars = {})
return char if safe_chars[char]
code = char.ord
hex = hex_for_non_alphanumeric_code(code)
return char if hex.nil?
if NON_PRINTABLE_CHARS[code]
hex = REPLACEMENT_HEX
end
if entity = HTML_ENTITIES[code]
"&#{ entity };"
else
"&#x#{ hex };"
end
end
# Transforms the given char code
#
# @since 0.4.0
# @api private
def self.hex_for_non_alphanumeric_code(input)
if input < LOW_HEX_CODE_LIMIT
HEX_CODES[input]
else
input.to_s(HEX_BASE)
end
end
end
end
end
| vyper/utils | lib/hanami/utils/escape.rb | Ruby | mit | 23,390 |
package org.distributedproficiency.dojo.dto;
import org.distributedproficiency.dojo.domain.KataContent;
public class KataSaveRequest {
private KataContent newContent;
public KataSaveRequest() {
super();
}
public KataSaveRequest(KataContent c) {
super();
this.newContent = c;
}
public KataContent getNewContent() {
return newContent;
}
public void setNewContent(KataContent newContent) {
this.newContent = newContent;
}
}
| gsoertsz/dojo-services | src/main/java/org/distributedproficiency/dojo/dto/KataSaveRequest.java | Java | mit | 503 |
/**
* drcProcess
* Created by dcorns on 1/2/15.
*/
'use strict';
var RunApp = require('./runApp');
var Server = require('./server');
var parseInput = require('./parseInput');
var CommandList = require('./commandList');
var runApp = new RunApp();
var cmds = new CommandList();
cmds.add(['ls', 'pwd', 'service', 'ps']);
var firstServer = new Server('firstServer');
firstServer.start(3000, function(err, cnn){
cnn.on('data', function(data){
parseInput(data, function(err, obj){
if(err) cnn.write(err);
else {
if(obj.cmd.substr(0, 6) === 'login:'){
cnn.loginID = obj.cmd.substr(6);
cnn.write('Welcome ' + cnn.loginID + '\r\n');
cnn.write('Valid Commands: ' + cmds.listCommands() + '\r\n');
cnn.write('Use # to add parameters: example: ls#/\r\n');
cnn.write('Use - to add options: example: ls#/ -al or ls#-al\r\n');
console.log(cnn.loginID + ' connected');
}
else {
if(cmds.validate(obj.cmd) > -1){
runApp.run(obj.params, cnn, obj.cmd);
}
else{
cnn.write('Valid commands: ' + cmds.listCommands());
}
}
}
});
});
});
| dcorns/processThis | drcProcess.js | JavaScript | mit | 1,200 |
import {ATTACHMENTS} from "../constants";
export default (...args) => {
// Use one or the other
const attachments = args.length ? args : ATTACHMENTS;
return {
props: {
attach: {
type: String,
validator: value => value === "" || attachments.includes(value)
}
},
computed: {
getAttach() {
if(typeof this.attach === "string") {
return this.attach ? `${this.attach} attached` : "attached";
}
}
}
};
}; | iFaxity/Semantic-UI-Vue | src/mixins/attach.js | JavaScript | mit | 489 |
require 'rails_helper'
describe "Describing Model", model: true do
context "Data Validation" do
end
context "Associations" do
before :each do
@describing = build(:describing)
end
it "has a description" do
expect(@describing).to respond_to :description
end
it "has a describable" do
expect(@describing).to respond_to :describable
end
end
end | rochej/ModResume | spec/models/describing_spec.rb | Ruby | mit | 399 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using gView.Framework.Data;
using gView.Framework.Offline;
namespace gView.Framework.Offline.UI
{
public partial class FormAddReplicationID : Form,IFeatureClassDialog
{
private IFeatureClass _fc;
private IFeatureDatabaseReplication _fdb;
private BackgroundWorker _worker;
public FormAddReplicationID()
{
InitializeComponent();
}
private void btnCreate_Click(object sender, EventArgs e)
{
btnCreate.Enabled = btnCancel.Enabled = false;
progressDisk1.Visible = lblCounter.Visible = true;
progressDisk1.Start(90);
_worker = new BackgroundWorker();
_worker.DoWork += new DoWorkEventHandler(_worker_DoWork);
_worker.RunWorkerAsync(txtFieldname.Text);
Cursor = Cursors.WaitCursor;
}
void _worker_DoWork(object sender, DoWorkEventArgs e)
{
string errMsg;
Replication repl = new Replication();
repl.ReplicationGuidsAppended += new Replication.ReplicationGuidsAppendedEventHandler(Replication_ReplicationGuidsAppended);
if (!repl.AppendReplicationIDField(_fdb, _fc, e.Argument.ToString(), out errMsg))
{
MessageBox.Show("Error: " + errMsg);
}
_worker = null;
CloseWindow();
}
private delegate void CloseWindowCallback();
private void CloseWindow()
{
if (this.InvokeRequired)
{
CloseWindowCallback callback = new CloseWindowCallback(CloseWindow);
this.Invoke(callback);
}
else
{
this.Close();
}
}
void Replication_ReplicationGuidsAppended(Replication sender, int count_appended)
{
if (this.InvokeRequired)
{
Replication.ReplicationGuidsAppendedEventHandler callback = new Replication.ReplicationGuidsAppendedEventHandler(Replication_ReplicationGuidsAppended);
this.Invoke(callback, new object[] { sender, count_appended });
}
else
{
lblCounter.Text = count_appended.ToString() + " Features updated...";
}
}
private void FormAddReplicationID_Load(object sender, EventArgs e)
{
if (_fc == null || _fdb == null) this.Close();
}
private void FormAddReplicationID_FormClosing(object sender, FormClosingEventArgs e)
{
if (_worker != null)
e.Cancel = true;
}
#region IFeatureClassDialog Member
public void ShowDialog(IFeatureClass fc)
{
_fc = fc;
if (_fc != null && fc.Dataset != null)
{
_fdb = _fc.Dataset.Database as IFeatureDatabaseReplication;
this.ShowDialog();
}
}
#endregion
}
} | jugstalt/gViewGisOS | gView.Offline.UI/Framework/Offline/UI/FormAddReplicationID.cs | C# | mit | 3,179 |
<?php
$this->load->view("header");
$this->load->view($view_name);
$this->load->view("footer");
?> | aya-gamal1/expenses | application/views/main.php | PHP | mit | 97 |
'use strict';
module.exports = Source;
const inherits = require('util').inherits;
const Stream = require('../stream');
const Chunk = require('../chunk');
const Compose = require('../through/compose');
const Break = require('../through/break');
const Filter = require('../through/filter');
const Map = require('../through/map');
const Take = require('../through/take');
const Each = require('../feed/each');
const Value = require('../feed/value');
module.exports = Source;
inherits(Source, Stream);
function Source(){
Stream.call(this);
this.async = false;
}
Source.prototype.iterator = function iterator() {
return new this.constructor.Iterator(this);
};
Source.prototype.pipe = function pipe(feed) {
return feed.feed([this]);
};
Source.prototype.break = function breake(fn, async){
return this.pipe(new Break(fn, async));
};
Source.prototype.filter = function filter(fn, async){
return this.pipe(new Filter(fn, async));
};
Source.prototype.map = function map(fn, async){
return this.pipe(new Map(fn, async));
};
Source.prototype.take = function take(max){
return this.pipe(new Take(max));
};
Source.prototype.each = function each(fn){
return this.pipe(new Each(fn));
};
Source.prototype.value = function value(async){
return this.pipe(new Value(async));
};
| shishidosoichiro/lazy | src/source/source.js | JavaScript | mit | 1,283 |
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Models;
namespace Services
{
public interface IArticlesService
{
Task<Section[]> GetSections();
Task<Section> GetSection(string sectionRef);
Task<Article[]> GetArticles(string sectionRef);
Task<Article[]> GetAllArticlesInTree(string sectionRef);
Task<Article> GetArticle(string sectionRef, string articleRef);
}
public class ArticlesService : IArticlesService
{
private ArticleGroup[] articleData = null;
private Section[] sectionData = null;
private readonly HttpClient httpClient;
private readonly ILogger logger;
public ArticlesService(HttpClient httpClient, ILogger<ArticlesService> logger)
{
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<Section[]> GetSections()
{
await EnsureDataLoaded();
return sectionData;
}
public async Task<Section> GetSection(string sectionRef)
{
await EnsureDataLoaded();
var section = Section.Flatten(sectionData).FirstOrDefault(s => s.Reference == sectionRef);
return section;
}
public async Task<Article[]> GetArticles(string sectionRef)
{
await EnsureDataLoaded();
var section = await GetSection(sectionRef);
var sectionArticles = articleData.FirstOrDefault(s => s.Reference == section.Reference).Articles;
return sectionArticles;
}
public async Task<Article[]> GetAllArticlesInTree(string sectionRef)
{
await EnsureDataLoaded();
var section = await GetSection(sectionRef);
var sectionArticles = articleData.FirstOrDefault(s => s.Reference == section.Reference).Articles;
var allArticles = Article.Flatten(sectionArticles);
return allArticles.ToArray();
}
public async Task<Article> GetArticle(string sectionRef, string articleRef)
{
await EnsureDataLoaded();
var allArticles = await GetAllArticlesInTree(sectionRef);
var article = allArticles.FirstOrDefault(a => a.Reference == articleRef);
return article;
}
private async Task EnsureDataLoaded()
{
// load the section data from `data/sections.json`
if (sectionData == null)
{
var loadedData = await httpClient.GetFromJsonAsync<Section[]>("data/sections.json");
lock(this)
{
sectionData = loadedData;
foreach (var section in sectionData)
{
PopulateParentage(section.Children, null);
}
}
}
if (articleData == null)
{
var loadedData = await httpClient.GetFromJsonAsync<ArticleGroup[]>("data/articles.json");
lock(this)
{
articleData = loadedData;
foreach(var section in articleData)
{
PopulateParentage(section.Articles, null);
}
}
}
}
private void PopulateParentage<T>(IHeirarchicalItem<T>[] items, T parent)
where T : IHeirarchicalItem<T>
{
foreach (var item in items.OfType<T>())
{
if (item.Parent == null)
{
item.Parent = parent;
}
var children = item.Children.OfType<IHeirarchicalItem<T>>().ToArray();
if (children.Any())
{
PopulateParentage<T>(children, item);
}
}
}
}
}
| Rammesses/5coy-archive | web/Services/ArticlesService.cs | C# | mit | 4,134 |
<?php
class itemModel extends CI_Model
{
public function insertItem()
{
$itemName = $this->input->post('itemName');
$this->db->where('item_name',$itemName);
$result=$this->db->get('shop_item');
if($result->num_rows()>0) {
$this->session->set_flashdata('Error','Item you entered is already exists.!');
redirect('itemController/addItem');
}
else {
$data = array(
'item_name' => $this->input->post('itemName'),
'item_category' => $this->input->post('itemCategory'),
'quantity' => ($this->input->post('quantity')),
'measuring_unit' => $this->input->post('measuring_unit'),
'unit_price' => $this->input->post('price'),
'item_description' => $this->input->post('description'),
'shop_shop_id'=>$_SESSION['shop_id'],
);
$this->db->insert('shop_item', $data);
}
}
public function viewItems() {
$this->db->select('*');
$this->db->from('shop_item');
$this->db->order_by('shop_item_id');
$this->db->where('shop_shop_id',$_SESSION['shop_id']);
$query = $this->db->get();
return $query->result();
}
// return the row that want to be edited
public function edit($id) {
$this->db->where('shop_item_id',$id);
$query = $this->db->get_where('shop_item', array('shop_item_id' => $id));
return $query->row();
}
//update the selected with the given data
public function update($id) {
$data = array(
'item_category' => $this->input->post('itemCategory'),
'item_name' => $this->input->post('itemName'),
'quantity' => ($this->input->post('quantity')),
'measuring_unit' => ($this->input->post('measuring_unit')),
'unit_price' => $this->input->post('price'),
'item_description' => $this->input->post('description'),
'shop_shop_id'=>$_SESSION['shop_id'],
);
$this->db->where('shop_item_id',$id);
$this->db->update('shop_item',$data);
return $id;
}
public function delete($id) {
$this->db->where('shop_item_id',$id);
$this->db->delete('shop_item');
}
function Search($searchkey){
$this->db->select('*');
$this->db->where('shop_shop_id',$_SESSION['shop_id']);
$this->db->from('shop_item');
$this->db->like('item_name', $searchkey);
$this->db->or_like('shop_item_id', $searchkey);
$this->db->or_like('item_category', $searchkey);
$this->db->or_like('quantity', $searchkey);
$this->db->or_like('measuring_unit', $searchkey);
$this->db->or_like('unit_price', $searchkey);
$this->db->or_like('item_description', $searchkey);
$query = $this->db->get();
return $query->result();
}
public function getCategory()
{
$this->db->select('shop_category');
$this->db->from('shop');
$this->db->where('shop_id',$_SESSION['shop_id']);
$query = $this->db->get();
$result=$query->result_array();
return $result;
}
}
?> | WeerakoonOS/iShop | Ishop 10.12.2017/Ishop/application/models/itemModel.php | PHP | mit | 3,245 |
public class ASTStringLiteral extends SimpleNode
{
String val;
public ASTStringLiteral(int id)
{
super(id);
}
public ASTStringLiteral(ParfA p, int id)
{
super(p, id);
}
public void interpret()
{
ParfANode.stack[++ParfANode.p] = new String(val);
}
} | arjunvnair/ParfA | src/ASTStringLiteral.java | Java | mit | 289 |
require 'one_gadget/gadget'
# https://gitlab.com/david942j/libcdb/blob/master/libc/libc0.1-2.21-9/lib/i386-kfreebsd-gnu/libc-2.21.so
#
# Intel 80386
#
# GNU C Library (Debian GLIBC 2.21-9) stable release version 2.21, by Roland McGrath et al.
# Copyright (C) 2015 Free Software Foundation, Inc.
# This is free software; see the source for copying conditions.
# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
# Compiled by GNU CC version 4.9.3.
# Available extensions:
# crypt add-on version 2.1 by Michael Glad and others
# Native POSIX Threads Library by Ulrich Drepper et al
# GNU Libidn by Simon Josefsson
# BIND-8.2.3-T5B
# libc ABIs: UNIQUE
# For bug reporting instructions, please see:
# <http://www.debian.org/Bugs/>.
build_id = File.basename(__FILE__, '.rb').split('-').last
OneGadget::Gadget.add(build_id, 233829,
constraints: ["ebx is the GOT address of libc", "[esp+0x2c] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x2c, environ)")
OneGadget::Gadget.add(build_id, 233831,
constraints: ["ebx is the GOT address of libc", "[esp+0x30] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x30, environ)")
OneGadget::Gadget.add(build_id, 233835,
constraints: ["ebx is the GOT address of libc", "[esp+0x34] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x34, environ)")
OneGadget::Gadget.add(build_id, 233842,
constraints: ["ebx is the GOT address of libc", "[esp+0x38] == NULL"],
effect: "execve(\"/bin/sh\", esp+0x38, environ)")
OneGadget::Gadget.add(build_id, 233877,
constraints: ["ebx is the GOT address of libc", "[eax] == NULL || eax == NULL", "[[esp]] == NULL || [esp] == NULL"],
effect: "execve(\"/bin/sh\", eax, [esp])")
OneGadget::Gadget.add(build_id, 233878,
constraints: ["ebx is the GOT address of libc", "[[esp]] == NULL || [esp] == NULL", "[[esp+0x4]] == NULL || [esp+0x4] == NULL"],
effect: "execve(\"/bin/sh\", [esp], [esp+0x4])")
OneGadget::Gadget.add(build_id, 395455,
constraints: ["ebx is the GOT address of libc", "eax == NULL"],
effect: "execl(\"/bin/sh\", eax)")
OneGadget::Gadget.add(build_id, 395456,
constraints: ["ebx is the GOT address of libc", "[esp] == NULL"],
effect: "execl(\"/bin/sh\", [esp])")
| david942j/one_gadget | lib/one_gadget/builds/libc-2.21-9595d37f80a7925dc75efa522c839df34edb4b46.rb | Ruby | mit | 2,530 |
using System.Windows.Controls;
namespace mze9412.ScriptCompiler.Views
{
/// <summary>
/// Interaction logic for SettingsView.xaml
/// </summary>
public partial class SettingsView : UserControl
{
public SettingsView()
{
InitializeComponent();
}
}
}
| mze9412/SpaceEngineers-Scripts | ScriptCompiler/Views/SettingsView.xaml.cs | C# | mit | 312 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* 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 license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Checkout
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Shopping cart model
*
* @category Mage
* @package Mage_Checkout
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Checkout_Model_Cart_Api_V2 extends Mage_Checkout_Model_Cart_Api
{
}
| portchris/NaturalRemedyCompany | src/app/code/core/Mage/Checkout/Model/Cart/Api/V2.php | PHP | mit | 1,175 |
Rails.application.routes.draw do
# Mount the physiqual engine
mount Physiqual::Engine => '/physiqual'
get 'welcome/index'
get 'welcome/example'
get 'welcome/example_data'
root 'welcome#index'
# Omniauth
get '/auth/:provider/callback', :to => 'sessions#create'
get '/auth/failure', :to => 'sessions#failure'
delete '/logout', :to => 'sessions#destroy'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
| roqua/physiqual.com | config/routes.rb | Ruby | mit | 1,966 |
// Idea and initial code from https://github.com/aomra015/ember-cli-chart
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'canvas',
attributeBindings: ['width', 'height'],
onlyValues: false,
chartData: {},
didInsertElement: function(){
var context = this.get('element').getContext('2d');
var type = Ember.String.classify(this.get('type'));
var options = {
responsive: true,
showTooltips: true,
pointDot: true,
pointDotRadius: 3,
pointHitDetectionRadius: 8,
bezierCurve: false,
barValueSpacing: 1,
datasetStrokeWidth: 3
};
// animation is very sexy, but it hogs browser. Waiting for chart.js 2.0
// https://github.com/nnnick/Chart.js/issues/653
options.animation = false;
if (this.get("onlyValues")) {
options.showScale = false;
}
var data = {labels: [], datasets: []};
this.get("chartData.labels").forEach((l) => {
data.labels.push(l);
});
this.get("chartData.datasets").forEach((ds) => {
var dataSet = this._chartColors(ds.label);
dataSet.data = ds.data.map((v) => { return v; });
data.datasets.push(dataSet);
});
var chart = new Chart(context)[type](data, options);
this.set('chart', chart);
},
willDestroyElement: function(){
this.get('chart').destroy();
},
updateChart: function() {
//// redraw
// this.willDestroyElement();
// this.didInsertElement();
var chart = this.get("chart");
while (chart.scale.xLabels.length && chart.scale.xLabels[0] !== this.get("chartData.labels")[0]) {
chart.removeData();
}
this.get("chartData.labels").forEach((label, i) => {
if (i < chart.scale.xLabels.length) {
this.get("chartData.datasets").forEach((ds, j) => {
if (this.get("type") === "Line") {
chart.datasets[j].points[i].value = ds.data[i];
} else {
chart.datasets[j].bars[i].value = ds.data[i];
}
});
} else {
var values = [];
this.get("chartData.datasets").forEach((ds) => {
values.push(ds.data[i]);
});
chart.addData(values, label);
}
});
chart.update();
}.observes("chartData", "chartData.[]"),
_chartColors: function(label) {
if (label === "count") {
return {
fillColor: "rgba(151,187,205,1)",
strokeColor: "rgba(151,187,205,1)"
};
} else {
var base = {
max: "203,46,255",
up: "46,255,203",
avg: "46,203,255",
min: "46,98,255",
sum: "98,56,255",
}[label] || "151,187,205";
return {
fillColor: "rgba(" + base + ",0.03)",
strokeColor: "rgba(" + base + ",0.5)",
pointColor: "rgba(" + base + ",0.5)",
// pointStrokeColor: "red", //"rgba(" + base + ")",
// pointHighlightFill: "green", //"rgba(" + base + ")",
// pointHighlightStroke: "blue",// "rgba(" + base + ")",
// pointStrokeColor: "#fff",
// pointHighlightFill: "#fff",
// pointHighlightStroke: "rgba(220,220,220,1)",
};
}
}
});
| snowman-io/snowman-io | ui/app/components/ember-chart.js | JavaScript | mit | 3,145 |
require 'spec'
require 'rr'
require File.join(File.dirname(__FILE__), '/../lib/chawan')
require File.join(File.dirname(__FILE__), '/provide_helper')
def data(key)
path = File.join(File.dirname(__FILE__) + "/fixtures/#{key}")
File.read(path){}
end
| maiha/chawan | spec/spec_helper.rb | Ruby | mit | 254 |
#include "ParticleData.h"
#include <algorithm>
#include <cassert>
namespace {
template<typename T>
void ResizeVector(T& obj, size_t size) {
obj.clear();
obj.resize(size);
obj.shrink_to_fit();
}
template<typename T>
size_t STLMemory(T& obj) {
using Type = typename T::value_type;
return obj.capacity() * sizeof(Type);
}
}
ParticleData::ParticleData()
: size(0)
, count(0) {
}
void ParticleData::Generate(size_t size) {
this->size = size;
count = 0;
ResizeVector(position, size);
ResizeVector(velocity, size);
ResizeVector(acceleration, size);
ResizeVector(color, size);
ResizeVector(alive, size);
}
size_t ParticleData::Wake(size_t count) {
size_t start = 0;
size_t end = std::min(std::max(this->count + count, start), size);
for (size_t i = start; i < end; ++i) {
alive[i] = true;
}
this->count = end;
return end;
}
void ParticleData::Kill(size_t id) {
assert(id < size && id >= 0);
if (alive[id]) {
count--;
alive[id] = false;
Swap(id, count);
}
}
void ParticleData::Swap(size_t left, size_t right) {
std::swap(position[left], position[right]);
std::swap(velocity[left], velocity[right]);
std::swap(acceleration[left], acceleration[right]);
std::swap(color[left], color[right]);
std::swap(alive[left], alive[right]);
}
size_t ParticleData::GetMemory(const ParticleData& system) {
size_t size = sizeof(system);
size += STLMemory(system.position);
size += STLMemory(system.velocity);
size += STLMemory(system.acceleration);
size += STLMemory(system.color);
size += STLMemory(system.alive);
return size;
}
| jedarnaude/particles | src/ParticleData.cpp | C++ | mit | 1,572 |
package commandParsing.drawableObectGenerationInterfaces;
import gui.factories.ShapePaletteEntryFactory;
import java.util.HashMap;
import java.util.Map;
import workspaceState.Shape;
import drawableobject.DrawableObject;
/**
* This class generates the actual ShapePaletteUpdate drawableObjects to give to the GUI.
*
* @author Stanley Yuan, Steve Kuznetsov
*
*/
public interface ShapePaletteUpdateGenerator {
default public DrawableObject generateDrawableObjectRepresentingShapePaletteUpdate (int index,
Shape shape) {
String parent = ShapePaletteEntryFactory.PARENT;
String type = ShapePaletteEntryFactory.TYPE;
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(ShapePaletteEntryFactory.INDEX, Integer.toString(index));
parameters.put(ShapePaletteEntryFactory.IMAGE_PATH, shape.getPath());
return new DrawableObject(parent, type, parameters);
}
}
| akyker20/Slogo_IDE | src/commandParsing/drawableObectGenerationInterfaces/ShapePaletteUpdateGenerator.java | Java | mit | 1,028 |
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, CodeMirror, window */
/**
* Editor is a 1-to-1 wrapper for a CodeMirror editor instance. It layers on Brackets-specific
* functionality and provides APIs that cleanly pass through the bits of CodeMirror that the rest
* of our codebase may want to interact with. An Editor is always backed by a Document, and stays
* in sync with its content; because Editor keeps the Document alive, it's important to always
* destroy() an Editor that's going away so it can release its Document ref.
*
* For now, there's a distinction between the "master" Editor for a Document - which secretly acts
* as the Document's internal model of the text state - and the multitude of "slave" secondary Editors
* which, via Document, sync their changes to and from that master.
*
* For now, direct access to the underlying CodeMirror object is still possible via _codeMirror --
* but this is considered deprecated and may go away.
*
* The Editor object dispatches the following events:
* - keyEvent -- When any key event happens in the editor (whether it changes the text or not).
* Event handlers are passed ({Editor}, {KeyboardEvent}). The 2nd arg is the raw DOM event.
* Note: most listeners will only want to respond when event.type === "keypress".
* - cursorActivity -- When the user moves the cursor or changes the selection, or an edit occurs.
* Note: do not listen to this in order to be generally informed of edits--listen to the
* "change" event on Document instead.
* - scroll -- When the editor is scrolled, either by user action or programmatically.
* - lostContent -- When the backing Document changes in such a way that this Editor is no longer
* able to display accurate text. This occurs if the Document's file is deleted, or in certain
* Document->editor syncing edge cases that we do not yet support (the latter cause will
* eventually go away).
*
* The Editor also dispatches "change" events internally, but you should listen for those on
* Documents, not Editors.
*
* These are jQuery events, so to listen for them you do something like this:
* $(editorInstance).on("eventname", handler);
*/
define(function (require, exports, module) {
"use strict";
var EditorManager = require("editor/EditorManager"),
CodeHintManager = require("editor/CodeHintManager"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager"),
Menus = require("command/Menus"),
PerfUtils = require("utils/PerfUtils"),
PreferencesManager = require("preferences/PreferencesManager"),
Strings = require("strings"),
TextRange = require("document/TextRange").TextRange,
ViewUtils = require("utils/ViewUtils");
var PREFERENCES_CLIENT_ID = "com.adobe.brackets.Editor",
defaultPrefs = { useTabChar: false, tabSize: 4, indentUnit: 4 };
/** Editor preferences */
var _prefs = PreferencesManager.getPreferenceStorage(PREFERENCES_CLIENT_ID, defaultPrefs);
/** @type {boolean} Global setting: When inserting new text, use tab characters? (instead of spaces) */
var _useTabChar = _prefs.getValue("useTabChar");
/** @type {boolean} Global setting: Tab size */
var _tabSize = _prefs.getValue("tabSize");
/** @type {boolean} Global setting: Indent unit (i.e. number of spaces when indenting) */
var _indentUnit = _prefs.getValue("indentUnit");
/**
* @private
* Handle Tab key press.
* @param {!CodeMirror} instance CodeMirror instance.
*/
function _handleTabKey(instance) {
// Tab key handling is done as follows:
// 1. If the selection is before any text and the indentation is to the left of
// the proper indentation then indent it to the proper place. Otherwise,
// add another tab. In either case, move the insertion point to the
// beginning of the text.
// 2. If the selection is after the first non-space character, and is not an
// insertion point, indent the entire line(s).
// 3. If the selection is after the first non-space character, and is an
// insertion point, insert a tab character or the appropriate number
// of spaces to pad to the nearest tab boundary.
var from = instance.getCursor(true),
to = instance.getCursor(false),
line = instance.getLine(from.line),
indentAuto = false,
insertTab = false;
if (from.line === to.line) {
if (line.search(/\S/) > to.ch || to.ch === 0) {
indentAuto = true;
}
}
if (indentAuto) {
var currentLength = line.length;
CodeMirror.commands.indentAuto(instance);
// If the amount of whitespace didn't change, insert another tab
if (instance.getLine(from.line).length === currentLength) {
insertTab = true;
to.ch = 0;
}
} else if (instance.somethingSelected()) {
CodeMirror.commands.indentMore(instance);
} else {
insertTab = true;
}
if (insertTab) {
if (instance.getOption("indentWithTabs")) {
CodeMirror.commands.insertTab(instance);
} else {
var i, ins = "", numSpaces = _indentUnit;
numSpaces -= to.ch % numSpaces;
for (i = 0; i < numSpaces; i++) {
ins += " ";
}
instance.replaceSelection(ins, "end");
}
}
}
/**
* @private
* Handle left arrow, right arrow, backspace and delete keys when soft tabs are used.
* @param {!CodeMirror} instance CodeMirror instance
* @param {number} direction Direction of movement: 1 for forward, -1 for backward
* @param {function} functionName name of the CodeMirror function to call
* @return {boolean} true if key was handled
*/
function _handleSoftTabNavigation(instance, direction, functionName) {
var handled = false;
if (!instance.getOption("indentWithTabs")) {
var cursor = instance.getCursor(),
jump = cursor.ch % _indentUnit,
line = instance.getLine(cursor.line);
if (direction === 1) {
jump = _indentUnit - jump;
if (cursor.ch + jump > line.length) { // Jump would go beyond current line
return false;
}
if (line.substr(cursor.ch, jump).search(/\S/) === -1) {
instance[functionName](jump, "char");
handled = true;
}
} else {
// Quick exit if we are at the beginning of the line
if (cursor.ch === 0) {
return false;
}
// If we are on the tab boundary, jump by the full amount,
// but not beyond the start of the line.
if (jump === 0) {
jump = _indentUnit;
}
// Search backwards to the first non-space character
var offset = line.substr(cursor.ch - jump, jump).search(/\s*$/g);
if (offset !== -1) { // Adjust to jump to first non-space character
jump -= offset;
}
if (jump > 0) {
instance[functionName](-jump, "char");
handled = true;
}
}
}
return handled;
}
/**
* Checks if the user just typed a closing brace/bracket/paren, and considers automatically
* back-indenting it if so.
*/
function _checkElectricChars(jqEvent, editor, event) {
var instance = editor._codeMirror;
if (event.type === "keypress") {
var keyStr = String.fromCharCode(event.which || event.keyCode);
if (/[\]\{\}\)]/.test(keyStr)) {
// If all text before the cursor is whitespace, auto-indent it
var cursor = instance.getCursor();
var lineStr = instance.getLine(cursor.line);
var nonWS = lineStr.search(/\S/);
if (nonWS === -1 || nonWS >= cursor.ch) {
// Need to do the auto-indent on a timeout to ensure
// the keypress is handled before auto-indenting.
// This is the same timeout value used by the
// electricChars feature in CodeMirror.
window.setTimeout(function () {
instance.indentLine(cursor.line);
}, 75);
}
}
}
}
function _handleKeyEvents(jqEvent, editor, event) {
_checkElectricChars(jqEvent, editor, event);
// Pass the key event to the code hint manager. It may call preventDefault() on the event.
CodeHintManager.handleKeyEvent(editor, event);
}
function _handleSelectAll() {
var editor = EditorManager.getFocusedEditor();
if (editor) {
editor._selectAllVisible();
}
}
/**
* List of all current (non-destroy()ed) Editor instances. Needed when changing global preferences
* that affect all editors, e.g. tabbing or color scheme settings.
* @type {Array.<Editor>}
*/
var _instances = [];
/**
* @constructor
*
* Creates a new CodeMirror editor instance bound to the given Document. The Document need not have
* a "master" Editor realized yet, even if makeMasterEditor is false; in that case, the first time
* an edit occurs we will automatically ask EditorManager to create a "master" editor to render the
* Document modifiable.
*
* ALWAYS call destroy() when you are done with an Editor - otherwise it will leak a Document ref.
*
* @param {!Document} document
* @param {!boolean} makeMasterEditor If true, this Editor will set itself as the (secret) "master"
* Editor for the Document. If false, this Editor will attach to the Document as a "slave"/
* secondary editor.
* @param {!string} mode Syntax-highlighting language mode; "" means plain-text mode.
* See {@link EditorUtils#getModeFromFileExtension()}.
* @param {!jQueryObject} container Container to add the editor to.
* @param {!Object<string, function(Editor)>} additionalKeys Mapping of keyboard shortcuts to
* custom handler functions. Mapping is in CodeMirror format
* @param {{startLine: number, endLine: number}=} range If specified, range of lines within the document
* to display in this editor. Inclusive.
*/
function Editor(document, makeMasterEditor, mode, container, additionalKeys, range) {
var self = this;
_instances.push(this);
// Attach to document: add ref & handlers
this.document = document;
document.addRef();
if (range) { // attach this first: want range updated before we process a change
this._visibleRange = new TextRange(document, range.startLine, range.endLine);
}
// store this-bound version of listeners so we can remove them later
this._handleDocumentChange = this._handleDocumentChange.bind(this);
this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this);
$(document).on("change", this._handleDocumentChange);
$(document).on("deleted", this._handleDocumentDeleted);
// (if makeMasterEditor, we attach the Doc back to ourselves below once we're fully initialized)
this._inlineWidgets = [];
// Editor supplies some standard keyboard behavior extensions of its own
var codeMirrorKeyMap = {
"Tab": _handleTabKey,
"Shift-Tab": "indentLess",
"Left": function (instance) {
if (!_handleSoftTabNavigation(instance, -1, "moveH")) {
CodeMirror.commands.goCharLeft(instance);
}
},
"Right": function (instance) {
if (!_handleSoftTabNavigation(instance, 1, "moveH")) {
CodeMirror.commands.goCharRight(instance);
}
},
"Backspace": function (instance) {
if (!_handleSoftTabNavigation(instance, -1, "deleteH")) {
CodeMirror.commands.delCharLeft(instance);
}
},
"Delete": function (instance) {
if (!_handleSoftTabNavigation(instance, 1, "deleteH")) {
CodeMirror.commands.delCharRight(instance);
}
},
"Esc": function (instance) {
self.removeAllInlineWidgets();
},
"'>'": function (cm) { cm.closeTag(cm, '>'); },
"'/'": function (cm) { cm.closeTag(cm, '/'); }
};
EditorManager.mergeExtraKeys(self, codeMirrorKeyMap, additionalKeys);
// We'd like null/"" to mean plain text mode. CodeMirror defaults to plaintext for any
// unrecognized mode, but it complains on the console in that fallback case: so, convert
// here so we're always explicit, avoiding console noise.
if (!mode) {
mode = "text/plain";
}
// Create the CodeMirror instance
// (note: CodeMirror doesn't actually require using 'new', but jslint complains without it)
this._codeMirror = new CodeMirror(container, {
electricChars: false, // we use our own impl of this to avoid CodeMirror bugs; see _checkElectricChars()
indentWithTabs: _useTabChar,
tabSize: _tabSize,
indentUnit: _indentUnit,
lineNumbers: true,
matchBrackets: true,
dragDrop: false, // work around issue #1123
extraKeys: codeMirrorKeyMap
});
// Can't get CodeMirror's focused state without searching for
// CodeMirror-focused. Instead, track focus via onFocus and onBlur
// options and track state with this._focused
this._focused = false;
this._installEditorListeners();
$(this)
.on("keyEvent", _handleKeyEvents)
.on("change", this._handleEditorChange.bind(this));
// Set code-coloring mode BEFORE populating with text, to avoid a flash of uncolored text
this._codeMirror.setOption("mode", mode);
// Initially populate with text. This will send a spurious change event, so need to make
// sure this is understood as a 'sync from document' case, not a genuine edit
this._duringSync = true;
this._resetText(document.getText());
this._duringSync = false;
if (range) {
// Hide all lines other than those we want to show. We do this rather than trimming the
// text itself so that the editor still shows accurate line numbers.
this._codeMirror.operation(function () {
var i;
for (i = 0; i < range.startLine; i++) {
self._hideLine(i);
}
var lineCount = self.lineCount();
for (i = range.endLine + 1; i < lineCount; i++) {
self._hideLine(i);
}
});
this.setCursorPos(range.startLine, 0);
}
// Now that we're fully initialized, we can point the document back at us if needed
if (makeMasterEditor) {
document._makeEditable(this);
}
// Add scrollTop property to this object for the scroll shadow code to use
Object.defineProperty(this, "scrollTop", {
get: function () {
return this._codeMirror.getScrollInfo().y;
}
});
}
/**
* Removes this editor from the DOM and detaches from the Document. If this is the "master"
* Editor that is secretly providing the Document's backing state, then the Document reverts to
* a read-only string-backed mode.
*/
Editor.prototype.destroy = function () {
// CodeMirror docs for getWrapperElement() say all you have to do is "Remove this from your
// tree to delete an editor instance."
$(this.getRootElement()).remove();
_instances.splice(_instances.indexOf(this), 1);
// Disconnect from Document
this.document.releaseRef();
$(this.document).off("change", this._handleDocumentChange);
$(this.document).off("deleted", this._handleDocumentDeleted);
if (this._visibleRange) { // TextRange also refs the Document
this._visibleRange.dispose();
}
// If we're the Document's master editor, disconnecting from it has special meaning
if (this.document._masterEditor === this) {
this.document._makeNonEditable();
}
// Destroying us destroys any inline widgets we're hosting. Make sure their closeCallbacks
// run, at least, since they may also need to release Document refs
this._inlineWidgets.forEach(function (inlineWidget) {
inlineWidget.onClosed();
});
};
/**
* Handles Select All specially when we have a visible range in order to work around
* bugs in CodeMirror when lines are hidden.
*/
Editor.prototype._selectAllVisible = function () {
var startLine = this.getFirstVisibleLine(),
endLine = this.getLastVisibleLine();
this.setSelection({line: startLine, ch: 0},
{line: endLine, ch: this.document.getLine(endLine).length});
};
/**
* Ensures that the lines that are actually hidden in the inline editor correspond to
* the desired visible range.
*/
Editor.prototype._updateHiddenLines = function () {
if (this._visibleRange) {
var cm = this._codeMirror,
self = this;
cm.operation(function () {
// TODO: could make this more efficient by only iterating across the min-max line
// range of the union of all changes
var i;
for (i = 0; i < cm.lineCount(); i++) {
if (i < self._visibleRange.startLine || i > self._visibleRange.endLine) {
self._hideLine(i);
} else {
// Double-check that the set of NON-hidden lines matches our range too
console.assert(!cm.getLineHandle(i).hidden);
}
}
});
}
};
Editor.prototype._applyChanges = function (changeList) {
// _visibleRange has already updated via its own Document listener. See if this change caused
// it to lose sync. If so, our whole view is stale - signal our owner to close us.
if (this._visibleRange) {
if (this._visibleRange.startLine === null || this._visibleRange.endLine === null) {
$(this).triggerHandler("lostContent");
return;
}
}
// Apply text changes to CodeMirror editor
var cm = this._codeMirror;
cm.operation(function () {
var change, newText;
for (change = changeList; change; change = change.next) {
newText = change.text.join('\n');
if (!change.from || !change.to) {
if (change.from || change.to) {
console.assert(false, "Change record received with only one end undefined--replacing entire text");
}
cm.setValue(newText);
} else {
cm.replaceRange(newText, change.from, change.to);
}
}
});
// The update above may have inserted new lines - must hide any that fall outside our range
this._updateHiddenLines();
};
/**
* Responds to changes in the CodeMirror editor's text, syncing the changes to the Document.
* There are several cases where we want to ignore a CodeMirror change:
* - if we're the master editor, editor changes can be ignored because Document is already listening
* for our changes
* - if we're a secondary editor, editor changes should be ignored if they were caused by us reacting
* to a Document change
*/
Editor.prototype._handleEditorChange = function (event, editor, changeList) {
// we're currently syncing from the Document, so don't echo back TO the Document
if (this._duringSync) {
return;
}
// Secondary editor: force creation of "master" editor backing the model, if doesn't exist yet
this.document._ensureMasterEditor();
if (this.document._masterEditor !== this) {
// Secondary editor:
// we're not the ground truth; if we got here, this was a real editor change (not a
// sync from the real ground truth), so we need to sync from us into the document
// (which will directly push the change into the master editor).
// FUTURE: Technically we should add a replaceRange() method to Document and go through
// that instead of talking to its master editor directly. It's not clear yet exactly
// what the right Document API would be, though.
this._duringSync = true;
this.document._masterEditor._applyChanges(changeList);
this._duringSync = false;
// Update which lines are hidden inside our editor, since we're not going to go through
// _applyChanges() in our own editor.
this._updateHiddenLines();
}
// Else, Master editor:
// we're the ground truth; nothing else to do, since Document listens directly to us
// note: this change might have been a real edit made by the user, OR this might have
// been a change synced from another editor
CodeHintManager.handleChange(this);
};
/**
* Responds to changes in the Document's text, syncing the changes into our CodeMirror instance.
* There are several cases where we want to ignore a Document change:
* - if we're the master editor, Document changes should be ignored becuase we already have the right
* text (either the change originated with us, or it has already been set into us by Document)
* - if we're a secondary editor, Document changes should be ignored if they were caused by us sending
* the document an editor change that originated with us
*/
Editor.prototype._handleDocumentChange = function (event, doc, changeList) {
var change;
// we're currently syncing to the Document, so don't echo back FROM the Document
if (this._duringSync) {
return;
}
if (this.document._masterEditor !== this) {
// Secondary editor:
// we're not the ground truth; and if we got here, this was a Document change that
// didn't come from us (e.g. a sync from another editor, a direct programmatic change
// to the document, or a sync from external disk changes)... so sync from the Document
this._duringSync = true;
this._applyChanges(changeList);
this._duringSync = false;
}
// Else, Master editor:
// we're the ground truth; nothing to do since Document change is just echoing our
// editor changes
};
/**
* Responds to the Document's underlying file being deleted. The Document is now basically dead,
* so we must close.
*/
Editor.prototype._handleDocumentDeleted = function (event) {
// Pass the delete event along as the cause (needed in MultiRangeInlineEditor)
$(this).triggerHandler("lostContent", [event]);
};
/**
* Install singleton event handlers on the CodeMirror instance, translating them into multi-
* listener-capable jQuery events on the Editor instance.
*/
Editor.prototype._installEditorListeners = function () {
var self = this;
// FUTURE: if this list grows longer, consider making this a more generic mapping
// NOTE: change is a "private" event--others shouldn't listen to it on Editor, only on
// Document
this._codeMirror.setOption("onChange", function (instance, changeList) {
$(self).triggerHandler("change", [self, changeList]);
});
this._codeMirror.setOption("onKeyEvent", function (instance, event) {
$(self).triggerHandler("keyEvent", [self, event]);
return event.defaultPrevented; // false tells CodeMirror we didn't eat the event
});
this._codeMirror.setOption("onCursorActivity", function (instance) {
$(self).triggerHandler("cursorActivity", [self]);
});
this._codeMirror.setOption("onScroll", function (instance) {
// If this editor is visible, close all dropdowns on scroll.
// (We don't want to do this if we're just scrolling in a non-visible editor
// in response to some document change event.)
if (self.isFullyVisible()) {
Menus.closeAll();
}
$(self).triggerHandler("scroll", [self]);
// notify all inline widgets of a position change
self._fireWidgetOffsetTopChanged(self.getFirstVisibleLine() - 1);
});
// Convert CodeMirror onFocus events to EditorManager activeEditorChanged
this._codeMirror.setOption("onFocus", function () {
self._focused = true;
EditorManager._notifyActiveEditorChanged(self);
});
this._codeMirror.setOption("onBlur", function () {
self._focused = false;
// EditorManager only cares about other Editors gaining focus, so we don't notify it of anything here
});
};
/**
* Sets the contents of the editor and clears the undo/redo history. Dispatches a change event.
* Semi-private: only Document should call this.
* @param {!string} text
*/
Editor.prototype._resetText = function (text) {
var perfTimerName = PerfUtils.markStart("Edtitor._resetText()\t" + (!this.document || this.document.file.fullPath));
var cursorPos = this.getCursorPos(),
scrollPos = this.getScrollPos();
// This *will* fire a change event, but we clear the undo immediately afterward
this._codeMirror.setValue(text);
// Make sure we can't undo back to the empty state before setValue()
this._codeMirror.clearHistory();
// restore cursor and scroll positions
this.setCursorPos(cursorPos);
this.setScrollPos(scrollPos.x, scrollPos.y);
PerfUtils.addMeasurement(perfTimerName);
};
/**
* Gets the current cursor position within the editor. If there is a selection, returns whichever
* end of the range the cursor lies at.
* @param {boolean} expandTabs If true, return the actual visual column number instead of the character offset in
* the "ch" property.
* @return !{line:number, ch:number}
*/
Editor.prototype.getCursorPos = function (expandTabs) {
var cursor = this._codeMirror.getCursor();
if (expandTabs) {
var line = this._codeMirror.getRange({line: cursor.line, ch: 0}, cursor),
tabSize = Editor.getTabSize(),
column = 0,
i;
for (i = 0; i < line.length; i++) {
if (line[i] === '\t') {
column += (tabSize - (column % tabSize));
} else {
column++;
}
}
cursor.ch = column;
}
return cursor;
};
/**
* Sets the cursor position within the editor. Removes any selection.
* @param {number} line The 0 based line number.
* @param {number=} ch The 0 based character position; treated as 0 if unspecified.
*/
Editor.prototype.setCursorPos = function (line, ch) {
this._codeMirror.setCursor(line, ch);
};
/**
* Given a position, returns its index within the text (assuming \n newlines)
* @param {!{line:number, ch:number}}
* @return {number}
*/
Editor.prototype.indexFromPos = function (coords) {
return this._codeMirror.indexFromPos(coords);
};
/**
* Returns true if pos is between start and end (inclusive at both ends)
* @param {{line:number, ch:number}} pos
* @param {{line:number, ch:number}} start
* @param {{line:number, ch:number}} end
*
*/
Editor.prototype.posWithinRange = function (pos, start, end) {
var startIndex = this.indexFromPos(start),
endIndex = this.indexFromPos(end),
posIndex = this.indexFromPos(pos);
return posIndex >= startIndex && posIndex <= endIndex;
};
/**
* @return {boolean} True if there's a text selection; false if there's just an insertion point
*/
Editor.prototype.hasSelection = function () {
return this._codeMirror.somethingSelected();
};
/**
* Gets the current selection. Start is inclusive, end is exclusive. If there is no selection,
* returns the current cursor position as both the start and end of the range (i.e. a selection
* of length zero).
* @return {!{start:{line:number, ch:number}, end:{line:number, ch:number}}}
*/
Editor.prototype.getSelection = function () {
var selStart = this._codeMirror.getCursor(true),
selEnd = this._codeMirror.getCursor(false);
return { start: selStart, end: selEnd };
};
/**
* @return {!string} The currently selected text, or "" if no selection. Includes \n if the
* selection spans multiple lines (does NOT reflect the Document's line-endings style).
*/
Editor.prototype.getSelectedText = function () {
return this._codeMirror.getSelection();
};
/**
* Sets the current selection. Start is inclusive, end is exclusive. Places the cursor at the
* end of the selection range.
* @param {!{line:number, ch:number}} start
* @param {!{line:number, ch:number}} end
*/
Editor.prototype.setSelection = function (start, end) {
this._codeMirror.setSelection(start, end);
};
/**
* Selects word that the given pos lies within or adjacent to. If pos isn't touching a word
* (e.g. within a token like "//"), moves the cursor to pos without selecting a range.
* Adapted from selectWordAt() in CodeMirror v2.
* @param {!{line:number, ch:number}}
*/
Editor.prototype.selectWordAt = function (pos) {
var line = this.document.getLine(pos.line),
start = pos.ch,
end = pos.ch;
function isWordChar(ch) {
return (/\w/).test(ch) || ch.toUpperCase() !== ch.toLowerCase();
}
while (start > 0 && isWordChar(line.charAt(start - 1))) {
--start;
}
while (end < line.length && isWordChar(line.charAt(end))) {
++end;
}
this.setSelection({line: pos.line, ch: start}, {line: pos.line, ch: end});
};
/**
* Gets the total number of lines in the the document (includes lines not visible in the viewport)
* @returns {!number}
*/
Editor.prototype.lineCount = function () {
return this._codeMirror.lineCount();
};
/**
* Gets the number of the first visible line in the editor.
* @returns {number} The 0-based index of the first visible line.
*/
Editor.prototype.getFirstVisibleLine = function () {
return (this._visibleRange ? this._visibleRange.startLine : 0);
};
/**
* Gets the number of the last visible line in the editor.
* @returns {number} The 0-based index of the last visible line.
*/
Editor.prototype.getLastVisibleLine = function () {
return (this._visibleRange ? this._visibleRange.endLine : this.lineCount() - 1);
};
// FUTURE change to "hideLines()" API that hides a range of lines at once in a single operation, then fires offsetTopChanged afterwards.
/* Hides the specified line number in the editor
* @param {!number}
*/
Editor.prototype._hideLine = function (lineNumber) {
var value = this._codeMirror.hideLine(lineNumber);
// when this line is hidden, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(lineNumber);
return value;
};
/**
* Gets the total height of the document in pixels (not the viewport)
* @param {!boolean} includePadding
* @returns {!number} height in pixels
*/
Editor.prototype.totalHeight = function (includePadding) {
return this._codeMirror.totalHeight(includePadding);
};
/**
* Gets the scroller element from the editor.
* @returns {!HTMLDivElement} scroller
*/
Editor.prototype.getScrollerElement = function () {
return this._codeMirror.getScrollerElement();
};
/**
* Gets the root DOM node of the editor.
* @returns {Object} The editor's root DOM node.
*/
Editor.prototype.getRootElement = function () {
return this._codeMirror.getWrapperElement();
};
/**
* Gets the lineSpace element within the editor (the container around the individual lines of code).
* FUTURE: This is fairly CodeMirror-specific. Logic that depends on this may break if we switch
* editors.
* @returns {Object} The editor's lineSpace element.
*/
Editor.prototype._getLineSpaceElement = function () {
return $(".CodeMirror-lines", this.getScrollerElement()).children().get(0);
};
/**
* Returns the current scroll position of the editor.
* @returns {{x:number, y:number}} The x,y scroll position in pixels
*/
Editor.prototype.getScrollPos = function () {
return this._codeMirror.getScrollInfo();
};
/**
* Sets the current scroll position of the editor.
* @param {number} x scrollLeft position in pixels
* @param {number} y scrollTop position in pixels
*/
Editor.prototype.setScrollPos = function (x, y) {
this._codeMirror.scrollTo(x, y);
};
/**
* Adds an inline widget below the given line. If any inline widget was already open for that
* line, it is closed without warning.
* @param {!{line:number, ch:number}} pos Position in text to anchor the inline.
* @param {!InlineWidget} inlineWidget The widget to add.
*/
Editor.prototype.addInlineWidget = function (pos, inlineWidget) {
var self = this;
inlineWidget.id = this._codeMirror.addInlineWidget(pos, inlineWidget.htmlContent, inlineWidget.height, function (id) {
self._removeInlineWidgetInternal(id);
inlineWidget.onClosed();
});
this._inlineWidgets.push(inlineWidget);
inlineWidget.onAdded();
// once this widget is added, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(pos.line);
};
/**
* Removes all inline widgets
*/
Editor.prototype.removeAllInlineWidgets = function () {
// copy the array because _removeInlineWidgetInternal will modifying the original
var widgets = [].concat(this.getInlineWidgets());
widgets.forEach(function (widget) {
this.removeInlineWidget(widget);
}, this);
};
/**
* Removes the given inline widget.
* @param {number} inlineWidget The widget to remove.
*/
Editor.prototype.removeInlineWidget = function (inlineWidget) {
var lineNum = this._getInlineWidgetLineNumber(inlineWidget);
// _removeInlineWidgetInternal will get called from the destroy callback in CodeMirror.
this._codeMirror.removeInlineWidget(inlineWidget.id);
// once this widget is removed, notify all following inline widgets of a position change
this._fireWidgetOffsetTopChanged(lineNum);
};
/**
* Cleans up the given inline widget from our internal list of widgets.
* @param {number} inlineId id returned by addInlineWidget().
*/
Editor.prototype._removeInlineWidgetInternal = function (inlineId) {
var i;
var l = this._inlineWidgets.length;
for (i = 0; i < l; i++) {
if (this._inlineWidgets[i].id === inlineId) {
this._inlineWidgets.splice(i, 1);
break;
}
}
};
/**
* Returns a list of all inline widgets currently open in this editor. Each entry contains the
* inline's id, and the data parameter that was passed to addInlineWidget().
* @return {!Array.<{id:number, data:Object}>}
*/
Editor.prototype.getInlineWidgets = function () {
return this._inlineWidgets;
};
/**
* Sets the height of an inline widget in this editor.
* @param {!InlineWidget} inlineWidget The widget whose height should be set.
* @param {!number} height The height of the widget.
* @param {boolean} ensureVisible Whether to scroll the entire widget into view.
*/
Editor.prototype.setInlineWidgetHeight = function (inlineWidget, height, ensureVisible) {
var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id),
oldHeight = (info && info.height) || 0;
this._codeMirror.setInlineWidgetHeight(inlineWidget.id, height, ensureVisible);
// update position for all following inline editors
if (oldHeight !== height) {
var lineNum = this._getInlineWidgetLineNumber(inlineWidget);
this._fireWidgetOffsetTopChanged(lineNum);
}
};
/**
* @private
* Get the starting line number for an inline widget.
* @param {!InlineWidget} inlineWidget
* @return {number} The line number of the widget or -1 if not found.
*/
Editor.prototype._getInlineWidgetLineNumber = function (inlineWidget) {
var info = this._codeMirror.getInlineWidgetInfo(inlineWidget.id);
return (info && info.line) || -1;
};
/**
* @private
* Fire "offsetTopChanged" events when inline editor positions change due to
* height changes of other inline editors.
* @param {!InlineWidget} inlineWidget
*/
Editor.prototype._fireWidgetOffsetTopChanged = function (lineNum) {
var self = this,
otherLineNum;
this.getInlineWidgets().forEach(function (other) {
otherLineNum = self._getInlineWidgetLineNumber(other);
if (otherLineNum > lineNum) {
$(other).triggerHandler("offsetTopChanged");
}
});
};
/** Gives focus to the editor control */
Editor.prototype.focus = function () {
this._codeMirror.focus();
};
/** Returns true if the editor has focus */
Editor.prototype.hasFocus = function () {
return this._focused;
};
/**
* Re-renders the editor UI
*/
Editor.prototype.refresh = function () {
this._codeMirror.refresh();
};
/**
* Re-renders the editor, and all children inline editors.
*/
Editor.prototype.refreshAll = function () {
this.refresh();
this.getInlineWidgets().forEach(function (multilineEditor, i, arr) {
multilineEditor.sizeInlineWidgetToContents(true);
multilineEditor._updateRelatedContainer();
multilineEditor.editors.forEach(function (editor, j, arr) {
editor.refresh();
});
});
};
/**
* Shows or hides the editor within its parent. Does not force its ancestors to
* become visible.
* @param {boolean} show true to show the editor, false to hide it
*/
Editor.prototype.setVisible = function (show) {
$(this.getRootElement()).css("display", (show ? "" : "none"));
this._codeMirror.refresh();
if (show) {
this._inlineWidgets.forEach(function (inlineWidget) {
inlineWidget.onParentShown();
});
}
};
/**
* Returns true if the editor is fully visible--i.e., is in the DOM, all ancestors are
* visible, and has a non-zero width/height.
*/
Editor.prototype.isFullyVisible = function () {
return $(this.getRootElement()).is(":visible");
};
/**
* Gets the syntax-highlighting mode for the current selection or cursor position. (The mode may
* vary within one file due to embedded languages, e.g. JS embedded in an HTML script block).
*
* Returns null if the mode at the start of the selection differs from the mode at the end -
* an *approximation* of whether the mode is consistent across the whole range (a pattern like
* A-B-A would return A as the mode, not null).
*
* @return {?(Object|String)} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}.
*/
Editor.prototype.getModeForSelection = function () {
var sel = this.getSelection();
// Check for mixed mode info (meaning mode varies depending on position)
// TODO (#921): this only works for certain mixed modes; some do not expose this info
var startState = this._codeMirror.getTokenAt(sel.start).state;
if (startState.mode) {
var startMode = startState.mode;
// If mixed mode, check that mode is the same at start & end of selection
if (sel.start.line !== sel.end.line || sel.start.ch !== sel.end.ch) {
var endState = this._codeMirror.getTokenAt(sel.end).state;
var endMode = endState.mode;
if (startMode !== endMode) {
return null;
}
}
return startMode;
} else {
// Mode does not vary: just use the editor-wide mode
return this._codeMirror.getOption("mode");
}
};
/**
* Gets the syntax-highlighting mode for the document.
*
* @return {Object|String} Object or Name of syntax-highlighting mode; see {@link EditorUtils#getModeFromFileExtension()}.
*/
Editor.prototype.getModeForDocument = function () {
return this._codeMirror.getOption("mode");
};
/**
* Sets the syntax-highlighting mode for the document.
*
* @param {string} mode Name of syntax highlighting mode.
*/
Editor.prototype.setModeForDocument = function (mode) {
this._codeMirror.setOption("mode", mode);
};
/**
* The Document we're bound to
* @type {!Document}
*/
Editor.prototype.document = null;
/**
* If true, we're in the middle of syncing to/from the Document. Used to ignore spurious change
* events caused by us (vs. change events caused by others, which we need to pay attention to).
* @type {!boolean}
*/
Editor.prototype._duringSync = false;
/**
* @private
* NOTE: this is actually "semi-private": EditorManager also accesses this field... as well as
* a few other modules. However, we should try to gradually move most code away from talking to
* CodeMirror directly.
* @type {!CodeMirror}
*/
Editor.prototype._codeMirror = null;
/**
* @private
* @type {!Array.<{id:number, data:Object}>}
*/
Editor.prototype._inlineWidgets = null;
/**
* @private
* @type {?TextRange}
*/
Editor.prototype._visibleRange = null;
// Global settings that affect all Editor instances (both currently open Editors as well as those created
// in the future)
/**
* Sets whether to use tab characters (vs. spaces) when inserting new text. Affects all Editors.
* @param {boolean} value
*/
Editor.setUseTabChar = function (value) {
_useTabChar = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("indentWithTabs", _useTabChar);
});
_prefs.setValue("useTabChar", Boolean(_useTabChar));
};
/** @type {boolean} Gets whether all Editors use tab characters (vs. spaces) when inserting new text */
Editor.getUseTabChar = function (value) {
return _useTabChar;
};
/**
* Sets tab character width. Affects all Editors.
* @param {number} value
*/
Editor.setTabSize = function (value) {
_tabSize = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("tabSize", _tabSize);
});
_prefs.setValue("tabSize", _tabSize);
};
/** @type {number} Get indent unit */
Editor.getTabSize = function (value) {
return _tabSize;
};
/**
* Sets indentation width. Affects all Editors.
* @param {number} value
*/
Editor.setIndentUnit = function (value) {
_indentUnit = value;
_instances.forEach(function (editor) {
editor._codeMirror.setOption("indentUnit", _indentUnit);
});
_prefs.setValue("indentUnit", _indentUnit);
};
/** @type {number} Get indentation width */
Editor.getIndentUnit = function (value) {
return _indentUnit;
};
// Global commands that affect the currently focused Editor instance, wherever it may be
CommandManager.register(Strings.CMD_SELECT_ALL, Commands.EDIT_SELECT_ALL, _handleSelectAll);
// Define public API
exports.Editor = Editor;
});
| nikmeiser/temboo-geocode | node_modules/brackets/brackets-src/src/editor/Editor.js | JavaScript | mit | 49,257 |
using System;
using System.Collections.Generic;
using System.Text;
namespace WilliamWsy.RegexGenerator
{
public abstract class RegexLookaroundAssertionNode
: RegexNode
{
public RegexLookaroundAssertionNode(string pattern, int? min = null, int? max = null, RegexQuantifierOption quantifierOption = RegexQuantifierOption.Greedy)
: base(pattern, min, max, quantifierOption)
{
}
public RegexLookaroundAssertionNode(RegexNode innerNode, int? min = null, int? max = null, RegexQuantifierOption quantifierOption = RegexQuantifierOption.Greedy)
: base(innerNode, min, max, quantifierOption)
{
}
}
}
| WilliamWsyHK/RegexGenerator | src/RegexGenerator/RegexLookaroundAssertionNode.cs | C# | mit | 688 |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import { HotKeyRegistry } from 'insomnia-common';
import React, { PureComponent } from 'react';
import { AUTOBIND_CFG, DEBOUNCE_MILLIS, SortOrder } from '../../../common/constants';
import { hotKeyRefs } from '../../../common/hotkeys';
import { executeHotKey } from '../../../common/hotkeys-listener';
import { KeydownBinder } from '../keydown-binder';
import { SidebarCreateDropdown } from './sidebar-create-dropdown';
import { SidebarSortDropdown } from './sidebar-sort-dropdown';
interface Props {
onChange: (value: string) => Promise<void>;
requestCreate: () => void;
requestGroupCreate: () => void;
sidebarSort: (sortOrder: SortOrder) => void;
filter: string;
hotKeyRegistry: HotKeyRegistry;
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class SidebarFilter extends PureComponent<Props> {
_input: HTMLInputElement | null = null;
_triggerTimeout: NodeJS.Timeout | null = null;
_setInputRef(n: HTMLInputElement) {
this._input = n;
}
_handleClearFilter() {
this.props.onChange('');
if (this._input) {
this._input.value = '';
this._input.focus();
}
}
_handleOnChange(e: React.SyntheticEvent<HTMLInputElement>) {
const value = e.currentTarget.value;
if (this._triggerTimeout) {
clearTimeout(this._triggerTimeout);
}
this._triggerTimeout = setTimeout(() => {
this.props.onChange(value);
}, DEBOUNCE_MILLIS);
}
_handleRequestGroupCreate() {
this.props.requestGroupCreate();
}
_handleRequestCreate() {
this.props.requestCreate();
}
_handleKeydown(event: KeyboardEvent) {
executeHotKey(event, hotKeyRefs.SIDEBAR_FOCUS_FILTER, () => {
this._input?.focus();
});
}
render() {
const { filter, hotKeyRegistry, sidebarSort } = this.props;
return (
<KeydownBinder onKeydown={this._handleKeydown}>
<div className="sidebar__filter">
<div className="form-control form-control--outlined form-control--btn-right">
<input
ref={this._setInputRef}
type="text"
placeholder="Filter"
defaultValue={filter}
onChange={this._handleOnChange}
/>
{filter && (
<button className="form-control__right" onClick={this._handleClearFilter}>
<i className="fa fa-times-circle" />
</button>
)}
</div>
<SidebarSortDropdown handleSort={sidebarSort} />
<SidebarCreateDropdown
handleCreateRequest={this._handleRequestCreate}
handleCreateRequestGroup={this._handleRequestGroupCreate}
hotKeyRegistry={hotKeyRegistry}
/>
</div>
</KeydownBinder>
);
}
}
| getinsomnia/insomnia | packages/insomnia-app/app/ui/components/sidebar/sidebar-filter.tsx | TypeScript | mit | 2,804 |
package com.mansonheart.data;
import java.util.Objects;
/**
* Created by alexandr on 18.09.16.
*/
public class Repository {
public Object get() {
return new Object();
}
public void add(Object object) {
}
}
| ZherebtsovAlexandr/Object-oriented-robot | sample/ObjectOrientedRobot/Data/src/com/mansonheart/data/Repository.java | Java | mit | 238 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Utilities.Editor;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input.Editor
{
[CustomEditor(typeof(SpeechInputHandler))]
public class SpeechInputHandlerInspector : BaseInputHandlerInspector
{
private static readonly GUIContent RemoveButtonContent = new GUIContent("-", "Remove keyword");
private static readonly GUIContent AddButtonContent = new GUIContent("+", "Add keyword");
private static readonly GUIContent KeywordContent = new GUIContent("Keyword", "Speech keyword item");
private static readonly GUILayoutOption MiniButtonWidth = GUILayout.Width(20.0f);
private string[] distinctRegisteredKeywords;
private SerializedProperty keywordsProperty;
private SerializedProperty persistentKeywordsProperty;
private SerializedProperty speechConfirmationTooltipPrefabProperty;
protected override void OnEnable()
{
base.OnEnable();
keywordsProperty = serializedObject.FindProperty("keywords");
persistentKeywordsProperty = serializedObject.FindProperty("persistentKeywords");
speechConfirmationTooltipPrefabProperty = serializedObject.FindProperty("speechConfirmationTooltipPrefab");
if (MixedRealityInspectorUtility.CheckMixedRealityConfigured(false))
{
distinctRegisteredKeywords = GetDistinctRegisteredKeywords();
}
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
bool enabled = CheckMixedRealityToolkit();
if (enabled)
{
if (!MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled)
{
EditorGUILayout.HelpBox("No input system is enabled, or you need to specify the type in the main configuration profile.", MessageType.Warning);
}
if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile == null)
{
EditorGUILayout.HelpBox("No Input System Profile Found, be sure to specify a profile in the main configuration profile.", MessageType.Error);
enabled = false;
}
else if (MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile == null)
{
EditorGUILayout.HelpBox("No Speech Commands profile Found, be sure to specify a profile in the Input System's configuration profile.", MessageType.Error);
enabled = false;
}
}
bool validKeywords = distinctRegisteredKeywords != null && distinctRegisteredKeywords.Length != 0;
// If we should be enabled but there are no valid keywords, alert developer
if (enabled && !validKeywords)
{
distinctRegisteredKeywords = GetDistinctRegisteredKeywords();
EditorGUILayout.HelpBox("No keywords registered. Some properties may not be editable.\n\nKeywords can be registered via Speech Commands Profile on the Mixed Reality Toolkit's Configuration Profile.", MessageType.Error);
}
enabled = enabled && validKeywords;
serializedObject.Update();
EditorGUILayout.PropertyField(persistentKeywordsProperty);
EditorGUILayout.PropertyField(speechConfirmationTooltipPrefabProperty);
bool wasGUIEnabled = GUI.enabled;
GUI.enabled = enabled;
ShowList(keywordsProperty);
GUI.enabled = wasGUIEnabled;
serializedObject.ApplyModifiedProperties();
// error and warning messages
if (keywordsProperty.arraySize == 0)
{
EditorGUILayout.HelpBox("No keywords have been assigned!", MessageType.Warning);
}
else
{
var handler = (SpeechInputHandler)target;
string duplicateKeyword = handler.Keywords
.GroupBy(keyword => keyword.Keyword.ToLower())
.Where(group => group.Count() > 1)
.Select(group => group.Key).FirstOrDefault();
if (duplicateKeyword != null)
{
EditorGUILayout.HelpBox($"Keyword \'{duplicateKeyword}\' is assigned more than once!", MessageType.Warning);
}
}
}
private void ShowList(SerializedProperty list)
{
using (new EditorGUI.IndentLevelScope())
{
// remove the keywords already assigned from the registered list
var handler = (SpeechInputHandler)target;
var availableKeywords = System.Array.Empty<string>();
if (handler.Keywords != null && distinctRegisteredKeywords != null)
{
availableKeywords = distinctRegisteredKeywords.Except(handler.Keywords.Select(keywordAndResponse => keywordAndResponse.Keyword)).ToArray();
}
// keyword rows
for (int index = 0; index < list.arraySize; index++)
{
// the element
SerializedProperty speechCommandProperty = list.GetArrayElementAtIndex(index);
GUILayout.BeginHorizontal();
bool elementExpanded = EditorGUILayout.PropertyField(speechCommandProperty);
GUILayout.FlexibleSpace();
// the remove element button
bool elementRemoved = GUILayout.Button(RemoveButtonContent, EditorStyles.miniButton, MiniButtonWidth);
GUILayout.EndHorizontal();
if (elementRemoved)
{
list.DeleteArrayElementAtIndex(index);
if (index == list.arraySize)
{
EditorGUI.indentLevel--;
return;
}
}
SerializedProperty keywordProperty = speechCommandProperty.FindPropertyRelative("keyword");
bool invalidKeyword = true;
if (distinctRegisteredKeywords != null)
{
foreach (string keyword in distinctRegisteredKeywords)
{
if (keyword == keywordProperty.stringValue)
{
invalidKeyword = false;
break;
}
}
}
if (invalidKeyword)
{
EditorGUILayout.HelpBox("Registered keyword is not recognized in the speech command profile!", MessageType.Error);
}
if (!elementRemoved && elementExpanded)
{
Rect position = EditorGUILayout.GetControlRect();
using (new EditorGUI.PropertyScope(position, KeywordContent, keywordProperty))
{
string[] keywords = availableKeywords.Concat(new[] { keywordProperty.stringValue }).OrderBy(keyword => keyword).ToArray();
int previousSelection = ArrayUtility.IndexOf(keywords, keywordProperty.stringValue);
int currentSelection = EditorGUILayout.Popup(KeywordContent, previousSelection, keywords);
if (currentSelection != previousSelection)
{
keywordProperty.stringValue = keywords[currentSelection];
}
}
SerializedProperty responseProperty = speechCommandProperty.FindPropertyRelative("response");
EditorGUILayout.PropertyField(responseProperty, true);
}
}
// add button row
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
// the add element button
if (GUILayout.Button(AddButtonContent, EditorStyles.miniButton, MiniButtonWidth))
{
var index = list.arraySize;
list.InsertArrayElementAtIndex(index);
var elementProperty = list.GetArrayElementAtIndex(index);
SerializedProperty keywordProperty = elementProperty.FindPropertyRelative("keyword");
keywordProperty.stringValue = string.Empty;
}
}
}
}
private static string[] GetDistinctRegisteredKeywords()
{
if (!MixedRealityToolkit.IsInitialized ||
!MixedRealityToolkit.Instance.HasActiveProfile ||
!MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled ||
MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile == null ||
MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands.Length == 0)
{
return null;
}
List<string> keywords = new List<string>();
var speechCommands = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands;
for (var i = 0; i < speechCommands.Length; i++)
{
keywords.Add(speechCommands[i].Keyword);
}
return keywords.Distinct().ToArray();
}
}
} | SystemFriend/HoloLensUnityChan | Assets/MRTK/SDK/Inspectors/Input/Handlers/SpeechInputHandlerInspector.cs | C# | mit | 10,111 |
<?php
namespace AppBundle\Service\OAuth\UserResponseHandler;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Interface ResponseHandlerInterface
* @package AppBundle\Service\OAuth\UserResponseHandler
*/
interface ResponseHandlerInterface
{
/**
* @param UserResponseInterface $response
*
* @return UserInterface
*/
public function processOauthUserResponse(UserResponseInterface $response): UserInterface;
} | SenseyePrototype/SenseyePrototype | src/AppBundle/Service/OAuth/UserResponseHandler/ResponseHandlerInterface.php | PHP | mit | 518 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if NETFX_CORE
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI;
using Windows.UI.Xaml.Media;
#else
using System.Windows;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Media;
#endif
namespace TestApplication.Shared
{
public class StringToBrushConverter : IValueConverter
{
#if NETFX_CORE
public object Convert(object value, Type targetType, object parameter, string language)
{
return InternalConvert(value, targetType, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
#else
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return InternalConvert(value, targetType, parameter);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endif
public object InternalConvert(object value, Type targetType, object parameter)
{
if (value == null)
{
return null;
}
string colorName = value.ToString();
SolidColorBrush scb = new SolidColorBrush();
switch (colorName as string)
{
case "Magenta":
scb.Color = Colors.Magenta;
return scb;
case "Purple":
scb.Color = Colors.Purple;
return scb;
case "Brown":
scb.Color = Colors.Brown;
return scb;
case "Orange":
scb.Color = Colors.Orange;
return scb;
case "Blue":
scb.Color = Colors.Blue;
return scb;
case "Red":
scb.Color = Colors.Red;
return scb;
case "Yellow":
scb.Color = Colors.Yellow;
return scb;
case "Green":
scb.Color = Colors.Green;
return scb;
default:
return null;
}
}
}
}
| xinjiguaike/pomodoro-keeper | TestApplication.Shared/Controls/StringToBrushConverter.cs | C# | mit | 2,567 |
'use strict';
/**
* Email.js service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
const _ = require('lodash');
const sendmail = require('sendmail')({
silent: true
});
module.exports = {
send: (options, cb) => {
return new Promise((resolve, reject) => {
// Default values.
options = _.isObject(options) ? options : {};
options.from = options.from || '"Administration Panel" <no-reply@strapi.io>';
options.replyTo = options.replyTo || '"Administration Panel" <no-reply@strapi.io>';
options.text = options.text || options.html;
options.html = options.html || options.text;
// Send the email.
sendmail({
from: options.from,
to: options.to,
replyTo: options.replyTo,
subject: options.subject,
text: options.text,
html: options.html
}, function (err) {
if (err) {
reject([{ messages: [{ id: 'Auth.form.error.email.invalid' }] }]);
} else {
resolve();
}
});
});
}
};
| strapi/strapi-examples | jekyll-strapi-tutorial/api/plugins/email/services/Email.js | JavaScript | mit | 1,088 |
package se.sciion.quake2d.level;
import java.io.File;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.ObjectMap;
import se.sciion.quake2d.ai.behaviour.BehaviourTree;
import se.sciion.quake2d.level.items.Weapon;
public class Statistics {
private ObjectMap<BehaviourTree,Float> totalDamageGiven;
private ObjectMap<BehaviourTree,Float> totalDamageTaken;
private ObjectMap<BehaviourTree,Float> armorAtEnd;
private ObjectMap<BehaviourTree,Float> healthAtEnd;
private ObjectMap<BehaviourTree,Boolean> survived;
private ObjectMap<BehaviourTree,Integer> killcount;
private ObjectMap<BehaviourTree,Integer> roundsPlayed;
private ObjectMap<BehaviourTree,Integer> pickedWeapon;
public Statistics() {
totalDamageGiven = new ObjectMap<BehaviourTree,Float>();
totalDamageTaken = new ObjectMap<BehaviourTree,Float>();
armorAtEnd = new ObjectMap<BehaviourTree,Float>();
healthAtEnd = new ObjectMap<BehaviourTree,Float>();
survived = new ObjectMap<BehaviourTree,Boolean>();
killcount = new ObjectMap<BehaviourTree,Integer>();
roundsPlayed = new ObjectMap<BehaviourTree, Integer>();
pickedWeapon = new ObjectMap<BehaviourTree, Integer>();
}
public void recordDamageTaken(BehaviourTree giver, BehaviourTree reciever, float amount) {
if(giver != null) {
if(!totalDamageGiven.containsKey(giver)) {
totalDamageGiven.put(giver, 0.0f);
}
totalDamageGiven.put(giver, totalDamageGiven.get(giver) + amount);
}
if(reciever != null) {
if(!totalDamageTaken.containsKey(reciever)) {
totalDamageTaken.put(reciever, 0.0f);
}
totalDamageTaken.put(reciever, totalDamageTaken.get(reciever) + amount);
}
}
public void recordHealth(float health, float armor, BehaviourTree entity) {
if(entity == null) {
return;
}
armorAtEnd.put(entity, armor);
healthAtEnd.put(entity, health);
}
public void recordWeaponPickup(BehaviourTree tree){
if(!pickedWeapon.containsKey(tree)){
pickedWeapon.put(tree, 0);
}
pickedWeapon.put(tree, pickedWeapon.get(tree) + 1);
}
public void recordParticipant(BehaviourTree tree){
if(!roundsPlayed.containsKey(tree)){
roundsPlayed.put(tree, 0);
}
roundsPlayed.put(tree, roundsPlayed.get(tree) + 1);
}
public void recordSurvivior(BehaviourTree entity) {
if(entity == null) {
return;
}
survived.put(entity, true);
}
public void recordKill(BehaviourTree giver) {
if(giver == null) {
return;
}
if(!killcount.containsKey(giver)) {
killcount.put(giver, 0);
}
killcount.put(giver, killcount.get(giver) + 1);
}
public float getFitness(BehaviourTree tree) {
float damageGiven = totalDamageGiven.get(tree, 0.0f);
float damageTaken = totalDamageTaken.get(tree, 0.0f);
float armor = armorAtEnd.get(tree, 0.0f);
//float health = healthAtEnd.get(tree,0.0f);
int killcount = this.killcount.get(tree, 0);
boolean survived = this.survived.get(tree, false);
int rounds = roundsPlayed.get(tree,1);
int weapon = pickedWeapon.get(tree, 0);
return (5.0f * damageGiven + 2.0f * armor + (survived ? 500.0f : 0.0f) + 50.0f * weapon + 1000.0f * killcount) / (float)(rounds);
}
public boolean hasSurvived(BehaviourTree tree) {
return survived.get(tree, false);
}
public int getTotalKillcount() {
int total = 0;
for(Integer i: killcount.values()) {
total += i;
}
return total;
}
@Override
public String toString() {
String output = "Match statistics:\n";
for(BehaviourTree tree: totalDamageGiven.keys()) {
output += "Tree: " + tree.toString() + " damage given: " + totalDamageGiven.get(tree) + "\n";
}
for(BehaviourTree tree: totalDamageTaken.keys()) {
output += "Tree: " + tree.toString() + " damage taken: " + totalDamageGiven.get(tree) + "\n";
}
for(BehaviourTree tree: healthAtEnd.keys()) {
output += "Tree: " + tree.toString() + " " + healthAtEnd.get(tree,0.0f) + " health at end\n";
}
for(BehaviourTree tree: armorAtEnd.keys()) {
output += "Tree: " + tree.toString() + " " + armorAtEnd.get(tree,0.0f) + " armor at end\n";
}
for(BehaviourTree tree: survived.keys()) {
output += "Tree: " + tree.toString() + " survived\n";
}
for(BehaviourTree tree: roundsPlayed.keys()) {
output += "Tree: " + tree.toString() + " played " + roundsPlayed.get(tree) + " rounds\n";
}
for(BehaviourTree tree: pickedWeapon.keys()) {
output += "Tree: " + tree.toString() + " picked weapon\n";
}
return output;
}
public void clear() {
armorAtEnd.clear();
healthAtEnd.clear();
killcount.clear();
survived.clear();
totalDamageGiven.clear();
totalDamageTaken.clear();
pickedWeapon.clear();
roundsPlayed.clear();
}
}
| sci10n/Quake2D | core/src/se/sciion/quake2d/level/Statistics.java | Java | mit | 4,664 |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title> Dados </title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Lanzamiento de dados del jugador 1:<input type="checkbox" name="dado1" required>
Lanzamiento de dados del jugador 2:<input type="checkbox" name="dado2" required><br>
<input type="submit" value="Enviar"><br>
<?php
$dado1 = $_POST['dado1'];
$dado2 = $_POST['dado2'];
if (isset($dado1)&& isset($dado2)) {
$tirada1 = mt_rand(1,6) + mt_rand(1,6);
echo "La tirada del jugador 1 es $tirada1 </br>";
$tirada2 = mt_rand(1,6) + mt_rand(1,6);
echo "La tirada del jugador 2 es $tirada2 </br>";
if ($tirada1 < $tirada2) {
echo "El jugador 2 gana";
}
elseif ($tirada1 == $tirada2) {
echo"Empate";
}
else {
echo "El jugador 1 gana";
}
}
else {
die("Ambos judadores deben lanzar dados");
}
?>
</body>
</html>
| RafaelAybar/EjerciciosPHP | Practicarecup/Práctica2/04_ejercicio.php | PHP | mit | 1,281 |
callback_functions = ["collision_enter", "collision_stay", "collision_exit"]
length_area_world = 75
raise_exception = False
# import all required modules
from game import *
from gameobject import *
from contracts import *
from configuration import *
from component import *
from loader import *
from physics import *
from scene import *
from timeutils import *
from builtincomponents import *
from builtincomponents.camera import *
from builtincomponents.collider import *
from builtincomponents.sprite_renderer import *
from builtincomponents.transform import * | temdisponivel/temdisponivellib_pygame | temdisponivellib/__init__.py | Python | mit | 564 |
using System.Threading.Tasks;
using BattleMech.WebAPI.PCL.Transports.CharacterProfile;
using BattleMech.WebAPI.PCL.Transports.Common;
using BattleMech.WebAPI.PCL.Transports.Internal;
namespace BattleMech.WebAPI.PCL.Handlers {
public class CharacterProfileHandler : BaseHandler {
public CharacterProfileHandler(HandlerItem handlerItem) : base(handlerItem, "CharacterProfile") { }
public async Task<CTI<CharacterProfileResponseItem>> GET() { return await GET<CTI<CharacterProfileResponseItem>>(string.Empty); }
}
} | jcapellman/BattleMech | BattleMech.WebAPI.lib/Handlers/CharacterProfileHandler.cs | C# | mit | 542 |
DS.classes.Message = function(create){
var relations = [];
//check
check(create, {
time: DS.classes.Time,
data: Match.Optional(Object)
});
//create
_.extend(this, create);
//add relations
this.addRelation = function(relation, reversed){
check(relation, DS.classes.Relation);
check(reversed, Boolean);
relations.push({
'relation': relation,
'reversed': reversed
});
};
this.getRelations = function(){
return relations;
}
};
| dpwoert/deepspace | packages/deepspace/classes/Message.js | JavaScript | mit | 556 |
#!/usr/bin/ruby
require 'sinatra'
require 'sinatra/json'
require 'json'
settings.public_folder = "client"
get '/' do
send_file File.join(
settings.public_folder,
"client.html"
)
end
get '/api' do
fp = "#{params['file_path']}/*"
files = []
folders = []
Dir.glob(fp).select do |f|
if (!File.directory? f) then
files.push File.basename(f)
else
folders.push File.basename(f)
end
end
json ({
:files => files,
:folders => folders
})
end
| mil/brows | server.rb | Ruby | mit | 493 |
from functools import reduce
# constants used in the multGF2 function
mask1 = mask2 = polyred = None
def setGF2(degree, irPoly):
"""Define parameters of binary finite field GF(2^m)/g(x)
- degree: extension degree of binary field
- irPoly: coefficients of irreducible polynomial g(x)
"""
def i2P(sInt):
"""Convert an integer into a polynomial"""
return [(sInt >> i) & 1
for i in reversed(range(sInt.bit_length()))]
global mask1, mask2, polyred
mask1 = mask2 = 1 << degree
mask2 -= 1
polyred = reduce(lambda x, y: (x << 1) + y, i2P(irPoly)[1:])
def multGF2(p1, p2):
"""Multiply two polynomials in GF(2^m)/g(x)"""
p = 0
while p2:
if p2 & 1:
p ^= p1
p1 <<= 1
if p1 & mask1:
p1 ^= polyred
p2 >>= 1
return p & mask2
if __name__ == "__main__":
# Define binary field GF(2^3)/x^3 + x + 1
setGF2(127, 2**127 + 2**63 + 1)
# Evaluate the product (x^2 + x + 1)(x^2 + 1)
print("{:02x}".format(multGF2(0x3f7e0000000000000000000000000000L, 0x3f7e00000000000000000000L))) | srijs/hwsl2-core | calc.py | Python | mit | 1,141 |
package com.cezarykluczynski.stapi.etl.template.starship_class.dto;
public class StarshipClassTemplateParameter {
public static final String NAME = "name";
public static final String OWNER = "owner";
public static final String OPERATOR = "operator";
public static final String AFFILIATION = "affiliation";
public static final String DECKS = "decks";
public static final String SPEED = "speed";
public static final String TYPE = "type";
public static final String ACTIVE = "active";
public static final String ARMAMENT = "armament";
}
| cezarykluczynski/stapi | etl/src/main/java/com/cezarykluczynski/stapi/etl/template/starship_class/dto/StarshipClassTemplateParameter.java | Java | mit | 546 |
'use strict';
import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
var products = [];
function addProducts(quantity) {
var startId = products.length;
for (var i = 0; i < quantity; i++) {
var id = startId + i;
products.push({
id: id,
name: "Item name " + id,
price: 100 + i
});
}
}
addProducts(5);
var order = 'desc';
export default class SortTable extends React.Component{
handleBtnClick = e => {
if(order === 'desc'){
this.refs.table.handleSort('asc', 'name');
order = 'asc';
} else {
this.refs.table.handleSort('desc', 'name');
order = 'desc';
}
}
render(){
return (
<div>
<p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p>
<button onClick={this.handleBtnClick}>Sort Product Name</button>
<BootstrapTable ref="table" data={products}>
<TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField="price">Product Price</TableHeaderColumn>
</BootstrapTable>
</div>
);
}
};
| opensourcegeek/react-bootstrap-table | examples/js/sort/sort-table.js | JavaScript | mit | 1,308 |
////////////////////////////////////////////////////////////////////////////////////
////// Events
////////////////////////////////////////////////////////////////////////////////////
'use strict';
// DI
var db,
responseHandler;
/**
*
* @param req the HTTP requests, contains header and body parameters
* @param res the callback to which send HTTP response
* @param next facilitate restify function chaining
*/
exports.findAll = function (req, res, next) {
req.check('appid', '"appid": must be a valid identifier').notNull();
var errors = req.validationErrors(),
appid;
if (errors) {
responseHandler(res).error(400, errors);
return;
}
appid = req.params.appid;
db.findAllEvents({'application_id': appid}, responseHandler(res, next));
};
/**
*
* @param req the HTTP requests, contains header and body parameters
* @param res the callback to which send HTTP response
* @param next facilitate restify function chaining
*/
exports.findById = function (req, res, next) {
req.check('appid', '"appid": must be a valid identifier').notNull();
req.check('eventid', '"eventid": must be a valid identifier').notNull();
var errors = req.validationErrors(),
appid,
eventid;
if (errors) {
responseHandler(res).error(400, errors);
return;
}
appid = req.params.appid;
eventid = req.params.eventid;
db.findEventById({'application_id': appid, 'event_id': eventid}, responseHandler(res, next));
};
/**
*
* @param req the HTTP requests, contains header and body parameters
* @param res the callback to which send HTTP response
* @param next facilitate restify function chaining
*/
exports.create = function (req, res, next) {
req.check('appid', '"appid": must be a valid identifier').notNull();
req.check('type', '"type": must be a valid identifier').notNull();
req.check('user', '"user": must be a valid identifier').notNull();
req.check('issued', '"date": must be a valid date').isDate();
var errors = req.validationErrors(),
appid,
type,
user,
issued;
if (errors) {
responseHandler(res).error(400, errors);
return;
}
appid = req.params.appid;
type = req.params.type;
user = req.params.user;
issued = req.params.issued; // or "2013-02-26"; // TODO today or specified
db.createEvent(
{'application_id': appid, 'type': type, 'user': user, 'issued': issued},
responseHandler(res, next)
);
};
| Gitification/gitification-server | controllers/events.js | JavaScript | mit | 2,351 |
'use strict';
const path = require('path');
const request = require('supertest');
const pedding = require('pedding');
const assert = require('assert');
const sleep = require('ko-sleep');
const mm = require('..');
const fixtures = path.join(__dirname, 'fixtures');
const baseDir = path.join(fixtures, 'app-event');
describe('test/app_event.test.js', () => {
afterEach(mm.restore);
describe('after ready', () => {
let app;
before(() => {
app = mm.app({
baseDir,
cache: false,
});
return app.ready();
});
after(() => app.close());
it('should listen by eventByRequest', done => {
done = pedding(3, done);
app.once('eventByRequest', done);
app.on('eventByRequest', done);
request(app.callback())
.get('/event')
.expect(200)
.expect('done', done);
});
});
describe('before ready', () => {
let app;
beforeEach(() => {
app = mm.app({
baseDir,
cache: false,
});
});
afterEach(() => app.ready());
afterEach(() => app.close());
it('should listen after app ready', done => {
done = pedding(2, done);
app.once('appReady', done);
app.on('appReady', done);
});
it('should listen after app instantiate', done => {
done = pedding(2, done);
app.once('appInstantiated', done);
app.on('appInstantiated', done);
});
});
describe('throw before app init', () => {
let app;
beforeEach(() => {
const baseDir = path.join(fixtures, 'app');
const customEgg = path.join(fixtures, 'error-framework');
app = mm.app({
baseDir,
customEgg,
cache: false,
});
});
afterEach(() => app.close());
it('should listen using app.on', done => {
app.on('error', err => {
assert(err.message === 'start error');
done();
});
});
it('should listen using app.once', done => {
app.once('error', err => {
assert(err.message === 'start error');
done();
});
});
it('should throw error from ready', function* () {
try {
yield app.ready();
} catch (err) {
assert(err.message === 'start error');
}
});
it('should close when app init failed', function* () {
app.once('error', () => {});
yield sleep(1000);
// app._app is undefined
yield app.close();
});
});
});
| eggjs/egg-mock | test/app_event.test.js | JavaScript | mit | 2,448 |
/*!
* Kaiseki
* Copyright(c) 2012 BJ Basañes / Shiki (shikishiji@gmail.com)
* MIT Licensed
*
* See the README.md file for documentation.
*/
var request = require('request');
var _ = require('underscore');
var Kaiseki = function(options) {
if (!_.isObject(options)) {
// Original signature
this.applicationId = arguments[0];
this.restAPIKey = arguments[1];
this.masterKey = null;
this.sessionToken = arguments[2] || null;
this.request = request;
this.baseURL = 'https://api.parse.com';
} else {
// New interface to allow masterKey and custom request function
options = options || {};
this.applicationId = options.applicationId;
this.restAPIKey = options.restAPIKey;
this.masterKey = options.masterKey || null;
this.sessionToken = options.sessionToken || null;
this.request = options.request || request;
this.baseURL = options.serverURL;
}
};
Kaiseki.prototype = {
applicationId: null,
restAPIKey: null,
masterKey: null, // required for deleting files
sessionToken: null,
createUser: function(data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/users',
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
getUser: function(objectId, params, callback) {
this._jsonRequest({
url: '/1/users/' + objectId,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
// Also used for validating a session token
// https://parse.com/docs/rest#users-validating
getCurrentUser: function(sessionToken, callback) {
if (_.isFunction(sessionToken)) {
callback = sessionToken;
sessionToken = undefined;
}
this._jsonRequest({
url: '/1/users/me',
sessionToken: sessionToken,
callback: callback
});
},
loginFacebookUser: function(facebookAuthData, callback) {
this._socialLogin({facebook: facebookAuthData}, callback);
},
loginTwitterUser: function(twitterAuthData, callback) {
this._socialLogin({twitter: twitterAuthData}, callback);
},
loginUser: function(username, password, callback) {
this._jsonRequest({
url: '/1/login',
params: {
username: username,
password: password
},
callback: callback
});
},
updateUser: function(objectId, data, callback) {
this._jsonRequest({
method: 'PUT',
url: '/1/users/' + objectId,
params: data,
callback: callback
});
},
deleteUser: function(objectId, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/users/' + objectId,
callback: callback
});
},
getUsers: function(params, callback) {
this._jsonRequest({
url: '/1/users',
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
requestPasswordReset: function(email, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/requestPasswordReset',
params: {'email': email},
callback: callback
});
},
createObjects: function(className, data, callback) {
var requests = [];
for (var i = 0; i < data.length; i++) {
requests.push({
'method': 'POST',
'path': '/1/classes/' + className,
'body': data[i]
});
}
this._jsonRequest({
method: 'POST',
url: '/1/batch/',
params: {
requests: requests
},
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
createObject: function(className, data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/classes/' + className,
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
getObject: function(className, objectId, params, callback) {
this._jsonRequest({
url: '/1/classes/' + className + '/' + objectId,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
updateObjects: function(className, updates, callback) {
var requests = [],
update = null;
for (var i = 0; i < updates.length; i++) {
update = updates[i];
requests.push({
'method': 'PUT',
'path': '/1/classes/' + className + '/' + update.objectId,
'body': update.data
});
}
this._jsonRequest({
method: 'POST',
url: '/1/batch/',
params: {
requests: requests
},
callback: callback
});
},
updateObject: function(className, objectId, data, callback) {
this._jsonRequest({
method: 'PUT',
url: '/1/classes/' + className + '/' + objectId,
params: data,
callback: callback
});
},
deleteObject: function(className, objectId, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/classes/' + className + '/' + objectId,
callback: callback
});
},
getObjects: function(className, params, callback) {
this._jsonRequest({
url: '/1/classes/' + className,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
countObjects: function(className, params, callback) {
var paramsMod = params;
if (_.isFunction(params)) {
paramsMod = {};
paramsMod['count'] = 1;
paramsMod['limit'] = 0;
} else {
paramsMod['count'] = 1;
paramsMod['limit'] = 0;
}
this._jsonRequest({
url: '/1/classes/' + className,
params: paramsMod,
callback: _.isFunction(params) ? params : callback
});
},
createRole: function(data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/roles',
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback(err, res, body, success);
}
});
},
getRole: function(objectId, params, callback) {
this._jsonRequest({
url: '/1/roles/' + objectId,
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
updateRole: function(objectId, data, callback) {
this._jsonRequest({
method: 'PUT',
url: '/1/roles/' + objectId,
params: data,
callback: callback
});
},
deleteRole: function(objectId, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/roles/' + objectId,
callback: callback
});
},
getRoles: function(params, callback) {
this._jsonRequest({
url: '/1/roles',
params: _.isFunction(params) ? null : params,
callback: _.isFunction(params) ? params : callback
});
},
uploadFile: function(filePath, fileName, callback) {
if (_.isFunction(fileName)) {
callback = fileName;
fileName = null;
}
var contentType = require('mime').lookup(filePath);
if (!fileName)
fileName = filePath.replace(/^.*[\\\/]/, ''); // http://stackoverflow.com/a/423385/246142
var buffer = require('fs').readFileSync(filePath);
this.uploadFileBuffer(buffer, contentType, fileName, callback);
},
uploadFileBuffer: function(buffer, contentType, fileName, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/files/' + fileName,
body: buffer,
headers: { 'Content-type': contentType },
callback: callback
});
},
deleteFile: function(name, callback) {
this._jsonRequest({
method: 'DELETE',
url: '/1/files/' + name,
callback: callback
});
},
sendPushNotification: function(data, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/push',
params: data,
callback: function(err, res, body, success) {
if (!err && success)
body = _.extend({}, data, body);
callback.apply(this, arguments);
}
});
},
sendAnalyticsEvent: function(eventName, dimensionsOrCallback, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/events/' + eventName,
params: _.isFunction(dimensionsOrCallback) ? {} : dimensionsOrCallback,
callback: _.isFunction(dimensionsOrCallback) ? dimensionsOrCallback : callback
});
},
stringifyParamValues: function(params) {
if (!params || _.isEmpty(params))
return null;
var values = _(params).map(function(value, key) {
if (_.isObject(value) || _.isArray(value))
return JSON.stringify(value);
else
return value;
});
var keys = _(params).keys();
var ret = {};
for (var i = 0; i < keys.length; i++)
ret[keys[i]] = values[i];
return ret;
},
_socialLogin: function(authData, callback) {
this._jsonRequest({
method: 'POST',
url: '/1/users',
params: {
authData: authData
},
callback: callback
});
},
_jsonRequest: function(opts) {
var sessionToken = opts.sessionToken || this.sessionToken;
opts = _.omit(opts, 'sessionToken');
opts = _.extend({
method: 'GET',
url: null,
params: null,
body: null,
headers: null,
callback: null
}, opts);
var reqOpts = {
method: opts.method,
headers: {
'X-Parse-Application-Id': this.applicationId,
'X-Parse-REST-API-Key': this.restAPIKey
}
};
if (sessionToken)
reqOpts.headers['X-Parse-Session-Token'] = sessionToken;
if (this.masterKey)
reqOpts.headers['X-Parse-Master-Key'] = this.masterKey;
if (opts.headers)
_.extend(reqOpts.headers, opts.headers);
if (opts.params) {
if (opts.method == 'GET')
opts.params = this.stringifyParamValues(opts.params);
var key = 'qs';
if (opts.method === 'POST' || opts.method === 'PUT')
key = 'json';
reqOpts[key] = opts.params;
} else if (opts.body) {
reqOpts.body = opts.body;
}
this.request(this.baseURL + opts.url, reqOpts, function(err, res, body) {
var isCountRequest = opts.params && !_.isUndefined(opts.params['count']) && !!opts.params.count;
var success = !err && res && (res.statusCode === 200 || res.statusCode === 201);
if (res && res.headers['content-type'] &&
res.headers['content-type'].toLowerCase().indexOf('application/json') >= 0) {
if (body != null && !_.isObject(body) && !_.isArray(body)) // just in case it's been parsed already
body = JSON.parse(body);
if (body != null) {
if (body.error) {
success = false;
} else if (body.results && _.isArray(body.results) && !isCountRequest) {
// If this is a "count" request. Don't touch the body/result.
body = body.results;
}
}
}
opts.callback(err, res, body, success);
});
}
};
module.exports = Kaiseki;
| GiantThinkwell/kaiseki | lib/kaiseki.js | JavaScript | mit | 11,280 |
# == Schema Information
#
# Table name: tags
#
# ID :integer not null, primary key
# Name :string(100)
# TagType :string(5) default("other"), not null
# Uses :integer default(1), not null
#
class Tag < ActiveRecord::Base
end
| XanderStrike/whatcd-browser | app/models/tag.rb | Ruby | mit | 266 |
(function(app) {
"use strict";
app.directive("ratingInput", [
"$rootScope", function($rootScope) {
return {
restrict: "A",
link: function($scope, $element, $attrs) {
$element.raty({
score: $attrs.cdRatingInput,
half: true,
halfShow: true,
starHalf: "/Content/Images/star-half-big.png",
starOff: "/Content/Images/star-off-big.png",
starOn: "/Content/Images/star-on-big.png",
hints: ["Poor", "Average", "Good", "Very Good", "Excellent"],
target: "#Rating",
targetKeep: true,
noRatedMsg: "Not Rated yet!",
scoreName: "Rating",
click: function(score) {
$rootScope.$broadcast("Broadcast::RatingAvailable", score);
}
});
}
};
}
]);
})(angular.module("books")); | shibbir/bookarena | Source/BookArena.Presentation/Scripts/books/directives/books.ratinginput.directive.js | JavaScript | mit | 1,138 |
{
"status": {
"error": false,
"code": 200,
"type": "success",
"message": "Success"
},
"pagination": {
"before_cursor": null,
"after_cursor": null,
"previous_link": null,
"next_link": null
},
"data": [
{
"id": 1111,
"name": "marketing"
}
]
}
| oswell/onelogin-go | testdata/get_roles.js | JavaScript | mit | 369 |
<?php
/**
* VersionControl_HG
* Simple OO implementation for Mercurial.
*
* PHP Version 5.4
*
* @copyright 2014 Siad Ardroumli
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link http://siad007.github.io/versioncontrol_hg
*/
namespace Siad007\VersionControl\HG\Command;
/**
* Simple OO implementation for Mercurial.
*
* @author Siad Ardroumli <siad.ardroumli@gmail.com>
*/
class TagsCommand extends BaseCommand
{
}
| siad007/versioncontrol_hg | src/Command/TagsCommand.php | PHP | mit | 452 |
// Copyright (c) 2017-2019 Jae-jun Kang
// See the file LICENSE for details.
using System.Reflection;
[assembly: AssemblyTitle("x2net.xpiler")]
[assembly: AssemblyDescription("x2net.xpiler")]
| jaykang920/x2net | src/xpiler/Properties/AssemblyInfo.cs | C# | mit | 197 |
import React from 'react'
import {Observable} from 'rx'
import {TextField} from 'material-ui'
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import MyRawTheme from '../components/Theme.js';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';
import {compose} from 'recompose'
import {observeProps, createEventHandler} from 'rx-recompose'
import {clickable} from '../style.css'
import {View} from '../components'
let Search = compose(
// ASDFGHJKL:
ThemeDecorator(ThemeManager.getMuiTheme(MyRawTheme))
,
observeProps(props$ => {
// Create search query observable
let setQuery = createEventHandler()
let query$ = setQuery.share()
query$
// Only search for songs that are not only spaces 😂
.filter(x => x.trim() !== '')
// Only every 300 ms
.debounce(300)
// Get the `doSearch` method from props
.withLatestFrom(props$.pluck('doSearch'), (query, doSearch) => doSearch(query))
// Search for the query
.subscribe(func => {
func()
})
return {
// Pass down function to set the query
setQuery: Observable.just(setQuery),
// Pass down the current query value
query: query$.startWith(''),
// Pass down force-search function when pressing enter
doSearch: props$.pluck('doSearch'),
// Function to start playing song when clicked on
playSong: props$.pluck('playSong'),
// Searchresults to display
searchResults:
Observable.merge(
// Results from the search
props$.pluck('results$') // Get results observable
.distinctUntilChanged() // Only when unique
.flatMapLatest(x => x) // Morph into the results$
.startWith([]) // And set off with a empty array
,
query$
// When query is only spaces
.filter(x => x.trim() === '')
// Reset the results to empty array
.map(() => [])
),
}
})
)(({query, setQuery, searchResults, playSong, doSearch}) => (
<View>
<TextField
hintText="Search for a song! :D"
onChange={(e,value) => setQuery(e.target.value)}
value={query}
onEnterKeyDown={doSearch(query)}
fullWidth={true}
underlineStyle={{borderWidth: 2}}
/>
<View>
{ /* List all the results */ }
{ searchResults.map(result =>
<View
key={result.nid}
className={clickable}
// On click, reset the query and play the song!
onClick={() => {
playSong(result)()
setQuery('')
}}
// Same as setting the text, but more compact
children={`${result.title} - ${result.artist}`}
/>
)}
</View>
</View>
))
export default Search
| dralletje/Tonlist | client/components/Search.js | JavaScript | mit | 2,794 |
(function(ns) {
/**
* JSON CORS utility
* Wraps up all the cors stuff into a simple post or get. Falls back to jsonp
*/
var JSONCORS = function() {
var self = this;
var supportsCORS = ('withCredentials' in new XMLHttpRequest()) || (typeof XDomainRequest != 'undefined');
/********************************************************************************/
// Utils
/********************************************************************************/
/**
* Serializes a dictionary into a url query
* @param m: the map to serialize
* @return the url query (no preceeding ?)
*/
var serializeURLQuery = function(m) {
var args = [];
for (var k in m) {
args.push(encodeURIComponent(k) + '=' + encodeURIComponent(m[k]))
}
return args.join('&');
};
/********************************************************************************/
// CORS
/********************************************************************************/
/**
* Performs a CORS request which wraps the response through our marshalled API
* @param url: the url to visit
* @param method: GET|POST the http method
* @param payload: the payload to send (undefined for GET)
* @param success: executed on success. Given response then http status then xhr
* @param failure: executed on failure. Given http status then error then xhr
* @return the XHR object
*/
self.requestCORS = function(url, method, payload, success, failure) {
method = method.toUpperCase();
var xhr;
if (typeof XDomainRequest != 'undefined') {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = new XMLHttpRequest();
xhr.open(method, url, true);
}
xhr.onload = function() {
var json;
try { json = JSON.parse(xhr.responseText); } catch(e) { /* noop */ }
var status = (json && json.http_status !== undefined) ? json.http_status : xhr.status;
if (status >= 200 && status <= 299) {
success(json, status, xhr);
} else {
failure(xhr.status, json ? json.error : undefined, xhr);
}
};
xhr.onerror = function() {
failure(xhr.status, undefined, xhr);
};
if (method === 'POST') {
xhr.setRequestHeader("Content-type","application/json");
xhr.send(JSON.stringify(payload));
} else {
xhr.send();
}
return xhr;
};
/********************************************************************************/
// JSONP
/********************************************************************************/
/**
* Performs a JSONP request which wraps the response through our marshalled API
* @param url: the url to visit
* @param method: GET|POST the http method
* @param payload: the payload to send (undefined for GET)
* @param success: executed on success. Given response then http status then xhr
* @param failure: executed on failure. Given http status then error then xhr
* @return the XHR object
*/
self.requestJSONP = function(url, method, payload, success, failure) {
method = method.toUpperCase();
var jsonp = document.createElement('script');
jsonp.type = 'text/javascript';
// Success callback
var id = '__jsonp_' + Math.ceil(Math.random() * 10000);
var dxhr = { jsonp:true, id:id, response:undefined };
window[id] = function(r) {
jsonp.parentElement.removeChild(jsonp);
delete window[id];
dxhr.response = r;
if (r === undefined || r === null) {
success(undefined, 200, dxhr);
} else {
if (r.http_status >= 200 && r.http_status <= 299) {
success(r, r.http_status, dxhr);
} else {
failure(r.http_status, r.error, dxhr);
}
}
};
// Error callback
jsonp.onerror = function() {
jsonp.parentElement.removeChild(jsonp);
dxhr.jsonp_transport_error = 'ScriptErrorFailure';
failure(0, undefined, dxhr);
};
var urlQuery;
if (method === 'POST') {
urlQuery = '?' + serializeURLQuery(payload) + '&callback=' + id + '&_=' + new Date().getTime();
} else {
urlQuery = '?' + 'callback=' + id + '&_=' + new Date().getTime();
}
jsonp.src = url + urlQuery;
document.head.appendChild(jsonp);
return dxhr;
};
/********************************************************************************/
// GET
/********************************************************************************/
/**
* Makes a get request
* @param url=/: the url to post to
* @param success=undefined: executed on http success with the response
* @param failure=undefined: executed on http failure
* @param complete=undefined: executed after http success or failure
* Returns either the xhr request or a jsonp holding object
*/
self.get = function(options) {
var method = supportsCORS ? 'requestCORS' : 'requestJSONP';
return self[method](options.url || window.location.href, 'GET', undefined, function(response, status, xhr) {
if (options.success) { options.success(response, status, xhr); }
if (options.complete) { options.complete(); }
}, function(status, error, xhr) {
if (options.failure) { options.failure(status, error, xhr); }
if (options.complete) { options.complete(); }
});
};
/********************************************************************************/
// POST
/********************************************************************************/
/**
* Makes a post request
* @param url=/: the url to post to
* @param payload={}: the payload to send
* @param success=undefined: executed on http success with the response
* @param failure=undefined: executed on http failure
* @param complete=undefined: executed after http success or failure
* Returns either the xhr request or a jsonp holding object
*/
self.post = function(options) {
var method = supportsCORS ? 'requestCORS' : 'requestJSONP';
return self[method](options.url || window.location.href, 'POST', options.payload || {}, function(response, status, xhr) {
if (options.success) { options.success(response, status, xhr); }
if (options.complete) { options.complete(); }
}, function(status, error, xhr) {
if (options.failure) { options.failure(status, error, xhr); }
if (options.complete) { options.complete(); }
});
};
return self;
};
ns.stacktodo = ns.stacktodo || {};
ns.stacktodo.core = ns.stacktodo.core || {};
ns.stacktodo.core.jsoncors = new JSONCORS();
})(window); | stacktodo/stacktodo_js_api | stacktodo/api/core/jsoncors.js | JavaScript | mit | 6,394 |
package fr.inria.jessy.transaction.termination.vote;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import fr.inria.jessy.ConstantPool;
/**
*
* @author Masoud Saeida Ardekani
*
*/
public class VotePiggyback implements Externalizable {
private static final long serialVersionUID = -ConstantPool.JESSY_MID;
Object piggyback;
public VotePiggyback() {
}
public VotePiggyback(Object piggyback) {
this.piggyback = piggyback;
}
public Object getPiggyback() {
return piggyback;
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
piggyback = in.readObject();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(piggyback);
}
}
| EvilMcJerkface/jessy | src/fr/inria/jessy/transaction/termination/vote/VotePiggyback.java | Java | mit | 817 |
{ //using constants
const a = 2;
console.log( a ); // 2
a = 3; // TypeError!
}
{ //an array constant
const a = [1,2,3];
a.push( 4 );
console.log( a ); // [1,2,3,4]
a = 42; // TypeError!
} //we can change the object using its methods, we just cannot reassign it...
| zerkotin/javascript | ES6/constants.js | JavaScript | mit | 284 |
import {ProviderSpecification} from 'dxref-core/system/provider/provider-specification';
import { module, test } from 'qunit';
module('Unit | dxref-core | system | provider | provider-specification');
test('provider-specification', function(assert) {
var myFunc = function() {};
var providerSpec = new ProviderSpecification(['VALUE$Date', 'A', 'B', 'C', myFunc]);
assert.deepEqual(providerSpec.getDependencies(), ['A', 'B', 'C']);
assert.strictEqual(providerSpec.getFunctionArg(), myFunc);
assert.equal(providerSpec.getOutputType(), 'VALUE$Date');
});
/** Validation of non-provider-specification conformance is tested in
the bootstrap-validators-test.js */ | jmccune/dxref-core | tests/unit/system/provider/provider-specification-test.js | JavaScript | mit | 685 |
version https://git-lfs.github.com/spec/v1
oid sha256:c1d57d1ad50c4639ecd398deb6c1db998e272cc6faf1314dec77ca509ca49153
size 1303
| yogeshsaroya/new-cdnjs | ajax/libs/uikit/2.10.0/js/addons/cover.min.js | JavaScript | mit | 129 |
require "active_support/core_ext/date/calculations"
require "active_support/core_ext/numeric/time"
require "active_support/core_ext/object/try"
require "google/api_client"
require "google/api_client/client_secrets"
require "ruboty"
require "time"
module Ruboty
module Handlers
class GoogleCalendar < Base
DEFAULT_CALENDAR_ID = "primary"
DEFAULT_DURATION = 1.day
env :GOOGLE_CALENDAR_ID, "Google Calendar ID (default: primary)", optional: true
env :GOOGLE_CLIENT_ID, "Client ID"
env :GOOGLE_CLIENT_SECRET, "Client Secret"
env :GOOGLE_REDIRECT_URI, "Redirect URI (http://localhost in most cases)"
env :GOOGLE_REFRESH_TOKEN, "Refresh token issued with access token"
on(
/list events( in (?<minute>\d+) minutes)?\z/,
description: "List events from Google Calendar",
name: "list_events",
)
def list_events(message)
event_items = client.list_events(
calendar_id: calendar_id,
duration: message[:minute].try(:to_i).try(:minute) || DEFAULT_DURATION,
).items
if event_items.size > 0
text = event_items.map do |item|
ItemView.new(item)
end.join("\n")
message.reply(text, code: true)
else
true
end
end
private
def calendar_id
ENV["GOOGLE_CALENDAR_ID"] || DEFAULT_CALENDAR_ID
end
def client
@client ||= Client.new(
client_id: ENV["GOOGLE_CLIENT_ID"],
client_secret: ENV["GOOGLE_CLIENT_SECRET"],
redirect_uri: ENV["GOOGLE_REDIRECT_URI"],
refresh_token: ENV["GOOGLE_REFRESH_TOKEN"],
)
end
class Client
APPLICATION_NAME = "ruboty-google_calendar"
AUTH_URI = "https://accounts.google.com/o/oauth2/auth"
SCOPE = "https://www.googleapis.com/auth/calendar"
TOKEN_URI = "https://accounts.google.com/o/oauth2/token"
def initialize(client_id: nil, client_secret: nil, redirect_uri: nil, refresh_token: nil)
@client_id = client_id
@client_secret = client_secret
@redirect_uri = redirect_uri
@refresh_token = refresh_token
authenticate!
end
# @param [String] calendar_id
# @param [ActiveSupport::Duration] duration
def list_events(calendar_id: nil, duration: nil)
api_client.execute(
api_method: calendar.events.list,
parameters: {
calendarId: calendar_id,
singleEvents: true,
orderBy: "startTime",
timeMin: Time.now.iso8601,
timeMax: duration.since.iso8601
}
).data
end
private
def api_client
@api_client ||= begin
_api_client = Google::APIClient.new(
application_name: APPLICATION_NAME,
application_version: Ruboty::GoogleCalendar::VERSION,
)
_api_client.authorization = authorization
_api_client.authorization.scope = SCOPE
_api_client
end
end
def authenticate!
api_client.authorization.fetch_access_token!
end
def authorization
client_secrets.to_authorization
end
def client_secrets
Google::APIClient::ClientSecrets.new(
flow: :installed,
installed: {
auth_uri: AUTH_URI,
client_id: @client_id,
client_secret: @client_secret,
redirect_uris: [@redirect_uri],
refresh_token: @refresh_token,
token_uri: TOKEN_URI,
},
)
end
def calendar
@calendar ||= api_client.discovered_api("calendar", "v3")
end
end
class ItemView
def initialize(item)
@item = item
end
def to_s
"#{started_at} - #{finished_at} #{summary}"
end
private
def all_day?
@item.start.date_time.nil?
end
def finished_at
case
when all_day?
"--:--"
when finished_in_same_day?
@item.end.date_time.localtime.strftime("%H:%M")
else
@item.end.date_time.localtime.strftime("%Y-%m-%d %H:%M")
end
end
def finished_in_same_day?
@item.start.date_time.localtime.day == @item.end.date_time.localtime.day
end
def started_at
if all_day?
"#{@item.start.date} --:--"
else
@item.start.date_time.localtime.strftime("%Y-%m-%d %H:%M")
end
end
def summary
@item.summary
end
end
end
end
end
| r7kamura/ruboty-google_calendar | lib/ruboty/handlers/google_calendar.rb | Ruby | mit | 4,793 |
package controller;
import java.text.DecimalFormat;
import util.Teclado;
public class Ex_5 {
public static void main(String[] args){
double salario;
salario = Teclado.lerDouble("Digite o salário desejado: ");
DecimalFormat df = new DecimalFormat("R$ ###, ###, ###.00");
System.out.println(df.format(salario));
}
}
| GiovanniSM20/Java | src/ExFixacao_02/src/controller/Ex_5.java | Java | mit | 330 |
team1 = {"name" : "Iron Patriot",
"key": "MURICA",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 1,
"eveningBufferIndex" : 0
}
team2 = {"name" : "War Machine",
"key": "WARMACHINEROX",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 2,
"eveningBufferIndex" : 0
}
team3 = {"name" : "Hulkbuster",
"key": "IRONSMASH",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 3,
"eveningBufferIndex" : 0
}
team4 = {"name" : "Mark I",
"key": "OLDSKOOL",
"puzzles" :
[{"idPz": 0}, // Breakfast
{"idPz": 1}, // Blueprints, all
{"idPz": 5}, // Morning Rotation # 4
// {"idPz": 17}, // Morning Rotation # 4 Item! (to alieviate routing issues slightly)
{"idPz": 2}, // Morning Rotation # 1
// {"idPz": 14}, // Morning Rotation # 1 Item! (to alieviate routing issues slightly)
{"idPz": 3}, // Morning Rotation # 2
// {"idPz": 15}, // Morning Rotation # 2 Item! (to alieviate routing issues slightly)
{"idPz": 4}, // Morning Rotation # 3
// {"idPz": 16}, // Morning Rotation # 3 Item! (to alieviate routing issues slightly)
{"idPz": 6}, // All together now.
{"idPz": 7}, // Lunch Time
{"idPz": 11}, // Evening Rotation # 4
{"idPz": 8}, // Evening Rotation # 1
{"idPz": 9}, // Evening Rotation # 2
{"idPz": 10}, // Evening Rotation # 3
{"idPz": 12}, // All together now (Blueprints)
{"idPz": 13}, // All together now (Final)
],
"wordweb":[],
"jarvisStream" : {},
"wordwebUnknown":[0],
"currentPuzzle" : 0,
"teamNum" : 4,
"eveningBufferIndex" : 0
}
allPuzzles = [{"name": "Breakfast", //0
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
// "showInput": false,
"endCondition" : {"websocket": "breakfastOver"},
// "puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>",
// ".mp3": null,
// "action": null},
"hint": [{"name": "Welcome to breakfast, relax, eat some.",
".mp3": null,
"trig": {'time': 10},
"action": null}]
},
{"name": "Blueprints", //1
"desc": "Our first Puzzle!",
"file": "./puzzles/puzzle1",
"estTime": 40,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"wrong": "Did you really think that was the right answer?",
"menace": true,
"insect": true,
"pluto": true,
"cable": true
},
"puzzIntro": {"name": "Go pick up physics quizzes",
".mp3": null,
"action": null},
"hint": [{"name": "This puzzle isn't about QR codes",
// ".mp3": "./audio/puzzle1/hint1",
"trig": {'time': 60*10},
"text": "I can't see what you're doing from here, but have you tried to stack them?",
"action": null},
{"name": "Look for letters",
// ".mp3": "./audio/puzzle1/hint1",
"trig": {'time': 60*15},
"text": "I can't see what you're doing from here, but have you tried to stack them?",
"action": null},
{"name": "You can use an anagram solver if you want",
// ".mp3": "./audio/puzzle1/hint1",
"trig": {'time': 60*20},
"text": "I can't see what you're doing from here, but have you tried to stack them?",
"action": null}]
},
{"name": "The Grid", //2
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"wolverine": true},
"puzzIntro": {"name": "We need you at the Admissions conference room",
".mp3": null,
"action": null},
"hint": [{"name": "It's a Sudoku",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*20},
"action": null},
{"name": "Oh look, semaphore!",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*25},
"action": null},
{"name": "You should probably look at it from the side the flags are on",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*30},
"action": null}]
},
{"name": "The Arc", //3
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"Colston": true},
"puzzIntro": {"name": "Eat",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Lasers", //4
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"nefaria": true},
"puzzIntro": {"name": "Spalding sub-basement",
".mp3": null,
"action": null},
"hint": [{"name": "If you give me power, I can give you information",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*15},
"action": null},
{"name": "The dates are important",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*15},
"action": null},
{"name": "Have you tried putting them in order?",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*20},
"action": null},
{"name": "More information about the songs is better (feel free to use Google)",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time': 60*25},
"action": null}]
},
{"name": "Rebus", //5
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"isStatPuzzle": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"Harold Hogan": true},
"puzzIntro": {"name": "Lloyd Deck",
".mp3": null,
"action": null},
"hint": [{"name": "The number of the puzzle will prove of use",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time':60*10},
"action": null},
{"name": "index puzzle answer by puzzle number",
// ".mp3": "./audio/puzzle2/hint1",
"trig": {'time':60*15},
"action": null}]
},
{"name": "Squares", //6 - Last before lunch
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"overlap": true,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"allSolveTogether": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"jhammer": true},
"puzzIntro": {"name": "Everyone meet at the BBB front patio",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Lunch", //7 - Lunch
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"showInput": false,
"endCondition" : {"websocket": "lunchOver"},
// "responses": {"": "You could try to give me something, anything before you press enter you know.",
// "answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "Teamwork", //8
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"isAfternoon" : true,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"stop hammer time!": true
},
"puzzIntro": {"name": "We need you at CDC 257",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Laserz", //9
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"isAfternoon" : true,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
"puzzIntro": {"name": "Moore (070 - 2)",
".mp3": null,
"action": null},
"hint": []
},
{"name": "The Game", //10
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"isAfternoon" : true,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"YAYYYYYYYYYyYYYyY": true},
"puzzIntro": {"name": "A projector room close to home",
".mp3": null,
"action": null},
"hint": []
},
{"name": "The Web", //11
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"endCondition" : {"websocket": "nextAfternoonPuzzle"},
"overlap": true,
"isAfternoon" : true,
"overlap": true,
"isWordWeb": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
"puzzIntro": {"name": "",
".mp3": null,
"action": null},
"hint": []
},
{"name": "Take two on Blueprints", //12
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"allSolveTogether": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "This is it", //13
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": false}, //Can't have a "correct answer" for the last puzzle, or else crash
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Mask", //14
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Glove", //15
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Core", //16
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
},
{"name": "The Repulsor", //17
"desc": "Our second Puzzle!",
"file": "./puzzles/puzzle2",
"estTime": 60,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true},
// "puzzIntro": {"name": "Eat",
// ".mp3": null,
// "action": null},
"hint": []
}
]
morningBuffers = [{"name": "First Square", //0
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"dues": true,
"birth": true,
"oracle": true,
"yolk": true
},
"puzzIntro": {"name": "<a href='squares/1987.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Second Square", //1
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"unix": true,
"choose": true,
"him": true,
"graft": true
},
"puzzIntro": {"name": "<a href='squares/2631.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Another Square", //2
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"seer": true,
"kraft": true,
"eunuchs": true
},
"puzzIntro": {"name": "<a href='squares/3237.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "The fourth", //3
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"paced": true,
"idle": true,
"paws": true,
"tea": true
},
"puzzIntro": {"name": "<a href='squares/4126.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Num Five.", //4
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"bode": true,
"idyll": true,
"grease": true,
"laze": true
},
"puzzIntro": {"name": "<a href='squares/5346.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Square six start", //5
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"lies": true,
"ax": true,
"tax": true,
"bask": true
},
"puzzIntro": {"name": "<a href='squares/6987.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Square 7 begin", //6
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"ail": true,
"tacks": true,
"yolk": true
},
"puzzIntro": {"name": "<a href='squares/7123.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Eight Squares In", //7
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"cedar": true,
"chorale": true,
"marquis": true
},
"puzzIntro": {"name": "<a href='squares/8873.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Nine lives, nine squares", //8
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"corral": true,
"bruise": true,
"sics": true,
"pair": true
},
"puzzIntro": {"name": "<a href='squares/9314.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Ten Four", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"oohs": true,
"six": true,
"quire": true,
"stayed": true
},
"puzzIntro": {"name": "<a href='squares/10242.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Square 11", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"want": true,
"few": true,
"avricle": true
},
"puzzIntro": {"name": "<a href='squares/11235.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "A Dozen!", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"pride": true,
"staid": true,
"paste": true,
"woe": true
},
"puzzIntro": {"name": "<a href='squares/12198.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Lucky 13", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"reads": true,
"place": true,
"whoa": true,
"bowed": true
},
"puzzIntro": {"name": "<a href='squares/13124.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "14 it is", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"profit": true,
"yule": true,
"basque": true,
"plaice": true
},
"puzzIntro": {"name": "<a href='squares/14092.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "You're at 15!", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"lichen": true,
"you'll": true,
"ale": true
},
"puzzIntro": {"name": "<a href='squares/15098.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Sweet 16", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"feeder": true,
"cere": true,
"sorted": true
},
"puzzIntro": {"name": "<a href='squares/16981.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Boring 17", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"pare": true,
"none": true,
"chews": true,
"sordid": true
},
"puzzIntro": {"name": "<a href='squares/17092.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "Old enough to go to War(machine)", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"nun": true,
"cache": true,
"ooze": true,
"wave": true
},
"puzzIntro": {"name": "<a href='squares/18923.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "19", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"coin": true,
"maid": true,
"pryed": true,
"waive": true
},
"puzzIntro": {"name": "<a href='squares/19238.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "20", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"plait": true,
"made": true,
"reeds": true,
"lynx": true
},
"puzzIntro": {"name": "<a href='squares/20.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "21", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"links": true,
"prophet": true,
"floes": true,
"rain": true
},
"puzzIntro": {"name": "<a href='squares/21.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "22", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"root": true,
"reign": true,
"liken": true
},
"puzzIntro": {"name": "<a href='squares/22.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "23", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"phew": true,
"crewel": true,
"tapir": true
},
"puzzIntro": {"name": "<a href='squares/23.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "24", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"taper": true,
"allowed": true
},
"puzzIntro": {"name": "<a href='squares/24.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},
{"name": "25", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"cents": true,
"ewe": true
},
"puzzIntro": {"name": "<a href='squares/25.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "26", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"jewel": true,
"whore": true,
"sense": true
},
"puzzIntro": {"name": "<a href='squares/26.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "27", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"cyclet": true,
"liar": true,
"joule": true
},
"puzzIntro": {"name": "<a href='squares/27.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "28", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"mood": true,
"pause": true,
"islet": true
},
"puzzIntro": {"name": "<a href='squares/28.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "29", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"epoch": true,
"phlox": true,
"want": true
},
"puzzIntro": {"name": "<a href='squares/29.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "30", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"mooed": true,
"Greece": true,
"word": true
},
"puzzIntro": {"name": "<a href='squares/30.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "31", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"acts": true,
"whirred": true,
"palate": true
},
"puzzIntro": {"name": "<a href='squares/31.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "32", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"maize": true,
"pallette": true
},
"puzzIntro": {"name": "<a href='squares/32.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "33", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"you": true,
"sine": true,
"marqaee": true
},
"puzzIntro": {"name": "<a href='squares/33.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "34", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"brews": true,
"massed": true,
"hoar": true,
"sign": true
},
"puzzIntro": {"name": "<a href='squares/34.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "35", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"potpourri": true,
"doe": true,
"epic": true
},
"puzzIntro": {"name": "<a href='squares/35.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "36", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"rabbit": true,
"rose": true,
"popery": true
},
"puzzIntro": {"name": "<a href='squares/36.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
},{"name": "37", //9
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"rabbet": true,
"illicit": true
},
"puzzIntro": {"name": "<a href='squares/37.jpg'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
} ]
eveningBuffers = [{"name": "To Find", //0
"desc": "Keep you computers open to await instruction.",
"file": "./puzzles/puzzle1",
"estTime": 30,
"answerResponse": {"name": "", ".mp3": null},
"isActive": false,
"overlap": true,
"showInput": false,
"endCondition" : {"websocket": "breakfastOver"},
"puzzIntro": {"name": "<a href='www.skeenan.com'>Something to help, take it with you.</a>",
".mp3": null,
"action": null},
"hint": []
}]
morningBufferIndex = 0
stats = {}
adminSockets = {sockets: []};
teams = [team1, team2, team3, team4];
function initTeams() {
for (var team in teams) {
teams[team].aboutToStart = 0;
teams[team].sockets = [];
for (var aPuzzle in teams[team].puzzles) {
aPuzzle = teams[team].puzzles[aPuzzle];
aPuzzle.puzzle = allPuzzles[aPuzzle.idPz];
aPuzzle.startTime = null;
aPuzzle.elapsed = null;
aPuzzle.hints = [];
}
startPuzzle(teams[team])
}
}
function reloadAllPuzzles(){
for (var team in teams) {
for (var aPuzzle in teams[team].puzzles) {
aPuzzle = teams[team].puzzles[aPuzzle];
aPuzzle.puzzle = allPuzzles[aPuzzle.idPz];
}
}
}
function startPuzzle(team) {
//Init Jarvis stream
team.jarvisStream[team.currentPuzzle] = {"name": team.puzzles[team.currentPuzzle].puzzle.name, "desc": team.puzzles[team.currentPuzzle].puzzle.desc, "data": []}
var nextIntro = team.puzzles[team.currentPuzzle].puzzle.puzzIntro
if (team.puzzles[team.currentPuzzle].puzzIntro){
nextIntro = team.puzzles[team.currentPuzzle].puzzIntro
}
if (nextIntro){
newJarvisMessageOut(team, nextIntro)
}
if (team.puzzles[team.currentPuzzle].puzzle.name === "Squares"){
for (var i = morningBufferIndex; i < morningBuffers.length; i++) {
newJarvisMessageOut(team, morningBuffers[i].puzzIntro)
};
}
if (team.puzzles[team.currentPuzzle].puzzle.name === "Lunch"){
morningBufferIndex = morningBuffers.length
}
startPuzzleTimer(team)
}
function resaveAllTeams(){
//Save all the teams
}
function logNewStat(team, statName, value, isIncrement){
// if (!stats[statName]){
// stats[statName] = {1: 0, 2: 0, 3: 0, 4: 0}
// }
// if (isIncrement){
// stats[statName][team.teamNum] += value
// } else {
// stats[statName][team.teamNum] = value
// }
// updateAllCompetitionData()
}
function logStatsOnTime(team){
if (team.puzzles[team.currentPuzzle].puzzle.isStatPuzzle){
logNewStat(team, team.puzzles[team.currentPuzzle].puzzle.name + " time", Math.floor(team.puzzles[team.currentPuzzle].elapsed/60), false)
}
}
function startNextPuzzle(team){
logStatsOnTime(team)
team.puzzles[team.currentPuzzle].puzzle.isActive = false
if (team.currentPuzzle === -1) {
team.currentPuzzle = team.lastPuzzleIndex
}
if (team.puzzles[team.currentPuzzle + 1].puzzle.overlap || !team.puzzles[team.currentPuzzle + 1].puzzle.isActive) {
if (team.puzzles[team.currentPuzzle].puzzle.isWordWeb){
emitToAllTeams(team, "bootOffWeb", true)
}
team.currentPuzzle ++
team.puzzles[team.currentPuzzle].puzzle.isActive = true
} else {
team.lastPuzzleIndex = team.currentPuzzle
team.currentPuzzle = -1
team.puzzles[-1] = {}
team.puzzles[-1].puzzle = getNextBuffer(team)
}
startPuzzle(team)
}
function getNextBuffer(team){
if (morningBufferIndex < morningBuffers.length){
logNewStat(team, "Pieces Found", 1, true)
output = morningBuffers[morningBufferIndex]
morningBufferIndex ++
return output
} else {
// I'm just going to assume that we're in the afternoon
// if (team.eveningBufferIndex < eveningBuffers.length){
// output = eveningBuffers[team.eveningBufferIndex]
// team.eveningBufferIndex ++
// return output
// } else {
return {"name": "Error finding next puzzle. Let's say SEGFAULT",
"responses": {"": "You could try to give me something, anything before you press enter you know.",
"answer": true}}
// }
}
}
function startPuzzleTimer(team){
if (team.timer == null){
team.puzzles[team.currentPuzzle].elapsed = 0;
team.timer = function(){
if (typeof this.puzzles[this.currentPuzzle].elapsed === 'undefined'){
return;
}
this.puzzles[this.currentPuzzle].elapsed ++;
emitToAllTeams(this, 'tick', {'elapsed' : this.puzzles[this.currentPuzzle].elapsed})
checkPuzzTimerHints(this);
}
var myVar=setInterval(function(){team.timer()},1000);
}
team.puzzles[team.currentPuzzle].start
}
function checkPuzzTimerHints(team){
var outHint = null;
var puzzHints = allPuzzles[team.currentPuzzle].hint;
// var outHintIndex = 0;
var isUpdated = false;
for (var hint in puzzHints){
if (puzzHints[hint].trig.time != null &&
puzzHints[hint].trig.time == team.puzzles[team.currentPuzzle].elapsed) {
outHint = puzzHints[hint];
isUpdated = true;
// isUpdated = (isUpdated || (hint != oldHints[outHintIndex]));
// outHintIndex ++;
}
}
if (isUpdated){
newJarvisMessageOut(team, outHint)
}
}
function sendAllPuzzleData(team){
//TODO: Send all relevant puzzle data, how do we make sure client only
// renders the most recent hint?
var puzzleOut = constructAllPuzzleData(team);
emitToAllTeams(team, 'jarvisUpdate', puzzleOut)
emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut)
}
function constructAllPuzzleData(team){
out = {};
out.name = team.name
out.currentPuzzle = team.currentPuzzle
out.currentPuzzleName = team.puzzles[team.currentPuzzle].puzzle.name
out.jarvisStream = team.jarvisStream
out.teamNum = team.teamNum
out.showInput = team.puzzles[team.currentPuzzle].puzzle.showInput
out.stats = stats
return out
}
function updateAllCompetitionData(){
try{
var puzzleOut = {}
for (team in teams){
team = teams[team]
puzzleOut = constructAllPuzzleData(team);
emitToAllTeams(team, 'compUpdate', puzzleOut)
}
emitToAllTeams(adminSockets, 'jarvisUpdate', puzzleOut)
} catch (err) {
console.log(err)
}
}
function newJarvisMessageOut(team, message){
team.jarvisStream[team.currentPuzzle].data.push(message);
// TODO: Persist!
sendAllPuzzleData(team);
emitToAllTeams(team, 'jarvisMessage', message)
}
if (teams[0].sockets == null) {
initTeams()
}
reloadAllPuzzles();
module.exports.teams = teams;
module.exports.allPuzzles = allPuzzles;
module.exports.reloadAllPuzzles = reloadAllPuzzles;
module.exports.resaveAllTeams = resaveAllTeams;
module.exports.startPuzzle = startPuzzle;
module.exports.startNextPuzzle = startNextPuzzle;
module.exports.sendAllPuzzleData = sendAllPuzzleData;
module.exports.emitToAllTeams = emitToAllTeams;
module.exports.constructAllPuzzleData = constructAllPuzzleData;
module.exports.adminSockets = adminSockets;
module.exports.newJarvisMessageOut = newJarvisMessageOut;
module.exports.stats = stats;
module.exports.logNewStat = logNewStat;
| sean9keenan/WordWeb | backend/puzzles.js | JavaScript | mit | 48,757 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "db.h"
#include "init.h"
#include "bitcoinrpc.h"
using namespace json_spirit;
using namespace std;
// Return average network hashes per second based on the last 'lookup' blocks,
// or from the last difficulty change if 'lookup' is nonpositive.
// If 'height' is nonnegative, compute the estimate at the time when a given block was found.
Value GetNetworkHashPS(int lookup, int height) {
CBlockIndex *pb = pindexBest;
if (height >= 0 && height < nBestHeight)
pb = FindBlockByHeight(height);
if (pb == NULL || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pb->nHeight % 2016 + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight)
lookup = pb->nHeight;
double sum = 0.0;
for (int i = 0; i < lookup; i++)
{
sum += (pb->GetBlockTime() - pb->pprev->GetBlockTime()) / GetDifficulty(pb);
pb = pb->pprev;
}
return (boost::int64_t)(pow(2.0, 32) / (sum / lookup));
}
Value getnetworkhashps(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getnetworkhashps [blocks] [height]\n"
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
"Pass in [height] to estimate the network speed at the time when a certain block was found.");
return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
Object obj;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("testnet", fTestNet));
return obj;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Colossus is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Colossus is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
static CReserveKey reservekey(pwalletMain);
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlock(reservekey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
printf("%s\n", merkleh.ToString().c_str());
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0];
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, reservekey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Colossus is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Colossus is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlockTemplate*> vNewBlockTemplate;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
delete pblocktemplate;
vNewBlockTemplate.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblocktemplate = CreateNewBlock(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlockTemplate.push_back(pblocktemplate);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Colossus is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Colossus is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64 nStart;
static CBlockTemplate* pblocktemplate;
if (pindexPrev != pindexBest ||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblocktemplate)
{
delete pblocktemplate;
pblocktemplate = NULL;
}
pblocktemplate = CreateNewBlock(*pMiningKey);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
Array deps;
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", HexBits(pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock pblock;
try {
ssBlock >> pblock;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
CValidationState state;
bool fAccepted = ProcessBlock(state, NULL, &pblock);
if (!fAccepted)
return "rejected"; // TODO: report validation state
return Value::null;
}
| gfneto/colossus | src/rpcmining.cpp | C++ | mit | 18,531 |
package com.asksunny.rpc.admin;
import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asksunny.protocol.rpc.RPCAdminCommand;
import com.asksunny.protocol.rpc.RPCAdminEnvelope;
import com.asksunny.protocol.rpc.RPCEnvelope;
import com.asksunny.rpc.mtserver.RPCRuntime;
public class AdminRPCRuntime implements RPCRuntime{
ExecutorService executorService;
final static Logger log = LoggerFactory.getLogger(AdminRPCRuntime.class);
public ExecutorService getExecutorService() {
return executorService;
}
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
public RPCEnvelope invoke(RPCEnvelope request) throws Exception
{
RPCAdminEnvelope adminRequest = (RPCAdminEnvelope)request;
RPCAdminEnvelope response = new RPCAdminEnvelope();
response.setRpcType(RPCEnvelope.RPC_TYPE_RESPONSE);
RPCAdminCommand cmd = RPCAdminCommand.valueOf(adminRequest.getAdminCommand());
if(cmd == RPCAdminCommand.PING ){
response.setAdminCommand(RPCAdminCommand.PING);
response.addRpcObjects(System.currentTimeMillis());
}else if(cmd == RPCAdminCommand.ECHO ){
response.setAdminCommand(RPCAdminCommand.ECHO);
response.setRpcObjects(request.getRpcObjects());
}else if(cmd == RPCAdminCommand.UPTIME ){
response.setAdminCommand(RPCAdminCommand.UPTIME);
response.addRpcObjects(System.currentTimeMillis());
}else if(cmd == RPCAdminCommand.STATUS ){
response.setAdminCommand(RPCAdminCommand.STATUS);
response.addRpcObjects(System.currentTimeMillis());
}else if(cmd == RPCAdminCommand.HEARTBEAT ){
response.setAdminCommand(RPCAdminCommand.HEARTBEAT);
response.addRpcObjects(System.currentTimeMillis());
}else if(cmd == RPCAdminCommand.SHUTDOWN ){
System.exit(0);
}
return response;
}
public boolean accept(RPCEnvelope envelope) throws Exception {
return envelope.getRpcType()==RPCEnvelope.RPC_ENVELOPE_TYPE_ADMIN;
}
}
| devsunny/mt-rpc-server | src/main/java/com/asksunny/rpc/admin/AdminRPCRuntime.java | Java | mit | 1,997 |
import DBService, { BuilderSingle } from '../DBService'
import Approval from '../../../models/extprod/Approval'
import { Map } from '../../../utils/map'
import { UndefinedError } from '../../../models/Error'
interface FindAllOptions {
userId?: string
}
export default class ApprovalService extends DBService<Approval> {
constructor() {
super(Approval)
}
public findAll = async (options?: FindAllOptions) => {
let query = this.Model.query().eager(
'[user, itemPrototype.[itemBase], itemRequest.[itemBase], itemService.[itemBase]]'
)
if (options && options.userId) {
query = query.where('userId', options.userId)
}
const approvals = await query
if (!approvals) {
throw new UndefinedError()
}
return approvals
}
}
| Portgass/api-server | src/services/db/extprod/ApprovalService.ts | TypeScript | mit | 750 |
<?php
/*
|--------------------------------------------------------------------------
| Oculus XMS
|--------------------------------------------------------------------------
|
| This file is part of the Oculus XMS Framework package.
|
| (c) Vince Kronlein <vince@ocx.io>
|
| For the full copyright and license information, please view the LICENSE
| file that was distributed with this source code.
|
*/
namespace Admin\Model\Sale;
use Oculus\Engine\Model;
use Oculus\Library\Language;
class Order extends Model {
public function addOrder($data) {
$this->theme->model('setting/store');
$store_info = $this->model_setting_store->getStore($data['store_id']);
if ($store_info) {
$store_name = $store_info['name'];
$store_url = $store_info['url'];
} else {
$store_name = $this->config->get('config_name');
$store_url = $this->app['http.public'];
}
$this->theme->model('setting/setting');
$setting_info = $this->model_setting_setting->getSetting('setting', $data['store_id']);
if (isset($setting_info['invoice_prefix'])) {
$invoice_prefix = $setting_info['invoice_prefix'];
} else {
$invoice_prefix = $this->config->get('config_invoice_prefix');
}
$this->theme->model('localization/country');
$this->theme->model('localization/zone');
$country_info = $this->model_localization_country->getCountry($data['shipping_country_id']);
if ($country_info) {
$shipping_country = $country_info['name'];
$shipping_address_format = $country_info['address_format'];
} else {
$shipping_country = '';
$shipping_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$zone_info = $this->model_localization_zone->getZone($data['shipping_zone_id']);
if ($zone_info) {
$shipping_zone = $zone_info['name'];
} else {
$shipping_zone = '';
}
$country_info = $this->model_localization_country->getCountry($data['payment_country_id']);
if ($country_info) {
$payment_country = $country_info['name'];
$payment_address_format = $country_info['address_format'];
} else {
$payment_country = '';
$payment_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$zone_info = $this->model_localization_zone->getZone($data['payment_zone_id']);
if ($zone_info) {
$payment_zone = $zone_info['name'];
} else {
$payment_zone = '';
}
$this->theme->model('localization/currency');
$currency_info = $this->model_localization_currency->getCurrencyByCode($this->config->get('config_currency'));
if ($currency_info) {
$currency_id = $currency_info['currency_id'];
$currency_code = $currency_info['code'];
$currency_value = $currency_info['value'];
} else {
$currency_id = 0;
$currency_code = $this->config->get('config_currency');
$currency_value = 1.00000;
}
$this->db->query("
INSERT INTO `{$this->db->prefix}order`
SET
invoice_prefix = '" . $this->db->escape($invoice_prefix) . "',
store_id = '" . (int)$data['store_id'] . "',
store_name = '" . $this->db->escape($store_name) . "',
store_url = '" . $this->db->escape($store_url) . "',
customer_id = '" . (int)$data['customer_id'] . "',
customer_group_id = '" . (int)$data['customer_group_id'] . "',
firstname = '" . $this->db->escape($data['firstname']) . "',
lastname = '" . $this->db->escape($data['lastname']) . "',
email = '" . $this->db->escape($data['email']) . "',
telephone = '" . $this->db->escape($data['telephone']) . "',
payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "',
payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "',
payment_company = '" . $this->db->escape($data['payment_company']) . "',
payment_company_id = '" . $this->db->escape($data['payment_company_id']) . "',
payment_tax_id = '" . $this->db->escape($data['payment_tax_id']) . "',
payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "',
payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "',
payment_city = '" . $this->db->escape($data['payment_city']) . "',
payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "',
payment_country = '" . $this->db->escape($payment_country) . "',
payment_country_id = '" . (int)$data['payment_country_id'] . "',
payment_zone = '" . $this->db->escape($payment_zone) . "',
payment_zone_id = '" . (int)$data['payment_zone_id'] . "',
payment_address_format = '" . $this->db->escape($payment_address_format) . "',
payment_method = '" . $this->db->escape($data['payment_method']) . "',
payment_code = '" . $this->db->escape($data['payment_code']) . "',
shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "',
shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "',
shipping_company = '" . $this->db->escape($data['shipping_company']) . "',
shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "',
shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "',
shipping_city = '" . $this->db->escape($data['shipping_city']) . "',
shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "',
shipping_country = '" . $this->db->escape($shipping_country) . "',
shipping_country_id = '" . (int)$data['shipping_country_id'] . "',
shipping_zone = '" . $this->db->escape($shipping_zone) . "',
shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "',
shipping_address_format = '" . $this->db->escape($shipping_address_format) . "',
shipping_method = '" . $this->db->escape($data['shipping_method']) . "',
shipping_code = '" . $this->db->escape($data['shipping_code']) . "',
comment = '" . $this->db->escape($data['comment']) . "',
order_status_id = '" . (int)$data['order_status_id'] . "',
affiliate_id = '" . (int)$data['affiliate_id'] . "',
language_id = '" . (int)$this->config->get('config_language_id') . "',
currency_id = '" . (int)$currency_id . "',
currency_code = '" . $this->db->escape($currency_code) . "',
currency_value = '" . (float)$currency_value . "',
date_added = NOW(),
date_modified = NOW()
");
$order_id = $this->db->getLastId();
if (isset($data['order_product'])) {
foreach ($data['order_product'] as $order_product) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_product
SET
order_id = '" . (int)$order_id . "',
product_id = '" . (int)$order_product['product_id'] . "',
name = '" . $this->db->escape($order_product['name']) . "',
model = '" . $this->db->escape($order_product['model']) . "',
quantity = '" . (int)$order_product['quantity'] . "',
price = '" . (float)$order_product['price'] . "',
total = '" . (float)$order_product['total'] . "',
tax = '" . (float)$order_product['tax'] . "',
reward = '" . (int)$order_product['reward'] . "'
");
$order_product_id = $this->db->getLastId();
$this->db->query("
UPDATE {$this->db->prefix}product
SET
quantity = (quantity - " . (int)$order_product['quantity'] . ")
WHERE product_id = '" . (int)$order_product['product_id'] . "'
AND subtract = '1'
");
if (isset($order_product['order_option'])) {
foreach ($order_product['order_option'] as $order_option) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_option
SET
order_id = '" . (int)$order_id . "',
order_product_id = '" . (int)$order_product_id . "',
product_option_id = '" . (int)$order_option['product_option_id'] . "',
product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "',
name = '" . $this->db->escape($order_option['name']) . "',
`value` = '" . $this->db->escape($order_option['value']) . "',
`type` = '" . $this->db->escape($order_option['type']) . "'
");
$this->db->query("
UPDATE {$this->db->prefix}product_option_value
SET
quantity = (quantity - " . (int)$order_product['quantity'] . ")
WHERE product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "'
AND subtract = '1'
");
}
}
if (isset($order_product['order_download'])) {
foreach ($order_product['order_download'] as $order_download) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_download
SET
order_id = '" . (int)$order_id . "',
order_product_id = '" . (int)$order_product_id . "',
name = '" . $this->db->escape($order_download['name']) . "',
filename = '" . $this->db->escape($order_download['filename']) . "',
mask = '" . $this->db->escape($order_download['mask']) . "',
remaining = '" . (int)$order_download['remaining'] . "'
");
}
}
}
}
if (isset($data['order_giftcard'])) {
foreach ($data['order_giftcard'] as $order_giftcard) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_giftcard
SET
order_id = '" . (int)$order_id . "',
giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "',
description = '" . $this->db->escape($order_giftcard['description']) . "',
code = '" . $this->db->escape($order_giftcard['code']) . "',
from_name = '" . $this->db->escape($order_giftcard['from_name']) . "',
from_email = '" . $this->db->escape($order_giftcard['from_email']) . "',
to_name = '" . $this->db->escape($order_giftcard['to_name']) . "',
to_email = '" . $this->db->escape($order_giftcard['to_email']) . "',
giftcard_theme_id = '" . (int)$order_giftcard['giftcard_theme_id'] . "',
message = '" . $this->db->escape($order_giftcard['message']) . "',
amount = '" . (float)$order_giftcard['amount'] . "'
");
$this->db->query("
UPDATE {$this->db->prefix}giftcard
SET
order_id = '" . (int)$order_id . "'
WHERE giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "'
");
}
}
// Get the total
$total = 0;
if (isset($data['order_total'])) {
foreach ($data['order_total'] as $order_total) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_total
SET
order_id = '" . (int)$order_id . "',
code = '" . $this->db->escape($order_total['code']) . "',
title = '" . $this->db->escape($order_total['title']) . "',
text = '" . $this->db->escape($order_total['text']) . "',
`value` = '" . (float)$order_total['value'] . "',
sort_order = '" . (int)$order_total['sort_order'] . "'
");
}
$total+= $order_total['value'];
}
// Affiliate
$affiliate_id = 0;
$commission = 0;
if (!empty($this->request->post['affiliate_id'])) {
$this->theme->model('people/customer');
$affiliate_info = $this->model_people_customer->getCustomer($this->request->post['affiliate_id']);
if ($affiliate_info) {
$affiliate_id = $affiliate_info['customer_id'];
$commission = ($total / 100) * $affiliate_info['commission'];
}
}
// Update order total
$this->db->query("
UPDATE `{$this->db->prefix}order`
SET
total = '" . (float)$total . "',
affiliate_id = '" . (int)$affiliate_id . "',
commission = '" . (float)$commission . "'
WHERE order_id = '" . (int)$order_id . "'
");
}
public function editOrder($order_id, $data) {
$this->theme->model('localization/country');
$this->theme->model('localization/zone');
$country_info = $this->model_localization_country->getCountry($data['shipping_country_id']);
if ($country_info) {
$shipping_country = $country_info['name'];
$shipping_address_format = $country_info['address_format'];
} else {
$shipping_country = '';
$shipping_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$zone_info = $this->model_localization_zone->getZone($data['shipping_zone_id']);
if ($zone_info) {
$shipping_zone = $zone_info['name'];
} else {
$shipping_zone = '';
}
$country_info = $this->model_localization_country->getCountry($data['payment_country_id']);
if ($country_info) {
$payment_country = $country_info['name'];
$payment_address_format = $country_info['address_format'];
} else {
$payment_country = '';
$payment_address_format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
}
$zone_info = $this->model_localization_zone->getZone($data['payment_zone_id']);
if ($zone_info) {
$payment_zone = $zone_info['name'];
} else {
$payment_zone = '';
}
// Restock products before subtracting the stock later on
$order_query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}order`
WHERE order_status_id > '0'
AND order_id = '" . (int)$order_id . "'
");
if ($order_query->num_rows) {
$product_query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_product
WHERE order_id = '" . (int)$order_id . "'
");
foreach ($product_query->rows as $product) {
$this->db->query("
UPDATE `{$this->db->prefix}product`
SET
quantity = (quantity + " . (int)$product['quantity'] . ")
WHERE product_id = '" . (int)$product['product_id'] . "'
AND subtract = '1'
");
$option_query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_option
WHERE order_id = '" . (int)$order_id . "'
AND order_product_id = '" . (int)$product['order_product_id'] . "'
");
foreach ($option_query->rows as $option) {
$this->db->query("
UPDATE {$this->db->prefix}product_option_value
SET
quantity = (quantity + " . (int)$product['quantity'] . ")
WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "'
AND subtract = '1'
");
}
}
}
$this->db->query("
UPDATE `{$this->db->prefix}order`
SET
firstname = '" . $this->db->escape($data['firstname']) . "',
lastname = '" . $this->db->escape($data['lastname']) . "',
email = '" . $this->db->escape($data['email']) . "',
telephone = '" . $this->db->escape($data['telephone']) . "',
payment_firstname = '" . $this->db->escape($data['payment_firstname']) . "',
payment_lastname = '" . $this->db->escape($data['payment_lastname']) . "',
payment_company = '" . $this->db->escape($data['payment_company']) . "',
payment_company_id = '" . $this->db->escape($data['payment_company_id']) . "',
payment_tax_id = '" . $this->db->escape($data['payment_tax_id']) . "',
payment_address_1 = '" . $this->db->escape($data['payment_address_1']) . "',
payment_address_2 = '" . $this->db->escape($data['payment_address_2']) . "',
payment_city = '" . $this->db->escape($data['payment_city']) . "',
payment_postcode = '" . $this->db->escape($data['payment_postcode']) . "',
payment_country = '" . $this->db->escape($payment_country) . "',
payment_country_id = '" . (int)$data['payment_country_id'] . "',
payment_zone = '" . $this->db->escape($payment_zone) . "',
payment_zone_id = '" . (int)$data['payment_zone_id'] . "',
payment_address_format = '" . $this->db->escape($payment_address_format) . "',
payment_method = '" . $this->db->escape($data['payment_method']) . "',
payment_code = '" . $this->db->escape($data['payment_code']) . "',
shipping_firstname = '" . $this->db->escape($data['shipping_firstname']) . "',
shipping_lastname = '" . $this->db->escape($data['shipping_lastname']) . "',
shipping_company = '" . $this->db->escape($data['shipping_company']) . "',
shipping_address_1 = '" . $this->db->escape($data['shipping_address_1']) . "',
shipping_address_2 = '" . $this->db->escape($data['shipping_address_2']) . "',
shipping_city = '" . $this->db->escape($data['shipping_city']) . "',
shipping_postcode = '" . $this->db->escape($data['shipping_postcode']) . "',
shipping_country = '" . $this->db->escape($shipping_country) . "',
shipping_country_id = '" . (int)$data['shipping_country_id'] . "',
shipping_zone = '" . $this->db->escape($shipping_zone) . "',
shipping_zone_id = '" . (int)$data['shipping_zone_id'] . "',
shipping_address_format = '" . $this->db->escape($shipping_address_format) . "',
shipping_method = '" . $this->db->escape($data['shipping_method']) . "',
shipping_code = '" . $this->db->escape($data['shipping_code']) . "',
comment = '" . $this->db->escape($data['comment']) . "',
order_status_id = '" . (int)$data['order_status_id'] . "',
affiliate_id = '" . (int)$data['affiliate_id'] . "',
date_modified = NOW()
WHERE order_id = '" . (int)$order_id . "'
");
$this->db->query("DELETE FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_download WHERE order_id = '" . (int)$order_id . "'");
if (isset($data['order_product'])) {
foreach ($data['order_product'] as $order_product) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_product
SET
order_product_id = '" . (int)$order_product['order_product_id'] . "',
order_id = '" . (int)$order_id . "',
product_id = '" . (int)$order_product['product_id'] . "',
name = '" . $this->db->escape($order_product['name']) . "',
model = '" . $this->db->escape($order_product['model']) . "',
quantity = '" . (int)$order_product['quantity'] . "',
price = '" . (float)$order_product['price'] . "',
total = '" . (float)$order_product['total'] . "',
tax = '" . (float)$order_product['tax'] . "',
reward = '" . (int)$order_product['reward'] . "'
");
$order_product_id = $this->db->getLastId();
$this->db->query("
UPDATE {$this->db->prefix}product
SET
quantity = (quantity - " . (int)$order_product['quantity'] . ")
WHERE product_id = '" . (int)$order_product['product_id'] . "'
AND subtract = '1'
");
if (isset($order_product['order_option'])) {
foreach ($order_product['order_option'] as $order_option) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_option
SET
order_option_id = '" . (int)$order_option['order_option_id'] . "',
order_id = '" . (int)$order_id . "',
order_product_id = '" . (int)$order_product_id . "',
product_option_id = '" . (int)$order_option['product_option_id'] . "',
product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "',
name = '" . $this->db->escape($order_option['name']) . "',
`value` = '" . $this->db->escape($order_option['value']) . "',
`type` = '" . $this->db->escape($order_option['type']) . "'
");
$this->db->query("
UPDATE {$this->db->prefix}product_option_value
SET
quantity = (quantity - " . (int)$order_product['quantity'] . ")
WHERE product_option_value_id = '" . (int)$order_option['product_option_value_id'] . "'
AND subtract = '1'
");
}
}
if (isset($order_product['order_download'])) {
foreach ($order_product['order_download'] as $order_download) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_download
SET
order_download_id = '" . (int)$order_download['order_download_id'] . "',
order_id = '" . (int)$order_id . "',
order_product_id = '" . (int)$order_product_id . "',
name = '" . $this->db->escape($order_download['name']) . "',
filename = '" . $this->db->escape($order_download['filename']) . "',
mask = '" . $this->db->escape($order_download['mask']) . "',
remaining = '" . (int)$order_download['remaining'] . "'
");
}
}
}
}
$this->db->query("DELETE FROM {$this->db->prefix}order_giftcard WHERE order_id = '" . (int)$order_id . "'");
if (isset($data['order_giftcard'])) {
foreach ($data['order_giftcard'] as $order_giftcard) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_giftcard
SET
order_giftcard_id = '" . (int)$order_giftcard['order_giftcard_id'] . "',
order_id = '" . (int)$order_id . "',
giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "',
description = '" . $this->db->escape($order_giftcard['description']) . "',
code = '" . $this->db->escape($order_giftcard['code']) . "',
from_name = '" . $this->db->escape($order_giftcard['from_name']) . "',
from_email = '" . $this->db->escape($order_giftcard['from_email']) . "',
to_name = '" . $this->db->escape($order_giftcard['to_name']) . "',
to_email = '" . $this->db->escape($order_giftcard['to_email']) . "',
giftcard_theme_id = '" . (int)$order_giftcard['giftcard_theme_id'] . "',
message = '" . $this->db->escape($order_giftcard['message']) . "',
amount = '" . (float)$order_giftcard['amount'] . "'
");
$this->db->query("
UPDATE {$this->db->prefix}giftcard
SET
order_id = '" . (int)$order_id . "'
WHERE giftcard_id = '" . (int)$order_giftcard['giftcard_id'] . "'
");
}
}
// Get the total
$total = 0;
$this->db->query("DELETE FROM {$this->db->prefix}order_total WHERE order_id = '" . (int)$order_id . "'");
if (isset($data['order_total'])) {
foreach ($data['order_total'] as $order_total) {
$this->db->query("
INSERT INTO {$this->db->prefix}order_total
SET
order_total_id = '" . (int)$order_total['order_total_id'] . "',
order_id = '" . (int)$order_id . "',
code = '" . $this->db->escape($order_total['code']) . "',
title = '" . $this->db->escape($order_total['title']) . "',
text = '" . $this->db->escape($order_total['text']) . "',
`value` = '" . (float)$order_total['value'] . "',
sort_order = '" . (int)$order_total['sort_order'] . "'
");
}
$total+= $order_total['value'];
}
// Affiliate
$affiliate_id = 0;
$commission = 0;
if (!empty($this->request->post['affiliate_id'])) {
$this->theme->model('people/customer');
$affiliate_info = $this->model_people_customer->getCustomer($this->request->post['affiliate_id']);
if ($affiliate_info) {
$affiliate_id = $affiliate_info['customer_id'];
$commission = ($total / 100) * $affiliate_info['commission'];
}
}
$this->db->query("
UPDATE `{$this->db->prefix}order`
SET
total = '" . (float)$total . "',
affiliate_id = '" . (int)$affiliate_id . "',
commission = '" . (float)$commission . "'
WHERE order_id = '" . (int)$order_id . "'
");
}
public function deleteOrder($order_id) {
$order_query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}order`
WHERE order_status_id > '0'
AND order_id = '" . (int)$order_id . "'
");
if ($order_query->num_rows) {
$product_query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_product
WHERE order_id = '" . (int)$order_id . "'
");
foreach ($product_query->rows as $product) {
$this->db->query("
UPDATE `{$this->db->prefix}product`
SET
quantity = (quantity + " . (int)$product['quantity'] . ")
WHERE product_id = '" . (int)$product['product_id'] . "'
AND subtract = '1'
");
$option_query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_option
WHERE order_id = '" . (int)$order_id . "'
AND order_product_id = '" . (int)$product['order_product_id'] . "'
");
foreach ($option_query->rows as $option) {
$this->db->query("
UPDATE {$this->db->prefix}product_option_value
SET
quantity = (quantity + " . (int)$product['quantity'] . ")
WHERE product_option_value_id = '" . (int)$option['product_option_value_id'] . "'
AND subtract = '1'
");
}
}
}
$this->db->query("DELETE FROM `{$this->db->prefix}order` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_product WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_option WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_download WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_giftcard WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_total WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_history WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_fraud WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}order_fraud WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}customer_credit WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}customer_reward WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM {$this->db->prefix}customer_commission WHERE order_id = '" . (int)$order_id . "'");
$recurring = $this->db->query("
SELECT order_recurring_id
FROM {$this->db->prefix}order_recurring
WHERE order_id = '" . (int)$order_id . "'");
if ($recurring->num_rows):
$recurring_order_id = $recurring->row['order_recurring_id'];
$this->db->query("
DELETE
FROM {$this->db->prefix}order_recurring_transaction
WHERE order_recurring_id = '" . (int)$recurring_order_id . "'");
$this->db->query("
DELETE
FROM {$this->db->prefix}order_recurring
WHERE order_id = '" . (int)$order_id . "'");
endif;
}
public function getOrder($order_id) {
$order_query = $this->db->query("
SELECT *,
(SELECT CONCAT(c.firstname, ' ', c.lastname)
FROM {$this->db->prefix}customer c
WHERE c.customer_id = o.customer_id) AS customer
FROM `{$this->db->prefix}order` o
WHERE o.order_id = '" . (int)$order_id . "'
");
if ($order_query->num_rows) {
$reward = 0;
$order_product_query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_product
WHERE order_id = '" . (int)$order_id . "'
");
foreach ($order_product_query->rows as $product) {
$reward+= $product['reward'];
}
$country_query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}country`
WHERE country_id = '" . (int)$order_query->row['payment_country_id'] . "'
");
if ($country_query->num_rows) {
$payment_iso_code_2 = $country_query->row['iso_code_2'];
$payment_iso_code_3 = $country_query->row['iso_code_3'];
} else {
$payment_iso_code_2 = '';
$payment_iso_code_3 = '';
}
$zone_query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}zone`
WHERE zone_id = '" . (int)$order_query->row['payment_zone_id'] . "'
");
if ($zone_query->num_rows) {
$payment_zone_code = $zone_query->row['code'];
} else {
$payment_zone_code = '';
}
$country_query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}country`
WHERE country_id = '" . (int)$order_query->row['shipping_country_id'] . "'
");
if ($country_query->num_rows) {
$shipping_iso_code_2 = $country_query->row['iso_code_2'];
$shipping_iso_code_3 = $country_query->row['iso_code_3'];
} else {
$shipping_iso_code_2 = '';
$shipping_iso_code_3 = '';
}
$zone_query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}zone`
WHERE zone_id = '" . (int)$order_query->row['shipping_zone_id'] . "'
");
if ($zone_query->num_rows) {
$shipping_zone_code = $zone_query->row['code'];
} else {
$shipping_zone_code = '';
}
if ($order_query->row['affiliate_id']) {
$affiliate_id = $order_query->row['affiliate_id'];
} else {
$affiliate_id = 0;
}
$this->theme->model('people/customer');
$affiliate_info = $this->model_people_customer->getCustomer($affiliate_id);
if ($affiliate_info) {
$affiliate_firstname = $affiliate_info['firstname'];
$affiliate_lastname = $affiliate_info['lastname'];
} else {
$affiliate_firstname = '';
$affiliate_lastname = '';
}
$this->theme->model('localization/language');
$language_info = $this->model_localization_language->getLanguage($order_query->row['language_id']);
if ($language_info) {
$language_code = $language_info['code'];
$language_filename = $language_info['filename'];
$language_directory = $language_info['directory'];
} else {
$language_code = '';
$language_filename = '';
$language_directory = '';
}
return array(
'order_id' => $order_query->row['order_id'],
'invoice_no' => $order_query->row['invoice_no'],
'invoice_prefix' => $order_query->row['invoice_prefix'],
'store_id' => $order_query->row['store_id'],
'store_name' => $order_query->row['store_name'],
'store_url' => $order_query->row['store_url'],
'customer_id' => $order_query->row['customer_id'],
'customer' => $order_query->row['customer'],
'customer_group_id' => $order_query->row['customer_group_id'],
'firstname' => $order_query->row['firstname'],
'lastname' => $order_query->row['lastname'],
'telephone' => $order_query->row['telephone'],
'email' => $order_query->row['email'],
'payment_firstname' => $order_query->row['payment_firstname'],
'payment_lastname' => $order_query->row['payment_lastname'],
'payment_company' => $order_query->row['payment_company'],
'payment_company_id' => $order_query->row['payment_company_id'],
'payment_tax_id' => $order_query->row['payment_tax_id'],
'payment_address_1' => $order_query->row['payment_address_1'],
'payment_address_2' => $order_query->row['payment_address_2'],
'payment_postcode' => $order_query->row['payment_postcode'],
'payment_city' => $order_query->row['payment_city'],
'payment_zone_id' => $order_query->row['payment_zone_id'],
'payment_zone' => $order_query->row['payment_zone'],
'payment_zone_code' => $payment_zone_code,
'payment_country_id' => $order_query->row['payment_country_id'],
'payment_country' => $order_query->row['payment_country'],
'payment_iso_code_2' => $payment_iso_code_2,
'payment_iso_code_3' => $payment_iso_code_3,
'payment_address_format' => $order_query->row['payment_address_format'],
'payment_method' => $order_query->row['payment_method'],
'payment_code' => $order_query->row['payment_code'],
'shipping_firstname' => $order_query->row['shipping_firstname'],
'shipping_lastname' => $order_query->row['shipping_lastname'],
'shipping_company' => $order_query->row['shipping_company'],
'shipping_address_1' => $order_query->row['shipping_address_1'],
'shipping_address_2' => $order_query->row['shipping_address_2'],
'shipping_postcode' => $order_query->row['shipping_postcode'],
'shipping_city' => $order_query->row['shipping_city'],
'shipping_zone_id' => $order_query->row['shipping_zone_id'],
'shipping_zone' => $order_query->row['shipping_zone'],
'shipping_zone_code' => $shipping_zone_code,
'shipping_country_id' => $order_query->row['shipping_country_id'],
'shipping_country' => $order_query->row['shipping_country'],
'shipping_iso_code_2' => $shipping_iso_code_2,
'shipping_iso_code_3' => $shipping_iso_code_3,
'shipping_address_format' => $order_query->row['shipping_address_format'],
'shipping_method' => $order_query->row['shipping_method'],
'shipping_code' => $order_query->row['shipping_code'],
'comment' => $order_query->row['comment'],
'total' => $order_query->row['total'],
'reward' => $reward,
'order_status_id' => $order_query->row['order_status_id'],
'affiliate_id' => $order_query->row['affiliate_id'],
'affiliate_firstname' => $affiliate_firstname,
'affiliate_lastname' => $affiliate_lastname,
'commission' => $order_query->row['commission'],
'language_id' => $order_query->row['language_id'],
'language_code' => $language_code,
'language_filename' => $language_filename,
'language_directory' => $language_directory,
'currency_id' => $order_query->row['currency_id'],
'currency_code' => $order_query->row['currency_code'],
'currency_value' => $order_query->row['currency_value'],
'ip' => $order_query->row['ip'],
'forwarded_ip' => $order_query->row['forwarded_ip'],
'user_agent' => $order_query->row['user_agent'],
'accept_language' => $order_query->row['accept_language'],
'date_added' => $order_query->row['date_added'],
'date_modified' => $order_query->row['date_modified']
);
} else {
return false;
}
}
public function getOrders($data = array()) {
$sql = "
SELECT
o.order_id,
CONCAT(o.firstname, ' ', o.lastname) AS customer,
(SELECT os.name
FROM {$this->db->prefix}order_status os
WHERE os.order_status_id = o.order_status_id
AND os.language_id = '" . (int)$this->config->get('config_language_id') . "') AS status,
o.total,
o.currency_code,
o.currency_value,
o.date_added,
o.date_modified
FROM `{$this->db->prefix}order` o";
if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) {
$sql.= " WHERE o.order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
} else {
$sql.= " WHERE o.order_status_id > '0'";
}
if (!empty($data['filter_order_id'])) {
$sql.= " AND o.order_id = '" . (int)$data['filter_order_id'] . "'";
}
if (!empty($data['filter_customer'])) {
$sql.= " AND CONCAT(o.firstname, ' ', o.lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
}
if (!empty($data['filter_date_added'])) {
$sql.= " AND DATE(o.date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
}
if (!empty($data['filter_date_modified'])) {
$sql.= " AND DATE(o.date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
}
if (!empty($data['filter_total'])) {
$sql.= " AND o.total = '" . (float)$data['filter_total'] . "'";
}
$sort_data = array('o.order_id', 'customer', 'status', 'o.date_added', 'o.date_modified', 'o.total');
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql.= " ORDER BY {$data['sort']}";
} else {
$sql.= " ORDER BY o.order_id";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql.= " DESC";
} else {
$sql.= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql.= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
public function getOrderProducts($order_id) {
$query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_product
WHERE order_id = '" . (int)$order_id . "'
");
return $query->rows;
}
public function getOrderOption($order_id, $order_option_id) {
$query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_option
WHERE order_id = '" . (int)$order_id . "'
AND order_option_id = '" . (int)$order_option_id . "'
");
return $query->row;
}
public function getOrderOptions($order_id, $order_product_id) {
$query = $this->db->query("
SELECT oo.*
FROM {$this->db->prefix}order_option AS oo
LEFT JOIN {$this->db->prefix}product_option po
USING(product_option_id)
LEFT JOIN `{$this->db->prefix}option` o
USING(option_id)
WHERE order_id = '" . (int)$order_id . "'
AND order_product_id = '" . (int)$order_product_id . "'
ORDER BY o.sort_order
");
return $query->rows;
}
public function getOrderDownloads($order_id, $order_product_id) {
$query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_download
WHERE order_id = '" . (int)$order_id . "'
AND order_product_id = '" . (int)$order_product_id . "'
");
return $query->rows;
}
public function getOrderGiftcards($order_id) {
$query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_giftcard
WHERE order_id = '" . (int)$order_id . "'
");
return $query->rows;
}
public function getOrderGiftcardByGiftcardId($giftcard_id) {
$query = $this->db->query("
SELECT *
FROM `{$this->db->prefix}order_giftcard`
WHERE giftcard_id = '" . (int)$giftcard_id . "'
");
return $query->row;
}
public function getOrderTotals($order_id) {
$query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_total
WHERE order_id = '" . (int)$order_id . "'
ORDER BY sort_order
");
return $query->rows;
}
public function getTotalOrders($data = array()) {
$sql = "
SELECT COUNT(*) AS total
FROM `{$this->db->prefix}order`";
if (isset($data['filter_order_status_id']) && !is_null($data['filter_order_status_id'])) {
$sql.= " WHERE order_status_id = '" . (int)$data['filter_order_status_id'] . "'";
} else {
$sql.= " WHERE order_status_id > '0'";
}
if (!empty($data['filter_order_id'])) {
$sql.= " AND order_id = '" . (int)$data['filter_order_id'] . "'";
}
if (!empty($data['filter_customer'])) {
$sql.= " AND CONCAT(firstname, ' ', lastname) LIKE '%" . $this->db->escape($data['filter_customer']) . "%'";
}
if (!empty($data['filter_date_added'])) {
$sql.= " AND DATE(date_added) = DATE('" . $this->db->escape($data['filter_date_added']) . "')";
}
if (!empty($data['filter_date_modified'])) {
$sql.= " AND DATE(date_modified) = DATE('" . $this->db->escape($data['filter_date_modified']) . "')";
}
if (!empty($data['filter_total'])) {
$sql.= " AND total = '" . (float)$data['filter_total'] . "'";
}
$query = $this->db->query($sql);
return $query->row['total'];
}
public function getTotalOrdersByStoreId($store_id) {
$query = $this->db->query("
SELECT
COUNT(*) AS total
FROM `{$this->db->prefix}order`
WHERE store_id = '" . (int)$store_id . "'
");
return $query->row['total'];
}
public function getTotalOrdersByOrderStatusId($order_status_id) {
$query = $this->db->query("
SELECT
COUNT(*) AS total
FROM `{$this->db->prefix}order`
WHERE order_status_id = '" . (int)$order_status_id . "'
AND order_status_id > '0'
");
return $query->row['total'];
}
public function getTotalOrdersByLanguageId($language_id) {
$query = $this->db->query("
SELECT
COUNT(*) AS total
FROM `{$this->db->prefix}order`
WHERE language_id = '" . (int)$language_id . "'
AND order_status_id > '0'
");
return $query->row['total'];
}
public function getTotalOrdersByCurrencyId($currency_id) {
$query = $this->db->query("
SELECT
COUNT(*) AS total
FROM `{$this->db->prefix}order`
WHERE currency_id = '" . (int)$currency_id . "'
AND order_status_id > '0'
");
return $query->row['total'];
}
public function getTotalSales() {
$query = $this->db->query("
SELECT
SUM(total) AS total
FROM `{$this->db->prefix}order`
WHERE order_status_id > '0'
");
return $query->row['total'];
}
public function getTotalSalesByYear($year) {
$query = $this->db->query("
SELECT
SUM(total) AS total
FROM `{$this->db->prefix}order`
WHERE order_status_id > '0'
AND YEAR(date_added) = '" . (int)$year . "'
");
return $query->row['total'];
}
public function createInvoiceNo($order_id) {
$order_info = $this->getOrder($order_id);
if ($order_info && !$order_info['invoice_no']) {
$query = $this->db->query("
SELECT
MAX(invoice_no) AS invoice_no
FROM `{$this->db->prefix}order`
WHERE invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "'
");
if ($query->row['invoice_no']) {
$invoice_no = $query->row['invoice_no'] + 1;
} else {
$invoice_no = 1;
}
$this->db->query("
UPDATE `{$this->db->prefix}order`
SET
invoice_no = '" . (int)$invoice_no . "',
invoice_prefix = '" . $this->db->escape($order_info['invoice_prefix']) . "'
WHERE order_id = '" . (int)$order_id . "'
");
return $order_info['invoice_prefix'] . $invoice_no;
}
}
public function addOrderHistory($order_id, $data) {
$this->db->query("
UPDATE `{$this->db->prefix}order`
SET
order_status_id = '" . (int)$data['order_status_id'] . "',
date_modified = NOW()
WHERE order_id = '" . (int)$order_id . "'
");
$this->db->query("
INSERT INTO {$this->db->prefix}order_history
SET
order_id = '" . (int)$order_id . "',
order_status_id = '" . (int)$data['order_status_id'] . "',
notify = '" . (isset($data['notify']) ? (int)$data['notify'] : 0) . "',
comment = '" . $this->db->escape(strip_tags($data['comment'])) . "',
date_added = NOW()
");
$order_info = $this->getOrder($order_id);
// Send out any gift giftcard mails
if ($this->config->get('config_complete_status_id') == $data['order_status_id']) {
$this->theme->model('sale/giftcard');
$results = $this->getOrderGiftcards($order_id);
foreach ($results as $result) {
$this->model_sale_giftcard->sendGiftcard($result['giftcard_id']);
}
}
if ($data['notify']) {
$order_status_query = $this->db->query("
SELECT *
FROM {$this->db->prefix}order_status
WHERE order_status_id = '" . (int)$data['order_status_id'] . "'
AND language_id = '" . (int)$order_info['language_id'] . "'
");
$status = $order_status_query->row['name'];
$link = html_entity_decode($order_info['store_url'] . 'account/order/info&order_id=' . $order_id, ENT_QUOTES, 'UTF-8');
if ($data['comment']):
$comment = strip_tags(html_entity_decode($data['comment'], ENT_QUOTES, 'UTF-8'));
else:
$comment = 'No further comments added.';
endif;
$callback = array(
'customer_id' => $order_info['customer_id'],
'order_id' => $order_info['order_id'],
'order' => $order_info,
'status' => $status,
'link' => $link,
'comment' => $comment,
'callback' => array(
'class' => __CLASS__,
'method' => 'admin_order_add_history'
)
);
$this->theme->notify('admin_order_add_history', $callback);
}
}
public function getOrderHistories($order_id, $start = 0, $limit = 10) {
if ($start < 0) {
$start = 0;
}
if ($limit < 1) {
$limit = 10;
}
$query = $this->db->query("
SELECT
oh.date_added,
os.name AS status,
oh.comment,
oh.notify
FROM {$this->db->prefix}order_history oh
LEFT JOIN {$this->db->prefix}order_status os
ON oh.order_status_id = os.order_status_id
WHERE oh.order_id = '" . (int)$order_id . "'
AND os.language_id = '" . (int)$this->config->get('config_language_id') . "'
ORDER BY oh.date_added ASC LIMIT " . (int)$start . "," . (int)$limit);
return $query->rows;
}
public function getTotalOrderHistories($order_id) {
$query = $this->db->query("
SELECT
COUNT(*) AS total
FROM {$this->db->prefix}order_history
WHERE order_id = '" . (int)$order_id . "'
");
return $query->row['total'];
}
public function getTotalOrderHistoriesByOrderStatusId($order_status_id) {
$query = $this->db->query("
SELECT
COUNT(*) AS total
FROM {$this->db->prefix}order_history
WHERE order_status_id = '" . (int)$order_status_id . "'
");
return $query->row['total'];
}
public function getCustomersByProductsOrdered($products, $start, $end) {
$implode = array();
foreach ($products as $product_id) {
$implode[] = "op.product_id = '" . (int)$product_id . "'";
}
$query = $this->db->query("
SELECT DISTINCT customer_id
FROM `{$this->db->prefix}order` o
LEFT JOIN {$this->db->prefix}order_product op
ON (o.order_id = op.order_id)
WHERE (" . implode(" OR ", $implode) . ")
AND o.order_status_id <> '0'
LIMIT " . (int)$start . "," . (int)$end);
return $query->rows;
}
public function getTotalCustomersByProductsOrdered($products) {
$implode = array();
foreach ($products as $product_id) {
$implode[] = "op.product_id = '" . (int)$product_id . "'";
}
$query = $this->db->query("
SELECT DISTINCT customer_id
FROM `{$this->db->prefix}order` o
LEFT JOIN {$this->db->prefix}order_product op
ON (o.order_id = op.order_id)
WHERE (" . implode(" OR ", $implode) . ")
AND o.order_status_id <> '0'
");
return $query->row['total'];
}
public function getShippingModules() {
$modules = array();
$this->theme->model('setting/module');
$query = $this->model_setting_module->getAll('shipping');
foreach ($query as $module):
if ($module['status']):
$this->theme->language('shipping/' . $module['code']);
$modules[] = array(
'code' => $module['code'],
'name' => $this->language->get('lang_heading_title')
);
endif;
endforeach;
return $modules;
}
public function getPaymentModules() {
$modules = array();
$this->theme->model('setting/module');
$query = $this->model_setting_module->getAll('payment');
foreach ($query as $module):
if ($module['status']):
$this->theme->language('payment/' . $module['code']);
$modules[] = array(
'code' => $module['code'],
'name' => $this->language->get('lang_heading_title')
);
endif;
endforeach;
return $modules;
}
/*
|--------------------------------------------------------------------------
| NOTIFICATIONS
|--------------------------------------------------------------------------
|
| The below methods are notification callbacks.
|
*/
public function admin_order_add_history($data, $message) {
$search = array(
'!order_id!',
'!status!',
'!link!',
'!comment!'
);
$replace = array(
$data['order_id'],
$data['status'],
$data['link'],
$data['comment']
);
$html_replace = array(
$data['order_id'],
$data['status'],
$data['link'],
nl2br($data['comment'])
);
foreach ($message as $key => $value):
if ($key == 'html'):
$message['html'] = str_replace($search, $html_replace, $value);
else:
$message[$key] = str_replace($search, $replace, $value);
endif;
endforeach;
return $message;
}
}
| oculusxms/ocx | app/admin/model/sale/order.php | PHP | mit | 54,683 |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateRestaurantCusineTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('restaurant_cuisine', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('restaurant_id')->unsigned();
$table->index('restaurant_id');
$table->foreign('restaurant_id')->references('id')->on('restaurant')->onDelete('cascade');
$table->integer('cuisine_id')->unsigned();
$table->index('cuisine_id');
$table->foreign('cuisine_id')->references('id')->on('cuisine')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('restaurant_cuisine');
}
}
| raymundogab7/ko-do-zakkichou-gfccm | database/migrations/2016_05_25_111023_create_restaurant_cusine_table.php | PHP | mit | 1,015 |
import Off from './Off';
import On from './On';
// ==============================
// CONCRETE CONTEXT
// ==============================
export default class Computer {
constructor() {
this._currentState = null;
this._states = {
off: new Off(),
on: new On()
};
}
power() {
this._currentState.power(this);
}
getCurrentState() {
return this._currentState;
}
setCurrentState(state) {
this._currentState = state;
}
getStates() {
return this._states;
}
}
| Badacadabra/PatternifyJS | GoF/classic/Behavioral/State/ECMAScript/ES6/API/Computer.js | JavaScript | mit | 579 |
module UkAddressParser
VERSION = "0.2.0"
end
| reggieb/uk_address_parser | lib/uk_address_parser/version.rb | Ruby | mit | 47 |
module SpecHelpers
def setup_site
site = create('test site')
writers = build(:content_type, site: site, name: "Writers", _user: true)
writers.entries_custom_fields.build(label: "Email", type: "email")
writers.entries_custom_fields.build(label: "First Name", type: "string", required: false)
writers.save!
editors = build(:content_type, site: site, name: "Editors", _user: true)
editors.entries_custom_fields.build(label: "Email", type: "email")
editors.entries_custom_fields.build(label: "First Name", type: "string", required: false)
editors.save!
# @ctype = build(:content_type, site: site, name: "Examples")
# @ctype.entries_custom_fields.build(label: "Name", type: "string", searchable: true)
# @ctype.save!
# @stuff_field = @ctype.entries_custom_fields.build(label: "Stuff", type: "text", searchable: false)
# @stuff_field.save!
# @ctype.entries.create!(name: "Findable entry", stuff: "Some stuff")
# @ctype.entries.create!(name: "Hidden", stuff: "Not findable")
create(:sub_page, site: site, title: "Please search for this findable page", slug: "findable", raw_template: "This is what you were looking for")
create(:sub_page, site: site, title: "Unpublished findable", slug: "unpublished-findable", raw_template: "Not published, so can't be found", published: false)
create(:sub_page, site: site, title: "Seems findable", slug: "seems-findable", raw_template: "Even if it seems findable, it sound't be found because of the searchable flag")
# create(:sub_page, site: site, title: "search", slug: "search", raw_template: <<-EOT
# * Search results:
# <ul>
# {% for result in site.search %}
# {% if result.content_type_slug == 'examples' %}
# <li><a href="/examples/{{result._slug}}">{{ result.name }}</a></li>
# {% else %}
# <li><a href="/{{result.fullpath}}">{{ result.title }}</a></li>
# {% endif %}
# {% endfor %}
# </ul>
# EOT
# )
another_site = create('another site')
create(:sub_page,
site: another_site,
title: 'Writers',
slug: 'writers',
raw_template: 'CMS Writers Page'
)
[site, another_site].each do |s|
create(:sub_page,
site: s,
title: 'User Status',
slug: 'status',
raw_template: <<-EOT
User Status:
{% if end_user.logged_in? %}
Logged in as {{ end_user.type }} with email {{ end_user.email }}
{% else %}
Not logged in.
{% endif %}
EOT
)
home = s.pages.where(slug: 'index').first
home.raw_template = <<-EOF
Notice: {{ flash.notice }}
Error: {{ flash.error }}
Content of the home page.
EOF
home.save!
end
another_editors = build(:content_type, site: another_site, name: "Editors", _user: true)
another_editors.entries_custom_fields.build(label: "Email", type: "email")
another_editors.entries_custom_fields.build(label: "First Name", type: "string", required: false)
another_editors.save!
end
end
RSpec.configure { |c| c.include SpecHelpers }
| ryanaip/locomotivecms-users | spec/support/helpers.rb | Ruby | mit | 3,170 |
var dir_f4703b3db1bd5f8d2d3fca771c570947 =
[
[ "led.c", "led_8c.html", "led_8c" ],
[ "tick.c", "tick_8c.html", "tick_8c" ],
[ "usart2.c", "usart2_8c.html", "usart2_8c" ]
]; | hedrickbt/TempSensor | firmware/Temperature/Documents/Code_Document/html/dir_f4703b3db1bd5f8d2d3fca771c570947.js | JavaScript | mit | 184 |
using System;
using System.Text.RegularExpressions;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
namespace Backend
{
/// <summary>
/// Operation compiler.
/// </summary>
public static class OperationCompiler
{
/// <summary>
/// Compiles a mathematical operation given by a string and constrained by the available parameters.
/// </summary>
/// <returns>The operation.</returns>
/// <param name="func">The arithmetic expression</param>
/// <param name="parameterNames">Array of all parameter by name</param>
public static Func<double[],double> CompileOperation (string func, string[] parameterNames)
{
//the blueprint for the class, wich will be compiled
string tobecompiled =
@"using System;
public class DynamicClass
{
public static double Main(double[] parameters)
{
try{
return ( function );
}
catch(Exception e)
{
Console.Error.WriteLine(e);
}
return double.NaN;
}
}";
//replace parameternames with representation in the array
int pos = 0;
// func = func.Replace ("A", "");
// func = func.Replace ("a", "");
foreach (string s in parameterNames)
{
var value = s.Replace (" ", "");
func = func.Replace (value, "parameters[" + pos + "]");
pos++;
}
//add a fored conversion to double, after each operator
//this is because of the way c# handles values without floating points
var parts = Regex.Split (func, @"(?<=[+,-,*,/])");
func = @"(double)" + parts [0];
for (int i = 1; i < parts.Length; i++)
{
func += @"(double)" + parts [i];
}
tobecompiled = tobecompiled.Replace ("function", func);
var provider = CodeDomProvider.CreateProvider ("c#");
var options = new CompilerParameters ();
var assemblyContainingNotDynamicClass = Path.GetFileName (Assembly.GetExecutingAssembly ().Location);
options.ReferencedAssemblies.Add (assemblyContainingNotDynamicClass);
var results = provider.CompileAssemblyFromSource (options, new[] { tobecompiled });
//if there were no errors while compiling
if (results.Errors.Count > 0)
{
#if DEBUG
foreach (var error in results.Errors)
{
Console.WriteLine (error);
}
#endif
} else
{
//extract class and method
var t = results.CompiledAssembly.GetType ("DynamicClass");
return (Func<double[],double>)Delegate.CreateDelegate (typeof(Func<double[],double>), t.GetMethod ("Main"));
}
return null;
}
}
}
| Onkeliroh/DSA | Code/Backend/OperationCompiler.cs | C# | mit | 2,516 |
module Kissable
VERSION = "1.0.1"
end
| kissmetrics/kissable | lib/kissable/version.rb | Ruby | mit | 40 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("circle", {
cx: "7.2",
cy: "14.4",
r: "3.2"
}), h("circle", {
cx: "14.8",
cy: "18",
r: "2"
}), h("circle", {
cx: "15.2",
cy: "8.8",
r: "4.8"
})), 'BubbleChart'); | AlloyTeam/Nuclear | components/icon/esm/bubble-chart.js | JavaScript | mit | 299 |
import UtilMath = require('./UtilMath');
import Timer = require('./Timer');
import Browser = require('./Browser');
import BaserElement = require('./BaserElement');
import AlignedBoxes = require('./AlignedBoxes');
import BackgroundContainer = require('./BackgroundContainer');
import Checkbox = require('./Checkbox');
import Radio = require('./Radio');
import Select = require('./Select');
import Scroll = require('./Scroll');
import GoogleMaps = require('./GoogleMaps');
import YouTube = require('./YouTube');
import BreakPointsOption = require('../Interface/BreakPointsOption');
import BackgroundContainerOption = require('../Interface/BackgroundContainerOption');
import AlignedBoxCallback = require('../Interface/AlignedBoxCallback');
import CheckableElementOption = require('../Interface/CheckableElementOption');
import SelectOption = require('../Interface/SelectOption');
import ScrollOptions = require('../Interface/ScrollOptions');
import GoogleMapsOption = require('../Interface/GoogleMapsOption');
import YouTubeOption = require('../Interface/YouTubeOption');
class JQueryAdapter {
public static bcScrollTo (selector: any, options?: ScrollOptions): void {
const scroll: Scroll = new Scroll();
scroll.to(selector, options);
}
/**
* 自信の要素を基準に、指定の子要素を背景のように扱う
*
* TODO: BaserElement化する
*
* CSSの`background-size`の`contain`と`cover`の振る舞いに対応
*
* 基準も縦横のセンター・上下・左右に指定可能
*
* @version 0.11.0
* @since 0.0.9
* @param {Object} options オプション
*
* * * *
*
* ## Sample
*
* ### Target HTML
*
* ```html
* <div class="sample" data-id="rb0zOstIiyU" data-width="3840" data-height="2160"></div>
* ```
*
* ### Execute
*
* ```js
* $('.sample').bcYoutube().find('iframe').bcKeepAspectRatio();
* ```
*
* ### Result
*
* comming soon...
*
*/
public bcBackground (options: BackgroundContainerOption): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLElement): void => {
/* tslint:disable */
new BackgroundContainer(elem, options);
/* tslint:enable */
});
}
/**
* 要素の高さを揃える
*
* @version 0.7.0
* @since 0.0.15
*
*/
public bcBoxAlignHeight (columnOrKeyword: string | number | BreakPointsOption<number> = 0, detailTarget?: string, callback?: AlignedBoxCallback): JQuery {
const self: JQuery = $(this);
if (typeof columnOrKeyword === 'string') {
const keyword: string = columnOrKeyword;
switch (keyword) {
case 'destroy': {
const boxes: AlignedBoxes = <AlignedBoxes> self.data(AlignedBoxes.DATA_KEY);
boxes.destroy();
break;
}
default: {
// void
}
}
} else {
const column: number | BreakPointsOption<number> = columnOrKeyword;
// 要素群の高さを揃え、setsに追加
if (detailTarget) {
const $detailTarget: JQuery = self.find(detailTarget);
if ($detailTarget.length) {
self.each(function () {
const $split: JQuery = $(this).find(detailTarget);
/* tslint:disable */
new AlignedBoxes($split, column, callback);
/* tslint:enable */
});
}
} else {
/* tslint:disable */
new AlignedBoxes(self, column, callback);
/* tslint:enable */
}
}
return self;
}
// @version 0.12.1
// @since 0.1.0
public bcBoxLink (): JQuery {
return $(this).on('click', function (e: JQueryEventObject): void {
const $elem: JQuery = $(this);
const $link: JQuery = $elem.find('a, area').eq(0);
const href: string = $link.prop('href');
if ($link.length && href) {
const isBlank: boolean = $link.prop('target') === '_blank';
Browser.jumpTo(href, isBlank);
e.preventDefault();
}
});
}
/**
* WAI-ARIAに対応した装飾可能な汎用要素でラップしたチェックボックスに変更する
*
* @version 0.9.0
* @since 0.0.1
*
* * * *
*
* ## Sample
*
* comming soon...
*
*/
public bcCheckbox (options: CheckableElementOption): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLInputElement): void => {
if (elem.nodeName === 'INPUT') {
/* tslint:disable */
new Checkbox(elem, options);
/* tslint:enable */
} else if ('console' in window) {
console.warn('TypeError: A Node is not HTMLInputElement');
}
});
}
/**
* WAI-ARIAに対応した装飾可能な汎用要素でラップしたラジオボタンに変更する
*
* @version 0.9.0
* @since 0.0.1
*
* * * *
*
* ## Sample
*
* comming soon...
*
*/
public bcRadio (options: CheckableElementOption): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLInputElement): void => {
if (elem.nodeName === 'INPUT') {
/* tslint:disable */
new Radio(elem, options);
/* tslint:enable */
} else if ('console' in window) {
console.warn('TypeError: A Node is not HTMLInputElement');
}
});
}
/**
* WAI-ARIAに対応した装飾可能な汎用要素でラップしたセレクトボックスに変更する
*
* @version 0.9.2
* @since 0.0.1
*
* * * *
*
* ## Sample
*
* comming soon...
*
*/
public bcSelect (options: string | SelectOption): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLSelectElement): void => {
const $elem: JQuery = $(elem);
if (typeof options === 'string') {
switch (options) {
case 'update': {
const select: Select = <Select> $elem.data('bc-element');
select.update();
break;
}
default: {
// void
}
}
} else if (elem.nodeName === 'SELECT') {
/* tslint:disable */
new Select(elem, options);
/* tslint:enable */
} else if ('console' in window) {
console.warn('TypeError: A Node is not HTMLSelectElement');
}
});
}
/**
* 要素内の画像の読み込みが完了してからコールバックを実行する
*
* @version 0.9.0
* @since 0.0.9
*
* * * *
*
* ## Sample
*
* comming soon...
*
*/
public bcImageLoaded (success: () => any, error?: (e: Event) => any): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLElement): void => {
const $elem: JQuery = $(elem);
const manifest: JQueryPromise<any>[] = [];
const $imgs: JQuery = $elem.filter('img').add($elem.find('img'));
if ($imgs.length) {
$imgs.each(function (): void {
const loaded: JQueryDeferred<any> = $.Deferred();
let img: HTMLImageElement = new Image();
img.onload = function (): any {
loaded.resolve();
img.onload = null; // GC
img = null; // GC
};
img.onabort = img.onerror = function (e: Event): any {
loaded.reject(e);
img.onload = null; // GC
img = null; // GC
};
img.src = this.src;
manifest.push(loaded.promise());
});
$.when.apply($, manifest).done( (): void => {
success.call(elem);
}).fail( (e: Event): void => {
if (error) {
error.call(elem, e);
}
});
} else {
success.call(elem);
}
});
}
/**
* 親のコンテナ要素の幅に合わせて、自信の縦横比を保ったまま幅の変更に対応する
*
* iframeなどの縦横比を保ちたいが、幅を変更しても高さが変化しない要素などに有効
*
* @version 0.0.9
* @since 0.0.9
*
* * * *
*
* ## Sample
*
* ### Target HTML
*
* ```html
* <div class="sample" data-id="rb0zOstIiyU" data-width="3840" data-height="2160"></div>
* ```
*
* ### Execute
*
* ```js
* $('.sample').bcYoutube().find('iframe').bcKeepAspectRatio();
* ```
*
* ### Result
*
* comming soon...
*
*/
public bcKeepAspectRatio (): JQuery {
const $w: JQuery = $(window);
const self: JQuery = $(this);
self.each( (i: number, elem: HTMLElement): void => {
const $elem: JQuery = $(elem);
const baseWidth: number = <number> +$elem.data('width');
const baseHeight: number = <number> +$elem.data('height');
const aspectRatio: number = baseWidth / baseHeight;
$w.on('resize', (): void => {
const width: number = $elem.width();
$elem.css({
width: '100%',
height: width / aspectRatio,
});
}).trigger('resize');
});
Timer.wait(30, () => {
$w.trigger('resize');
});
return self;
}
/**
* リンク要素からのアンカーまでスムーズにスクロールをさせる
*
* @version 0.1.0
* @since 0.0.8
*
* * * *
*
* ## Sample
*
* comming soon...
*
*/
public bcScrollTo (options?: ScrollOptions): JQuery {
const self: JQuery = $(this);
return self.on('click', function (e: JQueryMouseEventObject): void {
const $this: JQuery = $(this);
let href: string = $this.attr('href');
const scroll: Scroll = new Scroll();
if (href) {
// キーワードを一番に優先する
if (options && $.isPlainObject(options.keywords)) {
for (const keyword in options.keywords) {
if (options.keywords.hasOwnProperty(keyword)) {
const target: string = options.keywords[keyword];
if (keyword === href) {
scroll.to(target, options);
e.preventDefault();
return;
}
}
}
}
// 「/pathname/#hash」のリンクパターンの場合
// 「/pathname/」が現在のURLだった場合「#hash」に飛ばすようにする
const absPath: string = $this.prop('href');
const currentReferer: string = location.protocol + '//' + location.host + location.pathname + location.search;
href = absPath.replace(currentReferer, '');
// #top はHTML5ではページトップを意味する
if (href === '#top') {
scroll.to(0, options);
e.preventDefault();
return;
}
// セレクタとして要素が存在する場合はその要素に移動
// 「/」で始まるなどセレクターとして不正な場合、例外を投げることがあるので無視する
try {
const target: JQuery = $(href);
if (target.length) {
scroll.to(target, options);
e.preventDefault();
return;
}
} catch (err) { /* void */ }
}
return;
});
}
/**
* リストを均等に分割する
*
* @version 0.2.0
* @since 0.0.14
*
*/
public bcSplitList (columnSize: number, options: any): JQuery {
const self: JQuery = $(this);
const CLASS_NAME: string = 'splited-list';
const CLASS_NAME_NTH: string = 'nth';
const CLASS_NAME_ITEM: string = 'item';
const config: any = $.extend(
{
dataKey: '-bc-split-list-index',
splitChildren: true,
},
options,
);
self.each( (index: number, elem: HTMLElement): void => {
const $container: JQuery = $(elem);
const $list: JQuery = $container.find('>ul');
let $items: JQuery;
if (!config.splitChildren) {
// 直下のliのみ取得
$items = $list.find('>li').detach();
} else {
// 入れ子のliも含めて全て取得
$items = $list.find('li').detach();
// 入れ子のulの削除
$items.find('ul').remove();
}
// リストアイテムの総数
const size: number = $items.length;
const splited: number[] = UtilMath.split(size, columnSize);
const itemArray: HTMLElement[] = $items.toArray();
for (let i: number = 0; i < columnSize; i++) {
const sizeByColumn: number = splited[i];
const $col: JQuery = $('<ul></ul>');
BaserElement.addClassTo($col, CLASS_NAME);
BaserElement.addClassTo($col, CLASS_NAME, '', CLASS_NAME_NTH + columnSize);
$col.appendTo($container);
for (let j: number = 0; j < sizeByColumn; j++) {
const $item: JQuery = $(itemArray.shift());
$item.appendTo($col);
$item.data(config.dataKey, i);
BaserElement.addClassTo($item, CLASS_NAME, CLASS_NAME_ITEM);
BaserElement.addClassTo($item, CLASS_NAME, CLASS_NAME_ITEM, CLASS_NAME_NTH + i);
}
}
$list.remove();
});
return self;
}
/**
* マウスオーバー時に一瞬透明になるエフェクトをかける
*
* @version 0.0.14
* @since 0.0.14
*
*/
public bcWink (options: any): JQuery {
const self: JQuery = $(this);
const config: any = $.extend(
{
close: 50,
open: 200,
opacity: 0.4,
target: null,
stopOnTouch: true,
},
options,
);
self.each( (i: number, elem: HTMLElement): void => {
const $this: JQuery = $(elem);
let $target: JQuery;
if (config.target) {
$target = $this.find(config.target);
} else {
$target = $this;
}
$this.on('mouseenter', (e: JQueryEventObject): boolean => {
if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) {
$this.data('-bc-is-touchstarted', false);
return true;
}
$target
.stop(true, false)
.fadeTo(config.close, config.opacity)
.fadeTo(config.open, 1);
return true;
});
if (config.stopOnTouch) {
$this.on('touchstart', (e: JQueryEventObject): boolean => {
$this.data('-bc-is-touchstarted', true);
return true;
});
}
});
return self;
}
/**
* マップを埋め込む
*
* 現在の対応はGoogleMapsのみ
*
* @version 0.9.0
* @since 0.0.8
*
* * * *
*
* ## Sample
*
* ### Target HTML
*
* ```html
* <div class="sample" data-lat="33.606785" data-lng="130.418314"></div>
* ```
*
* ### Execute
*
* ```js
* $('.sample').bcMaps();
* ```
*
* ### Result
*
* comming soon...
*
*/
public bcMaps (options?: GoogleMapsOption): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLElement): void => {
const $elem: JQuery = $(elem);
const data: GoogleMaps = $elem.data(GoogleMaps.className);
if (data) {
data.reload(options);
} else {
/* tslint:disable */
new GoogleMaps(elem, options);
/* tslint:enable */
}
});
}
/**
* YouTubeを埋め込む
*
* @version 0.9.0
* @since 0.0.8
*
* * * *
*
* ## Sample
*
* ### Target HTML
*
* ```html
* <div class="sample" data-id="rb0zOstIiyU" data-width="720" data-height="480"></div>
* ```
*
* ### Execute
*
* ```js
* $('.sample').bcYoutube();
* ```
*
*/
public bcYoutube (options?: YouTubeOption): JQuery {
const self: JQuery = $(this);
return self.each( (i: number, elem: HTMLElement): void => {
const $elem: JQuery = $(elem);
const data: YouTube = $elem.data(YouTube.className);
if (data) {
data.reload(options);
} else {
/* tslint:disable */
new YouTube(elem, options);
/* tslint:enable */
}
});
}
/**
* マウスオーバー時に画像を切り替える
*
* 【使用非推奨】できるかぎり CSS の `:hover` と `background-image` を使用するべきです。
*
* @deprecated
* @version 0.0.15
* @since 0.0.15
*
*/
public bcRollover (options: any): JQuery {
const self: JQuery = $(this);
const config: any = $.extend(
{
pattern: /_off(\.(?:[a-z0-9]{1,6}))$/i,
replace: '_on$1',
dataPrefix: '-bc-rollover-',
ignore: '',
filter: null,
stopOnTouch: true,
},
options,
);
const dataKeyOff: string = config.dataPrefix + 'off';
const dataKeyOn: string = config.dataPrefix + 'on';
self.each( (i: number, elem: HTMLElement): void => {
const nodeName: string = elem.nodeName.toLowerCase();
const $img: JQuery = $(elem).not(config.ignore);
if ($img.length && nodeName === 'img' || (nodeName === 'input' && $img.prop('type') === 'image')) {
let avail: boolean = true;
if ($.isFunction(config.filter)) {
avail = !!config.filter.call(elem);
} else if (config.filter) {
avail = !!$img.filter(config.filter).length;
}
if (avail) {
const src: string = $img.attr('src');
if (src.match(config.pattern)) {
const onSrc: string = src.replace(config.pattern, config.replace);
$img.data(dataKeyOff, src);
$img.data(dataKeyOn, onSrc);
}
}
}
});
self.on('mouseenter', function (e: JQueryEventObject): boolean {
const $this: JQuery = $(this);
if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) {
$this.data('-bc-is-touchstarted', false);
return true;
}
const onSrc: string = <string> $this.data(dataKeyOn);
$this.prop('src', onSrc);
return true;
});
self.on('mouseleave', function (e: JQueryEventObject): boolean {
const $this: JQuery = $(this);
if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) {
$this.data('-bc-is-touchstarted', false);
return true;
}
const offSrc: string = <string> $this.data(dataKeyOff);
$this.prop('src', offSrc);
return true;
});
if (config.stopOnTouch) {
self.on('touchstart', function (e: JQueryEventObject): boolean {
const $this: JQuery = $(this);
$this.data('-bc-is-touchstarted', true);
return true;
});
}
return self;
}
/**
* マウスオーバー時に半透明になるエフェクトをかける
*
* 【使用非推奨】できるかぎり CSS の `:hover` と `opacity`、そして `transition` を使用するべきです。
*
* @deprecated
* @version 0.0.15
* @since 0.0.15
*
*/
public bcShy (options: any): JQuery {
const self: JQuery = $(this);
const config: any = $.extend(
{
close: 300,
open: 300,
opacity: 0.6,
target: null,
stopOnTouch: true,
},
options,
);
self.each( (i: number, elem: HTMLElement): void => {
const $this: JQuery = $(elem);
let $target: JQuery;
if (config.target) {
$target = $this.find(config.target);
} else {
$target = $this;
}
$this.on('mouseenter', (e: JQueryEventObject): boolean => {
if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) {
$this.data('-bc-is-touchstarted', false);
return true;
}
$target
.stop(true, false)
.fadeTo(config.close, config.opacity);
return true;
});
$this.on('mouseleave', (e: JQueryEventObject): boolean => {
if (config.stopOnTouch && $this.data('-bc-is-touchstarted')) {
$this.data('-bc-is-touchstarted', false);
return true;
}
$target
.stop(true, false)
.fadeTo(config.open, 1);
return true;
});
if (config.stopOnTouch) {
$this.on('touchstart', (e: JQueryEventObject): boolean => {
$this.data('-bc-is-touchstarted', true);
return true;
});
}
});
return self;
}
}
export = JQueryAdapter;
| baserproject/baserjs | src/Class/JQueryAdapter.ts | TypeScript | mit | 18,412 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.registry.type.world.gen;
import net.minecraft.block.BlockLeaves;
import net.minecraft.block.BlockOldLeaf;
import net.minecraft.block.BlockOldLog;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.world.gen.feature.WorldGenBigTree;
import net.minecraft.world.gen.feature.WorldGenBirchTree;
import net.minecraft.world.gen.feature.WorldGenCanopyTree;
import net.minecraft.world.gen.feature.WorldGenMegaJungle;
import net.minecraft.world.gen.feature.WorldGenMegaPineTree;
import net.minecraft.world.gen.feature.WorldGenSavannaTree;
import net.minecraft.world.gen.feature.WorldGenShrub;
import net.minecraft.world.gen.feature.WorldGenSwamp;
import net.minecraft.world.gen.feature.WorldGenTaiga1;
import net.minecraft.world.gen.feature.WorldGenTaiga2;
import net.minecraft.world.gen.feature.WorldGenTrees;
import net.minecraft.world.gen.feature.WorldGenerator;
import org.spongepowered.api.registry.util.RegisterCatalog;
import org.spongepowered.api.util.weighted.VariableAmount;
import org.spongepowered.api.world.gen.PopulatorObject;
import org.spongepowered.api.world.gen.type.BiomeTreeType;
import org.spongepowered.api.world.gen.type.BiomeTreeTypes;
import org.spongepowered.common.bridge.world.gen.WorldGenTreesBridge;
import org.spongepowered.common.registry.type.AbstractPrefixAlternateCatalogTypeRegistryModule;
import org.spongepowered.common.world.gen.type.SpongeBiomeTreeType;
import javax.annotation.Nullable;
@RegisterCatalog(BiomeTreeTypes.class)
public class BiomeTreeTypeRegistryModule extends AbstractPrefixAlternateCatalogTypeRegistryModule<BiomeTreeType> {
public BiomeTreeTypeRegistryModule() {
super("minecraft");
}
@Override
public void registerDefaults() {
register(create("oak", new WorldGenTrees(false), new WorldGenBigTree(false)));
register(create("birch", new WorldGenBirchTree(false, false), new WorldGenBirchTree(false, true)));
WorldGenMegaPineTree tall_megapine = new WorldGenMegaPineTree(false, true);
WorldGenMegaPineTree megapine = new WorldGenMegaPineTree(false, false);
register(create("tall_taiga", new WorldGenTaiga2(false), tall_megapine));
register(create("pointy_taiga", new WorldGenTaiga1(), megapine));
IBlockState jlog = Blocks.LOG.getDefaultState()
.withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE);
IBlockState jleaf = Blocks.LEAVES.getDefaultState()
.withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE)
.withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false));
IBlockState leaf = Blocks.LEAVES.getDefaultState()
.withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE)
.withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false));
WorldGenTreesBridge trees = (WorldGenTreesBridge) new WorldGenTrees(false, 4, jlog, jleaf, true);
trees.bridge$setMinHeight(VariableAmount.baseWithRandomAddition(4, 7));
WorldGenMegaJungle mega = new WorldGenMegaJungle(false, 10, 20, jlog, jleaf);
register(create("jungle", (WorldGenTrees) trees, mega));
WorldGenShrub bush = new WorldGenShrub(jlog, leaf);
register(create("jungle_bush", bush, null));
register(create("savanna", new WorldGenSavannaTree(false), null));
register(create("canopy", new WorldGenCanopyTree(false), null));
register(create("swamp", new WorldGenSwamp(), null));
}
private SpongeBiomeTreeType create(String name, WorldGenerator small, @Nullable WorldGenerator large) {
return new SpongeBiomeTreeType("minecraft:" + name, name, (PopulatorObject) small, (PopulatorObject) large);
}
}
| SpongePowered/SpongeCommon | src/main/java/org/spongepowered/common/registry/type/world/gen/BiomeTreeTypeRegistryModule.java | Java | mit | 5,058 |
var Nightmare = require('nightmare')
var NTU = require('./NightmareTestUtils')
const NounPhraseTest = (nightmare, delay) => {
return nightmare
// Can I open the addedit form and make it go away by clicking cancel?
.click('#add-np').wait(delay)
.click('#np-addedit-form #cancel').wait(delay)
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
// If I open the addedit form, enter and a save a noun,
// will the form then go away and can I see the insertNounPhraseCheck mark in the quiz?
/*.then( res => {
return nightmare
.click('#add-np').wait(delay)
.type('#base', 'carrot').wait(delay)
.click('#save-np').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
.then( res => {return NTU.lookFor(nightmare, '#insertNounPhraseCheck', true)})
// Can I open the addedit form via editing and make it go away by clicking cancel?
.then( res => {
return nightmare
.click('#id1').wait(delay)
.click('#cancel').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
// If I open the addedit form via editing, change and a save a noun,
// will the form then go away and can I see the updateNounPhraseCheck mark in the quiz?
.then( res => {
return nightmare
.click('#id1').wait(delay)
.type('#base', 'beaver').wait(delay)
.click('#save-np').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
.then( res => {return NTU.lookFor(nightmare, '#updateNounPhraseCheck', true)})
// If I open the addedit form via editing and delete the noun,
// will the form then go away and can I see the deleteNounPhraseCheck mark in the quiz?
.then( res => {
return nightmare
.click('#id1').wait(delay)
.click('#delete-np').wait(delay)
})
.then( res => {return NTU.lookFor(nightmare, '#np-addedit-form', false)})
.then( res => {return NTU.lookFor(nightmare, '#deleteNounPhraseCheck', true)})
//.then( res => {return NTU.lookFor(nightmare, '#quiz', false)})
.then( res => {
return nightmare
.click('#add-np').wait(delay)
.type('#base', 'carrot').wait(delay)
.click('#save-np').wait(delay)
})*/
// Can I see the examples button?
//.then( res => {return NTU.lookFor(nightmare, '#examples', true)})
// Does it go away after I click it?
//.then( res => {return nightmare.click('#examples')})
//.then( res => {return NTU.lookFor(nightmare, '#examples', false)})
}
module.exports = NounPhraseTest
| bostontrader/senmaker | src/nightmare/NounPhraseTest.js | JavaScript | mit | 2,952 |
<?php
namespace Soga\NominaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="trasladoeps")
* @ORM\Entity(repositoryClass="Soga\NominaBundle\Repository\TrasladoEpsRepository")
*/
class TrasladoEps
{
/**
* @ORM\Id
* @ORM\Column(name="id", type="integer")
*/
private $id;
/**
* @ORM\Column(name="cedemple", type="string", length=15, nullable=false)
*/
private $cedemple;
/**
* @ORM\Column(name="codigo_eps_actual_fk", type="integer")
*/
private $codigoEpsActualFk;
/**
* @ORM\Column(name="codigo_eps_nueva_fk", type="integer")
*/
private $codigoEpsNuevaFk;
/**
* @ORM\Column(name="fecha_inicio_traslado", type="date", nullable=true)
*/
private $fechaInicioTraslado;
/**
* @ORM\Column(name="fecha_aplicacion_traslado", type="date", nullable=true)
*/
private $fechaAplicacionTraslado;
/**
* Set id
*
* @param integer $id
* @return TrasladoEps
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set cedemple
*
* @param string $cedemple
* @return TrasladoEps
*/
public function setCedemple($cedemple)
{
$this->cedemple = $cedemple;
return $this;
}
/**
* Get cedemple
*
* @return string
*/
public function getCedemple()
{
return $this->cedemple;
}
/**
* Set codigoEpsActualFk
*
* @param integer $codigoEpsActualFk
* @return TrasladoEps
*/
public function setCodigoEpsActualFk($codigoEpsActualFk)
{
$this->codigoEpsActualFk = $codigoEpsActualFk;
return $this;
}
/**
* Get codigoEpsActualFk
*
* @return integer
*/
public function getCodigoEpsActualFk()
{
return $this->codigoEpsActualFk;
}
/**
* Set codigoEpsNuevaFk
*
* @param integer $codigoEpsNuevaFk
* @return TrasladoEps
*/
public function setCodigoEpsNuevaFk($codigoEpsNuevaFk)
{
$this->codigoEpsNuevaFk = $codigoEpsNuevaFk;
return $this;
}
/**
* Get codigoEpsNuevaFk
*
* @return integer
*/
public function getCodigoEpsNuevaFk()
{
return $this->codigoEpsNuevaFk;
}
/**
* Set fechaInicioTraslado
*
* @param \DateTime $fechaInicioTraslado
* @return TrasladoEps
*/
public function setFechaInicioTraslado($fechaInicioTraslado)
{
$this->fechaInicioTraslado = $fechaInicioTraslado;
return $this;
}
/**
* Get fechaInicioTraslado
*
* @return \DateTime
*/
public function getFechaInicioTraslado()
{
return $this->fechaInicioTraslado;
}
/**
* Set fechaAplicacionTraslado
*
* @param \DateTime $fechaAplicacionTraslado
* @return TrasladoEps
*/
public function setFechaAplicacionTraslado($fechaAplicacionTraslado)
{
$this->fechaAplicacionTraslado = $fechaAplicacionTraslado;
return $this;
}
/**
* Get fechaAplicacionTraslado
*
* @return \DateTime
*/
public function getFechaAplicacionTraslado()
{
return $this->fechaAplicacionTraslado;
}
}
| wariox3/soga | src/Soga/NominaBundle/Entity/TrasladoEps.php | PHP | mit | 3,539 |
import { UIPanel, UIRow, UIHorizontalRule } from './libs/ui.js';
import { AddObjectCommand } from './commands/AddObjectCommand.js';
import { RemoveObjectCommand } from './commands/RemoveObjectCommand.js';
import { MultiCmdsCommand } from './commands/MultiCmdsCommand.js';
import { SetMaterialValueCommand } from './commands/SetMaterialValueCommand.js';
function MenubarEdit( editor ) {
var strings = editor.strings;
var container = new UIPanel();
container.setClass( 'menu' );
var title = new UIPanel();
title.setClass( 'title' );
title.setTextContent( strings.getKey( 'menubar/edit' ) );
container.add( title );
var options = new UIPanel();
options.setClass( 'options' );
container.add( options );
// Undo
var undo = new UIRow();
undo.setClass( 'option' );
undo.setTextContent( strings.getKey( 'menubar/edit/undo' ) );
undo.onClick( function () {
editor.undo();
} );
options.add( undo );
// Redo
var redo = new UIRow();
redo.setClass( 'option' );
redo.setTextContent( strings.getKey( 'menubar/edit/redo' ) );
redo.onClick( function () {
editor.redo();
} );
options.add( redo );
// Clear History
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/clear_history' ) );
option.onClick( function () {
if ( confirm( 'The Undo/Redo History will be cleared. Are you sure?' ) ) {
editor.history.clear();
}
} );
options.add( option );
editor.signals.historyChanged.add( function () {
var history = editor.history;
undo.setClass( 'option' );
redo.setClass( 'option' );
if ( history.undos.length == 0 ) {
undo.setClass( 'inactive' );
}
if ( history.redos.length == 0 ) {
redo.setClass( 'inactive' );
}
} );
// ---
options.add( new UIHorizontalRule() );
// Clone
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/clone' ) );
option.onClick( function () {
var object = editor.selected;
if ( object.parent === null ) return; // avoid cloning the camera or scene
object = object.clone();
editor.execute( new AddObjectCommand( editor, object ) );
} );
options.add( option );
// Delete
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/delete' ) );
option.onClick( function () {
var object = editor.selected;
if ( object !== null && object.parent !== null ) {
editor.execute( new RemoveObjectCommand( editor, object ) );
}
} );
options.add( option );
// Minify shaders
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/minify_shaders' ) );
option.onClick( function () {
var root = editor.selected || editor.scene;
var errors = [];
var nMaterialsChanged = 0;
var path = [];
function getPath( object ) {
path.length = 0;
var parent = object.parent;
if ( parent !== undefined ) getPath( parent );
path.push( object.name || object.uuid );
return path;
}
var cmds = [];
root.traverse( function ( object ) {
var material = object.material;
if ( material !== undefined && material.isShaderMaterial ) {
try {
var shader = glslprep.minifyGlsl( [
material.vertexShader, material.fragmentShader ] );
cmds.push( new SetMaterialValueCommand( editor, object, 'vertexShader', shader[ 0 ] ) );
cmds.push( new SetMaterialValueCommand( editor, object, 'fragmentShader', shader[ 1 ] ) );
++ nMaterialsChanged;
} catch ( e ) {
var path = getPath( object ).join( "/" );
if ( e instanceof glslprep.SyntaxError )
errors.push( path + ":" +
e.line + ":" + e.column + ": " + e.message );
else {
errors.push( path +
": Unexpected error (see console for details)." );
console.error( e.stack || e );
}
}
}
} );
if ( nMaterialsChanged > 0 ) {
editor.execute( new MultiCmdsCommand( editor, cmds ), 'Minify Shaders' );
}
window.alert( nMaterialsChanged +
" material(s) were changed.\n" + errors.join( "\n" ) );
} );
options.add( option );
options.add( new UIHorizontalRule() );
// Set textures to sRGB. See #15903
var option = new UIRow();
option.setClass( 'option' );
option.setTextContent( strings.getKey( 'menubar/edit/fixcolormaps' ) );
option.onClick( function () {
editor.scene.traverse( fixColorMap );
} );
options.add( option );
var colorMaps = [ 'map', 'envMap', 'emissiveMap' ];
function fixColorMap( obj ) {
var material = obj.material;
if ( material !== undefined ) {
if ( Array.isArray( material ) === true ) {
for ( var i = 0; i < material.length; i ++ ) {
fixMaterial( material[ i ] );
}
} else {
fixMaterial( material );
}
editor.signals.sceneGraphChanged.dispatch();
}
}
function fixMaterial( material ) {
var needsUpdate = material.needsUpdate;
for ( var i = 0; i < colorMaps.length; i ++ ) {
var map = material[ colorMaps[ i ] ];
if ( map ) {
map.encoding = THREE.sRGBEncoding;
needsUpdate = true;
}
}
material.needsUpdate = needsUpdate;
}
return container;
}
export { MenubarEdit };
| fraguada/three.js | editor/js/Menubar.Edit.js | JavaScript | mit | 5,225 |
using System.Collections.Generic;
using System.Threading;
using LanguageExt;
namespace SJP.Schematic.Core
{
public interface IDatabaseViewProvider
{
OptionAsync<IDatabaseView> GetView(Identifier viewName, CancellationToken cancellationToken = default);
IAsyncEnumerable<IDatabaseView> GetAllViews(CancellationToken cancellationToken = default);
}
}
| sjp/SJP.Schema | src/SJP.Schematic.Core/IDatabaseViewProvider.cs | C# | mit | 382 |
import React from 'react';
class Icon extends React.Component {
constructor(props) {
super(props);
this.displayName = 'Icon';
this.icon = "fa " + this.props.icon + " " + this.props.size;
}
render() {
return (
<i className={this.icon}></i>
);
}
}
export default Icon;
| evilfaust/lyceum9sass | scripts/components/ui/icon.js | JavaScript | mit | 330 |
import pyak
import yikbot
import time
# Latitude and Longitude of location where bot should be localized
yLocation = pyak.Location("42.270340", "-83.742224")
yb = yikbot.YikBot("yikBot", yLocation)
print "DEBUG: Registered yikBot with handle %s and id %s" % (yb.handle, yb.id)
print "DEBUG: Going to sleep, new yakkers must wait ~90 seconds before they can act"
time.sleep(90)
print "DEBUG: yikBot instance 90 seconds after initialization"
print vars(yb)
yb.boot() | congrieb/yikBot | start.py | Python | mit | 469 |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :address do
name ""
city ""
postal_number "00970"
country ""
street "Aarteenetsijänkuja 8D 24"
phone_number "+358445655606"
description ""
end
end
| deiga/mall | spec/factories/address_factory.rb | Ruby | mit | 280 |
package com.avocarrot.adapters.sample.admob;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.avocarrot.adapters.sample.R;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.formats.NativeAd;
import com.google.android.gms.ads.formats.NativeAppInstallAd;
import com.google.android.gms.ads.formats.NativeAppInstallAdView;
import com.google.android.gms.ads.formats.NativeContentAd;
import com.google.android.gms.ads.formats.NativeContentAdView;
import java.util.List;
public class AdmobNativeActivity extends AppCompatActivity {
@NonNull
private static final String EXTRA_AD_UNIT_ID = "ad_unit_id";
@NonNull
public static Intent buildIntent(@NonNull final Context context, @NonNull final String adUnitId) {
return new Intent(context, AdmobNativeActivity.class).putExtra(EXTRA_AD_UNIT_ID, adUnitId);
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admob_native);
final Intent intent = getIntent();
final String adUnitId = intent.getStringExtra(EXTRA_AD_UNIT_ID);
if (TextUtils.isEmpty(adUnitId)) {
finish();
return;
}
final AdLoader adLoader = new AdLoader.Builder(this, adUnitId)
.forAppInstallAd(new NativeAppInstallAd.OnAppInstallAdLoadedListener() {
@Override
public void onAppInstallAdLoaded(final NativeAppInstallAd ad) {
final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.admob_ad_view);
final NativeAppInstallAdView adView = (NativeAppInstallAdView) getLayoutInflater().inflate(R.layout.admob_ad_app_install, null);
populate(ad, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
})
.forContentAd(new NativeContentAd.OnContentAdLoadedListener() {
@Override
public void onContentAdLoaded(final NativeContentAd ad) {
final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.admob_ad_view);
final NativeContentAdView adView = (NativeContentAdView) getLayoutInflater().inflate(R.layout.admob_ad_content, null);
populate(ad, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
})
.withAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(final int errorCode) {
Toast.makeText(getApplicationContext(), "Custom event native ad failed with code: " + errorCode, Toast.LENGTH_LONG).show();
}
})
.build();
adLoader.loadAd(new AdRequest.Builder().build());
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
/**
* Populates a {@link NativeAppInstallAdView} object with data from a given {@link NativeAppInstallAd}.
*/
private void populate(@NonNull final NativeAppInstallAd nativeAppInstallAd, @NonNull final NativeAppInstallAdView adView) {
adView.setNativeAd(nativeAppInstallAd);
adView.setHeadlineView(adView.findViewById(R.id.appinstall_headline));
adView.setImageView(adView.findViewById(R.id.appinstall_image));
adView.setBodyView(adView.findViewById(R.id.appinstall_body));
adView.setCallToActionView(adView.findViewById(R.id.appinstall_call_to_action));
adView.setIconView(adView.findViewById(R.id.appinstall_app_icon));
adView.setPriceView(adView.findViewById(R.id.appinstall_price));
adView.setStarRatingView(adView.findViewById(R.id.appinstall_stars));
adView.setStoreView(adView.findViewById(R.id.appinstall_store));
// Some assets are guaranteed to be in every NativeAppInstallAd.
((TextView) adView.getHeadlineView()).setText(nativeAppInstallAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAppInstallAd.getBody());
((Button) adView.getCallToActionView()).setText(nativeAppInstallAd.getCallToAction());
((ImageView) adView.getIconView()).setImageDrawable(nativeAppInstallAd.getIcon().getDrawable());
final List<NativeAd.Image> images = nativeAppInstallAd.getImages();
if (images.size() > 0) {
((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable());
}
// Some aren't guaranteed, however, and should be checked.
if (nativeAppInstallAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAppInstallAd.getPrice());
}
if (nativeAppInstallAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAppInstallAd.getStore());
}
if (nativeAppInstallAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView()).setRating(nativeAppInstallAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
}
/**
* Populates a {@link NativeContentAdView} object with data from a given {@link NativeContentAd}.
*/
private void populate(@NonNull final NativeContentAd nativeContentAd, @NonNull final NativeContentAdView adView) {
adView.setNativeAd(nativeContentAd);
adView.setHeadlineView(adView.findViewById(R.id.contentad_headline));
adView.setImageView(adView.findViewById(R.id.contentad_image));
adView.setBodyView(adView.findViewById(R.id.contentad_body));
adView.setCallToActionView(adView.findViewById(R.id.contentad_call_to_action));
adView.setLogoView(adView.findViewById(R.id.contentad_logo));
adView.setAdvertiserView(adView.findViewById(R.id.contentad_advertiser));
// Some assets are guaranteed to be in every NativeContentAd.
((TextView) adView.getHeadlineView()).setText(nativeContentAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeContentAd.getBody());
((TextView) adView.getCallToActionView()).setText(nativeContentAd.getCallToAction());
((TextView) adView.getAdvertiserView()).setText(nativeContentAd.getAdvertiser());
final List<NativeAd.Image> images = nativeContentAd.getImages();
if (images.size() > 0) {
((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable());
}
// Some aren't guaranteed, however, and should be checked.
final NativeAd.Image logoImage = nativeContentAd.getLogo();
if (logoImage == null) {
adView.getLogoView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getLogoView()).setImageDrawable(logoImage.getDrawable());
adView.getLogoView().setVisibility(View.VISIBLE);
}
}
}
| Avocarrot/android-adapters | avocarrot-app-sample/src/main/java/com/avocarrot/adapters/sample/admob/AdmobNativeActivity.java | Java | mit | 8,086 |
# frozen_string_literal: true
require 'expectacle/version'
require 'expectacle/thrower'
# Expectable: simple pry/expect wrapper.
module Expectacle; end
| stereocat/expectacle | lib/expectacle.rb | Ruby | mit | 154 |
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// appleseed.renderer headers.
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/platform/python.h"
namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
// Work around a regression in Visual Studio 2015 Update 3.
#if defined(_MSC_VER) && _MSC_VER == 1900
namespace boost
{
template <> Scene const volatile* get_pointer<Scene const volatile>(Scene const volatile* p) { return p; }
}
#endif
namespace
{
auto_release_ptr<Scene> create_scene()
{
return SceneFactory::create();
}
}
void bind_scene()
{
bpy::class_<Scene, auto_release_ptr<Scene>, bpy::bases<Entity, BaseGroup>, boost::noncopyable>("Scene", bpy::no_init)
.def("__init__", bpy::make_constructor(create_scene))
.def("get_uid", &Identifiable::get_uid)
.def("cameras", &Scene::cameras, bpy::return_value_policy<bpy::reference_existing_object>())
.def("get_environment", &Scene::get_environment, bpy::return_value_policy<bpy::reference_existing_object>())
.def("set_environment", &Scene::set_environment)
.def("environment_edfs", &Scene::environment_edfs, bpy::return_value_policy<bpy::reference_existing_object>())
.def("environment_shaders", &Scene::environment_shaders, bpy::return_value_policy<bpy::reference_existing_object>())
.def("compute_bbox", &Scene::compute_bbox)
;
}
| Biart95/appleseed | src/appleseed.python/bindscene.cpp | C++ | mit | 2,822 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2014-2019 The DigiByte Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <wallet/db.h>
#include <addrman.h>
#include <hash.h>
#include <protocol.h>
#include <utilstrencodings.h>
#include <wallet/walletutil.h>
#include <stdint.h>
#ifndef WIN32
#include <sys/stat.h>
#endif
#include <boost/thread.hpp>
namespace {
//! Make sure database has a unique fileid within the environment. If it
//! doesn't, throw an error. BDB caches do not work properly when more than one
//! open database has the same fileid (values written to one database may show
//! up in reads to other databases).
//!
//! BerkeleyDB generates unique fileids by default
//! (https://docs.oracle.com/cd/E17275_01/html/programmer_reference/program_copy.html),
//! so digibyte should never create different databases with the same fileid, but
//! this error can be triggered if users manually copy database files.
void CheckUniqueFileid(const BerkeleyEnvironment& env, const std::string& filename, Db& db)
{
if (env.IsMock()) return;
u_int8_t fileid[DB_FILE_ID_LEN];
int ret = db.get_mpf()->get_fileid(fileid);
if (ret != 0) {
throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (get_fileid failed with %d)", filename, ret));
}
for (const auto& item : env.mapDb) {
u_int8_t item_fileid[DB_FILE_ID_LEN];
if (item.second && item.second->get_mpf()->get_fileid(item_fileid) == 0 &&
memcmp(fileid, item_fileid, sizeof(fileid)) == 0) {
const char* item_filename = nullptr;
item.second->get_dbname(&item_filename, nullptr);
throw std::runtime_error(strprintf("BerkeleyBatch: Can't open database %s (duplicates fileid %s from %s)", filename,
HexStr(std::begin(item_fileid), std::end(item_fileid)),
item_filename ? item_filename : "(unknown database)"));
}
}
}
CCriticalSection cs_db;
std::map<std::string, BerkeleyEnvironment> g_dbenvs GUARDED_BY(cs_db); //!< Map from directory name to open db environment.
} // namespace
BerkeleyEnvironment* GetWalletEnv(const fs::path& wallet_path, std::string& database_filename)
{
fs::path env_directory;
if (fs::is_regular_file(wallet_path)) {
// Special case for backwards compatibility: if wallet path points to an
// existing file, treat it as the path to a BDB data file in a parent
// directory that also contains BDB log files.
env_directory = wallet_path.parent_path();
database_filename = wallet_path.filename().string();
} else {
// Normal case: Interpret wallet path as a directory path containing
// data and log files.
env_directory = wallet_path;
database_filename = "wallet.dat";
}
LOCK(cs_db);
// Note: An ununsed temporary BerkeleyEnvironment object may be created inside the
// emplace function if the key already exists. This is a little inefficient,
// but not a big concern since the map will be changed in the future to hold
// pointers instead of objects, anyway.
return &g_dbenvs.emplace(std::piecewise_construct, std::forward_as_tuple(env_directory.string()), std::forward_as_tuple(env_directory)).first->second;
}
//
// BerkeleyBatch
//
void BerkeleyEnvironment::Close()
{
if (!fDbEnvInit)
return;
fDbEnvInit = false;
for (auto& db : mapDb) {
auto count = mapFileUseCount.find(db.first);
assert(count == mapFileUseCount.end() || count->second == 0);
if (db.second) {
db.second->close(0);
delete db.second;
db.second = nullptr;
}
}
int ret = dbenv->close(0);
if (ret != 0)
LogPrintf("BerkeleyEnvironment::Close: Error %d closing database environment: %s\n", ret, DbEnv::strerror(ret));
if (!fMockDb)
DbEnv((u_int32_t)0).remove(strPath.c_str(), 0);
}
void BerkeleyEnvironment::Reset()
{
dbenv.reset(new DbEnv(DB_CXX_NO_EXCEPTIONS));
fDbEnvInit = false;
fMockDb = false;
}
BerkeleyEnvironment::BerkeleyEnvironment(const fs::path& dir_path) : strPath(dir_path.string())
{
Reset();
}
BerkeleyEnvironment::~BerkeleyEnvironment()
{
Close();
}
bool BerkeleyEnvironment::Open(bool retry)
{
if (fDbEnvInit)
return true;
boost::this_thread::interruption_point();
fs::path pathIn = strPath;
TryCreateDirectories(pathIn);
if (!LockDirectory(pathIn, ".walletlock")) {
LogPrintf("Cannot obtain a lock on wallet directory %s. Another instance of digibyte may be using it.\n", strPath);
return false;
}
fs::path pathLogDir = pathIn / "database";
TryCreateDirectories(pathLogDir);
fs::path pathErrorFile = pathIn / "db.log";
LogPrintf("BerkeleyEnvironment::Open: LogDir=%s ErrorFile=%s\n", pathLogDir.string(), pathErrorFile.string());
unsigned int nEnvFlags = 0;
if (gArgs.GetBoolArg("-privdb", DEFAULT_WALLET_PRIVDB))
nEnvFlags |= DB_PRIVATE;
dbenv->set_lg_dir(pathLogDir.string().c_str());
dbenv->set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet
dbenv->set_lg_bsize(0x10000);
dbenv->set_lg_max(1048576);
dbenv->set_lk_max_locks(40000);
dbenv->set_lk_max_objects(40000);
dbenv->set_errfile(fsbridge::fopen(pathErrorFile, "a")); /// debug
dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->set_flags(DB_TXN_WRITE_NOSYNC, 1);
dbenv->log_set_config(DB_LOG_AUTO_REMOVE, 1);
int ret = dbenv->open(strPath.c_str(),
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_RECOVER |
nEnvFlags,
S_IRUSR | S_IWUSR);
if (ret != 0) {
LogPrintf("BerkeleyEnvironment::Open: Error %d opening database environment: %s\n", ret, DbEnv::strerror(ret));
int ret2 = dbenv->close(0);
if (ret2 != 0) {
LogPrintf("BerkeleyEnvironment::Open: Error %d closing failed database environment: %s\n", ret2, DbEnv::strerror(ret2));
}
Reset();
if (retry) {
// try moving the database env out of the way
fs::path pathDatabaseBak = pathIn / strprintf("database.%d.bak", GetTime());
try {
fs::rename(pathLogDir, pathDatabaseBak);
LogPrintf("Moved old %s to %s. Retrying.\n", pathLogDir.string(), pathDatabaseBak.string());
} catch (const fs::filesystem_error&) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try opening it again one more time
if (!Open(false /* retry */)) {
// if it still fails, it probably means we can't even create the database env
return false;
}
} else {
return false;
}
}
fDbEnvInit = true;
fMockDb = false;
return true;
}
void BerkeleyEnvironment::MakeMock()
{
if (fDbEnvInit)
throw std::runtime_error("BerkeleyEnvironment::MakeMock: Already initialized");
boost::this_thread::interruption_point();
LogPrint(BCLog::DB, "BerkeleyEnvironment::MakeMock\n");
dbenv->set_cachesize(1, 0, 1);
dbenv->set_lg_bsize(10485760 * 4);
dbenv->set_lg_max(10485760);
dbenv->set_lk_max_locks(10000);
dbenv->set_lk_max_objects(10000);
dbenv->set_flags(DB_AUTO_COMMIT, 1);
dbenv->log_set_config(DB_LOG_IN_MEMORY, 1);
int ret = dbenv->open(nullptr,
DB_CREATE |
DB_INIT_LOCK |
DB_INIT_LOG |
DB_INIT_MPOOL |
DB_INIT_TXN |
DB_THREAD |
DB_PRIVATE,
S_IRUSR | S_IWUSR);
if (ret > 0)
throw std::runtime_error(strprintf("BerkeleyEnvironment::MakeMock: Error %d opening database environment.", ret));
fDbEnvInit = true;
fMockDb = true;
}
BerkeleyEnvironment::VerifyResult BerkeleyEnvironment::Verify(const std::string& strFile, recoverFunc_type recoverFunc, std::string& out_backup_filename)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
Db db(dbenv.get(), 0);
int result = db.verify(strFile.c_str(), nullptr, nullptr, 0);
if (result == 0)
return VerifyResult::VERIFY_OK;
else if (recoverFunc == nullptr)
return VerifyResult::RECOVER_FAIL;
// Try to recover:
bool fRecovered = (*recoverFunc)(fs::path(strPath) / strFile, out_backup_filename);
return (fRecovered ? VerifyResult::RECOVER_OK : VerifyResult::RECOVER_FAIL);
}
bool BerkeleyBatch::Recover(const fs::path& file_path, void *callbackDataIn, bool (*recoverKVcallback)(void* callbackData, CDataStream ssKey, CDataStream ssValue), std::string& newFilename)
{
std::string filename;
BerkeleyEnvironment* env = GetWalletEnv(file_path, filename);
// Recovery procedure:
// move wallet file to walletfilename.timestamp.bak
// Call Salvage with fAggressive=true to
// get as much data as possible.
// Rewrite salvaged data to fresh wallet file
// Set -rescan so any missing transactions will be
// found.
int64_t now = GetTime();
newFilename = strprintf("%s.%d.bak", filename, now);
int result = env->dbenv->dbrename(nullptr, filename.c_str(), nullptr,
newFilename.c_str(), DB_AUTO_COMMIT);
if (result == 0)
LogPrintf("Renamed %s to %s\n", filename, newFilename);
else
{
LogPrintf("Failed to rename %s to %s\n", filename, newFilename);
return false;
}
std::vector<BerkeleyEnvironment::KeyValPair> salvagedData;
bool fSuccess = env->Salvage(newFilename, true, salvagedData);
if (salvagedData.empty())
{
LogPrintf("Salvage(aggressive) found no records in %s.\n", newFilename);
return false;
}
LogPrintf("Salvage(aggressive) found %u records\n", salvagedData.size());
std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
filename.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("Cannot create database file %s\n", filename);
pdbCopy->close(0);
return false;
}
DbTxn* ptxn = env->TxnBegin();
for (BerkeleyEnvironment::KeyValPair& row : salvagedData)
{
if (recoverKVcallback)
{
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue))
continue;
}
Dbt datKey(&row.first[0], row.first.size());
Dbt datValue(&row.second[0], row.second.size());
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
ptxn->commit(0);
pdbCopy->close(0);
return fSuccess;
}
bool BerkeleyBatch::VerifyEnvironment(const fs::path& file_path, std::string& errorStr)
{
std::string walletFile;
BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile);
fs::path walletDir = env->Directory();
LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
LogPrintf("Using wallet %s\n", walletFile);
// Wallet file must be a plain filename without a directory
if (walletFile != fs::basename(walletFile) + fs::extension(walletFile))
{
errorStr = strprintf(_("Wallet %s resides outside wallet directory %s"), walletFile, walletDir.string());
return false;
}
if (!env->Open(true /* retry */)) {
errorStr = strprintf(_("Error initializing wallet database environment %s!"), walletDir);
return false;
}
return true;
}
bool BerkeleyBatch::VerifyDatabaseFile(const fs::path& file_path, std::string& warningStr, std::string& errorStr, BerkeleyEnvironment::recoverFunc_type recoverFunc)
{
std::string walletFile;
BerkeleyEnvironment* env = GetWalletEnv(file_path, walletFile);
fs::path walletDir = env->Directory();
if (fs::exists(walletDir / walletFile))
{
std::string backup_filename;
BerkeleyEnvironment::VerifyResult r = env->Verify(walletFile, recoverFunc, backup_filename);
if (r == BerkeleyEnvironment::VerifyResult::RECOVER_OK)
{
warningStr = strprintf(_("Warning: Wallet file corrupt, data salvaged!"
" Original %s saved as %s in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."),
walletFile, backup_filename, walletDir);
}
if (r == BerkeleyEnvironment::VerifyResult::RECOVER_FAIL)
{
errorStr = strprintf(_("%s corrupt, salvage failed"), walletFile);
return false;
}
}
// also return true if files does not exists
return true;
}
/* End of headers, beginning of key/value data */
static const char *HEADER_END = "HEADER=END";
/* End of key/value data */
static const char *DATA_END = "DATA=END";
bool BerkeleyEnvironment::Salvage(const std::string& strFile, bool fAggressive, std::vector<BerkeleyEnvironment::KeyValPair>& vResult)
{
LOCK(cs_db);
assert(mapFileUseCount.count(strFile) == 0);
u_int32_t flags = DB_SALVAGE;
if (fAggressive)
flags |= DB_AGGRESSIVE;
std::stringstream strDump;
Db db(dbenv.get(), 0);
int result = db.verify(strFile.c_str(), nullptr, &strDump, flags);
if (result == DB_VERIFY_BAD) {
LogPrintf("BerkeleyEnvironment::Salvage: Database salvage found errors, all data may not be recoverable.\n");
if (!fAggressive) {
LogPrintf("BerkeleyEnvironment::Salvage: Rerun with aggressive mode to ignore errors and continue.\n");
return false;
}
}
if (result != 0 && result != DB_VERIFY_BAD) {
LogPrintf("BerkeleyEnvironment::Salvage: Database salvage failed with result %d.\n", result);
return false;
}
// Format of bdb dump is ascii lines:
// header lines...
// HEADER=END
// hexadecimal key
// hexadecimal value
// ... repeated
// DATA=END
std::string strLine;
while (!strDump.eof() && strLine != HEADER_END)
getline(strDump, strLine); // Skip past header
std::string keyHex, valueHex;
while (!strDump.eof() && keyHex != DATA_END) {
getline(strDump, keyHex);
if (keyHex != DATA_END) {
if (strDump.eof())
break;
getline(strDump, valueHex);
if (valueHex == DATA_END) {
LogPrintf("BerkeleyEnvironment::Salvage: WARNING: Number of keys in data does not match number of values.\n");
break;
}
vResult.push_back(make_pair(ParseHex(keyHex), ParseHex(valueHex)));
}
}
if (keyHex != DATA_END) {
LogPrintf("BerkeleyEnvironment::Salvage: WARNING: Unexpected end of file while reading salvage output.\n");
return false;
}
return (result == 0);
}
void BerkeleyEnvironment::CheckpointLSN(const std::string& strFile)
{
dbenv->txn_checkpoint(0, 0, 0);
if (fMockDb)
return;
dbenv->lsn_reset(strFile.c_str(), 0);
}
BerkeleyBatch::BerkeleyBatch(BerkeleyDatabase& database, const char* pszMode, bool fFlushOnCloseIn) : pdb(nullptr), activeTxn(nullptr)
{
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
fFlushOnClose = fFlushOnCloseIn;
env = database.env;
if (database.IsDummy()) {
return;
}
const std::string &strFilename = database.strFile;
bool fCreate = strchr(pszMode, 'c') != nullptr;
unsigned int nFlags = DB_THREAD;
if (fCreate)
nFlags |= DB_CREATE;
{
LOCK(cs_db);
if (!env->Open(false /* retry */))
throw std::runtime_error("BerkeleyBatch: Failed to open database environment.");
pdb = env->mapDb[strFilename];
if (pdb == nullptr) {
int ret;
std::unique_ptr<Db> pdb_temp = MakeUnique<Db>(env->dbenv.get(), 0);
bool fMockDb = env->IsMock();
if (fMockDb) {
DbMpoolFile* mpf = pdb_temp->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0) {
throw std::runtime_error(strprintf("BerkeleyBatch: Failed to configure for no temp file backing for database %s", strFilename));
}
}
ret = pdb_temp->open(nullptr, // Txn pointer
fMockDb ? nullptr : strFilename.c_str(), // Filename
fMockDb ? strFilename.c_str() : "main", // Logical db name
DB_BTREE, // Database type
nFlags, // Flags
0);
if (ret != 0) {
throw std::runtime_error(strprintf("BerkeleyBatch: Error %d, can't open database %s", ret, strFilename));
}
// Call CheckUniqueFileid on the containing BDB environment to
// avoid BDB data consistency bugs that happen when different data
// files in the same environment have the same fileid.
//
// Also call CheckUniqueFileid on all the other g_dbenvs to prevent
// digibyte from opening the same data file through another
// environment when the file is referenced through equivalent but
// not obviously identical symlinked or hard linked or bind mounted
// paths. In the future a more relaxed check for equal inode and
// device ids could be done instead, which would allow opening
// different backup copies of a wallet at the same time. Maybe even
// more ideally, an exclusive lock for accessing the database could
// be implemented, so no equality checks are needed at all. (Newer
// versions of BDB have an set_lk_exclusive method for this
// purpose, but the older version we use does not.)
for (auto& env : g_dbenvs) {
CheckUniqueFileid(env.second, strFilename, *pdb_temp);
}
pdb = pdb_temp.release();
env->mapDb[strFilename] = pdb;
if (fCreate && !Exists(std::string("version"))) {
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(CLIENT_VERSION);
fReadOnly = fTmp;
}
}
++env->mapFileUseCount[strFilename];
strFile = strFilename;
}
}
void BerkeleyBatch::Flush()
{
if (activeTxn)
return;
// Flush database activity from memory pool to disk log
unsigned int nMinutes = 0;
if (fReadOnly)
nMinutes = 1;
env->dbenv->txn_checkpoint(nMinutes ? gArgs.GetArg("-dblogsize", DEFAULT_WALLET_DBLOGSIZE) * 1024 : 0, nMinutes, 0);
}
void BerkeleyDatabase::IncrementUpdateCounter()
{
++nUpdateCounter;
}
void BerkeleyBatch::Close()
{
if (!pdb)
return;
if (activeTxn)
activeTxn->abort();
activeTxn = nullptr;
pdb = nullptr;
if (fFlushOnClose)
Flush();
{
LOCK(cs_db);
--env->mapFileUseCount[strFile];
}
}
void BerkeleyEnvironment::CloseDb(const std::string& strFile)
{
{
LOCK(cs_db);
if (mapDb[strFile] != nullptr) {
// Close the database handle
Db* pdb = mapDb[strFile];
pdb->close(0);
delete pdb;
mapDb[strFile] = nullptr;
}
}
}
bool BerkeleyBatch::Rewrite(BerkeleyDatabase& database, const char* pszSkip)
{
if (database.IsDummy()) {
return true;
}
BerkeleyEnvironment *env = database.env;
const std::string& strFile = database.strFile;
while (true) {
{
LOCK(cs_db);
if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0) {
// Flush log data to the dat file
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(strFile);
bool fSuccess = true;
LogPrintf("BerkeleyBatch::Rewrite: Rewriting %s...\n", strFile);
std::string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {}
BerkeleyBatch db(database, "r");
std::unique_ptr<Db> pdbCopy = MakeUnique<Db>(env->dbenv.get(), 0);
int ret = pdbCopy->open(nullptr, // Txn pointer
strFileRes.c_str(), // Filename
"main", // Logical db name
DB_BTREE, // Database type
DB_CREATE, // Flags
0);
if (ret > 0) {
LogPrintf("BerkeleyBatch::Rewrite: Can't create database file %s\n", strFileRes);
fSuccess = false;
}
Dbc* pcursor = db.GetCursor();
if (pcursor)
while (fSuccess) {
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret1 = db.ReadAtCursor(pcursor, ssKey, ssValue);
if (ret1 == DB_NOTFOUND) {
pcursor->close();
break;
} else if (ret1 != 0) {
pcursor->close();
fSuccess = false;
break;
}
if (pszSkip &&
strncmp(ssKey.data(), pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
continue;
if (strncmp(ssKey.data(), "\x07version", 8) == 0) {
// Update version:
ssValue.clear();
ssValue << CLIENT_VERSION;
}
Dbt datKey(ssKey.data(), ssKey.size());
Dbt datValue(ssValue.data(), ssValue.size());
int ret2 = pdbCopy->put(nullptr, &datKey, &datValue, DB_NOOVERWRITE);
if (ret2 > 0)
fSuccess = false;
}
if (fSuccess) {
db.Close();
env->CloseDb(strFile);
if (pdbCopy->close(0))
fSuccess = false;
} else {
pdbCopy->close(0);
}
}
if (fSuccess) {
Db dbA(env->dbenv.get(), 0);
if (dbA.remove(strFile.c_str(), nullptr, 0))
fSuccess = false;
Db dbB(env->dbenv.get(), 0);
if (dbB.rename(strFileRes.c_str(), nullptr, strFile.c_str(), 0))
fSuccess = false;
}
if (!fSuccess)
LogPrintf("BerkeleyBatch::Rewrite: Failed to rewrite database file %s\n", strFileRes);
return fSuccess;
}
}
MilliSleep(100);
}
}
void BerkeleyEnvironment::Flush(bool fShutdown)
{
int64_t nStart = GetTimeMillis();
// Flush log data to the actual data file on all files that are not in use
LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started");
if (!fDbEnvInit)
return;
{
LOCK(cs_db);
std::map<std::string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end()) {
std::string strFile = (*mi).first;
int nRefCount = (*mi).second;
LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) {
// Move log data to the dat file
CloseDb(strFile);
LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s checkpoint\n", strFile);
dbenv->txn_checkpoint(0, 0, 0);
LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s detach\n", strFile);
if (!fMockDb)
dbenv->lsn_reset(strFile.c_str(), 0);
LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: %s closed\n", strFile);
mapFileUseCount.erase(mi++);
} else
mi++;
}
LogPrint(BCLog::DB, "BerkeleyEnvironment::Flush: Flush(%s)%s took %15dms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " database not started", GetTimeMillis() - nStart);
if (fShutdown) {
char** listp;
if (mapFileUseCount.empty()) {
dbenv->log_archive(&listp, DB_ARCH_REMOVE);
Close();
if (!fMockDb) {
fs::remove_all(fs::path(strPath) / "database");
}
g_dbenvs.erase(strPath);
}
}
}
}
bool BerkeleyBatch::PeriodicFlush(BerkeleyDatabase& database)
{
if (database.IsDummy()) {
return true;
}
bool ret = false;
BerkeleyEnvironment *env = database.env;
const std::string& strFile = database.strFile;
TRY_LOCK(cs_db, lockDb);
if (lockDb)
{
// Don't do this if any databases are in use
int nRefCount = 0;
std::map<std::string, int>::iterator mit = env->mapFileUseCount.begin();
while (mit != env->mapFileUseCount.end())
{
nRefCount += (*mit).second;
mit++;
}
if (nRefCount == 0)
{
boost::this_thread::interruption_point();
std::map<std::string, int>::iterator mi = env->mapFileUseCount.find(strFile);
if (mi != env->mapFileUseCount.end())
{
LogPrint(BCLog::DB, "Flushing %s\n", strFile);
int64_t nStart = GetTimeMillis();
// Flush wallet file so it's self contained
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(mi++);
LogPrint(BCLog::DB, "Flushed %s %dms\n", strFile, GetTimeMillis() - nStart);
ret = true;
}
}
}
return ret;
}
bool BerkeleyDatabase::Rewrite(const char* pszSkip)
{
return BerkeleyBatch::Rewrite(*this, pszSkip);
}
bool BerkeleyDatabase::Backup(const std::string& strDest)
{
if (IsDummy()) {
return false;
}
while (true)
{
{
LOCK(cs_db);
if (!env->mapFileUseCount.count(strFile) || env->mapFileUseCount[strFile] == 0)
{
// Flush log data to the dat file
env->CloseDb(strFile);
env->CheckpointLSN(strFile);
env->mapFileUseCount.erase(strFile);
// Copy wallet file
fs::path pathSrc = env->Directory() / strFile;
fs::path pathDest(strDest);
if (fs::is_directory(pathDest))
pathDest /= strFile;
try {
if (fs::equivalent(pathSrc, pathDest)) {
LogPrintf("cannot backup to wallet source file %s\n", pathDest.string());
return false;
}
fs::copy_file(pathSrc, pathDest, fs::copy_option::overwrite_if_exists);
LogPrintf("copied %s to %s\n", strFile, pathDest.string());
return true;
} catch (const fs::filesystem_error& e) {
LogPrintf("error copying %s to %s - %s\n", strFile, pathDest.string(), e.what());
return false;
}
}
}
MilliSleep(100);
}
}
void BerkeleyDatabase::Flush(bool shutdown)
{
if (!IsDummy()) {
env->Flush(shutdown);
if (shutdown) env = nullptr;
}
}
| digibyte/digibyte | src/wallet/db.cpp | C++ | mit | 29,494 |
<?php
/**
* @link http://zoopcommerce.github.io/shard
* @package Zoop
* @license MIT
*/
namespace Zoop\Shard\Serializer\Reference;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
/**
*
* @since 1.0
* @author Tim Roediger <superdweebie@gmail.com>
*/
class Eager implements ReferenceSerializerInterface, ServiceLocatorAwareInterface
{
use ServiceLocatorAwareTrait;
protected $serializer;
public function serialize($document)
{
if ($document) {
return $this->getSerializer()->toArray($document);
} else {
return null;
}
}
protected function getSerializer()
{
if (!isset($this->serializer)) {
$this->serializer = $this->serviceLocator->get('serializer');
}
return $this->serializer;
}
}
| zoopcommerce/shard | lib/Zoop/Shard/Serializer/Reference/Eager.php | PHP | mit | 884 |
package com.piggymetrics.user.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
@Entity
@NamedQuery(name = "User.findByName", query = "select name,address from User u where u.name=?1")
public class User implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
long id;
@Column(name = "name")
String name;
@Column(name = "address")
String address;
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
@Override
public String toString()
{
return this.id + "," + this.name + "," + this.address;
}
}
| yiping999/springcloud-pig | user-service/src/main/java/com/piggymetrics/user/domain/User.java | Java | mit | 1,115 |
package com.hkm.urbansdk.gson;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/**
* Created by hesk on 2/17/15.
*/
public class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Class<T> rawType = (Class<T>) type.getRawType();
if (!rawType.equals(String.class)) {
return null;
}
return (TypeAdapter<T>) new StringAdapter();
}
public class StringAdapter extends TypeAdapter<String> {
public String read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return "";
}
return reader.nextString();
}
public void write(JsonWriter writer, String value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.value(value);
}
}
}
| HKMOpen/UrbanDicSDK | urbanSDK/urbansdk/src/main/java/com/hkm/urbansdk/gson/NullStringToEmptyAdapterFactory.java | Java | mit | 1,266 |
package net.h31ix.travelpad.api;
import net.h31ix.travelpad.LangManager;
import org.bukkit.Location;
import org.bukkit.entity.Player;
/**
* <p>
* Defines a new Unnamed TravelPad on the map, this is only used before a pad is named by the player.
*/
public class UnnamedPad {
private Location location = null;
private Player owner = null;
public UnnamedPad(Location location, Player owner)
{
this.location = location;
this.owner = owner;
}
/**
* Get the location of the pad
*
* @return location Location of the obsidian center of the pad
*/
public Location getLocation()
{
return location;
}
/**
* Get the owner of the pad
*
* @return owner Player who owns the pad's name
*/
public Player getOwner()
{
return owner;
}
}
| gravitylow/TravelPad | src/main/java/net/h31ix/travelpad/api/UnnamedPad.java | Java | mit | 884 |