identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/yxlao/webrtc-cpp-sample/blob/master/webrtc/include/third_party/blink/renderer/core/css/style_traversal_root.h
Github Open Source
Open Source
MIT
null
webrtc-cpp-sample
yxlao
C
Code
428
891
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_TRAVERSAL_ROOT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_TRAVERSAL_ROOT_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/container_node.h" namespace blink { // Class used to represent a common ancestor for all dirty nodes in a DOM tree. // Subclasses implement the various types of dirtiness for style recalc, style // invalidation, and layout tree rebuild. The common ancestor is used as a // starting point for traversal to avoid unnecessary DOM tree traversal. // // The first dirty node is stored as a single root. When a second node is // added with a common child-dirty ancestor which is not dirty, we store that // as a common root. Any subsequent dirty nodes added whose closest child-dirty // ancestor is not itself dirty, or is the current root, will cause us to fall // back to use the document as the root node. In order to find a lowest common // ancestor we would have had to traverse up the ancestor chain to see if we are // below the current common root or not. // // Note that when the common ancestor candidate passed into Update is itself // dirty, we know that we are currently below the current root node and don't // have to modify it. class CORE_EXPORT StyleTraversalRoot { DISALLOW_NEW(); public: // Update the common ancestor root when dirty_node is marked dirty. The // common_ancestor is the closest ancestor of dirty_node which was already // marked as having dirty children. void Update(ContainerNode* common_ancestor, Node* dirty_node); // Clear the root if the removal caused the current root_node_ to be // disconnected. void ChildrenRemoved(ContainerNode& parent); Node* GetRootNode() const { return root_node_; } void Clear() { root_node_ = nullptr; root_type_ = RootType::kSingleRoot; } void Trace(Visitor* visitor) const { visitor->Trace(root_node_); } protected: virtual ~StyleTraversalRoot() = default; #if DCHECK_IS_ON() // Return the parent node for type of traversal for which the implementation // is a root. virtual ContainerNode* Parent(const Node&) const = 0; #endif // DCHECK_IS_ON() // Return true if the given node is dirty. virtual bool IsDirty(const Node&) const = 0; // Update the root node when removed. virtual void RootRemoved(ContainerNode& parent) = 0; bool IsSingleRoot() const { return root_type_ == RootType::kSingleRoot; } private: friend class StyleTraversalRootTestImpl; // The current root for dirty nodes. Member<Node> root_node_; // Is the current root a common ancestor or a single dirty node. enum class RootType { kSingleRoot, kCommonRoot }; RootType root_type_ = RootType::kSingleRoot; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_STYLE_TRAVERSAL_ROOT_H_
46,607
https://github.com/Delawen/camel-quarkus/blob/master/docs/modules/ROOT/partials/reference/components/aws2-lambda.adoc
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,021
camel-quarkus
Delawen
AsciiDoc
Code
47
201
// Do not edit directly! // This file was generated by camel-quarkus-maven-plugin:update-extension-doc-page :cq-artifact-id: camel-quarkus-aws2-lambda :cq-artifact-id-base: aws2-lambda :cq-native-supported: true :cq-status: Stable :cq-deprecated: false :cq-jvm-since: 1.1.0 :cq-native-since: 1.1.0 :cq-camel-part-name: aws2-lambda :cq-camel-part-title: AWS Lambda :cq-camel-part-description: Manage and invoke AWS Lambda functions using AWS SDK version 2.x. :cq-extension-page-title: AWS 2 Lambda
7,088
https://github.com/itsbino/fewpjs-stitching-together-the-three-pillars-new-online-web-sp-000/blob/master/node_modules/core-js/library/fn/array/slice.js
Github Open Source
Open Source
MIT, LicenseRef-scancode-public-domain, LicenseRef-scancode-unknown-license-reference
2,020
fewpjs-stitching-together-the-three-pillars-new-online-web-sp-000
itsbino
JavaScript
Code
4
41
require('core-js/library/modules/es6.array.slice'); module.exports = require('core-js/library/modules/_core').Array.slice;
11,135
https://github.com/FetchWeb/Log/blob/master/Data.go
Github Open Source
Open Source
MIT
2,019
Log
FetchWeb
Go
Code
21
33
package log // Data holds the data output in a log message. type Data struct { Level string Message string }
4,051
https://github.com/sriram18981/node-knex-poc/blob/master/db/knex.js
Github Open Source
Open Source
MIT
null
node-knex-poc
sriram18981
JavaScript
Code
106
375
'use strict'; const knex = require('./dbInit'); knex.schema .createTable('users', function(table) { table.increments('id'); table.string('user_name'); }) // ...and another .createTable('accounts', function(table) { table.increments('id'); table.string('account_name'); table .integer('user_id') .unsigned() .references('users.id'); }) // Then query the table... .then(function() { return knex('users').insert({ user_name: 'Tim' }); }) // ...and using the insert id, insert into the other table. .then(function(rows) { return knex('accounts').insert({ account_name: 'knex', user_id: rows[0] }); }) // Query both of the rows. .then(function() { return knex('users') .join('accounts', 'users.id', 'accounts.user_id') .select('users.user_name as user', 'accounts.account_name as account'); }) // .map over the results .map(function(row) { console.log(row); }) // Finally, add a .catch handler for the promise chain .catch(function(e) { console.error(e); }); module.exports = {knex};
9,036
https://github.com/GRFreire/nlw-01/blob/master/backend/src/controllers/ItemsController.ts
Github Open Source
Open Source
MIT
2,020
nlw-01
GRFreire
TypeScript
Code
76
221
import { Request, Response } from 'express'; import knex from '../database/connection'; interface IItemsController { index: any } function createItemsController(): IItemsController { async function index(req: Request, res: Response) { try { const items = await knex('items').select('*'); const HOST = `${req.protocol}://${req.get('host')}`; const serializedItems = items.map((item) => ({ ...item, image_url: `${HOST}/uploads/${item.image}`, })); return res.send({ items: serializedItems }); } catch (error) { return res.status(400).send({ error: 'Unnable to list items' }); } } return { index, }; } export default createItemsController;
10,840
https://github.com/Coderushnepal/PoojaShrestha/blob/master/beer-bank/src/actions/beers.js
Github Open Source
Open Source
MIT
null
PoojaShrestha
Coderushnepal
JavaScript
Code
117
400
import * as beerService from "../services/beer"; export const RESET_BEERS = "RESET_BEERS"; export const FETCH_BEERS = "FETCH_BEERS"; export const FETCH_BEERS_PENDING = "FETCH_BEERS_PENDING"; export const FETCH_BEERS_REJECTED = "FETCH_BEERS_REJECTED"; export const FETCH_BEERS_FULFILLED = "FETCH_BEERS_FULFILLED"; // pending , rejected , fulfilled export default function fetchBeers(params) { const { pageNumber: page, searchQuery: beer_name } = params; return async function (dispatch) { dispatch(fetchBeersPending()); try { const data = await beerService.fetchBeers({ page, beer_name }); dispatch(fetchBeersFulfilled(data)); } catch (err) { dispatch(fetchBeersRejected(err)); } }; } function fetchBeersFulfilled(beers) { return { type: FETCH_BEERS_FULFILLED, payload: beers, }; } function fetchBeersRejected(err) { return { type: FETCH_BEERS_REJECTED, payload: err, }; } function fetchBeersPending() { return { type: FETCH_BEERS_PENDING, }; } export function resetBeers() { return { type: RESET_BEERS, }; }
35,061
https://github.com/szymonk1101/Nexia/blob/master/application/models/Notifications_model.php
Github Open Source
Open Source
MIT
null
Nexia
szymonk1101
PHP
Code
187
696
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Notifications_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function addNotification($type, $content, $title = null, $data = null, $recipient = null, $level = NOTIFICATION_LVL_INFO, $created = false, $displayed = null) { if(!$created) $created = date('Y-m-d H:i:s'); return $this->db->insert('notifications', array( 'type' => $type, 'recipient' => $recipient, 'created' => $created, 'title' => $title, 'content' => $content, 'data' => $data, 'level' => $level, 'displayed' => $displayed ), TRUE); } public function getAllUserNotifications($userid, $limit = 50) { $notifications = $this->db->query("SELECT * FROM notifications WHERE `type` = '".NOTIFICATION_ALL."' OR (`type` = '".NOTIFICATION_USER."' AND recipient = '".$userid."') OR `type` = '".NOTIFICATION_ONLINE."' ORDER BY id DESC LIMIT ".$limit)->result(); foreach($notifications as $notify) { $notify->title = ($notify->title) ? lang('Notify_'.$notify->title) : NULL; $notify->content_uid = $notify->content; $notify->content = vsprintf(lang('Notify_'.$notify->content_uid), json_decode($notify->data, true)); $notify->data = json_decode($notify->data, true); $notify->displayed = json_decode($notify->displayed); } return $notifications; } public function addUserDisplayer($notify_id, $userid) { $notify = $this->db->select('displayed')->where('id', $notify_id, TRUE)->get('notifications')->row(); if($notify) { $displayed = json_decode($notify->displayed); if(is_array($displayed)) { if(!in_array($userid, $displayed)) { array_push($displayed, $userid); } } else { $displayed = array($userid); } return $this->db->update('notifications', array('displayed' => json_encode($displayed, JSON_NUMERIC_CHECK)), 'id = '.$notify_id); } return false; } }
19,860
https://github.com/kichuss/practica_baseDedatos/blob/master/TAREAA/ver.php
Github Open Source
Open Source
Apache-2.0
null
practica_baseDedatos
kichuss
PHP
Code
63
321
<?php require("conexion.php"); session_start($link); $id=$_GET["id"]; $query= "SELECT * FROM autores WHERE id='".$id."'"; $resultado=mysqli_query($link,$query) or die ("Error: ". mysqli_error()); if (mysqli_num_rows($resultado) > 0){ while ($row=mysqli_fetch_array($resultado)) { ?> <html> <body> <font size="5">autores</font></br> <label><?php echo "id: ".$row['id']; ?></label></br> <label><?php echo "autor: ".$row['autor']; ?></label></br> <label><?php echo "titulos: ".$row['titulos'] ?></label></br> <label><?php echo "fecha: ".$row['fecha'] ?></label></br> <label><?php echo "contenido: ".$row['contenido']; ?></label></br> <a href="indice.php">Indice</a> </body> </html> <?php } } mysqli_close($link); ?>
11,940
https://github.com/lumixraku/OpenCVRN/blob/master/src/webpage/phaser/src/game/facePosCheck.ts
Github Open Source
Open Source
MIT
2,020
OpenCVRN
lumixraku
TypeScript
Code
715
2,444
import PhaserImage = Phaser.GameObjects.Image; import Sprite = Phaser.GameObjects.Sprite; import Circle = Phaser.Geom.Circle; import Point = Phaser.Geom.Point; import Vector2 = Phaser.Math.Vector2; import Rectagle = Phaser.Geom.Rectangle; import Graphics = Phaser.GameObjects.Graphics; import PhaserText = Phaser.GameObjects.Text; import { Bounds } from "@root/faceData"; import { Scene, Tilemaps } from "phaser"; import { MSG_TYPE_FACE_TARGET_POS } from "@root/constants"; const stageWidth = document.body.clientWidth; const stageHeight = document.body.clientWidth / 9 * 16; interface FaceInCircle { pass: boolean bounds: Bounds } export { FaceInCircle } export default class CamFaceCheck { public facePoint: Point[] public faceBounds: Bounds public faceRect: Graphics public camPreviewArea: Rectagle public firstSetCamPreviewArea: Rectagle public previewRect: Graphics public facePosText: PhaserText // 第一次被认为 OK 的脸部位置 // 之后人脸应该试图保持在这个位置 public targetFaceBounds: Bounds public faceCenterPos: Vector2 public scene: Scene constructor(scene?: Scene) { this.scene = scene this.faceRect = scene.add.graphics() this.previewRect = scene.add.graphics() this.facePosText = scene.add.text(stageWidth - 100, 250, '', { fontFamily: '"Roboto Condensed"' }); } refreshFacePosition(faceBounds: Bounds, facePoints: Point[]) { this.faceBounds = faceBounds let centerX = faceBounds.origin.x + faceBounds.size.width/2 let centerY = faceBounds.origin.y + faceBounds.size.height/2 this.faceCenterPos = new Vector2(centerX, centerY) } // check if face is in the center of preview // private checkFacePosition(faceBounds: Bounds) { let rs: FaceInCircle = { pass: false, bounds: null } if (!this.camPreviewArea) { return rs } if (faceBounds) { let minFaceX = faceBounds.origin.x let maxFaceX = faceBounds.origin.x + faceBounds.size.width let minFaceY = faceBounds.origin.y let maxFaceY = faceBounds.origin.y + faceBounds.size.height this.drawFaceBounds(faceBounds) // this.drawPreviewBounds(this.camPreviewArea) let minPreviewX = this.camPreviewArea.x let maxPreviewX = this.camPreviewArea.x + this.camPreviewArea.width let minPreviewY = this.camPreviewArea.y let maxPreviewY = this.camPreviewArea.y + this.camPreviewArea.height let paddingLeft = minFaceX - minPreviewX let paddingRight = maxPreviewX - maxFaceX let paddingTop = maxFaceX - minPreviewX let paddingBottom = maxPreviewY - maxFaceY // this.facePosText.text = `${paddingLeft.toFixed(2)} --- ${paddingRight.toFixed(2)}` if (paddingLeft / paddingRight > 2) { this.facePosText.text = 'to right slightly' } else if (paddingRight / paddingLeft > 2) { this.facePosText.text = 'to left slightly' } else { this.facePosText.text = 'Hold your phone!' return { pass: true, bounds: faceBounds } } } return rs } drawPreviewBounds(previewCamArea: Rectagle) { if (!previewCamArea) { return } this.previewRect.clear() this.previewRect.lineStyle(5, 0x00FFFF, 1.0); this.previewRect.beginPath(); let minPreviewX = previewCamArea.x let maxPreviewX = previewCamArea.x + previewCamArea.width let minPreviewY = previewCamArea.y let maxPreviewY = previewCamArea.y + previewCamArea.height let points = [ new Point(minPreviewX, minPreviewY), new Point(maxPreviewX, minPreviewY), new Point(maxPreviewX, maxPreviewY), new Point(minPreviewX, maxPreviewY) ] let idx = 0 for (let p of points) { if (idx == 0) { this.previewRect.moveTo(p.x, p.y); } else { this.previewRect.lineTo(p.x, p.y); } idx++ } let centerX = previewCamArea.x + previewCamArea.width/2 let centerY = previewCamArea.y + previewCamArea.height/2 this.previewRect.fillStyle(0x00FFFF) this.previewRect.fillRect(centerX,centerY,10,10); this.previewRect.closePath(); this.previewRect.strokePath(); } drawFaceBounds(faceBounds: Bounds) { this.faceRect.clear() this.faceRect.lineStyle(5, 0xFF00FF, 1.0); this.faceRect.beginPath(); let minFaceX = faceBounds.origin.x let maxFaceX = faceBounds.origin.x + faceBounds.size.width let minFaceY = faceBounds.origin.y let maxFaceY = faceBounds.origin.y + faceBounds.size.height let points = [ new Point(minFaceX, minFaceY), new Point(maxFaceX, minFaceY), new Point(maxFaceX, maxFaceY), new Point(minFaceX, maxFaceY) ] let idx = 0 for (let p of points) { if (idx == 0) { this.faceRect.moveTo(p.x, p.y); } else { this.faceRect.lineTo(p.x, p.y); } idx++ } let centerX = faceBounds.origin.x + faceBounds.size.width/2 let centerY = faceBounds.origin.y + faceBounds.size.height/2 this.faceRect.fillStyle(0xFF00FF) this.faceRect.fillRect(centerX,centerY,10,10); this.faceRect.closePath(); this.faceRect.strokePath(); } setCameraArea(camPreviewArea: Rectagle) { this.camPreviewArea = camPreviewArea if (!this.firstSetCamPreviewArea) { this.firstSetCamPreviewArea = new Rectagle(0,0,0,0) this.firstSetCamPreviewArea.x = this.camPreviewArea.x this.firstSetCamPreviewArea.y = this.camPreviewArea.y this.firstSetCamPreviewArea.width = this.camPreviewArea.width this.firstSetCamPreviewArea.height = this.camPreviewArea.height } } // setTargetFaceBounds(facebds: Bounds) { // if (this.targetFaceBounds == null) { // this.targetFaceBounds = facebds // let centerX = facebds.origin.x + facebds.size.width // let centerY = facebds.origin.y + facebds.size.height // let distanceX = this.camPreviewArea.x - centerX // let distanceY = this.camPreviewArea.y - centerY // this.faceCenterPos = new Vector2(centerX, centerY) // // 同时告知 RN? //脸的位置确定了 // if (window["ReactNativeWebView"]) { // let msg = { // messageType: MSG_TYPE_FACE_TARGET_POS, // actualData: { // bounds: facebds, // }, // time: +new Date // } // window["ReactNativeWebView"].postMessage(JSON.stringify(msg)); // } // } // } getTargetFaceBounds(): Bounds { return this.faceBounds } updatePreviewPosByTarget(){ // let faceCenterPos = this.faceCenterPos // let firstCamPreviewArea = this.firstSetCamPreviewArea // if (!firstCamPreviewArea){ // return // } // if (!faceCenterPos) { // return // } // let originCamArea = this.firstSetCamPreviewArea // let faceBounds = this.faceBounds // let centerX = faceBounds.origin.x + faceBounds.size.width // let centerY = faceBounds.origin.y + faceBounds.size.height // let distanceX = this.camPreviewArea.x - centerX // let distanceY = this.camPreviewArea.y - centerY // let offset = new Point( // faceCenterPos.x - centerX, // faceCenterPos.y - centerY // ) // this.camPreviewArea.x = originCamArea.x + offset.x // this.camPreviewArea.y = originCamArea.y + offset.y // this.drawPreviewBounds(this.camPreviewArea) } }
41,356
https://github.com/gugarosa/opytimizer/blob/master/opytimizer/optimizers/swarm/sso.py
Github Open Source
Open Source
Apache-2.0
2,023
opytimizer
gugarosa
Python
Code
460
1,405
"""Simplified Swarm Optimization. """ import copy import time from typing import Any, Dict, Optional import numpy as np import opytimizer.math.random as r import opytimizer.utils.exception as e from opytimizer.core import Optimizer from opytimizer.core.function import Function from opytimizer.core.space import Space from opytimizer.utils import logging logger = logging.get_logger(__name__) class SSO(Optimizer): """A SSO class, inherited from Optimizer. This is the designed class to define SSO-related variables and methods. References: C. Bae et al. A new simplified swarm optimization (SSO) using exchange local search scheme. International Journal of Innovative Computing, Information and Control (2012). """ def __init__(self, params: Optional[Dict[str, Any]] = None) -> None: """Initialization method. Args: params: Contains key-value parameters to the meta-heuristics. """ logger.info("Overriding class: Optimizer -> SSO.") super(SSO, self).__init__() self.C_w = 0.1 self.C_p = 0.4 self.C_g = 0.9 self.build(params) logger.info("Class overrided.") @property def C_w(self) -> float: """Weighing constant.""" return self._C_w @C_w.setter def C_w(self, C_w: float) -> None: if not isinstance(C_w, (float, int)): raise e.TypeError("`C_w` should be a float or integer") if C_w < 0 or C_w > 1: raise e.ValueError("`C_w` should be between 0 and 1") self._C_w = C_w @property def C_p(self) -> float: """Local constant.""" return self._C_p @C_p.setter def C_p(self, C_p: float) -> None: if not isinstance(C_p, (float, int)): raise e.TypeError("`C_p` should be a float or integer") if C_p < self.C_w: raise e.ValueError("`C_p` should be equal or greater than `C_w`") self._C_p = C_p @property def C_g(self) -> float: """Global constant.""" return self._C_g @C_g.setter def C_g(self, C_g: float) -> None: if not isinstance(C_g, (float, int)): raise e.TypeError("`C_g` should be a float or integer") if C_g < self.C_p: raise e.ValueError("`C_g` should be equal or greater than `C_p`") self._C_g = C_g @property def local_position(self) -> np.ndarray: """Array of local positions.""" return self._local_position @local_position.setter def local_position(self, local_position: np.ndarray) -> None: if not isinstance(local_position, np.ndarray): raise e.TypeError("`local_position` should be a numpy array") self._local_position = local_position def compile(self, space: Space) -> None: """Compiles additional information that is used by this optimizer. Args: space: A Space object containing meta-information. """ self.local_position = np.zeros( (space.n_agents, space.n_variables, space.n_dimensions) ) def evaluate(self, space: Space, function: Function) -> None: """Evaluates the search space according to the objective function. Args: space: A Space object that will be evaluated. function: A Function object that will be used as the objective function. """ for i, agent in enumerate(space.agents): fit = function(agent.position) if fit < agent.fit: agent.fit = fit self.local_position[i] = copy.deepcopy(agent.position) if agent.fit < space.best_agent.fit: space.best_agent.position = copy.deepcopy(self.local_position[i]) space.best_agent.fit = copy.deepcopy(agent.fit) space.best_agent.ts = int(time.time()) def update(self, space: Space) -> None: """Wraps Simplified Swarm Optimization over all agents and variables. Args: space: Space containing agents and update-related information. """ for i, agent in enumerate(space.agents): for j in range(agent.n_variables): r1 = r.generate_uniform_random_number() if r1 < self.C_w: pass elif r1 < self.C_p: agent.position[j] = self.local_position[i][j] elif r1 < self.C_g: agent.position[j] = space.best_agent.position[j] else: agent.position[j] = r.generate_uniform_random_number( size=agent.n_dimensions )
224
https://github.com/dannypilkington/shopify-bootstrap-theme/blob/master/scss/_footer.scss
Github Open Source
Open Source
MIT
2,022
shopify-bootstrap-theme
dannypilkington
SCSS
Code
77
280
/* © 2021 KondaSoft https://www.kondasoft.com */ // Footer blocks #footer-blocks { .rte, .footer-menu, .social-menu { font-size: .95rem; } &.text-body { .nav-link { color: var(--color-body-text); &:hover { color: var(--color-body-text-lighten-10); } } } &.text-white { a:not(.btn) { color: white; transition: all .2s ease-out; &:hover { color: rgba(white, .75); } } } } // Footer #footer { font-style: italic; font-size: .90rem; &.text-white { a:not(.btn) { color: white; transition: all .2s ease-out; &:hover { color: rgba(white, .75); } } } }
44,390
https://github.com/eprislac/guard-yard/blob/master/vendor/jruby/1.9/gems/rubocop-0.25.0/lib/rubocop/cop/style/nested_ternary_operator.rb
Github Open Source
Open Source
MIT
2,015
guard-yard
eprislac
Ruby
Code
66
190
# encoding: utf-8 module RuboCop module Cop module Style # This cop checks for nested ternary op expressions. class NestedTernaryOperator < Cop MSG = 'Ternary operators must not be nested. Prefer `if`/`else` ' \ 'constructs instead.' def on_if(node) loc = node.loc # discard non-ternary ops return unless loc.respond_to?(:question) node.children.each do |child| on_node(:if, child) do |c| add_offense(c, :expression) if c.loc.respond_to?(:question) end end end end end end end
40,903
https://github.com/otengkwame/Ignite/blob/master/cli/templates/interfaces/base.php.twig
Github Open Source
Open Source
MIT
2,017
Ignite
otengkwame
Twig
Code
100
220
<?php namespace Ignite\App\Interfaces; if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * This is an Interface for {{ NAME }} */ Interface {{ NAME }}Interface { {% if ACTIONS is empty %} /** * Display a listing of the resource. * GET /{{ COLLECTION }} */ public function startInterface(); {% else %} {% for action in ACTIONS %} /** * {{action|upper}}|DESCRIPTION| * @param [type] $[name] [<description>] * @return [type] [<description>] */ public function {{action}}() { } {% endfor %}{% endif %} } /* End of file {{ FILENAME }} */ /* Location: {{ PATH }}/{{ FILENAME }} */
37,715
https://github.com/ardansisman/CQRS-Wrokshop/blob/master/CQRS-Wrokshop.Domain/Entities/Product.cs
Github Open Source
Open Source
MIT
2,021
CQRS-Wrokshop
ardansisman
C#
Code
50
128
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace CQRS_Wrokshop.Domain.Entities { [Table("products", Schema = "public")] public class Product { public long Id { get; set; } public string Name { get; set; } public decimal UnitPrice { get; set; } public virtual ICollection<OrderDetail> OrderDetails { get; set; } } }
38,312
https://github.com/YWADMIN/UnitTest/blob/master/src/test/java/adrninistrator/test/common/TestReplaceUtil.java
Github Open Source
Open Source
Apache-2.0
2,020
UnitTest
YWADMIN
Java
Code
169
936
package adrninistrator.test.common; import org.mockito.MockingDetails; import org.mockito.Mockito; import org.powermock.reflect.Whitebox; import static org.junit.Assert.fail; public class TestReplaceUtil { /** * 将对象object中的指定类型clazz成员变量替换为Mock对象并返回,简化操作,避免将现有Mock对象的Stub操作丢弃。 * * @param object 需要替换成员变量的对象 * @param clazz 需要被替换的成员变量的类型 * @return 需要被替换的成员变量对应的Mock对象 */ public static <T> T replaceMockMember(Object object, Class<T> clazz) { // 获取对象中的成员变量 T member = Whitebox.getInternalState(object, clazz); if (member == null) { fail("获取成员变量为空"); } MockingDetails mockingDetails = Mockito.mockingDetails(member); // 若成员变量为Mock对象,则直接返回 if (mockingDetails.isMock()) { return member; } // 若成员变量为Spy对象,则抛出异常 if (mockingDetails.isSpy()) { fail("成员变量为Spy对象"); } // 成员变量是原始对象 // 生成Mock对象 T mockMember = Mockito.mock(clazz); // 将成员变量替换为Mock对象 Whitebox.setInternalState(object, mockMember); return mockMember; } /** * 将对象object中的指定类型clazz成员变量替换为Spy对象并返回,简化操作,避免将现有Spy对象的Stub操作丢弃。 * * @param object 需要替换成员变量的对象 * @param clazz 需要被替换的成员变量的类型 * @return 需要被替换的成员变量对应的Spy对象 */ public static <T> T replaceSpyMember(Object object, Class<T> clazz) { // 获取对象中的成员变量 T member = Whitebox.getInternalState(object, clazz); if (member == null) { fail("获取成员变量为空"); } MockingDetails mockingDetails = Mockito.mockingDetails(member); // 若成员变量为Spy对象,则直接返回 if (mockingDetails.isSpy()) { return member; } // 若成员变量为Mock对象,则抛出异常 if (mockingDetails.isMock()) { fail("成员变量为Mock对象"); } // 成员变量是原始对象 // 生成Spy对象 T mockMember = Mockito.spy(member); // 将成员变量替换为Spy对象 Whitebox.setInternalState(object, mockMember); return mockMember; } private TestReplaceUtil() { throw new IllegalStateException("illegal"); } }
50,818
https://github.com/KDE/kdepim-runtime/blob/master/po/pt_BR/accountwizard_pop3.po
Github Open Source
Open Source
BSD-3-Clause
2,023
kdepim-runtime
KDE
Gettext Catalog
Code
137
520
# Translation of accountwizard_pop3.po to Brazilian Portuguese # Copyright (C) 2010-2013 This_file_is_part_of_KDE # This file is distributed under the same license as the PACKAGE package. # # André Marcelo Alvarenga <alvarenga@kde.org>, 2010, 2013. msgid "" msgstr "" "Project-Id-Version: accountwizard_pop3\n" "Report-Msgid-Bugs-To: https://bugs.kde.org\n" "POT-Creation-Date: 2020-08-15 02:21+0200\n" "PO-Revision-Date: 2013-11-14 01:40-0200\n" "Last-Translator: André Marcelo Alvarenga <alvarenga@kde.org>\n" "Language-Team: Brazilian Portuguese <kde-i18n-pt_br@kde.org>\n" "Language: pt_BR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Lokalize 1.5\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: pop3wizard.es:10 msgid "Personal Settings" msgstr "Configurações pessoais" #. i18n: ectx: property (text), widget (QLabel, label) #: pop3wizard.ui:21 #, kde-format msgid "Username:" msgstr "Nome de usuário:" #. i18n: ectx: property (text), widget (QLabel, label_2) #: pop3wizard.ui:28 #, kde-format msgid "Incoming server:" msgstr "Servidor de recepção:" #. i18n: ectx: property (text), widget (QLabel, label_4) #: pop3wizard.ui:38 #, kde-format msgid "Outgoing server:" msgstr "Servidor de envio:"
27,677
https://github.com/navikt/familie-ba-statistikk/blob/master/src/main/kotlin/no/nav/familie/ba/statistikk/config/FlywayConfiguration.kt
Github Open Source
Open Source
MIT
null
familie-ba-statistikk
navikt
Kotlin
Code
40
217
package no.nav.familie.ba.statistikk.config import org.flywaydb.core.api.configuration.FluentConfiguration import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.boot.autoconfigure.flyway.FlywayConfigurationCustomizer import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile @Configuration @ConditionalOnProperty("spring.flyway.enabled") class FlywayConfiguration { @Bean fun flywayConfig(@Value("\${spring.cloud.vault.database.role}") role: String): FlywayConfigurationCustomizer { return FlywayConfigurationCustomizer { c: FluentConfiguration -> c.initSql("SET ROLE \"$role\"") } } }
18,359
https://github.com/sjp/Schematic/blob/master/src/SJP.Schematic.Reporting/Html/ViewModels/Mappers/SynonymTargets.cs
Github Open Source
Open Source
MIT
2,022
Schematic
sjp
C#
Code
96
310
using System; using System.Collections.Generic; using SJP.Schematic.Core; namespace SJP.Schematic.Reporting.Html.ViewModels.Mappers { internal sealed class SynonymTargets { public SynonymTargets( IEnumerable<Identifier> tableNames, IEnumerable<Identifier> viewNames, IEnumerable<Identifier> sequenceNames, IEnumerable<Identifier> synonymNames, IEnumerable<Identifier> routineNames ) { TableNames = tableNames ?? throw new ArgumentNullException(nameof(tableNames)); ViewNames = viewNames ?? throw new ArgumentNullException(nameof(viewNames)); SequenceNames = sequenceNames ?? throw new ArgumentNullException(nameof(sequenceNames)); SynonymNames = synonymNames ?? throw new ArgumentNullException(nameof(synonymNames)); RoutineNames = routineNames ?? throw new ArgumentNullException(nameof(routineNames)); } public IEnumerable<Identifier> TableNames { get; } public IEnumerable<Identifier> ViewNames { get; } public IEnumerable<Identifier> SequenceNames { get; } public IEnumerable<Identifier> SynonymNames { get; } public IEnumerable<Identifier> RoutineNames { get; } } }
3,142
https://github.com/hanreev/types-ol/blob/master/@types/ol/TileRange.d.ts
Github Open Source
Open Source
MIT
2,023
types-ol
hanreev
TypeScript
Code
67
215
import { Size } from './size'; import { TileCoord } from './tilecoord'; export default class TileRange { constructor(minX: number, maxX: number, minY: number, maxY: number); contains(tileCoord: TileCoord): boolean; containsTileRange(tileRange: TileRange): boolean; containsXY(x: number, y: number): boolean; equals(tileRange: TileRange): boolean; extend(tileRange: TileRange): void; getHeight(): number; getSize(): Size; getWidth(): number; intersects(tileRange: TileRange): boolean; } export function createOrUpdate( minX: number, maxX: number, minY: number, maxY: number, tileRange?: TileRange, ): TileRange;
30,168
https://github.com/naveen5229/refPri/blob/master/src/app/modals/mobile-no/mobile-no.component.ts
Github Open Source
Open Source
MIT
null
refPri
naveen5229
TypeScript
Code
75
278
import { Component, OnInit } from '@angular/core'; import { CommonService } from '../../Service/common/common.service'; import { ApiService } from '../../Service/Api/api.service'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'ngx-mobile-no', templateUrl: './mobile-no.component.html', styleUrls: ['./mobile-no.component.scss'] }) export class MobileNoComponent implements OnInit { mobile = null; constructor( public common: CommonService, private activeModal: NgbActiveModal ) { //this.common.handleModalSize('class', 'modal-lg', '650'); this.common.handleModalSize('class', 'modal-lg', '650','px', 1); console.log("param", this.common.params); this.mobile = this.common.params; console.log("mobile 123", this.mobile); } ngOnInit() { } dismiss() { this.activeModal.close(); } }
31,750
https://github.com/OneSecure/onedrive-sdk-ios/blob/master/OneDriveSDK/Pods/ADAL/ADALiOS/ADALiOS/ADTokenCacheStoreKey.h
Github Open Source
Open Source
MIT, Apache-2.0
2,020
onedrive-sdk-ios
OneSecure
Objective-C
Code
257
477
// Copyright © Microsoft Open Technologies, Inc. // // All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION // ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A // PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache License, Version 2.0 for the specific language // governing permissions and limitations under the License. #import <Foundation/Foundation.h> @class ADAuthenticationError; /*! Defines the cache store key. The object is immutable and new one should be created each time a new key is required. Keys can be created or extracted from existing ADTokenCacheStoreItem objects. */ @interface ADTokenCacheStoreKey : NSObject<NSCopying> { NSUInteger hash; } /*! Creates a key @param authority Required. The authentication authority used. @param resource Optional. The resource used for the token. Multi-resource refresh token items can be extracted by specifying nil. @ param scope: Optional, can be nil. The OAuth2 scope. */ +(ADTokenCacheStoreKey*) keyWithAuthority: (NSString*) authority resource: (NSString*) resource clientId: (NSString*)clientId error: (ADAuthenticationError* __autoreleasing*) error; /*! The authority that issues access tokens */ @property (readonly) NSString* authority; /*! The resouce to which the access tokens are issued. May be nil in case of multi-resource refresh token. */ @property (readonly) NSString* resource; /*! The application client identifier */ @property (readonly) NSString* clientId; @end
28,986
https://github.com/quickskape/mapping/blob/master/convert-routing-file.sh
Github Open Source
Open Source
MIT
null
mapping
quickskape
Shell
Code
26
136
docker run -t -v "${PWD}/routing-files:/data" osrm/osrm-backend osrm-extract -p /opt/car.lua /data/england-latest.osm.pbf docker run -t -v "${PWD}/routing-files:/data" osrm/osrm-backend osrm-partition /data/england-latest.osrm docker run -t -v "${PWD}/routing-files:/data" osrm/osrm-backend osrm-customize /data/england-latest.osrm
25,532
https://github.com/softwarecapital/chr1shr.voro/blob/master/examples/no_release/import_nguyen.cc
Github Open Source
Open Source
BSD-3-Clause-LBNL
2,022
chr1shr.voro
softwarecapital
C++
Code
145
467
// File import example code // // Author : Chris H. Rycroft (Harvard University / LBL) // Email : chr@alum.mit.edu // Date : August 30th 2011 #include "voro++.hh" using namespace voro; #include <vector> using namespace std; // Set up constants for the container geometry const double x_min=-5,x_max=5; const double y_min=-5,y_max=5; const double z_min=-5,z_max=5; // Set up the number of blocks that the container is divided into const int n_x=6,n_y=6,n_z=6; int main() { // Construct container container con(-5,5,-5,5,0,10,6,6,6,false,false,false,8); // Import particles con.import("../basic/pack_ten_cube"); // Loop over all the particles and compute the Voronoi cell for each unsigned int i; int id; double x,y,z; vector<double> vd; voronoicell c; c_loop_all cl(con); if(cl.start()) do if(con.compute_cell(c,cl)) { // Get particle position and ID cl.pos(x,y,z);id=cl.pid(); // Get face areas c.face_areas(vd); // Output information (additional diagnostics could be done // here) printf("ID %d (%.3f,%.3f,%.3f) :",id,x,y,z); for(i=0;i<vd.size();i++) printf(" %.3f",vd[i]); puts(""); } while (cl.inc()); }
30,376
https://github.com/yoship1639/MikuMikuWorld/blob/master/MikuMikuWorldLib/MatrixHelper.cs
Github Open Source
Open Source
BSD-3-Clause
2,021
MikuMikuWorld
yoship1639
C#
Code
938
2,614
// // Miku Miku World License // // Copyright (c) 2017 Miku Miku World. // // 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. // using OpenTK; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MikuMikuWorld { /// <summary> /// 行列に関する処理のヘルパークラス /// </summary> public static class MatrixHelper { /// <summary> /// ZXY回転行列を作成する /// </summary> /// <param name="rot"></param> /// <returns></returns> public static Matrix4 CreateRotate(Vector3 rot) { return CreateRotate(rot.X, rot.Y, rot.Z); } /// <summary> /// ZXY回転行列を作成する /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <returns></returns> public static Matrix4 CreateRotate(float x, float y, float z) { var cosx = (float)Math.Cos(x); var cosy = (float)Math.Cos(-y); var cosz = (float)Math.Cos(z); var sinx = (float)Math.Sin(x); var siny = (float)Math.Sin(-y); var sinz = (float)Math.Sin(z); return new Matrix4( cosz * cosy + sinx * siny * sinz, sinz * cosx, cosz * -siny + sinz * sinx * cosy, 0.0f, -sinz * cosy + cosz * sinx * siny, cosz * cosx, -sinz * -siny + cosz * sinx * cosy, 0.0f, cosx * siny, -sinx, cosx * cosy, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ); /* return new Matrix4( cosy * cosz - sinx * siny * sinz, -cosx * sinz, siny * cosz + sinx * cosy * sinz, 0.0f, cosy * sinz + sinx * siny * cosz, cosx * cosz, sinz * siny - sinz * cosy * cosz, 0.0f, -cosx * siny, sinx, cosx * cosy, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f );*/ } public static Matrix4 CreateTransform(ref Vector3 pos, ref Quaternion rot) { Matrix4 m = Matrix4.Identity; if (rot != Quaternion.Identity) m = Matrix4.CreateFromQuaternion(rot); m.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); return m; } public static void CreateTransform(ref Vector3 pos, ref Quaternion rot, out Matrix4 m) { if (rot != Quaternion.Identity) m = Matrix4.CreateFromQuaternion(rot); else m = Matrix4.Identity; m.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); } public static Matrix4 CreateTransform(ref Vector3 pos, ref Quaternion rot, ref Vector3 scale) { Matrix4 m = Matrix4.Identity; if (rot != Quaternion.Identity) m = Matrix4.CreateFromQuaternion(rot); m.Row0 *= scale.X; m.Row1 *= scale.Y; m.Row2 *= scale.Z; m.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); return m; } public static void CreateTransform(ref Vector3 pos, ref Quaternion rot, ref Vector3 scale, out Matrix4 m) { m = Matrix4.Identity; if (rot != Quaternion.Identity) m = Matrix4.CreateFromQuaternion(rot); m.Row0 *= scale.X; m.Row1 *= scale.Y; m.Row2 *= scale.Z; m.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); } /// <summary> /// 姿勢行列を作成する /// </summary> public static Matrix4 CreateTransform(ref Vector3 pos, ref Vector3 rot, ref Vector3 scale) { Matrix4 m = Matrix4.Identity; if (rot != Vector3.Zero) m = CreateRotate(rot.X, rot.Y, rot.Z); m.Row0 *= scale.X; m.Row1 *= scale.Y; m.Row2 *= scale.Z; m.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); return m; } /// <summary> /// 姿勢行列を作成する /// </summary> public static void CreateTransform(ref Vector3 pos, ref Vector3 rot, ref Vector3 scale, out Matrix4 mat) { mat = Matrix4.Identity; if (rot != Vector3.Zero) mat = CreateRotate(rot.X, rot.Y, rot.Z); mat.Row0 *= scale.X; mat.Row1 *= scale.Y; mat.Row2 *= scale.Z; mat.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); } /// <summary> /// 姿勢行列を作成する /// </summary> public static Matrix4 CreateTransform(Vector3 pos, Vector3 rot, Vector3 scale) { Matrix4 m = Matrix4.Identity; if (rot != Vector3.Zero) m = CreateRotate(rot.X, rot.Y, rot.Z); m.Row0 *= scale.X; m.Row1 *= scale.Y; m.Row2 *= scale.Z; m.Row3 = new Vector4(pos.X, pos.Y, pos.Z, 1.0f); return m; /* var cosx = (float)Math.Cos(rot.X); var cosy = (float)Math.Cos(rot.Y); var cosz = (float)Math.Cos(rot.Z); var sinx = (float)Math.Sin(rot.X); var siny = (float)Math.Sin(rot.Y); var sinz = (float)Math.Sin(rot.Z); return new Matrix4( (cosy * cosz - sinx * siny * sinz) * scale.X, (-cosx * sinz) * scale.X, (siny * cosz + sinx * cosy * sinz) * scale.X, 0.0f, (cosy * sinz + sinx * siny * cosz) * scale.Y, (cosx * cosz) * scale.Y, (sinz * siny - sinz * cosy * cosz) * scale.Y, 0.0f, (-cosx * siny) * scale.Z, sinx * scale.Z, (cosx * cosy) * scale.Z, 0.0f, pos.X, pos.Y, pos.Z, 1.0f ); */ } public static Vector3 ExtractEulerRotation(this Matrix4 m) { if (m.M32 == 1.0f) { var x = MathHelper.PiOver2; var y = 0.0f; var z = (float)Math.Atan2(m.M21, m.M11); return new Vector3(x, -y, z); } else if (m.M32 == -1.0f) { var x = -MathHelper.PiOver2; var y = 0.0f; var z = (float)Math.Atan2(m.M21, m.M11); return new Vector3(x, -y, z); } else { var x = (float)Math.Asin(m.M32); var y = (float)Math.Atan2(-m.M31, m.M33); var z = (float)Math.Atan2(-m.M12, m.M22); return new Vector3(x, -y, z); } } public static Matrix4 CreateScreen(Vector2 size) { Matrix4 m = Matrix4.Identity; var w = size.X * 0.5f; var h = size.Y * 0.5f; m.M11 = w; m.M22 = -h; m.M41 = w; m.M42 = h; return m; } } }
31,816
https://github.com/tool-recommender-bot/hexa.tools/blob/master/hexa.core/src/main/java/fr/lteconsulting/hexa/client/ui/widget/ListBoxGen.java
Github Open Source
Open Source
MIT
2,017
hexa.tools
tool-recommender-bot
Java
Code
161
486
package fr.lteconsulting.hexa.client.ui.widget; import java.util.HashMap; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; public class ListBoxGen<T> extends Composite { int nextIdx = 0; ListBox base = new ListBox(); HashMap<Integer, T> items = new HashMap<Integer, T>(); HashMap<T, Integer> idxs = new HashMap<T, Integer>(); public ListBoxGen() { initWidget( base ); } public void clear() { base.clear(); items.clear(); idxs.clear(); } public void addItem( String text, T object ) { base.addItem( text ); items.put( nextIdx, object ); idxs.put( object, nextIdx ); nextIdx++; } public void setItemText( T object, String text ) { Integer idx = idxs.get( object ); if( idx == null ) return; base.setItemText( idx, text ); } public void setSelected( T object ) { Integer idx = idxs.get( object ); if( idx == null ) return; base.setSelectedIndex( idx ); } public T getSelected() { T res = items.get( base.getSelectedIndex() ); return res; } public void addChangeHandler( ChangeHandler handler ) { base.addChangeHandler( handler ); } public void setEnabled( boolean fEnabled ) { base.setEnabled( fEnabled ); } }
39,689
https://github.com/BASK-UFA/VMP/blob/master/public_html/app/Policies/BlogPostPolicy.php
Github Open Source
Open Source
Apache-2.0
2,020
VMP
BASK-UFA
PHP
Code
298
863
<?php namespace App\Policies; use App\Models\User; use App\Models\BlogPost; use Illuminate\Auth\Access\HandlesAuthorization; use Illuminate\Support\Facades\Gate; class BlogPostPolicy { use HandlesAuthorization; /** * Determine whether the user can view any blog posts. * * @param \App\Models\User $user * @return mixed */ public function viewAny(User $user) { return true; } /** * Determine whether the user can view the blog post. * * @param \App\Models\User $user * @param \App\Models\BlogPost $blogPost * @return mixed */ public function view(User $user, BlogPost $blogPost) { return true; } /** * Determine whether the user can create blog posts. * * @param \App\Models\User $user * @param \App\Models\BlogPost $blogPost * @return mixed */ public function create(User $user, BlogPost $blogPost) { return $this->checkPermissionModerate($blogPost); } /** * Determine whether the user can update the blog post. * * @param \App\Models\User $user * @param \App\Models\BlogPost $blogPost * @return mixed */ public function update(User $user, BlogPost $blogPost) { return $user->hasRole('admin') || (($user->id === $blogPost->user->id) && $this->checkPermissionModerate( $blogPost )); } /** * Determine whether the user can delete the blog post. * * @param \App\Models\User $user * @param \App\Models\BlogPost $blogPost * @return mixed */ public function delete(User $user, BlogPost $blogPost) { return $user->hasRole('admin') || ($user->id === $blogPost->user->id); } /** * Determine whether the user can restore the blog post. * * @param \App\Models\User $user * @param \App\Models\BlogPost $blogPost * @return mixed */ public function restore(User $user, BlogPost $blogPost) { return false; } /** * Determine whether the user can permanently delete the blog post. * * @param \App\Models\User $user * @param \App\Models\BlogPost $blogPost * @return mixed */ public function forceDelete(User $user, BlogPost $blogPost) { return false; } /** * Проверить право на публикацию статьи * * @param \App\Models\BlogPost $blogPost * @return bool */ private function checkPermissionModerate(BlogPost $blogPost): bool { if ($blogPost->isDirty('is_moderated')) { if (\Auth::user()->hasPermission('public-blog-post')) { return true; } return false; } return true; } }
13,743
https://github.com/abcpen-inc/ABCPaitiKit/blob/master/ABCPaitiDemo/ABCPaitiDemo/www/cordova_plugins.js
Github Open Source
Open Source
MIT
null
ABCPaitiKit
abcpen-inc
JavaScript
Code
46
217
cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ { "file": "plugins/ABCQuestionPlugin.js", "id": "com.abcpen.paiti.ABCQuestionPlugin", "clobbers": [ "myPlugin" ] }, { "file": "plugins/ABCMallPlugin.js", "id": "com.abcpen.paiti.ABCMallPlugin", "clobbers": [ "mallPlugin" ] } ]; module.exports.metadata = // TOP OF METADATA { "com.abcpen.paiti.ABCQuestionPlugin": "0.1.0", "com.abcpen.paiti.ABCMallPlugin": "0.1.0" } // BOTTOM OF METADATA });
43,566
https://github.com/StenAskerBergman/Moonlight/blob/master/Assets/Script/Main Game/GetResourceData.cs
Github Open Source
Open Source
Apache-2.0
null
Moonlight
StenAskerBergman
C#
Code
50
166
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GetResourceData : MonoBehaviour { //public TextMesh label; private string strStone; private void Awake() { strStone = Bank.stone.ToString(); GetComponent<UnityEngine.UI.Text>().text = "Stone : " + strStone; } void Update() { strStone = Bank.stone.ToString(); GetComponent<UnityEngine.UI.Text>().text = "Stone : " + strStone; } }
43,654
https://github.com/bio-guoda/preston/blob/master/preston-core/src/main/java/bio/guoda/preston/RefNodeConstants.java
Github Open Source
Open Source
MIT
2,022
preston
bio-guoda
Java
Code
361
1,749
package bio.guoda.preston; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.rdf.api.IRI; import org.apache.commons.rdf.api.RDFTerm; import java.net.URI; import java.util.UUID; import static bio.guoda.preston.RefNodeFactory.toIRI; public class RefNodeConstants { public static final String URN_UUID_PREFIX = "urn:uuid:"; public static final IRI HAD_MEMBER = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#hadMember")); public static final IRI SEE_ALSO = RefNodeFactory.toIRI(URI.create("http://www.w3.org/1999/02/22-rdf-syntax-ns#seeAlso")); public static final String PRESTON_URI = "https://preston.guoda.bio"; public static final IRI PRESTON = RefNodeFactory.toIRI(URI.create(PRESTON_URI)); public static final IRI HAS_FORMAT = RefNodeFactory.toIRI(URI.create("http://purl.org/dc/elements/1.1/format")); public static final IRI HAS_TYPE = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#type")); public static final IRI HAS_VALUE = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#value")); public static final IRI HAS_VERSION = RefNodeFactory.toIRI(URI.create("http://purl.org/pav/hasVersion")); public static final IRI HAS_PREVIOUS_VERSION = RefNodeFactory.toIRI(URI.create("http://purl.org/pav/previousVersion")); public static final IRI GENERATED_AT_TIME = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#generatedAtTime")); public static final IRI WAS_GENERATED_BY = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#wasGeneratedBy")); public static final IRI WAS_DERIVED_FROM = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#wasDerivedFrom")); public static final IRI QUALIFIED_GENERATION = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#qualifiedGeneration")); public static final String BIODIVERSITY_DATASET_GRAPH_UUID_STRING = "0659a54f-b713-4f86-a917-5be166a14110"; public static final UUID BIODIVERSITY_DATASET_GRAPH_UUID = UUID.fromString(BIODIVERSITY_DATASET_GRAPH_UUID_STRING); public static final IRI BIODIVERSITY_DATASET_GRAPH = toIRI(BIODIVERSITY_DATASET_GRAPH_UUID); public static final IRI BIODIVERSITY_DATASET_GRAPH_URN_UUID = toIRI(URN_UUID_PREFIX + BIODIVERSITY_DATASET_GRAPH_UUID_STRING); // Provenance Root Query is the starting point of any biodiversity dataset graph // for backwards compatibility, this root query is calculated from the *bare*, none URN uuid, // of the Biodiversity Dataset Graph Concept UUID. public static final Pair<RDFTerm, RDFTerm> PROVENANCE_ROOT_QUERY = Pair.of(BIODIVERSITY_DATASET_GRAPH, HAS_VERSION); public static final String PROVENANCE_ROOT_QUERY_HASH = "hash://sha256/2a5de79372318317a382ea9a2cef069780b852b01210ef59e06b640a3539cb5a"; public static final IRI PROVENANCE_ROOT_QUERY_HASH_URI = toIRI(PROVENANCE_ROOT_QUERY_HASH); public static final IRI STARTED_AT_TIME = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#startedAtTime")); public static final IRI ENDED_AT_TIME = RefNodeFactory.toIRI(URI.create("http://www.w3.org/ns/prov#endedAtTime")); public static final IRI USED_BY = toIRI("http://www.w3.org/ns/prov#usedBy"); public static final IRI AGENT = toIRI("http://www.w3.org/ns/prov#Agent"); public static final IRI SOFTWARE_AGENT = toIRI("http://www.w3.org/ns/prov#SoftwareAgent"); public static final IRI DESCRIPTION = toIRI("http://purl.org/dc/terms/description"); public static final IRI COLLECTION = toIRI("http://www.w3.org/ns/prov#Collection"); public static final IRI ORGANIZATION = toIRI("http://www.w3.org/ns/prov#Organization"); public static final IRI WAS_ASSOCIATED_WITH = toIRI("http://www.w3.org/ns/prov#wasAssociatedWith"); public static final IRI IS_A = toIRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); public static final IRI CREATED_BY = toIRI("http://purl.org/pav/createdBy"); public static final IRI WAS_INFORMED_BY = toIRI("http://www.w3.org/ns/prov#wasInformedBy"); public static final IRI ENTITY = toIRI("http://www.w3.org/ns/prov#Entity"); public static final IRI ACTIVITY = toIRI("http://www.w3.org/ns/prov#Activity"); public static final IRI USED = toIRI("http://www.w3.org/ns/prov#used"); public static final IRI OVERLAPS = toIRI("http://purl.obolibrary.org/obo/RO_0002131"); public static final IRI WAS_STARTED_BY = toIRI("http://www.w3.org/ns/prov#wasStartedBy"); public static final IRI DEPICTS = toIRI("http://xmlns.com/foaf/0.1/depicts"); public static final String BLOOM_HASH_PREFIX = "gz:bloom:"; public static final String THETA_SKETCH_PREFIX = "theta:"; public static final IRI STATISTICAL_ERROR = RefNodeFactory.toIRI("http://purl.obolibrary.org/obo/STATO_0000242"); public static final IRI CONFIDENCE_INTERVAL_95 = RefNodeFactory.toIRI("http://purl.obolibrary.org/obo/STATO_0000231"); }
18,485
https://github.com/eduardsui/edwork/blob/master/src/ui/htmlwindow.h
Github Open Source
Open Source
MIT
2,022
edwork
eduardsui
C
Code
161
575
#ifndef __HTMLWINDOW_H #define __HTMLWINDOW_H typedef void (*ui_trigger_event)(void *window); typedef void (*ui_idle_event)(void *userdata); typedef void (*ui_tray_event)(void *window); typedef void (*ui_event)(void *event_data, void *userdata); #define UI_EVENT_WINDOW_CREATE 0 #define UI_EVENT_WINDOW_CLOSE 1 #define UI_EVENT_LOOP_EXIT 2 #define UI_EVENTS 3 #define UI_SCHEDULER_SIZE 100 int ui_app_init(ui_trigger_event event_handler); void ui_app_tray_icon(const char *tooltip, const char *notification_title, const char *notification_text, ui_tray_event event_tray); void ui_app_tray_remove(); void ui_app_run_with_notify(ui_idle_event event_idle, void *userdata); void ui_app_run_schedule_once(ui_idle_event scheduled, void *userdata); void ui_app_run(); int ui_app_done(); void ui_app_quit(); void ui_set_event(int eid, ui_event callback, void *event_userdata); void ui_message(const char *title, const char *body, int level); int ui_question(const char *title, const char *body, int level); int ui_input(const char *title, const char *body, char *val, int val_len, int masked); void ui_js(void *wnd, const char *js); char *ui_call(void *wnd, const char *function, const char *arguments[]); void ui_free_string(void *ptr); void *ui_window(const char *title, const char *body); void ui_window_maximize(void *wnd); void ui_window_minimize(void *wnd); void ui_window_restore(void *wnd); void ui_window_top(void *wnd); void ui_window_close(void *wnd); void ui_window_set_content(void *wnd, const char *body); int ui_window_count(); void ui_lock(); void ui_unlock(); #endif
26,594
https://github.com/jsperts/workshop_unterlagen/blob/master/react/exercises/part_09/src/reducers/forms.js
Github Open Source
Open Source
MIT
2,018
workshop_unterlagen
jsperts
JavaScript
Code
70
194
import update from 'immutability-helper'; import initialState from '../initialState'; import { FIELD_UPDATED, INIT_FORM } from '../events'; function formsReducer(formsState = initialState.forms, action) { const { type, payload } = action; switch (type) { case INIT_FORM: return update(formsState, { [payload.formName]: { data: { $set: payload.data } }, }); case FIELD_UPDATED: return update(formsState, { [payload.formName]: { data: { [payload.fieldName]: { $set: payload.value } }, }, }); default: return formsState; } } export default formsReducer;
26,026
https://github.com/psubotic/souffle/blob/master/src/ram/ExistenceCheck.h
Github Open Source
Open Source
UPL-1.0
null
souffle
psubotic
C
Code
173
441
/* * Souffle - A Datalog Compiler * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved * Licensed under the Universal Permissive License v 1.0 as shown at: * - https://opensource.org/licenses/UPL * - <souffle root>/licenses/SOUFFLE-UPL.txt */ /************************************************************************ * * @file ExistenceCheck.h * * Defines a class for evaluating conditions in the Relational Algebra * Machine. * ***********************************************************************/ #pragma once #include "ram/AbstractExistenceCheck.h" #include "ram/Expression.h" #include "ram/Relation.h" #include "souffle/utility/MiscUtil.h" #include <memory> #include <utility> #include <vector> namespace souffle::ram { /** * @class ExistenceCheck * @brief Existence check for a tuple(-pattern) in a relation * * Returns true if the tuple is in the relation * * The following condition is evaluated to true if the * tuple element t0.1 is in the relation A: * ~~~~~~~~~~~~~~~~~~~~~~~~~~~ * t0.1 IN A * ~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ class ExistenceCheck : public AbstractExistenceCheck { public: ExistenceCheck(std::string rel, VecOwn<Expression> vals) : AbstractExistenceCheck(rel, std::move(vals)) {} ExistenceCheck* cloning() const override { VecOwn<Expression> newValues; for (auto& cur : values) { newValues.emplace_back(cur->cloning()); } return new ExistenceCheck(relation, std::move(newValues)); } }; } // namespace souffle::ram
29,151
https://github.com/OSU-slatelab/vp-unity-client-src/blob/master/Scripts/WatsonSpeechSynthesizer.cs
Github Open Source
Open Source
MIT
null
vp-unity-client-src
OSU-slatelab
C#
Code
277
1,013
using System; using System.Collections; using System.Collections.Generic; using System.Security; using UnityEngine; using UnityEngine.Events; using IBM.Watson.TextToSpeech.V1; using IBM.Cloud.SDK; using IBM.Cloud.SDK.Utilities; using IBM.Cloud.SDK.DataTypes; public class WatsonSpeechSynthesizer : SpeechProducer { private AuthenticationToken _authenticationToken; private TextToSpeechService _textToSpeech; private string serviceVoice = null; private bool _done_loading = false; public override bool loaded { get { return _done_loading; } } [Serializable] private class CredText { public string url; public string username; public string password; } IEnumerator Start () { yield return voice; if (voice == "michaelV3") { serviceVoice = "en-US_MichaelV3Voice"; } else if (voice == "michael") { serviceVoice = "en-US_MichaelVoice"; } TextAsset jsonCredText = Resources.Load ("tts_creds") as TextAsset; CredText creds = JsonUtility.FromJson<CredText>(jsonCredText.text); // Create credential and instantiate service Credentials credentials = new Credentials(creds.username, creds.password, creds.url); _textToSpeech = new TextToSpeechService(credentials); //_textToSpeech.Voice = VoiceType.en_US_Michael; _done_loading = true; } void Update () { } public override void Say (string text){ text = SecurityElement.Escape (text); //text = "<voice-transformation type=\"Custom\" glottal_tension=\"+80%\" breathiness=\"-80%\" pitch=\"-100%\" pitch_range=\"-25%\">" + text; //text += "</voice-transformation>"; print (text); if(!_textToSpeech.Synthesize(callback: OnSynthesize, text: text, voice: serviceVoice, accept: "audio/wav")) Log.Debug("SpeechSynthesizer.Synthesize()", "Failed to synthesize!"); } private void OnGetToken(AuthenticationToken authenticationToken, string customData) { _authenticationToken = authenticationToken; Log.Debug("SpeechSynthesizer.OnGetToken()", "created: {0} | time to expiration: {1} minutes | token: {2}", _authenticationToken.Created, _authenticationToken.TimeUntilExpiration, _authenticationToken.Token); } private void OnSynthesize(DetailedResponse<byte[]> response, IBMError error) { byte[] audioData = response.Result; AudioClip clip = WaveFile.ParseWAV("speech", audioData); speaking.Invoke (clip.length + 0.25f); Log.Debug("SpeechSynthesizer.OnSynthesize()", " called."); PlayClip(clip); } private void PlayClip(AudioClip clip) { if (Application.isPlaying && clip != null) { GameObject audioObject = new GameObject("AudioObject"); AudioSource source = audioObject.AddComponent<AudioSource>(); source.spatialBlend = 0.0f; source.loop = false; source.clip = clip; source.Play(); Destroy(audioObject, clip.length); } } // private void OnFail(RESTConnector.Error error, Dictionary<string, object> customData) // { // Log.Error("ExampleTextToSpeech.OnFail()", "Error received: {0}", error.ToString()); // } }
47,798
https://github.com/sigram/pcl-parser/blob/master/src/java/org/getopt/pcl5/PCL5Interpreter/cmd/CmdFormFeed.java
Github Open Source
Open Source
Apache-2.0
2,022
pcl-parser
sigram
Java
Code
61
203
/** * <b>Command CR</b> * Moves the print position to the left margin position. * * <i>implemented Sep 20, 2005</i> * * @author Piotrm */ package org.getopt.pcl5.PCL5Interpreter.cmd; import org.getopt.pcl5.PrinterState; import org.getopt.pcl5.PCL5Interpreter.ControlCodes; public class CmdFormFeed extends CommandPCL5 { public CmdFormFeed(PrinterState printerState) { super(printerState); } public boolean execute(int data) { if (data == ControlCodes.FF) { _printerState.newPage(); return true; } return false; } }
34,629
https://github.com/cowtowncoder/ClusterMate/blob/master/clustermate-dropwizard/src/main/java/com/fasterxml/clustermate/jaxrs/StreamingJson.java
Github Open Source
Open Source
Apache-2.0
2,017
ClusterMate
cowtowncoder
Java
Code
52
186
package com.fasterxml.clustermate.jaxrs; import java.io.IOException; import java.io.OutputStream; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.StreamingOutput; import com.fasterxml.jackson.databind.ObjectWriter; public class StreamingJson implements StreamingOutput { protected final ObjectWriter _writer; protected final Object _value; public StreamingJson(ObjectWriter w, Object value) { _writer = w; _value = value; } @Override public void write(OutputStream out) throws IOException, WebApplicationException { _writer.writeValue(out, _value); } }
40,185
https://github.com/ccx87/fsTest/blob/master/src/pages/home/index.js
Github Open Source
Open Source
MIT
null
fsTest
ccx87
JavaScript
Code
70
215
import React, { Component } from 'react'; import BaseLogo from '../common/baseLogo' import Footer from '../common/footer' import SearchBar from '../common/searchBar' import { Tool } from '../../js/config/tool' export default class Index extends Component { constructor() { super(); this.state = {}; } componentDidMount() { console.log('----Home----componentDidMount:',this.props) } render() { //isAuthenticated = 用户ID return ( <div className="home"> <div className="home-main container flex flex-a-c flex-j-c flex-d-c"> <BaseLogo /> <SearchBar isAuthenticated={654}/> <Footer /> </div> </div> ); } }
49,485
https://github.com/rostam/gradoop/blob/master/gradoop-temporal/src/test/java/org/gradoop/temporal/util/TimeFormatConversionTest.java
Github Open Source
Open Source
Apache-2.0
2,019
gradoop
rostam
Java
Code
236
620
/* * Copyright © 2014 - 2020 Leipzig University (Database Research Group) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradoop.temporal.util; import org.testng.AssertJUnit; import org.testng.annotations.Test; import java.time.LocalDateTime; /** * Test class of {@link TimeFormatConversion}. */ public class TimeFormatConversionTest { /** * Tests whether {@link TimeFormatConversion#toEpochMilli(LocalDateTime)} converts a given {@link LocalDateTime} * object to the correct number of milliseconds since Unix Epoch, if UTC is assumed. */ @Test public void toEpochMilliTest() { LocalDateTime unixEpoch = LocalDateTime.of(1970, 1, 1, 0, 0); LocalDateTime oneTwoThree = LocalDateTime.of(2009, 2, 13, 23, 31, 30); AssertJUnit.assertEquals(1234567890000L, TimeFormatConversion.toEpochMilli(oneTwoThree)); AssertJUnit.assertEquals(0L, TimeFormatConversion.toEpochMilli(unixEpoch)); } /** * Tests whether {@link TimeFormatConversion#toLocalDateTime(long)} converts a given {@code long} * to the correct {@link LocalDateTime} object, if UTC is assumed. */ @Test public void toLocalDateTimeTest() { LocalDateTime expectedUnixEpochZero = LocalDateTime.of(1970, 1, 1, 0, 0); LocalDateTime expectedOneTwoThree = LocalDateTime.of(2009, 2, 13, 23, 31, 30); long inputUnixEpochZero = 0L; long inputOneTwoThree = 1234567890000L; AssertJUnit.assertEquals(expectedUnixEpochZero, TimeFormatConversion.toLocalDateTime(inputUnixEpochZero)); AssertJUnit.assertEquals(expectedOneTwoThree, TimeFormatConversion.toLocalDateTime(inputOneTwoThree)); } }
44,776
https://github.com/emfomy/mcnla/blob/master/include/mcnla/core/matrix/collection/base.hpp
Github Open Source
Open Source
MIT
null
mcnla
emfomy
C++
Code
29
175
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @file include/mcnla/core/matrix/collection/base.hpp /// @brief The base container collection wrappers. /// /// @author Mu Yang <<emfomy@gmail.com>> /// #ifndef MCNLA_CORE_MATRIX_COLLECTION_BASE_HPP_ #define MCNLA_CORE_MATRIX_COLLECTION_BASE_HPP_ #include <mcnla/core/matrix/collection/base/vector_collection_wrapper.hpp> #include <mcnla/core/matrix/collection/base/matrix_collection_wrapper.hpp> #endif // MCNLA_CORE_MATRIX_COLLECTION_BASE_HPP_
23,483
https://github.com/malceore/knave/blob/master/pixi.js-master/test/unit/pixi/loaders/JsonLoader.js
Github Open Source
Open Source
MIT
2,018
knave
malceore
JavaScript
Code
22
77
describe('pixi/loaders/JsonLoader', function () { 'use strict'; var expect = chai.expect; var JsonLoader = PIXI.JsonLoader; it('Module exists', function () { expect(JsonLoader).to.be.a('function'); }); });
47,587
https://github.com/devdev0100/MD_HelloWorld/blob/master/CastMediaPlayerStreamingDRM-Rachel/mpl.js
Github Open Source
Open Source
Apache-2.0
2,015
MD_HelloWorld
devdev0100
JavaScript
Code
3,264
9,196
// Copyright 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the 'License'); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var senders = {}; // a list of Chrome senders var liveStreaming = false; // a flag to indicate live streaming or not var maxBW = null; // maximum bandwidth var videoStreamIndex = -1; // index for video stream var audioStreamIndex = -1; // index for audio stream var licenseUrl = null; // license server URL var videoQualityIndex = -1; // index for video quality level var audioQualityIndex = -1; // index for audio quality level var manifestCredentials = false; // a flag to indicate manifest credentials var segmentCredentials = false; // a flag to indicate segment credentials var licenseCredentials = false; // a flag to indicate license credentials var streamVideoBitrates; // bitrates of video stream selected var streamAudioBitrates; // bitrates of audio stream selected // an instance of cast.receiver.CastReceiverManager var castReceiverManager = null; var mediaManager = null; // an instance of cast.receiver.MediaManager var messageBus = null; // custom message bus var mediaElement = null; // media element var mediaHost = null; // an instance of cast.player.api.Host var mediaProtocol = null; // an instance of cast.player.api.Protocol var mediaPlayer = null; // an instance of cast.player.api.Player var trackDrmSeq = 0; /* * onLoad method as entry point to initialize custom receiver */ onload = function() { mediaElement = document.getElementById('receiverVideoElement'); mediaElement.autoplay = true; /** play – The process of play has started waiting – When the video stops due to buffering volumechange – volume has changed stalled – trying to get data, but not available ratechange – some speed changed canplay – It is possible to start playback, but no guarantee of not buffering canplaythrough – It seems likely that we can play w/o buffering issues ended – the video has finished error – error occured during loading of the video playing – when the video has started playing seeking – started seeking seeked – seeking has completed **/ mediaElement.addEventListener('loadstart', function(e) { console.log('######### MEDIA ELEMENT LOAD START'); setDebugMessage('mediaElementState', 'Load Start'); }); mediaElement.addEventListener('loadeddata', function(e) { console.log('######### MEDIA ELEMENT DATA LOADED'); setDebugMessage('mediaElementState', 'Data Loaded'); var streamCount = protocol.getStreamCount(); var streamInfo; var streamVideoCodecs; var streamAudioCodecs; var captions = {}; for (var c = 0; c < streamCount; c++) { streamInfo = protocol.getStreamInfo(c); if (streamInfo.mimeType === 'text') { captions[c] = streamInfo.language; } else if (streamInfo.mimeType === 'video/mp4' || streamInfo.mimeType === 'video/mp2t') { streamVideoCodecs = streamInfo.codecs; streamVideoBitrates = streamInfo.bitrates; if (maxBW) { var videoLevel = protocol.getQualityLevel(c, maxBW); } else { var videoLevel = protocol.getQualityLevel(c); } setDebugMessage('streamVideoQuality', streamInfo.bitrates[videoLevel]); videoStreamIndex = c; setDebugMessage('videoStreamIndex', videoStreamIndex); } else if (streamInfo.mimeType === 'audio/mp4') { audioStreamIndex = c; setDebugMessage('audioStreamIndex', audioStreamIndex); streamAudioCodecs = streamInfo.codecs; streamAudioBitrates = streamInfo.bitrates; var audioLevel = protocol.getQualityLevel(c); setDebugMessage('streamAudioQuality', streamInfo.bitrates[audioLevel]); } else { } } setDebugMessage('streamCount', streamCount); setDebugMessage('streamVideoCodecs', streamVideoCodecs); setDebugMessage('streamVideoBitrates', JSON.stringify(streamVideoBitrates)); setDebugMessage('streamAudioCodecs', streamAudioCodecs); setDebugMessage('streamAudioBitrates', JSON.stringify(streamAudioBitrates)); setDebugMessage('captions', JSON.stringify(captions)); // send captions to senders console.log(JSON.stringify(captions)); if (Object.keys(captions).length > 0) { var caption_message = {}; caption_message['captions'] = captions; //messageSender(senders[0], JSON.stringify(caption_message)); broadcast(JSON.stringify(caption_message)); } // send video bitrates to senders if (streamVideoBitrates && Object.keys(streamVideoBitrates).length > 0) { var video_bitrates_message = {}; video_bitrates_message['video_bitrates'] = streamVideoBitrates; broadcast(JSON.stringify(video_bitrates_message)); } // send audio bitrates to senders if (streamAudioBitrates && Object.keys(streamAudioBitrates).length > 0) { var audio_bitrates_message = {}; audio_bitrates_message['audio_bitrates'] = streamAudioBitrates; broadcast(JSON.stringify(audio_bitrates_message)); } getPlayerState(); }); mediaElement.addEventListener('canplay', function(e) { console.log('######### MEDIA ELEMENT CAN PLAY'); setDebugMessage('mediaElementState', 'Can Play'); getPlayerState(); }); mediaElement.addEventListener('ended', function(e) { console.log('######### MEDIA ELEMENT ENDED'); setDebugMessage('mediaElementState', 'Ended'); getPlayerState(); }); mediaElement.addEventListener('playing', function(e) { console.log('######### MEDIA ELEMENT PLAYING'); setDebugMessage('mediaElementState', 'Playing'); }); mediaElement.addEventListener('waiting', function(e) { console.log('######### MEDIA ELEMENT WAITING'); setDebugMessage('mediaElementState', 'Waiting'); getPlayerState(); }); mediaElement.addEventListener('stalled', function(e) { console.log('######### MEDIA ELEMENT STALLED'); setDebugMessage('mediaElementState', 'Stalled'); getPlayerState(); }); mediaElement.addEventListener('error', function(e) { console.log('######### MEDIA ELEMENT ERROR ' + e); setDebugMessage('mediaElementState', 'Error'); getPlayerState(); }); mediaElement.addEventListener('abort', function(e) { console.log('######### MEDIA ELEMENT ABORT ' + e); setDebugMessage('mediaElementState', 'Abort'); getPlayerState(); }); mediaElement.addEventListener('susppend', function(e) { console.log('######### MEDIA ELEMENT SUSPEND ' + e); setDebugMessage('mediaElementState', 'Suspended'); getPlayerState(); }); mediaElement.addEventListener('progress', function(e) { setDebugMessage('mediaElementState', 'Progress'); getPlayerState(); }); mediaElement.addEventListener('seeking', function(e) { console.log('######### MEDIA ELEMENT SEEKING ' + e); setDebugMessage('mediaElementState', 'Seeking'); getPlayerState(); }); mediaElement.addEventListener('seeked', function(e) { console.log('######### MEDIA ELEMENT SEEKED ' + e); setDebugMessage('mediaElementState', 'Seeked'); getPlayerState(); }); /** * Sets the log verbosity level. * * Debug logging (all messages). * DEBUG * * Verbose logging (sender messages). * VERBOSE * * Info logging (events, general logs). * INFO * * Error logging (errors). * ERROR * * No logging. * NONE **/ cast.receiver.logger.setLevelValue(cast.receiver.LoggerLevel.DEBUG); cast.player.api.setLoggerLevel(cast.player.api.LoggerLevel.DEBUG); castReceiverManager = cast.receiver.CastReceiverManager.getInstance(); /** * Called to process 'ready' event. Only called after calling * castReceiverManager.start(config) and the * system becomes ready to start receiving messages. * @param {cast.receiver.CastReceiverManager.Event} event - can be null * There is no default handler */ castReceiverManager.onReady = function(event) { console.log('### Cast Receiver Manager is READY: ' + JSON.stringify(event)); setDebugMessage('castReceiverManagerMessage', 'READY: ' + JSON.stringify(event)); setDebugMessage('applicationState', 'Loaded. Started. Ready.'); }; /** * If provided, it processes the 'senderconnected' event. * Called to process the 'senderconnected' event. * @param {cast.receiver.CastReceiverManager.Event} event - can be null * * There is no default handler */ castReceiverManager.onSenderConnected = function(event) { console.log('### Cast Receiver Manager - Sender Connected : ' + JSON.stringify(event)); setDebugMessage('castReceiverManagerMessage', 'Sender Connected: ' + JSON.stringify(event)); senders = castReceiverManager.getSenders(); setDebugMessage('senderCount', '' + senders.length); }; /** * If provided, it processes the 'senderdisconnected' event. * Called to process the 'senderdisconnected' event. * @param {cast.receiver.CastReceiverManager.Event} event - can be null * * There is no default handler */ castReceiverManager.onSenderDisconnected = function(event) { console.log('### Cast Receiver Manager - Sender Disconnected : ' + JSON.stringify(event)); setDebugMessage('castReceiverManagerMessage', 'Sender Disconnected: ' + JSON.stringify(event)); senders = castReceiverManager.getSenders(); setDebugMessage('senderCount', '' + senders.length); }; /** * If provided, it processes the 'systemvolumechanged' event. * Called to process the 'systemvolumechanged' event. * @param {cast.receiver.CastReceiverManager.Event} event - can be null * * There is no default handler */ castReceiverManager.onSystemVolumeChanged = function(event) { console.log('### Cast Receiver Manager - System Volume Changed : ' + JSON.stringify(event)); setDebugMessage('castReceiverManagerMessage', 'System Volume Changed: ' + JSON.stringify(event)); // See cast.receiver.media.Volume console.log('### Volume: ' + event.data['level'] + ' is muted? ' + event.data['muted']); setDebugMessage('volumeMessage', 'Level: ' + event.data['level'] + ' -- muted? ' + event.data['muted']); }; /** * Use the messageBus to listen for incoming messages on a virtual channel * using a namespace string.Also use messageBus to send messages back to a * sender or broadcast a message to all senders. * * You can check the cast.receiver.CastMessageBus.MessageType that a message * bus processes though a call to getMessageType. As well, you get the * namespace of a message bus by calling getNamespace() */ messageBus = castReceiverManager.getCastMessageBus( 'urn:x-cast:com.google.cast.sample.mediaplayer'); /** * The namespace urn:x-cast:com.google.cast.sample.mediaplayer is used to * identify the protocol of showing/hiding the heads up display messages * (The messages defined at the beginning of the html). * * The protocol consists of one string message: show * In the case of the message value not being show - the assumed value is hide. * @param {Object} event A returned object from callback **/ messageBus.onMessage = function(event) { console.log('### Message Bus - Media Message: ' + JSON.stringify(event)); setDebugMessage('messageBusMessage', event); console.log('### CUSTOM MESSAGE: ' + JSON.stringify(event)); // show/hide messages console.log(event['data']); var payload = JSON.parse(event['data']); if (payload['type'] === 'show') { if (payload['target'] === 'debug') { document.getElementById('messages').style.display = 'block'; } else { document.getElementById('receiverVideoElement').style.display = 'block'; } } else if (payload['type'] === 'hide') { if (payload['target'] === 'debug') { document.getElementById('messages').style.display = 'none'; } else { document.getElementById('receiverVideoElement').style.display = 'none'; } } else if (payload['type'] === 'ENABLE_CC') { var trackNumber = payload['trackNumber']; setCaption(trackNumber); } else if (payload['type'] === 'WebVTT') { mediaPlayer.enableCaptions(false); mediaPlayer.enableCaptions(true, 'webvtt', 'captions.vtt'); } else if (payload['type'] === 'TTML') { mediaPlayer.enableCaptions(false); mediaPlayer.enableCaptions(true, 'ttml', 'captions.ttml'); } else if (payload['type'] === 'live') { mediaManager.onGetStatus(event); if (payload['value'] === true) { liveStreaming = true; } else { liveStreaming = false; } } else if (payload['type'] === 'maxBW') { maxBW = payload['value']; } else if (payload['type'] === 'license') { licenseUrl = payload['value']; setDebugMessage('licenseUrl', licenseUrl); } else if (payload['type'] === 'qualityIndex' && payload['mediaType'] === 'video') { videoQualityIndex = payload['value']; setDebugMessage('videoQualityIndex', videoQualityIndex); } else if (payload['type'] === 'qualityIndex' && payload['mediaType'] === 'audio') { audioQualityIndex = payload['value']; setDebugMessage('audioQualityIndex', audioQualityIndex); } else if (payload['type'] === 'manifestCredentials') { manifestCredentials = payload['value']; setDebugMessage('manifestCredentials', manifestCredentials); } else if (payload['type'] === 'segmentCredentials') { segmentCredentials = payload['value']; setDebugMessage('segmentCredentials', segmentCredentials); } else if (payload['type'] === 'licenseCredentials') { licenseCredentials = payload['value']; setDebugMessage('licenseCredentials', licenseCredentials); } else if (payload['type'] === 'customData') { customData = payload['value']; setDebugMessage('customData', customData); } else { licenseUrl = null; } broadcast(event['data']); }; mediaManager = new cast.receiver.MediaManager(mediaElement); /** * Called when the media ends. * * mediaManager.resetMediaElement(cast.receiver.media.IdleReason.FINISHED); **/ mediaManager['onEndedOrig'] = mediaManager.onEnded; /** * Called when the media ends */ mediaManager.onEnded = function() { setDebugMessage('mediaManagerMessage', 'ENDED'); mediaManager['onEndedOrig'](); }; /** * Default implementation of onError. * * mediaManager.resetMediaElement(cast.receiver.media.IdleReason.ERROR) **/ mediaManager['onErrorOrig'] = mediaManager.onError; /** * Called when there is an error not triggered by a LOAD request * @param {Object} obj An error object from callback */ mediaManager.onError = function(obj) { setDebugMessage('mediaManagerMessage', 'ERROR - ' + JSON.stringify(obj)); mediaManager['onErrorOrig'](obj); if (mediaPlayer) { mediaPlayer.unload(); mediaPlayer = null; } }; /** * Processes the get status event. * * Sends a media status message to the requesting sender (event.data.requestId) **/ mediaManager['onGetStatusOrig'] = mediaManager.onGetStatus; /** * Processes the get status event. * @param {Object} event An status object */ mediaManager.onGetStatus = function(event) { console.log('### Media Manager - GET STATUS: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'GET STATUS ' + JSON.stringify(event)); mediaManager['onGetStatusOrig'](event); }; /** * Default implementation of onLoadMetadataError. * * mediaManager.resetMediaElement(cast.receiver.media.IdleReason.ERROR, false); * mediaManager.sendLoadError(cast.receiver.media.ErrorType.LOAD_FAILED); **/ mediaManager['onLoadMetadataErrorOrig'] = mediaManager.onLoadMetadataError; /** * Called when load has had an error, overridden to handle application * specific logic. * @param {Object} event An object from callback */ mediaManager.onLoadMetadataError = function(event) { console.log('### Media Manager - LOAD METADATA ERROR: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'LOAD METADATA ERROR: ' + JSON.stringify(event)); mediaManager['onLoadMetadataErrorOrig'](event); }; /** * Default implementation of onMetadataLoaded * * Passed a cast.receiver.MediaManager.LoadInfo event object * Sets the mediaElement.currentTime = loadInfo.message.currentTime * Sends the new status after a LOAD message has been completed succesfully. * Note: Applications do not normally need to call this API. * When the application overrides onLoad, it may need to manually declare that * the LOAD request was sucessful. The default implementaion will send the new * status to the sender when the video/audio element raises the * 'loadedmetadata' event. * The default behavior may not be acceptable in a couple scenarios: * * 1) When the application does not want to declare LOAD succesful until for * example 'canPlay' is raised (instead of 'loadedmetadata'). * 2) When the application is not actually loading the media element (for * example if LOAD is used to load an image). **/ mediaManager['onLoadMetadataOrig'] = mediaManager.onLoadMetadataLoaded; /** * Called when load has completed, overridden to handle application specific * logic. * @param {Object} event An object from callback */ mediaManager.onLoadMetadataLoaded = function(event) { console.log('### Media Manager - LOADED METADATA: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'LOADED METADATA: ' + JSON.stringify(event)); mediaManager['onLoadMetadataOrig'](event); }; /** * Processes the pause event. * * mediaElement.pause(); * Broadcast (without sending media information) to all senders that pause has * happened. **/ mediaManager['onPauseOrig'] = mediaManager.onPause; /** * Process pause event * @param {Object} event */ mediaManager.onPause = function(event) { console.log('### Media Manager - PAUSE: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'PAUSE: ' + JSON.stringify(event)); mediaManager['onPauseOrig'](event); }; /** * Default - Processes the play event. * * mediaElement.play(); * **/ mediaManager['onPlayOrig'] = mediaManager.onPlay; /** * Process play event * @param {Object} event */ mediaManager.onPlay = function(event) { console.log('### Media Manager - PLAY: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'PLAY: ' + JSON.stringify(event)); mediaManager['onPlayOrig'](event); }; /** * Default implementation of the seek event. * Sets the mediaElement.currentTime to event.data.currentTime. If the * event.data.resumeState is cast.receiver.media.SeekResumeState.PLAYBACK_START * and the mediaElement is paused then call mediaElement.play(). Otherwise if * event.data.resumeState is cast.receiver.media.SeekResumeState.PLAYBACK_PAUSE * and the mediaElement is not paused, call mediaElement.pause(). * Broadcast (without sending media information) to all senders that seek has * happened. **/ mediaManager['onSeekOrig'] = mediaManager.onSeek; /** * Process seek event * @param {Object} event */ mediaManager.onSeek = function(event) { console.log('### Media Manager - SEEK: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'SEEK: ' + JSON.stringify(event)); mediaManager['onSeekOrig'](event); }; /** * Default implementation of the set volume event. * Checks event.data.volume.level is defined and sets the mediaElement.volume * to the value. * Checks event.data.volume.muted is defined and sets the mediaElement.muted * to the value. * Broadcasts (without sending media information) to all senders that the * volume has changed. **/ mediaManager['onSetVolumeOrig'] = mediaManager.onSetVolume; /** * Process set volume event * @param {Object} event */ mediaManager.onSetVolume = function(event) { console.log('### Media Manager - SET VOLUME: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'SET VOLUME: ' + JSON.stringify(event)); mediaManager['onSetVolumeOrig'](event); }; /** * Processes the stop event. * * mediaManager.resetMediaElement(cast.receiver.media.IdleReason.CANCELLED, * true, event.data.requestId); * * Resets Media Element to IDLE state. After this call the mediaElement * properties will change, paused will be true, currentTime will be zero and * the src attribute will be empty. This only needs to be manually called if * the developer wants to override the default behavior of onError, onStop or * onEnded, for example. **/ mediaManager['onStopOrig'] = mediaManager.onStop; /** * Process stop event * @param {Object} event */ mediaManager.onStop = function(event) { console.log('### Media Manager - STOP: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'STOP: ' + JSON.stringify(event)); mediaManager['onStopOrig'](event); }; /** * Default implementation for the load event. * * Sets the mediaElement.autoplay to false. * Checks that data.media and data.media.contentId are valid then sets the * mediaElement.src to the data.media.contentId. * * Checks the data.autoplay value: * - if undefined sets mediaElement.autoplay = true * - if has value then sets mediaElement.autoplay to that value **/ mediaManager['onLoadOrig'] = mediaManager.onLoad; /** * Processes the load event. * @param {Object} event */ mediaManager.onLoad = function(event) { console.log('### Media Manager - LOAD: ' + JSON.stringify(event)); setDebugMessage('mediaManagerMessage', 'LOAD ' + JSON.stringify(event)); if (mediaPlayer !== null) { mediaPlayer.unload(); // Ensure unload before loading again } if (event.data['media'] && event.data['media']['contentId']) { var url = event.data['media']['contentId']; setDebugMessage('mediaPlayerState', '-'); mediaHost = new cast.player.api.Host({ 'mediaElement': mediaElement, 'url': url }); if (manifestCredentials) { mediaHost.updateManifestRequestInfo = function(requestInfo) { // example of setting CORS withCredentials if (!requestInfo.url) { requestInfo.url = url; } requestInfo.withCredentials = true; }; } if (segmentCredentials) { mediaHost.updateSegmentRequestInfo = function(requestInfo) { // example of setting CORS withCredentials requestInfo.withCredentials = true; // example of setting headers //requestInfo.headers = {}; //requestInfo.headers['content-type'] = 'text/xml;charset=utf-8'; }; } if (licenseCredentials) { mediaHost.updateLicenseRequestInfo = function(requestInfo) { // example of setting CORS withCredentials requestInfo.withCredentials = true; }; } if (licenseUrl) { mediaHost.licenseUrl = licenseUrl; } if (customData) { mediaHost.licenseCustomData = customData; console.log('### customData: ' + customData); } if ((videoQualityIndex != -1 && streamVideoBitrates && videoQualityIndex < streamVideoBitrates.length) || (audioQualityIndex != -1 && streamAudioBitrates && audioQualityIndex < streamAudioBitrates.length)) { mediaHost['getQualityLevelOrig'] = mediaHost.getQualityLevel; mediaHost.getQualityLevel = function(streamIndex, qualityLevel) { if (streamIndex == videoStreamIndex && videoQualityIndex != -1) { return videoQualityIndex; } else if (streamIndex == audioStreamIndex && audioQualityIndex != -1) { return audioQualityIndex; } else { return qualityLevel; } }; } mediaHost.onError = function(errorCode, requestStatus) { console.error('### HOST ERROR - Fatal Error: code = ' + errorCode); setDebugMessage('mediaHostState', 'Fatal Error: code = ' + errorCode); if (mediaPlayer !== null) { mediaPlayer.unload(); } }; /* David's additions */ mediaHost.prepareLicenseRequest = function () { trackDrmSeq++; msg = "[SEQ=" + trackDrmSeq.toString() + "] PrepareLicenseRequest called!" setDebugMessage('overridePrepareLicenseRequest', msg); return true; } //var origUpdateLicenseRequestInfo = window.mediaHost.updateLicenseRequestInfo; mediaHost.updateLicenseRequestInfo = function (requestInfo) { content = "" if (requestInfo.content) { content = String.fromCharCode.apply(null, requestInfo.content); var license_request_info_message = {}; license_request_info_message['license_request'] = content; //messageSender(senders[0], JSON.stringify(caption_message)); broadcast(JSON.stringify(license_request_info_message)); } headers = "" if (requestInfo.headers) { // for now, update the headers only if we sent custom data from the sender if (customData) { //requestInfo.headers['msprdrm_server_redirect_compat'] = 'false'; //requestInfo.headers['msprdrm_server_exception_compat'] = 'false'; //requestInfo.headers['Accept'] = 'application/xml, text/xml, */*'; //requestInfo.headers['Nds-Access-Criteria'] = '1430116314000,1430116315000'; //requestInfo.withCredentials = true; } headers = JSON.stringify(requestInfo.headers) } prot = requestInfo.protectionSystem url = requestInfo.url trackDrmSeq++; msg = "[SEQ=" + trackDrmSeq.toString() + "] Content: " + content + " || headers: " + headers + " || prot: " + prot + " || url: " + url setDebugMessage('requestInfo', msg); //origUpdateLicenseRequestInfo(requestInfo); } mediaHost.processLicense = function(param) { trackDrmSeq++; license = String.fromCharCode.apply(null, param) msg = "[SEQ=" + trackDrmSeq.toString() + "] " + license; setDebugMessage('license', msg); var license_message = {}; license_message['license_response'] = license; //messageSender(senders[0], JSON.stringify(caption_message)); broadcast(JSON.stringify(license_message)); return param; } /*var origTrackBandwidth = mediaHost.trackBandwidth; mediaHost.trackBandwidth = function (streamIndex, time, size) { setDebugMessage('TrackBandwidth', 'trackBandwidth...'); origTrackBandwidth(streamIndex, time, size); }*/ var initialTimeIndexSeconds = event.data['media']['currentTime'] || 0; protocol = null; var ext = null; if (url.lastIndexOf('.m3u8') >= 0) { protocol = cast.player.api.CreateHlsStreamingProtocol(mediaHost); ext = 'HLS'; } else if (url.lastIndexOf('.mpd') >= 0) { protocol = cast.player.api.CreateDashStreamingProtocol(mediaHost); ext = 'MPEG-DASH'; } else if (url.lastIndexOf('.ism/') >= 0 || url.lastIndexOf('.isml/') >= 0) { protocol = cast.player.api.CreateSmoothStreamingProtocol(mediaHost); ext = 'Smooth Streaming'; } console.log('### Media Protocol Identified as ' + ext); setDebugMessage('mediaProtocol', ext); // Advanced Playback - HLS, MPEG DASH, SMOOTH STREAMING // Player registers to listen to the media element events through the // mediaHost property of the mediaElement mediaPlayer = new cast.player.api.Player(mediaHost); if (liveStreaming) { mediaPlayer.load(protocol, Infinity); } else { mediaPlayer.load(protocol, initialTimeIndexSeconds); } setDebugMessage('mediaHostState', 'success'); } }; console.log('### Application Loaded. Starting system.'); setDebugMessage('applicationState', 'Loaded. Starting up.'); /** * Application config **/ var appConfig = new cast.receiver.CastReceiverManager.Config(); /** * Text that represents the application status. It should meet * internationalization rules as may be displayed by the sender application. * @type {string|undefined} **/ appConfig.statusText = 'Ready to play'; /** * Maximum time in seconds before closing an idle * sender connection. Setting this value enables a heartbeat message to keep * the connection alive. Used to detect unresponsive senders faster than * typical TCP timeouts. The minimum value is 5 seconds, there is no upper * bound enforced but practically it's minutes before platform TCP timeouts * come into play. Default value is 10 seconds. * @type {number|undefined} * 10 minutes for testing, use default 10sec in prod by not setting this value **/ appConfig.maxInactivity = 6000; /** * Initializes the system manager. The application should call this method when * it is ready to start receiving messages, typically after registering * to listen for the events it is interested on. */ castReceiverManager.start(appConfig); }; function setCaption(trackNumber) { var current, next; var streamCount = protocol.getStreamCount(); var streamInfo; for (current = 0; current < streamCount; current++) { if (protocol.isStreamEnabled(current)) { streamInfo = protocol.getStreamInfo(current); if (streamInfo.mimeType.indexOf('text') === 0) { protocol.enableStream(current, false); mediaPlayer.enableCaptions(false); break; } } } if (trackNumber) { protocol.enableStream(trackNumber, true); mediaPlayer.enableCaptions(true); } } function nextCaption() { var current, next; var streamCount = protocol.getStreamCount(); var streamInfo; for (current = 0; current < streamCount; current++) { if (protocol.isStreamEnabled(current)) { streamInfo = protocol.getStreamInfo(current); if (streamInfo.mimeType.indexOf('text') === 0) { break; } } } if (current === streamCount) { next = 0; } else { next = current + 1; } while (next !== current) { if (next === streamCount) { next = 0; } streamInfo = protocol.getStreamInfo(next); if (streamInfo.mimeType.indexOf('text') === 0) { break; } next++; } if (next !== current) { if (current !== streamCount) { protocol.enableStream(current, false); mediaPlayer.enableCaptions(false); } if (next !== streamCount) { protocol.enableStream(next, true); mediaPlayer.enableCaptions(true); } } } /* * send message to a sender via custom message channel @param {string} senderId A id string for specific sender @param {string} message A message string */ function messageSender(senderId, message) { messageBus.send(senderId, message); } /* * broadcast message to all senders via custom message channel @param {string} message A message string */ function broadcast(message) { messageBus.broadcast(message); } /* * set debug message on receiver screen/TV @param {string} message A message string */ function setDebugMessage(elementId, message) { document.getElementById(elementId).innerHTML = '' + JSON.stringify(message); } /* * get media player state */ function getPlayerState() { var playerState = mediaPlayer.getState(); setDebugMessage('mediaPlayerState', 'underflow: ' + playerState['underflow']); }
32,645
https://github.com/smkhalsa/flutter_cache_manager/blob/master/flutter_cache_manager/test/cache_store_test.dart
Github Open Source
Open Source
MIT
2,020
flutter_cache_manager
smkhalsa
Dart
Code
759
3,146
import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_cache_manager/src/cache_store.dart'; import 'package:flutter_cache_manager/src/storage/cache_object.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:flutter_cache_manager/src/storage/cache_info_repositories' '/cache_info_repository.dart'; import 'helpers/config_extensions.dart'; import 'helpers/test_configuration.dart'; void main() { group('Retrieving files from store', () { test('Store should return null when file not cached', () async { var repo = MockRepo(); when(repo.get(any)).thenAnswer((_) => Future.value(null)); var store = CacheStore(createTestConfig()); expect(await store.getFile('This is a test'), null); }); test('Store should return FileInfo when file is cached', () async { var fileName = 'testimage.png'; var fileUrl = 'baseflow.com/test.png'; var config = createTestConfig(); await config.returnsFile(fileName); config.returnsCacheObject(fileUrl, fileName, DateTime.now()); var tempDir = createDir(); await (await tempDir).childFile('testimage.png').create(); var store = CacheStore(config); expect(await store.getFile('baseflow.com/test.png'), isNotNull); }); test('Store should return null when file is no longer cached', () async { var repo = MockRepo(); when(repo.get('baseflow.com/test.png')).thenAnswer((_) => Future.value( CacheObject('baseflow.com/test.png', relativePath: 'testimage.png'))); var store = CacheStore(createTestConfig()); expect(await store.getFile('baseflow.com/test.png'), null); }); test('Store should return no CacheInfo when file not cached', () async { var repo = MockRepo(); when(repo.get(any)).thenAnswer((_) => Future.value(null)); var store = CacheStore(createTestConfig()); expect(await store.retrieveCacheData('This is a test'), null); }); test('Store should return CacheInfo when file is cached', () async { var fileName = 'testimage.png'; var fileUrl = 'baseflow.com/test.png'; var config = createTestConfig(); await config.returnsFile(fileName); config.returnsCacheObject(fileUrl, fileName, DateTime.now()); var store = CacheStore(config); expect(await store.retrieveCacheData(fileUrl), isNotNull); }); test('Store should return CacheInfo from memory when asked twice', () async { var fileName = 'testimage.png'; var fileUrl = 'baseflow.com/test.png'; var validTill = DateTime.now(); var config = createTestConfig(); await config.returnsFile(fileName); config.returnsCacheObject(fileUrl, fileName, validTill); var store = CacheStore(config); var result = await store.retrieveCacheData(fileUrl); expect(result, isNotNull); var _ = await store.retrieveCacheData(fileUrl); verify(config.repo.get(any)).called(1); }); test( 'Store should return File from memcache only when file is retrieved before', () async { var fileName = 'testimage.png'; var fileUrl = 'baseflow.com/test.png'; var validTill = DateTime.now(); var config = createTestConfig(); await config.returnsFile(fileName); config.returnsCacheObject(fileUrl, fileName, validTill); var store = CacheStore(config); expect(await store.getFileFromMemory(fileUrl), null); await store.getFile(fileUrl); expect(await store.getFileFromMemory(fileUrl), isNotNull); }); }); group('Storing files in store', () { test('Store should store fileinfo in repo', () async { var config = createTestConfig(); var store = CacheStore(config); var cacheObject = CacheObject('baseflow.com/test.png', relativePath: 'testimage.png'); await store.putFile(cacheObject); verify(config.repo.updateOrInsert(cacheObject)).called(1); }); }); group('Removing files in store', () { test('Store should remove fileinfo from repo on delete', () async { var fileName = 'testimage.png'; var fileUrl = 'baseflow.com/test.png'; var validTill = DateTime.now(); var config = createTestConfig(); await config.returnsFile(fileName); config.returnsCacheObject(fileUrl, fileName, validTill); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); var cacheObject = CacheObject(fileUrl, relativePath: fileName, id: 1); await store.removeCachedFile(cacheObject); verify(config.repo.deleteAll(argThat(contains(cacheObject.id)))) .called(1); }); test('Store should remove file over capacity', () async { var config = createTestConfig(); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); var cacheObject = CacheObject('baseflow.com/test.png', relativePath: 'testimage.png', id: 1); await config.returnsFile('testimage.png'); when(config.repo.getObjectsOverCapacity(any)) .thenAnswer((_) => Future.value([cacheObject])); when(config.repo.getOldObjects(any)).thenAnswer((_) => Future.value([])); when(config.repo.get('baseflow.com/test.png')) .thenAnswer((_) => Future.value(cacheObject)); expect(await store.getFile('baseflow.com/test.png'), isNotNull); await untilCalled(config.repo.deleteAll(any)); verify(config.repo.getObjectsOverCapacity(any)).called(1); verify(config.repo.deleteAll(argThat(contains(cacheObject.id)))) .called(1); }); test('Store should remove file over that are too old', () async { var config = createTestConfig(); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); await config.returnsFile('testimage.png'); var cacheObject = CacheObject('baseflow.com/test.png', relativePath: 'testimage.png', id: 1); when(config.repo.getObjectsOverCapacity(any)) .thenAnswer((_) => Future.value([])); when(config.repo.getOldObjects(any)) .thenAnswer((_) => Future.value([cacheObject])); when(config.repo.get('baseflow.com/test.png')) .thenAnswer((_) => Future.value(cacheObject)); expect(await store.getFile('baseflow.com/test.png'), isNotNull); await untilCalled(config.repo.deleteAll(any)); verify(config.repo.getOldObjects(any)).called(1); verify(config.repo.deleteAll(argThat(contains(cacheObject.id)))) .called(1); }); test('Store should remove file old and over capacity', () async { var config = createTestConfig(); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); await config.returnsFile('testimage.png'); var cacheObject = CacheObject('baseflow.com/test.png', relativePath: 'testimage.png', id: 1); when(config.repo.getObjectsOverCapacity(any)) .thenAnswer((_) => Future.value([cacheObject])); when(config.repo.getOldObjects(any)) .thenAnswer((_) => Future.value([cacheObject])); when(config.repo.get('baseflow.com/test.png')) .thenAnswer((_) => Future.value(cacheObject)); expect(await store.getFile('baseflow.com/test.png'), isNotNull); await untilCalled(config.repo.deleteAll(any)); await Future.delayed(const Duration(milliseconds: 5)); verify(config.repo.getObjectsOverCapacity(any)).called(1); verify(config.repo.getOldObjects(any)).called(1); verify(config.repo.deleteAll(argThat(contains(cacheObject.id)))) .called(1); }); test('Store should recheck cache info when file is removed', () async { var config = createTestConfig(); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); var file = await config.returnsFile('testimage.png'); var cacheObject = CacheObject('baseflow.com/test.png', relativePath: 'testimage.png', id: 1); when(config.repo.getObjectsOverCapacity(any)) .thenAnswer((_) => Future.value([])); when(config.repo.getOldObjects(any)).thenAnswer((_) => Future.value([])); when(config.repo.get('baseflow.com/test.png')) .thenAnswer((_) => Future.value(cacheObject)); expect(await store.getFile('baseflow.com/test.png'), isNotNull); await file.delete(); expect(await store.getFile('baseflow.com/test.png'), isNull); }); test('Store should not remove files that are not old or over capacity', () async { var config = createTestConfig(); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); await config.returnsFile('testimage.png'); var cacheObject = CacheObject('baseflow.com/test.png', relativePath: 'testimage.png', id: 1); when(config.repo.getObjectsOverCapacity(any)) .thenAnswer((_) => Future.value([])); when(config.repo.getOldObjects(any)).thenAnswer((_) => Future.value([])); when(config.repo.get('baseflow.com/test.png')) .thenAnswer((_) => Future.value(cacheObject)); expect(await store.getFile('baseflow.com/test.png'), isNotNull); await untilCalled(config.repo.deleteAll(any)); verify(config.repo.getOldObjects(any)).called(1); verifyNever(config.repo.deleteAll(argThat(contains(cacheObject.id)))); }); test('Store should remove all files when emptying cache', () async { var config = createTestConfig(); var store = CacheStore(config); store.cleanupRunMinInterval = const Duration(milliseconds: 1); await config.returnsFile('testimage.png'); var co1 = CacheObject('baseflow.com/test.png', relativePath: 'testimage1.png', id: 1); var co2 = CacheObject('baseflow.com/test.png', relativePath: 'testimage2.png', id: 2); var co3 = CacheObject('baseflow.com/test.png', relativePath: 'testimage3.png', id: 3); when(config.repo.getAllObjects()) .thenAnswer((_) => Future.value([co1, co2, co3])); await store.emptyCache(); verify(config.repo .deleteAll(argThat(containsAll([co1.id, co2.id, co3.id])))).called(1); }); }); } Future<Directory> createDir() async { final fileSystem = MemoryFileSystem(); return fileSystem.systemTempDirectory.createTemp('test'); } class MockRepo extends Mock implements CacheInfoRepository {}
49,637
https://github.com/ChirkovRoman/pp_2020_autumn_informatics/blob/master/modules/task_3/kulandin_d_quick_sort_simple/quick_sort.cpp
Github Open Source
Open Source
BSD-3-Clause
null
pp_2020_autumn_informatics
ChirkovRoman
C++
Code
464
1,474
// Copyright 2020 Kulandin Denis #include <mpi.h> #include <ctime> #include <iostream> #include <random> #include <utility> #include <vector> #include "../../../modules/task_3/kulandin_d_quick_sort_simple/quick_sort.h" std::mt19937 gen(time(0)); std::vector<int> randomVector(int sz) { std::vector<int> ans(sz); for (int i = 0; i < sz; ++i) { ans[i] = gen(); } return ans; } void division(std::vector<int>* a, int l, int r, int* t) { int mid = (*a)[l + gen() % (r - l + 1)]; while (l <= r) { while ((*a)[l] < mid) l++; while ((*a)[r] > mid) r--; if (l >= r) break; std::swap((*a)[l++], (*a)[r--]); } *t = r; } void quickSort(std::vector<int>* a, int l, int r) { // std::cout << l << ' ' << r << '\n'; if (l >= r) return; int t = 0; division(a, l, r, &t); quickSort(a, l, t); quickSort(a, t + 1, r); } std::vector<int> parallelQuickSort(const std::vector<int> &a) { int length = a.size(); int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Status status; int first = 0; int plength = length; std::vector<int> part = a; int leftProc = rank; int rightProc = size; if (rank != 0) { MPI_Recv(&first, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); MPI_Recv(&plength, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); part = std::vector<int>(plength); MPI_Recv(&part[0], plength, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); MPI_Recv(&rightProc, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status); } int l = 0; int r = plength - 1; // printf("initial size: rank = %d, l = %d, r = %d\n", rank, l, r); int m; int leftP = (rightProc + leftProc) / 2; int rightP = rightProc; while (r > l && leftP > leftProc) { division(&part, l, r, &m); int start = 0; int count = 0; if (m - l + 1 <= r - m) { start = l; count = m - l + 1; l = m + 1; } else { start = m + 1; count = r - m; r = m; } if (1) { // printf("from %d to %d, cnt = %d\n", rank, leftP, count); MPI_Send(&start, 1, MPI_INT, leftP, 0, MPI_COMM_WORLD); MPI_Send(&count, 1, MPI_INT, leftP, 0, MPI_COMM_WORLD); MPI_Send(&part[0] + start, count, MPI_INT, leftP, 0, MPI_COMM_WORLD); MPI_Send(&rightP, 1, MPI_INT, leftP, 0, MPI_COMM_WORLD); } rightP = leftP; leftP = (rightP + leftProc) / 2; } // printf("%d %d %d\n", rank, l, r); quickSort(&part, l, r); // MPI_Barrier(MPI_COMM_WORLD); leftP = (rightProc + leftProc) / 2; while (leftP > leftProc) { int start; int count; MPI_Status tmp; MPI_Recv(&start, 1, MPI_INT, leftP, 0, MPI_COMM_WORLD, &tmp); MPI_Recv(&count, 1, MPI_INT, leftP, 0, MPI_COMM_WORLD, &tmp); MPI_Recv(&part[0] + start, count, MPI_INT, leftP, 0, MPI_COMM_WORLD, &tmp); // printf("recieve from %d to %d, cnt = %d\n", leftP, rank, count); leftP = (leftP + leftProc) / 2; } if (rank != 0) { MPI_Send(&first, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD); MPI_Send(&plength, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD); MPI_Send(&part[0], plength, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD); } return part; }
30,493
https://github.com/grzegorz-kraszewski/libvstring/blob/master/src/gcc/freevecpooled.s
Github Open Source
Open Source
MIT
null
libvstring
grzegorz-kraszewski
GAS
Code
100
294
/****** FreeVecPooled ******************************************************** * NAME * FreeVecPooled -- frees memory block allocated with AllocVecPooled * SYNOPSIS * FreeVecPooled(pool, block) * A0 A1 * * void FreeVecPooled(APTR, APTR); * FUNCTION * Frees memory block allocated from given memory pool with AllocVecPooled. * INPUTS * pool - memory pool handle * block - block to be freed * RESULT * None. * NOTES * Requires external _SysBase symbol. * No sanity checks are done on arguments. * SEE ALSO * AllocVecPooled * *****************************************************************************/ .global _FreeVecPooled .xref _SysBase FreePooled = -714 _FreeVecPooled: MOVE.L a6,-(sp) MOVE.L -(a1),d0 MOVEA.L _SysBase,a6 JSR FreePooled(a6) MOVEA.L (sp)+,a6 RTS
31,626
https://github.com/zchajax/WiEngine/blob/master/src/com/wiyun/engine/nodes/RenderTexture.java
Github Open Source
Open Source
MIT
2,021
WiEngine
zchajax
Java
Code
750
1,832
/* * Copyright (c) 2010 WiYun Inc. * Author: luma(stubma@gmail.com) * * For all entities this program is free software; you can redistribute * it and/or modify it under the terms of the 'WiEngine' license with * the additional provision that 'WiEngine' must be credited in a manner * that can be be observed by end users, for example, in the credits or during * start up. (please find WiEngine logo in sdk's logo folder) * * 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 com.wiyun.engine.nodes; import com.wiyun.engine.opengl.Texture2D; import com.wiyun.engine.types.WYBlendFunc; import com.wiyun.engine.types.WYColor3B; /** * 设置自定义frame buffer,使渲染结果保存在贴图中。用于实现一些特殊效果。 */ public class RenderTexture extends Node implements Node.IColorable { /** * \if English * Create a render texture with specified size * * @param width width in pixel * @param height height in pixel * \else * 静态构造函数 * * @param width 宽度 * @param height 高度 * \endif */ public static RenderTexture make(int width, int height) { return new RenderTexture(width, height); } /** * \if English * Create a render texture which is full screen size * \else * 创建一个全屏大小的渲染贴图 * \endif */ public static RenderTexture make() { return new RenderTexture(); } protected RenderTexture(int width, int height) { nativeInit(width, height); } public RenderTexture() { nativeInit(); } /** * 从底层指针获得一个RenderTexture的Java对象 * * @param pointer 底层指针 * @return {@link RenderTexture} */ public static RenderTexture from(int pointer) { return pointer == 0 ? null : new RenderTexture(pointer); } protected RenderTexture(int pointer) { super(pointer); } @Override protected void doNativeInit() { } private native void nativeInit(); private native void nativeInit(int width, int height); /** * \if English * Start render something into texture. You can specify background color of * texture * * @param r red component of background * @param g green component of background * @param b blue component of background * @param a alpha component of background * \else * Render之前调用, 开始讲渲染操作重定向到贴图中. 这个方法可以指定贴图背景色 * * @param r 背景色的红色部分 * @param g 背景色的绿色部分 * @param b 背景色的蓝色部分 * @param a 背景色的透明度 * \endif */ public native void beginRender(float r, float g, float b, float a); /** * \if English * Start render something into texture * \else * Render之前调用, 开始讲渲染操作重定向到贴图中 * \endif */ public native void beginRender(); /** * \if English * End render redirecting * \else * Render之后调用, 结束渲染重定向 * \endif */ public native void endRender(); /** * \if English * Clear texture with a color * * @param r red component of background * @param g green component of background * @param b blue component of background * @param a alpha component of background * \else * 用某个颜色清空贴图内容 * * @param r 背景色的红色部分 * @param g 背景色的绿色部分 * @param b 背景色的蓝色部分 * @param a 背景色的透明度 * \endif */ public native void clear(float r, float g, float b, float a); public WYBlendFunc getBlendFunc() { return new WYBlendFunc(getBlendFuncSrc(), getBlendFuncDst()); } private native int getBlendFuncSrc(); private native int getBlendFuncDst(); public void setBlendFunc(WYBlendFunc blendFunc) { nativeSetBlendFunc(blendFunc.src, blendFunc.dst); } private native void nativeSetBlendFunc(int src, int dst); public native int getAlpha(); public native void setAlpha(int alpha); public WYColor3B getColor() { WYColor3B color = new WYColor3B(); nativeGetColor(color); return color; } private native void nativeGetColor(WYColor3B color); public void setColor(WYColor3B color) { nativeSetColor(color.r, color.g, color.b); } private native void nativeSetColor(int r, int g, int b); /** * \if English * Get \link Texture2D Texture2D\endlink object from render texture * * @return \link Texture2D Texture2D\endlink * \else * 从当前对象得到一个\link Texture2D Texture2D\endlink对象 * * @return \link Texture2D Texture2D\endlink * \endif */ public Texture2D createTexture() { return Texture2D.from(nativeCreateTexture()); } private native int nativeCreateTexture(); }
36,124
https://github.com/tonykolomeytsev/mospolyhelper-android/blob/master/app/src/main/java/com/mospolytech/mospolyhelper/features/ui/schedule/ids/ScheduleIdsAdapter.kt
Github Open Source
Open Source
MIT
null
mospolyhelper-android
tonykolomeytsev
Kotlin
Code
184
682
package com.mospolytech.mospolyhelper.features.ui.schedule.ids import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.mospolytech.mospolyhelper.R class ScheduleIdsAdapter( private val idList: List<Pair<Boolean, String>>, private var query: String, private var filterMode: FilterModes, private val onItemClick: (Pair<Boolean, String>) -> Unit ): RecyclerView.Adapter<ScheduleIdsAdapter.ViewHolder>() { private var filteredIdList: List<Pair<Boolean, String>> init { filteredIdList = setFilteredList() } override fun getItemCount() = filteredIdList.size private fun setFilteredList(): List<Pair<Boolean, String>> { return if (filterMode == FilterModes.All) { idList.filter { it.second.contains(query, ignoreCase = true) } } else { idList.filter { it.second.contains(query, ignoreCase = true) && it.first == (filterMode == FilterModes.Groups)} } } fun update(filterMode: FilterModes, query: String) { this.filterMode = filterMode this.query = query filteredIdList = setFilteredList() notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater .from(parent.context) .inflate(R.layout.item_schedule_id, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind() } inner class ViewHolder( view: View ): RecyclerView.ViewHolder(view) { private val textView = view.findViewById<TextView>(R.id.textview_id) init { textView.setOnClickListener { onItemClick(filteredIdList[adapterPosition]) } } fun bind() { val item = filteredIdList[adapterPosition] textView.text = item.second if (item.first) { textView.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_id_group, 0, 0, 0) } else { textView.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_id_teacher, 0, 0, 0) } } } }
49,469
https://github.com/mihailj/libyuv-node/blob/master/.npmignore
Github Open Source
Open Source
MIT
2,020
libyuv-node
mihailj
Ignore List
Code
4
15
node_modules/ external/ build/ debug.log
26,748
https://github.com/math-lab/ImageBlendingAlgorithms/blob/master/ImageBlendingAlgorithms/IBALib/Interfaces/IScaleAlgorithm.cs
Github Open Source
Open Source
MIT
2,019
ImageBlendingAlgorithms
math-lab
C#
Code
26
81
using IBALib.Types; using System; using System.Collections.Generic; using System.Text; namespace IBALib.Interfaces { public interface IScaleAlgorithm : IAlgorithm { Colour[,] Scale<T>(IMatrix<T> src, int x, int y); } }
6,761
https://github.com/djingwu/hybrid-development/blob/master/clbs/src/main/java/com/zw/ws/impl/WsOilSensorCommandService.java
Github Open Source
Open Source
MIT
2,021
hybrid-development
djingwu
Java
Code
627
3,861
package com.zw.ws.impl; import com.zw.platform.basic.constant.RedisKeyEnum; import com.zw.platform.basic.core.RedisHelper; import com.zw.platform.basic.dto.BindDTO; import com.zw.platform.commons.SystemHelper; import com.zw.platform.domain.basicinfo.VehicleInfo; import com.zw.platform.domain.vas.monitoring.form.T808_0x8202; import com.zw.platform.domain.vas.oilmassmgt.OilVehicleSetting; import com.zw.platform.domain.vas.oilmassmgt.form.FuelTankForm; import com.zw.platform.domain.vas.oilmassmgt.form.OilCalibrationForm; import com.zw.platform.push.cache.ParamSendingCache; import com.zw.platform.push.cache.SendModule; import com.zw.platform.push.cache.SendTarget; import com.zw.platform.push.controller.SubscibeInfo; import com.zw.platform.push.controller.SubscibeInfoCache; import com.zw.platform.push.controller.UserCache; import com.zw.platform.util.ConstantUtil; import com.zw.platform.util.MsgUtil; import com.zw.protocol.msg.t808.T808Message; import com.zw.protocol.netty.client.manager.WebSubscribeManager; import com.zw.ws.common.PublicVariable; import com.zw.ws.entity.t808.oil.OilSensorParam; import com.zw.ws.entity.t808.oil.PeripheralMessageItem; import com.zw.ws.entity.t808.oil.SensorParam; import com.zw.ws.entity.t808.oil.T808_0x8900; import com.zw.ws.entity.t808.parameter.ParamItem; import com.zw.ws.entity.t808.parameter.T808_0x8103; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; /** * Created by jiangxiaoqiang on 2016/11/8. */ @Component public class WsOilSensorCommandService { @Autowired private ParamSendingCache paramSendingCache; /** * 油杆数据下发 */ public void oilRodSensorCompose(OilVehicleSetting vehicleSetting, Integer transNo, BindDTO vehicleInfo) { T808_0x8103 parameter = new T808_0x8103(); if (vehicleSetting != null) { parameter.setParametersCount(1); List<ParamItem> oilSensorParams = new ArrayList<>(); OilSensorParam oilSensorParam = new OilSensorParam(); String oilSensorType = vehicleSetting.getOilBoxType(); // 若邮箱type为1,则外设id为0xF341; 若为2,则外设id为0xF342 ParamItem paramItem = new ParamItem(); paramItem.setParamLength(56); if ("1".equals(oilSensorType)) { paramItem.setParamId(0xF341); } else if ("2".equals(oilSensorType)) { paramItem.setParamId(0xF342); } // 若邮箱type为1,则外设id为0x41; 若为2,则外设id为0x42 if ("1".equals(oilSensorType)) { oilSensorParam.setParamItemId(PublicVariable.OILLEVEL_SENSOR_ONE_ID); } else if ("2".equals(oilSensorType)) { oilSensorParam.setParamItemId(PublicVariable.OILLEVEL_SENSOR_OTWO_ID); } oilSensorParam.setInertiaCompEn( vehicleSetting.getCompensationCanMake() != null ? vehicleSetting.getCompensationCanMake() : 1); oilSensorParam.setRange(StringUtils.isNotBlank(vehicleSetting.getSensorLength()) ? Integer.parseInt(vehicleSetting.getSensorLength()) * 10 : 0); oilSensorParam.setSmoothing(StringUtils.isNotBlank(vehicleSetting.getFilteringFactor()) ? Integer.parseInt(vehicleSetting.getFilteringFactor()) : 2); oilSensorParam.setAutoInterval(StringUtils.isNotBlank(vehicleSetting.getAutomaticUploadTime()) ? Integer.parseInt(vehicleSetting.getAutomaticUploadTime()) : 1); oilSensorParam.setOutputCorrectionK( StringUtils.isNotBlank(vehicleSetting.getOutputCorrectionCoefficientK()) ? Integer.parseInt(vehicleSetting.getOutputCorrectionCoefficientK()) : 100); oilSensorParam.setOutputCorrectionB( StringUtils.isNotBlank(vehicleSetting.getOutputCorrectionCoefficientB()) ? Integer.parseInt(vehicleSetting.getOutputCorrectionCoefficientB()) : 100); oilSensorParam.setOilType(StringUtils.isNotBlank(vehicleSetting.getFuelOil()) ? Integer.parseInt(vehicleSetting.getFuelOil()) : 1); // 01-长方体;02-圆柱形;03-D形;04-椭圆形;05-其他 oilSensorParam.setMeasureFun(getShape( StringUtils.isNotBlank(vehicleSetting.getShape()) ? Integer.parseInt(vehicleSetting.getShape()) : 0)); oilSensorParam.setTankSize1( StringUtils.isNotBlank(vehicleSetting.getBoxLength()) ? Integer.parseInt(vehicleSetting.getBoxLength()) : 0); oilSensorParam.setTankSize2( StringUtils.isNotBlank(vehicleSetting.getBoxLength()) ? Integer.parseInt(vehicleSetting.getWidth()) : 0); oilSensorParam.setTankSize3( StringUtils.isNotBlank(vehicleSetting.getBoxLength()) ? Integer.parseInt(vehicleSetting.getHeight()) : 0); oilSensorParam.setMaxAddTime(StringUtils.isNotBlank(vehicleSetting.getAddOilTimeThreshold()) ? Integer.parseInt(vehicleSetting.getAddOilTimeThreshold()) : 0); oilSensorParam.setMaxAddOil(StringUtils.isNotBlank(vehicleSetting.getAddOilAmountThreshol()) ? Integer.parseInt(vehicleSetting.getAddOilAmountThreshol()) : 0); oilSensorParam.setMaxDelTime(StringUtils.isNotBlank(vehicleSetting.getSeepOilTimeThreshold()) ? Integer.parseInt(vehicleSetting.getSeepOilTimeThreshold()) : 0); oilSensorParam.setMaxDelOil(StringUtils.isNotBlank(vehicleSetting.getSeepOilAmountThreshol()) ? Integer.parseInt(vehicleSetting.getSeepOilAmountThreshol()) : 0); paramItem.setParamValue(oilSensorParam); oilSensorParams.add(paramItem); parameter.setParamItems(oilSensorParams); final Map<String, String> vehicleMap = RedisHelper.getHashMap( RedisKeyEnum.MONITOR_INFO.of(vehicleSetting.getVehicleId(), "deviceId", "simCardNumber")); String deviceId = vehicleMap.get("deviceId"); String simcardNumber = vehicleMap.get("simCardNumber"); //下发后需要更新外设轮询模块,调用通用应答模块的逻辑,推送用户订阅的外设轮询websocket接口 paramSendingCache.put(SystemHelper.getCurrentUsername(), transNo, simcardNumber, SendTarget.getInstance(SendModule.OIL)); //订阅推送消息 SubscibeInfo info = new SubscibeInfo(SystemHelper.getCurrentUsername(), deviceId, transNo, ConstantUtil.T808_DEVICE_GE_ACK, 1); SubscibeInfoCache.getInstance().putTable(info); info = new SubscibeInfo(SystemHelper.getCurrentUsername(), deviceId, transNo, ConstantUtil.T808_DATA_PERMEANCE_REPORT); SubscibeInfoCache.getInstance().putTable(info); paramSendingCache.put(SystemHelper.getCurrentUsername(), transNo, simcardNumber, SendTarget.getInstance(SendModule.ALARM_PARAMETER_SETTING)); T808Message message = MsgUtil.get808Message(simcardNumber, ConstantUtil.T808_SET_PARAM, transNo, parameter, vehicleInfo); WebSubscribeManager.getInstance().sendMsgToAll(message, ConstantUtil.T808_SET_PARAM, deviceId); } } public int getShape(int measureType) { int resultShape = 5; switch (measureType) { case PublicVariable.RECTANGLE: resultShape = 0x01; break; case PublicVariable.CYLINDER: resultShape = 0x02; break; case PublicVariable.DSHAPE: resultShape = 0x03; break; case PublicVariable.OVAL: resultShape = 0x04; break; case PublicVariable.OTHERSHAPE: resultShape = 0x05; break; default: break; } return resultShape; } /** * 标定下发 */ public void markDataCompose(Integer transNo, BindDTO vehicleInfo, List<FuelTankForm> fuelTankForm) { T808_0x8900<PeripheralMessageItem<SensorParam>> parameter = new T808_0x8900<>(); parameter.setType(PublicVariable.CALIBRATION_DATA); if (fuelTankForm != null && fuelTankForm.size() > 0) { parameter.setSum(fuelTankForm.size()); List<PeripheralMessageItem<SensorParam>> peripheralMessageItems = new ArrayList<>(); for (FuelTankForm fuelTank : fuelTankForm) { PeripheralMessageItem<SensorParam> per = new PeripheralMessageItem<>(); String sensorType = fuelTank.getTanktyp(); // 若邮箱type为1,则外设id为0x41; 若为2,则外设id为0x42 if ("1".equals(sensorType)) { per.setSensorID(PublicVariable.OILLEVEL_SENSOR_ONE_ID); } else if ("2".equals(sensorType)) { per.setSensorID(PublicVariable.OILLEVEL_SENSOR_OTWO_ID); } List<OilCalibrationForm> calList = fuelTank.getOilCalList(); List<SensorParam> list = new ArrayList<>(); if (calList != null && calList.size() > 0) { for (int j = 0; j < calList.size(); j++) { OilCalibrationForm oilCal = fuelTank.getOilCalList().get(j); SensorParam sensorParam = new SensorParam(); sensorParam.setHeight(Double.parseDouble(oilCal.getOilLevelHeight())); sensorParam.setSurplus(Double.parseDouble(oilCal.getOilValue())); list.add(sensorParam); } if (calList.size() < 50) { SensorParam sensorParam = new SensorParam(); sensorParam.setHeight(0xFFFFFFFF); sensorParam.setSurplus(0xFFFFFFFF); list.add(sensorParam); } per.setSensorSum(list.size()); per.setDemarcates(list); } else { per.setSensorSum(0); } peripheralMessageItems.add(per); } parameter.setSensorDatas(peripheralMessageItems); if (vehicleInfo != null) { String deviceId = vehicleInfo.getDeviceId(); String simcardNumber = vehicleInfo.getSimCardNumber(); //下发后需要更新外设轮询模块,调用通用应答模块的逻辑,推送用户订阅的外设轮询websocket接口 paramSendingCache.put(SystemHelper.getCurrentUsername(), transNo, simcardNumber, SendTarget.getInstance(SendModule.OIL)); //订阅推送消息 SubscibeInfo info = new SubscibeInfo(SystemHelper.getCurrentUsername(), deviceId, transNo, ConstantUtil.T808_DEVICE_GE_ACK, 1); SubscibeInfoCache.getInstance().putTable(info); info = new SubscibeInfo(SystemHelper.getCurrentUsername(), deviceId, transNo, ConstantUtil.T808_DATA_PERMEANCE_REPORT); SubscibeInfoCache.getInstance().putTable(info); T808Message message = MsgUtil .get808Message(simcardNumber, ConstantUtil.T808_PENETRATE_DOWN, transNo, parameter, vehicleInfo); WebSubscribeManager.getInstance().sendMsgToAll(message, ConstantUtil.T808_PENETRATE_DOWN, deviceId); } } } /** * 查询车辆位置信息 */ public void vehicleLocationQuery(Integer transNo, BindDTO bindDTO) { Objects.requireNonNull(transNo, "消息流水号不能为空"); //订阅推送消息 final String username = SystemHelper.getCurrentUsername(); Objects.requireNonNull(username, "用户名不能为空"); String deviceId = bindDTO.getDeviceId(); String deviceType = bindDTO.getDeviceType(); String simCardNumber = bindDTO.getSimCardNumber(); SubscibeInfo info = new SubscibeInfo(username, deviceId, transNo, ConstantUtil.T808_GPS_INFO_ACK); SubscibeInfoCache.getInstance().putTable(info); UserCache.getInstance().put(transNo.toString(), username); T808Message message = MsgUtil.get808Message(simCardNumber, ConstantUtil.T808_QUERY_LOCATION_COMMAND, transNo, null, deviceType); WebSubscribeManager.getInstance().sendMsgToAll(message, ConstantUtil.T808_QUERY_LOCATION_COMMAND, deviceId); } public void parametersTrace(T808_0x8202 form, Integer transNo, VehicleInfo vehicleInfo) { String deviceId = vehicleInfo.getDeviceId(); //订阅推送消息 SubscibeInfo info = new SubscibeInfo(SystemHelper.getCurrentUsername(), deviceId, transNo, ConstantUtil.T808_DEVICE_GE_ACK); SubscibeInfoCache.getInstance().putTable(info); T808Message message = MsgUtil .get808Message(vehicleInfo.getSimcardNumber(), ConstantUtil.T808_INTERIM_TRACE, transNo, form, vehicleInfo); WebSubscribeManager.getInstance().sendMsgToAll(message, ConstantUtil.T808_INTERIM_TRACE, deviceId); } }
30,014
https://github.com/gladguy/js-algorand-sdk/blob/master/tests/cucumber/docker/sdk.py
Github Open Source
Open Source
MIT
null
js-algorand-sdk
gladguy
Python
Code
62
368
#!/usr/bin/env python3 import subprocess import sys default_dirs = { 'features_dir': '/opt/js-algorand-sdk/tests/cucumber/features', 'source': '/opt/js-algorand-sdk', 'docker': '/opt/js-algorand-sdk/tests/cucumber/docker', 'steps': '/opt/js-algorand-sdk/tests/cucumber/steps' } def setup_sdk(): """ Setup js cucumber environment. """ subprocess.check_call(['npm install --silent'], shell=True, cwd=default_dirs['source']) subprocess.check_call(['npm install %s --silent' % default_dirs['source']], shell=True) def test_sdk(): sys.stdout.flush() subprocess.check_call(['node_modules/.bin/cucumber-js %s --require %s/*' % (default_dirs["features_dir"], default_dirs["steps"])], shell=True) # subprocess.check_call(['mvn test -Dcucumber.options="--tags @template"'], shell=True, cwd=sdk.default_dirs['cucumber']) # subprocess.check_call(['mvn test -Dcucumber.options="/opt/sdk-testing/features/template.feature"'], shell=True, cwd=sdk.default_dirs['cucumber'])
18,821
https://github.com/dmba/android-boilerplate/blob/master/app-data/src/release/java/me/dmba/mychecks/data/di/DevDataModule.kt
Github Open Source
Open Source
MIT
null
android-boilerplate
dmba
Kotlin
Code
50
197
package me.dmba.mychecks.data.di import dagger.Module import dagger.Provides import io.reactivex.Flowable import me.dmba.mychecks.common.scopes.ForApplication import me.dmba.mychecks.data.source.remote.ChecksApi import me.dmba.mychecks.data.source.remote.model.CheckListResponse /** * Created by dmba on 6/8/18. */ @Module internal object DevDataModule { @Provides @JvmStatic @ForApplication internal fun provideChecksApi(): ChecksApi = object : ChecksApi { override fun getAll(): Flowable<CheckListResponse> { //TODO return Flowable.empty() } } }
10,308
https://github.com/zyhfish/ClientDependency/blob/master/ClientDependency.Web.Test/Pages/Master.Master.designer.cs
Github Open Source
Open Source
MS-PL
2,020
ClientDependency
zyhfish
C#
Code
334
893
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ClientDependency.Web.Test.Pages { public partial class Master { /// <summary> /// head control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder head; /// <summary> /// CssPlaceHolder control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder CssPlaceHolder; /// <summary> /// Loader control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ClientDependency.Core.Controls.ClientDependencyLoader Loader; /// <summary> /// CssInclude1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ClientDependency.Core.Controls.CssInclude CssInclude1; /// <summary> /// CssInclude2 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ClientDependency.Core.Controls.CssInclude CssInclude2; /// <summary> /// Header1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ClientDependency.Web.Test.Controls.Header Header1; /// <summary> /// Sidebar1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ClientDependency.Web.Test.Controls.Sidebar Sidebar1; /// <summary> /// ContentPlaceHolder1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1; /// <summary> /// Footer1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::ClientDependency.Web.Test.Controls.Footer Footer1; /// <summary> /// JavaScriptPlaceHolder control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.PlaceHolder JavaScriptPlaceHolder; } }
50,797
https://github.com/FoundationDB/fdb-record-layer/blob/master/fdb-record-layer-core/src/main/java/com/apple/foundationdb/record/query/plan/cascades/properties/NormalizedResidualPredicateProperty.java
Github Open Source
Open Source
Apache-2.0
2,023
fdb-record-layer
FoundationDB
Java
Code
421
1,387
/* * NormalizedResidualPredicateProperty.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2019 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apple.foundationdb.record.query.plan.cascades.properties; import com.apple.foundationdb.annotation.API; import com.apple.foundationdb.record.query.plan.cascades.ExpressionProperty; import com.apple.foundationdb.record.query.plan.cascades.ExpressionRef; import com.apple.foundationdb.record.query.plan.cascades.expressions.RelationalExpression; import com.apple.foundationdb.record.query.plan.cascades.expressions.RelationalExpressionVisitorWithDefaults; import com.apple.foundationdb.record.query.plan.cascades.expressions.RelationalExpressionWithPredicates; import com.apple.foundationdb.record.query.plan.cascades.predicates.AndPredicate; import com.apple.foundationdb.record.query.plan.cascades.predicates.OrPredicate; import com.apple.foundationdb.record.query.plan.cascades.predicates.QueryPredicate; import com.apple.foundationdb.record.query.plan.planning.BooleanPredicateNormalizer; import com.apple.foundationdb.record.query.plan.plans.RecordQueryUnionOnValuesPlan; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import javax.annotation.Nonnull; import java.util.List; import java.util.Objects; /** * This property collects a {@link QueryPredicate} that represents the entirety of all accumulated residual predicates. * This predicate cannot be applied in any meaningful way to a stream of data, but it can be reasoned over using boolean * algebra. In addition, this approach also allows us to unify set operations such a UNION and INTERSECTION with their * boolean counterparts OR and AND. * One particular use of the collected residual predicate is to derive the number of effective boolean factors of its * CNF which is a direct measure of the number of residual filters that have to be applied and therefore its static * filter factor. Note that such a number can always be computed without actually materializing the CNF. */ @API(API.Status.EXPERIMENTAL) public class NormalizedResidualPredicateProperty implements ExpressionProperty<QueryPredicate>, RelationalExpressionVisitorWithDefaults<QueryPredicate> { @Nonnull private static final NormalizedResidualPredicateProperty INSTANCE = new NormalizedResidualPredicateProperty(); @Nonnull @Override public QueryPredicate visitRecordQueryUnionOnValuesPlan(@Nonnull final RecordQueryUnionOnValuesPlan unionPlan) { final var predicatesFromQuantifiers = visitQuantifiers(unionPlan).stream() .filter(Objects::nonNull) .filter(predicate -> !predicate.isTautology()) .collect(ImmutableList.toImmutableList()); return OrPredicate.orOrTrue(predicatesFromQuantifiers); } @Nonnull @Override public QueryPredicate evaluateAtExpression(@Nonnull RelationalExpression expression, @Nonnull List<QueryPredicate> childResults) { final var resultPredicatesBuilder = ImmutableList.<QueryPredicate>builder(); childResults.stream() .filter(Objects::nonNull) .filter(predicate -> !predicate.isTautology()) .forEach(resultPredicatesBuilder::add); if (expression instanceof RelationalExpressionWithPredicates) { ((RelationalExpressionWithPredicates)expression).getPredicates() .stream() .filter(predicate -> !predicate.isTautology()) .forEach(resultPredicatesBuilder::add); } return AndPredicate.andOrTrue(resultPredicatesBuilder.build()); } @Nonnull @Override public QueryPredicate evaluateAtRef(@Nonnull ExpressionRef<? extends RelationalExpression> ref, @Nonnull List<QueryPredicate> memberResults) { Verify.verify(memberResults.size() == 1); return Iterables.getOnlyElement(memberResults); } @Nonnull public static QueryPredicate evaluate(ExpressionRef<? extends RelationalExpression> ref) { return Verify.verifyNotNull(ref.acceptPropertyVisitor(INSTANCE)); } @Nonnull public static QueryPredicate evaluate(@Nonnull RelationalExpression expression) { return Verify.verifyNotNull(expression.acceptPropertyVisitor(INSTANCE)); } public static long countNormalizedConjuncts(@Nonnull RelationalExpression expression) { final var magicPredicate = evaluate(expression); return magicPredicate.isTautology() ? 0 : BooleanPredicateNormalizer .getDefaultInstanceForCnf() .getMetrics(magicPredicate) .getNormalFormFullSize(); } }
50,152
https://github.com/Kndgy/echthra-bot/blob/master/src/commands/misc/devide.js
Github Open Source
Open Source
MIT
null
echthra-bot
Kndgy
JavaScript
Code
33
100
module.exports = { name : 'devide', description: 'devide integer given as arguments', aliases:['divide'], execute(message, args){ const numArgs = args.map(x => parseFloat(x)); const devide = numArgs.reduce((counter, x) => counter /=x); message.channel.send(`total ${devide}`) } }
38,529
https://github.com/JustTaPo/blobber2/blob/master/client/src/blobs/mainPlayer.js
Github Open Source
Open Source
MIT
2,018
blobber2
JustTaPo
JavaScript
Code
237
740
import React, { Component } from 'react' import { UserInput, Directions } from '../eventSources/userInput' import { GameState } from '../eventSources/gameState' import { Blob, Vector } from './blob' export class MainPlayer extends Component { constructor () { super() this.state = { id: 0, location: Vector.create(), lookDir: Vector.create(), size: 0. } } componentDidMount () { this.subscriptions = [ GameState.get('initialize').subscribe(this.initialize) ] } componentWillUnmount () { this.subscriptions.forEach(s => s.unsubscribe()) } initialize = data => { this.setState(prevState => ({ id: data.id, location: data.location, size: data.size })) this.subscriptions.push( GameState.get('move', data.id) .map(event => event.location) .subscribe(this.move), UserInput.mouseMove().subscribe(this.mouseHandle(data.id)), UserInput.mouseDown().subscribe(this.clickHandle(data.id)), UserInput.keyPress().subscribe(this.handleKeyPress(data.id)) ) } //User Input Handlers handleKeyPress = id => event => { const newDirection = Vector.create() event.keyCombo().forEach(keyCode => { if (keyCode in Directions) { newDirection.x = newDirection.x + Directions[keyCode].x newDirection.y = newDirection.y + Directions[keyCode].y } }) if (newDirection !== this.location) { const mag = Math.sqrt((newDirection.x * newDirection.x) + (newDirection.y * newDirection.y)) newDirection.x = newDirection.x / mag newDirection.y = newDirection.y / mag GameState.notify('updateDirection', {id: id, direction: newDirection}) } } mouseHandle = id => location => { const newLookDirection = Vector.create() const mag = Math.sqrt((location.x * location.x) + (location.y * location.y)) newLookDirection.x = location.x / mag newLookDirection.y = location.y / mag GameState.notify('mouseMove', {id: id, direction: newLookDirection}) } clickHandle = id => location => { //pass } //Server Command Handlers move = newPosition => { this.setState(prevState => ({location: newPosition})) } msg = message => { console.log(message) } render () { return ( <Blob location={this.state.location} size={this.state.size} top={true}/> ) } }
46,267
https://github.com/Xioer/php-structures/blob/master/LeetCode/Linked/Linked0202.php
Github Open Source
Open Source
Apache-2.0
null
php-structures
Xioer
PHP
Code
125
347
<?php class ListNode { public $val = 0; public $next = null; function __construct($val) { $this->val = $val; } } /** * 返回倒数第 k 个节点 * Class Linked0202 */ class Linked0202 { /** * @param ListNode $head * @param Integer $k * @return Integer */ function kthToLast($head, $k) { //计算链表的长度 - 然后找长度 - $k的链表数据 // $cur = $head; // $index = 0; // // while ($cur != null){ // $cur = $cur->next; // $index++; // } // $cur = $head; // for ($i = 0; $i < $index - $k; $i++){ // $cur = $cur->next; // } // return $cur->val; //双指针移动 $p = $head; for($i=0; $i<$k; $i++){ $p = $p->next; } while($p != null){ $p = $p->next; $head = $head->next; } return $head->val; } }
15,167
https://github.com/bailingzhl/rothui/blob/master/wow5.0/oUF_SquarePortrait/core.lua
Github Open Source
Open Source
MIT
2,022
rothui
bailingzhl
Lua
Code
159
609
--addonName and namespace local addonName, ns = ... --container local core = CreateFrame("Frame") ns.core = core --------------------------------------------- -- FUNCTIONS --------------------------------------------- function core:CreateDropShadow(parent,edgeFile,edgeSize,padding) if parent.dropShadow then return end edgeFile = edgeFile or "" edgeSize = edgeSize or 8 padding = padding or 8 parent.dropShadow = CreateFrame("Frame", nil, parent) parent.dropShadow:SetPoint("TOPLEFT",-padding,padding) parent.dropShadow:SetPoint("BOTTOMRIGHT",padding,-padding) parent.dropShadow:SetBackdrop({ bgFile = nil, edgeFile = edgeFile, tile = false, tileSize = 16, edgeSize = edgeSize, insets = { left = 0, right = 0, top = 0, bottom = 0, }, }) local mt = getmetatable(parent).__index mt.SetDropShadowColor = function(self,r,g,b,a) self.dropShadow:SetBackdropBorderColor(r or 1, g or 1, b or 1, a or 1) end end --fontstring func function core:NewFontString(parent,family,size,outline,layer) local fs = parent:CreateFontString(nil, layer or "OVERLAY") fs:SetFont(family,size,outline) fs:SetShadowOffset(0, -2) fs:SetShadowColor(0,0,0,1) return fs end --------------------------------------------- -- TAGS --------------------------------------------- --unit name tag oUF.Tags.Methods["square_portrait:name"] = function(unit) local name = oUF.Tags.Methods["name"](unit) return "|cffffffff"..name.."|r" end oUF.Tags.Events["square_portrait:name"] = "UNIT_NAME_UPDATE UNIT_CONNECTION" --unit health tag oUF.Tags.Methods["square_portrait:health"] = function(unit) local perhp = oUF.Tags.Methods["perhp"](unit) return "|cffffffff"..perhp.."|r" end oUF.Tags.Events["square_portrait:health"] = "UNIT_HEALTH_FREQUENT UNIT_MAXHEALTH"
26,600
https://github.com/mpetrun5/vedran/blob/master/internal/controllers/metrics_test.go
Github Open Source
Open Source
Apache-2.0
null
vedran
mpetrun5
Go
Code
601
3,285
package controllers import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "testing" "time" "github.com/NodeFactoryIo/vedran/internal/auth" "github.com/NodeFactoryIo/vedran/internal/models" "github.com/NodeFactoryIo/vedran/internal/repositories" mocks "github.com/NodeFactoryIo/vedran/mocks/repositories" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" ) func TestApiController_SaveMetricsHandler(t *testing.T) { tests := []struct { name string metricsRequest interface{} nodeId string httpStatus int // NodeRepo.FindByID nodeRepoIsNodeOnCooldownReturns bool nodeRepoIsNodeOnCooldownError error nodeRepoIsNodeOnNumOfCalls int // NodeRepo.AddNodeToActive nodeRepoAddNodeToActiveError error nodeRepoAddNodeToActiveNumOfCalls int // NodeRepo.IsNodeActive nodeRepoIsNodeActiveReturn bool // MetricsRepo.FindByID metricsRepoFindByIDError error metricsRepoFindByIDReturn *models.Metrics metricsRepoFindByIDNumOfCalls int // MetricsRepo.GetLatestBlockMetrics metricsRepoGetLatestBlockMetricsError error metricsRepoGetLatestBlockMetricsReturn *models.LatestBlockMetrics metricsRepoGetLatestBlockMetricsNumOfCalls int // MetricsRepo.Save metricsRepoSaveError error metricsRepoSaveNumOfCalls int }{ { name: "Valid metrics save request and node should be added to active nodes", metricsRequest: MetricsRequest{ PeerCount: 0, BestBlockHeight: 1000, FinalizedBlockHeight: 995, ReadyTransactionCount: 0, }, nodeId: "1", httpStatus: http.StatusOK, // NodeRepo.FindByID nodeRepoIsNodeOnCooldownReturns: false, nodeRepoIsNodeOnCooldownError: nil, nodeRepoIsNodeOnNumOfCalls: 1, // NodeRepo.AddNodeToActive nodeRepoAddNodeToActiveError: nil, nodeRepoAddNodeToActiveNumOfCalls: 1, // NodeRepo.IsNodeActive nodeRepoIsNodeActiveReturn: false, // MetricsRepo.FindByID metricsRepoFindByIDReturn: &models.Metrics{ NodeId: "1", PeerCount: 0, BestBlockHeight: 1000, FinalizedBlockHeight: 995, ReadyTransactionCount: 0, }, metricsRepoFindByIDError: nil, metricsRepoFindByIDNumOfCalls: 1, // MetricsRepo.GetLatestBlockMetrics metricsRepoGetLatestBlockMetricsReturn: &models.LatestBlockMetrics{ BestBlockHeight: 1001, FinalizedBlockHeight: 998, }, metricsRepoGetLatestBlockMetricsError: nil, metricsRepoGetLatestBlockMetricsNumOfCalls: 1, // MetricsRepo.Save metricsRepoSaveError: nil, metricsRepoSaveNumOfCalls: 1, }, { name: "Valid metrics save request and node should not be added to active nodes as it already is in active", metricsRequest: MetricsRequest{ PeerCount: 0, BestBlockHeight: 1000, FinalizedBlockHeight: 995, ReadyTransactionCount: 0, }, nodeId: "1", httpStatus: http.StatusOK, // NodeRepo.FindByID nodeRepoIsNodeOnCooldownReturns: false, nodeRepoIsNodeOnCooldownError: nil, nodeRepoIsNodeOnNumOfCalls: 0, // NodeRepo.AddNodeToActive nodeRepoAddNodeToActiveError: nil, nodeRepoAddNodeToActiveNumOfCalls: 0, // NodeRepo.IsNodeActive nodeRepoIsNodeActiveReturn: true, // MetricsRepo.FindByID metricsRepoFindByIDReturn: nil, metricsRepoFindByIDError: nil, metricsRepoFindByIDNumOfCalls: 0, // MetricsRepo.GetLatestBlockMetrics metricsRepoGetLatestBlockMetricsReturn: nil, metricsRepoGetLatestBlockMetricsError: nil, metricsRepoGetLatestBlockMetricsNumOfCalls: 0, // MetricsRepo.Save metricsRepoSaveError: nil, metricsRepoSaveNumOfCalls: 1, }, { name: "Valid metrics save request and node should not be added to active nodes as it is penalized", metricsRequest: MetricsRequest{ PeerCount: 10, BestBlockHeight: 100, FinalizedBlockHeight: 100, ReadyTransactionCount: 10, }, nodeId: "1", httpStatus: http.StatusOK, // NodeRepo.FindByID nodeRepoIsNodeOnCooldownReturns: true, nodeRepoIsNodeOnCooldownError: nil, nodeRepoIsNodeOnNumOfCalls: 1, // NodeRepo.AddNodeToActive nodeRepoAddNodeToActiveError: nil, nodeRepoAddNodeToActiveNumOfCalls: 0, // NodeRepo.IsNodeActive nodeRepoIsNodeActiveReturn: false, // MetricsRepo.FindByID metricsRepoFindByIDReturn: nil, metricsRepoFindByIDError: nil, metricsRepoFindByIDNumOfCalls: 0, // MetricsRepo.GetLatestBlockMetrics metricsRepoGetLatestBlockMetricsReturn: nil, metricsRepoGetLatestBlockMetricsError: nil, metricsRepoGetLatestBlockMetricsNumOfCalls: 0, // MetricsRepo.Save metricsRepoSaveError: nil, metricsRepoSaveNumOfCalls: 1, }, { name: "Valid metrics save request and node should not be added to active nodes as metrics are invalid", metricsRequest: MetricsRequest{ PeerCount: 0, BestBlockHeight: 1000, FinalizedBlockHeight: 995, ReadyTransactionCount: 0, }, nodeId: "1", httpStatus: http.StatusOK, // NodeRepo.FindByID nodeRepoIsNodeOnCooldownReturns: false, nodeRepoIsNodeOnCooldownError: nil, nodeRepoIsNodeOnNumOfCalls: 1, // NodeRepo.AddNodeToActive nodeRepoAddNodeToActiveError: nil, nodeRepoAddNodeToActiveNumOfCalls: 0, // NodeRepo.IsNodeActive nodeRepoIsNodeActiveReturn: false, // MetricsRepo.FindByID metricsRepoFindByIDReturn: &models.Metrics{ NodeId: "1", PeerCount: 0, BestBlockHeight: 1000, FinalizedBlockHeight: 995, ReadyTransactionCount: 0, }, metricsRepoFindByIDError: nil, metricsRepoFindByIDNumOfCalls: 1, // MetricsRepo.GetLatestBlockMetrics metricsRepoGetLatestBlockMetricsReturn: &models.LatestBlockMetrics{ BestBlockHeight: 1021, FinalizedBlockHeight: 1017, }, metricsRepoGetLatestBlockMetricsError: nil, metricsRepoGetLatestBlockMetricsNumOfCalls: 1, // MetricsRepo.Save metricsRepoSaveError: nil, metricsRepoSaveNumOfCalls: 1, }, { name: "Invalid metrics save request", metricsRequest: struct{ PeerCount string }{PeerCount: "10"}, nodeId: "1", httpStatus: http.StatusBadRequest, }, { name: "Database fails on saving metrics", metricsRequest: MetricsRequest{ PeerCount: 10, BestBlockHeight: 100, FinalizedBlockHeight: 100, ReadyTransactionCount: 10, }, nodeId: "1", httpStatus: http.StatusInternalServerError, metricsRepoSaveNumOfCalls: 1, metricsRepoSaveError: errors.New("db error"), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { timestamp := time.Now() // create mock controller pingRepoMock := mocks.PingRepository{} recordRepoMock := mocks.RecordRepository{} nodeRepoMock := mocks.NodeRepository{} nodeRepoMock.On("IsNodeOnCooldown", test.nodeId).Return( test.nodeRepoIsNodeOnCooldownReturns, test.nodeRepoIsNodeOnCooldownError, ) nodeRepoMock.On("AddNodeToActive", test.nodeId).Return( test.nodeRepoAddNodeToActiveError, ) nodeRepoMock.On("IsNodeActive", test.nodeId).Return( test.nodeRepoIsNodeActiveReturn, ) metricsRepoMock := mocks.MetricsRepository{} metricsRepoMock.On("FindByID", test.nodeId).Return( test.metricsRepoFindByIDReturn, test.metricsRepoFindByIDError, ) metricsRepoMock.On("GetLatestBlockMetrics").Return( test.metricsRepoGetLatestBlockMetricsReturn, test.metricsRepoGetLatestBlockMetricsError, ) metricsRepoMock.On("Save", mock.Anything).Return( test.metricsRepoSaveError, ) downtimeRepoMock := mocks.DowntimeRepository{} apiController := NewApiController(false, repositories.Repos{ NodeRepo: &nodeRepoMock, PingRepo: &pingRepoMock, MetricsRepo: &metricsRepoMock, RecordRepo: &recordRepoMock, DowntimeRepo: &downtimeRepoMock, }, nil, "") handler := http.HandlerFunc(apiController.SaveMetricsHandler) // create test request rb, _ := json.Marshal(test.metricsRequest) req, _ := http.NewRequest("POST", "/api/v1/metrics", bytes.NewReader(rb)) c := &auth.RequestContext{ NodeId: test.nodeId, Timestamp: timestamp, } ctx := context.WithValue(req.Context(), auth.RequestContextKey, c) req = req.WithContext(ctx) rr := httptest.NewRecorder() // invoke test request handler.ServeHTTP(rr, req) // asserts assert.Equal(t, test.httpStatus, rr.Code, fmt.Sprintf("Response status code should be %d", test.httpStatus)) nodeRepoMock.AssertNumberOfCalls(t, "IsNodeOnCooldown", test.nodeRepoIsNodeOnNumOfCalls) nodeRepoMock.AssertNumberOfCalls(t, "AddNodeToActive", test.nodeRepoAddNodeToActiveNumOfCalls) metricsRepoMock.AssertNumberOfCalls(t, "FindByID", test.metricsRepoFindByIDNumOfCalls) metricsRepoMock.AssertNumberOfCalls(t, "GetLatestBlockMetrics", test.metricsRepoGetLatestBlockMetricsNumOfCalls) metricsRepoMock.AssertNumberOfCalls(t, "Save", test.metricsRepoSaveNumOfCalls) }) } }
4,121
https://github.com/SteveGreatApe/RIBs/blob/master/libraries/rib-base/src/test/java/com/badoo/ribs/clienthelper/childaware/ChildAwareImplTest.kt
Github Open Source
Open Source
Apache-2.0
null
RIBs
SteveGreatApe
Kotlin
Code
841
2,441
package com.badoo.ribs.clienthelper.childaware import android.os.Parcelable import com.badoo.ribs.builder.Builder import com.badoo.ribs.core.Node import com.badoo.ribs.core.Rib import com.badoo.ribs.core.customisation.RibCustomisationDirectoryImpl import com.badoo.ribs.core.modality.AncestryInfo import com.badoo.ribs.core.modality.BuildContext import com.badoo.ribs.core.modality.BuildParams import com.badoo.ribs.core.view.RibView import com.badoo.ribs.routing.Routing import kotlinx.android.parcel.Parcelize import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test class ChildAwareImplTest { private val registry = ChildAwareImpl() private val rootNode = createViaBuilder(isRoot = true) { buildContext -> Node<RibView>( buildParams = BuildParams(payload = null, buildContext = buildContext), viewFactory = null, plugins = listOf(registry), ) }.apply { onCreate() } // region Single @Test fun `whenChildBuilt is invoked if registered before onChildBuilt`() { var capturedNode: Rib? = null registry.whenChildBuilt<Child1> { _, child -> capturedNode = child } val child1 = createChild1(attach = false) assertEquals(child1, capturedNode) } @Test fun `whenChildBuilt is invoked if registered after onChildBuilt`() { val child1 = createChild1() var capturedNode: Rib? = null registry.whenChildBuilt<Child1> { _, child -> capturedNode = child } assertEquals(child1, capturedNode) } @Test fun `whenChildAttached is invoked if registered before onChildAttached`() { var capturedNode: Rib? = null registry.whenChildAttached<Child1> { _, child -> capturedNode = child } val child1 = createChild1() assertEquals(child1, capturedNode) } @Test fun `whenChildAttached is invoked if registered after onChildAttached`() { val child1 = createChild1() var capturedNode: Rib? = null registry.whenChildAttached<Child1> { _, child -> capturedNode = child } assertEquals(child1, capturedNode) } @Test fun `every whenChildBuilt is invoked`() { var capturedNode1: Rib? = null var capturedNode2: Rib? = null registry.whenChildBuilt<Child1> { _, child -> capturedNode1 = child } registry.whenChildBuilt<Child1> { _, child -> capturedNode2 = child } val child1 = createChild1(attach = false) assertEquals(child1, capturedNode1) assertEquals(child1, capturedNode2) } @Test fun `whenChildBuilt is invoked multiple times for each instance`() { val child1 = createChild1() val child2 = createChild1() val capturedNodes = ArrayList<Rib>() registry.whenChildBuilt<Child1> { _, child -> capturedNodes += child } assertEquals(listOf(child1, child2), capturedNodes) } @Test fun `whenChildAttached is not invoked for unrelated child`() { createChild1() var capturedNode: Rib? = null registry.whenChildAttached<Child2> { _, child -> capturedNode = child } assertNull(capturedNode) } // endregion // region Double @Test fun `whenChildrenBuilt is invoked if registered before onChildBuilt`() { val capturedNodes = ArrayList<Rib>() registry.whenChildrenBuilt<Child1, Child2> { _, c1, c2 -> capturedNodes += c1 capturedNodes += c2 } val child1 = createChild1() val child2 = createChild2(attach = false) assertEquals(listOf(child1, child2), capturedNodes) } @Test fun `whenChildrenBuilt is invoked if registered after onChildBuilt`() { val child1 = createChild1() val child2 = createChild2() val capturedNodes = ArrayList<Rib>() registry.whenChildrenBuilt<Child1, Child2> { _, c1, c2 -> capturedNodes += c1 capturedNodes += c2 } assertEquals(listOf(child1, child2), capturedNodes) } @Test fun `whenChildrenAttached is invoked if registered before onChildAttached`() { val capturedNodes = ArrayList<Rib>() registry.whenChildrenAttached<Child1, Child2> { _, c1, c2 -> capturedNodes += c1 capturedNodes += c2 } val child1 = createChild1() val child2 = createChild2() assertEquals(listOf(child1, child2), capturedNodes) } @Test fun `whenChildrenAttached is invoked if registered after onChildAttached`() { val child1 = createChild1() val child2 = createChild2() val capturedNodes = ArrayList<Rib>() registry.whenChildrenAttached<Child1, Child2> { _, c1, c2 -> capturedNodes += c1 capturedNodes += c2 } assertEquals(listOf(child1, child2), capturedNodes) } @Test fun `whenChildrenAttached is not invoked for unrelated children`() { createChild1() createChild3() val capturedNodes = ArrayList<Rib>() registry.whenChildrenAttached<Child1, Child2> { _, c1, c2 -> capturedNodes += c1 capturedNodes += c2 } assertTrue(capturedNodes.isEmpty()) } @Test fun `whenChildrenAttached is invoked multiple times for each pair of children`() { val child11 = createChild1() val child12 = createChild1() val child21 = createChild2() val child22 = createChild2() val capturedNodes = ArrayList<Pair<Rib, Rib>>() registry.whenChildrenAttached<Child1, Child2> { _, child1, child2 -> capturedNodes += child1 to child2 } assertEquals( listOf(child11 to child21, child11 to child22, child12 to child21, child12 to child22), capturedNodes ) } @Test fun `whenChildrenAttached is invoked properly for same class connections`() { val child1 = createChild1() val child2 = createChild1() val child3 = createChild1() val capturedNodes = ArrayList<Pair<Rib, Rib>>() registry.whenChildrenAttached<Child1, Child1> { _, c1, c2 -> capturedNodes += c1 to c2 } assertEquals( listOf(child1 to child2, child1 to child3, child2 to child3), capturedNodes ) } // endregion // region Setup private fun createChild1(attach: Boolean = true) = createViaBuilder(attach = attach) { Child1Node(it) } private fun createChild2(attach: Boolean = true) = createViaBuilder(attach = attach) { Child2Node(it) } private fun createChild3(attach: Boolean = true) = createViaBuilder(attach = attach) { Child3Node(it) } private fun <T : Node<*>> createViaBuilder( isRoot: Boolean = false, attach: Boolean = true, factory: (BuildContext) -> T ): T = object : Builder<Nothing?, T>() { override fun build(buildParams: BuildParams<Nothing?>): T = factory(buildParams.buildContext) }.build( buildContext = BuildContext( ancestryInfo = if (isRoot) { AncestryInfo.Root } else { AncestryInfo.Child(rootNode, Routing(Configuration)) }, savedInstanceState = null, customisations = RibCustomisationDirectoryImpl(), ), payload = null ).also { if (!isRoot && attach) { rootNode.attachChildNode(it) } } @Parcelize object Configuration : Parcelable interface Child1 : Rib class Child1Node( buildContext: BuildContext, ) : Node<RibView>( buildParams = BuildParams(payload = null, buildContext = buildContext), viewFactory = null, ), Child1 { override fun toString(): String = "${this::class.simpleName}@${hashCode()}" } interface Child2 : Rib class Child2Node( buildContext: BuildContext, ) : Node<RibView>( buildParams = BuildParams(payload = null, buildContext = buildContext), viewFactory = null, ), Child2 { override fun toString(): String = "${this::class.simpleName}@${hashCode()}" } interface Child3 : Rib class Child3Node( buildContext: BuildContext, ) : Node<RibView>( buildParams = BuildParams(payload = null, buildContext = buildContext), viewFactory = null, ), Child3 { override fun toString(): String = "${this::class.simpleName}@${hashCode()}" } // endregion }
33,372
https://github.com/evanmok2401/Makanbook/blob/master/src/test/java/seedu/address/storage/XmlAdaptedUserReviewTest.java
Github Open Source
Open Source
MIT
null
Makanbook
evanmok2401
Java
Code
213
1,074
package seedu.address.storage; import static org.junit.Assert.assertEquals; import static seedu.address.logic.commands.CommandTestUtil.VALID_USER_REVIEW; import static seedu.address.storage.XmlAdaptedUserReview.MISSING_FIELD_MESSAGE_FORMAT; import org.junit.Test; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.restaurant.Rating; import seedu.address.model.restaurant.WrittenReview; import seedu.address.model.user.Username; import seedu.address.testutil.Assert; public class XmlAdaptedUserReviewTest { private static final String INVALID_RATING = "50"; private static final String INVALID_USERNAME = " "; private static final String INVALID_WRITTEN_REVIEW = " "; private static final String VALID_RATING = Integer.toString(VALID_USER_REVIEW.getRating()); private static final String VALID_USERNAME = VALID_USER_REVIEW.getUsername(); private static final String VALID_WRITTEN_REVIEW = VALID_USER_REVIEW.getWrittenReview(); @Test public void toModelType_validUserReviews() throws Exception { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview(VALID_USER_REVIEW); assertEquals(VALID_USER_REVIEW, userReview.toModelType()); } @Test public void toModelType_invalidRating_throwsIllegalValueException() { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview(INVALID_RATING, VALID_USERNAME, VALID_WRITTEN_REVIEW); String expectedMessage = Rating.MESSAGE_RATING_CONSTRAINTS; Assert.assertThrows(IllegalValueException.class, expectedMessage, userReview::toModelType); } @Test public void toModelType_nullRating_throwsIllegalValueException() { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview( null, VALID_USERNAME, VALID_WRITTEN_REVIEW); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, Rating.class.getSimpleName()); Assert.assertThrows(IllegalValueException.class, expectedMessage, userReview::toModelType); } @Test public void toModelType_invalidUsername_throwsIllegalValueException() { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview(VALID_RATING, INVALID_USERNAME, VALID_WRITTEN_REVIEW); String expectedMessage = Username.MESSAGE_USERNAME_CONSTRAINTS; Assert.assertThrows(IllegalValueException.class, expectedMessage, userReview::toModelType); } @Test public void toModelType_nullUsername_throwsIllegalValueException() { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview( VALID_RATING, null, VALID_WRITTEN_REVIEW); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, Username.class.getSimpleName()); Assert.assertThrows(IllegalValueException.class, expectedMessage, userReview::toModelType); } @Test public void toModelType_invalidWrittenReview_throwsIllegalValueException() { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview(VALID_RATING, VALID_USERNAME, INVALID_WRITTEN_REVIEW); String expectedMessage = WrittenReview.MESSAGE_REVIEW_CONSTRAINTS; Assert.assertThrows(IllegalValueException.class, expectedMessage, userReview::toModelType); } @Test public void toModelType_nullWrittenReview_throwsIllegalValueException() { XmlAdaptedUserReview userReview = new XmlAdaptedUserReview( VALID_RATING, VALID_USERNAME, null); String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, WrittenReview.class.getSimpleName()); Assert.assertThrows(IllegalValueException.class, expectedMessage, userReview::toModelType); } }
26,547
https://github.com/pgu/data-prep/blob/master/dataprep-backend-common/src/main/java/org/talend/dataprep/transformation/pipeline/node/LimitNode.java
Github Open Source
Open Source
Apache-2.0
2,018
data-prep
pgu
Java
Code
220
585
// ============================================================================ // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // https://github.com/Talend/data-prep/blob/master/LICENSE // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataprep.transformation.pipeline.node; import static org.slf4j.LoggerFactory.getLogger; import org.slf4j.Logger; import org.talend.dataprep.api.dataset.RowMetadata; import org.talend.dataprep.api.dataset.row.DataSetRow; import org.talend.dataprep.transformation.pipeline.Node; /** * Node that limit input. * When the input limit received is reached, a callback can be triggered. */ public class LimitNode extends BasicNode { /** This class' logger. */ private static final Logger LOGGER = getLogger(LimitNode.class); private int count = 0; private final long limit; private final Runnable callback; public LimitNode(final long limit) { this(limit, null); LOGGER.trace("Limit set to {}", limit); } public LimitNode(final long limit, final Runnable callback) { this.limit = limit; this.callback = callback; } @Override public void receive(final DataSetRow row, final RowMetadata metadata) { if (count >= limit) { return; } super.receive(row, metadata); increment(); } @Override public void receive(final DataSetRow[] rows, final RowMetadata[] metadatas) { if (count >= limit) { return; } super.receive(rows, metadatas); increment(); } private void increment() { if (++count == limit && callback != null) { LOGGER.debug("limit {} reached", limit); callback.run(); } } @Override public Node copyShallow() { return new LimitNode(limit, callback); } }
45,826
https://github.com/ericbai/textup-frontend/blob/master/tests/unit/utils/photo-test.js
Github Open Source
Open Source
Apache-2.0
2,019
textup-frontend
ericbai
JavaScript
Code
843
2,912
import * as ImageCompression from 'npm:browser-image-compression'; // needs wildward to override default import import Constants from 'textup-frontend/constants'; import Ember from 'ember'; import PhotoUtils from 'textup-frontend/utils/photo'; import sinon from 'sinon'; import { mockValidMediaImage } from 'textup-frontend/tests/helpers/utilities'; import { moduleFor, test } from 'ember-qunit'; const { RSVP, typeOf, run } = Ember; let overallStub, compressionStub, dataUrlStub, loadImageStub; let compressionReturnVal, dataUrlReturnVal, loadImageReturnVal; moduleFor('util:photo', 'Unit | Utility | photo', { needs: ['model:media-element', 'model:media-element-version'], beforeEach() { compressionStub = sinon.stub(); dataUrlStub = sinon.stub(); loadImageStub = sinon.stub(); compressionStub.callsFake(() => compressionReturnVal); dataUrlStub.callsFake(() => new RSVP.Promise(resolve => resolve(dataUrlReturnVal))); loadImageStub.callsFake(() => new RSVP.Promise(resolve => resolve(loadImageReturnVal))); overallStub = sinon.stub(ImageCompression, 'default').get(() => { compressionStub.getDataUrlFromFile = dataUrlStub; compressionStub.loadImage = loadImageStub; return compressionStub; }); }, afterEach() { overallStub.restore(); }, }); test('whether or not an event has files', function(assert) { assert.notOk(PhotoUtils.eventHasFiles()); assert.notOk(PhotoUtils.eventHasFiles(null)); assert.notOk(PhotoUtils.eventHasFiles([])); assert.notOk(PhotoUtils.eventHasFiles('hi')); assert.notOk(PhotoUtils.eventHasFiles({})); assert.notOk(PhotoUtils.eventHasFiles({ target: 'hi' })); assert.notOk(PhotoUtils.eventHasFiles({ target: {} })); assert.notOk(PhotoUtils.eventHasFiles({ target: { files: 88 } })); assert.equal(PhotoUtils.eventHasFiles({ target: { files: [] } }), 0); assert.equal(PhotoUtils.eventHasFiles({ target: { files: ['hi'] } }), 1); }); test('invalid inputs when extracting images from an event', function(assert) { const done = assert.async(8); PhotoUtils.extractImagesFromEvent().then(null, res => { assert.notOk(res, 'short circuits when event not an object'); done(); }); PhotoUtils.extractImagesFromEvent(null).then(null, res => { assert.notOk(res, 'short circuits when event not an object'); done(); }); PhotoUtils.extractImagesFromEvent('not an object').then(null, res => { assert.notOk(res, 'short circuits when event not an object'); done(); }); PhotoUtils.extractImagesFromEvent(88).then(null, res => { assert.notOk(res, 'short circuits when event not an object'); done(); }); PhotoUtils.extractImagesFromEvent([]).then(null, res => { assert.notOk(res, 'short circuits when event not an object'); done(); }); PhotoUtils.extractImagesFromEvent({ testing: 'ok' }).then(null, res => { assert.notOk(res, 'short circuits when missing target prop'); done(); }); PhotoUtils.extractImagesFromEvent({ target: 'ok' }).then(null, res => { assert.notOk(res, 'short circuits when target prop not an object'); done(); }); PhotoUtils.extractImagesFromEvent({ target: {} }).then(null, res => { assert.notOk(res, 'short circuits when no files'); done(); }); }); test('extracting images from an event', function(assert) { const done = assert.async(), files = ['valid file object', 'valid file object', 'valid file object']; compressionReturnVal = { type: Math.random() }; dataUrlReturnVal = Math.random(); loadImageReturnVal = { naturalWidth: Math.random(), naturalHeight: Math.random() }; PhotoUtils.extractImagesFromEvent({ target: { files } }).then(results => { assert.equal(compressionStub.callCount, files.length); assert.equal(dataUrlStub.callCount, files.length); assert.equal(loadImageStub.callCount, files.length); results.forEach(result => { assert.equal(typeOf(result), 'object', 'result is an object'); assert.deepEqual(result.mimeType, compressionReturnVal.type, 'mime type is correct value'); assert.equal(result.data, dataUrlReturnVal, 'data is correct value'); assert.equal(result.width, loadImageReturnVal.naturalWidth, 'width is correct value'); assert.equal(result.height, loadImageReturnVal.naturalHeight, 'height is correct value'); }); done(); }); }); test('ensuring image dimensions a variety of inputs', function(assert) { const done = assert.async(6); PhotoUtils.ensureImageDimensions().then(null, res => { assert.equal(res, undefined, 'invalid inputs are rejected'); done(); }); PhotoUtils.ensureImageDimensions(null).then(null, res => { assert.equal(res, null, 'invalid inputs are rejected'); done(); }); PhotoUtils.ensureImageDimensions('hello').then(null, res => { assert.equal(res, 'hello', 'invalid inputs are rejected'); done(); }); PhotoUtils.ensureImageDimensions(88).then(null, res => { assert.equal(res, 88, 'invalid inputs are rejected'); done(); }); PhotoUtils.ensureImageDimensions({}).then(null, res => { assert.deepEqual(res, {}, 'invalid inputs are rejected'); done(); }); PhotoUtils.ensureImageDimensions([]).then(res => { assert.deepEqual(res, [], 'empty arrays pass through, NOT REJECTED'); done(); }); }); test('ensuring image dimensions for all with dimensions', function(assert) { const store = Ember.getOwner(this).lookup('service:store'), done = assert.async(); PhotoUtils.ensureImageDimensions([mockValidMediaImage(store), mockValidMediaImage(store)]).then( mediaImages => { assert.equal(mediaImages.length, 2); assert.ok(loadImageStub.notCalled, 'load image never called because already have dimensions'); done(); } ); }); test('ensuring image dimensions for some without dimensions', function(assert) { run(() => { const store = Ember.getOwner(this).lookup('service:store'), done = assert.async(), withDimensions = [mockValidMediaImage(store), mockValidMediaImage(store)], numVersionsPerNoDimension = 3, noDimensions = Array(5) .fill() .map(() => { const el = store.createFragment('media-element', { [Constants.PROP_NAME.MEDIA_ID]: 'id', }); Array(numVersionsPerNoDimension) .fill() .forEach(() => { el.addVersion('image/jpeg', 'https://via.placeholder.com/350x150'); }); return el; }); loadImageReturnVal = { naturalWidth: Math.random(), naturalHeight: Math.random() }; PhotoUtils.ensureImageDimensions([].pushObjects(withDimensions).pushObjects(noDimensions)).then( mediaImages => { assert.equal(mediaImages.length, withDimensions.length + noDimensions.length); assert.equal(loadImageStub.callCount, noDimensions.length * numVersionsPerNoDimension); noDimensions.forEach(mElements => { mElements.get('versions').forEach(version => { assert.equal(version.get('width'), loadImageReturnVal.naturalWidth); assert.equal(version.get('height'), loadImageReturnVal.naturalHeight); }); }); done(); } ); }); }); test('if should rebuild responsive gallery', function(assert) { const fn = PhotoUtils.shouldRebuildResponsiveGallery; assert.equal(fn(), false, 'false for invalid input'); assert.equal(fn('blah'), false, 'false for invalid input'); assert.equal(fn(200, 1, 400, 2), true, 'mobile/tablet'); assert.equal(fn(400, 2, 600, 2), true, 'tablet/desktop'); assert.equal(fn(100, 2, 600, 2), true, 'mobile/desktop'); assert.equal(fn(200, 1, 400, 1), false, 'both mobile'); assert.equal(fn(100, 5, 400, 2), false, 'both tablet'); assert.equal(fn(800, 2, 600, 2), false, 'both desktop'); }); test('selecting appropriate image version for display in gallery', function(assert) { run(() => { const store = Ember.getOwner(this).lookup('service:store'), fn = PhotoUtils.formatResponsiveMediaImageForGallery, el = store.createFragment('media-element', { [Constants.PROP_NAME.MEDIA_ID]: 'id' }); assert.notOk(fn(), 'short circuits invalid input'); assert.notOk(fn('not a number', 8), 'short circuits invalid input'); assert.notOk(fn(3, 8, []), 'short circuits invalid input'); assert.deepEqual(fn(3, 8, el), { src: '', w: 0, h: 0 }); el.addVersion('image/jpeg', 'test1', 1); el.addVersion('image/jpeg', 'test2', 100); el.addVersion('image/jpeg', 'test3', 1000); assert.equal(el.get('versions.length'), 3); assert.deepEqual(fn(3, 8, el), { src: 'test1', w: 1, h: null }); assert.deepEqual(fn(33, 3, el), { src: 'test2', w: 100, h: null }); assert.deepEqual(fn(33, 1000, el), { src: 'test3', w: 1000, h: null }); }); }); test('getting boundary coordinates for preview thumbnail', function(assert) { const fn = PhotoUtils.getPreviewBounds, windowStub = sinon.stub(window, 'pageYOffset').value(0); assert.notOk(fn(), 'short circuits invalid input'); assert.notOk(fn(null), 'not an object'); assert.notOk(fn('blah'), 'not an object'); assert.notOk(fn(88), 'not an object'); assert.notOk(fn({}), 'getBoundingClientRect is not a function'); assert.notOk(fn({ getBoundingClientRect: 'hi' }), 'getBoundingClientRect is not a function'); const bounds = { left: Math.random(), top: Math.random(), width: Math.random() }; assert.deepEqual(fn({ getBoundingClientRect: () => bounds }), { x: bounds.left, y: bounds.top, w: bounds.width, }); windowStub.restore(); });
13,875
https://github.com/Interkarma/daggerfall-unity/blob/master/Assets/Prefabs/World/StreamingWorld.prefab.meta
Github Open Source
Open Source
MIT
2,023
daggerfall-unity
Interkarma
Unity3D Asset
Code
6
42
fileFormatVersion: 2 guid: bbe5e15c9f6b3dc47bb9485a437750a0 NativeFormatImporter: userData:
30,761
https://github.com/scottmac/hiphop-php/blob/master/src/cpp/base/thread_info.cpp
Github Open Source
Open Source
PHP-3.01, Zend-2.0
2,019
hiphop-php
scottmac
C++
Code
150
416
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <cpp/base/types.h> #include <cpp/base/memory/smart_allocator.h> using namespace std; namespace HPHP { /////////////////////////////////////////////////////////////////////////////// IMPLEMENT_THREAD_LOCAL(ThreadInfo, ThreadInfo::s_threadInfo); ThreadInfo::ThreadInfo() { map<int, ObjectAllocatorWrapper *> &wrappers = ObjectAllocatorCollector::getWrappers(); m_allocators.resize(wrappers.size()); for (map<int, ObjectAllocatorWrapper *>::iterator it = wrappers.begin(); it != wrappers.end(); it++) { m_allocators[it->first] = it->second->get(); } m_top = NULL; m_stackdepth = 0; m_profiler = NULL; } /////////////////////////////////////////////////////////////////////////////// }
45,914
https://github.com/cyphyhouse/CyPyHous3/blob/master/src/harness/msg_create.py
Github Open Source
Open Source
MIT
2,019
CyPyHous3
cyphyhouse
Python
Code
593
1,700
# Copyright (c) 2019 CyPhyHouse. All Rights Reserved. import src.datatypes.message_types as mt import src.objects.message as message def round_update_msg_create(pid: int, round_num: int, ts: float) -> message.Message: """ create message to update round :param pid: agent pid that is ready to update round :type pid: int :param round_num: round number :type round_num: int :param ts: time stamp :type ts: float :return: round update message :rtype: Message """ return message.Message(pid, mt.MsgType.ROUND_UPDATE, round_num, ts) def round_update_msg_confirm_create(pid: int, leader_id: int, round_num: int, ts: float) -> message.Message: """ create message to confirm round update :param pid: agent pid :type pid: int :param leader_id: leader pid :type leader_id: int :param round_num: round number :type round_num: int :param ts: time stamp :type ts: float :return: round update confirmation message :rtype: Message """ return message.Message(pid, mt.MsgType.ROUND_UPDATE_CONFIRM, (leader_id, round_num), ts) def stop_msg_create(pid: int, round_num: int, ts: float) -> message.Message: """ create message to stop :param pid: agent pid :type pid: int :param round_num: round number :type round_num: int :param ts: time stamp :type ts: float :return: stop message creation :rtype: Message """ return message.Message(pid, mt.MsgType.STOP, round_num, ts) def stop_msg_confirm_create(pid: int, leader_id: int, ts: float) -> message.Message: """ create to confirm stop :param pid: agent pid :type pid: int :param leader_id: leader pid :type leader_id: int :param ts: time stamp :type ts: float :return: stop message confirmation create :rtype: Message """ return message.Message(pid, mt.MsgType.STOP_CONFIRM, leader_id, ts) def init_msg_create(pid: int, ts: float) -> message.Message: """ create init message :param pid: agent pid :type pid: int :param ts: time stamp :type ts: float :return: init message :rtype: Message """ return message.Message(pid, mt.MsgType.INIT, None, ts) def init_msg_confirm_create(pid: int, leader_id: int, ts: float) -> message.Message: """ create init confirmation message :param pid: agent pid :type pid: int :param leader_id: leader pid :type leader_id: int :param ts: timestamp :type ts: float :return: init confirmation message :rtype: Message """ return message.Message(pid, mt.MsgType.INIT_CONFIRM, leader_id, ts) def stop_comm_msg_create(pid: int, ts: float) -> message.Message: """ create a message to stop the comm_handler :param pid: agent pid :type pid: int :param ts: timestamp :type ts: float :return: stop communication handler message :rtype: Message """ return message.Message(pid, mt.MsgType.STOP_COMM, None, ts) def mutex_request_create(mutex_id: str, req_num: int, pid: int, ts: float) -> message.Message: """ create mutex request message :param mutex_id: variable to create mutex request for :type mutex_id: str :param pid: pid of agent requesting mutex :type pid: int :param req_num: request number :type req_num: int :param ts: time stamp :type ts: float :return: mutex request message :rtype: Message """ contents = (mutex_id, req_num) return message.Message(pid, mt.MsgType.MUTEX_REQUEST, contents, ts) def mutex_grant_create(mutex_id: str, agent_id: int, pid: int, mutex_num: int, ts: float) -> message.Message: """ grant mutex creation message :param mutex_num: mutex number :type mutex_num: int :param mutex_id: variable to grant mutex on :type mutex_id: str :param agent_id: agent to grant mutex to :type agent_id: int :param pid: leader pid who is granting the mutex :type pid: int :param ts: timestamp :type ts: float :return: mutex grant message :rtype: Message """ contents = (mutex_id, agent_id, mutex_num) return message.Message(pid, mt.MsgType.MUTEX_GRANT, contents, ts) def mutex_release_create(mutex_id: str, pid: int, ts: float) -> message.Message: """ create release held mutex message :param mutex_id: mutex name :type mutex_id: str :param pid: releasing agent's pid :type pid: int :param ts: timestamp :type ts: float :return: mutex release message :rtype: Message """ contents = mutex_id return message.Message(pid, mt.MsgType.MUTEX_RELEASE, contents, ts) def dsm_update_create(pid: int, dsm_var_updated, round_num): """ create dsm update message. :param pid: agent pid :type pid: int :param dsm_var_updated: dsm_var to be updated :type dsm_var_updated: DSM :param round_num: round number of update :type round_num: int :return: dsm update message :rtype: Message """ return message.Message(pid, mt.MsgType.VAR_UPDATE, dsm_var_updated, round_num)
50,369
https://github.com/ArchimedesDigital/spotlight/blob/master/spec/factories/featured_images.rb
Github Open Source
Open Source
Apache-2.0
null
spotlight
ArchimedesDigital
Ruby
Code
31
162
FactoryBot.define do factory :featured_image, class: Spotlight::FeaturedImage do image { Rack::Test::UploadedFile.new(File.expand_path(File.join('..', 'fixtures', 'avatar.png'), __dir__)) } iiif_tilesource 'https://exhibits-stage.stanford.edu/images/78' end factory :masthead, class: Spotlight::Masthead do image { Rack::Test::UploadedFile.new(File.expand_path(File.join('..', 'fixtures', 'avatar.png'), __dir__)) } end end
46,536
https://github.com/shakeyourbunny/appget/blob/master/src/AppGet.Tests/Infrastructure/Composition/ContainerBuilderFixture.cs
Github Open Source
Open Source
Apache-2.0
2,022
appget
shakeyourbunny
C#
Code
170
757
using System; using System.Linq; using AppGet.Commands; using AppGet.CreatePackage.Installer; using AppGet.CreatePackage.Root; using AppGet.FileTransfer; using AppGet.Infrastructure.Composition; using AppGet.Installers.InstallerWhisperer; using AppGet.Installers.UninstallerWhisperer; using DryIoc; using FluentAssertions; using NUnit.Framework; namespace AppGet.Tests.Infrastructure.Composition { [TestFixture] public class ContainerBuilderFixture { [Test] public void check_multi_registration() { var container = ContainerBuilder.Container; void Assert<T>() { var commandHandler = ContainerBuilder.AssemblyTypes.Where(c => c.ImplementsServiceType<T>()).ToList(); var registered = container.ResolveMany<T>().Select(e => e.GetType()).ToList(); commandHandler.Should().BeEquivalentTo(registered); } Assert<ICommandHandler>(); Assert<InstallerBase>(); Assert<IExtractToManifestRoot>(); Assert<IManifestPrompt>(); Assert<IInstallerPrompt>(); Assert<IFileTransferClient>(); } [Test] public void installer_whisperer_check() { var container = ContainerBuilder.Container; var whisperersFac = container.Resolve<Func<InstallerBase[]>>(); var whisperers = whisperersFac(); whisperers.Should().OnlyHaveUniqueItems(c => c.InstallMethod); } [Test] public void uninstaller_whisperer_check() { var container = ContainerBuilder.Container; var whisperersFac = container.Resolve<Func<UninstallerBase[]>>(); var whisperers = whisperersFac(); whisperers.Should().OnlyHaveUniqueItems(c => c.InstallMethod); } [Test] public void installers_should_be_transient() { var container = ContainerBuilder.Container; var whisperersFac = container.Resolve<Func<InstallerBase[]>>(); var whisperers1 = whisperersFac(); var whisperers2 = whisperersFac(); whisperers2.Should().NotEqual(whisperers1); } [Test] public void uninstallers_should_be_transient() { var container = ContainerBuilder.Container; var whisperersFac = container.Resolve<Func<UninstallerBase[]>>(); var whisperers1 = whisperersFac(); var whisperers2 = whisperersFac(); whisperers2.Should().NotEqual(whisperers1); } [Test] public void check_commands() { var container = ContainerBuilder.Container; var handlers = container.ResolveMany<ICommandHandler>(); handlers.Should().NotBeEmpty(); } } }
19,186
https://github.com/aherbst-broad/terra-interoperability-model/blob/master/releases/1.x/terra-core/TerraCoreDataModel.ttl
Github Open Source
Open Source
BSD-3-Clause
2,021
terra-interoperability-model
aherbst-broad
Turtle
Code
5,700
20,215
# baseURI: https://datamodel.terra.bio/TerraCore # imports: https://datamodel.terra.bio/imports/EFO_subset # imports: https://datamodel.terra.bio/imports/NCBITaxon_Organisms_subset # imports: https://datamodel.terra.bio/imports/OBI_assay_subset # imports: https://datamodel.terra.bio/imports/OBI_core # imports: https://datamodel.terra.bio/TerraCoreValueSets # imports: https://datamodel.terra.bio/TerraDCAT_ap # imports: https://www.w3.org/2002/07/owl # prefix: TerraCore @prefix : <https://datamodel.terra.bio/TerraCore#> . @prefix TerraCore: <https://datamodel.terra.bio/TerraCore#> . @prefix TerraCoreValueSets: <https://datamodel.terra.bio/TerraCoreValueSets#> . @prefix TerraDCAT_ap: <https://datamodel.terra.bio/TerraDCAT_ap#> . @prefix dc: <http://purl.org/dc/elements/1.1/> . @prefix dcat: <http://www.w3.org/ns/dcat#> . @prefix dct: <http://purl.org/dc/terms/> . @prefix duo: <http://purl.obolibrary.org/obo/duo-basic.owl#> . @prefix nsf2_full_mtg: <http://www.jcvi.org/framework/nsf2_full_mtg#> . @prefix obo: <http://purl.obolibrary.org/obo/> . @prefix oboInOwl: <http://www.geneontology.org/formats/oboInOwl#> . @prefix owl: <http://www.w3.org/2002/07/owl#> . @prefix prov: <http://www.w3.org/ns/prov#> . @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . @prefix skos: <http://www.w3.org/2004/02/skos/core#> . @prefix xsd: <http://www.w3.org/2001/XMLSchema#> . <https://datamodel.terra.bio/TerraCore> a owl:Ontology ; dc:creator "Kathy Reinold" ; dct:date "20 Jul 2020" ; dct:license <https://github.com/DataBiosphere/terra-interoperability-model/blob/master/LICENSE> ; rdfs:comment "Please cite The Broad Institute of Harvard and MIT, Data Sciences Platform." ; owl:imports <https://datamodel.terra.bio/imports/EFO_subset> ; owl:imports <https://datamodel.terra.bio/imports/NCBITaxon_Organisms_subset> ; owl:imports <https://datamodel.terra.bio/imports/OBI_assay_subset> ; owl:imports <https://datamodel.terra.bio/imports/OBI_core> ; owl:imports <https://datamodel.terra.bio/TerraCoreValueSets> ; owl:imports <https://datamodel.terra.bio/TerraDCAT_ap> ; owl:imports <http://www.w3.org/2002/07/owl> ; owl:versionInfo "Version 1.0.0" ; . TerraCore:Activity a owl:Class ; rdfs:label "Activity" ; rdfs:subClassOf prov:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty dct:created ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:endedAtTime ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:startedAtTime ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hadProtocol ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasDataModality ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty prov:wasAssociatedWith ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:usedSample ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:generated ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:used ; ] ; skos:prefLabel "Activity" ; prov:definition "An activity occurs over a period of time, generates an entity, and may include consuming, processing, transforming, modifying, relocating, or using entities. This subclass of prov:Activity restricts members to those with a DataModality relevant to biomedical research." ; . TerraCore:Address a owl:Class ; rdfs:label "Address" ; rdfs:subClassOf obo:IAO_0000030 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasPostalCode ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasCountry ; ] ; prov:definition "A physical address for a Person or Organization." ; . TerraCore:Age a owl:Class ; rdfs:label "Age" ; rdfs:subClassOf obo:OBI_0001167 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAgeCategory ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasLowerBound ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasUpperBound ; ] ; owl:equivalentClass [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAgeUnit ; ] ; skos:prefLabel "Age " ; . TerraCore:Alignment a owl:Class ; rdfs:label "Alignment" ; rdfs:subClassOf TerraCore:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:usedReferenceAssembly ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:AlignmentFile ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom TerraCore:SequenceFile ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom prov:SoftwareAgent ; ] ; owl:disjointWith TerraCore:AlignmentPostProcessing ; owl:disjointWith TerraCore:AssayActivity ; owl:disjointWith TerraCore:LibraryPreparation ; owl:disjointWith TerraCore:Pipeline ; owl:disjointWith TerraCore:Sequencing ; owl:disjointWith TerraCore:VariantCalling ; skos:prefLabel "Alignment" ; prov:definition "An activity that aligns the output of a Sequencing Activity (a genetic sequence) to produce an aligned sequence." ; . TerraCore:AlignmentFile a owl:Class ; rdfs:label "AlignmentFile" ; rdfs:subClassOf TerraCore:File ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:usedReferenceAssembly ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasPercentAlignedReads ; ] ; skos:definition "An electronic record of the alignment of a genetic sequence for a particular Sample compared with a reference sequence generated by an AlignmentActivity." ; skos:prefLabel "AlignmentFile" ; . TerraCore:AlignmentPostProcessing a owl:Class ; rdfs:label "AlignmentPostProcessing" ; rdfs:subClassOf TerraCore:Pipeline ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:AlignmentFile ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom TerraCore:AlignmentFile ; ] ; owl:disjointWith TerraCore:Alignment ; owl:disjointWith TerraCore:AssayActivity ; owl:disjointWith TerraCore:LibraryPreparation ; owl:disjointWith TerraCore:Sequencing ; owl:disjointWith TerraCore:VariantCalling ; skos:prefLabel "AlignmentPostProcessing" ; prov:definition "An activity that further processed the output of an Alignment Activity on a genetic sequence." ; . TerraCore:Antibody a owl:Class ; rdfs:label "Antibody" ; rdfs:subClassOf obo:BFO_0000040 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasHostOrganism ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasClonality ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasTarget ; ] ; . TerraCore:AssayActivity a owl:Class ; rdfs:label "Assay" ; rdfs:subClassOf TerraCore:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAssayCategory ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAssayType ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:generated ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:File ; ] ; owl:disjointWith TerraCore:Alignment ; owl:disjointWith TerraCore:AlignmentPostProcessing ; owl:disjointWith TerraCore:LibraryPreparation ; owl:disjointWith TerraCore:Pipeline ; owl:disjointWith TerraCore:Sequencing ; owl:disjointWith TerraCore:VariantCalling ; skos:prefLabel "Assay" ; prov:definition "An activity that generates an electronic record documenting the result of the Assay performed." ; . TerraCore:BioSample a owl:Class ; rdfs:label "BioSample" ; rdfs:subClassOf TerraCore:Sample ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAnatomicalSite ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasPreservationState ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty dct:source ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasCrossReference ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty prov:wasDerivedFrom ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:donatedBy ; ] ; owl:equivalentClass [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasBioSampleType ; ] ; skos:altLabel "Biospecimen" ; skos:altLabel "Specimen from organism" ; skos:definition "Data about a physical sample consisting of one or more cells taken from an organism (living or deceased) or derived from such a Sample." ; skos:prefLabel "BioSample" ; . TerraCore:BioSampleDissociation a owl:Class ; rdfs:label "BioSampleDissociation" ; rdfs:subClassOf TerraCore:Activity ; owl:equivalentClass <http://www.ebi.ac.uk/efo/EFO_0009091> ; skos:definition "Activity which results in the separation of a BioSample into individual cells or a cell suspension." ; . TerraCore:BiologicalSex a owl:Class ; rdfs:label "Biological sex" ; rdfs:subClassOf obo:BFO_0000019 ; rdfs:subClassOf obo:PATO_0001894 ; skos:definition "A quality of an organism indicating physical sexual characteristics. Equivalent of PATO's phenotypic sex but pseudohermaphrodite is not relevant to existing data and is not recommended." ; . TerraCore:ChromosomalLocation a owl:Class ; rdfs:label "ChromosomalLocation" ; rdfs:subClassOf TerraCore:SequenceLocation ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasChromosome ; ] ; prov:definition "The location of a sequence feature defined by its start and end position on a chromosome in a reference coordinate system. " ; . TerraCore:Country a owl:Class ; rdfs:label "Country" ; rdfs:subClassOf <http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing> ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAlpha2Code ; ] ; skos:definition "A country represented by the ISO-3166 Alpha-2 code and name (as a label). https://www.iso.org/obp/ui/#search" ; . TerraCore:Diagnosis a owl:Class ; rdfs:label "Diagnosis" ; rdfs:subClassOf obo:IAO_0000030 ; skos:definition "Result of a medical investigation that often identies a disease or condition." ; . TerraCore:Dog a obo:NCBITaxon_9615 ; rdfs:label "Dog" ; . TerraCore:DogDonor a owl:Class ; rdfs:label "DogDonor" ; rdfs:subClassOf TerraCore:Donor ; owl:equivalentClass [ a owl:Restriction ; owl:hasValue TerraCore:Dog ; owl:onProperty TerraCore:hasOrganism ; ] ; skos:definition "Extension of Donor class for dogs." ; . TerraCore:Donor a owl:Class ; rdfs:label "Donor" ; rdfs:subClassOf obo:OBI_0100026 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasOrganism ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAge ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasSex ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasMedicalHistory ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:donated ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty dct:isPartOf ; owl:someValuesFrom TerraDCAT_ap:Dataset ; ] ; skos:definition "An organism from which a sample or test result is available" ; skos:prefLabel "Donor" ; . TerraCore:FamilyMember a owl:Class ; rdfs:label "Family Member" ; rdfs:subClassOf obo:OBI_0100026 ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hadMannerOfDeath ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasEthnicity ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasRace ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasSex ; ] ; owl:equivalentClass [ a owl:Restriction ; owl:hasValue TerraCore:Homo_sapiens ; owl:onProperty TerraCore:hasOrganism ; ] ; . TerraCore:Female a TerraCore:FemaleSex ; rdfs:label "Female" ; . TerraCore:FemaleSex a owl:Class ; oboInOwl:hasExactSynonym "F" ; rdfs:label "Female" ; rdfs:subClassOf TerraCore:BiologicalSex ; owl:equivalentClass obo:PATO_0000383 ; skos:altLabel "F" ; . TerraCore:File a owl:Class ; rdfs:comment "Used definition from http://semanticscience.org/resource/SIO_000396 but equivalence to http://www.w3.org/ns/dcat#Distribution doesn't make sense to me; thus we have our own object. Also added electronic. This will be subclassed for different file types to allow for file type-specific metadata, but for now, all metadata is an option for all Files." ; rdfs:label "File" ; rdfs:subClassOf obo:IAO_0000030 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasFileFormat ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty dcat:byteSize ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasChecksum ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty TerraCore:hasCrossReference ; owl:someValuesFrom dct:URI ; ] ; skos:definition "A file is an information-bearing electronic object that contains a physical embodiment of some information using a particular character encoding." ; skos:prefLabel "File" ; . TerraCore:GRCh37 a TerraCore:ReferenceAssembly ; TerraCore:hasGRCName "GRCh37" ; TerraCore:hasOrganism TerraCore:Homo_sapiens ; rdfs:label "GRCh37" ; . TerraCore:GeneralResearchUse a obo:DUO_0000005 ; rdfs:label "General Research Use" ; skos:prefLabel "General Research Use" ; . TerraCore:GrCh38 a TerraCore:ReferenceAssembly ; TerraCore:hasGRCName "GRCh38" ; TerraCore:hasOrganism TerraCore:Homo_sapiens ; rdfs:label "GRCh38" ; . TerraCore:Hermaphrodite a TerraCore:HermaphroditeSex ; rdfs:label "Hermaphrodite" ; . TerraCore:HermaphroditeSex a owl:Class ; oboInOwl:hasExactSynonym "intersex" ; rdfs:label "Intersex" ; rdfs:subClassOf TerraCore:BiologicalSex ; owl:equivalentClass obo:PATO_0001340 ; skos:altLabel "Hermaphrodite" ; . TerraCore:Homo_sapiens a obo:NCBITaxon_9606 ; rdfs:label "Human" ; skos:prefLabel "Homo sapiens" ; . TerraCore:HumanDonor a owl:Class ; rdfs:label "HumanDonor" ; rdfs:subClassOf TerraCore:Donor ; owl:equivalentClass [ a owl:Restriction ; owl:hasValue TerraCore:Homo_sapiens ; owl:onProperty TerraCore:hasOrganism ; ] ; skos:definition "Extension of Donor class for Humans." ; . TerraCore:Library a owl:Class ; rdfs:label "Library" ; rdfs:subClassOf obo:BFO_0000040 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:wasGeneratedBy ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hadAssay ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty prov:wasUsedBy ; ] ; skos:definition "A collection of nucleic acid molecules." ; skos:prefLabel "Library" ; . TerraCore:LibraryPreparation a owl:Class ; rdfs:label "LibraryPreparation" ; rdfs:subClassOf TerraCore:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasLibraryPreparationType ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:Library ; ] ; owl:disjointWith TerraCore:Alignment ; owl:disjointWith TerraCore:AlignmentPostProcessing ; owl:disjointWith TerraCore:AssayActivity ; owl:disjointWith TerraCore:Pipeline ; owl:disjointWith TerraCore:Sequencing ; owl:disjointWith TerraCore:VariantCalling ; skos:definition "Activity which results in the creation of a library from fragments of genomic material in preparation for further analysis." ; skos:prefLabel "LibraryPreparation" ; . TerraCore:Male a TerraCore:MaleSex ; rdfs:label "Male" ; . TerraCore:MaleSex a owl:Class ; oboInOwl:hasExactSynonym "M" ; rdfs:label "Male" ; rdfs:subClassOf TerraCore:BiologicalSex ; owl:equivalentClass obo:PATO_0000384 ; skos:altLabel "M" ; . TerraCore:MedicalHistory a owl:Class ; rdfs:label "MedicalHistory" ; rdfs:subClassOf obo:IAO_0000030 ; skos:definition "Placeholder for medical record information. Likely a series of visits/encounters with results. Need to connect to the BioSample." ; . TerraCore:MolecularSample a owl:Class ; rdfs:label "MolecularSample" ; rdfs:subClassOf TerraCore:Sample ; skos:prefLabel "MolecularSample" ; prov:definition "Data about a physical sample consisting of one or more molecular entities, either purified from a Sample or synthesized." ; . TerraCore:MouseDonor a owl:Class ; rdfs:label "MouseDonor" ; rdfs:subClassOf TerraCore:Donor ; owl:equivalentClass [ a owl:Restriction ; owl:hasValue TerraCore:Mus_musculus ; owl:onProperty TerraCore:hasOrganism ; ] ; skos:definition "Extension of Donor class for mice." ; . TerraCore:Mus_musculus a obo:NCBITaxon_10090 ; rdfs:label "Mus musculus" ; . TerraCore:NoRestriction a obo:DUO_0000004 ; rdfs:label "NoRestriction" ; skos:prefLabel "NoRestriction" ; . TerraCore:NucleusIsolation a owl:Class ; rdfs:label "NucleusIsolation" ; rdfs:subClassOf TerraCore:Activity ; owl:equivalentClass <http://www.ebi.ac.uk/efo/EFO_0007831> ; skos:definition "Activity to separate the nucleus from the cell. " ; . TerraCore:Pipeline a owl:Class ; rdfs:label "Pipeline" ; rdfs:subClassOf TerraCore:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:File ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom TerraCore:File ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom prov:SoftwareAgent ; ] ; owl:disjointWith TerraCore:Alignment ; owl:disjointWith TerraCore:AlignmentPostProcessing ; owl:disjointWith TerraCore:AssayActivity ; owl:disjointWith TerraCore:LibraryPreparation ; owl:disjointWith TerraCore:Sequencing ; owl:disjointWith TerraCore:VariantCalling ; prov:definition "An activity that records the output of a specific software pipeline. Pipeline version, components, arguments are described in prov:SoftwareAgent." ; . TerraCore:PrincipalInvestigator a owl:Class ; rdfs:label "Principal Investigator" ; rdfs:subClassOf prov:Person ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty <http://xmlns.com/foaf/0.1/title> ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty <http://xmlns.com/foaf/0.1/family_name> ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty <http://xmlns.com/foaf/0.1/givenname> ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty <http://xmlns.com/foaf/0.1/mbox> ; ] ; prov:definition "The principal or lead person who carries out an investigation assigned by a sponsor or authorizing agent." ; . TerraCore:Project a owl:Class ; rdfs:label "Project" ; rdfs:subClassOf prov:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:hasValue 1 ; owl:onProperty dct:title ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasCrossReference ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:wasFundedBy ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraDCAT_ap:hasOriginalPublication ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty dct:contributor ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty dct:isReferencedBy ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraDCAT_ap:wasPrincipalInvestigator ; ] ; skos:definition "A collective effort with an objective related to biomedical research." ; skos:prefLabel "Project" ; . TerraCore:Rabbit a obo:NCBITaxon_9986 ; rdfs:label "Rabbit" ; . TerraCore:ReferenceAssembly a owl:Class ; obo:IAO_0000114 "DRAFT" ; rdfs:comment "Instances should include either a cross reference to the reference sequence or an official GRCName from the Genome Reference Consortium, or both." ; rdfs:label "ReferenceAssembly" ; rdfs:subClassOf obo:OBI_0001573 ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasCrossReference ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasGRCName ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasOrganism ; ] ; skos:prefLabel "ReferenceAssembly" ; prov:definition "DNA sequence data identified as representative of specific organism's DNA." ; . TerraCore:Sample a owl:Class ; rdfs:label "Sample" ; rdfs:subClassOf obo:OBI_0100051 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraDCAT_ap:hasDataUseLimitation ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:dateObtained ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty dct:created ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraDCAT_ap:hasDataUseRequirement ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty prov:hadDerivation ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty dct:isPartOf ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minQualifiedCardinality "0"^^xsd:nonNegativeInteger ; owl:onClass TerraCore:Sample ; owl:onProperty prov:wasDerivedFrom ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minQualifiedCardinality "1"^^xsd:nonNegativeInteger ; owl:onClass TerraCore:Activity ; owl:onProperty prov:wasUsedBy ; ] ; skos:definition "Data about a physical material collected for the purpose of research." ; skos:prefLabel "Sample" ; . TerraCore:SequenceFile a owl:Class ; rdfs:label "SequenceFile" ; rdfs:subClassOf TerraCore:File ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasLibraryLayout ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasPercentDuplicateFragments ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasReadCount ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:maxCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasReadLength ; ] ; skos:definition "An electronic record of the genetic sequence for a particular Sample generated by a SequencingActivity." ; skos:prefLabel "SequenceFile" ; . TerraCore:SequenceLocation a owl:Class ; rdfs:label "SequenceLocation" ; rdfs:subClassOf <http://www.w3.org/2003/01/geo/wgs84_pos#SpatialThing> ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasLocation ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasStartPosition ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasStopPosition ; ] ; skos:prefLabel "SequenceLocation" ; prov:definition "The location of a sequence feature defined by its start and end position based on a reference coordinate system." ; . TerraCore:Sequencing a owl:Class ; rdfs:label "Sequencing" ; rdfs:subClassOf TerraCore:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:usedSample ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:SequenceFile ; ] ; owl:disjointWith TerraCore:Alignment ; owl:disjointWith TerraCore:AlignmentPostProcessing ; owl:disjointWith TerraCore:AssayActivity ; owl:disjointWith TerraCore:LibraryPreparation ; owl:disjointWith TerraCore:Pipeline ; owl:disjointWith TerraCore:VariantCalling ; skos:prefLabel "Sequencing" ; prov:definition "An activity that produces an electronic record of a genetic sequence from a Sample" ; . TerraCore:SingleCell a owl:Class ; rdfs:label "SingleCell" ; rdfs:subClassOf TerraCore:BioSample ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAnatomicalRegion ; ] ; skos:definition "Data about a physical sample consisting of a single cell or nucleus taken from an organism (living or deceased) or derived from such a Sample." ; . TerraCore:SingleCellAssignment a owl:Class ; rdfs:label "SingleCellAssignment" ; rdfs:subClassOf TerraCore:Activity ; skos:definition "An activity that infers a cell type based on analysis. " ; . TerraCore:SingleCellIsolation a owl:Class ; rdfs:label "SingleCellIsolation" ; rdfs:subClassOf TerraCore:Activity ; skos:definition "Activity to separate individual cells or nuclei. " ; . TerraCore:UserRestriction a obo:DUO_0000026 ; rdfs:label "User Restriction" ; skos:prefLabel "User Restriction" ; . TerraCore:VariantCall a owl:Class ; rdfs:label "VariantCall" ; rdfs:subClassOf obo:OBI_0001364 ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasAllele ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:cardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasSequenceLocation ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasVariantReference ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom TerraCore:VariantCallSet ; ] ; skos:prefLabel "VariantCall" ; prov:definition "A variation in genetic sequence for a particular Sample and VariantCallingActivity." ; . TerraCore:VariantCallSet a owl:Class ; rdfs:label "VariantCallSet" ; rdfs:subClassOf TerraCore:File ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:hasVariantCall ; ] ; skos:prefLabel "VariantCallSet" ; prov:definition "An electronic record of a collection of variations in genetic sequence for a particular Sample that have been generated by a VariantCallingActivity." ; . TerraCore:VariantCalling a owl:Class ; rdfs:label "VariantCalling" ; rdfs:subClassOf TerraCore:Activity ; rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "1"^^xsd:nonNegativeInteger ; owl:onProperty TerraCore:usedReferenceAssembly ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:generated ; owl:someValuesFrom TerraCore:VariantCallSet ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom TerraCore:AlignmentFile ; ] ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty prov:used ; owl:someValuesFrom prov:SoftwareAgent ; ] ; owl:disjointWith TerraCore:Alignment ; owl:disjointWith TerraCore:AlignmentPostProcessing ; owl:disjointWith TerraCore:AssayActivity ; owl:disjointWith TerraCore:LibraryPreparation ; owl:disjointWith TerraCore:Pipeline ; owl:disjointWith TerraCore:Sequencing ; skos:definition "An activity that identifies genetic sequence alterations in a Sample when compared to a reference." ; skos:prefLabel "VariantCalling" ; . TerraCore:Weight a owl:Class ; rdfs:label "Weight" ; rdfs:subClassOf obo:IAO_0000109 ; owl:equivalentClass obo:PATO_0000128 ; skos:definition "A measurement of the mass of an entity." ; . TerraCore:ageAtDiagnosis a owl:ObjectProperty ; rdfs:domain TerraCore:Diagnosis ; rdfs:label "ageAtDiagnosis" ; rdfs:range TerraCore:Age ; skos:definition "A reference to the Age of the Donor at the point in time that diagnosis was made." ; skos:prefLabel "ageAtDiagnosis" ; . TerraCore:ageAtOnset a owl:ObjectProperty ; rdfs:domain TerraCore:Diagnosis ; rdfs:label "ageAtOnset" ; rdfs:range TerraCore:Age ; skos:definition "A reference to the Age of the Donor at the onset of the disease associated with the diagnosis." ; skos:prefLabel "ageAtOnset" ; . TerraCore:confirmedDisease a owl:ObjectProperty ; rdfs:domain TerraCore:Diagnosis ; rdfs:label "confirmedDisease" ; rdfs:range obo:MONDO_0000001 ; . TerraCore:contributedToDeath a owl:ObjectProperty ; rdfs:domain TerraCore:Diagnosis ; rdfs:label "contributedToDeath" ; rdfs:range xsd:boolean ; . TerraCore:dateObtained a rdf:Property ; rdfs:domain TerraCore:BioSample ; rdfs:label "Date Obtained" ; rdfs:range xsd:dateTime ; rdfs:subPropertyOf dct:date ; skos:definition "Date the BioSample was originally obtained from its Donor." ; skos:prefLabel "Date Obtained" ; . TerraCore:dateOfBirth a rdf:Property ; a owl:DatatypeProperty ; rdfs:domain TerraCore:Donor ; rdfs:domain TerraCore:FamilyMember ; rdfs:label "Date of Birth" ; rdfs:range xsd:date ; rdfs:subPropertyOf dct:date ; . TerraCore:dateOfDeath a rdf:Property ; a owl:DatatypeProperty ; rdfs:domain TerraCore:Donor ; rdfs:domain TerraCore:FamilyMember ; rdfs:label "Date of Death" ; rdfs:range xsd:date ; rdfs:range xsd:dateTime ; rdfs:subPropertyOf dct:date ; . TerraCore:donated a owl:ObjectProperty ; rdfs:domain TerraCore:Donor ; rdfs:label "donated" ; rdfs:range TerraCore:BioSample ; owl:inverseOf TerraCore:donatedBy ; skos:definition "The donated property references the BioSample that was contributed by the Donor." ; skos:prefLabel "donated" ; . TerraCore:donatedBy a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "donatedBy" ; rdfs:range TerraCore:Donor ; owl:inverseOf TerraCore:donated ; skos:definition "The donatedBy property references the Donor organism from which the BioSample was acquired." ; skos:prefLabel "donatedBy" ; . TerraCore:exhibitsDisease a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "exhibitsDisease" ; rdfs:range obo:OGMS_0000031 ; . TerraCore:hadAgeAtDeath a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hadAgeAtDeath" ; rdfs:range TerraCore:Age ; skos:definition "A reference to the Age of the Donor at time of death." ; skos:prefLabel "hadAgeAtDeath" ; . TerraCore:hadAssay a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "hadAssay" ; rdfs:range TerraCore:AssayActivity ; rdfs:subPropertyOf prov:wasUsedBy ; skos:prefLabel "hadAssay" ; . TerraCore:hadCellCycle a owl:DatatypeProperty ; rdfs:domain TerraCore:SingleCell ; rdfs:label "hadCellCycle" ; rdfs:range xsd:anyURI ; rdfs:range xsd:string ; skos:definition "A property that describes the stage of the cell cycle at the time the sample was obtained." ; skos:prefLabel "hadCellCycle" ; . TerraCore:hadCellState a owl:DatatypeProperty ; rdfs:domain TerraCore:SingleCell ; rdfs:label "hadCellState" ; rdfs:range xsd:anyURI ; rdfs:range xsd:string ; skos:definition "A property that describes the cell’s metabolic or electrophysiological state." ; skos:prefLabel "hadCellState" ; . TerraCore:hadDiagnosis a owl:DatatypeProperty ; rdfs:comment "Considering using HANCESTRO ancestry category subclasses as options here. In the meantime, capturing a text string. Also consider whether we need to track reported and genetic as determined by genetic analysis." ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hadDiagnosis" ; rdfs:range TerraCore:Diagnosis ; skos:definition "A property that relects a HumanDonor's reported race. " ; skos:prefLabel "had diagnosis" ; . TerraCore:hadLibraryPrep a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "hadLibraryPrep" ; rdfs:range TerraCore:LibraryPreparation ; rdfs:subPropertyOf prov:wasUsedBy ; skos:prefLabel "hadLibraryPrep" ; . TerraCore:hadMannerOfDeath a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "had manner of death" ; rdfs:range xsd:string ; skos:prefLabel "had manner of death" ; . TerraCore:hadProtocol a owl:DatatypeProperty ; rdfs:domain TerraCore:Activity ; rdfs:label "hadProtocol" ; rdfs:range xsd:anyURI ; rdfs:range xsd:string ; rdfs:subPropertyOf prov:used ; skos:prefLabel "hadProtocol" ; . TerraCore:hadSequencing a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "hadSequencing" ; rdfs:range TerraCore:Sequencing ; rdfs:subPropertyOf prov:wasUsedBy ; skos:prefLabel "hadSequencing" ; . TerraCore:hasAge a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:domain TerraCore:Donor ; rdfs:domain TerraCore:FamilyMember ; rdfs:label "hasAge" ; rdfs:range TerraCore:Age ; skos:definition "A reference to the Age of the Donor at the point in time that data was collected or that the BioSample was obtained." ; skos:prefLabel "hasAge" ; . TerraCore:hasAgeCategory a owl:DatatypeProperty ; rdfs:domain TerraCore:Age ; rdfs:label "hasAgeCategory" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "Embryonic" "Postnatal" ) ; ] ; skos:prefLabel "hasAgeCategory" ; . TerraCore:hasAgeUnit a owl:DatatypeProperty ; rdfs:domain TerraCore:Age ; rdfs:label "hasAgeUnit" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "days" "years" ) ; ] ; rdfs:subPropertyOf TerraCore:hasUnit ; skos:definition "A reference to the unit of time during which an entity has existed." ; . TerraCore:hasAlignedFragments a owl:DatatypeProperty ; rdfs:comment "For alignment file types." ; rdfs:domain TerraCore:AlignmentFile ; rdfs:domain TerraCore:File ; rdfs:label "hasAlignedFragments" ; rdfs:range xsd:integer ; skos:prefLabel "hasAlignedFragments" ; . TerraCore:hasAllele a owl:DatatypeProperty ; rdfs:domain TerraCore:VariantCall ; rdfs:label "hasAllele" ; rdfs:range xsd:string ; skos:prefLabel "hasAllele" ; . TerraCore:hasAlpha2Code a owl:AnnotationProperty ; rdfs:domain TerraCore:Country ; rdfs:label "hasAlpha2Code" ; rdfs:range xsd:string ; . TerraCore:hasAnatomicalRegion a owl:DatatypeProperty ; rdfs:comment "Many groups are convening to define Common Coordinate Frameworks for specific organs/species. This will be a rapidly evolving area in the near future. Thus allowing text or URI as we wait for the field to mature allows us to support what we hope will at a minimum be controlled vocabulary under discussion of these groups." ; rdfs:domain TerraCore:SingleCell ; rdfs:label "hasAnatomicalRegion" ; rdfs:range xsd:anyURI ; rdfs:range xsd:string ; skos:definition "A reference to the physical location within the AnatomicalSite from which the BioSample was taken." ; skos:prefLabel "hasAnatomicalRegion" ; . TerraCore:hasAnatomicalSite a owl:DatatypeProperty ; rdfs:comment "May want to consider restricting this to UBERON terms but currently any URI is allowed." ; rdfs:domain TerraCore:BioSample ; rdfs:label "hasAnatomicalSite" ; rdfs:range xsd:anyURI ; skos:definition "A reference to the site within the organism from which the BioSample was taken." ; skos:prefLabel "hasAnatomicalSite" ; . TerraCore:hasAntibody a owl:ObjectProperty ; rdfs:comment "Antibody should be linked to OBI in future." ; rdfs:domain TerraCore:AssayActivity ; rdfs:domain obo:OBI_0001954 ; rdfs:label "hasAntibody" ; rdfs:range TerraCore:Antibody ; rdfs:subPropertyOf prov:used ; skos:prefLabel "hasAntibody" ; . TerraCore:hasAprioriCellType a owl:ObjectProperty ; rdfs:domain TerraCore:SingleCell ; rdfs:label "hasAprioriCellType" ; rdfs:range obo:CL_0000003 ; . TerraCore:hasAssayCategory a owl:ObjectProperty ; rdfs:comment "Subject to Terra Core Team Review; seems useful to group assays but still support an ontology term which is recorded in hasAssayType. This set of options is used by Encode." ; rdfs:domain TerraCore:AssayActivity ; rdfs:label "hasAssayCategory" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "DNA Binding" "DNA Accessibility" "DNA Methylation" "3D Chromatin Structure" "Transcription" "RNA Binding" ) ; ] ; . TerraCore:hasAssayType a owl:ObjectProperty ; rdfs:domain TerraCore:AssayActivity ; rdfs:label "hasAssayType" ; rdfs:range obo:OBI_0000070 ; . TerraCore:hasAverageReadLength a owl:DatatypeProperty ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasAverageReadLength" ; rdfs:range xsd:decimal ; . TerraCore:hasBioSampleType a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "hasBioSampleType" ; rdfs:range TerraCoreValueSets:BioSampleType ; rdfs:subPropertyOf TerraCore:hasSampleType ; . TerraCore:hasBirthYear a rdf:Property ; a owl:DatatypeProperty ; rdfs:domain TerraCore:Donor ; rdfs:domain TerraCore:FamilyMember ; rdfs:label "has birth year" ; rdfs:range xsd:integer ; . TerraCore:hasChecksum a owl:DatatypeProperty ; rdfs:domain TerraCore:File ; rdfs:label "hasChecksum" ; rdfs:range xsd:string ; skos:prefLabel "hasChecksum" ; . TerraCore:hasChild a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hasChild" ; rdfs:range TerraCore:FamilyMember ; rdfs:range TerraCore:HumanDonor ; skos:definition "A property that identifies genetic children." ; . TerraCore:hasChromosome a owl:DatatypeProperty ; rdfs:domain TerraCore:ChromosomalLocation ; rdfs:label "hasChromosome" ; rdfs:range xsd:string ; skos:prefLabel "hasChromosome" ; . TerraCore:hasClonality a owl:DatatypeProperty ; rdfs:domain TerraCore:Antibody ; rdfs:label "hasClonality" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "monoclonal" "polyclonal" ) ; ] ; . TerraCore:hasCountry a owl:ObjectProperty ; rdfs:label "hasCountry" ; . TerraCore:hasCrossReference a owl:ObjectProperty ; rdfs:label "hasCrossReference" ; rdfs:range xsd:anyURI ; rdfs:range xsd:string ; rdfs:subPropertyOf skos:closeMatch ; skos:definition "Reference to the entity in another electronic system. The data stored about the entity may vary from system to system, but this relationship asserts that the reference represents the same entity." ; skos:prefLabel "hasCrossReference" ; . TerraCore:hasCurrentAddress a owl:ObjectProperty ; rdfs:domain prov:Organization ; rdfs:domain prov:Person ; rdfs:label "hasCurrentAddress" ; rdfs:range TerraCore:Address ; . TerraCore:hasDataModality a owl:ObjectProperty ; rdfs:domain TerraCore:Activity ; rdfs:domain TerraCore:File ; rdfs:label "hasDataModality" ; rdfs:range TerraCoreValueSets:DataModality ; . TerraCore:hasDataUseLimitation rdfs:domain TerraCore:Donor ; rdfs:domain TerraCore:File ; rdfs:domain TerraCore:Library ; rdfs:domain TerraCore:Sample ; . TerraCore:hasDataUseRequirement rdfs:domain TerraCore:Donor ; rdfs:domain TerraCore:File ; rdfs:domain TerraCore:Library ; rdfs:domain TerraCore:Sample ; . TerraCore:hasDevelopmentalStage a owl:ObjectProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "hasDevelopmentalStage" ; rdfs:range xsd:anyURI ; rdfs:range xsd:string ; skos:prefLabel "hasDevelopmentalStage" ; . TerraCore:hasDuplicateFragments a owl:DatatypeProperty ; rdfs:comment "For alignment data types." ; rdfs:domain TerraCore:AlignmentFile ; rdfs:domain TerraCore:File ; rdfs:label "hasDuplicateFragments" ; rdfs:range xsd:integer ; skos:prefLabel "hasDuplicateFragments" ; . TerraCore:hasEstimatedLibrarySize a owl:DatatypeProperty ; rdfs:comment "For alignment file types." ; rdfs:domain TerraCore:AlignmentFile ; rdfs:domain TerraCore:File ; rdfs:label "hasEstimatedLibrarySize" ; rdfs:range xsd:integer ; skos:prefLabel "hasEstimatedLibrarySize" ; . TerraCore:hasEthnicity a owl:DatatypeProperty ; rdfs:comment "Considering using HANCESTRO ancestry category subclasses as options here. In the meantime, capturing a text string. Also consider whether we need to track reported and genetic as determined by genetic analysis." ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "has ethnicity" ; rdfs:range xsd:string ; skos:definition "A property that relects a HumanDonor's reported ethnic origin. " ; skos:prefLabel "has ethnicity" ; . TerraCore:hasFamilyID a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hasFamilyID" ; rdfs:range xsd:string ; skos:definition "A property identifies the family with whom this Donor is affiliated." ; . TerraCore:hasFileFormat a owl:DatatypeProperty ; rdfs:comment "Indicate the full file extension including compression extensions." ; rdfs:domain TerraCore:File ; rdfs:label "hasFileFormat" ; rdfs:range xsd:string ; rdfs:subPropertyOf dct:format ; . TerraCore:hasFragments a owl:DatatypeProperty ; rdfs:comment "For alignment file types." ; rdfs:domain TerraCore:AlignmentFile ; rdfs:domain TerraCore:File ; rdfs:label "hasFragments" ; rdfs:range xsd:integer ; skos:prefLabel "hasFragments" ; . TerraCore:hasGRCName a owl:DatatypeProperty ; rdfs:comment "Name of the Reference Assembly in Genome Reference Consortium format (ncbi.nlm.nih.gov/grc. Still draft." ; rdfs:label "hasGRCName" ; rdfs:range xsd:string ; skos:prefLabel "hasGRCName" ; . TerraCore:hasHalfSibling a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hasHalfSibling" ; rdfs:range TerraCore:FamilyMember ; rdfs:range TerraCore:HumanDonor ; skos:definition "A property that identifies genetic half siblings." ; . TerraCore:hasLibraryLayout a owl:DatatypeProperty ; rdfs:domain TerraCore:Library ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasLibraryLayout" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "paired" "single" ) ; ] ; skos:prefLabel "hasLibraryLayout" ; . TerraCore:hasLibraryPreparationType a owl:ObjectProperty ; rdfs:domain TerraCore:Library ; rdfs:domain TerraCore:LibraryPreparation ; rdfs:label "hasLibraryPreparationType" ; rdfs:range obo:OBI_0000711 ; . TerraCore:hasLocation a owl:DatatypeProperty ; rdfs:comment "Location of variation on a sequence. For example, for human genome: chr7:140753336-140753337" ; rdfs:domain TerraCore:SequenceLocation ; rdfs:label "hasLocation" ; rdfs:range xsd:string ; . TerraCore:hasLowerBound a owl:DatatypeProperty ; rdfs:domain TerraCore:Age ; rdfs:domain TerraCore:Weight ; rdfs:label "hasLowerBound" ; rdfs:range xsd:decimal ; skos:prefLabel "hasLowerBound" ; . TerraCore:hasMailingAddress a rdf:Property ; rdfs:domain TerraCore:Address ; rdfs:label "hasMailingAddress" ; rdfs:range xsd:string ; skos:definition "Text form of the address, including country and postal code." ; . TerraCore:hasMedicalHistory a owl:ObjectProperty ; rdfs:domain TerraCore:Donor ; rdfs:label "hasMedicalHistory" ; rdfs:range TerraCore:MedicalHistory ; . TerraCore:hasMolecularSampleType a owl:ObjectProperty ; rdfs:domain TerraCore:MolecularSample ; rdfs:label "hasMolecularSampleType" ; rdfs:range TerraCoreValueSets:MolecularSampleType ; rdfs:subPropertyOf TerraCore:hasSampleType ; . TerraCore:hasNonDuplicatedFragments a owl:DatatypeProperty ; rdfs:comment "For alignment file types." ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasNonDuplicatedFragments" ; rdfs:range xsd:integer ; skos:prefLabel "hasNonDuplicatedFragments" ; . TerraCore:hasOrganism a owl:ObjectProperty ; rdfs:comment "For example: Homo sapiens from obo:NCBITaxon_9606" ; rdfs:domain TerraCore:Donor ; rdfs:label "hasOrganism" ; rdfs:range obo:OBI_0100026 ; skos:definition "A reference to the organism type." ; skos:prefLabel "hasOrganism" ; . TerraCore:hasPairedEndIdentifier a owl:DatatypeProperty ; rdfs:label "hasPairedEndIdentifier" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( 1 2 ) ; ] ; . TerraCore:hasParent a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hasParent" ; rdfs:range TerraCore:FamilyMember ; rdfs:range TerraCore:HumanDonor ; skos:definition "A property that identifies genetic parents." ; . TerraCore:hasPercentAlignedReads a owl:DatatypeProperty ; rdfs:comment "Domain will change from File to SequencingOutputFile or SequenceActivity in future." ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasPercentAlignedReads" ; rdfs:range xsd:decimal ; skos:prefLabel "hasPercentAlignedReads" ; . TerraCore:hasPercentDuplicateFragments a owl:DatatypeProperty ; rdfs:comment "For alignment file types." ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasPercentDuplicateFragments" ; rdfs:range xsd:decimal ; skos:prefLabel "hasPercentDuplicateFragments" ; . TerraCore:hasPostalCode a rdf:Property ; rdfs:domain TerraCore:Address ; rdfs:label "hasPostalCode" ; rdfs:range xsd:string ; . TerraCore:hasPreservationState a owl:DatatypeProperty ; rdfs:domain TerraCore:BioSample ; rdfs:label "hasPreservationState" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "Cryopreserved" "FFPE" "Fresh" "Frozen" "OCT" "Snap Frozen" ) ; ] ; skos:definition "Method used to preserve the BioSample, if relevant, or Fresh for BioSamples that were not preserved." ; . TerraCore:hasRace a owl:DatatypeProperty ; rdfs:comment "Considering using HANCESTRO ancestry category subclasses as options here. In the meantime, capturing a text string. Also consider whether we need to track reported and genetic as determined by genetic analysis." ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hasRace" ; rdfs:range xsd:string ; skos:definition "A property that relects a HumanDonor's reported race. " ; skos:prefLabel "has race" ; . TerraCore:hasReadCount a owl:DatatypeProperty ; rdfs:comment "Domain will change from File to SequencingOutputFile or SequenceActivity in future." ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasReadCount" ; rdfs:range xsd:integer ; skos:prefLabel "hasReadCount" ; . TerraCore:hasReadLength a owl:DatatypeProperty ; rdfs:comment "Domain will change from File to SequencingOutputFile or SequenceActivity in future." ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "hasReadLength" ; rdfs:range xsd:integer ; skos:prefLabel "hasReadLength" ; . TerraCore:hasSampleType a owl:ObjectProperty ; rdfs:domain TerraCore:Sample ; rdfs:label "hasSampleType" ; . TerraCore:hasSequenceLocation a owl:ObjectProperty ; rdfs:domain TerraCore:VariantCall ; rdfs:label "hasSequenceLocation" ; rdfs:range TerraCore:SequenceLocation ; skos:prefLabel "hasSequenceLocation" ; . TerraCore:hasSex a owl:ObjectProperty ; rdfs:domain TerraCore:Donor ; rdfs:label "hasSex" ; rdfs:range TerraCore:BiologicalSex ; skos:definition "A reference to the BiologicalSex of the Donor organism." ; skos:prefLabel "hasSex" ; . TerraCore:hasSibling a owl:ObjectProperty ; rdfs:domain TerraCore:FamilyMember ; rdfs:domain TerraCore:HumanDonor ; rdfs:label "hasSibling" ; rdfs:range TerraCore:FamilyMember ; rdfs:range TerraCore:HumanDonor ; skos:definition "A property that identifies full genetic siblings." ; . TerraCore:hasStartPosition a owl:DatatypeProperty ; rdfs:domain TerraCore:SequenceLocation ; rdfs:label "hasStartPosition" ; rdfs:range xsd:integer ; . TerraCore:hasStopPosition a owl:DatatypeProperty ; rdfs:domain TerraCore:SequenceLocation ; rdfs:label "hasStopPosition" ; rdfs:range xsd:integer ; . TerraCore:hasStrain a owl:DatatypeProperty ; rdfs:domain TerraCore:MouseDonor ; rdfs:label "hasStrain" ; rdfs:range xsd:string ; skos:definition "Text string to represent the strain." ; skos:prefLabel "hasStrain" ; . TerraCore:hasTarget a owl:DatatypeProperty ; rdfs:comment "Target is a string for now but will ultimately be a class." ; rdfs:domain TerraCore:Antibody ; rdfs:domain TerraCore:AssayActivity ; rdfs:label "hasTarget" ; rdfs:range xsd:anyURI ; skos:prefLabel "hasTarget" ; . TerraCore:hasUnit a owl:DatatypeProperty ; rdfs:label "hasUnit" ; skos:prefLabel "hasUnit" ; . TerraCore:hasUpperBound a owl:DatatypeProperty ; rdfs:domain TerraCore:Age ; rdfs:domain TerraCore:Weight ; rdfs:label "hasUpperBound" ; rdfs:range xsd:decimal ; skos:prefLabel "hasUpperBound" ; . TerraCore:hasVariantCall a owl:ObjectProperty ; rdfs:domain TerraCore:VariantCallSet ; rdfs:label "hasVariantCall" ; rdfs:range TerraCore:VariantCall ; skos:prefLabel "hasVariantCall" ; . TerraCore:hasVariantReference a owl:ObjectProperty ; rdfs:domain TerraCore:VariantCall ; rdfs:label "hasVariantReference" ; rdfs:range xsd:string ; rdfs:subPropertyOf skos:relatedMatch ; . TerraCore:hasVersion a owl:DatatypeProperty ; rdfs:label "hasVersion" ; rdfs:range xsd:string ; . TerraCore:hasWeight a owl:ObjectProperty ; rdfs:domain obo:BFO_0000040 ; rdfs:label "hasWeight" ; rdfs:range TerraCore:Weight ; skos:definition "A property that provides a measurement of the mass of a material entity." ; . TerraCore:hasWeightUnit a owl:DatatypeProperty ; rdfs:domain TerraCore:Weight ; rdfs:label "hasWeightUnit" ; rdfs:range [ a rdfs:Datatype ; owl:oneOf ( "lbs" "kg" ) ; ] ; rdfs:subPropertyOf TerraCore:hasUnit ; skos:definition "A reference to the measurement unit for mass." ; . TerraCore:investigatedBy a owl:ObjectProperty ; rdfs:label "investigatedBy" ; skos:prefLabel "investigatedBy" ; . TerraCore:isWholeCell a owl:ObjectProperty ; rdfs:domain TerraCore:SingleCell ; rdfs:label "isWholeCell" ; rdfs:range xsd:boolean ; . TerraCore:usedLibrary a owl:ObjectProperty ; rdfs:domain TerraCore:SequenceFile ; rdfs:domain TerraCore:Sequencing ; rdfs:label "usedLibrary" ; rdfs:range TerraCore:Library ; rdfs:subPropertyOf prov:used ; . TerraCore:usedReferenceAssembly a owl:ObjectProperty ; rdfs:comment "Still in draft" ; rdfs:domain TerraCore:Alignment ; rdfs:domain TerraCore:AlignmentFile ; rdfs:domain TerraCore:SequenceFile ; rdfs:domain TerraCore:Sequencing ; rdfs:label "usedReferenceAssembly" ; rdfs:range TerraCore:ReferenceAssembly ; rdfs:subPropertyOf prov:used ; skos:prefLabel "usedReferenceAssembly" ; . TerraCore:usedSample a owl:ObjectProperty ; rdfs:label "usedSample" ; rdfs:range TerraCore:BioSample ; rdfs:subPropertyOf prov:used ; skos:prefLabel "usedSample" ; . TerraCore:wasFundedBy a owl:ObjectProperty ; rdfs:label "wasFundedBy" ; skos:definition "A relationship defining the funding source. The range is expected to include grants, organizations, or a string indicating the funding source." ; . TerraCore:wasGeneratedByPipeline a owl:ObjectProperty ; rdfs:label "wasGeneratedByPipeline" ; rdfs:range TerraCore:Pipeline ; rdfs:subPropertyOf prov:wasGeneratedBy ; . TerraCore:wasPairedWith a owl:ObjectProperty ; rdfs:domain TerraCore:Library ; rdfs:domain TerraCore:SequenceFile ; rdfs:label "wasPairedWith" ; rdfs:range TerraCore:Library ; rdfs:range TerraCore:SequenceFile ; . obo:BFO_0000001 owl:equivalentClass prov:Entity ; . obo:NCBITaxon_10090 skos:definition "Instance of Mus musculus organism to define organism type." ; . obo:NCBITaxon_9606 skos:definition "Instance of Homo sapiens organism to define organism type." ; . obo:OGMS_0000031 owl:equivalentClass obo:MONDO_0000001 ; . prov:Agent owl:equivalentClass <http://xmlns.com/foaf/0.1/Agent> ; . prov:Entity owl:equivalentClass obo:BFO_0000001 ; . prov:Person owl:equivalentClass <http://xmlns.com/foaf/0.1/Person> ; . prov:SoftwareAgent rdfs:subClassOf [ a owl:Restriction ; owl:minCardinality "0"^^xsd:nonNegativeInteger ; owl:onProperty dct:hasVersion ; ] ; . prov:hadDerivation a owl:ObjectProperty ; rdfs:label "hadDerivation" ; owl:inverseOf prov:wasDerivedFrom ; prov:definition "Inverse of prov:wasDerivedFrom" ; . prov:used owl:inverseOf prov:wasUsedBy ; . prov:wasUsedBy a owl:ObjectProperty ; rdfs:label "wasUsedBy" ; rdfs:subPropertyOf prov:wasInfluencedBy ; skos:prefLabel "wasUsedBy" ; . <http://xmlns.com/foaf/0.1/Agent> owl:equivalentClass prov:Agent ; .
14,250
https://github.com/twocatsinatrenchcoat/code-golf/blob/master/js/codemirror-legacy/_clike.js
Github Open Source
Open Source
MIT
2,022
code-golf
twocatsinatrenchcoat
JavaScript
Code
2,067
5,623
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { mod(require("./_codemirror")); })(function(CodeMirror) { "use strict"; function Context(indented, column, type, info, align, prev) { this.indented = indented; this.column = column; this.type = type; this.info = info; this.align = align; this.prev = prev; } function pushContext(state, col, type, info) { var indent = state.indented; if (state.context && state.context.type == "statement" && type != "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, info, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } function typeBefore(stream, state, pos) { if (state.prevToken == "variable" || state.prevToken == "type") return true; if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; } function isTopScope(context) { for (;;) { if (!context || context.type == "top") return true; if (context.type == "}" && context.prev.info != "namespace") return false; context = context.prev; } } CodeMirror.defineMode("clike", function(config, parserConfig) { var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, dontAlignCalls = parserConfig.dontAlignCalls, keywords = parserConfig.keywords || {}, types = parserConfig.types || {}, builtin = parserConfig.builtin || {}, blockKeywords = parserConfig.blockKeywords || {}, defKeywords = parserConfig.defKeywords || {}, atoms = parserConfig.atoms || {}, hooks = parserConfig.hooks || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false, indentSwitch = parserConfig.indentSwitch !== false, namespaceSeparator = parserConfig.namespaceSeparator, isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, numberStart = parserConfig.numberStart || /[\d\.]/, number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/, // An optional function that takes a {string} token and returns true if it // should be treated as a builtin. isReservedIdentifier = parserConfig.isReservedIdentifier || false; var curPunc, isDefKeyword; function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (numberStart.test(ch)) { stream.backUp(1) if (stream.match(number)) return "number" stream.next() } if (isPunctuationChar.test(ch)) { curPunc = ch; return null; } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} return "operator"; } stream.eatWhile(isIdentifierChar); if (namespaceSeparator) while (stream.match(namespaceSeparator)) stream.eatWhile(isIdentifierChar); var cur = stream.current(); if (contains(keywords, cur)) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; if (contains(defKeywords, cur)) isDefKeyword = true; return "keyword"; } if (contains(types, cur)) return "type"; if (contains(builtin, cur) || (isReservedIdentifier && isReservedIdentifier(cur))) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; return "builtin"; } if (contains(atoms, cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function maybeEOL(stream, state) { if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), indented: 0, startOfLine: true, prevToken: null }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) { maybeEOL(stream, state); return null; } curPunc = isDefKeyword = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) while (state.context.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || (ctx.type == "statement" && curPunc == "newstatement"))) { pushContext(state, stream.column(), "statement", stream.current()); } if (style == "variable" && ((state.prevToken == "def" || (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && isTopScope(state.context) && stream.match(/^\s*\(/, false))))) style = "def"; if (hooks.token) { var result = hooks.token(stream, state, style); if (result !== undefined) style = result; } if (style == "def" && parserConfig.styleDefs === false) style = "variable"; state.startOfLine = false; state.prevToken = isDefKeyword ? "def" : style || curPunc; maybeEOL(stream, state); return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); var closing = firstChar == ctx.type; if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; if (parserConfig.dontIndentStatements) while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) ctx = ctx.prev if (hooks.indent) { var hook = hooks.indent(state, ctx, textAfter, indentUnit); if (typeof hook == "number") return hook } var switchBlock = ctx.prev && ctx.prev.info == "switch"; if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev return ctx.indented } if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1); if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; return ctx.indented + (closing ? 0 : indentUnit) + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); }, electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", lineComment: "//", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function contains(words, word) { if (typeof words === "function") { return words(word); } else { return words.propertyIsEnumerable(word); } } var cKeywords = "auto if break case register continue return default do sizeof " + "static else struct switch extern typedef union for goto while enum const " + "volatile inline restrict asm fortran"; // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20. var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch " + "class compl concept constexpr const_cast decltype delete dynamic_cast " + "explicit export final friend import module mutable namespace new noexcept " + "not not_eq operator or or_eq override private protected public " + "reinterpret_cast requires static_assert static_cast template this " + "thread_local throw try typeid typename using virtual xor xor_eq"; var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy " + "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " + "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " + "@public @package @private @protected @required @optional @try @catch @finally @import " + "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"; var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION " + " NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER " + "NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION " + "NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT" // Do not use this. Use the cTypes function below. This is global just to avoid // excessive calls when cTypes is being called multiple times during a parse. var basicCTypes = words("int long char short double float unsigned signed " + "void bool"); // Do not use this. Use the objCTypes function below. This is global just to avoid // excessive calls when objCTypes is being called multiple times during a parse. var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL"); // Returns true if identifier is a "C" type. // C type is defined as those that are reserved by the compiler (basicTypes), // and those that end in _t (Reserved by POSIX for types) // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html function cTypes(identifier) { return contains(basicCTypes, identifier) || /.+_t$/.test(identifier); } // Returns true if identifier is a "Objective C" type. function objCTypes(identifier) { return cTypes(identifier) || contains(basicObjCTypes, identifier); } var cBlockKeywords = "case do else for if switch while struct enum union"; var cDefKeywords = "struct enum union"; function cppHook(stream, state) { if (!state.startOfLine) return false for (var ch, next = null; ch = stream.peek();) { if (ch == "\\" && stream.match(/^.$/)) { next = cppHook break } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { break } stream.next() } state.tokenize = next return "meta" } function pointerHook(_stream, state) { if (state.prevToken == "type") return "type"; return false; } // For C and C++ (and ObjC): identifiers starting with __ // or _ followed by a capital letter are reserved for the compiler. function cIsReservedIdentifier(token) { if (!token || token.length < 2) return false; if (token[0] != '_') return false; return (token[1] == '_') || (token[1] !== token[1].toLowerCase()); } function cpp14Literal(stream) { stream.eatWhile(/[\w\.']/); return "number"; } function cpp11StringHook(stream, state) { stream.backUp(1); // Raw strings. if (stream.match(/^(?:R|u8R|uR|UR|LR)/)) { var match = stream.match(/^"([^\s\\()]{0,16})\(/); if (!match) { return false; } state.cpp11RawStringDelim = match[1]; state.tokenize = tokenRawString; return tokenRawString(stream, state); } // Unicode strings/chars. if (stream.match(/^(?:u8|u|U|L)/)) { if (stream.match(/^["']/, /* eat */ false)) { return "string"; } return false; } // Ignore this hook. stream.next(); return false; } function cppLooksLikeConstructor(word) { var lastTwo = /(\w+)::~?(\w+)$/.exec(word); return lastTwo && lastTwo[1] == lastTwo[2]; } // C#-style strings where "" escapes a quote. function tokenAtString(stream, state) { var next; while ((next = stream.next()) != null) { if (next == '"' && !stream.eat('"')) { state.tokenize = null; break; } } return "string"; } // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where // <delim> can be a string up to 16 characters long. function tokenRawString(stream, state) { // Escape characters that have special regex meanings. var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); var match = stream.match(new RegExp(".*?\\)" + delim + '"')); if (match) state.tokenize = null; else stream.skipToEnd(); return "string"; } function def(mime, mode) { var words = []; function add(obj) { if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop); } add(mode.keywords); add(mode.types); add(mode.builtin); add(mode.atoms); if (words.length) { mode.helperType = mime; CodeMirror.registerHelper("hintWords", mime, words); } CodeMirror.defineMIME(mime, mode); } def("text/x-c", { name: "clike", keywords: words(cKeywords), types: cTypes, blockKeywords: words(cBlockKeywords), defKeywords: words(cDefKeywords), typeFirstDefinitions: true, atoms: words("NULL true false"), isReservedIdentifier: cIsReservedIdentifier, hooks: { "#": cppHook, "*": pointerHook, }, modeProps: {fold: ["brace", "include"]} }); def("text/x-java", { name: "clike", keywords: words("abstract assert break case catch class const continue default " + "do else enum extends final finally for goto if implements import " + "instanceof interface native new package private protected public " + "return static strictfp super switch synchronized this throw throws transient " + "try volatile while @interface"), types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), blockKeywords: words("catch class do else finally for if switch try while"), defKeywords: words("class interface enum @interface"), typeFirstDefinitions: true, atoms: words("true false null"), number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, hooks: { "@": function(stream) { // Don't match the @interface keyword. if (stream.match('interface', false)) return false; stream.eatWhile(/[\w\$_]/); return "meta"; } }, modeProps: {fold: ["brace", "import"]} }); def("text/x-c-sharp", { name: "clike", keywords: words("abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in interface internal is lock namespace new" + " operator out override params private protected public readonly ref return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield"), types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"), blockKeywords: words("catch class do else finally for foreach if struct switch try while"), defKeywords: words("class interface namespace struct var"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: { "@": function(stream, state) { if (stream.eat('"')) { state.tokenize = tokenAtString; return tokenAtString(stream, state); } stream.eatWhile(/[\w\$_]/); return "meta"; } } }); });
41,734
https://github.com/zackcl/UpGrade/blob/master/backend/packages/Upgrade/src/api/controllers/validators/MarkExperimentValidator.ts
Github Open Source
Open Source
BSD-3-Clause
2,022
UpGrade
zackcl
TypeScript
Code
34
106
import { IsNotEmpty, IsDefined } from 'class-validator'; export class MarkExperimentValidator { public partitionId: string | undefined; @IsNotEmpty() @IsDefined() public experimentPoint: string; @IsNotEmpty() @IsDefined() public userId: string; @IsNotEmpty() @IsDefined() public condition: string | null; }
50,189
https://github.com/ArshanAlam/sandbox/blob/master/algorithms-data-structures/ctci/04.Trees.and.Graphs/Graph/Graph.h
Github Open Source
Open Source
Apache-2.0
2,023
sandbox
ArshanAlam
C++
Code
141
308
/** * Graph * * A template for a graph. */ #ifndef __GRAPH_H__ #define __GRAPH_H__ using namespace std; #include <vector> typedef struct GraphNode { int data; vector<GraphNode *> children; } GraphNode; typedef bool (*searchCallback)(GraphNode *); class Graph { private: vector<GraphNode *> vertices; public: Graph(); ~Graph(); /** * addVertex * * Add the given graph node to this graph. */ Graph & addVertex(GraphNode *); /** * Apply BFS with the given callback function. * * The callback function is called with each new * node being searched. * * If the callback returns 'false' the search terminates. */ Graph & BFS(searchCallback); /** * Apply DFS with the given callback function. * * The callback function is called with each new * node being searched. * * If the callback returns 'false' the search terminates. */ Graph & DFS(searchCallback); }; // Graph #endif
41,023
https://github.com/wodor/printshop/blob/master/src/WodorNet/PrintShopBundle/Command/MachineModelAddCommand.php
Github Open Source
Open Source
MIT
2,014
printshop
wodor
PHP
Code
141
587
<?php namespace WodorNet\PrintShopBundle\Command; use Doctrine\Common\Persistence\ObjectRepository; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use WodorNet\PrintShopBundle\Entity\MachineModel; class MachineModelAddCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('printshop:model:add') ->setDescription('Hello World example command') ->addArgument('task', InputArgument::REQUIRED, 'What to do' ) ->addArgument('name', InputArgument::OPTIONAL, 'Modelname' ); } protected function execute(InputInterface $input, OutputInterface $output) { $task = $input->getArgument('task'); if(is_callable(array($this, $task))) { $this->{$task}($input, $output); } else{ $output->writeln($task . ' is not a thing to do'); } } /** * @param InputInterface $input * @param OutputInterface $output */ protected function add(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $em = $this->getContainer()->get('doctrine.orm.entity_manager'); $machineModel = new MachineModel(); $machineModel->setName($name); $em->persist($machineModel); $em->flush(); $output->writeln('Added ' . $name . ' machineModel'); } protected function listall(InputInterface $input, OutputInterface $output) { $em = $this->getContainer()->get('doctrine.orm.entity_manager'); /** @var ObjectRepository $repo */ $repo = $em->getRepository('WodorNetPrintShopBundle:MachineModel'); $models = $repo->findAll(); foreach($models as $model) { /** @var MachineModel $model */ $output->writeln(print_r(unserialize(serialize($model)),1)); } } }
35,689
https://github.com/lexand/micro-api-framework/blob/master/tests/units/DispatcherTest.php
Github Open Source
Open Source
MIT
2,019
micro-api-framework
lexand
PHP
Code
198
841
<?php /** * Created by IntelliJ IDEA. * User: alex * Date: 22.07.17 * Time: 16:01 */ namespace microapi; use app\controller\Adminest6547586Ctl; use app\controller\Test6547586Ctl; use GuzzleHttp\Psr7\ServerRequest; use microapi\event\Event; use microapi\http\DefaultResponseFactory; use microapi\util\Tokenizer; use PHPUnit\Framework\TestCase; class DispatcherTest extends TestCase { /** * @var \microapi\http\ResponseFactory */ private static $drf; public static function setUpBeforeClass() { parent::setUpBeforeClass(); static::$drf = new DefaultResponseFactory(); } public function testGetEndpointFromCache() { $sr = new ServerRequest('get', '/'); $d = new Dispatcher(); $d->addDefaultModule('\app'); $d->setEndpointCachePath(TESTS_ROOT . '/data'); $end = $d->getEndpointFromCache($sr, Test6547586Ctl::class, 'get'); self::assertNotNull($end); $res = $end->invoke(static::$drf->create()); static::assertEquals((new Test6547586Ctl())->actionGet(), $res->data); } public function testGetEndpointFromReflection() { $sr = new ServerRequest('get', '/'); $d = new Dispatcher(); $d->addDefaultModule('\app'); $end = $d->getEndpointFromReflection($sr, Test6547586Ctl::class, 'get'); self::assertNotNull($end); $res = $end->invoke(static::$drf->create()); static::assertEquals((new Test6547586Ctl())->actionGet(), $res->data); } public function testGetEndpoint() { $sr = new ServerRequest( 'get', '/test6547586/get' ); $d = new Dispatcher(); $d->addDefaultModule('\app'); $end = $d->getEndpoint( new Tokenizer($sr->getUri()->getPath(), '/', 0), $sr ); self::assertNotNull($end); $res = $end->invoke(static::$drf->create()); static::assertEquals((new Test6547586Ctl())->actionGet(), $res->data); } public function testDispatch() { $_SERVER['REQUEST_URI'] = '/test6547586/get'; $_SERVER['REQUEST_METHOD'] = 'get'; /** @var \microapi\http\WrappedResponse $data */ $data = null; $d = new Dispatcher(); $d->addDefaultModule('\app'); $d->on( 'afterdispatch', [ function (Event $e) use (&$data) { /** @var \microapi\event\object\AfterDispatch $e */ $data = $e->wr; return $e; } ] ); $d->dispatch(); static::assertEquals((new Test6547586Ctl())->actionGet(), $data->data); } }
9,588
https://github.com/StephenBrown2/typer/blob/master/typer/models.py
Github Open Source
Open Source
MIT
null
typer
StephenBrown2
Python
Code
999
3,262
import io from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Type, TypeVar, Union, ) import click if TYPE_CHECKING: # pragma: no cover from .main import Typer # noqa NoneType = type(None) AnyType = Type[Any] Required = ... class Context(click.Context): pass class FileText(io.TextIOWrapper): pass class FileTextWrite(FileText): pass class FileBinaryRead(io.BufferedReader): pass class FileBinaryWrite(io.BufferedWriter): pass class CallbackParam(click.Parameter): pass class DefaultPlaceholder: """ You shouldn't use this class directly. It's used internally to recognize when a default value has been overwritten, even if the new value is `None`. """ def __init__(self, value: Any): self.value = value def __bool__(self) -> bool: return bool(self.value) DefaultType = TypeVar("DefaultType") CommandFunctionType = TypeVar("CommandFunctionType", bound=Callable[..., Any]) def Default(value: DefaultType) -> DefaultType: """ You shouldn't use this function directly. It's used internally to recognize when a default value has been overwritten, even if the new value is `None`. """ return DefaultPlaceholder(value) # type: ignore class CommandInfo: def __init__( self, name: Optional[str] = None, *, cls: Optional[Type[click.Command]] = None, context_settings: Optional[Dict[Any, Any]] = None, callback: Optional[Callable] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: str = "[OPTIONS]", add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, ): self.name = name self.cls = cls self.context_settings = context_settings self.callback = callback self.help = help self.epilog = epilog self.short_help = short_help self.options_metavar = options_metavar self.add_help_option = add_help_option self.no_args_is_help = no_args_is_help self.hidden = hidden self.deprecated = deprecated class TyperInfo: def __init__( self, typer_instance: Optional["Typer"] = Default(None), *, name: Optional[str] = Default(None), cls: Optional[Type[click.Command]] = Default(None), invoke_without_command: bool = Default(False), no_args_is_help: Optional[bool] = Default(None), subcommand_metavar: Optional[str] = Default(None), chain: bool = Default(False), result_callback: Optional[Callable] = Default(None), # Command context_settings: Optional[Dict[Any, Any]] = Default(None), callback: Optional[Callable] = Default(None), help: Optional[str] = Default(None), epilog: Optional[str] = Default(None), short_help: Optional[str] = Default(None), options_metavar: str = Default("[OPTIONS]"), add_help_option: bool = Default(True), hidden: bool = Default(False), deprecated: bool = Default(False), ): self.typer_instance = typer_instance self.name = name self.cls = cls self.invoke_without_command = invoke_without_command self.no_args_is_help = no_args_is_help self.subcommand_metavar = subcommand_metavar self.chain = chain self.result_callback = result_callback self.context_settings = context_settings self.callback = callback self.help = help self.epilog = epilog self.short_help = short_help self.options_metavar = options_metavar self.add_help_option = add_help_option self.hidden = hidden self.deprecated = deprecated class ParameterInfo: def __init__( self, *, default: Optional[Any] = None, param_decls: Optional[Sequence[str]] = None, callback: Optional[Callable] = None, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Optional[Union[str, List[str]]] = None, autocompletion: Optional[Callable] = None, # Choice case_sensitive: bool = True, # Numbers min: Optional[Union[int, float]] = None, max: Optional[Union[int, float]] = None, clamp: bool = False, # DateTime formats: Optional[Union[List[str]]] = None, # File mode: str = None, encoding: Optional[str] = None, errors: Optional[str] = "strict", lazy: Optional[bool] = None, atomic: Optional[bool] = False, # Path exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Union[None, Type[str], Type[bytes]] = None, ): self.default = default self.param_decls = param_decls self.callback = callback self.metavar = metavar self.expose_value = expose_value self.is_eager = is_eager self.envvar = envvar self.autocompletion = autocompletion # Choice self.case_sensitive = case_sensitive # Numbers self.min = min self.max = max self.clamp = clamp # DateTime self.formats = formats # File self.mode = mode self.encoding = encoding self.errors = errors self.lazy = lazy self.atomic = atomic # Path self.exists = exists self.file_okay = file_okay self.dir_okay = dir_okay self.writable = writable self.readable = readable self.resolve_path = resolve_path self.allow_dash = allow_dash self.path_type = path_type class OptionInfo(ParameterInfo): def __init__( self, *, # ParameterInfo default: Optional[Any] = None, param_decls: Optional[Sequence[str]] = None, callback: Optional[Callable] = None, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Optional[Union[str, List[str]]] = None, autocompletion: Optional[Callable] = None, # Option show_default: bool = False, prompt: Union[bool, str] = False, confirmation_prompt: bool = False, hide_input: bool = False, is_flag: Optional[bool] = None, flag_value: Optional[Any] = None, count: bool = False, allow_from_autoenv: bool = True, help: Optional[str] = None, hidden: bool = False, show_choices: bool = True, show_envvar: bool = False, # Choice case_sensitive: bool = True, # Numbers min: Optional[Union[int, float]] = None, max: Optional[Union[int, float]] = None, clamp: bool = False, # DateTime formats: Optional[Union[List[str]]] = None, # File mode: str = None, encoding: Optional[str] = None, errors: Optional[str] = "strict", lazy: Optional[bool] = None, atomic: Optional[bool] = False, # Path exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Union[None, Type[str], Type[bytes]] = None, ): super().__init__( default=default, param_decls=param_decls, callback=callback, metavar=metavar, expose_value=expose_value, is_eager=is_eager, envvar=envvar, autocompletion=autocompletion, # Choice case_sensitive=case_sensitive, # Numbers min=min, max=max, clamp=clamp, # DateTime formats=formats, # File mode=mode, encoding=encoding, errors=errors, lazy=lazy, atomic=atomic, # Path exists=exists, file_okay=file_okay, dir_okay=dir_okay, writable=writable, readable=readable, resolve_path=resolve_path, allow_dash=allow_dash, path_type=path_type, ) self.show_default = show_default self.prompt = prompt self.confirmation_prompt = confirmation_prompt self.hide_input = hide_input self.is_flag = is_flag self.flag_value = flag_value self.count = count self.allow_from_autoenv = allow_from_autoenv self.help = help self.hidden = hidden self.show_choices = show_choices self.show_envvar = show_envvar class ArgumentInfo(ParameterInfo): def __init__( self, *, # ParameterInfo default: Optional[Any] = None, param_decls: Optional[Sequence[str]] = None, callback: Optional[Callable] = None, metavar: Optional[str] = None, expose_value: bool = True, is_eager: bool = False, envvar: Optional[Union[str, List[str]]] = None, autocompletion: Optional[Callable] = None, # Choice case_sensitive: bool = True, # Numbers min: Optional[Union[int, float]] = None, max: Optional[Union[int, float]] = None, clamp: bool = False, # DateTime formats: Optional[Union[List[str]]] = None, # File mode: str = None, encoding: Optional[str] = None, errors: Optional[str] = "strict", lazy: Optional[bool] = None, atomic: Optional[bool] = False, # Path exists: bool = False, file_okay: bool = True, dir_okay: bool = True, writable: bool = False, readable: bool = True, resolve_path: bool = False, allow_dash: bool = False, path_type: Union[None, Type[str], Type[bytes]] = None, ): super().__init__( default=default, param_decls=param_decls, callback=callback, metavar=metavar, expose_value=expose_value, is_eager=is_eager, envvar=envvar, autocompletion=autocompletion, # Choice case_sensitive=case_sensitive, # Numbers min=min, max=max, clamp=clamp, # DateTime formats=formats, # File mode=mode, encoding=encoding, errors=errors, lazy=lazy, atomic=atomic, # Path exists=exists, file_okay=file_okay, dir_okay=dir_okay, writable=writable, readable=readable, resolve_path=resolve_path, allow_dash=allow_dash, path_type=path_type, )
758
https://github.com/AhmedHawam9/ANPA/blob/master/database/factories/Models/CourseCurriculumFactory.php
Github Open Source
Open Source
MIT
null
ANPA
AhmedHawam9
PHP
Code
64
216
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; use App\Course; use App\Models\CourseCurriculum; class CourseCurriculumFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = CourseCurriculum::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'course_id' => Course::factory(), 'type' => $this->faker->randomElement(["video","article","live"]), 'info' => $this->faker->regexify('[A-Za-z0-9]{255}'), ]; } }
34,016
https://github.com/polyfloyd/go-errorlint/blob/master/errorlint/testdata/src/fmterrorf-go1.19/github-36.go
Github Open Source
Open Source
MIT
2,023
go-errorlint
polyfloyd
Go
Code
60
178
package issues import ( "errors" "fmt" ) func Single() error { err1 := errors.New("oops1") err2 := errors.New("oops2") err3 := errors.New("oops3") return fmt.Errorf("%w, %v, %v", err1, err2, err3) } func Multiple() error { err1 := errors.New("oops1") err2 := errors.New("oops2") err3 := errors.New("oops3") return fmt.Errorf("%w, %w, %w", err1, err2, err3) // want "only one %w verb is permitted per format string" }
19,203
https://github.com/jdhenke/pad/blob/master/js/worker.js
Github Open Source
Open Source
MIT
2,014
pad
jdhenke
JavaScript
Code
1,255
2,678
// web worker responsible for heavy lifting of computing diffs. useful because // off of the UI thread, so delays don't 1) slow down a live interface 2) force // the UI to be locked for a long time. // globally define git utility functions: getDiff, rebase, applyDiff importScripts("/js/git.js"); // current state of this document var state = { headText: "", head: 0, clientID: + new Date(), pendingUpdates: [], isUpdating: false, docID: null, paused: false, currentCommit: null, nextDiff: 0, }; // commits diff from headText to newText and sends it to the server. parent is // included because pending live updates makes the use of head inconsistent. function commitAndPush(newText, parent) { var diff = getDiff(state.headText, newText); var commit = { clientID: state.clientID, parent: parent, diff: diff, id: (+ new Date()), // unique ID allows server to deduplicate requests }; // create function to keep trying to commit until successful. function sendCommit() { var req = new XMLHttpRequest(); req.onerror = function() { console.log(this.responseText); setTimeout(sendCommit, 1000); } req.open("put", "/commits/put"); req.setRequestHeader('doc-id', state.docID); req.send(JSON.stringify(commit)); } sendCommit(); } // continuously tries to establish connection and apply served updates function startContinuousPull() { function success() { var commit = JSON.parse(this.responseText); if (commit.parent != state.nextDiff - 1) { console.log("bad commit received"); console.log(JSON.stringify(commit)); console.log(JSON.stringify(state)); } else { state.pendingUpdates.push(commit); state.nextDiff += 1 tryNextUpdate(); } doPull(); } function failure() { console.log(this.responseText); setTimeout(startContinuousPull, 1000); } function cancel() { console.log("request cancel encountered", this.responseText); setTimeout(doPull, 1000); } function doPull() { var req = new XMLHttpRequest(); req.addEventListener("load", success, true); req.addEventListener("error", failure, true); req.addEventListener("abort", cancel, true); req.open("post", "/commits/get"); req.setRequestHeader('doc-id', state.docID); req.setRequestHeader('next-commit', state.nextDiff); req.send(); } // retreive the starting state from the server, then initiate process to // receive all subsequent updates. var req = new XMLHttpRequest(); req.addEventListener("load", function() { state.headText = JSON.parse(this.responseText); state.head = parseInt(this.getResponseHeader("head")); state.nextDiff = state.head + 1; setMainText(state.headText); doPull(); }, true); req.addEventListener("error", function() { console.log(this.responseText); setTimeout(startContinuousPull, 1000); }, true); req.open("post", "/init"); req.setRequestHeader('doc-id', state.docID); req.send(); } // tell main thread to set their text to this function setMainText(text) { postMessage({ type: "set-text", text: text, head: state.head, }); } // if not already trying to update and queued updates from the server exist, // pops the next one off and ensures it is eventually pushed to the UI. function tryNextUpdate() { // ignore if in the middle of an update or there are no updates to apply or // this client is paused. if (state.isUpdating || state.pendingUpdates.length == 0 || state.paused) { return; } // "lock" by marking isUpdating as true, get the next queued commit and rebase // it to head. note, fastForward actually adds it to the list of commits, // making head dangerous to use. state.isUpdating = true; var commit = state.pendingUpdates.shift(); state.currentCommit = commit; // now in an inconsistent state, but it's protected by isPending. headText // is as of head() - 1, because we've added the new commit to commits but did // NOT updating headText. // // now we kick off a back and forth between main and this worker, which only // ends when main accepts a live update. at that point, the logic in the // handler should update headText, release isUpdating, and try again. if (commit.clientID == state.clientID) { // because this commit actually originated from this client, it's been // rebasing it's local changes for every commit up to this point, so there // is no need to modify the UI at all! simply yet the UI know so it can try // another commit and have an up to date head. advanceHeadState(); state.isUpdating = false; postMessage({ type: "commit-received", head: state.head, }); tryNextUpdate(); } else { // this commit came from a different client, so its changes have yet to be // reflected in the UI. initiate the messaging back and forth; the rest of // the logic is in the message handlers. postMessage({ type: "get-live-state", }); } } // adjust head state to reflect the latest diff. now head() is reasonable again. function advanceHeadState() { var newHeadtext = applyDiff(state.headText, state.currentCommit.diff); state.headText = newHeadtext; state.head += 1; } // given data containing the latest state of the UI, rebase the changes since // the last commit reflected in the UI ontop the result of applying the next // commit from the server, and send to the UI. the UI will reply back with a // response, either accepting or rejecting it. this response is handled // separately. // // note: the location of the selection is handled by including two null // characters, one for the start and one for the end. therefore, their locations // are preserved relative to the characters. the only tricky part is that if a // region a cursor was in was deleted, the cursor position must still remain. // therefore, rebase was modified to include an additional insert of a cursor // into the correct location in the event this happens. function tryUpdateMain(data) { var currentText = data.text; var selectionStart = data.selectionStart; var selectionEnd = data.selectionEnd; currentText = currentText.substring(0, selectionStart) + "\x00" + currentText.substring(selectionStart, selectionEnd) + "\x00" + currentText.substring(selectionEnd); var newDiff = state.currentCommit.diff; var localDiff = getDiff(state.headText, currentText); var newLocalDiff = rebase(newDiff, localDiff); var newHeadtext = applyDiff(state.headText, newDiff); var newText = applyDiff(newHeadtext, newLocalDiff); var newSelectionStart = newText.indexOf("\x00"); var newSelectionEnd = newText.lastIndexOf("\x00") - 1; newText = newText.replace("\x00", ""); newText = newText.replace("\x00", ""); postMessage({ type: "live-update", oldState: data, newState: { text: newText, selectionStart: newSelectionStart, selectionEnd: newSelectionEnd, }, head: state.head + 1, }); } // handle messages sent from main onmessage = function(evt) { var data = evt.data; if (data.type == "docID") { // first message this worker should receive; this is the docID which // uniquely identifies the doc this worker is responsible for. only once // this has been given can the worker initiate a continuous back and forth // with the server. state.docID = data.docID; startContinuousPull(); } else if (data.type == "commit") { // main is sending its current state to create a commit and send to the // server. this attempt could be rejected if the diff is empty, or this web // worker is currently updating the UI, which could lead to inconsistent // commits. rejecting still sends back a "commit-received" message, freeing // main to try again. accepting a commit means it will be sent to the server // and commit-received will be sent once the commit is received back from // the server and processed as the latest commit. if (data.text == state.headText || state.isPending || data.parent != state.head) { postMessage({ type: "commit-received", }); } else { commitAndPush(data.text, data.parent); } } else if (data.type == "live-state") { // this web worker is in the middle of trying to push an update to the UI, // so the current state of the UI was requested so it can be adjusted to // incorporate these changes. tryUpdateMain(data.state); } else if (data.type == "live-update-response") { // main has either accepted or rejected the latest "live-update" attempt to // incorporate the latest commit into the UI. if (data.success) { // main has accepted it, so the commit can be finally processed completely // and the next update processed. advanceHeadState(); state.isUpdating = false; tryNextUpdate(); } else { // main rejected the last "live-update" because the user made changes in // the meantime, so using the "live-update" would lose those changes. // therefore, we should request the latest state again, hoping the user is // done making changes for a long enough time for the process to work. postMessage({ type: "get-live-state", }); } } else if (data.type == "pause") { state.paused = true; } else if (data.type == "play") { state.paused = false; tryNextUpdate(); } };
39,114
https://github.com/ZhenchaoWang/passport-oauth/blob/master/oauth-token/src/main/java/org/zhenchao/oauth/token/MacAccessToken.java
Github Open Source
Open Source
Apache-2.0
2,021
passport-oauth
ZhenchaoWang
Java
Code
92
317
package org.zhenchao.oauth.token; import org.zhenchao.oauth.token.enums.TokenType; /** * mac type access token * * @author zhenchao.wang 2017-01-23 17:56 * @version 1.0.0 */ public class MacAccessToken extends AbstractAccessToken { public enum ALGORITHM { HMAC_SHA_1("hmac-sha-1"), HMAC_SHA_256("hmac-sha-256"); private String value; ALGORITHM(String value) { this.value = value; } public String getValue() { return value; } } public static final TokenType TYPE = TokenType.MAC; /** 目前仅支持hmac-sha-1 */ private ALGORITHM algorithm = ALGORITHM.HMAC_SHA_1; @Override public TokenType getType() { return TYPE; } public ALGORITHM getAlgorithm() { return algorithm; } public MacAccessToken setAlgorithm(ALGORITHM algorithm) { this.algorithm = algorithm; return this; } }
8,785
https://github.com/action-hong/unocss/blob/master/packages/vscode/src/annonation.ts
Github Open Source
Open Source
MIT
2,022
unocss
action-hong
TypeScript
Code
313
1,102
import { relative } from 'path' import type { DecorationOptions, ExtensionContext, StatusBarItem } from 'vscode' import { DecorationRangeBehavior, MarkdownString, Range, window, workspace } from 'vscode' import type { UnocssPluginContext } from '@unocss/core' import { INCLUDE_COMMENT_IDE, getMatchedPositions } from './integration' import { log } from './log' import { getPrettiedMarkdown, throttle } from './utils' export async function registerAnnonations( cwd: string, context: UnocssPluginContext, status: StatusBarItem, ext: ExtensionContext, ) { const { sources } = await context.ready const { uno, filter } = context let underline: boolean = workspace.getConfiguration().get('unocss.underline') ?? true ext.subscriptions.push(workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration('unocss.underline')) { underline = workspace.getConfiguration().get('unocss.underline') ?? true updateAnnotation() } })) workspace.onDidSaveTextDocument(async (doc) => { if (sources.includes(doc.uri.fsPath)) { try { await context.reloadConfig() log.appendLine(`Config reloaded by ${relative(cwd, doc.uri.fsPath)}`) } catch (e) { log.appendLine('Error on loading config') log.appendLine(String(e)) } } }) const UnderlineDecoration = window.createTextEditorDecorationType({ textDecoration: 'none; border-bottom: 1px dashed currentColor', rangeBehavior: DecorationRangeBehavior.ClosedClosed, }) const NoneDecoration = window.createTextEditorDecorationType({ textDecoration: 'none', rangeBehavior: DecorationRangeBehavior.ClosedClosed, }) async function updateAnnotation(editor = window.activeTextEditor) { try { const doc = editor?.document if (!doc) return reset() const code = doc.getText() const id = doc.uri.fsPath if (!code || (!code.includes(INCLUDE_COMMENT_IDE) && !filter(code, id))) return reset() const result = await uno.generate(code, { id, preflights: false, minify: true }) const ranges: DecorationOptions[] = ( await Promise.all( getMatchedPositions(code, Array.from(result.matched)) .map(async (i): Promise<DecorationOptions> => { try { const md = await getPrettiedMarkdown(uno, i[2]) return { range: new Range(doc.positionAt(i[0]), doc.positionAt(i[1])), get hoverMessage() { return new MarkdownString(md) }, } } catch (e) { log.appendLine(`Failed to parse ${i[2]}`) log.appendLine(String(e)) return undefined! } }), ) ).filter(Boolean) if (underline) { editor.setDecorations(NoneDecoration, []) editor.setDecorations(UnderlineDecoration, ranges) } else { editor.setDecorations(UnderlineDecoration, []) editor.setDecorations(NoneDecoration, ranges) } status.text = `UnoCSS: ${result.matched.size}` status.tooltip = new MarkdownString(`${result.matched.size} utilities used in this file`) status.show() function reset() { editor?.setDecorations(UnderlineDecoration, []) editor?.setDecorations(NoneDecoration, []) status.hide() } } catch (e) { log.appendLine('Error on annotation') log.appendLine(String(e)) } } const throttledUpdateAnnotation = throttle(updateAnnotation, 200) window.onDidChangeActiveTextEditor(updateAnnotation) workspace.onDidChangeTextDocument((e) => { if (e.document === window.activeTextEditor?.document) throttledUpdateAnnotation() }) await updateAnnotation() }
10,749
https://github.com/dbaba4u/cfresh/blob/master/resources/views/admin/customers/customer_balance_pdfview.blade.php
Github Open Source
Open Source
MIT
null
cfresh
dbaba4u
PHP
Code
343
1,883
<?php $settings = \App\Setting::where('id',1)->first(); $first = \App\Box::all()->first()->id; $last = \App\Box::all()->last()->id; $cases = \App\Box::all(); ?> <!DOCTYPE html> <html lang="en"> <head> {{-- <meta charset="UTF-8">--}} {{-- <meta name="viewport" content="width=device-width, initial-scale=1.0">--}} <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Document</title> <link rel="stylesheet" href="{{asset('frontend/vendors/bootstrap/bootstrap.min.css')}}"> </head> <body > <header class="clearfix" style="padding-bottom: -0.2rem; "> <div id="logo" style="text-align: center; padding-bottom: -1rem"> <img src="data:image/png;base64, {{base64_encode(@file_get_contents(asset('images/logo/Cfresh-label.png')))}}" height="100px" width="100px"><br><br> <h3 class="text-bold text-primary">Customer's Balance Details </h3> <br><br> </div> <div class="row" style="margin-top: 0.5rem;" > <div class="float-left col-md-6" style="width: 350px"> <table class="table table-bordered table-sm" style="font-size: 12px"> <tr > <td style="background-color: darkred; color: white;"><strong>Statement Period</strong></td> <td>{{\Carbon\Carbon::parse($from)->toFormattedDateString()}} to {{\Carbon\Carbon::parse($to)->toFormattedDateString()}}</td> </tr> <tr> <td style="background-color: darkred; color: white;"><strong>Total Opening balance </strong></td> <td> NGN {{number_format($tot_opening_bal,2)}} </td> </tr> <tr> <td style="background-color: darkred; color: white;"><strong>Total Closing balance </strong></td> <td> NGN {{number_format($tot_closing_bal,2)}} </td> </tr> <tr> <td style="background-color: darkred; color: white;"><strong>Total Current balance </strong></td> <td> NGN {{number_format($tot_current_bal,2)}} </td> </tr> {{-- @foreach($cases as $case)--}} {{-- @endforeach--}} {{-- <tr>--}} {{-- <td style="background-color: darkred; color: white;"><strong>In flow</strong></td>--}} {{-- <td>{{number_format($in_flow, 2)}}</td>--}} {{-- </tr>--}} {{-- <tr>--}} {{-- <td style="background-color: darkred; color: white;"><strong>Out flow</strong></td>--}} {{-- <td>{{number_format($out_flow, 2)}}</td>--}} {{-- </tr>--}} </table> </div> <div class="col"></div> <div class="float-right col-md-6" > <table class="table table-borderless table-sm" > <tr> <td><span style="color: darkred; font-size: 14px; text-align: right"><strong><h3>{{$settings->site_name}}</h3></strong></span></td> </tr> <tr> <td style="font-size: 12px; color: #cccccc; text-align: right; padding-top: -0.2rem ">{{$settings->contact_address}}</td> </tr> <tr> <td style="font-size: 12px; color: #cccccc; text-align: right; padding-top: -0.5rem ">{{$settings->contact_email}}-({{$settings->contact_number}})</td> </tr> </table> </div> </div> </header> <div class="table-responsive" style="padding-top: -0.2rem"> <table class="table table-striped table-bordered" style='background: url("data:image/png;base64, {{base64_encode(@file_get_contents(asset('images/logo/dimension.png')))}}"); font-size: 12px' > <thead> <tr style="background-color: darkred; color: white; font-size: 12px"> <th>Name</th> <th>Opening Balance</th> <th>Closing Balance</th> <th>Current Balance</th> <th>Address</th> <th>State</th> <th>Phone</th> <th>Sales Reps</th> </tr> </thead> <tbody> <?php $i = 0 ?> @foreach ($customers as $customer) @if(!empty($customer->name)) <tr> <td>{{$customer->name}}</td> <td>NGN {{number_format($openingBalanace[$i], 2)}}</td> <td>NGN {{number_format($closingBalance[$i], 2)}}</td> <td>NGN {{number_format($currentBalance[$i], 2)}}</td> <td>{{$customer->address}}</td> <td>{{$customer->state->name}}</td> <td>{{$customer->mobile}}</td> <td>{{\App\Employee::where('id',$customer->vendor)->first()->name}}</td> </tr> @endif <?php $i++ ?> @endforeach </tbody> </table> </div> <footer> <script type="text/php"> if ( isset($pdf) ) { $font = $fontMetrics->getFont("Times", "bold"); $color = array(0,0,0); $w = $pdf->get_width(); $h = $pdf->get_height(); $pdf->page_text(30, 810, "{{\Carbon\Carbon::parse(today())->toFormattedDateString()}}-({{\Carbon\Carbon::parse(now())->format('h:i A')}})", $font, 6, array(0,0,1)); $pdf->page_text(270, 810, "Page {PAGE_NUM} of {PAGE_COUNT}", $font, 6, $color); $pdf->page_text(530, 810, "cfresh.org", $font, 8, array(0,0,1)); } </script> </footer> <script src="{{asset('frontend/vendors/jquery/jquery-3.2.1.min.js')}}"></script> <script src="{{ asset('assets/libs/popper.js/dist/popper.min.js') }}"></script> <script src="{{asset('frontend/vendors/bootstrap/bootstrap.bundle.min.js')}}"></script> </body> </html>
37,521
https://github.com/frib-high-level-controls/save-set-restore/blob/master/plugins/org.csstudio.saverestore/src/org/csstudio/saverestore/Utilities.java
Github Open Source
Open Source
MIT
2,016
save-set-restore
frib-high-level-controls
Java
Code
5,176
13,278
/* * This software is Copyright by the Board of Trustees of Michigan * State University (c) Copyright 2016. * * Contact Information: * Facility for Rare Isotope Beam * Michigan State University * East Lansing, MI 48824-1321 * http://frib.msu.edu */ package org.csstudio.saverestore; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import org.csstudio.saverestore.data.Threshold; import org.csstudio.saverestore.data.VDisconnectedData; import org.csstudio.saverestore.data.VNoData; import org.diirt.util.array.ArrayBoolean; import org.diirt.util.array.ArrayByte; import org.diirt.util.array.ArrayDouble; import org.diirt.util.array.ArrayFloat; import org.diirt.util.array.ArrayInt; import org.diirt.util.array.ArrayLong; import org.diirt.util.array.ArrayShort; import org.diirt.util.array.IteratorNumber; import org.diirt.util.array.ListBoolean; import org.diirt.util.array.ListInt; import org.diirt.util.array.ListLong; import org.diirt.util.array.ListNumber; import org.diirt.util.text.NumberFormats; import org.diirt.vtype.Alarm; import org.diirt.vtype.AlarmSeverity; import org.diirt.vtype.Array; import org.diirt.vtype.SimpleValueFormat; import org.diirt.vtype.Time; import org.diirt.vtype.VBoolean; import org.diirt.vtype.VBooleanArray; import org.diirt.vtype.VByte; import org.diirt.vtype.VByteArray; import org.diirt.vtype.VDouble; import org.diirt.vtype.VDoubleArray; import org.diirt.vtype.VEnum; import org.diirt.vtype.VEnumArray; import org.diirt.vtype.VFloat; import org.diirt.vtype.VFloatArray; import org.diirt.vtype.VInt; import org.diirt.vtype.VIntArray; import org.diirt.vtype.VLong; import org.diirt.vtype.VLongArray; import org.diirt.vtype.VNumber; import org.diirt.vtype.VNumberArray; import org.diirt.vtype.VShort; import org.diirt.vtype.VShortArray; import org.diirt.vtype.VString; import org.diirt.vtype.VStringArray; import org.diirt.vtype.VType; import org.diirt.vtype.ValueFactory; import org.diirt.vtype.ValueFormat; /** * * <code>Utilities</code> provides common methods to transform between different data types used by the save and * restore. This class also provides methods to transform the timestamps into human readable formats. All methods are * thread safe. * * @author <a href="mailto:jaka.bobnar@cosylab.com">Jaka Bobnar</a> * */ public final class Utilities { /** * <code>VTypeComparison</code> is the result of comparison of two {@link VType} values. The {@link #string} field * provides the textual representation of the comparison and the {@link #valuesEqual} provides information whether * the values are equal (0), the first value is greater than second (1), or the first value is less than second * (-1). This only applies to scalar values. In case of array values the comparison can only result in 0 or 1. * * @author <a href="mailto:jaka.bobnar@cosylab.com">Jaka Bobnar</a> * */ public static class VTypeComparison { private final String string; private final int valuesEqual; private final boolean withinThreshold; VTypeComparison(String string, int equal, boolean withinThreshold) { this.string = string; this.valuesEqual = equal; this.withinThreshold = withinThreshold; } /** * Returns the string representation of the comparison result. * * @return the comparison result as a string */ public String getString() { return string; } /** * Returns 0 if values are identical, -1 if first value is less than second or 1 otherwise. * * @return the code describing the values equality */ public int getValuesEqual() { return valuesEqual; } /** * Indicates if the values are within the allowed threshold or not. * * @return true if values are within threshold or false otherwise */ public boolean isWithinThreshold() { return withinThreshold; } } /** The character code for the greek delta letter */ public static final char DELTA_CHAR = '\u0394'; private static final char SEMI_COLON = ';'; private static final char COMMA = ','; // All formats use thread locals, to avoid problems if any of the static methods are invoked concurrently private static final ThreadLocal<ValueFormat> FORMAT = ThreadLocal.withInitial(() -> { ValueFormat vf = new SimpleValueFormat(3); vf.setNumberFormat(NumberFormats.toStringFormat()); return vf; }); private static final ThreadLocal<DateFormat> LE_TIMESTAMP_FORMATTER = ThreadLocal .withInitial(() -> new SimpleDateFormat("HH:mm:ss.SSS MMM dd")); private static final ThreadLocal<DateFormat> SLE_TIMESTAMP_FORMATTER = ThreadLocal .withInitial(() -> new SimpleDateFormat("HH:mm:ss.SSS MMM dd yyyy")); private static final ThreadLocal<DateFormat> BE_TIMESTAMP_FORMATTER = ThreadLocal .withInitial(() -> new SimpleDateFormat("MMM dd HH:mm:ss")); private static final ThreadLocal<DateFormat> SBE_TIMESTAMP_FORMATTER = ThreadLocal .withInitial(() -> new SimpleDateFormat("yyyy MMM dd HH:mm:ss")); private static final Pattern COMMA_PATTERN = Pattern.compile("\\,"); private static final ThreadLocal<DecimalFormat> NANO_FORMATTER = ThreadLocal .withInitial(() -> new DecimalFormat("000000000")); /** * Private constructor to prevent instantiation of this class. */ private Utilities() { } /** * Transform the string <code>data</code> to a {@link VType} which is of identical type as the parameter * <code>type</code>. The data is expected to be in a proper format so that it can be parsed into the requested * type. The alarm of the returned object is none, with message USER DEFINED and the timestamp of the object is now. * If the given type is an array type, the number of elements in the new value has to match the number of elements * in the type. Individual elements in the input data are separated by comma. This method is the inverse of the * {@link #valueToString(VType)}. * * @param data the data to parse and transform into VType * @param type the type of the destination object * @return VType representing the data# * @throws IllegalArgumentException if the numbers of array elements do not match */ public static VType valueFromString(String indata, VType type) throws IllegalArgumentException { String data = indata.trim(); if (data.isEmpty()) { return type; } if (data.charAt(0) == '[') { data = data.substring(1); } if (data.charAt(data.length() - 1) == ']') { data = data.substring(0, data.length() - 1); } Alarm alarm = ValueFactory.newAlarm(AlarmSeverity.NONE, "USER DEFINED"); Time time = ValueFactory.timeNow(); if (type instanceof VNumberArray) { ListNumber list = null; String[] elements = data.split("\\,"); if (((VNumberArray) type).getData().size() != elements.length) { throw new IllegalArgumentException("The number of array elements is different from the original."); } if (type instanceof VDoubleArray) { double[] array = new double[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Double.parseDouble(elements[i].trim()); } list = new ArrayDouble(array); } else if (type instanceof VFloatArray) { float[] array = new float[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Float.parseFloat(elements[i].trim()); } list = new ArrayFloat(array); } else if (type instanceof VLongArray) { long[] array = new long[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Long.parseLong(elements[i].trim()); } list = new ArrayLong(array); } else if (type instanceof VIntArray) { int[] array = new int[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Integer.parseInt(elements[i].trim()); } list = new ArrayInt(array); } else if (type instanceof VShortArray) { short[] array = new short[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Short.parseShort(elements[i].trim()); } list = new ArrayShort(array); } else if (type instanceof VByteArray) { byte[] array = new byte[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Byte.parseByte(elements[i].trim()); } list = new ArrayByte(array); } return ValueFactory.newVNumberArray(list, alarm, time, (VNumberArray) type); } else if (type instanceof VEnumArray) { String[] elements = data.split("\\,"); if (((VEnumArray) type).getIndexes().size() != elements.length) { throw new IllegalArgumentException("The number of array elements is different from the original."); } int[] array = new int[elements.length]; List<String> labels = ((VEnumArray) type).getLabels(); for (int i = 0; i < elements.length; i++) { array[i] = labels.indexOf(elements[i].trim()); } ListInt list = new ArrayInt(array); return ValueFactory.newVEnumArray(list, labels, alarm, time); } else if (type instanceof VStringArray) { String[] elements = data.split("\\,"); if (((VStringArray) type).getData().size() != elements.length) { throw new IllegalArgumentException("The number of array elements is different from the original."); } for (int i = 0; i < elements.length; i++) { elements[i] = elements[i].trim(); } List<String> list = Arrays.asList(elements); return ValueFactory.newVStringArray(list, alarm, time); } else if (type instanceof VBooleanArray) { String[] elements = data.split("\\,"); if (((VBooleanArray) type).getData().size() != elements.length) { throw new IllegalArgumentException("The number of array elements is different from the original."); } boolean[] array = new boolean[elements.length]; for (int i = 0; i < elements.length; i++) { array[i] = Boolean.parseBoolean(elements[i].trim()); } ListBoolean list = new ArrayBoolean(array); return ValueFactory.newVBooleanArray(list, alarm, time); } else if (type instanceof VDouble) { return ValueFactory.newVDouble(Double.parseDouble(data), alarm, time, (VDouble) type); } else if (type instanceof VFloat) { return ValueFactory.newVFloat(Float.parseFloat(data), alarm, time, (VFloat) type); } else if (type instanceof VLong) { return ValueFactory.newVLong(Long.parseLong(data), alarm, time, (VLong) type); } else if (type instanceof VInt) { return ValueFactory.newVInt(Integer.parseInt(data), alarm, time, (VInt) type); } else if (type instanceof VShort) { return ValueFactory.newVShort(Short.parseShort(data), alarm, time, (VShort) type); } else if (type instanceof VByte) { return ValueFactory.newVByte(Byte.parseByte(data), alarm, time, (VByte) type); } else if (type instanceof VEnum) { List<String> labels = new ArrayList<>(((VEnum) type).getLabels()); int idx = labels.indexOf(data); if (idx < 0) { try { idx = Integer.parseInt(data); } catch (NumberFormatException e) { throw new IllegalArgumentException("'" + data + "' is not a valid enum value."); } } if (labels.size() <= idx) { for (int i = labels.size(); i <= idx; i++) { labels.add(String.valueOf(i)); } } return ValueFactory.newVEnum(idx, labels, alarm, time); } else if (type instanceof VString) { return ValueFactory.newVString(data, alarm, time); } else if (type instanceof VBoolean) { return ValueFactory.newVBoolean(Boolean.parseBoolean(data), alarm, time); } else if (type == VDisconnectedData.INSTANCE || type == VNoData.INSTANCE) { try { long v = Long.parseLong(indata); return ValueFactory.newVLong(v, alarm, time, ValueFactory.displayNone()); } catch (NumberFormatException e) { // ignore } try { double v = Double.parseDouble(indata); return ValueFactory.newVDouble(v, alarm, time, ValueFactory.displayNone()); } catch (NumberFormatException e) { // ignore } return ValueFactory.newVString(indata, alarm, time); } return type; } /** * Extracts the raw value from the given data object. The raw value is either one of the primitive wrappers or some * kind of a list type if the value is an {@link Array}. * * @param type the value to extract the raw data from * @return the raw data */ public static Object toRawValue(VType type) { if (type == null) { return null; } if (type instanceof VNumberArray) { return ((VNumberArray) type).getData(); } else if (type instanceof VEnumArray) { return ((VEnumArray) type).getData(); } else if (type instanceof VStringArray) { List<String> data = ((VStringArray) type).getData(); return data == null ? new String[0] : data.toArray(new String[data.size()]); } else if (type instanceof VBooleanArray) { return ((VBooleanArray) type).getData(); } else if (type instanceof VNumber) { return ((VNumber) type).getValue(); } else if (type instanceof VEnum) { VEnum en = (VEnum) type; String val = en.getValue(); if (val.isEmpty()) { // if all labels are empty, return the index as a string, otherwise return the label List<String> labels = en.getLabels(); for (String s : labels) { if (!s.isEmpty()) { return val; } } return String.valueOf(en.getIndex()); } else { return val; } } else if (type instanceof VString) { return ((VString) type).getValue(); } else if (type instanceof VBoolean) { return ((VBoolean) type).getValue(); } return null; } /** * Transforms the vtype to a string representing the raw value in the vtype. If the value is an array it is * encapsulated into rectangular parenthesis and individual items are separated by semi-colon. In case of enums the * value is followed by a tilda and another rectangular parenthesis containing all possible enumeration values. This * method should be used to create a string representation of the value for storage. * * @param type the type to transform * @return the string representing the raw value */ public static String toRawStringValue(VType type) { if (type instanceof VNumberArray) { ListNumber list = ((VNumberArray) type).getData(); StringBuilder sb = new StringBuilder(list.size() * 10); sb.append('['); IteratorNumber it = list.iterator(); if (type instanceof VDoubleArray) { while (it.hasNext()) { String str = String.valueOf(it.nextDouble()); sb.append(COMMA_PATTERN.matcher(str).replaceAll("\\.")).append(SEMI_COLON); } } else if (type instanceof VFloatArray) { while (it.hasNext()) { String str = String.valueOf(it.nextFloat()); sb.append(COMMA_PATTERN.matcher(str).replaceAll("\\.")).append(SEMI_COLON); } } else if (type instanceof VLongArray) { while (it.hasNext()) { sb.append(it.nextLong()).append(SEMI_COLON); } } else if (type instanceof VIntArray) { while (it.hasNext()) { sb.append(it.nextInt()).append(SEMI_COLON); } } else if (type instanceof VShortArray) { while (it.hasNext()) { sb.append(it.nextShort()).append(SEMI_COLON); } } else if (type instanceof VByteArray) { while (it.hasNext()) { sb.append(it.nextByte()).append(SEMI_COLON); } } if (list.size() == 0) { sb.append(']'); } else { sb.setCharAt(sb.length() - 1, ']'); } return sb.toString(); } else if (type instanceof VEnumArray) { List<String> list = ((VEnumArray) type).getData(); List<String> labels = ((VEnumArray) type).getLabels(); final StringBuilder sb = new StringBuilder((list.size() + labels.size()) * 10); sb.append('['); list.forEach(s -> sb.append(s).append(SEMI_COLON)); if (list.isEmpty()) { sb.append(']'); } else { sb.setCharAt(sb.length() - 1, ']'); } sb.append('~').append('['); labels.forEach(s -> sb.append(s).append(SEMI_COLON)); if (labels.isEmpty()) { sb.append(']'); } else { sb.setCharAt(sb.length() - 1, ']'); } return sb.toString(); } else if (type instanceof VStringArray) { List<String> list = ((VStringArray) type).getData(); final StringBuilder sb = new StringBuilder(list.size() * 20); sb.append('['); list.forEach(s -> sb.append(s).append(SEMI_COLON)); if (list.isEmpty()) { sb.append(']'); } else { sb.setCharAt(sb.length() - 1, ']'); } return sb.toString(); } else if (type instanceof VBooleanArray) { ListBoolean list = ((VBooleanArray) type).getData(); final StringBuilder sb = new StringBuilder(list.size() * 6); sb.append('['); int size = list.size(); for (int i = 0; i < size; i++) { sb.append(list.getBoolean(i)).append(SEMI_COLON); } if (list.size() == 0) { sb.append(']'); } else { sb.setCharAt(sb.length() - 1, ']'); } return sb.toString(); } else if (type instanceof VDouble || type instanceof VFloat) { // for some locales string.valueof might produce String str = String.valueOf(((VNumber) type).getValue()); return COMMA_PATTERN.matcher(str).replaceAll("\\."); } else if (type instanceof VNumber) { return String.valueOf(((VNumber) type).getValue()); } else if (type instanceof VEnum) { List<String> labels = ((VEnum) type).getLabels(); boolean allEmpty = true; for (String s : labels) { if (!s.isEmpty()) { allEmpty = false; break; } } String value = ((VEnum) type).getValue(); if (allEmpty) { List<String> newLabels = new ArrayList<>(labels.size()); for (int i = 0; i < labels.size(); i++) { newLabels.add(String.valueOf(i)); } labels = newLabels; if (value.isEmpty()) { value = String.valueOf(((VEnum) type).getIndex()); } } final StringBuilder sb = new StringBuilder((labels.size() + 1) * 10); sb.append(value); sb.append('~').append('['); labels.forEach(s -> sb.append(s).append(SEMI_COLON)); if (labels.isEmpty()) { sb.append(']'); } else { sb.setCharAt(sb.length() - 1, ']'); } return sb.toString(); } else if (type instanceof VString) { return ((VString) type).getValue(); } else if (type instanceof VBoolean) { return String.valueOf(((VBoolean) type).getValue()); } return type.toString(); } /** * Transforms the value of the given {@link VType} to a human readable string. This method uses formatting to format * all values, which may result in the arrays being truncated. * * @param type the data to transform * @return string representation of the data */ public static String valueToString(VType type) { return valueToString(type, 15); } /** * Transforms the value of the given {@link VType} to a human readable string. All values are formatted, which means * that they may not be exact. If the value is an array type, the maximum number of elements that are included is * given by the <code>arrayLimi</code> parameter. This method should only be used for presentation of the value on * the screen. * * @param type the data to transform * @param arrayLimit the maximum number of array elements to include * @return string representation of the data */ public static String valueToString(VType type, int arrayLimit) { if (type == null) { return null; } else if (type instanceof VNumberArray) { ListNumber list = ((VNumberArray) type).getData(); int size = Math.min(arrayLimit, list.size()); StringBuilder sb = new StringBuilder(size * 15 + 2); sb.append('['); Pattern pattern = Pattern.compile("\\,"); NumberFormat formatter = FORMAT.get().getNumberFormat(); if (type instanceof VDoubleArray) { for (int i = 0; i < size; i++) { sb.append(pattern.matcher(formatter.format(list.getDouble(i))).replaceAll("\\.")).append(COMMA) .append(' '); } } else if (type instanceof VFloatArray) { for (int i = 0; i < size; i++) { sb.append(pattern.matcher(formatter.format(list.getFloat(i))).replaceAll("\\.")).append(COMMA) .append(' '); } } else if (type instanceof VLongArray) { for (int i = 0; i < size; i++) { sb.append(list.getLong(i)).append(COMMA).append(' '); } } else if (type instanceof VIntArray) { for (int i = 0; i < size; i++) { sb.append(list.getInt(i)).append(COMMA).append(' '); } } else if (type instanceof VShortArray) { for (int i = 0; i < size; i++) { sb.append(list.getShort(i)).append(COMMA).append(' '); } } else if (type instanceof VByteArray) { for (int i = 0; i < size; i++) { sb.append(list.getByte(i)).append(COMMA).append(' '); } } if (size == 0) { sb.append(']'); } else if (size < list.size()) { sb.setCharAt(sb.length() - 1, '.'); sb.append("..]"); } else { sb.setCharAt(sb.length() - 2, ']'); } return sb.toString().trim(); } else if (type instanceof VEnumArray) { List<String> list = ((VEnumArray) type).getData(); int size = Math.min(arrayLimit, list.size()); final StringBuilder sb = new StringBuilder(size * 15 + 2); sb.append('['); for (int i = 0; i < size; i++) { sb.append(list.get(i)).append(COMMA).append(' '); } if (size == 0) { sb.append(']'); } else if (size < list.size()) { sb.setCharAt(sb.length() - 1, '.'); sb.append("..]"); } else { sb.setCharAt(sb.length() - 2, ']'); } return sb.toString().trim(); } else if (type instanceof VStringArray) { List<String> list = ((VStringArray) type).getData(); int size = Math.min(arrayLimit, list.size()); final StringBuilder sb = new StringBuilder(size * 20 + 2); sb.append('['); for (int i = 0; i < size; i++) { sb.append(list.get(i)).append(COMMA).append(' '); } if (size == 0) { sb.append(']'); } else if (size < list.size()) { sb.setCharAt(sb.length() - 1, '.'); sb.append("..]"); } else { sb.setCharAt(sb.length() - 2, ']'); } return sb.toString().trim(); } else if (type instanceof VBooleanArray) { ListBoolean list = ((VBooleanArray) type).getData(); int size = Math.min(arrayLimit, list.size()); final StringBuilder sb = new StringBuilder(size * 7 + 2); sb.append('['); for (int i = 0; i < size; i++) { sb.append(list.getBoolean(i)).append(COMMA).append(' '); } if (list.size() == 0) { sb.append(']'); } else if (size < list.size()) { sb.setCharAt(sb.length() - 1, '.'); sb.append("..]"); } else { sb.setCharAt(sb.length() - 2, ']'); } return sb.toString().trim(); } else if (type instanceof VNumber) { if (type instanceof VDouble) { return FORMAT.get().getNumberFormat().format(((VDouble) type).getValue()); } else if (type instanceof VFloat) { return FORMAT.get().getNumberFormat().format(((VFloat) type).getValue()); } else { return String.valueOf(((VNumber) type).getValue()); } } else if (type instanceof VEnum) { VEnum en = (VEnum) type; String val = en.getValue(); if (val.isEmpty()) { // if all labels are empty, return the index as a string, otherwise return the label List<String> labels = en.getLabels(); for (String s : labels) { if (!s.isEmpty()) { return val; } } return String.valueOf(en.getIndex()); } else { return val; } } else if (type instanceof VString) { return ((VString) type).getValue(); } else if (type instanceof VBoolean) { return String.valueOf(((VBoolean) type).getValue()); } // no support for MultiScalars (VMultiDouble, VMultiInt, VMultiString, VMultiEnum), VStatistics, VTable and // VImage) return null; } /** * Transforms the value of the given {@link VType} to a string and makes a comparison to the <code>baseValue</code>. * If the base value and the transformed value are both of a {@link VNumber} type, the difference of the transformed * value to the base value is added to the returned string. * * @param value the value to compare * @param baseValue the base value to compare the value to * @param threshold the threshold values to use for comparing the values, if defined and difference is within * threshold limits the values are equal * @return string representing the value and the difference from the base value together with the flag indicating * the comparison result */ @SuppressWarnings("unchecked") public static VTypeComparison valueToCompareString(VType value, VType baseValue, Optional<Threshold<?>> threshold) { if (value == null && baseValue == null || value == VDisconnectedData.INSTANCE && baseValue == VDisconnectedData.INSTANCE) { return new VTypeComparison(VDisconnectedData.INSTANCE.toString(), 0, true); } else if (value == null || baseValue == null) { return value == null ? new VTypeComparison(VDisconnectedData.INSTANCE.toString(), -1, false) : new VTypeComparison(valueToString(value), 1, false); } else if (value == VDisconnectedData.INSTANCE || baseValue == VDisconnectedData.INSTANCE) { return value == VDisconnectedData.INSTANCE ? new VTypeComparison(VDisconnectedData.INSTANCE.toString(), -1, false) : new VTypeComparison(valueToString(value), 1, false); } if (value instanceof VNumber && baseValue instanceof VNumber) { StringBuilder sb = new StringBuilder(20); int diff = 0; boolean withinThreshold = threshold.isPresent(); sb.append(FORMAT.get().format((VNumber) value)); if (value instanceof VDouble) { double data = ((VDouble) value).getValue(); double base = ((VNumber) baseValue).getValue().doubleValue(); double newd = data - base; diff = Double.compare(data, base); if (threshold.isPresent()) { withinThreshold = ((Threshold<Double>) threshold.get()).isWithinThreshold(data, base); } else { withinThreshold = diff == 0; } sb.append(' ').append(DELTA_CHAR); if (newd > 0) { sb.append('+'); } sb.append(FORMAT.get().getNumberFormat().format(newd)); } else if (value instanceof VFloat) { float data = ((VFloat) value).getValue(); float base = ((VNumber) baseValue).getValue().floatValue(); float newd = data - base; diff = Float.compare(data, base); if (threshold.isPresent()) { withinThreshold = ((Threshold<Float>) threshold.get()).isWithinThreshold(data, base); } else { withinThreshold = diff == 0; } sb.append(' ').append(DELTA_CHAR); if (newd > 0) { sb.append('+'); } sb.append(FORMAT.get().getNumberFormat().format(newd)); } else if (value instanceof VLong) { long data = ((VLong) value).getValue(); long base = ((VNumber) baseValue).getValue().longValue(); long newd = data - base; diff = Long.compare(data, base); if (threshold.isPresent()) { withinThreshold = ((Threshold<Long>) threshold.get()).isWithinThreshold(data, base); } else { withinThreshold = diff == 0; } sb.append(' ').append(DELTA_CHAR); if (newd > 0) { sb.append('+'); } sb.append(FORMAT.get().getNumberFormat().format(newd)); } else if (value instanceof VInt) { int data = ((VInt) value).getValue(); int base = ((VNumber) baseValue).getValue().intValue(); int newd = data - base; diff = Integer.compare(data, base); if (threshold.isPresent()) { withinThreshold = ((Threshold<Integer>) threshold.get()).isWithinThreshold(data, base); } else { withinThreshold = diff == 0; } sb.append(' ').append(DELTA_CHAR); if (newd > 0) { sb.append('+'); } sb.append(FORMAT.get().getNumberFormat().format(newd)); } else if (value instanceof VShort) { short data = ((VShort) value).getValue(); short base = ((VNumber) baseValue).getValue().shortValue(); short newd = (short) (data - base); diff = Short.compare(data, base); if (threshold.isPresent()) { withinThreshold = ((Threshold<Short>) threshold.get()).isWithinThreshold(data, base); } else { withinThreshold = diff == 0; } sb.append(' ').append(DELTA_CHAR); if (newd > 0) { sb.append('+'); } sb.append(FORMAT.get().getNumberFormat().format(newd)); } else if (value instanceof VByte) { byte data = ((VByte) value).getValue(); byte base = ((VNumber) baseValue).getValue().byteValue(); byte newd = (byte) (data - base); diff = Byte.compare(data, base); if (threshold.isPresent()) { withinThreshold = ((Threshold<Byte>) threshold.get()).isWithinThreshold(data, base); } else { withinThreshold = diff == 0; } sb.append(' ').append(DELTA_CHAR); if (newd > 0) { sb.append('+'); } sb.append(FORMAT.get().getNumberFormat().format(newd)); } return new VTypeComparison(sb.toString(), diff, withinThreshold); } else if (value instanceof VBoolean && baseValue instanceof VBoolean) { String str = valueToString(value); boolean b = ((VBoolean) value).getValue(); boolean c = ((VBoolean) baseValue).getValue(); return new VTypeComparison(str, Boolean.compare(b, c), b == c); } else if (value instanceof VEnum && baseValue instanceof VEnum) { String str = valueToString(value); String b = ((VEnum) value).getValue(); String c = ((VEnum) baseValue).getValue(); int diff = b == null ? (c == null ? 0 : 1) : (c == null ? -1 : b.compareTo(c)); return new VTypeComparison(str, diff, diff == 0); } else if (value instanceof VString && baseValue instanceof VString) { String str = valueToString(value); String b = ((VString) value).getValue(); String c = ((VString) baseValue).getValue(); int diff = b == null ? (c == null ? 0 : 1) : (c == null ? -1 : b.compareTo(c)); return new VTypeComparison(str, diff, diff == 0); } else if (value instanceof VNumberArray && baseValue instanceof VNumberArray) { String sb = valueToString(value); boolean equal = areValuesEqual(value, baseValue, Optional.empty()); return new VTypeComparison(sb, equal ? 0 : 1, equal); } else { String str = valueToString(value); boolean valuesEqual = areValuesEqual(value, baseValue, Optional.empty()); return new VTypeComparison(str, valuesEqual ? 0 : 1, valuesEqual); } } /** * Converts the timestamp to seconds as a floating point (seconds.nano). * * @param t the timstamp to transform * @return the string representation of the timestamp using the decimal format */ public static String timestampToDecimalString(Instant t) { return t.getEpochSecond() + "." + NANO_FORMATTER.get().format(t.getNano()); } /** * Transforms the timestamp to string, using the format HH:mm:ss.SSS MMM dd. * * @param t the timestamp to transform * @return string representation of the timestamp using the above format */ public static String timestampToString(Instant t) { return timestampToLittleEndianString(t, false); } /** * Transforms the timestamp to string, using the format HH:mm:ss.SSS MMM dd (yyyy). * * @param t the timestamp to transform * @param includeYear true if the year should included in the format * @return string representation of the timestamp using the above format */ public static String timestampToLittleEndianString(Instant t, boolean includeYear) { if (t == null) { return null; } return includeYear ? SLE_TIMESTAMP_FORMATTER.get().format(Date.from(t)) : LE_TIMESTAMP_FORMATTER.get().format(Date.from(t)); } /** * Transforms the date to string formatted as yyyy MMM dd HH:mm:ss. Year is only included if the parameter * <code>includeYear</code> is true. * * @param t the date to transform * @param includeYear true if the year should be included or false otherwise * @return string representation of the date */ public static String timestampToBigEndianString(Instant t, boolean includeYear) { if (t == null) { return null; } return includeYear ? SBE_TIMESTAMP_FORMATTER.get().format(Date.from(t)) : BE_TIMESTAMP_FORMATTER.get().format(Date.from(t)); } /** * Checks if the values of the given vtype are equal and returns true if they are or false if they are not. * Timestamps, alarms and other parameters are ignored. * * @param v1 the first value to check * @param v2 the second value to check * @param threshold the threshold values which define if the difference is within limits or not * @return true if the values are equal or false otherwise */ @SuppressWarnings("unchecked") public static boolean areValuesEqual(VType v1, VType v2, Optional<Threshold<?>> threshold) { if (v1 == null && v2 == null) { return true; } else if (v1 == null || v2 == null) { return false; } else if (v1 == VDisconnectedData.INSTANCE && v2 == VDisconnectedData.INSTANCE) { return true; } else if (v1 == VDisconnectedData.INSTANCE || v2 == VDisconnectedData.INSTANCE) { return false; } if (v1 instanceof VNumber && v2 instanceof VNumber) { if (v1 instanceof VDouble) { double data = ((VDouble) v1).getValue(); double base = ((VNumber) v2).getValue().doubleValue(); if (threshold.isPresent()) { return ((Threshold<Double>) threshold.get()).isWithinThreshold(data, base); } return Double.compare(data, base) == 0; } else if (v1 instanceof VFloat) { float data = ((VFloat) v1).getValue(); float base = ((VNumber) v2).getValue().floatValue(); if (threshold.isPresent()) { return ((Threshold<Float>) threshold.get()).isWithinThreshold(data, base); } return Float.compare(data, base) == 0; } else if (v1 instanceof VLong) { long data = ((VLong) v1).getValue(); long base = ((VNumber) v2).getValue().longValue(); if (threshold.isPresent()) { return ((Threshold<Long>) threshold.get()).isWithinThreshold(data, base); } return Long.compare(data, base) == 0; } else if (v1 instanceof VInt) { int data = ((VInt) v1).getValue(); int base = ((VNumber) v2).getValue().intValue(); if (threshold.isPresent()) { return ((Threshold<Integer>) threshold.get()).isWithinThreshold(data, base); } return Integer.compare(data, base) == 0; } else if (v1 instanceof VShort) { short data = ((VShort) v1).getValue(); short base = ((VNumber) v2).getValue().shortValue(); if (threshold.isPresent()) { return ((Threshold<Short>) threshold.get()).isWithinThreshold(data, base); } return Short.compare(data, base) == 0; } else if (v1 instanceof VByte) { byte data = ((VByte) v1).getValue(); byte base = ((VNumber) v2).getValue().byteValue(); if (threshold.isPresent()) { return ((Threshold<Byte>) threshold.get()).isWithinThreshold(data, base); } return Byte.compare(data, base) == 0; } } else if (v1 instanceof VBoolean && v2 instanceof VBoolean) { boolean b = ((VBoolean) v1).getValue(); boolean c = ((VBoolean) v2).getValue(); return b == c; } else if (v1 instanceof VEnum && v2 instanceof VEnum) { String b = ((VEnum) v1).getValue(); String c = ((VEnum) v2).getValue(); return b != null && b.equals(c) || b == c; } else if (v1 instanceof VString && v2 instanceof VString) { String b = ((VString) v1).getValue(); String c = ((VString) v2).getValue(); return b != null && b.equals(c) || b == c; } else if (v1 instanceof VNumberArray && v2 instanceof VNumberArray) { if ((v1 instanceof VByteArray && v2 instanceof VByteArray) || (v1 instanceof VShortArray && v2 instanceof VShortArray) || (v1 instanceof VIntArray && v2 instanceof VIntArray) || (v1 instanceof VFloatArray && v2 instanceof VFloatArray) || (v1 instanceof VDoubleArray && v2 instanceof VDoubleArray)) { ListNumber b = ((VNumberArray) v1).getData(); ListNumber c = ((VNumberArray) v2).getData(); int size = b.size(); if (size != c.size()) { return false; } for (int i = 0; i < size; i++) { if (Double.compare(b.getDouble(i), c.getDouble(i)) != 0) { return false; } } return true; } else if (v1 instanceof VLongArray && v2 instanceof VLongArray) { ListLong b = ((VLongArray) v1).getData(); ListLong c = ((VLongArray) v2).getData(); int size = b.size(); if (size != c.size()) { return false; } for (int i = 0; i < size; i++) { if (Long.compare(b.getLong(i), c.getLong(i)) != 0) { return false; } } return true; } } else if (v1 instanceof VStringArray && v2 instanceof VStringArray) { List<String> b = ((VStringArray) v1).getData(); List<String> c = ((VStringArray) v2).getData(); return b.equals(c); } else if (v1 instanceof VEnumArray && v2 instanceof VEnumArray) { ListInt b = ((VEnumArray) v1).getIndexes(); ListInt c = ((VEnumArray) v2).getIndexes(); int size = b.size(); if (size != c.size()) { return false; } for (int i = 0; i < size; i++) { if (Integer.compare(b.getInt(i), c.getInt(i)) != 0) { return false; } } return true; } // no support for MultiScalars (VMultiDouble, VMultiInt, VMultiString, VMultiEnum), VStatistics, VTable and // VImage) return false; } /** * Compares two instances of {@link VType} and returns true if they are identical or false of they are not. Values * are identical if their alarm signatures are identical, timestamps are the same, values are the same and in case * of enum and enum array also the labels have to be identical. * * @param v1 the first value * @param v2 the second value to compare to the first one * @param compareAlarmAndTime true if alarm and time values should be compare or false if no * @return true if values are identical or false otherwise */ public static boolean areVTypesIdentical(VType v1, VType v2, boolean compareAlarmAndTime) { if (v1 == v2) { // this works for no data as well return true; } else if (v1 == null || v2 == null) { return false; } if (compareAlarmAndTime && !isAlarmAndTimeEqual(v1, v2)) { return false; } if (v1 instanceof VNumber && v2 instanceof VNumber) { if (v1 instanceof VDouble && v2 instanceof VDouble) { double data = ((VDouble) v1).getValue(); double base = ((VDouble) v2).getValue(); return Double.compare(data, base) == 0; } else if (v1 instanceof VFloat && v2 instanceof VFloat) { float data = ((VFloat) v1).getValue(); float base = ((VFloat) v2).getValue(); return Float.compare(data, base) == 0; } else if (v1 instanceof VLong && v2 instanceof VLong) { long data = ((VLong) v1).getValue(); long base = ((VLong) v2).getValue(); return Long.compare(data, base) == 0; } else if (v1 instanceof VInt && v2 instanceof VInt) { int data = ((VInt) v1).getValue(); int base = ((VInt) v2).getValue(); return Integer.compare(data, base) == 0; } else if (v1 instanceof VShort && v2 instanceof VShort) { short data = ((VShort) v1).getValue(); short base = ((VShort) v2).getValue(); return Short.compare(data, base) == 0; } else if (v1 instanceof VByte && v2 instanceof VByte) { byte data = ((VByte) v1).getValue(); byte base = ((VByte) v2).getValue().byteValue(); return Byte.compare(data, base) == 0; } } else if (v1 instanceof VBoolean && v2 instanceof VBoolean) { boolean b = ((VBoolean) v1).getValue(); boolean c = ((VBoolean) v2).getValue(); return b == c; } else if (v1 instanceof VEnum && v2 instanceof VEnum) { int b = ((VEnum) v1).getIndex(); int c = ((VEnum) v2).getIndex(); if (b == c) { List<String> l1 = ((VEnum) v1).getLabels(); List<String> l2 = ((VEnum) v2).getLabels(); return l1.equals(l2); } return false; } else if (v1 instanceof VNumberArray && v2 instanceof VNumberArray) { if ((v1 instanceof VByteArray && v2 instanceof VByteArray) || (v1 instanceof VShortArray && v2 instanceof VShortArray) || (v1 instanceof VIntArray && v2 instanceof VIntArray) || (v1 instanceof VFloatArray && v2 instanceof VFloatArray) || (v1 instanceof VDoubleArray && v2 instanceof VDoubleArray)) { ListNumber b = ((VNumberArray) v1).getData(); ListNumber c = ((VNumberArray) v2).getData(); int size = b.size(); if (size != c.size()) { return false; } for (int i = 0; i < size; i++) { if (Double.compare(b.getDouble(i), c.getDouble(i)) != 0) { return false; } } return true; } else if (v1 instanceof VLongArray && v2 instanceof VLongArray) { ListLong b = ((VLongArray) v1).getData(); ListLong c = ((VLongArray) v2).getData(); int size = b.size(); if (size != c.size()) { return false; } for (int i = 0; i < size; i++) { if (Long.compare(b.getLong(i), c.getLong(i)) != 0) { return false; } } return true; } } else if (v1 instanceof VStringArray && v2 instanceof VStringArray) { List<String> b = ((VStringArray) v1).getData(); List<String> c = ((VStringArray) v2).getData(); return b.equals(c); } else if (v1 instanceof VEnumArray && v2 instanceof VEnumArray) { ListInt b = ((VEnumArray) v1).getIndexes(); ListInt c = ((VEnumArray) v2).getIndexes(); int size = b.size(); if (size != c.size()) { return false; } for (int i = 0; i < size; i++) { if (Integer.compare(b.getInt(i), c.getInt(i)) != 0) { return false; } } List<String> l1 = ((VEnumArray) v1).getLabels(); List<String> l2 = ((VEnumArray) v2).getLabels(); return l1.equals(l2); } // no support for MultiScalars (VMultiDouble, VMultiInt, VMultiString, VMultiEnum), VStatistics, VTable and // VImage) return false; } private static boolean isAlarmAndTimeEqual(VType a1, VType a2) { if (a1 instanceof Alarm && a2 instanceof Alarm) { if (!Objects.equals(((Alarm) a1).getAlarmSeverity(), ((Alarm) a2).getAlarmSeverity()) || !Objects.equals(((Alarm) a1).getAlarmName(), ((Alarm) a2).getAlarmName())) { return false; } } else if (a1 instanceof Alarm || a2 instanceof Alarm) { return false; } if (a1 instanceof Time && a2 instanceof Time) { return ((Time) a1).getTimestamp().equals(((Time) a2).getTimestamp()); } else if (a1 instanceof Time || a2 instanceof Time) { return false; } return true; } }
26,435
https://github.com/mrhuigou/web/blob/master/h5/views/user/bind-telephone.php
Github Open Source
Open Source
BSD-3-Clause
null
web
mrhuigou
PHP
Code
119
582
<?php /** * Created by PhpStorm. * User: mac * Date: 2017/4/19 * Time: 10:40 */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; $this->title="验证手机"; ?> <div class="tc p20 f14"> <img src="<?=\common\component\image\Image::resize(Yii::$app->user->identity->photo,120,120)?>" width="120" height="120" class="img-circle mt30"> <h3 class="pt5 f16"><?=Yii::$app->user->identity->nickname?></h3> <p class="gray9 pt15 pb5 tit--">验证手机,继续购物</p> <div class="tl"> <?php $form = ActiveForm::begin(['id' => 'form-signup','fieldConfig' => [ 'template' => "<div class='pr pt-15em'>{input}<p class=\"input-setup clearfix\"><a href=\"javascript:void(0);\" class=\"input-del fr\" style=\"display:none;\"></a></p></div>{error}", 'inputOptions' => ['class' => 'input-text w',"autocomplete"=>"off"], 'errorOptions'=>['class'=>'error db'] ], ]);?> <?= $form->field($model, 'telephone',["inputOptions"=>['placeholder'=>'请输入手机号','class' => 'input-text w telephone']]) ?> <?= $form->field($model, 'verifyCode',[ 'template' => "<div class='pt-15em clearfix'><div class=\"pr w-per60 fl\">{input}</div><a href=\"javascript:;\" class=\"btn lbtn graybtn w-per40 f12 \" id='send-vcode'>获取验证码</a></div>{error}", "inputOptions"=>["maxlength"=>"6","autocomplete"=>"off",'placeholder'=>'验证码'], ]) ?> <?= Html::submitButton('提交验证', ['class' => 'btn lbtn greenbtn w mt10', 'name' => 'signup-button']) ?> <?php ActiveForm::end(); ?> </div> </div>
10,695
https://github.com/drpietz/sunaware/blob/master/src/page/user/SunClock/AllowanceClock/AllowanceClock.js
Github Open Source
Open Source
MIT
null
sunaware
drpietz
JavaScript
Code
201
803
import React, {Component} from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import {synchronizeAllowance} from "../../../../actions/uvTimer"; class AllowanceClock extends Component { constructor(props) { super(props) this.state = { text: '0 minutes' } } componentWillMount() { this.startAllowanceSyncTimer() if (this.props.timerIsRunning) { this.startUpdateTimer() this.updateText() } } componentWillReceiveProps(nextProps) { this.updateText(nextProps) if (this.props.timerIsRunning && !nextProps.timerIsRunning) this.stopUpdateTimer() else if (!this.props.timerIsRunning && nextProps.timerIsRunning) { this.startUpdateTimer() } } componentWillUnmount() { this.stopAllowanceSyncTimer() if (this.props.timerIsRunning) this.stopUpdateTimer() } startAllowanceSyncTimer = () => { this.syncronizeAllowance() this.syncAllowanceTimer = setInterval(this.syncronizeAllowance, 60000) } stopAllowanceSyncTimer = () => { clearInterval(this.syncAllowanceTimer); } startUpdateTimer = () => { this.timer = setInterval(this.updateText, 1000) } stopUpdateTimer = () => { clearInterval(this.timer) } syncronizeAllowance = () => { this.props.actions.synchronizeAllowance() } updateText = (props = this.props) => { let remaining = props.remainingAllowance if (props.timerIsRunning && props.allowanceSyncTime) { let now = new Date() remaining -= now.getTime() - props.allowanceSyncTime.getTime() } let minutes = Math.floor(remaining / 60000) let text; if (minutes === 1) text = "1 minute" else text = minutes + " minutes" if (text !== this.state.text) this.setState({text}) } render() { return <span className={this.props.className}>{this.state.text}</span> } } function mapStateToProps(state) { return { timerIsRunning: !!state.uvTimer.timer && !state.uvTimer.timer.end, allowanceSyncTime: state.uvTimer.allowanceSyncTime, remainingAllowance: state.uvTimer.remainingAllowance } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({synchronizeAllowance}, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(AllowanceClock)
21,663
https://github.com/i-gaven/Just_a_dumper/blob/master/all_headers/百度地图-出行导航必备的智能路线规划软件-10.6.5(越狱应用)_headers/BMTraceRecordItem.h
Github Open Source
Open Source
MIT
2,018
Just_a_dumper
i-gaven
Objective-C
Code
83
316
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <UIKit/UIView.h> @class BMMaterialDesignButton, UIImageView, UILabel; @interface BMTraceRecordItem : UIView { UIImageView *_iconImage; UILabel *_titleLabel; BMMaterialDesignButton *_button; } @property(retain, nonatomic) BMMaterialDesignButton *button; // @synthesize button=_button; @property(retain, nonatomic) UILabel *titleLabel; // @synthesize titleLabel=_titleLabel; @property(retain, nonatomic) UIImageView *iconImage; // @synthesize iconImage=_iconImage; - (void).cxx_destruct; - (void)addTarget:(id)arg1 action:(SEL)arg2 forControlEvents:(unsigned long long)arg3; - (void)initConstraints; - (id)initWithFrame:(struct CGRect)arg1 withIconImage:(id)arg2 withTitle:(id)arg3; @end
4,011
https://github.com/jponge/playground-go-microservices/blob/master/pulsar/run-pulsar-in-docker.sh
Github Open Source
Open Source
MIT
null
playground-go-microservices
jponge
Shell
Code
15
83
#!/bin/sh docker run -it -p 6650:6650 -p 8080:8080 --mount source=pulsardata,target=/pulsar/data --mount source=pulsarconf,target=/pulsar/conf apachepulsar/pulsar:2.9.1 bin/pulsar standalone
30,305
https://github.com/carlosmiranda/s3auth/blob/master/s3auth-hosts/src/main/java/com/s3auth/hosts/H2DomainStatsData.java
Github Open Source
Open Source
BSD-3-Clause
null
s3auth
carlosmiranda
Java
Code
735
1,889
/** * Copyright (c) 2012-2017, s3auth.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the s3auth.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.s3auth.hosts; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Loggable; import com.jcabi.jdbc.JdbcSession; import com.jcabi.jdbc.Outcome; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.Properties; import lombok.EqualsAndHashCode; import org.h2.Driver; /** * Storage of {@link Stats} per domain with H2 Database. * * @author Carlos Miranda (miranda.cma@gmail.com) * @version $Id: ddaa83d1fff1c1b2db9310b1e08741bfacd822ea $ * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) */ @Immutable @EqualsAndHashCode(of = "jdbc") @Loggable(Loggable.DEBUG) final class H2DomainStatsData implements DomainStatsData { /** * Create Table statement. */ private static final String CREATE = new StringBuilder("CREATE TABLE ") .append("IF NOT EXISTS DOMAIN_STATS( ") .append("ID INT IDENTITY,") .append("DOMAIN VARCHAR(255),") .append("BYTES INT,") .append("CREATE_TIME TIMESTAMP") .append(" )").toString(); /** * Insert statement. */ private static final String INSERT = new StringBuilder("INSERT INTO ") .append("DOMAIN_STATS (DOMAIN, BYTES, CREATE_TIME) ") .append("values (?, ?, CURRENT_TIMESTAMP())").toString(); /** * Outcome for obtaining a single Stats per domain. */ private static final Outcome<Stats> STATS = new Outcome<Stats>() { @Override public Stats handle(final ResultSet rset, final Statement stmt) throws SQLException { rset.next(); return new Stats.Simple(rset.getLong(1)); } }; /** * Outcome for obtaining a single Stats for all domains. */ private static final Outcome<Map<String, Stats>> STATS_ALL = new Outcome<Map<String, Stats>>() { @Override @SuppressWarnings("PMD.UseConcurrentHashMap") public Map<String, Stats> handle(final ResultSet rset, final Statement stmt) throws SQLException { final Map<String, Stats> stats = new HashMap<String, Stats>(); while (rset.next()) { stats.put( rset.getString(1), new Stats.Simple(rset.getLong(2)) ); } return stats; } }; /** * The JDBC URL. */ private final transient String jdbc; /** * Public ctor. * @throws IOException If an IO Exception occurs. */ H2DomainStatsData() throws IOException { this(new File("s3auth-domainStats")); } /** * Public ctor. * @param file The file pointing to the database to use. * @throws IOException If an IO Exception occurs. */ H2DomainStatsData(final File file) throws IOException { this.jdbc = String.format("jdbc:h2:file:%s", file.getAbsolutePath()); try { new JdbcSession(this.connection()).sql(CREATE).execute(); } catch (final SQLException ex) { throw new IOException(ex); } } @Override public void put(final String domain, final Stats stats) throws IOException { try { new JdbcSession(this.connection()) .sql(INSERT) .set(domain) .set(stats.bytesTransferred()) .execute(); } catch (final SQLException ex) { throw new IOException(ex); } } @Override public Stats get(final String domain) throws IOException { try { final JdbcSession session = new JdbcSession(this.connection()) .autocommit(false); // @checkstyle LineLength (2 lines) final Stats result = session .sql("SELECT SUM(BYTES) FROM DOMAIN_STATS WHERE DOMAIN = ? FOR UPDATE") .set(domain) .select(STATS); session.sql("DELETE FROM DOMAIN_STATS WHERE DOMAIN = ?") .set(domain) .execute() .commit(); return result; } catch (final SQLException ex) { throw new IOException(ex); } } @Override @SuppressWarnings("PMD.UseConcurrentHashMap") public Map<String, Stats> all() throws IOException { try { final JdbcSession session = new JdbcSession(this.connection()) .autocommit(false); // @checkstyle LineLength (2 lines) final Map<String, Stats> result = session .sql("SELECT DOMAIN, SUM(BYTES) FROM DOMAIN_STATS GROUP BY DOMAIN FOR UPDATE") .select(STATS_ALL); session.sql("DELETE FROM DOMAIN_STATS").execute().commit(); return result; } catch (final SQLException ex) { throw new IOException(ex); } } /** * Make data source. * @return Data source for JDBC * @throws SQLException If it fails */ private Connection connection() throws SQLException { return new Driver().connect(this.jdbc, new Properties()); } }
20,846
https://github.com/m1ndcoderr/learning_java/blob/master/chapter_011/mvc/src/main/java/ru/evgenyhodz/controller/MainController.java
Github Open Source
Open Source
Apache-2.0
null
learning_java
m1ndcoderr
Java
Code
301
986
package ru.evgenyhodz.controller; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import ru.evgenyhodz.models.Advertisement; import ru.evgenyhodz.service.AdvertisementService; /** * @author Evgeny Khodzitskiy (evgeny.hodz@gmail.com) * @since 04.10.2017 */ @Controller public class MainController { /** * Advertisement service. */ private AdvertisementService advertisementService; /** * Setter for spring autowire. * * @param as advertisement service. */ @Autowired @Qualifier(value = "advertisementService") public void setPersonService(AdvertisementService as) { this.advertisementService = as; } /** * Shows basic page. // Здесь немного костыльнул, т.к. использовал БД с предыдущего задания. // * * @return basic page. */ @RequestMapping(value = "/basic", method = RequestMethod.GET) public String showBasicPage(Model model) { String htmlResponse = " <div class=\"row\">"; int count = 0; for (Advertisement adv : this.advertisementService.getAllAds()) { htmlResponse = htmlResponse + "<div class=\"col-md-4 center-block\">\n" + "<h2>" + adv.getCar().getBrand().getName() + " " + adv.getCar().getModel().getModel() + "</h2>\n" + "<p><img src=\"/carstore/resources/" + adv.getImage().getUrl().substring(3) + "\"/></p>\n" + "<p><a class=\"btn btn-secondary\" " + "role=\"button\" id=\"" + adv.getId() + "\" onclick=\"redirect_by_id()\">View details</a></p>\n" + "</div>"; count++; if (count == 3) { htmlResponse = htmlResponse + "</div><div class=\"row\">"; count = 0; } } htmlResponse = htmlResponse + "</div>"; model.addAttribute("advertisements", htmlResponse); return "basic"; } /** * Shows car details page. * * @return car details page. */ @RequestMapping(value = "/car", method = RequestMethod.GET) public String showCarDetailsPage(Model model) { int id = 1; Advertisement advertisement = advertisementService.findById(id); model.addAttribute("advertisement", advertisement); return "car"; } /** * Shows sign in page. * * @return sign in page. */ @RequestMapping(value = "/signin", method = RequestMethod.GET) public String showSignInPage() { return "sign_in"; } /** * Shows sign up page. * * @return sign up page. */ @RequestMapping(value = "/signup", method = RequestMethod.GET) public String showSignUpPage() { return "sign_up"; } /** * Shows add_new_adv page. * * @return advertisement's creation page. */ @RequestMapping(value = "/add_new_adv", method = RequestMethod.GET) public String showAddAdvPage() { return "add_new_adv"; } }
34,767
https://github.com/ajvarela/amadeus-exploit/blob/master/fm/models/paper_JSS/evaluation_performance/CVE-2017-6102.afm
Github Open Source
Open Source
MIT
2,022
amadeus-exploit
ajvarela
Adobe Font Metrics
Code
35
296
# vul_description: Persistent XSS in wordpress plugin rockhoist_badges v1.2.2. %Relationships CVE_2017_6102: types sources exploits rockhoist__badges__project; types: application; sources: nvd; exploits: [direct] [indirect]; rockhoist__badges__project: rockhoist__badges__project_rockhoist__badges__plugin; rockhoist__badges__project_rockhoist__badges__plugin: rockhoist__badges__project_rockhoist__badges__plugin_version rockhoist__badges__project_rockhoist__badges__plugin_target__sw; rockhoist__badges__project_rockhoist__badges__plugin_version: rockhoist__badges__project_rockhoist__badges__plugin_version_1__2__2; rockhoist__badges__project_rockhoist__badges__plugin_target__sw: rockhoist__badges__project_rockhoist__badges__plugin_target__sw_wordpress; %Constraints rockhoist__badges__project_rockhoist__badges__plugin REQUIRES application;
6,999
https://github.com/nandansn/seleniumlab/blob/master/src/main/java/com/nanda/testlab/selenium/page/IndeedHomePage.java
Github Open Source
Open Source
MIT
null
seleniumlab
nandansn
Java
Code
263
913
/** * */ package com.nanda.testlab.selenium.page; import java.io.FileNotFoundException; import org.apache.log4j.Logger; import org.openqa.selenium.support.FindBy; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import com.nanda.testlab.selenium.page.element.Button; import com.nanda.testlab.selenium.page.element.Link; import com.nanda.testlab.selenium.page.element.TextBox; import com.nanda.testlab.selenium.resource.util.JsonPageDataToPageObjectMapper; /** * @author Nandakumar 20-Apr-2017 * */ public class IndeedHomePage extends Page { final static String filePath = "src/main/resources/home-page.json"; Button findJobButton; String link; TextBox whatTextBox; TextBox whereTextBox; public static IndeedHomePage loadPage() throws JsonSyntaxException, JsonIOException, FileNotFoundException { IndeedHomePage homePage = (IndeedHomePage) JsonPageDataToPageObjectMapper .getPageObjectFromJson(IndeedHomePage.class, filePath); homePage.open(); return homePage; } /** * @return the whatTextBox */ public TextBox getWhatTextBox() { return whatTextBox; } /** * @param whatTextBox * the whatTextBox to set */ public void setWhatTextBox(TextBox whatTextBox) { this.whatTextBox = whatTextBox; } /** * @return the whereTextBox */ public TextBox getWhereTextBox() { return whereTextBox; } /** * @param whereTextBox * the whereTextBox to set */ public void setWhereTextBox(TextBox whereTextBox) { this.whereTextBox = whereTextBox; } /** * @return the findJobButton */ public Button getFindJobButton() { return findJobButton; } /** * @param findJobButton * the findJobButton to set */ public void setFindJobButton(Button findJobButton) { this.findJobButton = findJobButton; } /** * @return the link */ public String getLink() { return link; } /** * @param link * the link to set */ public void setLink(String link) { this.link = link; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "TestHomePage [link=" + link + ", findJobButton=" + findJobButton + "]"; } public IndeedHomePage open() { super.open(this.getLink()); return this; } public boolean close() { super.closePage(); return true; } public void clickFindJobButton() { super.clickButton(this.findJobButton); } public void sendTextToWhatTextBox(String text) { super.type(whatTextBox, text); } public void sendTextToWhereTextBox(String text) { super.type(whereTextBox, text); } }
9,718
https://github.com/Shuvayu/DevPracticeBox/blob/master/ENET MVC/EnetMVC/DAL/DAL/Website/ViewModels/DistributionViewModel.cs
Github Open Source
Open Source
MIT
2,016
DevPracticeBox
Shuvayu
C#
Code
93
188
using System; using System.ComponentModel.DataAnnotations; namespace Website.ViewModels { /// <summary> /// Model Distribution /// Have the setters for the Distribution DB /// </summary> public class DistributionViewModel { public int DistributionId { get; set; } public string Username { get; set; } public int PackageId { get; set; } public string BarcodeId { get; set; } public DateTime On { get; set; } public DateTime ExpiryDate { get; set; } [Required] public string Description { get; set; } public int UserId { get; set; } public virtual MedicineViewModel Medicine { get; set; } } }
48,286
https://github.com/ParishConnect/ui/blob/master/src/Icon/generated/Book.tsx
Github Open Source
Open Source
MIT
null
ui
ParishConnect
TypeScript
Code
55
218
import React from 'react' import { Icon, IconProps } from '../Icon' export function BookIcon(props: IconProps) { return ( <Icon xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" {...props}> <path d="M21 23.25H5.25A2.25 2.25 0 013 21M6 .75a3 3 0 00-3 3V21a2.25 2.25 0 012.25-2.25h15A.75.75 0 0021 18V1.5a.75.75 0 00-.75-.75zM19.5 23.25v-4.5" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} /> </Icon> ) }
36,063
https://github.com/svanichkin/Feedback/blob/master/Classes/ios/Feedback.h
Github Open Source
Open Source
Apache-2.0
null
Feedback
svanichkin
C
Code
208
556
// // Feedback.h // Version 1.4 // // Created by Sergey Vanichkin on 15.02.2018. // Copyright © 2018 Sergey Vanichkin. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Setup with your email or/and imessage // // [Feedback // setupWithIMessage:@"my_imessage@me.com" // email:@"my_email.me.com"]; // // Then do action on user button "Send feedback" // // [Feedback // sendFeedbackWithController:self // text:@"User send feedback from App"]; // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #define ENABLE_iNFO_LOG NO #define ENABLE_ERROR_LOG NO @interface FeedbackAttachment : NSObject @property (nonatomic, strong) NSData *attachmentData; @property (nonatomic, strong) NSString *typeIdentifier; @property (nonatomic, strong) NSString *mimeType; @property (nonatomic, strong) NSString *filename; @end @interface Feedback : NSObject +(void)setupWithURLString:(NSString *)urlString; +(void)setupWithIMessage:(NSString *)iMessage email:(NSString *)email; +(void)sendFeedbackWithController:(UIViewController *)controller; +(void)sendFeedbackWithController:(UIViewController *)controller text:(NSString *)text; +(void)sendFeedbackWithController:(UIViewController *)controller attachments:(NSArray <FeedbackAttachment *> *)attachments; @end
6,499
https://github.com/qwtel/redux-switch-action/blob/master/test/index.spec.js
Github Open Source
Open Source
MIT
null
redux-switch-action
qwtel
JavaScript
Code
192
553
import expect from 'expect'; import createSwitchAction from '../src'; describe('createSwitchAction', () => { it('should exist', () => { expect(typeof createSwitchAction !== 'undefined').toBe(true); }); const ADD = 'ADD'; const SUB = 'SUB'; const OTHER = 'OTHER'; const INC = 'INC'; const RETURN_THIS = 'RETURN_THIS'; function addReducer(state, {payload}) { return state + payload.amount; } function subReducer(state, {payload}) { return state - payload.amount; } function incReducer(state) { return state + 1; } function returnThisReducer() { return this; } const switchAction = createSwitchAction({ [ADD]: addReducer, [SUB]: subReducer, [INC]: incReducer, [RETURN_THIS]: returnThisReducer, }); it('should call a reducer according to an action type', () => { const addAction = { type: ADD, payload: { amount: 2, }, }; const subAction = { type: SUB, payload: { amount: 2, }, }; expect(switchAction(5, addAction)).toBe(7); expect(switchAction(5, subAction)).toBe(3); }); it('should return the state for an unknown action', () => { const otherAction = { type: OTHER, payload: { other: 'data', }, }; expect(switchAction(5, otherAction)).toBe(5); }); it('should accept actions without payload', () => { const incAction = { type: INC, }; expect(switchAction(5, incAction)).toBe(6); }); it('should retain the `this` context', () => { const returnThisAction = { type: RETURN_THIS, }; expect(switchAction.call('thisContext', 5, returnThisAction)).toBe('thisContext'); }); });
21,861
https://github.com/jiangmichaellll/java-pubsublite/blob/master/pubsublite-beam-io/src/main/java/com/google/cloud/pubsublite/beam/AddUuidsTransform.java
Github Open Source
Open Source
Apache-2.0
null
java-pubsublite
jiangmichaellll
Java
Code
164
554
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.pubsublite.beam; import com.google.cloud.pubsublite.Message; import com.google.common.collect.ImmutableListMultimap; import com.google.protobuf.ByteString; import org.apache.beam.sdk.transforms.MapElements; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.Reshuffle; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.TypeDescriptor; class AddUuidsTransform extends PTransform<PCollection<Message>, PCollection<Message>> { private static Message addUuid(Message message) { ImmutableListMultimap.Builder<String, ByteString> attributesBuilder = ImmutableListMultimap.builder(); message.attributes().entries().stream() .filter(entry -> !entry.getKey().equals(Uuid.DEFAULT_ATTRIBUTE)) .forEach(attributesBuilder::put); attributesBuilder.put(Uuid.DEFAULT_ATTRIBUTE, Uuid.random().value()); return message.toBuilder().setAttributes(attributesBuilder.build()).build(); } @Override public PCollection<Message> expand(PCollection<Message> input) { PCollection<Message> withUuids = input .apply( "AddUuids", MapElements.into(new TypeDescriptor<Message>() {}).via(AddUuidsTransform::addUuid)) .setCoder(new MessageCoder()); return withUuids.apply("ShuffleToPersist", Reshuffle.viaRandomKey()); } }
34,306
https://github.com/lesleyhaha/REGNet_for_3D_Grasping/blob/master/utils.py
Github Open Source
Open Source
MIT
2,022
REGNet_for_3D_Grasping
lesleyhaha
Python
Code
1,602
8,644
import os import numpy as np import time import pickle import transforms3d import torch from tensorboardX import SummaryWriter import torch.utils.data import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.lr_scheduler import StepLR, MultiStepLR from dataset_utils.scoredataset import ScoreDataset from multi_model.score_network import ScoreNetwork from multi_model.gripper_region_network import GripperRegionNetwork from dataset_utils.eval_score.eval import eval_test, eval_validate def mkdir_output(base_path, tag, mode="train", log_flag=False): path = os.path.join(base_path, tag) if not os.path.exists(path): os.mkdir(path) if log_flag: logger = SummaryWriter(path) return logger def get_dataset(all_points_num, base_path, tag="train", seed=1, width=None): dataset = ScoreDataset( all_points_num = all_points_num, path = base_path, tag = tag, data_seed = seed, data_width = width) print(len(dataset)) return dataset def get_dataloader(dataset, batchsize, shuffle=True, num_workers=8, pin_memory=True): def my_worker_init_fn(pid): np.random.seed(torch.initial_seed() % (2**31-1)) def my_collate(batch): batch = list(filter(lambda x:x[0] is not None, batch)) return torch.utils.data.dataloader.default_collate(batch) dataloader = torch.utils.data.DataLoader( dataset, batch_size=batchsize, num_workers=num_workers, pin_memory=pin_memory, shuffle=shuffle, worker_init_fn=my_worker_init_fn, collate_fn=my_collate, ) return dataloader def construct_scorenet(load_flag, obj_class_num=2, model_path=None, gpu_num=0): score_model = ScoreNetwork(training=True, k_obj=obj_class_num) resume_num = 0 if load_flag and model_path is not '': model_dict = torch.load(model_path, map_location='cuda:{}'.format(gpu_num)).state_dict() #, map_location='cpu' new_model_dict = {} for key in model_dict.keys(): new_model_dict[key.replace("module.", "")] = model_dict[key] score_model.load_state_dict(new_model_dict) resume_num = 1+int(model_path.split('/')[-1].split('_')[1].split('.model')[0]) return score_model, resume_num def construct_rnet(load_flag, training_refine, group_num, gripper_num, grasp_score_threshold, depth, reg_channel, model_path=None, gpu_num=0): #-------------- load region (refine) network---------------- region_model = GripperRegionNetwork(training=training_refine, group_num=group_num, \ gripper_num=gripper_num, grasp_score_threshold=grasp_score_threshold, radius=depth, reg_channel=reg_channel) resume_num = 0 if load_flag and model_path is not '': cur_dict = region_model.state_dict() model_dict = torch.load(model_path, map_location='cuda:{}'.format(gpu_num)).state_dict() new_model_dict = {} for key in model_dict.keys(): new_model_dict[key.replace("module.", "")] = model_dict[key] cur_dict.update(new_model_dict) region_model.load_state_dict(cur_dict) resume_num = 1+int(model_path.split('/')[-1].split('_')[1].split('.model')[0]) return region_model, resume_num def construct_net(params, mode, gpu_num=0, load_score_flag=True, score_path=None, load_rnet_flag=True, rnet_path=None): # mode = ['train', 'pretrain_score', 'pretrain_region', 'validate', \ # 'validate_score', 'validate_region', 'test', 'test_score', 'test_region'] obj_class_num, group_num, gripper_num, grasp_score_threshold, depth, reg_channel = params if 'validate' in mode or 'test' in mode or mode == 'train': load_score_flag, load_rnet_flag = True, True elif mode == 'pretrain_region': load_score_flag = True score_model, score_resume = construct_scorenet(load_score_flag, obj_class_num, score_path, gpu_num) if 'score' in mode: return score_model, None, score_resume elif 'region' in mode: training_refine = False else: training_refine = True region_model, rnet_resume = construct_rnet(load_rnet_flag, training_refine, group_num, gripper_num, grasp_score_threshold, depth, reg_channel, rnet_path, gpu_num) if mode == "train" and 'pretrain' in rnet_path.split('/')[-1]: rnet_resume = 0 return score_model, region_model, rnet_resume def construct_scheduler(model, lr, resume_num=0): optimizer = optim.Adam([{'params':model.parameters(), 'initial_lr':lr}], lr=lr) #print(resume_num) scheduler = StepLR(optimizer, step_size=5, gamma=0.5, last_epoch=resume_num-1) return optimizer, scheduler def map_model(score_model, region_model, gpu_num:int, gpu_id:int, gpu_ids:str): device = torch.device("cuda:"+str(gpu_id)) score_model = score_model.to(device) if region_model is not None: region_model = region_model.to(device) if gpu_num > 1: device_id = [int(i) for i in gpu_ids.split(',')] score_model = nn.DataParallel(score_model, device_ids=device_id) if region_model is not None: region_model = nn.DataParallel(region_model, device_ids=device_id) print("Construct network successfully!") return score_model, region_model def add_log_epoch(logger, data, epoch, mode="train", method="refine"): if method == "score": logger.add_scalar('epoch_'+mode+'_stage1_loss_score', data[0], epoch) # scorenet regression loss elif method == "region": logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_center', data[0], epoch) logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_cos_orientation', data[1], epoch) logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_theta', data[2], epoch) logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_score', data[3], epoch) elif method == "refine": logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_center', data[0], epoch) logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_cos_orientation', data[1], epoch) logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_theta', data[2], epoch) logger.add_scalar('epoch_'+mode+'_stage2_pre_loss_score', data[3], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_center_stage2', data[4], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_cos_orientation_stage2', data[5], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_theta_stage2', data[6], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_score_stage2', data[7], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_center', data[8], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_cos_orientation', data[9], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_theta', data[10], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_score', data[11], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_center_score', data[12], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_cos_orientation_score', data[13], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_theta_score', data[14], epoch) logger.add_scalar('epoch_'+mode+'_stage3_pre_loss_score_score', data[15], epoch) def add_log_batch(logger, data, index, mode="train", method="refine"): def add_log_stage1(logger, loss, index, mode): logger.add_scalar('batch_'+mode+'_stage1_loss_score', loss, index) # scorenet regression loss def add_log_stage2(logger, acc, loss_tuple, index, mode): logger.add_scalar('batch_'+mode+'_stage2_anchor_acc', acc, index) # acc logger.add_scalar('batch_'+mode+'_stage2_loss', (loss_tuple[0].mean().data), index) logger.add_scalar('batch_'+mode+'_stage2_loss_class', (loss_tuple[1].mean()), index) logger.add_scalar('batch_'+mode+'_stage2_loss_first1', (loss_tuple[2].mean()), index) logger.add_scalar('batch_'+mode+'_stage2_loss_first2', (loss_tuple[3].mean()), index) logger.add_scalar('batch_'+mode+'_stage2_loss_first3', (loss_tuple[4].mean()), index) logger.add_scalar('batch_'+mode+'_stage2_loss_first4', (loss_tuple[5].mean()), index) logger.add_scalar('batch_'+mode+'_stage2_pre_loss_center', (loss_tuple[6].mean().data), index) logger.add_scalar('batch_'+mode+'_stage2_pre_loss_cos_orientation', (loss_tuple[7].mean()), index) logger.add_scalar('batch_'+mode+'_stage2_pre_loss_theta', (loss_tuple[8].mean().data), index) logger.add_scalar('batch_'+mode+'_stage2_pre_loss_score', (loss_tuple[9].mean().data), index) def add_log_stage3(logger, acc_refine, loss_refine_tuple, index, mode): logger.add_scalar('batch_'+mode+'_stage3_refine_acc', acc_refine, index) # acc_refine logger.add_scalar('batch_'+mode+'_stage3_loss', (loss_refine_tuple[0].mean().data), index) logger.add_scalar('batch_'+mode+'_stage3_loss_class', (loss_refine_tuple[1].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_loss_first1', (loss_refine_tuple[2].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_loss_first2', (loss_refine_tuple[3].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_loss_first3', (loss_refine_tuple[4].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_loss_first4', (loss_refine_tuple[5].data.mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_center_stage2', (loss_refine_tuple[6].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_cos_orientation_stage2', (loss_refine_tuple[7].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_theta_stage2', (loss_refine_tuple[8].mean().data), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_score_stage2', (loss_refine_tuple[9].mean().data), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_center', (loss_refine_tuple[10].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_cos_orientation', (loss_refine_tuple[11].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_theta', (loss_refine_tuple[12].mean().data), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_score', (loss_refine_tuple[13].mean().data), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_center_score', (loss_refine_tuple[14].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_cos_orientation_score', (loss_refine_tuple[15].mean()), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_theta_score', (loss_refine_tuple[16].mean().data), index) logger.add_scalar('batch_'+mode+'_stage3_pre_loss_score_score', (loss_refine_tuple[17].mean().data), index) if method == "score": add_log_stage1(logger, data[0].mean().data, index, mode) elif method == "region": add_log_stage1(logger, data[0].mean().data, index, mode) loss_tuple = data[2] acc = data[1].mean().data add_log_stage2(logger, acc, loss_tuple, index, mode) elif method == "refine": add_log_stage1(logger, data[0].mean().data, index, mode) loss_tuple, loss_refine_tuple = data[3], data[4] acc, acc_refine = data[1].mean().data, data[2].mean().data add_log_stage2(logger, acc, loss_tuple, index, mode) add_log_stage3(logger, acc_refine, loss_refine_tuple, index, mode) if mode == "train": if method == "direct": logger.add_scalar('train_loss_first1', (loss_tuple[1].mean()), index) logger.add_scalar('train_loss_first2', (loss_tuple[2].mean()), index) logger.add_scalar('train_loss_first3', (loss_tuple[3].mean()), index) logger.add_scalar('train_loss_first4', (loss_tuple[4].mean()), index) logger.add_scalar('train_loss_cos_roi_pre', (loss_tuple[5].mean()), index) logger.add_scalar('train_loss_theta_pre', (loss_tuple[6].mean()), index) logger.add_scalar('train_loss_center_pre', (loss_tuple[7].mean().data), index) logger.add_scalar('train_loss_score_pre', (loss_tuple[8].mean().data), index) def map_grasp_pc(data_path, keep_grasp_num, grasp, params, mask): ''' Input: keep_grasp_num: the number of predicted grasps for each data_path data_path : List grasp : torch.Tensor [N, 8] ''' print(keep_grasp_num) keep_grasp_num_new = keep_grasp_num[0].view(-1,1) #print(keep_grasp_num_new) for i in range(1, len(keep_grasp_num)): keep_grasp_num_new = torch.cat((keep_grasp_num_new, keep_grasp_num[i].view(-1,1)), dim=1) keep_grasp_num_new = keep_grasp_num_new.view(-1) for i in range(1, len(keep_grasp_num_new)): keep_grasp_num_new[i] += keep_grasp_num_new[i-1] # print(len(data_path),len(keep_grasp_num_new)) # print(keep_grasp_num_new) assert len(data_path) == len(keep_grasp_num_new) map_dict = {data_path[0]: grasp[:keep_grasp_num_new[0]]} for i in range(1, len(data_path)): map_dict.update({data_path[i]: grasp[keep_grasp_num_new[i-1]:keep_grasp_num_new[i]]}) if type(params[0]) is float: return map_dict, None lengths = params[0].view(-1,1).repeat(1,params[-1]).view(-1) lengths = lengths[mask] map_param_dict = {data_path[0]: lengths[:keep_grasp_num_new[0]]} for i in range(1, len(data_path)): map_param_dict.update({data_path[i]: lengths[keep_grasp_num_new[i-1]:keep_grasp_num_new[i]]}) return map_dict, map_param_dict def eval_grasp_with_gt(map_dict, record_data, params, map_param_dict, score_thres=None): ''' map_dict : {data_path: grasp} ''' total_vgr, total_score, grasp_num, grasp_num_before = record_data batch_vgr, batch_score, batch_vgr_before, batch_grasp_num, batch_grasp_before_num = 0, 0, 0, 0, 0 total_vgrs, total_scores, total_grasp_nums, total_grasp_before_nums = None, None, None, None depths, width, table_height, gpu, N_C = params for cur_data_path in map_dict.keys(): cur_grasp = map_dict[cur_data_path] # print("formal grasp number: {}".format(len(cur_grasp))) if len(cur_grasp) <= 0: continue cur_data = np.load(cur_data_path, allow_pickle=True) if '0' in cur_data_path.split('/')[-3]: width = float(cur_data_path.split('/')[-3]) # eg. .../4080_view_1.p if 'noise' not in cur_data_path.split('_')[-1]: view_num = int(cur_data_path.split('_')[-1].split('.')[0]) # eg. .../4080_view_1.p else: view_num = int(cur_data_path.split('_')[-2]) # eg. .../4080_view_1_noise.p depths = depths if map_param_dict is None else map_param_dict[cur_data_path] vgr, score, grasp_nocoll_view_num, grasp_nocoll_view, grasp_nocoll_scene = \ eval_validate(cur_data, cur_grasp[:,:8], view_num, table_height, depths, width, gpu) total_vgr += vgr total_score += score grasp_num += grasp_nocoll_view_num grasp_num_before += len(cur_grasp) batch_vgr += vgr batch_score += score batch_grasp_num += grasp_nocoll_view_num batch_grasp_before_num += len(cur_grasp) if grasp_nocoll_view_num == 0: grasp_nocoll_view_num = 1 print("before vgr: {}".format(vgr/len(cur_grasp)) ) print("vgr: {}".format(vgr/grasp_nocoll_view_num) ) print("score: {}".format(score/grasp_nocoll_view_num) ) if batch_grasp_before_num == 0: batch_grasp_before_num = 1 if batch_grasp_num == 0: batch_grasp_num = 1 batch_vgr_before = batch_vgr / batch_grasp_before_num batch_vgr /= batch_grasp_num batch_score /= batch_grasp_num print("#before batch vgr \t", batch_vgr_before) print("#batch vgr \t", batch_vgr) print("#batch score \t", batch_score) record_data = (total_vgr, total_score, grasp_num, grasp_num_before) if score_thres: total_vgrs, total_scores, total_grasp_nums, total_grasp_before_nums = \ [0]*len(score_thres), [0]*len(score_thres), [0]*len(score_thres), [0]*len(score_thres), [0]*len(score_thres) for ind in range(len(score_thres)): score_thre = score_thres[ind] for cur_data_path in map_dict.keys(): cur_grasp = map_dict[cur_data_path] cur_grasp = cur_grasp(cur_grasp[:,7] > score_thre) # print("formal grasp number: {}".format(len(cur_grasp))) if len(cur_grasp) <= 0: continue cur_data = np.load(cur_data_path, allow_pickle=True) if '0' in cur_data_path.split('/')[-3]: width = float(cur_data_path.split('/')[-3]) # eg. .../4080_view_1.p if 'noise' not in cur_data_path.split('_')[-1]: view_num = int(cur_data_path.split('_')[-1].split('.')[0]) # eg. .../4080_view_1.p else: view_num = int(cur_data_path.split('_')[-2]) # eg. .../4080_view_1_noise.p depths = depths if map_param_dict is None else map_param_dict[cur_data_path] vgr, score, grasp_nocoll_view_num, grasp_nocoll_view, grasp_nocoll_scene = \ eval_validate(cur_data, cur_grasp[:,:8], view_num, table_height, depths, width, gpu) total_vgrs[ind] += vgr total_scores[ind] += score total_grasp_nums[ind] += grasp_nocoll_view_num total_grasp_before_nums[ind] += len(cur_grasp) return batch_vgr, batch_score, batch_vgr_before, record_data, \ total_vgrs, total_scores, total_grasp_nums, total_grasp_before_nums def eval_and_log(logger, data_path, keep_grasp_num, mask, grasp, record_data, params, index, mode, stage='stage2'): map_dict, map_param_dict = map_grasp_pc(data_path, keep_grasp_num, grasp, params, mask) print("=======================evaluate grasp from {}=======================".format(stage)) score_thres = None # if 'test' in mode and stage == 'stage3_class': # score_thres = [0.1, 0.2, 0.3, 0.5, 0.6, 0.7, 0.8, 0.9] batch_vgr, batch_score, batch_vgr_before, record_data, \ total_vgrs, total_scores, total_grasp_nums, total_grasp_before_nums = \ eval_grasp_with_gt(map_dict, record_data, params, map_param_dict, score_thres) if batch_vgr !=0 and batch_score !=0 and batch_vgr_before !=0 : logger.add_scalar('batch_'+mode+'_vgr_'+stage, batch_vgr, index) logger.add_scalar('batch_'+mode+'_score_'+stage, batch_score, index) logger.add_scalar('batch_'+mode+'_vgr_before_'+stage, batch_vgr_before, index) print("=========================================================================") return record_data def add_eval_log_epoch(logger, data, batch_nums, epoch, mode, stages): for i in range(len(data)): data_i = data[i] stage_i = stages[i] #### data_i :(nocoll_scene_num, total_score, nocoll_view_num, formal_num) total_vgr_before = data_i[0] / data_i[3] total_score = data_i[1] / data_i[2] total_vgr = data_i[0] / data_i[2] print("{} before_total_vgr: \t{}".format(stage_i, total_vgr_before) ) print("{} total_vgr: \t{}".format(stage_i, total_vgr) ) print("{} total_score: \t{}".format(stage_i, total_score) ) logger.add_scalar('epoch_'+mode+'_'+stage_i+'_vgr_before', total_vgr_before, epoch) logger.add_scalar('epoch_'+mode+'_'+stage_i+'_vgr', total_vgr, epoch) logger.add_scalar('epoch_'+mode+'_'+stage_i+'_score', total_score, epoch) ####___________________________test function_____________________________ def eval_notruth(pc, color, grasp_stage2, grasp_stage3, grasp_stage3_score, grasp_stage3_stage2, output_score, params, grasp_save_path=None): depths, width, table_height, gpu, _ = params view_num = None if len(grasp_stage2) >= 1: grasp_stage2 = eval_test(pc, grasp_stage2[:,:8], view_num, table_height, depths, width, gpu) if len(grasp_stage3_stage2) >= 1: grasp_stage3_stage2 = eval_test(pc, grasp_stage3_stage2[:,:8], view_num, table_height, depths, width, gpu) if len(grasp_stage3) >= 1: grasp_stage3 = eval_test(pc, grasp_stage3[:,:8], view_num, table_height, depths, width, gpu) if len(grasp_stage3_score) >= 1: grasp_stage3_score = eval_test(pc, grasp_stage3_score[:,:8], view_num, table_height, depths, width, gpu) if gpu != -1: output_score = output_score.view(-1,1).cpu() grasp_stage2 = grasp_stage2.cpu() grasp_stage3_stage2 = grasp_stage3_stage2.cpu() grasp_stage3 = grasp_stage3.cpu() grasp_stage3_score = grasp_stage3_score.cpu() print("stage2 grasp num:", len(grasp_stage2)) print("stage3 grasp num:", len(grasp_stage2)) print("stage3 grasp num (with scorethre):", len(grasp_stage3_score)) output_dict = { 'points' : pc, 'colors' : color, 'scores' : output_score.numpy(), 'grasp_stage2' : grasp_stage2.numpy(), 'grasp_stage3_stage2': grasp_stage3_stage2.numpy(), 'grasp_stage3' : grasp_stage3.numpy(), 'grasp_stage3_score' : grasp_stage3_score.numpy(), } print(grasp_save_path) if grasp_save_path: with open(grasp_save_path, 'wb') as file: pickle.dump(output_dict, file) def noise_color(pc_color): obj_color_time = 1-np.random.rand(3) / 5 print("noise color time", obj_color_time) for i in range(3,6): pc_color[:,i] *= obj_color_time[i-3] return pc_color def local_to_global_transformation_quat(point): T_local_to_global = np.eye(4) #quat = transforms3d.quaternions.axangle2quat([1,0,0], np.pi*1.13) quat = transforms3d.euler.euler2quat(-0.87*np.pi, 0, 0) frame = transforms3d.quaternions.quat2mat(quat) T_local_to_global[0:3, 0:3] = frame T_local_to_global[0:3, 3] = point return T_local_to_global def transform_grasp(grasp_ori): ''' Input: grasp_ori: [B, 13] Output: grasp_trans:[B, 8] (center[3], axis_y[3], grasp_angle[1], score[1]) ''' B, _ = grasp_ori.shape grasp_trans = torch.full((B, 8), -1) # axis_x = torch.cat([grasp_ori[:,0:1], grasp_ori[:,4:5], grasp_ori[:,8:9]], dim=1) # axis_y = torch.cat([grasp_ori[:,1:2], grasp_ori[:,5:6], grasp_ori[:,9:10]], dim=1) # axis_z = torch.cat([grasp_ori[:,2:3], grasp_ori[:,6:7], grasp_ori[:,10:11]], dim=1) # center = torch.cat([grasp_ori[:,3:4], grasp_ori[:,7:8], grasp_ori[:,11:12]], dim=1) axis_x, axis_y, axis_z, center = grasp_ori[:,0:3], grasp_ori[:,3:6], grasp_ori[:,6:9], grasp_ori[:,9:12] grasp_angle = torch.atan2(axis_x[:,2], axis_z[:,2]) ## torch.atan(torch.div(axis_x[:,2], axis_z[:,2])) is not OK!!! ''' grasp_angle[axis_y[:,0] < 0] = np.pi-grasp_angle[axis_y[:,0] < 0] axis_y[axis_y[:,0] < 0] = -axis_y[axis_y[:,0] < 0] grasp_angle[grasp_angle >= 2*np.pi] = grasp_angle[grasp_angle >= 2*np.pi] - 2*np.pi grasp_angle[grasp_angle <= -2*np.pi] = grasp_angle[grasp_angle <= -2*np.pi] + 2*np.pi grasp_angle[grasp_angle > np.pi] = grasp_angle[grasp_angle > np.pi] - 2*np.pi grasp_angle[grasp_angle <= -np.pi] = grasp_angle[grasp_angle <= -np.pi] + 2*np.pi ''' grasp_trans[:,:3] = center grasp_trans[:,3:6] = axis_y grasp_trans[:,6] = grasp_angle grasp_trans[:,7] = grasp_ori[:,12] return grasp_trans
18,649
https://github.com/mylibero/rv-monitor/blob/master/rv-monitor/src/main/java/com/runtimeverification/rvmonitor/java/rvj/parser/ast/visitor/DumpVisitor.java
Github Open Source
Open Source
MIT
2,021
rv-monitor
mylibero
Java
Code
585
2,101
/* * Copyright (C) 2008 Feng Chen. * * This file is part of RV Monitor parser. * * RV Monitor is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RV Monitor is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with RV Monitor. If not, see <http://www.gnu.org/licenses/>. */ package com.runtimeverification.rvmonitor.java.rvj.parser.ast.visitor; import java.util.Iterator; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.ImportDeclaration; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.Node; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.PackageDeclaration; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.RVMSpecFile; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.expr.NameExpr; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.expr.QualifiedNameExpr; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.EventDefinition; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.Formula; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.PropertyAndHandlers; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.RVMParameter; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.RVMParameters; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.RVMonitorSpec; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.rvmspec.SpecModifierSet; import com.runtimeverification.rvmonitor.java.rvj.parser.ast.typepattern.BaseTypePattern; /** * @author Julio Vilmar Gesser */ public class DumpVisitor implements VoidVisitor<Object> { protected final SourcePrinter printer = new SourcePrinter(); public String getSource() { return printer.getSource(); } protected void printSpecModifiers(int modifiers) { if (SpecModifierSet.isAvoid(modifiers)) { printer.print("avoid "); } if (SpecModifierSet.isConnected(modifiers)) { printer.print("connected "); } if (SpecModifierSet.isDecentralized(modifiers)) { printer.print("decentralized "); } if (SpecModifierSet.isEnforce(modifiers)) { printer.print("enforce "); } if (SpecModifierSet.isFullBinding(modifiers)) { printer.print("full-binding "); } if (SpecModifierSet.isPerThread(modifiers)) { printer.print("perthread "); } if (SpecModifierSet.isSuffix(modifiers)) { printer.print("suffix "); } if (SpecModifierSet.isUnSync(modifiers)) { printer.print("unsynchronized "); } } protected void printSpecParameters(RVMParameters args, Object arg) { printer.print("("); if (args != null) { for (Iterator<RVMParameter> i = args.iterator(); i.hasNext();) { RVMParameter t = i.next(); t.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } } printer.print(")"); } @Override public void visit(Node n, Object arg) { throw new IllegalStateException(n.getClass().getName()); } /* visit functions for RV Monitor components */ @Override public void visit(RVMSpecFile f, Object arg) { if (f.getPakage() != null) f.getPakage().accept(this, arg); if (f.getImports() != null) { for (ImportDeclaration i : f.getImports()) { i.accept(this, arg); } printer.printLn(); } if (f.getSpecs() != null) { for (RVMonitorSpec i : f.getSpecs()) { i.accept(this, arg); printer.printLn(); } } } @Override public void visit(RVMonitorSpec s, Object arg) { printSpecModifiers(s.getModifiers()); printer.print(s.getName()); printSpecParameters(s.getParameters(), arg); if (s.getInMethod() != null) { printer.print(" within "); printer.print(s.getInMethod()); // s.getInMethod().accept(this, arg); } printer.printLn(" {"); printer.indent(); if (s.getDeclarationsStr() != null) { printer.printLn(s.getDeclarationsStr()); } if (s.getEvents() != null) { for (EventDefinition e : s.getEvents()) { e.accept(this, arg); } } if (s.getPropertiesAndHandlers() != null) { for (PropertyAndHandlers p : s.getPropertiesAndHandlers()) { p.accept(this, arg); } } printer.unindent(); printer.printLn("}"); } @Override public void visit(RVMParameter p, Object arg) { p.getType().accept(this, arg); printer.print(" " + p.getName()); } @Override public void visit(EventDefinition e, Object arg) { printer.print("event " + e.getId() + " "); printSpecParameters(e.getParameters(), arg); printer.printLn(e.getAction()); printer.printLn(); } @Override public void visit(PropertyAndHandlers p, Object arg) { p.getProperty().accept(this, arg); printer.printLn(); for (String event : p.getHandlers().keySet()) { String stmt = p.getHandlers().get(event); printer.printLn("@" + event); printer.indent(); printer.printLn(stmt); printer.unindent(); printer.printLn(); } } @Override public void visit(Formula f, Object arg) { printer.print(f.getType() + ": " + f.getFormula()); } /* visit functions for AspectJ components */ @Override public void visit(BaseTypePattern p, Object arg) { printer.print(p.getOp()); } /** visit functions for Java components */ @Override public void visit(PackageDeclaration n, Object arg) { printer.print("package "); n.getName().accept(this, arg); printer.printLn(";"); printer.printLn(); } @Override public void visit(NameExpr n, Object arg) { printer.print(n.getName()); } @Override public void visit(QualifiedNameExpr n, Object arg) { n.getQualifier().accept(this, arg); printer.print("."); printer.print(n.getName()); } @Override public void visit(ImportDeclaration n, Object arg) { printer.print("import "); if (n.isStatic()) { printer.print("static "); } n.getName().accept(this, arg); if (n.isAsterisk()) { printer.print(".*"); } printer.printLn(";"); } }
34,473
https://github.com/sanaullah099/fullstack/blob/master/resources/js/components/about.vue
Github Open Source
Open Source
MIT
null
fullstack
sanaullah099
Vue
Code
23
87
<template> <div> <navbar-component /> <router-link to="/example"> Back to example</router-link> <router-link to="/test"> go to sana page </router-link> <h1>Welcome to about us page</h1> </div> </template>
48,859
https://github.com/georgiachr/app-based-on-md/blob/master/tasks/config/jsdocs.js
Github Open Source
Open Source
MIT
null
app-based-on-md
georgiachr
JavaScript
Code
67
243
/** * Clean files and folders. * * --------------------------------------------------------------- * * This grunt task is configured to clean out the contents in the .tmp/public of your * sails project. * * For usage docs see: * https://github.com/gruntjs/grunt-contrib-clean */ module.exports = function(grunt) { var path = 'c:/Users/Georgia Chr/workspace/mytriangular' grunt.config.set('jsdoc',{ api: { src: [path+'/api/**/*.js',path + '/api/*.js'], options:{destination: 'docs-api'} }, client: { src: [path+'/client/**/*.js',path+'/client/**/*.js'], options:{destination: 'docs-client'} } }); grunt.loadNpmTasks('grunt-jsdoc'); };
4,840
https://github.com/Teravus/RebootTechChatBot/blob/master/TwitchLib.Api/TwitchLib.Api.Helix.Models/Common/Pagination.cs
Github Open Source
Open Source
MIT
2,021
RebootTechChatBot
Teravus
C#
Code
22
66
using Newtonsoft.Json; namespace TwitchLib.Api.Helix.Models.Common { public class Pagination { [JsonProperty(PropertyName = "cursor")] public string Cursor { get; protected set; } } }
19,551
https://github.com/tranek/coh2_rgt_extractor/blob/master/coh2_rgt_extractor/Rainman_src/gnuc_defines.cpp
Github Open Source
Open Source
MIT
2,016
coh2_rgt_extractor
tranek
C++
Code
373
823
/* Rainman Library Copyright (C) 2006 Corsix <corsix@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "gnuc_defines.h" #ifdef RAINMAN_GNUC #include <cmath> #include <algorithm> wchar_t* _ltow(long iVal, wchar_t* sStr, int iRadix) { if (iRadix < 2 || iRadix > 16) { *sStr = 0; return sStr; } wchar_t* out = sStr; long quotient = iVal; long base = (long)iRadix; do { *out = "0123456789abcdef"[ std::abs( quotient % base ) ]; ++out; quotient /= base; } while ( quotient ); if ( iVal < 0 && base == 10) *out++ = '-'; std::reverse( sStr, out ); *out = 0; return sStr; } wchar_t* _ultow(unsigned long iVal, wchar_t* sStr, int iRadix) { if (iRadix < 2 || iRadix > 16) { *sStr = 0; return sStr; } wchar_t* out = sStr; unsigned long quotient = iVal; unsigned long base = (unsigned long)iRadix; do { *out = "0123456789abcdef"[ std::abs( (long)(quotient % base) ) ]; ++out; quotient /= base; } while ( quotient ); if ( iVal < 0 && base == 10) *out++ = '-'; std::reverse( sStr, out ); *out = 0; return sStr; } char* _ultoa(unsigned long iVal, char* sStr, int iRadix) { if (iRadix < 2 || iRadix > 16) { *sStr = 0; return sStr; } char* out = sStr; unsigned long quotient = iVal; unsigned long base = (unsigned long)iRadix; do { *out = "0123456789abcdef"[ std::abs( (long)(quotient % base) ) ]; ++out; quotient /= base; } while ( quotient ); if ( iVal < 0 && base == 10) *out++ = '-'; std::reverse( sStr, out ); *out = 0; return sStr; } #endif
6,539