text
stringlengths
12
215k
#ifndef __GTHREE_VECTOR_KEYFRAME_TRACK_H__ #define __GTHREE_VECTOR_KEYFRAME_TRACK_H__ #if !defined (__GTHREE_H_INSIDE__) && !defined (GTHREE_COMPILATION) #error "Only <gthree/gthree.h> can be included directly." #endif #include <gthree/gthreekeyframetrack.h> G_BEGIN_DECLS #define GTHREE_TYPE_VECTOR_KEYFRAME_TRACK (gthree_vector_keyframe_track_get_type ()) #define GTHREE_VECTOR_KEYFRAME_TRACK(inst) (G_TYPE_CHECK_INSTANCE_CAST ((inst), \ GTHREE_TYPE_VECTOR_KEYFRAME_TRACK, \ GthreeVectorKeyframeTrack)) #define GTHREE_IS_VECTOR_KEYFRAME_TRACK(inst) (G_TYPE_CHECK_INSTANCE_TYPE ((inst), \ GTHREE_TYPE_VECTOR_KEYFRAME_TRACK)) #define GTHREE_VECTOR_KEYFRAME_TRACK_GET_CLASS(inst) (G_TYPE_INSTANCE_GET_CLASS ((inst), GTHREE_TYPE_VECTOR_KEYFRAME_TRACK, GthreeVectorKeyframeTrackClass)) typedef struct { GthreeKeyframeTrack parent; } GthreeVectorKeyframeTrack; typedef struct { GthreeKeyframeTrackClass parent_class; } GthreeVectorKeyframeTrackClass; G_DEFINE_AUTOPTR_CLEANUP_FUNC (GthreeVectorKeyframeTrack, g_object_unref) GTHREE_API GType gthree_vector_keyframe_track_get_type (void) G_GNUC_CONST; GTHREE_API GthreeKeyframeTrack *gthree_vector_keyframe_track_new (const char *name, GthreeAttributeArray *times, GthreeAttributeArray *values); G_END_DECLS #endif /* __GTHREE_VECTOR_KEYFRAME_TRACK_H__ */
var width = window.innerWidth, height = window.innerHeight, boids = [], destination, canvas, context; const MAX_NUMBER = 100; const MAX_SPEED = 1; const radius = 5; init(); animation(); function init(){ canvas = document.getElementById('canvas'), context = canvas.getContext( "2d" ); canvas.width = width; canvas.height = height; destination = { x:Math.random()*width, y:Math.random()*height }; for (var i = 0; i <MAX_NUMBER; i++) { boids[i] = new Boid(); }; } var _animation; function animation(){ _animation = requestAnimationFrame(animation); context.clearRect(0,0,width,height); for (var i = 0; i < boids.length; i++) { boids[i].rule1(); boids[i].rule2(); boids[i].rule3(); boids[i].rule4(); boids[i].rule5(); boids[i].rule6(); var nowSpeed = Math.sqrt(boids[i].vx * boids[i].vx + boids[i].vy * boids[i].vy ); if(nowSpeed > MAX_SPEED){ boids[i].vx *= MAX_SPEED / nowSpeed; boids[i].vy *= MAX_SPEED / nowSpeed; } boids[i].x += boids[i].vx; boids[i].y += boids[i].vy; drawCircle(boids[i].x,boids[i].y); drawVector(boids[i].x,boids[i].y,boids[i].vx,boids[i].vy); }; } /* //mouseEvent document.onmousemove = function (event){ destination ={ x:event.screenX, y:event.screenY } }; */ function Boid(){ this.x = Math.random()*width; this.y = Math.random()*height; this.vx = 0.0; this.vy = 0.0; this.dx = Math.random()*width; this.dy = Math.random()*height; //群れの中心に向かう this.rule1 = function(){ var centerx = 0, centery = 0; for (var i = 0; i < boids.length; i++) { if (boids[i] != this) { centerx += boids[i].x; centery += boids[i].y; }; }; centerx /= MAX_NUMBER-1; centery /= MAX_NUMBER-1; this.vx += (centerx-this.x)/1000; this.vy += (centery-this.y)/1000; } //他の個体と離れるように動く this.rule2 = function(){ var _vx = 0, _vy = 0; for (var i = 0; i < boids.length; i++) { if(this != boids[i]){ var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y); if(distance<25){ distance += 0.001; _vx -= (boids[i].x - this.x)/distance; _vy -= (boids[i].y - this.y)/distance; //this.dx = -boids[i].x; //this.dy = -boids[i].y; } } }; this.vx += _vx; this.vy += _vy; } //他の個体と同じ速度で動こうとする this.rule3 = function(){ var _pvx = 0, _pvy = 0; for (var i = 0; i < boids.length; i++) { if (boids[i] != this) { _pvx += boids[i].vx; _pvy += boids[i].vy; } }; _pvx /= MAX_NUMBER-1; _pvy /= MAX_NUMBER-1; this.vx += (_pvx - this.vx)/10; this.vy += (_pvy - this.vy)/10; }; //壁側の時の振る舞い this.rule4 = function(){ if(this.x < 10 && this.vx < 0)this.vx += 10/(Math.abs( this.x ) + 1 ); if(this.x > width && this.vx > 0)this.vx -= 10/(Math.abs( width - this.x ) + 1 ); if (this.y < 10 && this.vy < 0)this.vy += 10/(Math.abs( this.y ) + 1 ); if(this.y > height && this.vy > 0)this.vy -= 10/(Math.abs( height - this.y ) + 1 ); }; //目的地に行く this.rule5 = function(){ var _dx = this.dx - this.x, _dy = this.dy - this.y; this.vx += (this.dx - this.x)/500; this.vy += (this.dy - this.y)/500; } //捕食する this.rule6 = function(){ var _vx = Math.random()-0.5, _vy = Math.random()-0.5; for (var i = 0; i < boids.length; i++) { if(this != boids[i] && this.dx != boids[i].dx && this.dy != boids[i].dy){ var distance = distanceTo(this.x,boids[i].x,this.y,boids[i].y); if(distance<20 && distance>15){ console.log(distance); distance += 0.001; _vx += (boids[i].x - this.x)/distance; _vy += (boids[i].y - this.y)/distance; drawLine(this.x,this.y,boids[i].x,boids[i].y); this.dx = boids[i].dx; this.dy = boids[i].dy; } } }; this.vx += _vx; this.vy += _vy; } } function distanceTo(x1,x2,y1,y2){ var dx = x2-x1, dy = y2-y1; return Math.sqrt(dx*dx+dy*dy); } function drawCircle(x,y){ context.beginPath(); context.strokeStyle = "#fff"; context.arc(x,y,radius,0,Math.PI*2,false); context.stroke(); } const VectorLong = 10; function drawVector(x,y,vx,vy){ context.beginPath(); var pointx = x+vx*VectorLong; var pointy = y+vy*VectorLong; context.moveTo(x,y); context.lineTo(pointx,pointy); context.stroke(); } function drawLine(x1,y1,x2,y2){ context.beginPath(); context.moveTo(x1,y1); context.lineTo(x2,y2); context.stroke(); }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreatePlatformsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('platforms', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('short_name'); $table->string('slug')->unique(); $table->string('logo'); $table->string('banner'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('platforms'); } }
b'What is -38 - (-57 - -20 - -10)?\n'
b'What is -11 + (-4 - (16 + -8 - 1 - 1))?\n'
b'What is 23 + (-6 - (8 + -13 + -7) - 9)?\n'
version https://git-lfs.github.com/spec/v1 oid sha256:f5c198d5eef0ca0f41f87746ef8fefe819a727fcd59a6477c76b94b55d27128d size 1730
b'What is -5 + -1 - (-12 + 6) - -7?\n'
/* Copyright (c) 2019, 2022 Dennis Wölfing * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* libc/src/stdio/__file_write.c * Write data to a file. (called from C89) */ #define write __write #include <unistd.h> #include "FILE.h" size_t __file_write(FILE* file, const unsigned char* p, size_t size) { size_t written = 0; while (written < size) { ssize_t result = write(file->fd, p, size - written); if (result < 0) { file->flags |= FILE_FLAG_ERROR; return written; } written += result; p += result; } return written; }
from api_request import Api from util import Util from twocheckout import Twocheckout class Sale(Twocheckout): def __init__(self, dict_): super(self.__class__, self).__init__(dict_) @classmethod def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale @classmethod def list(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/list_sales', params)) return response.sale_summary def refund(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id url = 'sales/refund_lineitem' elif hasattr(self, 'invoice_id'): params['invoice_id'] = self.invoice_id url = 'sales/refund_invoice' else: params['sale_id'] = self.sale_id url = 'sales/refund_invoice' return Sale(Api.call(url, params)) def stop(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id return Api.call('sales/stop_lineitem_recurring', params) elif hasattr(self, 'sale_id'): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v params = {'lineitem_id': lineitem_id} result[i] = Api.call('sales/stop_lineitem_recurring', params) i += 1 response = { "response_code": "OK", "response_message": str(len(result)) + " lineitems stopped successfully" } else: response = { "response_code": "NOTICE", "response_message": "No active recurring lineitems" } else: response = { "response_code": "NOTICE", "response_message": "This method can only be called on a sale or lineitem" } return Sale(response) def active(self): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v result[i] = lineitem_id i += 1 response = { "response_code": "ACTIVE", "response_message": str(len(result)) + " active recurring lineitems" } else: response = { "response_code": "NOTICE","response_message": "No active recurring lineitems" } return Sale(response) def comment(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/create_comment', params)) def ship(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/mark_shipped', params))
#include <stdio.h> #include "cgm_play.h" #include "cgm_list.h" #ifndef _CGM_TYPES_H_ #define _CGM_TYPES_H_ #ifdef __cplusplus extern "C" { #endif typedef int(*CGM_FUNC)(tCGM* cgm); typedef struct { double xmin; double xmax; double ymin; double ymax; } tLimit; typedef struct { unsigned long red; unsigned long green; unsigned long blue; } tRGB; typedef union { unsigned long index; tRGB rgb; } tColor; typedef struct { char *data; int size; /* allocated size */ int len; /* used size */ int bc; /* byte count */ int pc; /* pixel count */ } tData; typedef struct { const char *name; CGM_FUNC func; } tCommand; typedef struct { long index; long type; long linecap; long dashcap; /* unused */ long linejoin; double width; tColor color; } tLineAtt; typedef struct { long index; long type; long linecap; long dashcap; /* unused */ long linejoin; double width; tColor color; short visibility; } tEdgeAtt; typedef struct { long index; long type; double size; tColor color; } tMarkerAtt; typedef struct { long index; long font_index; tList *font_list; short prec; /* unused */ double exp_fact; double char_spacing; /* unused */ tColor color; double height; cgmPoint char_up; /* unused */ cgmPoint char_base; short path; long restr_type; /* unused */ struct { short hor; short ver; double cont_hor; /* unused */ double cont_ver; /* unused */ } alignment; } tTextAtt; typedef struct { long index; short int_style; tColor color; long hatch_index; long pat_index; tList *pat_list; cgmPoint ref_pt; /* unused */ struct { cgmPoint height; /* unused */ cgmPoint width; /* unused */ } pat_size; /* unused */ } tFillAtt; typedef struct { long index; long nx, ny; tColor *pattern; } tPatTable; typedef struct { short type; short value; } tASF; struct _tCGM { FILE *fp; int file_size; tData buff; union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec ; } int_prec; union { long b_prec; /* 0=float*32, 1=float*64(double), 2=fixed*32, 3=fixed*64 */ struct { double minreal; double maxreal; long digits; } t_prec; } real_prec; union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec; } ix_prec; long cd_prec; /* used only for binary */ long cix_prec; /* used only for binary */ struct { tRGB black; tRGB white; } color_ext; long max_cix; tRGB* color_table; struct { short mode; /* abstract (pixels, factor is always 1), metric (coordinate * factor = coordinate_mm) */ double factor; } scale_mode; short color_mode; /* indexed, direct */ short linewidth_mode; /* absolute, scaled, fractional, mm */ short markersize_mode; /* absolute, scaled, fractional, mm */ short edgewidth_mode; /* absolute, scaled, fractional, mm */ short interiorstyle_mode; /* absolute, scaled, fractional, mm (unused) */ short vdc_type; /* integer, real */ union { long b_prec; /* 0=8, 1=16, 2=24, 3=32 */ struct { long minint; long maxint; } t_prec; } vdc_int; union { long b_prec; /* 0=float*32, 1=float*64(double), 2=fixed*32, 3=fixed*64 */ struct { double minreal; double maxreal; long digits; } t_prec; } vdc_real; struct { cgmPoint first; /* lower-left corner */ cgmPoint second; /* upper-right corner */ cgmPoint maxFirst; /* maximum lower-left corner */ cgmPoint maxSecond; /* maximum upper-right corner */ short has_max; } vdc_ext; tRGB back_color; tColor aux_color; short transparency; short cell_transp; /* (affects cellarray and pattern) unused */ tColor cell_color; /* unused */ struct { cgmPoint first; cgmPoint second; } clip_rect; short clip_ind; long region_idx; /* unused */ long region_ind; /* unused */ long gdp_sample_type, gdp_n_samples; cgmPoint gdp_pt[4]; char* gdp_data_rec; double mitrelimit; /* unused */ tLineAtt line_att; tMarkerAtt marker_att; tTextAtt text_att; tFillAtt fill_att; tEdgeAtt edge_att; tList* asf_list; /* unused */ cgmPoint* point_list; int point_list_n; cgmPlayFuncs dof; void* userdata; }; #define CGM_CONT 3 enum { CGM_OFF, CGM_ON }; enum { CGM_INTEGER, CGM_REAL }; enum { CGM_STRING, CGM_CHAR, CGM_STROKE }; enum { CGM_ABSOLUTE, CGM_SCALED, CGM_FRACTIONAL, CGM_MM }; enum { CGM_ABSTRACT, CGM_METRIC }; enum { CGM_INDEXED, CGM_DIRECT }; enum { CGM_HOLLOW, CGM_SOLID, CGM_PATTERN, CGM_HATCH, CGM_EMPTY, CGM_GEOPAT, CGM_INTERP }; enum { CGM_INVISIBLE, CGM_VISIBLE, CGM_CLOSE_INVISIBLE, CGM_CLOSE_VISIBLE }; enum { CGM_PATH_RIGHT, CGM_PATH_LEFT, CGM_PATH_UP, CGM_PATH_DOWN }; int cgm_bin_rch(tCGM* cgm); int cgm_txt_rch(tCGM* cgm); void cgm_strupper(char *s); void cgm_calc_arc_3p(cgmPoint start, cgmPoint intermediate, cgmPoint end, cgmPoint *center, double *radius, double *angle1, double *angle2); void cgm_calc_arc(cgmPoint start, cgmPoint end, double *angle1, double *angle2); void cgm_calc_arc_rev(cgmPoint start, cgmPoint end, double *angle1, double *angle2); void cgm_calc_ellipse(cgmPoint center, cgmPoint first, cgmPoint second, cgmPoint start, cgmPoint end, double *angle1, double *angle2); cgmRGB cgm_getcolor(tCGM* cgm, tColor color); cgmRGB cgm_getrgb(tCGM* cgm, tRGB rgb); void cgm_getcolor_ar(tCGM* cgm, tColor color, unsigned char *r, unsigned char *g, unsigned char *b); void cgm_setmarker_attrib(tCGM* cgm); void cgm_setline_attrib(tCGM* cgm); void cgm_setedge_attrib(tCGM* cgm); void cgm_setfill_attrib(tCGM* cgm); void cgm_settext_attrib(tCGM* cgm); int cgm_inccounter(tCGM* cgm); void cgm_polygonset(tCGM* cgm, int np, cgmPoint* pt, short* flags); void cgm_generalizeddrawingprimitive(tCGM* cgm, int id, int np, cgmPoint* pt, const char* data_rec); void cgm_sism5(tCGM* cgm, const char *data_rec); #ifdef __cplusplus } #endif #endif
b'-13 - -5 - (-11 + -2 + -3)\n'
package com.arekusu.datamover.model.jaxb; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.arekusu.com}DefinitionType"/> * &lt;/sequence> * &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "definitionType" }) @XmlRootElement(name = "ModelType", namespace = "http://www.arekusu.com") public class ModelType { @XmlElement(name = "DefinitionType", namespace = "http://www.arekusu.com", required = true) protected DefinitionType definitionType; @XmlAttribute(name = "version") protected String version; /** * Gets the value of the definitionType property. * * @return * possible object is * {@link DefinitionType } * */ public DefinitionType getDefinitionType() { return definitionType; } /** * Sets the value of the definitionType property. * * @param value * allowed object is * {@link DefinitionType } * */ public void setDefinitionType(DefinitionType value) { this.definitionType = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link String } * */ public String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link String } * */ public void setVersion(String value) { this.version = value; } }
var utils = require('./utils') , request = require('request') ; module.exports = { fetchGithubInfo: function(email, cb) { var githubProfile = {}; var api_call = "https://api.github.com/search/users?q="+email+"%20in:email"; var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } }; console.log("Calling "+api_call); request(options, function(err, res, body) { if(err) return cb(err); res = JSON.parse(body); if(res.total_count==1) githubProfile = res.items[0]; cb(null, githubProfile); }); }, fetchGravatarProfile: function(email, cb) { var gravatarProfile = {}; var hash = utils.getHash(email); var api_call = "http://en.gravatar.com/"+hash+".json"; console.log("Calling "+api_call); var options = { url: api_call, headers: { 'User-Agent': 'Blogdown' } }; request(options, function(err, res, body) { if(err) return cb(err); try { res = JSON.parse(body); } catch(e) { console.error("fetchGravatarProfile: Couldn't parse response JSON ", body, e); return cb(e); } if(res.entry && res.entry.length > 0) gravatarProfile = res.entry[0]; return cb(null, gravatarProfile); }); } };
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * The location of Google Cloud Storage dataset. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = GoogleCloudStorageLocation.class) @JsonTypeName("GoogleCloudStorageLocation") public class GoogleCloudStorageLocation extends DatasetLocation { /** * Specify the bucketName of Google Cloud Storage. Type: string (or * Expression with resultType string). */ @JsonProperty(value = "bucketName") private Object bucketName; /** * Specify the version of Google Cloud Storage. Type: string (or Expression * with resultType string). */ @JsonProperty(value = "version") private Object version; /** * Get specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the bucketName value */ public Object bucketName() { return this.bucketName; } /** * Set specify the bucketName of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param bucketName the bucketName value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withBucketName(Object bucketName) { this.bucketName = bucketName; return this; } /** * Get specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @return the version value */ public Object version() { return this.version; } /** * Set specify the version of Google Cloud Storage. Type: string (or Expression with resultType string). * * @param version the version value to set * @return the GoogleCloudStorageLocation object itself. */ public GoogleCloudStorageLocation withVersion(Object version) { this.version = version; return this; } }
// Copyright (c) 2021 The Decred developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package indexers import ( "context" "fmt" "sync" "sync/atomic" "github.com/decred/dcrd/blockchain/v4/internal/progresslog" "github.com/decred/dcrd/database/v3" "github.com/decred/dcrd/dcrutil/v4" ) // IndexNtfnType represents an index notification type. type IndexNtfnType int const ( // ConnectNtfn indicates the index notification signals a block // connected to the main chain. ConnectNtfn IndexNtfnType = iota // DisconnectNtfn indicates the index notification signals a block // disconnected from the main chain. DisconnectNtfn ) var ( // bufferSize represents the index notification buffer size. bufferSize = 128 // noPrereqs indicates no index prerequisites. noPrereqs = "none" ) // IndexNtfn represents an index notification detailing a block connection // or disconnection. type IndexNtfn struct { NtfnType IndexNtfnType Block *dcrutil.Block Parent *dcrutil.Block PrevScripts PrevScripter IsTreasuryEnabled bool Done chan bool } // IndexSubscription represents a subscription for index updates. type IndexSubscription struct { id string idx Indexer subscriber *IndexSubscriber mtx sync.Mutex // prerequisite defines the notification processing hierarchy for this // subscription. It is expected that the subscriber associated with the // prerequisite provided processes notifications before they are // delivered by this subscription to its subscriber. An empty string // indicates the subscription has no prerequisite. prerequisite string // dependent defines the index subscription that requires the subscriber // associated with this subscription to have processed incoming // notifications before it does. A nil dependency indicates the subscription // has no dependencies. dependent *IndexSubscription } // newIndexSubscription initializes a new index subscription. func newIndexSubscription(subber *IndexSubscriber, indexer Indexer, prereq string) *IndexSubscription { return &IndexSubscription{ id: indexer.Name(), idx: indexer, prerequisite: prereq, subscriber: subber, } } // stop prevents any future index updates from being delivered and // unsubscribes the associated subscription. func (s *IndexSubscription) stop() error { // If the subscription has a prerequisite, find it and remove the // subscription as a dependency. if s.prerequisite != noPrereqs { s.mtx.Lock() prereq, ok := s.subscriber.subscriptions[s.prerequisite] s.mtx.Unlock() if !ok { return fmt.Errorf("no subscription found with id %s", s.prerequisite) } prereq.mtx.Lock() prereq.dependent = nil prereq.mtx.Unlock() return nil } // If the subscription has a dependent, stop it as well. if s.dependent != nil { err := s.dependent.stop() if err != nil { return err } } // If the subscription is independent, remove it from the // index subscriber's subscriptions. s.mtx.Lock() delete(s.subscriber.subscriptions, s.id) s.mtx.Unlock() return nil } // IndexSubscriber subscribes clients for index updates. type IndexSubscriber struct { subscribers uint32 // update atomically. c chan IndexNtfn subscriptions map[string]*IndexSubscription mtx sync.Mutex ctx context.Context cancel context.CancelFunc quit chan struct{} } // NewIndexSubscriber creates a new index subscriber. It also starts the // handler for incoming index update subscriptions. func NewIndexSubscriber(sCtx context.Context) *IndexSubscriber { ctx, cancel := context.WithCancel(sCtx) s := &IndexSubscriber{ c: make(chan IndexNtfn, bufferSize), subscriptions: make(map[string]*IndexSubscription), ctx: ctx, cancel: cancel, quit: make(chan struct{}), } return s } // Subscribe subscribes an index for updates. The returned index subscription // has functions to retrieve a channel that produces a stream of index updates // and to stop the stream when the caller no longer wishes to receive updates. func (s *IndexSubscriber) Subscribe(index Indexer, prerequisite string) (*IndexSubscription, error) { sub := newIndexSubscription(s, index, prerequisite) // If the subscription has a prequisite, find it and set the subscription // as a dependency. if prerequisite != noPrereqs { s.mtx.Lock() prereq, ok := s.subscriptions[prerequisite] s.mtx.Unlock() if !ok { return nil, fmt.Errorf("no subscription found with id %s", prerequisite) } prereq.mtx.Lock() defer prereq.mtx.Unlock() if prereq.dependent != nil { return nil, fmt.Errorf("%s already has a dependent set: %s", prereq.id, prereq.dependent.id) } prereq.dependent = sub atomic.AddUint32(&s.subscribers, 1) return sub, nil } // If the subscription does not have a prerequisite, add it to the index // subscriber's subscriptions. s.mtx.Lock() s.subscriptions[sub.id] = sub s.mtx.Unlock() atomic.AddUint32(&s.subscribers, 1) return sub, nil } // Notify relays an index notification to subscribed indexes for processing. func (s *IndexSubscriber) Notify(ntfn *IndexNtfn) { subscribers := atomic.LoadUint32(&s.subscribers) // Only relay notifications when there are subscribed indexes // to be notified. if subscribers > 0 { select { case <-s.quit: case s.c <- *ntfn: } } } // findLowestIndexTipHeight determines the lowest index tip height among // subscribed indexes and their dependencies. func (s *IndexSubscriber) findLowestIndexTipHeight(queryer ChainQueryer) (int64, int64, error) { // Find the lowest tip height to catch up among subscribed indexes. bestHeight, _ := queryer.Best() lowestHeight := bestHeight for _, sub := range s.subscriptions { tipHeight, tipHash, err := sub.idx.Tip() if err != nil { return 0, bestHeight, err } // Ensure the index tip is on the main chain. if !queryer.MainChainHasBlock(tipHash) { return 0, bestHeight, fmt.Errorf("%s: index tip (%s) is not on the "+ "main chain", sub.idx.Name(), tipHash) } if tipHeight < lowestHeight { lowestHeight = tipHeight } // Update the lowest tip height if a dependent has a lower tip height. dependent := sub.dependent for dependent != nil { tipHeight, _, err := sub.dependent.idx.Tip() if err != nil { return 0, bestHeight, err } if tipHeight < lowestHeight { lowestHeight = tipHeight } dependent = dependent.dependent } } return lowestHeight, bestHeight, nil } // CatchUp syncs all subscribed indexes to the the main chain by connecting // blocks from after the lowest index tip to the current main chain tip. // // This should be called after all indexes have subscribed for updates. func (s *IndexSubscriber) CatchUp(ctx context.Context, db database.DB, queryer ChainQueryer) error { lowestHeight, bestHeight, err := s.findLowestIndexTipHeight(queryer) if err != nil { return err } // Nothing to do if all indexes are synced. if bestHeight == lowestHeight { return nil } // Create a progress logger for the indexing process below. progressLogger := progresslog.NewBlockProgressLogger("Indexed", log) // tip and need to be caught up, so log the details and loop through // each block that needs to be indexed. log.Infof("Catching up from height %d to %d", lowestHeight, bestHeight) var cachedParent *dcrutil.Block for height := lowestHeight + 1; height <= bestHeight; height++ { if interruptRequested(ctx) { return indexerError(ErrInterruptRequested, interruptMsg) } hash, err := queryer.BlockHashByHeight(height) if err != nil { return err } // Ensure the next tip hash is on the main chain. if !queryer.MainChainHasBlock(hash) { msg := fmt.Sprintf("the next block being synced to (%s) "+ "at height %d is not on the main chain", hash, height) return indexerError(ErrBlockNotOnMainChain, msg) } var parent *dcrutil.Block if cachedParent == nil && height > 0 { parentHash, err := queryer.BlockHashByHeight(height - 1) if err != nil { return err } parent, err = queryer.BlockByHash(parentHash) if err != nil { return err } } else { parent = cachedParent } child, err := queryer.BlockByHash(hash) if err != nil { return err } // Construct and send the index notification. var prevScripts PrevScripter err = db.View(func(dbTx database.Tx) error { if interruptRequested(ctx) { return indexerError(ErrInterruptRequested, interruptMsg) } prevScripts, err = queryer.PrevScripts(dbTx, child) if err != nil { return err } return nil }) if err != nil { return err } isTreasuryEnabled, err := queryer.IsTreasuryAgendaActive(parent.Hash()) if err != nil { return err } ntfn := &IndexNtfn{ NtfnType: ConnectNtfn, Block: child, Parent: parent, PrevScripts: prevScripts, IsTreasuryEnabled: isTreasuryEnabled, } // Relay the index update to subscribed indexes. for _, sub := range s.subscriptions { err := updateIndex(ctx, sub.idx, ntfn) if err != nil { s.cancel() return err } } cachedParent = child progressLogger.LogBlockHeight(child.MsgBlock(), parent.MsgBlock()) } log.Infof("Caught up to height %d", bestHeight) return nil } // Run relays index notifications to subscribed indexes. // // This should be run as a goroutine. func (s *IndexSubscriber) Run(ctx context.Context) { for { select { case ntfn := <-s.c: // Relay the index update to subscribed indexes. for _, sub := range s.subscriptions { err := updateIndex(ctx, sub.idx, &ntfn) if err != nil { log.Error(err) s.cancel() break } } if ntfn.Done != nil { close(ntfn.Done) } case <-ctx.Done(): log.Infof("Index subscriber shutting down") close(s.quit) // Stop all updates to subscribed indexes and terminate their // processes. for _, sub := range s.subscriptions { err := sub.stop() if err != nil { log.Error("unable to stop index subscription: %v", err) } } s.cancel() return } } }
b'Calculate -8 - (19 - -5) - -14.\n'
b'What is -9 + (10 - 8) - 2?\n'
b'Calculate (13 + -20 + 6 - 5) + -4 + 0.\n'
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL'; -- ---------------------------------------------------------------------------------------------------------- -- TABLES -- ---------------------------------------------------------------------------------------------------------- -- ----------------------------------------------------- -- Table `gene` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `hgnc_id` int(10) unsigned NOT NULL, `symbol` varchar(40) NOT NULL, `name` TEXT NOT NULL, `type` enum('protein-coding gene','pseudogene','non-coding RNA','other') NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `hgnc_id` (`hgnc_id`), UNIQUE KEY `symbol` (`symbol`), KEY `type` (`type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Genes from HGNC'; -- ----------------------------------------------------- -- Table `gene_alias` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_alias` ( `gene_id` int(10) unsigned NOT NULL, `symbol` varchar(40) NOT NULL, `type` enum('synonym','previous') NOT NULL, KEY `fk_gene_id1` (`gene_id` ASC) , CONSTRAINT `fk_gene_id1` FOREIGN KEY (`gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, KEY `symbol` (`symbol`), KEY `type` (`type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Alternative symbols of genes'; -- ----------------------------------------------------- -- Table `gene_transcript` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_transcript` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `gene_id` int(10) unsigned NOT NULL, `name` varchar(40) NOT NULL, `source` enum('ccds', 'ensembl') NOT NULL, `chromosome` enum('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','X','Y','MT') NOT NULL, `start_coding` int(10) unsigned NULL, `end_coding` int(10) unsigned NULL, `strand` enum('+', '-') NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_gene_id3` FOREIGN KEY (`gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE KEY `gene_name_unique` (`gene_id`, `name`), UNIQUE KEY `name` (`name`) , KEY `source` (`source`), KEY `chromosome` (`chromosome`), KEY `start_coding` (`start_coding`), KEY `end_coding` (`end_coding`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Gene transcipts'; -- ----------------------------------------------------- -- Table `gene_exon` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_exon` ( `transcript_id` int(10) unsigned NOT NULL, `start` int(10) unsigned NOT NULL, `end` int(10) unsigned NOT NULL, KEY `fk_transcript_id2` (`transcript_id` ASC) , CONSTRAINT `fk_transcript_id2` FOREIGN KEY (`transcript_id` ) REFERENCES `gene_transcript` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, KEY `start` (`start`), KEY `end` (`end`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Transcript exons'; -- ----------------------------------------------------- -- Table `geneinfo_germline` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `geneinfo_germline` ( `symbol` VARCHAR(40) NOT NULL, `inheritance` ENUM('AR','AD','AR+AD','XLR','XLD','XLR+XLD','MT','MU','n/a') NOT NULL, `gnomad_oe_syn` FLOAT NULL, `gnomad_oe_mis` FLOAT NULL, `gnomad_oe_lof` FLOAT NULL, `comments` text NOT NULL, PRIMARY KEY `symbol` (`symbol`) ) ENGINE=InnoDB CHARSET=utf8; -- ----------------------------------------------------- -- Table `mid` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mid` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `sequence` VARCHAR(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `genome` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `genome` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `build` VARCHAR(45) NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `build_UNIQUE` (`build` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `processing_system` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processing_system` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name_short` VARCHAR(50) NOT NULL, `name_manufacturer` VARCHAR(100) NOT NULL, `adapter1_p5` VARCHAR(45) NULL DEFAULT NULL, `adapter2_p7` VARCHAR(45) NULL DEFAULT NULL, `type` ENUM('WGS','WGS (shallow)','WES','Panel','Panel Haloplex','Panel MIPs','RNA','ChIP-Seq', 'cfDNA (patient-specific)', 'cfDNA') NOT NULL, `shotgun` TINYINT(1) NOT NULL, `umi_type` ENUM('n/a','HaloPlex HS','SureSelect HS','ThruPLEX','Safe-SeqS','MIPs','QIAseq','IDT-UDI-UMI','IDT-xGen-Prism') NOT NULL DEFAULT 'n/a', `target_file` VARCHAR(255) NULL DEFAULT NULL COMMENT 'filename of sub-panel BED file relative to the megSAP enrichment folder.', `genome_id` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_short` (`name_short` ASC), UNIQUE INDEX `name_manufacturer` (`name_manufacturer` ASC), INDEX `fk_processing_system_genome1` (`genome_id` ASC), CONSTRAINT `fk_processing_system_genome1` FOREIGN KEY (`genome_id`) REFERENCES `genome` (`id`) ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `device` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `device` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `type` ENUM('GAIIx','MiSeq','HiSeq2500','NextSeq500','NovaSeq5000','NovaSeq6000','MGI-2000','SequelII','PromethION') NOT NULL, `name` VARCHAR(45) NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sequencing_run` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sequencing_run` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `fcid` VARCHAR(45) NULL DEFAULT NULL, `flowcell_type` ENUM('Illumina MiSeq v2','Illumina MiSeq v2 Micro','Illumina MiSeq v2 Nano','Illumina MiSeq v3','Illumina NextSeq High Output','Illumina NextSeq Mid Output','Illumina NovaSeq SP','Illumina NovaSeq S1','Illumina NovaSeq S2','Illumina NovaSeq S4','PromethION FLO-PRO002','SMRTCell 8M','n/a') NOT NULL DEFAULT 'n/a', `start_date` DATE NULL DEFAULT NULL, `end_date` DATE NULL DEFAULT NULL, `device_id` INT(11) NOT NULL, `recipe` VARCHAR(45) NOT NULL COMMENT 'Read length for reads and index reads separated by \'+\'', `pool_molarity` float DEFAULT NULL, `pool_quantification_method` enum('n/a','Tapestation','Bioanalyzer','qPCR','Tapestation & Qubit','Bioanalyzer & Qubit','Bioanalyzer & Tecan Infinite','Fragment Analyzer & Qubit','Fragment Analyzer & Tecan Infinite','Illumina 450bp & Qubit ssDNA','PCR Size & ssDNA') NOT NULL DEFAULT 'n/a', `comment` TEXT NULL DEFAULT NULL, `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', `status` ENUM('n/a','run_started','run_finished','run_aborted','demultiplexing_started','analysis_started','analysis_finished','analysis_not_possible','analysis_and_backup_not_required') NOT NULL DEFAULT 'n/a', `backup_done` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), UNIQUE INDEX `fcid_UNIQUE` (`fcid` ASC), INDEX `fk_run_device1` (`device_id` ASC), CONSTRAINT `fk_run_device1` FOREIGN KEY (`device_id`) REFERENCES `device` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `runqc_read` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `runqc_read` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `read_num` INT NOT NULL, `cycles` INT NOT NULL, `is_index` BOOLEAN NOT NULL, `q30_perc` FLOAT NOT NULL, `error_rate` FLOAT DEFAULT NULL, `sequencing_run_id` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE (`sequencing_run_id`, `read_num`), INDEX `fk_sequencing_run_id` (`sequencing_run_id` ASC), CONSTRAINT `fk_sequencing_run_id` FOREIGN KEY (`sequencing_run_id`) REFERENCES `sequencing_run` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `runqc_lane` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `runqc_lane` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `lane_num` INT NOT NULL, `cluster_density` FLOAT NOT NULL, `cluster_density_pf` FLOAT NOT NULL, `yield` FLOAT NOT NULL, `error_rate` FLOAT DEFAULT NULL, `q30_perc` FLOAT NOT NULL, `occupied_perc` FLOAT DEFAULT NULL, `runqc_read_id` INT(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE (`runqc_read_id`, `lane_num`), INDEX `fk_runqc_read_id` (`runqc_read_id` ASC), CONSTRAINT `fk_runqc_read_id` FOREIGN KEY (`runqc_read_id`) REFERENCES `runqc_read` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `species` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `species` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sender` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sender` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `phone` VARCHAR(45) NULL DEFAULT NULL, `email` VARCHAR(45) NULL DEFAULT NULL, `affiliation` VARCHAR(100) NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `user` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `user` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `user_id` VARCHAR(45) NOT NULL COMMENT 'Use the lower-case Windows domain name!', `password` VARCHAR(64) NOT NULL, `user_role` ENUM('user','admin','special') NOT NULL, `name` VARCHAR(45) NOT NULL, `email` VARCHAR(100) NOT NULL, `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, `last_login` DATETIME NULL DEFAULT NULL, `active` TINYINT(1) DEFAULT 1 NOT NULL, `salt` VARCHAR(40) NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`user_id` ASC), UNIQUE INDEX `email_UNIQUE` (`email` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(20) NOT NULL, `name_external` VARCHAR(255) NULL DEFAULT NULL COMMENT 'External names.<br>If several, separate by comma!<br>Always enter full names, no short forms!', `received` DATE NULL DEFAULT NULL, `receiver_id` INT(11) NULL DEFAULT NULL, `sample_type` ENUM('DNA','DNA (amplicon)','DNA (native)','RNA','cfDNA') NOT NULL, `species_id` INT(11) NOT NULL, `concentration` FLOAT NULL DEFAULT NULL, `volume` FLOAT NULL DEFAULT NULL, `od_260_280` FLOAT NULL DEFAULT NULL, `gender` ENUM('male','female','n/a') NOT NULL, `comment` TEXT NULL DEFAULT NULL, `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', `od_260_230` FLOAT NULL DEFAULT NULL, `integrity_number` FLOAT NULL DEFAULT NULL, `tumor` TINYINT(1) NOT NULL, `ffpe` TINYINT(1) NOT NULL, `sender_id` INT(11) NOT NULL, `disease_group` ENUM('n/a','Neoplasms','Diseases of the blood or blood-forming organs','Diseases of the immune system','Endocrine, nutritional or metabolic diseases','Mental, behavioural or neurodevelopmental disorders','Sleep-wake disorders','Diseases of the nervous system','Diseases of the visual system','Diseases of the ear or mastoid process','Diseases of the circulatory system','Diseases of the respiratory system','Diseases of the digestive system','Diseases of the skin','Diseases of the musculoskeletal system or connective tissue','Diseases of the genitourinary system','Developmental anomalies','Other diseases') NOT NULL DEFAULT 'n/a', `disease_status` ENUM('n/a','Affected','Unaffected','Unclear') NOT NULL DEFAULT 'n/a', `tissue` ENUM('n/a','Blood','Buccal mucosa','Skin') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), INDEX `fk_samples_species1` (`species_id` ASC), INDEX `sender_id` (`sender_id` ASC), INDEX `receiver_id` (`receiver_id` ASC), INDEX `name_external` (`name_external` ASC), INDEX `tumor` (`tumor` ASC), INDEX `quality` (`quality` ASC), INDEX `disease_group` (`disease_group`), INDEX `disease_status` (`disease_status`), CONSTRAINT `fk_samples_species1` FOREIGN KEY (`species_id`) REFERENCES `species` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `sample_ibfk_1` FOREIGN KEY (`sender_id`) REFERENCES `sender` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `sample_ibfk_2` FOREIGN KEY (`receiver_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample_disease_info` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample_disease_info` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_id` INT(11) NOT NULL, `disease_info` TEXT NOT NULL, `type` ENUM('HPO term id', 'ICD10 code', 'OMIM disease/phenotype identifier', 'Orpha number', 'CGI cancer type', 'tumor fraction', 'age of onset', 'clinical phenotype (free text)', 'RNA reference tissue') NOT NULL, `user_id` int(11) DEFAULT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), CONSTRAINT `fk_sample_id` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample_relations` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample_relations` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample1_id` INT(11) NOT NULL, `relation` ENUM('parent-child', 'tumor-normal', 'siblings', 'same sample', 'tumor-cfDNA', 'same patient', 'cousins', 'twins', 'twins (monozygotic)') NOT NULL, `sample2_id` INT(11) NOT NULL, `user_id` int(11) DEFAULT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE INDEX `relation_unique` (`sample1_id` ASC, `relation` ASC, `sample2_id` ASC), CONSTRAINT `fk_sample1_id` FOREIGN KEY (`sample1_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_sample2_id` FOREIGN KEY (`sample2_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_user2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `project` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `project` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `aliases` TEXT DEFAULT NULL, `type` ENUM('diagnostic','research','test','external') NOT NULL, `internal_coordinator_id` INT(11) NOT NULL COMMENT 'Person who is responsible for this project.<br>The person will be notified when new samples are available.', `comment` TEXT NULL DEFAULT NULL, `analysis` ENUM('fastq','mapping','variants') NOT NULL DEFAULT 'variants' COMMENT 'Bioinformatics analysis to be done for non-tumor germline samples in this project.<br>"fastq" skips the complete analysis.<br>"mapping" creates the BAM file but calls no variants.<br>"variants" performs the full analysis.', `preserve_fastqs` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Prevents FASTQ files from being deleted after mapping in this project.<br>Has no effect if megSAP is not configured to delete FASTQs automatically.<br>For diagnostics, do not check. For other project types ask the bioinformatician in charge.', `email_notification` varchar(200) DEFAULT NULL COMMENT 'List of email addresses (separated by semicolon) that are notified in addition to the project coordinator when new samples are available.', PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), INDEX `internal_coordinator_id` (`internal_coordinator_id` ASC), CONSTRAINT `project_ibfk_1` FOREIGN KEY (`internal_coordinator_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `processed_sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processed_sample` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_id` INT(11) NOT NULL, `process_id` INT(2) NOT NULL, `sequencing_run_id` INT(11) NULL DEFAULT NULL, `lane` varchar(15) NOT NULL COMMENT 'Comma-separated lane list (1-8)', `mid1_i7` INT(11) NULL DEFAULT NULL, `mid2_i5` INT(11) NULL DEFAULT NULL, `operator_id` INT(11) NULL DEFAULT NULL, `processing_system_id` INT(11) NOT NULL, `comment` TEXT NULL DEFAULT NULL, `project_id` INT(11) NOT NULL, `processing_input` FLOAT NULL DEFAULT NULL, `molarity` FLOAT NULL DEFAULT NULL, `normal_id` INT(11) NULL DEFAULT NULL COMMENT 'For tumor samples, a normal sample can be given here which is used as reference sample during the data analysis.', `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), UNIQUE INDEX `sample_psid_unique` (`sample_id` ASC, `process_id` ASC), INDEX `fk_processed_sample_samples1` (`sample_id` ASC), INDEX `fk_processed_sample_mid1` (`mid1_i7` ASC), INDEX `fk_processed_sample_processing_system1` (`processing_system_id` ASC), INDEX `fk_processed_sample_run1` (`sequencing_run_id` ASC), INDEX `fk_processed_sample_mid2` (`mid2_i5` ASC), INDEX `project_id` (`project_id` ASC), INDEX `operator_id` (`operator_id` ASC), INDEX `normal_id_INDEX` (`normal_id` ASC), INDEX `quality` (`quality` ASC), CONSTRAINT `fk_processed_sample_mid1` FOREIGN KEY (`mid1_i7`) REFERENCES `mid` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_mid2` FOREIGN KEY (`mid2_i5`) REFERENCES `mid` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_processing_system1` FOREIGN KEY (`processing_system_id`) REFERENCES `processing_system` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_run1` FOREIGN KEY (`sequencing_run_id`) REFERENCES `sequencing_run` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_sample2` FOREIGN KEY (`normal_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_samples1` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `processed_sample_ibfk_1` FOREIGN KEY (`project_id`) REFERENCES `project` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `processed_sample_ibfk_2` FOREIGN KEY (`operator_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) NOT NULL, `end` INT(11) NOT NULL, `ref` TEXT NOT NULL, `obs` TEXT NOT NULL, `1000g` FLOAT NULL DEFAULT NULL, `gnomad` FLOAT NULL DEFAULT NULL, `coding` TEXT NULL DEFAULT NULL, `comment` TEXT NULL DEFAULT NULL, `cadd` FLOAT NULL DEFAULT NULL, `spliceai` FLOAT NULL DEFAULT NULL, `germline_het` INT(11) NOT NULL DEFAULT '0', `germline_hom` INT(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE INDEX `variant_UNIQUE` (`chr` ASC, `start` ASC, `end` ASC, `ref`(255) ASC, `obs`(255) ASC), INDEX `1000g` (`1000g` ASC), INDEX `gnomad` (`gnomad` ASC), INDEX `comment` (`comment`(50) ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant_publication` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_publication` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_id` INT(11) NOT NULL, `variant_id` INT(11) NOT NULL, `db` ENUM('LOVD','ClinVar') NOT NULL, `class` ENUM('1','2','3','4','5', 'M') NOT NULL, `details` TEXT NOT NULL, `user_id` INT(11) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `result` TEXT DEFAULT NULL, `replaced` BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (`id`), CONSTRAINT `fk_variant_publication_has_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_publication_has_sample` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_publication_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant_classification` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_classification` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `variant_id` INT(11) NOT NULL, `class` ENUM('n/a','1','2','3','4','5','M') NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `fk_variant_classification_has_variant` (`variant_id`), CONSTRAINT `fk_variant_classification_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `class` (`class` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_variant_classification` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_variant_classification` ( `id` int(11) NOT NULL AUTO_INCREMENT, `variant_id` int(11) NOT NULL, `class` ENUM('n/a','activating','likely_activating','inactivating','likely_inactivating','unclear','test_dependent') NOT NULL, `comment` TEXT, PRIMARY KEY (`id`), UNIQUE KEY `somatic_variant_classification_has_variant` (`variant_id`), CONSTRAINT `somatic_variant_classification_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_vicc_interpretation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_vicc_interpretation` ( `id` int(11) NOT NULL AUTO_INCREMENT, `variant_id` int(11) NOT NULL, `null_mutation_in_tsg` BOOLEAN NULL DEFAULT NULL, `known_oncogenic_aa` BOOLEAN NULL DEFAULT NULL, `oncogenic_funtional_studies` BOOLEAN NULL DEFAULT NULL, `strong_cancerhotspot` BOOLEAN NULL DEFAULT NULL, `located_in_canerhotspot` BOOLEAN NULL DEFAULT NULL, `absent_from_controls` BOOLEAN NULL DEFAULT NULL, `protein_length_change` BOOLEAN NULL DEFAULT NULL, `other_aa_known_oncogenic` BOOLEAN NULL DEFAULT NULL, `weak_cancerhotspot` BOOLEAN NULL DEFAULT NULL, `computational_evidence` BOOLEAN NULL DEFAULT NULL, `mutation_in_gene_with_etiology` BOOLEAN NULL DEFAULT NULL, `very_weak_cancerhotspot` BOOLEAN NULL DEFAULT NULL, `very_high_maf` BOOLEAN NULL DEFAULT NULL, `benign_functional_studies` BOOLEAN NULL DEFAULT NULL, `high_maf` BOOLEAN NULL DEFAULT NULL, `benign_computational_evidence` BOOLEAN NULL DEFAULT NULL, `synonymous_mutation` BOOLEAN NULL DEFAULT NULL, `comment` TEXT NULL DEFAULT NULL, `created_by` int(11) DEFAULT NULL, `created_date` DATETIME NOT NULL, `last_edit_by` int(11) DEFAULT NULL, `last_edit_date` TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `somatic_vicc_interpretation_has_variant` (`variant_id`), CONSTRAINT `somatic_vicc_interpretation_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_vicc_interpretation_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_vicc_interpretation_last_edit_by_user` FOREIGN KEY (`last_edit_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_gene_role` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_gene_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `symbol` VARCHAR(40) NOT NULL, `gene_role` ENUM('activating','loss_of_function', 'ambiguous') NOT NULL, `high_evidence` BOOLEAN DEFAULT FALSE, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY (`symbol`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `detected_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `detected_variant` ( `processed_sample_id` INT(11) NOT NULL, `variant_id` INT(11) NOT NULL, `genotype` ENUM('hom','het') NOT NULL, PRIMARY KEY (`processed_sample_id`, `variant_id`), INDEX `fk_detected_variant_variant1` (`variant_id` ASC), CONSTRAINT `fk_processed_sample_has_variant_processed_sample1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_has_variant_variant1` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `qc_terms` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `qc_terms` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `qcml_id` VARCHAR(10) NULL DEFAULT NULL, `name` VARCHAR(45) NOT NULL, `description` TEXT NOT NULL, `type` ENUM('float', 'int', 'string') NOT NULL, `obsolete` TINYINT(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC), UNIQUE INDEX `qcml_id_UNIQUE` (`qcml_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `processed_sample_qc` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processed_sample_qc` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `qc_terms_id` INT(11) NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `c_processing_id_qc_terms_id` (`processed_sample_id` ASC, `qc_terms_id` ASC), INDEX `fk_qcvalues_processing1` (`processed_sample_id` ASC), INDEX `fk_processed_sample_annotaiton_qcml1` (`qc_terms_id` ASC), CONSTRAINT `fk_processed_sample_annotaiton_qcml1` FOREIGN KEY (`qc_terms_id`) REFERENCES `qc_terms` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_qcvalues_processing1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sample_group` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sample_group` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `nm_sample_sample_group` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `nm_sample_sample_group` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `sample_group_id` INT(11) NOT NULL, `sample_id` INT(11) NOT NULL, PRIMARY KEY (`id`), INDEX `fk_sample_group_has_sample_sample1` (`sample_id` ASC), INDEX `fk_sample_group_has_sample_sample_group1` (`sample_group_id` ASC), CONSTRAINT `fk_sample_group_has_sample_sample1` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_sample_group_has_sample_sample_group1` FOREIGN KEY (`sample_group_id`) REFERENCES `sample_group` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `detected_somatic_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `detected_somatic_variant` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id_tumor` INT(11) NOT NULL, `processed_sample_id_normal` INT(11) NULL DEFAULT NULL, `variant_id` INT(11) NOT NULL, `variant_frequency` FLOAT NOT NULL, `depth` INT(11) NOT NULL, `quality_snp` FLOAT NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `detected_somatic_variant_UNIQUE` (`processed_sample_id_tumor` ASC, `processed_sample_id_normal` ASC, `variant_id` ASC), INDEX `variant_id_INDEX` (`variant_id` ASC), INDEX `processed_sample_id_tumor_INDEX` (`processed_sample_id_tumor` ASC), INDEX `processed_sample_id_normal_INDEX` (`processed_sample_id_normal` ASC), INDEX `fk_dsv_has_ps1` (`processed_sample_id_tumor` ASC), INDEX `fk_dsv_has_ps2` (`processed_sample_id_normal` ASC), CONSTRAINT `fk_dsv_has_ps1` FOREIGN KEY (`processed_sample_id_tumor`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_dsv_has_ps2` FOREIGN KEY (`processed_sample_id_normal`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_dsv_has_v` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `diag_status` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `diag_status` ( `processed_sample_id` INT(11) NOT NULL, `status` ENUM('pending','in progress','done','done - follow up pending','cancelled','not usable because of data quality') NOT NULL, `user_id` INT(11) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `outcome` ENUM('n/a','no significant findings','uncertain','significant findings','significant findings - second method', 'significant findings - non-genetic', 'candidate gene') NOT NULL DEFAULT 'n/a', `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`processed_sample_id`), INDEX `user_id` (`user_id` ASC), CONSTRAINT `diag_status_ibfk_1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `diag_status_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `kasp_status` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `kasp_status` ( `processed_sample_id` INT(11) NOT NULL, `random_error_prob` FLOAT UNSIGNED NOT NULL, `snps_evaluated` INT(10) UNSIGNED NOT NULL, `snps_match` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`processed_sample_id`), CONSTRAINT `processed_sample0` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `hpo_term` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `hpo_term` ( `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `hpo_id` VARCHAR(10) NOT NULL, `name` TEXT NOT NULL, `definition` TEXT NOT NULL, `synonyms` TEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `hpo_id` (`hpo_id` ASC), INDEX `name` (`name`(100) ASC), INDEX `synonyms` (`synonyms`(100) ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `hpo_genes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `hpo_genes` ( `hpo_term_id` INT(10) UNSIGNED NOT NULL, `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `details` TEXT COMMENT 'Semicolon seperated pairs of database sources with evidences of where the connection was found (Source, Original Evidence, Evidence translated; Source2, ....)', `evidence` ENUM('n/a','low','medium','high') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`hpo_term_id`, `gene`), CONSTRAINT `hpo_genes_ibfk_1` FOREIGN KEY (`hpo_term_id`) REFERENCES `hpo_term` (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `hpo_parent` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `hpo_parent` ( `parent` INT(10) UNSIGNED NOT NULL, `child` INT(10) UNSIGNED NOT NULL, PRIMARY KEY (`parent`, `child`), INDEX `child` (`child` ASC), CONSTRAINT `hpo_parent_ibfk_2` FOREIGN KEY (`child`) REFERENCES `hpo_term` (`id`), CONSTRAINT `hpo_parent_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `hpo_term` (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `analysis_job` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `analysis_job` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `type` enum('single sample','multi sample','trio','somatic') NOT NULL, `high_priority` TINYINT(1) NOT NULL, `args` text NOT NULL, `sge_id` varchar(10) DEFAULT NULL, `sge_queue` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `analysis_job_sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `analysis_job_sample` ( `id` int(11) NOT NULL AUTO_INCREMENT, `analysis_job_id` int(11) NOT NULL, `processed_sample_id` int(11) NOT NULL, `info` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_analysis_job_id` FOREIGN KEY (`analysis_job_id` ) REFERENCES `analysis_job` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_processed_sample_id` FOREIGN KEY (`processed_sample_id` ) REFERENCES `processed_sample` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `analysis_job_history` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `analysis_job_history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `analysis_job_id` int(11) NOT NULL, `time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `user_id` int(11) DEFAULT NULL, `status` enum('queued','started','finished','cancel','canceled','error') NOT NULL, `output` text DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_analysis_job_id2` FOREIGN KEY (`analysis_job_id` ) REFERENCES `analysis_job` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_user_id2` FOREIGN KEY (`user_id` ) REFERENCES `user` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `omim_gene` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `omim_gene` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `mim` VARCHAR(10) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `mim_unique` (`mim`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `omim_phenotype` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `omim_phenotype` ( `omim_gene_id` INT(11) UNSIGNED NOT NULL, `phenotype` VARCHAR(255) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`omim_gene_id`, `phenotype`), CONSTRAINT `omim_gene_id_FK` FOREIGN KEY (`omim_gene_id` ) REFERENCES `omim_gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `omim_preferred_phenotype` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `omim_preferred_phenotype` ( `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `disease_group` ENUM('Neoplasms','Diseases of the blood or blood-forming organs','Diseases of the immune system','Endocrine, nutritional or metabolic diseases','Mental, behavioural or neurodevelopmental disorders','Sleep-wake disorders','Diseases of the nervous system','Diseases of the visual system','Diseases of the ear or mastoid process','Diseases of the circulatory system','Diseases of the respiratory system','Diseases of the digestive system','Diseases of the skin','Diseases of the musculoskeletal system or connective tissue','Diseases of the genitourinary system','Developmental anomalies','Other diseases') NOT NULL, `phenotype_accession` VARCHAR(6) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`gene`,`disease_group`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `merged_processed_samples` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `merged_processed_samples` ( `processed_sample_id` INT(11) NOT NULL, `merged_into` INT(11) NOT NULL, PRIMARY KEY (`processed_sample_id`), CONSTRAINT `merged_processed_samples_ps_id` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `merged_processed_samples_merged_into` FOREIGN KEY (`merged_into`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `somatic_report_configuration` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration` ( `id` int(11) NOT NULL AUTO_INCREMENT, `ps_tumor_id` int(11) NOT NULL, `ps_normal_id` int(11) NOT NULL, `created_by` int(11) NOT NULL, `created_date` DATETIME NOT NULL, `last_edit_by` int(11) DEFAULT NULL, `last_edit_date` timestamp NULL DEFAULT NULL, `mtb_xml_upload_date` timestamp NULL DEFAULT NULL, `target_file` VARCHAR(255) NULL DEFAULT NULL COMMENT 'filename of sub-panel BED file without path', `tum_content_max_af` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include tumor content calculated by median value maximum allele frequency', `tum_content_max_clonality` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include tumor content calculated by maximum CNV clonality', `tum_content_hist` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include histological tumor content estimate ', `msi_status` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'include microsatellite instability status', `cnv_burden` BOOLEAN NOT NULL DEFAULT FALSE, `hrd_score` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'homologous recombination deficiency score, determined manually by user', `hrd_statement` ENUM('no proof', 'proof', 'undeterminable') NULL DEFAULT NULL COMMENT 'comment to be shown in somatic report about HRD score', `cnv_loh_count` INT(11) NULL DEFAULT NULL COMMENT 'number of somatic LOH events, determined from CNV file', `cnv_tai_count` INT(11) NULL DEFAULT NULL COMMENT 'number of somatic telomer allelic imbalance events, determined from CNV file', `cnv_lst_count` INT(11) NULL DEFAULT NULL COMMENT 'number of somatic long state transitions events, determined from CNV file', `tmb_ref_text` VARCHAR(200) NULL DEFAULT NULL COMMENT 'reference data as free text for tumor mutation burden', `quality` ENUM('no abnormalities','tumor cell content too low', 'quality of tumor DNA too low', 'DNA quantity too low', 'heterogeneous sample') NULL DEFAULT NULL COMMENT 'user comment on the quality of the DNA', `fusions_detected` BOOLEAN NOT NULL DEFAULT FALSE COMMENT 'fusions or other SVs were detected. Cannot be determined automatically, because manta files contain too many false positives', `cin_chr` TEXT NULL DEFAULT NULL COMMENT 'comma separated list of instable chromosomes', `limitations` TEXT NULL DEFAULT NULL COMMENT 'manually created text if the analysis has special limitations', `filter` VARCHAR(255) NULL DEFAULT NULL COMMENT 'name of the variant filter', PRIMARY KEY (`id`), UNIQUE INDEX `combo_som_rep_conf_ids` (`ps_tumor_id` ASC, `ps_normal_id` ASC), CONSTRAINT `somatic_report_config_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_config_last_edit_by_user` FOREIGN KEY (`last_edit_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_config_ps_normal_id` FOREIGN KEY (`ps_normal_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_config_ps_tumor_id` FOREIGN KEY (`ps_tumor_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARSET = utf8; -- ----------------------------------------------------- -- Table `somatic_report_configuration_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration_variant` ( `id` int(11) NOT NULL AUTO_INCREMENT, `somatic_report_configuration_id` int(11) NOT NULL, `variant_id` int(11) NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_low_tumor_content` BOOLEAN NOT NULL, `exclude_low_copy_number` BOOLEAN NOT NULL, `exclude_high_baf_deviation` BOOLEAN NOT NULL, `exclude_other_reason` BOOLEAN NOT NULL, `include_variant_alteration` text DEFAULT NULL, `include_variant_description` text DEFAULT NULL, `comment` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `som_rep_conf_var_has_som_rep_conf_id` FOREIGN KEY (`somatic_report_configuration_id`) REFERENCES `somatic_report_configuration` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `somatic_report_configuration_variant_has_variant_id` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `som_conf_var_combo_uniq_index` (`somatic_report_configuration_id` ASC, `variant_id` ASC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `somatic_report_configuration_germl_snv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration_germl_var` ( `id` int(11) NOT NULL AUTO_INCREMENT, `somatic_report_configuration_id` int(11) NOT NULL, `variant_id` int(11) NOT NULL, `tum_freq` FLOAT UNSIGNED NULL DEFAULT NULL COMMENT 'frequency of this variant in the tumor sample.', `tum_depth` int(11) UNSIGNED NULL DEFAULT NULL COMMENT 'depth of this variant in the tumor sample.', PRIMARY KEY (`id`), CONSTRAINT `som_rep_conf_germl_var_has_rep_conf_id` FOREIGN KEY (`somatic_report_configuration_id`) REFERENCES `somatic_report_configuration` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `som_rep_germl_var_has_var_id` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `som_conf_germl_var_combo_uni_idx` (`somatic_report_configuration_id` ASC, `variant_id` ASC) ) COMMENT='variants detected in control tissue that are marked as tumor related by the user' ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `somatic_cnv_callset` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_cnv_callset` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `ps_tumor_id` INT(11) NOT NULL, `ps_normal_id` INT(11) NOT NULL, `caller` ENUM('ClinCNV') NOT NULL, `caller_version` varchar(25) NOT NULL, `call_date` DATETIME NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), INDEX `caller` (`caller` ASC), INDEX `call_date` (`call_date` ASC), INDEX `quality` (`quality` ASC), UNIQUE INDEX `combo_ids` (`ps_tumor_id` ASC, `ps_normal_id` ASC), CONSTRAINT `som_cnv_callset_ps_normal_id` FOREIGN KEY (`ps_normal_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `som_cnv_callset_ps_tumor_id` FOREIGN KEY (`ps_tumor_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='somatic CNV call set'; -- ----------------------------------------------------- -- Table `somatic_cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_cnv` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `somatic_cnv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `cn` FLOAT UNSIGNED NOT NULL COMMENT 'copy-number change in whole sample, including normal parts', `tumor_cn` INT(11) UNSIGNED NOT NULL COMMENT 'copy-number change normalized to tumor tissue only', `tumor_clonality` FLOAT NOT NULL COMMENT 'tumor clonality, i.e. fraction of tumor cells', `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `som_cnv_references_cnv_callset` FOREIGN KEY (`somatic_cnv_callset_id`) REFERENCES `somatic_cnv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `unique_callset_cnv_pair` UNIQUE(`somatic_cnv_callset_id`,`chr`,`start`,`end`), INDEX `chr` (`chr` ASC), INDEX `start` (`start` ASC), INDEX `end` (`end` ASC), INDEX `tumor_cn` (`tumor_cn` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='somatic CNV'; -- ----------------------------------------------------- -- Table `somatic_report_configuration_cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `somatic_report_configuration_cnv` ( `id` int(11) NOT NULL AUTO_INCREMENT, `somatic_report_configuration_id` int(11) NOT NULL, `somatic_cnv_id` int(11) UNSIGNED NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_low_tumor_content` BOOLEAN NOT NULL, `exclude_low_copy_number` BOOLEAN NOT NULL, `exclude_high_baf_deviation` BOOLEAN NOT NULL, `exclude_other_reason` BOOLEAN NOT NULL, `comment` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `som_rep_conf_cnv_has_som_rep_conf_id` FOREIGN KEY (`somatic_report_configuration_id`) REFERENCES `somatic_report_configuration` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `som_report_conf_cnv_has_som_cnv_id` FOREIGN KEY (`somatic_cnv_id`) REFERENCES `somatic_cnv` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `som_conf_cnv_combo_uniq_index` (`somatic_report_configuration_id` ASC, `somatic_cnv_id` ASC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------------------------------- -- Table `report_configuration` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `created_by` int(11) NOT NULL, `created_date` DATETIME NOT NULL, `last_edit_by` int(11) DEFAULT NULL, `last_edit_date` TIMESTAMP NULL DEFAULT NULL, `finalized_by` int(11) DEFAULT NULL, `finalized_date` TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `processed_sample_id_unique` (`processed_sample_id`), CONSTRAINT `fk_processed_sample_id2` FOREIGN KEY (`processed_sample_id` ) REFERENCES `processed_sample` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `report_configuration_created_by` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `report_configuration_last_edit_by` FOREIGN KEY (`last_edit_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `report_configuration_finalized_by` FOREIGN KEY (`finalized_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `report_configuration_variant` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration_variant` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `report_configuration_id` INT(11) NOT NULL, `variant_id` INT(11) NOT NULL, `type` ENUM('diagnostic variant', 'candidate variant', 'incidental finding') NOT NULL, `causal` BOOLEAN NOT NULL, `inheritance` ENUM('n/a', 'AR','AD','XLR','XLD','MT') NOT NULL, `de_novo` BOOLEAN NOT NULL, `mosaic` BOOLEAN NOT NULL, `compound_heterozygous` BOOLEAN NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_frequency` BOOLEAN NOT NULL, `exclude_phenotype` BOOLEAN NOT NULL, `exclude_mechanism` BOOLEAN NOT NULL, `exclude_other` BOOLEAN NOT NULL, `comments` text NOT NULL, `comments2` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_report_configuration` FOREIGN KEY (`report_configuration_id` ) REFERENCES `report_configuration` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_variant_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `config_variant_combo_uniq` (`report_configuration_id` ASC, `variant_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `disease_term` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `disease_term` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `source` ENUM('OrphaNet') NOT NULL, `identifier` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `name` TEXT CHARACTER SET 'utf8' NOT NULL, `synonyms` TEXT CHARACTER SET 'utf8' DEFAULT NULL, PRIMARY KEY (`id`), INDEX `disease_source` (`source` ASC), UNIQUE KEY `disease_id` (`identifier`), INDEX `disease_name` (`name`(50) ASC), INDEX `disease_synonyms` (`synonyms`(50) ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `disease_gene` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `disease_gene` ( `disease_term_id` INT(11) UNSIGNED NOT NULL, `gene` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`disease_term_id`, `gene`), CONSTRAINT `disease_genes_ibfk_1` FOREIGN KEY (`disease_term_id`) REFERENCES `disease_term` (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `cnv_callset` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cnv_callset` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `caller` ENUM('CnvHunter', 'ClinCNV') NOT NULL, `caller_version` varchar(25) NOT NULL, `call_date` DATETIME DEFAULT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', `quality` ENUM('n/a','good','medium','bad') NOT NULL DEFAULT 'n/a', PRIMARY KEY (`id`), INDEX `caller` (`quality` ASC), INDEX `call_date` (`call_date` ASC), INDEX `quality` (`quality` ASC), UNIQUE KEY `cnv_callset_references_processed_sample` (`processed_sample_id`), CONSTRAINT `cnv_callset_references_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='germline CNV call set'; -- ----------------------------------------------------- -- Table `cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cnv` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `cnv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `cn` INT(11) UNSIGNED NOT NULL COMMENT 'copy-number', `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `cnv_references_cnv_callset` FOREIGN KEY (`cnv_callset_id`) REFERENCES `cnv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `chr` (`chr` ASC), INDEX `start` (`start` ASC), INDEX `end` (`end` ASC), INDEX `cn` (`cn` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='germline CNV'; -- ----------------------------------------------------- -- Table `report_configuration_cnv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration_cnv` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `report_configuration_id` INT(11) NOT NULL, `cnv_id` INT(11) UNSIGNED NOT NULL, `type` ENUM('diagnostic variant', 'candidate variant', 'incidental finding') NOT NULL, `causal` BOOLEAN NOT NULL, `class` ENUM('n/a','1','2','3','4','5','M') NOT NULL, `inheritance` ENUM('n/a', 'AR','AD','XLR','XLD','MT') NOT NULL, `de_novo` BOOLEAN NOT NULL, `mosaic` BOOLEAN NOT NULL, `compound_heterozygous` BOOLEAN NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_frequency` BOOLEAN NOT NULL, `exclude_phenotype` BOOLEAN NOT NULL, `exclude_mechanism` BOOLEAN NOT NULL, `exclude_other` BOOLEAN NOT NULL, `comments` text NOT NULL, `comments2` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_report_configuration2` FOREIGN KEY (`report_configuration_id` ) REFERENCES `report_configuration` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_cnv_has_cnv` FOREIGN KEY (`cnv_id`) REFERENCES `cnv` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `config_variant_combo_uniq` (`report_configuration_id` ASC, `cnv_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `sv_callset` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_callset` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `caller` ENUM('Manta') NOT NULL, `caller_version` varchar(25) NOT NULL, `call_date` DATETIME DEFAULT NULL, PRIMARY KEY (`id`), INDEX `call_date` (`call_date` ASC), UNIQUE KEY `sv_callset_references_processed_sample` (`processed_sample_id`), CONSTRAINT `sv_callset_references_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV call set'; -- ----------------------------------------------------- -- Table `sv_deletion` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_deletion` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start_min` INT(11) UNSIGNED NOT NULL, `start_max` INT(11) UNSIGNED NOT NULL, `end_min` INT(11) UNSIGNED NOT NULL, `end_max` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_del_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `exact_match` (`chr`, `start_min`, `start_max`, `end_min`, `end_max`), INDEX `overlap_match` (`chr`, `start_min`, `end_max`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV deletion'; -- ----------------------------------------------------- -- Table `sv_duplication` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_duplication` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start_min` INT(11) UNSIGNED NOT NULL, `start_max` INT(11) UNSIGNED NOT NULL, `end_min` INT(11) UNSIGNED NOT NULL, `end_max` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_dup_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `exact_match` (`chr`, `start_min`, `start_max`, `end_min`, `end_max`), INDEX `overlap_match` (`chr`, `start_min`, `end_max`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV duplication'; -- ----------------------------------------------------- -- Table `sv_insertion` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_insertion` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `pos`INT(11) UNSIGNED NOT NULL, `ci_lower` INT(5) UNSIGNED NOT NULL DEFAULT 0, `ci_upper` INT(5) UNSIGNED NOT NULL, `inserted_sequence` TEXT DEFAULT NULL, `known_left` TEXT DEFAULT NULL, `known_right` TEXT DEFAULT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_ins_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `match` (`chr`, `pos`, `ci_upper`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV insertion'; -- ----------------------------------------------------- -- Table `sv_inversion` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_inversion` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start_min` INT(11) UNSIGNED NOT NULL, `start_max` INT(11) UNSIGNED NOT NULL, `end_min` INT(11) UNSIGNED NOT NULL, `end_max` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_inv_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `exact_match` (`chr`, `start_min`, `start_max`, `end_min`, `end_max`), INDEX `overlap_match` (`chr`, `start_min`, `end_max`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV inversion'; -- ----------------------------------------------------- -- Table `sv_translocation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `sv_translocation` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `sv_callset_id` INT(11) UNSIGNED NOT NULL, `chr1` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start1` INT(11) UNSIGNED NOT NULL, `end1` INT(11) UNSIGNED NOT NULL, `chr2` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start2` INT(11) UNSIGNED NOT NULL, `end2` INT(11) UNSIGNED NOT NULL, `quality_metrics` TEXT DEFAULT NULL COMMENT 'quality metrics as JSON key-value array', PRIMARY KEY (`id`), CONSTRAINT `sv_bnd_references_sv_callset` FOREIGN KEY (`sv_callset_id`) REFERENCES `sv_callset` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `match` (`chr1`, `start1`, `end1`, `chr2`, `start2`, `end2`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COMMENT='SV translocation'; -- ----------------------------------------------------- -- Table `report_configuration_sv` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `report_configuration_sv` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `report_configuration_id` INT(11) NOT NULL, `sv_deletion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_duplication_id` INT(11) UNSIGNED DEFAULT NULL, `sv_insertion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_inversion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_translocation_id` INT(11) UNSIGNED DEFAULT NULL, `type` ENUM('diagnostic variant', 'candidate variant', 'incidental finding') NOT NULL, `causal` BOOLEAN NOT NULL, `class` ENUM('n/a','1','2','3','4','5','M') NOT NULL, `inheritance` ENUM('n/a', 'AR','AD','XLR','XLD','MT') NOT NULL, `de_novo` BOOLEAN NOT NULL, `mosaic` BOOLEAN NOT NULL, `compound_heterozygous` BOOLEAN NOT NULL, `exclude_artefact` BOOLEAN NOT NULL, `exclude_frequency` BOOLEAN NOT NULL, `exclude_phenotype` BOOLEAN NOT NULL, `exclude_mechanism` BOOLEAN NOT NULL, `exclude_other` BOOLEAN NOT NULL, `comments` text NOT NULL, `comments2` text NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_report_configuration3` FOREIGN KEY (`report_configuration_id` ) REFERENCES `report_configuration` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_deletion` FOREIGN KEY (`sv_deletion_id`) REFERENCES `sv_deletion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_duplication` FOREIGN KEY (`sv_duplication_id`) REFERENCES `sv_duplication` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_insertion` FOREIGN KEY (`sv_insertion_id`) REFERENCES `sv_insertion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_inversion` FOREIGN KEY (`sv_inversion_id`) REFERENCES `sv_inversion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_report_configuration_sv_has_sv_translocation` FOREIGN KEY (`sv_translocation_id`) REFERENCES `sv_translocation` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `config_variant_combo_uniq` (`report_configuration_id` ASC, `sv_deletion_id` ASC, `sv_duplication_id` ASC, `sv_insertion_id` ASC, `sv_inversion_id` ASC, `sv_translocation_id` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `evaluation_sheet_data` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `evaluation_sheet_data` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `processed_sample_id` INT(11) NOT NULL, `dna_rna_id` TEXT CHARACTER SET 'utf8' DEFAULT NULL, `reviewer1` INT NOT NULL, `review_date1` DATE NOT NULL, `reviewer2` INT NOT NULL, `review_date2` DATE NOT NULL, `analysis_scope` TEXT CHARACTER SET 'utf8' DEFAULT NULL, `acmg_requested` BOOLEAN DEFAULT FALSE NOT NULL, `acmg_analyzed` BOOLEAN DEFAULT FALSE NOT NULL, `acmg_noticeable` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_freq_based_dominant` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_freq_based_recessive` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_mito` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_x_chr` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_cnv` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_svs` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_res` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_mosaic` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_phenotype` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_multisample` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_trio_stringent` BOOLEAN DEFAULT FALSE NOT NULL, `filtered_by_trio_relaxed` BOOLEAN DEFAULT FALSE NOT NULL, PRIMARY KEY (`id`), INDEX `processed_sample_id` (`processed_sample_id` ASC), UNIQUE KEY `evaluation_sheet_data_references_processed_sample` (`processed_sample_id`), CONSTRAINT `evaluation_sheet_data_references_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `evaluation_sheet_data_references_user1` FOREIGN KEY (`reviewer1`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `evaluation_sheet_data_references_user2` FOREIGN KEY (`reviewer2`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `preferred_transcripts` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `preferred_transcripts` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `added_by` INT(11) NOT NULL, `added_date` timestamp NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `combo_som_rep_conf_ids` (`name` ASC), CONSTRAINT `preferred_transcriptsg_created_by_user` FOREIGN KEY (`added_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; -- ----------------------------------------------------- -- Table `variant_validation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_validation` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `user_id` INT(11) NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `sample_id` INT(11) NOT NULL, `variant_type` ENUM('SNV_INDEL', 'CNV', 'SV') NOT NULL, `variant_id` INT(11) DEFAULT NULL, `cnv_id` INT(11) UNSIGNED DEFAULT NULL, `sv_deletion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_duplication_id` INT(11) UNSIGNED DEFAULT NULL, `sv_insertion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_inversion_id` INT(11) UNSIGNED DEFAULT NULL, `sv_translocation_id` INT(11) UNSIGNED DEFAULT NULL, `genotype` ENUM('hom','het') DEFAULT NULL, `validation_method` ENUM('Sanger sequencing', 'breakpoint PCR', 'qPCR', 'MLPA', 'Array', 'shallow WGS', 'fragment length analysis', 'n/a') NOT NULL DEFAULT 'n/a', `status` ENUM('n/a','to validate','to segregate','for reporting','true positive','false positive','wrong genotype') NOT NULL DEFAULT 'n/a', `comment` TEXT NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `fk_user_id` (`user_id` ASC), CONSTRAINT `vv_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sample` FOREIGN KEY (`sample_id`) REFERENCES `sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_variant` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_cnv` FOREIGN KEY (`cnv_id`) REFERENCES `cnv` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_deletion` FOREIGN KEY (`sv_deletion_id`) REFERENCES `sv_deletion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_duplication` FOREIGN KEY (`sv_duplication_id`) REFERENCES `sv_duplication` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_insertion` FOREIGN KEY (`sv_insertion_id`) REFERENCES `sv_insertion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_inversion` FOREIGN KEY (`sv_inversion_id`) REFERENCES `sv_inversion` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_variant_validation_has_sv_translocation` FOREIGN KEY (`sv_translocation_id`) REFERENCES `sv_translocation` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `variant_validation_unique_var` (`sample_id`, `variant_id`, `cnv_id`, `sv_deletion_id`, `sv_duplication_id`, `sv_insertion_id`, `sv_inversion_id`, `sv_translocation_id`), INDEX `status` (`status` ASC), INDEX `variant_type` (`variant_type` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `study` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `study` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, `description` TEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `name_UNIQUE` (`name` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `study_sample` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `study_sample` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `study_id` INT(11) NOT NULL, `processed_sample_id` INT(11) NOT NULL, `study_sample_idendifier` VARCHAR(50) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_study_sample_has_study` FOREIGN KEY (`study_id`) REFERENCES `study` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_study_sample_has_ps` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE INDEX `unique_sample_ps` (`study_id`, `processed_sample_id`), INDEX `i_study_sample_idendifier` (`study_sample_idendifier` ASC) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `secondary_analysis` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `secondary_analysis` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `type` enum('multi sample','trio','somatic') NOT NULL, `gsvar_file` VARCHAR(1000) NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX `unique_gsvar` (`gsvar_file`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `gaps` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gaps` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `processed_sample_id` INT(11) NOT NULL, `status` enum('checked visually','to close','in progress','closed','canceled') NOT NULL, `history` TEXT, PRIMARY KEY (`id`), INDEX `gap_index` (`chr` ASC, `start` ASC, `end` ASC), INDEX `processed_sample_id` (`processed_sample_id` ASC), INDEX `status` (`status` ASC), CONSTRAINT `fk_gap_has_processed_sample1` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `gene_pseudogene_relation` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `gene_pseudogene_relation` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `parent_gene_id` int(10) unsigned NOT NULL, `pseudogene_gene_id` int(10) unsigned DEFAULT NULL, `gene_name` varchar(40) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `fk_parent_gene_id` FOREIGN KEY (`parent_gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_pseudogene_gene_id` FOREIGN KEY (`pseudogene_gene_id` ) REFERENCES `gene` (`id` ) ON DELETE NO ACTION ON UPDATE NO ACTION, UNIQUE KEY `pseudo_gene_relation` (`parent_gene_id`, `pseudogene_gene_id`, `gene_name`), INDEX `parent_gene_id` (`parent_gene_id` ASC), INDEX `pseudogene_gene_id` (`pseudogene_gene_id` ASC) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Gene-Pseudogene relation'; -- ----------------------------------------------------- -- Table `processed_sample_ancestry` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `processed_sample_ancestry` ( `processed_sample_id` INT(11) NOT NULL, `num_snps` INT(11) NOT NULL, `score_afr` FLOAT NOT NULL, `score_eur` FLOAT NOT NULL, `score_sas` FLOAT NOT NULL, `score_eas` FLOAT NOT NULL, `population` enum('AFR','EUR','SAS','EAS','ADMIXED/UNKNOWN') NOT NULL, PRIMARY KEY (`processed_sample_id`), CONSTRAINT `fk_processed_sample_ancestry_has_processed_sample` FOREIGN KEY (`processed_sample_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `subpanels` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `subpanels` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `created_by` int(11) DEFAULT NULL, `created_date` DATE NOT NULL, `mode` ENUM('exon', 'gene') NOT NULL, `extend` INT(11) NOT NULL, `genes` MEDIUMTEXT NOT NULL, `roi` MEDIUMTEXT NOT NULL, `archived` TINYINT(1) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`), INDEX(`created_by`), INDEX(`created_date`), INDEX(`archived`), CONSTRAINT `subpanels_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `cfdna_panels` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cfdna_panels` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `tumor_id` INT(11) NOT NULL, `cfdna_id` INT(11) DEFAULT NULL, `created_by` INT(11) DEFAULT NULL, `created_date` DATE NOT NULL, `processing_system_id` INT(11) NOT NULL, `bed` MEDIUMTEXT NOT NULL, `vcf` MEDIUMTEXT NOT NULL, `excluded_regions` MEDIUMTEXT DEFAULT NULL, PRIMARY KEY (`id`), INDEX(`created_by`), INDEX(`created_date`), INDEX(`tumor_id`), UNIQUE `unique_cfdna_panel`(`tumor_id`, `processing_system_id`), CONSTRAINT `cfdna_panels_tumor_id` FOREIGN KEY (`tumor_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cfdna_panels_cfdna_id` FOREIGN KEY (`cfdna_id`) REFERENCES `processed_sample` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cfdna_panels_created_by_user` FOREIGN KEY (`created_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `cfdna_panels_processing_system_id` FOREIGN KEY (`processing_system_id`) REFERENCES `processing_system` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `cfdna_panel_genes` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `cfdna_panel_genes` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `gene_name` VARCHAR(40) CHARACTER SET 'utf8' NOT NULL, `chr` ENUM('chr1','chr2','chr3','chr4','chr5','chr6','chr7','chr8','chr9','chr10','chr11','chr12','chr13','chr14','chr15','chr16','chr17','chr18','chr19','chr20','chr21','chr22','chrY','chrX','chrMT') NOT NULL, `start` INT(11) UNSIGNED NOT NULL, `end` INT(11) UNSIGNED NOT NULL, `date` DATE NOT NULL, `bed` MEDIUMTEXT NOT NULL, PRIMARY KEY (`id`), UNIQUE INDEX(`gene_name`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `variant_literature` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `variant_literature` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `variant_id` INT(11) NOT NULL, `pubmed` VARCHAR(12) CHARACTER SET 'utf8' NOT NULL, PRIMARY KEY (`id`), INDEX(`variant_id`), UNIQUE INDEX `variant_literature_UNIQUE` (`variant_id` ASC, `pubmed` ASC), CONSTRAINT `variant_literature_variant_id` FOREIGN KEY (`variant_id`) REFERENCES `variant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;
b'What is the value of 8 + 10 + (5 - 11)?\n'
b'What is (-1 - -19) + (-48 - -28)?\n'
b'What is 5 - (-12 + 5 + -2) - 4?\n'
require 'spec_helper' require 'serializables/vector3' describe Moon::Vector3 do context 'Serialization' do it 'serializes' do src = described_class.new(12, 8, 4) result = described_class.load(src.export) expect(result).to eq(src) end end end
<!-- Safe sample input : backticks interpretation, reading the file /tmp/tainted.txt SANITIZE : use of preg_replace with another regex File : use of untrusted data in one side of a quoted expression in a script --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <script> <?php $tainted = `cat /tmp/tainted.txt`; $tainted = preg_replace('/\W/si','',$tainted); echo "x='". $tainted ."'" ; ?> </script> </head> <body> <h1>Hello World!</h1> </body> </html>
<!DOCTYPE HTML> <html> <head> <title>Gamecraft CI</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css"/> <link rel="stylesheet" href="/css/dashboard.css"/> <script src="/webjars/jquery/1.11.1/jquery.min.js"></script> <script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script> <script src="/js/account_operations.js"></script> <script src="/js/ui_operations.js"></script> <script src="/js/validator.min.js"></script> <script src="/js/lang_operations.js"></script> <script> checkAuthState(); setDefaultLanguage(); loadNavbar(); </script> </head> <body> <div class="navbar-frame"></div> <div class="container"> <!-- Main component for a primary marketing message or call to action --> <div class="jumbotron"> <h1>Welcome to Gamecraft!</h1> <div class="alert alert-success" role="alert">You are logged in as user "<script> document.write(getUsername())</script>".</div> <p>If you have any question on Gamecraft:</p> <ul> <li><a href="https://github.com/iMartinezMateu/gamecraft/issues?state=open" target="_blank" rel="noopener" >Gamecraft bug tracker</a></li> <li><a href="https://github.com/iMartinezMateu/gamecraft/wiki" target="_blank" rel="noopener" >Gamecraft wiki</a></li> </ul> <p> <span jhiTranslate="home.like">If you like Gamecraft, don't forget to give us a star on</span> <a href="https://github.com/iMartinezMateu/gamecraft" target="_blank" rel="noopener" >GitHub</a>! </p> <img src="/img/gamecraft.png" alt="Gamecraft" class="center-block" /> </div> </div> <!-- /container --> </body> </html>
<?php // Documentation test config file for "Components / Jumbotron" part return [ 'title' => 'Jumbotron', 'url' => '%bootstrap-url%/components/jumbotron/', 'rendering' => function (\Laminas\View\Renderer\PhpRenderer $oView) { echo $oView->jumbotron([ 'title' => 'Hello, world!', 'lead' => 'This is a simple hero unit, a simple jumbotron-style component ' . 'for calling extra attention to featured content or information.', '---' => ['attributes' => ['class' => 'my-4']], 'It uses utility classes for typography and spacing to space ' . 'content out within the larger container.', 'button' => [ 'options' => [ 'tag' => 'a', 'label' => 'Learn more', 'variant' => 'primary', 'size' => 'lg', ], 'attributes' => [ 'href' => '#', ] ], ]) . PHP_EOL; // To make the jumbotron full width, and without rounded corners, add the option fluid echo $oView->jumbotron( [ 'title' => 'Fluid jumbotron', 'lead' => 'This is a modified jumbotron that occupies the entire horizontal space of its parent.', ], ['fluid' => true] ); }, 'expected' => '<div class="jumbotron">' . PHP_EOL . ' <h1 class="display-4">Hello, world!</h1>' . PHP_EOL . ' <p class="lead">This is a simple hero unit, a simple jumbotron-style component ' . 'for calling extra attention to featured content or information.</p>' . PHP_EOL . ' <hr class="my-4" />' . PHP_EOL . ' <p>It uses utility classes for typography and spacing to space ' . 'content out within the larger container.</p>' . PHP_EOL . ' <a href="&#x23;" class="btn&#x20;btn-lg&#x20;btn-primary" role="button">Learn more</a>' . PHP_EOL . '</div>' . PHP_EOL . '<div class="jumbotron&#x20;jumbotron-fluid">' . PHP_EOL . ' <div class="container">' . PHP_EOL . ' <h1 class="display-4">Fluid jumbotron</h1>' . PHP_EOL . ' <p class="lead">This is a modified jumbotron that occupies ' . 'the entire horizontal space of its parent.</p>' . PHP_EOL . ' </div>' . PHP_EOL . '</div>', ];
# mpps web repository
b'What is 3 + 27 + 335 + -372?\n'
import * as yargs from "yargs"; import { getEnvironment, getSlimConfig } from "../cli-helpers"; export const devCommand: yargs.CommandModule = { command: "dev", describe: "Start a development server.", builder: { open: { alias: "o", type: "boolean", description: "Automatically open the web browser." }, "update-dlls": { alias: "u", type: "boolean", description: "Create dynamically linked libraries for vendors (@angular/core, etc.) and polyfills." }, cordova: { type: "boolean", description: "Output the build to the target directory." }, aot: { type: "boolean", description: "Use the Angular AOT compiler." } }, handler: (options: Options) => { const dllTask = require("../tasks/dll.task"); const devTask = require("../tasks/dev.task"); const rootDir = process.cwd(); const slimConfig = getSlimConfig(rootDir); const environmentVariables = getEnvironment(rootDir); return dllTask(environmentVariables, slimConfig, options["update-dlls"]) .then(() => devTask(environmentVariables, slimConfig, options.open, options.aot)) .then(code => { process.exit(code); }) .catch(code => { process.exit(code); }); } };
b'What is the value of (6 + -6 - 1) + (-6 - -13) + -20?\n'
<?php /* SQL Laboratory - Web based MySQL administration http://projects.deepcode.net/sqllaboratory/ types.php - list of data types MIT-style license 2008 Calvin Lough <http://calv.in>, 2010 Steve Gricci <http://deepcode.net> */ $typeList[] = "varchar"; $typeList[] = "char"; $typeList[] = "text"; $typeList[] = "tinytext"; $typeList[] = "mediumtext"; $typeList[] = "longtext"; $typeList[] = "tinyint"; $typeList[] = "smallint"; $typeList[] = "mediumint"; $typeList[] = "int"; $typeList[] = "bigint"; $typeList[] = "real"; $typeList[] = "double"; $typeList[] = "float"; $typeList[] = "decimal"; $typeList[] = "numeric"; $typeList[] = "date"; $typeList[] = "time"; $typeList[] = "datetime"; $typeList[] = "timestamp"; $typeList[] = "tinyblob"; $typeList[] = "blob"; $typeList[] = "mediumblob"; $typeList[] = "longblob"; $typeList[] = "binary"; $typeList[] = "varbinary"; $typeList[] = "bit"; $typeList[] = "enum"; $typeList[] = "set"; $textDTs[] = "text"; $textDTs[] = "mediumtext"; $textDTs[] = "longtext"; $numericDTs[] = "tinyint"; $numericDTs[] = "smallint"; $numericDTs[] = "mediumint"; $numericDTs[] = "int"; $numericDTs[] = "bigint"; $numericDTs[] = "real"; $numericDTs[] = "double"; $numericDTs[] = "float"; $numericDTs[] = "decimal"; $numericDTs[] = "numeric"; $binaryDTs[] = "tinyblob"; $binaryDTs[] = "blob"; $binaryDTs[] = "mediumblob"; $binaryDTs[] = "longblob"; $binaryDTs[] = "binary"; $binaryDTs[] = "varbinary"; $sqliteTypeList[] = "varchar"; $sqliteTypeList[] = "integer"; $sqliteTypeList[] = "float"; $sqliteTypeList[] = "varchar"; $sqliteTypeList[] = "nvarchar"; $sqliteTypeList[] = "text"; $sqliteTypeList[] = "boolean"; $sqliteTypeList[] = "clob"; $sqliteTypeList[] = "blob"; $sqliteTypeList[] = "timestamp"; $sqliteTypeList[] = "numeric"; ?>
# BKAsciiImage [![Version](https://img.shields.io/cocoapods/v/BKAsciiImage.svg?style=flat)](http://cocoapods.org/pods/BKAsciiImage) [![License](https://img.shields.io/cocoapods/l/BKAsciiImage.svg?style=flat)](http://cocoapods.org/pods/BKAsciiImage) [![Platform](https://img.shields.io/cocoapods/p/BKAsciiImage.svg?style=flat)](http://cocoapods.org/pods/BKAsciiImage) ![Example gif image](./Screenshots/example.gif) ### As seen on Cmd.fm iOS App https://itunes.apple.com/app/cmd.fm-radio-for-geeks-hackers/id935765356 ![Cmd.fm screenshot 1](./Screenshots/cmdfm_01.jpg) ![Cmd.fm screenshot 2](./Screenshots/cmdfm_02.jpg) ## Installation BKAsciiImage is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "BKAsciiImage" ``` ## Usage ### Using BKAsciiConverter class Import BKAsciiConverter header file ```objective-c #import <BKAsciiImage/BKAsciiConverter.h> ``` Create a BKAsciiConverter instance ```objective-c BKAsciiConverter *converter = [BKAsciiConverter new]; ``` Convert synchronously ```objective-c UIImage *inputImage = [UIImage imageNamed:@"anImage"]; UIImage *asciiImage = [converter convertImage:inputImage]; ``` Convert in the background providing a completion block. Completion block will be called on the main thread. ```objective-c [converter convertImage:self.inputImage completionHandler:^(UIImage *asciiImage) { // do whatever you want with the resulting asciiImage }]; ``` Convert to NSString ```objective-c NSLog(@"%@",[converter convertToString:self.inputImage]); // asynchronous [converter convertToString:self.inputImage completionHandler:^(NSString *asciiString) { NSLog(@"%@",asciiString); }]; ``` #### Converter options ```objective-c converter.backgroundColor = [UIColor whiteColor]; // default: Clear color. Image background is transparent converter.grayscale = YES; // default: NO converter.font = [UIFont fontWithName:@"Monaco" size:13.0]; // default: System font of size 10 converter.reversedLuminance = NO; // Reverses the luminance mapping. Reversing gives better results on a dark bg. default: YES converter.columns = 50; // By default columns is derived by the font size if not set explicitly ``` ### Using UIImage category Import header file ```objective-c #import <BKAsciiImage/UIImage+BKAscii.h> ``` Use the provided category methods ```objective-c UIImage *inputImage = [UIImage imageNamed:@"anImage"]; [inputImage bk_asciiImageCompletionHandler:^(UIImage *asciiImage) { }]; [inputImage bk_asciiStringCompletionHandler:^(NSString *asciiString) { }]; [inputImage bk_asciiImageWithFont: [UIFont fontWithName:@"Monaco" size:13.0] bgColor: [UIColor redColor]; columns: 30 reversed: YES grayscale: NO completionHandler: ^(NSString *asciiString) { // do whatever you want with the resulting asciiImage }]; ``` ## Advanced usage By default luminance values are mapped to strings using ```objective-c NSDictionary *dictionary = @{ @1.0: @" ", @0.95:@"`", @0.92:@".", @0.9 :@",", @0.8 :@"-", @0.75:@"~", @0.7 :@"+", @0.65:@"<", @0.6 :@">", @0.55:@"o", @0.5 :@"=", @0.35:@"*", @0.3 :@"%", @0.1 :@"X", @0.0 :@"@" }; ``` You can instantiate a converter with your own mapping dictionary ```objective-c NSDictionary *dictionary = @{ @1.0: @" ", @0.7 :@"a", @0.65:@"b", @0.6 :@"c", @0.55:@"d", @0.5 :@"e", @0.35:@"f", @0.3 :@"g", @0.1 :@" ", @0.0 :@" " }; BKAsciiConverter *converter = [[BKAsciiConverter alloc] initWithDictionary:dictionary]; UIImage *inputImage = [UIImage imageNamed:@"anImage"]; UIImage *asciiImage = [converter convertImage:inputImage]; ``` ![Mapping example screenshot](./Screenshots/mappingExample.jpg) ## Author Barış Koç, https://github.com/bkoc ## License BKAsciiImage is available under the MIT license. See the LICENSE file for more info.
b'What is the value of (29 - 35) + (12 - 0) + -4 + 4?\n'
#LocalFolderPathStr=${PWD} #LocalFilePathStr=$LocalFolderPathStr'/.pypirc' #HomeFilePathStr=$HOME'/.pypirc' #echo $LocalFilePathStr #echo $HomeFilePathStr #cp $LocalFilePathStr $HomeFilePathStr python setup.py register sudo python setup.py sdist upload
b'2 + -4 + (-19 + 12 - -4)\n'
import { expect } from 'chai'; import buildUriTemplate from '../src/uri-template'; describe('URI Template Handler', () => { context('when there are path object parameters', () => { context('when the path object parameters are not query parameters', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'path', description: 'Path parameter from path object', name: 'fromPath', required: true, type: 'string', }, ]; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, { in: 'query', description: 'For tests. Unknown type of query parameter.', name: 'unknown', required: true, type: 'unknown', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?tags,unknown}'); }); }); context('when there are no query parameters but have one path object parameter', () => { const basePath = '/api'; const href = '/pet/{id}'; const pathObjectParams = [ { in: 'path', description: 'Pet\'s identifier', name: 'id', required: true, type: 'number', }, ]; const queryParams = []; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/{id}'); }); }); context('when there are query parameters defined', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'query', description: 'Query parameter from path object', name: 'fromPath', required: true, type: 'string', }, ]; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, { in: 'query', description: 'For tests. Unknown type of query parameter.', name: 'unknown', required: true, type: 'unknown', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?fromPath,tags,unknown}'); }); }); context('when there are parameters with reserved characters', () => { const basePath = '/my-api'; const href = '/pet/{unique%2did}'; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tag-names[]', required: true, type: 'string', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, [], queryParams); expect(hrefForResource).to.equal('/my-api/pet/{unique%2did}{?tag%2dnames%5B%5D}'); }); }); context('when there is a conflict in parameter names', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, ]; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, ]; it('only adds one to the query parameters', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?tags}'); }); }); context('when there are no query parameters defined', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = [ { in: 'query', description: 'Query parameter from path object', name: 'fromPath', required: true, type: 'string', }, ]; const queryParams = []; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?fromPath}'); }); }); }); context('when there are query parameters but no path object parameters', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = []; const queryParams = [ { in: 'query', description: 'Tags to filter by', name: 'tags', required: true, type: 'string', }, { in: 'query', description: 'For tests. Unknown type of query parameter.', name: 'unknown', required: true, type: 'unknown', }, ]; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags{?tags,unknown}'); }); }); context('when there are no query or path object parameters', () => { const basePath = '/api'; const href = '/pet/findByTags'; const pathObjectParams = []; const queryParams = []; it('returns the correct URI', () => { const hrefForResource = buildUriTemplate(basePath, href, pathObjectParams, queryParams); expect(hrefForResource).to.equal('/api/pet/findByTags'); }); }); describe('array parameters with collectionFormat', () => { it('returns a template with default format', () => { const parameter = { in: 'query', name: 'tags', type: 'array', }; const hrefForResource = buildUriTemplate('', '/example', [parameter]); expect(hrefForResource).to.equal('/example{?tags}'); }); it('returns a template with csv format', () => { const parameter = { in: 'query', name: 'tags', type: 'array', collectionFormat: 'csv', }; const hrefForResource = buildUriTemplate('', '/example', [parameter]); expect(hrefForResource).to.equal('/example{?tags}'); }); it('returns an exploded template with multi format', () => { const parameter = { in: 'query', name: 'tags', type: 'array', collectionFormat: 'multi', }; const hrefForResource = buildUriTemplate('', '/example', [parameter]); expect(hrefForResource).to.equal('/example{?tags*}'); }); }); });
b'18 + 7 + (19 - 39)\n'
b'What is the value of -5 - (22 + (-15 - 1) - (-2 - -26))?\n'
b'What is the value of 19 - -5 - 50 - -30?\n'
b'28 - 21 - (6 + 1) - -7 - 2\n'
b'What is the value of -7 + (42 - 53) - 14?\n'
b'6 + -2 + -10 - (-1 + -12)\n'
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <meta name="collection" content="api"> <!-- Generated by javadoc (build 1.5.0-rc) on Wed Aug 11 07:27:53 PDT 2004 --> <TITLE> Binding (Java 2 Platform SE 5.0) </TITLE> <META NAME="keywords" CONTENT="org.omg.CosNaming.Binding class"> <META NAME="keywords" CONTENT="binding_name"> <META NAME="keywords" CONTENT="binding_type"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Binding (Java 2 Platform SE 5.0)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Binding.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Java<sup><font size=-2>TM</font></sup>&nbsp;2&nbsp;Platform<br>Standard&nbsp;Ed. 5.0</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/omg/CosNaming/_NamingContextStub.html" title="class in org.omg.CosNaming"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/omg/CosNaming/BindingHelper.html" title="class in org.omg.CosNaming"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/omg/CosNaming/Binding.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Binding.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.omg.CosNaming</FONT> <BR> Class Binding</H2> <PRE> <A HREF="../../../java/lang/Object.html" title="class in java.lang">java.lang.Object</A> <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.omg.CosNaming.Binding</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../java/io/Serializable.html" title="interface in java.io">Serializable</A>, <A HREF="../../../org/omg/CORBA/portable/IDLEntity.html" title="interface in org.omg.CORBA.portable">IDLEntity</A></DD> </DL> <HR> <DL> <DT><PRE>public final class <B>Binding</B><DT>extends <A HREF="../../../java/lang/Object.html" title="class in java.lang">Object</A><DT>implements <A HREF="../../../org/omg/CORBA/portable/IDLEntity.html" title="interface in org.omg.CORBA.portable">IDLEntity</A></DL> </PRE> <P> org/omg/CosNaming/Binding.java . Generated by the IDL-to-Java compiler (portable), version "3.2" from ../../../../src/share/classes/org/omg/CosNaming/nameservice.idl Wednesday, August 11, 2004 5:04:12 AM GMT-08:00 <P> <P> <DL> <DT><B>See Also:</B><DD><A HREF="../../../serialized-form.html#org.omg.CosNaming.Binding">Serialized Form</A></DL> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[]</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#binding_name">binding_name</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#binding_type">binding_type</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#Binding()">Binding</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../org/omg/CosNaming/Binding.html#Binding(org.omg.CosNaming.NameComponent[], org.omg.CosNaming.BindingType)">Binding</A></B>(<A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[]&nbsp;_binding_name, <A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A>&nbsp;_binding_type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="../../../java/lang/Object.html" title="class in java.lang">Object</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../java/lang/Object.html#clone()">clone</A>, <A HREF="../../../java/lang/Object.html#equals(java.lang.Object)">equals</A>, <A HREF="../../../java/lang/Object.html#finalize()">finalize</A>, <A HREF="../../../java/lang/Object.html#getClass()">getClass</A>, <A HREF="../../../java/lang/Object.html#hashCode()">hashCode</A>, <A HREF="../../../java/lang/Object.html#notify()">notify</A>, <A HREF="../../../java/lang/Object.html#notifyAll()">notifyAll</A>, <A HREF="../../../java/lang/Object.html#toString()">toString</A>, <A HREF="../../../java/lang/Object.html#wait()">wait</A>, <A HREF="../../../java/lang/Object.html#wait(long)">wait</A>, <A HREF="../../../java/lang/Object.html#wait(long, int)">wait</A></CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="binding_name"><!-- --></A><H3> binding_name</H3> <PRE> public <A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[] <B>binding_name</B></PRE> <DL> <DL> </DL> </DL> <HR> <A NAME="binding_type"><!-- --></A><H3> binding_type</H3> <PRE> public <A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A> <B>binding_type</B></PRE> <DL> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="Binding()"><!-- --></A><H3> Binding</H3> <PRE> public <B>Binding</B>()</PRE> <DL> </DL> <HR> <A NAME="Binding(org.omg.CosNaming.NameComponent[], org.omg.CosNaming.BindingType)"><!-- --></A><H3> Binding</H3> <PRE> public <B>Binding</B>(<A HREF="../../../org/omg/CosNaming/NameComponent.html" title="class in org.omg.CosNaming">NameComponent</A>[]&nbsp;_binding_name, <A HREF="../../../org/omg/CosNaming/BindingType.html" title="class in org.omg.CosNaming">BindingType</A>&nbsp;_binding_type)</PRE> <DL> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Binding.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>Java<sup><font size=-2>TM</font></sup>&nbsp;2&nbsp;Platform<br>Standard&nbsp;Ed. 5.0</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../org/omg/CosNaming/_NamingContextStub.html" title="class in org.omg.CosNaming"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../org/omg/CosNaming/BindingHelper.html" title="class in org.omg.CosNaming"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?org/omg/CosNaming/Binding.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Binding.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_java.lang.Object">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <font size="-1"><a href="http://java.sun.com/cgi-bin/bugreport.cgi">Submit a bug or feature</a><br>For further API reference and developer documentation, see <a href="../../../../relnotes/devdocs-vs-specs.html">Java 2 SDK SE Developer Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. <p>Copyright &#169; 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to <a href="../../../../relnotes/license.html">license terms</a>. Also see the <a href="http://java.sun.com/docs/redist.html">documentation redistribution policy</a>.</font> <!-- Start SiteCatalyst code --> <script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code_download.js"></script> <script language="JavaScript" src="http://www.oracle.com/ocom/groups/systemobject/@mktg_admin/documents/systemobject/s_code.js"></script> <!-- ********** DO NOT ALTER ANYTHING BELOW THIS LINE ! *********** --> <!-- Below code will send the info to Omniture server --> <script language="javascript">var s_code=s.t();if(s_code)document.write(s_code)</script> <!-- End SiteCatalyst code --> </body> </HTML>
#AtaK ##The Atari 2600 Compiler Kit AtaK, pronounced attack, is a collection of programs built to aid in the development of Atari 2600 programs. ##Programs(Planned/Developing): * AtaR(ah-tar), The **Ata**ri 2600 Assemble**r** * AtaC(attack), The **Ata**ri 2600 **C** Compiler ##Universal Features: * Programmed in C89 ##Contributing: Here are some ways to contribute: * Come up with features * Criticize source code and programming methods * Put comments where you see fit * Build/test the program on other machines ##Versioning Scheme: [major release(roman)].[year of release(roman)], rev. [revision (arabic)] Example: AraR I.MMXVI, rev. 0 was the first release of AtaR(a development stub) ##Contributers: Charles "Gip-Gip" Thompson - Author/Maintainer<br> [ZackAttack](http://atariage.com/forums/user/40226-zackattack/) - General Critic <br>
require 'cred_hubble/resources/credential' module CredHubble module Resources class UserValue include Virtus.model attribute :username, String attribute :password, String attribute :password_hash, String def to_json(options = {}) attributes.to_json(options) end def attributes_for_put attributes.delete_if { |k, _| immutable_attributes.include?(k) } end private def immutable_attributes [:password_hash] end end class UserCredential < Credential attribute :value, UserValue def type Credential::USER_TYPE end def attributes_for_put super.merge(value: value && value.attributes_for_put) end end end end
package org.anodyneos.xp.tag.core; import javax.servlet.jsp.el.ELException; import org.anodyneos.xp.XpException; import org.anodyneos.xp.XpOutput; import org.anodyneos.xp.tagext.XpTagSupport; import org.xml.sax.SAXException; /** * @author jvas */ public class DebugTag extends XpTagSupport { public DebugTag() { super(); } /* (non-Javadoc) * @see org.anodyneos.xp.tagext.XpTag#doTag(org.anodyneos.xp.XpContentHandler) */ public void doTag(XpOutput out) throws XpException, ELException, SAXException { XpOutput newOut = new XpOutput(new DebugCH(System.err, out.getXpContentHandler())); getXpBody().invoke(newOut); } }
b'Evaluate -16 + 11 - -10 - (-6 - 2).\n'
b'Evaluate -9 + -10 + (4 - -34).\n'
b'Evaluate -7 + (26 - (17 - 3)).\n'
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail()
b'What is 4 + -2 + (-3 - -3) + 14?\n'
b'What is 17 - (2 - -13) - (3 - 1)?\n'
require 'spec_helper' RSpec.describe RailsAdmin::ApplicationHelper, type: :helper do describe '#authorized?' do let(:abstract_model) { RailsAdmin.config(FieldTest).abstract_model } it 'doesn\'t use unpersisted objects' do expect(helper).to receive(:action).with(:edit, abstract_model, nil).and_call_original helper.authorized?(:edit, abstract_model, FactoryBot.build(:field_test)) end end describe 'with #authorized? stubbed' do before do allow(controller).to receive(:authorized?).and_return(true) end describe '#current_action?' do it 'returns true if current_action, false otherwise' do @action = RailsAdmin::Config::Actions.find(:index) expect(helper.current_action?(RailsAdmin::Config::Actions.find(:index))).to be_truthy expect(helper.current_action?(RailsAdmin::Config::Actions.find(:show))).not_to be_truthy end end describe '#action' do it 'returns action by :custom_key' do RailsAdmin.config do |config| config.actions do dashboard do custom_key :my_custom_dashboard_key end end end expect(helper.action(:my_custom_dashboard_key)).to be end it 'returns only visible actions' do RailsAdmin.config do |config| config.actions do dashboard do visible false end end end expect(helper.action(:dashboard)).to be_nil end it 'returns only visible actions, passing all bindings' do RailsAdmin.config do |config| config.actions do member :test_bindings do visible do bindings[:controller].is_a?(ActionView::TestCase::TestController) && bindings[:abstract_model].model == Team && bindings[:object].is_a?(Team) end end end end expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Team.new)).to be expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Team), Player.new)).to be_nil expect(helper.action(:test_bindings, RailsAdmin::AbstractModel.new(Player), Team.new)).to be_nil end end describe '#actions' do it 'returns actions by type' do abstract_model = RailsAdmin::AbstractModel.new(Player) object = FactoryBot.create :player expect(helper.actions(:all, abstract_model, object).collect(&:custom_key)).to eq([:dashboard, :index, :show, :new, :edit, :export, :delete, :bulk_delete, :history_show, :history_index, :show_in_app]) expect(helper.actions(:root, abstract_model, object).collect(&:custom_key)).to eq([:dashboard]) expect(helper.actions(:collection, abstract_model, object).collect(&:custom_key)).to eq([:index, :new, :export, :bulk_delete, :history_index]) expect(helper.actions(:member, abstract_model, object).collect(&:custom_key)).to eq([:show, :edit, :delete, :history_show, :show_in_app]) end it 'only returns visible actions, passing bindings correctly' do RailsAdmin.config do |config| config.actions do member :test_bindings do visible do bindings[:controller].is_a?(ActionView::TestCase::TestController) && bindings[:abstract_model].model == Team && bindings[:object].is_a?(Team) end end end end expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Team.new).collect(&:custom_key)).to eq([:test_bindings]) expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Team), Player.new).collect(&:custom_key)).to eq([]) expect(helper.actions(:all, RailsAdmin::AbstractModel.new(Player), Team.new).collect(&:custom_key)).to eq([]) end end describe '#logout_method' do it 'defaults to :delete when Devise is not defined' do allow(Object).to receive(:defined?).with(Devise).and_return(false) expect(helper.logout_method).to eq(:delete) end it 'uses first sign out method from Devise when it is defined' do allow(Object).to receive(:defined?).with(Devise).and_return(true) expect(Devise).to receive(:sign_out_via).and_return([:whatever_defined_on_devise, :something_ignored]) expect(helper.logout_method).to eq(:whatever_defined_on_devise) end end describe '#wording_for' do it 'gives correct wording even if action is not visible' do RailsAdmin.config do |config| config.actions do index do visible false end end end expect(helper.wording_for(:menu, :index)).to eq('List') end it 'passes correct bindings' do expect(helper.wording_for(:title, :edit, RailsAdmin::AbstractModel.new(Team), Team.new(name: 'the avengers'))).to eq("Edit Team 'the avengers'") end it 'defaults correct bindings' do @action = RailsAdmin::Config::Actions.find :edit @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = Team.new(name: 'the avengers') expect(helper.wording_for(:title)).to eq("Edit Team 'the avengers'") end it 'does not try to use the wrong :label_metod' do @abstract_model = RailsAdmin::AbstractModel.new(Draft) @object = Draft.new expect(helper.wording_for(:link, :new, RailsAdmin::AbstractModel.new(Team))).to eq('Add a new Team') end end describe '#breadcrumb' do it 'gives us a breadcrumb' do @action = RailsAdmin::Config::Actions.find(:edit, abstract_model: RailsAdmin::AbstractModel.new(Team), object: FactoryBot.create(:team, name: 'the avengers')) bc = helper.breadcrumb expect(bc).to match(/Dashboard/) # dashboard expect(bc).to match(/Teams/) # list expect(bc).to match(/the avengers/) # show expect(bc).to match(/Edit/) # current (edit) end end describe '#menu_for' do it 'passes model and object as bindings and generates a menu, excluding non-get actions' do RailsAdmin.config do |config| config.actions do dashboard index do visible do bindings[:abstract_model].model == Team end end show do visible do bindings[:object].class == Team end end delete do http_methods [:post, :put, :delete] end end end @action = RailsAdmin::Config::Actions.find :show @abstract_model = RailsAdmin::AbstractModel.new(Team) @object = FactoryBot.create(:team, name: 'the avengers') expect(helper.menu_for(:root)).to match(/Dashboard/) expect(helper.menu_for(:collection, @abstract_model)).to match(/List/) expect(helper.menu_for(:member, @abstract_model, @object)).to match(/Show/) @abstract_model = RailsAdmin::AbstractModel.new(Player) @object = Player.new expect(helper.menu_for(:collection, @abstract_model)).not_to match(/List/) expect(helper.menu_for(:member, @abstract_model, @object)).not_to match(/Show/) end it 'excludes non-get actions' do RailsAdmin.config do |config| config.actions do dashboard do http_methods [:post, :put, :delete] end end end @action = RailsAdmin::Config::Actions.find :dashboard expect(helper.menu_for(:root)).not_to match(/Dashboard/) end it 'shows actions which are marked as show_in_menu' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_menu: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_menu false end root :shown_in_menu, :dashboard do action_name :dashboard show_in_menu true end end end @action = RailsAdmin::Config::Actions.find :dashboard expect(helper.menu_for(:root)).not_to match(/Dashboard/) expect(helper.menu_for(:root)).to match(/Look this/) end end describe '#main_navigation' do it 'shows included models' do RailsAdmin.config do |config| config.included_models = [Ball, Comment] end expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Balls).*(Comments)/m) end it 'does not draw empty navigation labels' do RailsAdmin.config do |config| config.included_models = [Ball, Comment, Comment::Confirmed] config.model Comment do navigation_label 'Commentz' end config.model Comment::Confirmed do label_plural 'Confirmed' end end expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Balls).*(Commentz).*(Confirmed)/m) expect(helper.main_navigation).not_to match(/(dropdown-header).*(Navigation).*(Balls).*(Commentz).*(Confirmed).*(Comment)/m) end it 'does not show unvisible models' do RailsAdmin.config do |config| config.included_models = [Ball, Comment] config.model Comment do hide end end result = helper.main_navigation expect(result).to match(/(dropdown-header).*(Navigation).*(Balls)/m) expect(result).not_to match('Comments') end it 'shows children of hidden models' do # https://github.com/sferik/rails_admin/issues/978 RailsAdmin.config do |config| config.included_models = [Ball, Hardball] config.model Ball do hide end end expect(helper.main_navigation).to match(/(dropdown\-header).*(Navigation).*(Hardballs)/m) end it 'shows children of excluded models' do RailsAdmin.config do |config| config.included_models = [Hardball] end expect(helper.main_navigation).to match(/(dropdown-header).*(Navigation).*(Hardballs)/m) end it 'nests in navigation label' do RailsAdmin.config do |config| config.included_models = [Comment] config.model Comment do navigation_label 'commentable' end end expect(helper.main_navigation).to match(/(dropdown\-header).*(commentable).*(Comments)/m) end it 'nests in parent model' do RailsAdmin.config do |config| config.included_models = [Player, Comment] config.model Comment do parent Player end end expect(helper.main_navigation).to match(/(Players).* (nav\-level\-1).*(Comments)/m) end it 'orders' do RailsAdmin.config do |config| config.included_models = [Player, Comment] end expect(helper.main_navigation).to match(/(Comments).*(Players)/m) RailsAdmin.config(Comment) do weight 1 end expect(helper.main_navigation).to match(/(Players).*(Comments)/m) end end describe '#root_navigation' do it 'shows actions which are marked as show_in_sidebar' do I18n.backend.store_translations( :en, admin: {actions: { shown_in_sidebar: {menu: 'Look this'}, }} ) RailsAdmin.config do |config| config.actions do dashboard do show_in_sidebar false end root :shown_in_sidebar, :dashboard do action_name :dashboard show_in_sidebar true end end end expect(helper.root_navigation).not_to match(/Dashboard/) expect(helper.root_navigation).to match(/Look this/) end it 'allows grouping by sidebar_label' do I18n.backend.store_translations( :en, admin: { actions: { foo: {menu: 'Foo'}, bar: {menu: 'Bar'}, }, } ) RailsAdmin.config do |config| config.actions do dashboard do show_in_sidebar true sidebar_label 'One' end root :foo, :dashboard do action_name :dashboard show_in_sidebar true sidebar_label 'Two' end root :bar, :dashboard do action_name :dashboard show_in_sidebar true sidebar_label 'Two' end end end expect(helper.strip_tags(helper.root_navigation).delete(' ')).to eq 'OneDashboardTwoFooBar' end end describe '#static_navigation' do it 'shows not show static nav if no static links defined' do RailsAdmin.config do |config| config.navigation_static_links = {} end expect(helper.static_navigation).to be_empty end it 'shows links if defined' do RailsAdmin.config do |config| config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(/Test Link/) end it 'shows default header if navigation_static_label not defined in config' do RailsAdmin.config do |config| config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(I18n.t('admin.misc.navigation_static_label')) end it 'shows custom header if defined' do RailsAdmin.config do |config| config.navigation_static_label = 'Test Header' config.navigation_static_links = { 'Test Link' => 'http://www.google.com', } end expect(helper.static_navigation).to match(/Test Header/) end end describe '#bulk_menu' do it 'includes all visible bulkable actions' do RailsAdmin.config do |config| config.actions do index collection :zorg do bulkable true action_name :zorg_action end collection :blub do bulkable true visible do bindings[:abstract_model].model == Team end end end end # Preload all models to prevent I18n being cleared in Mongoid builds RailsAdmin::AbstractModel.all en = {admin: {actions: { zorg: {bulk_link: 'Zorg all these %{model_label_plural}'}, blub: {bulk_link: 'Blub all these %{model_label_plural}'}, }}} I18n.backend.store_translations(:en, en) @abstract_model = RailsAdmin::AbstractModel.new(Team) result = helper.bulk_menu expect(result).to match('zorg_action') expect(result).to match('Zorg all these Teams') expect(result).to match('blub') expect(result).to match('Blub all these Teams') result_2 = helper.bulk_menu(RailsAdmin::AbstractModel.new(Player)) expect(result_2).to match('zorg_action') expect(result_2).to match('Zorg all these Players') expect(result_2).not_to match('blub') expect(result_2).not_to match('Blub all these Players') end end describe '#edit_user_link' do it "don't include email column" do allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:player)) result = helper.edit_user_link expect(result).to eq nil end it 'include email column' do allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user)) result = helper.edit_user_link expect(result).to match('href') end it 'show gravatar' do allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user)) result = helper.edit_user_link expect(result).to include('gravatar') end it "don't show gravatar" do RailsAdmin.config do |config| config.show_gravatar = false end allow(helper).to receive(:_current_user).and_return(FactoryBot.create(:user)) result = helper.edit_user_link expect(result).not_to include('gravatar') end context 'when the user is not authorized to perform edit' do let(:user) { FactoryBot.create(:user) } before do allow_any_instance_of(RailsAdmin::Config::Actions::Edit).to receive(:authorized?).and_return(false) allow(helper).to receive(:_current_user).and_return(user) end it 'show gravatar and email without a link' do result = helper.edit_user_link expect(result).to include('gravatar') expect(result).to include(user.email) expect(result).not_to match('href') end end end end describe '#flash_alert_class' do it 'makes errors red with alert-danger' do expect(helper.flash_alert_class('error')).to eq('alert-danger') end it 'makes alerts yellow with alert-warning' do expect(helper.flash_alert_class('alert')).to eq('alert-warning') end it 'makes notices blue with alert-info' do expect(helper.flash_alert_class('notice')).to eq('alert-info') end it 'prefixes others with "alert-"' do expect(helper.flash_alert_class('foo')).to eq('alert-foo') end end end
export default { hello : "hello" };
// // #ifndef _Rectangle_h #define _Rectangle_h // Includes #include <Engine/Core/Shape.h> #include <Engine/Core/Vector.h> //============================================================================== namespace ptc { class Ray; class Rectangle : public Shape { public: Rectangle(); Rectangle( const Vector& center, const Vector& right, const Vector& normal, float width, //< in right dir float height ); //< in cross( right, normal ) dir void setIsDoubleSided( bool new_value ); bool getIsDoubleSided() const; IntersectDescr intersect( const Ray& ray ) override; private: Vector center_; Vector right_; Vector up_; Vector normal_; float width_; float height_; bool is_double_sided_; }; } // namespace ptc #endif // Include guard
b'What is the value of (3 - -2) + (33 - 39) + -17 + 16?\n'
<?php /** * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace Clash82\EzPlatformStudioTipsBlockBundle\Installer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use eZ\Publish\API\Repository\ContentTypeService; use eZ\Publish\API\Repository\Exceptions\ForbiddenException; use eZ\Publish\API\Repository\Exceptions\NotFoundException; use eZ\Publish\API\Repository\Exceptions\UnauthorizedException; use eZ\Publish\API\Repository\Repository; use eZ\Publish\API\Repository\UserService; class ContentTypeInstaller extends Command { /** @var int */ const ADMIN_USER_ID = 14; /** @var \eZ\Publish\API\Repository\Repository */ private $repository; /** @var \eZ\Publish\API\Repository\UserService */ private $userService; /** @var \eZ\Publish\API\Repository\ContentTypeService */ private $contentTypeService; /** * @param \eZ\Publish\API\Repository\Repository $repository * @param \eZ\Publish\API\Repository\UserService $userService * @param \eZ\Publish\API\Repository\ContentTypeService $contentTypeService */ public function __construct( Repository $repository, UserService $userService, ContentTypeService $contentTypeService ) { $this->repository = $repository; $this->userService = $userService; $this->contentTypeService = $contentTypeService; parent::__construct(); } protected function configure() { $this->setName('ezstudio:tips-block:install') ->setHelp('Creates a new `Tip` ContentType.') ->addOption( 'name', null, InputOption::VALUE_OPTIONAL, 'replaces default ContentType <info>name</info>', 'Tip' ) ->addOption( 'identifier', null, InputOption::VALUE_OPTIONAL, 'replaces default ContentType <info>identifier</info>', 'tip' ) ->addOption( 'group_identifier', null, InputOption::VALUE_OPTIONAL, 'replaces default ContentType <info>group_identifier</info>', 'Content' ); } protected function execute(InputInterface $input, OutputInterface $output) { $groupIdentifier = $input->getOption('group_identifier'); $identifier = $input->getOption('identifier'); $name = $input->getOption('name'); try { $contentTypeGroup = $this->contentTypeService->loadContentTypeGroupByIdentifier($groupIdentifier); } catch (NotFoundException $e) { $output->writeln(sprintf('ContentType group with identifier %s not found', $groupIdentifier)); return; } // create basic ContentType structure $contentTypeCreateStruct = $this->contentTypeService->newContentTypeCreateStruct($identifier); $contentTypeCreateStruct->mainLanguageCode = 'eng-GB'; $contentTypeCreateStruct->nameSchema = '<title>'; $contentTypeCreateStruct->names = [ 'eng-GB' => $identifier, ]; $contentTypeCreateStruct->descriptions = [ 'eng-GB' => 'Tip of the day', ]; // add Title field $titleFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('title', 'ezstring'); $titleFieldCreateStruct->names = [ 'eng-GB' => 'Title', ]; $titleFieldCreateStruct->descriptions = [ 'eng-GB' => 'Title', ]; $titleFieldCreateStruct->fieldGroup = 'content'; $titleFieldCreateStruct->position = 1; $titleFieldCreateStruct->isTranslatable = true; $titleFieldCreateStruct->isRequired = true; $titleFieldCreateStruct->isSearchable = true; $contentTypeCreateStruct->addFieldDefinition($titleFieldCreateStruct); // add Description field $bodyFieldCreateStruct = $this->contentTypeService->newFieldDefinitionCreateStruct('body', 'ezrichtext'); $bodyFieldCreateStruct->names = [ 'eng-GB' => 'Body', ]; $bodyFieldCreateStruct->descriptions = [ 'eng-GB' => 'Body', ]; $bodyFieldCreateStruct->fieldGroup = 'content'; $bodyFieldCreateStruct->position = 2; $bodyFieldCreateStruct->isTranslatable = true; $bodyFieldCreateStruct->isRequired = true; $bodyFieldCreateStruct->isSearchable = true; $contentTypeCreateStruct->addFieldDefinition($bodyFieldCreateStruct); try { $contentTypeDraft = $this->contentTypeService->createContentType($contentTypeCreateStruct, [ $contentTypeGroup, ]); $this->contentTypeService->publishContentTypeDraft($contentTypeDraft); $output->writeln(sprintf( '<info>%s ContentType created with ID %d</info>', $name, $contentTypeDraft->id )); } catch (UnauthorizedException $e) { $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); return; } catch (ForbiddenException $e) { $output->writeln(sprintf('<error>%s</error>', $e->getMessage())); return; } $output->writeln(sprintf( 'Place all your <info>%s</info> content objects into desired folder and then select it as a Parent container in eZ Studio Tips Block options form.', $name )); } protected function initialize(InputInterface $input, OutputInterface $output) { $this->repository->setCurrentUser( $this->userService->loadUser(self::ADMIN_USER_ID) ); } }
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Dimension(Model): """Dimension of a resource metric. For e.g. instance specific HTTP requests for a web app, where instance name is dimension of the metric HTTP request. :param name: :type name: str :param display_name: :type display_name: str :param internal_name: :type internal_name: str :param to_be_exported_for_shoebox: :type to_be_exported_for_shoebox: bool """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'internal_name': {'key': 'internalName', 'type': 'str'}, 'to_be_exported_for_shoebox': {'key': 'toBeExportedForShoebox', 'type': 'bool'}, } def __init__(self, name=None, display_name=None, internal_name=None, to_be_exported_for_shoebox=None): super(Dimension, self).__init__() self.name = name self.display_name = display_name self.internal_name = internal_name self.to_be_exported_for_shoebox = to_be_exported_for_shoebox
require File.join(File.dirname(__FILE__), 'test_helper') require 'activesupport' class SplamTest < Test::Unit::TestCase class FixedRule < Splam::Rule def run add_score 25, "The force is strong with this one" end end # It should not be in the default set Splam::Rule.default_rules.delete SplamTest::FixedRule class Foo include ::Splam splammable :body attr_accessor :body def body @body || "This is body\320\224 \320\199" end end class FooReq include ::Splam splammable :body do |s| s.rules = [ Splam::Rules::Keyhits, Splam::Rules::True ] end attr_accessor :body attr_accessor :request def request(obj) @request end end class FooCond include ::Splam splammable :body, 0, lambda { |s| false } attr_accessor :body end class PickyFoo include ::Splam splammable :body do |s| s.rules = [:fixed_rule, FixedRule] end def body 'lol wut' end end class HeavyFoo include ::Splam splammable :body do |s| s.rules = {:fixed_rule => 3} end def body 'lol wut' end end def test_runs_plugins f = Foo.new assert ! f.splam? assert_equal 10, f.splam_score end def test_runs_plugins_with_specified_rules f = PickyFoo.new assert ! f.splam? assert_equal 25, f.splam_score end def test_runs_plugins_with_specified_weighted_rules f = HeavyFoo.new assert ! f.splam? assert_equal 75, f.splam_score end def test_runs_conditions f = FooCond.new assert f.splam? # it IS spam, coz threshold is 0 end def test_scores_spam_really_high Dir.glob(File.join(File.dirname(__FILE__), "fixtures", "comment", "spam", "*.txt")).each do |f| comment = Foo.new spam = File.open(f).read comment.body = spam # some spam have a lower threshold denoted by their filename # trickier to detect if f =~ /\/(\d+)_.*\.txt/ Foo.splam_suite.threshold = $1.to_i else Foo.splam_suite.threshold = 180 end spam = comment.splam? score = comment.splam_score #$stderr.puts "#{f} score: #{score}\n#{comment.splam_reasons.inspect}" #$stderr.puts "=====================" assert spam, "Comment #{f} was not spam, score was #{score} but threshold was #{Foo.splam_suite.threshold}\nReasons were #{comment.splam_reasons.inspect}" end end def test_scores_ham_low Dir.glob(File.join(File.dirname(__FILE__), "fixtures", "comment", "ham", "*.txt")).each do |f| comment = Foo.new comment.body = File.open(f).read spam = comment.splam? score = comment.splam_score #$stderr.puts "#{f} score: #{score}" #$stderr.puts "=====================" assert !spam, "File #{f} should be marked ham < #{Foo.splam_suite.threshold}, but was marked with score #{score}\nReasons were #{comment.splam_reasons.inspect}\n\n#{comment.body}" end end def test_keyhits_with_true f = FooReq.new f.body = "true" f.request = {:counter => "", :time => 3, :remote_ip => "1.2.3.4"} assert f.splam? assert_equal 300, f.splam_score end def test_keyhits_with_word f = FooReq.new f.body = "8趷" f.request = {:counter => "", :time => 3, :remote_ip => "1.2.3.4"} assert f.splam? assert_equal 300, f.splam_score end end
<?php /** * Time Controller * * @package Argentum * @author Argentum Team * @copyright (c) 2008 Argentum Team * @license http://www.argentuminvoice.com/license.txt */ class Time_Controller extends Website_Controller { /** * Creates a new time block on a ticket */ public function add($ticket_id) { $time = new Time_Model(); $time->ticket_id = $ticket_id; if ( ! $_POST) // Display the form { $this->template->body = new View('admin/time/add'); $this->template->body->errors = ''; $this->template->body->time = $time; } else { $time->set_fields($this->input->post()); $time->user_id = $_SESSION['auth_user']->id; try { $time->save(); if ($this->input->post('ticket_complete')) { $ticket = new Ticket_Model($time->ticket_id); $ticket->complete= TRUE; $ticket->close_date = time(); $ticket->save(); Event::run('argentum.ticket_close', $ticket); } Event::run('argentum.ticket_time', $time); url::redirect('ticket/'.($time->ticket->complete ? 'closed' : 'active').'/'.$time->ticket->project->id); } catch (Kohana_User_Exception $e) { $this->template->body = new View('admin/time/add'); $this->template->body->time = $time; $this->template->body->errors = $e; $this->template->body->set($this->input->post()); } } } /** * Deletes a time item for a ticket */ public function delete() { $time = new Time_Model($this->input->post('id')); $time->delete(); url::redirect('ticket/view/'.$time->ticket->id); } }
b'What is the value of (-6 - (-35 + 16)) + -7 + -4?\n'
b'What is the value of -5 - (-1 + (-3 - -6)) - (2 + -26)?\n'
<?php /** * This file is part of the Cubiche package. * * Copyright (c) Cubiche * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cubiche\Core\EventDispatcher; use Cubiche\Core\Bus\MessageInterface; /** * Event interface. * * @author Ivannis Suárez Jerez <[email protected]> */ interface EventInterface extends MessageInterface { /** * Stop event propagation. * * @return $this */ public function stopPropagation(); /** * Check whether propagation was stopped. * * @return bool */ public function isPropagationStopped(); /** * Get the event name. * * @return string */ public function eventName(); }
b'What is the value of (9 - 9) + 19 + -15?\n'
# Starter Web App This is my attempt to create a dev workflow which hot reloads client and server side changes. Note: This is still a work in progress ## Installation git clone xyz rm -rf .git npm install gulp (npm run dev) open http://localhost:3000 ## Deployment gulp bundle (npm run bundle) ## What do you get ## Configuration HOST_NAME - used when logging and sending stats to statsd. default is jonsmac STATSD_HOST - the ip address for the statsd server
package com.github.kwoin.kgate.core.sequencer; import com.github.kwoin.kgate.core.message.Message; import com.github.kwoin.kgate.core.session.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.SocketException; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; /** * @author P. WILLEMET */ public abstract class AbstractSequencer<T extends Message> implements Iterator<T> { private final Logger logger = LoggerFactory.getLogger(AbstractSequencer.class); protected Session<T> session; protected boolean hasNext; protected final ByteArrayOutputStream baos = new ByteArrayOutputStream(); protected @Nullable CountDownLatch oppositeSessionSignal; public void setSession(Session<T> session) { this.session = session; hasNext = !session.getInput().isInputShutdown(); } @Override public boolean hasNext() { hasNext &= !session.getInput().isClosed(); return hasNext; } @Override @Nullable public T next() { if(!hasNext()) throw new NoSuchElementException(); baos.reset(); if(oppositeSessionSignal != null) { try { oppositeSessionSignal.await(); } catch (InterruptedException e) { logger.warn("Waiting for opposite session signal interrupted"); oppositeSessionSignal = null; } } try { return readNextMessage(); } catch (SocketException e) { logger.debug("Input read() interrupted because socket has been closed"); hasNext = false; return null; } catch (IOException e) { logger.error("Unexpected error while reading next message", e); return null; } finally { resetState(); } } protected abstract T readNextMessage() throws IOException; protected abstract void resetState(); protected void waitForOppositeSessionSignal() { if(oppositeSessionSignal == null) { logger.debug("Wait for opposite session..."); oppositeSessionSignal = new CountDownLatch(1); } } public void oppositeSessionSignal() { if(oppositeSessionSignal != null) { logger.debug("wait for opposite session RELEASED"); oppositeSessionSignal.countDown(); } } protected byte readByte() throws IOException { int read = session.getInput().getInputStream().read(); baos.write(read); return (byte) read; } protected byte[] readBytes(int n) throws IOException { byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) bytes[i] = readByte(); return bytes; } protected byte[] readUntil(byte[] end, boolean withEnd) throws IOException { int read; int cursor = 0; ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); while(cursor < end.length) { read = readByte(); cursor = read == end[cursor] ? cursor + 1 : 0; tmpBaos.write(read); } byte[] bytes = tmpBaos.toByteArray(); return withEnd ? bytes : Arrays.copyOf(bytes, bytes.length - end.length); } }
/*The MIT License (MIT) Copyright (c) 2016 Muhammad Hammad 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 Sogiftware. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ package org.dvare.annotations; import org.dvare.expression.datatype.DataType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Type { DataType dataType(); }
> Link jsreport browser sdk into your page and easily render a report from the browser or open limited version of jsreport studio inside any web application and let end users to customize their reports. There are various scenarios where this can be used. Typical example can be when application is sending invoices to the customers and allows them to modify invoice template to the required design. ##Getting started To start using jsreport browser sdk you need to: 1. Include jquery into page 2. Include jsreport `embed.js` into page 3. Create `jsreportInit` function in the global scope with similar meaning as `$.ready` 4. Use global object `jsreport` to open editor or render a template ```html <!DOCTYPE html> <html> <head lang="en"> <!-- jquery is required for jsreport embedding --> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script src="http://local.net:2000/extension/embedding/public/js/embed.js"></script> </head> <body> <script> //jsreport will call jsreportInit function from global scope when its initialized jsreportInit = function () { //use jsreport object to render reports or open editor }; </script> </body> </html> ``` ##Rendering template Use `jsreport.render` function to invoke template server side rendering. Function takes a whole template json definition or just a string shortid as a parameter. The output report is opened in a new browser tab by default. This can be overridden by setting the first function parameter to jquery object placeholder. ```js //render a template into the new tab jsreport.render({ conent: "foo", recipe: "phantom-pdf", engine: "jsrender" }); //render a template into the placeholder jsreport.render($("#placeholder"), { conent: "foo", recipe: "phantom-pdf", engine: "jsrender" }); ``` ##Opening editor Use `jseport.openEditor` function to pop up jsreport designer in the modal. This functions takes a whole template definition or just a string shortid as a parameter. Function returns an even emitter to which you can bind and listen to `close` or `template-change` events. ```js jsreport.openEditor(template .on("template-change", function (tmpl) { //store changes template= tmpl; }).on("close", function() { //save template to your storage }); ``` You can also submit additional options for jsreport extensions like sample data or custom script in the `openEditor` parameters. ```js jsreport.openEditor({ content: "<h1>Hello World</h1>", data: { dataJson: { price: "1234" } } }); ``` Where `dataJson` can be any json object or parse-able json string. You can also set up a [custom script](/learn/scripts) to the report template loading input data for the report preview. Using custom scripts user can even specify desired input data source on its own. ###Using jsreport storage The jsreport designer is by default stateless and doesn't store the template in any storage. It is expected you listen to the emitted events and store the template in your own storage if you want. To enable storing templates in the jsreport storage just add `useStandardStorage` option when opening editor: ```js //open template from jsreport storage jsreport.openEditor("Z1vT7FHyU", { useStandardStorage: true }); ``` ## Security Using `embed.js` to render or edit templates is possible only when the browser get's access to the jsreport server. Exposing unsecured jsreport server to the public audience doesn't need to be a good idea for the internet applications. In this case you can secure jsreport and keep using `embed.js` using following approaches. One option is to use secure jsreport server using [authentication](/learn/authentication) and [authorization](/learn/authorization) extension to limit access to the jsreport. Anonymous user using `embed.js` can be then authorized using secure token generated by [public-templates](/learn/public-templates) extension. Another options is to create a tunnel forwarding request to jsreport through your application. This hides jsreport behind your security layers and also eliminates cross domain calls. You basically just need to catch and resend requests to jsreport and add `serverUrl` query parameter to specify where the jsreport web client should route requests back. In other words you create a route in your web server which will proxy jsreport server. Example of such a proxy in asp.net can be found [here](https://github.com/jsreport/net/blob/master/jsreport/jsreport.Client/JsReportWebHandler.cs). Implementing such a tunnel in any other language should not be difficult.
b'Evaluate (-68 - (-185 - -108)) + -1 + 9 + 1.\n'
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. /* * Copyright 2000-2010 JetBrains s.r.o. * * 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.microsoft.alm.plugin.idea.tfvc.ui; import com.google.common.annotations.VisibleForTesting; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.util.ui.AbstractTableCellEditor; import com.intellij.util.ui.CellEditorComponentWithBrowseButton; import com.microsoft.alm.plugin.context.ServerContext; import com.microsoft.alm.plugin.idea.common.resources.TfPluginBundle; import com.microsoft.alm.plugin.idea.common.utils.VcsHelper; import com.microsoft.alm.plugin.idea.tfvc.ui.servertree.ServerBrowserDialog; import org.apache.commons.lang.StringUtils; import javax.swing.JTable; import javax.swing.JTextField; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ServerPathCellEditor extends AbstractTableCellEditor { private final String title; private final Project project; private final ServerContext serverContext; private CellEditorComponentWithBrowseButton<JTextField> component; public ServerPathCellEditor(final String title, final Project project, final ServerContext serverContext) { this.title = title; this.project = project; this.serverContext = serverContext; } public Object getCellEditorValue() { return component.getChildComponent().getText(); } public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column) { final ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { createBrowserDialog(); } }; component = new CellEditorComponentWithBrowseButton<JTextField>(new TextFieldWithBrowseButton(listener), this); component.getChildComponent().setText((String) value); return component; } /** * Creates the browser dialog for file selection */ @VisibleForTesting protected void createBrowserDialog() { final String serverPath = getServerPath(); if (StringUtils.isNotEmpty(serverPath)) { final ServerBrowserDialog dialog = new ServerBrowserDialog(title, project, serverContext, serverPath, true, false); if (dialog.showAndGet()) { component.getChildComponent().setText(dialog.getSelectedPath()); } } else { Messages.showErrorDialog(project, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_MSG), TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_TITLE)); } } /** * Get a server path to pass into the dialog * * @return */ @VisibleForTesting protected String getServerPath() { String serverPath = (String) getCellEditorValue(); // if there is no entry in the cell to find the root server path with then find it from the server context if (StringUtils.isEmpty(serverPath) && serverContext != null && serverContext.getTeamProjectReference() != null) { serverPath = VcsHelper.TFVC_ROOT.concat(serverContext.getTeamProjectReference().getName()); } return serverPath; } }
'use babel'; import MapQueries from '../lib/map-queries'; // Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs. // // To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit` // or `fdescribe`). Remove the `f` to unfocus the block. describe('MapQueries', () => { let workspaceElement, activationPromise; beforeEach(() => { workspaceElement = atom.views.getView(atom.workspace); activationPromise = atom.packages.activatePackage('map-queries'); }); describe('when the map-queries:toggle event is triggered', () => { it('hides and shows the modal panel', () => { // Before the activation event the view is not on the DOM, and no panel // has been created expect(workspaceElement.querySelector('.map-queries')).not.toExist(); // This is an activation event, triggering it will cause the package to be // activated. atom.commands.dispatch(workspaceElement, 'map-queries:toggle'); waitsForPromise(() => { return activationPromise; }); runs(() => { expect(workspaceElement.querySelector('.map-queries')).toExist(); let mapQueriesElement = workspaceElement.querySelector('.map-queries'); expect(mapQueriesElement).toExist(); let mapQueriesPanel = atom.workspace.panelForItem(mapQueriesElement); expect(mapQueriesPanel.isVisible()).toBe(true); atom.commands.dispatch(workspaceElement, 'map-queries:toggle'); expect(mapQueriesPanel.isVisible()).toBe(false); }); }); it('hides and shows the view', () => { // This test shows you an integration test testing at the view level. // Attaching the workspaceElement to the DOM is required to allow the // `toBeVisible()` matchers to work. Anything testing visibility or focus // requires that the workspaceElement is on the DOM. Tests that attach the // workspaceElement to the DOM are generally slower than those off DOM. jasmine.attachToDOM(workspaceElement); expect(workspaceElement.querySelector('.map-queries')).not.toExist(); // This is an activation event, triggering it causes the package to be // activated. atom.commands.dispatch(workspaceElement, 'map-queries:toggle'); waitsForPromise(() => { return activationPromise; }); runs(() => { // Now we can test for view visibility let mapQueriesElement = workspaceElement.querySelector('.map-queries'); expect(mapQueriesElement).toBeVisible(); atom.commands.dispatch(workspaceElement, 'map-queries:toggle'); expect(mapQueriesElement).not.toBeVisible(); }); }); }); });
b'What is 4 + (-6 + -4 + 18 - (22 + -16))?\n'
export const browserVersions = () => { let u = navigator.userAgent return { // 移动终端浏览器版本信息 trident: u.indexOf('Trident') > -1, // IE内核 presto: u.indexOf('Presto') > -1, // opera内核 webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或者uc浏览器 iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, // 是否iPad webApp: u.indexOf('Safari') === -1 // 是否web应该程序,没有头部与底部 } }
b'What is -6 + 11 + 6 + (-3 - 9)?\n'
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_SUPPORT_STANDARD #define BOOST_SPIRIT_INCLUDE_SUPPORT_STANDARD #if defined(_MSC_VER) #pragma once #endif #include <lslboost/spirit/home/support/char_encoding/standard.hpp> #endif
b'22 + 5 + -17 + -13\n'
b'Calculate (-7 - (5 - (14 - 7))) + 5 - 3.\n'
b'1 + -3 + (3 - -6) - (-28 + 34)\n'
b'(10 - 5) + (-5 - -9 - 4)\n'
b'What is -8 + 1 + (-18 - -3) + 20?\n'
b'8 + (-1 - (11 - 3)) + 12\n'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleCiphers.Models { public static class ArrayOperations { // Содержится ли text в encAbc. Если да, то возвращаются индексы в encAbc // a b text = 1 // a 1 2 return x = 0, y = 0 // b 3 4 abc[0,0] = aa - расшифрованный // encAbc[0,0] = 1 - зашифрованный public static bool ContainsIn(string text, string[,] encAbc, out int x, out int y) { for (var i = 0; i < encAbc.GetLength(0); i++) { for (var j = 0; j < encAbc.GetLength(1); j++) { if (text != encAbc[i, j]) continue; x = i; y = j; return true; } } x = -1; y = -1; return false; } public static string[,] Turn1DTo2D(string[] encAbc) { var arr = new string[1, encAbc.Length]; for (var i = 0; i < encAbc.Length; i++) { arr[0, i] = $"{encAbc[i]}"; } return arr; } } }
doskey comit =python c:\Windows\ComIt\runWithoutRequests.py $*
b'Calculate -9 + -2 + 36 + -77 + 44.\n'
namespace UCloudSDK.Models { /// <summary> /// 获取流量信息 /// <para> /// http://docs.ucloud.cn/api/ucdn/get_ucdn_traffic.html /// </para> /// </summary> public partial class GetUcdnTrafficRequest { /// <summary> /// 默认Action名称 /// </summary> private string _action = "GetUcdnTraffic"; /// <summary> /// API名称 /// <para> /// GetUcdnTraffic /// </para> /// </summary> public string Action { get { return _action; } set { _action = value; } } /// <summary> /// None /// </summary> public string 不需要提供参数 { get; set; } } }
using System; using System.Collections.Generic; using Esb.Transport; namespace Esb.Message { public interface IMessageQueue { void Add(Envelope message); IEnumerable<Envelope> Messages { get; } Envelope GetNextMessage(); void SuspendMessages(Type messageType); void ResumeMessages(Type messageType); void RerouteMessages(Type messageType); void RemoveMessages(Type messageType); event EventHandler<EventArgs> OnMessageArived; IRouter Router { get; set; } } }
/* MIT License (From https://choosealicense.com/ ) Copyright (c) 2017 Jonathan Burget [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "TigerEngine.h" // Global variable so the objects are not lost static TIGValue *theNumberStack; static TIGValue *theStringStack; static int stackNumber; static char *stackString; // ************* For debugging Purposes ************* TIGValue *TIGStringNumberStack(void) { return theNumberStack; } TIGValue *TIGStringStringStack(void) { return theStringStack; } // ************* For debugging Purposes ************* void TIGStringStartStack(const char *startStackString) { // If there is another start stack called before the end stack free it if (stackString != NULL) { free(stackString); stackString = NULL; } if (startStackString == NULL) { stackNumber++; } else { stackString = (char *)malloc((strlen(startStackString) + 1) * sizeof(char)); if (startStackString != NULL) { strcpy(stackString, startStackString); } } } void TIGStringEndStack(const char *endStackString) { if (endStackString != NULL) { while (theStringStack != NULL) { TIGValue *theNextStack = theStringStack->nextStack; // 0 means both strings are the same if (strcmp(theStringStack->stackString, endStackString) == 0) { theStringStack = TIGStringDestroy(theStringStack); } theStringStack = theNextStack; } } else { while (theNumberStack != NULL) { TIGValue *theNextStack = theNumberStack->nextStack; if (theNumberStack->stackNumber == stackNumber) { theNumberStack = TIGStringDestroy(theNumberStack); } theNumberStack = theNextStack; } } // If there is another end or start stack string called before this end stack free it if (stackString != NULL) { free(stackString); stackString = NULL; } if (endStackString == NULL) { stackNumber--; } } TIGValue *TIGStringCreate(TIGValue *tigString, TIGBool useStack) { tigString = (TIGValue *)malloc(1 * sizeof(TIGValue)); if (tigString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringCreate() Variable:tigString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } if (useStack) { if (stackString != NULL) { if (theStringStack == NULL) { tigString->nextStack = NULL; } // Add the last added TIGString to the new tigString's ->nextStack else { tigString->nextStack = theStringStack; } tigString->stackNumber = -1; tigString->stackString = (char *)malloc((strlen(stackString) + 1) * sizeof(char)); if (tigString->stackString != NULL) { strcpy(tigString->stackString, stackString); } else { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringCreate() Variable:tigString->stackString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif } // This adds the new tigString to the global TIGString stack theStringStack = tigString; } else { if (theNumberStack == NULL) { tigString->nextStack = NULL; } // Add the last added TIGString to the new tigString's ->nextStack else { tigString->nextStack = theNumberStack; } tigString->stackNumber = stackNumber; tigString->stackString = NULL; // This adds the tigString to the global TIGString stack theNumberStack = tigString; } } else { tigString->nextStack = NULL; tigString->stackString = NULL; tigString->stackNumber = -2; } tigString->nextLevel = NULL; tigString->thisLevel = NULL; tigString->number = 0.0; // Sets the TIGObject's string to an empty string tigString->string = NULL; // object type tigString->type = "String"; return tigString; } TIGValue *TIGStringDestroy(TIGValue *tigString) { // If the "tigString" pointer has already been used free it if (tigString != NULL) { if (strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringDestroy() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return tigString; } if (tigString->string != NULL) { free(tigString->string); tigString->string = NULL; } if (tigString->stackString != NULL) { free(tigString->stackString); tigString->stackString = NULL; } tigString->number = 0.0; tigString->stackNumber = 0; tigString->type = NULL; tigString->nextStack = NULL; tigString->nextLevel = NULL; tigString->thisLevel = NULL; free(tigString); tigString = NULL; } return tigString; } TIGValue *TIGStr(const char *string) { return TIGStringInput(NULL, string); } TIGValue *TIGStringInput(TIGValue *tigString, const char *string) { return TIGStringStackInput(tigString, string, TIGYes); } TIGValue *TIGStringStackInput(TIGValue *tigString, const char *string, TIGBool useStack) { if (tigString == NULL) { tigString = TIGStringCreate(tigString, useStack); if (tigString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringStackInput() Variable:tigString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } } else if (strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringStackInput() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } // If there is already a string free it if (tigString->string != NULL) { free(tigString->string); tigString->string = NULL; } tigString->string = (char *)malloc((strlen(string) + 1) * sizeof(char)); if (tigString->string == NULL || string == NULL) { #ifdef TIG_DEBUG if (string == NULL) { printf("ERROR Function:TIGStringStackInput() Variable:string Equals:NULL\n"); } if (tigString->string == NULL) { printf("ERROR Function:TIGStringStackInput() Variable:tigString->string Equals:NULL\n"); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { strcpy(tigString->string, string); } return tigString; } char *TIGStringOutput(TIGValue *tigString) { if (tigString == NULL || tigString->string == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringOutput() Variable:tigString Equals:NULL\n"); } else { if (tigString->string == NULL) { printf("ERROR Function:TIGStringOutput() Variable:tigString->string Equals:NULL\n"); } if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringOutput() Variable:tigString->string Equals:%s Valid:\"String\"\n", tigString->type); } } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { return tigString->string; } } TIGInteger TIGStringLength(TIGValue *tigString) { if (tigString == NULL || tigString->string == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringLength() Variable:tigString Equals:NULL\n"); } else { if (tigString->string == NULL) { printf("ERROR Function:TIGStringLength() Variable:tigString->string Equals:NULL\n"); } if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringLength() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return -1; } //if (tigString != NULL && tigString->string != NULL && strcmp(tigString->type, "String") == 0) else { return (int)strlen(tigString->string); } } TIGValue *TIGStringInsertStringAtIndex(TIGValue *tigString1, TIGValue *tigString2, int index) { if (tigString1 == NULL || tigString2 == NULL || strcmp(tigString1->type, "String") != 0 || strcmp(tigString2->type, "String") != 0 || index < 0 || index > TIGStringLength(tigString1)) { #ifdef TIG_DEBUG if (tigString1 == NULL) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigString1 Equals:NULL\n"); } else if (strcmp(tigString1->type, "String") != 0) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigNumber Equals:%s Valid:\"String\"\n", tigString1->type); } if (tigString2 == NULL) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigString2 Equals:NULL\n"); } else if (strcmp(tigString2->type, "String") != 0) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:tigNumber Equals:%s Valid:\"String\"\n", tigString2->type); } if (index < 0 || index > TIGStringLength(tigString1)) { printf("ERROR Function:TIGStringInsertStringAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString1)); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *newString = (char *)malloc(strlen(tigString1->string) + strlen(tigString2->string) + 1); if (index == strlen(tigString1->string)) { strcat(newString, tigString1->string); strcat(newString, tigString2->string); } else { char character[2]; int i; for (i = 0; i < strlen(tigString1->string); i++) { character[0] = tigString1->string[i]; character[1] = '\0'; if (index == i) { strcat(newString, tigString2->string); } strcat(newString, character); } } TIGValue *theString = TIGStringInput(NULL, newString); free(newString); newString = NULL; return theString; } TIGValue *TIGStringCharacterAtIndex(TIGValue *tigString, int index) { if (tigString == NULL || index < 0 || index >= TIGStringLength(tigString)) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringCharacterAtIndex() Variable:tigString Equals:NULL\n"); } if (index < 0 || index >= TIGStringLength(tigString)) { printf("ERROR Function:TIGStringCharacterAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString) - 1); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *character = TIGStringOutput(tigString); return TIGStringWithFormat(NULL, "%c", character[index]); } void TIGStringRemoveCharacterAtIndex(TIGValue *tigString, int index) { if (tigString == NULL || index < 0 || index >= TIGStringLength(tigString)) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringRemoveCharacterAtIndex() Variable:tigString Equals:NULL\n"); } if (index < 0 || index >= TIGStringLength(tigString)) { printf("ERROR Function:TIGStringRemoveCharacterAtIndex() Variable:index Equals:%d Valid:0 to %d\n", index, TIGStringLength(tigString) - 1); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return; } int length = TIGStringLength(tigString); char *characters = TIGStringOutput(tigString); // Since a character is being removed don't add +1 to the malloc length char *newCharacters = (char *)malloc(length * sizeof(char)); int newIndex = 0; int i; for (i = 0; i < length; i++) { if (index != i) { newCharacters[newIndex] = characters[i]; newIndex++; } } TIGStringInput(tigString, newCharacters); free(newCharacters); newCharacters = NULL; } TIGValue *TIGStringFromNumber(TIGValue *tigNumber) { if (tigNumber == NULL || strcmp(tigNumber->type, "Number") != 0) { #ifdef TIG_DEBUG if (tigNumber == NULL) { printf("ERROR Function:TIGStringFromNumber() Variable:tigNumber Equals:NULL\n"); } else if (strcmp(tigNumber->type, "Number") != 0) { printf("ERROR Function:TIGStringFromNumber() Variable:tigNumber->type Equals:%s Valid:\"Number\"\n", tigNumber->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { int stringLength = snprintf( NULL, 0, "%f", tigNumber->number) + 1; char *stringBuffer = (char *)malloc(stringLength * sizeof(char)); if (stringBuffer == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringFromNumber() Variable:stringBuffer Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } snprintf(stringBuffer, stringLength, "%f", tigNumber->number); TIGValue *tigString = TIGStringInput(NULL, stringBuffer); free(stringBuffer); stringBuffer = NULL; return tigString; } } TIGBool TIGStringEqualsString(TIGValue *tigString1, TIGValue *tigString2) { if (tigString1 != NULL && strcmp(tigString1->type, "String") == 0 && tigString2 != NULL && strcmp(tigString2->type, "String") == 0 && strcmp(tigString1->string, tigString2->string) == 0) { return TIGYes; } return TIGNo; } TIGValue *TIGStringObjectType(TIGValue *tigObject) { if (tigObject == NULL || tigObject->type == NULL) { #ifdef TIG_DEBUG if (tigObject == NULL) { printf("ERROR Function:TIGStringObjectType() Variable:tigObject Equals:NULL\n"); } else if (tigObject->type == NULL) { printf("ERROR Function:TIGStringObjectType() Variable:tigObject->type Equals:NULL\n"); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } return TIGStringInput(NULL, tigObject->type); } TIGValue *TIGStringAddEscapeCharacters(TIGValue *tigString) { if (tigString == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *string = tigString->string; int extraCount = 0; int i; for (i = 0; i < strlen(string); i++) { switch (string[i]) { case '"': case '\\': case '/': case '\b': case '\f': case '\n': case '\r': case '\t': extraCount++; break; } } if (extraCount > 0) { char *newString = (char *)malloc((strlen(string) + extraCount + 1) * sizeof(char)); int index = 0; if (newString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringAddEscapeCharacters() Variable:newString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } for (i = 0; i < strlen(string); i++) { switch (string[i]) { case '\"': newString[index] = '\\'; newString[index + 1] = '"'; index += 2; break; case '\\': newString[index] = '\\'; newString[index + 1] = '\\'; index += 2; break; case '/': newString[index] = '\\'; newString[index + 1] = '/'; index += 2; break; case '\b': newString[index] = '\\'; newString[index + 1] = 'b'; index += 2; break; case '\f': newString[index] = '\\'; newString[index + 1] = 'f'; index += 2; break; case '\n': newString[index] = '\\'; newString[index + 1] = 'n'; index += 2; break; case '\r': newString[index] = '\\'; newString[index + 1] = 'r'; index += 2; break; case '\t': newString[index] = '\\'; newString[index + 1] = 't'; index += 2; break; default: newString[index] = string[i]; index++; break; } } TIGValue *theNewTIGString = TIGStringInput(NULL, newString); free(newString); newString = NULL; return theNewTIGString; } return tigString; } TIGValue *TIGStringRemoveEscapeCharacters(TIGValue *tigString) { if (tigString == NULL || strcmp(tigString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:tigObject->type Equals:%s Valid:\"String\"\n", tigString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } char *string = tigString->string; int extraCount = 0; int i; for (i = 0; i < strlen(string); i++) { if (string[i] == '\\') { switch (string[i + 1]) { case '"': case '\\': case '/': case 'b': case 'f': case 'n': case 'r': case 't': extraCount++; // Below makes sure it is not read as something like \\t instead of \\ and \t i++; break; } } } //printf("extraCount %d\n", extraCount); if (extraCount > 0) { char *newString = (char *)malloc(((strlen(string) - extraCount) + 1) * sizeof(char)); int index = 0; if (newString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringRemoveEscapeCharacters() Variable:newString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } for (i = 0; i < strlen(string); i++) { if (string[i] == '\\') { switch (string[i + 1]) { case '\"': newString[index] = '"'; index++; i++; break; case '\\': newString[index] = '\\'; index++; i++; break; case '/': newString[index] = '/'; index++; i++; break; case 'b': newString[index] = '\b'; index++; i++; break; case 'f': newString[index] = '\f'; index++; i++; break; case 'n': newString[index] = '\n'; index++; i++; break; case 'r': newString[index] = '\r'; index++; i++; break; case 't': newString[index] = '\t'; index++; i++; break; } } else { newString[index] = string[i]; index++; } } newString[index] = '\0'; TIGValue *theNewTIGString = TIGStringInput(NULL, newString); if (newString != NULL) { free(newString); newString = NULL; } return theNewTIGString; } return tigString; } TIGValue *TIGStringWithFormat(TIGValue *tigString, const char *format, ...) { va_list arguments; // Find out how long the string is when the arguments are converted to text va_start(arguments, format); int stringLength = vsnprintf( NULL, 0, format, arguments) + 1; va_end(arguments); // Create the new buffer with the new string length char *stringBuffer = (char *)malloc(stringLength * sizeof(char)); if (stringBuffer == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringWithFormat() Variable:stringBuffer Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } else { // Use the new length of text and add the arguments to the new string buffer va_start(arguments, format); vsnprintf(stringBuffer, stringLength, format, arguments); va_end(arguments); if (stringBuffer != NULL) { if (tigString == NULL) { tigString = TIGStringInput(tigString, stringBuffer); } else if (tigString->string != NULL && strcmp(tigString->type, "String") == 0) { //printf("Length: %d\n", (int)(strlen(tigString->string) + stringLength)); // stringLength already has +1 added to it for the '\0' so adding another +1 below is not necessary tigString->string = (char *)realloc(tigString->string, (strlen(tigString->string) + stringLength) * sizeof(char)); strcat(tigString->string, stringBuffer); } } else { #ifdef TIG_DEBUG if (tigString->string == NULL) { printf("ERROR Function:TIGStringWithFormat() Variable:tigString->string Equals:NULL\n"); } if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringWithFormat() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } free(stringBuffer); stringBuffer = NULL; } return tigString; } TIGValue *TIGStringWithAddedString(TIGValue *oldTigString, TIGValue *newTigString) { if (oldTigString == NULL || newTigString == NULL || oldTigString->string == NULL) { #ifdef TIG_DEBUG if (oldTigString == NULL) { printf("ERROR Function:TIGStringWithAddedString() Variable:oldTigString Equals:NULL\n"); } else if (oldTigString->string == NULL) { printf("ERROR Function:TIGStringWithAddedString() Variable:oldTigString->string Equals:NULL\n"); } if (newTigString == NULL) { printf("ERROR Function:TIGStringWithAddedString() Variable:newTigString Equals:NULL\n"); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } oldTigString = TIGStringInsertStringAtIndex(oldTigString, newTigString, (int)strlen(oldTigString->string)); return oldTigString; } TIGValue *TIGStringFromObject(TIGValue *tigObject) { if (tigObject == NULL || strcmp(tigObject->type, "Object") != 0) { #ifdef TIG_DEBUG if (tigObject == NULL) { printf("ERROR Function:TIGStringFromObject() Variable:tigObject Equals:NULL\n"); } else if (strcmp(tigObject->type, "Object") != 0) { printf("ERROR Function:TIGStringFromObject() Variable:tigObject->type Equals:%s Valid:\"Object\"\n", tigObject->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigObject, 1, TIGYes); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } TIGValue *TIGStringFromObjectForNetwork(TIGValue *tigObject) { if (tigObject == NULL || strcmp(tigObject->type, "Object") != 0) { #ifdef TIG_DEBUG if (tigObject == NULL) { printf("ERROR Function:TIGStringFromObjectForNetwork() Variable:tigObject Equals:NULL\n"); } else if (strcmp(tigObject->type, "Object") != 0) { printf("ERROR Function:TIGStringFromObjectForNetwork() Variable:tigObject->type Equals:%s Valid:\"Object\"\n", tigObject->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigObject, 1, TIGNo); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } TIGValue *TIGStringFromArray(TIGValue *tigArray) { if (tigArray == NULL || strcmp(tigArray->type, "Array") != 0) { #ifdef TIG_DEBUG if (tigArray == NULL) { printf("ERROR Function:TIGStringFromArray() Variable:tigArray Equals:NULL\n"); } else if (strcmp(tigArray->type, "Array") != 0) { printf("ERROR Function:TIGStringFromArray() Variable:tigArray->type Equals:%s Valid:\"Array\"\n", tigArray->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigArray, 1, TIGYes); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } TIGValue *TIGStringFromArrayForNetwork(TIGValue *tigArray) { if (tigArray == NULL || strcmp(tigArray->type, "Array") != 0) { #ifdef TIG_DEBUG if (tigArray == NULL) { printf("ERROR Function:TIGStringFromArrayForNetwork() Variable:tigArray Equals:NULL\n"); } else if (strcmp(tigArray->type, "Array") != 0) { printf("ERROR Function:TIGStringFromArrayForNetwork() Variable:tigArray->type Equals:%s Valid:\"Array\"\n", tigArray->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return NULL; } TIGObjectStartStack(NULL); TIGArrayStartStack(NULL); TIGNumberStartStack(NULL); TIGValue *theString = TIGStringFromObjectWithLevel(NULL, tigArray, 1, TIGNo); TIGNumberEndStack(NULL); TIGArrayEndStack(NULL); TIGObjectEndStack(NULL); return theString; } // The JSON string outputs a TIGString but the functions below have their own stack TIGValue *TIGStringFromObjectWithLevel(TIGValue *tigString, TIGValue *tigValue, int level, TIGBool useEscapeCharacters) { int i; if (strcmp(tigValue->type, "Array") == 0) { TIGValue *theTIGStringTabs = NULL; TIGValue *theTIGStringEndTab = NULL; if (useEscapeCharacters) { for (i = 0; i < level; i++) { theTIGStringTabs = TIGStringWithFormat(theTIGStringTabs, "\t"); if (i < level - 1) { theTIGStringEndTab = TIGStringWithFormat(theTIGStringEndTab, "\t"); } } tigString = TIGStringWithFormat(tigString, "[\n"); } else { tigString = TIGStringWithFormat(tigString, "["); } for (i = 0; i < TIGArrayCount(tigValue); i++) { TIGValue *theTIGValue = TIGArrayValueAtIndex(tigValue, i); if (useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringTabs); } tigString = TIGStringFromObjectWithLevel(tigString, theTIGValue, level + 1, useEscapeCharacters); if (useEscapeCharacters) { if (i < TIGArrayCount(tigValue) - 1) { tigString = TIGStringWithFormat(tigString, ",\n"); } else { tigString = TIGStringWithFormat(tigString, "\n"); } } else { if (i < TIGArrayCount(tigValue) - 1) { tigString = TIGStringWithFormat(tigString, ","); } } } if (level > 1 && useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringEndTab); } tigString = TIGStringWithFormat(tigString, "]"); } else if (strcmp(tigValue->type, "Number") == 0) { if (tigValue->string != NULL) { if (strcmp(tigValue->string, "false") == 0 || strcmp(tigValue->string, "true") == 0) { tigString = TIGStringWithAddedString(tigString, TIGStringInput(NULL, tigValue->string)); } } else { tigString = TIGStringWithAddedString(tigString, TIGStringFromNumber(tigValue)); } } else if (strcmp(tigValue->type, "Object") == 0) { TIGValue *theTIGArrayStrings = TIGArrayOfObjectStrings(tigValue); TIGValue *theTIGArrayValues = TIGArrayOfObjectValues(tigValue); TIGValue *theTIGStringTabs = NULL; TIGValue *theTIGStringEndTab = NULL; if (useEscapeCharacters) { for (i = 0; i < level; i++) { theTIGStringTabs = TIGStringWithFormat(theTIGStringTabs, "\t"); if (i < level - 1) { theTIGStringEndTab = TIGStringWithFormat(theTIGStringEndTab, "\t"); } } tigString = TIGStringWithFormat(tigString, "{\n"); } else { tigString = TIGStringWithFormat(tigString, "{"); } for (i = 0; i < TIGArrayCount(theTIGArrayStrings); i++) { TIGValue *theTIGString = TIGArrayValueAtIndex(theTIGArrayStrings, i); TIGValue *theTIGValue = TIGArrayValueAtIndex(theTIGArrayValues, i); if (useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringTabs); tigString = TIGStringWithFormat(tigString, "\"%s\": ", TIGStringOutput(TIGStringAddEscapeCharacters(theTIGString))); } else { tigString = TIGStringWithFormat(tigString, "\"%s\":", TIGStringOutput(TIGStringAddEscapeCharacters(theTIGString))); } tigString = TIGStringFromObjectWithLevel(tigString, theTIGValue, level + 1, useEscapeCharacters); if (useEscapeCharacters) { if (i < TIGArrayCount(theTIGArrayStrings) - 1) { tigString = TIGStringWithFormat(tigString, ",\n"); } else { tigString = TIGStringWithFormat(tigString, "\n"); } } else { if (i < TIGArrayCount(theTIGArrayStrings) - 1) { tigString = TIGStringWithFormat(tigString, ","); } } } if (level > 1 && useEscapeCharacters) { tigString = TIGStringWithAddedString(tigString, theTIGStringEndTab); } tigString = TIGStringWithFormat(tigString, "}"); } else if (strcmp(tigValue->type, "String") == 0) { tigString = TIGStringWithFormat(tigString, "\"%s\"", TIGStringOutput(TIGStringAddEscapeCharacters(tigValue))); } return tigString; } void TIGStringWriteWithFilename(TIGValue *tigString, TIGValue *filenameString) { if (tigString == NULL || filenameString == NULL || strcmp(tigString->type, "String") != 0 || strcmp(filenameString->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } if (filenameString == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString Equals:NULL\n"); } else if (strcmp(filenameString->type, "String") != 0) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->type Equals:%s Valid:\"String\"\n", filenameString->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif } else { FILE *theFile = fopen(filenameString->string, "w"); if (theFile != NULL) { fprintf(theFile, "%s", tigString->string); } else { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringWriteWithFilename() Variable:theFile Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif } fclose(theFile); } } TIGValue *TIGStringReadFromFilename(TIGValue *filenameString) { if (filenameString == NULL || filenameString->string == NULL || strcmp(filenameString->type, "String") != 0) { if (filenameString == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:tigString Equals:NULL\n"); } else { if (strcmp(filenameString->type, "String") != 0) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->type Equals:%s Valid:\"String\"\n", filenameString->type); } if (filenameString->string == NULL) { printf("ERROR Function:TIGStringWriteWithFilename() Variable:filenameString->string Equals:NULL\n"); } } return NULL; } FILE *theFile = fopen(filenameString->string, "r"); int index = 0, block = 1, maxBlockLength = 100; char *newString = NULL; char *buffer = malloc(maxBlockLength * sizeof(char)); if (theFile == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringReadFromFilename() Variable:theFile Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif if (buffer != NULL) { free(buffer); buffer = NULL; } fclose(theFile); return NULL; } if (buffer == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringReadFromFilename() Variable:buffer Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif fclose(theFile); return NULL; } while (1) { buffer[index] = fgetc(theFile); if ((buffer[index] != EOF && index >= maxBlockLength - 2) || buffer[index] == EOF) { int stringLength; buffer[index + 1] = '\0'; if (newString == NULL) { stringLength = 0; } else { stringLength = (int)strlen(newString); } if (buffer[index] == EOF) { //printf("END Buffer: %d String Length: %d\n", (int)strlen(buffer), stringLength); // Since the "buffer" variable already has '\0' +1 is not needed newString = realloc(newString, (strlen(buffer) + stringLength) * sizeof(char)); } else { //printf("Buffer: %d String Length: %d\n", (int)strlen(buffer), stringLength); newString = realloc(newString, (strlen(buffer) + stringLength) * sizeof(char)); } if (newString == NULL) { #ifdef TIG_DEBUG printf("ERROR Function:TIGStringReadFromFilename() Variable:newString Equals:NULL\n"); #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif free(buffer); buffer = NULL; fclose(theFile); return NULL; } strcat(newString, buffer); if (buffer[index] == EOF) { //printf("Total String Length: %d", (int)strlen(newString)); // Since the "buffer" always uses the same size block '\0' with -1 is needed for the last index number newString[strlen(newString) - 1] = '\0'; free(buffer); buffer = NULL; break; } else { free(buffer); buffer = NULL; buffer = malloc(maxBlockLength * sizeof(char)); index = -1; block++; } } index++; } fclose(theFile); TIGValue *theString = TIGStringInput(NULL, newString); free(newString); newString = NULL; return theString; } TIGBool TIGStringPrefix(TIGValue *tigString, TIGValue *tigStringPrefix) { if (tigString == NULL || strcmp(tigString->type, "String") != 0 || tigStringPrefix == NULL || strcmp(tigStringPrefix->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringPrefix() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringPrefix() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } if (tigStringPrefix == NULL) { printf("ERROR Function:TIGStringPrefix() Variable:tigStringPrefix Equals:NULL\n"); } else if (strcmp(tigStringPrefix->type, "String") != 0) { printf("ERROR Function:TIGStringPrefix() Variable:tigStringPrefix->type Equals:%s Valid:\"String\"\n", tigStringPrefix->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return TIGNo; } if (strlen(tigString->string) > 0 && strlen(tigStringPrefix->string) > 0) { int i; for (i = 0; i < strlen(tigString->string); i++) { if (tigString->string[i] == tigStringPrefix->string[i]) { // The prefix has been found if (i >= strlen(tigStringPrefix->string) - 1) { return TIGYes; } } else { return TIGNo; } } } return TIGNo; } TIGBool TIGStringSuffix(TIGValue *tigString, TIGValue *tigStringSuffix) { if (tigString == NULL || strcmp(tigString->type, "String") != 0 || tigStringSuffix == NULL || strcmp(tigStringSuffix->type, "String") != 0) { #ifdef TIG_DEBUG if (tigString == NULL) { printf("ERROR Function:TIGStringSuffix() Variable:tigString Equals:NULL\n"); } else if (strcmp(tigString->type, "String") != 0) { printf("ERROR Function:TIGStringSuffix() Variable:tigString->type Equals:%s Valid:\"String\"\n", tigString->type); } if (tigStringSuffix == NULL) { printf("ERROR Function:TIGStringSuffix() Variable:tigStringSuffix Equals:NULL\n"); } else if (strcmp(tigStringSuffix->type, "String") != 0) { printf("ERROR Function:TIGStringSuffix() Variable:tigStringSuffix->type Equals:%s Valid:\"String\"\n", tigStringSuffix->type); } #ifdef TIG_DEBUG_ASSERT assert(0); #endif #endif return TIGNo; } if (strlen(tigString->string) > 0 && strlen(tigStringSuffix->string) > 0) { int suffixIndex = 0, suffixTotal = (int)strlen(tigStringSuffix->string), index = 0, total = (int)strlen(tigString->string); while (1) { if (tigString->string[total - index - 1] == tigStringSuffix->string[suffixTotal - suffixIndex - 1]) { // The suffix was found if (suffixIndex >= suffixTotal - 1) { return TIGYes; } suffixIndex++; index++; } else { return TIGNo; } } } return TIGNo; }
<?php namespace Faker\Provider\fa_IR; class PhoneNumber extends \Faker\Provider\PhoneNumber { /** * @link https://fa.wikipedia.org/wiki/%D8%B4%D9%85%D8%A7%D8%B1%D9%87%E2%80%8C%D9%87%D8%A7%DB%8C_%D8%AA%D9%84%D9%81%D9%86_%D8%AF%D8%B1_%D8%A7%DB%8C%D8%B1%D8%A7%D9%86#.D8.AA.D9.84.D9.81.D9.86.E2.80.8C.D9.87.D8.A7.DB.8C_.D9.87.D9.85.D8.B1.D8.A7.D9.87 */ protected static $formats = array( // land line formts seprated by province "011########", //Mazandaran "013########", //Gilan "017########", //Golestan "021########", //Tehran "023########", //Semnan "024########", //Zanjan "025########", //Qom "026########", //Alborz "028########", //Qazvin "031########", //Isfahan "034########", //Kerman "035########", //Yazd "038########", //Chaharmahal and Bakhtiari "041########", //East Azerbaijan "044########", //West Azerbaijan "045########", //Ardabil "051########", //Razavi Khorasan "054########", //Sistan and Baluchestan "056########", //South Khorasan "058########", //North Khorasan "061########", //Khuzestan "066########", //Lorestan "071########", //Fars "074########", //Kohgiluyeh and Boyer-Ahmad "076########", //Hormozgan "077########", //Bushehr "081########", //Hamadan "083########", //Kermanshah "084########", //Ilam "086########", //Markazi "087########", //Kurdistan ); protected static $mobileNumberPrefixes = array( '0910#######',//mci '0911#######', '0912#######', '0913#######', '0914#######', '0915#######', '0916#######', '0917#######', '0918#######', '0919#######', '0901#######', '0901#######', '0902#######', '0903#######', '0930#######', '0933#######', '0935#######', '0936#######', '0937#######', '0938#######', '0939#######', '0920#######', '0921#######', '0937#######', '0990#######', // MCI ); public static function mobileNumber() { return static::numerify(static::randomElement(static::$mobileNumberPrefixes)); } }
<?php /* TwigBundle:Exception:traces.html.twig */ class __TwigTemplate_034400bfb816a72b7b3da36dd2d8e07ee89621bac614688be25a4e8ff872b3ad extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div class=\"block\"> "; // line 2 if (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) > 0)) { // line 3 echo " <h2> <span><small>["; // line 4 echo twig_escape_filter($this->env, (((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) - (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position"))) + 1), "html", null, true); echo "/"; echo twig_escape_filter($this->env, ((isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")) + 1), "html", null, true); echo "]</small></span> "; // line 5 echo $this->env->getExtension('code')->abbrClass($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "class", array())); echo ": "; echo $this->env->getExtension('code')->formatFileFromText(nl2br(twig_escape_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "message", array()), "html", null, true))); echo "&nbsp; "; // line 6 ob_start(); // line 7 echo " <a href=\"#\" onclick=\"toggle('traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "', 'traces'); switchIcons('icon-traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-open', 'icon-traces-"; echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-close'); return false;\"> <img class=\"toggle\" id=\"icon-traces-"; // line 8 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("inline") : ("none")); echo "\" /> <img class=\"toggle\" id=\"icon-traces-"; // line 9 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("none") : ("inline")); echo "\" /> </a> "; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); // line 12 echo " </h2> "; } else { // line 14 echo " <h2>Stack Trace</h2> "; } // line 16 echo " <a id=\"traces-link-"; // line 17 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "\"></a> <ol class=\"traces list-exception\" id=\"traces-"; // line 18 echo twig_escape_filter($this->env, (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "html", null, true); echo "\" style=\"display: "; echo (((0 == (isset($context["count"]) ? $context["count"] : $this->getContext($context, "count")))) ? ("block") : ("none")); echo "\"> "; // line 19 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array())); foreach ($context['_seq'] as $context["i"] => $context["trace"]) { // line 20 echo " <li> "; // line 21 $this->loadTemplate("TwigBundle:Exception:trace.html.twig", "TwigBundle:Exception:traces.html.twig", 21)->display(array("prefix" => (isset($context["position"]) ? $context["position"] : $this->getContext($context, "position")), "i" => $context["i"], "trace" => $context["trace"])); // line 22 echo " </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['i'], $context['trace'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 24 echo " </ol> </div> "; } public function getTemplateName() { return "TwigBundle:Exception:traces.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 101 => 24, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 7, 39 => 6, 33 => 5, 27 => 4, 24 => 3, 22 => 2, 19 => 1,); } } /* <div class="block">*/ /* {% if count > 0 %}*/ /* <h2>*/ /* <span><small>[{{ count - position + 1 }}/{{ count + 1 }}]</small></span>*/ /* {{ exception.class|abbr_class }}: {{ exception.message|nl2br|format_file_from_text }}&nbsp;*/ /* {% spaceless %}*/ /* <a href="#" onclick="toggle('traces-{{ position }}', 'traces'); switchIcons('icon-traces-{{ position }}-open', 'icon-traces-{{ position }}-close'); return false;">*/ /* <img class="toggle" id="icon-traces-{{ position }}-close" alt="-" src="data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=" style="display: {{ 0 == count ? 'inline' : 'none' }}" />*/ /* <img class="toggle" id="icon-traces-{{ position }}-open" alt="+" src="data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7" style="display: {{ 0 == count ? 'none' : 'inline' }}" />*/ /* </a>*/ /* {% endspaceless %}*/ /* </h2>*/ /* {% else %}*/ /* <h2>Stack Trace</h2>*/ /* {% endif %}*/ /* */ /* <a id="traces-link-{{ position }}"></a>*/ /* <ol class="traces list-exception" id="traces-{{ position }}" style="display: {{ 0 == count ? 'block' : 'none' }}">*/ /* {% for i, trace in exception.trace %}*/ /* <li>*/ /* {% include 'TwigBundle:Exception:trace.html.twig' with { 'prefix': position, 'i': i, 'trace': trace } only %}*/ /* </li>*/ /* {% endfor %}*/ /* </ol>*/ /* </div>*/ /* */
b'(10 - 1) + (17 - 19 - (3 - -1))\n'
b'-24 + (-2 - -13) + (-9 - -5)\n'
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2019_11_01 module Models # # Properties of the Radius client root certificate of # VpnServerConfiguration. # class VpnServerConfigRadiusClientRootCertificate include MsRestAzure # @return [String] The certificate name. attr_accessor :name # @return [String] The Radius client root certificate thumbprint. attr_accessor :thumbprint # # Mapper for VpnServerConfigRadiusClientRootCertificate class as Ruby # Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'VpnServerConfigRadiusClientRootCertificate', type: { name: 'Composite', class_name: 'VpnServerConfigRadiusClientRootCertificate', model_properties: { name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, thumbprint: { client_side_validation: true, required: false, serialized_name: 'thumbprint', type: { name: 'String' } } } } } end end end end
b'Calculate (-1 - -14 - 2) + (54 + -24 - 34).\n'
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Gama.Atenciones.Wpf.Views { /// <summary> /// Interaction logic for SearchBoxView.xaml /// </summary> public partial class SearchBoxView : UserControl { public SearchBoxView() { InitializeComponent(); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> const importObject = Object.freeze({ env: { __memory_base: 0, __table_base: 0, memory: new WebAssembly.Memory({ initial: 1, // 64KiB - single page maximum: 10 // 640KiB }), table: new WebAssembly.Table({ // Table initial: 0, // length element: 'anyfunc' }) } }); // 1st option ----------------------- const loadWASM = (url, importObject) => fetch(url) .then(response => response.arrayBuffer()) .then(buffer => WebAssembly .instantiate(buffer, importObject) ) .then(results => results.instance); loadWASM('sum.wasm', importObject).then(instance => { const {exports} = instance; const result = exports._sum(40, 2); console.log({instance, result}); }); // 2d option ------------------------ const loadWASM2 = async (url, importObject) => { const buffer = await fetch(url).then(r => r.arrayBuffer()); const result = await WebAssembly.instantiate(buffer, importObject); return result.instance; }; loadWASM2('sum.wasm', importObject).then(instance => { const {exports} = instance; const result = exports._sum(40, 2); console.log({instance, result}); }); // 3d way, disabled because: // RangeError: WebAssembly.Instance is disallowed on the main thread, if the buffer size is larger than 4KB. Use WebAssembly.instantiate. // Note: To generate fib-module with html example smaller than 11kb, use option -g2 instead of -g4 // const loadWASM3 = (url, importObject) => fetch(url) // .then(response => response.arrayBuffer()) // .then(buffer => WebAssembly.compile(buffer)) // .then(module => new WebAssembly.Instance(module, importObject)); // loadWASM3('sum.wasm', importObject).then(instance => { // const {exports} = instance; // const result = exports._sum(40, 2); // console.log({ // instance, // result // }); // }); </script> </body> </html>
b'(-34 + 25 - 23) + 38\n'
import { stringify } from 'qs' import _request from '@/utils/request' import mini from '@/utils/mini' import env from '@/config/env' // import { modelApis, commonParams } from './model' // import { version } from '../package.json' let apiBaseUrl apiBaseUrl = `${env.apiBaseUrl}` const regHttp = /^https?/i const isMock = true; // const regMock = /^mock?/i function compact(obj) { for (const key in obj) { if (!obj[key]) { delete obj[key] } } return obj } function request(url, options, success, fail) { const originUrl = regHttp.test(url) ? url : `${apiBaseUrl}${url}` return _request(originUrl, compact(options), success, fail) } /** * API 命名规则 * - 使用 camelCase 命名格式(小驼峰命名) * - 命名尽量对应 RESTful 风格,`${动作}${资源}` * - 假数据增加 fake 前缀 * - 便捷易用大于规则,程序是给人看的 */ // api 列表 const modelApis = { // 初始化配置 test: 'https://easy-mock.com/mock/5aa79bf26701e17a67bde1d7/', getConfig: '/common/initconfig', getWxSign: '/common/getwxsign', // 积分兑换 getPointIndex: '/point/index', getPointList: '/point/skulist', getPointDetail: '/point/iteminfo', getPointDetaiMore: '/product/productdetail', getRList: '/point/recommenditems', // 专题 getPointTopicInfo: '/point/topicinfo', getPointTopicList: '/point/topicbuskulist', // 主站专题 getTopicInfo: '/product/topicskusinfo', getTopicList: '/product/topicskulist', // 个人中心 getProfile: '/user/usercenter', // 拼团相关 getCoupleList: '/product/coupleskulist', getCoupleDetail: '/product/coupleskudetail', getMerchantList: '/merchant/coupleskulist', coupleOrderInit: 'POST /order/coupleorderinit', coupleOrderList: '/user/usercouplelist', coupleOrderDetail: '/user/usercoupleorderdetail', coupleUserList: '/market/pinactivitiesuserlist', // 分享页拼团头像列表 coupleShareDetail: '/user/coupleactivitiedetail', // 分享详情 // 首页 getIndex: '/common/index', getIndexNew: '/common/index_v1', getHotSearch: '/common/hotsearchsug', // 主流程 orderInit: 'POST /order/orderinit', orderSubmit: 'POST /order/submitorder', orderPay: 'POST /order/orderpay', orderPayConfirm: '/order/orderpayconfirm', // 确认支付状态 getUserOrders: '/order/getuserorders', // 订单列表 getNeedCommentOrders: '/order/waitcommentlist', // 待评论 getUserRefundorders: '/order/userrefundorder', // 退款 getUserServiceOrders: '/order/userserviceorders', // 售后 orderCancel: 'POST /order/cancelorder', // 取消订单 orderDetail: '/order/orderdetail', confirmReceived: 'POST /order/userorderconfirm', // 确认收货 orderComplaint: 'POST /refund/complaint', // 订单申诉 // 积分订单相关 pointOrderInit: 'POST /tradecenter/pointorderpreview', pointOrderSubmit: 'POST /tradecenter/pointordersubmit', pointOrderCancel: 'POST /tradecenter/ordercancel', pointOrderList: '/tradecenter/orderlist', pointOrderDetail: '/tradecenter/orderinfo', pointOrderSuccess: '/tradecenter/ordersuccess', // 退款相关 refundInit: '/refund/init', refundDetail: '/refund/detail', refundApply: 'POST /refund/apply', // 登录注销 login: 'POST /user/login', logout: 'POST /user/logout', // 地址管理 addressList: '/user/addresslist', addAddress: 'POST /user/addaddress', updateAddress: 'POST /user/updateaddress', setDefaultAddress: 'POST /user/setdefaultaddress', deleteAddress: 'POST /user/deleteaddress', provinceList: '/nation/provincelist', cityList: '/nation/citylist', districtList: '/nation/districtlist', // 查看物流 getDelivery: '/order/deliverymessage', // 获取七牛 token getQiniuToken: '/common/qiniutoken', } // 仅限本地调试支持 // if (__DEV__ && env.mock) { if (__DEV__ && isMock) { apiBaseUrl = `${env.apiMockUrl}` // Object.assign(modelApis, require('../mock')) } // 线上代理 if (__DEV__ && env.proxy) { const proxyUrl = '/proxy' apiBaseUrl = `${env.origin}${proxyUrl}` } const { width, height, } = window.screen // 公共参数 const commonParams = { uuid: '', // 用户唯一标志 udid: '', // 设备唯一标志 device: '', // 设备 net: '', // 网络 uid: '', token: '', timestamp: '', // 时间 channel: 'h5', // 渠道 spm: 'h5', v: env.version, // 系统版本 terminal: env.terminal, // 终端 swidth: width, // 屏幕宽度 分辨率 sheight: height, // 屏幕高度 location: '', // 地理位置 zoneId: 857, // 必须 } // console.log(Object.keys(modelApis)) const apiList = Object.keys(modelApis).reduce((api, key) => { const val = modelApis[key] const [url, methodType = 'GET'] = val.split(/\s+/).reverse() const method = methodType.toUpperCase() // let originUrl = regHttp.test(url) ? url : `${env.apiBaseUrl}${url}`; // NOTE: headers 在此处设置? // if (__DEV__ && regLocalMock.test(url)) { // api[key] = function postRequest(params, success, fail) { // const res = require(`../${url}.json`) // mini.hideLoading() // res.errno === 0 ? success(res) : fail(res) // } // return api // } switch (method) { case 'POST': // originUrl = `${originUrl}`; api[key] = function postRequest(params, success, fail) { return request(url, { headers: { // Accept: 'application/json', // 我们的 post 请求,使用的这个,不是 application/json // 'Content-Type': 'application/x-www-form-urlencoded', }, method, data: compact(Object.assign({}, getCommonParams(), params)), }, success, fail) } break case 'GET': default: api[key] = function getRequest(params, success, fail) { params = compact(Object.assign({}, getCommonParams(), params)) let query = stringify(params) if (query) query = `?${query}` return request(`${url}${query}`, {}, success, fail) } break } return api }, {}) function setCommonParams(params) { return Object.assign(commonParams, params) } function getCommonParams(key) { return key ? commonParams[key] : { // ...commonParams, } } apiList.getCommonParams = getCommonParams apiList.setCommonParams = setCommonParams // console.log(apiList) export default apiList
b'What is the value of 3 - ((-1 + -4 - -10) + (-10 - 0))?\n'
b'Evaluate -7 + 6 + 5 + (-10 + 8 - 0).\n'