repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
sharidas/core
lib/l10n/sv.js
14303
OC.L10N.register( "lib", { "Cannot write into \"config\" directory!" : "Kan inte skriva till \"config\" katalogen!", "This can usually be fixed by giving the webserver write access to the config directory" : "Detta kan vanligtvis åtgärdas genom att ge skrivrättigheter till config katalgogen", "See %s" : "Se %s", "This can usually be fixed by %sgiving the webserver write access to the config directory%s." : "Detta kan vanligtvis åtgärdas genom att %s ger webbservern skrivrättigheter till konfigurations-katalogen %s.", "Sample configuration detected" : "Exempel-konfiguration detekterad", "It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php" : "Det har detekterats att exempel-konfigurationen har kopierats. Detta kan förstöra din installation och stöds ej. Vänligen läs dokumentationen innan ändringar på config.php utförs", "PHP %s or higher is required." : "PHP %s eller högre krävs.", "PHP with a version lower than %s is required." : "PHP med version lägre än %s krävs.", "%sbit or higher PHP required." : "%sbit eller nyare PHP krävs.", "Following databases are supported: %s" : "Följande databastyper stödjs: %s", "The command line tool %s could not be found" : "Kommandoradsverktyget %s hittades inte.", "The library %s is not available." : "Biblioteket %s är inte tillgängligt.", "Library %s with a version higher than %s is required - available version %s." : "Bibliotek %s med version högre än %s krävs - tillgänglig version %s.", "Library %s with a version lower than %s is required - available version %s." : "Bibliotek %s med version lägre än %s krävs - tillgänglig version %s.", "Following platforms are supported: %s" : "Följande plattformar stödjs: %s", "ownCloud %s or higher is required." : "ownCloud %s eller högre krävs.", "ownCloud %s or lower is required." : "ownCloud %s eller lägre krävs.", "Unknown filetype" : "Okänd filtyp", "Invalid image" : "Ogiltig bild", "today" : "i dag", "yesterday" : "i går", "_%n day ago_::_%n days ago_" : ["%n dag sedan","%n dagar sedan"], "last month" : "förra månaden", "_%n month ago_::_%n months ago_" : ["%n månad sedan","%n månader sedan"], "last year" : "förra året", "_%n year ago_::_%n years ago_" : ["%n år sedan","%n år sedan"], "_%n hour ago_::_%n hours ago_" : ["%n timme sedan","%n timmar sedan"], "_%n minute ago_::_%n minutes ago_" : ["%n minut sedan","%n minuter sedan"], "seconds ago" : "sekunder sedan", "Builtin" : "Inbyggt", "None" : "Ingen", "Username and password" : "Användarnamn och lösenord", "Username" : "Användarnamn", "Password" : "Lösenord", "Log-in credentials, save in session" : "Inloggninguppgifter, spara i sessionen", "Empty filename is not allowed" : "Tomt filnamn är inte tillåtet", "Dot files are not allowed" : "Punkt-filer är inte tillåtna", "4-byte characters are not supported in file names" : "4-bytestecken stöds inte i filnamn", "File name is a reserved word" : "Filnamnet är ett reserverat ord", "File name contains at least one invalid character" : "Filnamnet innehåller minst ett ogiltigt tecken", "File name is too long" : "Filnamnet är för långt", "App directory already exists" : "Appens mapp finns redan", "Can't create app folder. Please fix permissions. %s" : "Kan inte skapa appens mapp. Var god åtgärda rättigheterna. %s", "Archive does not contain a directory named %s" : "Arkivet innehåller inte en mapp som heter %s", "No source specified when installing app" : "Ingen källa angiven vid installation av app ", "No href specified when installing app from http" : "Ingen href angiven vid installation av app från http", "No path specified when installing app from local file" : "Ingen sökväg angiven vid installation av app från lokal fil", "Archives of type %s are not supported" : "Arkiv av typen %s stöds ej", "Failed to open archive when installing app" : "Kunde inte öppna arkivet när appen skulle installeras", "App does not provide an info.xml file" : "Appen har ingen info.xml fil", "App cannot be installed because appinfo file cannot be read." : "Appen kunde inte installeras för att filen appinfo inte kunde läsas.", "Signature could not get checked. Please contact the app developer and check your admin screen." : "Signaturen kunde inte kontrolleras. Vänligen kontakta apputvecklaren och kontrollera din adminskärm.", "App can't be installed because of not allowed code in the App" : "Appen kan inte installeras eftersom att den innehåller otillåten kod", "App can't be installed because it is not compatible with this version of ownCloud" : "Appen kan inte installeras eftersom att den inte är kompatibel med denna version av ownCloud", "App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps" : "Appen kan inte installeras eftersom att den innehåller etiketten <shipped>true</shipped> vilket inte är tillåtet för icke inkluderade appar", "App can't be installed because the version in info.xml is not the same as the version reported from the app store" : "Appen kunde inte installeras eftersom versionen i info.xml inte är samma som versionen som rapporteras från appstore", "General" : "Allmänt", "Storage" : "Lagring", "Security" : "Säkerhet", "Authentication" : "Autentisering", "Encryption" : "Kryptering", "Sharing" : "Dela", "Apps" : "Program", "Updates" : "Uppdateringar", "%s enter the database username." : "%s ange databasanvändare.", "%s enter the database name." : "%s ange databasnamn", "%s you may not use dots in the database name" : "%s du får inte använda punkter i databasnamnet", "Oracle connection could not be established" : "Oracle-anslutning kunde inte etableras", "Oracle username and/or password not valid" : "Oracle-användarnamnet och/eller lösenordet är felaktigt", "DB Error: \"%s\"" : "DB fel: \"%s\"", "Offending command was: \"%s\"" : "Det felaktiga kommandot var: \"%s\"", "You need to enter either an existing account or the administrator." : "Du måste antingen ange ett befintligt konto eller administratör.", "Offending command was: \"%s\", name: %s, password: %s" : "Det felande kommandot var: \"%s\", name: %s, password: %s", "PostgreSQL username and/or password not valid" : "PostgreSQL-användarnamnet och/eller lösenordet är felaktigt", "Mac OS X is not supported and %s will not work properly on this platform. Use it at your own risk! " : "Mac OS X stöds inte och %s kommer inte att fungera korrekt på denna plattform. Använd på egen risk!", "For the best results, please consider using a GNU/Linux server instead." : "För bästa resultat, överväg att använda en GNU/Linux server istället.", "Set an admin username." : "Ange ett användarnamn för administratören.", "Set an admin password." : "Ange ett administratörslösenord.", "Can't create or write into the data directory %s" : "Kan inte skapa eller skriva till data-katalogen %s", "Invalid Federated Cloud ID" : "Ogiltigt \"Federated Cloud\"-ID", "%s shared »%s« with you" : "%s delade »%s« med dig", "Sharing %s failed, because the backend does not allow shares from type %i" : "Misslyckades dela ut %s då backend inte tillåter delningar från typ %i", "Sharing %s failed, because the file does not exist" : "Delning av %s misslyckades på grund av att filen inte existerar", "You are not allowed to share %s" : "Du har inte rätt att dela %s", "Sharing %s failed, because the user %s does not exist" : "Delning %s misslyckades därför att användaren %s inte existerar", "Sharing %s failed, because the user %s is not a member of any groups that %s is a member of" : "Delning %s misslyckades därför att användaren %s inte är medlem i någon utav de grupper som %s är medlem i", "Sharing %s failed, because this item is already shared with %s" : "Delning %s misslyckades därför att objektet redan är delat med %s", "Sharing %s failed, because the group %s does not exist" : "Delning %s misslyckades därför att gruppen %s inte existerar", "Sharing %s failed, because %s is not a member of the group %s" : "Delning %s misslyckades därför att %s inte ingår i gruppen %s", "You need to provide a password to create a public link, only protected links are allowed" : "Du måste ange ett lösenord för att skapa en offentlig länk, endast skyddade länkar är tillåtna", "Sharing %s failed, because sharing with links is not allowed" : "Delning %s misslyckades därför att delning utav länkar inte är tillåtet", "Not allowed to create a federated share with the same user" : "Ej tillåtet att skapa en förbundsdelning med samma användare", "Sharing %s failed, could not find %s, maybe the server is currently unreachable." : "Misslyckades dela ut %s, kan inte hitta %s, kanske är servern inte åtkomlig för närvarande.", "Share type %s is not valid for %s" : "Delningstyp %s är inte giltig för %s", "Setting permissions for %s failed, because the permissions exceed permissions granted to %s" : "Misslyckades att sätta rättigheter för %s därför att rättigheterna överskrider de som är tillåtna för %s", "Setting permissions for %s failed, because the item was not found" : "Att sätta rättigheterna för %s misslyckades därför att objektet inte hittades", "Cannot set expiration date. Shares cannot expire later than %s after they have been shared" : "Kan inte sätta utgångsdatum. Utdelningar kan inte utgå senare än %s efter de har delats ut", "Cannot set expiration date. Expiration date is in the past" : "Kan inte sätta utgångsdatum. Utgångsdatumet är i det förflutna.", "Sharing backend %s must implement the interface OCP\\Share_Backend" : "Delningsgränssnittet %s måste implementera gränssnittet OCP\\Share_Backend", "Sharing backend %s not found" : "Delningsgränssnittet %s hittades inte", "Sharing backend for %s not found" : "Delningsgränssnittet för %s hittades inte", "Sharing %s failed, because the permissions exceed permissions granted to %s" : "Delning %s misslyckades därför att rättigheterna överskrider de rättigheter som är tillåtna för %s", "Sharing %s failed, because resharing is not allowed" : "Delning %s misslyckades därför att vidaredelning inte är tillåten", "Sharing %s failed, because the sharing backend for %s could not find its source" : "Delning %s misslyckades därför att delningsgränsnittet för %s inte kunde hitta sin källa", "Sharing %s failed, because the file could not be found in the file cache" : "Delning %s misslyckades därför att filen inte kunde hittas i filcachen", "Could not find category \"%s\"" : "Kunde inte hitta kategorin \"%s\"", "A valid username must be provided" : "Ett giltigt användarnamn måste anges", "A valid password must be provided" : "Ett giltigt lösenord måste anges", "The username is already being used" : "Användarnamnet används redan", "Help" : "Hjälp", "Settings" : "Inställningar", "Users" : "Användare", "web services under your control" : "webbtjänster under din kontroll", "Application is not enabled" : "Applikationen är inte aktiverad", "Authentication error" : "Fel vid autentisering", "Token expired. Please reload page." : "Ogiltig token. Ladda om sidan.", "Unknown user" : "Okänd användare", "No database drivers (sqlite, mysql, or postgresql) installed." : "Inga databasdrivrutiner (sqlite, mysql, eller postgresql) installerade.", "Cannot write into \"config\" directory" : "Kan inte skriva till \"config\" katalogen", "Cannot write into \"apps\" directory" : "Kan inte skriva till \"apps\" katalogen!", "This can usually be fixed by %sgiving the webserver write access to the apps directory%s or disabling the appstore in the config file." : "Detta kan vanligtvis åtgärdas genom att %s ger webbservern skrivrättigheter till applikationskatalogen %s eller stänga av app-butik i konfigurationsfilen.", "Permissions can usually be fixed by %sgiving the webserver write access to the root directory%s." : "Rättigheterna kan vanligtvis åtgärdas genom att %s ger webbservern skrivrättigheter till rootkatalogen %s.", "Setting locale to %s failed" : "Sätta locale till %s misslyckades", "Please install one of these locales on your system and restart your webserver." : "Vänligen installera en av dessa locale på din server och starta om dinn webbserver,", "Please ask your server administrator to install the module." : "Vänligen be din administratör att installera modulen.", "PHP module %s not installed." : "PHP modulen %s är inte installerad.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Detta orsakas troligtvis av en cache/accelerator som t ex Zend OPchache eller eAccelerator.", "PHP modules have been installed, but they are still listed as missing?" : "PHP-moduler har installerats, men de listas fortfarande som saknade?", "Please ask your server administrator to restart the web server." : "Vänligen be din serveradministratör att starta om webservern.", "PostgreSQL >= 9 required" : "PostgreSQL >= 9 krävs", "Please upgrade your database version" : "Vänligen uppgradera din databas-version", "Please change the permissions to 0770 so that the directory cannot be listed by other users." : "Vänligen ändra rättigheterna till 0770 så att katalogen inte kan listas utav andra användare.", "Please check that the data directory contains a file \".ocdata\" in its root." : "Vänligen kontrollera att datakatalogen innehåller filen \".ocdata\" i rooten.", "Could not obtain lock type %d on \"%s\"." : "Kan inte hämta låstyp %d på \"%s\".", "Storage is temporarily not available" : "Lagring är temporärt inte tillgänglig" }, "nplurals=2; plural=(n != 1);");
agpl-3.0
mholiv/priceWatch
priceWatcher/sql.py
3527
from sqlalchemy import Column, Integer, Float, DateTime, String, MetaData,Table, create_engine, ForeignKey, join from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.exc import NoResultFound import yaml #Import out settings with open('settings.yaml', 'r') as f: doc = yaml.load(f) sqlConf = doc['sqlConfiguration'] # ======================================================================= # =================== Database Descriptors & MetaData =================== # ======================================================================= metadata = MetaData() Base = declarative_base() price = Table('prices', metadata, Column('price_id', Integer, primary_key = True), Column('availabilityCount', Integer, nullable = False), Column('wholeCost', Float, nullable = False), Column('roundCost', Float, nullable = False), Column('roundCount', Integer, nullable = False), Column('dateTime', DateTime, nullable = False), Column('_roundType_id', Integer, ForeignKey("roundTypes.roundType_id")), Column('_source_id', Integer, ForeignKey("sources.source_id")) ) roundType = Table('roundTypes', metadata, Column('roundType_id', Integer, primary_key = True), Column('roundName', String(200), unique=True) ) source = Table('sources', metadata, Column('source_id', Integer, primary_key = True), Column('source', String(200), unique=True) ) # ======================================================================= # ====================== Relevant DataBase Objects ====================== # ======================================================================= class Source(Base): __tablename__ = 'sources' source_id = Column(Integer, primary_key=True) source = Column(String(200), unique=True) def __repr__(self): return "<Source (id='%s', name='%s')>" % (self.source_id, self.source) class RoundType(Base): __tablename__ = 'roundTypes' roundType_id = Column(Integer, primary_key=True) roundName = Column(String(200), unique=True) def __repr__(self): return "<Roundtype (id='%s', name='%s')>" % (self.roundType_id, self.roundName) class Price(Base): __tablename__ = 'prices' price_id = Column(Integer, primary_key=True) availabilityCount = Column(Integer, nullable = False) wholeCost = Column(Float, nullable = False) roundCost = Column(Float, nullable = False) roundCount = Column(Integer, nullable = False) dateTime = Column(DateTime, nullable = False) _roundType_id = Column(Integer, ForeignKey("roundTypes.roundType_id")) roundType = relationship("RoundType") _source_id = Column(Integer, ForeignKey("sources.source_id")) source = relationship("Source") def __repr__(self): return "<PriceInfo (price='%s', id='%s')>" % (self.wholeCost, self.price_id) # ======================================================================= # ====================== SQLAlchemy Engine Details ====================== # ======================================================================= #We create an engine engine = create_engine('mysql+pymysql://%s:%s@%s/%s'% (sqlConf['username'],sqlConf['password'],sqlConf['dbLocation'],sqlConf['dbName'])) #This causes all missing tables to be created, Comment to prevent this. metadata.create_all(engine) # You can import alcsession and use to to access the relevant database. Session = sessionmaker() Session.configure(bind=engine) alcsession = Session()
agpl-3.0
flaviohenso/projeto-JSF2
src/main/java/com/flavio/model/registros/s1000/Reg_situacaoPF.java
261
/** * projeto-web : 10 de out de 2017 */ package com.flavio.model.registros.s1000; import com.thoughtworks.xstream.annotations.XStreamAlias; /** * @author flavio * */ @XStreamAlias("situacaoPF") public class Reg_situacaoPF { private String indSitPF; }
agpl-3.0
vatesfr/xo-web
@xen-orchestra/backups-cli/commands/create-symlink-index.js
1012
const filenamify = require('filenamify') const get = require('lodash/get') const { asyncMap } = require('@xen-orchestra/async-map') const { dirname, join, relative } = require('path') const { mktree, readdir2, readFile, symlink2 } = require('../_fs') module.exports = async function createSymlinkIndex([backupDir, fieldPath]) { const indexDir = join(backupDir, 'indexes', filenamify(fieldPath)) await mktree(indexDir) await asyncMap(await readdir2(backupDir), async vmDir => asyncMap( (await readdir2(vmDir)).filter(_ => _.endsWith('.json')), async json => { const metadata = JSON.parse(await readFile(json)) const value = get(metadata, fieldPath) if (value !== undefined) { const target = relative(indexDir, dirname(json)) const path = join(indexDir, filenamify(String(value))) await symlink2(target, path).catch(error => { console.warn('symlink(%s, %s)', target, path, error) }) } } ) ) }
agpl-3.0
CatoTH/antragsgruen
models/forms/MotionDeepCopy.php
7091
<?php declare(strict_types=1); namespace app\models\forms; use app\models\db\{Amendment, AmendmentAdminComment, AmendmentComment, AmendmentSection, AmendmentSupporter, ConsultationAgendaItem, ConsultationMotionType, Motion, MotionAdminComment, MotionComment, MotionSection, MotionSupporter}; class MotionDeepCopy { public static function copyMotion(Motion $motion, ConsultationMotionType $motionType, ?ConsultationAgendaItem $agendaItem, string $newPrefix): Motion { $newConsultation = $motionType->getConsultation(); $slug = $motion->slug; if ($motion->consultationId === $newConsultation->id) { $motion->slug = null; $motion->save(); } $newMotion = new Motion(); $newMotion->setAttributes($motion->getAttributes(), false); $newMotion->id = null; $newMotion->agendaItemId = ($agendaItem ? $agendaItem->id : null); $newMotion->titlePrefix = $newPrefix; $newMotion->consultationId = $newConsultation->id; $newMotion->cache = ''; $newMotion->slug = $slug; $newMotion->save(); static::copyTags($motion, $newMotion); static::copyMotionSections($motion, $newMotion); static::copyMotionSupporters($motion, $newMotion); static::copyMotionAdminComments($motion, $newMotion); static::copyMotionComments($motion, $newMotion); static::copyAmendments($motion, $newMotion); if ($newMotion->motionTypeId !== $motionType->id) { $newMotion->setMotionType($motionType); } return $newMotion; } private static function copyTags(Motion $oldMotion, Motion $newMotion) { foreach ($oldMotion->getPublicTopicTags() as $tag) { $newMotion->link('tags', $tag); } } private static function copyMotionSections(Motion $oldMotion, Motion $newMotion) { foreach ($oldMotion->sections as $section) { $newSection = new MotionSection(); $newSection->setAttributes($section->getAttributes(), false); $newSection->setData($section->getData()); $newSection->motionId = $newMotion->id; $newSection->cache = ''; $newSection->save(); } } private static function copyMotionSupporters(Motion $oldMotion, Motion $newMotion) { foreach ($oldMotion->motionSupporters as $supporter) { $newSupporter = new MotionSupporter(); $newSupporter->setAttributes($supporter->getAttributes(), false); $newSupporter->id = null; $newSupporter->motionId = $newMotion->id; $newSupporter->save(); } } private static function copyMotionAdminComments(Motion $oldMotion, Motion $newMotion) { foreach ($oldMotion->getAllAdminComments() as $comment) { $newComment = new MotionAdminComment(); $newComment->setAttributes($comment->getAttributes(), false); $newComment->id = null; $newComment->motionId = $newMotion->id; $newComment->save(); } } private static function copyMotionComments(Motion $oldMotion, Motion $newMotion) { foreach ($oldMotion->comments as $comment) { $newComment = new MotionComment(); $newComment->setAttributes($comment->getAttributes(), false); $newComment->id = null; $newComment->motionId = $newMotion->id; $newComment->save(); } } private static function copyAmendments(Motion $oldMotion, Motion $newMotion) { $amendmentIdMapping = []; $newAmendments = []; foreach ($oldMotion->amendments as $amendment) { $newAmendment = new Amendment(); $newAmendment->setAttributes($amendment->getAttributes(), false); $newAmendment->id = null; $newAmendment->motionId = $newMotion->id; $newAmendment->cache = ''; $oldTitlePre = $oldMotion->titlePrefix . '-'; $newTitlePre = $newMotion->titlePrefix . '-'; if ($amendment->titlePrefix) { $newAmendment->titlePrefix = str_replace($oldTitlePre, $newTitlePre, $amendment->titlePrefix); } else { $newAmendment->titlePrefix = null; } $newAmendment->save(); $amendmentIdMapping[$amendment->id] = $newAmendment->id; $newAmendments[] = $newAmendment; static::copyAmendmentSections($amendment, $newAmendment); static::copyAmendmentSupporters($amendment, $newAmendment); static::copyAmendmentComments($amendment, $newAmendment); static::copyAmendmentAdminComments($amendment, $newAmendment); } foreach ($newAmendments as $newAmendment) { if ($newAmendment->proposalReferenceId && isset($amendmentIdMapping[$newAmendment->proposalReferenceId])) { $newAmendment->proposalReferenceId = $amendmentIdMapping[$newAmendment->proposalReferenceId]; $newAmendment->save(); } } } private static function copyAmendmentSections(Amendment $oldAmendment, Amendment $newAmendment) { foreach ($oldAmendment->sections as $section) { $newSection = new AmendmentSection(); $newSection->setAttributes($section->getAttributes(), false); $newSection->amendmentId = $newAmendment->id; $newSection->cache = ''; $newSection->save(); } } private static function copyAmendmentSupporters(Amendment $oldAmendment, Amendment $newAmendment) { foreach ($oldAmendment->amendmentSupporters as $supporter) { $newSupporter = new AmendmentSupporter(); $newSupporter->setAttributes($supporter->getAttributes(), false); $newSupporter->id = null; $newSupporter->amendmentId = $newAmendment->id; $newSupporter->save(); } } private static function copyAmendmentComments(Amendment $oldAmendment, Amendment $newAmendment) { foreach ($oldAmendment->comments as $comment) { $newComment = new AmendmentComment(); $newComment->setAttributes($comment->getAttributes(), false); $newComment->id = null; $newComment->amendmentId = $newAmendment->id; $newComment->save(); } } private static function copyAmendmentAdminComments(Amendment $oldAmendment, Amendment $newAmendment) { foreach ($oldAmendment->getAllAdminComments() as $comment) { $newComment = new AmendmentAdminComment(); $newComment->setAttributes($comment->getAttributes(), false); $newComment->id = null; $newComment->amendmentId = $newAmendment->id; $newComment->save(); } } }
agpl-3.0
Fabs/wikiurbo
app/models/citizen.rb
2403
require 'digest/sha1' class Citizen < ActiveRecord::Base include Authentication include Authentication::ByPassword include Authentication::ByCookieToken validates_presence_of :login validates_length_of :login, :within => 3..40 validates_uniqueness_of :login validates_format_of :login, :with => Authentication.login_regex, :message => Authentication.bad_login_message validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true validates_length_of :name, :maximum => 100 validates_presence_of :email validates_length_of :email, :within => 6..100 #r@a.wk validates_uniqueness_of :email validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message before_create :make_activation_code # HACK HACK HACK -- how to do attr_accessible from here? # prevents a user from submitting a crafted form that bypasses activation # anything else you want your user to change should be added here. attr_accessible :login, :email, :name, :password, :password_confirmation # Activates the user in the database. def activate! @activated = true self.activated_at = Time.now.utc self.activation_code = nil save(false) end # Returns true if the user has just been activated. def recently_activated? @activated end def active? # the existence of an activation code means they have not activated yet activation_code.nil? end # Authenticates a user by their login name and unencrypted password. Returns the user or nil. # # uff. this is really an authorization, not authentication routine. # We really need a Dispatch Chain here or something. # This will also let us return a human error message. # def self.authenticate(login, password) return nil if login.blank? || password.blank? u = find :first, :conditions => ['login = ? and activated_at IS NOT NULL', login] # need to get the salt u && u.authenticated?(password) ? u : nil end def login=(value) write_attribute :login, (value ? value.downcase : nil) end def email=(value) write_attribute :email, (value ? value.downcase : nil) end protected def make_activation_code self.activation_code = self.class.make_token end end
agpl-3.0
tenders-exposed/elvis-ember
app/services/songs.js
19176
import Service from '@ember/service'; const songs = [ `500 Miles`, `Adam and Evil`, `After Loving You`, `"Ain't That Lovin' You, Baby"`, `All I Needed Was the Rain`, `All Shook Up`, `All That I Am`, `Allá en el Rancho Grande`, `Almost`, `Almost Always True`, `Almost in Love`, `Aloha 'Oe`, `"Alright, Okay, You Win"`, `Always on My Mind`, `Am I Ready`, `Amazing Grace`, `America the Beautiful`, `An American Trilogy`, `And I Love You So`, `And the Grass Won't Pay No Mind`, `Angel`, `Animal Instinct`, `Any Day Now`, `Any Way You Want Me (That's How I Will Be)`, `Anyone (Could Fall in Love with You)`, `Anyplace Is Paradise`, `Anything That's Part of You`, `Apron Strings`, `Are You Lonesome Tonight?`, `Are You Sincere`, `As Long As I Have You`, `Ask Me`, `Aubrey`, `Baby Let's Play House`, `Baby What You Want Me to Do`, `"Baby, If You'll Give Me All of Your Love"`, `Barefoot Ballad`, `Beach Boy Blues`, `Beach Shack`, `Because of Love`, `Beginner's Luck`, `Beyond the Bend`, `Beyond the Reef`, `Big Boots`, `Big Boss Man`, `A Big Hunk O' Love`, `"Big Love, Big Heartache"`, `"Bitter They Are, Harder They Fall"`, `Blessed Jesus (Hold My Hand)`, `Blowin' in the Wind`, `Blue Christmas`, `Blue Eyes Crying in the Rain`, `Blue Hawaii`, `Blue Moon of Kentucky`, `Blue Moon`, `Blue River`, `Blue Suede Shoes`, `Blueberry Hill`, `Bosom of Abraham`, `Bossa Nova Baby`, `"A Boy Like Me, A Girl Like You"`, `Bridge Over Troubled Water`, `Bringin' It Back`, `Britches`, `Brown Eyed Handsome Man`, `The Bullfighter Was a Lady`, `Burning Love`, `By and By`, `A Cane and a High Starched Collar`, `Can't Help Falling in Love`, `Carny Town`, `Catchin' On Fast`, `Cattle Call`, `Change of Habit`, `Charro`, `Chesay`, `"Cindy, Cindy"`, `City By Night`, `Clambake`, `Clean Up Your Own Backyard`, `The Climb`, `C'mon Everybody`, `Columbus Stockade Blues`, `Come Along`, `Come What May`, `Confidence`, `Cotton Candy Land`, `Cottonfields`, `Could I Fall in Love`, `Crawfish`, `Crazy Arms`, `Cross My Heart and Hope to Die`, `Crying in the Chapel`, `Dainty Little Moonbeams`, `Danny`, `Danny Boy`, `Dark Moon`, `Datin'`, `Didja' Ever`, `"Dirty, Dirty Feeling"`, `Dixieland Rock`, `Do Not Disturb`, `Do the Clam`, `Do the Vega`, `Do You Know Who I Am?`, `A Dog's Life`, `Doin' the Best I Can`, `Dominic`, `Doncha' Think It's Time`, `Don't`, `Don't Ask Me Why`, `Don't Be Cruel`, `Don't Cry Daddy`, `Don't Forbid Me`, `Don't Leave Me Now`, `"Don't Think Twice, It's All Right"`, `Double Trouble`, `Down by the Riverside`, `Down in the Alley`, `Drums of the Islands`, `Early Morning Rain`, `Earth Angel`, `Earth Boy`, `"Easy Come, Easy Go"`, `Echoes of Love`, `Edge of Reality`, `El Toro`, `End of the Road`, `An Evening Prayer`, `Everybody Come Aboard`, `The Eyes of Texas`, `Faded Love`, `The Fair's Moving On`, `Fairytale`, `Fame and Fortune`, `Farther Along`, `Fever`, `Find Out What's Happening`, `"Finders Keepers, Losers Weepers"`, `First in Line`, `The First Noel`, `The First Time Ever I Saw Your Face`, `Five Sleepy Heads`, `Flaming Star[4]`, `"Flip, Flop and Fly[5]"`, `Follow That Dream`, `Fool`, `"Fool, Fool, Fool"`, `The Fool[6]`, `Fools Fall in Love`, `Fools Rush In (Where Angels Fear to Tread)`, `For Ol' Times Sake`, `For the Good Times`, `For the Heart`, `For the Millionth and the Last Time`, `Forget Me Never`, `Fort Lauderdale Chamber of Commerce`, `Fountain of Love`, `Frankfort Special`, `Frankie and Johnny`, `Froggy Went A-Courting`, `From a Jack to a King`, `Fun in Acapulco`, `Funny How Time Slips Away`, `G.I. Blues`, `Gentle on My Mind`, `Gently`, `Ghost Riders in the Sky`, `Girl Happy`, `The Girl I Never Loved`, `Girl Next Door Went A-Walking`, `Girl of Mine`, `The Girl of My Best Friend`, `Girls! Girls! Girls!`, `Give Me the Right`, `Go East-Young Man`, `Goin' Home`, `Golden Coins`, `Gonna Get Back Home Somehow`, `Good Luck Charm`, `Good Rocking Tonight`, `Good Time Charlie's Got the Blues`, `Got a Lot o' Livin' to Do`, `Got My Mojo Working`, `"Green, Green Grass of Home"`, `Guadalajara`, `Guitar Man`, `Hands Off`, `Happy Ending`, `"Happy, Happy Birthday Baby"`, `Harbor Lights`, `Hard Headed Woman`, `Hard Knocks`, `Hard Luck`, `Harem Holiday`, `Have a Happy`, `Have I Told You Lately That I Love You?`, `Hawaiian Sunset`, `Hawaiian Wedding Song`, `He is My Everything`, `He Knows Just What I Need`, `He`, `He Touched Me`, `Heart of Rome`, `Heartbreak Hotel`, `Hearts of Stone`, `He'll Have to Go`, `Help Me`, `Help Me Make It Through the Night`, `Here Comes Santa Claus`, `"He's Your Uncle, Not Your Dad"`, `Hey Jude`, `Hey Little Girl`, `"Hey, Hey, Hey"`, `Hide Thou Me`, `Hi-Heel Sneakers`, `His Hand in Mine`, `Holly Leaves and Christmas Trees`, `Home Is Where the Heart Is`, `Hot Dog`, `Hound Dog`, `House of Sand`, `A House That Has Everything`, `How Can You Lose What You Never Had`, `How Do You Think I Feel`, `How Great Thou Art`, `How the Web Was Woven`, `How Would You Like to Be`, `How's the World Treating You?`, `A Hundred Years from Now`, `Hurt`, `"Husky, Dusky Day"`, `I Asked the Lord (He's Only a Prayer Away)`, `I Beg of You`, `I Believe`, `I Believe in the Man in the Sky`, `I Can Help`, `I Can't Help It (If I'm Still in Love with You)`, `I Can't Stop Loving You`, `I Didn't Make It On Playing Guitar (Informal Jam session)`, `I Don't Care if the Sun Don't Shine`, `I Don't Wanna Be Tied`, `I Don't Want To`, `I Feel So Bad`, `I Feel That I've Known You Forever`, `I Forgot to Remember to Forget`, `I Got a Feelin' in My Body`, `I Got a Woman`, `I Got Lucky`, `I Got Stung`, `I Gotta Know`, `I Hear a Sweet Voice Calling`, `I Just Can't Help Believin'`, `I Just Can't Make It by Myself`, `I Love Only One Girl`, `I Love You Because`, `I Met Her Today`, `I Miss You`, `I Need Somebody to Lean On`, `I Need You So`, `I Need Your Love Tonight`, `I Need Your Loving (Every Day)`, `I Really Don't Want to Know`, `I Shall Be Released`, `I Shall Not Be Moved`, `"I Slipped, I Stumbled, I Fell"`, `I Think I'm Gonna Like It Here`, `I Understand (Just How You Feel)`, `I Walk the Line`, `I Want to Be Free`, `I Want You with Me`, `"I Want You, I Need You, I Love You"`, `I Was Born About Ten Thousand Years Ago`, `I Was the One`, `I Washed My Hands In Muddy Water`, `I Will Be Home Again`, `I Will Be True`, `"I Wonder, I Wonder, I Wonder"`, `"I, John"`, `If Every Day Was Like Christmas`, `If I Can Dream`, `If I Get Home on Christmas Day`, `If I Loved You`, `If I Were You`, `If I'm a Fool (For Loving You)`, `If That Isn't Love`, `If the Lord Wasn't Walking by My Side`, `If We Never Meet Again`, `If You Don't Come Back`, `If You Love Me (Let Me Know)`, `If You Talk in Your Sleep`, `If You Think I Don't Need You`, `I'll Be Back`, `I'll Be Home for Christmas`, `I'll Be Home on Christmas Day`, `I'll Be There`, `I'll Hold You in My Heart (Till I Can Hold You in My Arms)`, `I'll Never Fall in Love Again`, `I'll Never Know`, `I'll Never Let You Go (Little Darlin')`, `I'll Never Stand In Your Way`, `I'll Remember You*`, `I'll Take Love`, `"I'll Take You Home Again, Kathleen"`, `I'm a Roustabout`, `I'm Beginning to Forget You`, `I'm Comin' Home`, `I'm Counting on You`, `I'm Falling in Love Tonight`, `I'm Gonna Bid My Blues Goodbye`, `I'm Gonna Sit Right Down and Cry (Over You)`, `I'm Gonna Walk Dem Golden Stairs`, `I'm Leavin'`, `"I'm Left, You're Right, She's Gone"`, `I'm Movin' On`, `I'm Not the Marrying Kind`, `I'm So Lonesome I Could Cry`, `I'm With a Crowd (But So Alone)`, `I'm Yours`, `The Impossible Dream`, `In My Father's House`, `In My Way`, `In the Garden`, `In the Ghetto`, `In Your Arms`, `Indescribably Blue`, `Inherit the Wind`, `Is It So Strange`, `Island Of Love`, `It Ain't No Big Thing (But It's Growing)`, `It Feels So Right`, `It Hurts Me`, `It Is No Secret (What God Can Do)`, `It Keeps Right On A-Hurtin'`, `It Won't Be Long`, `It Won't Seem Like Christmas (Without You)`, `It Wouldn't Be the Same without You`, `Ito Eats`, `It's a Matter of Time`, `It's a Sin`, `It's a Sin to Tell a Lie`, `It's a Wonderful World`, `(It's a) Long Lonely Highway`, `It's Been So Long Darling`, `It's Carnival Time`, `It's Diff'rent Now`, `It's Easy for You`, `It's Impossible`, `It’s Midnight`, `It’s No Fun Being Lonely`, `It's Now or Never`, `It's Only Love`, `It's Over`, `It's Still Here`, `It's Your Baby You Rock It`, `I've Got a Thing About You Baby`, `I've Got Confidence`, `I've Got To Find My Baby`, `I've Lost You`, `Jailhouse Rock`, `Johnny B. Goode`, `Joshua Fit the Battle`, `Judy`, `Just a Closer Walk with Thee`, `Just a Little Bit`, `Just a Little Talk with Jesus`, `Just Because`, `Just Call Me Lonesome`, `Just for Old Time Sake`, `Just Pretend`, `Just Tell Her Jim Said Hello`, `Keep Your Hands Off Of It[10]`, `Keeper Of The Key`, `Kentucky Rain`, `King Creole`, `King of the Whole Wide World`, `Kismet`, `Kiss Me Quick`, `Kissin' Cousins`, `Kissin' Cousins (Number 2)`, `Known Only to Him`, `Ku-U-I-Po`, `The Lady Loves Me (with Ann-Margret)`, `Lady Madonna`, `The Last Farewell`, `Lawdy Miss Clawdy`, `"Lead Me, Guide Me"`, `Let It Be Me`, `Let Me`, `Let Me Be the One`, `Let Me Be There`, `(Let Me Be Your) Teddy Bear`, `Let Yourself Go`, `Let's Be Friends`, `Let's Forget About the Stars`, `Let Us Pray`, `Life`, `Like a Baby`, `Listen to the Bells`, `A Little Bit of Green`, `Little Cabin on the Hill`, `Little Darlin'`, `Little Egypt (Ying-Yang)`, `A Little Less Conversation`, `Little Mama`, `Little Sister`, `Lonely Man`, `Lonesome Cowboy`, `Long Black Limousine`, `Long Legged Girl (With the Short Dress On)`, `Long Tall Sally`, `"Look Out, Broadway"`, `The Lord's Prayer`, `Love Coming Down`, `Love Letters`, `The Love Machine`, `Love Me`, `Love Me Tender`, `Love Me Tonight`, `"Love Me, Love the Life I Lead"`, `Love Song of the Year`, `Lover Doll`, `Loving Arms`, `Loving You`, `Make Me Know It`, `Make the World Go Away`, `Mama`, `Mama Liked the Roses`, `Mansion Over the Hilltop`, `Marguerita`, `(Marie's the Name) His Latest Flame`, `Mary in the Morning`, `Mary Lou Brown`, `Maybellene`, `Mean Woman Blues`, `The Meanest Girl in Town`, `Memories`, `Memphis Tennessee`, `Men with Broken Hearts`, `Merry Christmas Baby`, `A Mess of Blues`, `Mexico`, `Mickey Mouse Club March`, `Milkcow Blues Boogie`, `Milky White Way`, `Mine`, `Miracle of the Rosary`, `Mirage`, `Mona Lisa`, `Money Honey`, `Moody Blue`, `Moonlight Sonata`, `Moonlight Swim`, `Mr. Songman`, `Must Jesus Bear the Cross Alone`, `My Babe`, `My Baby Left Me`, `My Boy`, `My Desert Serenade`, `My Happiness`, `My Heart Cries for You`, `My Little Friend`, `My Way`, `My Wish Came True`, `Mystery Train`, `"Nearer, My God, to Thee"`, `Never Again`, `Never Been to Spain`, `Never Ending`, `Never Say Yes`, `New Orleans`, `The Next Step Is Love`, `Night Life`, `Night Rider`, `No More`, `No Room to Rhumba in a Sports Car`, `Nothingville`, `(Now and Then There's) A Fool Such as I`, `"O Come, All Ye Faithful"`, `O Little Town of Bethlehem`, `Oh Happy Day (1)`, `Oh Happy Day (2)`, `"Oh, How I Love Jesus"`, `Old MacDonald`, `Old Shep`, `On a Snowy Christmas Night`, `On the Jericho Road`, `Once Is Enough`, `"One Boy, Two Little Girls"`, `One Broken Heart for Sale`, `One Night[13]`, `One-sided Love Affair`, `One Track Heart`, `Only Believe`, `Only the Strong Survive`, `"Out Of Sight, Out Of Mind"`, `Padre`, `"Paradise, Hawaiian Style"`, `Paralyzed`, `Party`, `Patch It Up`, `(There'll Be) Peace in the Valley (For Me)`, `Peter Gunn Theme[15]`, `"Petunia, the Gardener's Daughter"`, `Pieces of My Life`, `Plantation Rock`, `Playing for Keeps`, `Please Don't Drag That String Around`, `Please Don't Stop Loving Me`, `Pledging My Love`, `Pocketful of Rainbows`, `Poison Ivy League`, `Polk Salad Annie`, `Poor Boy`, `Poor Man's Gold`, `Portrait of My Love`, `Power of My Love`, `Promised Land`, `Proud Mary`, `Puppet On A String`, `Put the Blame On Me`, `Put Your Hand in the Hand`, `Queenie Wahine's Papaya`, `Rags to Riches`, `Raised on Rock`, `Reach Out to Jesus`, `Ready Teddy`, `Reconsider Baby`, `Relax`, `Release Me`, `Return to Sender`, `Riding the Rainbow`, `Rip It Up`, `Rock-A-Hula Baby`, `Roustabout`, `Rubberneckin'`, `Run On`, `Runaway`, `San Antonio Rose`, `Sand Castles`, `Santa Claus Is Back In Town`, `Santa Lucia`, `Santa Bring My Baby Back (to Me)`, `Saved`, `Scratch My Back`, `See See Rider`, `Seeing Is Believing`, `Send Me Some Lovin'`, `Sentimental Me`, `Separate Ways`, `Shake a Hand`, `"Shake, Rattle and Roll"`, `Shake That Tambourine`, `She Thinks I Still Care`, `She Wears My Ring`, `She's a Machine`, `She's Not You`, `Shoppin' Around`, `Shout It Out`, `"Show Me Thy Ways, O Lord"`, `Signs of the Zodiac`, `Silent Night`, `Silver Bells`, `Sing You Children`, `Singing Tree`, `Slicin' Sand`, `Slowly But Surely`, `Smokey Mountain Boy`, `Smorgasbord`, `Snowbird`, `"So Close, Yet So Far (From Paradise)"`, `So Glad You're Mine`, `So High`, `Softly and Tenderly`, `Softly As I Leave You`, `Soldier Boy`, `Solitaire`, `Somebody Bigger Than You and I`, `Something Blue`, `Something`, `Song of the Shrimp`, `Sound Advice`, `The Sound of Your Cry`, `Spanish Eyes`, `Speedway`, `Spinout`, `Spring Fever`, `Stand by Me`, `Startin' Tonight`, `Starting Today`, `Stay Away`, `"Stay Away, Joe"`, `"Steadfast, Loyal and True"`, `Steamroller Blues`, `Steppin' Out of Line`, `"Stop, Look and Listen"`, `Stop Where You Are`, `Stranger In My Own Home Town`, `Stranger in the Crowd`, `Stuck on You`, `Such a Night`, `(Such an) Easy Question`, `"Summer Kisses, Winter Tears"`, `Summertime Has Passed and Gone`, `Suppose`, `Surrender`, `Susan When She Tried`, `Suspicion`, `Suspicious Minds`, `Sweet Angeline`, `Sweet Caroline`, `Sweet Leilani`, `"Sweetheart, You Done Me Wrong"`, `Swing Down Sweet Chariot`, `Sylvia`, `Take Good Care of Her`, `Take Me to the Fair`, `"Take My Hand, Precious Lord"`, `Talk About the Good Times`, `Tell Me Why`, `Tender Feeling`, `Tennessee Waltz`, `Thanks to the Rolling Sea`, `That's All Right`, `That's My Desire`, `That's Someone You Never Forget`, `(That's What You Get) For Lovin' Me`, `That's When Your Heartaches Begin`, `There Ain't Nothing Like a Song (with Nancy Sinatra)`, `There Goes My Everything`, `There Is No God But God`, `There Is So Much World to See`, `There's a Brand New Day on the Horizon`, `There's a Honky Tonk Angel (Who'll Take Me Back In)`, `There's Always Me`, `There's Gold in the Mountains`, `There's No Place Like Home`, `There's No Tomorrow`, `They Remind Me Too Much of You`, `A Thing Called Love`, `Thinking About You`, `This Is Living`, `This Is My Heaven`, `This Is Our Dance`, `This Is the Story`, `This Time`, `Three Corn Patches`, `Thrill of Your Love`, `Tiger Man`, `The Titles Will Tell`, `"Today, Tomorrow and Forever"`, `Tomorrow is a Long Time`, `Tomorrow Never Comes`, `Tomorrow Night`, `Tonight Is So Right for Love`, `Tonight's All Right for Love`, `Too Much`, `Too Much Monkey Business`, `Treat Me Nice`, `T-R-O-U-B-L-E`, `Trouble`, `True Love`, `True Love Travels on a Gravel Road`, `Tryin' to Get to You`, `Tumbling Tumbleweeds`, `"Turn Around, Look at Me"`, `Turn Your Eyes Upon Jesus`, `Tutti Frutti`, `Tweedle Dee`, `The Twelfth of Never`, `Twenty Days and Twenty Nights`, `U.S. Male`, `Unchained Melody`, `Until It's Time for You to Go`, `Until Then`, `Up Above My Head`, `"Vino, Dinero y Amor"`, `Violet`, `Viva Las Vegas`, `Walk a Mile in My Shoes`, `Walk That Lonesome Road`, `The Walls Have Ears`, `Wasted Years`, `Way Down`, `We Call On Him`, `We Can Make the Morning`, `Wear My Ring Around Your Neck`, `Wearin' That Loved-On Look`, `Welcome to My World`, `We'll Be Together`, `We're Comin' In Loaded`, `We're Gonna Move`, `Western Union`, `What a Wonderful Life`, `What Every Woman Lives For`, `What Now My Love`, `"What Now, What Next, Where To"`, `What'd I Say`, `What's She Really Like`, `Wheels on My Heels`, `When God Dips His Love In My Heart`, `When I'm Over You`, `"When It Rains, It Really Pours"`, `When My Blue Moon Turns to Gold Again`, `When the Saints Go Marching In[17]`, `When the Snow Is on the Roses`, `When the Swallows Come Back to Capistrano`, `Where Could I Go but to the Lord`, `Where Did They Go Lord`, `Where Do I Go from Here?`, `Where Do You Come From`, `Where No One Stands Alone`, `The Whiffenpoof Song`, `A Whistling Tune`, `White Christmas`, `Who Am I?`, `Who Are You (Who Am I?)`, `Who Needs Money`, `Whole Lotta Shakin' Goin' On`, `Who's Sorry Now`, `"Why Me, Lord?"`, `Wild in the Country`, `Winter Wonderland`, `Wisdom of the Ages`, `Witchcraft (1)`, `Witchcraft (2)`, `Without a Song`, `Without Him`, `Without Love (There Is Nothing)`, `Wolf Call`, `Woman Without Love`, `The Wonder of You`, `Wonderful World`, `The Wonderful World of Christmas`, `Wooden Heart`, `Words`, `A World of Our Own`, `Working on the Building`, `Write to Me from Naples`, `The Yellow Rose of Texas`, `Yoga is as Yoga Does`, `You Asked Me To`, `You Belong to My Heart`, `You Better Run`, `You Can Have Her`, `You Can't Say No in Acapulco`, `You Don't Have to Say You Love Me`, `You Don't Know Me`, `You Gave Me a Mountain`, `You Gotta Stop`, `You'll Be Gone`, `You'll Never Walk Alone`, `You'll Think of Me`, `Young and Beautiful`, `Young Dreams`, `Young Love`, `Your Cheatin' Heart`, `Your Love's Been a Long Time Coming`, `Your Mama Don't Dance`, `"Your Time Hasn't Come Yet, Baby"`, `You're a Heartbreaker`, `(You're So Square) Baby I Don't Care`, `You're the Boss (with Ann-Margret)`, `You're the Reason I'm Living`, `(You're the) Devil in Disguise`, `You've Lost That Lovin' Feelin'` ]; export default Service.extend({ init() { this.set('data', songs); }, random() { return this.get('data')[Math.floor(Math.random() * this.get('data').length)]; } });
agpl-3.0
mattsoldo/fat_free_crm
app/helpers/campaigns_helper.rb
1899
# Fat Free CRM # Copyright (C) 2008-2009 by Michael Dvorkin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #------------------------------------------------------------------------------ module CampaignsHelper # Sidebar checkbox control for filtering campaigns by status. #---------------------------------------------------------------------------- def campaign_status_checbox(status, count) checked = (session[:filter_by_campaign_status] ? session[:filter_by_campaign_status].split(",").include?(status.to_s) : count > 0) check_box_tag("status[]", status, checked, :onclick => remote_function(:url => { :action => :filter }, :with => %Q/"status=" + $$("input[name='status[]']").findAll(function (el) { return el.checked }).pluck("value")/)) end #---------------------------------------------------------------------------- def performance(actual, target) if target.to_i > 0 && actual.to_i > 0 if target > actual n = 100 - actual * 100 / target html = content_tag(:span, "(-#{number_to_percentage(n, :precision => 1)})", :class => "warn") else n = actual * 100 / target - 100 html = content_tag(:span, "(+#{number_to_percentage(n, :precision => 1)})", :class => "cool") end end html || "" end end
agpl-3.0
StylishTriangles/TadzikEngine
Tadzik/levels/rpg.hpp
25777
#ifndef RPG_HPP #define RPG_HPP #include "../include/Scene.hpp" #include "../include/AnimatedSprite.hpp" #include "../include/Collision.hpp" #include "../include/Utils.hpp" #include <string> #include <vector> #include <ctime> #include <cstdlib> #include <cmath> #include <fstream> class RPG : public Scene { public: RPG(std::string _name, SceneManager* mgr, sf::RenderWindow* w) : Scene(_name, mgr, w) {} enum Direction { None = 0, Down = 1, Up = -1, Right = 1, Left = -1 }; class Entity: public sf::Drawable { public: Entity(sf::Vector2f V, ARO::Anim* A) { aSprite.setAnimation(A); aSprite.setPosition(V); } Entity() { } ARO::AnimSprite aSprite; int health = 100; int damage = 10; float basespeed = 10; float speedX = 0; float speedY = 0; char dir = 'N'; int side = Right; bool isAttacking; std::vector<sf::Vector2i> equipment; void move(sf::Vector2f a) { aSprite.move(a); } void move(float x, float y) { if (x == 0 || y == 0) aSprite.move(sf::Vector2f(x, y)); else aSprite.move( sf::Vector2f(x * (double)0.70710678, y * (double)0.70710678)); //std::cout << dir << "\t" << speedY << "\n"; } void changeAnimation(ARO::Anim* a) { aSprite.move(sf::Vector2f(aSprite.getAnim()->width-a->width, aSprite.getAnim()->height-a->height)*aSprite.getScale().x); aSprite.setAnimation(a); } void AImove(const sf::Sprite s, RPG* erpeg) { float dist = erpeg->distance(aSprite, s); int x=0, y=0; aSprite.move(basespeed,0); if( erpeg->distance(aSprite,s)<dist ) x=1; aSprite.move(-2*basespeed,0); if(erpeg->distance(aSprite,s)<dist) x=-1; aSprite.move(basespeed,basespeed); if(erpeg->distance(aSprite,s)<dist) y=1; aSprite.move(0,-2*basespeed); if(erpeg->distance(aSprite,s)<dist) y=-1; aSprite.move(0,basespeed); speedX=x*basespeed; speedY=y*basespeed; erpeg->staticCollision(*this); aSprite.move(speedX,speedY); } sf::Vector2f getPosition() { return aSprite.getPosition(); } private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(aSprite); } }; class Slice : public ARO::AnimSprite { public: Slice(sf::Vector2f V, ARO::Anim* A, int dmg, bool b=1) { setAnimation(A); setPosition(V); damage = dmg; isPlayer = b; } int damage = 50; bool isPlayer = 0; void collide(std::vector<Entity>& E) { for (int i = E.size()-1; i >= 0; i--) if (Collision::PixelPerfectTest(*this, E[i].aSprite)) { E[i].health-=damage; E[i].aSprite.setColor(sf::Color(255,0,0)); } } }; class Chest: public sf::Sprite { public: Chest(sf::Vector2f V, const sf::Texture& T, int n = 5) { setPosition(V); setTexture(T); setScale(n,n); } int number = 3; }; class Chestwo: public sf::Sprite { public: Chestwo(int x, int y, std::vector<sf::Vector2i> V, sf::Texture& t, int scale = 5) { items = V; setTexture(t); setScale(scale,scale); setPosition(sf::Vector2f(x*30,y*30)); } std::vector <sf::Vector2i> items; void giveItem(sf::Vector2i V) { for(int i=items.size()-1; i>=0; i--) if(items[i].x==V.x) { items[i].y+=V.y; break; } else if(i==0) items.push_back(V); std::sort(items.begin(), items.end(), [](sf::Vector2i a, sf::Vector2i b) { return b.x < a.x; }); } void takeItem(sf::Vector2i V) { for(int i=items.size()-1; i>=0; i--) if(items[i].x==V.x) { items[i].y-=V.y; if(items[i].y<=0) items.erase(items.begin()+i); break; } } }; class Item: public sf::Sprite { public: Item(int i, std::string n, const sf::Texture &tex, const sf::IntRect I, int v,int d=0, int scale=30) { setTexture(tex); setTextureRect(I); name=n; id=i; value=v; damage=d; setScale(scale,scale); } std::string name; int id; int value; int damage = 0; }; void loadMap(sf::Image mapa, std::string s) { for (int i = 0; i < mapa.getSize().x; i++) { for (int j = 0; j < mapa.getSize().y; j++) { if (mapa.getPixel(i, j) == sf::Color(0, 0, 0)) { tempWall.setPosition(i * tilesize, j * tilesize); spWall.push_back(tempWall); } else { tempGrass.setPosition(i * tilesize, j * tilesize); spGrass.push_back(tempGrass); } if (mapa.getPixel(i, j) == sf::Color(255,128,0)) { // vecChest.push_back(Chest(sf::Vector2f(i*tilesize,j*tilesize),texChest)); } if (mapa.getPixel(i, j) == sf::Color(0, 0, 255)) { Player.aSprite.setPosition(i * tilesize, j * tilesize); } if (mapa.getPixel(i, j) == sf::Color(255, 0, 0)) { vecSkeleton.push_back(Entity(sf::Vector2f(i*tilesize, j*tilesize), &enemySkeleton)); vecSkeleton[vecSkeleton.size()-1].aSprite.setScale(5,5); vecSkeleton[vecSkeleton.size()-1].basespeed=2; } } } std::ifstream chests; chests.open(s); int x, y; while(chests >> x >> y) { std::vector <sf::Vector2i> V; sf::Vector2i Vi; while(1) { chests >> Vi.x >> Vi.y; if(Vi.x==-1) break; V.push_back(Vi); } vecChest.push_back(Chestwo(x,y,V, texChest)); } } float distance(sf::Sprite spA, sf::Sprite spB) { return sqrt((spA.getPosition().x - spB.getPosition().x) * (spA.getPosition().x - spB.getPosition().x) + (spA.getPosition().y - spB.getPosition().y) * (spA.getPosition().y - spB.getPosition().y)); } void staticCollision(Entity& E) { sf::FloatRect R = E.aSprite.getGlobalBounds(); bool b = 0; int w; for (int i = 0; i < spWall.size(); i++) if (spWall[i].getGlobalBounds().intersects(R)) { b = 1; w = i; break; } if (b) { E.speedX = 0; E.speedY = 0; E.move((spWall[w].getPosition().x - E.aSprite.getPosition().x) * 2, (spWall[w].getPosition().y - E.aSprite.getPosition().y) * 2); } else { /// x R.left += E.speedX; for (int i = 0; i < spWall.size(); i++) if (spWall[i].getGlobalBounds().intersects(R)) { E.speedX = 0; break; } R = E.aSprite.getGlobalBounds(); /// y R.top += E.speedY; for (int i = 0; i < spWall.size(); i++) if (spWall[i].getGlobalBounds().intersects(R)) { E.speedY = 0; } } } void openChest(Chestwo, sf::Vector2f Pos, sf::Sprite s) { s.setPosition(Pos); window->draw(s); } void fixView() { sf::Vector2i pos = rGame.mapCoordsToPixel(Player.getPosition(), view); int scrollArea = 300; if (pos.y > windowSize.y-scrollArea && Utils::getViewOffset(&rGame).y+windowSize.y<mapSize.y) { view.move(0, pos.y-windowSize.y+scrollArea); if (Utils::getViewOffset(&rGame).y+windowSize.y>mapSize.y) { view.move(0, -Utils::getViewOffset(&rGame).y-windowSize.y+mapSize.y); } } else if (pos.y < scrollArea && Utils::getViewOffset(&rGame).y>0) { view.move(0, pos.y-scrollArea); if (Utils::getViewOffset(&rGame).y<0) { view.move(0, -Utils::getViewOffset(&rGame).y); } } if (pos.x > windowSize.x-scrollArea && Utils::getViewOffset(&rGame).x+windowSize.x<mapSize.x) { view.move(pos.x-windowSize.x+scrollArea, 0); if (Utils::getViewOffset(&rGame).x+windowSize.x>mapSize.x) { view.move(-Utils::getViewOffset(&rGame).x-windowSize.x+mapSize.x, 0); } } else if (pos.x < scrollArea && Utils::getViewOffset(&rGame).x>0) { view.move(pos.x-scrollArea, 0); if (Utils::getViewOffset(&rGame).x<0) { view.move(-Utils::getViewOffset(&rGame).x, 0); } } rGame.setView(view); } virtual void onSceneLoadToMemory() { rGame.create(window->getSize().x,window->getSize().y); ///window->setView(view); ///itemy texItemSheet.loadFromFile("files/textures/rpg/items.png"); std::ifstream baseItem("files/maps/rpg/items.txt"); int itemsInRow = 5; for(int j=0, sizeItem =texItemSheet.getSize().x/itemsInRow ; j<texItemSheet.getSize().y/sizeItem; j++) { int id, value, damage; std::string name; for(int i=0; i<itemsInRow; i++) { baseItem >> id >> name >> value >> damage; // std::cout << id << name << value <<damage << std::endl; vecItem.push_back(Item(id,name,texItemSheet, sf::IntRect(i*sizeItem, j*sizeItem,sizeItem,sizeItem),value,damage)); } } texInventoryBackground.loadFromFile("files/textures/rpg/inventoryBackground.png"); inventoryBackground.setTexture(texInventoryBackground); inventoryBackground.setOrigin(texInventoryBackground.getSize().x*0.5,0.5*texInventoryBackground.getSize().y); inventoryBackground.setPosition(window->getSize().x/2,window->getSize().y/2); inventoryBackground.setScale(10,10); texUpRun.loadFromFile("files/textures/rpg/up/run.png"); upRun.setSpriteSheet(&texUpRun, 17, sf::milliseconds(60)); texDownRun.loadFromFile("files/textures/rpg/down/run.png"); downRun.setSpriteSheet(&texDownRun, 17, sf::milliseconds(60)); texRightRun.loadFromFile("files/textures/rpg/right/run.png"); rightRun.setSpriteSheet(&texRightRun, 23, sf::milliseconds(60)); texLeftRun.loadFromFile("files/textures/rpg/left/run.png"); leftRun.setSpriteSheet(&texLeftRun, 23, sf::milliseconds(60)); texDownAttack.loadFromFile("files/textures/rpg/down/attack.png"); downAttack.setSpriteSheet(&texDownAttack, 30, sf::milliseconds(100)); texUpAttack.loadFromFile("files/textures/rpg/up/attack.png"); upAttack.setSpriteSheet(&texUpAttack, 24, sf::milliseconds(100)); texRightAttack.loadFromFile("files/textures/rpg/right/attack.png"); rightAttack.setSpriteSheet(&texRightAttack, 30, sf::milliseconds(100)); texLeftAttack.loadFromFile("files/textures/rpg/left/attack.png"); leftAttack.setSpriteSheet(&texLeftAttack, 30, sf::milliseconds(100)); texSliceDown.loadFromFile("files/textures/rpg/down/projectile.png"); sliceDown.setSpriteSheet(&texSliceDown, 50, sf::milliseconds(12)); texSliceRight.loadFromFile("files/textures/rpg/right/projectile.png"); sliceRight.setSpriteSheet(&texSliceRight, 66, sf::milliseconds(12)); texSliceLeft.loadFromFile("files/textures/rpg/left/projectile.png"); sliceLeft.setSpriteSheet(&texSliceLeft, 66, sf::milliseconds(12)); texIdle.loadFromFile("files/textures/rpg/down/idle.png"); Idle.setSpriteSheet(&texIdle, 15, sf::milliseconds(300)); Player.aSprite.setAnimation(&Idle); Player.aSprite.setScale(5, 5); // Player.aSprite.setOrigin(sf::Vector2f(Player.aSprite.getTextureRect().width*0.5,Player.aSprite.getTextureRect().height*0.5)); texWall.loadFromFile("files/textures/rpg/Wall.png"); tempWall.setTexture(texWall); tempWall.setScale(1, 1); texSkeleton.loadFromFile("files/textures/rpg/enemyStand.png"); enemySkeleton.setSpriteSheet(&texSkeleton, texSkeleton.getSize().x, sf::milliseconds(100)); texChest.loadFromFile("files/textures/rpg/chest.png"); texGrass.loadFromFile("files/textures/rpg/grass.png"); tempGrass.setTexture(texGrass); texDoor.loadFromFile("files/textures/rpg/door.png"); texDoorOpen.loadFromFile("files/textures/rpg/doorOpen.png"); // window->setMouseCursorVisible(0); texCrosshair.loadFromFile("files/textures/rpg/crosshair.png"); spCrosshair.setTexture(texCrosshair); spCrosshair.setOrigin(spCrosshair.getTextureRect().height * 0.5, spCrosshair.getTextureRect().width * 0.5); mapa.loadFromFile("files/maps/rpg/mapa1.png"); chestPath="files/maps/rpg/chest1.txt"; loadMap(mapa, chestPath); temptext.setFont(Common::Font::Digital_7); temptext.setScale(tilesize*0.1,0.1*tilesize); temptext.setOrigin(sf::Vector2f(0,temptext.getLocalBounds().height)); windowSize = sf::Vector2i(window->getSize()); view = sf::View(sf::FloatRect(0, 0, window->getSize().x, window->getSize().y)); } virtual void onSceneActivate() {} void deliverEvent(sf::Event& event) { if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Tab) { if(tab>1) tab=1; tab*=-1; temptext.setString("Inventory"); } if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::E) { for(int i=0; i<vecChest.size(); i++) if(Collision::BoundingBoxTest(Player.aSprite,vecChest[i])) { tab=i+2; temptext.setString("Chest"+Utils::stringify(i)); } } } virtual void draw(sf::Time deltaTime) { float dT = deltaTime.asMilliseconds(); fixView(); if(tab>0) { rGame.draw(inventoryBackground); if(tab>1) rGame.draw(vecItem[vecChest[tab-2].items[0].x]); rGame.draw(temptext); } else { // Player.speedX=0, Player.speedY=0; /// Movement Player.speedX = Player.speedX * 0.5; Player.speedY = Player.speedY * 0.5; /// Kierunki if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && Player.isAttacking == false) { Player.isAttacking = true; if (Player.dir == 'U') { Player.changeAnimation(&upAttack); sliceVec.push_back( Slice(Player.aSprite.getPosition(), &sliceRight, 10, true)); } else if (Player.dir == 'R') { Player.changeAnimation(&rightAttack); sliceVec.push_back( Slice(Player.aSprite.getPosition(), &sliceRight, 10, true)); } else if (Player.dir == 'L') { Player.changeAnimation(&leftAttack); sliceVec.push_back( Slice(Player.aSprite.getPosition(), &sliceLeft, 10, true)); } else { Player.changeAnimation(&downAttack); sliceVec.push_back( Slice(Player.aSprite.getPosition(), &sliceDown, 10, true)); } Player.aSprite.reset(); Player.aSprite.setLooped(false); sliceVec[sliceVec.size() - 1].setLooped(false); sliceVec[sliceVec.size() - 1].setScale(5, 5); } if (Player.aSprite.shouldDestroy()) { Player.isAttacking = false; Player.aSprite.setLooped(true); } if (Player.isAttacking == false) { if (Player.dir != 'N') { if ((Player.dir == 'U' || Player.dir == 'D') && std::abs(Player.speedY) < std::abs(Player.speedX)) Player.dir = 'N', Player.changeAnimation(&Idle); if ((Player.dir == 'R' || Player.dir == 'L') && std::abs(Player.speedY) > std::abs(Player.speedX)) Player.dir = 'N', Player.changeAnimation(&Idle); else if (std::abs(Player.speedX) < 0.5 && std::abs(Player.speedY) < 0.5) Player.dir = 'N', Player.changeAnimation(&Idle); } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up))) { Player.speedY -= 0.6 * Player.basespeed; if (Player.dir == 'N' || Player.dir == 'D') { Player.dir = 'U'; Player.changeAnimation(&upRun); } } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))) { Player.speedY += 0.6 * Player.basespeed; if (Player.dir == 'N' || Player.dir == 'U') { Player.dir = 'D'; Player.changeAnimation(&downRun); } } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left))) { Player.speedX -= 0.6 * Player.basespeed; if (Player.dir == 'N' || Player.dir == 'R') { Player.dir = 'L'; Player.changeAnimation(&leftRun); } } if ((sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right))) { Player.speedX += 0.6 * Player.basespeed; if (Player.dir == 'N' || Player.dir == 'L') { Player.dir = 'R'; Player.changeAnimation(&rightRun); } } if (Player.speedX < -Player.basespeed) Player.speedX = -Player.basespeed; if (Player.speedY < -Player.basespeed) Player.speedY = -Player.basespeed; if (Player.speedX > Player.basespeed) Player.speedX = Player.basespeed; if (Player.speedY > Player.basespeed) Player.speedY = Player.basespeed; staticCollision(Player); if (Player.aSprite.getAnim() == &Idle) Player.aSprite.update(dT); else if (((std::abs(Player.speedX) + std::abs(Player.speedY)) / Player.basespeed) > 1) Player.aSprite.update(dT); else Player.aSprite.update( dT * (std::abs(Player.speedX) + std::abs(Player.speedY)) / (2 * Player.basespeed)); Player.move(Player.speedX, Player.speedY); //view.setCenter(Player.aSprite.getPosition()); rGame.setView(view); } else { staticCollision(Player); if (Player.aSprite.shouldDestroy() == 0) Player.aSprite.update(dT); if ((sf::Keyboard::isKeyPressed(sf::Keyboard::D) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right))) Player.dir = 'R'; else if ((sf::Keyboard::isKeyPressed(sf::Keyboard::A) || sf::Keyboard::isKeyPressed(sf::Keyboard::Left))) Player.dir = 'L'; else if ((sf::Keyboard::isKeyPressed(sf::Keyboard::S) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))) Player.dir = 'D'; else if ((sf::Keyboard::isKeyPressed(sf::Keyboard::W) || sf::Keyboard::isKeyPressed(sf::Keyboard::Up))) Player.dir = 'U'; } /// Kolizja gdzies tu if (Player.speedX < -Player.basespeed) Player.speedX = -Player.basespeed; if (Player.speedY < -Player.basespeed) Player.speedY = -Player.basespeed; if (Player.speedX > Player.basespeed) Player.speedX = Player.basespeed; if (Player.speedY > Player.basespeed) Player.speedY = Player.basespeed; spCrosshair.setPosition(sf::Vector2f(sf::Mouse::getPosition(*window))); // OBRACANIE // DRAW STARTS rGame. clear(sf::Color()); for (int i = 0; i < spGrass.size(); i++) rGame. draw(spGrass[i]); for (int i = 0; i < spWall.size(); i++) rGame. draw(spWall[i]); rGame.draw(spCrosshair); for (int i = 0; i < vecChest.size(); i++) { rGame.draw(vecChest[i]); } for(int i=0; i<vecChest.size(); i++) rGame.draw(vecChest[i]); rGame.draw(Player); // SKELETON MOVEMENT for (int i = vecSkeleton.size()-1; i>=0; i--) { if(vecSkeleton[i].health<=0) { vecSkeleton.erase(vecSkeleton.begin()+i); break; } vecSkeleton[i].AImove(Player.aSprite,this); // vecSkeleton[i].draw(window); rGame.draw(vecSkeleton[i]); if(vecSkeleton[i].aSprite.getColor()==sf::Color(255,0,0)) vecSkeleton[i].aSprite.setColor(sf::Color(255,255,255)); } for (int i = sliceVec.size() - 1; i >= 0; i--) if (sliceVec[i].isPlayer == true) { if (Player.isAttacking == 0) sliceVec.erase(sliceVec.begin() + i); } else if (sliceVec[i].shouldDestroy()) sliceVec.erase(sliceVec.begin() + i); for (int i = 0; i < sliceVec.size(); i++) { sliceVec[i].update(dT); rGame.draw(sliceVec[i]); sliceVec[i].collide(vecSkeleton); } rGame.display(); window->draw(sf::Sprite(rGame.getTexture())); } } protected: sf::RenderTexture rGame; int tab=-1; sf::Text temptext; sf::View view; sf::Vector2i windowSize; sf::Vector2i mapSize = sf::Vector2i(100000, 100000); sf::Image mapa; std::string chestPath; sf::Texture texWall; std::vector<sf::Sprite> spWall; sf::Sprite tempWall; int tilesize = 30; sf::Texture texSkeleton; ARO::Anim enemySkeleton; std::vector<Entity> vecSkeleton; sf::Texture texChest; std::vector<Chestwo> vecChest; sf::Texture texGrass; std::vector<sf::Sprite> spGrass; sf::Sprite tempGrass; sf::Texture texDoor; sf::Texture texDoorOpen; std::vector<sf::Sprite> spDoor; sf::Sprite tempDoor; sf::Texture texCrosshair; sf::Sprite spCrosshair; std::vector<Slice> sliceVec; sf::Texture texSliceDown; ARO::Anim sliceDown; sf::Texture texSliceRight; ARO::Anim sliceRight; sf::Texture texSliceLeft; ARO::Anim sliceLeft; Entity Player; sf::Texture texIdle; ARO::Anim Idle; sf::Texture texDownRun; ARO::Anim downRun; sf::Texture texUpRun; ARO::Anim upRun; sf::Texture texRightRun; ARO::Anim rightRun; sf::Texture texLeftRun; ARO::Anim leftRun; sf::Texture texDownAttack; ARO::Anim downAttack; sf::Texture texUpAttack; ARO::Anim upAttack; sf::Texture texRightAttack; ARO::Anim rightAttack; sf::Texture texLeftAttack; ARO::Anim leftAttack; sf::Texture texItemSheet; std::vector<Item> vecItem; sf::Sprite inventoryBackground; sf::Texture texInventoryBackground; }; #endif // RPG
agpl-3.0
Yusspy/Jolt-Sphere
desktop/src/org/joltsphere/main/desktop/DesktopLauncher.java
831
package org.joltsphere.main.desktop; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration; import org.joltsphere.main.JoltSphereMain; public class DesktopLauncher { static Lwjgl3ApplicationConfiguration config; public static void main(String[] arg) { config = new Lwjgl3ApplicationConfiguration(); config.setWindowedMode(JoltSphereMain.Companion.getWIDTH(), JoltSphereMain.Companion.getHEIGHT()); new Lwjgl3Application(new JoltSphereMain(), config); /*new Lwjgl3Application(new JoltSphereMain() { @Override protected void setFPSLimit(int value) { config.foregroundFPS = value; config.backgroundFPS = value; } }, config); */ } }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-core/src/main/java/com/ephesoft/gxt/core/shared/constant/CoreErrorConstant.java
2819
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.gxt.core.shared.constant; import java.util.logging.Level; /** * Refers to all the error messages which are to be displayed when ever an error situation is encountered. * * <p> * Use this class to either log error messages or for keeping the reference variable to the internationalized messages. * </p> * * @author Ephesoft * @version 1.0. */ public final class CoreErrorConstant { /** * Private Constructor declared so that the Object of the class cannot be initialized. */ private CoreErrorConstant() { // Will ensure that no object of the class cannot be initialized by any mean. throw new UnsupportedOperationException(); } /** * When an invalid Log {@link Level} is encountered. */ public static final String INVALID_LOGGING_LEVEL = "The error message is logged at an invalid level."; }
agpl-3.0
damianmoore/photo-manager
ui/src/components/Settings.js
7259
import React, { useState, useEffect } from 'react' import { useQuery, useMutation } from '@apollo/client' import { useSelector } from 'react-redux' import { getActiveLibrary } from '../stores/libraries/selector' import { Switch, Flex, Stack, FormLabel, // Input, // InputGroup, // IconButton, } from '@chakra-ui/core' import Modal from './Modal' import { SETTINGS_STYLE, SETTINGS_COLOR, SETTINGS_LOCATION, SETTINGS_OBJECT, SETTINGS_FACE, // SETTINGS_SOURCE_FOLDER, GET_SETTINGS, } from '../graphql/settings' // import folder from '../static/images/folder.svg' import '../static/css/Settings.css' export default function Settings() { const activeLibrary = useSelector(getActiveLibrary) const [settings, setSettings] = useSettings(activeLibrary) const availableSettings = [ // { // key: 'sourceDirs', // type: 'path', // label: 'Source folder', // }, { key: 'watchPhotos', type: 'boolean', label: 'Watch folder for new photos', }, { key: 'classificationColorEnabled', type: 'boolean', label: 'Run color analysis on photos', }, { key: 'classificationLocationEnabled', type: 'boolean', label: 'Run location detection on photos', }, { key: 'classificationFaceEnabled', type: 'boolean', label: 'Run face recognition on photos', }, { key: 'classificationStyleEnabled', type: 'boolean', label: 'Run style classification on photos', }, { key: 'classificationObjectEnabled', type: 'boolean', label: 'Run object detection on photos', }, ] function toggleBooleanSetting(key) { let newSettings = { ...settings } newSettings[key] = !settings[key] setSettings(newSettings) switch (key) { case 'classificationStyleEnabled': settingUpdateStyle({ variables: { classificationStyleEnabled: newSettings.classificationStyleEnabled, libraryId: activeLibrary?.id, }, }).catch((e) => {}) return key case 'classificationLocationEnabled': settingUpdateLocation({ variables: { classificationLocationEnabled: newSettings.classificationLocationEnabled, libraryId: activeLibrary?.id, }, }).catch((e) => {}) return key case 'classificationObjectEnabled': settingUpdateObject({ variables: { classificationObjectEnabled: newSettings.classificationObjectEnabled, libraryId: activeLibrary?.id, }, }).catch((e) => {}) return key case 'classificationColorEnabled': settingUpdateColor({ variables: { classificationColorEnabled: newSettings.classificationColorEnabled, libraryId: activeLibrary?.id, }, }).catch((e) => {}) return key case 'classificationFaceEnabled': settingUpdateFace({ variables: { classificationFaceEnabled: newSettings.classificationFaceEnabled, libraryId: activeLibrary?.id, }, }).catch((e) => {}) return key default: return null } } // TODO: Re-implement desktop app settings integration // function onSelectSourceDir() { // if (window.sendSyncToElectron) { // let dirs = window.sendSyncToElectron('select-dir') // setSettings({ sourceDirs: dirs }) // } // } // function onChangeSourceDir(e) { // let newSettings = { ...settings } // newSettings.sourceDirs = e.currentTarget.value // setSettings(newSettings) // settingUpdateSourceFolder({ // variables: { // sourceFolder: newSettings.sourceDirs, // libraryId: activeLibrary?.id, // }, // }).catch((e) => {}) // } const [settingUpdateStyle] = useMutation(SETTINGS_STYLE) const [settingUpdateColor] = useMutation(SETTINGS_COLOR) const [settingUpdateLocation] = useMutation(SETTINGS_LOCATION) const [settingUpdateObject] = useMutation(SETTINGS_OBJECT) const [settingUpdateFace] = useMutation(SETTINGS_FACE) // const [settingUpdateSourceFolder] = useMutation(SETTINGS_SOURCE_FOLDER) return ( <Modal className="Settings" topAccent={true}> <h1 className="heading">Settings</h1> <h2 className="subHeading">{activeLibrary?.name}</h2> <Stack spacing={4}> {availableSettings.map((item, index) => { let field = null if (settings) { if (item.type === 'path') { // field = ( // <InputGroup size="sm"> // <Input // rounded="0" // value={settings ? settings[item.key] : 'empty'} // onChange={onChangeSourceDir} // /> // <IconButton // aria-label="Select source folder" // icon="search" // onClick={onSelectSourceDir} // /> // </InputGroup> // ) } else if (item.type === 'boolean') { field = ( <Switch key={index} id={item.key + 'New'} isChecked={settings[item.key]} onChange={() => toggleBooleanSetting(item.key)} variantColor="cyan" /> ) } } return ( <Flex justify="space-between" key={item.key + item.type}> <FormLabel htmlFor={item.key}>{item.label}</FormLabel> {field} </Flex> ) })} </Stack> </Modal> ) } export const useSettings = (activeLibrary) => { const [existingSettings, setSettings] = useState({}) const { loading, data, refetch } = useQuery(GET_SETTINGS, { variables: { libraryId: activeLibrary?.id }, }) // console.log(error) // const isInitialMount = useRef(true) // useEffect(() => { // refetch() // }, [activeLibrary, refetch]) useEffect(() => { if (activeLibrary && !loading) { refetch() } }, [activeLibrary, loading, refetch]) useEffect(() => { // if (isInitialMount.current) { // isInitialMount.current = false // } else { if (!loading && data) { let setting = { ...data.librarySetting.library } setting.sourceDirs = data.librarySetting.sourceFolder setSettings(setting) } }, [data, loading]) // useEffect(() => { // if (activeLibrary) { // refetch() // } // if (!loading) { // let setting = {...data.librarySetting.library} // setting.sourceDirs = data.librarySetting.sourceFolder // setSettings(setting) // } // if (window.sendSyncToElectron) { // let result = window.sendSyncToElectron('get-settings') // setSettings(result) // } // }, [activeLibrary, loading, refetch, data]) function setAndSaveSettings(newSettings) { // if (window.sendSyncToElectron) { // window.sendSyncToElectron('set-settings', newSettings) // } setSettings(newSettings) } return [existingSettings, setAndSaveSettings] }
agpl-3.0
digitalpetri/ua-server-sdk
ua-server/src/main/java/com/digitalpetri/opcua/sdk/server/model/objects/InitialStateNode.java
1943
/* * digitalpetri OPC-UA SDK * * Copyright (C) 2015 Kevin Herron * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.digitalpetri.opcua.sdk.server.model.objects; import java.util.Optional; import com.digitalpetri.opcua.sdk.core.model.objects.InitialStateType; import com.digitalpetri.opcua.sdk.server.api.UaNodeManager; import com.digitalpetri.opcua.stack.core.types.builtin.LocalizedText; import com.digitalpetri.opcua.stack.core.types.builtin.NodeId; import com.digitalpetri.opcua.stack.core.types.builtin.QualifiedName; import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UByte; import com.digitalpetri.opcua.stack.core.types.builtin.unsigned.UInteger; @com.digitalpetri.opcua.sdk.server.util.UaObjectNode(typeName = "0:InitialStateType") public class InitialStateNode extends StateNode implements InitialStateType { public InitialStateNode( UaNodeManager nodeManager, NodeId nodeId, QualifiedName browseName, LocalizedText displayName, Optional<LocalizedText> description, Optional<UInteger> writeMask, Optional<UInteger> userWriteMask, UByte eventNotifier) { super(nodeManager, nodeId, browseName, displayName, description, writeMask, userWriteMask, eventNotifier); } }
agpl-3.0
NamoDev/Galileo
resources/views/components/modal_data_policy.blade.php
14950
<div class="modal fade" id="dataPolicyModal" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title"><i class="fa fa-legal"></i> Data Policy <span class="text-muted pull-right" style="margin-right:20px;">อัพเดตล่าสุดเมื่อ 22/11/2017</span></h4> </div> <div class="modal-body"> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <p style="font-size:1.3em;font-weight:300;">เราให้อำนาจคุณในการแชร์ข้อมูล ซึ่งเป็นภารกิจของเราในการทำให้น้องๆ สายลำดับสามารถพบกับพี่ๆ ได้สะดวกและง่ายยิ่งขึ้น นโยบายนี้อธิบายว่าข้อมูลอะไรบ้างที่เรารวบรวม และข้อมูลนั้นมีการใช้งานอย่างไร</p> </div> </div> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <h4 class="text-light">เราเก็บรวบรวมข้อมูลประเภทใดบ้าง</h4> <p>เราเก็บรวมรวมข้อมูลประเภทต่างๆ จากคุณหรือเกี่ยวกับตัวคุณ ทั้งนี้โดยขึ้นอยู่กับว่าคุณใช้บริการใด</p> <div class="row"> <div class="col-md-6"> <div class="well"> <small><b>สิ่งที่คุณทำ และข้อมูลที่คุณให้</b></small> <p> เราเก็บรวบรวมเนื้อหาและข้อมูลอื่นๆ ที่คุณให้เมื่อคุณใช้บริการของเรา โดยรวมถึงเมื่อคุณเพิ่มข้อมูลติดต่อเข้าในระบบของเรา ข้อมูลเหล่านี้อาจรวมถึงข้อมูลที่อยู่ในเนื้อหาที่คุณให้ เช่นการฝากข้อความ </p> </div> </div> <div class="col-md-6"> <div class="well"> <small><b>ข้อมูลของอุปกรณ์ และการเชื่อมต่อเครือข่าย</b></small> <p> เราเก็บรวบรวมข้อมูลที่มาจาก หรือเกี่ยวกับคอมพิวเตอร์ โทรศัพท์ หรืออุปกรณ์อื่นๆ ที่คุณใช้ในการเข้าถึงบริการของเรา ตัวอย่างบางส่วนของข้อมูลอุปกรณ์ที่เราเก็บรวบรวม เช่น: </p> <ul> <li>ข้อมูลการเชื่อมต่อ เช่น ชื่อของผู้ให้บริการเครือข่าย ประเภทเบราว์เซอร์ ภาษาและเขตเวลา และที่อยู่ IP (IP address)</li> <li>แอตทริบิวต์ต่างๆ เช่น ระบบปฏิบัติการ ขนาดและความละเอียดของหน้าจอ เวอร์ชันของซอฟต์แวร์และฮาร์ดแวร์</li> </ul> </div> </div> </div> </div> </div> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <h4 class="text-light">ข้อมูลนี้มีการแชร์อย่างไร</h4> <p>จุดมุ่งหมายของเราคือการทำให้น้องลำดับและพี่ๆ สามารถพบกันได้ง่ายยิ่งขึ้น<br />ซึ่งเราทำให้เป็นไปได้โดยการแชร์ข้อมูลของคุณในรูปแบบต่อไปนี้:</p> <div class="row"> <div class="col-md-12"> <div class="well"> <small><b>จัดเก็บข้อมูลเพื่อการค้นหาแบบสาธารณะ</b></small> <p> เมื่อคุณบันทึกข้อมูลติดต่อโดยใช้บริการของเรา เราจะทำการบันทึกข้อมูลนั้น และจัดเก็บเข้าสู่ฐานข้อมูลสายลำดับ ซึ่งเป็นฐานข้อมูลสาธารณะที่สามารถค้นหาได้ (โดยการค้นหาด้วยลำดับ) และเปิดเผยต่อทุกคนทั้งในหรือนอกบริการของเรา <br /><br /> เรามีการใช้มาตรการทางเทคนิคในการป้องกันไม่ให้เครื่องมือค้นหาออนไลน์และโปรแกรมอัตโนมัติทำการจัดเก็บ (index) ข้อมูลสายลำดับ และข้อมูลติดต่อ โดยมีข้อยกเว้นคือระบบจัดเก็บข้อมูลทางประวัติศาสตร์ของ Internet Archive <a href="https://archive.org" target="_blank">(https://archive.org)</a> </p> </div> </div> </div> </div> </div> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <h4 class="text-light">เราใช้ข้อมูลนี้อย่างไร</h4> <div class="row"> <div class="col-md-6"> <div class="well"> <small><b>ให้บริการ ปรับปรุงบริการ และพัฒนาบริการ</b></small> <p> <ul> <li>เราสามารถส่งมอบบริการแก่คุณได้ โดยการใช้ข้อมูลนี้เพื่อทำความเข้าใจว่าคุณใช้และโต้ตอบกับบริการของเราอย่างไร</li> <li>เราวิเคราะห์ข้อมูลที่เรามี เพื่อทำการประเมิน และปรับปรุงการให้บริการของเรา รวมไปถึงการตรวจสอบและการแก้ไขปัญหาต่างๆ</li> <li>ข้อมูลที่จัดเก็บจะถูกรักษาไว้เป็นความลับ ยกเว้นในส่วนของข้อมูลติดต่อ ซึ่งเป็นสาธารณะและสามารถค้นหาได้จากหน้าเว็บของเรา</li> </ul> </p> </div> </div> <div class="col-md-6"> <div class="well"> <small><b>คำขอทางกฎหมาย</b></small> <p> เราอาจเข้าถึง รักษา และแชร์ข้อมูลของคุณเพื่อตอบสนองต่อคำขอตามกฎหมาย (เช่น หมายค้น คำสั่งศาล หรือหมายเรียก) หากเราเชื่อโดยสุจริตว่ากฎหมายต้องการให้เราทำเช่นนั้น และสอดคล้องกับมาตรฐานที่ยอมรับกันโดยสากล <br /><br /> <i class="fa fa-info-circle"></i> จนถึง ณ วันนี้ เรายังไม่เคยรับคำขอเพื่อเปิดเผยข้อมูลจากหน่วยงานราชการใดๆ หากเราได้รับคำขอเช่นนั้น เราจะพยายามอย่างที่สุดในการแจ้งให้สาธารณะทราบถึงคำขอนั้น </p> </div> </div> </div> </div> </div> <hr /> <div class="row"> <div class="col-sm-10 col-sm-offset-1"> <div class="well"> <small><b>ความปลอดภัยของข้อมูล</b></small> <p>เรามีการใช้มาตรการทางเทคนิคตามมาตรฐานความปลอดภัยที่ได้รับการยอมรับโดยสากล เพื่อรักษาความปลอดภัยของระบบ เช่น: </p> <ul> <li>การเข้ารหัสข้อมูลระหว่างการส่งผ่านเครือข่าย โดยมาตรฐาน TLS (transport layer security) เพื่อป้องกันการดักจับข้อมูลระหว่างการส่งผ่านเครือข่าย</li> <li>การจัดเก็บรหัสผ่านแบบเข้ารหัสทางเดียว (hash) ด้วยอัลกอริทึมที่ได้รับการยอมรับโดยสากล เพื่อป้องกันรหัสผ่านรั่วไหล และเพื่อให้คุณมั่นใจได้ว่ารหัสผ่านจะไม่สามารถถูกแปลงกลับได้ในทุกกรณี</li> <li>การรักษาความปลอดภัยทางกายภาพของเครื่องเซิร์ฟเวอร์ (physical server security) ตามมาตรฐานของศูนย์ข้อมูลที่ได้รับการยอมรับโดยสากล (SOC 2 Type II certified datacenter)</li> </ul> </div> <div class="well"> <small><b>Disclaimer</b></small> <p>เว็บไซต์นี้ไม่ใช่เว็บประกาศผล และไม่มีส่วนเกี่ยวข้องกับโรงเรียนเตรียมอุดมศึกษาแต่อย่างใด</p> <p>อนึ่ง ข้อมูลในระบบนี้ ถูกสร้างขึ้นจากการกรอกข้อมูลของแต่ละบุคคลด้วยตนเอง เราไม่มีนโยบายในการสร้างหรือนำข้อมูลจากแหล่งอื่นๆ เข้ามาในระบบ และเราไม่สามารถยืนยันหรือตรวจสอบได้ว่าข้อมูลในระบบเป็นจริงหรือเท็จแต่ประการใด</p> </div> <h6 class="text-light"><i class="fa fa-asterisk"></i> &nbsp;เราใช้คุกกี้และเทคโนโลยีอื่นที่คล้ายคลึงกันในการให้และสนับสนุนบริการของเรา ซึ่งรวมถึง แต่ไม่จำกัดเพียง การยืนยันตัวตนและสิทธิ์การใช้งานของผู้ใช้ การรักษาความปลอดภัย และการวิเคราะห์การใช้งานระบบ (analytics)</h6> </div> </div> </div> </div> </div> </div>
agpl-3.0
marcoalbarelli/PostgreSQL
Symfony/src/Scuola247/Bundle/CoreBundle/Entity/Firme.php
1301
<?php namespace Scuola247\Bundle\CoreBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Firme * * @ORM\Table(name="firme") * @ORM\Entity */ class Firme { /** * @var \DateTime * * @ORM\Column(name="giorno", type="date", nullable=false) */ private $giorno; /** * @var integer * * @ORM\Column(name="periododilezione", type="integer", nullable=false) */ private $periododilezione; /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="SEQUENCE") * @ORM\SequenceGenerator(sequenceName="firme_firma_seq", allocationSize=1, initialValue=1) */ private $id; /** * @var \Scuola247\Bundle\CoreBundle\Entity\Personefisiche * * @ORM\ManyToOne(targetEntity="Scuola247\Bundle\CoreBundle\Entity\Personefisiche") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="docente", referencedColumnName="id") * }) */ private $docente; /** * @var \Scuola247\Bundle\CoreBundle\Entity\Classi * * @ORM\ManyToOne(targetEntity="Scuola247\Bundle\CoreBundle\Entity\Classi") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="classe", referencedColumnName="id") * }) */ private $classe; }
agpl-3.0
ProximoSrl/Jarvis.DocumentStore
src/Jarvis.DocumentStore.Core/Domain/DocumentDescriptor/Commands/InitializeDocumentDescriptorAsAttach.cs
922
using Jarvis.DocumentStore.Core.Model; namespace Jarvis.DocumentStore.Core.Domain.DocumentDescriptor.Commands { public class InitializeDocumentDescriptorAsAttach : InitializeDocumentDescriptor { public DocumentHandle FatherHandle { get; private set; } public DocumentDescriptorId FatherDocumentDescriptorId { get; set; } public InitializeDocumentDescriptorAsAttach( DocumentDescriptorId aggregateId, BlobId blobId, DocumentHandleInfo handleInfo, DocumentHandle fatherHandle, DocumentDescriptorId fatherDocumentDescriptorId, FileHash hash, FileNameWithExtension fileName) : base(aggregateId, blobId, handleInfo, hash, fileName) { FatherHandle = fatherHandle; FatherDocumentDescriptorId = fatherDocumentDescriptorId; } } }
agpl-3.0
jpmml/jpmml-evaluator
pmml-evaluator/src/main/java/org/jpmml/evaluator/HasModel.java
1039
/* * Copyright (c) 2018 Villu Ruusmann * * This file is part of JPMML-Evaluator * * JPMML-Evaluator is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JPMML-Evaluator is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with JPMML-Evaluator. If not, see <http://www.gnu.org/licenses/>. */ package org.jpmml.evaluator; import org.dmg.pmml.Model; /** * <p> * A marker interface for {@link Evaluator} implementations that are backed by an in-memory {@link Model} object. * </p> */ public interface HasModel<M extends Model> extends HasPMML { M getModel(); }
agpl-3.0
yamatt/bbcazlisting
routes/atoz.js
411
var express = require('express'); var router = express.Router(); var datastore = require('../datastore')(); /* GET home page. */ router.get('/:letter/programmes', function(req, res, next) { res.set('Content-Type', 'application/json'); var response = datastore.get(req.params.letter) if (response != undefined) { res.send(response); } else { res.status(404); next(); } }); module.exports = router;
agpl-3.0
jfritz/greenlight
greenlight/urls.py
760
"""greenlight URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ]
agpl-3.0
pgpst/pgpst
internal/github.com/dancannon/gorethink/gorethink_test.go
9317
package gorethink import ( "encoding/json" "flag" "fmt" "math/rand" "os" "runtime" "sync" "testing" "time" test "github.com/pgpst/pgpst/internal/gopkg.in/check.v1" ) var session *Session var debug = flag.Bool("gorethink.debug", false, "print query trees") var testdata = flag.Bool("gorethink.testdata", true, "create test data") var url, url1, url2, url3, db, authKey string func init() { flag.Parse() SetVerbose(true) // If the test is being run by wercker look for the rethink url url = os.Getenv("RETHINKDB_URL") if url == "" { url = "localhost:28015" } url2 = os.Getenv("RETHINKDB_URL_1") if url2 == "" { url2 = "localhost:28016" } url2 = os.Getenv("RETHINKDB_URL_2") if url2 == "" { url2 = "localhost:28017" } url3 = os.Getenv("RETHINKDB_URL_3") if url3 == "" { url3 = "localhost:28018" } db = os.Getenv("RETHINKDB_DB") if db == "" { db = "test" } // Needed for running tests for RethinkDB with a non-empty authkey authKey = os.Getenv("RETHINKDB_AUTHKEY") } // // Begin TestMain(), Setup, Teardown // func testSetup(m *testing.M) { var err error session, err = Connect(ConnectOpts{ Address: url, AuthKey: authKey, }) if err != nil { Log.Fatalln(err.Error()) } setupTestData() } func testTeardown(m *testing.M) { session.Close() } func testBenchmarkSetup() { DBDrop("benchmarks").Exec(session) DBCreate("benchmarks").Exec(session) DB("benchmarks").TableDrop("benchmarks").Run(session) DB("benchmarks").TableCreate("benchmarks").Run(session) } func testBenchmarkTeardown() { DBDrop("benchmarks").Run(session) } func TestMain(m *testing.M) { // seed randomness for use with tests rand.Seed(time.Now().UTC().UnixNano()) testSetup(m) testBenchmarkSetup() res := m.Run() testBenchmarkTeardown() testTeardown(m) os.Exit(res) } // // End TestMain(), Setup, Teardown // // Hook up gocheck into the gotest runner. func Test(t *testing.T) { test.TestingT(t) } type RethinkSuite struct{} var _ = test.Suite(&RethinkSuite{}) // Expressions used in tests var now = time.Now() var arr = []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9} var darr = []interface{}{1, 1, 2, 2, 3, 3, 5, 5, 6} var narr = []interface{}{ 1, 2, 3, 4, 5, 6, []interface{}{ 7.1, 7.2, 7.3, }, } var obj = map[string]interface{}{"a": 1, "b": 2, "c": 3} var nobj = map[string]interface{}{ "A": 1, "B": 2, "C": map[string]interface{}{ "1": 3, "2": 4, }, } var noDupNumObjList = []interface{}{ map[string]interface{}{"id": 1, "g1": 1, "g2": 1, "num": 0}, map[string]interface{}{"id": 2, "g1": 2, "g2": 2, "num": 5}, map[string]interface{}{"id": 3, "g1": 3, "g2": 2, "num": 10}, map[string]interface{}{"id": 5, "g1": 2, "g2": 3, "num": 100}, map[string]interface{}{"id": 6, "g1": 1, "g2": 1, "num": 15}, map[string]interface{}{"id": 8, "g1": 4, "g2": 2, "num": 50}, map[string]interface{}{"id": 9, "g1": 2, "g2": 3, "num": 25}, } var objList = []interface{}{ map[string]interface{}{"id": 1, "g1": 1, "g2": 1, "num": 0}, map[string]interface{}{"id": 2, "g1": 2, "g2": 2, "num": 5}, map[string]interface{}{"id": 3, "g1": 3, "g2": 2, "num": 10}, map[string]interface{}{"id": 4, "g1": 2, "g2": 3, "num": 0}, map[string]interface{}{"id": 5, "g1": 2, "g2": 3, "num": 100}, map[string]interface{}{"id": 6, "g1": 1, "g2": 1, "num": 15}, map[string]interface{}{"id": 7, "g1": 1, "g2": 2, "num": 0}, map[string]interface{}{"id": 8, "g1": 4, "g2": 2, "num": 50}, map[string]interface{}{"id": 9, "g1": 2, "g2": 3, "num": 25}, } var nameList = []interface{}{ map[string]interface{}{"id": 1, "first_name": "John", "last_name": "Smith", "gender": "M"}, map[string]interface{}{"id": 2, "first_name": "Jane", "last_name": "Smith", "gender": "F"}, } var defaultObjList = []interface{}{ map[string]interface{}{"a": 1}, map[string]interface{}{}, } var joinTable1 = []interface{}{ map[string]interface{}{"id": 0, "name": "bob"}, map[string]interface{}{"id": 1, "name": "tom"}, map[string]interface{}{"id": 2, "name": "joe"}, } var joinTable2 = []interface{}{ map[string]interface{}{"id": 0, "title": "goof"}, map[string]interface{}{"id": 2, "title": "lmoe"}, } var joinTable3 = []interface{}{ map[string]interface{}{"it": 0, "title": "goof"}, map[string]interface{}{"it": 2, "title": "lmoe"}, } type TStr string type TMap map[string]interface{} type T struct { A string `gorethink:"id, omitempty"` B int C int `gorethink:"-"` D map[string]interface{} E []interface{} F X } type SimpleT struct { A string B int } type X struct { XA int XB string XC []string XD Y XE TStr XF []TStr } type Y struct { YA int YB map[string]interface{} YC map[string]string YD TMap } type PseudoTypes struct { T time.Time Z time.Time B []byte } var str = T{ A: "A", B: 1, C: 1, D: map[string]interface{}{ "D1": 1, "D2": "2", }, E: []interface{}{ "E1", "E2", "E3", 4, }, F: X{ XA: 2, XB: "B", XC: []string{"XC1", "XC2"}, XD: Y{ YA: 3, YB: map[string]interface{}{ "1": "1", "2": "2", "3": 3, }, YC: map[string]string{ "YC1": "YC1", }, YD: TMap{ "YD1": "YD1", }, }, XE: "XE", XF: []TStr{ "XE1", "XE2", }, }, } func (s *RethinkSuite) BenchmarkExpr(c *test.C) { for i := 0; i < c.N; i++ { // Test query query := Expr(true) err := query.Exec(session) c.Assert(err, test.IsNil) } } func (s *RethinkSuite) BenchmarkNoReplyExpr(c *test.C) { for i := 0; i < c.N; i++ { // Test query query := Expr(true) err := query.Exec(session, ExecOpts{NoReply: true}) c.Assert(err, test.IsNil) } } func (s *RethinkSuite) BenchmarkGet(c *test.C) { // Ensure table + database exist DBCreate("test").RunWrite(session) DB("test").TableCreate("TestMany").RunWrite(session) DB("test").Table("TestMany").Delete().RunWrite(session) // Insert rows data := []interface{}{} for i := 0; i < 100; i++ { data = append(data, map[string]interface{}{ "id": i, }) } DB("test").Table("TestMany").Insert(data).Run(session) for i := 0; i < c.N; i++ { n := rand.Intn(100) // Test query var response interface{} query := DB("test").Table("TestMany").Get(n) res, err := query.Run(session) c.Assert(err, test.IsNil) err = res.One(&response) c.Assert(err, test.IsNil) c.Assert(response, jsonEquals, map[string]interface{}{"id": n}) } } func (s *RethinkSuite) BenchmarkGetStruct(c *test.C) { // Ensure table + database exist DBCreate("test").RunWrite(session) DB("test").TableCreate("TestMany").RunWrite(session) DB("test").Table("TestMany").Delete().RunWrite(session) // Insert rows data := []interface{}{} for i := 0; i < 100; i++ { data = append(data, map[string]interface{}{ "id": i, "name": "Object 1", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }) } DB("test").Table("TestMany").Insert(data).Run(session) for i := 0; i < c.N; i++ { n := rand.Intn(100) // Test query var resObj object query := DB("test").Table("TestMany").Get(n) res, err := query.Run(session) c.Assert(err, test.IsNil) err = res.One(&resObj) c.Assert(err, test.IsNil) } } func (s *RethinkSuite) BenchmarkSelectMany(c *test.C) { // Ensure table + database exist DBCreate("test").RunWrite(session) DB("test").TableCreate("TestMany").RunWrite(session) DB("test").Table("TestMany").Delete().RunWrite(session) // Insert rows data := []interface{}{} for i := 0; i < 100; i++ { data = append(data, map[string]interface{}{ "id": i, }) } DB("test").Table("TestMany").Insert(data).Run(session) for i := 0; i < c.N; i++ { // Test query res, err := DB("test").Table("TestMany").Run(session) c.Assert(err, test.IsNil) var response []map[string]interface{} err = res.All(&response) c.Assert(err, test.IsNil) c.Assert(response, test.HasLen, 100) } } func (s *RethinkSuite) BenchmarkSelectManyStruct(c *test.C) { // Ensure table + database exist DBCreate("test").RunWrite(session) DB("test").TableCreate("TestMany").RunWrite(session) DB("test").Table("TestMany").Delete().RunWrite(session) // Insert rows data := []interface{}{} for i := 0; i < 100; i++ { data = append(data, map[string]interface{}{ "id": i, "name": "Object 1", "Attrs": []interface{}{map[string]interface{}{ "Name": "attr 1", "Value": "value 1", }}, }) } DB("test").Table("TestMany").Insert(data).Run(session) for i := 0; i < c.N; i++ { // Test query res, err := DB("test").Table("TestMany").Run(session) c.Assert(err, test.IsNil) var response []object err = res.All(&response) c.Assert(err, test.IsNil) c.Assert(response, test.HasLen, 100) } } func doConcurrentTest(c *test.C, ct func()) { maxProcs, numReqs := 1, 150 if testing.Short() { maxProcs, numReqs = 4, 50 } defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(maxProcs)) var wg sync.WaitGroup wg.Add(numReqs) reqs := make(chan bool) defer close(reqs) for i := 0; i < maxProcs*2; i++ { go func() { for _ = range reqs { ct() if c.Failed() { wg.Done() continue } wg.Done() } }() } for i := 0; i < numReqs; i++ { reqs <- true } wg.Wait() } // Test utils // Print variable as JSON func jsonPrint(v interface{}) { b, err := json.MarshalIndent(v, "", " ") if err != nil { fmt.Println(err) return } fmt.Println(string(b)) }
agpl-3.0
sohaniacademy/mathstreams
src/Magnets/MathgymBundle/Entity/Chat/Ticket.php
3147
<?php /* * This file is part of Mathstreams. * * Copyright (c) 2015 Sohani Academy <developer@sohaniacademy.com> * * Mathstreams is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace Magnets\MathgymBundle\Entity\Chat; use Doctrine\ORM\Mapping as ORM; /** * Magnets\MathgymBundle\Entity\Chat\Ticket * * @ORM\Table(name="chat_tickets") * @ORM\Entity(repositoryClass="Magnets\MathgymBundle\Entity\Chat\TicketRepository") */ class Ticket { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="\Magnets\MathgymBundle\Entity\User", inversedBy="tickets") * @ORM\JoinColumn(name="user_id", referencedColumnName="id") */ protected $user; /** * @ORM\ManyToOne(targetEntity="Chatroom", inversedBy="tickets") * @ORM\JoinColumn(name="room_id", referencedColumnName="id") */ private $room; /** * @ORM\Column(type="datetime") */ private $expires; public function __construct($room, $user, $expires) { $this->setUser($user); $this->setRoom($room); $this->setExpires($expires); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set user * * @param \Magnets\MathgymBundle\Entity\User $user * @return Ticket */ public function setUser(\Magnets\MathgymBundle\Entity\User $user = null) { $this->user = $user; return $this; } /** * Get user * * @return \Magnets\MathgymBundle\Entity\User */ public function getUser() { return $this->user; } /** * Set room * * @param \Magnets\MathgymBundle\Entity\Chat\Chatroom $room * @return Ticket */ public function setRoom(\Magnets\MathgymBundle\Entity\Chat\Chatroom $room = null) { $this->room = $room; return $this; } /** * Get room * * @return \Magnets\MathgymBundle\Entity\Chat\Chatroom */ public function getRoom() { return $this->room; } /** * Set expires * * @param \DateTime $expires * * @return Ticket */ public function setExpires($expires) { $this->expires = $expires; return $this; } /** * Get expires * * @return \DateTime */ public function getExpires() { return $this->expires; } }
agpl-3.0
ianopolous/Peergos
src/peergos/shared/user/fs/CapabilityStore.java
21206
package peergos.shared.user.fs; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.crypto.hash.*; import peergos.shared.user.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.*; import java.util.stream.*; /** This class implements the mechanism by which users share Capabilities with each other * * Each unidirectional sharing relationship has a sharing folder /source_user/sharing/recipient_user/ * In this sharing directory is an append only list of capabilities which the source user has granted to the recipient * user. This is implemented as a series of numbered files in the directory with a maximum number of capabilities per * file. Knowing the index of the capability in the overall list you can calculate the file name, and the offset in the * file at which the capability is stored. Write and read capabilities form logically separate append only lists. */ public class CapabilityStore { public static final String CAPABILITY_CACHE_DIR = ".capabilitycache"; private static final String READ_SHARING_FILE_NAME = "sharing.r"; private static final String EDIT_SHARING_FILE_NAME = "sharing.w"; public static CompletableFuture<Snapshot> addReadOnlySharingLinkTo(FileWrapper sharedDir, AbsoluteCapability capability, Committer c, NetworkAccess network, Crypto crypto) { return addSharingLinkTo(sharedDir, capability.readOnly(), network, crypto, CapabilityStore.READ_SHARING_FILE_NAME, c); } public static CompletableFuture<Snapshot> addEditSharingLinkTo(FileWrapper sharedDir, WritableAbsoluteCapability capability, Committer c, NetworkAccess network, Crypto crypto) { return addSharingLinkTo(sharedDir, capability, network, crypto, CapabilityStore.EDIT_SHARING_FILE_NAME, c); } private static CompletableFuture<Snapshot> addSharingLinkTo(FileWrapper sharedDir, AbsoluteCapability capability, NetworkAccess network, Crypto crypto, String capStoreFilename, Committer c) { if (! sharedDir.isDirectory() || ! sharedDir.isWritable()) { return Futures.errored(new IllegalArgumentException("Can only add link to a writable directory!")); } return sharedDir.getChild(capStoreFilename, crypto.hasher, network) .thenCompose(capStore -> { byte[] serializedCapability = capability.toCbor().toByteArray(); AsyncReader.ArrayBacked newCapability = new AsyncReader.ArrayBacked(serializedCapability); long startIndex = capStore.map(f -> f.getSize()).orElse(0L); return sharedDir.uploadFileSection(sharedDir.version, c, capStoreFilename, newCapability, false, startIndex, startIndex + serializedCapability.length, Optional.empty(), true, false, network, crypto, x -> {}, crypto.random.randomBytes(32)); }); } /** * * @param cacheDir * @param friendSharedDir * @param friendName * @param network * @param crypto * @return the current byte index, and the valid capabilities */ public static CompletableFuture<CapabilitiesFromUser> loadReadOnlyLinks(FileWrapper cacheDir, FileWrapper friendSharedDir, String friendName, NetworkAccess network, Crypto crypto, boolean inbound) { return loadSharingLinks(cacheDir, friendSharedDir, friendName, network, crypto, inbound, READ_SHARING_FILE_NAME); } /** * * @param cacheDir * @param friendName * @param network * @param crypto * @return the current byte index, and the valid capabilities */ public static CompletableFuture<CapabilitiesFromUser> loadCachedReadOnlyLinks(FileWrapper cacheDir, String friendName, NetworkAccess network, Crypto crypto) { return loadSharingLinksCache(cacheDir, friendName, network, crypto, cacheFilename(true, READ_SHARING_FILE_NAME)); } /** * * @param cacheDir * @param friendSharedDir * @param friendName * @param network * @param crypto * @return the current byte index, and the valid capabilities */ public static CompletableFuture<CapabilitiesFromUser> loadWriteableLinks(FileWrapper cacheDir, FileWrapper friendSharedDir, String friendName, NetworkAccess network, Crypto crypto, boolean inbound) { return loadSharingLinks(cacheDir, friendSharedDir, friendName, network, crypto, inbound, EDIT_SHARING_FILE_NAME); } /** * * @param cacheDir * @param friendName * @param network * @param crypto * @return the current byte index, and the valid capabilities */ public static CompletableFuture<CapabilitiesFromUser> loadCachedWriteableLinks(FileWrapper cacheDir, String friendName, NetworkAccess network, Crypto crypto) { return loadSharingLinksCache(cacheDir, friendName, network, crypto, cacheFilename(true, EDIT_SHARING_FILE_NAME)); } private static CompletableFuture<CapabilitiesFromUser> loadSharingLinks(FileWrapper cacheDir, FileWrapper friendSharedDir, String friendName, NetworkAccess network, Crypto crypto, boolean inbound, String capStoreFilename) { return friendSharedDir.getChild(capStoreFilename, crypto.hasher, network) .thenCompose(capFile -> { if (! capFile.isPresent()) return CompletableFuture.completedFuture(new CapabilitiesFromUser(0, Collections.emptyList())); long capFilesize = capFile.get().getSize(); String cacheFilenameSuffix = cacheFilename(inbound, capStoreFilename); return getSharingCacheFile(friendName, cacheDir, network, crypto, cacheFilenameSuffix).thenCompose(optCachedFile -> { if (! optCachedFile.isPresent()) { return readSharingFile(friendSharedDir.getName(), friendSharedDir.owner(), capFile.get(), network, crypto) .thenCompose(res -> Futures.of(new CapabilitiesFromUser(capFilesize, res))); } else { FileWrapper cachedFile = optCachedFile.get(); return readRetrievedCapabilityCache(cachedFile, network, crypto).thenCompose(cache -> { if (capFilesize == cache.getBytesRead()) return CompletableFuture.completedFuture(cache); return readSharingFile(cache.getBytesRead(), friendSharedDir.getName(), friendSharedDir.owner(), capFile.get(), network, crypto) .thenCompose(res -> Futures.of(new CapabilitiesFromUser(capFilesize, res))); }); } }); }); } private static CompletableFuture<CapabilitiesFromUser> loadSharingLinksCache(FileWrapper cacheDir, String friendName, NetworkAccess network, Crypto crypto, String capStoreFilename) { return getSharingCacheFile(friendName, cacheDir, network, crypto, capStoreFilename) .thenCompose(optCachedFile -> { if(! optCachedFile.isPresent()) { return CompletableFuture.completedFuture(new CapabilitiesFromUser(0, Collections.emptyList())); } else { FileWrapper cachedFile = optCachedFile.get(); return readRetrievedCapabilityCache(cachedFile, network, crypto); } }); } public static CompletableFuture<CapabilitiesFromUser> loadReadAccessSharingLinksFromIndex(FileWrapper cacheDir, FileWrapper friendSharedDir, String friendName, NetworkAccess network, Crypto crypto, long startOffset, boolean saveCache, boolean inbound) { return loadSharingLinksFromIndex(cacheDir, friendSharedDir, friendName, network, crypto, startOffset, saveCache, inbound, READ_SHARING_FILE_NAME); } public static CompletableFuture<CapabilitiesFromUser> loadWriteAccessSharingLinksFromIndex(FileWrapper cacheDir, FileWrapper friendSharedDir, String friendName, NetworkAccess network, Crypto crypto, long startOffset, boolean saveCache, boolean inbound) { return loadSharingLinksFromIndex(cacheDir, friendSharedDir, friendName, network, crypto, startOffset, saveCache, inbound, EDIT_SHARING_FILE_NAME); } private static CompletableFuture<CapabilitiesFromUser> loadSharingLinksFromIndex(FileWrapper cacheDir, FileWrapper friendSharedDir, String friendName, NetworkAccess network, Crypto crypto, long startOffset, boolean saveCache, boolean inbound, String capFilename) { return friendSharedDir.getChild(capFilename, crypto.hasher, network) .thenCompose(file -> { if (! file.isPresent()) return Futures.of(CapabilitiesFromUser.empty()); long capFileSize = file.get().getSize(); if (capFileSize == startOffset) return Futures.of(CapabilitiesFromUser.empty()); return readSharingFile(startOffset, friendSharedDir.getName(), friendSharedDir.owner(), file.get(), network, crypto) .thenCompose(res -> Futures.of(new CapabilitiesFromUser(capFileSize - startOffset, res))); }); } private static String cacheFilename(boolean inbound, String suffix) { return (inbound ? "-in-" : "-out-") + suffix; } public static CompletableFuture<Long> getReadOnlyCapabilityFileSize(FileWrapper friendSharedDir, Crypto crypto, NetworkAccess network) { return getCapabilityFileSize(READ_SHARING_FILE_NAME, friendSharedDir, crypto, network); } public static CompletableFuture<Long> getEditableCapabilityFileSize(FileWrapper friendSharedDir, Crypto crypto, NetworkAccess network) { return getCapabilityFileSize(EDIT_SHARING_FILE_NAME, friendSharedDir, crypto, network); } private static CompletableFuture<Long> getCapabilityFileSize(String filename, FileWrapper friendSharedDir, Crypto crypto, NetworkAccess network) { return friendSharedDir.getChild(filename, crypto.hasher, network) .thenApply(capFile -> capFile.map(f -> f.getFileProperties().size).orElse(0L)); } public static CompletableFuture<List<CapabilityWithPath>> readSharingFile(String ownerName, PublicKeyHash owner, FileWrapper file, NetworkAccess network, Crypto crypto) { return readSharingFile(0, ownerName, owner, file, network, crypto); } public static CompletableFuture<List<CapabilityWithPath>> readSharingFile(long startOffset, String ownerName, PublicKeyHash owner, FileWrapper file, NetworkAccess network, Crypto crypto) { return file.getInputStream(network, crypto, x -> {}) .thenCompose(reader -> reader.seek(startOffset)) .thenCompose(seeked -> readSharingRecords(ownerName, owner, seeked, file.getSize() - startOffset, network)); } private static CompletableFuture<List<CapabilityWithPath>> readSharingRecords(String ownerName, PublicKeyHash owner, AsyncReader reader, long maxBytesToRead, NetworkAccess network) { if (maxBytesToRead == 0) return CompletableFuture.completedFuture(Collections.emptyList()); List<AbsoluteCapability> caps = new ArrayList<>(); return reader.parseStream(AbsoluteCapability::fromCbor, caps::add, maxBytesToRead) .thenCompose(bytesRead -> { return Futures.combineAllInOrder(caps.stream().map(pointer -> { EntryPoint entry = new EntryPoint(pointer, ownerName); return network.retrieveEntryPoint(entry).thenCompose(fileOpt -> { if (fileOpt.isPresent()) { try { CompletableFuture<List<CapabilityWithPath>> res = fileOpt.get().getPath(network) .thenApply(path -> Collections.singletonList(new CapabilityWithPath(path, pointer))); return res; } catch (NoSuchElementException nsee) { return Futures.errored(nsee); //a file ancestor no longer exists!? } } else { return CompletableFuture.completedFuture(Collections.<CapabilityWithPath>emptyList()); } }).exceptionally(t -> Collections.<CapabilityWithPath>emptyList()); }).collect(Collectors.toList())) .thenApply(res -> res.stream().flatMap(x -> x.stream()).collect(Collectors.toList())) .thenCompose(results -> readSharingRecords(ownerName, owner, reader, maxBytesToRead - bytesRead, network) .thenApply(recurse -> Stream.concat(results.stream(), recurse.stream()) .collect(Collectors.toList()))); }); } private static CompletableFuture<Optional<FileWrapper>> getSharingCacheFile(String friendName, FileWrapper cacheDir, NetworkAccess network, Crypto crypto, String filenameSuffix) { return cacheDir.getUpdated(network) .thenCompose(updated -> updated.getChild(friendName + filenameSuffix, crypto.hasher, network)); } private static CompletableFuture<CapabilitiesFromUser> readRetrievedCapabilityCache(FileWrapper cacheFile, NetworkAccess network, Crypto crypto) { return cacheFile.getInputStream(network, crypto, x -> { }) .thenCompose(reader -> { byte[] storeData = new byte[(int) cacheFile.getSize()]; return reader.readIntoArray(storeData, 0, storeData.length) .thenApply(x -> CapabilitiesFromUser.fromCbor(CborObject.fromByteArray(storeData))); }); } }
agpl-3.0
ProtocolSupport/ProtocolSupport
src/protocolsupport/protocol/packet/middle/impl/clientbound/play/v_8_9r1_9r2/EntityEffectAdd.java
1312
package protocolsupport.protocol.packet.middle.impl.clientbound.play.v_8_9r1_9r2; import protocolsupport.protocol.codec.VarNumberCodec; import protocolsupport.protocol.packet.ClientBoundPacketData; import protocolsupport.protocol.packet.ClientBoundPacketType; import protocolsupport.protocol.packet.middle.base.clientbound.play.MiddleEntityEffectAdd; import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV8; import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV9r1; import protocolsupport.protocol.packet.middle.impl.clientbound.IClientboundMiddlePacketV9r2; public class EntityEffectAdd extends MiddleEntityEffectAdd implements IClientboundMiddlePacketV8, IClientboundMiddlePacketV9r1, IClientboundMiddlePacketV9r2 { public EntityEffectAdd(IMiddlePacketInit init) { super(init); } @Override protected void write() { ClientBoundPacketData entityeffectadd = ClientBoundPacketData.create(ClientBoundPacketType.PLAY_ENTITY_EFFECT_ADD); VarNumberCodec.writeVarInt(entityeffectadd, entity.getId()); entityeffectadd.writeByte(effectId); entityeffectadd.writeByte(amplifier); VarNumberCodec.writeVarInt(entityeffectadd, duration); entityeffectadd.writeBoolean((flags & 0x01) != 0); io.writeClientbound(entityeffectadd); } }
agpl-3.0
aborg0/rapidminer-vega
src/liblinear/Model.java
3412
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package liblinear; import java.io.Serializable; import java.util.Arrays; import static liblinear.Linear.copyOf; /** * use {@link Linear#loadModel(String)} and {@link Linear#saveModel(String, Model)} to load/save it */ public final class Model implements Serializable { private static final long serialVersionUID = -6456047576741854834L; public double bias; /** label of each class (label[n]) */ public int[] label; /** number of classes */ public int nr_class; public int nr_feature; public SolverType solverType; public double[] w; public int getNrClass() { return nr_class; } public int getNrFeature() { return nr_feature; } public int[] getLabels() { return copyOf(label, nr_class); } @Override public String toString() { StringBuilder sb = new StringBuilder("Model"); sb.append(" bias=").append(bias); sb.append(" nr_class=").append(nr_class); sb.append(" nr_feature=").append(nr_feature); sb.append(" solverType=").append(solverType); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(bias); result = prime * result + (int)(temp ^ (temp >>> 32)); result = prime * result + Arrays.hashCode(label); result = prime * result + nr_class; result = prime * result + nr_feature; result = prime * result + ((solverType == null) ? 0 : solverType.hashCode()); result = prime * result + Arrays.hashCode(w); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; Model other = (Model)obj; if ( Double.doubleToLongBits(bias) != Double.doubleToLongBits(other.bias) ) return false; if ( !Arrays.equals(label, other.label) ) return false; if ( nr_class != other.nr_class ) return false; if ( nr_feature != other.nr_feature ) return false; if ( solverType == null ) { if ( other.solverType != null ) return false; } else if ( !solverType.equals(other.solverType) ) return false; if ( !Arrays.equals(w, other.w) ) return false; return true; } }
agpl-3.0
ownchan/server-persistence
src/main/java/org/ownchan/server/persistence/typehandler/auto/PhysicalContentTypeTypeHandler.java
1310
/******************************************************************************* * @author Stefan Gündhör <stefan@guendhoer.com> * * @copyright Copyright (c) 2017, Stefan Gündhör <stefan@guendhoer.com> * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> *******************************************************************************/ package org.ownchan.server.persistence.typehandler.auto; import org.apache.ibatis.type.MappedTypes; import org.ownchan.server.joint.persistence.valuetype.PhysicalContentType; @MappedTypes(PhysicalContentType.class) public class PhysicalContentTypeTypeHandler extends PersistableEnumTypeHandler<PhysicalContentType> { public PhysicalContentTypeTypeHandler() { super(); } }
agpl-3.0
dmitr25/demobbed-viewer
js/nuEventsData/nuMu/loadEvent12207011104.js
7671
demobbed.resetEvent(); demobbed.event().id(12207011104); demobbed.event().date(1343187073000); demobbed.event().hitsTT()[0] = [ new HitTT(10000, -212.7, 536.79, 27.89), new HitTT(10001, -204.78, 536.79, 34.05), new HitTT(10002, -212.89, 550.19, 24.77), new HitTT(10003, -207.61, 550.19, 40), new HitTT(10004, -194.41, 550.19, 26.91), new HitTT(10005, -202.33, 550.19, 32.94), new HitTT(10006, -186.39, 563.59, 32.06), new HitTT(10007, -204.87, 563.59, 16.92), new HitTT(10008, -207.51, 563.59, 50.48), new HitTT(10009, -199.59, 563.59, 19.22) ]; demobbed.event().hitsTT()[1] = [ new HitTT(11000, 129.26, 535.33, 10.65), new HitTT(11001, 126.62, 535.33, 145.41), new HitTT(11002, 123.56, 535.33, 134.64), new HitTT(11003, 127.25, 548.73, 24.37), new HitTT(11004, 129.89, 548.73, 23.08), new HitTT(11005, 118.94, 548.73, 95.26), new HitTT(11006, 124.22, 548.73, 142.63), new HitTT(11007, 129.91, 562.13, 13.67), new HitTT(11008, 127.27, 562.13, 3.51), new HitTT(11009, 113.73, 562.13, 40.98), new HitTT(11010, 124.29, 562.13, 56.58) ]; demobbed.event().hitsRPC()[0] = [ new HitRPC(20000, -315.1, 672.71, 2.6), new HitRPC(20001, -207.2, 672.71, 10.4), new HitRPC(20002, -182.5, 672.71, 2.6), new HitRPC(20003, -122.7, 672.71, 7.8), new HitRPC(20004, 230.9, 672.71, 2.6), new HitRPC(20005, 237.4, 672.71, 5.2), new HitRPC(20006, 319.3, 672.71, 153.4), new HitRPC(20007, 276.4, 672.71, 5.2), new HitRPC(20008, -211.1, 679.71, 7.8), new HitRPC(20009, -116.2, 679.71, 15.6), new HitRPC(20010, -211.1, 686.71, 7.8), new HitRPC(20011, -181.2, 686.71, 5.2), new HitRPC(20012, -120.1, 686.71, 2.6), new HitRPC(20013, -112.3, 686.71, 2.6), new HitRPC(20014, -211.1, 693.71, 2.6), new HitRPC(20015, -204.6, 693.71, 5.2), new HitRPC(20016, -182.5, 693.71, 2.6), new HitRPC(20017, -109.7, 693.71, 2.6), new HitRPC(20018, -211.1, 700.71, 2.6), new HitRPC(20019, -204.6, 700.71, 5.2), new HitRPC(20020, -205.9, 707.71, 2.6), new HitRPC(20021, -199.4, 707.71, 5.2), new HitRPC(20022, -204.6, 714.71, 5.2), new HitRPC(20023, -211.1, 721.71, 2.6), new HitRPC(20024, -203.3, 721.71, 2.6), new HitRPC(20025, -212.4, 728.71, 5.2), new HitRPC(20026, -203.3, 728.71, 2.6), new HitRPC(20027, -212.4, 735.71, 5.2), new HitRPC(20028, -200.7, 735.71, 2.6), new HitRPC(20029, -213.7, 742.71, 2.6), new HitRPC(20030, -198.1, 742.71, 2.6), new HitRPC(20031, -218.9, 874.01, 2.6), new HitRPC(20032, -131.8, 874.01, 5.2), new HitRPC(20033, -218.9, 881.01, 2.6), new HitRPC(20034, -218.9, 888.01, 2.6), new HitRPC(20035, -220.2, 895.01, 5.2), new HitRPC(20036, -220.2, 902.01, 5.2), new HitRPC(20037, -221.5, 909.01, 7.8), new HitRPC(20038, -220.2, 916.01, 5.2), new HitRPC(20039, -221.5, 930.01, 2.6), new HitRPC(20040, -220.2, 937.01, 5.2), new HitRPC(20041, -221.5, 944.01, 2.6) ]; demobbed.event().hitsRPC()[1] = [ new HitRPC(21000, 69.05, 672.71, 7), new HitRPC(21001, 79.55, 672.71, 7), new HitRPC(21002, 126.3, 672.71, 3.5), new HitRPC(21003, 150.8, 672.71, 3.5), new HitRPC(21004, 74.3, 679.71, 10.5), new HitRPC(21005, 154.3, 679.71, 10.5), new HitRPC(21006, 74.3, 686.71, 3.5), new HitRPC(21007, 156.05, 686.71, 7), new HitRPC(21008, 74.3, 693.71, 3.5), new HitRPC(21009, 70.8, 700.71, 3.5), new HitRPC(21010, 157.8, 700.71, 3.5), new HitRPC(21011, 150.8, 707.71, 3.5), new HitRPC(21012, 175.3, 707.71, 3.5), new HitRPC(21013, 67.3, 714.71, 3.5), new HitRPC(21014, 63.8, 721.71, 3.5), new HitRPC(21015, 161.3, 721.71, 3.5), new HitRPC(21016, 63.8, 728.71, 3.5), new HitRPC(21017, 164.8, 728.71, 3.5), new HitRPC(21018, 164.8, 735.71, 3.5), new HitRPC(21019, 63.8, 742.71, 3.5), new HitRPC(21020, 164.8, 742.71, 3.5), new HitRPC(21021, 91.8, 874.01, 3.5), new HitRPC(21022, 192.8, 874.01, 3.5), new HitRPC(21023, 192.8, 881.01, 3.5), new HitRPC(21024, 192.8, 888.01, 3.5), new HitRPC(21025, 196.3, 895.01, 3.5), new HitRPC(21026, 196.3, 902.01, 3.5), new HitRPC(21027, 198.05, 909.01, 7), new HitRPC(21028, 199.8, 916.01, 3.5), new HitRPC(21029, 203.3, 930.01, 3.5), new HitRPC(21030, 203.3, 937.01, 3.5), new HitRPC(21031, 203.3, 944.01, 3.5) ]; demobbed.event().hitsDT()[0] = [ new HitDT(30000, -240.05, 574.23, 1.81), new HitDT(30001, -244.25, 574.23, 1.7), new HitDT(30002, -256.85, 574.24, 1.34), new HitDT(30003, -181.25, 574.19, 1.54), new HitDT(30004, -198.05, 574.2, 0.87), new HitDT(30005, -206.45, 574.2, 0.67), new HitDT(30006, -246.35, 577.87, 1.25), new HitDT(30007, -179.15, 577.83, 1.55), new HitDT(30008, -204.35, 577.84, 0.63), new HitDT(30009, -208.55, 577.85, 0.56), new HitDT(30010, -247.44, 581.93, 0.67), new HitDT(30011, -255.84, 581.93, 1.13), new HitDT(30012, -197.04, 581.9, 0.63), new HitDT(30013, -205.44, 581.9, 0.7), new HitDT(30014, -209.64, 581.91, 1.21), new HitDT(30015, -176.04, 581.89, 1.03), new HitDT(30016, -249.54, 585.57, 1.05), new HitDT(30017, -253.74, 585.57, 1.31), new HitDT(30018, -194.94, 585.54, 1.79), new HitDT(30019, -207.54, 585.55, 1.18), new HitDT(30020, -173.94, 585.53, 1.06), new HitDT(30021, -295.74, 644.3, 1.13), new HitDT(30022, -136.14, 644.22, 1.69), new HitDT(30023, -211.74, 644.25, 1.54), new HitDT(30024, -203.34, 644.25, 1.49), new HitDT(30025, -186.54, 644.24, 0.66), new HitDT(30026, -297.84, 647.94, 0.75), new HitDT(30027, -134.04, 647.85, 1.64), new HitDT(30028, -205.44, 647.89, 0.96), new HitDT(30029, -184.44, 647.88, 1.18), new HitDT(30030, -209.64, 647.89, 0.75), new HitDT(30031, -298.93, 652, 1.13), new HitDT(30032, -135.13, 651.91, 1.51), new HitDT(30033, -185.53, 651.94, 0.89), new HitDT(30034, -210.73, 651.95, 0.7), new HitDT(30035, -301.03, 655.64, 1.44), new HitDT(30036, -204.43, 655.59, 0.56), new HitDT(30037, -183.43, 655.58, 0.84), new HitDT(30038, -133.03, 655.55, 1.56), new HitDT(30039, -208.63, 655.59, 1.79), new HitDT(30040, -191.07, 755.53, 0.73), new HitDT(30041, -188.97, 759.16, 0.92), new HitDT(30042, -214.17, 759.18, 0.6), new HitDT(30043, -352.9, 759.26, 0.01), new HitDT(30044, 428.3, 758.85, 1.82), new HitDT(30045, -185.86, 763.22, 0.83), new HitDT(30046, -215.26, 763.24, 0.84), new HitDT(30047, 427.2, 762.91, 1.82), new HitDT(30048, -213.16, 766.88, 1.69), new HitDT(30049, -187.96, 766.86, 1.82), new HitDT(30050, -219.01, 849.57, 0.53), new HitDT(30051, -143.41, 849.51, 1.42), new HitDT(30052, -141.3, 853.15, 1.66), new HitDT(30053, -218, 857.27, 1.38), new HitDT(30054, -142.4, 857.21, 1.29), new HitDT(30055, -220.1, 860.91, 0.81), new HitDT(30056, -140.3, 860.84, 1.05), new HitDT(30057, -224.31, 956.88, 1.59), new HitDT(30058, -222.21, 960.52, 0.59), new HitDT(30059, -210.71, 964.57, 0.94), new HitDT(30060, -214.91, 964.58, 0.69), new HitDT(30061, -219.11, 964.58, 0.57), new HitDT(30062, -223.31, 964.58, 0.95), new HitDT(30063, -217.01, 968.22, 0.74), new HitDT(30064, -221.21, 968.22, 1.47), new HitDT(30065, -222.55, 1058.2, 1.6), new HitDT(30066, -224.65, 1061.84, 0.73), new HitDT(30067, -225.75, 1065.9, 1.61), new HitDT(30068, -223.64, 1069.54, 0.82) ]; demobbed.event().verticesECC([new Vertex([106722, 10043.4, 26716], [-207.128, 124.694, 527.553])]); demobbed.event().tracksECC([ new TrackECC(0, 1, [106708, 10124, 27157], [-0.0231, 0.1835]), new TrackECC(1, 2, [106755, 9469.2, 28430], [0.0174, -0.3352]), new TrackECC(2, 2, [106838, 10811.3, 28430], [0.0712, 0.4696]), new TrackECC(3, 2, [106907, 10375.9, 28430], [0.1036, 0.1853]) ]); demobbed.mgrDrawED().onEventChange(); demobbed.mgrDrawECC().onEventChange();
agpl-3.0
zhangdakun/funasyn
src/com/eben/client/InvalidFormatException.java
1198
/* * Copyright (C) 2010 Moduad Co., Ltd. * * 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.eben.client; /** * Runtime exceptions produced by wrong meta-data settings. * * @author Sehwan Noh (devnoh@gmail.com) */ public class InvalidFormatException extends RuntimeException { private static final long serialVersionUID = 1L; public InvalidFormatException() { super(); } public InvalidFormatException(String message) { super(message); } public InvalidFormatException(Throwable cause) { super(cause); } public InvalidFormatException(String message, Throwable cause) { super(message, cause); } }
agpl-3.0
exomiser/Exomiser
exomiser-core/src/main/java/org/monarchinitiative/exomiser/core/model/SampleGenotypes.java
5995
/* * The Exomiser - A tool to annotate and prioritize genomic variants * * Copyright (c) 2016-2021 Queen Mary University of London. * Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.monarchinitiative.exomiser.core.model; import javax.annotation.Nullable; import java.util.*; import java.util.stream.Stream; public class SampleGenotypes implements Iterable<SampleData> { private final Map<String, SampleData> sampleDataById; private SampleGenotypes(List<SampleData> sampleData) { Objects.requireNonNull(sampleData); this.sampleDataById = buildSamplesMap(sampleData); } private Map<String, SampleData> buildSamplesMap(List<SampleData> samples) { Map<String, SampleData> sampleMap = new LinkedHashMap<>(samples.size()); for (SampleData sampleData : samples) { sampleMap.put(sampleData.getId(), sampleData); } return Collections.unmodifiableMap(sampleMap); } public static SampleGenotypes of(List<SampleData> samples) { return new SampleGenotypes(samples); } public static SampleGenotypes of(SampleData... samples) { return of(List.of(samples)); } public static SampleGenotypes of(String s1, SampleGenotype g1) { return of(SampleData.of(s1, g1)); } public static SampleGenotypes of(String s1, SampleGenotype g1, String s2, SampleGenotype g2) { return of(SampleData.of(s1, g1), SampleData.of(s2, g2)); } public static SampleGenotypes of(String s1, SampleGenotype g1, String s2, SampleGenotype g2, String s3, SampleGenotype g3) { return of(SampleData.of(s1, g1), SampleData.of(s2, g2), SampleData.of(s3, g3)); } public static SampleGenotypes of(String s1, SampleGenotype g1, String s2, SampleGenotype g2, String s3, SampleGenotype g3, String s4, SampleGenotype g4) { return of(SampleData.of(s1, g1), SampleData.of(s2, g2), SampleData.of(s3, g3), SampleData.of(s4, g4)); } public List<SampleData> getSampleData() { return List.copyOf(sampleDataById.values()); } @Nullable public SampleData getSampleData(String sampleId) { return sampleDataById.get(sampleId); } public SampleGenotype getSampleGenotype(String sampleId) { SampleData sampleData = sampleDataById.get(sampleId); return sampleData == null ? SampleGenotype.empty() : sampleData.getSampleGenotype(); } public CopyNumber getSampleCopyNumber(String sampleId) { SampleData sampleData = sampleDataById.get(sampleId); return sampleData == null ? CopyNumber.empty() : sampleData.getCopyNumber(); } public boolean isEmpty() { return sampleDataById.isEmpty(); } public int size() { return sampleDataById.size(); } @Override public Iterator<SampleData> iterator() { return sampleDataById.values().iterator(); } public Stream<SampleData> stream() { return sampleDataById.values().stream(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SampleGenotypes that = (SampleGenotypes) o; return sampleDataById.equals(that.sampleDataById); } @Override public int hashCode() { return Objects.hash(sampleDataById); } @Override public String toString() { StringJoiner commaSeparated = new StringJoiner(", ", "{", "}"); for (SampleData sampleData : sampleDataById.values()) { commaSeparated.add(sampleData.getId() + "=" + formatValues(sampleData)); } return commaSeparated.toString(); } private String formatValues(SampleData sampleData) { String gt = sampleData.getSampleGenotype().toString(); return sampleData.hasCopyNumber() ? gt + ":" + sampleData.getCopyNumber().copies() : gt; } public static class SingleSampleGenotypes implements Iterable<SampleData> { private final SampleData sampleData; public SingleSampleGenotypes(SampleData sampleData) { Objects.requireNonNull(sampleData); this.sampleData = sampleData; } public SampleGenotype getSampleGenotype(String sampleId) { return sampleData.getId().equals(sampleId) ? sampleData.getSampleGenotype() : SampleGenotype.empty(); } public CopyNumber getSampleCopyNumber(String sampleId) { return sampleData.getId().equals(sampleId) ? sampleData.getCopyNumber() : CopyNumber.empty(); } public boolean isEmpty() { return false; } public Iterator<SampleData> iterator() { return new Iterator<>() { int cursor = 0; @Override public boolean hasNext() { return cursor == 0; } @Override public SampleData next() { if (++cursor == 1) { return sampleData; } throw new NoSuchElementException(); } }; } public Stream<SampleData> stream() { return Stream.of(sampleData); } } }
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/interfaces/objects/SUserSession.java
5842
package org.bimserver.interfaces.objects; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import java.util.Date; import javax.xml.bind.annotation.XmlTransient; import java.util.UUID; import org.bimserver.shared.meta.*; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class SUserSession implements SDataBase { private long oid = -1; private UUID uuid; private int rid = 0; @XmlTransient private static SClass sClass; private long userId = -1; private java.lang.String username; private java.lang.String name; private SUserType type; private java.lang.String remoteAddress; private java.util.Date activeSince; private java.util.Date lastActive; private SAccessMethod accessMethod; public long getOid() { return this.oid; } public void setOid(long oid) { this.oid = oid; } public UUID getUuid() { return this.uuid; } public void setUuid(UUID uuid) { this.uuid = uuid; } public int getRid() { return rid; } public void setRid(int rid) { this.rid = rid; } @XmlTransient public SClass getSClass() { return sClass; } public static void setSClass(SClass sClass) { SUserSession.sClass = sClass; } public Object sGet(SField sField) { if (sField.getName().equals("userId")) { return getUserId(); } if (sField.getName().equals("username")) { return getUsername(); } if (sField.getName().equals("name")) { return getName(); } if (sField.getName().equals("type")) { return getType(); } if (sField.getName().equals("remoteAddress")) { return getRemoteAddress(); } if (sField.getName().equals("activeSince")) { return getActiveSince(); } if (sField.getName().equals("lastActive")) { return getLastActive(); } if (sField.getName().equals("accessMethod")) { return getAccessMethod(); } if (sField.getName().equals("oid")) { return getOid(); } if (sField.getName().equals("rid")) { return getRid(); } if (sField.getName().equals("uuid")) { return getUuid(); } throw new RuntimeException("Field " + sField.getName() + " not found"); } public void sSet(SField sField, Object val) { if (sField.getName().equals("userId")) { setUserId((Long)val); return; } if (sField.getName().equals("username")) { setUsername((String)val); return; } if (sField.getName().equals("name")) { setName((String)val); return; } if (sField.getName().equals("type")) { setType((SUserType)val); return; } if (sField.getName().equals("remoteAddress")) { setRemoteAddress((String)val); return; } if (sField.getName().equals("activeSince")) { setActiveSince((Date)val); return; } if (sField.getName().equals("lastActive")) { setLastActive((Date)val); return; } if (sField.getName().equals("accessMethod")) { setAccessMethod((SAccessMethod)val); return; } if (sField.getName().equals("oid")) { setOid((Long)val); return; } if (sField.getName().equals("rid")) { setRid((Integer)val); return; } if (sField.getName().equals("uuid")) { setUuid((UUID)val); return; } throw new RuntimeException("Field " + sField.getName() + " not found"); } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public java.lang.String getUsername() { return username; } public void setUsername(java.lang.String username) { this.username = username; } public java.lang.String getName() { return name; } public void setName(java.lang.String name) { this.name = name; } public SUserType getType() { return type; } public void setType(SUserType type) { this.type = type; } public java.lang.String getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(java.lang.String remoteAddress) { this.remoteAddress = remoteAddress; } public java.util.Date getActiveSince() { return activeSince; } public void setActiveSince(java.util.Date activeSince) { this.activeSince = activeSince; } public java.util.Date getLastActive() { return lastActive; } public void setLastActive(java.util.Date lastActive) { this.lastActive = lastActive; } public SAccessMethod getAccessMethod() { return accessMethod; } public void setAccessMethod(SAccessMethod accessMethod) { this.accessMethod = accessMethod; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (oid ^ (oid >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SUserSession other = (SUserSession) obj; if (oid != other.oid) return false; return true; } }
agpl-3.0
nmunro/azathoth
emotion/migrations/0015_auto_20171203_1606.py
383
# Generated by Django 2.0 on 2017-12-03 16:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emotion', '0014_auto_20171203_1527'), ] operations = [ migrations.AlterField( model_name='emotion', name='percent', field=models.FloatField(default=0), ), ]
agpl-3.0
harish-patel/ecrm
portal/include/SugarFields/Fields/SugarFieldLink/SugarFieldLink.php
2137
<?php /********************************************************************************* * The contents of this file are subject to the SugarCRM Master Subscription * Agreement ("License") which can be viewed at * http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf * By installing or using this file, You have unconditionally agreed to the * terms and conditions of the License, and You may not use this file except in * compliance with the License. Under the terms of the license, You shall not, * among other things: 1) sublicense, resell, rent, lease, redistribute, assign * or otherwise transfer Your rights to the Software, and 2) use the Software * for timesharing or service bureau purposes such as hosting the Software for * commercial gain and/or for the benefit of a third party. Use of the Software * may be subject to applicable fees and any use of the Software without first * paying applicable fees is strictly prohibited. You do not have the right to * remove SugarCRM copyrights from the source code or user interface. * * All copies of the Covered Code must include on each user interface screen: * (i) the "Powered by SugarCRM" logo and * (ii) the SugarCRM copyright notice * in the same form as they appear in the distribution. See full license for * requirements. * * Your Warranty, Limitations of liability and Indemnity are expressly stated * in the License. Please refer to the License for the specific language * governing these rights and limitations under the License. Portions created * by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved. ********************************************************************************/ require_once('include/SugarFields/Fields/SugarFieldBase/SugarFieldBase.php'); class SugarFieldLink extends SugarFieldBase { function getDetailViewSmarty($parentFieldArray, $vardef, $displayParams) { $this->setup($parentFieldArray, $vardef, $displayParams); return $this->ss->fetch('include/SugarFields/Fields/SugarFieldLink/SugarFieldLinkDetailViewSmarty.tpl'); } } ?>
agpl-3.0
printedheart/opennars
nars_gui/src/main/java/automenta/vivisect/swing/property/propertysheet/PropertySheetPanel.java
15441
/** * L2FProd Common v9.2 License. * * Copyright 2005 - 2009 L2FProd.com * * 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 automenta.vivisect.swing.property.propertysheet; import automenta.vivisect.swing.property.swing.IconPool; import automenta.vivisect.swing.property.swing.LookAndFeelTweaks; import automenta.vivisect.swing.property.swing.plaf.blue.BlueishButtonUI; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.beans.BeanInfo; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.util.Comparator; import java.util.Iterator; import java.util.Map; /** * An implementation of a PropertySheet which shows a table to edit/view values, * a description pane which updates when the selection changes and buttons to * toggle between a flat view and a by-category view of the properties. A button * in the toolbar allows to sorted the properties and categories by name. * <p> * Default sorting is by name (case-insensitive). Custom sorting can be * implemented through * {@link com.l2fprod.common.propertysheet.PropertySheetTableModel#setCategorySortingComparator(Comparator)} * and * {@link com.l2fprod.common.propertysheet.PropertySheetTableModel#setPropertySortingComparator(Comparator)} */ public class PropertySheetPanel extends JPanel implements PropertySheet, PropertyChangeListener { private PropertySheetTable table; private PropertySheetTableModel model; private JScrollPane tableScroll; private ListSelectionListener selectionListener = new SelectionListener(); private JPanel actionPanel; private JToggleButton sortButton; private JToggleButton asCategoryButton; private JToggleButton descriptionButton; private JSplitPane split; private int lastDescriptionHeight; private JEditorPane descriptionPanel; private JScrollPane descriptionScrollPane; public PropertySheetPanel() { this(new PropertySheetTable()); } public PropertySheetPanel(PropertySheetTable table) { buildUI(); setTable(table); } /** * Sets the table used by this panel. * * Note: listeners previously added with * {@link PropertySheetPanel#addPropertySheetChangeListener(PropertyChangeListener)} * must be re-added after this call if the table model is not the same as * the previous table. * * @param table */ public void setTable(PropertySheetTable table) { if (table == null) { throw new IllegalArgumentException("table must not be null"); } // remove the property change listener from any previous model if (model != null) model.removePropertyChangeListener(this); // get the model from the table model = (PropertySheetTableModel) table.getModel(); model.addPropertyChangeListener(this); // remove the listener from the old table if (this.table != null) this.table.getSelectionModel().removeListSelectionListener( selectionListener); // prepare the new table table.getSelectionModel().addListSelectionListener(selectionListener); tableScroll.getViewport().setView(table); // use the new table as our table this.table = table; } /** * React to property changes by repainting. */ @Override public void propertyChange(PropertyChangeEvent evt) { repaint(); } /** * @return the table used to edit/view Properties. */ public PropertySheetTable getTable() { return table; } /** * Toggles the visibility of the description panel. * * @param visible */ public void setDescriptionVisible(boolean visible) { if (visible) { add("Center", split); split.setTopComponent(tableScroll); split.setBottomComponent(descriptionScrollPane); // restore the divider location split.setDividerLocation(split.getHeight() - lastDescriptionHeight); } else { // save the size of the description pane to restore it later lastDescriptionHeight = split.getHeight() - split.getDividerLocation(); remove(split); add("Center", tableScroll); } descriptionButton.setSelected(visible); PropertySheetPanel.this.revalidate(); } /** * Toggles the visibility of the toolbar panel * * @param visible */ public void setToolBarVisible(boolean visible) { actionPanel.setVisible(visible); PropertySheetPanel.this.revalidate(); } /** * Set the current mode, either {@link PropertySheet#VIEW_AS_CATEGORIES} or * {@link PropertySheet#VIEW_AS_FLAT_LIST}. */ public void setMode(int mode) { model.setMode(mode); asCategoryButton.setSelected(PropertySheet.VIEW_AS_CATEGORIES == mode); } @Override public void setProperties(Property[] properties) { model.setProperties(properties); } @Override public Property[] getProperties() { return model.getProperties(); } @Override public void addProperty(Property property) { model.addProperty(property); } @Override public void addProperty(int index, Property property) { model.addProperty(index, property); } @Override public void removeProperty(Property property) { model.removeProperty(property); } @Override public int getPropertyCount() { return model.getPropertyCount(); } @Override public Iterator propertyIterator() { return model.propertyIterator(); } public void setBeanInfo(BeanInfo beanInfo) { setProperties(beanInfo.getPropertyDescriptors()); } public void setProperties(PropertyDescriptor[] descriptors) { Property[] properties = new Property[descriptors.length]; for (int i = 0, c = descriptors.length; i < c; i++) { properties[i] = new PropertyDescriptorAdapter(descriptors[i]); } setProperties(properties); } /** * Initializes the PropertySheet from the given object. If any, it cancels * pending edit before proceeding with properties. * * @param data */ public void readFromObject(Object data) { // cancel pending edits getTable().cancelEditing(); Property[] properties = model.getProperties(); for (int i = 0, c = properties.length; i < c; i++) { properties[i].readFromObject(data); } repaint(); } /** * Writes the PropertySheet to the given object. If any, it commits pending * edit before proceeding with properties. * * @param data */ public void writeToObject(Object data) { // ensure pending edits are committed getTable().commitEditing(); Property[] properties = getProperties(); for (int i = 0, c = properties.length; i < c; i++) { properties[i].writeToObject(data); } } public void addPropertySheetChangeListener(PropertyChangeListener listener) { model.addPropertyChangeListener(listener); } public void removePropertySheetChangeListener(PropertyChangeListener listener) { model.removePropertyChangeListener(listener); } public void setEditorFactory(PropertyEditorFactory factory) { table.setEditorFactory(factory); } public PropertyEditorFactory getEditorFactory() { return table.getEditorFactory(); } /** * @deprecated use {@link #setEditorFactory(PropertyEditorFactory)} * @param registry */ @Deprecated public void setEditorRegistry(PropertyEditorRegistry registry) { table.setEditorFactory(registry); } /** * @deprecated use {@link #getEditorFactory()} */ @Deprecated public PropertyEditorRegistry getEditorRegistry() { return (PropertyEditorRegistry) table.getEditorFactory(); } public void setRendererFactory(PropertyRendererFactory factory) { table.setRendererFactory(factory); } public PropertyRendererFactory getRendererFactory() { return table.getRendererFactory(); } /** * @deprecated use {@link #setRendererFactory(PropertyRendererFactory)} * @param registry */ @Deprecated public void setRendererRegistry(PropertyRendererRegistry registry) { table.setRendererRegistry(registry); } /** * @deprecated use {@link #getRendererFactory()} */ @Deprecated public PropertyRendererRegistry getRendererRegistry() { return table.getRendererRegistry(); } /** * Sets sorting of categories enabled or disabled. * * @param value true to enable sorting */ public void setSortingCategories(boolean value) { model.setSortingCategories(value); sortButton.setSelected(isSorting()); } /** * Is sorting of categories enabled. * * @return true if category sorting is enabled */ public boolean isSortingCategories() { return model.isSortingCategories(); } /** * Sets sorting of properties enabled or disabled. * * @param value true to enable sorting */ public void setSortingProperties(boolean value) { model.setSortingProperties(value); sortButton.setSelected(isSorting()); } /** * Is sorting of properties enabled. * * @return true if property sorting is enabled */ public boolean isSortingProperties() { return model.isSortingProperties(); } /** * Sets sorting properties and categories enabled or disabled. * * @param value true to enable sorting */ public void setSorting(boolean value) { model.setSortingCategories(value); model.setSortingProperties(value); sortButton.setSelected(value); } /** * @return true if properties or categories are sorted. */ public boolean isSorting() { return model.isSortingCategories() || model.isSortingProperties(); } /** * Sets the Comparator to be used with categories. Categories are treated as * String-objects. * * @param comp java.other.Comparator used to compare categories */ public void setCategorySortingComparator(Comparator comp) { model.setCategorySortingComparator(comp); } /** * Sets the Comparator to be used with Property-objects. * * @param comp java.other.Comparator used to compare Property-objects */ public void setPropertySortingComparator(Comparator comp) { model.setPropertySortingComparator(comp); } /** * Set wether or not toggle states are restored when new properties are * applied. * * @param value true to enable */ public void setRestoreToggleStates(boolean value) { model.setRestoreToggleStates(value); } /** * @return true is toggle state restore is enabled */ public boolean isRestoreToggleStates() { return model.isRestoreToggleStates(); } /** * @return the category view toggle states. */ public Map getToggleStates() { return model.getToggleStates(); } /** * Sets the toggle states for the category views. Note this <b>MUST</b> be * called <b>BEFORE</b> setting any properties. * * @param toggleStates the toggle states as returned by getToggleStates */ public void setToggleStates(Map toggleStates) { model.setToggleStates(toggleStates); } private void buildUI() { LookAndFeelTweaks.setBorderLayout(this); LookAndFeelTweaks.setBorder(this); actionPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 2, 0)); actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 0, 2, 0)); actionPanel.setOpaque(false); add("North", actionPanel); sortButton = new JToggleButton(new ToggleSortingAction()); sortButton.setUI(new BlueishButtonUI()); sortButton.setText(null); sortButton.setOpaque(false); actionPanel.add(sortButton); asCategoryButton = new JToggleButton(new ToggleModeAction()); asCategoryButton.setUI(new BlueishButtonUI()); asCategoryButton.setText(null); asCategoryButton.setOpaque(false); actionPanel.add(asCategoryButton); descriptionButton = new JToggleButton(new ToggleDescriptionAction()); descriptionButton.setUI(new BlueishButtonUI()); descriptionButton.setText(null); descriptionButton.setOpaque(false); actionPanel.add(descriptionButton); split = new JSplitPane(JSplitPane.VERTICAL_SPLIT); split.setBorder(null); split.setResizeWeight(1.0); split.setContinuousLayout(true); add("Center", split); tableScroll = new JScrollPane(); tableScroll.setBorder(BorderFactory.createEmptyBorder()); split.setTopComponent(tableScroll); descriptionPanel = new JEditorPane("text/html", "<html>"); descriptionPanel.setBorder(BorderFactory.createEmptyBorder()); descriptionPanel.setEditable(false); descriptionPanel.setBackground(UIManager.getColor("Panel.background")); LookAndFeelTweaks.htmlize(descriptionPanel); selectionListener = new SelectionListener(); descriptionScrollPane = new JScrollPane(descriptionPanel); descriptionScrollPane.setBorder(LookAndFeelTweaks.addMargin(BorderFactory .createLineBorder(UIManager.getColor("controlDkShadow")))); descriptionScrollPane.getViewport().setBackground( descriptionPanel.getBackground()); descriptionScrollPane.setMinimumSize(new Dimension(50, 50)); split.setBottomComponent(descriptionScrollPane); // by default description is not visible, toolbar is visible. setDescriptionVisible(false); setToolBarVisible(true); } class SelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { int row = table.getSelectedRow(); Property prop = null; if (row >= 0 && table.getRowCount() > row) prop = model.getPropertySheetElement(row).getProperty(); if (prop != null) { descriptionPanel.setText("<html>" + "<b>" + (prop.getDisplayName() == null ? "" : prop.getDisplayName()) + "</b><br>" + (prop.getShortDescription() == null ? "" : prop .getShortDescription())); } else { descriptionPanel.setText("<html>"); } // position it at the top descriptionPanel.setCaretPosition(0); } } class ToggleModeAction extends AbstractAction { public ToggleModeAction() { super("toggle", IconPool.shared().get( PropertySheet.class.getResource("icons/category.gif"))); /*putValue(Action.SHORT_DESCRIPTION, ResourceManager.get( PropertySheet.class).getString( "PropertySheetPanel.category.shortDescription"));*/ } @Override public void actionPerformed(ActionEvent e) { if (asCategoryButton.isSelected()) { model.setMode(PropertySheet.VIEW_AS_CATEGORIES); } else { model.setMode(PropertySheet.VIEW_AS_FLAT_LIST); } } } class ToggleDescriptionAction extends AbstractAction { public ToggleDescriptionAction() { super("toggleDescription", IconPool.shared().get( PropertySheet.class.getResource("icons/description.gif"))); /*putValue(Action.SHORT_DESCRIPTION, ResourceManager.get( PropertySheet.class).getString( "PropertySheetPanel.description.shortDescription"));*/ } @Override public void actionPerformed(ActionEvent e) { setDescriptionVisible(descriptionButton.isSelected()); } } class ToggleSortingAction extends AbstractAction { public ToggleSortingAction() { super("toggleSorting", IconPool.shared().get( PropertySheet.class.getResource("icons/sorted.gif"))); /*putValue(Action.SHORT_DESCRIPTION, ResourceManager.get( PropertySheet.class).getString( "PropertySheetPanel.sorted.shortDescription"));*/ } @Override public void actionPerformed(ActionEvent e) { setSorting(sortButton.isSelected()); } } }
agpl-3.0
icedream/gmod-disguiser
lua/weapons/disguiser/init.lua
11546
/** * Disguiser SWEP - Lets you disguise as any prop on a map. * * File: * init.lua * * Purpose: * Initializes server-side stuff including weapon information, actual weapon * hooks and whatever stuff is also needed to make the server work on servers. * * Copyright (C) 2013 Carl Kittelberger (Icedream) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Weapon info for server SWEP.Weight = 5 SWEP.AutoSwitchTo = true SWEP.AutoSwitchFrom = false SWEP.ShouldDropOnDie = false // DEBUG DEBUG DEBUG print("[Disguiser] Loading serverside...") // Downloads for the client // TODO: Dynamic file addition here AddCSLuaFile("cl_init.lua") AddCSLuaFile("cl_3rdperson.lua") AddCSLuaFile("cl_obb.lua") AddCSLuaFile("cl_fxfake.lua") AddCSLuaFile("cl_worldtips.lua") AddCSLuaFile("sh_init.lua") // Shared stuff include("sh_init.lua") // Local stuff SWEP.UndisguiseAs = nil SWEP.UndisguiseAsMass = nil SWEP.UndisguiseAsSkin = nil SWEP.UndisguiseAsSolid = nil SWEP.UndisguiseAsFullRotation = nil SWEP.DisguisedAs = nil // Banned prop models SWEP.PropConfiguration = { ["models/props/cs_assault/dollar.mdl"] = { Banned = true }, ["models/props/cs_assault/money.mdl"] = { Banned = true }, ["models/props/cs_office/snowman_arm.mdl"] = { Banned = true }, ["models/props/cs_office/computer_mouse.mdl"] = { Banned = true }, ["models/props/cs_office/projector_remote.mdl"] = { Banned = true }, ["models/props_junk/bicycle01a.mdl"] = { // The bicycle in cs_italy has a too big bounding box, you // can't even get through doors without this correction OBBMinsCorrection = Vector(28, -28, 0), OBBMaxsCorrection = Vector(-28, 28, 0) } // TODO: There is another item on cs_office which needs to be corrected. Forgot which one though. } // Door exploits local ExploitableDoors = { "func_door", "prop_door_rotating", "func_door_rotating" } // The actual disguise action function SWEP:Disguise(entity) // Make sure the model file is not banned if self:HasPropConfig(entity:GetModel()) && self:GetPropConfig(entity:GetModel()).Banned then umsg.Start("cantDisguiseAsBannedProp") umsg.End() return end // Make sure we are valid if (!IsValid(self)) then return false end // Make sure the player is alive and valid if (!IsValid(self.Owner) || !self.Owner:Alive()) then return false end local owner = self.Owner // Make sure we aren't already that model if (owner:GetModel() == entity:GetModel() && owner:GetSkin() == entity:GetSkin() && owner:GetColor() == entity:GetColor()) then return true end // Make sure the new model is actually marked as a prop if ( string.sub(string.lower(entity:GetClass()), 1, 5) != "prop_" && string.sub(string.lower(entity:GetClass()), -5, -1) != "_prop" && string.find(string.lower(entity:GetClass()), "_prop_") == nil ) then return false end local physobj = entity:GetPhysicsObject() local ophysobj = owner:GetPhysicsObject() // Back up model if (!self.UndisguiseAs) then self.UndisguiseAs = owner:GetModel() self.UndisguiseAsSkin = owner:GetSkin() self.UndisguiseAsMass = ophysobj:GetMass() self.UndisguiseAsColor = owner:GetColor() self.UndisguiseAsBloodColor = owner:GetBloodColor() self.UndisguiseAsSolid = owner:GetSolid() end // Disguise as given model self:EnableThirdPerson(owner) owner:DrawViewModel(false) owner:DrawWorldModel(false) owner:SetModel(entity:GetModel()) owner:SetSolid(SOLID_BSP) owner:SetBloodColor(BLOOD_COLOR_RED) if entity:GetSkin() != nil then owner:SetSkin(entity:GetSkin()) // coloring end owner:SetColor(entity:GetColor()) owner:SetPos(owner:GetPos() - Vector(0, 0, entity:OBBMins().z - 2)) // anti-stuck // Apply new physics, too ophysobj:SetMass(physobj:GetMass()) self:UpdateHealth(math.Clamp(physobj:GetVolume() / 300, 1, 200)) // Apply new hull local obbmaxs = entity:OBBMaxs() local obbmins = entity:OBBMins() // Look for correction values local pcfg = self:GetPropConfig(entity:GetModel()) if !!pcfg["OBBMaxsCorrection"] then obbmaxs = obbmaxs + pcfg["OBBMaxsCorrection"] end if !!pcfg["OBBMinsCorrection"] then obbmins = obbmins + pcfg["OBBMinsCorrection"] end owner:SetHull(obbmins, obbmaxs) owner:SetHullDuck(obbmins, obbmaxs) -- ducking shouldn't work for props // Notify all clients about the new hull so the player appears // correct for everyone umsg.Start("setBounding") umsg.Entity(owner) umsg.Vector(entity:OBBMins()) umsg.Vector(entity:OBBMaxs()) umsg.End() // Pop! owner:EmitSound("Disguiser.Disguise") // We're now disguised! owner:SetNetworkedBool("isDisguised", true) self.DisguisedAs = entity:GetModel() owner.Disguised = true // DEBUG DEBUG DEBUG print(owner:Name() .. " switched to model " .. entity:GetModel()) return true end // Undisguise function SWEP:Undisguise() // Make sure we are valid if (!IsValid(self)) then return false end // Make sure the player is alive and valid if (!IsValid(self.Owner) || !self.Owner:Alive()) then return false end // Make sure we are disguised already if (self.DisguisedAs == nil) then return false end // Make sure we have an old model to revert to if (self.UndisguiseAs == nil) then return false end local owner = self.Owner local ophysobj = owner:GetPhysicsObject() // Revert to old model owner:SetModel(self.UndisguiseAs) owner:SetMoveType(MOVETYPE_WALK) if self.UndisguiseAsSkin != nil then owner:SetSkin(self.UndisguiseAsSkin) end owner:SetColor(self.UndisguiseAsColor) owner:SetSolid(self.UndisguiseAsSolid) owner:SetBloodColor(self.UndisguiseAsBloodColor) // Revert to old physics ophysobj:SetMass(self.UndisguiseAsMass) self:UpdateHealth(100) // Hull reset owner:ResetHull() owner:SetPos(owner:GetPos() - Vector(0, 0,owner:OBBMins().z - 2)) // anti-stuck umsg.Start("resetHull", owner) umsg.Entity(owner) umsg.End() // Pop! owner:EmitSound("Disguiser.Undisguise") // We're no longer disguised owner:SetNetworkedBool("isDisguised", false) self:DisableThirdPerson(owner) owner:DrawViewModel(true) owner:DrawWorldModel(true) self.UndisguiseAs = nil self.DisguisedAs = nil owner.Disguised = false return true end function SWEP:UpdateHealth(ent_health) local player = self.Owner if (!player || !IsValid(player)) then return false end // Scale player health up to entity's maximum health local new_health = math.Clamp((player:Health() / player:GetMaxHealth()) * ent_health, 1, 200) // Transfer to player player:SetHealth(new_health) player:SetMaxHealth(ent_health) end // this is usually triggered on left mouse click function SWEP:PrimaryAttack() local trace = util.TraceLine({ start = self.Owner:GetShootPos(), endpos = self.Owner:GetShootPos() + (self.Owner:GetAimVector() * 900 /* pretty cheaty */), filter = self.Owner, mask = MASK_SHOT }) // Are we aiming at an actual prop? local entity = trace.Entity if !trace.HitNonWorld || !trace.Entity || !entity:GetModel() || table.HasValue(ExploitableDoors, entity:GetClass()) // banned door exploit then return false end // Make sure the model is not banned if self:GetPropConfig(entity:GetModel()).Banned then umsg.Start("cantDisguiseAsBannedProp") umsg.Entity(entity) umsg.End() return false end // Make sure the new model is actually marked as a prop if ( string.sub(string.lower(entity:GetClass()), 1, 5) != "prop_" && string.sub(string.lower(entity:GetClass()), -5, -1) != "_prop" && string.find(string.lower(entity:GetClass()), "_prop_") == nil ) then return false end // Now let's disguise, shall we? self:DoShootEffect(trace.HitPos, trace.HitNormal, trace.Entity, trace.PhysicsBone, IsFirstTimePredicted()) self:Disguise(entity) end // this is usually triggered on right mouse click function SWEP:SecondaryAttack() self:Undisguise() end function SWEP:DisableThirdPerson(player) if !player:GetNetworkedBool("thirdperson") then return end local entity = player:GetViewEntity() player:SetNetworkedBool("thirdperson", false) entity:Remove() player:SetViewEntity(player) end function SWEP:EnableThirdPerson(player) if player:GetNetworkedBool("thirdperson") then return end local entity = ents.Create("prop_dynamic") entity:SetModel(player:GetModel()) entity:Spawn() entity:SetAngles(player:GetAngles()) entity:SetVelocity(player:GetVelocity()) entity:SetMoveType(MOVETYPE_NONE) entity:SetParent(player) entity:SetOwner(player) entity:SetPos(player:GetPos() + Vector(0, 0, 60)) entity:SetRenderMode(RENDERMODE_NONE) entity:SetSolid(SOLID_NONE) player:SetViewEntity(entity) player:SetNetworkedBool("thirdperson", true) end hook.Add("PlayerDeath", "Disguiser.ThirdPersonDeath", function(victim, inflictor, killer) // Escape third-person mode if victim:GetNWBool("thirdperson") then victim:SetNetworkedBool("thirdperson", false) local ventity = victim:GetViewEntity() if (IsValid(ventity)) then victim:SetViewEntity(victim) ventity:Remove() end end // Undisguise basically but with a few tweaks to avoid some bugs if victim:GetNWBool("isDisguised") then victim:SetNetworkedBool("isDisguised", false) // fake entity for spectacular death! local dentity = ents.Create("prop_physics") dentity:SetModel(victim:GetModel()) if !!victim:GetSkin() then dentity:SetSkin(victim:GetSkin()) end dentity:SetColor(victim:GetColor()) dentity:SetAngles(victim:GetAngles()) dentity:SetPos(victim:GetPos()) dentity:SetVelocity(victim:GetVelocity()) local physics = victim:GetPhysicsObject() if !!victim:GetBloodColor() then dentity:SetBloodColor(victim:GetBloodColor()) -- this thing was alive, ya know? :( end dentity:Spawn() local dphysics = dentity:GetPhysicsObject() dphysics:SetAngles(physics:GetAngles()) dphysics:SetVelocity(physics:GetVelocity()) dphysics:SetDamping(physics:GetDamping()) dphysics:SetInertia(physics:GetInertia()) dentity:Fire("break", "", 0) dentity:Fire("kill", "", 1) dentity:Fire("enablemotion","",0) // Let the entity bleed wahahaha. I'm mad, ain't I? local traceworld = {} traceworld.start = victim:GetPos() + Vector(0, 0, 20) traceworld.endpos = traceworld.start + (Vector(0,0,-1) * 8000) // aim max. 8000 units down traceworld.filter = victim local trw = util.TraceLine(traceworld) // Send the trace and get the results. local edata = EffectData() edata:SetStart(victim:GetPos() - physics:GetVelocity()) edata:SetOrigin(victim:GetPos()) edata:SetNormal(trw.Normal) edata:SetEntity(dentity) util.Effect("BloodImpact", edata) // Reset the victim's bounding box to solve the issue with getting stuck at spawn victim:ResetHull() umsg.Start("resetHull", victim) umsg.Entity(victim) umsg.End() end end) function SWEP:HasPropConfig(name) return !!self.PropConfiguration && !!self.PropConfiguration[name] end function SWEP:GetPropConfig(name) return self.PropConfiguration[name] or {} end
agpl-3.0
gymnasium/edx-platform
lms/djangoapps/badges/models.py
12332
""" Database models for the badges app """ from importlib import import_module from config_models.models import ConfigurationModel from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import ugettext_lazy as _ from jsonfield import JSONField from lazy import lazy from model_utils.models import TimeStampedModel from opaque_keys import InvalidKeyError from opaque_keys.edx.django.models import CourseKeyField from opaque_keys.edx.keys import CourseKey from badges.utils import deserialize_count_specs from xmodule.modulestore.django import modulestore def validate_badge_image(image): """ Validates that a particular image is small enough to be a badge and square. """ if image.width != image.height: raise ValidationError(_(u"The badge image must be square.")) if not image.size < (250 * 1024): raise ValidationError(_(u"The badge image file size must be less than 250KB.")) def validate_lowercase(string): """ Validates that a string is lowercase. """ if not string.islower(): raise ValidationError(_(u"This value must be all lowercase.")) class CourseBadgesDisabledError(Exception): """ Exception raised when Course Badges aren't enabled, but an attempt to fetch one is made anyway. """ class BadgeClass(models.Model): """ Specifies a badge class to be registered with a backend. """ slug = models.SlugField(max_length=255, unique=True) issuing_component = models.SlugField(max_length=50, default='', blank=True, validators=[validate_lowercase]) display_name = models.CharField(max_length=255) course_id = CourseKeyField(max_length=255, blank=True, default=None) description = models.TextField() criteria = models.TextField() # TODO: Badgr and Open Badges spec can take both text and url criteria mode = models.CharField(max_length=100, default='', blank=True) image = models.ImageField(upload_to='badge_classes', validators=[validate_badge_image]) def __unicode__(self): return u"<Badge '{slug}' for '{issuing_component}', {course_id} {mode}>".format( slug=self.slug, issuing_component=self.issuing_component, course_id=unicode(self.course_id), mode=self.mode ) @classmethod def get_badge_class( cls, slug=None, issuing_component=None, display_name=None, description=None, criteria=None, image_file_handle=None, mode='', course_id=None, create=True ): """ Looks up a badge class by its slug, or combination of mode and course_id and returns it should it exist. If it does not exist, and create is True, creates it according to the arguments. Otherwise, returns None. The expectation is that an XBlock or platform developer should not need to concern themselves with whether or not a badge class has already been created, but should just feed all requirements to this function and it will 'do the right thing'. It should be the exception, rather than the common case, that a badge class would need to be looked up without also being created were it missing. """ if course_id and not modulestore().get_course(course_id).issue_badges: raise CourseBadgesDisabledError("This course does not have badges enabled.") if not course_id: course_id = CourseKeyField.Empty try: if slug: return cls.objects.get(slug=slug) else: if mode: return cls.objects.get(mode=mode, course_id=course_id) else: # allow setting a BadgeClass with no mode, can be used for all modes return cls.objects.get(course_id=course_id) except cls.DoesNotExist: if not create: return None badge_class = cls( slug=slug, issuing_component=issuing_component, display_name=display_name, course_id=course_id, mode=mode, description=description, criteria=criteria, ) badge_class.image.save(image_file_handle.name, image_file_handle) badge_class.full_clean() badge_class.save() return badge_class @lazy def backend(self): """ Loads the badging backend. """ module, klass = settings.BADGING_BACKEND.rsplit('.', 1) module = import_module(module) return getattr(module, klass)() def get_for_user(self, user): """ Get the assertion for this badge class for this user, if it has been awarded. """ return self.badgeassertion_set.filter(user=user) def award(self, user, evidence_url=None): """ Contacts the backend to have a badge assertion created for this badge class for this user. """ return self.backend.award(self, user, evidence_url=evidence_url) # def save(self, **kwargs): # #""" # # Slugs must always be lowercase. # #""" # super(BadgeClass, self).save(**kwargs) class Meta(object): app_label = "badges" unique_together = (('mode', 'course_id'),) verbose_name_plural = "Badge Classes" class BadgeAssertion(TimeStampedModel): """ Tracks badges on our side of the badge baking transaction """ user = models.ForeignKey(User, on_delete=models.CASCADE) badge_class = models.ForeignKey(BadgeClass, on_delete=models.CASCADE) data = JSONField() backend = models.CharField(max_length=50) image_url = models.URLField() assertion_url = models.URLField() def __unicode__(self): return u"<{username} Badge Assertion for {slug} for {issuing_component}".format( username=self.user.username, slug=self.badge_class.slug, issuing_component=self.badge_class.issuing_component, ) @classmethod def assertions_for_user(cls, user, course_id=None): """ Get all assertions for a user, optionally constrained to a course. """ if course_id: return cls.objects.filter(user=user, badge_class__course_id=course_id) return cls.objects.filter(user=user) class Meta(object): app_label = "badges" # Abstract model doesn't index this, so we have to. BadgeAssertion._meta.get_field('created').db_index = True # pylint: disable=protected-access class CourseCompleteImageConfiguration(models.Model): """ Contains the icon configuration for badges for a specific course mode. """ mode = models.CharField( max_length=125, help_text=_(u'The course mode for this badge image. For example, "verified" or "honor".'), unique=True, ) icon = models.ImageField( # Actual max is 256KB, but need overhead for badge baking. This should be more than enough. help_text=_( u"Badge images must be square PNG files. The file size should be under 250KB." ), upload_to='course_complete_badges', validators=[validate_badge_image] ) default = models.BooleanField( help_text=_( u"Set this value to True if you want this image to be the default image for any course modes " u"that do not have a specified badge image. You can have only one default image." ), default=False, ) def __unicode__(self): return u"<CourseCompleteImageConfiguration for '{mode}'{default}>".format( mode=self.mode, default=u" (default)" if self.default else u'' ) def clean(self): """ Make sure there's not more than one default. """ # pylint: disable=no-member if self.default and CourseCompleteImageConfiguration.objects.filter(default=True).exclude(id=self.id): raise ValidationError(_(u"There can be only one default image.")) @classmethod def image_for_mode(cls, mode): """ Get the image for a particular mode. """ try: return cls.objects.get(mode=mode).icon except cls.DoesNotExist: # Fall back to default, if there is one. return cls.objects.get(default=True).icon class Meta(object): app_label = "badges" class CourseEventBadgesConfiguration(ConfigurationModel): """ Determines the settings for meta course awards-- such as completing a certain number of courses or enrolling in a certain number of them. """ courses_completed = models.TextField( blank=True, default='', help_text=_( u"On each line, put the number of completed courses to award a badge for, a comma, and the slug of a " u"badge class you have created that has the issuing component 'openedx__course'. " u"For example: 3,enrolled_3_courses" ) ) courses_enrolled = models.TextField( blank=True, default='', help_text=_( u"On each line, put the number of enrolled courses to award a badge for, a comma, and the slug of a " u"badge class you have created that has the issuing component 'openedx__course'. " u"For example: 3,enrolled_3_courses" ) ) course_groups = models.TextField( blank=True, default='', help_text=_( u"Each line is a comma-separated list. The first item in each line is the slug of a badge class you " u"have created that has an issuing component of 'openedx__course'. The remaining items in each line are " u"the course keys the learner needs to complete to be awarded the badge. For example: " u"slug_for_compsci_courses_group_badge,course-v1:CompSci+Course+First,course-v1:CompsSci+Course+Second" ) ) def __unicode__(self): return u"<CourseEventBadgesConfiguration ({})>".format(u"Enabled" if self.enabled else u"Disabled") @property def completed_settings(self): """ Parses the settings from the courses_completed field. """ return deserialize_count_specs(self.courses_completed) @property def enrolled_settings(self): """ Parses the settings from the courses_completed field. """ return deserialize_count_specs(self.courses_enrolled) @property def course_group_settings(self): """ Parses the course group settings. In example, the format is: slug_for_compsci_courses_group_badge,course-v1:CompSci+Course+First,course-v1:CompsSci+Course+Second """ specs = self.course_groups.strip() if not specs: return {} specs = [line.split(',', 1) for line in specs.splitlines()] return { slug.strip().lower(): [CourseKey.from_string(key.strip()) for key in keys.strip().split(',')] for slug, keys in specs } def clean_fields(self, exclude=tuple()): """ Verify the settings are parseable. """ errors = {} error_message = _(u"Please check the syntax of your entry.") if 'courses_completed' not in exclude: try: self.completed_settings except (ValueError, InvalidKeyError): errors['courses_completed'] = [unicode(error_message)] if 'courses_enrolled' not in exclude: try: self.enrolled_settings except (ValueError, InvalidKeyError): errors['courses_enrolled'] = [unicode(error_message)] if 'course_groups' not in exclude: store = modulestore() try: for key_list in self.course_group_settings.values(): for course_key in key_list: if not store.get_course(course_key): ValueError(u"The course {course_key} does not exist.".format(course_key=course_key)) except (ValueError, InvalidKeyError): errors['course_groups'] = [unicode(error_message)] if errors: raise ValidationError(errors) class Meta(object): app_label = "badges"
agpl-3.0
nttks/edx-platform
lms/djangoapps/instructor/features/bulk_email.py
7501
""" Define steps for bulk email acceptance test. """ # pylint: disable=missing-docstring # pylint: disable=redefined-outer-name from lettuce import world, step from lettuce.django import mail from nose.tools import assert_in, assert_equal from django.core.management import call_command from django.conf import settings from django.contrib.auth.models import User from courseware.tests.factories import StaffFactory, InstructorFactory from student.models import UserStanding from student.tests.factories import UserStandingFactory @step(u'Given there is a course with a staff, instructor and student') def make_populated_course(step): # pylint: disable=unused-argument ## This is different than the function defined in common.py because it enrolls ## a staff, instructor, and student member regardless of what `role` is, then ## logs `role` in. This is to ensure we have 3 class participants to email. # Clear existing courses to avoid conflicts world.clear_courses() # Create a new course course = world.CourseFactory.create( org='edx', number='888', display_name='Bulk Email Test Course' ) world.bulk_email_course_key = course.id try: # See if we've defined the instructor & staff user yet world.bulk_email_instructor except AttributeError: # Make & register an instructor for the course world.bulk_email_instructor = InstructorFactory(course_key=world.bulk_email_course_key) world.enroll_user(world.bulk_email_instructor, world.bulk_email_course_key) # Make & register a staff member world.bulk_email_staff = StaffFactory(course_key=course.id) world.enroll_user(world.bulk_email_staff, world.bulk_email_course_key) # Make & register a student world.register_by_course_key( course.id, username='student', password='test', is_staff=False ) # Make & register & disabled a student. world.register_by_course_key( course.id, username='resign', password='test', is_staff=False ) resign_user = User.objects.get(username='resign') # This function is performed by the number of Examples in bulk_email.feature # So, if the UserStanding already exists, don't try to create it again. if len(UserStanding.objects.filter(user=resign_user)) == 0: UserStandingFactory(user=resign_user, account_status=UserStanding.ACCOUNT_DISABLED, changed_by=resign_user) # Store the expected recipients # given each "send to" option staff_emails = [world.bulk_email_staff.email, world.bulk_email_instructor.email] world.expected_addresses = { 'course staff': staff_emails, 'students, staff, and instructors': staff_emails + ['student@edx.org'] } # Dictionary mapping a description of the email recipient # to the corresponding <option> value in the UI. SEND_TO_OPTIONS = { 'myself': 'myself', 'course staff': 'staff', 'students, staff, and instructors': 'all' } @step(u'I am logged in to the course as "([^"]*)"') def log_into_the_course(step, role): # pylint: disable=unused-argument # Store the role assert_in(role, ['instructor', 'staff', 'beta_tester']) # Log in as the an instructor or staff for the course my_email = world.bulk_email_instructor.email if role == 'instructor': world.log_in( username=world.bulk_email_instructor.username, password='test', email=my_email, name=world.bulk_email_instructor.profile.name ) else: my_email = world.bulk_email_staff.email world.log_in( username=world.bulk_email_staff.username, password='test', email=my_email, name=world.bulk_email_staff.profile.name ) # Store the "myself" send to option world.expected_addresses['myself'] = [my_email] @step(u'I send email to "([^"]*)"') def when_i_send_an_email(step, recipient): # pylint: disable=unused-argument # Check that the recipient is valid assert_in( recipient, SEND_TO_OPTIONS, msg="Invalid recipient: {}".format(recipient) ) # Clear the queue of existing emails while not mail.queue.empty(): # pylint: disable=no-member mail.queue.get() # pylint: disable=no-member # Because we flush the database before each run, # we need to ensure that the email template fixture # is re-loaded into the database call_command('loaddata', 'course_email_template.json') # Go to the email section of the instructor dash url = '/courses/{}'.format(world.bulk_email_course_key) world.visit(url) world.css_click('a[href="{}/instructor"]'.format(url)) world.css_click('a[data-section="send_email"]') # Select the recipient world.select_option('send_to', SEND_TO_OPTIONS[recipient]) # Enter subject and message world.css_fill('input#id_subject', 'Hello') with world.browser.get_iframe('mce_0_ifr') as iframe: editor = iframe.find_by_id('tinymce')[0] editor.fill('test message') # Click send world.css_click('input[name="send"]', dismiss_alert=True) # Expect to see a message that the email was sent expected_msg = "Your email was successfully queued for sending." world.wait_for_visible('#request-response') assert_in( expected_msg, world.css_text('#request-response'), msg="Could not find email success message." ) UNSUBSCRIBE_MSG = 'To stop receiving email like this' @step(u'Email is sent to "([^"]*)"') def then_the_email_is_sent(step, recipient): # pylint: disable=unused-argument # Check that the recipient is valid assert_in( recipient, SEND_TO_OPTIONS, msg="Invalid recipient: {}".format(recipient) ) # Retrieve messages. Because we are using celery in "always eager" # mode, we expect all messages to be sent by this point. messages = [] while not mail.queue.empty(): # pylint: disable=no-member messages.append(mail.queue.get()) # pylint: disable=no-member # Check that we got the right number of messages assert_equal( len(messages), len(world.expected_addresses[recipient]), msg="Received {0} instead of {1} messages for {2}".format( len(messages), len(world.expected_addresses[recipient]), recipient ) ) # Check that the message properties were correct recipients = [] for msg in messages: assert_in('Hello', msg.subject) assert_in(settings.BULK_EMAIL_DEFAULT_FROM_EMAIL, msg.from_email) # Message body should have the message we sent # and an unsubscribe message assert_in('test message', msg.body) assert_in(UNSUBSCRIBE_MSG, msg.body) # Should have alternative HTML form assert_equal(len(msg.alternatives), 1) content, mime_type = msg.alternatives[0] assert_equal(mime_type, 'text/html') assert_in('test message', content) assert_in(UNSUBSCRIBE_MSG, content) # Store the recipient address so we can verify later recipients.extend(msg.recipients()) # Check that the messages were sent to the right people # Because "myself" can vary based on who sent the message, # we use the world.expected_addresses dict we configured # in an earlier step. for addr in world.expected_addresses[recipient]: assert_in(addr, recipients)
agpl-3.0
kaltura/KalturaGeneratedAPIClientsCsharp
KalturaClient/Types/SearchAuthData.cs
3728
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2021 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== using System; using System.Xml; using System.Collections.Generic; using Kaltura.Enums; using Kaltura.Request; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Kaltura.Types { public class SearchAuthData : ObjectBase { #region Constants public const string AUTH_DATA = "authData"; public const string LOGIN_URL = "loginUrl"; public const string MESSAGE = "message"; #endregion #region Private Fields private string _AuthData = null; private string _LoginUrl = null; private string _Message = null; #endregion #region Properties /// <summary> /// Use AuthDataAsDouble property instead /// </summary> [JsonProperty] public string AuthData { get { return _AuthData; } set { _AuthData = value; OnPropertyChanged("AuthData"); } } /// <summary> /// Use LoginUrlAsDouble property instead /// </summary> [JsonProperty] public string LoginUrl { get { return _LoginUrl; } set { _LoginUrl = value; OnPropertyChanged("LoginUrl"); } } /// <summary> /// Use MessageAsDouble property instead /// </summary> [JsonProperty] public string Message { get { return _Message; } set { _Message = value; OnPropertyChanged("Message"); } } #endregion #region CTor public SearchAuthData() { } public SearchAuthData(JToken node) : base(node) { if(node["authData"] != null) { this._AuthData = node["authData"].Value<string>(); } if(node["loginUrl"] != null) { this._LoginUrl = node["loginUrl"].Value<string>(); } if(node["message"] != null) { this._Message = node["message"].Value<string>(); } } #endregion #region Methods public override Params ToParams(bool includeObjectType = true) { Params kparams = base.ToParams(includeObjectType); if (includeObjectType) kparams.AddReplace("objectType", "KalturaSearchAuthData"); kparams.AddIfNotNull("authData", this._AuthData); kparams.AddIfNotNull("loginUrl", this._LoginUrl); kparams.AddIfNotNull("message", this._Message); return kparams; } protected override string getPropertyName(string apiName) { switch(apiName) { case AUTH_DATA: return "AuthData"; case LOGIN_URL: return "LoginUrl"; case MESSAGE: return "Message"; default: return base.getPropertyName(apiName); } } #endregion } }
agpl-3.0
aimrebirth/Polygon4
Plugins/DBTool/Source/DBTool/Widgets/SDBToolTableView.cpp
12360
/* * Polygon-4 * Copyright (C) 2015 lzwdgc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "SDBToolTableView.h" #include "SDBToolTreeView.h" #include <algorithm> #include <Polygon4/DataManager/Common.h> #include <Polygon4/DataManager/StorageImpl.h> #define LOCTEXT_NAMESPACE "DBTool" void SDBToolTableView::Construct(const FArguments& InArgs) { Storage = InArgs._Storage; ParentType::FArguments args; args .SelectionMode(ESelectionMode::Single) .ListItemsSource(&Data) .OnGenerateRow(this, &SDBToolTableView::OnGenerateRow) .HeaderRow( SNew(SHeaderRow) .Visibility(EVisibility::Hidden) // + SHeaderRow::Column("Name") .DefaultLabel(LOCTEXT("DBToolNameLabel", "Name")) .IsEnabled(true) .FillWidth(0.35) .VAlignHeader(EVerticalAlignment::VAlign_Center) .HAlignHeader(EHorizontalAlignment::HAlign_Center) .VAlignCell(EVerticalAlignment::VAlign_Center) .HAlignCell(EHorizontalAlignment::HAlign_Left) // + SHeaderRow::Column("Type") .DefaultLabel(LOCTEXT("DBToolTypeLabel", "Type")) .IsEnabled(false) .FillWidth(0.25) .VAlignHeader(EVerticalAlignment::VAlign_Center) .HAlignHeader(EHorizontalAlignment::HAlign_Center) .VAlignCell(EVerticalAlignment::VAlign_Center) .HAlignCell(EHorizontalAlignment::HAlign_Left) // + SHeaderRow::Column("Value") .DefaultLabel(LOCTEXT("DBToolValueLabel", "Value")) .IsEnabled(true) .FillWidth(0.4) .VAlignHeader(EVerticalAlignment::VAlign_Center) .HAlignHeader(EHorizontalAlignment::HAlign_Center) .VAlignCell(EVerticalAlignment::VAlign_Center) .HAlignCell(EHorizontalAlignment::HAlign_Fill) ) ; ParentType::Construct(args); } TSharedRef<ITableRow> SDBToolTableView::OnGenerateRow(ListItem InItem, const TSharedRef<STableViewBase>& OwnerTable) { return SNew(SButtonRowWidget, OwnerTable, InItem) .TableView(this) ; } void SDBToolTableView::ResetTable() { Data.Empty(); ClearSelection(); HeaderRow->SetVisibility(EVisibility::Hidden); ReGenerateItems(PanelGeometryLastTick); RequestListRefresh(); } void SDBToolTableView::RefreshTable(TreeItem *Item) { auto &table = Item->P4Item->object->getClass(); TArray<ListItem> NewData; for (auto &v : table.getVariables()) NewData.Add(MakeShareable(new RowData{ Item, Item->P4Item.get(), v })); NewData.Sort([](const auto &i1, const auto i2) { return i1->Var.getId() < i2->Var.getId(); }); Data = NewData; ClearSelection(); HeaderRow->SetVisibility(EVisibility::Visible); ReGenerateItems(PanelGeometryLastTick); RequestListRefresh(); } void SButtonRowWidget::Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& InOwnerTable, ListItem InItem) { TableView = InArgs._TableView; Item = InItem; SMultiColumnTableRow<ListItem>::Construct(FSuperRowType::FArguments(), InOwnerTable); } TSharedRef<SWidget> SButtonRowWidget::GenerateWidgetForColumn(const FName& ColumnName) { using namespace polygon4::detail; using cb_item_type = TSharedPtr<ComboBoxItem>; using cb_item_array = TArray<cb_item_type>; using cb_item_array_ptr = TSharedPtr<cb_item_array>; using cb_type = SComboBox<cb_item_type>; auto &table = Item->Data->object->getClass(); auto &var = Item->Var; auto Value = Item->Data->object->getVariableString(var.getId()); TSharedPtr<SWidget> Widget; if (ColumnName == "Name") { auto dn = var.getDisplayName(); auto s = polygon4::tr(dn); SAssignNew(Widget, STextBlock) .Text(s.toFText()) ; } else if (ColumnName == "Type") { auto type = FText::FromString(polygon4::tr(var.getType()->getDataType())); SAssignNew(Widget, STextBlock) .Text(type) ; } else if (ColumnName == "Value") { bool enabled = true; if (var.isId()) enabled = false; auto EditableTextBox = [&]() { TSharedPtr<SWidget> EditableTextBox; SAssignNew(EditableTextBox, SEditableTextBox) .IsEnabled(enabled) .RevertTextOnEscape(true) .Text(Value.toFText()) .OnTextCommitted_Lambda([Item = Item](const FText &NewText, ETextCommit::Type Type) { try { Item->Data->object->setVariableString(Item->Var.getId(), NewText); Item->Data->update(); Item->Item->UpdateName(); GDBToolModule->SetDataChanged(); } catch (std::exception &e) { UE_LOG(LogTemp, Warning, TEXT("Cannot parse value of type '%s': %s"), polygon4::tr(Item->Var.getDataType()).c_str(), polygon4::String(e.what()).c_str()); } }) ; return EditableTextBox; }; if (var.isFk()) { if (table.getParent() && var.getType()->getCppName() == table.getParent()->getCppName()) { enabled = false; Widget = EditableTextBox(); } else { bool set = false; OrderedObjectMap m; std::tie(set, m) = Item->Data->object->getOrderedObjectMap(var.getId(), TableView->Storage); cb_item_array_ptr Items = MakeShareable(new cb_item_array); cb_item_type SelectedItem; bool found = false; for (auto &v : m) { Items->Add(MakeShareable(new ComboBoxItem{ FText::FromString(v.first), v.second })); if (!found && Value == v.second->getName()) { SelectedItem = Items->Last(); found = true; } } if (!found) { Items->Add(MakeShareable(new ComboBoxItem{ FText::GetEmpty(), nullptr })); SelectedItem = Items->Last(); } TSharedRef<cb_type> cb = SNew(cb_type) .OptionsSource(Items.Get()) .InitiallySelectedItem(SelectedItem) .OnSelectionChanged_Lambda([ParentData = Item.Get(), Items, var, this, Data = Item->Data] (const cb_item_type &InItem, ESelectInfo::Type type) { auto data = ParentData->Data; auto cb_data = InItem->Object; if (cb_data) { data->object->setVariableString(ParentData->Var.getId(), cb_data); data->update(); ParentData->Item->UpdateName(); TableView->RefreshTable(ParentData->Item); GDBToolModule->SetDataChanged(); } }) .OnGenerateWidget_Lambda([](const cb_item_type &InItem) { return SNew(STextBlock) .Text(InItem->Text); }) .Content() [ SNew(STextBlock) .Text(SelectedItem->Text) ] ; Widget = StaticCastSharedRef<SWidget>(cb); } } else if (var.getDataType() == DataType::Bool) { TSharedRef<SCheckBox> cb = SNew(SCheckBox) .OnCheckStateChanged_Lambda([var, Data = Item->Data](ECheckBoxState state) { Data->object->setVariableString(var.getId(), state == ECheckBoxState::Checked ? "1" : "0"); }); cb->SetIsChecked(Value == "1" ? ECheckBoxState::Checked : ECheckBoxState::Unchecked); Widget = cb; return SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(10, 1) .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ Widget.ToSharedRef() ]; } else if (var.getDataType() == DataType::Enum) { cb_item_array_ptr Items = MakeShareable(new cb_item_array); cb_item_type SelectedItem; auto n = var.getType()->getCppName(); int val = std::stoi(Value.toString()); auto m = getOrderedMap(n); bool found = false; for (auto &v : m) { Items->Add(MakeShareable(new ComboBoxItem{ v.first.toFText(), (polygon4::detail::IObjectBase *)(uint64_t)v.second })); if (val == v.second) { SelectedItem = Items->Last(); found = true; } } if (!found) { Items->Add(MakeShareable(new ComboBoxItem{ FText::GetEmpty(), nullptr })); SelectedItem = Items->Last(); } TSharedRef<cb_type> cb = SNew(cb_type) .OptionsSource(Items.Get()) .InitiallySelectedItem(SelectedItem) .OnSelectionChanged_Lambda([ParentData = Item.Get(), Items, var, this, Data = Item->Data] (const cb_item_type &Item, ESelectInfo::Type type) { int cb_data = (uint64_t)Item->Object; Data->object->setVariableString(var.getId(), std::to_string(cb_data)); Data->update(); ParentData->Item->UpdateName(); TableView->RefreshTable(ParentData->Item); GDBToolModule->SetDataChanged(); }) .OnGenerateWidget_Lambda([](const cb_item_type &InItem) { return SNew(STextBlock) .Text(InItem->Text); }) .Content() [ SNew(STextBlock) .Text(SelectedItem->Text) ] ; Widget = StaticCastSharedRef<SWidget>(cb); } else if (var.hasFlags({ fBigEdit })) { TSharedRef<SMultiLineEditableTextBox> tb = SNew(SMultiLineEditableTextBox) .Text(Value.toFText()) .AutoWrapText(true) .OnTextCommitted_Lambda([ParentData = Item.Get(), var, this, Data = Item->Data] (const FText &text, ETextCommit::Type type) { Data->object->setVariableString(var.getId(), text); Data->name = Data->object->getName(); ParentData->Item->UpdateName(); TableView->RefreshTable(ParentData->Item); GDBToolModule->SetDataChanged(); }) ; Widget = StaticCastSharedRef<SWidget>(tb); } else { Widget = EditableTextBox(); } } return SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(10, 1) [ Widget.ToSharedRef() ]; } #undef LOCTEXT_NAMESPACE
agpl-3.0
ILCARLO/SalesTaxProblem
SalesTaxProblem.ConsoleApp/Properties/AssemblyInfo.cs
1393
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApp1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApp1")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c39699bd-b339-4ade-bf1e-938713185582")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
agpl-3.0
MimocomMedia/kaltura
package/app/app/infra/cdl/kdl/KDLMediaDataSet.php
5596
<?php include_once("KDLCommon.php"); include_once("KDLMediaObjectData.php"); /* --------------------------- * KDLMediaDataSet */ class KDLMediaDataSet { /* --------------------- * Data */ public $_pdf=null; public $_swf=null; public $_container=null; public $_video=null; public $_audio=null; public $_image=null; public $_streamsCollectionStr=null; public $_errors=array(), $_warnings=array(); /* ---------------------- * Cont/Dtor */ public function __construct() { ; } public function __destruct() { unset($this); } /* ------------------------------ * Initialize */ public function Initialize() { if($this->_video) { $this->_video->CheckAndFixFormat(); /* * If video.BR is undefined ==> evaluate from file size & duration */ $br = 0; if($this->_video->_bitRate=="" && $this->_container && $this->_container->_duration>0){ $br = round($this->_container->_fileSize*8*1024/$this->_container->_duration); if($this->_audio->_bitRate!=="") $br = $br - $this->_audio->_bitRate; if($br>0) $this->_video->_bitRate = $br; else { $this->_video->_bitRate = 100; $this->_warnings[KDLConstants::VideoIndex][] = //"Invalid bitrate value. Set to defualt ".$this->_video->_bitRate; KDLWarnings::ToString(KDLWarnings::SetDefaultBitrate, $this->_video->_bitRate); } } } if($this->_audio) { $this->_audio->CheckAndFixFormat(); } if($this->_container) { $this->_container->CheckAndFixFormat(); if($this->_container->_bitRate=="" && $this->_container->_duration>0){ $this->_container->_bitRate = round($this->_container->_fileSize*8*1024/$this->_container->_duration); } } if($this->Validate()!=true) return false; return true; } /* ------------------------------ * Validate */ public function Validate() { if($this->_video!="") $this->_video->Validate($this->_errors, $this->_warnings); if($this->_audio!="") $this->_audio->Validate($this->_errors, $this->_warnings); if($this->_container!="" && $this->_image=="") $this->_container->Validate($this->_errors, $this->_warnings); if($this->_video=="" && $this->_audio=="" && $this->_image==""){ // "Invalid File - No media content"; $this->_errors[KDLConstants::ContainerIndex][] = KDLErrors::ToString(KDLErrors::NoValidMediaStream); } if(count($this->_errors)>0) return false; return true; } /* --------------------------- * IsDataSet */ public function IsDataSet() { $count=0; if($this->_container && $this->_container->IsDataSet()) $count++; if($this->_video && $this->_video->IsDataSet()) $count++; if($this->_audio && $this->_audio->IsDataSet()) $count++; if($count==0) return false; else return true; } /* --------------------------- * ToTags */ public function ToTags($tagList) { $tagsOut = array(); if($this->_container==null){ return $tagsOut; } $flashContainerFormats = array("flash video", "flv", "f4v","flash","flashvideo"); $mp4ContainerFormats = array("mpeg-4"); $mp4VideoFormats = array("avc","avc1","h264","h.264"); $mp4AudioFormats = array("mpeg audio","mp3","aac"); $wmvContainerFormats = array("windows media"); $itunesContainerFormats = array("mpeg-4","mpeg audio", "aiff", "wave"); foreach($tagList as $tag) { switch($tag){ case "flv": if($this->_container->IsFormatOf($flashContainerFormats)) $tagsOut[] = $tag; break; case "web": case "mbr": if($this->_video && $this->_video->_rotation>0) { break; } // $formats = array("flash video", "flv", "f4v","flash","flashvideo"); if($this->_container->IsFormatOf($flashContainerFormats)) $tagsOut[] = $tag; else { if($this->_container->IsFormatOf($mp4ContainerFormats)) { if($this->_video || $this->_audio) { if((!$this->_video || ($this->_video && $this->_video->IsFormatOf($mp4VideoFormats))) && (!$this->_audio || ($this->_audio && $this->_audio->IsFormatOf($mp4AudioFormats)))){ $tagsOut[] = $tag; } } } } break; case "slweb": if($this->_container->IsFormatOf($wmvContainerFormats)) $tagsOut[] = $tag; break; case "itunes": if($this->_container->_id=="qt" || $this->_container->IsFormatOf($itunesContainerFormats)) $tagsOut[] = $tag; break; default: break; } } return $tagsOut; } /* --------------------------- * ToString */ public function ToString(){ $rvStr = null; if($this->_container) { $str = $this->_container->ToString(); if($str) $rvStr = $str; } if($this->_video){ $str = $this->_video->ToString(); if($str) if($rvStr) $rvStr = $rvStr.", ".$str; else $rvStr = $str; } if($this->_audio){ $str = $this->_audio->ToString(); if($rvStr) $rvStr = $rvStr.", ".$str; else $rvStr = $str; } if($this->_image){ $str = $this->_image->ToString(); if($str) if($rvStr) $rvStr = $rvStr.", ".$str; else $rvStr = $str; } if($this->_pdf){ $str = $this->_pdf->ToString(); if($str) if($rvStr) $rvStr = $rvStr.", ".$str; else $rvStr = $str; } if($this->_swf){ $str = $this->_swf->ToString(); if($str) if($rvStr) $rvStr = $rvStr.", ".$str; else $rvStr = $str; } return $rvStr; } } ?>
agpl-3.0
dropmann/jasp-desktop
JASP-Desktop/widgets/tablemodelvariablesassigned.cpp
5255
// // Copyright (C) 2013-2015 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. // #include "tablemodelvariablesassigned.h" #include <vector> #include <string> #include <QMimeData> #include <QTimer> #include <QDebug> using namespace std; TableModelVariablesAssigned::TableModelVariablesAssigned(QObject *parent) : TableModelVariables(parent) { _boundTo = NULL; _source = NULL; _sorted = false; } void TableModelVariablesAssigned::bindTo(Option *option) { _boundTo = dynamic_cast<OptionTerms *>(option); if (_boundTo != NULL) { if (_source != NULL) { const vector<vector<string> > assigned = _boundTo->value(); beginResetModel(); _variables.set(assigned); endResetModel(); _source->notifyAlreadyAssigned(_variables); } else { qDebug() << "TableModelVariablesAssigned::bindTo(); source not set"; } } else { qDebug() << "TableModelVariablesAssigned::bindTo(); option not of type OptionVariables*"; } } void TableModelVariablesAssigned::unbind() { _boundTo = NULL; } void TableModelVariablesAssigned::setSource(TableModelVariablesAvailable *source) { _source = source; setInfoProvider(source); if (_sorted) _variables.setSortParent(_source->allVariables()); connect(source, SIGNAL(variablesChanged()), this, SLOT(sourceVariablesChanged())); } bool TableModelVariablesAssigned::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { if (_boundTo == NULL) return false; if (isDroppingToSelf(data)) return false; if ( ! TableModelVariables::canDropMimeData(data, action, row, column, parent)) return false; if (_boundTo->onlyOneTerm()) { QByteArray encodedData = data->data(_mimeType); Terms variables; variables.set(encodedData); if (variables.size() != 1) return false; } return true; } bool TableModelVariablesAssigned::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (_boundTo == NULL) return false; if (action == Qt::IgnoreAction) return true; if ( ! canDropMimeData(data, action, row, column, parent)) return false; if (action != Qt::MoveAction && action != Qt::CopyAction) return false; QByteArray encodedData = data->data(_mimeType); _delayDropped.set(encodedData); QTimer::singleShot(0, this, SLOT(delayAssignDroppedData())); emit assignmentsChanging(); return true; } void TableModelVariablesAssigned::delayAssignDroppedData() { assign(_delayDropped); emit assignmentsChanged(); } void TableModelVariablesAssigned::mimeDataMoved(const QModelIndexList &indices) { emit assignmentsChanging(); Terms variablesToRemove; foreach (const QModelIndex &index, indices) variablesToRemove.add(_variables.at(index.row())); unassign(variablesToRemove); emit assignmentsChanged(); } void TableModelVariablesAssigned::setSorted(bool sorted) { _sorted = sorted; if (sorted && _source != NULL) _variables.setSortParent(_source->allVariables()); } const Terms &TableModelVariablesAssigned::assigned() const { return _variables; } void TableModelVariablesAssigned::sourceVariablesChanged() { emit assignmentsChanging(); const Terms &variables = _source->allVariables(); Terms variablesToKeep; bool variableRemoved = false; variablesToKeep.set(_variables); variableRemoved = variablesToKeep.discardWhatDoesntContainTheseComponents(variables); if (variableRemoved) setAssigned(variablesToKeep); emit assignmentsChanged(); } void TableModelVariablesAssigned::assign(const Terms &variables) { if (_boundTo == NULL) return; Terms v; if (_boundTo->onlyOneTerm()) { if (variables.size() > 0) v.add(variables.at(0)); if (_variables.size() > 0) { _toSendBack.set(_variables); _variables.clear(); QTimer::singleShot(0, this, SLOT(sendBack())); } } else { v.set(_variables); v.add(variables); } setAssigned(v); emit assignedTo(variables); } void TableModelVariablesAssigned::unassign(const Terms &variables) { Terms variablesToKeep; variablesToKeep.set(_variables); variablesToKeep.remove(variables); setAssigned(variablesToKeep); emit unassigned(variables); } void TableModelVariablesAssigned::setAssigned(const Terms &variables) { if (_source == NULL) { qDebug() << "TableModelVariablesAssigned::setAssigned() : Source not set!"; return; } beginResetModel(); _variables.set(variables); endResetModel(); if (_boundTo != NULL) _boundTo->setValue(_variables.asVectorOfVectors()); } void TableModelVariablesAssigned::sendBack() { _source->sendBack(_toSendBack); _toSendBack.clear(); }
agpl-3.0
wallyworld/juju
provider/vsphere/internal/vsphereclient/client.go
24054
// Copyright 2015-2017 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package vsphereclient import ( "context" "net/url" "path" "strings" "github.com/dustin/go-humanize" "github.com/juju/clock" "github.com/juju/errors" "github.com/juju/loggo" "github.com/juju/mutex" "github.com/kr/pretty" "github.com/vmware/govmomi" "github.com/vmware/govmomi/find" "github.com/vmware/govmomi/list" "github.com/vmware/govmomi/object" "github.com/vmware/govmomi/property" "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/mo" "github.com/vmware/govmomi/vim25/soap" "github.com/vmware/govmomi/vim25/types" ) // ErrExtendDisk is returned if we timed out trying to extend the root // disk of a VM. type extendDiskError struct { err error } // Error is part of the error interface. func (e *extendDiskError) Error() string { return "extending disk failed: " + e.err.Error() } // IsExtendDiskError returns whether the cause of this error was a // failure to extend a VM disk. func IsExtendDiskError(err error) bool { _, ok := errors.Cause(err).(*extendDiskError) return ok } // ComputeResource stores an mo.ComputeResource along with its full path type ComputeResource struct { Resource *mo.ComputeResource Path string } // Client encapsulates a vSphere client, exposing the subset of // functionality that we require in the Juju provider. type Client struct { client *govmomi.Client datacenter string logger loggo.Logger clock clock.Clock acquireMutex func(mutex.Spec) (func(), error) } // Dial dials a new vSphere client connection using the given URL, // scoped to the specified datacenter. The resulting Client's Close // method must be called in order to release resources allocated by // Dial. func Dial( ctx context.Context, u *url.URL, datacenter string, logger loggo.Logger, ) (*Client, error) { client, err := govmomi.NewClient(ctx, u, true) if err != nil { return nil, errors.Trace(err) } return &Client{ client: client, datacenter: datacenter, logger: logger, clock: clock.WallClock, acquireMutex: acquireMutex, }, nil } // Close logs out and closes the client connection. func (c *Client) Close(ctx context.Context) error { return c.client.Logout(ctx) } func (c *Client) lister(ref types.ManagedObjectReference) *list.Lister { return &list.Lister{ Collector: property.DefaultCollector(c.client.Client), Reference: ref, All: true, } } // FindFolder should be able to search for both entire filepaths // or relative (.) filepaths. // If the user passes "test" or "/<DC>/vm/test" as folder, it should // return the pointer for the same folder, and should also deal with // the case where folderPath is nil or empty. func (c *Client) FindFolder(ctx context.Context, folderPath string) (vmFolder *object.Folder, err error) { c.logger.Tracef("FindFolder() path=%q", folderPath) if strings.Contains(folderPath, "..") { // ".." not supported as per: // https://github.com/vmware/govmomi/blob/master/find/finder.go#L114 c.logger.Errorf("vm folder path %q contains %q which is not supported", folderPath, "..") return nil, errors.NotSupportedf("vm folder path contains ..") } fi, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } dcfolders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } if folderPath == "" { c.logger.Warningf("empty string passed as vm-folder, using Datacenter root folder instead") return dcfolders.VmFolder, nil } // We either have a folder that is a relative path or an absolute path. // We'll accept an absolute path as is. Relative paths will use the DC vm folder as a parent. folderPath = strings.TrimPrefix(folderPath, "./") if strings.HasPrefix(folderPath, "/") { c.logger.Debugf("using absolute folder path %q", folderPath) } else if !strings.HasPrefix(folderPath, dcfolders.VmFolder.InventoryPath) { c.logger.Debugf("relative folderPath %q found, join with DC vm folder %q now", folderPath, dcfolders.VmFolder.InventoryPath) folderPath = path.Join(dcfolders.VmFolder.InventoryPath, folderPath) } vmFolder, err = fi.Folder(ctx, folderPath) if err == nil { return vmFolder, nil } if _, ok := err.(*find.NotFoundError); ok { return nil, errors.NotFoundf("folder path %q", folderPath) } return nil, errors.Trace(err) } func (c *Client) finder(ctx context.Context) (*find.Finder, *object.Datacenter, error) { finder := find.NewFinder(c.client.Client, true) datacenter, err := finder.Datacenter(ctx, c.datacenter) if err != nil { return nil, nil, errors.Trace(err) } finder.SetDatacenter(datacenter) return finder, datacenter, nil } // RemoveVirtualMachines removes VMs matching the given path from the // system. The path may include wildcards, to match multiple VMs. func (c *Client) RemoveVirtualMachines(ctx context.Context, path string) error { c.logger.Tracef("RemoveVirtualMachines() path=%q", path) finder, _, err := c.finder(ctx) if err != nil { return errors.Trace(err) } vms, err := finder.VirtualMachineList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { c.logger.Debugf("no VMs matching path %q", path) return nil } return errors.Annotatef(err, "listing VMs at %q", path) } // Retrieve VM details so we know which ones to power off. refs := make([]types.ManagedObjectReference, len(vms)) for i, vm := range vms { refs[i] = vm.Reference() } var mos []mo.VirtualMachine if err := c.client.Retrieve(ctx, refs, nil, &mos); err != nil { return errors.Annotate(err, "retrieving VM details") } // We run all tasks in parallel, and wait for them below. var lastError error tasks := make([]*object.Task, 0, len(vms)*2) for i, vm := range vms { if mos[i].Runtime.PowerState == types.VirtualMachinePowerStatePoweredOn { c.logger.Debugf("powering off %q", vm.Name()) task, err := vm.PowerOff(ctx) if err != nil { lastError = errors.Annotatef(err, "powering off %q", vm.Name()) c.logger.Errorf(err.Error()) continue } tasks = append(tasks, task) } c.logger.Debugf("destroying %q", vm.Name()) task, err := vm.Destroy(ctx) if err != nil { lastError = errors.Annotatef(err, "destroying %q", vm.Name()) c.logger.Errorf(err.Error()) continue } tasks = append(tasks, task) } for _, task := range tasks { _, err := task.WaitForResult(ctx, nil) if err != nil && !isManagedObjectNotFound(err) { lastError = err c.logger.Errorf(err.Error()) } } return errors.Annotate(lastError, "failed to remove instances") } // VirtualMachines return list of all VMs in the system matching the given path. func (c *Client) VirtualMachines(ctx context.Context, path string) ([]*mo.VirtualMachine, error) { c.logger.Tracef("VirtualMachines() path=%q", path) finder, _, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } items, err := finder.VirtualMachineList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { return nil, nil } return nil, errors.Annotate(err, "listing VMs") } vms := make([]*mo.VirtualMachine, len(items)) for i, item := range items { var vm mo.VirtualMachine err := c.client.RetrieveOne(ctx, item.Reference(), nil, &vm) if err != nil { return nil, errors.Trace(err) } vms[i] = &vm } return vms, nil } // ComputeResources returns a slice of all compute resources in the datacenter, // along with a slice of each compute resource's full path. func (c *Client) ComputeResources(ctx context.Context) ([]ComputeResource, error) { c.logger.Tracef("ComputeResources()") _, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } return c.computeResourcesFromRef(ctx, folders.HostFolder.Reference(), folders.HostFolder.InventoryPath) } // computeResourcesFromRef returns a slice of compute resources under the given // reference (folder), recursively including folders. func (c *Client) computeResourcesFromRef(ctx context.Context, ref types.ManagedObjectReference, path string) ([]ComputeResource, error) { es, err := c.lister(ref).List(ctx) if err != nil { return nil, errors.Trace(err) } var crs []ComputeResource for _, e := range es { switch o := e.Object.(type) { case mo.ClusterComputeResource: cr := ComputeResource{ Resource: &o.ComputeResource, Path: path + "/" + o.ComputeResource.Name, } crs = append(crs, cr) c.logger.Tracef("added cluster crPath %q", cr.Path) case mo.ComputeResource: cr := ComputeResource{ Resource: &o, Path: path + "/" + o.Name, } crs = append(crs, cr) c.logger.Tracef("added host crPath %q", cr.Path) case mo.Folder: subCrs, err := c.computeResourcesFromRef(ctx, o.Reference(), path+"/"+o.Name) if err != nil { return nil, errors.Trace(err) } crs = append(crs, subCrs...) c.logger.Tracef("added %d compute resources from %q", len(subCrs), path+"/"+o.Name) } } return crs, nil } // Folders returns the datacenter's folders object. func (c *Client) Folders(ctx context.Context) (*object.DatacenterFolders, error) { c.logger.Tracef("Folders()") _, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } return folders, nil } // Datastores returns list of all datastores in the system. func (c *Client) Datastores(ctx context.Context) ([]mo.Datastore, error) { c.logger.Tracef("Datastores()") finder, datacenter, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } folders, err := datacenter.Folders(ctx) if err != nil { return nil, errors.Trace(err) } dsPath := path.Join(folders.DatastoreFolder.InventoryPath, "...") c.logger.Tracef("listing datastores under %q", dsPath) items, err := finder.DatastoreList(ctx, dsPath) if err != nil { if _, ok := err.(*find.NotFoundError); ok { c.logger.Debugf("no datastores for path %q", dsPath) return nil, nil } return nil, errors.Trace(err) } refs := make([]types.ManagedObjectReference, len(items)) for i, item := range items { c.logger.Tracef("%s", item.InventoryPath) refs[i] = item.Reference() } var datastores []mo.Datastore err = c.client.Retrieve(ctx, refs, nil, &datastores) if err != nil { return nil, errors.Annotate(err, "retrieving datastore details") } return datastores, nil } // ResourcePools returns a list of all of the resource pools (possibly // nested) under the given path. func (c *Client) ResourcePools(ctx context.Context, path string) ([]*object.ResourcePool, error) { c.logger.Tracef("ResourcePools() path=%q", path) finder, _, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } c.logger.Tracef("listing resource pools under %q", path) items, err := finder.ResourcePoolList(ctx, path) if err != nil { if _, ok := err.(*find.NotFoundError); ok { c.logger.Debugf("no resource pools for path %q", path) return nil, nil } return nil, errors.Annotate(err, "listing resource pools") } return items, nil } // EnsureVMFolder creates the a VM folder with the given path if it doesn't already exist. // Two string arguments needed: relativeFolderPath will be split on "/" // whereas parentFolderName is the subfolder in DC's root-folder. // The parentFolderName will fallback to DC's root-folder if it's an empty string. func (c *Client) EnsureVMFolder(ctx context.Context, parentFolderName string, relativeFolderPath string) (*object.Folder, error) { c.logger.Tracef("EnsureVMFolder() parent=%q, rel=%q", parentFolderName, relativeFolderPath) finder, _, err := c.finder(ctx) if err != nil { return nil, errors.Trace(err) } createFolder := func(parent *object.Folder, name string) (*object.Folder, error) { getFolder := func() (*object.Folder, error) { fd, err := finder.Folder(ctx, path.Join(parent.InventoryPath, name)) if err != nil { return nil, errors.Trace(err) } return fd, nil } fd, err := parent.CreateFolder(ctx, name) if err == nil { return fd, nil } if soap.IsSoapFault(err) { switch soap.ToSoapFault(err).VimFault().(type) { case types.DuplicateName: return getFolder() } } return nil, errors.Trace(err) } parentFolder, err := c.FindFolder(ctx, parentFolderName) if err != nil { return nil, errors.Trace(err) } // Creating "Juju Controller (...)" folder and then model folder, for example. for _, name := range strings.Split(relativeFolderPath, "/") { folder, err := createFolder(parentFolder, name) if err != nil { return nil, errors.Annotatef(err, "creating folder %q in %q", name, parentFolder.InventoryPath) } parentFolder = folder } return parentFolder, nil } // DestroyVMFolder destroys a folder(folderPath could be either relative path of vmfolder of datacenter or full path). func (c *Client) DestroyVMFolder(ctx context.Context, folderPath string) error { c.logger.Tracef("DestroyVMFolder() path=%q", folderPath) folder, err := c.FindFolder(ctx, folderPath) if errors.IsNotFound(err) { return nil } if err != nil { return errors.Trace(err) } task, err := folder.Destroy(ctx) if err != nil { return errors.Trace(err) } _, err = task.WaitForResult(ctx, nil) if err != nil && !isManagedObjectNotFound(err) { return errors.Trace(err) } return nil } // MoveVMFolderInto moves one VM folder into another. func (c *Client) MoveVMFolderInto(ctx context.Context, parentPath, childPath string) error { c.logger.Tracef("MoveVMFolderInto() parent=%q, child=%q", parentPath, childPath) parent, err := c.FindFolder(ctx, parentPath) if err != nil { return errors.Trace(err) } child, err := c.FindFolder(ctx, childPath) if err != nil { return errors.Trace(err) } task, err := parent.MoveInto(ctx, []types.ManagedObjectReference{child.Reference()}) if err != nil { return errors.Trace(err) } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Trace(err) } return nil } // MoveVMsInto moves a set of VMs into a folder. func (c *Client) MoveVMsInto( ctx context.Context, folderPath string, vms ...types.ManagedObjectReference, ) error { c.logger.Tracef("MoveVMsInto() path=%q, vms=%v", folderPath, vms) folder, err := c.FindFolder(ctx, folderPath) if err != nil { return errors.Trace(err) } task, err := folder.MoveInto(ctx, vms) if err != nil { return errors.Trace(err) } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Trace(err) } return nil } // UpdateVirtualMachineExtraConfig updates the "ExtraConfig" attributes // of the specified virtual machine. Keys with empty values will be // removed from the config; existing keys that are unspecified in the // map will be untouched. func (c *Client) UpdateVirtualMachineExtraConfig( ctx context.Context, vmInfo *mo.VirtualMachine, metadata map[string]string, ) error { c.logger.Tracef("UpdateVirtualMachineExtraConfig() vmInfo.Name=%q, metadata=%v", vmInfo.Name, metadata) var spec types.VirtualMachineConfigSpec for k, v := range metadata { opt := &types.OptionValue{Key: k, Value: v} spec.ExtraConfig = append(spec.ExtraConfig, opt) } vm := object.NewVirtualMachine(c.client.Client, vmInfo.Reference()) task, err := vm.Reconfigure(ctx, spec) if err != nil { return errors.Annotate(err, "reconfiguring VM") } if _, err := task.WaitForResult(ctx, nil); err != nil { return errors.Annotate(err, "reconfiguring VM") } return nil } // DeleteDatastoreFile deletes a file or directory in the datastore. func (c *Client) DeleteDatastoreFile(ctx context.Context, datastorePath string) error { c.logger.Tracef("DeleteDatastoreFile() path=%q", datastorePath) _, datacenter, err := c.finder(ctx) if err != nil { return errors.Trace(err) } fileManager := object.NewFileManager(c.client.Client) deleteTask, err := fileManager.DeleteDatastoreFile(ctx, datastorePath, datacenter) if err != nil { return errors.Trace(err) } if _, err := deleteTask.WaitForResult(ctx, nil); err != nil { if types.IsFileNotFound(err) { return nil } return errors.Trace(err) } return nil } // megabytesToB converts the root disk constraint (which uses megabytes for its unit) to bytes func megabytesToB(diskMiB uint64) uint64 { return diskMiB * 1024 * 1024 } // megabytesToKiB converts the root disk constraint (which uses megabytes for its unit) to kibibytes func megabytesToKiB(diskMiB uint64) uint64 { return diskMiB * 1024 } func (c *Client) cloneVM( ctx context.Context, args CreateVirtualMachineParams, srcVM *object.VirtualMachine, vmFolder *object.Folder, datastore *object.Datastore, ) (*object.VirtualMachine, error) { taskWaiter := &taskWaiter{ args.Clock, args.UpdateProgress, args.UpdateProgressInterval, } vmConfigSpec, err := c.buildConfigSpec(ctx, args, srcVM) if err != nil { return nil, errors.Annotate(err, "building clone VM config") } datastoreRef := datastore.Reference() task, err := srcVM.Clone(ctx, vmFolder, args.Name, types.VirtualMachineCloneSpec{ Config: vmConfigSpec, Location: types.VirtualMachineRelocateSpec{ Pool: &args.ResourcePool, Datastore: &datastoreRef, }, }) if err != nil { return nil, errors.Annotatef(err, "cloning VM %q from %q", args.Name, srcVM.Name()) } info, err := taskWaiter.waitTask(ctx, task, "cloning VM") if err != nil { return nil, errors.Annotatef(err, "waiting for task %q", info.Name) } vm := object.NewVirtualMachine(c.client.Client, info.Result.(types.ManagedObjectReference)) return vm, nil } func (c *Client) buildConfigSpec( ctx context.Context, args CreateVirtualMachineParams, srcVM *object.VirtualMachine, ) (*types.VirtualMachineConfigSpec, error) { var spec types.VirtualMachineConfigSpec if args.Constraints.HasCpuCores() { spec.NumCPUs = int32(*args.Constraints.CpuCores) } if args.Constraints.HasMem() { spec.MemoryMB = int64(*args.Constraints.Mem) } if args.Constraints.HasCpuPower() { cpuPower := int64(*args.Constraints.CpuPower) spec.CpuAllocation = &types.ResourceAllocationInfo{ Limit: &cpuPower, Reservation: &cpuPower, } } spec.Flags = &types.VirtualMachineFlagInfo{ DiskUuidEnabled: types.NewBool(args.EnableDiskUUID), } for k, v := range args.Metadata { spec.ExtraConfig = append(spec.ExtraConfig, &types.OptionValue{Key: k, Value: v}) } networks, dvportgroupConfig, err := c.computeResourceNetworks(ctx, args.ComputeResource) if err != nil { return nil, errors.Trace(err) } for i, networkDevice := range args.NetworkDevices { network := networkDevice.Network if network == "" { network = defaultNetwork } networkReference, err := findNetwork(networks, network) if err != nil { return nil, errors.Trace(err) } device, err := c.addNetworkDevice(ctx, &spec, networkReference, networkDevice.MAC, dvportgroupConfig) if err != nil { return nil, errors.Annotatef(err, "adding network device %d - network %s", i, network) } c.logger.Debugf("network device: %+v", device) } newVAppConfig, err := customiseVAppConfig(ctx, srcVM, args) if err != nil { return nil, errors.Annotate(err, "changing VApp config") } spec.VAppConfig = newVAppConfig return &spec, nil } // customiseVAppConfig gets the existing VApp config properties from // the template VM passed in and uses them to construct edits for the // new cloned VM. func customiseVAppConfig( ctx context.Context, srcVM *object.VirtualMachine, args CreateVirtualMachineParams, ) (*types.VmConfigSpec, error) { var vmProps mo.VirtualMachine if err := srcVM.Properties(ctx, srcVM.Reference(), []string{"config.vAppConfig"}, &vmProps); err != nil { return nil, errors.Annotate(err, "getting vAppConfig from template") } hostnameKey := int32(-1) userDataKey := int32(-1) vmConfigInfo := vmProps.Config.VAppConfig.GetVmConfigInfo() for _, property := range vmConfigInfo.Property { switch property.Id { case "hostname": hostnameKey = property.Key case "user-data": userDataKey = property.Key } } if hostnameKey == -1 { return nil, errors.Errorf("couldn't find hostname property on template %q", srcVM.InventoryPath) } if userDataKey == -1 { return nil, errors.Errorf("couldn't find user-data property on template %q", srcVM.InventoryPath) } return &types.VmConfigSpec{ Property: []types.VAppPropertySpec{{ ArrayUpdateSpec: types.ArrayUpdateSpec{Operation: "edit"}, Info: &types.VAppPropertyInfo{Key: hostnameKey, Value: args.Name}, }, { ArrayUpdateSpec: types.ArrayUpdateSpec{Operation: "edit"}, Info: &types.VAppPropertyInfo{Key: userDataKey, Value: args.UserData}, }}, }, nil } func (c *Client) getDisk( ctx context.Context, vm *object.VirtualMachine, ) (*types.VirtualDisk, error) { var mo mo.VirtualMachine if err := c.client.RetrieveOne(ctx, vm.Reference(), []string{"config.hardware"}, &mo); err != nil { return nil, errors.Trace(err) } for _, dev := range mo.Config.Hardware.Device { if dev, ok := dev.(*types.VirtualDisk); ok { return dev, nil } } return nil, errors.NotFoundf("disk") } func (c *Client) extendDisk( ctx context.Context, vm *object.VirtualMachine, disk *types.VirtualDisk, desiredCapacityKB int64, ) error { prettySize := func(kb int64) string { return humanize.IBytes(uint64(kb) * 1024) } c.logger.Debugf("extending disk from %q to %q", prettySize(disk.CapacityInKB), prettySize(desiredCapacityKB)) // Resize the disk to desired size. disk.CapacityInKB = desiredCapacityKB spec := types.VirtualMachineConfigSpec{} spec.DeviceChange = append(spec.DeviceChange, &types.VirtualDeviceConfigSpec{ Device: disk, Operation: types.VirtualDeviceConfigSpecOperationEdit, FileOperation: "", }) c.logger.Tracef("extending disk, config change -> %s", pretty.Sprint(spec)) task, err := vm.Reconfigure(ctx, spec) if err != nil { return errors.Trace(&extendDiskError{err}) } if err := task.Wait(ctx); err != nil { return errors.Trace(&extendDiskError{err}) } return nil } func isManagedObjectNotFound(err error) bool { if err == nil { return false } if f, ok := err.(types.HasFault); ok { switch f.Fault().(type) { case *types.ManagedObjectNotFound: return true } } return false } // UserHasRootLevelPrivilege returns whether the connected user has the // specified privilege on the root-level object. func (c *Client) UserHasRootLevelPrivilege(ctx context.Context, privilege string) (bool, error) { c.logger.Tracef("UserHasRootLevelPrivilege() privilege=%q", privilege) session, err := c.client.SessionManager.UserSession(ctx) if err != nil { return false, errors.Annotate(err, "getting user session") } vimClient := c.client.Client req := types.HasPrivilegeOnEntities{ This: *vimClient.ServiceContent.AuthorizationManager, Entity: []types.ManagedObjectReference{vimClient.ServiceContent.RootFolder}, SessionId: session.Key, PrivId: []string{privilege}, } resp, err := methods.HasPrivilegeOnEntities(ctx, vimClient, &req) if privilege == "System.Read" && isPermissionError(err) { // This is a special case - for System.Read you need the // privilege to check whether you have the privilege. return false, nil } else if err != nil { return false, errors.Annotatef(err, "checking for %q privilege", privilege) } if count := len(resp.Returnval); count != 1 { return false, errors.Errorf("expected 1 privilege response, got %d", count) } entityPriv := resp.Returnval[0] if count := len(entityPriv.PrivAvailability); count != 1 { return false, errors.Errorf("expected 1 privilege availability, got %d", count) } return entityPriv.PrivAvailability[0].IsGranted, nil } func isPermissionError(err error) bool { if err == nil || !soap.IsSoapFault(err) { return false } switch soap.ToSoapFault(err).VimFault().(type) { case types.NoPermission: return true } return false }
agpl-3.0
shaoliancheng/videoplayer-android-tv
playkit/src/main/java/com/kaltura/playkit/api/phoenix/services/PhoenixService.java
1408
/* * ============================================================================ * Copyright (C) 2017 Kaltura Inc. * * Licensed under the AGPLv3 license, unless a different license for a * particular library is specified in the applicable library path. * * You may obtain a copy of the License at * https://www.gnu.org/licenses/agpl-3.0.html * ============================================================================ */ package com.kaltura.playkit.api.phoenix.services; import android.support.annotation.Nullable; import android.text.TextUtils; import com.google.gson.JsonObject; import com.kaltura.netkit.connect.request.MultiRequestBuilder; import com.kaltura.playkit.api.phoenix.PhoenixConfigs; /** * @hide */ public class PhoenixService { public static JsonObject getPhoenixConfigParams(){ JsonObject params = new JsonObject(); params.addProperty("clientTag", PhoenixConfigs.ClientTag); params.addProperty("apiVersion",PhoenixConfigs.ApiVersion); return params; } public static MultiRequestBuilder getMultirequest(String baseUrl, @Nullable String ks){ JsonObject params = getPhoenixConfigParams(); if(!TextUtils.isEmpty(ks)) { params.addProperty("ks", ks); } return (MultiRequestBuilder) new MultiRequestBuilder().service("multirequest").method("POST").url(baseUrl).params(params); } }
agpl-3.0
maurelio1234/6wc
process.py
2883
import csv from datetime import datetime, timedelta import string import re def get_time(s): """ interprets time based expressions in s and returns it as a number of minutes """ def get_match_int(res, s, g=1): match = re.search(res, s) if match: return int(match.group(g)) else: return 0 hours = get_match_int(r'(?P<hours>[0-9]+)\s*(h|hour(s)?)', s) minutes = get_match_int(r'(?P<minutes>[0-9]+)\s*(min|minute(s)?)', s) return hours*60 + minutes def extract_6wcbot(): with open('tweets.csv') as f: with open('tweets_6wcbot.csv', 'w') as g: for line in csv.reader(f, delimiter=','): if line[0] == 'tweet_id': continue timestamp = datetime.strptime(line[5][:-6], "%Y-%m-%d %H:%M:%S") text = line[7].lower() if '@6wcbot' in text and \ ('#chinese' in text or \ '#zh' in text or \ '#mandarin' in text): time = get_time(text) if time: if 'yesterday' in text: timestamp = timestamp - timedelta(days=1) g.write(str(timestamp) + ';' + str(time) + '\n') else: print 'huh? ' + text def reverse(fin='tweets_6wcbot.csv', fout='tweets_6wcbot_r.csv'): with open(fin) as f: with open(fout, 'w') as g: for line in reversed(f.readlines()): g.write(line + '\n') def accumulative(fin='tweets_6wcbot_r.csv', fout='tweets_6wcbot_r_a.csv'): with open(fin) as f: with open(fout, 'w') as g: acc = 0 first_ts = None for line in csv.reader(f, delimiter=';'): if line: ts = datetime.strptime(line[0], "%Y-%m-%d %H:%M:%S") if not first_ts: first_ts = ts acc = acc + int(line[1]) delta = ts - first_ts g.write(str(delta.total_seconds()) + ';' + str(acc)+'\n') def compute_acc(reference_start, reference_end=None, duration=6, fname='tweets_6wcbot_r_a.csv'): """computes the number of minutes accumulated in the reference CSV taking reference start and end dates, and a challenge duration in weeks""" if not reference_end: reference_end = datetime.now() current_ts = (reference_end - reference_start).total_seconds() with open(fname) as f: last_ts = None last_acc = 0 for line in csv.reader(f, delimiter=';'): ts = float(line[0])*duration / 6.0 acc = int(int(line[1])*duration/6.0) if current_ts < ts: return last_acc last_ts = ts last_acc = acc return 0 def minutes2hm(min): """ returns hour,minute from an int representing an amount of minutes """ return min/60, min%60 def normalize(in_duration, fin='current.6wc.csv',fout='current.norm.6wc.csv'): with open(fin) as f: with open(fout, 'w') as g: for line in csv.reader(f, delimiter=';'): ts = float(line[0])*6.0/in_duration acc = int(int(line[1])*6.0/in_duration) g.write(str(ts)+';'+str(int(acc))+'\n') #normalize(1) # usage #print compute_acc(datetime(2014,12,05)) #print get_time(raw_input())
agpl-3.0
ingadhoc/odoo-help
help_doc_account/__openerp__.py
1597
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Accounting Help Documentation', 'version': '8.0.1.0.0', 'category': 'Hidden', 'sequence': 14, 'summary': '', 'description': """ Accounting Documentation ======================== """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'license': 'AGPL-3', 'images': [ ], 'depends': [ 'help_doc', 'account', ], 'data': [ 'document_page_data.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': True, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
pculture/unisubs
media/src/js/subtitle-editor/tests/subtitleListSpec.js
38971
describe('Test the SubtitleList class', function() { var subtitleList = null; beforeEach(module('amara.SubtitleEditor.subtitles.models')); beforeEach(module('amara.SubtitleEditor.mocks')); beforeEach(inject(function(SubtitleList) { subtitleList = new SubtitleList(); subtitleList.loadEmptySubs('en'); jasmine.addMatchers({ toHaveTimes: function(util, customEqualityTesters) { return { compare: function(actual, expected) { var result = {}; result.pass = util.equals([actual.startTime, actual.endTime], expected); return result; } }; } }); })); // This is the best way to track changes to the list. It intercepts all // calls to the low-level mutator functions and updates a list of changes // based on them function trackChanges(subtitleList) { var origInsertSubtitles = subtitleList._insertSubtitle; var origRemoveSubtitles = subtitleList._removeSubtitle; var origUpdateSubtitles = subtitleList._updateSubtitle; var changes = []; spyOn(subtitleList, '_insertSubtitle').and.callFake(function(index, attrs) { changes.push(['insert', index, attrs]); return origInsertSubtitles.call(subtitleList, index, attrs); }); spyOn(subtitleList, '_removeSubtitle').and.callFake(function(index, attrs) { changes.push(['remove', index, attrs]); return origRemoveSubtitles.call(subtitleList, index, attrs); }); spyOn(subtitleList, '_updateSubtitle').and.callFake(function(index, attrs) { changes.push(['update', index, attrs]); return origUpdateSubtitles.call(subtitleList, index, attrs); }); return changes; } describe('low level change functions', function() { it('inserts subtitles', function() { var sub1 = subtitleList._insertSubtitle(0); var sub2 = subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100, region: 'top', content: 'test-content' }); var sub3 = subtitleList._insertSubtitle(2, {startOfParagraph: true, content: 'test-content2'}); expect(subtitleList.subtitles).toEqual([sub2, sub1, sub3]); expect(subtitleList.syncedCount).toEqual(1); expect(sub1).toHaveTimes([-1, -1]); expect(sub1.region).toEqual(undefined); expect(sub1.startOfParagraph).toEqual(true); // sub1 was the first subtitle, so startOfParagraph is true expect(sub1.markdown).toEqual(''); expect(sub2).toHaveTimes([0, 100]); expect(sub2.region).toEqual('top'); expect(sub2.startOfParagraph).toEqual(true); expect(sub2.markdown).toEqual('test-content'); expect(sub3).toHaveTimes([-1, -1]); expect(sub3.region).toEqual(undefined); expect(sub3.startOfParagraph).toEqual(true); expect(sub3.markdown).toEqual('test-content2'); }); it('updates subtitles', function() { subtitleList._insertSubtitle(0); var sub = subtitleList._insertSubtitle(1); subtitleList._updateSubtitle(1, { startTime: 500, endTime: 1000, region: 'top', startOfParagraph: true, content: 'test' }); expect(sub.startTime).toEqual(500); expect($(sub.node).attr('begin')).toEqual('500'); expect(sub.endTime).toEqual(1000); expect($(sub.node).attr('end')).toEqual('1000'); expect(sub.region).toEqual('top'); expect($(sub.node).attr('region')).toEqual('top'); expect(sub.markdown).toEqual('test'); expect($(sub.node).text()).toEqual('test'); }); it('removes subtitles', function() { var sub1 = subtitleList._insertSubtitle(0, {startTime: 500, endTime: 1000}); var sub2 = subtitleList._insertSubtitle(1); var sub3 = subtitleList._insertSubtitle(2); expect(subtitleList.subtitles).toEqual([sub1, sub2, sub3]); expect(subtitleList.syncedCount).toEqual(1); subtitleList._removeSubtitle(1); expect(subtitleList.subtitles).toEqual([sub1, sub3]); expect(subtitleList.syncedCount).toEqual(1); subtitleList._removeSubtitle(1); expect(subtitleList.subtitles).toEqual([sub1]); expect(subtitleList.syncedCount).toEqual(1); subtitleList._removeSubtitle(0); expect(subtitleList.subtitles).toEqual([]); expect(subtitleList.syncedCount).toEqual(0); }); it('supports bulk changes', function() { subtitleList._bulkChange([ [subtitleList._insertSubtitle, 0, {startTime: 0, endTime: 100}], [subtitleList._insertSubtitle, 1, {startTime: 100, endTime: 200}], [subtitleList._insertSubtitle, 2, {startTime: 200, endTime:300}], [subtitleList._updateSubtitle, 2, {content: 'test-content'}], [subtitleList._removeSubtitle, 1, {}], ]); expect(subtitleList.subtitles.length).toEqual(2); expect(subtitleList.subtitles[0]).toHaveTimes([0, 100]); expect(subtitleList.subtitles[1]).toHaveTimes([200, 300]); expect(subtitleList.subtitles[1].markdown).toEqual('test-content'); }); it('invokes change callbacks', function() { var handler = jasmine.createSpyObj('handler', ['onChange']); subtitleList.addChangeCallback(handler.onChange); var sub = subtitleList._insertSubtitle(0); subtitleList._invokeChangeCallbacks(); expect(handler.onChange).toHaveBeenCalledWith([{ type: 'insert', subtitle: sub, before: null, }]); handler.onChange.calls.reset(); var sub2 = subtitleList._insertSubtitle(0); subtitleList._invokeChangeCallbacks(); expect(handler.onChange).toHaveBeenCalledWith([{ type: 'insert', subtitle: sub2, before: sub }]); handler.onChange.calls.reset(); subtitleList.updateSubtitleTime(sub, 500, 1500); subtitleList._invokeChangeCallbacks(); expect(handler.onChange).toHaveBeenCalledWith([{ type: 'update', subtitle: sub, }]); handler.onChange.calls.reset(); subtitleList.updateSubtitleTime(sub, 500, 1500); subtitleList._invokeChangeCallbacks(); expect(handler.onChange).toHaveBeenCalledWith([{ type: 'update', subtitle: sub, }]); handler.onChange.calls.reset(); subtitleList.updateSubtitleContent(sub, 'content'); subtitleList._invokeChangeCallbacks(); expect(handler.onChange).toHaveBeenCalledWith([{ type: 'update', subtitle: sub, }]); handler.onChange.calls.reset(); subtitleList._removeSubtitle(1); subtitleList._invokeChangeCallbacks(); expect(handler.onChange).toHaveBeenCalledWith([{ type: 'remove', subtitle: sub, }]); handler.onChange.calls.reset(); subtitleList.removeChangeCallback(handler.onChange); var sub3 = subtitleList._insertSubtitle(0); subtitleList.updateSubtitleTime(sub3, 500, 1500); subtitleList.updateSubtitleContent(sub3, 'content'); subtitleList._removeSubtitle(0); expect(handler.onChange.calls.count()).toEqual(0); }); }); it('updates timings', function() { var sub1 = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.insertSubtitleBefore(null); expect(subtitleList.syncedCount).toEqual(0); subtitleList.updateSubtitleTime(sub1, 500, 1500); expect(sub1).toHaveTimes([500, 1500]); expect(subtitleList.syncedCount).toEqual(1); subtitleList.updateSubtitleTime(sub1, 1000, 1500); expect(sub1).toHaveTimes([1000, 1500]); expect(subtitleList.syncedCount).toEqual(1); subtitleList.updateSubtitleTime(sub2, 2000, 2500); expect(sub2).toHaveTimes([2000, 2500]); expect(subtitleList.syncedCount).toEqual(2); }); it('updates multiple timings at once', function() { var sub1 = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 100, endTime: 200 }, { subtitle: sub2, startTime: 200, endTime: 300 }, ]); expect(sub1).toHaveTimes([100, 200]); expect(sub2).toHaveTimes([200, 300]); expect(subtitleList.syncedCount).toEqual(2); }); it('clears all timings', function() { var sub1 = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 100, endTime: 200 }, { subtitle: sub2, startTime: 200, endTime: 300 }, ]); subtitleList.clearAllTimings(); expect(sub1).toHaveTimes([-1, -1]); expect(sub2).toHaveTimes([-1, -1]); expect(subtitleList.syncedCount).toEqual(0); }); it('clears all text', function() { var sub1 = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleContent(sub1, 'test'); subtitleList.updateSubtitleContent(sub2, 'test2'); subtitleList.clearAllText(); expect(sub1.markdown).toEqual(''); expect(sub2.markdown).toEqual(''); }); it('should get and update regions', function() { var sub = subtitleList.insertSubtitleBefore(null); expect(sub.region).toEqual(undefined); subtitleList.updateSubtitleRegion(sub, 'top'); expect($(sub.node).attr('region')).toEqual('top'); expect(sub.region).toEqual('top'); subtitleList.updateSubtitleRegion(sub, undefined); expect($(sub.node).attr('region')).toEqual(undefined); expect(sub.region).toEqual(undefined); }); describe('insertBefore unsynced subtitle', function() { it('appends at the end if otherSubtitle is null', function() { var sub1 = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.insertSubtitleBefore(null); expect(subtitleList.subtitles).toEqual([sub1, sub2]); }); it('inserts unsynced subtitles otherSubtitle is unsynced', function() { var sub1 = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.insertSubtitleBefore(sub1); expect(subtitleList.subtitles).toEqual([sub2, sub1]); expect(sub2.startTime).toEqual(-1); expect(sub2.endTime).toEqual(-1); }); }); describe('insertBefore with two synced subtitles', function() { var sub1, sub2; beforeEach(function() { sub1 = subtitleList._insertSubtitle(0); sub2 = subtitleList._insertSubtitle(1); }); it('inserts a 1 second subtitle in the between otherSubtitle and the previous subtitle, if there is at least a 1 second gap', function() { subtitleList.updateSubtitleTime(sub1, 0, 1000); subtitleList.updateSubtitleTime(sub2, 5000, 6000); var newSub = subtitleList.insertSubtitleBefore(sub2); expect(subtitleList.subtitles).toEqual([sub1, newSub, sub2]); expect(newSub).toHaveTimes([2500, 3500]); }); it('adjusts the end time of the previous subtitle to make room for the new subtitle, if there is less than a 1 second gap', function() { subtitleList.updateSubtitleTime(sub1, 0, 5500); subtitleList.updateSubtitleTime(sub2, 6000, 7000); var newSub = subtitleList.insertSubtitleBefore(sub2); expect(subtitleList.subtitles).toEqual([sub1, newSub, sub2]); expect(sub1).toHaveTimes([0, 5000]); expect(newSub).toHaveTimes([5000, 6000]); }); it('splits the time between the previous subtitle and the new subtitle if there is less than 2 seconds for them both', function() { subtitleList.updateSubtitleTime(sub1, 0, 1000); subtitleList.updateSubtitleTime(sub2, 1500, 2500); var newSub = subtitleList.insertSubtitleBefore(sub2); expect(subtitleList.subtitles).toEqual([sub1, newSub, sub2]); expect(sub1).toHaveTimes([0, 750]); expect(newSub).toHaveTimes([750, 1500]); }); it('never lengthens the previous subtitle', function() { subtitleList.updateSubtitleTime(sub1, 0, 400); subtitleList.updateSubtitleTime(sub2, 1000, 7000); var newSub = subtitleList.insertSubtitleBefore(sub2); // when we insert the subtitle, don't split the time since that // would cause sub1 to be longer than before. Instead just newSub // should just take up the entire 2 second gap. expect(subtitleList.subtitles).toEqual([sub1, newSub, sub2]); expect(sub1).toHaveTimes([0, 400]); expect(newSub).toHaveTimes([400, 1000]); }); }); describe('insertBefore with first synced subtitle', function() { var sub1; beforeEach(function() { sub1 = subtitleList.insertSubtitleBefore(null); }); it('inserts a 1 second subtitle in the middle of the initial empty time, if there is at least a 1 second gap', function() { subtitleList.updateSubtitleTime(sub1, 2000, 5000); var newSub = subtitleList.insertSubtitleBefore(sub1); expect(subtitleList.subtitles).toEqual([newSub, sub1]); expect(newSub).toHaveTimes([500, 1500]); }); it('adjusts the start time of the next subtitle to make room for the new subtitle, if there is less than a 1 second gap', function() { subtitleList.updateSubtitleTime(sub1, 700, 7000); var newSub = subtitleList.insertSubtitleBefore(sub1); expect(subtitleList.subtitles).toEqual([newSub, sub1]); expect(newSub).toHaveTimes([0, 1000]); expect(sub1).toHaveTimes([1000, 7000]); }); it('splits the time between the next subtitle and the new subtitle if there is less than 2 seconds for them both', function() { subtitleList.updateSubtitleTime(sub1, 0, 800); var newSub = subtitleList.insertSubtitleBefore(sub1); expect(subtitleList.subtitles).toEqual([newSub, sub1]); expect(newSub).toHaveTimes([0, 400]); expect(sub1).toHaveTimes([400, 800]); }); it('never lengthens the next subtitle', function() { subtitleList.updateSubtitleTime(sub1, 800, 1000); var newSub = subtitleList.insertSubtitleBefore(sub1); // when we insert the subtitle, don't split the time since that // would cause sub1 to be longer than before. Instead just newSub // should just take up the entire 2 second gap. expect(subtitleList.subtitles).toEqual([newSub, sub1]); expect(newSub).toHaveTimes([0, 800]); expect(sub1).toHaveTimes([800, 1000]); }); }); describe('split subtitles', function() { it('splits subtitles', function() { var sub1 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleTime(sub1, 0, 8000); var sub2 = subtitleList.splitSubtitle(sub1, 'foo', 'bar'); expect(sub1).toHaveTimes([0, 4000]); expect(sub1.markdown).toEqual('foo'); expect(sub2).toHaveTimes([4000, 8000]); expect(sub2.markdown).toEqual('bar'); expect(subtitleList.syncedCount).toEqual(2); expect(subtitleList.firstSubtitle()).toBe(sub1); expect(subtitleList.nextSubtitle(sub1)).toBe(sub2); expect(subtitleList.nextSubtitle(sub2)).toBe(null); var sub3 = subtitleList.splitSubtitle(sub2, 'b', 'ar'); expect(sub2).toHaveTimes([4000, 6000]); expect(sub2.markdown).toEqual('b'); expect(sub3).toHaveTimes([6000, 8000]); expect(sub3.markdown).toEqual('ar'); expect(subtitleList.syncedCount).toEqual(3); expect(subtitleList.firstSubtitle()).toBe(sub1); expect(subtitleList.nextSubtitle(sub1)).toBe(sub2); expect(subtitleList.nextSubtitle(sub2)).toBe(sub3); expect(subtitleList.nextSubtitle(sub3)).toBe(null); }); it('splits unsynced subtitles', function() { var sub = subtitleList.insertSubtitleBefore(null); var sub2 = subtitleList.splitSubtitle(sub, 'one', 'two'); expect(sub).toHaveTimes([-1, -1]); expect(sub2).toHaveTimes([-1, -1]); expect(sub.markdown).toEqual('one') expect(sub2.markdown).toEqual('two') expect(subtitleList.syncedCount).toEqual(0); }); it('preserves region when splitting subtitles', function() { var sub1 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleTime(sub1, 0, 8000); subtitleList.updateSubtitleRegion(sub1, 'top'); var sub2 = subtitleList.splitSubtitle(sub1, 'foo', 'bar'); expect(sub2.region).toBe('top'); }); }); describe('copyTiming', function() { var referenceSubs; beforeEach(inject(function(SubtitleList) { referenceSubs = new SubtitleList(); referenceSubs.loadEmptySubs('en'); referenceSubs._insertSubtitle(0, { startTime: 100, endTime: 200, startOfParagraph: true }); referenceSubs._insertSubtitle(1, { startTime: 200, endTime: 300, startOfParagraph: true }); referenceSubs._changesDone('insert'); subtitleList.insertSubtitleBefore(null); subtitleList.insertSubtitleBefore(null); })); it('copies timings from another subtitleList', function() { subtitleList.copyTimingsFrom(referenceSubs); expect(subtitleList.subtitles[0]).toHaveTimes([100, 200]); expect(subtitleList.subtitles[1]).toHaveTimes([200, 300]); }); it('copies paragraph starts too', function() { subtitleList.copyTimingsFrom(referenceSubs); expect(subtitleList.subtitles[0].startOfParagraph).toEqual(true); expect(subtitleList.subtitles[1].startOfParagraph).toEqual(true); }); it('unsets timings past the last subtitle of the reference subs', function() { subtitleList.insertSubtitleBefore(null); _.each(subtitleList.subtitles, function(sub, i) { subtitleList.updateSubtitleTime(sub, i * 100, i * 100 + 50); }); subtitleList.copyTimingsFrom(referenceSubs); expect(subtitleList.subtitles[2]).toHaveTimes([-1, -1]); }); }); it('shift subtitles forward', function() { subtitleList._insertSubtitle(0, { startTime: 100, endTime: 200 }); subtitleList._insertSubtitle(1, { startTime: 300, endTime: 400 }); subtitleList._insertSubtitle(2, { startTime: 500, endTime: 600 }); subtitleList._insertSubtitle(3, {}); subtitleList._changesDone('init'); var changes = trackChanges(subtitleList); subtitleList.shiftForward(350, 1000); // Subtitle 0 should be unchanged, since it's before start time // Subtitle 1 should be lengthed, since it overlaps start time // Subtitle 2 should be shifted forward in time, since it's after start time // Subtitle 3 should be unchanged, since it's unsynced expect(changes).toEqual([ ['update', 1, {endTime: 1400}], ['update', 2, {startTime: 1500, endTime: 1600}], ]); }); it('shift subtitles backward', function() { subtitleList._insertSubtitle(0, { startTime: 100, endTime: 200 }); subtitleList._insertSubtitle(1, { startTime: 300, endTime: 400 }); subtitleList._insertSubtitle(2, { startTime: 500, endTime: 600 }); subtitleList._insertSubtitle(3, { startTime: 700, endTime: 800 }); subtitleList._insertSubtitle(4, { startTime: 900, endTime: 1000 }); subtitleList._insertSubtitle(5, {}); subtitleList._changesDone('init'); var changes = trackChanges(subtitleList); subtitleList.shiftBackward(350, 400); // Subtitle 0 should be unchanged, since it's before the removed time // Subtitle 1 should be shortened, since it's end time is inside the removed time // Subtitle 2 should be removed, since all of it is contained in the removed time // Subtitle 3 should be shortened and moved back, since it's start time is inside the removed time // Subtitle 4 should be moved back, since it's after the removed time // Subtitle 5 should be unchanged, since it's unsynced expect(changes).toEqual([ ['update', 1, {endTime: 350}], ['remove', 2, {}], // Note, this decriments all indexs after 2 ['update', 2, {startTime: 350, endTime: 400}], ['update', 3, {startTime: 500, endTime: 600}], ]); }); describe('undo', function() { it('can undo operations', function() { var sub = subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100, content: 'test-content' }); subtitleList._resetUndo(); subtitleList.splitSubtitle(sub, 'test', 'content'); expect(subtitleList.canUndo()).toEqual(true); subtitleList.undo(); expect(subtitleList.subtitles.length).toEqual(1); expect(subtitleList.subtitles[0]).toHaveTimes([0, 100]); expect(subtitleList.subtitles[0].markdown).toEqual('test-content'); expect(subtitleList.canUndo()).toEqual(false); }); it('can redo operations', function() { var sub = subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100, content: 'test-content' }); subtitleList._resetUndo(); subtitleList.splitSubtitle(sub, 'test', 'content'); subtitleList.undo(); expect(subtitleList.canRedo()).toEqual(true); subtitleList.redo(); expect(subtitleList.subtitles.length).toEqual(2); expect(subtitleList.subtitles[0]).toHaveTimes([0, 50]); expect(subtitleList.subtitles[0].markdown).toEqual('test'); expect(subtitleList.subtitles[1]).toHaveTimes([50, 100]); expect(subtitleList.subtitles[1].markdown).toEqual('content'); expect(subtitleList.canUndo()).toEqual(true); expect(subtitleList.canRedo()).toEqual(false); }); it('can recreate removed subtitles', function() { subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100 }); subtitleList._resetUndo(); var sub = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleContent(sub, 'test-content'); subtitleList.updateSubtitleTime(sub, 200, 300); subtitleList.updateSubtitleParagraph(sub, true); subtitleList.updateSubtitleRegion(sub, 'top'); subtitleList.removeSubtitle(sub); subtitleList.undo(); // test that all attributes were successfully recreated var sub = subtitleList.subtitles[1]; expect(sub.startTime).toEqual(200); expect(sub.endTime).toEqual(300); expect(sub.markdown).toEqual('test-content'); expect(sub.startOfParagraph).toEqual(true); expect(sub.region).toEqual('top'); }); it('can recreate updated subtitles', function() { subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100 }); subtitleList._resetUndo(); var sub = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleContent(sub, 'changed'); subtitleList.updateSubtitleTime(sub, 1000, 2000); subtitleList.updateSubtitleParagraph(sub, true); subtitleList.updateSubtitleRegion(sub, 'top'); subtitleList.undo(); subtitleList.undo(); subtitleList.undo(); subtitleList.undo(); // test that all attributes were successfully recreated var sub = subtitleList.subtitles[1]; expect(sub).toHaveTimes([-1, -1]); expect(sub.markdown).toEqual(''); expect(sub.startOfParagraph).toEqual(false); expect(sub.region).toEqual(undefined); }); it('undos operations in the correct order', function() { subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100, content: 'test-content' }); subtitleList._removeSubtitle(0, {}); subtitleList._changesDone('test'); // When we undo multiple changes, we need to undo them in reverse // order. If we try to undo the insert before undoing the remove, // then things will fail subtitleList.undo(); expect(subtitleList.subtitles).toEqual([]); // Try redo and undo again to test the code there subtitleList.redo(); subtitleList.undo(); expect(subtitleList.subtitles).toEqual([]); }); it('has helper methods for the undo/redo menu items', function() { expect(subtitleList.canUndo()).toEqual(false); expect(subtitleList.canRedo()).toEqual(false); subtitleList._insertSubtitle(0, {}); subtitleList._changesDone('change 1'); expect(subtitleList.canUndo()).toEqual(true); expect(subtitleList.canRedo()).toEqual(false); expect(subtitleList.undoText().data.command).toEqual('change 1'); subtitleList._insertSubtitle(0, {}); subtitleList._changesDone('change 2'); expect(subtitleList.canUndo()).toEqual(true); expect(subtitleList.canRedo()).toEqual(false); expect(subtitleList.undoText().data.command).toEqual('change 2'); subtitleList.undo(); expect(subtitleList.canUndo()).toEqual(true); expect(subtitleList.canRedo()).toEqual(true); expect(subtitleList.undoText().data.command).toEqual('change 1'); expect(subtitleList.redoText().data.command).toEqual('change 2'); subtitleList.undo(); expect(subtitleList.canUndo()).toEqual(false); expect(subtitleList.canRedo()).toEqual(true); expect(subtitleList.redoText().data.command).toEqual('change 1'); }); it('can handle complex undo/redo stacks', function() { var sub = subtitleList._insertSubtitle(0, { startTime: 0, endTime: 100, content: 'test-content' }); subtitleList._resetUndo(); subtitleList.splitSubtitle(sub, 'test', 'content'); subtitleList.insertSubtitleBefore(null); subtitleList.undo(); subtitleList.undo(); subtitleList.redo(); subtitleList.undo(); subtitleList.updateSubtitleContent(sub, 'test-content2'); expect(subtitleList.subtitles.length).toEqual(1); expect(subtitleList.subtitles[0]).toHaveTimes([0, 100]); expect(subtitleList.subtitles[0].markdown).toEqual('test-content2'); subtitleList.undo(); expect(subtitleList.subtitles.length).toEqual(1); expect(subtitleList.subtitles[0]).toHaveTimes([0, 100]); expect(subtitleList.subtitles[0].markdown).toEqual('test-content'); }); }); describe('the changeGroup parameter of updateSubtitleTimes', function() { var sub1, sub2, sub3, changes; beforeEach(function() { sub1 = subtitleList.insertSubtitleBefore(null); sub2 = subtitleList.insertSubtitleBefore(null); sub3 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1000, endTime: 1001 }, { subtitle: sub2, startTime: 2000, endTime: 2001 }, ]); subtitleList._resetUndo(); changes = trackChanges(subtitleList); }); it('groups multiple changes into a single undo', function() { subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1001, endTime: 1002 } ], 'changegroup1'); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1002, endTime: 1003, } ], 'changegroup1'); expect(subtitleList.subtitles[0]).toHaveTimes([1002, 1003]); expect(subtitleList.canUndo()).toBe(true); // Undo should undo both changes at once, and do it efficiently (not updating the same subtitle more than once) changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {startTime: 1000, endTime: 1001}], ]); expect(subtitleList.canUndo()).toBe(false); }); it('handles changes that involve multiple subtitles', function() { // Do the same test as before, but with multiple subtitles involved subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1001, endTime: 1002, }, { subtitle: sub2, startTime: 2001, endTime: 2002 } ], 'changegroup1'); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1002, endTime: 1003 } ], 'changegroup1'); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1003, endTime: 1004, }, { subtitle: sub2, startTime: 2002, endTime: 2003 }, { subtitle: sub3, startTime: 3000, endTime: 3001 } ], 'changegroup1'); expect(subtitleList.subtitles[0]).toHaveTimes([1003, 1004]); expect(subtitleList.subtitles[1]).toHaveTimes([2002, 2003]); expect(subtitleList.subtitles[2]).toHaveTimes([3000, 3001]); expect(subtitleList.canUndo()).toBe(true); // Undo should undo both changes at once, and do it efficiently (not updating the same subtitle more than once) changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 1, {startTime: 2000, endTime: 2001}], ['update', 0, {startTime: 1000, endTime: 1001}], ['update', 2, {startTime: -1, endTime: -1}], ]); expect(subtitleList.canUndo()).toBe(false); }); it('does not group changes when changeGroup is different', function() { subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1001, endTime: 1002 } ], 'changegroup1'); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1002, endTime: 1003, } ], 'changegroup2'); // Undo should only undo 1 change at once since the changeGroup ids were different changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {startTime: 1001, endTime: 1002}], ]); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {startTime: 1000, endTime: 1001}], ]); }); it('does not group changes when another operation is in the middle', function() { subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1001, endTime: 1002 } ], 'changegroup1'); subtitleList.updateSubtitleContent(sub1, "content"); subtitleList.updateSubtitleTimes([ { subtitle: sub1, startTime: 1002, endTime: 1003, } ], 'changegroup1'); // Undo should only undo 1 change at once since the changeGroup ids were different changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {startTime: 1001, endTime: 1002}], ]); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: ''}], ]); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {startTime: 1000, endTime: 1001}], ]); }); }); describe('the changeGroup parameter of updateSubtitleContent', function() { var sub1, sub2, sub3, changes; beforeEach(function() { sub1 = subtitleList.insertSubtitleBefore(null); sub2 = subtitleList.insertSubtitleBefore(null); sub3 = subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleContent(sub1, 'content'); subtitleList.updateSubtitleContent(sub2, 'content2'); subtitleList.updateSubtitleContent(sub3, 'content3'); subtitleList._resetUndo(); changes = trackChanges(subtitleList); }); it('groups multiple changes into a single undo', function() { subtitleList.updateSubtitleContent(sub1, 'new-content', 'changegroup1'); subtitleList.updateSubtitleContent(sub1, 'new-content2', 'changegroup1'); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: 'content'}], ]); expect(subtitleList.canUndo()).toBe(false); }); it('handles changes that involve multiple subtitles', function() { subtitleList.updateSubtitleContent(sub1, 'new-content', 'changegroup1'); subtitleList.updateSubtitleContent(sub2, 'new-content2', 'changegroup1'); subtitleList.updateSubtitleContent(sub1, 'new-content3', 'changegroup1'); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: 'content'}], ['update', 1, {content: 'content2'}], ]); expect(subtitleList.canUndo()).toBe(false); }); it('does not group changes when changeGroup is different', function() { subtitleList.updateSubtitleContent(sub1, 'new-content', 'changegroup1'); subtitleList.updateSubtitleContent(sub1, 'new-content2', 'changegroup2'); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: 'new-content'}], ]); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: 'content'}], ]); }); it('does not group changes when another operation is in the middle', function() { subtitleList.updateSubtitleContent(sub1, 'new-content', 'changegroup1'); subtitleList.insertSubtitleBefore(null); subtitleList.updateSubtitleContent(sub1, 'new-content2', 'changegroup1'); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: 'new-content'}], ]); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['remove', 3, {}], ]); changes.length = 0; subtitleList.undo(); expect(changes).toEqual([ ['update', 0, {content: 'content'}], ]); }); }); });
agpl-3.0
AMSoftwareNL/crmpowershell
AMSoftware.Crm.PowerShell.Commands/Administration/NewEnvironmentVariableCommand.cs
4418
/* CRM PowerShell Library Copyright (C) 2017 Arjan Meskers / AMSoftware This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Management.Automation; using AMSoftware.Crm.PowerShell.Common; using AMSoftware.Crm.PowerShell.Common.Repositories; using Microsoft.Xrm.Sdk; namespace AMSoftware.Crm.PowerShell.Commands.Administration { [Cmdlet(VerbsCommon.New, "CrmEnvironmentVariable", HelpUri = HelpUrlConstants.NewEnvironmentVariableHelpUrl)] [OutputType(typeof(Entity))] public sealed class NewEnvironmentVariableCommand : CrmOrganizationCmdlet { private readonly ContentRepository _repository = new ContentRepository(); [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty] public string DisplayName { get; set; } [Parameter()] [ValidateNotNullOrEmpty] public string Description { get; set; } [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty] public CrmEnvironmentVariableType VariableType { get; set; } [Parameter()] [ValidateNotNullOrEmpty] public object DefaultValue { get; set; } [Parameter()] [ValidateNotNullOrEmpty] public object Value { get; set; } [Parameter] public SwitchParameter PassThru { get; set; } protected override void ExecuteCmdlet() { base.ExecuteCmdlet(); switch (VariableType) { case CrmEnvironmentVariableType.All: throw new PSNotSupportedException("Type 'All' is not a supported EnvironmentVariable Type."); case CrmEnvironmentVariableType.String: break; case CrmEnvironmentVariableType.Number: break; case CrmEnvironmentVariableType.Boolean: break; case CrmEnvironmentVariableType.JSON: break; case CrmEnvironmentVariableType.DataSource: throw new PSNotImplementedException(); default: break; } Entity newEnvironmentVariable = new Entity("environmentvariabledefinition") { Attributes = new AttributeCollection() }; newEnvironmentVariable.Attributes.Add("schemaname", Name); newEnvironmentVariable.Attributes.Add("displayname", DisplayName); newEnvironmentVariable.Attributes.Add("type", new OptionSetValue((int)VariableType)); if (!string.IsNullOrWhiteSpace(Description)) { newEnvironmentVariable.Attributes.Add("description", Description); } if (DefaultValue != null) { newEnvironmentVariable.Attributes.Add("defaultvalue", DefaultValue); } Guid newEnvironmentVariableId = _repository.Add(newEnvironmentVariable); if (Value != null) { Entity newEnvironmentVariableValue = new Entity("environmentvariablevalue") { Attributes = new AttributeCollection() }; newEnvironmentVariableValue.Attributes.Add("environmentvariabledefinitionid", new EntityReference("environmentvariabledefinition", newEnvironmentVariableId)); newEnvironmentVariableValue.Attributes.Add("value", Value); _repository.Add(newEnvironmentVariableValue); } if (PassThru) { WriteObject(_repository.Get("environmentvariabledefinition", newEnvironmentVariableId)); } } } }
agpl-3.0
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/core/client/widget/CheckboxLabel.java
1449
/* * CheckboxLabel.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.widget; import com.google.gwt.dom.client.Style.Cursor; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; public class CheckboxLabel implements IsWidget { public CheckboxLabel(final CheckBox checkbox, String label) { label_ = new Label(label); label_.getElement().getStyle().setCursor(Cursor.DEFAULT); label_.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { event.preventDefault(); checkbox.setValue(!checkbox.getValue()); } }); } @Override public Widget asWidget() { return label_; } public Label getLabel() { return label_; } private final Label label_; }
agpl-3.0
3drepo/3drepo.io
frontend/src/v4/modules/presentation/presentation.selectors.ts
2561
/** * Copyright (C) 2020 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import { createSelector } from 'reselect'; import { ROUTES } from '../../constants/routes'; import { selectCurrentModel, selectCurrentModelTeamspace } from '../model'; import { selectQueryParams, selectUrlParams } from '../router/router.selectors'; import { PresentationMode } from './presentation.constants'; export const selectPresentationDomain = (state) => state.presentation; export const selectIsPresenting = createSelector( selectPresentationDomain, (state) => state.isPresenting ); export const selectJoinedPresentation = createSelector( selectPresentationDomain, (state) => state.joinedPresentation ); export const selectPresentationMode = createSelector( selectIsPresenting, selectJoinedPresentation, (isPresenting, joinedPresentation) => isPresenting ? PresentationMode.PRESENTER : joinedPresentation ? PresentationMode.PARTICIPANT : PresentationMode.INITIAL ); export const selectSessionCode = createSelector( selectPresentationDomain, (state) => state.sessionCode ); export const selectIsPaused = createSelector( selectPresentationDomain, (state) => state.isPaused ); export const selectIsViewerManipulationEnabled = createSelector( selectJoinedPresentation, selectIsPaused, (joined, paused) => !joined || paused ); export const selectIsPresentationActive = createSelector( selectPresentationMode, (mode) => mode !== PresentationMode.INITIAL ); export const selectPresentationUrl = createSelector( selectSessionCode, selectCurrentModelTeamspace, selectCurrentModel, (code, teamspace, modelId) => `${location.protocol}//${location.hostname}${ROUTES.VIEWER}/${teamspace}/${modelId}?presenter=${code}` ); export const selectJoinedUrlQueryPresentation = createSelector( selectQueryParams, selectSessionCode, selectJoinedPresentation, ( params, code, joined) => params.presenter === code && joined );
agpl-3.0
juju/juju
worker/apiservercertwatcher/authorityworker.go
1770
// Copyright 2020 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package apiservercertwatcher import ( "github.com/juju/errors" "github.com/juju/worker/v3/catacomb" "github.com/juju/juju/agent" "github.com/juju/juju/pki" ) // OperatorWatcher is responsible for creating a new PKI certificate chain to // use in operators that need to start their own HTTPS servers. // TODO this watcher should be replaced in the future to use an intermediate CA // from the controller type PKIAuthorityWorker struct { authority pki.Authority catacomb catacomb.Catacomb } func NewAuthorityWorker(_ agent.Agent) (AuthorityWorker, error) { return newPKIAuthorityWorker() } func newPKIAuthorityWorker() (*PKIAuthorityWorker, error) { signer, err := pki.DefaultKeyProfile() if err != nil { return nil, errors.Annotate(err, "creating agent watcher signer") } cert, err := pki.NewCA("juju agent", signer) if err != nil { return nil, errors.Annotate(err, "creating agent ca certificate") } authority, err := pki.NewDefaultAuthority(cert, signer) if err != nil { return nil, errors.Annotate(err, "creating authority for agent ca and signer") } agentWatcher := &PKIAuthorityWorker{ authority: authority, } if err := catacomb.Invoke(catacomb.Plan{ Site: &agentWatcher.catacomb, Work: agentWatcher.loop, }); err != nil { return agentWatcher, errors.Trace(err) } return agentWatcher, nil } func (a *PKIAuthorityWorker) Authority() pki.Authority { return a.authority } func (a *PKIAuthorityWorker) Kill() { a.catacomb.Kill(nil) } func (a *PKIAuthorityWorker) Wait() error { return a.catacomb.Wait() } func (a *PKIAuthorityWorker) loop() error { select { case <-a.catacomb.Dying(): return a.catacomb.ErrDying() } }
agpl-3.0
timetabio/code
Framework/src/Pdo/Value/Boolean.php
831
<?php /** * Copyright (c) 2016 Ruben Schmidmeister <ruben.schmidmeister@icloud.com> * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the GNU Affero General Public License, * version 3, as published by the Free Software Foundation. */ namespace Timetabio\Framework\Pdo\Value { class Boolean implements ValueInterface { /** * @var bool */ private $value; public function __construct(bool $value) { $this->value = $value; } public function getType(): int { return \PDO::PARAM_BOOL; } public function getValue(): bool { return $this->value; } } }
agpl-3.0
Lidefeath/ACE
Source/ACE.Database/Models/Shard/BiotaPropertiesGenerator.cs
1078
using System; using System.Collections.Generic; namespace ACE.Database.Models.Shard { public partial class BiotaPropertiesGenerator { public uint Id { get; set; } public uint ObjectId { get; set; } public float Probability { get; set; } public uint WeenieClassId { get; set; } public float? Delay { get; set; } public uint InitCreate { get; set; } public uint MaxCreate { get; set; } public uint WhenCreate { get; set; } public uint WhereCreate { get; set; } public int? StackSize { get; set; } public uint? PaletteId { get; set; } public float? Shade { get; set; } public uint? ObjCellId { get; set; } public float? OriginX { get; set; } public float? OriginY { get; set; } public float? OriginZ { get; set; } public float? AnglesW { get; set; } public float? AnglesX { get; set; } public float? AnglesY { get; set; } public float? AnglesZ { get; set; } public Biota Object { get; set; } } }
agpl-3.0
nvoron23/rstudio
src/cpp/desktop/DesktopSatelliteWindow.cpp
2123
/* * DesktopSatelliteWindow.cpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "DesktopSatelliteWindow.hpp" #include <QWebFrame> #include "DesktopGwtCallback.hpp" namespace desktop { SatelliteWindow::SatelliteWindow(MainWindow* pMainWindow, QString name) : GwtWindow(false, true, name), gwtCallback_(pMainWindow, this) { setAttribute(Qt::WA_QuitOnClose, false); setAttribute(Qt::WA_DeleteOnClose, true); setWindowIcon(QIcon(QString::fromUtf8(":/icons/RStudio.ico"))); } void SatelliteWindow::onJavaScriptWindowObjectCleared() { webView()->page()->mainFrame()->addToJavaScriptWindowObject( QString::fromUtf8("desktop"), &gwtCallback_, QWebFrame::QtOwnership); connect(webView(), SIGNAL(onCloseWindowShortcut()), this, SLOT(onCloseWindowShortcut())); } void SatelliteWindow::onCloseWindowShortcut() { close(); } void SatelliteWindow::finishLoading(bool ok) { BrowserWindow::finishLoading(ok); if (ok) avoidMoveCursorIfNecessary(); } void SatelliteWindow::closeEvent(QCloseEvent *event) { webView()->page()->mainFrame()->evaluateJavaScript(QString::fromUtf8( "if (window.notifyRStudioSatelliteClosing) " " window.notifyRStudioSatelliteClosing();")); // forward the close event to the web view webView()->event(event); } void SatelliteWindow::onActivated() { webView()->page()->mainFrame()->evaluateJavaScript(QString::fromUtf8( "if (window.notifyRStudioSatelliteReactivated) " " window.notifyRStudioSatelliteReactivated(null);")); } } // namespace desktop
agpl-3.0
yinhm/sugarcrm
modules/Leads/metadata/editviewdefs.php
6342
<?php /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $viewdefs['Leads']['EditView'] = array( 'templateMeta' => array('form' => array('hidden'=>array('<input type="hidden" name="prospect_id" value="{if isset($smarty.request.prospect_id)}{$smarty.request.prospect_id}{else}{$bean->prospect_id}{/if}">', '<input type="hidden" name="account_id" value="{if isset($smarty.request.account_id)}{$smarty.request.account_id}{else}{$bean->account_id}{/if}">', '<input type="hidden" name="contact_id" value="{if isset($smarty.request.contact_id)}{$smarty.request.contact_id}{else}{$bean->contact_id}{/if}">', '<input type="hidden" name="opportunity_id" value="{if isset($smarty.request.opportunity_id)}{$smarty.request.opportunity_id}{else}{$bean->opportunity_id}{/if}">'), 'buttons' => array( 'SAVE', 'CANCEL', ) ), 'maxColumns' => '2', 'widths' => array( array('label' => '10', 'field' => '30'), array('label' => '10', 'field' => '30') ), 'javascript' => '<script type="text/javascript" language="Javascript">function copyAddressRight(form) {ldelim} form.alt_address_street.value = form.primary_address_street.value;form.alt_address_city.value = form.primary_address_city.value;form.alt_address_state.value = form.primary_address_state.value;form.alt_address_postalcode.value = form.primary_address_postalcode.value;form.alt_address_country.value = form.primary_address_country.value;return true; {rdelim} function copyAddressLeft(form) {ldelim} form.primary_address_street.value =form.alt_address_street.value;form.primary_address_city.value = form.alt_address_city.value;form.primary_address_state.value = form.alt_address_state.value;form.primary_address_postalcode.value =form.alt_address_postalcode.value;form.primary_address_country.value = form.alt_address_country.value;return true; {rdelim} </script>', ), 'panels' =>array ( 'LBL_CONTACT_INFORMATION' => array ( array ( array ( 'name' => 'first_name', 'customCode' => '{html_options id="salutation" name="salutation" options=$fields.salutation.options selected=$fields.salutation.value}&nbsp;<input id="first_name" name="first_name" size="25" maxlength="25" type="text" value="{$fields.first_name.value}">', ), ), array ( array('name'=>'last_name', 'displayParams'=>array('required'=>true), ), 'phone_work', ), array ( 'title', 'phone_mobile' ), array ( 'department', 'phone_fax' ), array ( array('name'=>'account_name', 'type'=>'varchar', 'validateDependency'=>false,'customCode' => '<input name="account_name" {if ($fields.converted.value == 1)}disabled="true"{/if} size="30" maxlength="255" type="text" value="{$fields.account_name.value}">'), 'website', ), array ( array ( 'name' => 'primary_address_street', 'hideLabel' => true, 'type' => 'address', 'displayParams'=>array('key'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), ), array ( 'name' => 'alt_address_street', 'hideLabel'=>true, 'type' => 'address', 'displayParams'=>array('key'=>'alt', 'copy'=>'primary', 'rows'=>2, 'cols'=>30, 'maxlength'=>150), ), ), array ( 'email1', ), array ( 'description', ), ), 'LBL_PANEL_ADVANCED' => array( array( 'status', 'lead_source', ), array ( array('name'=>'status_description'), array('name'=>'lead_source_description'), ), array( 'campaign_name', 'refered_by' ), array ( '', 'do_not_call', ), ), 'LBL_PANEL_ASSIGNMENT' => array ( array ( array ( 'name' => 'assigned_user_name', 'label' => 'LBL_ASSIGNED_TO', ), ), ), ), ); ?>
agpl-3.0
teoincontatto/engine
packaging-utils/src/main/java/com/torodb/packaging/config/util/ConfigUtils.java
16093
/* * ToroDB * Copyright © 2014 8Kdata Technology (www.8kdata.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.torodb.packaging.config.util; import com.beust.jcommander.internal.Console; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException.Reference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.exc.PropertyBindingException; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import com.google.common.base.Charsets; import com.torodb.packaging.config.model.backend.BackendPasswordConfig; import com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig; import org.apache.logging.log4j.Logger; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Path; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; public class ConfigUtils { public static final String getUserHomePath() { return System.getProperty("user.home", "."); } public static final String getUserHomeFilePath(String file) { return getUserHomePath() + File.separatorChar + file; } public static ObjectMapper mapper(boolean excludeDefaults) { ObjectMapper objectMapper = new ObjectMapper(); configMapper(objectMapper, excludeDefaults); return objectMapper; } public static YAMLMapper yamlMapper(boolean excludeDefaults) { YAMLMapper yamlMapper = new YAMLMapper(); configMapper(yamlMapper, excludeDefaults); return yamlMapper; } public static XmlMapper xmlMapper(boolean excludeDefaults) { XmlMapper xmlMapper = new XmlMapper(); configMapper(xmlMapper, excludeDefaults); return xmlMapper; } private static void configMapper(ObjectMapper objectMapper, boolean excludeDefaults) { objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, true); objectMapper.configure(Feature.ALLOW_COMMENTS, true); objectMapper.configure(Feature.ALLOW_YAML_COMMENTS, true); objectMapper.setSerializationInclusion(Include.NON_EMPTY); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); if (excludeDefaults) { objectMapper.setSerializationInclusion(Include.NON_DEFAULT); } } public static IllegalArgumentException transformJsonMappingException( JsonMappingException jsonMappingException) { JsonPointer jsonPointer = JsonPointer.compile("/config"); for (Reference reference : jsonMappingException.getPath()) { if (reference.getIndex() != -1) { jsonPointer = jsonPointer.append(JsonPointer.compile("/" + reference.getIndex())); } if (reference.getFieldName() != null) { jsonPointer = jsonPointer.append(JsonPointer.compile("/" + reference.getFieldName())); } } if (jsonMappingException instanceof PropertyBindingException) { return transformJsonMappingException(jsonPointer, (PropertyBindingException) jsonMappingException); } return transformJsonMappingException(jsonPointer, jsonMappingException); } private static IllegalArgumentException transformJsonMappingException(JsonPointer jsonPointer, JsonMappingException jsonMappingException) { return transformJsonMappingException(jsonPointer, "Wrong value", jsonMappingException); } private static IllegalArgumentException transformJsonMappingException(JsonPointer jsonPointer, PropertyBindingException jsonMappingException) { return transformJsonMappingException(jsonPointer, "Unrecognized field " + jsonMappingException .getPropertyName() + " (known fields: " + jsonMappingException.getKnownPropertyIds() + ")", jsonMappingException); } private static IllegalArgumentException transformJsonMappingException(JsonPointer jsonPointer, String message, JsonMappingException jsonMappingException) { return new IllegalArgumentException("Validation error at " + jsonPointer + ": " + message, jsonMappingException); } public static <T> T readConfigFromYaml(Class<T> configClass, String yamlString) throws JsonProcessingException, IOException { ObjectMapper objectMapper = mapper(true); YAMLMapper yamlMapper = yamlMapper(true); JsonNode configNode = yamlMapper.readTree(yamlString); T config = objectMapper.treeToValue(configNode, configClass); validateBean(config); return config; } public static <T> T readConfigFromXml(Class<T> configClass, String xmlString) throws JsonProcessingException, IOException { ObjectMapper objectMapper = mapper(true); XmlMapper xmlMapper = xmlMapper(true); JsonNode configNode = xmlMapper.readTree(xmlString); T config = objectMapper.treeToValue(configNode, configClass); validateBean(config); return config; } public static void parseToropassFile(final BackendPasswordConfig backendPasswordConfig, Logger logger) throws FileNotFoundException, IOException { backendPasswordConfig.setPassword(getPasswordFromPassFile( backendPasswordConfig.getToropassFile(), backendPasswordConfig.getHost(), backendPasswordConfig.getPort(), backendPasswordConfig.getDatabase(), backendPasswordConfig.getUser(), logger )); } public static void parseMongopassFile(final MongoPasswordConfig mongoPasswordConfig, Logger logger) throws FileNotFoundException, IOException { mongoPasswordConfig.setPassword(getPasswordFromPassFile( mongoPasswordConfig.getMongopassFile(), mongoPasswordConfig.getHost(), mongoPasswordConfig.getPort(), mongoPasswordConfig.getDatabase(), mongoPasswordConfig.getUser(), logger )); } private static String getPasswordFromPassFile( String passFile, String host, int port, String database, String user, Logger logger) throws FileNotFoundException, IOException { File pass = new File(passFile); if (pass.exists() && pass.canRead() && pass.isFile()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(pass), Charsets.UTF_8)); try { String line; int index = 0; while ((line = br.readLine()) != null) { index++; String[] passChunks = line.split(":"); if (passChunks.length != 5) { logger.warn("Wrong format at line " + index + " of file " + passFile); continue; } if ((passChunks[0].equals("*") || passChunks[0].equals(host)) && (passChunks[1].equals("*") || passChunks[1].equals(String.valueOf(port))) && (passChunks[2].equals("*") || passChunks[2].equals(database)) && (passChunks[3].equals("*") || passChunks[3].equals(user))) { return passChunks[4]; } } br.close(); } finally { br.close(); } } return null; } public static ObjectNode mergeParam(ObjectMapper objectMapper, ObjectNode configRootNode, String pathAndProp, String value) throws Exception { if (JsonPointer.compile(pathAndProp).equals(JsonPointer.compile("/"))) { return (ObjectNode) objectMapper.readTree(value); } String path = pathAndProp.substring(0, pathAndProp.lastIndexOf("/")); String prop = pathAndProp.substring(pathAndProp.lastIndexOf("/") + 1); JsonPointer pathPointer = JsonPointer.compile(path); JsonNode pathNode = configRootNode.at(pathPointer); if (pathNode.isMissingNode() || pathNode.isNull()) { JsonPointer currentPointer = pathPointer; JsonPointer childOfCurrentPointer = null; List<JsonPointer> missingPointers = new ArrayList<>(); List<JsonPointer> childOfMissingPointers = new ArrayList<>(); do { if (pathNode.isMissingNode() || pathNode.isNull()) { missingPointers.add(0, currentPointer); childOfMissingPointers.add(0, childOfCurrentPointer); } childOfCurrentPointer = currentPointer; currentPointer = currentPointer.head(); pathNode = configRootNode.at(currentPointer); } while (pathNode.isMissingNode() || pathNode.isNull()); for (int missingPointerIndex = 0; missingPointerIndex < missingPointers.size(); missingPointerIndex++) { final JsonPointer missingPointer = missingPointers.get(missingPointerIndex); final JsonPointer childOfMissingPointer = childOfMissingPointers.get(missingPointerIndex); final List<JsonNode> newNodes = new ArrayList<>(); if (pathNode.isObject()) { ((ObjectNode) pathNode).set(missingPointer.last().getMatchingProperty(), createNode(childOfMissingPointer, newNodes)); } else if (pathNode.isArray() && missingPointer.last().mayMatchElement()) { for (int index = ((ArrayNode) pathNode).size(); index < missingPointer.last() .getMatchingIndex() + 1; index++) { ((ArrayNode) pathNode).add(createNode(childOfMissingPointer, newNodes)); } } else { throw new RuntimeException("Cannot set param " + pathAndProp + "=" + value); } pathNode = newNodes.get(newNodes.size() - 1); } } Object valueAsObject; try { valueAsObject = objectMapper.readValue(value, Object.class); } catch (JsonMappingException jsonMappingException) { throw JsonMappingException.wrapWithPath(jsonMappingException, configRootNode, path .substring(1) + "/" + prop); } if (pathNode instanceof ObjectNode) { ObjectNode objectNode = (ObjectNode) pathNode; if (valueAsObject != null) { JsonNode valueNode = objectMapper.valueToTree(valueAsObject); objectNode.set(prop, valueNode); } else { objectNode.remove(prop); } } else if (pathNode instanceof ArrayNode) { ArrayNode arrayNode = (ArrayNode) pathNode; Integer index = Integer.valueOf(prop); if (valueAsObject != null) { JsonNode valueNode = objectMapper.valueToTree(valueAsObject); arrayNode.set(index, valueNode); } else { arrayNode.remove(index); } } return configRootNode; } public static <T> JsonNode getParam(T config, String pathAndProp) throws Exception { ObjectMapper mapper = mapper(false); JsonNode configNode = mapper.valueToTree(config); if (JsonPointer.compile(pathAndProp).equals(JsonPointer.compile("/"))) { return configNode; } JsonPointer pathPointer = JsonPointer.compile(pathAndProp); JsonNode pathNode = configNode.at(pathPointer); if (pathNode.isMissingNode() || pathNode.isNull()) { return null; } return pathNode; } private static JsonNode createNode(JsonPointer childOfPointer, List<JsonNode> newNodes) { JsonNode newNode; if (childOfPointer == null || !childOfPointer.last().mayMatchElement()) { newNode = JsonNodeFactory.instance.objectNode(); } else { newNode = JsonNodeFactory.instance.arrayNode(); } newNodes.add(newNode); return newNode; } public static <T> void printYamlConfig(T config, Console console) throws IOException, JsonGenerationException, JsonMappingException { ObjectMapper objectMapper = yamlMapper(false); ObjectWriter objectWriter = objectMapper.writer(); printConfig(config, console, objectWriter); } public static <T> void printXmlConfig(T config, Console console) throws IOException, JsonGenerationException, JsonMappingException { ObjectMapper objectMapper = xmlMapper(false); ObjectWriter objectWriter = objectMapper.writer(); objectWriter = objectWriter.withRootName("config"); printConfig(config, console, objectWriter); } private static <T> void printConfig(T config, Console console, ObjectWriter objectWriter) throws IOException, JsonGenerationException, JsonMappingException, UnsupportedEncodingException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(byteArrayOutputStream, false, Charsets.UTF_8.name()); objectWriter.writeValue(printStream, config); console.println(byteArrayOutputStream.toString(Charsets.UTF_8.name())); } public static <T> void printParamDescriptionFromConfigSchema(Class<T> configClass, ResourceBundle resourceBundle, Console console, int tabs) throws UnsupportedEncodingException, JsonMappingException { ObjectMapper objectMapper = mapper(false); DescriptionFactoryWrapper visitor = new DescriptionFactoryWrapper( resourceBundle, console, tabs); objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(configClass), visitor); console.println(""); } public static <T> void validateBean(T config) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(config); if (!constraintViolations.isEmpty()) { IllegalArgumentException illegalArgumentException = transformConstraintsValidation( constraintViolations); throw illegalArgumentException; } } private static <T> IllegalArgumentException transformConstraintsValidation( Set<ConstraintViolation<T>> constraintViolations) { ConstraintViolation<T> constraintViolation = constraintViolations.iterator().next(); Path path = constraintViolation.getPropertyPath(); JsonPointer jsonPointer = toJsonPointer(path); return new IllegalArgumentException("Constraint validation errors at " + jsonPointer.toString() + ": " + constraintViolation.getMessage()); } public static JsonPointer toJsonPointer(Path path) { JsonPointer pointer = JsonPointer.valueOf(null); for (Path.Node pathNode : path) { if (pathNode.getIndex() != null) { pointer = pointer.append(JsonPointer.valueOf("/" + pathNode.getIndex())); } if (pathNode.getName() != null) { pointer = pointer.append(JsonPointer.valueOf("/" + pathNode.getName())); } } return pointer; } }
agpl-3.0
fundacionempowerment/VACH
modules/admin/views/team-type/dimensions.php
1943
<?php use yii\bootstrap\ActiveForm; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $teamType app\models\TeamType */ $this->title = ($teamType->id == 0 ? Yii::t('team', 'New team type') : Yii::t('app', 'Edit') . ' ' . $teamType->name); $this->params['breadcrumbs'][] = ['label' => Yii::t('team', 'Team Types'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $teamType->name, 'url' => ['view', 'id' => $teamType->id]]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="site-wheel"> <h1><?= Html::encode($this->title) ?></h1> <?php $form = ActiveForm::begin(['id' => 'questions-form']); ?> <h3><?= $teamType->getAttributeLabel('wheelDimensions') ?></h3> <div class="row col-xs-12"> <?php $current_level = -1; $div_open = false; foreach ($teamType->dimensions as $dimension) { if (!$teamType->isLevelEnabled($dimension->level)) { continue; } if ($current_level != $dimension->level) { $current_level = $dimension->level; if ($div_open == true) { echo '</div>'; $div_open = false; } echo '<div class="box"><h3>' . $teamType->levelName($current_level) . '</h3>'; $div_open = true; } ?> <div class="form-group"> <?= Html::input('text', "name-$dimension->level-$dimension->order", $dimension->name, ['class' => 'form-control']) ?> <?= Html::textarea("desc-$dimension->level-$dimension->order", $dimension->description, ['class' => 'form-control']) ?> </div> <?php } ?> <?= '</div>' ?> </div> <p> <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-primary']); ?> </p> <?php ActiveForm::end(); ?> </div>
agpl-3.0
StartupdotSC/Lemyr
db/migrate/20130712133825_add_attachment_avatar_attached_to_users.rb
237
class AddAttachmentAvatarAttachedToUsers < ActiveRecord::Migration def self.up change_table :users do |t| t.attachment :avatar_attached end end def self.down drop_attached_file :users, :avatar_attached end end
agpl-3.0
fakena/myoc4078
opencog/embodiment/Control/PerceptionActionInterface/ActionParamType.cc
5012
/* * opencog/embodiment/Control/PerceptionActionInterface/ActionParamType.cc * * Copyright (C) 2002-2009 Novamente LLC * All Rights Reserved * Author(s): Novamente team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "ActionParamType.h" #include <opencog/util/Logger.h> #include <opencog/util/oc_assert.h> #include <iostream> using namespace PerceptionActionInterface; /*====================================* * Static data members initialization * * ===================================*/ // Internal maps ActionParamType::Name2ActionParamTypeMap ActionParamType::nameMap; ActionParamType::Code2ActionParamTypeMap ActionParamType::codeMap; // Definition of all action type values const ActionParamType& ActionParamType::BOOLEAN() { static ActionParamType* result = new ActionParamType(BOOLEAN_CODE, "boolean"); return *result; } const ActionParamType& ActionParamType::INT() { static ActionParamType* result = new ActionParamType(INT_CODE, "int"); return *result; } const ActionParamType& ActionParamType::FLOAT() { static ActionParamType* result = new ActionParamType(FLOAT_CODE, "float"); return *result; } const ActionParamType& ActionParamType::STRING() { static ActionParamType* result = new ActionParamType(STRING_CODE, "string"); return *result; } const ActionParamType& ActionParamType::VECTOR() { static ActionParamType* result = new ActionParamType(VECTOR_CODE, "vector"); return *result; } const ActionParamType& ActionParamType::ROTATION() { static ActionParamType* result = new ActionParamType(ROTATION_CODE, "rotation"); return *result; } const ActionParamType& ActionParamType::ENTITY() { static ActionParamType* result = new ActionParamType(ENTITY_CODE, "entity"); return *result; } // Constructors ActionParamType::ActionParamType() {}; ActionParamType::ActionParamType(ActionParamTypeCode _code, const std::string& _name): code(_code), name(_name) { if (ActionParamType::existCode(code)) { OC_ASSERT(false, "ActionParamType - Duplicate action parameter type code: %d", _code); } if (ActionParamType::existName(name)) { OC_ASSERT(false, "ActionParamType - Duplicate action parameter type name: %s", _name.c_str()); } nameMap[name] = this; codeMap[code] = this; } // GETTERS const std::string& ActionParamType::getName() const { return name; } ActionParamTypeCode ActionParamType::getCode() const { return code; } bool ActionParamType::operator==(const ActionParamType& other) const { return (code == other.code); } bool ActionParamType::operator!=(const ActionParamType& other) const { return (code != other.code); } // STATIC METHODS: void ActionParamType::init() { static bool initialized = false; if (!initialized) { BOOLEAN(); INT(); FLOAT(); STRING(); VECTOR(); ROTATION(); ENTITY(); initialized = true; } } const ActionParamType& ActionParamType::getFromName(const std::string& name) throw (opencog::InvalidParamException, std::bad_exception) { init(); Name2ActionParamTypeMap::const_iterator itr = nameMap.find(name); if (itr == nameMap.end()) { throw opencog::InvalidParamException(TRACE_INFO, "ActionParamType - Invalid/unknown ActionParam name: %s\n", name.c_str()); } return *(itr->second); } const ActionParamType& ActionParamType::getFromCode(ActionParamTypeCode code) throw (opencog::InvalidParamException, std::bad_exception) { init(); Code2ActionParamTypeMap::const_iterator itr = codeMap.find(code); if (itr == codeMap.end()) { throw opencog::InvalidParamException(TRACE_INFO, "ActionParamType - Invalid/unknown ActionParam code: %d\n", code); } return *(itr->second); } bool ActionParamType::existName(const std::string& name) { Name2ActionParamTypeMap::const_iterator itr = nameMap.find(name); return (itr != nameMap.end()); } bool ActionParamType::existCode(ActionParamTypeCode code) { Code2ActionParamTypeMap::const_iterator itr = codeMap.find(code); return (itr != codeMap.end()); } std::ostream& operator<<(std::ostream& out, const ActionParamType& arg) { return (out << arg.getName()); }
agpl-3.0
combefis/OpenSM
modules/exams/client/exams.client.module.js
601
(function (app) { 'use strict'; app.registerModule('exams', ['core']);// The core module is required for special route handling; see /core/client/config/core.client.routes app.registerModule('exams.routes', ['ui.router', 'core.routes', 'exams.services']); app.registerModule('exams.manager'); app.registerModule('exams.manager.routes', ['ui.router', 'core.routes', 'exams.services']); app.registerModule('exams.admin'); app.registerModule('exams.admin.routes', ['ui.router', 'core.admin.routes', 'exams.services']); app.registerModule('exams.services'); }(ApplicationConfiguration));
agpl-3.0
tradity/tradity-server
test/cli/config.js
1976
// Tradity.de Server // Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de> // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. 'use strict'; const assert = require('assert'); const path = require('path'); const fs = require('fs'); const spawnSync = require('./cli-helpers.js').spawnSync; const Config = require('../../config.js'); const cfg = new Config().reloadConfig().config(); describe('config.js', function() { it('Can list the current config', function() { const result = spawnSync('./config.js', []); assert.strictEqual(result.status, 0); assert.ok(result.stdout.toString().match(/defaultStartingMoney:/)); }); it('Can list all included config files', function() { const result = spawnSync('./config.js', ['--show-files']); assert.strictEqual(result.status, 0); const configFiles = result.stdout.toString().split('\n').filter(f => f); assert.ok(configFiles.length > 0); configFiles.forEach(filename => { // throws on failure fs.accessSync(path.resolve(__dirname, '../../', filename), fs.R_OK); }); }); it('Can extract config properties by path', function() { const result = spawnSync('./config.js', ['clientconfig', 3]); assert.strictEqual(result.status, 0); assert.strictEqual(result.stdout.toString().trim(), cfg.clientconfig[3]); }); });
agpl-3.0
apmuthu/radicore
radicore/product/prod_cat_class.add.php
533
<?php //***************************************************************************** // Allow a new occurrence to be added to the PROD_CAT_CLASS table for a particular // value of PRODUCT_ID, as selected in the previous screen.. //***************************************************************************** //DebugBreak(); $table_id = 'prod_cat_class'; // table name $screen = 'prod_cat_class.detail.screen.inc'; // file identifying screen structure // activate page controller require 'std.add2.inc'; ?>
agpl-3.0
PyBossa/pybossa
pybossa/cache/site_stats.py
4920
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PYBOSSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>. """Cache module for site statistics.""" from sqlalchemy.sql import text from flask import current_app from pybossa.core import db from pybossa.cache import cache, ONE_DAY session = db.slave_session @cache(timeout=ONE_DAY, key_prefix="site_n_auth_users") def n_auth_users(): """Return number of authenticated users.""" sql = text('''SELECT COUNT("user".id) AS n_auth FROM "user";''') results = session.execute(sql) for row in results: n_auth = row.n_auth return n_auth or 0 @cache(timeout=ONE_DAY, key_prefix="site_n_anon_users") def n_anon_users(): """Return number of anonymous users.""" sql = text('''SELECT COUNT(DISTINCT(task_run.user_ip)) AS n_anon FROM task_run;''') results = session.execute(sql) for row in results: n_anon = row.n_anon return n_anon or 0 @cache(timeout=ONE_DAY, key_prefix="site_n_tasks") def n_tasks_site(): """Return number of tasks in the server.""" sql = text('''SELECT COUNT(task.id) AS n_tasks FROM task''') results = session.execute(sql) for row in results: n_tasks = row.n_tasks return n_tasks or 0 @cache(timeout=ONE_DAY, key_prefix="site_n_total_tasks") def n_total_tasks_site(): """Return number of total tasks based on redundancy.""" sql = text('''SELECT SUM(n_answers) AS n_tasks FROM task''') results = session.execute(sql) for row in results: total = row.n_tasks return total or 0 @cache(timeout=ONE_DAY, key_prefix="site_n_task_runs") def n_task_runs_site(): """Return number of task runs in the server.""" sql = text('''SELECT COUNT(task_run.id) AS n_task_runs FROM task_run''') results = session.execute(sql) for row in results: n_task_runs = row.n_task_runs return n_task_runs or 0 @cache(timeout=ONE_DAY, key_prefix="site_n_results") def n_results_site(): """Return number of results in the server.""" sql = text(''' SELECT COUNT(id) AS n_results FROM result WHERE info IS NOT NULL AND cast(info AS TEXT) != 'null' AND cast(info AS TEXT) != ''; ''') results = session.execute(sql) for row in results: n_results = row.n_results return n_results or 0 @cache(timeout=ONE_DAY, key_prefix="site_top5_apps_24_hours") def get_top5_projects_24_hours(): """Return the top 5 projects more active in the last 24 hours.""" # Top 5 Most active projects in last 24 hours sql = text('''SELECT project.id, project.name, project.short_name, project.info, COUNT(task_run.project_id) AS n_answers FROM project, task_run WHERE project.id=task_run.project_id AND DATE(task_run.finish_time) > NOW() - INTERVAL '24 hour' AND DATE(task_run.finish_time) <= NOW() GROUP BY project.id ORDER BY n_answers DESC LIMIT 5;''') results = session.execute(sql, dict(limit=5)) top5_apps_24_hours = [] for row in results: tmp = dict(id=row.id, name=row.name, short_name=row.short_name, info=row.info, n_answers=row.n_answers) top5_apps_24_hours.append(tmp) return top5_apps_24_hours @cache(timeout=ONE_DAY, key_prefix="site_top5_users_24_hours") def get_top5_users_24_hours(): """Return top 5 users in last 24 hours.""" # Top 5 Most active users in last 24 hours sql = text('''SELECT "user".id, "user".fullname, "user".name, "user".restrict, COUNT(task_run.project_id) AS n_answers FROM "user", task_run WHERE "user".restrict=false AND "user".id=task_run.user_id AND DATE(task_run.finish_time) > NOW() - INTERVAL '24 hour' AND DATE(task_run.finish_time) <= NOW() GROUP BY "user".id ORDER BY n_answers DESC LIMIT 5;''') results = session.execute(sql, dict(limit=5)) top5_users_24_hours = [] for row in results: user = dict(id=row.id, fullname=row.fullname, name=row.name, n_answers=row.n_answers) top5_users_24_hours.append(user) return top5_users_24_hours
agpl-3.0
feriasvivas/rbat
db/migrate/20160606183809_remove_alcohol_drugs_victim.rb
140
class RemoveAlcoholDrugsVictim < ActiveRecord::Migration def change remove_columns :victims, :effect_drugs, :effect_alcohol end end
agpl-3.0
videodromm/website
src/components/Github.js
218
import { Menu } from './Menu' export const Github = () => <div className="component"> <Menu /> <ul> <li><a target="_blank" href="https://github.com/videodromm">github</a></li> </ul> </div>
agpl-3.0
melmsie/Dank-Memer
src/commands/memeyCommands/surreal.js
281
const { GenericRedditCommand } = require('../../models') module.exports = new GenericRedditCommand({ triggers: ['surreal', 'surrealmemes'], description: 'I really do not understand these', endpoint: '/r/surrealmemes/top/.json?sort=top&t=week&limit=100', type: 'image' })
agpl-3.0
OCA/l10n-italy
l10n_it_fatturapa_in/__init__.py
62
from . import models from . import tests from . import wizard
agpl-3.0
oeoeaio/openfoodnetwork
app/controllers/user_confirmations_controller.rb
1522
class UserConfirmationsController < DeviseController include Spree::Core::ControllerHelpers::Auth # Needed for access to current_ability, so we can authorize! actions # GET /resource/confirmation/new def new build_resource({}) end # POST /resource/confirmation def create set_return_url if params.key? :return_url self.resource = resource_class.send_confirmation_instructions(resource_params) if is_navigational_format? if successfully_sent?(resource) set_flash_message(:success, :confirmation_sent) else set_flash_message(:error, :confirmation_not_sent) end end respond_with_navigational(resource){ redirect_to login_path } end # GET /resource/confirmation?confirmation_token=abcdef def show self.resource = resource_class.confirm_by_token(params[:confirmation_token]) respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource) } end protected def set_return_url session[:confirmation_return_url] = params[:return_url] end def after_confirmation_path_for(resource) result = if resource.errors.empty? 'confirmed' else 'not_confirmed' end if resource.reset_password_token.present? return spree.edit_spree_user_password_path(reset_password_token: resource.reset_password_token) end path = (session[:confirmation_return_url] || login_path).to_s path += path.include?('?') ? '&' : '?' path + "validation=#{result}" end end
agpl-3.0
lmdu/krait
src/widgets.py
81720
# -*- coding: utf-8 -*- import os import sys import csv import apsw import time import json import shutil import requests import platform from PySide2.QtCore import * from PySide2.QtGui import * #from PySide2.QtSql import * #from PySide2.QtWebEngineWidgets import * from PySide2.QtWidgets import * #from PySide2.QtPrintSupport import * #from PySide.QtCore import * #from PySide.QtGui import * #from PySide.QtWebKit import * from db import * from utils import * from detail import * from workers import * from config import * from motif import StandardMotif class SSRMainWindow(QMainWindow): def __init__(self): super(SSRMainWindow, self).__init__() self.setWindowTitle("Krait v%s" % VERSION) #self.setWindowIcon(QIcon('icons/logo.png')) self.setWindowIcon(QIcon(':/icons/logo.ico')) #stacked widget self.main_widget = QStackedWidget(self) self.setCentralWidget(self.main_widget) self.table = SSRTableView(self) self.createTableModel() #self.browser = QWebEngineView(self) #self.browser = BrowserWidget(self) #QWebSettings.globalSettings().setAttribute(QWebSettings.DeveloperExtrasEnabled, True); #self.browser = QTextBrowser(self) self.main_widget.addWidget(self.table) #self.main_widget.addWidget(self.browser) #search text input self.filter = SSRFilterInput(self) self.filter.returnPressed.connect(self.filterTable) #create fasta table #self.fasta_table = FastaTable() #status message self.status_message = None self.createActions() self.createMenus() self.createToolBars() self.createStatusBar() #connect to database self.db = Database() #opened project self.opened_project = None #annotation file self.annot_file = None #statistical results self.statis_result = None self.statis_outfile = None #changed rows in database self.changed_rows = 0 #read settings self.readSettings() #read home page #self.homepage() #Enable dragging and dropping onto the main window self.setAcceptDrops(True) self.show() def swichMainWidget(self, widget): if widget == 'table': self.exportTableAct.setEnabled(True) #self.exportStatsAct.setDisabled(True) self.main_widget.setCurrentIndex(0) if self.model.tableName() in ('ssr', 'issr', 'cssr', 'vntr'): self.exportFastaAct.setEnabled(True) self.exportGFFAct.setEnabled(True) else: self.exportFastaAct.setDisabled(True) self.exportGFFAct.setDisabled(True) else: self.exportTableAct.setDisabled(True) #self.exportStatsAct.setEnabled(True) self.main_widget.setCurrentIndex(1) self.exportFastaAct.setDisabled(True) self.exportGFFAct.setDisabled(True) #def homepage(self): #content = template_render('index.html') #self.browser.setHtml(content, QUrl("qrc:/")) #self.browser.load(QUrl('https://github.com/lmdu/krait')) def createTableModel(self): self.model = TableModel() self.table.setModel(self.model) self.model.row_col.connect(self.changeRowColCount) self.model.sel_row.connect(self.changeSelectCount) def readSettings(self): self.settings = QSettings(CONFIG_FILE, QSettings.IniFormat) if len(self.settings.allKeys()) == 0: dialog = PreferenceDialog(self, self.settings) dialog.saveSettings() self.resize(self.settings.value("size", QSize(1000, 600))) def writeSettings(self): if not self.isMaximized(): self.settings.setValue("size", self.size()) def closeEvent(self, event): self.writeSettings() if self.changed_rows == self.db.changes(): event.accept() return ret = QMessageBox.question(self, "Closing", "Would you like to save results before exiting", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel ) if ret == QMessageBox.Yes: self.saveProject() elif ret == QMessageBox.Cancel: event.ignore() elif ret == QMessageBox.No: event.accept() def dragEnterEvent(self, event): if event.mimeData().hasUrls(): event.accept() else: event.ignore() def dragMoveEvent(self, event): if event.mimeData().hasUrls(): event.accept() else: event.ignore() def dropEvent(self, event): if not event.mimeData().hasUrls(): return urls = event.mimeData().urls() if len(urls) > 1: return drag_file = urls[0].toLocalFile() if drag_file.endswith('.kdb'): self.openProject(drag_file) return for suffix in ['.fa', '.fna', '.fas', '.fasta', '.fa.gz', '.fna.gz', '.fas.gz', '.fasta.gz']: if drag_file.endswith(suffix) or drag_file.endswith(suffix.upper()): self.importFasta(drag_file) return warn_msg = ( "Please drag a project file with .kdb suffix to open project, or " "Drag a fasta formatted sequence file with .fa, .fna, .fas, .fasta, " ".fa.gz, .fna.gz, .fas.gz, .fasta.gz suffix to search repeats" ) QMessageBox.warning(self, "Input file format not right", warn_msg) def createActions(self): #open a project action self.openProjectAct = QAction(self.tr("Open Project"), self) self.openProjectAct.setShortcut(QKeySequence.Open) self.openProjectAct.triggered.connect(self.openProject) #close a project action self.closeProjectAct = QAction(self.tr("Close Project"), self) self.closeProjectAct.setShortcut(QKeySequence.Close) self.closeProjectAct.triggered.connect(self.closeProject) #save a project action self.saveProjectAct = QAction(self.tr("Save Project"), self) self.saveProjectAct.setShortcut(QKeySequence.Save) self.saveProjectAct.triggered.connect(self.saveProject) #save as a project action self.saveAsProjectAct = QAction(self.tr("Save Project As..."), self) self.saveAsProjectAct.setShortcut(QKeySequence.SaveAs) self.saveAsProjectAct.triggered.connect(self.saveProjectAs) #load fasta file or genome action self.loadFastaAct = QAction(self.tr("Import Fasta"), self) self.loadFastaAct.triggered.connect(self.importFasta) self.loadFastaAct.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_O)) #self.loadFastasAct = QAction(self.tr("Import Fastas in Folder"), self) #self.loadFastasAct.triggered.connect(self.importFastas) #export the Results self.exportWholeTableAct = QAction(self.tr("Export Whole Table"), self) self.exportWholeTableAct.triggered.connect(self.exportWholeTable) self.exportWholeTableAct.setDisabled(True) self.exportSelectedRowsAct = QAction(self.tr("Export Selected Rows"), self) self.exportSelectedRowsAct.triggered.connect(self.exportSelectedRows) self.exportSelectedRowsAct.setDisabled(True) self.exportTableAct = QAction(self.tr("Exprot Selected as Table"), self) self.exportTableAct.triggered.connect(self.exportTableRows) self.exportTableAct.setDisabled(True) self.exportTableAct.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_T)) self.exportFastaAct = QAction(self.tr("Export Selected as Fasta"), self) self.exportFastaAct.triggered.connect(self.exportTableFastas) self.exportFastaAct.setDisabled(True) self.exportGFFAct = QAction(self.tr("Export Selected as GFF"), self) self.exportGFFAct.triggered.connect(self.exportTableGFF) self.exportGFFAct.setDisabled(True) self.exportStatsAct = QAction(self.tr("Export Statistical Report"), self) self.exportStatsAct.setShortcut(QKeySequence(Qt.CTRL+Qt.Key_P)) #self.exportStatsAct.setDisabled(True) self.exportStatsAct.triggered.connect(self.exportStatisResult) #exit action self.exitAct = QAction(self.tr("Exit"), self) self.exitAct.setShortcut(QKeySequence.Quit) self.exitAct.triggered.connect(self.close) #copy action self.copyAct = QAction(self.tr("Copy"), self) self.copyAct.setShortcut(QKeySequence.Copy) self.copyAct.triggered.connect(self.doCopy) self.cutAct = QAction(self.tr("Cut"), self) self.cutAct.setShortcut(QKeySequence.Cut) self.cutAct.triggered.connect(self.doCut) self.pasteAct = QAction(self.tr("Paste"), self) self.pasteAct.setShortcut(QKeySequence.Paste) self.pasteAct.triggered.connect(self.doPaste) self.selectAllAct = QAction(self.tr("Select All"), self) self.selectAllAct.setShortcut(QKeySequence.SelectAll) self.selectAllAct.triggered.connect(self.doSelectAll) self.preferenceAct = QAction(self.tr("Preferences"), self) self.preferenceAct.setShortcut(QKeySequence.Preferences) self.preferenceAct.triggered.connect(self.setPreference) #toolbar actions #search perfect ssrs tool button self.SSRSearchAct = QAction(QIcon(":/icons/ssr.png"), self.tr("SSRs"), self) self.SSRSearchAct.setToolTip(self.tr("Search for Perfect SSRs")) self.SSRSearchAct.setStatusTip(self.tr("Search for Perfect Microsatellites")) self.SSRSearchAct.triggered.connect(self.searchOrShowSSR) self.SSRForceAct = QAction(self.tr("Redo Search for SSRs"), self) self.SSRForceAct.setShortcut(QKeySequence(Qt.CTRL+Qt.Key_1)) self.SSRForceAct.triggered.connect(self.searchSSR) self.SSRShowAct = QAction(self.tr("Show Perfect SSRs"), self) self.SSRShowAct.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_1)) self.SSRShowAct.triggered.connect(self.showSSR) self.SSRRemoveAct = QAction(self.tr("Remove Perfect SSRs"), self) self.SSRRemoveAct.triggered.connect(self.removeSSR) self.SSRSetAct = QAction(self.tr("Specify Minimum Repeats"), self) self.SSRSetAct.triggered.connect(self.setPreference) #search compound ssrs tool button self.CSSRSearchAct = QAction(QIcon(":/icons/cssr.png"), self.tr("cSSRs"), self) self.CSSRSearchAct.setToolTip(self.tr("Search for Compound SSRs")) self.CSSRSearchAct.setStatusTip(self.tr("Search for Compound Microsatellites")) self.CSSRSearchAct.triggered.connect(self.searchOrShowCSSR) self.CSSRForceAct = QAction(self.tr("Redo Search for cSSRs"), self) self.CSSRForceAct.setShortcut(QKeySequence(Qt.CTRL+Qt.Key_2)) self.CSSRForceAct.triggered.connect(self.searchCSSR) self.CSSRShowAct = QAction(self.tr("Show Compound SSRs"), self) self.CSSRShowAct.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_2)) self.CSSRShowAct.triggered.connect(self.showCSSR) self.CSSRRemoveAct = QAction(self.tr("Remove Compound SSRs"), self) self.CSSRRemoveAct.triggered.connect(self.removeCSSR) #self.bestDmaxAct = QAction(self.tr("Estimate best dMax"), self) #self.bestDmaxAct.triggered.connect(self.estimateBestMaxDistance) self.CSSRSetAct = QAction(self.tr("Specify Maximal Distance"), self) self.CSSRSetAct.triggered.connect(self.setPreference) #search VNTRs self.VNTRSearchAct = QAction(QIcon(":/icons/vntr.png"), self.tr("VNTRs"), self) self.VNTRSearchAct.setToolTip(self.tr("Search for Minisatellites or Macrosatellites")) self.VNTRSearchAct.setStatusTip(self.tr("Search for Minisatellites or Macrosatellites")) self.VNTRSearchAct.triggered.connect(self.searchOrShowVNTR) self.VNTRForceAct = QAction(self.tr("Redo Search for VNTRs"), self) self.VNTRForceAct.setShortcut(QKeySequence(Qt.CTRL+Qt.Key_4)) self.VNTRForceAct.triggered.connect(self.searchVNTR) self.VNTRShowAct = QAction(self.tr("Show VNTRs"), self) self.VNTRShowAct.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_4)) self.VNTRShowAct.triggered.connect(self.showVNTR) self.VNTRRemoveAct = QAction(self.tr("Remove VNTRs"), self) self.VNTRRemoveAct.triggered.connect(self.removeVNTR) self.VNTRSetAct = QAction(self.tr("Specify Search Parameters"), self) self.VNTRSetAct.triggered.connect(self.setPreference) #search imperfect microsatellites self.ISSRSearchAct = QAction(QIcon(":/icons/issr.png"), self.tr("iSSRs"), self) self.ISSRSearchAct.setToolTip(self.tr("Search for Imperfect SSRs")) self.ISSRSearchAct.setStatusTip(self.tr("Search for Imperfect Microsatellites")) self.ISSRSearchAct.triggered.connect(self.searchOrShowISSR) self.ISSRForceAct = QAction(self.tr("Redo Search for iSSRs"), self) self.ISSRForceAct.setShortcut(QKeySequence(Qt.CTRL+Qt.Key_3)) self.ISSRForceAct.triggered.connect(self.searchISSR) self.ISSRShowAct = QAction(self.tr("Show Imperfect SSRs"), self) self.ISSRShowAct.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_3)) self.ISSRShowAct.triggered.connect(self.showISSR) self.ISSRRemoveAct = QAction(self.tr("Remove Imperfect SSRs"), self) self.ISSRRemoveAct.triggered.connect(self.removeISSR) self.ISSRSetAct = QAction(self.tr("Specify Search Parameters"), self) self.ISSRSetAct.triggered.connect(self.setPreference) #locate ssrs self.locateAct = QAction(QIcon(":/icons/locate.png"), self.tr("Mapping"), self) self.locateAct.setToolTip(self.tr("Mapping tandem repeats to genic regions")) self.locateAct.setStatusTip(self.tr("Mapping tandem repeats to genic regions")) #self.locateAct.triggered.connect(self.LocateOrShowTandem) self.locateAct.triggered.connect(self.locateTandem) self.locateToolAct = QAction(self.tr("Redo Mapping"), self) self.locateToolAct.triggered.connect(self.locateTandem) #self.locateShowAct = QAction(self.tr("Show mapping reslult"), self) #self.locateShowAct.triggered.connect(self.showLocation) self.locateSetAct = QAction(self.tr("Import Annotation File"), self) self.locateSetAct.triggered.connect(self.provideAnnotation) self.removeLocateAct = QAction(self.tr("Remove mapping reslult"), self) self.removeLocateAct.triggered.connect(self.removeMarker) cds_icon = QPixmap(16, 16) cds_icon.fill(QColor(245, 183, 177)) self.showCDSAct = QAction(QIcon(cds_icon), self.tr("Show repeats in CDS"), self) self.showCDSAct.triggered.connect(self.showCDSMarker) exon_icon = QPixmap(16, 16) exon_icon.fill(QColor(169, 223, 191)) self.showExonAct = QAction(QIcon(exon_icon), self.tr("Show repeats in exon"), self) self.showExonAct.triggered.connect(self.showExonMarker) utr_icon = QPixmap(16, 16) utr_icon.fill(QColor(250, 215, 160)) self.showUTRAct = QAction(QIcon(utr_icon), self.tr("Show repeats in UTR"), self) self.showUTRAct.triggered.connect(self.showUTRMarker) intron_icon = QPixmap(16, 16) intron_icon.fill(QColor(174, 214, 241)) self.showIntronAct = QAction(QIcon(intron_icon), self.tr("Show repeats in intron"), self) self.showIntronAct.triggered.connect(self.showIntronMarker) #design primer self.primerDesignAct = QAction(QIcon(":/icons/primer.png"), self.tr("Primer"), self) self.primerDesignAct.setToolTip(self.tr("Design primers")) self.primerDesignAct.setStatusTip(self.tr("Start design primers")) self.primerDesignAct.triggered.connect(self.designOrShowPrimer) self.primerForceAct = QAction(self.tr("Redo Design Primers"), self) self.primerForceAct.triggered.connect(self.designPrimer) self.primerShowAct = QAction(self.tr("Show Designed Primer"), self) self.primerShowAct.triggered.connect(self.showPrimer) self.primerRemoveAct = QAction(self.tr("Remove Designed Primer"), self) self.primerRemoveAct.triggered.connect(self.removePrimer) self.primerSetAct = QAction(self.tr("Specify Primer3 Settings"), self) self.primerSetAct.triggered.connect(self.setPrimerSettings) #statistics report self.statisticsAct = QAction(QIcon(":/icons/report.png"), self.tr("Statistics"), self) self.statisticsAct.triggered.connect(self.exportStatisResult) #self.statisticsAct.triggered.connect(self.doOrShowStatistics) self.statisticsAct.setStatusTip(self.tr("Generate Statistical Report")) self.statisticsForceAct = QAction(self.tr("Refresh Statistical Analysis"), self) self.statisticsForceAct.triggered.connect(self.performStatistics) #self.statisticsShowAct = QAction(self.tr("Show Statistical Result"), self) #self.statisticsShowAct.triggered.connect(self.showStatistics) #self.statisticsRemoveAct = QAction(self.tr("Remove Statistical Result"), self) #self.statisticsRemoveAct.triggered.connect(self.removeStatistics) #tool action self.downloadNCBIAct = QAction(self.tr("Download sequence from NCBI"), self) self.downloadNCBIAct.triggered.connect(self.downloadFasta) #self.motifMappingAct = QAction(self.tr("Generate standard motif mapping"), self) #self.motifMappingAct.triggered.connect(self.generateMotifMapping) #about action self.aboutAct = QAction(self.tr("About Krait"), self) self.aboutAct.triggered.connect(self.openAboutMessage) #documentation action self.documentAct = QAction(self.tr("Documentation"), self) self.documentAct.setShortcut(QKeySequence.HelpContents) self.documentAct.triggered.connect(self.openDocumentation) #report issue action self.issueAct = QAction(self.tr("Report issue..."), self) self.issueAct.triggered.connect(self.reportIssue) #view input action self.showInputAct = QAction(self.tr("Show Input Files"), self) self.showInputAct.triggered.connect(self.showInputFastas) def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.editMenu = self.menuBar().addMenu("&Edit") self.searchMenu = self.menuBar().addMenu("&Search") self.viewMenu = self.menuBar().addMenu("&View") self.toolMenu = self.menuBar().addMenu("&Tool") self.helpMenu = self.menuBar().addMenu("&Help") self.fileMenu.addAction(self.openProjectAct) self.fileMenu.addAction(self.closeProjectAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.saveProjectAct) self.fileMenu.addAction(self.saveAsProjectAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.loadFastaAct) #self.fileMenu.addAction(self.loadFastasAct) self.fileMenu.addAction(self.locateSetAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exportWholeTableAct) self.fileMenu.addAction(self.exportSelectedRowsAct) #self.fileMenu.addAction(self.exportTableAct) #self.fileMenu.addAction(self.exportFastaAct) #self.fileMenu.addAction(self.exportGFFAct) self.fileMenu.addAction(self.exportStatsAct) self.fileMenu.addSeparator() self.fileMenu.addAction(self.exitAct) self.editMenu.addAction(self.copyAct) self.editMenu.addAction(self.cutAct) self.editMenu.addAction(self.pasteAct) self.editMenu.addSeparator() self.editMenu.addAction(self.selectAllAct) self.editMenu.addSeparator() self.editMenu.addAction(self.preferenceAct) self.searchMenu.addAction(self.SSRForceAct) self.searchMenu.addAction(self.CSSRForceAct) self.searchMenu.addAction(self.ISSRForceAct) self.searchMenu.addAction(self.VNTRForceAct) self.viewMenu.addAction(self.showInputAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.SSRShowAct) self.viewMenu.addAction(self.CSSRShowAct) self.viewMenu.addAction(self.ISSRShowAct) self.viewMenu.addAction(self.VNTRShowAct) self.viewMenu.addSeparator() self.viewMenu.addAction(self.SSRRemoveAct) self.viewMenu.addAction(self.CSSRRemoveAct) self.viewMenu.addAction(self.ISSRRemoveAct) self.viewMenu.addAction(self.VNTRRemoveAct) #self.toolMenu.addAction(self.bestDmaxAct) self.toolMenu.addAction(self.primerForceAct) self.toolMenu.addAction(self.locateToolAct) #self.toolMenu.addAction(self.statisticsForceAct) self.toolMenu.addSeparator() self.toolMenu.addAction(self.downloadNCBIAct) #self.toolMenu.addSeparator() #self.toolMenu.addAction(self.motifMappingAct) self.helpMenu.addAction(self.documentAct) self.helpMenu.addAction(self.issueAct) self.helpMenu.addSeparator() self.helpMenu.addAction(self.aboutAct) #tool bar menus #search ssrs tool button menu self.SSRMenu = QMenu() self.SSRMenu.addAction(self.SSRForceAct) self.SSRMenu.addAction(self.SSRShowAct) self.SSRMenu.addSeparator() self.SSRMenu.addAction(self.SSRRemoveAct) self.SSRMenu.addSeparator() self.SSRMenu.addAction(self.loadFastaAct) #self.SSRMenu.addAction(self.loadFastasAct) self.SSRMenu.addSeparator() self.SSRMenu.addAction(self.SSRSetAct) self.CSSRMenu = QMenu() self.CSSRMenu.addAction(self.CSSRForceAct) self.CSSRMenu.addAction(self.CSSRShowAct) self.CSSRMenu.addSeparator() self.CSSRMenu.addAction(self.CSSRRemoveAct) self.CSSRMenu.addSeparator() #self.CSSRMenu.addAction(self.bestDmaxAct) self.CSSRMenu.addAction(self.CSSRSetAct) self.VNTRMenu = QMenu() self.VNTRMenu.addAction(self.VNTRForceAct) self.VNTRMenu.addAction(self.VNTRShowAct) self.VNTRMenu.addSeparator() self.VNTRMenu.addAction(self.VNTRRemoveAct) self.VNTRMenu.addSeparator() self.VNTRMenu.addAction(self.VNTRSetAct) self.ISSRMenu = QMenu() self.ISSRMenu.addAction(self.ISSRForceAct) self.ISSRMenu.addAction(self.ISSRShowAct) self.ISSRMenu.addSeparator() self.ISSRMenu.addAction(self.ISSRRemoveAct) self.ISSRMenu.addSeparator() self.ISSRMenu.addAction(self.ISSRSetAct) self.locateMenu = QMenu() self.locateMenu.addAction(self.locateSetAct) self.locateMenu.addAction(self.locateToolAct) #self.locateMenu.addAction(self.locateShowAct) self.locateMenu.addSeparator() self.locateMenu.addAction(self.removeLocateAct) self.locateMenu.addSeparator() self.locateMenu.addAction(self.showCDSAct) self.locateMenu.addAction(self.showExonAct) self.locateMenu.addAction(self.showUTRAct) self.locateMenu.addAction(self.showIntronAct) self.primerMenu = QMenu() self.primerMenu.addAction(self.primerForceAct) self.primerMenu.addAction(self.primerShowAct) self.primerMenu.addSeparator() self.primerMenu.addAction(self.primerRemoveAct) self.primerMenu.addSeparator() self.primerMenu.addAction(self.primerSetAct) self.statisticsMenu = QMenu() self.statisticsMenu.addAction(self.statisticsForceAct) #self.statisticsMenu.addAction(self.statisticsShowAct) #self.statisticsMenu.addSeparator() #self.statisticsMenu.addAction(self.statisticsRemoveAct) self.statisticsMenu.addAction(self.exportStatsAct) def createToolBars(self): self.toolBar = self.addToolBar('') self.toolBar.setMovable(False) self.toolBar.setIconSize(QSize(36, 36)) self.toolBar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) #search ssr action and menus self.SSRSearchAct.setMenu(self.SSRMenu) self.toolBar.addAction(self.SSRSearchAct) self.CSSRSearchAct.setMenu(self.CSSRMenu) self.toolBar.addAction(self.CSSRSearchAct) self.ISSRSearchAct.setMenu(self.ISSRMenu) self.toolBar.addAction(self.ISSRSearchAct) self.VNTRSearchAct.setMenu(self.VNTRMenu) self.toolBar.addAction(self.VNTRSearchAct) self.locateAct.setMenu(self.locateMenu) self.toolBar.addAction(self.locateAct) self.primerDesignAct.setMenu(self.primerMenu) self.toolBar.addAction(self.primerDesignAct) self.statisticsAct.setMenu(self.statisticsMenu) self.toolBar.addAction(self.statisticsAct) #self.reportToolBtn.setDisabled(True) #search input #self.filter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.toolBar.addWidget(self.filter) def createStatusBar(self): self.statusBar = self.statusBar() self.statusBar.messageChanged.connect(self.resetStatusMessage) #self.statusBar.showMessage("Genome-wide microsatellites analysis tool.") self.setStatusMessage("Genome-wide microsatellites analysis tool.") #add row and column counts widget self.rowCounts = QLabel("Row: 0", self) self.rowCounts.setStyleSheet("margin-right:10px;") self.statusBar.addPermanentWidget(self.rowCounts) self.colCounts = QLabel("Column: 0", self) self.colCounts.setStyleSheet("margin-right:10px;") self.statusBar.addPermanentWidget(self.colCounts) self.selectCounts = QLabel("Select: 0", self) self.selectCounts.setStyleSheet("margin-right:10px;") self.statusBar.addPermanentWidget(self.selectCounts) #add progressing bar self.progressBar = QProgressBar(self) self.progressBar.setMaximum(100) self.progressBar.setMinimum(0) self.statusBar.addPermanentWidget(self.progressBar) def showInputFastas(self, event): inputs = [] if self.opened_project: inputs.append("<b>Input project:</b><p>{}</p>".format(self.opened_project)) if self.annot_file: inputs.append("<b>Input annotation:</b><p>{}</p>".format(self.annot_file)) fastas = self.db.get_all("SELECT * FROM fasta") if fastas: inputs.append("<b>Input Fastas:</b>") for fasta in fastas: inputs.append("<p>{}</p>".format(fasta[1])) if not inputs: QMessageBox.information(self, "Input files", "No input file found, import fasta file for analysis") else: QMessageBox.information(self, "Input files", "".join(inputs)) def openProject(self, dbfile=None): if not dbfile: dbfile, _ = QFileDialog.getOpenFileName(self, filter="Krait Database (*.kdb)") if not dbfile: return self.opened_project = dbfile self.db.drop_tables() self.db.open(dbfile) if not self.db.is_empty('ssr'): self.showSSR() elif not self.db.is_empty('cssr'): self.showCSSR() elif not self.db.is_empty('issr'): self.showISSR() elif not self.db.is_empty('vntr'): self.showVNTR() self.setStatusMessage("%s has been successfully opened" % dbfile) def saveProject(self): if self.opened_project and not self.db.changes(): return if self.opened_project is None: dbfile, _ = QFileDialog.getSaveFileName(self, filter="Krait Database (*.kdb)") if not dbfile: return self.opened_project = dbfile self.db.save(self.opened_project) worker = SaveProjectWorker(self.opened_project) self.executeTask(worker, lambda: 1) self.changed_rows = self.db.changes() def saveProjectAs(self): dbfile, _ = QFileDialog.getSaveFileName(self, filter="Krait Database (*.kdb)") if not dbfile: return self.changed_rows = self.db.changes() worker = SaveProjectWorker(dbfile) self.executeTask(worker, lambda: 1) self.opened_project = dbfile def closeProject(self): if self.changed_rows != self.db.changes(): ret = QMessageBox.question(self, "Closing", "Would you like to save results before exiting", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel ) if ret == QMessageBox.Cancel: return if ret == QMessageBox.Yes: self.saveProject() self.db.drop_tables() self.createTableModel() #self.browser.setHtml('') self.changed_rows = self.db.changes() def importFasta(self, fasta=None): ''' Import a fasta file from a directory ''' if not self.db.is_empty('fasta'): ret = QMessageBox.warning(self, "Closing", "Are you sure you want to import new fasta file?<br>This will remove the previously imported fasta file.", QMessageBox.Yes | QMessageBox.No ) if ret == QMessageBox.No: return if not fasta: fasta, _ = QFileDialog.getOpenFileName(self, filter="Fasta (*.fa *.fna *.fas *.fasta *.fna.gz *.fa.gz *.fasta.gz);;All files (*.*)") if not fasta: return tables = ['ssr', 'cssr', 'issr', 'vntr', 'fasta', 'seq', 'option', 'meta', 'primer', 'primer_meta', 'gene', 'location'] for tb in tables: self.db.clear(tb) self.model.clear() self.db.get_cursor().execute('INSERT INTO fasta VALUES (?,?)', (None, fasta)) self.setStatusMessage("Import fasta %s" % fasta) """ def importFastas(self): ''' import all fasta files from a directory ''' if not self.db.is_empty('fasta'): ret = QMessageBox.warning(self, "Closing", "Are you sure you want to import new fasta file?<br>This will remove the previously imported fasta file.", QMessageBox.Yes | QMessageBox.No ) if ret == QMessageBox.No: return directory = QFileDialog.getExistingDirectory(self) if not directory: return folder = QDir(directory) fastas = folder.entryList(QDir.Files) if not fastas: return tables = ['ssr', 'cssr', 'issr', 'vntr', 'fasta', 'seq', 'option', 'meta', 'primer', 'primer_meta', 'gene', 'location'] for tb in tables: self.db.clear(tb) self.model.clear() count = 0 for fasta in fastas: count += 1 self.db.get_cursor().execute("INSERT INTO fasta VALUES (?,?)", (None, folder.absoluteFilePath(fasta))) self.setStatusMessage("Import %s fastas in %s" % (count, directory)) """ def downloadFasta(self): ''' download fasta file from NCBI database ''' dialog = DownloadDialog(self) status = dialog.exec_() if not status: return acc, out = dialog.get() if not acc or not out: return self.progressBar.setMaximum(0) worker = EutilWorker(acc, out) self.executeTask(worker, lambda: self.progressBar.setMaximum(100)) """ def generateMotifMapping(self): ''' generate standard motif mapping matrix ''' levels = ["1", "2", "3", "4"] level, ok = QInputDialog.getItem(self, "Standard level", "Level:", levels, 0, False) if not ok: return outfile, _ = QFileDialog.getSaveFileName(self, filter="CSV (*.csv)") if not outfile: return StandardMotif(int(level)).generate_matrix(outfile) QMessageBox.information(self, "Information", "Successfully exported to %s" % outfile) """ def exportTable(self, selected): suffix = ['Tabular (*.tsv)', 'CSV (*.csv)'] if self.main_widget.currentWidget() == self.table: if self.model.tableName() in ('ssr', 'issr', 'cssr', 'vntr'): suffix.append('Fasta (*.fa);;GFF3 (*.gff)') suffix.append('TXT (*.txt)') outfile, _ = QFileDialog.getSaveFileName(self, filter=";;".join(suffix)) if not outfile: return if self.model.tableName() == 'primer': worker = ExportPrimerWorker(selected, self.model, outfile) elif self.model.tableName() == 'feature': worker = ExportFeatureWorker(selected, self.model, outfile) elif outfile.endswith('.fa'): flank = int(self.settings.value('ssr/flank', 100)) worker = ExportFastaWorker(selected, self.model, flank, outfile) else: worker = ExportTableWorker(selected, self.model, outfile) #worker.process() self.executeTask(worker, lambda: QMessageBox.information(self, "Export Successed", "Successfully exported to {}".format(outfile)) ) def exportWholeTable(self): self.exportTable('whole') def exportSelectedRows(self): if not self.model.selected: return QMessageBox.warning(self, 'Warning', "No rows in table have been selected to export.") self.exportTable('selecte') def exportTableRows(self): #selected = self.model.getSelectedRows() if not self.model.selected: return QMessageBox.warning(self, 'Warning', "Please select rows in table to export.") exp_file, _ = QFileDialog.getSaveFileName(self, filter="CSV (*.csv);;Tabular text (*.txt)") if not exp_file: return worker = ExportTableWorker(self.model, exp_file) self.executeTask(worker, lambda: QMessageBox.information(self, "Information", "Successfully exported to %s" % exp_file) ) def exportTableGFF(self): if not self.model.selected: return QMessageBox.warning(self, 'Warning', "Please select rows in table to export.") exp_file, _ = QFileDialog.getSaveFileName(self, filter="GFF3 (*.gff)") if not exp_file: return worker = ExportTableWorker(self.model, exp_file) self.executeTask(worker, lambda: QMessageBox.information(self, "Information", "Successfully exported to %s" % exp_file) ) def exportTableFastas(self): if not self.model.selected: return QMessageBox.warning(self, 'Warning', "Please select rows in table to export.") #if table not in ('ssr', 'issr', 'cssr', 'vntr'): # return QMessageBox.warning(self, 'Warning', "Your selected rows are not SSRs") exp_file, _ = QFileDialog.getSaveFileName(self, filter="Fasta (*.fa);;Fasta (*.fasta)") if not exp_file: return flank = int(self.settings.value('ssr/flank', 100)) worker = ExportFastaWorker(self.model, flank, exp_file) self.executeTask(worker, lambda: QMessageBox.information(self, "Information", "Successfully exported to %s" % exp_file) ) def exportStatisResult(self): htmlfile, _ = QFileDialog.getSaveFileName(self, filter="HTML Report (*.html)") if not htmlfile: return self.statis_outfile = htmlfile if not self.statis_result: self.performStatistics() else: self.showStatistics() def doCopy(self): focus = QApplication.focusWidget() if focus == 0: return QApplication.postEvent(focus, QKeyEvent(QEvent.KeyPress, Qt.Key_C, Qt.ControlModifier)) QApplication.postEvent(focus, QKeyEvent(QEvent.KeyRelease, Qt.Key_C, Qt.ControlModifier)) def doCut(self): focus = QApplication.focusWidget() if focus == 0: return QApplication.postEvent(focus, QKeyEvent(QEvent.KeyPress, Qt.Key_X, Qt.ControlModifier)) QApplication.postEvent(focus, QKeyEvent(QEvent.KeyRelease, Qt.Key_X, Qt.ControlModifier)) def doPaste(self): focus = QApplication.focusWidget() if focus == 0: return QApplication.postEvent(focus, QKeyEvent(QEvent.KeyPress, Qt.Key_V, Qt.ControlModifier)) QApplication.postEvent(focus, QKeyEvent(QEvent.KeyRelease, Qt.Key_V, Qt.ControlModifier)) def doSelectAll(self): focus = QApplication.focusWidget() if focus == 0: return QApplication.postEvent(focus, QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.ControlModifier)) QApplication.postEvent(focus, QKeyEvent(QEvent.KeyRelease, Qt.Key_A, Qt.ControlModifier)) def setPreference(self): dialog = PreferenceDialog(self, self.settings) if dialog.exec_() == QDialog.Accepted: dialog.saveSettings() def setPrimerSettings(self): dialog = PreferenceDialog(self, self.settings) dialog.gotoPrimer() if dialog.exec_() == QDialog.Accepted: dialog.saveSettings() def executeTask(self, worker, finish_callback): #check the running task if hasattr(self, 'work_thread') and self.work_thread.isRunning(): return QMessageBox.warning(self, "Warning", "Task is running! Please wait until finished.") self.worker = worker self.worker.update_message.connect(self.setStatusMessage) self.worker.update_progress.connect(self.setProgress) self.worker.error_message.connect(lambda x: QMessageBox.critical(self, 'Error', x)) self.worker.finished.connect(finish_callback) self.work_thread = QThread() self.work_thread.started.connect(self.worker.run) self.worker.finished.connect(self.work_thread.quit) self.worker.finished.connect(self.worker.deleteLater) self.worker.failed.connect(self.work_thread.quit) self.worker.failed.connect(self.worker.deleteLater) self.worker.moveToThread(self.work_thread) self.work_thread.start() def getInputFastas(self): ''' get all fasta files with path provided by user ''' if self.db.is_empty('fasta'): QMessageBox.critical(self, "Error occurred", "No fasta file imported. Please import fasta files.") return None else: return self.db.get_all("SELECT * FROM fasta") #handle perfect SSRs search def searchSSR(self): fastas = self.getInputFastas() if not fastas: return self.removeSSR() rules = [ int(self.settings.value('ssr/mono', 12)), int(self.settings.value('ssr/di', 7)), int(self.settings.value('ssr/tri', 5)), int(self.settings.value('ssr/tetra', 4)), int(self.settings.value('ssr/penta', 4)), int(self.settings.value('ssr/hexa', 4)) ] level = int(self.settings.value('ssr/level', 3)) worker = SSRWorker(fastas, rules, level) self.executeTask(worker, self.showSSR) def searchOrShowSSR(self): if self.db.is_empty('ssr'): self.searchSSR() else: self.showSSR() def showSSR(self): self.model.setTable('ssr') self.model.select() self.swichMainWidget('table') def removeSSR(self): self.model.remove('ssr') #handle compound SSRs search def searchCSSR(self): if self.db.is_empty('ssr'): QMessageBox.warning(self, "Warning", "Please search perfect SSRs first, before search compound SSRs.") return self.removeCSSR() dmax = int(self.settings.value('ssr/dmax', 10)) worker = CSSRWorker(dmax) self.executeTask(worker, self.showCSSR) def searchOrShowCSSR(self): if self.db.is_empty('cssr'): self.searchCSSR() else: self.showCSSR() def showCSSR(self): self.model.setTable('cssr') self.model.select() self.swichMainWidget('table') def removeCSSR(self): self.model.remove('cssr') #handle VNTRs search def searchVNTR(self): fastas = self.getInputFastas() if not fastas: return self.removeVNTR() min_motif = int(self.settings.value('ssr/vmin', 7)) max_motif = int(self.settings.value('ssr/vmax', 30)) min_repeat = int(self.settings.value('ssr/vrep', 2)) worker = VNTRWorker(fastas, min_motif, max_motif, min_repeat) self.executeTask(worker, self.showVNTR) def searchOrShowVNTR(self): if self.db.is_empty('vntr'): self.searchVNTR() else: self.showVNTR() def showVNTR(self): self.model.setTable('vntr') self.model.select() self.swichMainWidget('table') def removeVNTR(self): self.model.remove('vntr') #handle imperfect SSRs search def searchISSR(self): fastas = self.getInputFastas() if not fastas: return self.removeISSR() seed_repeat = int(self.settings.value('ssr/srep', 3)) seed_length = int(self.settings.value('ssr/slen', 8)) max_eidts = int(self.settings.value('ssr/error', 2)) mis_penalty = int(self.settings.value('ssr/mismatch', 1)) gap_penalty = int(self.settings.value('ssr/gap', 2)) score = int(self.settings.value('ssr/score', 12)) level = int(self.settings.value('ssr/level', 3)) worker = ISSRWorker(fastas, seed_repeat, seed_length, max_eidts, mis_penalty, gap_penalty, score, level) self.executeTask(worker, self.showISSR) def searchOrShowISSR(self): if self.db.is_empty('issr'): self.searchISSR() else: self.showISSR() def showISSR(self): self.model.setTable('issr') self.model.select() self.swichMainWidget('table') def removeISSR(self): self.model.remove('issr') def getPrimerSettings(self): p3_settings = dict( PRIMER_TASK = 'generic', PRIMER_PICK_LEFT_PRIMER = 1, PRIMER_PICK_INTERNAL_OLIGO = 0, PRIMER_PICK_RIGHT_PRIMER = 1 ) repeat_library = ['', os.path.join(PRIMER3_CONFIG, 'humrep_and_simple.txt'), os.path.join(PRIMER3_CONFIG, 'rodent_ref.txt'), os.path.join(PRIMER3_CONFIG, 'rodrep_and_simple.txt'), os.path.join(PRIMER3_CONFIG, 'drosophila.w.transposons.txt') ] self.settings.beginGroup("primer") keys = self.settings.childKeys() for key in keys: if key == 'PRIMER_PRODUCT_SIZE_RANGE': sgs = self.settings.value(key) p3_settings[key] = [list(map(int, sg.split('-'))) for sg in sgs.split()] else: p3_settings[key] = int(self.settings.value(key)) self.settings.endGroup() p3_settings['PRIMER_MISPRIMING_LIBRARY'] = repeat_library[p3_settings['PRIMER_MISPRIMING_LIBRARY']] return p3_settings #design primers for ssrs def designPrimer(self): if not self.model.selected: return QMessageBox.warning(self, "Warning", "Please select tandem repeat makers") flank = int(self.settings.value('ssr/flank')) primer3_settings = self.getPrimerSettings() worker = PrimerWorker(self.model, flank, primer3_settings) self.removePrimer() #worker.process() #self.showPrimer() self.executeTask(worker, self.showPrimer) def designOrShowPrimer(self): if self.db.is_empty('primer'): self.designPrimer() else: self.showPrimer() def showPrimer(self): self.model.setTable('primer') self.model.select() self.swichMainWidget('table') def removePrimer(self): self.model.remove('primer') def provideAnnotation(self): #dialog = AnnotationDialog(self, self.annot_file) #dialog.exec_() #self.annot_file = dialog.get() filters = "GFF or GTF (*.gtf *.gtf.gz *.gff *.gff3 *.gff.gz *.gff3.gz);;ALL (*.*)" annot_file, _ = QFileDialog.getOpenFileName(self, "GFF or GTF annotation file", filter=filters) if not annot_file: return self.annot_file = annot_file self.setStatusMessage("Import annotation file %s" % self.annot_file) #def LocateOrShowTandem(self): # if self.db.is_empty('feature'): # self.locateTandem() # else: # self.showLocation() def locateTandem(self): if not self.annot_file: return QMessageBox.warning(self, "Warning", "Please provide gtf or gff well formated annotation file") table = self.model.table if not table: return QMessageBox.warning(self, "Warning", "You have not yet detected SSRs") if table not in ['ssr', 'issr', 'cssr', 'vntr']: return QMessageBox.warning(self, "Warning", "No SSRs displayed") if self.db.is_empty(table): return QMessageBox.warning(self, "warning", "No SSRs in table") worker = LocateWorker(table, self.annot_file) #worker.process() #self.showLocation() self.executeTask(worker, self.showLocation) def showLocation(self): # self.model.setTable('feature') # self.model.select() # self.swichMainWidget('table') self.model.beginResetModel() self.model.endResetModel() def removeMarker(self): self.model.remove('location') def showMarker(self, marker): repeat_types = {'ssr': 1, 'cssr': 2, 'issr': 3, 'vntr': 4} feature_maps = {'CDS': 1, 'exon': 2, 'UTR': 3, 'intron': 4} table = self.model.table if table not in repeat_types: return QMessageBox.warning(self, 'Warning', "No tandem repeats displayed") #if not table or table == 'primer': # return if feature_maps[marker] == 3: sql = "SELECT target FROM location WHERE reptype={} AND (feature=3 OR feature=5)".format(repeat_types[table]) else: sql = "SELECT target FROM location WHERE reptype={} AND feature={}".format(repeat_types[table], feature_maps[marker]) #data = self.db.get_column(sql) #if not data: # return QMessageBox.warning(self, "Warning", "No %ss located in %s region" % (table.upper(), marker)) self.model.setFilter('id IN (%s)' % sql) def showCDSMarker(self): self.showMarker('CDS') def showExonMarker(self): self.showMarker('exon') def showUTRMarker(self): self.showMarker('UTR') def showIntronMarker(self): self.showMarker('intron') def filterTable(self): filters = str(self.filter.text()) if 'table=' in filters: self.model.setTable(filters.split('=')[1]) self.model.select() return sqlwhere = format_sql_where(filters) self.model.setFilter(sqlwhere) def performStatistics(self): if self.db.is_empty('fasta'): return QMessageBox.warning(self, "Warning", "No fasta file inputted") worker = StatisWorker() #worker.process() self.progressBar.setMaximum(0) self.executeTask(worker, self.showStatistics) #def doOrShowStatistics(self): # if self.statis_result: # self.swichMainWidget('browser') # self.browser.setHtml(self.statis_result, QUrl("qrc:/")) # else: # self.performStatistics() def showStatistics(self): seq_statis = None ssr_statis = None issr_statis = None cssr_statis = None vntr_statis = None opt = self.db.get_option('seq_statis') if opt is not None: seq_statis = json.loads(opt) opt = self.db.get_option('ssr_statis') if opt is not None: ssr_statis = json.loads(opt) opt = self.db.get_option('issr_statis') if opt is not None: issr_statis = json.loads(opt) opt = self.db.get_option('cssr_statis') if opt is not None: cssr_statis = json.loads(opt) opt = self.db.get_option('vntr_statis') if opt is not None: vntr_statis = json.loads(opt) self.statis_result = template_render('report.html', seq = seq_statis, ssr = ssr_statis, issr = issr_statis, cssr = cssr_statis, vntr = vntr_statis ) with open(self.statis_outfile, 'w', encoding='utf-8') as fw: fw.write(self.statis_result) self.progressBar.setMaximum(100) QDesktopServices.openUrl(QUrl("file:///{}".format(self.statis_outfile), QUrl.TolerantMode)) self.setStatusMessage("Statistical report was successfully save to %s" % self.statis_outfile) def removeStatistics(self): if self.statis_result: self.statis_result = None #self.browser.setHtml('') def changeRowColCount(self, count): #self.table.setColumnWidth(0, 30) self.table.resizeColumnToContents(0) #self.table.horizontalHeader().setSortIndicator(1, Qt.AscendingOrder) #self.table.resizeColumnsToContents() labels = {'ssr':'SSRs', 'vntr':'VNTRs', 'cssr':'cSSRs', 'issr':'iSSRs', 'primer':'Primers'} label = labels.get(count[0], 'Row') self.rowCounts.setText("%s: %s" % (label, count[1])) self.colCounts.setText("Column: %s" % count[2]) if count[1] > 0: self.exportWholeTableAct.setDisabled(False) def changeSelectCount(self, count): self.selectCounts.setText("Select: {}".format(count)) if count > 0: self.exportSelectedRowsAct.setDisabled(False) else: self.exportSelectedRowsAct.setDisabled(True) def setProgress(self, percent): self.progressBar.setValue(percent) def setStatusMessage(self, msg): self.status_message = msg self.statusBar.showMessage(msg) def resetStatusMessage(self, msg): if not msg: self.statusBar.showMessage(self.status_message) def openAboutMessage(self): #system_info = "%s%s %s" % (platform.system(), platform.release(), platform.architecture()[0]) #python_info = sys.version.split()[0] about_message = """ <p><b>Krait - Microsatellite Identification and Primer Design</b></p> <p>Version v{version} Build {build}<p> <p>Krait is a robust and ultrafast tool that provides a user-friendly GUI for no computationally skilled biologists to extract perfect, imperfect and compound microsatellites and VNTRs from fasta formatted DNA sequences; and design primers; and perform statistical analysis.</p> <p><b>Acknowledgements:</b><br><a href="https://wiki.qt.io/Qt_for_Python">PySide2</a> for rendering GUI. <a href="https://github.com/lmdu/pyfastx">pyfastx</a> for parsing fasta. <a href="https://github.com/libnano/primer3-py">primer3-py</a> and <a href="http://primer3.sourceforge.net/">primer3</a> for primer design. <a href="https://github.com/hunt-genes/ncls">NCLS</a> for mapping SSRs. <a href="https://plotly.com/javascript/">plotly.js</a> for plotting. <a href="https://datatables.net/">DataTables</a> for statistical tables. <a href="https://jinja.palletsprojects.com/">jinja2</a> for generating statistical report. <a href="https://github.com/rogerbinns/apsw">apsw</a> for storing data. </p> <p><b>Citation:</b><br>Du L, Zhang C, Liu Q, Zhang X, Yue B (2018) Krait: an ultrafast tool for genome-wide survey of microsatellites and primer design. Bioinformatics. 34(4):681-683.</p> <p><b>Contact:</b><br>dulianming@cdu.edu.cn</p> """.format(version=VERSION, build=BUILD) QMessageBox.about(self, "About Krait", about_message) def openDocumentation(self): QDesktopServices.openUrl(QUrl("https://krait.biosv.com")) def reportIssue(self): QDesktopServices.openUrl(QUrl("https://github.com/lmdu/krait/issues")) class SSRFilterInput(QLineEdit): def __init__(self, parent=None): super(SSRFilterInput, self).__init__(parent) self.setPlaceholderText("Filter data in table e.g. motif=AT and repeat>10") #class SSRWebView(QWebView): # def __init__(self, parent=None): # super(SSRWebView, self).__init__(parent) # self.load(QUrl('http://www.baidu.com')) # self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) # self.linkClicked.connect(self.openUrl) # def openUrl(self, url): # QDesktopServices.openUrl(url) class SSRTableView(QTableView): def __init__(self, parent=None): super(SSRTableView, self).__init__(parent) self.parent = parent self.verticalHeader().hide() self.horizontalHeader().setHighlightSections(False) self.horizontalHeader().setStretchLastSection(True) #self.horizontalHeader().setDefaultSectionSize(150) self.setEditTriggers(QAbstractItemView.NoEditTriggers) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.SingleSelection) #self.setSelectionMode(QAbstractItemView.MultiSelection) self.setSortingEnabled(True) self.checkbox = QCheckBox(self.horizontalHeader()) self.checkbox.setGeometry(QRect(3,5,20,20)) self.checkbox.stateChanged.connect(self.checkboxAction) self.clicked.connect(self.showCellContent) def showCellContent(self, index): msg = self.model().data(index) self.parent.setStatusMessage(str(msg)) def contextMenuEvent(self, event): self.current_row = self.rowAt(event.pos().y()) if self.current_row == -1: return self.menu = QMenu(self) select_action = QAction('Select', self) select_action.triggered.connect(self.selectCurrentRow) deselect_action = QAction("Deselect", self) deselect_action.triggered.connect(self.deselectCurrentRow) select_all_action = QAction("Select All", self) select_all_action.setShortcut(QKeySequence(Qt.CTRL+Qt.Key_A)) select_all_action.triggered.connect(self.selectAll) deselect_all_action = QAction("Deselect All", self) deselect_all_action.setShortcut(QKeySequence(Qt.CTRL+Qt.SHIFT+Qt.Key_A)) deselect_all_action.triggered.connect(self.deselectAll) #delete_action = QAction("Delete All", self) detail_action = QAction("View Sequence", self) detail_action.triggered.connect(self.viewDetail) self.menu.addAction(select_action) self.menu.addAction(deselect_action) self.menu.addAction(select_all_action) self.menu.addAction(deselect_all_action) #self.menu.addSeparator() #self.menu.addAction(delete_action) self.menu.addSeparator() self.menu.addAction(detail_action) self.menu.popup(QCursor.pos()) def checkboxAction(self, state): if state > 0: self.selectAll() else: self.deselectAll() def selectCurrentRow(self): self.model().selectRow(self.current_row) def deselectCurrentRow(self): self.model().deselectRow(self.current_row) def selectAll(self): self.model().selectAll() def deselectAll(self): self.model().deselectAll() def viewDetail(self): ''' view sequence and detail information of tandem repeats ''' table = self.model().table flank = int(self.parent.settings.value('ssr/flank', 50)) seed_repeat = int(self.parent.settings.value('ssr/srep', 3)) seed_minlen = int(self.parent.settings.value('ssr/slen', 8)) max_error = int(self.parent.settings.value('ssr/error', 3)) _id = self.model().getCellId(self.current_row) if table == 'primer': content = PrimerDetail(table, _id, flank).generateHtml() elif table == 'issr': content = ISSRSeqDetail(table, _id, flank, seed_repeat, seed_minlen, max_error).generateHtml() else: content = SequenceDetail(table, _id, flank).generateHtml() dialog=SSRDetailDialog(self.parent, "%s Sequence" % table.upper(), content) dialog.exec_() class TableModel(QAbstractTableModel): row_col = Signal(tuple) sel_row = Signal(int) def __init__(self, parent=None): super(TableModel, self).__init__(parent) self.headers = [] #store ids of selected row self.selected = set() #store ids of displayed row self.displayed = [] self.total_row_counts = 0 self.readed_row_counts = 0 #connect to database self.db = Database() #["Select", "Where", "Order"] self.query = ['', '', ''] #table name self.table = None #cache row (index, data) self.cached_row = [-1, None] #mapping self.repeat_types = {'ssr': 1, 'cssr': 2, 'issr': 3, 'vntr': 4} def getRowCounts(self): return self.total_row_counts def getColCounts(self): return len(self.headers) def getAllItems(self): return self.total_row_counts def selectRow(self, row): if row not in self.selected: self.beginResetModel() self.selected.add(self.getCellId(row)) self.endResetModel() self.sel_row.emit(len(self.selected)) def deselectRow(self, row): if row in self.selected: self.beginResetModel() self.selected.remove(self.getCellId(row)) self.endResetModel() self.sel_row.emit(len(self.selected)) def selectAll(self): self.beginResetModel() sql = self.query[0] % 'COUNT(1)' + ' ' + self.query[1] if self.query[1]: self.selected = set(self.db.get_column(self.sql % 'id')) else: self.selected = set(range(1, self.total_row_counts+1)) #if self.db.get_one(sql) == self.total_row_counts: #self.selected = set(range(self.total_row_counts)) #else: #self.selected = set(range(len(self.displayed))) self.endResetModel() self.sel_row.emit(len(self.selected)) def deselectAll(self): self.beginResetModel() self.selected = set() self.endResetModel() self.sel_row.emit(0) def setTable(self, table): self.table = table self.repeat_type = self.repeat_types.get(self.table, 0) self.headers = self.db.get_fields(self.table) or [] self.query = ["SELECT %s FROM {0}".format(self.table), '', ''] def tableName(self): return self.table def columnNames(self): return self.headers def setFilter(self, condition=None): if condition: self.query[1] = "WHERE %s" % condition self.select() else: self.query[1] = '' self.select() def sort(self, column, order): if column == 0: return colname = self.headers[column-1] if order == Qt.SortOrder.DescendingOrder: self.query[2] = "ORDER BY %s DESC" % colname self.select() elif order == Qt.AscendingOrder: self.query[2] = 'ORDER BY %s' % colname self.select() else: self.query[2] = '' self.select() def select(self): self.sql = " ".join(self.query) self.selected = set() self.cached_row = [-1, None] self.total_row_counts = self.db.get_one(self.query[0] % "COUNT(*)" + " " + self.query[1] + " LIMIT 1") self.beginResetModel() self.displayed = self.db.get_column(self.sql % 'id' + " LIMIT 100") self.readed_row_counts = len(self.displayed) self.endResetModel() self.row_col.emit((self.table, self.total_row_counts, len(self.headers))) self.sel_row.emit(len(self.selected)) def clear(self): self.beginResetModel() self.total_row_counts = 0 self.readed_row_counts = 0 self.selected = set() self.cached_row = [-1, None] self.headers = [] self.displayed = [] self.endResetModel() self.row_col.emit((self.table, self.total_row_counts, len(self.headers))) self.sel_row.emit(len(self.selected)) def remove(self, table): if table == self.table: self.clear() self.db.clear(table) #def getSelectedRows(self): # if self.total_row_counts == len(self.selected): # return 'whole' # else: # return [str(self.displayed[i]) for i in sorted(self.selected)] def getCellId(self, row): #return self.displayed[row] return self.db.get_one("%s LIMIT %s,1" % (self.sql % 'id', row)) def value(self, index): row = index.row() col = index.column() - 1 if row == self.cached_row[0]: return self.cached_row[1][col] ID = self.displayed[row] self.cached_row[0] = row sql = self.query[0] % '*' + " WHERE id=%s LIMIT 1" % ID self.cached_row[1] = self.db.get_row(sql) return self.cached_row[1][col] def rowColor(self, index): ID = self.displayed[index.row()] if self.table == 'primer' or self.db.is_empty('location'): return QColor(255, 255, 255) colors = { 1: QColor(245, 183, 177), 2: QColor(250, 215, 160), 3: QColor(169, 223, 191), 4: QColor(174, 214, 241) } sql = "SELECT feature FROM location WHERE reptype=%s AND target=%s LIMIT 1" feature = self.db.get_one(sql % (self.repeat_type, ID)) return colors.get(feature, QColor(255, 255, 255)) def rowCount(self, parent=QModelIndex()): if parent.isValid(): return 0 return self.readed_row_counts def columnCount(self, parent=QModelIndex()): if parent.isValid(): return 0 if len(self.headers) > 0: return len(self.headers) + 1 return len(self.headers) def data(self, index, role=Qt.DisplayRole): if not index.isValid(): return None if not (0 <= index.row() < self.rowCount()): return None elif role == Qt.DisplayRole: if index.column() > 0: return self.value(index) else: return None elif role == Qt.CheckStateRole: if index.column() == 0: if self.displayed[index.row()] in self.selected: return Qt.Checked else: return Qt.Unchecked #elif role == Qt.BackgroundRole: # if index.row() in self.selected: # return QColor(215, 242, 222) elif role == Qt.BackgroundColorRole: return self.rowColor(index) #return QColor(215, 242, 222) return None def headerData(self, section, orientation, role=Qt.DisplayRole): #if role == Qt.SizeHintRole: # if section == 0: # return QSize(20, -1) if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: if section == 0: return None else: return self.headers[section-1] elif orientation == Qt.Vertical: #return self.value(section, 1) if role == Qt.CheckStateRole: if index.column() == 0: if self.displayed[index.row()] in self.selected: return Qt.ItemIsUserCheckable else: return Qt.ItemIsUserCheckable return None def setHeaderData(self, section, orientation, value, role=Qt.DisplayRole): if role == Qt.CheckStateRole: if orientation == Qt.Vertical: return def setData(self, index, value, role): if not index.isValid(): return False if index.column() != 0: return False _id = self.getCellId(index.row()) if role == Qt.CheckStateRole: if value == Qt.Checked: self.selected.add(_id) else: if _id in self.selected: self.selected.remove(_id) self.dataChanged.emit(index, index) self.sel_row.emit(len(self.selected)) return True return False def flags(self, index): if not index.isValid(): #return QAbstractItemModel.flags(index) return Qt.ItemIsSelectable flag = Qt.ItemIsEnabled | Qt.ItemIsSelectable if index.column() == 0: return flag | Qt.ItemIsUserCheckable return flag def canFetchMore(self, parent): return not parent.isValid() and (self.readed_row_counts < self.total_row_counts) def fetchMore(self, parent): if parent.isValid(): return remainder = self.total_row_counts - self.readed_row_counts fetch_row = min(100, remainder) sql = self.sql % 'id' + " LIMIT %s,%s" % (self.readed_row_counts, fetch_row) IDs = self.db.get_column(sql) self.beginInsertRows(QModelIndex(), self.readed_row_counts, self.readed_row_counts+fetch_row-1) self.displayed.extend(IDs) self.readed_row_counts += fetch_row self.endInsertRows() class AnnotationDialog(QDialog): def __init__(self, parent=None, gff_file='', rm_file=''): super(AnnotationDialog, self).__init__(parent) self.resize(QSize(450, 80)) self.setWindowTitle(self.tr("Provide annotation file")) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) buttonBox.accepted.connect(self.accept) self.gff_label = QLabel(self.tr("Select GTF, GFF or gz compressed genome annotation file"), self) self.gff_input = QLineEdit(self) self.gff_input.setText(gff_file) self.gff_input.setReadOnly(True) self.gff_btn = QPushButton(self.tr("Select"), self) self.gff_btn.clicked.connect(self.selectAnnotationFile) annotLayout = QGridLayout() annotLayout.setColumnStretch(0, 1) annotLayout.addWidget(self.gff_label, 0, 0) annotLayout.addWidget(self.gff_input, 1, 0) annotLayout.addWidget(self.gff_btn, 1, 1) annotLayout.addWidget(buttonBox, 2, 1) self.setLayout(annotLayout) def selectAnnotationFile(self): filters = "GTF (*.gtf *.gtf.gz);;GFF (*.gff *.gff.gz);;ALL (*.*)" annot_file, _ = QFileDialog.getOpenFileName(self, "GFF or GTF annotation file", filter=filters) if annot_file: self.gff_input.setText(annot_file) def get(self): return self.gff_input.text() class PreferenceDialog(QDialog): def __init__(self, parent=None, settings=None): super(PreferenceDialog, self).__init__(parent) self.settings = settings self.setWindowTitle(self.tr("Preferences")) #self.setMinimumWidth(500) self.general_tab = GeneralTab(self.settings) self.primer_tab = PrimerTab(self.settings) self.tabWidget = QTabWidget() self.tabWidget.addTab(self.general_tab, 'SSR search') self.tabWidget.addTab(self.primer_tab, 'Primer design') buttonBox = QDialogButtonBox(QDialogButtonBox.RestoreDefaults | QDialogButtonBox.Save | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.RestoreDefaults).clicked.connect(self.resetSettings) spacerItem = QSpacerItem(10, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) mainLayout = QVBoxLayout() mainLayout.addWidget(self.tabWidget) mainLayout.addItem(spacerItem) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) def saveSettings(self): self.general_tab.saveSettings() self.primer_tab.saveSettings() def resetSettings(self): self.settings.clear() self.general_tab.getSettings() self.primer_tab.getSettings() self.saveSettings() def gotoPrimer(self): self.tabWidget.setCurrentIndex(1) class GeneralTab(QWidget): def __init__(self, settings, parent=None): super(GeneralTab, self).__init__(parent) self.settings = settings repeatsGroup = QGroupBox(self.tr("Minimum repeats for each SSR type")) monoLabel = QLabel("Mono-nucleotide") self.monoValue = QSpinBox() diLabel = QLabel("Di-nucleotide") self.diValue = QSpinBox() triLabel = QLabel("Tri-nucleotide") self.triValue = QSpinBox() tetraLabel = QLabel("Tetra-nucleotide") self.tetraValue = QSpinBox() pentaLabel = QLabel("Penta-nucleotide") self.pentaValue = QSpinBox() hexaLabel = QLabel("Hexa-nucleotide") self.hexaValue = QSpinBox() repeatLayout = QGridLayout() repeatLayout.setVerticalSpacing(10) repeatLayout.setHorizontalSpacing(10) repeatLayout.setColumnStretch(1, 1) repeatLayout.setColumnStretch(3, 1) repeatLayout.setColumnStretch(5, 1) repeatLayout.addWidget(monoLabel, 0, 0) repeatLayout.addWidget(self.monoValue, 0, 1) repeatLayout.addWidget(diLabel, 0, 2) repeatLayout.addWidget(self.diValue, 0, 3) repeatLayout.addWidget(triLabel, 0, 4) repeatLayout.addWidget(self.triValue, 0, 5) repeatLayout.addWidget(tetraLabel, 1, 0) repeatLayout.addWidget(self.tetraValue, 1, 1) repeatLayout.addWidget(pentaLabel, 1, 2) repeatLayout.addWidget(self.pentaValue, 1, 3) repeatLayout.addWidget(hexaLabel, 1, 4) repeatLayout.addWidget(self.hexaValue, 1, 5) repeatsGroup.setLayout(repeatLayout) distanceGroup = QGroupBox(self.tr("Compound microsatellite, cSSR")) distanceLabel = QLabel("Max distance allowed between two SSRs (dMAX)") self.distanceValue = QSpinBox() self.distanceValue.setMaximum(1000) #self.distanceValue.setSuffix(' bp') distanceLayout = QHBoxLayout() distanceLayout.addWidget(distanceLabel) distanceLayout.addWidget(self.distanceValue, 1) distanceGroup.setLayout(distanceLayout) satelliteGroup = QGroupBox(self.tr("Minisatellite and Macrosatellite, VNTRs")) min_tandem_label = QLabel("Min motif length") self.min_tandem_motif = QSpinBox() self.min_tandem_motif.setMinimum(7) max_tandem_label = QLabel("Max motif length") self.max_tandem_motif = QSpinBox() self.max_tandem_motif.setMinimum(7) self.max_tandem_motif.setMaximum(1000) repeat_tandem_label = QLabel("Min repeats") self.min_tandem_repeat = QSpinBox() self.min_tandem_repeat.setMinimum(2) satelliteLayout = QGridLayout() satelliteLayout.addWidget(min_tandem_label, 0, 0) satelliteLayout.addWidget(self.min_tandem_motif, 0, 1) satelliteLayout.addWidget(max_tandem_label, 0, 2) satelliteLayout.addWidget(self.max_tandem_motif, 0, 3) satelliteLayout.addWidget(repeat_tandem_label, 0, 4) satelliteLayout.addWidget(self.min_tandem_repeat, 0, 5) satelliteGroup.setLayout(satelliteLayout) issrGroup = QGroupBox(self.tr("Imperfect microsatellite, iSSR")) seed_mrep_label = QLabel("Min seed repeats") self.seed_min_repeat = QSpinBox() self.seed_min_repeat.setMinimum(1) seed_mlen_label = QLabel("Min seed length") self.seed_min_length = QSpinBox() max_error_label = QLabel("Max continuous edits") self.max_error = QSpinBox() mis_penalty_label = QLabel("Mismatch penalty") self.mis_penalty = QSpinBox() gap_penalty_label = QLabel("Gap penalty") self.gap_penalty = QSpinBox() min_score_label = QLabel("Min required score") self.min_score = QSpinBox() issrLayout = QGridLayout() issrLayout.addWidget(seed_mrep_label, 0, 0) issrLayout.addWidget(self.seed_min_repeat, 0, 1) issrLayout.addWidget(seed_mlen_label, 0, 2) issrLayout.addWidget(self.seed_min_length, 0, 3) issrLayout.addWidget(max_error_label, 0, 4) issrLayout.addWidget(self.max_error, 0, 5) issrLayout.addWidget(mis_penalty_label, 1, 0) issrLayout.addWidget(self.mis_penalty, 1, 1) issrLayout.addWidget(gap_penalty_label, 1, 2) issrLayout.addWidget(self.gap_penalty, 1, 3) issrLayout.addWidget(min_score_label, 1, 4) issrLayout.addWidget(self.min_score, 1, 5) issrGroup.setLayout(issrLayout) level_group = QGroupBox(self.tr("Motif standardization level")) level_label = QLabel(self.tr("Standard level")) self.level_select = QComboBox() #self.level_select.currentIndexChanged.connect(self.showStandardLevelDetail) #self.level_detail = QLabel() standard_level = [ "Level 0 No standard", "Level 1 Similar motifs", "Level 2 Reverse complementary motifs + Level 1", "Level 3 complementary motifs + Level 2", "Level 4 Reverse motifs + Level 3 (not recommend)" ] self.level_select.addItems(standard_level) level_layout = QHBoxLayout() #level_layout.setColumnStretch(1, 1) level_layout.addWidget(level_label) level_layout.addWidget(self.level_select, 1) #level_layout.addWidget(self.level_detail, 1, 1) level_group.setLayout(level_layout) flankGroup = QGroupBox(self.tr("Flanking sequence for exporting and primer design")) flankLabel = QLabel("Flanking sequence length") self.flankValue = QSpinBox() #self.flankValue.setSuffix(' bp') self.flankValue.setMaximum(10000) flankLayout = QHBoxLayout() flankLayout.addWidget(flankLabel) flankLayout.addWidget(self.flankValue, 1) flankGroup.setLayout(flankLayout) mainLayout = QVBoxLayout() mainLayout.addWidget(repeatsGroup) mainLayout.addWidget(distanceGroup) mainLayout.addWidget(satelliteGroup) mainLayout.addWidget(issrGroup) mainLayout.addWidget(level_group) mainLayout.addWidget(flankGroup) self.setLayout(mainLayout) self.getSettings() def getSettings(self): self.monoValue.setValue(int(self.settings.value('ssr/mono', 12))) self.diValue.setValue(int(self.settings.value('ssr/di', 7))) self.triValue.setValue(int(self.settings.value('ssr/tri', 5))) self.tetraValue.setValue(int(self.settings.value('ssr/tetra', 4))) self.pentaValue.setValue(int(self.settings.value('ssr/penta', 4))) self.hexaValue.setValue(int(self.settings.value('ssr/hexa', 4))) self.distanceValue.setValue(int(self.settings.value('ssr/dmax', 10))) self.flankValue.setValue(int(self.settings.value('ssr/flank', 100))) self.min_tandem_motif.setValue(int(self.settings.value('ssr/vmin', 7))) self.max_tandem_motif.setValue(int(self.settings.value('ssr/vmax', 30))) self.min_tandem_repeat.setValue(int(self.settings.value('ssr/vrep', 2))) self.seed_min_repeat.setValue(int(self.settings.value('ssr/srep', 3))) self.seed_min_length.setValue(int(self.settings.value('ssr/slen', 8))) self.max_error.setValue(int(self.settings.value('ssr/error', 3))) self.min_score.setValue(int(self.settings.value('ssr/score', 10))) self.mis_penalty.setValue(int(self.settings.value('ssr/mismatch', 1))) self.gap_penalty.setValue(int(self.settings.value('ssr/gap', 2))) self.level_select.setCurrentIndex(int(self.settings.value('ssr/level', 3))) def saveSettings(self): self.settings.setValue('ssr/mono', self.monoValue.value()) self.settings.setValue('ssr/di', self.diValue.value()) self.settings.setValue('ssr/tri', self.triValue.value()) self.settings.setValue('ssr/tetra', self.tetraValue.value()) self.settings.setValue('ssr/penta', self.pentaValue.value()) self.settings.setValue('ssr/hexa', self.hexaValue.value()) self.settings.setValue('ssr/dmax', self.distanceValue.value()) self.settings.setValue('ssr/flank', self.flankValue.value()) self.settings.setValue('ssr/vmin', self.min_tandem_motif.value()) self.settings.setValue('ssr/vmax', self.max_tandem_motif.value()) self.settings.setValue('ssr/vrep', self.min_tandem_repeat.value()) self.settings.setValue('ssr/level', self.level_select.currentIndex()) self.settings.setValue('ssr/srep', self.seed_min_repeat.value()) self.settings.setValue('ssr/slen', self.seed_min_length.value()) self.settings.setValue('ssr/error', self.max_error.value()) self.settings.setValue('ssr/score', self.min_score.value()) self.settings.setValue('ssr/mismatch', self.mis_penalty.value()) self.settings.setValue('ssr/gap', self.gap_penalty.value()) #def showStandardLevelDetail(self, idx): # if idx == 0: # detail = 'No standard' # elif idx == 1: # detail = 'standard similar motifs' # elif idx == 2: # detail = 'Level 1 + reverse complementary motifs' # elif idx == 3: # detail = 'Level 2 + complementary motifs' # elif idx == 4: # detail = 'Level 3 + reverse motifs (not recommend)' # self.level_detail.setText(detail) class PrimerTab(QWidget): def __init__(self, settings, parent=None): super(PrimerTab, self).__init__(parent) self.settings = settings self.product_size = QLineEdit() self.primer_num_return = QSpinBox() self.repeat_library = QComboBox() self.repeat_library.addItems(['None', 'Human', 'Rodent', 'Rodent and Simple', 'Drosophila']) product_size_group = QGroupBox(self.tr('General Settings')) product_size_layout = QGridLayout() product_size_layout.addWidget(PrimerTagLabel('PRIMER_PRODUCT_SIZE_RANGE'), 0, 0) product_size_layout.addWidget(self.product_size, 0, 1, 1, 3) product_size_layout.addWidget(PrimerTagLabel('PRIMER_MISPRIMING_LIBRARY'), 1, 0) product_size_layout.addWidget(self.repeat_library, 1, 1) product_size_layout.addWidget(PrimerTagLabel("PRIMER_NUM_RETURN"), 1, 2) product_size_layout.addWidget(self.primer_num_return, 1, 3) product_size_group.setLayout(product_size_layout) primer_size_group = QGroupBox(self.tr("Primer Size and GC content")) primer_size_layout = QGridLayout() self.primer_size_min = QSpinBox() self.primer_size_opt = QSpinBox() self.primer_size_max = QSpinBox() self.primer_gc_min = QDoubleSpinBox() self.primer_gc_max = QDoubleSpinBox() self.primer_gc_clamp = QSpinBox() primer_size_layout.addWidget(PrimerTagLabel("PRIMER_MIN_SIZE"), 0, 0) primer_size_layout.addWidget(self.primer_size_min, 0, 1) primer_size_layout.addWidget(PrimerTagLabel("PRIMER_OPT_SIZE"), 0, 2) primer_size_layout.addWidget(self.primer_size_opt, 0, 3) primer_size_layout.addWidget(PrimerTagLabel("PRIMER_MAX_SIZE"), 0, 4) primer_size_layout.addWidget(self.primer_size_max, 0, 5) primer_size_layout.addWidget(PrimerTagLabel("PRIMER_MIN_GC"), 1, 0) primer_size_layout.addWidget(self.primer_gc_min, 1, 1) primer_size_layout.addWidget(PrimerTagLabel("PRIMER_MAX_GC"), 1, 2) primer_size_layout.addWidget(self.primer_gc_max, 1, 3) primer_size_layout.addWidget(PrimerTagLabel("PRIMER_GC_CLAMP"), 1, 4) primer_size_layout.addWidget(self.primer_gc_clamp, 1, 5) primer_size_group.setLayout(primer_size_layout) primer_tm_group = QGroupBox(self.tr("Primer Melting Temperature")) primer_tm_layout = QGridLayout() self.primer_tm_min = QDoubleSpinBox() self.primer_tm_opt = QDoubleSpinBox() self.primer_tm_max = QDoubleSpinBox() self.primer_tm_pair = QDoubleSpinBox() self.primer_tm_pair.setMaximum(1000) primer_tm_layout.addWidget(PrimerTagLabel("PRIMER_MIN_TM"), 0, 0) primer_tm_layout.addWidget(self.primer_tm_min, 0, 1) primer_tm_layout.addWidget(PrimerTagLabel("PRIMER_OPT_TM"), 0, 2) primer_tm_layout.addWidget(self.primer_tm_opt, 0, 3) primer_tm_layout.addWidget(PrimerTagLabel("PRIMER_MAX_TM"), 0, 4) primer_tm_layout.addWidget(self.primer_tm_max, 0, 5) primer_tm_group.setLayout(primer_tm_layout) primer_bind_group = QGroupBox(self.tr("Self-binding (primer-dimer and hairpins)")) primer_bind_layout = QGridLayout() self.primer_max_self_any = QDoubleSpinBox() self.primer_max_self_any.setMaximum(1000000) self.primer_pair_max_compl_any = QDoubleSpinBox() self.primer_pair_max_compl_any.setMaximum(10000) self.primer_max_self_end = QDoubleSpinBox() self.primer_max_self_end.setMaximum(10000) self.primer_pair_max_compl_end = QDoubleSpinBox() self.primer_pair_max_compl_end.setMaximum(10000) self.primer_max_hairpin = QDoubleSpinBox() primer_bind_layout.addWidget(PrimerTagLabel("PRIMER_MAX_SELF_ANY_TH"), 0, 0) primer_bind_layout.addWidget(self.primer_max_self_any, 0, 1) primer_bind_layout.addWidget(PrimerTagLabel("PRIMER_PAIR_MAX_COMPL_ANY_TH"), 0, 2) primer_bind_layout.addWidget(self.primer_pair_max_compl_any, 0, 3) primer_bind_layout.addWidget(PrimerTagLabel("PRIMER_MAX_SELF_END_TH"), 1, 0) primer_bind_layout.addWidget(self.primer_max_self_end, 1, 1) primer_bind_layout.addWidget(PrimerTagLabel("PRIMER_PAIR_MAX_COMPL_END_TH"), 1, 2) primer_bind_layout.addWidget(self.primer_pair_max_compl_end, 1, 3) primer_bind_layout.addWidget(PrimerTagLabel("PRIMER_MAX_HAIRPIN_TH"), 2, 0) primer_bind_layout.addWidget(self.primer_max_hairpin, 2, 1) primer_bind_group.setLayout(primer_bind_layout) primer_other_group = QGroupBox(self.tr("PolyX and Other")) primer_other_layout = QGridLayout() self.primer_max_end_stability = QDoubleSpinBox() self.primer_max_end_stability.setMaximum(1000) self.primer_max_ns_accepted = QSpinBox() self.primer_max_poly_x = QSpinBox() primer_other_layout.addWidget(PrimerTagLabel("PRIMER_MAX_END_STABILITY"), 0, 0) primer_other_layout.addWidget(self.primer_max_end_stability, 0, 1) primer_other_layout.addWidget(PrimerTagLabel("PRIMER_MAX_POLY_X"), 0, 2) primer_other_layout.addWidget(self.primer_max_poly_x, 0, 3) primer_other_layout.addWidget(PrimerTagLabel("PRIMER_MAX_NS_ACCEPTED"), 1, 0) primer_other_layout.addWidget(self.primer_max_ns_accepted, 1, 1) primer_other_layout.addWidget(PrimerTagLabel("PRIMER_PAIR_MAX_DIFF_TM"), 1, 2) primer_other_layout.addWidget(self.primer_tm_pair, 1, 3) primer_other_group.setLayout(primer_other_layout) mainLayout = QVBoxLayout() mainLayout.addWidget(product_size_group) mainLayout.addWidget(primer_size_group) mainLayout.addWidget(primer_tm_group) mainLayout.addWidget(primer_bind_group) mainLayout.addWidget(primer_other_group) self.setLayout(mainLayout) self.getSettings() def getSettings(self): self.product_size.setText(self.settings.value('primer/PRIMER_PRODUCT_SIZE_RANGE', '100-300')) self.primer_size_min.setValue(int(self.settings.value('primer/PRIMER_MIN_SIZE', 18))) self.primer_size_opt.setValue(int(self.settings.value('primer/PRIMER_OPT_SIZE', 20))) self.primer_size_max.setValue(int(self.settings.value('primer/PRIMER_MAX_SIZE', 27))) self.primer_tm_min.setValue(int(self.settings.value('primer/PRIMER_MIN_TM', 58))) self.primer_tm_opt.setValue(int(self.settings.value('primer/PRIMER_OPT_TM', 60))) self.primer_tm_max.setValue(int(self.settings.value('primer/PRIMER_MAX_TM', 65))) self.primer_gc_min.setValue(int(self.settings.value('primer/PRIMER_MIN_GC', 30))) self.primer_gc_max.setValue(int(self.settings.value('primer/PRIMER_MAX_GC', 80))) self.primer_gc_clamp.setValue(int(self.settings.value('primer/PRIMER_GC_CLAMP', 2))) self.primer_tm_pair.setValue(int(self.settings.value('primer/PRIMER_PAIR_MAX_DIFF_TM', 2))) self.primer_max_self_any.setValue(int(self.settings.value('primer/PRIMER_MAX_SELF_ANY_TH', 47))) self.primer_pair_max_compl_any.setValue(int(self.settings.value('primer/PRIMER_PAIR_MAX_COMPL_ANY_TH', 47))) self.primer_max_self_end.setValue(int(self.settings.value('primer/PRIMER_MAX_SELF_END_TH', 47))) self.primer_pair_max_compl_end.setValue(int(self.settings.value('primer/PRIMER_PAIR_MAX_COMPL_END_TH', 47))) self.primer_max_hairpin.setValue(int(self.settings.value('primer/PRIMER_MAX_HAIRPIN_TH', 47))) self.primer_max_end_stability.setValue(int(self.settings.value('primer/PRIMER_MAX_END_STABILITY', 100))) self.primer_max_ns_accepted.setValue(int(self.settings.value('primer/PRIMER_MAX_POLY_X', 5))) self.primer_max_poly_x.setValue(int(self.settings.value('primer/PRIMER_MAX_NS_ACCEPTED', 0))) self.primer_num_return.setValue(int(self.settings.value('primer/PRIMER_NUM_RETURN', 1))) self.repeat_library.setCurrentIndex(int(self.settings.value('primer/PRIMER_MISPRIMING_LIBRARY', 0))) def saveSettings(self): self.settings.setValue('primer/PRIMER_PRODUCT_SIZE_RANGE', self.product_size.text()) self.settings.setValue('primer/PRIMER_MIN_SIZE', self.primer_size_min.value()) self.settings.setValue('primer/PRIMER_OPT_SIZE', self.primer_size_opt.value()) self.settings.setValue('primer/PRIMER_MAX_SIZE', self.primer_size_max.value()) self.settings.setValue('primer/PRIMER_MIN_TM', self.primer_tm_min.value()) self.settings.setValue('primer/PRIMER_OPT_TM', self.primer_tm_opt.value()) self.settings.setValue('primer/PRIMER_MAX_TM', self.primer_tm_max.value()) self.settings.setValue('primer/PRIMER_MIN_GC', self.primer_gc_min.value()) self.settings.setValue('primer/PRIMER_MAX_GC', self.primer_gc_max.value()) self.settings.setValue('primer/PRIMER_GC_CLAMP', self.primer_gc_clamp.value()) self.settings.setValue('primer/PRIMER_PAIR_MAX_DIFF_TM', self.primer_tm_pair.value()) self.settings.setValue('primer/PRIMER_MAX_SELF_ANY_TH', self.primer_max_self_any.value()) self.settings.setValue('primer/PRIMER_PAIR_MAX_COMPL_ANY_TH', self.primer_pair_max_compl_any.value()) self.settings.setValue('primer/PRIMER_MAX_SELF_END_TH', self.primer_max_self_end.value()) self.settings.setValue('primer/PRIMER_PAIR_MAX_COMPL_END_TH', self.primer_pair_max_compl_end.value()) self.settings.setValue('primer/PRIMER_MAX_HAIRPIN_TH', self.primer_max_hairpin.value()) self.settings.setValue('primer/PRIMER_MAX_END_STABILITY', self.primer_max_end_stability.value()) self.settings.setValue('primer/PRIMER_MAX_POLY_X', self.primer_max_ns_accepted.value()) self.settings.setValue('primer/PRIMER_MAX_NS_ACCEPTED', self.primer_max_poly_x.value()) self.settings.setValue('primer/PRIMER_NUM_RETURN', self.primer_num_return.value()) self.settings.setValue('primer/PRIMER_MISPRIMING_LIBRARY', self.repeat_library.currentIndex()) class PrimerTagLabel(QLabel): base_url = "https://primer3.org/manual.html#%s" def __init__(self, tag, parent=None): super(PrimerTagLabel, self).__init__(parent) #self.setOpenExternalLinks(True) self.tag = tag self.setText('<a href="#%s">%s</a>' % (self.tag, self.tag)) self.linkActivated.connect(self.openLink) def openLink(self, link): url = QUrl.fromLocalFile(self.base_url % self.tag) QDesktopServices.openUrl(url) class SSRDetailDialog(QDialog): def __init__(self, parent=None, title=None, content=None): super(SSRDetailDialog, self).__init__(parent) self.setWindowTitle(title) #self.viewer = QWebEngineView(self) #self.viewer = QWebView(self) self.viewer = QTextBrowser(self) #self.viewer.setStyleSheet("font-family:robotomono"); #self.viewer.setSource(QUrl('https://www.baidu.com')) self.viewer.setHtml(content) #buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) #buttonBox.accepted.connect(self.accept) mainLayout = QVBoxLayout() #mainLayout.setSpacing(0) #mainLayout.setMargin(0) mainLayout.addWidget(self.viewer) #mainLayout.addWidget(buttonBox) self.resize(700, 500) self.setLayout(mainLayout) #self.open() class DownloadDialog(QDialog): def __init__(self, parent=None): super(DownloadDialog, self).__init__(parent) self.setMinimumWidth(500) self.setWindowTitle("Download sequence from NCBI") self.acc_label = QLabel(self.tr("NCBI Accession Number:"), self) self.acc_input = QLineEdit(self) self.out_label = QLabel(self.tr("Select output path:"), self) self.out_input = QLineEdit(self) self.browser_btn = QPushButton(self.tr("Browser"), self) self.browser_btn.clicked.connect(self.select) self.out_input.setReadOnly(True) layout = QGridLayout() layout.setColumnStretch(0, 1) layout.addWidget(self.acc_label, 0, 0) layout.addWidget(self.acc_input, 1, 0, 1, 2) layout.addWidget(self.out_label, 2, 0) layout.addWidget(self.out_input, 3, 0) layout.addWidget(self.browser_btn, 3, 1) buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) layout.addWidget(buttonBox, 4, 0, Qt.AlignLeft) self.setLayout(layout) def select(self): exp_file, _ = QFileDialog.getSaveFileName(self, filter="Fasta (*.fa);;Fasta (*.fasta)") if exp_file: self.out_input.setText(exp_file) def get(self): acc = self.acc_input.text().strip() out = self.out_input.text() return acc, out #class BrowserWidget(QWebEngineView): #class BrowserWidget(QWebView): #def __init__(self, parent): #super(BrowserWidget, self).__init__(parent) #self.parent = parent #self.db = Database() #self.pageAction(QWebEnginePage.DownloadImageToDisk).triggered.connect(self.saveImage) #self.pageAction(QWebEnginePage.OpenImageInNewWindow).triggered.connect(self.openImage) #self.page().setLinkDelegationPolicy(QWebEnginePage.DelegateAllLinks) #self.page().linkClicked.connect(self.saveTable) #def openImage(self): # url = self.page().mainFrame().hitTestContent(QCursor.pos()).imageUrl() # QDesktopServices.openUrl(url) #def saveImage(self): # pm = self.page().mainFrame().hitTestContent(QCursor.pos()).pixmap() # filepath, _ = QFileDialog.getSaveFileName(self, "Save image", # filter="TIFF File (*.tiff);;JPEG File (*.jpg);;PNG File (*.png)" # ) # if not filepath: return # pm.save(filepath) # self.parent.setStatusMessage('Image %s has been successfully saved' % filepath) #def saveTable(self, url): # url = url.toString() # table, name = url.split('/')[-1].split('-') # stats_str = self.db.get_option('%s_statis' % table) # stats_obj = json.loads(stats_str) # outfile, _ = QFileDialog.getSaveFileName(self, filter="CSV (*.csv)") # if not outfile: return # with open(outfile, 'wb') as fh: # writer = csv.writer(fh) # writer.write(stats_obj[name][0]) # write_to_csv(writer, stats_obj[name][1:]) # self.parent.setStatusMessage("Table %s has been successfully saved" % outfile) #class SSRTableModel(QSqlTableModel): # def __init__(self): # super(SSRTableModel, self).__init__() # self.setTable('ssr') # self.select() #def data(self, index, role=Qt.DisplayRole): # if role == Qt.TextAlignmentRole: # return Qt.AlignCenter # return QSqlTableModel.data(self, index, role)
agpl-3.0
gabrys/wikidot
web/default_flow.php
1287
<?php /** * Wikidot - free wiki collaboration software * Copyright (c) 2008, Wikidot Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * For more information about licensing visit: * http://www.wikidot.org/license * * @category Wikidot * @package Wikidot_Web * @version $Id$ * @copyright Copyright (c) 2008, Wikidot Inc. * @license http://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License */ require ('../php/setup.php'); // to avoid caching header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past setcookie("wikidot_token7", md5(rand(0, 10000)), null, '/'); try { $controller = new WDDefaultFlowController(); $controller->process(); } catch (Exception $e) { echo $e->getMessage(); }
agpl-3.0
numenta/NAB
nab/detectors/context_ose/context_operator.py
8514
# ---------------------------------------------------------------------- # Copyright (C) 2016, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- class ContextOperator(object): """ Contextual Anomaly Detector - Open Source Edition 2016, Mikhail Smirnov smirmik@gmail.com https://github.com/smirmik/CAD """ def __init__(self, maxLeftSemiContextsLenght): self.maxLeftSemiContextsLenght = maxLeftSemiContextsLenght self.factsDics = [{},{}] self.semiContextDics = [{},{}] self.semiContValLists = [[],[]] self.crossedSemiContextsLists = [[],[]] self.contextsValuesList = [] self.newContextID = False def getContextByFacts (self, newContextsList, zerolevel = 0 ) : """ The function which determines by the complete facts list whether the context is already saved to the memory. If the context is not found the function immediately creates such. To optimize speed and volume of the occupied memory the contexts are divided into semi-contexts as several contexts can contain the same facts set in its left and right parts. @param newContextsList: list of potentially new contexts @param zerolevel: flag indicating the context type in transmitted list @return : depending on the type of potentially new context transmitted as an input parameters the function returns either: a) flag indicating that the transmitted zero-level context is a new/existing one; or: b) number of the really new contexts that have been saved to the context memory. """ numAddedContexts = 0 for leftFacts, rightFacts in newContextsList : leftHash = leftFacts.__hash__() rightHash = rightFacts.__hash__() nextLeftSemiContextNumber = len(self.semiContextDics[0]) leftSemiContextID = self.semiContextDics[0].setdefault( leftHash, nextLeftSemiContextNumber ) if leftSemiContextID == nextLeftSemiContextNumber : leftSemiContVal = [[] , len(leftFacts), 0, {}] self.semiContValLists[0].append(leftSemiContVal) for fact in leftFacts : semiContextList = self.factsDics[0].setdefault(fact, []) semiContextList.append(leftSemiContVal) nextRightSemiContextNumber = len(self.semiContextDics[1]) rightSemiContextID = self.semiContextDics[1].setdefault( rightHash, nextRightSemiContextNumber ) if rightSemiContextID == nextRightSemiContextNumber : rightSemiContextValues = [[] , len(rightFacts), 0] self.semiContValLists[1].append(rightSemiContextValues) for fact in rightFacts : semiContextList = self.factsDics[1].setdefault(fact, []) semiContextList.append(rightSemiContextValues) nextFreeContextIDNumber = len(self.contextsValuesList) contextID = self.semiContValLists[0][leftSemiContextID][3].setdefault( rightSemiContextID, nextFreeContextIDNumber ) if contextID == nextFreeContextIDNumber : numAddedContexts += 1 contextValues = [0, zerolevel, leftHash, rightHash] self.contextsValuesList.append(contextValues) if zerolevel : self.newContextID = contextID return True else : contextValues = self.contextsValuesList[contextID] if zerolevel : contextValues[1] = 1 return False return numAddedContexts def contextCrosser( self, leftOrRight, factsList, newContextFlag = False, potentialNewContexts = None): if leftOrRight == 0 : if len(potentialNewContexts) > 0 : numNewContexts = self.getContextByFacts (potentialNewContexts) else : numNewContexts = 0 for semiContextValues in self.crossedSemiContextsLists[leftOrRight] : semiContextValues[0] = [] semiContextValues[2] = 0 for fact in factsList : for semiContextValues in self.factsDics[leftOrRight].get(fact, []) : semiContextValues[0].append(fact) newCrossedValues = [] for semiContextValues in self.semiContValLists[leftOrRight] : lenSemiContextValues0 = len(semiContextValues[0]) semiContextValues[2] = lenSemiContextValues0 if lenSemiContextValues0 > 0 : newCrossedValues.append(semiContextValues) self.crossedSemiContextsLists[leftOrRight] = newCrossedValues if leftOrRight : return self.updateContextsAndGetActive(newContextFlag) else : return numNewContexts def updateContextsAndGetActive(self, newContextFlag): """ This function reviews the list of previously selected left semi-contexts, creates the list of potentially new contexts resulted from intersection between zero-level contexts, determines the contexts that coincide with the input data and require activation. @param newContextFlag: flag indicating that a new zero-level context is not recorded at the current step, which means that all contexts already exist and there is no need to create new ones. @return activeContexts: list of identifiers of the contexts which completely coincide with the input stream, should be considered active and be recorded to the input stream of "neurons" @return potentialNewContextsLists: list of contexts based on intersection between the left and the right zero-level semi-contexts, which are potentially new contexts requiring saving to the context memory """ activeContexts = [] numSelectedContext = 0 potentialNewContexts = [] for leftSemiContVal in self.crossedSemiContextsLists[0]: for rightSemiContextID, contextID in leftSemiContVal[3].items(): if self.newContextID != contextID : contextValues = self.contextsValuesList[contextID] rightSemiContVal = self.semiContValLists[1][rightSemiContextID] rightSemConVal0, rightSemConVal1, rightSemConVal2 = rightSemiContVal if leftSemiContVal[1] == leftSemiContVal[2] : numSelectedContext += 1 if rightSemConVal2 > 0 : if rightSemConVal1 == rightSemConVal2 : contextValues[0] += 1 activeContexts.append([ contextID, contextValues[0], contextValues[2], contextValues[3] ]) elif contextValues[1] and newContextFlag : if leftSemiContVal[2] <= self.maxLeftSemiContextsLenght : leftFacts = tuple(leftSemiContVal[0]) rightFacts = tuple(rightSemConVal0) potentialNewContexts.append(tuple([leftFacts, rightFacts])) elif contextValues[1] and newContextFlag and rightSemConVal2 > 0 : if leftSemiContVal[2] <= self.maxLeftSemiContextsLenght : leftFacts = tuple(leftSemiContVal[0]) rightFacts = tuple(rightSemConVal0) potentialNewContexts.append(tuple([leftFacts, rightFacts])) self.newContextID = False return activeContexts, numSelectedContext, potentialNewContexts
agpl-3.0
Tisseo/EndivBundle
Entity/PoiType.php
959
<?php namespace Tisseo\EndivBundle\Entity; /** * PoiType */ class PoiType { /** * @var int */ private $id; /** * @var string */ private $name; /** * @var string */ private $long_name; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return PoiType */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * @return string */ public function getLongName() { return $this->long_name; } /** * @param string $long_name */ public function setLongName($long_name) { $this->long_name = $long_name; } }
agpl-3.0
opentechnologist/redtree
admin/page/ottr.php
501
<?php class page_ottr extends Page { function init() { parent::init(); $this->api->auth->check(); $obj=$this->add('CRUD')->setModel('OTTrans'); if($this->api->recall('payrollperiod')) $this->add('Text')->set('Filtered on Payroll Period: '. $this->api->recall('payrollperioddesc')); if($this->api->recall('payrollperiod')) $obj->addCondition('payrollperiod=',$this->api->recall('payrollperiod')); if($obj->owner->owner->grid) $obj->owner->owner->grid->addPaginator(10); } }
agpl-3.0
Talocha/PHP-Fusion
locale/Lithuanian/permalinks/profiles.php
147
<?php $locale['pl_profiles_title'] = "Narių profiliai"; $locale['pl_profiles_desc'] = "Įjungti pastovias nuorodas narių profilių nuorodoms.";
agpl-3.0
simonzhangsm/voltdb
src/frontend/org/voltdb/expressions/ExpressionUtil.java
28291
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.expressions; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import org.voltdb.VoltType; import org.voltdb.planner.PlanningErrorException; import org.voltdb.types.ExpressionType; /** * */ public abstract class ExpressionUtil { public static void finalizeValueTypes(AbstractExpression exp) { exp.normalizeOperandTypes_recurse(); exp.finalizeValueTypes(); } @SafeVarargs public static AbstractExpression cloneAndCombinePredicates(Collection<AbstractExpression>... colExps) { Stack<AbstractExpression> stack = new Stack<AbstractExpression>(); for (Collection<AbstractExpression> exps : colExps) { if (exps == null) { continue; } for (AbstractExpression expr : exps) { stack.add(expr.clone()); } } if (stack.isEmpty()) { return null; } return combineStack(stack); } /** * * @param colExps */ @SafeVarargs public static AbstractExpression combinePredicates(Collection<AbstractExpression>... colExps) { Stack<AbstractExpression> stack = new Stack<AbstractExpression>(); for (Collection<AbstractExpression> exps : colExps) { if (exps != null) { stack.addAll(exps); } } if (stack.isEmpty()) { return null; } return combineStack(stack); } private static AbstractExpression combineStack(Stack<AbstractExpression> stack) { // TODO: This code probably doesn't need to go through all this trouble to create AND trees // like "((D and C) and B) and A)" from the list "[A, B, C, D]". // There is an easier algorithm that does not require stacking intermediate results. // Even better, it would be easier here to generate "(D and (C and (B and A)))" // which would also short-circuit slightly faster in the executor. // NOTE: Any change to the structure of the trees produced by this algorithm should be // reflected in the algorithm used to reverse the process in uncombine(AbstractExpression expr). AbstractExpression ret = null; while (stack.size() > 1) { AbstractExpression child_exp = stack.pop(); // // If our return node is null, then we need to make a new one // if (ret == null) { ret = new ConjunctionExpression(ExpressionType.CONJUNCTION_AND); ret.setLeft(child_exp); // // Check whether we can add it to the right side // } else if (ret.getRight() == null) { ret.setRight(child_exp); stack.push(ret); ret = null; } } if (ret == null) { ret = stack.pop(); } else { ret.setRight(stack.pop()); } // Simplify combined expression if possible return ExpressionUtil.evaluateExpression(ret); } /** * Undo the effects of the combine(List<AbstractExpression> exps) method to reconstruct the list * of expressions in its original order, basically right-to-left in the given expression tree. * NOTE: This implementation is tuned to the odd shape of the trees produced by combine, * namely leaf-nodes-on-the-right "(((D and C) and B) and A)" from "[A,B,C,D]". * Any change there should have a corresponding change here. * @param expr * @return */ public static List<AbstractExpression> uncombinePredicate(AbstractExpression expr) { if (expr == null) { return new ArrayList<AbstractExpression>(); } if (expr instanceof ConjunctionExpression) { ConjunctionExpression conj = (ConjunctionExpression)expr; if (conj.getExpressionType() == ExpressionType.CONJUNCTION_AND) { // Calculate the list for the tree or leaf on the left. List<AbstractExpression> branch = uncombinePredicate(conj.getLeft()); // Insert the leaf on the right at the head of that list branch.add(0, conj.getRight()); return branch; } // Any other kind of conjunction must have been a leaf. Fall through. } // At the left-most leaf, start a new list. List<AbstractExpression> leaf = new ArrayList<AbstractExpression>(); leaf.add(expr); return leaf; } /** * Convert one or more predicates, potentially in an arbitrarily nested conjunction tree * into a flattened collection. Similar to uncombine but for arbitrary tree shapes and with no * guarantee of the result collection type or of any ordering within the collection. * In fact, it currently fills an ArrayDeque via a left=to-right breadth first traversal, * but for no particular reason, so that's all subject to change. * @param expr * @return a Collection containing expr or if expr is a conjunction, its top-level non-conjunction * child expressions. */ public static Collection<AbstractExpression> uncombineAny(AbstractExpression expr) { ArrayDeque<AbstractExpression> out = new ArrayDeque<AbstractExpression>(); if (expr != null) { ArrayDeque<AbstractExpression> in = new ArrayDeque<AbstractExpression>(); // this chunk of code breaks the code into a list of expression that // all have to be true for the where clause to be true in.add(expr); AbstractExpression inExpr = null; while ((inExpr = in.poll()) != null) { if (inExpr.getExpressionType() == ExpressionType.CONJUNCTION_AND) { in.add(inExpr.getLeft()); in.add(inExpr.getRight()); } else { out.add(inExpr); } } } return out; } /** * Find any listed expressions that qualify as potential partitioning where filters, * which is to say are equality comparisons with a TupleValueExpression on at least one side, * and a TupleValueExpression, ConstantValueExpression, or ParameterValueExpression on the other. * Add them to a map keyed by the TupleValueExpression(s) involved. * @param filterList a list of candidate expressions * @param the running result * @return a Collection containing the qualifying filter expressions. */ public static void collectPartitioningFilters(Collection<AbstractExpression> filterList, HashMap<AbstractExpression, Set<AbstractExpression> > equivalenceSet) { for (AbstractExpression expr : filterList) { if ( ! expr.isColumnEquivalenceFilter()) { continue; } AbstractExpression leftExpr = expr.getLeft(); AbstractExpression rightExpr = expr.getRight(); // Any two asserted-equal expressions need to map to the same equivalence set, // which must contain them and must be the only such set that contains them. Set<AbstractExpression> eqSet1 = null; if (equivalenceSet.containsKey(leftExpr)) { eqSet1 = equivalenceSet.get(leftExpr); } if (equivalenceSet.containsKey(rightExpr)) { Set<AbstractExpression> eqSet2 = equivalenceSet.get(rightExpr); if (eqSet1 == null) { // Add new leftExpr into existing rightExpr's eqSet. equivalenceSet.put(leftExpr, eqSet2); eqSet2.add(leftExpr); } else { // Merge eqSets, re-mapping all the rightExpr's equivalents into leftExpr's eqset. for (AbstractExpression eqMember : eqSet2) { eqSet1.add(eqMember); equivalenceSet.put(eqMember, eqSet1); } } } else { if (eqSet1 == null) { // Both leftExpr and rightExpr are new -- add leftExpr to the new eqSet first. eqSet1 = new HashSet<AbstractExpression>(); equivalenceSet.put(leftExpr, eqSet1); eqSet1.add(leftExpr); } // Add new rightExpr into leftExpr's eqSet. equivalenceSet.put(rightExpr, eqSet1); eqSet1.add(rightExpr); } } } /** * * @param left * @param right * @return Both expressions passed in combined by an And conjunction. */ public static AbstractExpression combine(AbstractExpression left, AbstractExpression right) { AbstractExpression retval = new ConjunctionExpression(ExpressionType.CONJUNCTION_AND, left, right); // Simplify combined expression if possible return ExpressionUtil.evaluateExpression(retval); } /** * Recursively walk an expression and return a list of all the tuple * value expressions it contains. */ public static List<TupleValueExpression> getTupleValueExpressions(AbstractExpression input) { ArrayList<TupleValueExpression> tves = new ArrayList<TupleValueExpression>(); // recursive stopping steps if (input == null) { return tves; } else if (input instanceof TupleValueExpression) { tves.add((TupleValueExpression) input); return tves; } // recursive calls tves.addAll(getTupleValueExpressions(input.m_left)); tves.addAll(getTupleValueExpressions(input.m_right)); if (input.m_args != null) { for (AbstractExpression argument : input.m_args) { tves.addAll(getTupleValueExpressions(argument)); } } return tves; } /** * Method to simplify an expression by eliminating identical subexpressions (same id) * If the expression is a logical conjunction of the form e1 AND e2 AND e3 AND e4, * and subexpression e1 is identical to the subexpression e2 the simplified expression is * e1 AND e3 AND e4. * * @param expr to simplify * @return simplified expression. */ public static AbstractExpression eliminateDuplicates(Collection<AbstractExpression> exprList) { // Eliminate duplicates by building the map of expression's ids, values. Map<String, AbstractExpression> subExprMap = new HashMap<String, AbstractExpression>(); for (AbstractExpression subExpr : exprList) { subExprMap.put(subExpr.m_id, subExpr); } // Now reconstruct the expression return ExpressionUtil.combinePredicates(subExprMap.values()); } /** * A condition is null-rejected for a given table in the following cases: * If it is of the form A IS NOT NULL, where A is an attribute of any of the inner tables * If it is a predicate containing a reference to an inner table that evaluates to UNKNOWN * when one of its arguments is NULL * If it is a conjunction containing a null-rejected condition as a conjunct * If it is a disjunction of null-rejected conditions * * @param expr * @param tableAlias * @return */ public static boolean isNullRejectingExpression(AbstractExpression expr, String tableAlias) { ExpressionType exprType = expr.getExpressionType(); if (exprType == ExpressionType.CONJUNCTION_AND) { assert(expr.m_left != null && expr.m_right != null); return isNullRejectingExpression(expr.m_left, tableAlias) || isNullRejectingExpression(expr.m_right, tableAlias); } if (exprType == ExpressionType.CONJUNCTION_OR) { assert(expr.m_left != null && expr.m_right != null); return isNullRejectingExpression(expr.m_left, tableAlias) && isNullRejectingExpression(expr.m_right, tableAlias); } if (exprType == ExpressionType.COMPARE_NOTDISTINCT) { return false; } if (exprType == ExpressionType.OPERATOR_NOT) { assert(expr.m_left != null); // "NOT ( P and Q )" is as null-rejecting as "NOT P or NOT Q" // "NOT ( P or Q )" is as null-rejecting as "NOT P and NOT Q" // Handling AND and OR expressions requires a "negated" flag to the recursion that tweaks // (switches?) the handling of ANDs and ORs to enforce the above equivalences. if (expr.m_left.getExpressionType() == ExpressionType.OPERATOR_IS_NULL) { return containsMatchingTVE(expr, tableAlias); } if (expr.m_left.getExpressionType() == ExpressionType.CONJUNCTION_AND || expr.m_left.getExpressionType() == ExpressionType.CONJUNCTION_OR) { assert(expr.m_left.m_left != null && expr.m_left.m_right != null); // Need to test for an existing child NOT and skip it. // e.g. NOT (P AND NOT Q) --> (NOT P) OR NOT NOT Q --> (NOT P) OR Q AbstractExpression tempLeft = null; if (expr.m_left.m_left.getExpressionType() != ExpressionType.OPERATOR_NOT) { tempLeft = new OperatorExpression(ExpressionType.OPERATOR_NOT, expr.m_left.m_left, null); } else { assert(expr.m_left.m_left.m_left != null); tempLeft = expr.m_left.m_left.m_left; } AbstractExpression tempRight = null; if (expr.m_left.m_right.getExpressionType() != ExpressionType.OPERATOR_NOT) { tempRight = new OperatorExpression(ExpressionType.OPERATOR_NOT, expr.m_left.m_right, null); } else { assert(expr.m_left.m_right.m_left != null); tempRight = expr.m_left.m_right.m_left; } ExpressionType type = (expr.m_left.getExpressionType() == ExpressionType.CONJUNCTION_AND) ? ExpressionType.CONJUNCTION_OR : ExpressionType.CONJUNCTION_AND; AbstractExpression tempExpr = new OperatorExpression(type, tempLeft, tempRight); return isNullRejectingExpression(tempExpr, tableAlias); } if (expr.m_left.getExpressionType() == ExpressionType.OPERATOR_NOT) { // It's probably safe to assume that HSQL will have stripped out other double negatives, // (like "NOT T.c IS NOT NULL"). Yet, we could also handle them here assert(expr.m_left.m_left != null); return isNullRejectingExpression(expr.m_left.m_left, tableAlias); } return isNullRejectingExpression(expr.m_left, tableAlias); } if (exprType == ExpressionType.COMPARE_NOTDISTINCT) { // IS NOT DISTINCT FROM is not NULL rejecting, // particularly when applied to pairs of NULL values. //TODO: There are subcases that actually are NULL rejecting, // with various degrees of easy detectability here, namely... // ...IS NOT DISTINCT FROM <non-null-constant> // ...IS NOT DISTINCT FROM <non-nullable-column> // ...IS NOT DISTINCT FROM <most-expressions-built-of-these> // but for now, we are lazy in the planner and possibly slower // at runtime, keeping the joins outer and relying more on the // runtime filters. return false; } if (exprType == ExpressionType.OPERATOR_IS_NULL) { // IS NOT NULL is NULL rejecting -- IS NULL is not return false; } if (expr.hasAnySubexpressionOfClass(OperatorExpression.class)) { // COALESCE expression is a sub-expression // For example, COALESCE (C1, C2) > 0 List<OperatorExpression> coalesceExprs = expr.findAllSubexpressionsOfClass(OperatorExpression.class); for (OperatorExpression coalesceExpr : coalesceExprs) { if ((coalesceExpr.getExpressionType() == ExpressionType.OPERATOR_ALTERNATIVE) && containsMatchingTVE(coalesceExpr, tableAlias)) { // This table is part of the COALESCE expression - not NULL-rejecting return false; } } // If we get there it means that the tableAlias is not part of any of COALESCE expression // still need to check the catch all case } // @TODO ENG_3038 Is it safe to assume for the rest of the expressions that if // it contains a TVE with the matching table name then it is NULL rejection expression? // Presently, yes, logical expressions are not expected to appear inside other // generalized expressions, so since the handling of other kinds of expressions // is pretty much "containsMatchingTVE", this fallback should be safe. // The only planned developments that might contradict this restriction (AFAIK --paul) // would be support for standard pseudo-functions that take logical condition arguments. // These should probably be supported as special non-functions/operations for a number // of reasons and may need special casing here. return containsMatchingTVE(expr, tableAlias); } /** * Given two equal length lists of the expressions build a combined equivalence expression * (le1, le2,..., leN) (re1, re2,..., reN) => * (le1=re1) AND (le2=re2) AND .... AND (leN=reN) * * @param leftExprs * @param rightExprs * @return AbstractExpression */ public static AbstractExpression buildEquavalenceExpression(Collection<AbstractExpression> leftExprs, Collection<AbstractExpression> rightExprs) { assert(leftExprs.size() == rightExprs.size()); Iterator<AbstractExpression> leftIt = leftExprs.iterator(); Iterator<AbstractExpression> rightIt = rightExprs.iterator(); AbstractExpression result = null; while (leftIt.hasNext() && rightIt.hasNext()) { AbstractExpression leftExpr = leftIt.next(); AbstractExpression rightExpr = rightIt.next(); AbstractExpression eqaulityExpr = new ComparisonExpression(ExpressionType.COMPARE_EQUAL, leftExpr, rightExpr); if (result == null) { result = eqaulityExpr; } else { result = new ConjunctionExpression(ExpressionType.CONJUNCTION_AND, result, eqaulityExpr); } } return result; } /** * Return true/false whether an expression contains any aggregate expression * * @param expr * @return true is expression contains an aggregate subexpression */ public static boolean containsAggregateExpression(AbstractExpression expr) { AbstractExpression.SubexprFinderPredicate pred = new AbstractExpression.SubexprFinderPredicate() { @Override public boolean matches(AbstractExpression expr) { return expr.getExpressionType().isAggregateExpression(); } }; return expr.hasAnySubexpressionWithPredicate(pred); } private static boolean containsMatchingTVE(AbstractExpression expr, String tableAlias) { assert(expr != null); List<TupleValueExpression> tves = getTupleValueExpressions(expr); for (TupleValueExpression tve : tves) { if (tve.matchesTableAlias(tableAlias)) { return true; } } return false; } /** * Traverse this expression tree. Where we find a SelectSubqueryExpression, wrap it * in a ScalarValueExpression if its parent is not one of: * - comparison (=, !=, <, etc) * - operator exists * @param expr - the expression that may contain subqueries that need to be wrapped * @return the expression with subqueries wrapped where needed */ public static AbstractExpression wrapScalarSubqueries(AbstractExpression expr) { return wrapScalarSubqueriesHelper(null, expr); } private static AbstractExpression wrapScalarSubqueriesHelper(AbstractExpression parentExpr, AbstractExpression expr) { // Bottom-up recursion. Proceed to the children first. AbstractExpression leftChild = expr.getLeft(); if (leftChild != null) { AbstractExpression newLeft = wrapScalarSubqueriesHelper(expr, leftChild); if (newLeft != leftChild) { expr.setLeft(newLeft); } } AbstractExpression rightChild = expr.getRight(); if (rightChild != null) { AbstractExpression newRight = wrapScalarSubqueriesHelper(expr, rightChild); if (newRight != rightChild) { expr.setRight(newRight); } } // Let's not forget the args, which may also contain subqueries. List<AbstractExpression> args = expr.getArgs(); if (args != null) { for (int i = 0; i < args.size(); ++i) { AbstractExpression arg = args.get(i); AbstractExpression newArg = wrapScalarSubqueriesHelper(expr, arg); if (newArg != arg) { expr.setArgAtIndex(i, newArg); } } } if (expr instanceof SelectSubqueryExpression && subqueryRequiresScalarValueExpressionFromContext(parentExpr)) { expr = addScalarValueExpression((SelectSubqueryExpression)expr); } return expr; } /** * Return true if we must insert a ScalarValueExpression between a subquery * and its parent expression. * @param parentExpr the parent expression of a subquery * @return true if the parent expression is not a comparison, EXISTS operator, or * a scalar value expression */ private static boolean subqueryRequiresScalarValueExpressionFromContext(AbstractExpression parentExpr) { if (parentExpr == null) { // No context: we are a top-level expression. E.g, an item on the // select list. In this case, assume the expression must be scalar. return true; } // Exists and comparison operators can handle non-scalar subqueries. if (parentExpr.getExpressionType() == ExpressionType.OPERATOR_EXISTS || parentExpr instanceof ComparisonExpression) { return false; } // There is already a ScalarValueExpression above the subquery. if (parentExpr instanceof ScalarValueExpression) { return false; } // By default, assume that the subquery must produce a single value. return true; } /** * Add a ScalarValueExpression on top of the SubqueryExpression * @param expr - subquery expression * @return ScalarValueExpression */ private static AbstractExpression addScalarValueExpression(SelectSubqueryExpression expr) { if (expr.getSubqueryScan().getOutputSchema().size() != 1) { throw new PlanningErrorException("Scalar subquery can have only one output column"); } expr.changeToScalarExprType(); AbstractExpression scalarExpr = new ScalarValueExpression(); scalarExpr.setLeft(expr); scalarExpr.setValueType(expr.getValueType()); scalarExpr.setValueSize(expr.getValueSize()); return scalarExpr; } /** * Evaluate/reduce/simplify an input expression at the compilation time * * @param expr Original Expression * @return AbstractExpression */ public static AbstractExpression evaluateExpression(AbstractExpression expr) { if (expr == null) { return null; } // Evaluate children first expr.setLeft(evaluateExpression(expr.getLeft())); expr.setRight(evaluateExpression(expr.getRight())); // Evaluate self if (ExpressionType.CONJUNCTION_AND == expr.getExpressionType()) { if (ExpressionType.VALUE_CONSTANT == expr.getLeft().getExpressionType()) { if (ConstantValueExpression.isBooleanTrue(expr.getLeft())) { return expr.getRight(); } else { return expr.getLeft(); } } if (ExpressionType.VALUE_CONSTANT == expr.getRight().getExpressionType()) { if (ConstantValueExpression.isBooleanTrue(expr.getRight())) { return expr.getLeft(); } else { return expr.getRight(); } } } else if (ExpressionType.CONJUNCTION_OR == expr.getExpressionType()) { if (ExpressionType.VALUE_CONSTANT == expr.getLeft().getExpressionType()) { if (ConstantValueExpression.isBooleanTrue(expr.getLeft())) { return expr.getLeft(); } else { return expr.getRight(); } } if (ExpressionType.VALUE_CONSTANT == expr.getRight().getExpressionType()) { if (ConstantValueExpression.isBooleanTrue(expr.getRight())) { return expr.getRight(); } else { return expr.getLeft(); } } } else if (ExpressionType.OPERATOR_NOT == expr.getExpressionType()) { AbstractExpression leftExpr = expr.getLeft(); // function expressions can also return boolean. So the left child expression // can be expression which are not constant value expressions, so don't // evaluate every left child expr as constant value expression if ((VoltType.BOOLEAN == leftExpr.getValueType()) && (leftExpr instanceof ConstantValueExpression)) { if (ConstantValueExpression.isBooleanTrue(leftExpr)) { return ConstantValueExpression.getFalse(); } else { return ConstantValueExpression.getTrue(); } } else if (ExpressionType.OPERATOR_NOT == leftExpr.getExpressionType()) { return leftExpr.getLeft(); } else if (ExpressionType.CONJUNCTION_OR == leftExpr.getExpressionType()) { // NOT (.. OR .. OR ..) => NOT(..) AND NOT(..) AND NOT(..) AbstractExpression l = new OperatorExpression(ExpressionType.OPERATOR_NOT, leftExpr.getLeft(), null); AbstractExpression r = new OperatorExpression(ExpressionType.OPERATOR_NOT, leftExpr.getRight(), null); leftExpr = new OperatorExpression(ExpressionType.CONJUNCTION_AND, l, r); return evaluateExpression(leftExpr); } // NOT (expr1 AND expr2) => (NOT expr1) || (NOT expr2) // The above case is probably not interesting to do for short circuit purpose } return expr; } }
agpl-3.0
almonteb/scoot
spec/controllers/searches_controller_spec.rb
1501
#-- # Copyright (C) 2008 Johan Sørensen <johan@johansorensen.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ require File.dirname(__FILE__) + '/../spec_helper' describe SearchesController do describe "#show" do it "searches for the given query" do searcher = mock("ultrasphinx search") Ultrasphinx::Search.expects(:new).with({ :query => "foo", :page => 1 }).returns(searcher) searcher.expects(:run) searcher.expects(:results).returns(results = mock("results")) get :show, :q => "foo" assigns["search"].should == searcher assigns["results"].should == results end it "doesnt search if there's no :q param" do Ultrasphinx::Search.expects(:new).never get :show, :q => "" assigns["search"].should == nil assigns["results"].should == nil end end end
agpl-3.0
rkfg/jbot
src/main/java/me/rkfg/xmpp/bot/plugins/game/command/RulesCommand.java
646
package me.rkfg.xmpp.bot.plugins.game.command; import java.util.Optional; import java.util.stream.Stream; import me.rkfg.xmpp.bot.plugins.game.IPlayer; public class RulesCommand extends AbstractCommand { @Override public String getCommand() { return "правила"; } @Override public Optional<String> exec(IPlayer player, Stream<String> args) { return Optional.of("Читайте правила на https://rkfg.me/sbr.html"); } @Override public boolean deadAllowed() { return true; } @Override public boolean pregameAllowed() { return true; } }
agpl-3.0
kingkino/Implem.Pleasanter
Implem.Pleasanter/Scripts/_Time.js
876
$p.dateAdd = function (type, num, date) { switch (type) { case 'd': return new Date(new Date(date).setDate(date.getDate() + num)); } } $p.dateDiff = function (type, date1, date2) { switch (type) { case 'd': return parseInt((date1 - date2) / 86400000); } } $p.shortDate = function (date) { if (date === undefined) date = new Date(); return new Date($p.shortDateString(date)); } $p.shortDateString = function (date) { if (date === undefined) date = new Date(); return date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate(); } $p.dateTimeString = function (date) { if (date === undefined) date = new Date(); return $p.shortDateString(date) + (date.getHours() + date.getMinutes() !== 0 ? ' ' + date.getHours() + ':' + date.getMinutes() : ''); }
agpl-3.0
o2oa/o2oa
o2server/x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/factory/BBSForumInfoFactory.java
4455
package com.x.bbs.assemble.control.factory; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import com.x.base.core.project.exception.ExceptionWhen; import com.x.base.core.project.tools.ListTools; import com.x.bbs.assemble.control.AbstractFactory; import com.x.bbs.assemble.control.Business; import com.x.bbs.entity.BBSForumInfo; import com.x.bbs.entity.BBSForumInfo_; /** * 类 名:BBSForumInfoFactory<br/> * 实体类:BBSForumInfo<br/> * 作 者:Liyi<br/> * 单 位:O2 Team<br/> * 日 期:2016-08-10 17:17:26 **/ public class BBSForumInfoFactory extends AbstractFactory { public BBSForumInfoFactory(Business business) throws Exception { super(business); } //@MethodDescribe( "获取指定Id的BBSForumInfo实体信息对象" ) public BBSForumInfo get( String id ) throws Exception { return this.entityManagerContainer().find( id, BBSForumInfo.class, ExceptionWhen.none ); } //@MethodDescribe( "列示指定Id的BBSForumInfo实体信息列表" ) public List<BBSForumInfo> list(List<String> ids) throws Exception { if( ids == null || ids.size() == 0 ){ return new ArrayList<BBSForumInfo>(); } EntityManager em = this.entityManagerContainer().get(BBSForumInfo.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<BBSForumInfo> cq = cb.createQuery(BBSForumInfo.class); Root<BBSForumInfo> root = cq.from(BBSForumInfo.class); Predicate p = root.get(BBSForumInfo_.id).in(ids); cq.orderBy( cb.asc( root.get( BBSForumInfo_.orderNumber ) ) ); return em.createQuery(cq.where(p)).setMaxResults( 1000 ).getResultList(); } //@MethodDescribe( "列示全部的BBSForumInfo实体信息列表" ) public List<BBSForumInfo> listAll() throws Exception { EntityManager em = this.entityManagerContainer().get(BBSForumInfo.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<BBSForumInfo> cq = cb.createQuery(BBSForumInfo.class); Root<BBSForumInfo> root = cq.from(BBSForumInfo.class); cq.orderBy( cb.asc( root.get( BBSForumInfo_.orderNumber ) ) ); return em.createQuery( cq ).setMaxResults( 1000 ).getResultList(); } //@MethodDescribe( "根据用户权限列示全部的BBSForumInfo实体信息列表" ) public List<BBSForumInfo> listAllViewAbleForumWithMyPermission( List<String> viewAbleForumIds ) throws Exception { EntityManager em = this.entityManagerContainer().get( BBSForumInfo.class ); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<BBSForumInfo> cq = cb.createQuery(BBSForumInfo.class); Root<BBSForumInfo> root = cq.from(BBSForumInfo.class); Predicate p = cb.equal( root.get( BBSForumInfo_.forumVisible ), "所有人" ); if( ListTools.isNotEmpty(viewAbleForumIds) ){ p = cb.or( p, root.get( BBSForumInfo_.id ).in( viewAbleForumIds ) ); } cq.orderBy( cb.asc( root.get( BBSForumInfo_.orderNumber ) ) ); return em.createQuery( cq.where(p) ).setMaxResults( 1000 ).getResultList(); } // @MethodDescribe( "列示全部可见性为所有人的BBSForumInfo实体信息ID列表" ) public List<String> listAllPublicForumIds() throws Exception { EntityManager em = this.entityManagerContainer().get( BBSForumInfo.class ); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<String> cq = cb.createQuery(String.class); Root<BBSForumInfo> root = cq.from(BBSForumInfo.class); Predicate p = cb.equal( root.get(BBSForumInfo_.forumStatus ), "启用" ); p = cb.and( p, cb.equal( root.get(BBSForumInfo_.forumVisible ), "所有人" ) ); cq.select( root.get( BBSForumInfo_.id ) ); return em.createQuery( cq.where(p) ).setMaxResults( 1000 ).getResultList(); } //@MethodDescribe( "列示已经启用的BBSForumInfo实体信息ID列表" ) public List<BBSForumInfo> listAllOpenForumInfo() throws Exception { EntityManager em = this.entityManagerContainer().get(BBSForumInfo.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<BBSForumInfo> cq = cb.createQuery(BBSForumInfo.class); Root<BBSForumInfo> root = cq.from(BBSForumInfo.class); Predicate p = cb.equal( root.get(BBSForumInfo_.forumStatus ), "启用" ); cq.orderBy( cb.asc( root.get( BBSForumInfo_.orderNumber ) ) ); return em.createQuery( cq.where(p) ).setMaxResults( 1000 ).getResultList(); } }
agpl-3.0
et304383/passbolt_api
app/webroot/js/lib/can/dist/cjs/view/stache/stache.js
10563
/*! * CanJS - 2.2.9 * http://canjs.com/ * Copyright (c) 2015 Bitovi * Fri, 11 Sep 2015 23:12:43 GMT * Licensed MIT */ /*can@2.2.9#view/stache/stache*/ var can = require('../../util/util.js'); var parser = require('../parser/parser.js'); var target = require('../target/target.js'); var HTMLSectionBuilder = require('./html_section.js'); var TextSectionBuilder = require('./text_section.js'); var mustacheCore = require('./mustache_core.js'); var mustacheHelpers = require('./mustache_helpers.js'); var getIntermediateAndImports = require('./intermediate_and_imports.js'); var viewCallbacks = require('../callbacks/callbacks.js'); require('../bindings/bindings.js'); parser = parser || can.view.parser; viewCallbacks = viewCallbacks || can.view.callbacks; var svgNamespace = 'http://www.w3.org/2000/svg'; var namespaces = { 'svg': svgNamespace, 'g': svgNamespace }; function stache(template) { if (typeof template === 'string') { template = mustacheCore.cleanLineEndings(template); } var section = new HTMLSectionBuilder(), state = { node: null, attr: null, sectionElementStack: [], text: false, namespaceStack: [] }, makeRendererAndUpdateSection = function (section, mode, stache) { if (mode === '>') { section.add(mustacheCore.makeLiveBindingPartialRenderer(stache, state)); } else if (mode === '/') { section.endSection(); if (section instanceof HTMLSectionBuilder) { state.sectionElementStack.pop(); } } else if (mode === 'else') { section.inverse(); } else { var makeRenderer = section instanceof HTMLSectionBuilder ? mustacheCore.makeLiveBindingBranchRenderer : mustacheCore.makeStringBranchRenderer; if (mode === '{' || mode === '&') { section.add(makeRenderer(null, stache, copyState())); } else if (mode === '#' || mode === '^') { section.startSection(makeRenderer(mode, stache, copyState())); if (section instanceof HTMLSectionBuilder) { state.sectionElementStack.push('section'); } } else { section.add(makeRenderer(null, stache, copyState({ text: true }))); } } }, copyState = function (overwrites) { var lastElement = state.sectionElementStack[state.sectionElementStack.length - 1]; var cur = { tag: state.node && state.node.tag, attr: state.attr && state.attr.name, directlyNested: state.sectionElementStack.length ? lastElement === 'section' || lastElement === 'custom' : true }; return overwrites ? can.simpleExtend(cur, overwrites) : cur; }, addAttributesCallback = function (node, callback) { if (!node.attributes) { node.attributes = []; } node.attributes.push(callback); }; parser(template, { start: function (tagName, unary) { var matchedNamespace = namespaces[tagName]; if (matchedNamespace && !unary) { state.namespaceStack.push(matchedNamespace); } state.node = { tag: tagName, children: [], namespace: matchedNamespace || can.last(state.namespaceStack) }; }, end: function (tagName, unary) { var isCustomTag = viewCallbacks.tag(tagName); if (unary) { section.add(state.node); if (isCustomTag) { addAttributesCallback(state.node, function (scope, options, parentNodeList) { viewCallbacks.tagHandler(this, tagName, { scope: scope, options: options, subtemplate: null, templateType: 'stache', parentNodeList: parentNodeList }); }); } } else { section.push(state.node); state.sectionElementStack.push(isCustomTag ? 'custom' : 'element'); if (isCustomTag) { section.startSubSection(); } } state.node = null; }, close: function (tagName) { var matchedNamespace = namespaces[tagName]; if (matchedNamespace) { state.namespaceStack.pop(); } var isCustomTag = viewCallbacks.tag(tagName), renderer; if (isCustomTag) { renderer = section.endSubSectionAndReturnRenderer(); } var oldNode = section.pop(); if (isCustomTag) { addAttributesCallback(oldNode, function (scope, options, parentNodeList) { viewCallbacks.tagHandler(this, tagName, { scope: scope, options: options, subtemplate: renderer, templateType: 'stache', parentNodeList: parentNodeList }); }); } state.sectionElementStack.pop(); }, attrStart: function (attrName) { if (state.node.section) { state.node.section.add(attrName + '="'); } else { state.attr = { name: attrName, value: '' }; } }, attrEnd: function (attrName) { if (state.node.section) { state.node.section.add('" '); } else { if (!state.node.attrs) { state.node.attrs = {}; } state.node.attrs[state.attr.name] = state.attr.section ? state.attr.section.compile(copyState()) : state.attr.value; var attrCallback = viewCallbacks.attr(attrName); if (attrCallback) { if (!state.node.attributes) { state.node.attributes = []; } state.node.attributes.push(function (scope, options) { attrCallback(this, { attributeName: attrName, scope: scope, options: options }); }); } state.attr = null; } }, attrValue: function (value) { var section = state.node.section || state.attr.section; if (section) { section.add(value); } else { state.attr.value += value; } }, chars: function (text) { section.add(text); }, special: function (text) { var firstAndText = mustacheCore.splitModeFromExpression(text, state), mode = firstAndText.mode, expression = firstAndText.expression; if (expression === 'else') { (state.attr && state.attr.section ? state.attr.section : section).inverse(); return; } if (mode === '!') { return; } if (state.node && state.node.section) { makeRendererAndUpdateSection(state.node.section, mode, expression); if (state.node.section.subSectionDepth() === 0) { state.node.attributes.push(state.node.section.compile(copyState())); delete state.node.section; } } else if (state.attr) { if (!state.attr.section) { state.attr.section = new TextSectionBuilder(); if (state.attr.value) { state.attr.section.add(state.attr.value); } } makeRendererAndUpdateSection(state.attr.section, mode, expression); } else if (state.node) { if (!state.node.attributes) { state.node.attributes = []; } if (!mode) { state.node.attributes.push(mustacheCore.makeLiveBindingBranchRenderer(null, expression, copyState())); } else if (mode === '#' || mode === '^') { if (!state.node.section) { state.node.section = new TextSectionBuilder(); } makeRendererAndUpdateSection(state.node.section, mode, expression); } else { throw new Error(mode + ' is currently not supported within a tag.'); } } else { makeRendererAndUpdateSection(section, mode, expression); } }, comment: function (text) { section.add({ comment: text }); }, done: function () { } }); return section.compile(); } var escMap = { '\n': '\\n', '\r': '\\r', '\u2028': '\\u2028', '\u2029': '\\u2029' }; var esc = function (string) { return ('' + string).replace(/["'\\\n\r\u2028\u2029]/g, function (character) { if ('\'"\\'.indexOf(character) >= 0) { return '\\' + character; } else { return escMap[character]; } }); }; can.view.register({ suffix: 'stache', contentType: 'x-stache-template', fragRenderer: function (id, text) { return stache(text); }, script: function (id, src) { return 'can.stache("' + esc(src) + '")'; } }); can.view.ext = '.stache'; can.extend(can.stache, mustacheHelpers); can.extend(stache, mustacheHelpers); can.stache.safeString = stache.safeString = function (text) { return { toString: function () { return text; } }; }; can.stache.async = function (source) { var iAi = getIntermediateAndImports(source); var importPromises = can.map(iAi.imports, function (moduleName) { return can['import'](moduleName); }); return can.when.apply(can, importPromises).then(function () { return stache(iAi.intermediate); }); }; module.exports = stache;
agpl-3.0
GrahamDeprecated/CMS-Core
src/Models/Relations/Interfaces/BelongsToPostInterface.php
1136
<?php /** * This file is part of CMS Core by Graham Campbell. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. */ namespace GrahamCampbell\CMSCore\Models\Relations\Interfaces; /** * This is the belongs to post interface. * * @package CMS-Core * @author Graham Campbell * @copyright Copyright (C) 2013-2014 Graham Campbell * @license https://github.com/GrahamCampbell/CMS-Core/blob/master/LICENSE.md * @link https://github.com/GrahamCampbell/CMS-Core */ interface BelongsToPostInterface { /** * Get the post relation. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function post(); }
agpl-3.0
iCloudWorkGroup/fengniao
test/test.js
2461
(function(root, factory) { if(typeof exports === 'object') { module.exports = factory(require, exports, module); } else if(typeof define === 'function' && define.amd) { define(['require', 'exports', 'module'], factory); } else { var req = function(id) {return root[id];}, exp = root, mod = {exports: exp}; root['extend'] = factory(req, exp, mod); } }(this, function(require, exports, module) { /** * @module extend */ /** * Inherit one class (constructor function) from another by using prototype inheritance. * Based on <code>extend</code> method from YUI library. * <br> * Set the following static fields for child class: * <ul> * <li><code>superconstructor</code> - reference to parent class * <li><code>superclass</code> - reference to <code>prototype</code> of parent class * </ul> * * @param {Function} SubClass * Child class that will inherit. * @param {Function} ParentClass * Parent class. * @return {Function} * Modified child class. */ function extend(SubClass, ParentClass) { "use strict"; function F() {} F.prototype = ParentClass.prototype; SubClass.prototype = new F(); SubClass.prototype.constructor = SubClass; SubClass.superclass = ParentClass.prototype; SubClass.superconstructor = ParentClass; return SubClass; } /** * Test whether the specified class is inherited from another. * * @param {Function} subClass * The class that should be tested. * @param {Function} parentClass * The parent class. * @return {Boolean} * <code>true</code>, if <code>subClass</code> is inherited from <code>parentClass</code>, * otherwise <code>false</code>. * @author Denis Sikuler * @see suifw#extend */ extend.isSubclass = function isSubclass(subClass, parentClass) { "use strict"; if (typeof parentClass === "function" && typeof subClass === "function") { var superClass = subClass; while (superClass = superClass.superconstructor) { if (superClass === parentClass) { return true; } } } return false; }; // Exports module.exports = extend; return extend; }));
agpl-3.0
richhl/kalturaCE
package/app/app/plugins/kaltura_internal_tools/admin/forms/SystemHelperResult.php
643
<?php class Form_SystemHelperResult extends Zend_Form { public function init() { // Set the method for the display form to POST $this->setMethod('post'); $this->setAttrib('class', 'inline-form'); $this->setAttrib('id', 'frmSystemHelperResults'); $this->addElement('textarea', 'results', array( 'label' => 'Results:', 'cols' => 48, 'rows' => 7, 'filters' => array('StringTrim'), )); $this->setDecorators(array( 'FormElements', array('HtmlTag', array('tag' => 'dl')), array('Description', array('placement' => 'prepend')), 'Fieldset', 'Form', )); } }
agpl-3.0
ProjetSigma/frontend
src/resources/group-field-value.ts
1083
import {Record} from 'utils/record'; import {GroupField} from './group-field'; import {Membership} from './membership'; export class GroupFieldValue extends Record { public id: number; public membership: Membership; public field: GroupField; public value: string; } // export const groupFieldValueSchema = new Schema({ // type: 'object', // properties: { // id: { type: 'integer' }, // name: { type: 'string' }, // type: { type: 'integer' }, // accept: { type: 'integer' }, // is_protected: { type: 'boolean' }, // multiple_values_allowed: { type: 'boolean' } // } // }); // export const groupFieldValueRelations = { // belongsTo: { // "membership": { // localKey: 'membership_id', // localField: 'membership' // }, // "group-field": { // localKey: 'field_id', // localField: 'field' // } // } // }; export const groupFieldValueRessource = { name: 'group-field-value', klass: GroupFieldValue };
agpl-3.0
cdparra/reminiscens-book
placebooks-webapp/src/placebooks/client/controllers/DelegateController.java
1134
package placebooks.client.controllers; public abstract class DelegateController<T> extends ControllerBase<T> implements SimpleController<T> { protected final SimpleController<?> controller; public DelegateController(final SimpleController<?> controller) { this.controller = controller; } @Override public void add(final ControllerStateListener listener) { controller.add(listener); } @Override public ControllerState getState() { return controller.getState(); } @Override public boolean hasLoaded() { return controller.hasLoaded(); } @Override public void load() { controller.load(); } @Override public void load(final String id) { controller.load(id); } @Override public void markChanged() { markChanged(true); } @Override public void markChanged(boolean refresh) { controller.markChanged(false); if(refresh) { fireChange(); } } @Override public void pause() { controller.pause(); } @Override public void refresh() { controller.refresh(); } @Override public void remove(final ControllerStateListener listener) { controller.add(listener); } }
agpl-3.0
pombredanne/discern
ml_grading/mock_ml_grading.py
485
def grade(grader_data,student_response): result_dict = {'errors': [],'tests': [],'score': 0, 'feedback' : "", 'success' : False, 'confidence' : 1} return result_dict def create(essay_text, scores, prompt): result_dict = {'errors': [],'success' : False, 'cv_kappa' : 0, 'cv_mean_absolute_error': 0, 'feature_ext' : "", 'classifier' : "", 'algorithm' : "C", 'score' : scores, 'text' : essay_text, 'prompt' : prompt, 's3_public_url' : 'blah'} return result_dict
agpl-3.0
shybyte/web-midi-patcher
src/effects/control-sequence-stepper.ts
917
import {MidiEvent} from '../midi-event'; import {MidiFilter} from '../midi-filter'; import {MidiOut} from '../midi-out'; import {Effect} from '../patch'; export interface ControlSequenceStepperProps { trigger: MidiFilter; resetFilter: MidiFilter; outputPortName: string; control: number, values: number[]; } export class ControlSequenceStepper implements Effect { private valueIndex = 0; constructor(private props: ControlSequenceStepperProps) { } async onMidiEvent(midiEvent: MidiEvent, midiOut: MidiOut) { const props = this.props; if (props.resetFilter(midiEvent)) { this.valueIndex = 0; } if (props.trigger(midiEvent)) { const value = props.values[this.valueIndex]; console.log('Send Value!', value); this.valueIndex = (this.valueIndex + 1) % props.values.length; midiOut.controlChange(props.outputPortName, props.control, value); } } }
agpl-3.0
bschiefer/sqlcoach
sqlcoach-persistence/src/main/java/de/sqlcoach/db/executionPlan/MaxDB.java
2049
/******************************************************************************* * This file is part of SQLCoach. * * SQLCoach is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SQLCoach is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package de.sqlcoach.db.executionPlan; import java.sql.Connection; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.sqlcoach.util.DBViewResultSet; import de.sqlcoach.util.ViewResultSet; /** * MaxDB class create explain and execute statement for database Sap DB * * @author Michael Paulus * @version 1.0 */ public class MaxDB extends Database{ private static final Logger LOG = LoggerFactory.getLogger(MaxDB.class); private static final String EXPLAIN = "explain "; public MaxDB() { LOG.debug("enter MaxDB"); } //TODO ViewResult, evtl. in Fasade public ViewResultSet explain(String query, Connection cn) { ViewResultSet viewResultSet = null; String sqlString = EXPLAIN + query; LOG.info("MPA sqlString:" + sqlString); viewResultSet = execute(sqlString, cn); return viewResultSet; } public ViewResultSet execute(String query, Connection cn) { ViewResultSet viewResultSet = null; try { viewResultSet = DBViewResultSet.get(cn, query); } catch (SQLException e) { LOG.error("SQLException: " + e); } return viewResultSet; } }
agpl-3.0
gw2efficiency/gw2-api.com
src/static/categories.js
1358
module.exports = { Armor: [0, { Boots: 0, Coat: 1, Gloves: 2, Helm: 3, HelmAquatic: 4, Leggings: 5, Shoulders: 6 }], Back: [1], Bag: [2], Consumable: [3, { AppearanceChange: 0, Booze: 1, ContractNpc: 2, Food: 3, Generic: 4, Halloween: 5, Immediate: 6, Transmutation: 7, Unlock: 8, UnTransmutation: 9, UpgradeRemoval: 10, Utility: 11, Unknown: 12 }], Container: [4, { Default: 0, GiftBox: 1, OpenUI: 2 }], CraftingMaterial: [5], Gathering: [6, { Foraging: 0, Logging: 1, Mining: 2 }], Gizmo: [7, { Default: 0, ContainerKey: 1, RentableContractNpc: 2, UnlimitedConsumable: 3 }], MiniPet: [8], Tool: [9, { Salvage: 0 }], Trait: [10], Trinket: [11, { Amulet: 0, Accessory: 1, Ring: 2 }], Trophy: [12], UpgradeComponent: [13, { Default: 0, Gem: 1, Rune: 2, Sigil: 3 }], Weapon: [14, { Axe: 0, Dagger: 1, Focus: 2, Greatsword: 3, Hammer: 4, Harpoon: 5, LargeBundle: 6, LongBow: 7, Mace: 8, Pistol: 9, Rifle: 10, Scepter: 11, Shield: 12, ShortBow: 13, SmallBundle: 14, Speargun: 15, Staff: 16, Sword: 17, Torch: 18, Toy: 19, Trident: 20, TwoHandedToy: 21, Warhorn: 22 }] }
agpl-3.0
lyoshenka/full-text-rss
admin/update.php
11562
<?php // Update site config files for Full-Text RSS // Author: Keyvan Minoukadeh // Copyright (c) 2014 Keyvan Minoukadeh // License: AGPLv3 // Date: 2013-05-02 // More info: http://fivefilters.org/content-only/ // Help: http://help.fivefilters.org /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ // Usage // ----- // * Access this file in your browser and follow the instructions to update your site config files. // * See section on automatic updates for a URL you can fetch periodically (e.g. with cron) to update site config files error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); @set_time_limit(120); //////////////////////////////// // Load config file //////////////////////////////// $admin_page = 'update'; require_once('../config.php'); require_once 'template.php'; tpl_header('Update site patterns'); ////////////////////////////////// // Username and password must be available ////////////////////////////////// if (!isset($options->admin_credentials) || $options->admin_credentials['username'] == '' || $options->admin_credentials['password'] == '') { header("X-Robots-Tag: noindex, nofollow", true); die('<h2>Username and password not set</h2><p>Full-Text RSS has not been configured with admin credentials.</p><p>If you are the administrator, please edit your <tt>custom_config.php</tt> file and enter the credentials in the appropriate section. When you\'ve done that, this page will prompt you for your admin credentials.</p>'); } $admin_hash = sha1($options->admin_credentials['username'].'+'.$options->admin_credentials['password']); $_self_host = $_SERVER['HTTP_HOST']; $_self_path = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\'); $self_update_url = 'http://'.htmlspecialchars($_self_host.$_self_path).'/update.php?key='.urlencode($admin_hash); $latest_remote = 'https://codeload.github.com/fivefilters/ftr-site-config/zip/master'; $version = @file_get_contents('../site_config/standard/version.txt'); ///////////////////////////////// // Check for update key ///////////////////////////////// if (!isset($_REQUEST['key']) || trim($_REQUEST['key']) == '') { require_once 'require_login.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { header('Location: update.php'); exit; } $auto = true; $no_auto_reasons = array(); if (!class_exists('ZipArchive')) { $auto = false; $no_auto_reasons[] = 'zip support (PHP\'s <a href="http://php.net/manual/en/zip.requirements.php">ZipArchive</a> class) is missing'; } if (!is_writable('../site_config')) { $auto = false; $no_auto_reasons[] = 'your <tt>site_config/</tt> folder is not writable - change permissions to 777 and try again.</p>'; } if (!file_exists('../site_config/standard/version.txt')) { die('Could not determine current version of your site pattern files (site_config/standard/version.txt). Make sure you\'re using at least version 3.2 of Full-Text RSS.'); } ?> <p>You have Full-Text RSS <strong><?php echo _FF_FTR_VERSION; ?></strong> (Site Patterns version: <strong><?php echo (isset($version) ? $version : 'Unknown'); ?></strong>) </p> <p>To see if you have the latest versions, <a href="http://fivefilters.org/content-only/latest_version.php?version=<?php echo urlencode(_FF_FTR_VERSION).'&site_config='.urlencode(@$version); ?>">check for updates</a>.</p> <?php if ($auto) { echo '<p>This update tool will attempt to fetch the latest site patterns from our <a href="https://github.com/fivefilters/ftr-site-config/">GitHub repository</a>.</p>'; echo '<p><strong>Important: </strong>if you\'ve modified or added your own config files in the <tt>site_config/standard/</tt> folder, please move them to <tt>site_config/custom/</tt> &mdash; the update process will attempt to replace everything in <tt>site_config/standard/</tt> with our updated version.</p>'; echo '<form method="post" action="update.php" class="well">'; echo '<input type="hidden" name="key" value="'.$admin_hash.'" />'; echo '<input type="submit" value="Update site config files" />'; echo '</form>'; echo '<h3>Automatic updates</h3>'; echo '<p>You can schedule automatic updates using something like cron. The URL to call is:</p>'; echo '<p class="well">'.$self_update_url.'</p>'; echo '<p>We recommend you schedule this URL to be fetched once a day. If you do not have access to a scheduling service '; echo 'you may want to consider one of these online services: <a href="http://www.easycron.com/">Easycron</a>, <a href="https://www.setcronjob.com/">SetCronJob</a>, <a href="http://www.onlinecronjobs.com/">onlinecronjobs.com</a>.</p>'; echo '<p>Note: the key contained in the URL is a hash value generated from your admin credentials. If you change these, the key will also change.</p>'; } else { echo '<div class="notice">'; echo '<p>We cannot automatically update your site pattern files because:</p>'; echo '<ul>'; foreach ($no_auto_reasons as $reason) { echo '<li>',$reason,'</li>'; } echo '</ul>'; echo '<p>You can still manually update by downloading the zip file and replacing everything in your <tt>site_config/standard/</tt> folder with the contents of the zip file.</p>'; echo '</div>'; echo '<p><a href="'.$latest_remote.'">Download site config files (zip)</a></p>'; } echo '<h3>Help</h3>'; echo '<p>If you have any trouble, please contact us via our <a href="http://help.fivefilters.org">support site</a>.</p>'; exit; } ////////////////////////////////// // Check update key valid ////////////////////////////////// if ($_REQUEST['key'] !== $admin_hash) { println("Sorry, invalid key supplied."); exit; } ////////////////////////////////// // Check for updates ////////////////////////////////// //$ff_version = @file_get_contents('http://fivefilters.org/content-only/site_config/standard/version.txt'); $_context = stream_context_create(array('http' => array('user_agent' => 'PHP/5.4'))); $latest_info_json = @file_get_contents('https://api.github.com/repos/fivefilters/ftr-site-config', false, $_context); if (!$latest_info_json) { println("Sorry, couldn't get info on latest site config files. Please try again later or contact us."); exit; } $latest_info_json = @json_decode($latest_info_json); if (!is_object($latest_info_json)) { println("Sorry, couldn't parse JSON from GitHub. Please try again later or contact us."); exit; } $ff_version = $latest_info_json->updated_at; if ($version == $ff_version) { die('Your site config files are up to date! If you have trouble extracting from a particular site, please email us: help@fivefilters.org'); } else { println("Updated site patterns are available (version $ff_version)..."); } ////////////////////////////////// // Prepare ////////////////////////////////// $tmp_latest_local = '../site_config/latest_site_config.zip'; $tmp_latest_local_dir = '../site_config/standard_latest'; $tmp_old_local_dir = '../site_config/standard_old'; if (file_exists($tmp_latest_local)) unlink($tmp_latest_local); if (file_exists($tmp_latest_local_dir)) { if (!rrmdir($tmp_latest_local_dir)) { println("Sorry, couldn't remove old folder from last update"); exit; } } if (file_exists($tmp_old_local_dir)) { rrmdir($tmp_old_local_dir); } $standard_local_dir = '../site_config/standard/'; //@copy($latest_remote, $tmp_latest_local); //copy() does not appear to fill $http_response_header in certain environments @file_put_contents($tmp_latest_local, @file_get_contents($latest_remote)); $headers = implode("\n", $http_response_header); //var_dump($headers); exit; if ((strpos($headers, 'HTTP/1.0 200') === false) && (strpos($headers, 'HTTP/1.1 200') === false)) { println("Sorry, something went wrong. Please contact us if the problem persists."); exit; } if (class_exists('ZipArchive') && file_exists($tmp_latest_local)) { println("Downloaded latest copy of the site pattern files to $tmp_latest_local"); $zip = new ZipArchive; if ($zip->open($tmp_latest_local) === TRUE) { $zip->extractTo($tmp_latest_local_dir); $zip->close(); @unlink($tmp_latest_local); if (file_exists($tmp_latest_local_dir)) { println("Unzipped contents to $tmp_latest_local_dir"); if (!file_exists($tmp_latest_local_dir.'/ftr-site-config-master/README.md')) { println("There was a problem extracting the latest site patterns archive - your current site patterns remain untouched."); println("Please <a href=\"$latest_remote\">update manually</a>."); exit; } @file_put_contents($tmp_latest_local_dir.'/ftr-site-config-master/version.txt', $ff_version); if (!file_exists($tmp_latest_local_dir.'/ftr-site-config-master/version.txt')) { println("There was a problem writing the new version number - your current site patterns remain untouched."); println("Please <a href=\"$latest_remote\">update manually</a>."); exit; } rename($standard_local_dir, $tmp_old_local_dir); if (file_exists($tmp_old_local_dir)) println("Renamed $standard_local_dir to $tmp_old_local_dir"); rename($tmp_latest_local_dir."/ftr-site-config-master", $standard_local_dir); if (file_exists($standard_local_dir)) println("Renamed $tmp_latest_local_dir/ftr-site-config-master to $standard_local_dir"); rmdir($tmp_latest_local_dir); // clear cached site config files from APC if ($options->apc && function_exists('apc_delete') && function_exists('apc_cache_info')) { $_apc_data = apc_cache_info('user'); foreach ($_apc_data['cache_list'] as $_apc_item) { // APCu keys incompatible with original APC keys, apparently fixed in newer versions, but not in 4.0.4 // So let's look for those keys and fix here (key -> info). if (isset($_apc_item['key'])) $_apc_item['info'] = $_apc_item['key']; if (substr($_apc_item['info'], 0, 3) == 'sc.') { apc_delete($_apc_item['info']); } } println('Cleared site config cache in APC.'); } // all done! println("<strong style=\"color: darkgreen;\">All done!</strong> Your old site config files are in $tmp_old_local_dir &mdash; these will be removed next time you go through the update process."); } else { if (file_exists($tmp_latest_local)) @unlink($tmp_latest_local); println("Failed to unzip to $tmp_latest_local_dir - your current site patterns remain untouched"); } } else { if (file_exists($tmp_latest_local)) @unlink($tmp_latest_local); println("Failed to extract from $tmp_latest_local - your current site patterns remain untouched"); } } else { println("Could not download the latest site config files. Please <a href=\"$latest_remote\">update manually</a> - your current site patterns remain untouched."); } function println($txt) { echo $txt,"<br />\n"; ob_end_flush(); ob_flush(); flush(); } function rrmdir($dir) { foreach(glob($dir . '/{*.txt,*.php,.*.txt,.*.php,.gitattributes,.gitignore,ftr-site-config-master,README.md}', GLOB_BRACE|GLOB_NOSORT) as $file) { if(is_dir($file)) { rrmdir($file); } else { unlink($file); } } return rmdir($dir); }
agpl-3.0
splicemachine/spliceengine
splice_machine/src/main/java/com/splicemachine/derby/impl/sql/execute/operations/WindowOperation.java
6449
/* * Copyright (c) 2012 - 2020 Splice Machine, Inc. * * This file is part of Splice Machine. * Splice Machine is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either * version 3, or (at your option) any later version. * Splice Machine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with Splice Machine. * If not, see <http://www.gnu.org/licenses/>. */ package com.splicemachine.derby.impl.sql.execute.operations; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.splicemachine.derby.stream.function.CloneFunction; import com.splicemachine.si.api.txn.TxnView; import splice.com.google.common.base.Strings; import com.splicemachine.db.iapi.error.StandardException; import com.splicemachine.db.iapi.services.loader.GeneratedMethod; import com.splicemachine.db.iapi.sql.Activation; import com.splicemachine.db.iapi.sql.execute.ExecRow; import com.splicemachine.derby.stream.iapi.DataSet; import com.splicemachine.derby.stream.iapi.DataSetProcessor; import com.splicemachine.derby.stream.iapi.OperationContext; import org.apache.log4j.Logger; import com.splicemachine.derby.iapi.sql.execute.SpliceOperation; import com.splicemachine.derby.iapi.sql.execute.SpliceOperationContext; import com.splicemachine.derby.impl.sql.execute.operations.window.DerbyWindowContext; import com.splicemachine.derby.impl.sql.execute.operations.window.WindowContext; import com.splicemachine.utils.SpliceLogUtils; /** * * A Window operation is a three step process. * * Step 1: Read from source and write to temp buckets with extraUniqueSequenceID prefix * (Not needed in the case that data is sorted). The rows are sorted by (partition, orderBy) columns from * over clause. * * Step 2: compute window functions in parallel and write results to temp using uniqueSequenceID prefix. * * Step 3: scan results produced by step 2. */ public class WindowOperation extends SpliceBaseOperation { private static final long serialVersionUID = 1l; private static Logger LOG = Logger.getLogger(WindowOperation.class); protected boolean isInSortedOrder; private WindowContext windowContext; protected SpliceOperation source; protected ExecRow sortTemplateRow; private ExecRow templateRow; protected static final String NAME = WindowOperation.class.getSimpleName().replaceAll("Operation",""); @Override public String getName() { return NAME; } public WindowOperation() {} public WindowOperation( SpliceOperation source, boolean isInSortedOrder, int aggregateItem, Activation activation, GeneratedMethod rowAllocator, int resultSetNumber, double optimizerEstimatedRowCount, double optimizerEstimatedCost) throws StandardException { super(activation, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost); this.source = source; this.isInSortedOrder = isInSortedOrder; this.windowContext = new DerbyWindowContext((rowAllocator==null? null:rowAllocator.getMethodName()), aggregateItem); } public SpliceOperation getSource() { return this.source; } @Override public void init(SpliceOperationContext context) throws StandardException, IOException { SpliceLogUtils.trace(LOG, "init called"); super.init(context); if (source != null) { source.init(context); } windowContext.init(context); sortTemplateRow = windowContext.getSortTemplateRow(); templateRow = windowContext.getSourceIndexRow(); } @Override public DataSet<ExecRow> getDataSet(DataSetProcessor dsp) throws StandardException { if (!isOpen) throw new IllegalStateException("Operation is not open"); OperationContext<WindowOperation> operationContext = dsp.createOperationContext(this); operationContext.pushScopeForOp(OperationContext.Scope.WINDOW); dsp.incrementOpDepth(); DataSet<ExecRow> sourceDataSet = source.getDataSet(dsp); dsp.decrementOpDepth(); DataSet<ExecRow> dataSet = sourceDataSet.map(new CloneFunction<>(operationContext)); operationContext.popScope(); try { dataSet = dataSet.windows(windowContext,operationContext,true, OperationContext.Scope.EXECUTE.displayName()); handleSparkExplain(dataSet, sourceDataSet, dsp); } finally { operationContext.popScope(); } return dataSet; } @Override public ExecRow getExecRowDefinition() { return templateRow; } @Override public String toString() { return "WindowOperation{"+windowContext+"}"; } @Override public String prettyPrint(int indentLevel) { String indent = "\n"+ Strings.repeat("\t", indentLevel); return "Window:" + indent + "resultSetNumber:" + operationInformation.getResultSetNumber() + indent + "source:" + source.prettyPrint(indentLevel + 1); } @Override public int[] getRootAccessedCols(long tableNumber) throws StandardException { if(source != null && source.isReferencingTable(tableNumber)) return source.getRootAccessedCols(tableNumber); return null; } @Override public boolean isReferencingTable(long tableNumber) { return source.isReferencingTable(tableNumber); } @Override public List<SpliceOperation> getSubOperations() { List<SpliceOperation> operations = new ArrayList<SpliceOperation>(); operations.add(source); return operations; } @Override public SpliceOperation getLeftOperation() { return this.source; } public WindowContext getWindowContext() { return windowContext; } public String getScopeName() { return "Window Function"; } @Override public TxnView getCurrentTransaction() throws StandardException{ return source.getCurrentTransaction(); } }
agpl-3.0
stsouko/naivemapper
NaiveMapper/ValFix.py
1955
import time class ValFix(object): def getMap(self, s_graph, p_graph, _map, matrix, weights): self.__time = time.perf_counter() self.__cost, self.new_map = 0, dict() twins = {x: set(m.loc[lambda m_row: abs(m_row - c) < .0000001].index.tolist()) for x, m, c in ((x, matrix[x], matrix.loc[y, x]) for y, x in _map.items())} def dinamic_bonds(c, s_edge, p_edge, s_implicit_h, p_implicit_h, maps): ms, mp = set(maps.keys()) & set(s_edge.keys()), set(maps.values()) & set(p_edge.keys()) mps = set([s for s, p in maps.items() if p in mp]) c += weights[0]*len(ms ^ mps) c += weights[1]*abs(sum([s_edge[i]['s_bond'] for i in ms]) - sum([p_edge[j]['s_bond'] for j in mp])) c += weights[2]*abs(s_implicit_h - p_implicit_h) return c def dfs(s_atom, n_map, c): for p_atom in sorted(twins[s_atom]-set(n_map.values())): c = dinamic_bonds(c, s_graph.adj[s_atom], p_graph.adj[p_atom], s_graph.atom_implicit_h(s_atom), p_graph.atom_implicit_h(p_atom), n_map) if c < self.__cost: n_map[s_atom] = p_atom atom = next((x for x in twins if x not in n_map), False) t = time.perf_counter() - self.__time if atom and t < 30.0: dfs(atom, n_map.copy(), c) elif t < 30.0 and len(n_map) == len(self.new_map): self.new_map = n_map self.__cost = c for p, s in _map.items(): self.new_map[s] = p self.__cost = dinamic_bonds(self.__cost, s_graph.adj[s], p_graph.adj[p], s_graph.atom_implicit_h(s), p_graph.atom_implicit_h(p), self.new_map) dfs(min(twins), dict(), 0) return {p: s for s, p in self.new_map.items()}
agpl-3.0
vimsvarcode/elmis
modules/odk-api/src/main/java/org/openlmis/odkapi/parser/ODKProofOfDeliveryXFormBuilder.java
14540
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. *   * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.  */ /** * Created with IntelliJ IDEA. * User: Messay Yohannes <deliasmes@gmail.com> * To change this template use File | Settings | File Templates. */ package org.openlmis.odkapi.parser; import org.openlmis.rnr.domain.RnrLineItem; import java.util.List; public class ODKProofOfDeliveryXFormBuilder { private StringBuilder xformStringBuilder; public String buildXForm(String facilityName, String programAbbreviation, String periodString,List<RnrLineItem> listOfRequisitionItems) { int sizeOfList = listOfRequisitionItems.size(); int itemCount = 0; xformStringBuilder = new StringBuilder(); xformStringBuilder.append("<h:html xmlns=\"http://www.w3.org/2002/xforms\" xmlns:h=\"http://www.w3.org/1999/xhtml\" xmlns:ev=\"http://www.w3.org/2001/xml-events\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:jr=\"http://openrosa.org/javarosa\">\n" + "\t<h:head>\n" + "\t\t<h:title>Proof of Delivery SurveyV2</h:title>\n" + "\t\t<model>\n" + "\t\t\t<instance>\n" + "\t\t\t\t<data id=\""); xformStringBuilder.append(facilityName + "-" + programAbbreviation + "-" + periodString +"\">"); xformStringBuilder.append("<meta>\n" + "\t\t\t\t\t\t<instanceID/>\n" + "\t\t\t\t\t</meta>\n" + "\t\t\t\t\t<itemName/>"); // add the data and instance section for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<proof_of_delivery_survey_" + itemCount + ">"); xformStringBuilder.append("<quantityToDeliver>" + lineItem.getQuantityRequested() + "</quantityToDeliver>"); xformStringBuilder.append("<allQuantityDelivered/>"); xformStringBuilder.append("<actualQuantityDelivered/>"); xformStringBuilder.append("<discrepancyAmount/>"); xformStringBuilder.append("<commentForShortfallItem/>"); xformStringBuilder.append("<firstPictureOfDeliveredCartoons/>"); xformStringBuilder.append("<secondPictureOfDeliveredCartoons/>"); xformStringBuilder.append("<thirdPictureOfDeliveredCartoons/>"); xformStringBuilder.append("<reveivedBy/>"); xformStringBuilder.append("</proof_of_delivery_survey_" + itemCount + ">"); itemCount ++; } // add the device id xformStringBuilder.append("<deviceID/>"); // add end of data and instance xformStringBuilder.append("</data>\n" + "\t\t\t</instance>"); // add itext section xformStringBuilder.append("<itext>\n" + "\t\t\t\t<translation lang=\"eng\">"); // add the item name and option values itemCount = 0; xformStringBuilder.append("<text id=\"/data/itemName:label\">"); xformStringBuilder.append("<value>Item Name </value> </text>"); for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<text id=\"/data/itemName:option"+itemCount+"\">"); xformStringBuilder.append("<value>" + lineItem.getProduct()+ "</value> </text>"); itemCount ++; } itemCount = 0; for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+":label\">"); xformStringBuilder.append("<value>" + lineItem.getProduct() + "</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/quantityToDeliver:label\">"); xformStringBuilder.append("<value>Quantity To Deliver</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered:label\">"); xformStringBuilder.append("<value>All quantity Delivered ?</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered:option0\">"); xformStringBuilder.append("<value>Yes</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered:option1\">"); xformStringBuilder.append("<value>No</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/actualQuantityDelivered:label\">"); xformStringBuilder.append("<value>Actual Delivered Quantity</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/discrepancyAmount:label\">"); xformStringBuilder.append("<value>Discrepancy Amount</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/commentForShortfallItem:label\">"); xformStringBuilder.append("<value>Comment For Shortfall</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/firstPictureOfDeliveredCartoons:label\">"); xformStringBuilder.append("<value>First Picture of Delivered Cartoons</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/secondPictureOfDeliveredCartoons:label\">"); xformStringBuilder.append("<value>Second Picture of Delivered Cartoons</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/thirdPictureOfDeliveredCartoons:label\">"); xformStringBuilder.append("<value>Third Picture of Delivered Cartoons</value> </text>"); xformStringBuilder.append("<text id=\"/data/proof_of_delivery_survey_"+itemCount+"/reveivedBy:label\">"); xformStringBuilder.append("<value>Received By</value> </text>"); itemCount++; } // add end of itext section xformStringBuilder.append("</translation>\n" + "\t\t\t</itext>"); itemCount = 0; // add the bind section xformStringBuilder.append("<bind nodeset=\"/data/meta/instanceID\" type=\"string\" readonly=\"true()\" calculate=\"concat('uuid:', uuid())\"/>"); xformStringBuilder.append("<bind nodeset=\"/data/itemName\" type=\"select1\" required=\"true()\"/>"); for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"\" relevant=\"(/data/itemName = '"+lineItem.getProductCode()+"')\"/>"); itemCount ++; } itemCount = 0; for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/quantityToDeliver\" type=\"int\" readonly=\"true()\" />"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered\" type=\"select1\" required=\"true()\" />"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/actualQuantityDelivered\" type=\"int\" required=\"true()\" relevant=\"(/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered = 'No')\"/>"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/discrepancyAmount\" type=\"int\" required=\"true()\" relevant=\"(/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered = 'No')\"/>"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/commentForShortfallItem\" type=\"string\" required=\"true()\" relevant=\"(/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered = 'No')\"/>"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/firstPictureOfDeliveredCartoons\" type=\"binary\" />"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/secondPictureOfDeliveredCartoons\" type=\"binary\" />"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/thirdPictureOfDeliveredCartoons\" type=\"binary\" />"); xformStringBuilder.append("<bind nodeset=\"/data/proof_of_delivery_survey_"+itemCount+"/reveivedBy\" type=\"string\" required=\"true()\"/>"); itemCount ++; } // add the bind for the device id xformStringBuilder.append("<bind nodeset=\"/data/deviceID\" type=\"string\" jr:preload=\"property\" jr:preloadParams=\"deviceid\"/>"); // close model and head xformStringBuilder.append("</model>\n" + "\t</h:head>"); // start the body part itemCount = 0; xformStringBuilder.append("<h:body>"); // add the item name and option values xformStringBuilder.append("<select1 ref=\"/data/itemName\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/itemName:label')\"/>"); for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<item>\n" + "\t\t\t\t\t<label ref=\"jr:itext('/data/itemName:option"+itemCount+"')\"/>"); xformStringBuilder.append("<value>" +lineItem.getProductCode() + "</value> </item>"); itemCount ++; } xformStringBuilder.append(" </select1>"); // start adding the group itemCount = 0; for(RnrLineItem lineItem :listOfRequisitionItems) { xformStringBuilder.append("<group>"); xformStringBuilder.append("<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+":label')\"/>"); xformStringBuilder.append("<input ref=\"/data/proof_of_delivery_survey_"+itemCount+"/quantityToDeliver\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/quantityToDeliver:label')\"/>\n" + "\t\t\t</input>"); xformStringBuilder.append("<select1 ref=\"/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered:label')\"/>\n" + "\t\t\t\t<item>\n" + "\t\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered:option0')\"/>\n" + "\t\t\t\t\t<value>Yes</value>\n" + "\t\t\t\t</item>\n" + "\t\t\t\t<item>\n" + "\t\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/allQuantityDelivered:option1')\"/>\n" + "\t\t\t\t\t<value>No</value>\n" + "\t\t\t\t</item>\n" + "\t\t\t</select1>"); xformStringBuilder.append("<input ref=\"/data/proof_of_delivery_survey_"+itemCount+"/actualQuantityDelivered\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/actualQuantityDelivered:label')\"/>\n" + "\t\t\t</input>"); xformStringBuilder.append("<input ref=\"/data/proof_of_delivery_survey_"+itemCount+"/discrepancyAmount\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/discrepancyAmount:label')\"/>\n" + "\t\t\t</input>"); xformStringBuilder.append("<input ref=\"/data/proof_of_delivery_survey_"+itemCount+"/commentForShortfallItem\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/commentForShortfallItem:label')\"/>\n" + "\t\t\t</input>"); xformStringBuilder.append("<upload ref=\"/data/proof_of_delivery_survey_"+itemCount+"/firstPictureOfDeliveredCartoons\" mediatype=\"image/*\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/firstPictureOfDeliveredCartoons:label')\"/>\n" + "\t\t\t</upload>"); xformStringBuilder.append("<upload ref=\"/data/proof_of_delivery_survey_"+itemCount+"/secondPictureOfDeliveredCartoons\" mediatype=\"image/*\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/secondPictureOfDeliveredCartoons:label')\"/>\n" + "\t\t\t</upload>"); xformStringBuilder.append("<upload ref=\"/data/proof_of_delivery_survey_"+itemCount+"/thirdPictureOfDeliveredCartoons\" mediatype=\"image/*\">\n" + "\t\t\t\t<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/thirdPictureOfDeliveredCartoons:label')\"/>\n" + "\t\t\t</upload>"); xformStringBuilder.append("<input ref=\"/data/proof_of_delivery_survey_"+itemCount+"/reveivedBy\">"); xformStringBuilder.append("<label ref=\"jr:itext('/data/proof_of_delivery_survey_"+itemCount+"/reveivedBy:label')\"/> </input>"); xformStringBuilder.append("</group>"); itemCount ++; } // end the body and document xformStringBuilder.append("</h:body> </h:html>"); return xformStringBuilder.toString(); } }
agpl-3.0
afshinnj/php-mvc
assets/framework/ckeditor/plugins/newpage/lang/lt.js
231
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'newpage', 'lt', { toolbar: 'Naujas puslapis' } );
agpl-3.0
jpajuelo/wirecloud
src/wirecloud/platform/wiring/utils.py
9474
# -*- coding: utf-8 -*- # Copyright (c) 2012-2016 CoNWeT Lab., Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # Wirecloud is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with Wirecloud. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from io import BytesIO from django.conf import settings from django.template import loader, Context, Template from lxml import etree from wirecloud.commons.utils.http import get_absolute_static_url, get_current_domain from wirecloud.platform.plugins import get_operator_api_extensions def has_component(endpoint, component_id, component_type): c_type, c_id, e_name = tuple(endpoint.split('/')) return c_type == component_type and c_id == component_id def is_component(connection, endpoint_type, component_type, component_id): return connection[endpoint_type]['type'] == component_type and connection[endpoint_type]['id'] == component_id def remove_related_iwidget_connections(wiring, iwidget): removed_connections = [] for i, connection in enumerate(wiring['connections']): if is_component(connection, 'source', 'widget', iwidget.id) or is_component(connection, 'target', 'widget', iwidget.id): removed_connections.append(connection) if 'visualdescription' in wiring: if 'connections' in wiring['visualdescription']: removed_visual_connections = [] for connection in wiring['visualdescription']['connections']: if has_component(connection['sourcename'], iwidget.id, 'widget') or has_component(connection['targetname'], iwidget.id, 'widget'): removed_visual_connections.append(connection) for connection in removed_visual_connections: wiring['visualdescription']['connections'].remove(connection) for connection in removed_connections: wiring['connections'].remove(connection) def get_operator_cache_key(operator, domain, mode): return '_operator_xhtml/%s/%s/%s?mode=%s' % (operator.cache_version, domain, operator.id, mode) def get_operator_api_files(request): from django.core.cache import cache from wirecloud.platform.core.plugins import get_version_hash key = 'operator_api_files/%s?v=%s' % (get_current_domain(request), get_version_hash()) operator_api_files = cache.get(key) if operator_api_files is None or settings.DEBUG is True: code = '''{% load compress %}{% load static from staticfiles %}{% compress js %} <script type="text/javascript" src="{% static "js/WirecloudAPI/WirecloudAPIBootstrap.js" %}"></script> <script type="text/javascript" src="{% static "js/WirecloudAPI/WirecloudOperatorAPI.js" %}"></script> <script type="text/javascript" src="{% static "js/WirecloudAPI/WirecloudAPICommon.js" %}"></script> {% endcompress %}''' result = Template(code).render(Context({})) doc = etree.parse(BytesIO(('<files>' + result + '</files>').encode('utf-8')), etree.XMLParser()) files = [script.get('src') for script in doc.getroot()] operator_api_files = tuple([get_absolute_static_url(file, request=request, versioned=True) for file in files]) cache.set(key, operator_api_files) return list(operator_api_files) def generate_xhtml_operator_code(js_files, base_url, request, requirements, mode): api_closure_url = get_absolute_static_url('js/WirecloudAPI/WirecloudAPIClosure.js', request=request, versioned=True) extra_api_js_files = [get_absolute_static_url(url, request=request, versioned=True) for url in get_operator_api_extensions(mode, requirements)] api_js = get_operator_api_files(request) + extra_api_js_files + [api_closure_url] t = loader.get_template('wirecloud/operator_xhtml.html') c = Context({'base_url': base_url, 'js_files': api_js + js_files}) xhtml = t.render(c) return xhtml def get_endpoint_name(endpoint): return "%s/%s/%s" % (endpoint['type'], endpoint['id'], endpoint['endpoint']) def rename_component_type(component_type): return component_type[1:] if component_type in ['iwidget', 'ioperator'] else "not_supported" def get_behaviour_skeleton(): return { 'title': None, 'description': None, 'components': { 'operator': {}, 'widget': {} }, 'connections': [] } def get_wiring_skeleton(): return { 'version': "2.0", 'connections': [], 'operators': {}, 'visualdescription': { 'behaviours': [], 'components': { 'operator': {}, 'widget': {} }, 'connections': [] } } def is_empty_wiring(visualInfo): return len(visualInfo['connections']) == 0 and len(visualInfo['components']['operator']) == 0 and len(visualInfo['components']['widget']) == 0 def parse_wiring_old_version(wiring_status): # set the structure for version 2.0 new_version = get_wiring_skeleton() # set up business description for operator_id, operator in wiring_status.get('operators', {}).items(): for preference_id, preference in operator.get('preferences', {}).items(): if 'readOnly' in preference and 'readonly' not in preference: preference['readonly'] = preference['readOnly'] if 'readOnly' in preference: del preference['readOnly'] new_version['operators'][operator_id] = operator for connection in wiring_status.get('connections', []): new_version['connections'].append({ 'readonly': connection.get('readonly', connection.get('readOnly', False)), 'source': { 'type': rename_component_type(connection['source']['type']), 'id': connection['source']['id'], 'endpoint': connection['source']['endpoint'] }, 'target': { 'type': rename_component_type(connection['target']['type']), 'id': connection['target']['id'], 'endpoint': connection['target']['endpoint'] } }) # set up visual description if 'views' in wiring_status and len(wiring_status['views']) > 0: old_view = wiring_status['views'][0] # rebuild connections connections_length = len(new_version['connections']) for connection_index, connection_view in enumerate(old_view.get('connections', [])): if connection_index < connections_length: # get connection info from business part connection = new_version['connections'][connection_index] # set info into global behaviour new_version['visualdescription']['connections'].append({ 'sourcename': get_endpoint_name(connection['source']), 'sourcehandle': { 'x': connection_view['pullerStart']['posX'], 'y': connection_view['pullerStart']['posY'] }, 'targetname': get_endpoint_name(connection['target']), 'targethandle': { 'x': connection_view['pullerEnd']['posX'], 'y': connection_view['pullerEnd']['posY'] }, }) # rebuild operators for operator_id, operator in old_view['operators'].items(): if operator_id in new_version['operators']: # set info into global behaviour visualInfo = {} visualInfo['collapsed'] = operator.get('minimized', False) visualInfo['position'] = { 'x': operator['position']['posX'], 'y': operator['position']['posY'] } if 'endPointsInOuts' in operator: visualInfo['endpoints'] = { 'source': operator['endPointsInOuts']['sources'], 'target': operator['endPointsInOuts']['targets'] } new_version['visualdescription']['components']['operator'][operator_id] = visualInfo # rebuild widgets for widget_id, widget in old_view['iwidgets'].items(): # set info into global behaviour new_version['visualdescription']['components']['widget'][widget_id] = { 'endpoints': { 'source': widget['endPointsInOuts']['sources'], 'target': widget['endPointsInOuts']['targets'] }, 'position': { 'x': widget['position']['posX'], 'y': widget['position']['posY'] } } if 'name' in widget: new_version['visualdescription']['components']['widget'][widget_id]['name'] = widget['name'] return new_version
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/impl/IfcControllerImpl.java
3610
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bimserver.models.ifc4.impl; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.bimserver.models.ifc4.Ifc4Package; import org.bimserver.models.ifc4.IfcController; import org.bimserver.models.ifc4.IfcControllerTypeEnum; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Controller</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.bimserver.models.ifc4.impl.IfcControllerImpl#getPredefinedType <em>Predefined Type</em>}</li> * </ul> * * @generated */ public class IfcControllerImpl extends IfcDistributionControlElementImpl implements IfcController { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcControllerImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_CONTROLLER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IfcControllerTypeEnum getPredefinedType() { return (IfcControllerTypeEnum) eGet(Ifc4Package.Literals.IFC_CONTROLLER__PREDEFINED_TYPE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setPredefinedType(IfcControllerTypeEnum newPredefinedType) { eSet(Ifc4Package.Literals.IFC_CONTROLLER__PREDEFINED_TYPE, newPredefinedType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetPredefinedType() { eUnset(Ifc4Package.Literals.IFC_CONTROLLER__PREDEFINED_TYPE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetPredefinedType() { return eIsSet(Ifc4Package.Literals.IFC_CONTROLLER__PREDEFINED_TYPE); } } //IfcControllerImpl
agpl-3.0
hwjworld/xiaodun-canvas
gems/lti_outbound/spec/spec_helper.rb
960
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration require 'lti_outbound' Dir.glob("#{File.dirname(__FILE__).gsub(/\\/, "/")}/shared_examples/*.rb").each { |file| require file } Dir.glob("#{File.dirname(__FILE__).gsub(/\\/, "/")}/support/*.rb").each { |file| require file } RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' end
agpl-3.0
XGTeam/HoumaChuangYeDaSai
app/Presenters/OwnerPresenterTrait.php
705
<?php /* * This file is part of Bootstrap CMS. * * (c) Graham Campbell <graham@alt-three.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\BootstrapCMS\Presenters; /** * This is the owner presenter trait. * * @author Graham Campbell <graham@alt-three.com> */ trait OwnerPresenterTrait { /** * Get the owner. * * @return string */ public function owner() { $user = $this->getWrappedObject()->user()->withTrashed()->first(['first_name', 'last_name', 'email']); return $user->last_name.$user->first_name.' ('.$user->email.')'; } }
agpl-3.0
MiguelSMendoza/Kunagi
WEB-INF/classes/ilarkesto/mda/legacy/model/CompositeModel.java
1061
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package ilarkesto.mda.legacy.model; public class CompositeModel extends AModel { private String type; public CompositeModel(String type, String name) { super(name); this.type = type; } public String getType() { return type; } @Override public String toString() { return getName() + ":" + getType(); } }
agpl-3.0
madhuni/AstroBox
src/astroprint/static/js/app/views/home.js
1402
/* Commenting the below initialization code as we are not using the Uploading feature in new UI */ var HomeView = Backbone.View.extend({ el: '#home-view', uploadBtn: null, events: { 'show': 'onShow', 'click .new-release a.check': 'onReleaseInfoClicked', 'click .new-release a.close': 'onCloseReleaseInfoClicked' }, initialize: function() { this.listenTo(app.printerProfile, 'change:driver', this.onDriverChanged); this.onDriverChanged(app.printerProfile, app.printerProfile.get('driver')); this.listenTo(app.socketData, 'new_sw_release', _.bind(function(data){ this.$('.new-release .version-label').text(data.release.major+'.'+data.release.minor+'('+data.release.build+')'); this.$('.new-release').removeClass('hide'); }, this)); }, onDriverChanged: function(model, newDriver) { if (newDriver == 'marlin') { this.$("#app-container ul li.gcode-terminal-app-icon").removeClass('hide'); } else { this.$("#app-container ul li.gcode-terminal-app-icon").addClass('hide'); } }, onReleaseInfoClicked: function(e) { e.preventDefault(); if (!app.router.settingsView) { app.router.settingsView = new SettingsView(); } app.router.settingsView.subviews['software-update'].onCheckClicked(e); }, onCloseReleaseInfoClicked: function(e) { e.preventDefault(); this.$('.new-release').remove() } });
agpl-3.0
Micah-S/hidden-ms
src/src/net/sf/odinms/provider/MapleData.java
357
package net.sf.odinms.provider; import java.util.List; import net.sf.odinms.provider.wz.MapleDataType; public interface MapleData extends MapleDataEntity, Iterable<MapleData> { public String getName(); public MapleDataType getType(); public List<MapleData> getChildren(); public MapleData getChildByPath(String path); public Object getData(); }
agpl-3.0
RestComm/jss7
map/map-impl/src/test/java/org/restcomm/protocols/ss7/map/service/mobility/subscriberInformation/CallWaitingDataTest.java
3236
package org.restcomm.protocols.ss7.map.service.mobility.subscriberInformation; import org.mobicents.protocols.asn.AsnInputStream; import org.mobicents.protocols.asn.AsnOutputStream; import org.mobicents.protocols.asn.Tag; import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberInformation.ExtCwFeature; import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberManagement.ExtBasicServiceCode; import org.restcomm.protocols.ss7.map.api.service.mobility.subscriberManagement.TeleserviceCodeValue; import org.restcomm.protocols.ss7.map.service.mobility.subscriberInformation.CallWaitingDataImpl; import org.restcomm.protocols.ss7.map.service.mobility.subscriberInformation.ExtCwFeatureImpl; import org.restcomm.protocols.ss7.map.service.mobility.subscriberManagement.ExtBasicServiceCodeImpl; import org.restcomm.protocols.ss7.map.service.mobility.subscriberManagement.ExtSSStatusImpl; import org.restcomm.protocols.ss7.map.service.mobility.subscriberManagement.ExtTeleserviceCodeImpl; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.Arrays; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; /** * @author vadim subbotin */ public class CallWaitingDataTest { private byte[] data = {48, 14, -95, 10, 48, 8, -95, 3, -125, 1, 0, -126, 1, 15, -126, 0}; @Test(groups = {"functional.decode", "subscriberInformation"}) public void testDecode() throws Exception { AsnInputStream asn = new AsnInputStream(data); int tag = asn.readTag(); assertEquals(tag, Tag.SEQUENCE); assertEquals(asn.getTagClass(), Tag.CLASS_UNIVERSAL); CallWaitingDataImpl callWaitingData = new CallWaitingDataImpl(); callWaitingData.decodeAll(asn); assertNotNull(callWaitingData.getCwFeatureList()); assertEquals(callWaitingData.getCwFeatureList().size(), 1); assertTrue(callWaitingData.getNotificationToCSE()); ExtCwFeature extCwFeature = callWaitingData.getCwFeatureList().get(0); assertNotNull(extCwFeature.getSsStatus()); assertTrue(extCwFeature.getSsStatus().getBitQ()); assertTrue(extCwFeature.getSsStatus().getBitP()); assertTrue(extCwFeature.getSsStatus().getBitR()); assertTrue(extCwFeature.getSsStatus().getBitA()); assertEquals(extCwFeature.getBasicService().getExtTeleservice().getTeleserviceCodeValue(), TeleserviceCodeValue.allTeleservices); } @Test(groups = {"functional.encode", "subscriberInformation"}) public void testEncode() throws Exception { ExtBasicServiceCode extBasicServiceCode = new ExtBasicServiceCodeImpl(new ExtTeleserviceCodeImpl(TeleserviceCodeValue.allTeleservices)); final ExtCwFeatureImpl extCwFeature = new ExtCwFeatureImpl(extBasicServiceCode, new ExtSSStatusImpl(true, true, true, true)); CallWaitingDataImpl callWaitingData = new CallWaitingDataImpl(new ArrayList<ExtCwFeature>(){{add(extCwFeature);}}, true); AsnOutputStream asnOS = new AsnOutputStream(); callWaitingData.encodeAll(asnOS); byte[] raw = asnOS.toByteArray(); assertTrue(Arrays.equals(raw, data)); } }
agpl-3.0