code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Playdar - music content resolver Copyright (C) 2009 Richard Jones Copyright (C) 2009 Last.fm Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __RESOLVED_ITEM_BUILDER_H__ #define __RESOLVED_ITEM_BUILDER_H__ #include "playdar/resolved_item.h" #include "library.h" using namespace json_spirit; namespace playdar { /* Builds a ResolvedItem describing something (a song) that can be played. */ class ResolvedItemBuilder { public: static void createFromFid(Library& lib, int fid, json_spirit::Object& out) { createFromFid( lib.db(), fid, out ); } static void createFromFid( sqlite3pp::database& db, int fid, Object& out) { LibraryFile_ptr file( Library::file_from_fid(db, fid) ); out.push_back( Pair("mimetype", file->mimetype) ); out.push_back( Pair("size", file->size) ); out.push_back( Pair("duration", file->duration) ); out.push_back( Pair("bitrate", file->bitrate) ); artist_ptr artobj = Library::load_artist( db, file->piartid); track_ptr trkobj = Library::load_track( db, file->pitrkid); out.push_back( Pair("artist", artobj->name()) ); out.push_back( Pair("track", trkobj->name()) ); // album metadata kinda optional for now if (file->pialbid) { album_ptr albobj = Library::load_album(db, file->pialbid); out.push_back( Pair("album", albobj->name()) ); } out.push_back( Pair("url", file->url) ); } }; } // ns #endif //__RESOLVED_ITEM_BUILDER_H__
RJ/playdar
resolvers/local/resolved_item_builder.hpp
C++
gpl-3.0
2,176
#region License // // GroupableTest.cs // // Copyright (C) 2009-2013 Alex Taylor. All Rights Reserved. // // This file is part of Digitalis.LDTools.DOM.UnitTests.dll // // Digitalis.LDTools.DOM.UnitTests.dll is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Digitalis.LDTools.DOM.UnitTests.dll is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Digitalis.LDTools.DOM.UnitTests.dll. If not, see <http://www.gnu.org/licenses/>. // #endregion License namespace UnitTests { #region Usings using System; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Digitalis.LDTools.DOM; using Digitalis.LDTools.DOM.API; #endregion Usings [TestClass] public sealed class GroupableTest : IGroupableTest { #region Infrastructure protected override Type TestClassType { get { return typeof(Groupable); } } protected override IGroupable CreateTestGroupable() { return new MockGroupable(); } #endregion Infrastructure #region Definition Test [TestMethod] public override void DefinitionTest() { Assert.IsTrue(TestClassType.IsAbstract); Assert.IsFalse(TestClassType.IsSealed); base.DefinitionTest(); } #endregion Definition Test #region Disposal [TestMethod] public override void DisposeTest() { LDStep step = new LDStep(); MockGroupable groupable = new MockGroupable(); MLCadGroup group = new MLCadGroup(); step.Add(group); Assert.AreEqual(1, step.PathToDocumentChangedSubscribers); Assert.AreEqual(0, group.PathToDocumentChangedSubscribers); step.Add(groupable); groupable.Group = group; // the Groupable should subscribe to its step's PathToDocumentChanged event... Assert.AreEqual(3, step.PathToDocumentChangedSubscribers); // adds two subscribers: Groupable and its superclass Element // ...and to its group's PathToDocumentChanged event Assert.AreEqual(1, group.PathToDocumentChangedSubscribers); groupable.Dispose(); Assert.AreEqual(1, step.PathToDocumentChangedSubscribers); Assert.AreEqual(0, group.PathToDocumentChangedSubscribers); base.DisposeTest(); } #endregion Disposal #region Grouping [TestMethod] public override void GroupTest() { IGroupable groupable = CreateTestGroupable(); IStep step = new LDStep(); MLCadGroup group = new MLCadGroup(); step.Add(groupable); step.Add(group); Assert.AreEqual(0, group.PathToDocumentChangedSubscribers); groupable.Group = group; Assert.AreEqual(1, group.PathToDocumentChangedSubscribers); groupable.Group = null; Assert.AreEqual(0, group.PathToDocumentChangedSubscribers); base.GroupTest(); } #endregion Grouping } }
alex-taylor/Digitalis.LDTools.DOM
UnitTests/GroupableTest.cs
C#
gpl-3.0
3,733
use std::collections::HashMap; use std::rc::Rc; use serde::de::{Deserialize, Deserializer}; use serde_derive::Deserialize; use toml::value; use crate::errors; use crate::icons::Icons; use crate::protocol::i3bar_event::MouseButton; use crate::themes::Theme; #[derive(Debug)] pub struct SharedConfig { pub theme: Rc<Theme>, icons: Rc<Icons>, icons_format: String, pub scrolling: Scrolling, } impl SharedConfig { pub fn new(config: &Config) -> Self { Self { theme: Rc::new(config.theme.clone()), icons: Rc::new(config.icons.clone()), icons_format: config.icons_format.clone(), scrolling: config.scrolling, } } pub fn icons_format_override(&mut self, icons_format: String) { self.icons_format = icons_format; } pub fn theme_override(&mut self, overrides: &HashMap<String, String>) -> errors::Result<()> { let mut theme = self.theme.as_ref().clone(); theme.apply_overrides(overrides)?; self.theme = Rc::new(theme); Ok(()) } pub fn icons_override(&mut self, overrides: HashMap<String, String>) { let mut icons = self.icons.as_ref().clone(); icons.0.extend(overrides); self.icons = Rc::new(icons); } pub fn get_icon(&self, icon: &str) -> crate::errors::Result<String> { use crate::errors::OptionExt; Ok(self.icons_format.clone().replace( "{icon}", self.icons .0 .get(icon) .internal_error("get_icon()", &format!("icon '{}' not found in your icons file. If you recently upgraded to v0.2 please check NEWS.md.", icon))?, )) } } impl Default for SharedConfig { fn default() -> Self { Self { theme: Rc::new(Theme::default()), icons: Rc::new(Icons::default()), icons_format: " {icon} ".to_string(), scrolling: Scrolling::default(), } } } impl Clone for SharedConfig { fn clone(&self) -> Self { Self { theme: Rc::clone(&self.theme), icons: Rc::clone(&self.icons), icons_format: self.icons_format.clone(), scrolling: self.scrolling, } } } #[derive(Deserialize, Debug, Clone)] pub struct Config { #[serde(default)] pub icons: Icons, #[serde(default)] pub theme: Theme, #[serde(default = "Config::default_icons_format")] pub icons_format: String, /// Direction of scrolling, "natural" or "reverse". /// /// Configuring natural scrolling on input devices changes the way i3status-rust /// processes mouse wheel events: pushing the wheen away now is interpreted as downward /// motion which is undesired for sliders. Use "natural" to invert this. #[serde(default)] pub scrolling: Scrolling, #[serde(rename = "block", deserialize_with = "deserialize_blocks")] pub blocks: Vec<(String, value::Value)>, } impl Config { fn default_icons_format() -> String { " {icon} ".to_string() } } impl Default for Config { fn default() -> Self { Config { icons: Icons::default(), theme: Theme::default(), icons_format: Config::default_icons_format(), scrolling: Scrolling::default(), blocks: Vec::new(), } } } #[derive(Deserialize, Copy, Clone, Debug)] #[serde(rename_all = "lowercase")] pub enum Scrolling { Reverse, Natural, } #[derive(Copy, Clone, Debug)] pub enum LogicalDirection { Up, Down, } impl Scrolling { pub fn to_logical_direction(self, button: MouseButton) -> Option<LogicalDirection> { use LogicalDirection::*; use MouseButton::*; use Scrolling::*; match (self, button) { (Reverse, WheelUp) | (Natural, WheelDown) => Some(Up), (Reverse, WheelDown) | (Natural, WheelUp) => Some(Down), _ => None, } } } impl Default for Scrolling { fn default() -> Self { Scrolling::Reverse } } fn deserialize_blocks<'de, D>(deserializer: D) -> Result<Vec<(String, value::Value)>, D::Error> where D: Deserializer<'de>, { let mut blocks: Vec<(String, value::Value)> = Vec::new(); let raw_blocks: Vec<value::Table> = Deserialize::deserialize(deserializer)?; for mut entry in raw_blocks { if let Some(name) = entry.remove("block") { if let Some(name) = name.as_str() { blocks.push((name.to_owned(), value::Value::Table(entry))) } } } Ok(blocks) }
greshake/i3status-rust
src/config.rs
Rust
gpl-3.0
4,609
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2016 Wandora Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * JoinDirective.java * * Created on 25. lokakuuta 2007, 11:38 * */ package org.wandora.query; import org.wandora.topicmap.*; import java.util.*; /** * @deprecated * * @author olli */ public class JoinDirective implements Directive { private Directive query; private Locator joinContext; private Directive joinQuery; /** Creates a new instance of JoinDirective */ public JoinDirective(Directive query,Directive joinQuery) { this(query,(Locator)null,joinQuery); } public JoinDirective(Directive query,Locator joinContext,Directive joinQuery) { this.query=query; this.joinContext=joinContext; this.joinQuery=joinQuery; } public JoinDirective(Directive query,String joinContext,Directive joinQuery) { this(query,new Locator(joinContext),joinQuery); } public ArrayList<ResultRow> query(QueryContext context) throws TopicMapException { return query(context,null,null); } public ArrayList<ResultRow> query(QueryContext context,FilterDirective filter,Object filterParam) throws TopicMapException { Topic contextTopic=context.getContextTopic(); TopicMap tm=contextTopic.getTopicMap(); ArrayList<ResultRow> inner=query.query(context); ArrayList<ResultRow> res=new ArrayList<ResultRow>(); ArrayList<ResultRow> cachedJoin=null; boolean useCache=!joinQuery.isContextSensitive(); for(ResultRow row : inner){ Topic t=null; if(joinContext!=null){ Locator c=row.getPlayer(joinContext); if(c==null) continue; t=tm.getTopic(c); } else t=context.getContextTopic(); if(t==null) continue; ArrayList<ResultRow> joinRes; if(!useCache || cachedJoin==null){ joinRes=joinQuery.query(context.makeNewWithTopic(t)); if(useCache) cachedJoin=joinRes; } else joinRes=cachedJoin; for(ResultRow joinRow : joinRes){ ResultRow joined=ResultRow.joinRows(row,joinRow); if(filter!=null && !filter.includeRow(joined, contextTopic, tm, filterParam)) continue; res.add(joined); } } return res; } public boolean isContextSensitive(){ return query.isContextSensitive(); // note joinQuery gets context from query so it's sensitivity is same // as that of query } }
wandora-team/wandora
src/org/wandora/query/JoinDirective.java
Java
gpl-3.0
3,327
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd"> <HTML style="overflow:auto;"> <HEAD> <meta name="generator" content="JDiff v1.1.0"> <!-- Generated by the JDiff Javadoc doclet --> <!-- (http://www.jdiff.org) --> <meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared."> <meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet"> <TITLE> android.transition.AutoTransition </TITLE> <link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" /> <link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" /> <noscript> <style type="text/css"> body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> <style type="text/css"> </style> </HEAD> <BODY> <!-- Start of nav bar --> <a name="top"></a> <div id="header" style="margin-bottom:0;padding-bottom:0;"> <div id="headerLeft"> <a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a> </div> <div id="headerRight"> <div id="headerLinks"> <!-- <img src="/assets/images/icon_world.jpg" alt="" /> --> <span class="text"> <!-- &nbsp;<a href="#">English</a> | --> <nobr><a href="//developer.android.com" target="_top">Android Developers</a> | <a href="//www.android.com" target="_top">Android.com</a></nobr> </span> </div> <div class="and-diff-id" style="margin-top:6px;margin-right:8px;"> <table class="diffspectable"> <tr> <td colspan="2" class="diffspechead">API Diff Specification</td> </tr> <tr> <td class="diffspec" style="padding-top:.25em">To Level:</td> <td class="diffvaluenew" style="padding-top:.25em">21</td> </tr> <tr> <td class="diffspec">From Level:</td> <td class="diffvalueold">l-preview</td> </tr> <tr> <td class="diffspec">Generated</td> <td class="diffvalue">2014.10.15 14:58</td> </tr> </table> </div><!-- End and-diff-id --> <div class="and-diff-id" style="margin-right:8px;"> <table class="diffspectable"> <tr> <td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a> </tr> </table> </div> <!-- End and-diff-id --> </div> <!-- End headerRight --> </div> <!-- End header --> <div id="body-content" xstyle="padding:12px;padding-right:18px;"> <div id="doc-content" style="position:relative;"> <div id="mainBodyFluid"> <H2> Class android.transition.<A HREF="../../../../reference/android/transition/AutoTransition.html" target="_top"><font size="+2"><code>AutoTransition</code></font></A> </H2> <a NAME="constructors"></a> <p> <a NAME="Added"></a> <TABLE summary="Added Constructors" WIDTH="100%"> <TR> <TH VALIGN="TOP" COLSPAN=2>Added Constructors</FONT></TD> </TH> <TR BGCOLOR="#FFFFFF" CLASS="TableRowColor"> <TD VALIGN="TOP" WIDTH="25%"> <A NAME="android.transition.AutoTransition.ctor_added(android.content.Context, android.util.AttributeSet)"></A> <nobr><A HREF="../../../../reference/android/transition/AutoTransition.html#AutoTransition(android.content.Context, android.util.AttributeSet)" target="_top"><code>AutoTransition</code></A>(<code>Context,</nobr> AttributeSet<nobr><nobr></code>)</nobr> </TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <a NAME="methods"></a> <a NAME="fields"></a> </div> <div id="footer"> <div id="copyright"> Except as noted, this content is licensed under <a href="//creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>. For details and restrictions, see the <a href="/license.html">Content License</a>. </div> <div id="footerlinks"> <p> <a href="//www.android.com/terms.html">Site Terms of Service</a> - <a href="//www.android.com/privacy.html">Privacy Policy</a> - <a href="//www.android.com/branding.html">Brand Guidelines</a> </p> </div> </div> <!-- end footer --> </div><!-- end doc-content --> </div> <!-- end body-content --> <script src="//www.google-analytics.com/ga.js" type="text/javascript"> </script> <script type="text/javascript"> try { var pageTracker = _gat._getTracker("UA-5831155-1"); pageTracker._setAllowAnchor(true); pageTracker._initData(); pageTracker._trackPageview(); } catch(e) {} </script> </BODY> </HTML>
s20121035/rk3288_android5.1_repo
frameworks/base/docs/html/sdk/api_diff/preview-21/changes/android.transition.AutoTransition.html
HTML
gpl-3.0
4,850
<?php // Heading $_['heading_title'] = 'Εγγραφή'; // Text $_['text_account'] = 'Λογαριασμός'; $_['text_register'] = 'Εγγραφή'; $_['text_account_already'] = 'Εάν έχετε ήδη λογαριασμό, εισέλθετε από <a href="%s">εδώ</a>.'; $_['text_your_details'] = 'Προσωπικά Στοιχεία'; $_['text_your_address'] = 'Διεύθυνση'; $_['text_newsletter'] = 'Ενημερώσεις'; $_['text_your_password'] = 'Ο Κωδικός σας'; $_['text_agree'] = 'Αποδέχομαι τους <a class="fancybox" href="%s" alt="%s"><b>%s</b></a>'; // Entry $_['entry_firstname'] = 'Όνομα:'; $_['entry_lastname'] = 'Επίθετο:'; $_['entry_email'] = 'E-Mail:'; $_['entry_telephone'] = 'Τηλέφωνο:'; $_['entry_fax'] = 'Fax:'; $_['entry_company'] = 'Εταιρία:'; $_['entry_customer_group'] = 'Είδος Εταιρίας:'; $_['entry_company_id'] = 'Αναγνωριστικό (ID) Εταιρίας:'; $_['entry_tax_id'] = 'ΑΦΜ:'; $_['entry_address_1'] = 'Διεύθυνση 1:'; $_['entry_address_2'] = 'Διεύθυνση 2:'; $_['entry_postcode'] = 'Ταχυδρομικός Κώδικας:'; $_['entry_city'] = 'Πόλη:'; $_['entry_country'] = 'Χώρα:'; $_['entry_zone'] = 'Περιοχή:'; $_['entry_newsletter'] = 'Συνδρομή:'; $_['entry_password'] = 'Κωδικός:'; $_['entry_confirm'] = 'Επαλήθευση Κωδικού:'; // Error $_['error_exists'] = 'Προειδοποίηση: Η διεύθυνση E-Mail είναι ήδη καταχωρημένη!'; $_['error_firstname'] = 'Το Όνομα πρέπει να είναι από 1 έως 32 χαρακτήρες!'; $_['error_lastname'] = 'Το Επίθετο πρέπει να είναι από 1 έως 32 χαρακτήρες!'; $_['error_email'] = 'Η διεύθυνση E-Mail φαίνεται να μην είναι έγκυρη!'; $_['error_telephone'] = 'Το Τηλέφωνο πρέπει να είναι από 3 έως 32 χαρακτήρες!'; $_['error_password'] = 'Ο Κωδικός πρέπει να είναι από 4 έως 20 χαρακτήρες!'; $_['error_confirm'] = 'Η Επαλήθευση Κωδικού δεν ταιριάζει με τον αρχικό Κωδικό!'; $_['error_company_id'] = 'Απαιτείται η εισαγωγή του Αναγνωριστικού (ID) Εταιρίας!'; $_['error_tax_id'] = 'Απαιτείται η εισαγωγή ΑΦΜ!'; $_['error_vat'] = 'Ο ΦΠΑ είναι λανθασμένος!'; $_['error_address_1'] = 'Η Διεύθυνση 1 πρέπει να είναι από 3 έως 128 χαρακτήρες!'; $_['error_city'] = 'Η Πόλη πρέπει να είναι από 2 έως 128 χαρακτήρες!'; $_['error_postcode'] = 'Ο Ταχυδρομικός Κώδικας πρέπει να είναι από 2 έως 10 χαρακτήρες!'; $_['error_country'] = 'Εισάγετε Χώρα!'; $_['error_zone'] = 'Εισάγετε Περιοχή!'; $_['error_agree'] = 'Προειδοποίηση: Πρέπει να συμφωνήσετε με %s!'; ?>
lathan/opencart-greek
catalog/language/greek/account/register.php
PHP
gpl-3.0
3,384
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-03 08:56 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('snapventure', '0004_auto_20161102_2043'), ] operations = [ migrations.CreateModel( name='Inscription', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created', models.DateTimeField(auto_now_add=True)), ('last_updated', models.DateTimeField(auto_now=True)), ('journey', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='snapventure.Journey')), ], ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('bio', models.TextField(blank=True, max_length=500)), ('location', models.CharField(blank=True, max_length=30)), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.AddField( model_name='inscription', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='snapventure.Profile'), ), migrations.AddField( model_name='journey', name='inscriptions', field=models.ManyToManyField(through='snapventure.Inscription', to='snapventure.Profile'), ), ]
DomDomPow/snapventure
snapventure-backend/snapventure/migrations/0005_auto_20161103_0856.py
Python
gpl-3.0
1,892
// // CreditsViewController.h // P5P // // Created by CNPP on 25.2.2011. // Copyright Beat Raess 2011. All rights reserved. // // This file is part of P5P. // // P5P is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // P5P is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with P5P. If not, see www.gnu.org/licenses/. #import <UIKit/UIKit.h> #import "CellLink.h" // Sections enum { SectionCreditsReferences, SectionCreditsFrameworks, SectionCreditsComponents, SectionCreditsAssets } P5PCreditsSections; /** * Credit. */ @interface Credit : NSObject { } // Properties @property (nonatomic, retain) NSString *name; @property (nonatomic, retain) NSString *meta; @property (nonatomic, retain) NSString *url; // Initializer - (id)initWithName:(NSString*)n meta:(NSString*)m url:(NSString*)u; @end /** * CreditsViewController. */ @interface CreditsViewController : UITableViewController <CellLinkDelegate> { // data NSMutableArray *references; NSMutableArray *frameworks; NSMutableArray *components; NSMutableArray *assets; } @end
braess/p5p
Classes/CreditsViewController.h
C
gpl-3.0
1,526
#ifndef CONFIGURATION_H #define CONFIGURATION_H #include <QObject> #include <qsettings.h> class Configuration { public: Configuration(); QString Hostname; QString Username; QString AutoLogin; QString SaveDir; int ConcurrentDownloads; bool UseSSL; QSettings *settings; void Load(); void Save(); }; #endif // CONFIGURATION_H
eternalvr/qtmultidl
src/configuration.h
C
gpl-3.0
371
Note: This is not the [authoritative source](https://www.comlaw.gov.au/Details/C2012C00832) for this act, and likely contains errors # Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 ##### Act No. 56 of 2011 as amended ##### This compilation was prepared on 20 November 2012 ##### taking into account amendments up to Act No. 136 of 2012 ##### The text of any of those amendments not in force ##### on that date is appended in the Notes section ##### The operation of amendments that have been incorporated may be ##### affected by application provisions that are set out in the Notes section ##### Prepared by the Office of Parliamentary Counsel, Canberra ## ## Contents * "1-9" \t "ActHead 1,2,ActHead 2,2,ActHead 3,3,ActHead 4,4,ActHead 5,5, Schedule,2, Schedule Text,3, NotesSection,6" 1 Short title [_see_ Note 1] * 2 Commencement * 3 Schedule(s) * 4 Review of operation of AUSTRAC cost recovery levy * **Schedule 1--Amendment of the Anti-Money Laundering and Counter-Terrorism Financing Act 2006 ** * Schedule 2--Infringement notice provisions ** * **Part 1--Amendments * _Anti-Money Laundering and Counter-Terrorism Financing Act 2006 _ * _Part 2--Transitional provision * **Notes ** ### ** ### An Act to deal with consequential matters relating to the enactment of the Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011, and for related purposes * 1** Short title **[_see_ Note 1] * This Act may be cited as the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_. ##### 2 Commencement * (1) Each provision of this Act specified in column 1 of the table commences, or is taken to have commenced, in accordance with column 2 of the table. Any other statement in column 2 has effect according to its terms. **Commencement information** Column 1** Column 2** Column 3** Provision(s)** Commencement** Date/Details** **1. Sections 1 to 3 and anything in this Act not elsewhere covered by this table The day this Act receives the Royal Assent. 28 June 2011 2. Schedule 1 A single day to be fixed by Proclamation. However, if any of the provision(s) do not commence within the period of 6 months beginning on the day this Act receives the Royal Assent, they commence on the day after the end of that period. 1 November 2011 (_see_ F2011L02035) 3. Schedule 2, Part 1 The later of: * (a) the commencement of item 31 of Schedule 1 to the _Combating the Financing of People Smuggling and Other Measures Act 2011_; and * (b) immediately after the commencement of the provision(s) covered by table item 2. However, the provision(s) do not commence at all unless both of the events mentioned in paragraphs (a) and (b) occur. 1 November 2011 4. Schedule 2, Part 2 Immediately after the commencement of the provision(s) covered by table item 2. 1 November 2011 * Note: This table relates only to the provisions of this Act as originally enacted. It will not be amended to deal with any later amendments of this Act. * (2) Any information in column 3 of the table is not part of this Act. Information may be inserted in this column, or information in it may be edited, in any published version of this Act. ##### 3 Schedule(s) * Each Act that is specified in a Schedule to this Act is amended or repealed as set out in the applicable items in the Schedule concerned, and any other item in a Schedule to this Act has effect according to its terms. ##### 4 Review of operation of AUSTRAC cost recovery levy * (1) The Minister must cause an independent review of the operation of the levy imposed by the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011_ to be undertaken as soon as possible after the second anniversary of the commencement of section 3 of that Act. * (2) The person who undertakes the review must give the Minister a written report of the review within 6 months after the second anniversary of the commencement of section 3 of the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011_. * (3) The Minister must cause a copy of the report of the review to be tabled in each House of Parliament within 15 sitting days of receiving it. * (4) A report prepared under subsection (1) must include but is not limited to: * (a) a review of the levy calculation methodology; and * (b) consultation with industry participants including small and micro businesses about the impact of the levy and the costs of complying with the _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy Act 2011_. ### ### Schedule 1--Amendment of the Anti-Money Laundering and Counter-Terrorism Financing Act 2006 ##### 1 Section 5 * Insert: * **_enrolment details_**, in relation to a person, means such information relating to the person as is specified in the AML/CTF Rules. ##### 2 After Part 3 * Insert: ### Part 3A--Reporting Entities Roll ##### 51A Simplified outline * The following is a simplified outline of this Part: * Providers of designated services must be entered on the Reporting Entities Roll. ##### 51B Reporting entities must enrol * (1) If a person's name is not entered on the Reporting Entities Roll, the person must: * (a) if the person provided a designated service during the period of 28 days before the commencement of this section--apply in writing to the AUSTRAC CEO under subsection 51E(1) within 28 days after the commencement of this section; or * (b) if the person commences to provide a designated service after the commencement of this section--apply in writing to the AUSTRAC CEO under subsection 51E(1) within 28 days after commencing to provide the designated service. * (2) Subsection (1) does not apply if the person: * (a) has applied under subsection 51E(1) in relation to the provision of another designated service; and * (b) has not since requested under section 51G that the AUSTRAC CEO remove the person's name and enrolment details from the Reporting Entities Roll. * _Civil penalty_ * _ (3) Subsection (1) is a civil penalty provision. ##### 51C Reporting Entities Roll * (1) The AUSTRAC CEO must maintain a roll for the purposes of this Part, to be known as the Reporting Entities Roll. * (2) The AUSTRAC CEO may maintain the Reporting Entities Roll by electronic means. * (3) The Reporting Entities Roll is not a legislative instrument. * (4) The AML/CTF Rules may make provision for and in relation to either or both of the following: * (a) the correction of entries in the Reporting Entities Roll; * (b) any other matter relating to the administration or operation of the Reporting Entities Roll, including the removal of names and enrolment details from the Reporting Entities Roll. ##### 51D Enrolment * If a person applies to the AUSTRAC CEO under subsection 51E(1) and the person's name is not already entered on the Reporting Entities Roll, the AUSTRAC CEO must enter on the Reporting Entities Roll: * (a) the person's name; and * (b) the person's enrolment details. ##### 51E Applications for enrolment * (1) A person may apply in writing to the AUSTRAC CEO for enrolment as a reporting entity. * (2) The application must: * (a) be in accordance with the approved form, or in a manner specified in the AML/CTF Rules; and * (b) contain the information required by the AML/CTF Rules. ##### 51F Enrolled persons to advise of change in enrolment details * (1) A person who is enrolled under this Part must advise the AUSTRAC CEO, in accordance with subsection (2), of any change in the person's enrolment details that is of a kind specified in the AML/CTF Rules. * (2) A person who is required by subsection (1) to advise the AUSTRAC CEO of a change in enrolment details must do so: * (a) within 14 days of the change arising; and * (b) in accordance with the approved form, or in a manner specified in the AML/CTF Rules. * _Civil penalty_ * _ (3) Subsection (1) is a civil penalty provision. ##### 51G Removal of entries from the Reporting Entities Roll * (1) A person may, in writing, request the AUSTRAC CEO to remove the person's name and enrolment details from the Reporting Entities Roll. * (2) The request must: * (a) be in the approved form; and * (b) contain the information required by the AML/CTF Rules. * (3) The AUSTRAC CEO must consider the request and remove the person's name and enrolment details from the Reporting Entities Roll if the AUSTRAC CEO is satisfied that it is appropriate to do so, having regard to: * (a) whether the person has ceased to provide designated services; and * (b) the likelihood of the person providing a designated service in the financial year beginning after the request is given; and * (c) any outstanding obligations the person has (if any) to provide a report under any of the following provisions: * (i) section 43 (threshold transaction reports); * (ii) section 45 (international funds transfer instruction reports); * (iii) section 47 (AML/CTF compliance reports). ### Schedule 2--Infringement notice provisions ##### Part 1--Amendments #### Anti-Money Laundering and Counter-Terrorism Financing Act 2006 ##### 1 Before paragraph 184(1A)(a) * Insert: * (aaa) subsection 51B(1) (which deals with the requirement for reporting entities to enrol on the Reporting Entities Roll); * (aa) subsection 51F(1) (which deals with reporting entities notifying changes of their enrolment details); ##### 2 Subsection 186A(1) * Before "by a body corporate", insert "or subsection 51B(1) or 51F(1) (a **_Part 3A infringement notice provision_**)". * Note: The heading to section 186A is altered by adding at the end "**or Part 3A**". ##### 3 Subsection 186A(2) * After "Part 6 infringement notice provision", insert "or a Part 3A infringement notice provision". ##### 4 Paragraphs 186A(3)(a) and (4)(a) * After "Part 6 infringement notice provision", insert "or a Part 3A infringement notice provision". ##### 5 Paragraph 186A(4)(b) * After "Part 6 infringement notice provisions", insert "or Part 3A infringement notice provisions". ##### 6 Paragraph 186A(4)(b) * After "Part 6 infringement notice provision", insert "or a Part 3A infringement notice provision". ##### Part 2--Transitional provision ##### 7 Transitional * (1) If this item commences before the commencement of Part 1 of this Schedule, Division 3 of Part 15 of the _Anti-Money Laundering and Counter-Terrorism Financing Act 2006 _applies with the modifications set out in this item for the period: * (a) beginning immediately after the commencement of this item; and * (b) ending just before the commencement of Part 1 of this Schedule. * (2) Treat a reference in that Division to "subsection 53(3) or 59(4)" as a reference to "subsection 51B(1), 51F(1), 53(3) or 59(4)". * (3) Assume the following subsection was added at the end of section 185 of that Act: * (2) An infringement notice may specify more than one alleged contravention of one or more of the provisions referred to in subsection 184(1). If it does so, the infringement notice must set out the details referred to in paragraph (1)(c) in relation to each alleged contravention. * (4) Assume that the following section was inserted after section 186 of that Act: ##### 186A Amount of penalty--breaches of certain provisions of Part 3A * The penalty to be specified in an infringement notice for an alleged contravention of subsection 51B(1) or 51F(1) must be: * (a) for an alleged contravention by a body corporate--a pecuniary penalty equal to 60 penalty units; and * (b) for an alleged contravention by a person other than a body corporate--12 penalty units. ##### ##### Notes to the \* MERGEFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 ##### Note 1 The _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _as shown in this compilation comprises Act No. 56, 2011 amended as indicated in the Tables below. ##### Table of Acts Act Number and year Date of Assent Date of commencement Application, saving or transitional provisions _Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _56, 2011 28 June 2011 _See_ s. 2(1) _Statute Law Revision Act 2012_ _136, 2012 22 Sept 2012 Schedule 2 (item 1): Royal Assent -- * * **Table of Amendments** **ad. = added or inserted am. = amended rep. = repealed rs. = repealed and substituted Provision affected How affected S. 4 am. No. 136, 2012 _PAGE iii \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE iii_ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE iii_ Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 Act No. 56 of 2011 as amended PAGE iii_ FILENAME \p K:\Consolidated Acts\- A -\AustTransRepAnalyCentSuperCostRecLevyConseqAmend2011\2011A056_20121116_2012A136_Conversion_A\AustTranRepAnalCenSupCostRecLevyConAmend2011.doc TIME \@ "d/M/yyyy h:mm AM/PM" 20/11/2012 8:58 AM_ _** ** ** ** _PAGE 2 \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE 9_ _ _ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE 1_ _** Schedule 2** Infringement notice provisions ** Part 1** Amendments Infringement notice provisions ** Schedule 2** ** Transitional provision ** Part 2** **_PAGE 8 \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 _ _ STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _**Table of Acts** ** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _**Table of Acts** ** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _**Table of Acts** **_ \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011 PAGE 11_ _ STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _** STYLEREF TableOfAmendHead \* CHARFORMAT Table of Amendments** ** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _** STYLEREF TableOfAmendHead \* CHARFORMAT Table of Amendments** ** STYLEREF CharNotesReg \* CHARFORMAT Notes to the _ STYLEREF CharNotesItals \* CHARFORMAT Australian Transaction Reports and Analysis Centre Supervisory Cost Recovery Levy (Consequential Amendments) Act 2011_ _** STYLEREF TableOfAmendHead \* CHARFORMAT Table of Amendments**
xlfe/gitlaw-au
acts/current/a/australian transaction reports and analysis centre supervisory cost recovery levy (consequential amendments) act 2011.md
Markdown
gpl-3.0
16,763
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace SO.SilList.Manager.Models.ValueObjects { [Table("JobType", Schema = "app" )] [Serializable] public class JobTypeVo { [DisplayName("job Type Id")] [Required] [Key] public int jobTypeId { get; set; } [DisplayName("name")] [StringLength(50)] public string name { get; set; } [DisplayName("description")] public string description { get; set; } [DisplayName("created")] public Nullable<DateTime> created { get; set; } [DisplayName("modified")] public Nullable<DateTime> modified { get; set; } [DisplayName("created By")] public Nullable<int> createdBy { get; set; } [DisplayName("modified By")] public Nullable<int> modifiedBy { get; set; } [DisplayName("is Active")] [Required] public bool isActive { get; set; } [Association("JobType_Job", "jobTypeId", "jobTypeId")] public List<JobVo> jobses { get; set; } public JobTypeVo() { this.isActive = true; } } }
SilverObject/SilList
SO.SilList.Manager/Models/ValueObjects/JobTypeVo.cs
C#
gpl-3.0
1,430
/**************************************************************************** ** ** Copyright (C) 2014-2015 Dinu SV. ** (contact: [email protected]) ** This file is part of C++ Snippet Assist application. ** ** GNU General Public License Usage ** ** This file may be used under the terms of the GNU General Public License ** version 3.0 as published by the Free Software Foundation and appearing ** in the file LICENSE.GPL included in the packaging of this file. Please ** review the following information to ensure the GNU General Public License ** version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html. ** ****************************************************************************/ #ifndef QSOURCELOCATION_HPP #define QSOURCELOCATION_HPP #include "QCSAGlobal.hpp" #include <QString> #include <QObject> namespace csa{ class Q_CSA_EXPORT QSourceLocation : public QObject{ Q_OBJECT public: QSourceLocation( const QString& file, unsigned int line, unsigned int column, unsigned int offset, QObject* parent = 0); QSourceLocation( const char* file, unsigned int line, unsigned int column, unsigned int offset, QObject* parent = 0); QSourceLocation( const QSourceLocation& other, QObject* parent = 0); ~QSourceLocation(); void assign(const QSourceLocation& other); QSourceLocation& operator =(const QSourceLocation& other); public slots: unsigned int line() const; unsigned int column() const; unsigned int offset() const; QString filePath() const; QString fileName() const; QString toString() const; private: QString m_filePath; unsigned int m_line; unsigned int m_column; unsigned int m_offset; }; inline unsigned int QSourceLocation::line() const{ return m_line; } inline unsigned int QSourceLocation::column() const{ return m_column; } inline unsigned int QSourceLocation::offset() const{ return m_offset; } inline QString QSourceLocation::filePath() const{ return m_filePath; } }// namespace Q_DECLARE_METATYPE(csa::QSourceLocation*) #endif // QSOURCELOCATION_HPP
dinusv/cpp-snippet-assist
modules/csa-lib/codebase/QSourceLocation.hpp
C++
gpl-3.0
2,242
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CentralAirportSupervision.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute( )] [global::System.CodeDom.Compiler.GeneratedCodeAttribute( "Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0" )] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ( (Settings)( global::System.Configuration.ApplicationSettingsBase.Synchronized( new Settings( ) ) ) ); public static Settings Default { get { return defaultInstance; } } } }
Rapster/handling-simulation
trunk/handling_simulation_1.1/CentralAirportSupervision/Properties/Settings.Designer.cs
C#
gpl-3.0
1,088
{% load fiber_tags imagekit %} <div> {% thumbnail '150x150' product.image %} <div> {{ product.text|safe }} <span class="product-name"> {{ product.name }} </span> </div> <div class="paypal-button"> {{ product.paypal_button|safe }} </div> </div> {% if 'change_product' in perms %} <a href="{% url "admin:products_product_change" product.pk %}" class="no-ajax"> edit </a> {% endif %}
ebrelsford/growing_cities
growing_cities/templates/products/_product_detail.html
HTML
gpl-3.0
454
package cat.foixench.test.parcelable; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
gothalo/Android-2017
014-Parcelable/app/src/test/java/cat/foixench/test/parcelable/ExampleUnitTest.java
Java
gpl-3.0
406
package com.acgmodcrew.kip.tileentity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; /** * Created by Malec on 05/03/2015. */ public class TileEntityRepositry extends TileEntity implements IInventory { private ItemStack[] inventory = new ItemStack[4]; @Override public int getSizeInventory() { return 4; } @Override public ItemStack getStackInSlot(int slot) { return inventory[slot]; } @Override public ItemStack decrStackSize(int slot, int p_70298_2_) { if (this.inventory[slot] != null) { ItemStack itemstack; if (this.inventory[slot].stackSize <= p_70298_2_) { itemstack = this.inventory[slot]; this.inventory[slot] = null; this.markDirty(); return itemstack; } else { itemstack = this.inventory[slot].splitStack(p_70298_2_); if (this.inventory[slot].stackSize == 0) { this.inventory[slot] = null; } this.markDirty(); return itemstack; } } else { return null; } } @Override public ItemStack getStackInSlotOnClosing(int p_70304_1_) { return null; } @Override public void setInventorySlotContents(int slot, ItemStack itemStack) { inventory[slot] = itemStack; } @Override public String getInventoryName() { return "Repository"; } @Override public boolean hasCustomInventoryName() { return false; } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { if (worldObj == null) { return true; } if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this) { return false; } return entityplayer.getDistanceSq((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D; } @Override public void openInventory() { } @Override public void closeInventory() { } @Override public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) { return false; } }
ACGModCrew/kip
src/main/java/com/acgmodcrew/kip/tileentity/TileEntityRepositry.java
Java
gpl-3.0
2,563
<html> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="report.css" type="text/css"/> <title></title> <script type="text/javascript" src="report.js"></script> <script type="text/javascript" src="link_popup.js"></script> <script type="text/javascript" src="tooltip.js"></script> </head> <body style="margin-left: 10px; margin-right: 10px; margin-top: 10px; margin-bottom: 10px;"> <div style="position:absolute; z-index:21; visibility:hidden" id="vplink"> <table border="1" cellpadding="0" cellspacing="0" bordercolor="#A9BFD3"> <tr> <td> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr style="background:#DDDDDD"> <td style="font-size: 12px;" align="left"> <select onchange="vpLinkToggleName()" id="vplink-linkType"> <option value="Project Link">Project Link</option> <option value="Page URL">Page URL</option> </select> </td> <td style="font-size: 12px;" align="right"> <input onclick="javascript: vpLinkToggleName()" id="vplink-checkbox" type="checkbox" /> <label for="vplink-checkbox">with Name</label> </td> </tr> </table> </td> </tr> <tr> <td> <textarea id="vplink-text" style="width: 348px; height: 60px; border-color: #7EADD9; outline: none;"></textarea> </td> </tr> </table> </div> <div class="HeaderText"> <span> discovery </span> </div> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td class="HeaderLine1"> </td> </tr> <tr> <td class="HeaderLine2"> </td> </tr> <tr> <td class="HeaderLine3"> </td> </tr> </table> <p> <a href="ProjectFormat_LjXSTsKAUChCqADJ.html" class="PageParentTitle"> ProjectFormat : ProjectFormat</a> </p> <p class="PageTitle"> ProjectFillColorModel - <a onclick="javascript: showVpLink('discovery.vpp://modelelement/5TXSTsKAUChCqAHD', '\ndiscovery.vpp://modelelement/5TXSTsKAUChCqAHD', '', this); return false;" style="padding-left: 16px; font-size: 12px" href="#"> <img src="../images/icons/link.png" border="0"> Lien</a> </p> <p> </p> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td class="Category"> Propriétés </td> </tr> <tr> <td class="TableCellSpaceHolder5PxTall"> </td> </tr> </table> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td colSpan="4" class="TableHeaderLine"> </td> </tr> <tr> <td colSpan="4" class="TableHeaderLine1"> </td> </tr> <tr class="TableHeader"> <td class="TableCellSpaceHolder10Px"> </td> <td width="25%"> <span class="TableHeaderText">Nom</span> </td> <td class="TableCellSpaceHolder20Px"> </td> <td> <span class="TableHeaderText">Valeur</span> </td> </tr> <tr> <td colSpan="4" class="TableHeaderLine2"> </td> </tr> <tr class="TableRow1"> <td> </td> <td> <span class="TableContent">Base Type</span> </td> <td> </td> <td> <span class="TableContent">ArchiMateDriver</span> </td> </tr> <tr class="TableRow2"> <td> </td> <td> <span class="TableContent">Fill Color Type</span> </td> <td> </td> <td> <span class="TableContent">Solid</span> </td> </tr> <tr class="TableRow1"> <td> </td> <td> <span class="TableContent">Fill Color Gradient Style</span> </td> <td> </td> <td> <span class="TableContent">S-N</span> </td> </tr> <tr class="TableRow2"> <td> </td> <td> <span class="TableContent">Fill Color Transparency</span> </td> <td> </td> <td> <span class="TableContent">0</span> </td> </tr> <tr class="TableRow1"> <td> </td> <td> <span class="TableContent">Fill Color Color1</span> </td> <td> </td> <td> <span class="TableContent">-2380289</span> </td> </tr> <tr class="TableRow2"> <td> </td> <td> <span class="TableContent">Fill Color Color2</span> </td> <td> </td> <td> <span class="TableContent">0</span> </td> </tr> </table> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td class="TableCellSpaceHolder1PxTall"> </td> </tr> <tr> <td class="TableFooter"> </td> </tr> </table> <p> </p> <p> </p> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td class="Category"> Diagrammes Occupés </td> </tr> <tr> <td class="TableCellSpaceHolder5PxTall"> </td> </tr> </table> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td colSpan="4" class="TableHeaderLine"> </td> </tr> <tr> <td colSpan="4" class="TableHeaderLine1"> </td> </tr> <tr class="TableHeader"> <td class="TableCellSpaceHolder10Px"> </td> <td> <span class="TableHeaderText">Diagramme</span> </td> </tr> <tr> <td colSpan="2" class="TableHeaderLine2"> </td> </tr> </table> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td class="TableCellSpaceHolder1PxTall"> </td> </tr> <tr> <td class="TableFooter"> </td> </tr> </table> <div style="height: 20px;"> </div> <table border="0" cellpadding="0" width="100%" cellspacing="0"> <tr> <td class="FooterLine"> </td> </tr> </table> <div class="HeaderText"> discovery </div> </body> </html>
jpdms/snDiscovery
Modele/Consultation/content/ProjectFillColorModel_5TXSTsKAUChCqAHD.html
HTML
gpl-3.0
5,311
import os import re import subprocess # Copied from Trojita """Fetch the .po files from KDE's SVN for GCompris Run me from GCompris's top-level directory. """ SVN_PATH = "svn://anonsvn.kde.org/home/kde/trunk/l10n-kf5/" SOURCE_PO_PATH = "/messages/kdereview/gcompris_qt.po" OUTPUT_PO_PATH = "./po/" OUTPUT_PO_PATTERN = "gcompris_%s.po" fixer = re.compile(r'^#~\| ', re.MULTILINE) re_empty_msgid = re.compile('^msgid ""$', re.MULTILINE) re_empty_line = re.compile('^$', re.MULTILINE) re_has_qt_contexts = re.compile('X-Qt-Contexts: true\\n') if not os.path.exists(OUTPUT_PO_PATH): os.mkdir(OUTPUT_PO_PATH) all_languages = subprocess.check_output(['svn', 'cat', SVN_PATH + 'subdirs'], stderr=subprocess.STDOUT) all_languages = [x.strip() for x in all_languages.split("\n") if len(x)] all_languages.remove("x-test") for lang in all_languages: try: raw_data = subprocess.check_output(['svn', 'cat', SVN_PATH + lang + SOURCE_PO_PATH], stderr=subprocess.PIPE) (transformed, subs) = fixer.subn('# ~| ', raw_data) pos1 = re_empty_msgid.search(transformed).start() pos2 = re_empty_line.search(transformed).start() if re_has_qt_contexts.search(transformed, pos1, pos2) is None: transformed = transformed[:pos2] + \ '"X-Qt-Contexts: true\\n"\n' + \ transformed[pos2:] subs = subs + 1 if (subs > 0): print "Fetched %s (and performed %d cleanups)" % (lang, subs) else: print "Fetched %s" % lang file(OUTPUT_PO_PATH + OUTPUT_PO_PATTERN % lang, "wb").write(transformed) except subprocess.CalledProcessError: print "No data for %s" % lang # Inform qmake about the updated file list #os.utime("CMakeLists.txt", None)
siddhism/GCompris-qt
tools/l10n-fetch-po-files.py
Python
gpl-3.0
1,862
#include <includes.h> #include <utils.h> #include <methnum.h> #include "s_param.h" #include "integral.h" double Ivac ( Param * P , double m ) { double m2 = m*m ; double LE = sqrt ( m2 + P->L2 ); return 0.5 * ONE_OVER_8PI_2 * ( P->L * LE * ( m2 + 2*P->L ) + m2*m2 * log ( m/(P->L + LE) ) ) ; } double dm_Ivac ( Param * P , double m ) { double m2 = m*m ; double LE = sqrt ( m2 + P->L2 ); return m * ONE_OVER_4PI_2 * ( P->L * LE + m2 * log ( m/(P->L + LE) ) ); } double dm2_Ivac ( Param * P , double m ) { double m2 = m*m ; double LE = sqrt ( m2 + P->L2 ); return ONE_OVER_4PI_2 * ( P->L*(3*m2 + P->L2)/LE + 3*m2 * log ( m / (P->L + LE) ) ) ; } double dm3_Ivac ( Param * P , double m ) { double m2 = m*m ; double LE2 = m2 + P->L2 ; double LE = sqrt( LE2 ); return 3 * m * ONE_OVER_2PI_2 * ( P->L*( 3*m2 + 4*P->L2 )/(3*LE2*LE) + log ( m / (P->L + LE) ) ); } double Imed ( Param * P , double m , double T , double mu ) { double m2 = m*m ; double b = 1./T ; double integ ( double p ) { double p2 = p*p ; double E2 = p2 + m2 ; double E = sqrt ( E2 ); double x = -(E - mu) * b ; double y = -(E + mu) * b ; double a = log ( 1 + exp ( x ) ) ; double b = log ( 1 + exp ( y ) ) ; return p2 * ( a + b ); } double I = ONE_OVER_2PI_2 * integ_dp ( integ , 0. , P->L , cutoff ); return I ; } double dm_Imed ( Param * P , double m , double T , double mu ) { double m2 = m*m ; double b = 1./T ; double integ ( double p ) { double p2 = p*p ; double E2 = p2 + m2 ; double E = sqrt ( E2 ); double x = (E - mu) * b ; double y = (E + mu) * b ; double ex = exp ( x ) ; double ey = exp ( y ); double f = 1. / ( 1 + ex ); double fb = 1. / ( 1 + ey ); return p2 * ( - f - fb ) / E ; } double I = integ_dp ( integ , 0. , P->L , cutoff ); return m * I ; } double dT_Imed ( Param * P , double m , double T , double mu ) { } double dmu_Imed ( Param * P , double m , double T , double mu ); /* double dm2_Imed ( Param * P , double m , double T , double mu ); */ /* double dmT_Imed ( Param * P , double m , double T , double mu ); */ /* double dmmu_Imed ( Param * P , double m , double T , double mu ); */ /* double dT2_Imed ( Param * P , double m , double T , double mu ); */ /* double dTmu_Imed ( Param * P , double m , double T , double mu ); */ /* double dmu2_Imed ( Param * P , double m , double T , double mu ); */
AlexandreBiguet/NJLlikeModels
legacy/programs/njl-0/njl1-b/integral.c
C
gpl-3.0
2,487
#include "Scene.h" #include "Screen.h" Scene::Scene() { } void Scene::Update() { Object::AddPreparedObjects(); for (Object* obj : Object::objects) { if (obj->IsActive()) obj->Update(); } for (auto iter = Object::objects.begin(); iter != Object::objects.end(); iter++) { if (!(*iter)->IsActive()) { Object::DeleteObject(*iter); break; } } } void Scene::Render() { SDL_SetRenderDrawColor(Screen::GetRenderer(), 0, 0, 0, 255); SDL_RenderClear(Screen::GetRenderer()); for (Object* obj : Object::objects) { if(obj->IsActive()) obj->Render(); } SDL_RenderPresent(Screen::GetRenderer()); } Object* Scene::FindObject(string name) { return Object::FindObject(name); } void Scene::OnOpened() { } void Scene::OnClosed() { Object::ClearObjects(); } Object** Scene::GetObjectsOfName(string name, int* count) { *count = 0; for (auto iter = Object::objects.begin(); iter != Object::objects.end(); iter++) { if (!(*iter)->IsActive()) continue; Object* obj = *iter; if (obj->GetObjectName() == name) (*count)++; } Object** objs = new Object*[*count]; int index = 0; for (auto iter = Object::objects.begin(); iter != Object::objects.end(); iter++) { if (!(*iter)->IsActive()) continue; Object* obj = *iter; if (obj->GetObjectName() == name) { objs[index] = obj; index++; } } return objs; }
TrinityLab/MagicEdge
MagicEdge/Scene.cpp
C++
gpl-3.0
1,367
package com.simplecity.amp_library.playback; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.RemoteControlClient; import android.os.Bundle; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.text.TextUtils; import android.util.Log; import com.annimon.stream.Stream; import com.bumptech.glide.Glide; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.cantrowitz.rxbroadcast.RxBroadcast; import com.simplecity.amp_library.R; import com.simplecity.amp_library.ShuttleApplication; import com.simplecity.amp_library.androidauto.CarHelper; import com.simplecity.amp_library.androidauto.MediaIdHelper; import com.simplecity.amp_library.data.Repository; import com.simplecity.amp_library.model.Song; import com.simplecity.amp_library.playback.constants.InternalIntents; import com.simplecity.amp_library.ui.screens.queue.QueueItem; import com.simplecity.amp_library.ui.screens.queue.QueueItemKt; import com.simplecity.amp_library.utils.LogUtils; import com.simplecity.amp_library.utils.MediaButtonIntentReceiver; import com.simplecity.amp_library.utils.SettingsManager; import io.reactivex.Completable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import java.util.List; import kotlin.Unit; class MediaSessionManager { private static final String TAG = "MediaSessionManager"; private Context context; private MediaSessionCompat mediaSession; private QueueManager queueManager; private PlaybackManager playbackManager; private PlaybackSettingsManager playbackSettingsManager; private SettingsManager settingsManager; private CompositeDisposable disposables = new CompositeDisposable(); private MediaIdHelper mediaIdHelper; private static String SHUFFLE_ACTION = "ACTION_SHUFFLE"; MediaSessionManager( Context context, QueueManager queueManager, PlaybackManager playbackManager, PlaybackSettingsManager playbackSettingsManager, SettingsManager settingsManager, Repository.SongsRepository songsRepository, Repository.AlbumsRepository albumsRepository, Repository.AlbumArtistsRepository albumArtistsRepository, Repository.GenresRepository genresRepository, Repository.PlaylistsRepository playlistsRepository ) { this.context = context.getApplicationContext(); this.queueManager = queueManager; this.playbackManager = playbackManager; this.settingsManager = settingsManager; this.playbackSettingsManager = playbackSettingsManager; mediaIdHelper = new MediaIdHelper((ShuttleApplication) context.getApplicationContext(), songsRepository, albumsRepository, albumArtistsRepository, genresRepository, playlistsRepository); ComponentName mediaButtonReceiverComponent = new ComponentName(context.getPackageName(), MediaButtonIntentReceiver.class.getName()); mediaSession = new MediaSessionCompat(context, "Shuttle", mediaButtonReceiverComponent, null); mediaSession.setCallback(new MediaSessionCompat.Callback() { @Override public void onPause() { playbackManager.pause(true); } @Override public void onPlay() { playbackManager.play(); } @Override public void onSeekTo(long pos) { playbackManager.seekTo(pos); } @Override public void onSkipToNext() { playbackManager.next(true); } @Override public void onSkipToPrevious() { playbackManager.previous(false); } @Override public void onSkipToQueueItem(long id) { List<QueueItem> queueItems = queueManager.getCurrentPlaylist(); QueueItem queueItem = Stream.of(queueItems) .filter(aQueueItem -> (long) aQueueItem.hashCode() == id) .findFirst() .orElse(null); if (queueItem != null) { playbackManager.setQueuePosition(queueItems.indexOf(queueItem)); } } @Override public void onStop() { playbackManager.stop(true); } @Override public boolean onMediaButtonEvent(Intent mediaButtonEvent) { Log.e("MediaButtonReceiver", "OnMediaButtonEvent called"); MediaButtonIntentReceiver.handleIntent(context, mediaButtonEvent, playbackSettingsManager); return true; } @Override public void onPlayFromMediaId(String mediaId, Bundle extras) { mediaIdHelper.getSongListForMediaId(mediaId, (songs, position) -> { playbackManager.load((List<Song>) songs, position, true, 0); return Unit.INSTANCE; }); } @SuppressWarnings("ResultOfMethodCallIgnored") @SuppressLint("CheckResult") @Override public void onPlayFromSearch(String query, Bundle extras) { if (TextUtils.isEmpty(query)) { playbackManager.play(); } else { mediaIdHelper.handlePlayFromSearch(query, extras) .observeOn(AndroidSchedulers.mainThread()) .subscribe( pair -> { if (!pair.getFirst().isEmpty()) { playbackManager.load(pair.getFirst(), pair.getSecond(), true, 0); } else { playbackManager.pause(false); } }, error -> LogUtils.logException(TAG, "Failed to gather songs from search. Query: " + query, error) ); } } @Override public void onCustomAction(String action, Bundle extras) { if (action.equals(SHUFFLE_ACTION)) { queueManager.setShuffleMode(queueManager.shuffleMode == QueueManager.ShuffleMode.ON ? QueueManager.ShuffleMode.OFF : QueueManager.ShuffleMode.ON); } updateMediaSession(action); } }); mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS | MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS); //For some reason, MediaSessionCompat doesn't seem to pass all of the available 'actions' on as //transport control flags for the RCC, so we do that manually RemoteControlClient remoteControlClient = (RemoteControlClient) mediaSession.getRemoteControlClient(); if (remoteControlClient != null) { remoteControlClient.setTransportControlFlags( RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_NEXT | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_STOP); } IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(InternalIntents.QUEUE_CHANGED); intentFilter.addAction(InternalIntents.META_CHANGED); intentFilter.addAction(InternalIntents.PLAY_STATE_CHANGED); intentFilter.addAction(InternalIntents.POSITION_CHANGED); disposables.add(RxBroadcast.fromBroadcast(context, intentFilter).subscribe(intent -> { String action = intent.getAction(); if (action != null) { updateMediaSession(intent.getAction()); } })); } private void updateMediaSession(final String action) { int playState = playbackManager.isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED; long playbackActions = getMediaSessionActions(); QueueItem currentQueueItem = queueManager.getCurrentQueueItem(); PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder(); builder.setActions(playbackActions); switch (queueManager.shuffleMode) { case QueueManager.ShuffleMode.OFF: builder.addCustomAction( new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_on), R.drawable.ic_shuffle_off_circled).build()); break; case QueueManager.ShuffleMode.ON: builder.addCustomAction( new PlaybackStateCompat.CustomAction.Builder(SHUFFLE_ACTION, context.getString(R.string.btn_shuffle_off), R.drawable.ic_shuffle_on_circled).build()); break; } builder.setState(playState, playbackManager.getSeekPosition(), 1.0f); if (currentQueueItem != null) { builder.setActiveQueueItemId((long) currentQueueItem.hashCode()); } PlaybackStateCompat playbackState = builder.build(); if (action.equals(InternalIntents.PLAY_STATE_CHANGED) || action.equals(InternalIntents.POSITION_CHANGED) || action.equals(SHUFFLE_ACTION)) { mediaSession.setPlaybackState(playbackState); } else if (action.equals(InternalIntents.META_CHANGED) || action.equals(InternalIntents.QUEUE_CHANGED)) { if (currentQueueItem != null) { MediaMetadataCompat.Builder metaData = new MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, String.valueOf(currentQueueItem.getSong().id)) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, currentQueueItem.getSong().artistName) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, currentQueueItem.getSong().albumArtistName) .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, currentQueueItem.getSong().albumName) .putString(MediaMetadataCompat.METADATA_KEY_TITLE, currentQueueItem.getSong().name) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, currentQueueItem.getSong().duration) .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, (long) (queueManager.queuePosition + 1)) //Getting the genre is expensive.. let's not bother for now. //.putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName()) .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null) .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, (long) (queueManager.getCurrentPlaylist().size())); // If we're in car mode, don't wait for the artwork to load before setting session metadata. if (CarHelper.isCarUiMode(context)) { mediaSession.setMetadata(metaData.build()); } mediaSession.setPlaybackState(playbackState); mediaSession.setQueue(QueueItemKt.toMediaSessionQueueItems(queueManager.getCurrentPlaylist())); mediaSession.setQueueTitle(context.getString(R.string.menu_queue)); if (settingsManager.showLockscreenArtwork() || CarHelper.isCarUiMode(context)) { updateMediaSessionArtwork(metaData); } else { mediaSession.setMetadata(metaData.build()); } } } } private void updateMediaSessionArtwork(MediaMetadataCompat.Builder metaData) { QueueItem currentQueueItem = queueManager.getCurrentQueueItem(); if (currentQueueItem != null) { disposables.add(Completable.defer(() -> Completable.fromAction(() -> Glide.with(context) .load(currentQueueItem.getSong().getAlbum()) .asBitmap() .override(1024, 1024) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) { if (bitmap != null) { metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bitmap); } try { mediaSession.setMetadata(metaData.build()); } catch (NullPointerException e) { metaData.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, null); mediaSession.setMetadata(metaData.build()); } } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); mediaSession.setMetadata(metaData.build()); } }) )) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe() ); } } private long getMediaSessionActions() { return PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS | PlaybackStateCompat.ACTION_STOP | PlaybackStateCompat.ACTION_SEEK_TO | PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH | PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM; } MediaSessionCompat.Token getSessionToken() { return mediaSession.getSessionToken(); } void setActive(boolean active) { mediaSession.setActive(active); } void destroy() { disposables.clear(); mediaSession.release(); } }
timusus/Shuttle
app/src/main/java/com/simplecity/amp_library/playback/MediaSessionManager.java
Java
gpl-3.0
15,327
#!/usr/bin/env perl use strict; use warnings; @ARGV >= 1 or die "Usage: \n\tperl $0 event1 event2 ... eventn\n\tperl $0 events.info\n"; my @events; if (@ARGV == 1 and -f $ARGV[0]) { open(IN, "< $ARGV[0]"); foreach (<IN>) { my ($event) = split /\s+/; push @events, $event; } close(IN); } else { @events = @ARGV; } foreach my $event (@events) { system "perl rdseed.pl $event"; system "perl eventinfo.pl $event"; system "perl marktime.pl $event"; system "perl transfer.pl $event"; system "perl rotate.pl $event"; system "perl resample.pl $event"; }
wangliang1989/oh-my-cap
example/process.pl
Perl
gpl-3.0
610
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ (function(){var l={_attachScript:function(e,c){var d=new CKEDITOR.dom.element("script");d.setAttribute("src",e);d.on("error",c);CKEDITOR.document.getBody().append(d);return d},sendRequest:function(e,c,d,a){function b(){g&&(g.remove(),delete CKEDITOR._.jsonpCallbacks[h],g=null)}var k={};c=c||{};var h=CKEDITOR.tools.getNextNumber(),g;c.callback="CKEDITOR._.jsonpCallbacks["+h+"]";CKEDITOR._.jsonpCallbacks[h]=function(a){setTimeout(function(){b();d(a)})};g=this._attachScript(e.output(c),function(){b(); a&&a()});k.cancel=b;return k}};CKEDITOR.plugins.add("embedbase",{lang:"az,ca,cs,da,de,de-ch,en,eo,es,es-mx,eu,fr,gl,hr,hu,id,it,ja,ko,ku,nb,nl,oc,pl,pt,pt-br,ru,sk,sv,tr,ug,uk,zh,zh-cn",requires:"dialog,widget,notificationaggregator",onLoad:function(){CKEDITOR._.jsonpCallbacks={}},init:function(){CKEDITOR.dialog.add("embedBase",this.path+"dialogs/embedbase.js")}});CKEDITOR.plugins.embedBase={createWidgetBaseDefinition:function(e){var c,d=e.lang.embedbase;return{mask:!0,template:"\x3cdiv\x3e\x3c/div\x3e", pathName:d.pathName,_cache:{},urlRegExp:/^((https?:)?\/\/|www\.)/i,init:function(){this.on("sendRequest",function(a){this._sendRequest(a.data)},this,null,999);this.on("dialog",function(a){a.data.widget=this},this);this.on("handleResponse",function(a){if(!a.data.html){var b=this._responseToHtml(a.data.url,a.data.response);null!==b?a.data.html=b:(a.data.errorMessage="unsupportedUrl",a.cancel())}},this,null,999)},loadContent:function(a,b){function c(e){f.response=e;d.editor.widgets.instances[d.id]?d._handleResponse(f)&& (d._cacheResponse(a,e),b.callback&&b.callback()):(CKEDITOR.warn("embedbase-widget-invalid"),f.task&&f.task.done())}b=b||{};var d=this,e=this._getCachedResponse(a),f={noNotifications:b.noNotifications,url:a,callback:c,errorCallback:function(a){d._handleError(f,a);b.errorCallback&&b.errorCallback(a)}};if(e)setTimeout(function(){c(e)});else return b.noNotifications||(f.task=this._createTask()),this.fire("sendRequest",f),f},isUrlValid:function(a){return this.urlRegExp.test(a)&&!1!==this.fire("validateUrl", a)},getErrorMessage:function(a,b,c){(c=e.lang.embedbase[a+(c||"")])||(c=a);return(new CKEDITOR.template(c)).output({url:b||""})},_sendRequest:function(a){var b=this,c=l.sendRequest(this.providerUrl,{url:encodeURIComponent(a.url)},a.callback,function(){a.errorCallback("fetchingFailed")});a.cancel=function(){c.cancel();b.fire("requestCanceled",a)}},_handleResponse:function(a){var b={url:a.url,html:"",response:a.response};if(!1!==this.fire("handleResponse",b))return a.task&&a.task.done(),this._setContent(a.url, b.html),!0;a.errorCallback(b.errorMessage);return!1},_handleError:function(a,b){a.task&&(a.task.cancel(),a.noNotifications||e.showNotification(this.getErrorMessage(b,a.url),"warning"))},_responseToHtml:function(a,b){return"photo"==b.type?'\x3cimg src\x3d"'+CKEDITOR.tools.htmlEncodeAttr(b.url)+'" alt\x3d"'+CKEDITOR.tools.htmlEncodeAttr(b.title||"")+'" style\x3d"max-width:100%;height:auto" /\x3e':"video"==b.type||"rich"==b.type?(b.html=b.html.replace(/<iframe/g,'\x3ciframe tabindex\x3d"-1"'),b.html): null},_setContent:function(a,b){this.setData("url",a);this.element.setHtml(b)},_createTask:function(){if(!c||c.isFinished())c=new CKEDITOR.plugins.notificationAggregator(e,d.fetchingMany,d.fetchingOne),c.on("finished",function(){c.notification.hide()});return c.createTask()},_cacheResponse:function(a,b){this._cache[a]=b},_getCachedResponse:function(a){return this._cache[a]}}},_jsonp:l}})();
Daniel-KM/Omeka-S
application/asset/vendor/ckeditor/plugins/embedbase/plugin.js
JavaScript
gpl-3.0
3,601
<?php require_once 'header.php';?> <div class="page-header"> <h1><?=APP_NAME ?></h1> </div> <a href="auth">auth</a> <!--echo "role=".<?=$role ?>; --> <?php $app = \Slim\Slim::getInstance(); // echo "user->role=".$app->user->role; ?> <?php require_once 'footer.php';?>
winguse/GithubApp
assets/index.php
PHP
gpl-3.0
279
/** * Copyright 2017 Kaloyan Raev * * This file is part of chitanka4kindle. * * chitanka4kindle is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * chitanka4kindle is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with chitanka4kindle. If not, see <http://www.gnu.org/licenses/>. */ package name.raev.kaloyan.kindle.chitanka.model.search.label; public class Label { private String slug; private String name; private int nrOfTexts; public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumberOfTexts() { return nrOfTexts; } public void setNumberOfTexts(int nrOfTexts) { this.nrOfTexts = nrOfTexts; } }
kaloyan-raev/chitanka4kindle
src/main/java/name/raev/kaloyan/kindle/chitanka/model/search/label/Label.java
Java
gpl-3.0
1,251
export class GameId { constructor( public game_id: string) { } }
mkokotovich/play_smear
front_end/src/app/model/game-id.ts
TypeScript
gpl-3.0
81
namespace Net.Demandware.Ocapi.Resources.Data { class Coupons { } }
CoderHead/DemandwareDotNet
Net.Demandware.Ocapi/Resources/Data/Coupons.cs
C#
gpl-3.0
89
/** File errors.cc author Vladislav Tcendrovskii * Copyright (c) 2013 * This source subjected to the Gnu General Public License v3 or later (see LICENSE) * All other rights reserved * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. * */ #include "errors.h" std::string error_str(int errnum) { std::string ans; switch(errnum) { case ENO: ans = "No error"; break; case EZERO: ans = "Division by zero"; break; case EDIM: ans = "Dimension mismatch"; break; case EMEM: ans = "Memory allocation fail"; break; case ETYPE: ans = "Wrong object type/form"; break; case EIND: ans = "Index out of range"; break; default: ans = "Error number " + errnum; break; } return ans; }
vladtcvs/geodesic
src/errors.cc
C++
gpl-3.0
987
#! /usr/bin/python from xml.sax.saxutils import escape import re def ConvertDiagnosticLineToSonqarqube(item): try: id, line, message, source_file = GetDiagnosticFieldsFromDiagnosticLine(item) WriteDiagnosticFieldsToFile(id, line, message, source_file) except: print 'Cant parse line {}'.format(item) def GetDiagnosticFieldsFromDiagnosticLine(item): source_file = re.search('\/(.*?):', item).group(0).replace(':', '') line = re.search(':\d*:', item).group(0).replace(':', '') id = re.search('\[.*\]', item).group(0).replace('[', '').replace(']', '') + '-clang-compiler' message = re.search('warning: (.*)\[', item).group(0).replace('[', '').replace('warning: ', '') return id, line, message, source_file def WriteDiagnosticFieldsToFile(id, line, message, source_file): clang_sonar_report.write(" <error file=\"" + str(source_file) + "\" line=\"" + str(line) + "\" id=\"" + str(id) + "\" msg=\"" + escape(str(message)) + "\"/>\n") def CreateOutputFile(): file_to_write = open('clang_compiler_report.xml', 'w') file_to_write.write('<?xml version="1.0" encoding="UTF-8"?>\n') file_to_write.write('<results>\n') return file_to_write def ReadCompilerReportFile(): file = open('clang_compiler_report_formatted', 'r') messages_xml = file.readlines() return messages_xml def CloseOutputFile(): clang_sonar_report.write('</results>\n') clang_sonar_report.close() def WriteSonarRulesToOutputFile(): item_list = clang_compiler_report for item in item_list: ConvertDiagnosticLineToSonqarqube(item) if __name__ == '__main__': clang_sonar_report = CreateOutputFile() clang_compiler_report = ReadCompilerReportFile() WriteSonarRulesToOutputFile() CloseOutputFile()
deadloko/ClangCompilerWarningsToSonarQubeRules
report_converter.py
Python
gpl-3.0
1,862
/* Coolors Exported Palette - coolors.co/393d3f-437f97-f2bb05-ff8552-071e22 * * Black Olive * rgba(57, 61, 63, 1) * Queen Blue * rgba(67, 127, 151, 1) * Selective Yellow * rgba(242, 187, 5, 1) * Coral * rgba(255, 133, 82, 1) * Dark Jungle Green * rgba(7, 30, 34, 1) * */ html { background: url(../img/6794800763_72896eacd3_o.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } .main { background: rgba(255, 255, 255, 0.75); padding: 2em; margin-top: 2em; margin-bottom: 2em; border-radius: 2px; } i { color: rgba(242, 187, 5, 1); } h1, h2, h3, h4, h5, h6 { color: rgba(7, 30, 34, 1)); }
Seetee/floss.design
css/main.css
CSS
gpl-3.0
743
#!/usr/bin/env python import os import tempfile import pipes import subprocess import time import random import shutil try: from wand.image import Image from wand.display import display except ImportError as e: # cd /usr/lib/ # ln -s libMagickWand-6.Q16.so libMagickWand.so print("Couldn't import Wand package.") print("Please refer to #http://dahlia.kr/wand/ to install it.") import traceback; traceback.print_exc() raise e try: import magic mime = magic.Magic() except ImportError: mime = None #https://github.com/ahupp/python-magic try: from docopt import docopt except ImportError: print("Couldn't import Docopt package.") print("Please refer to#https://github.com/docopt/docopt to install it.") print("/!\\ Option parsing not possible, defaulting to hardcoded values/!\\") def to_bool(val): if val is None: return false return val == 1 def to_int(val): return int(val) def to_str(val): return val def to_path(val): return val OPT_TO_KEY = { '--do-wrap' : ("DO_WRAP", to_bool), '--line-height': ("LINE_HEIGHT", to_int), '--nb-lines' : ('LINES', to_int), '--no-caption' : ("WANT_NO_CAPTION", to_bool), '--force-no-vfs': ("FORCE_VFS", to_bool), '--force-vfs' : ("FORCE_NO_VFS", to_bool), '--pick-random': ("PICK_RANDOM", to_bool), '--put-random' : ("PUT_RANDOM", to_bool), '--resize' : ("DO_RESIZE", to_bool), '--sleep' : ('SLEEP_TIME', to_int), '--width' : ('WIDTH', to_int), '--no-switch-to-mini': ("NO_SWITCH_TO_MINI", to_bool), '<path>' : ('PATH', to_path), '<target>' : ('TARGET', to_path), '--polaroid' : ("DO_POLAROID", to_bool), '--format' : ("IMG_FORMAT_SUFFIX", to_str), '--crop-size' : ("CROP_SIZE", to_int), '~~use-vfs' : ("USE_VFS", to_bool), '--help' : ("HELP", to_bool) } KEY_TO_OPT = dict([(key, (opt, ttype)) for opt, (key, ttype) in OPT_TO_KEY.items()]) PARAMS = { "PATH" : "/home/kevin/mount/first", "TARGET" : "/tmp/final.png", #define the size of the picture "WIDTH" : 2000, #define how many lines do we want "LINES": 2, "LINE_HEIGHT": 200, #minimum width of cropped image. Below that, we black it out #only for POLAROID "CROP_SIZE": 1000, "IMG_FORMAT_SUFFIX": ".png", # False if PATH is a normal directory, True if it is WebAlbums-FS "USE_VFS": False, "FORCE_VFS": False, "FORCE_NO_VFS": False, # True if end-of-line photos are wrapped to the next line "DO_WRAP": False, # True if we want a black background and white frame, plus details "DO_POLAROID": True, "WANT_NO_CAPTION": True, # False if we want to add pictures randomly "PUT_RANDOM": False, "DO_RESIZE": False, ### VFS options ### "NO_SWITCH_TO_MINI": False, ### Directory options ### # False if we pick directory images sequentially, false if we take them randomly "PICK_RANDOM": False, #not implemented yet ## Random wall options ## "SLEEP_TIME": 0, "HELP": False } DEFAULTS = dict([(key, value) for key, value in PARAMS.items()]) DEFAULTS_docstr = dict([(KEY_TO_OPT[key][0], value) for key, value in PARAMS.items()]) usage = """Photo Wall for WebAlbums 3. Usage: photowall.py <path> <target> [options] Arguments: <path> The path where photos are picked up from. [default: %(<path>)s] <target> The path where the target photo is written. Except in POLAROID+RANDOM mode, the image will be blanked out first. [default: %(<target>)s] Options: --polaroid Use polaroid-like images for the wall --width <width> Set final image width. [default: %(--width)d] --nb-lines <nb> Number on lines of the target image. [default: %(--nb-lines)d] --resize Resize images before putting in the wall. [default: %(--resize)s] --line-height <height> Set the height of a single image. [default: %(--line-height)d] --do-wrap If not POLAROID, finish images on the next line. [default: %(--do-wrap)s] --help Display this message Polaroid mode options: --crop-size <crop> Minimum size to allow cropping an image. [default: %(--crop-size)s] --no-caption Disable caption. [default: %(--no-caption)s] --put-random Put images randomly instead of linearily. [default: %(--put-random)s] --sleep <time> If --put-random, time (in seconds) to go asleep before adding a new image. [default: %(--sleep)d] Filesystem options: --force-vfs Treat <path> as a VFS filesystem. [default: %(--force-vfs)s] --force-no-vfs Treat <path> as a normal filesystem. [default: %(--force-no-vfs)s] --no-switch-to-mini If VFS, don't switch from the normal image to the miniature. [default: %(--no-switch-to-mini)s] --pick-random If not VFS, pick images randomly in the <path> folder. [default: %(--pick-random)s] """ % DEFAULTS_docstr class UpdateCallback: def newExec(self): pass def newImage(self, row=0, col=0, filename=""): print("%d.%d > %s" % (row, col, filename)) def updLine(self, row, tmpLine): #print("--- %d ---" % row) pass def newFinal(self, name): pass def finished(self, name): print("==========") def stopRequested(self): return False def checkPause(self): pass updateCB = UpdateCallback() if __name__ == "__main__": arguments = docopt(usage, version="3.5-dev") if arguments["--help"]: print(usage) exit() param_args = dict([(OPT_TO_KEY[opt][0], OPT_TO_KEY[opt][1](value)) for opt, value in arguments.items()]) PARAMS = dict(PARAMS, **param_args) ########################################### ########################################### previous = None def get_next_file_vfs(): global previous if previous is not None: try: os.unlink(previous) except OSerror: pass files = os.listdir(PARAMS["PATH"]) for filename in files: if not "By Years" in filename: previous = PARAMS["PATH"]+filename if "gpx" in previous: return get_next_file() to_return = previous try: to_return = os.readlink(to_return) except OSError: pass if not PARAMS["NO_SWITCH_TO_MINI"]: to_return = to_return.replace("/images/", "/miniatures/") + ".png" return to_return def get_file_details(filename): try: link = filename try: link = os.readlink(filename) except OSError: pass link = pipes.quote(link) names = link[link.index("/miniatures/" if not PARAMS["NO_SWITCH_TO_MINI"] else "/images"):].split("/")[2:] theme, year, album, fname = names return "%s (%s)" % (album, theme) except Exception as e: #print("Cannot get details from {}: {}".format(filename, e)) fname = get_file_details_dir(filename) fname = fname.rpartition(".")[0] fname = fname.replace("_", "\n") return fname ########################################### class GetFileDir: def __init__(self, randomize): self.idx = 0 self.files = os.listdir(PARAMS["PATH"]) if len(self.files) == 0: raise EnvironmentError("No file available") self.files.sort() if randomize: print("RANDOMIZE") random.shuffle(self.files) def get_next_file(self): to_return = self.files[self.idx] self.idx += 1 self.idx %= len(self.files) return PARAMS["PATH"]+to_return def get_file_details_dir(filename): return filename[filename.rindex("/")+1:] ########################################### ########################################### def do_append(first, second, underneath=False): sign = "-" if underneath else "+" background = "-background black" if PARAMS["DO_POLAROID"] else "" command = "convert -gravity center %s %sappend %s %s %s" % (background, sign, first, second, first) ret = subprocess.call(command, shell=True) if ret != 0: raise Exception("Command failed: ", command) def do_polaroid (image, filename=None, background="black", suffix=None): if suffix is None: suffix = PARAMS["IMG_FORMAT_SUFFIX"] tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) tmp.close() image.save(filename=tmp.name) if not(PARAMS["WANT_NO_CAPTION"]) and filename: details = get_file_details(filename) caption = """-caption "%s" """ % details.replace("'", "\\'") else: caption = "" command = "convert -bordercolor snow -background %(bg)s -gravity center %(caption)s +polaroid %(name)s %(name)s" % {"bg" : background, "name":tmp.name, "caption":caption} ret = subprocess.call(command, shell=True) if ret != 0: raise Exception("Command failed: "+ command) img = Image(filename=tmp.name).clone() os.unlink(tmp.name) img.resize(width=image.width, height=image.height) return img def do_blank_image(height, width, filename, color="black"): command = "convert -size %dx%d xc:%s %s" % (width, height, color, filename) ret = subprocess.call(command, shell=True) if ret != 0: raise Exception("Command failed: "+ command) def do_polaroid_and_random_composite(target_filename, target, image, filename): PERCENT_IN = 100 image = do_polaroid(image, filename, background="transparent", suffix=".png") tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"]) image.save(filename=tmp.name) height = random.randint(0, target.height - image.height) - target.height/2 width = random.randint(0, target.width - image.width) - target.width/2 geometry = ("+" if height >= 0 else "") + str(height) + ("+" if width >= 0 else "") + str(width) command = "composite -geometry %s -compose Over -gravity center %s %s %s" % (geometry, tmp.name, target_filename, target_filename) ret = os.system(command) os.unlink(tmp.name) if ret != 0: raise object("failed") def photowall(name): output_final = None previous_filename = None #for all the rows, for row in range(PARAMS["LINES"]): output_row = None row_width = 0 #concatenate until the image width is reached img_count = 0 while row_width < PARAMS["WIDTH"]: # get a new file, or the end of the previous one, if it was split filename = get_next_file() if previous_filename is None else previous_filename mimetype = None previous_filename = None # get a real image if mime is not None: mimetype = mime.from_file(filename) if "symbolic link" in mimetype: filename = os.readlink(filename) mimetype = mime.from_file(filename) if not "image" in mimetype: continue else: try: filename = os.readlink(filename) except OSError: pass updateCB.newImage(row, img_count, filename) img_count += 1 # resize the image image = Image(filename=filename) with image.clone() as clone: factor = float(PARAMS["LINE_HEIGHT"])/clone.height clone.resize(height=PARAMS["LINE_HEIGHT"], width=int(clone.width*factor)) #if the new image makes an overflow if row_width + clone.width > PARAMS["WIDTH"]: #compute how many pixels will overflow overflow = row_width + clone.width - PARAMS["WIDTH"] will_fit = clone.width - overflow if PARAMS["DO_POLAROID"] and will_fit < PARAMS["CROP_SIZE"]: row_width = PARAMS["WIDTH"] previous_filename = filename print("Doesn't fit") continue if PARAMS["DO_WRAP"]: with clone.clone() as next_img: next_img.crop(will_fit+1, 0, width=overflow, height=PARAMS["LINE_HEIGHT"]) tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"]) tmp.close() next_img.save(filename=tmp.name) previous_filename = tmp.name clone.crop(0, 0, width=will_fit, height=PARAMS["LINE_HEIGHT"]) if PARAMS["DO_POLAROID"]: clone = do_polaroid(clone, filename) tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"]) tmp.close() clone.save(filename=tmp.name) row_width += clone.width if output_row is not None: do_append(output_row.name, tmp.name) os.unlink(tmp.name) else: output_row = tmp updateCB.updLine(row, output_row.name) updateCB.checkPause() if updateCB.stopRequested(): break else: if output_final is not None: do_append(output_final.name, output_row.name, underneath=True) os.unlink(output_row.name) else: output_final = output_row updateCB.newFinal(output_final.name) if output_final is not None: shutil.move(output_final.name, name) updateCB.finished(name) else: updateCB.finished(None) return name def random_wall(real_target_filename): name = real_target_filename filename = name[name.rindex("/"):] name = filename[:filename.index(".")] ext = filename[filename.index("."):] target_filename = tempfile.gettempdir()+"/"+name+".2"+ext try: #remove any existing tmp file os.unlink(target_filename) except: pass try: #if source already exist, build up on it os.system("cp %s %s" % (target_filename, real_target_filename)) except: pass print("Target file is %s" % real_target_filename ) target = None if mime is not None: try: mimetype = mime.from_file(target_filename) if "symbolic link" in mimetype: filename = os.readlink(target_filename) mimetype = mime.from_file(target_filename) if "image" in mimetype: target = Image(filename=target_filename) except IOError: pass if target is None: height = PARAMS["LINES"] * PARAMS["LINE_HEIGHT"] do_blank_image(height, PARAMS["WIDTH"], target_filename) target = Image(filename=target_filename) cnt = 0 while True: updateCB.checkPause() if updateCB.stopRequested(): break filename = get_next_file() print(filename) img = Image(filename=filename) with img.clone() as clone: if PARAMS["DO_RESIZE"]: factor = float(PARAMS["LINE_HEIGHT"])/clone.height clone.resize(width=int(clone.width*factor), height=int(clone.height*factor)) do_polaroid_and_random_composite(target_filename, target, clone, filename) updateCB.checkPause() if updateCB.stopRequested(): break updateCB.newImage(row=cnt, filename=filename) updateCB.newFinal(target_filename) os.system("cp %s %s" % (target_filename, real_target_filename)) cnt += 1 updateCB.checkPause() if updateCB.stopRequested(): break time.sleep(PARAMS["SLEEP_TIME"]) updateCB.checkPause() if updateCB.stopRequested(): break get_next_file = None def path_is_jnetfs(path): #check if PATH is VFS or not df_output_lines = os.popen("df -Ph '%s'" % path).read().splitlines() return df_output_lines and "JnetFS" in df_output_lines[1] def fix_args(): global get_next_file if PARAMS["PATH"][-1] != "/": PARAMS["PATH"] += "/" if PARAMS["FORCE_NO_VFS"]: PARAMS["USE_VFS"] elif PARAMS["FORCE_NO_VFS"]: PARAMS["USE_VFS"] else: PARAMS["USE_VFS"] = path_is_jnetfs(PARAMS["PATH"]) if not PARAMS["USE_VFS"]: get_next_file = GetFileDir(PARAMS["PICK_RANDOM"]).get_next_file else: get_next_file = get_next_file_vfs def do_main(): fix_args() updateCB.newExec() target = PARAMS["TARGET"] if not(PARAMS["PUT_RANDOM"]): photowall(target) else: random_wall(target) if __name__== "__main__": do_main()
wazari972/WebAlbums
WebAlbums-FS/WebAlbums-Utils/Photowall/photowall.py
Python
gpl-3.0
15,846
/* * Copyright (C) 2019 phramusca ( https://github.com/phramusca/ ) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jamuz.process.book; import java.util.List; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author phramusca ( https://github.com/phramusca/ ) */ public class TableModelBookTest { /** * */ public TableModelBookTest() { } /** * */ @BeforeClass public static void setUpClass() { } /** * */ @AfterClass public static void tearDownClass() { } /** * */ @Before public void setUp() { } /** * */ @After public void tearDown() { } /** * Test of isCellEditable method, of class TableModelBook. */ @Test public void testIsCellEditable() { System.out.println("isCellEditable"); int row = 0; int col = 0; TableModelBook instance = new TableModelBook(); boolean expResult = false; boolean result = instance.isCellEditable(row, col); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of isCellEnabled method, of class TableModelBook. */ @Test public void testIsCellEnabled() { System.out.println("isCellEnabled"); int row = 0; int col = 0; TableModelBook instance = new TableModelBook(); boolean expResult = false; boolean result = instance.isCellEnabled(row, col); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getBooks method, of class TableModelBook. */ @Test public void testGetBooks() { System.out.println("getBooks"); TableModelBook instance = new TableModelBook(); List<Book> expResult = null; List<Book> result = instance.getBooks(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getFile method, of class TableModelBook. */ @Test public void testGetFile() { System.out.println("getFile"); int index = 0; TableModelBook instance = new TableModelBook(); Book expResult = null; Book result = instance.getFile(index); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getLengthAll method, of class TableModelBook. */ @Test public void testGetLengthAll() { System.out.println("getLengthAll"); TableModelBook instance = new TableModelBook(); long expResult = 0L; long result = instance.getLengthAll(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getNbSelected method, of class TableModelBook. */ @Test public void testGetNbSelected() { System.out.println("getNbSelected"); TableModelBook instance = new TableModelBook(); int expResult = 0; int result = instance.getNbSelected(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getRowCount method, of class TableModelBook. */ @Test public void testGetRowCount() { System.out.println("getRowCount"); TableModelBook instance = new TableModelBook(); int expResult = 0; int result = instance.getRowCount(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getValueAt method, of class TableModelBook. */ @Test public void testGetValueAt() { System.out.println("getValueAt"); int rowIndex = 0; int columnIndex = 0; TableModelBook instance = new TableModelBook(); Object expResult = null; Object result = instance.getValueAt(rowIndex, columnIndex); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of setValueAt method, of class TableModelBook. */ @Test public void testSetValueAt() { System.out.println("setValueAt"); Object value = null; int row = 0; int col = 0; TableModelBook instance = new TableModelBook(); instance.setValueAt(value, row, col); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of select method, of class TableModelBook. */ @Test public void testSelect() { System.out.println("select"); Book book = null; boolean selected = false; TableModelBook instance = new TableModelBook(); instance.select(book, selected); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getLengthSelected method, of class TableModelBook. */ @Test public void testGetLengthSelected() { System.out.println("getLengthSelected"); TableModelBook instance = new TableModelBook(); long expResult = 0L; long result = instance.getLengthSelected(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of getColumnClass method, of class TableModelBook. */ @Test public void testGetColumnClass() { System.out.println("getColumnClass"); int col = 0; TableModelBook instance = new TableModelBook(); Class expResult = null; Class result = instance.getColumnClass(col); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of clear method, of class TableModelBook. */ @Test public void testClear() { System.out.println("clear"); TableModelBook instance = new TableModelBook(); instance.clear(); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of addRow method, of class TableModelBook. */ @Test public void testAddRow() { System.out.println("addRow"); Book file = null; TableModelBook instance = new TableModelBook(); instance.addRow(file); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of removeRow method, of class TableModelBook. */ @Test public void testRemoveRow() { System.out.println("removeRow"); Book file = null; TableModelBook instance = new TableModelBook(); instance.removeRow(file); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of loadThumbnails method, of class TableModelBook. */ @Test public void testLoadThumbnails() { System.out.println("loadThumbnails"); TableModelBook instance = new TableModelBook(); instance.loadThumbnails(); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
phramusca/JaMuz
test/jamuz/process/book/TableModelBookTest.java
Java
gpl-3.0
7,906
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <style> table.head, table.foot { width: 100%; } td.head-rtitle, td.foot-os { text-align: right; } td.head-vol { text-align: center; } table.foot td { width: 50%; } table.head td { width: 33%; } div.spacer { margin: 1em 0; } </style> <title> LNSTAT(8)</title> </head> <body> <div class="mandoc"> <table class="head"> <tbody> <tr> <td class="head-ltitle"> LNSTAT(8)</td> <td class="head-vol"> System Manager's Manual</td> <td class="head-rtitle"> LNSTAT(8)</td> </tr> </tbody> </table> <div class="section"> <h1>NAME</h1> lnstat - unified linux network statistics</div> <div class="section"> <h1>SYNOPSIS</h1> <b>lnstat</b> [<i>options</i>]</div> <div class="section"> <h1>DESCRIPTION</h1> This manual page documents briefly the <b>lnstat</b> command.<div class="spacer"> </div> <b>lnstat</b> is a generalized and more feature-complete replacement for the old rtstat program. In addition to routing cache statistics, it supports any kind of statistics the linux kernel exports via a file in /proc/net/stat/.</div> <div class="section"> <h1>OPTIONS</h1> lnstat supports the following options.<dl> <dt> <b>-h, --help</b></dt> <dd> Show summary of options.</dd> </dl> <dl> <dt> <b>-V, --version</b></dt> <dd> Show version of program.</dd> </dl> <dl> <dt> <b>-c, --count &lt;count&gt;</b></dt> <dd> Print &lt;count&gt; number of intervals.</dd> </dl> <dl> <dt> <b>-d, --dump</b></dt> <dd> Dump list of available files/keys.</dd> </dl> <dl> <dt> <b>-f, --file &lt;file&gt;</b></dt> <dd> Statistics file to use.</dd> </dl> <dl> <dt> <b>-i, --interval &lt;intv&gt;</b></dt> <dd> Set interval to 'intv' seconds.</dd> </dl> <dl> <dt> <b>-j, --json</b></dt> <dd> Display results in JSON format</dd> </dl> <dl> <dt> <b>-k, --keys k,k,k,...</b></dt> <dd> Display only keys specified.</dd> </dl> <dl> <dt> <b>-s, --subject [0-2]</b></dt> <dd> Specify display of subject/header. '0' means no header at all, '1' prints a header only at start of the program and '2' prints a header every 20 lines.</dd> </dl> <dl> <dt> <b>-w, --width n,n,n,...</b></dt> <dd> Width for each field.</dd> </dl> </div> <div class="section"> <h1>USAGE EXAMPLES</h1><dl> <dt> <b># lnstat -d</b></dt> <dd> Get a list of supported statistics files.</dd> </dl> <dl> <dt> <b># lnstat -k arp_cache:entries,rt_cache:in_hit,arp_cache:destroys</b></dt> <dd> Select the specified files and keys.</dd> </dl> <dl> <dt> <b># lnstat -i 10</b></dt> <dd> Use an interval of 10 seconds.</dd> </dl> <dl> <dt> <b># lnstat -f ip_conntrack</b></dt> <dd> Use only the specified file for statistics.</dd> </dl> <dl> <dt> <b># lnstat -s 0</b></dt> <dd> Do not print a header at all.</dd> </dl> <dl> <dt> <b># lnstat -s 20</b></dt> <dd> Print a header at start and every 20 lines.</dd> </dl> <dl> <dt> <b># lnstat -c -1 -i 1 -f rt_cache -k entries,in_hit,in_slow_tot</b></dt> <dd> Display statistics for keys entries, in_hit and in_slow_tot of field rt_cache every second.</dd> </dl> </div> <div class="section"> <h1>SEE ALSO</h1> <b>ip</b>(8), and /usr/share/doc/iproute-doc/README.lnstat (package iproute-doc on Debian)<div style="height: 0.00em;"> &#160;</div> </div> <div class="section"> <h1>AUTHOR</h1> lnstat was written by Harald Welte &lt;[email protected]&gt;.<div class="spacer"> </div> This manual page was written by Michael Prokop &lt;[email protected]&gt; for the Debian project (but may be used by others).</div> <table class="foot"> <tr> <td class="foot-date"> </td> <td class="foot-os"> </td> </tr> </table> </div> </body> </html>
fusion809/fusion809.github.io-old
man/lnstat.8.html
HTML
gpl-3.0
3,538
#!/bin/sh # # Build and test mocpy in a 32-bit environment with python3 # # Usage: # testing_py3_ubuntu32.sh # # Update packages to the latest available versions linux32 --32bit i386 sh -c ' apt update > /dev/null && apt install -y curl pkg-config libfreetype6-dev \ python3 python3-pip >/dev/null && # Symbolic link so that pyO3 points to the # python3 version ln -s /usr/bin/python3 /usr/bin/python ' && # Run the tests linux32 --32bit i386 sh -c ' pip3 install -U pip && # Download the dependencies for compiling cdshealpix pip install -r requirements/contributing.txt && pip install setuptools_rust && # Install Rust compiler curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain nightly -y && export PATH="$HOME/.cargo/bin:$PATH" && # Build the rust dynamic library python3 setup.py build_rust && # Move the dynamic lib to the python package folder find build/ -name "*.so" -type f -exec cp {} ./mocpy \; && python3 -m pytest -v mocpy '
tboch/mocpy
travis/testing_i686.sh
Shell
gpl-3.0
1,050
<?PHP class ftp { /** * @var string FTP Host */ private $_host; /** * @var string FTP Port */ private $_port; /** * @var string FTP User */ private $_user; /** * @var string FTP Passwort */ private $_password; /** * @var ressource FTP Verbindung */ private $_connection; /** * @var bool befindet man sich im Lito Ordner (Root) */ public $lito_root = false; //Wenn true, kann der Paketmanager diese Verbindung verwenden /** * @var bool Steht die Verbindung? */ public $connected = false; /** * @var string PHP or FTP */ private $_method = 'PHP'; /** * Daten angeben um eine Verbindung herzustellen * @param string host * @param string user * @param string password * @param string rootdir Verzeichniss auf dem Server * @param int port */ /** * @var string rootdir for phpmode */ private $rootdir = './'; public function ftp($host = '', $user = '', $password = '', $rootdir = './', $port = 21) { if(defined('C_FTP_METHOD')){ $this->_method = C_FTP_METHOD; } if($this->_method == 'PHP'){ $rootdir=LITO_ROOT_PATH; if(!is_dir($rootdir)) return false; $this->rootdir = preg_replace('!\/$!', '', $rootdir); $this->connected = true; $this->lito_root = true; //echo 'Useing PHP as a workaround!'; } else { $this->_host = $host; $this->_port = $port; $this->_user = $user; $this->_password = $password; if (!@ $this->_connection = ftp_connect($this->_host, $this->_port)) return false; if (!@ ftp_login($this->_connection, $this->_user, $this->_password)) return false; $this->connected = true; ftp_chdir($this->_connection, $rootdir); //if ($this->exists('litotex.php')) $this->lito_root = true; } } /** * Erstellt ein Verzeichniss * @param string dir Verzeichnissname */ public function mk_dir($dir) { if (!$this->connected) return false; if ($this->exists($dir)){ return true; } if($this->_method == 'PHP') return mkdir($this->rootdir.'/'.$dir); else return @ ftp_mkdir($this->_connection, $dir); } /** * L�scht ein Verzeichniss * @param string dir Verzeichnissname */ public function rm_dir($dir) { $dir = preg_replace('!^\/!', '', $dir); if (!$this->connected) return false; if (!$this->exists($dir)) return false; if($this->_method == 'PHP'){ $this->_php_all_delete($this->_rootdir.'/'.$dir); } else { $list = $this->list_files($dir); if (is_array($list)) { foreach ($list as $file) { if (!is_array($this->list_files($file)) || in_array($file, $this->list_files($file))) { $this->rm_file($file); } else { $this->rm_dir($file); } } } return @ ftp_rmdir($this->_connection, $dir); } } /** * Verschiebt ein Verzeichniss oder eine Datei * @param string file Verzeichnissname/Dateiname * @param string dest Ziel */ public function mv($file, $dest) { if (!$this->connected) return false; if (!$this->exists($file)) return false; if($this->_method == 'PHP'){ return @ rename($this->rootdir.'/'.$file, $this->rootdir.'/'.$dest); } else return @ftp_rename($this->_connection, $file, $dest); } /** * Listet den Inhalt eines Verzeichnisses auf * @param string dir Verzeichnissname */ public function list_files($dir = './') { if (!$this->connected) return false; if($this->_method == 'PHP'){ if(!is_dir($this->rootdir.'/'.$dir)) return false; $dir = opendir($this->rootdir.'/'.$dir); $return = array(); while($file = readdir($dir)){ if($file == '.' || $file == '..') continue; $return[] = $file; } return $return; } else { $dir = preg_replace('!^\/!', '', $dir); $return = @ ftp_nlist($this->_connection, './'.$dir); if(!is_array($return)) return false; foreach($return as $i => $param){ $return[$i] = preg_replace('!^'.str_replace("/", "\\/", $dir).'\\/!', '', $param); } return $return; } } /** * L�scht eine Datei * @param string file Dateiname */ public function rm_file($file) { if (!$this->connected) return false; if (!$this->exists($file)) return true; if($file == '.' || $file == '..') return false; if($this->_method == 'PHP'){ if(!is_file($this->rootdir.'/'.$file)) return false; return @unlink($this->rootdir.'/'.$file); } else return @ftp_delete($this->_connection, $file); } /** * Setzt Berechtigungen * @param string ch Berechtigungen * @param string file Dateiname */ public function chown_perm($ch, $file) { if (!$this->connected) return false; if (!$this->exists($file)){ return false; } if($this->_method == 'PHP'){ return @chmod($this->rootdir.'/'.$file, $ch); } else return @ftp_chmod($this->_connection, $ch, $file); } /** * Gibt den Inhalt einer Datei zur�ck * @param string file Dateiname */ public function get_contents($file) { if (!$this->connected) return false; if (!$this->exists($file)) return false; if($this->_method == 'PHP'){ if(!is_file($this->rootdir.'/'.$file)) return false; return file_get_contents($this->rootdir.'/'.$file); } else { $time = time(); $local_cache = fopen(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time, 'w'); ftp_fget($this->_connection, $local_cache, $file, FTP_BINARY); $return = file_get_contents(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time); fclose($local_cache); unlink(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time); return $return; } } /** * Schreibt in eine Datei * @param string file Dateiname * @param string new Neuer Inhalt */ public function write_contents($file, $new, $overwrite = true) { if (!$this->connected) return false; if ($overwrite && $this->exists($file)) return false; if($this->_method == 'PHP'){ $file_h = fopen($this->rootdir.'/'.$file, 'w'); fwrite($file_h, $new); return @fclose($file_h); } else { $time = time(); $local_cache = fopen(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time, 'w'); fwrite($local_cache, $new); fclose($local_cache); $local_cache = fopen(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time, 'r'); @$return = ftp_fput($this->_connection, $file, $local_cache, FTP_BINARY); fclose($local_cache); unlink(LITO_ROOT_PATH . 'cache/ftpcache.php' . $time); return $return; } } /** * Kopiert dateien per FTP * @param string file Zu kopierende Datei * @param string dest Ziel */ public function copy_file($file, $dest){ $file_c = $this->get_contents($file); $this->write_contents($dest, $file_c); } /** * Kopiert Dateien und Ordner rekursiv per FTP * @param string source Zu kopierendes Verzeichniss * @param string dest Ziel */ public function copy_req($source, $dest){ $source = preg_replace("!\/$!", '', $source); if(!$this->list_files($source)) return false; if(!$this->exists($dest)) if(!$this->mk_dir($dest)) return false; $source_files = $this->list_files($source); foreach($source_files as $file){ if($file == '.' || $file == '..' || $file == $source.'/.' || $file == $source.'/..') continue; if(!preg_match('!'.preg_replace('!^\/!', '', $source).'!', $file)) $file = $source.'/'.$file; if($this->isdir($file)) $this->copy_req($file, str_replace($source, $dest, $file)); else{ $this->copy_file($file, str_replace($source, $dest, $file)); } } } /** * Löscht ein Verzeichniss rekursiv * @param string dir Verzeichniss */ public function req_remove($dir){ $dir = preg_replace('!\/$!', '', $dir); if(!$this->exists($dir)){ return true; } if($dir == '.' || $dir == '..') return false; if(!$this->isdir($dir)){ return $this->rm_file($dir); } if($this->_method == 'PHP'){ $this->_php_all_delete($this->rootdir.'/'.$dir); } else { $files = $this->list_files($dir); foreach($files as $file){ if($file == '.' || $file == '..') continue; $file = $dir.'/'.$file; $this->req_remove($file); } $this->rm_dir($dir); } } public function isdir($file){ if(!$this->exists($file)) return false; if($this->_method == 'PHP'){ return is_dir($this->rootdir.'/'.$file); } else { if(ftp_size($this->_connection, $file) == -1) return true; return false; } } /** * Schließt die FTP Verbindung */ public function disconnect() { if($this->_method == 'PHP') $this->connected = false; else{ if (!$this->connected) return false; ftp_close($this->_connection); $this->connected = false; } } /** * �berpr�ft ob die angegebene Datei/das Verzeichniss existiert * @param string file * @return bool */ public function exists($file) { if($this->_method == 'PHP'){ return file_exists($this->rootdir.'/'.$file); } else { $dir = dirname($file); $file = basename($file); if($dir == '.') $dir = ''; if($dir == '' && count($this->list_files($dir)) == 0) $dir = '.'; if (@ in_array($file, @ $this->list_files($dir), '/')) return true; else return false; } } /** * Deletes a Directory recursivly * @param $verz Direcotory * @param $folder foldersarray (ignore!) * @return array, deletet folders */ private function _php_dir_delete($verz, $folder = array()) { $folder[] = $verz; $fp = opendir($verz); while ($dir_file = readdir($fp)) { if (($dir_file == '.') || ($dir_file == '..')) continue; $neu_file = $verz . '/' . $dir_file; if (is_dir($neu_file)) $folder = $this->_php_dir_delete($neu_file, $folder); else unlink($neu_file); } closedir($fp); return $folder; } /** * Deletes all (dirs and files) * @param $dir_file dir or file to delete * @return bool */ private function _php_all_delete($dir_file) { if (is_dir($dir_file)) { $array = $this->_php_dir_delete($dir_file); $array = array_reverse($array); foreach ($array as $elem) rmdir($elem); } elseif (is_file($dir_file)) unlink($dir_file); else return false; } } ?>
extremmichi/Litotex-0.7
setup/ftp_class.php
PHP
gpl-3.0
9,941
<head><title>Popular Baby Names</title> <meta name="dc.language" scheme="ISO639-2" content="eng"> <meta name="dc.creator" content="OACT"> <meta name="lead_content_manager" content="JeffK"> <meta name="coder" content="JeffK"> <meta name="dc.date.reviewed" scheme="ISO8601" content="2005-12-30"> <link rel="stylesheet" href="../OACT/templatefiles/master.css" type="text/css" media="screen"> <link rel="stylesheet" href="../OACT/templatefiles/custom.css" type="text/css" media="screen"> <link rel="stylesheet" href="../OACT/templatefiles/print.css" type="text/css" media="print"> </head> <body bgcolor="#ffffff" text="#000000" topmargin="1" leftmargin="0"> <table width="100%" border="0" cellspacing="0" cellpadding="4"> <tbody> <tr> <td class="sstop" valign="bottom" align="left" width="25%"> Social Security Online </td> <td valign="bottom" class="titletext"> <!-- sitetitle -->Popular Baby Names </td> </tr> <tr bgcolor="#333366"><td colspan="2" height="2"></td></tr> <tr> <td class="graystars" width="25%" valign="top"> </td> <td valign="top"> <a href="http://www.ssa.gov/"><img src="/templateimages/tinylogo.gif" width="52" height="47" align="left" alt="SSA logo: link to Social Security home page" border="0"></a><a name="content"></a> <h1>Popular Names by State</h1>August 31, 2007</td> </tr> <tr bgcolor="#333366"><td colspan="2" height="1"></td></tr> </tbody></table> <table width="100%" border="0" cellspacing="0" cellpadding="4" summary="formatting"> <tbody> <tr align="left" valign="top"> <td width="25%" class="whiteruled2-td"> <table width="92%" border="0" cellpadding="4" class="ninetypercent"> <tr> <td class="whiteruled-td"><a href="../OACT/babynames/index.html">Popular Baby Names</a></td> </tr> <tr> <td class="whiteruled-td"><a href="../OACT/babynames/background.html"> Background information</a></td> </tr> <tr> <td class="whiteruled2-td"><a href="../OACT/babynames/USbirthsNumident.html">Number of U. S. births</a> based on Social Security card applications</td> </tr> </table> <p> Make another selection?<br /> <form method="post" action="/cgi-bin/namesbystate.cgi"> &nbsp;<label for="state">Select State</label><br /> &nbsp;<select name="state" size="1" id="state"> <option value="AK">Alaska</option> <option value="AL">Alabama</option> <option value="AR" selected>Arkansas</option> <option value="AZ">Arizona</option> <option value="CA">California</option> <option value="CO">Colorado</option> <option value="CT">Connecticut</option> <option value="DC">District of Columbia</option> <option value="DE">Delaware</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="HI">Hawaii</option> <option value="IA">Iowa</option> <option value="ID">Idaho</option> <option value="IL">Illinois</option> <option value="IN">Indiana</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="MA">Massachusetts</option> <option value="MD">Maryland</option> <option value="ME">Maine</option> <option value="MI">Michigan</option> <option value="MN">Minnesota</option> <option value="MO">Missouri</option> <option value="MS">Mississippi</option> <option value="MT">Montana</option> <option value="NC">North Carolina</option> <option value="ND">North Dakota</option> <option value="NE">Nebraska</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NM">New Mexico</option> <option value="NV">Nevada</option> <option value="NY">New York</option> <option value="OH">Ohio</option> <option value="OK">Oklahoma</option> <option value="OR">Oregon</option> <option value="PA">Pennsylvania</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="SD">South Dakota</option> <option value="TN">Tennessee</option> <option value="TX">Texas</option> <option value="UT">Utah</option> <option value="VA">Virginia</option> <option value="VT">Vermont</option> <option value="WA">Washington</option> <option value="WI">Wisconsin</option> <option value="WV">West Virginia</option> <option value="WY">Wyoming</option> </select><p> &nbsp;<label for="year">Enter a year between<br />&nbsp;1960-2004:</label> &nbsp; <input type="text" name="year" size="4" maxlength="4" id="year" value="1981"> <p>&nbsp;<input type="submit" value=" Go "> </form> </p> </td> <td class="greyruled-td"> <p> The following table shows the 100 most frequent given names for male and female births in 1981 in Arkansas. The number to the right of each name is the number of occurrences in the data. The source is a 100% sample based on Social Security card application data. See the <a href="../OACT/babynames/background.html">limitations</a> of this data source. <p align="center"> <table width="72%" border="1" bordercolor="#aaabbb" cellpadding="1" cellspacing="0"> <caption><b>Popularity for top 100 names in Arkansas for births in 1981</b> </caption> <tr align="center" valign="bottom"> <th scope="col" width="12%" bgcolor="#efefef">Rank</th> <th scope="col" width="22%" bgcolor="#99ccff">Male name</th> <th scope="col" width="22%" bgcolor="#99ccff">Number of<br /> males</th> <th scope="col" width="22%" bgcolor="pink">Female name</th> <th scope="col" width="22%" bgcolor="pink">Number of<br /> females</th></tr> <tr align="right"><td>1</td> <td align="center">Joshua</td> <td>519</td> <td align="center">Amanda</td> <td>517</td></tr> <tr align="right"><td>2</td> <td align="center">Michael</td> <td>512</td> <td align="center">Jennifer</td> <td>508</td></tr> <tr align="right"><td>3</td> <td align="center">James</td> <td>499</td> <td align="center">Jessica</td> <td>354</td></tr> <tr align="right"><td>4</td> <td align="center">Christopher</td> <td>478</td> <td align="center">Crystal</td> <td>268</td></tr> <tr align="right"><td>5</td> <td align="center">Jason</td> <td>430</td> <td align="center">Sarah</td> <td>241</td></tr> <tr align="right"><td>6</td> <td align="center">John</td> <td>392</td> <td align="center">Amber</td> <td>233</td></tr> <tr align="right"><td>7</td> <td align="center">Matthew</td> <td>351</td> <td align="center">Ashley</td> <td>223</td></tr> <tr align="right"><td>8</td> <td align="center">David</td> <td>331</td> <td align="center">Amy</td> <td>204</td></tr> <tr align="right"><td>9</td> <td align="center">Brandon</td> <td>328</td> <td align="center">Kimberly</td> <td>202</td></tr> <tr align="right"><td>10</td> <td align="center">Justin</td> <td>317</td> <td align="center">Melissa</td> <td>200</td></tr> <tr align="right"><td>11</td> <td align="center">Robert</td> <td>312</td> <td align="center">Tiffany</td> <td>198</td></tr> <tr align="right"><td>12</td> <td align="center">Jeremy</td> <td>300</td> <td align="center">Angela</td> <td>188</td></tr> <tr align="right"><td>13</td> <td align="center">William</td> <td>285</td> <td align="center">Stephanie</td> <td>185</td></tr> <tr align="right"><td>14</td> <td align="center">Jonathan</td> <td>265</td> <td align="center">April</td> <td>183</td></tr> <tr align="right"><td>15</td> <td align="center">Joseph</td> <td>245</td> <td align="center">Heather</td> <td>177</td></tr> <tr align="right"><td>16</td> <td align="center">Brian</td> <td>204</td> <td align="center">Brandy</td> <td>165</td></tr> <tr align="right"><td>17</td> <td align="center">Daniel</td> <td>194</td> <td align="center">Rebecca</td> <td>159</td></tr> <tr align="right"><td>18</td> <td align="center">Charles</td> <td>174</td> <td align="center">Rachel</td> <td>157</td></tr> <tr align="right"><td>19</td> <td align="center">Kevin</td> <td>171</td> <td align="center">Mary</td> <td>132</td></tr> <tr align="right"><td>20</td> <td align="center">Steven</td> <td>167</td> <td align="center">Elizabeth</td> <td>131</td></tr> <tr align="right"><td>21</td> <td align="center">Timothy</td> <td>162</td> <td align="center">Jamie</td> <td>125</td></tr> <tr align="right"><td>22</td> <td align="center">Eric</td> <td>158</td> <td align="center">Andrea</td> <td>119</td></tr> <tr align="right"><td>23</td> <td align="center">Nicholas</td> <td>155</td> <td align="center">Brandi</td> <td>117</td></tr> <tr align="right"><td>24</td> <td align="center">Aaron</td> <td>154</td> <td align="center">Laura</td> <td>116</td></tr> <tr align="right"><td>25</td> <td align="center">Adam</td> <td>151</td> <td align="center">Lisa</td> <td>116</td></tr> <tr align="right"><td>26</td> <td align="center">Dustin</td> <td>148</td> <td align="center">Misty</td> <td>116</td></tr> <tr align="right"><td>27</td> <td align="center">Richard</td> <td>136</td> <td align="center">Leslie</td> <td>86</td></tr> <tr align="right"><td>28</td> <td align="center">Anthony</td> <td>133</td> <td align="center">Courtney</td> <td>85</td></tr> <tr align="right"><td>29</td> <td align="center">Ryan</td> <td>133</td> <td align="center">Michelle</td> <td>85</td></tr> <tr align="right"><td>30</td> <td align="center">Thomas</td> <td>131</td> <td align="center">Erin</td> <td>84</td></tr> <tr align="right"><td>31</td> <td align="center">Benjamin</td> <td>114</td> <td align="center">Christina</td> <td>82</td></tr> <tr align="right"><td>32</td> <td align="center">Nathan</td> <td>113</td> <td align="center">Erica</td> <td>77</td></tr> <tr align="right"><td>33</td> <td align="center">Stephen</td> <td>109</td> <td align="center">Sara</td> <td>77</td></tr> <tr align="right"><td>34</td> <td align="center">Travis</td> <td>109</td> <td align="center">Julie</td> <td>76</td></tr> <tr align="right"><td>35</td> <td align="center">Bradley</td> <td>106</td> <td align="center">Shannon</td> <td>76</td></tr> <tr align="right"><td>36</td> <td align="center">Chad</td> <td>106</td> <td align="center">Emily</td> <td>73</td></tr> <tr align="right"><td>37</td> <td align="center">Andrew</td> <td>101</td> <td align="center">Latoya</td> <td>70</td></tr> <tr align="right"><td>38</td> <td align="center">Marcus</td> <td>96</td> <td align="center">Samantha</td> <td>70</td></tr> <tr align="right"><td>39</td> <td align="center">Jacob</td> <td>95</td> <td align="center">Kelly</td> <td>69</td></tr> <tr align="right"><td>40</td> <td align="center">Jeffrey</td> <td>94</td> <td align="center">Tara</td> <td>66</td></tr> <tr align="right"><td>41</td> <td align="center">Mark</td> <td>93</td> <td align="center">Carrie</td> <td>65</td></tr> <tr align="right"><td>42</td> <td align="center">Patrick</td> <td>88</td> <td align="center">Holly</td> <td>64</td></tr> <tr align="right"><td>43</td> <td align="center">Kenneth</td> <td>82</td> <td align="center">Lindsey</td> <td>58</td></tr> <tr align="right"><td>44</td> <td align="center">Jesse</td> <td>78</td> <td align="center">Natalie</td> <td>58</td></tr> <tr align="right"><td>45</td> <td align="center">Billy</td> <td>77</td> <td align="center">Natasha</td> <td>58</td></tr> <tr align="right"><td>46</td> <td align="center">Bobby</td> <td>77</td> <td align="center">Alicia</td> <td>57</td></tr> <tr align="right"><td>47</td> <td align="center">Paul</td> <td>77</td> <td align="center">Katherine</td> <td>57</td></tr> <tr align="right"><td>48</td> <td align="center">Larry</td> <td>75</td> <td align="center">Christy</td> <td>56</td></tr> <tr align="right"><td>49</td> <td align="center">Gary</td> <td>74</td> <td align="center">Patricia</td> <td>56</td></tr> <tr align="right"><td>50</td> <td align="center">Derrick</td> <td>73</td> <td align="center">Brooke</td> <td>55</td></tr> <tr align="right"><td>51</td> <td align="center">Jared</td> <td>73</td> <td align="center">Lauren</td> <td>54</td></tr> <tr align="right"><td>52</td> <td align="center">Jimmy</td> <td>70</td> <td align="center">Kristin</td> <td>53</td></tr> <tr align="right"><td>53</td> <td align="center">Jeffery</td> <td>69</td> <td align="center">Kristen</td> <td>52</td></tr> <tr align="right"><td>54</td> <td align="center">Keith</td> <td>68</td> <td align="center">Nicole</td> <td>52</td></tr> <tr align="right"><td>55</td> <td align="center">Scott</td> <td>67</td> <td align="center">Cynthia</td> <td>51</td></tr> <tr align="right"><td>56</td> <td align="center">Antonio</td> <td>64</td> <td align="center">Leah</td> <td>51</td></tr> <tr align="right"><td>57</td> <td align="center">Phillip</td> <td>64</td> <td align="center">Dana</td> <td>50</td></tr> <tr align="right"><td>58</td> <td align="center">Shawn</td> <td>63</td> <td align="center">Tonya</td> <td>50</td></tr> <tr align="right"><td>59</td> <td align="center">Jerry</td> <td>61</td> <td align="center">Pamela</td> <td>49</td></tr> <tr align="right"><td>60</td> <td align="center">Terry</td> <td>59</td> <td align="center">Katrina</td> <td>48</td></tr> <tr align="right"><td>61</td> <td align="center">Gregory</td> <td>58</td> <td align="center">Tina</td> <td>48</td></tr> <tr align="right"><td>62</td> <td align="center">Kyle</td> <td>58</td> <td align="center">Candace</td> <td>46</td></tr> <tr align="right"><td>63</td> <td align="center">Zachary</td> <td>57</td> <td align="center">Candice</td> <td>45</td></tr> <tr align="right"><td>64</td> <td align="center">Cody</td> <td>56</td> <td align="center">Kristy</td> <td>44</td></tr> <tr align="right"><td>65</td> <td align="center">Brent</td> <td>55</td> <td align="center">Lori</td> <td>44</td></tr> <tr align="right"><td>66</td> <td align="center">Wesley</td> <td>53</td> <td align="center">Megan</td> <td>44</td></tr> <tr align="right"><td>67</td> <td align="center">Bryan</td> <td>52</td> <td align="center">Miranda</td> <td>44</td></tr> <tr align="right"><td>68</td> <td align="center">Corey</td> <td>52</td> <td align="center">Stacy</td> <td>44</td></tr> <tr align="right"><td>69</td> <td align="center">Derek</td> <td>51</td> <td align="center">Casey</td> <td>41</td></tr> <tr align="right"><td>70</td> <td align="center">Ricky</td> <td>51</td> <td align="center">Krystal</td> <td>41</td></tr> <tr align="right"><td>71</td> <td align="center">Casey</td> <td>50</td> <td align="center">Monica</td> <td>40</td></tr> <tr align="right"><td>72</td> <td align="center">Ronald</td> <td>50</td> <td align="center">Robin</td> <td>40</td></tr> <tr align="right"><td>73</td> <td align="center">Donald</td> <td>49</td> <td align="center">Anna</td> <td>39</td></tr> <tr align="right"><td>74</td> <td align="center">Edward</td> <td>48</td> <td align="center">Latasha</td> <td>38</td></tr> <tr align="right"><td>75</td> <td align="center">Randy</td> <td>45</td> <td align="center">Tasha</td> <td>38</td></tr> <tr align="right"><td>76</td> <td align="center">Samuel</td> <td>45</td> <td align="center">Susan</td> <td>37</td></tr> <tr align="right"><td>77</td> <td align="center">Johnny</td> <td>44</td> <td align="center">Felicia</td> <td>35</td></tr> <tr align="right"><td>78</td> <td align="center">Danny</td> <td>43</td> <td align="center">Lindsay</td> <td>35</td></tr> <tr align="right"><td>79</td> <td align="center">Jeremiah</td> <td>40</td> <td align="center">Mandy</td> <td>35</td></tr> <tr align="right"><td>80</td> <td align="center">Raymond</td> <td>39</td> <td align="center">Melanie</td> <td>35</td></tr> <tr align="right"><td>81</td> <td align="center">Sean</td> <td>39</td> <td align="center">Tracy</td> <td>35</td></tr> <tr align="right"><td>82</td> <td align="center">Clinton</td> <td>38</td> <td align="center">Alisha</td> <td>34</td></tr> <tr align="right"><td>83</td> <td align="center">Blake</td> <td>37</td> <td align="center">Linda</td> <td>34</td></tr> <tr align="right"><td>84</td> <td align="center">Douglas</td> <td>36</td> <td align="center">Bethany</td> <td>33</td></tr> <tr align="right"><td>85</td> <td align="center">Johnathan</td> <td>36</td> <td align="center">Cassandra</td> <td>33</td></tr> <tr align="right"><td>86</td> <td align="center">Nathaniel</td> <td>36</td> <td align="center">Danielle</td> <td>33</td></tr> <tr align="right"><td>87</td> <td align="center">Tony</td> <td>36</td> <td align="center">Julia</td> <td>33</td></tr> <tr align="right"><td>88</td> <td align="center">Jessie</td> <td>35</td> <td align="center">Summer</td> <td>33</td></tr> <tr align="right"><td>89</td> <td align="center">Lucas</td> <td>35</td> <td align="center">Tammy</td> <td>33</td></tr> <tr align="right"><td>90</td> <td align="center">Ronnie</td> <td>35</td> <td align="center">Allison</td> <td>32</td></tr> <tr align="right"><td>91</td> <td align="center">Tommy</td> <td>35</td> <td align="center">Brittany</td> <td>32</td></tr> <tr align="right"><td>92</td> <td align="center">Clayton</td> <td>34</td> <td align="center">Rebekah</td> <td>32</td></tr> <tr align="right"><td>93</td> <td align="center">George</td> <td>34</td> <td align="center">Sherry</td> <td>32</td></tr> <tr align="right"><td>94</td> <td align="center">Joe</td> <td>34</td> <td align="center">Jenny</td> <td>31</td></tr> <tr align="right"><td>95</td> <td align="center">Rodney</td> <td>34</td> <td align="center">Katie</td> <td>31</td></tr> <tr align="right"><td>96</td> <td align="center">Adrian</td> <td>33</td> <td align="center">Regina</td> <td>31</td></tr> <tr align="right"><td>97</td> <td align="center">Micheal</td> <td>33</td> <td align="center">Rhonda</td> <td>31</td></tr> <tr align="right"><td>98</td> <td align="center">Randall</td> <td>33</td> <td align="center">Stacey</td> <td>31</td></tr> <tr align="right"><td>99</td> <td align="center">Lee</td> <td>32</td> <td align="center">Tabitha</td> <td>31</td></tr> <tr align="right"><td>100</td> <td align="center">Shane</td> <td>32</td> <td align="center">Whitney</td> <td>31</td></tr> </table></td></tr></table> <table class="printhide" width="100%" border="0" cellpadding="1" cellspacing="0"> <tr bgcolor="#333366"><td height="1" valign="top" height="1" colspan="3"></td></tr> <tr> <td width="26%" valign="middle">&nbsp;<a href="http://www.firstgov.gov"><img src="/templateimages/firstgov3.gif" width="72" height="15" alt="Link to FirstGov.gov: U.S. Government portal" border="0"></a></td> <td valign="top" class="seventypercent"> <a href="http://www.ssa.gov/privacy.html">Privacy Policy</a>&nbsp; | <a href="http://www.ssa.gov/websitepolicies.htm">Website Policies &amp; Other Important Information</a>&nbsp; | <a href="http://www.ssa.gov/sitemap.htm">Site Map</a></td> </tr> </table> </body></html>
guydavis/babynamemap
stats/usa/AR/1981.html
HTML
gpl-3.0
20,463
#ifndef RESIDUAL_H #define RESIDUAL_H #include "base.h" #include "peak_detection.h" #include "partial_tracking.h" #include "synthesis.h" extern "C" { #include "sms.h" } using namespace std; namespace simpl { // --------------------------------------------------------------------------- // Residual // // Calculate a residual signal // --------------------------------------------------------------------------- class Residual { protected: int _frame_size; int _hop_size; int _sampling_rate; Frames _frames; void clear(); public: Residual(); ~Residual(); virtual void reset(); int frame_size(); virtual void frame_size(int new_frame_size); int hop_size(); virtual void hop_size(int new_hop_size); int sampling_rate(); void sampling_rate(int new_sampling_rate); virtual void residual_frame(Frame* frame); virtual void find_residual(int synth_size, sample* synth, int original_size, sample* original, int residual_size, sample* residual); virtual void synth_frame(Frame* frame); virtual Frames synth(Frames& frames); virtual Frames synth(int original_size, sample* original); }; // --------------------------------------------------------------------------- // SMSResidual // --------------------------------------------------------------------------- class SMSResidual : public Residual { private: SMSResidualParams _residual_params; SMSPeakDetection _pd; SMSPartialTracking _pt; SMSSynthesis _synth; public: SMSResidual(); ~SMSResidual(); void reset(); void frame_size(int new_frame_size); void hop_size(int new_hop_size); int num_stochastic_coeffs(); void num_stochastic_coeffs(int new_num_stochastic_coeffs); void residual_frame(Frame* frame); void synth_frame(Frame* frame); }; } // end of namespace Simpl #endif
johnglover/simpl
src/simpl/residual.h
C
gpl-3.0
2,081
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.12"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>ndnSIM for iCenS: /home/network/NSOL/ndnSIM-dev/ns-3/src/ndnSIM/model/cs/custom-policies Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">ndnSIM for iCenS </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.12 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,'Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_3f14f6767c31cb4a1d22c13c18cc6fc3.html">model</a></li><li class="navelem"><a class="el" href="dir_b8559f3e867009595f1342820a7715ba.html">cs</a></li><li class="navelem"><a class="el" href="dir_5d6f6271b0ce2ddab294170ccac04363.html">custom-policies</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">custom-policies Directory Reference</div> </div> </div><!--header--> <div class="contents"> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.12 </small></address> </body> </html>
nsol-nmsu/ndnSIM
docs/icens/html/dir_5d6f6271b0ce2ddab294170ccac04363.html
HTML
gpl-3.0
3,033
/* * This file is part of EchoPet. * * EchoPet is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EchoPet is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EchoPet. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.echopet.compat.nms.v1_14_R1.entity.type; import com.dsh105.echopet.compat.api.entity.EntityPetType; import com.dsh105.echopet.compat.api.entity.EntitySize; import com.dsh105.echopet.compat.api.entity.IPet; import com.dsh105.echopet.compat.api.entity.PetType; import com.dsh105.echopet.compat.api.entity.SizeCategory; import com.dsh105.echopet.compat.api.entity.type.nms.IEntityGiantPet; import net.minecraft.server.v1_14_R1.EntityTypes; import net.minecraft.server.v1_14_R1.World; @EntitySize(width = 5.5F, height = 5.5F) @EntityPetType(petType = PetType.GIANT) public class EntityGiantPet extends EntityZombiePet implements IEntityGiantPet{ public EntityGiantPet(World world){ super(EntityTypes.GIANT, world); } public EntityGiantPet(World world, IPet pet){ super(EntityTypes.GIANT, world, pet); } @Override public SizeCategory getSizeCategory(){ return SizeCategory.OVERSIZE; } }
Borlea/EchoPet
modules/v1_14_R1/src/com/dsh105/echopet/compat/nms/v1_14_R1/entity/type/EntityGiantPet.java
Java
gpl-3.0
1,596
<?php namespace GO\Base\Fs; class MemoryFile extends File{ private $_data; public function __construct($filename, $data) { $this->_data = $data; return parent::__construct($filename); } public function getContents() { return $this->_data; } public function contents() { return $this->_data; } public function putContents($data, $flags = null, $context = null) { if($flags = FILE_APPEND){ $this->_data .= $data; }else { $this->_data = $data; } } public function size() { return strlen($this->_data); } public function mtime() { return time(); } public function ctime() { return time(); } public function exists() { return true; } public function move(Base $destinationFolder, $newFileName = false, $isUploadedFile = false, $appendNumberToNameIfDestinationExists = false) { throw Exception("move not implemented for memory file"); } public function copy(Folder $destinationFolder, $newFileName = false) { throw Exception("copy not implemented for memory file"); } public function parent() { return false; } public function child($filename) { throw Exception("child not possible for memory file"); } public function createChild($filename, $isFile = true) { throw Exception("createChild not possible for memory file"); } /** * Check if the file or folder is writable for the webserver user. * * @return boolean */ public function isWritable(){ return true; } /** * Change owner * @param StringHelper $user * @return boolean */ public function chown($user){ return false; } /** * Change group * * @param StringHelper $group * @return boolean */ public function chgrp($group){ return false; } /** * * @param int $permissionsMode <p> * Note that mode is not automatically * assumed to be an octal value, so strings (such as "g+w") will * not work properly. To ensure the expected operation, * you need to prefix mode with a zero (0): * </p> * * @return boolean */ public function chmod($permissionsMode){ return false; } /** * Delete the file * * @return boolean */ public function delete(){ return false; } public function isFolder() { return false; } /** * Check if this object is a file. * * @return boolean */ public function isFile(){ return true; } public function rename($name){ $this->path=$name; } public function appendNumberToNameIfExists() { return $this->path; } public function output() { echo $this->_data; } public function setDefaultPermissions() { } public function md5Hash(){ return md5($this->_data); } }
deependhulla/powermail-debian9
files/rootdir/usr/local/src/groupoffice-6.3/go/base/fs/MemoryFile.php
PHP
gpl-3.0
2,677
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.11"/> <title>My Project: SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">My Project </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.11 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespace_sample_hospital_model.html">SampleHospitalModel</a></li><li class="navelem"><a class="el" href="namespace_sample_hospital_model_1_1_visualization.html">Visualization</a></li><li class="navelem"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html">WPFVisualizationEngineOutpatientDepartment</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#properties">Properties</a> &#124; <a href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>Additional visualization for outpatient control units, with extra visualization of waiting list numbers: Number of patients waiting for a slot to be assigned Number of patients waiting for slots <a href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#details">More...</a></p> <div class="dynheader"> Inheritance diagram for SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment:</div> <div class="dyncontent"> <div class="center"> <img src="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.png" usemap="#SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment_map" alt=""/> <map id="SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment_map" name="SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment_map"> <area href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html" alt="SampleHospitalModel.Visualization.WPFVisualizationEngineHealthCareDepartmentControlUnit&lt; OutpatientActionTypeClass &gt;" shape="rect" coords="0,0,715,24"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a50cbb97ee541ebb20c7ce54fb48960ed"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#a50cbb97ee541ebb20c7ce54fb48960ed">WPFVisualizationEngineOutpatientDepartment</a> (<a class="el" href="class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html">DrawingOnCoordinateSystem</a> drawingSystem, Point position, <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a> size, double personSize)</td></tr> <tr class="memdesc:a50cbb97ee541ebb20c7ce54fb48960ed"><td class="mdescLeft">&#160;</td><td class="mdescRight">Basic constructor, just calls base constructor <a href="#a50cbb97ee541ebb20c7ce54fb48960ed">More...</a><br /></td></tr> <tr class="separator:a50cbb97ee541ebb20c7ce54fb48960ed"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af8be5c28237bb4fc3261b13bcdb5aa45"><td class="memItemLeft" align="right" valign="top">override void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#af8be5c28237bb4fc3261b13bcdb5aa45">AdditionalStaticVisualization</a> (DateTime initializationTime, <a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> simModel, <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> parentControlUnit)</td></tr> <tr class="memdesc:af8be5c28237bb4fc3261b13bcdb5aa45"><td class="mdescLeft">&#160;</td><td class="mdescRight">Calls base class method and additiona visualization for string captions <a href="#af8be5c28237bb4fc3261b13bcdb5aa45">More...</a><br /></td></tr> <tr class="separator:af8be5c28237bb4fc3261b13bcdb5aa45"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ab14586d925c0fcb7c6d77394fe4c8d65"><td class="memItemLeft" align="right" valign="top">override void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#ab14586d925c0fcb7c6d77394fe4c8d65">AdditionalDynamicVisualization</a> (DateTime currentTime, <a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> simModel, <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> parentControlUnit, IEnumerable&lt; <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> &gt; currentEvents)</td></tr> <tr class="memdesc:ab14586d925c0fcb7c6d77394fe4c8d65"><td class="mdescLeft">&#160;</td><td class="mdescRight">Additionally to event handling methods for visualization, the number of patients waiting for a slot to be assigned or waiting for a slot are showed. <a href="#ab14586d925c0fcb7c6d77394fe4c8d65">More...</a><br /></td></tr> <tr class="separator:ab14586d925c0fcb7c6d77394fe4c8d65"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html">SampleHospitalModel.Visualization.WPFVisualizationEngineHealthCareDepartmentControlUnit&lt; OutpatientActionTypeClass &gt;</a></td></tr> <tr class="memitem:a897a51338edd7243dcf4dfda927be6b6 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a897a51338edd7243dcf4dfda927be6b6">WPFVisualizationEngineHealthCareDepartmentControlUnit</a> (<a class="el" href="class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html">DrawingOnCoordinateSystem</a> drawingSystem, Point position, <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a> size, double personSize)</td></tr> <tr class="memdesc:a897a51338edd7243dcf4dfda927be6b6 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Basic constructor, assigns visualization methods to dictionaries for event and activity types <a href="#a897a51338edd7243dcf4dfda927be6b6">More...</a><br /></td></tr> <tr class="separator:a897a51338edd7243dcf4dfda927be6b6 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3571407fd3c83321bab8ccdae3baac0e inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a3571407fd3c83321bab8ccdae3baac0e">CreatePatient</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr> <tr class="memdesc:a3571407fd3c83321bab8ccdae3baac0e inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates a patient drawing object <a href="#a3571407fd3c83321bab8ccdae3baac0e">More...</a><br /></td></tr> <tr class="separator:a3571407fd3c83321bab8ccdae3baac0e inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ab39da1d23eebe1d8fe34c03b137e877f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ab39da1d23eebe1d8fe34c03b137e877f">CreateDoctor</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr> <tr class="memdesc:ab39da1d23eebe1d8fe34c03b137e877f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates a doctor drawing object <a href="#ab39da1d23eebe1d8fe34c03b137e877f">More...</a><br /></td></tr> <tr class="separator:ab39da1d23eebe1d8fe34c03b137e877f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a650fbd7d7bb218e7e719a4dcac3d4a3f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a650fbd7d7bb218e7e719a4dcac3d4a3f">CreateNurse</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr> <tr class="memdesc:a650fbd7d7bb218e7e719a4dcac3d4a3f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates a nurse drawing object <a href="#a650fbd7d7bb218e7e719a4dcac3d4a3f">More...</a><br /></td></tr> <tr class="separator:a650fbd7d7bb218e7e719a4dcac3d4a3f inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa97bfcd681045655d1d5e43d77a1722a inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#aa97bfcd681045655d1d5e43d77a1722a">CreateTreatmentFacility</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr> <tr class="memdesc:aa97bfcd681045655d1d5e43d77a1722a inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates a treatment facility drawing object, different objects for different skill types of treatment facilities are generated, e.g. CT or MRI <a href="#aa97bfcd681045655d1d5e43d77a1722a">More...</a><br /></td></tr> <tr class="separator:aa97bfcd681045655d1d5e43d77a1722a inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a88c622beb3aaa3efa3e10e9cf9a3ce24 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a88c622beb3aaa3efa3e10e9cf9a3ce24">CreateMultiplePatientTreatmentFacility</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr> <tr class="memdesc:a88c622beb3aaa3efa3e10e9cf9a3ce24 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates a multiple patient treatment facility drawing object <a href="#a88c622beb3aaa3efa3e10e9cf9a3ce24">More...</a><br /></td></tr> <tr class="separator:a88c622beb3aaa3efa3e10e9cf9a3ce24 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae89366f9a28ea6a3ac75891fca0f50a9 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae89366f9a28ea6a3ac75891fca0f50a9"></a> <a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object.html">DrawingObject</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ae89366f9a28ea6a3ac75891fca0f50a9">CreateWaitingRoom</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_entity.html">Entity</a> entity)</td></tr> <tr class="memdesc:ae89366f9a28ea6a3ac75891fca0f50a9 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates a waiting room drawing object </p><dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">entity</td><td>Treatment facility entity</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>A drawing object visualizing a waiting room</dd></dl> <br /></td></tr> <tr class="separator:ae89366f9a28ea6a3ac75891fca0f50a9 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a0d4ef8176bd2251ff53971e7ddfad3f3 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a0d4ef8176bd2251ff53971e7ddfad3f3">DrawHoldingEntity</a> (<a class="el" href="interface_simulation_core_1_1_h_c_c_m_elements_1_1_i_dynamic_holding_entity.html">IDynamicHoldingEntity</a> holdingEntity)</td></tr> <tr class="memdesc:a0d4ef8176bd2251ff53971e7ddfad3f3 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Draws a holding entity, if size is sufficient for all entities holded, they are visualized in a grid form, if they do not fit they are all visualized in the middle and a string representing the count of holded entities is visualized <a href="#a0d4ef8176bd2251ff53971e7ddfad3f3">More...</a><br /></td></tr> <tr class="separator:a0d4ef8176bd2251ff53971e7ddfad3f3 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa57efb82b63494b349a5977073019c43 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">override void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#aa57efb82b63494b349a5977073019c43">AdditionalStaticVisualization</a> (DateTime initializationTime, <a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a> simModel, <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a> parentControlUnit)</td></tr> <tr class="memdesc:aa57efb82b63494b349a5977073019c43 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Creates the static visualization, draws all treatment facilities, waiting rooms and multiple patient treatment facilities for each structural area <a href="#aa57efb82b63494b349a5977073019c43">More...</a><br /></td></tr> <tr class="separator:aa57efb82b63494b349a5977073019c43 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a780a15d08281938df5c17a0b24584d2d inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a780a15d08281938df5c17a0b24584d2d">HealthCareActionEnd</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr> <tr class="memdesc:a780a15d08281938df5c17a0b24584d2d inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Method that visualized the end of a health care action, patient is removed from the drawing system <a href="#a780a15d08281938df5c17a0b24584d2d">More...</a><br /></td></tr> <tr class="separator:a780a15d08281938df5c17a0b24584d2d inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3394a6e0359fa0246fff89c9313965d4 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a3394a6e0359fa0246fff89c9313965d4">HealthCareActionStart</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr> <tr class="memdesc:a3394a6e0359fa0246fff89c9313965d4 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Method that visualized the start of a health care action, patient is added to the drawing system and all entities (staff and patient) are set to the corresponding positions in the treatment facility (if it is not a multiple patient treatment facility). <a href="#a3394a6e0359fa0246fff89c9313965d4">More...</a><br /></td></tr> <tr class="separator:a3394a6e0359fa0246fff89c9313965d4 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:adfff669d5726f33626b88c1a72b8ab96 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#adfff669d5726f33626b88c1a72b8ab96">WaitInFacilityEnd</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr> <tr class="memdesc:adfff669d5726f33626b88c1a72b8ab96 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Method that visualized the end of a wait in facility activity, patient is removed from the drawing system <a href="#adfff669d5726f33626b88c1a72b8ab96">More...</a><br /></td></tr> <tr class="separator:adfff669d5726f33626b88c1a72b8ab96 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad09159950ba3f4c77bda340214bcce44 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ad09159950ba3f4c77bda340214bcce44">WaitInFacilityStart</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_activity.html">Activity</a> activity, DateTime time)</td></tr> <tr class="memdesc:ad09159950ba3f4c77bda340214bcce44 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Method that visualized the start of a wait in facility action, patient is added to the drawing system and set to the corresponding positions in the treatment facility (if it is not a multiple patient treatment facility). <a href="#ad09159950ba3f4c77bda340214bcce44">More...</a><br /></td></tr> <tr class="separator:ad09159950ba3f4c77bda340214bcce44 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae7b7553c4abb3871ccadbd93a336cf69 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#ae7b7553c4abb3871ccadbd93a336cf69">EventPatientLeave</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> ev)</td></tr> <tr class="memdesc:ae7b7553c4abb3871ccadbd93a336cf69 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Upon patient leave events the drawing object is removed from the system <a href="#ae7b7553c4abb3871ccadbd93a336cf69">More...</a><br /></td></tr> <tr class="separator:ae7b7553c4abb3871ccadbd93a336cf69 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a64759dc8379a68dd03c80d7fde9b2b71 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a64759dc8379a68dd03c80d7fde9b2b71">EventLeavingStaff</a> (<a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> ev)</td></tr> <tr class="memdesc:a64759dc8379a68dd03c80d7fde9b2b71 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Upon staff leave events the drawing object is removed from the system <a href="#a64759dc8379a68dd03c80d7fde9b2b71">More...</a><br /></td></tr> <tr class="separator:a64759dc8379a68dd03c80d7fde9b2b71 inherit pub_methods_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a> Properties</h2></td></tr> <tr class="memitem:a992d490ed94e38c9a9cf1b1f2ddff207"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#a992d490ed94e38c9a9cf1b1f2ddff207">NumberSlotWaitString</a><code> [get]</code></td></tr> <tr class="memdesc:a992d490ed94e38c9a9cf1b1f2ddff207"><td class="mdescLeft">&#160;</td><td class="mdescRight">Drawing object for the string representing the number of patients waiting for a slot <a href="#a992d490ed94e38c9a9cf1b1f2ddff207">More...</a><br /></td></tr> <tr class="separator:a992d490ed94e38c9a9cf1b1f2ddff207"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af57ab2efb02c541b204a377740f69906"><td class="memItemLeft" align="right" valign="top"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html#af57ab2efb02c541b204a377740f69906">NumberSlotAssignString</a><code> [get]</code></td></tr> <tr class="memdesc:af57ab2efb02c541b204a377740f69906"><td class="mdescLeft">&#160;</td><td class="mdescRight">Drawing object for the string representing the number of patients waiting for a slot to be assigned <a href="#af57ab2efb02c541b204a377740f69906">More...</a><br /></td></tr> <tr class="separator:af57ab2efb02c541b204a377740f69906"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td colspan="2" onclick="javascript:toggleInherit('properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit')"><img src="closed.png" alt="-"/>&#160;Properties inherited from <a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html">SampleHospitalModel.Visualization.WPFVisualizationEngineHealthCareDepartmentControlUnit&lt; OutpatientActionTypeClass &gt;</a></td></tr> <tr class="memitem:a7af7fadd903ca4aa578ceb80cf4747dd inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">Point&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a7af7fadd903ca4aa578ceb80cf4747dd">Position</a><code> [get]</code></td></tr> <tr class="memdesc:a7af7fadd903ca4aa578ceb80cf4747dd inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Position of control unit visualization on drawing system <a href="#a7af7fadd903ca4aa578ceb80cf4747dd">More...</a><br /></td></tr> <tr class="separator:a7af7fadd903ca4aa578ceb80cf4747dd inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:abe4ba0d78d527ff6c4cdde7dd27943fc inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">Size&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a><code> [get]</code></td></tr> <tr class="memdesc:abe4ba0d78d527ff6c4cdde7dd27943fc inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Size of control unit visualization on drawing system <a href="#abe4ba0d78d527ff6c4cdde7dd27943fc">More...</a><br /></td></tr> <tr class="separator:abe4ba0d78d527ff6c4cdde7dd27943fc inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a53651357a0075b021a5ebad63112fc1a inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memItemLeft" align="right" valign="top">double&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#a53651357a0075b021a5ebad63112fc1a">PersonSize</a><code> [get]</code></td></tr> <tr class="memdesc:a53651357a0075b021a5ebad63112fc1a inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="mdescLeft">&#160;</td><td class="mdescRight">Size in which persons are visualized <a href="#a53651357a0075b021a5ebad63112fc1a">More...</a><br /></td></tr> <tr class="separator:a53651357a0075b021a5ebad63112fc1a inherit properties_class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Additional visualization for outpatient control units, with extra visualization of waiting list numbers: Number of patients waiting for a slot to be assigned Number of patients waiting for slots </p> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="a50cbb97ee541ebb20c7ce54fb48960ed"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.WPFVisualizationEngineOutpatientDepartment </td> <td>(</td> <td class="paramtype"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_on_coordinate_system.html">DrawingOnCoordinateSystem</a>&#160;</td> <td class="paramname"><em>drawingSystem</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">Point&#160;</td> <td class="paramname"><em>position</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_health_care_department_control_unit.html#abe4ba0d78d527ff6c4cdde7dd27943fc">Size</a>&#160;</td> <td class="paramname"><em>size</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&#160;</td> <td class="paramname"><em>personSize</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Basic constructor, just calls base constructor </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">drawingSystem</td><td>Drawing system used for visualization</td></tr> <tr><td class="paramname">position</td><td>Position of control unit visualization on drawing system</td></tr> <tr><td class="paramname">size</td><td>Size of control unit visualization on drawing system</td></tr> <tr><td class="paramname">personSize</td><td>Size in which persons are visualized</td></tr> </table> </dd> </dl> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="ab14586d925c0fcb7c6d77394fe4c8d65"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override void SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.AdditionalDynamicVisualization </td> <td>(</td> <td class="paramtype">DateTime&#160;</td> <td class="paramname"><em>currentTime</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a>&#160;</td> <td class="paramname"><em>simModel</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a>&#160;</td> <td class="paramname"><em>parentControlUnit</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">IEnumerable&lt; <a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_event.html">Event</a> &gt;&#160;</td> <td class="paramname"><em>currentEvents</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Additionally to event handling methods for visualization, the number of patients waiting for a slot to be assigned or waiting for a slot are showed. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">currentTime</td><td>Time for additional dynamic visualization</td></tr> <tr><td class="paramname">simModel</td><td>Simulation model to be visualized</td></tr> <tr><td class="paramname">parentControlUnit</td><td>Control to be visualized</td></tr> <tr><td class="paramname">currentEvents</td><td>Events that have been triggered at current time</td></tr> </table> </dd> </dl> </div> </div> <a class="anchor" id="af8be5c28237bb4fc3261b13bcdb5aa45"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override void SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.AdditionalStaticVisualization </td> <td>(</td> <td class="paramtype">DateTime&#160;</td> <td class="paramname"><em>initializationTime</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="class_simulation_core_1_1_simulation_classes_1_1_simulation_model.html">SimulationModel</a>&#160;</td> <td class="paramname"><em>simModel</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="class_simulation_core_1_1_h_c_c_m_elements_1_1_control_unit.html">ControlUnit</a>&#160;</td> <td class="paramname"><em>parentControlUnit</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Calls base class method and additiona visualization for string captions </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">initializationTime</td><td>Time at which static visualization is generated</td></tr> <tr><td class="paramname">simModel</td><td>Simulation model for which the visuslization is generated</td></tr> <tr><td class="paramname">parentControlUnit</td><td>Control unit that is visualized</td></tr> </table> </dd> </dl> </div> </div> <h2 class="groupheader">Property Documentation</h2> <a class="anchor" id="af57ab2efb02c541b204a377740f69906"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a> SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.NumberSlotAssignString</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">get</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Drawing object for the string representing the number of patients waiting for a slot to be assigned </p> </div> </div> <a class="anchor" id="a992d490ed94e38c9a9cf1b1f2ddff207"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="class_w_p_f_visualization_base_1_1_drawing_object_string.html">DrawingObjectString</a> SampleHospitalModel.Visualization.WPFVisualizationEngineOutpatientDepartment.NumberSlotWaitString</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">get</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Drawing object for the string representing the number of patients waiting for a slot </p> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.11 </small></address> </body> </html>
nikolausfurian/HCDESLib
API/class_sample_hospital_model_1_1_visualization_1_1_w_p_f_visualization_engine_outpatient_department.html
HTML
gpl-3.0
44,934
<?PHP require_once("./include/membersite_config.php"); if(isset($_POST['submitted'])) { if($fgmembersite->RegisterUser()) { require_once("config.php"); mkdir($dataDir); mkdir($dataDir."CLASSTéléversés"); $fgmembersite->RedirectToURL("thank-you.html"); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> <title>Register</title> <link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css" /> <script type='text/javascript' src='scripts/gen_validatorv31.js'></script> <link rel="STYLESHEET" type="text/css" href="style/pwdwidget.css" /> <script src="scripts/pwdwidget.js" type="text/javascript"></script> </head> <body> <!-- Form Code Start --> <div id='fg_membersite'> <form id='register' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'> <fieldset > <legend>Register</legend> <input type='hidden' name='submitted' id='submitted' value='1'/> <div class='short_explanation'>* required fields</div> <input type='text' class='spmhidip' name='<?php echo $fgmembersite->GetSpamTrapInputName(); ?>' /> <div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?></span></div> <div class='container'> <label for='name' >Your Full Name*: </label><br/> <input type='text' name='name' id='name' value='<?php echo $fgmembersite->SafeDisplay('name') ?>' maxlength="50" /><br/> <span id='register_name_errorloc' class='error'></span> </div> <div class='container'> <label for='email' >Email Address*:</label><br/> <input type='text' name='email' id='email' value='<?php echo $fgmembersite->SafeDisplay('email') ?>' maxlength="50" /><br/> <span id='register_email_errorloc' class='error'></span> </div> <div class='container'> <label for='username' >UserName*:</label><br/> <input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username') ?>' maxlength="50" /><br/> <span id='register_username_errorloc' class='error'></span> </div> <div class='container' style='height:80px;'> <label for='password' >Password*:</label><br/> <div class='pwdwidgetdiv' id='thepwddiv' ></div> <noscript> <input type='password' name='password' id='password' maxlength="50" /> </noscript> <div id='register_password_errorloc' class='error' style='clear:both'></div> </div> <div class='container'> <input type='submit' name='Submit' value='Submit' /> </div> </fieldset> </form> <!-- client-side Form Validations: Uses the excellent form validation script from JavaScript-coder.com--> <script type='text/javascript'> // <![CDATA[ var pwdwidget = new PasswordWidget('thepwddiv','password'); pwdwidget.MakePWDWidget(); var frmvalidator = new Validator("register"); frmvalidator.EnableOnPageErrorDisplay(); frmvalidator.EnableMsgsTogether(); frmvalidator.addValidation("name","req","Please provide your name"); frmvalidator.addValidation("email","req","Please provide your email address"); frmvalidator.addValidation("email","email","Please provide a valid email address"); frmvalidator.addValidation("username","req","Please provide a username"); frmvalidator.addValidation("password","req","Please provide a password"); // ]]> </script> <!-- Form Code End (see html-form-guide.com for more info.) --> </body> </html>
LaboManu/bloc-notes
app/register.php
PHP
gpl-3.0
3,638
/* * Copyright (C) 2006-2008 Alfresco Software Limited. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * As a special exception to the terms and conditions of version 2.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * and Open Source Software ("FLOSS") applications as described in Alfresco's * FLOSS exception. You should have recieved a copy of the text describing * the FLOSS exception, and it is also available here: * http://www.alfresco.com/legal/licensing" */ package org.alfresco.jlan.server.filesys; import org.alfresco.jlan.server.SrvSession; /** * Transactional Filesystem Interface * * <p>Optional interface that a filesystem driver can implement to add support for transactions around filesystem calls. * * @author gkspencer */ public interface TransactionalFilesystemInterface { /** * Begin a read-only transaction * * @param sess SrvSession */ public void beginReadTransaction(SrvSession sess); /** * Begin a writeable transaction * * @param sess SrvSession */ public void beginWriteTransaction(SrvSession sess); /** * End an active transaction * * @param sess SrvSession * @param tx Object */ public void endTransaction(SrvSession sess, Object tx); }
arcusys/Liferay-CIFS
source/java/org/alfresco/jlan/server/filesys/TransactionalFilesystemInterface.java
Java
gpl-3.0
1,957
// // ECCardView.h // Beacon // // Created by 段昊宇 on 2017/5/29. // Copyright © 2017年 Echo. All rights reserved. // #import <UIKit/UIKit.h> #import "CCDraggableCardView.h" #import "ECReturningVideo.h" @interface ECCardView : CCDraggableCardView - (void)initialData:(ECReturningVideo *)video; - (void)addLiked; - (void)delLiked; @end
SeaHub/Beacon
Beacon/Beacon/ECCardView.h
C
gpl-3.0
350
-- >> INVENTORY << DROP TABLE Items CASCADE; DROP TABLE contient; DROP TRIGGER IF EXISTS delcharacter ON Characterr; CREATE TABLE public.Items( id_inventory INT, item_name VARCHAR(100), qte INT CONSTRAINT item_qte_null NOT NULL CONSTRAINT item_qte_check CHECK (qte > 0) , weight FLOAT CONSTRAINT item_weight_null NOT NULL CONSTRAINT item_weight_check CHECK (weight > 0), CONSTRAINT prk_constraint_item PRIMARY KEY (id_inventory,item_name) )WITHOUT OIDS; ALTER TABLE public.Items ADD CONSTRAINT FK_items_inventory FOREIGN KEY (id_inventory) REFERENCES public.Inventaire(id_inventory); -- Reimplementation of broken features CREATE OR REPLACE FUNCTION delCharacter () RETURNS TRIGGER AS $delCharacter$ BEGIN DELETE FROM items WHERE id_inventory = old.id_inventory; DELETE FROM inventaire WHERE id_inventory = old.id_inventory; RETURN old; END; $delCharacter$ LANGUAGE plpgsql; CREATE TRIGGER delCharacter AFTER DELETE ON Characterr FOR EACH ROW EXECUTE PROCEDURE delCharacter(); CREATE OR REPLACE FUNCTION inventory_Manager () RETURNS TRIGGER AS $inventory_Manager$ DECLARE poids ITEMS.WEIGHT%TYPE; poids_max ITEMS.WEIGHT%TYPE; BEGIN IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN SELECT size_ INTO poids FROM inventaire WHERE id_inventory = old.id_inventory; poids := poids - (old.qte * old.weight); UPDATE inventaire SET size_ = poids WHERE id_inventory = old.id_inventory; END IF; IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN SELECT size_ INTO poids FROM inventaire WHERE id_inventory = new.id_inventory; poids := poids + (new.qte * new.weight); SELECT size_max INTO poids_max FROM inventaire WHERE id_inventory = new.id_inventory; --IF poids > poids_max THEN --RAISE EXCEPTION 'Inventory size exceeded'; --ELSE UPDATE inventaire SET size_ = poids WHERE id_inventory = new.id_inventory; --END IF; END IF; IF TG_OP = 'DELETE' THEN RETURN old; ELSE RETURN new; END IF; END; $inventory_Manager$ LANGUAGE plpgsql; CREATE TRIGGER inventory_Manager BEFORE INSERT OR UPDATE OR DELETE ON Items FOR EACH ROW EXECUTE PROCEDURE inventory_Manager(); CREATE OR REPLACE FUNCTION additem ( dbkey Characterr.charkey%TYPE, idserv JDR.id_server%TYPE, idchan JDR.id_channel%TYPE, itname Items.item_name%TYPE, quantite INT, poids Items.weight%TYPE ) RETURNS void AS $$ DECLARE inv Inventaire.id_inventory%TYPE; nbr INT; BEGIN SELECT id_inventory INTO inv FROM Characterr WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan); SELECT COUNT(*) INTO nbr FROM Items WHERE (item_name LIKE LOWER(itname) AND id_inventory = inv); IF nbr = 0 THEN INSERT INTO Items VALUES (inv,itname,quantite,poids); ELSE UPDATE Items SET qte = qte + quantite WHERE (item_name = itname AND id_inventory = inv); END IF; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION removeitem ( dbkey Characterr.charkey%TYPE, idserv JDR.id_server%TYPE, idchan JDR.id_channel%TYPE, itname Items.item_name%TYPE, quantite INT ) RETURNS void AS $$ DECLARE inv Inventaire.id_inventory%TYPE; nbr INT; BEGIN SELECT id_inventory INTO inv FROM Characterr WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan); SELECT qte INTO nbr FROM Items WHERE (id_inventory = inv AND item_name = itname); nbr := nbr - quantite; IF nbr <= 0 THEN DELETE FROM Items WHERE (item_name = itname AND id_inventory = inv); ELSE UPDATE Items SET qte = nbr WHERE (item_name = itname AND id_inventory = inv); END IF; END; $$ LANGUAGE plpgsql; CREATE OR REPLACE FUNCTION forceinvcalc () RETURNS void AS $$ DECLARE poids INVENTAIRE.SIZE_%TYPE; inv RECORD; item RECORD; po Characterr.argent%TYPE; BEGIN FOR inv IN (SELECT id_inventory FROM inventaire) LOOP SELECT argent INTO po FROM characterr WHERE id_inventory = inv.id_inventory; poids := CEIL(po/5000); FOR item IN (SELECT item_name,qte,weight FROM Items WHERE id_inventory = inv.id_inventory) LOOP poids := poids + (item.qte * item.weight); END LOOP; UPDATE inventaire SET size_ = poids WHERE id_inventory = inv.id_inventory; END LOOP; END; $$ LANGUAGE plpgsql; -- >> XP << ALTER TABLE public.Characterr ADD COLUMN xp INT; -- Perform update of characterr DO $$ <<xpupdate>> BEGIN UPDATE Characterr SET xp = 0; END xpupdate $$; -- Update old fonctions CREATE OR REPLACE FUNCTION charcreate ( dbkey Characterr.charkey%TYPE, idserv JDR.id_server%TYPE, idchan JDR.id_channel%TYPE, cl Classe.id_classe%TYPE ) RETURNS void AS $$ DECLARE inv inventaire.id_inventory%TYPE; BEGIN INSERT INTO inventaire (charkey) VALUES (dbkey); SELECT MAX(id_inventory) INTO inv FROM inventaire WHERE charkey = dbkey; --update here INSERT INTO Characterr VALUES (dbkey, dbkey, '', 1, 1, 1, 1, 1, 50, 50, 50, 50, 0, 0, 0, 1, 1, 3, 100, 0, 0, 0, 0, 0, 0, 0, idserv, idchan, 'O', 'O', inv, 'NULL',false,cl,false,0); --end of update END; $$ LANGUAGE plpgsql; -- new fonctions CREATE OR REPLACE FUNCTION charxp ( dbkey Characterr.charkey%TYPE, idserv JDR.id_server%TYPE, idchan JDR.id_channel%TYPE, amount Characterr.xp%TYPE, allowlevelup BOOL ) RETURNS INT AS $$ DECLARE earnedlvl INT; curxp Characterr.xp%TYPE; BEGIN earnedlvl := 0; IF allowlevelup THEN SELECT xp INTO curxp FROM Characterr WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan); earnedlvl := FLOOR((curxp + amount) / 100); amount := curxp + amount - (earnedlvl * 100); UPDATE Characterr SET xp = amount WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan); ELSE UPDATE Characterr SET xp = xp + amount WHERE (charkey = dbkey AND id_server = idserv AND id_channel = idchan); END IF; RETURN earnedlvl; END; $$ LANGUAGE plpgsql;
ttgc/TtgcBot
database-scripts/jdr_rewrite.sql
SQL
gpl-3.0
5,931
#PASTOR: Code generated by XML::Pastor/1.0.4 at 'Sun Jun 28 20:44:47 2015' use utf8; use strict; use warnings; no warnings qw(uninitialized); use XML::Pastor; #================================================================ package SAN::Cat::Type::catRecord; use SAN::Cat::Type::catRecordBody; use SAN::Cat::Type::catRecordHeader; our @ISA=qw(XML::Pastor::ComplexType); SAN::Cat::Type::catRecord->mk_accessors( qw(catRecordHeader catRecordBody)); SAN::Cat::Type::catRecord->XmlSchemaType( bless( { 'attributeInfo' => {}, 'attributePrefix' => '_', 'attributes' => [], 'baseClasses' => [ 'XML::Pastor::ComplexType' ], 'class' => 'SAN::Cat::Type::catRecord', 'contentType' => 'complex', 'elementInfo' => { 'catRecordBody' => bless( { 'class' => 'SAN::Cat::Type::catRecordBody', 'metaClass' => 'SAN::Cat::Pastor::Meta', 'minOccurs' => '0', 'name' => 'catRecordBody', 'scope' => 'local', 'targetNamespace' => 'http://san.mibac.it/cat-import', 'type' => 'catRecordBody|http://san.mibac.it/cat-import' }, 'XML::Pastor::Schema::Element' ), 'catRecordHeader' => bless( { 'class' => 'SAN::Cat::Type::catRecordHeader', 'maxOccurs' => '1', 'metaClass' => 'SAN::Cat::Pastor::Meta', 'minOccurs' => '1', 'name' => 'catRecordHeader', 'scope' => 'local', 'targetNamespace' => 'http://san.mibac.it/cat-import', 'type' => 'catRecordHeader|http://san.mibac.it/cat-import' }, 'XML::Pastor::Schema::Element' ) }, 'elements' => [ 'catRecordHeader', 'catRecordBody' ], 'isRedefinable' => 1, 'metaClass' => 'SAN::Cat::Pastor::Meta', 'name' => 'catRecord', 'scope' => 'global', 'targetNamespace' => 'http://san.mibac.it/cat-import' }, 'XML::Pastor::Schema::ComplexType' ) ); 1; __END__ =head1 NAME B<SAN::Cat::Type::catRecord> - A class generated by L<XML::Pastor> . =head1 ISA This class descends from L<XML::Pastor::ComplexType>. =head1 CODE GENERATION This module was automatically generated by L<XML::Pastor> version 1.0.4 at 'Sun Jun 28 20:44:47 2015' =head1 CHILD ELEMENT ACCESSORS =over =item B<catRecordBody>() - See L<SAN::Cat::Type::catRecordBody>. =item B<catRecordHeader>() - See L<SAN::Cat::Type::catRecordHeader>. =back =head1 SEE ALSO L<XML::Pastor::ComplexType>, L<XML::Pastor>, L<XML::Pastor::Type>, L<XML::Pastor::ComplexType>, L<XML::Pastor::SimpleType> =cut
pro-memoria/caHarvester
lib/SAN/Cat/Type/catRecord.pm
Perl
gpl-3.0
3,566
/* * This file is part of InTEL, the Interactive Toolkit for Engineering Learning. * http://intel.gatech.edu * * InTEL is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * InTEL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with InTEL. If not, see <http://www.gnu.org/licenses/>. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package keyboard; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.system.DisplaySystem; import edu.gatech.statics.application.StaticsApplication; import edu.gatech.statics.exercise.Diagram; import edu.gatech.statics.exercise.DiagramType; import edu.gatech.statics.exercise.Schematic; import edu.gatech.statics.math.Unit; import edu.gatech.statics.math.Vector3bd; import edu.gatech.statics.modes.description.Description; import edu.gatech.statics.modes.equation.EquationDiagram; import edu.gatech.statics.modes.equation.EquationMode; import edu.gatech.statics.modes.equation.EquationState; import edu.gatech.statics.modes.equation.worksheet.TermEquationMathState; import edu.gatech.statics.modes.frame.FrameExercise; import edu.gatech.statics.objects.Body; import edu.gatech.statics.objects.DistanceMeasurement; import edu.gatech.statics.objects.Force; import edu.gatech.statics.objects.Point; import edu.gatech.statics.objects.bodies.Bar; import edu.gatech.statics.objects.bodies.Beam; import edu.gatech.statics.objects.connectors.Connector2ForceMember2d; import edu.gatech.statics.objects.connectors.Pin2d; import edu.gatech.statics.objects.connectors.Roller2d; import edu.gatech.statics.objects.representations.ModelNode; import edu.gatech.statics.objects.representations.ModelRepresentation; import edu.gatech.statics.tasks.Solve2FMTask; import edu.gatech.statics.ui.AbstractInterfaceConfiguration; import edu.gatech.statics.ui.windows.navigation.Navigation3DWindow; import edu.gatech.statics.ui.windows.navigation.ViewConstraints; import java.math.BigDecimal; import java.util.Map; /** * * @author Calvin Ashmore */ public class KeyboardExercise extends FrameExercise { @Override public AbstractInterfaceConfiguration createInterfaceConfiguration() { AbstractInterfaceConfiguration ic = super.createInterfaceConfiguration(); ic.setNavigationWindow(new Navigation3DWindow()); ic.setCameraSpeed(.2f, 0.02f, .05f); ViewConstraints vc = new ViewConstraints(); vc.setPositionConstraints(-2, 2, -1, 4); vc.setZoomConstraints(0.5f, 1.5f); vc.setRotationConstraints(-5, 5, 0, 5); ic.setViewConstraints(vc); return ic; } @Override public Description getDescription() { Description description = new Description(); description.setTitle("Keyboard Stand"); description.setNarrative( "Kasiem Hill is in a music group comprised of Civil Engineering " + "students from Georgia Tech, in which he plays the keyboard. " + "For his birthday, he received a new keyboard, but it is much bigger " + "(both in size and weight) than his last one, so he needs to buy a " + "new keyboard stand. He finds one he really likes from a local " + "dealer and is unsure if the connections will be able to support " + "the weight of the new keyboard. He measures the dimensions of " + "the stand and he wants to calculate how much force he can expect " + "at each connection in the cross bar before he makes the investment."); description.setProblemStatement( "The stand can be modeled as a frame and is supported by two beams and a cross bar PQ. " + "The supports at B and E are rollers and the floor is frictionless."); description.setGoals( "Find the force in PQ and define whether it is in tension or compression."); description.addImage("keyboard/assets/keyboard 1.png"); description.addImage("keyboard/assets/keyboard 2.jpg"); description.addImage("keyboard/assets/keyboard 3.jpg"); return description; } @Override public void initExercise() { // setName("Keyboard Stand"); // // setDescription( // "This is a keyboard stand supported by two beams and a cross bar, PQ. " + // "Find the force in PQ and define whether it is in tension or compression. " + // "The supports at B and E are rollers, and the floor is frictionless."); Unit.setSuffix(Unit.distance, " m"); Unit.setSuffix(Unit.moment, " N*m"); Unit.setDisplayScale(Unit.distance, new BigDecimal("10")); getDisplayConstants().setMomentSize(0.5f); getDisplayConstants().setForceSize(0.5f); getDisplayConstants().setPointSize(0.5f); getDisplayConstants().setCylinderRadius(0.5f); //getDisplayConstants().setForceLabelDistance(1f); //getDisplayConstants().setMomentLabelDistance(0f); //getDisplayConstants().setMeasurementBarSize(0.1f); // 10/21/2010 HOTFIX: THIS CORRECTS AN ISSUE IN WHICH OBSERVATION DIRECTION IS SET TO NULL IN EQUATIONS for (Map<DiagramType, Diagram> diagramMap : getState().allDiagrams().values()) { EquationDiagram eqDiagram = (EquationDiagram) diagramMap.get(EquationMode.instance.getDiagramType()); if(eqDiagram == null) continue; EquationState.Builder builder = new EquationState.Builder(eqDiagram.getCurrentState()); TermEquationMathState.Builder xBuilder = new TermEquationMathState.Builder((TermEquationMathState) builder.getEquationStates().get("F[x]")); xBuilder.setObservationDirection(Vector3bd.UNIT_X); TermEquationMathState.Builder yBuilder = new TermEquationMathState.Builder((TermEquationMathState) builder.getEquationStates().get("F[y]")); yBuilder.setObservationDirection(Vector3bd.UNIT_Y); TermEquationMathState.Builder zBuilder = new TermEquationMathState.Builder((TermEquationMathState) builder.getEquationStates().get("M[p]")); zBuilder.setObservationDirection(Vector3bd.UNIT_Z); builder.putEquationState(xBuilder.build()); builder.putEquationState(yBuilder.build()); builder.putEquationState(zBuilder.build()); eqDiagram.pushState(builder.build()); eqDiagram.clearStateStack(); } } Point A, B, C, D, E, P, Q; Pin2d jointC; Connector2ForceMember2d jointP, jointQ; Roller2d jointB, jointE; Body leftLeg, rightLeg; Bar bar; @Override public void loadExercise() { Schematic schematic = getSchematic(); DisplaySystem.getDisplaySystem().getRenderer().setBackgroundColor(new ColorRGBA(.7f, .8f, .9f, 1.0f)); StaticsApplication.getApp().getCamera().setLocation(new Vector3f(0.0f, 0.0f, 65.0f)); A = new Point("A", "0", "6", "0"); D = new Point("D", "8", "6", "0"); B = new Point("B", "8", "0", "0"); E = new Point("E", "0", "0", "0"); C = new Point("C", "4", "3", "0"); P = new Point("P", "2.7", "4", "0"); Q = new Point("Q", "5.3", "4", "0"); leftLeg = new Beam("Left Leg", B, A); bar = new Bar("Bar", P, Q); rightLeg = new Beam("Right Leg", E, D); jointC = new Pin2d(C); jointP = new Connector2ForceMember2d(P, bar); //Pin2d(P); jointQ = new Connector2ForceMember2d(Q, bar); //new Pin2d(Q); jointB = new Roller2d(B); jointE = new Roller2d(E); jointB.setDirection(Vector3bd.UNIT_Y); jointE.setDirection(Vector3bd.UNIT_Y); DistanceMeasurement distance1 = new DistanceMeasurement(D, A); distance1.setName("Measure AD"); distance1.createDefaultSchematicRepresentation(0.5f); distance1.addPoint(E); distance1.addPoint(B); schematic.add(distance1); DistanceMeasurement distance2 = new DistanceMeasurement(C, D); distance2.setName("Measure CD"); distance2.createDefaultSchematicRepresentation(0.5f); distance2.forceVertical(); distance2.addPoint(A); schematic.add(distance2); DistanceMeasurement distance3 = new DistanceMeasurement(C, Q); distance3.setName("Measure CQ"); distance3.createDefaultSchematicRepresentation(1f); distance3.forceVertical(); distance3.addPoint(P); schematic.add(distance3); DistanceMeasurement distance4 = new DistanceMeasurement(B, D); distance4.setName("Measure BD"); distance4.createDefaultSchematicRepresentation(2.4f); distance4.addPoint(A); distance4.addPoint(E); schematic.add(distance4); Force keyboardLeft = new Force(A, Vector3bd.UNIT_Y.negate(), new BigDecimal(50)); keyboardLeft.setName("Keyboard Left"); leftLeg.addObject(keyboardLeft); Force keyboardRight = new Force(D, Vector3bd.UNIT_Y.negate(), new BigDecimal(50)); keyboardRight.setName("Keyboard Right"); rightLeg.addObject(keyboardRight); jointC.attach(leftLeg, rightLeg); jointC.setName("Joint C"); jointP.attach(leftLeg, bar); jointP.setName("Joint P"); jointQ.attach(bar, rightLeg); jointQ.setName("Joint Q"); jointE.attachToWorld(rightLeg); jointE.setName("Joint E"); jointB.attachToWorld(leftLeg); jointB.setName("Joint B"); A.createDefaultSchematicRepresentation(); B.createDefaultSchematicRepresentation(); C.createDefaultSchematicRepresentation(); D.createDefaultSchematicRepresentation(); E.createDefaultSchematicRepresentation(); P.createDefaultSchematicRepresentation(); Q.createDefaultSchematicRepresentation(); keyboardLeft.createDefaultSchematicRepresentation(); keyboardRight.createDefaultSchematicRepresentation(); //leftLeg.createDefaultSchematicRepresentation(); //bar.createDefaultSchematicRepresentation(); //rightLeg.createDefaultSchematicRepresentation(); schematic.add(leftLeg); schematic.add(bar); schematic.add(rightLeg); ModelNode modelNode = ModelNode.load("keyboard/assets/", "keyboard/assets/keyboard.dae"); float scale = .28f; ModelRepresentation rep = modelNode.extractElement(leftLeg, "VisualSceneNode/stand/leg1"); rep.setLocalScale(scale); rep.setModelOffset(new Vector3f(14f, 0, 0)); leftLeg.addRepresentation(rep); rep.setSynchronizeRotation(false); rep.setSynchronizeTranslation(false); rep.setHoverLightColor(ColorRGBA.yellow); rep.setSelectLightColor(ColorRGBA.yellow); rep = modelNode.extractElement(rightLeg, "VisualSceneNode/stand/leg2"); rep.setLocalScale(scale); rep.setModelOffset(new Vector3f(14f, 0, 0)); rightLeg.addRepresentation(rep); rep.setSynchronizeRotation(false); rep.setSynchronizeTranslation(false); rep.setHoverLightColor(ColorRGBA.yellow); rep.setSelectLightColor(ColorRGBA.yellow); rep = modelNode.extractElement(bar, "VisualSceneNode/stand/middle_support"); rep.setLocalScale(scale); rep.setModelOffset(new Vector3f(14f, 0, 0)); bar.addRepresentation(rep); rep.setSynchronizeRotation(false); rep.setSynchronizeTranslation(false); rep.setHoverLightColor(ColorRGBA.yellow); rep.setSelectLightColor(ColorRGBA.yellow); rep = modelNode.getRemainder(schematic.getBackground()); schematic.getBackground().addRepresentation(rep); rep.setLocalScale(scale); rep.setModelOffset(new Vector3f(14f, 0, 0)); rep.setSynchronizeRotation(false); rep.setSynchronizeTranslation(false); addTask(new Solve2FMTask("Solve PQ", bar, jointP)); } }
jogjayr/InTEL-Project
exercises/Keyboard/src/keyboard/KeyboardExercise.java
Java
gpl-3.0
12,512
<?php /** * Online Course Resources [Pre-Clerkship] * Module: Courses * Area: Admin * @author Unit: Medical Education Technology Unit * @author Director: Dr. Benjamin Chen <[email protected]> * @author Developer: James Ellis <[email protected]> * @version 0.8.3 * @copyright Copyright 2009 Queen's University, MEdTech Unit * * $Id: add.inc.php 505 2009-07-09 19:15:57Z jellis $ */ @set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__) . "/../core", dirname(__FILE__) . "/../core/includes", dirname(__FILE__) . "/../core/library", dirname(__FILE__) . "/../core/library/vendor", get_include_path(), ))); /** * Include the Entrada init code. */ require_once("init.inc.php"); if((!isset($_SESSION["isAuthorized"])) || (!$_SESSION["isAuthorized"])) { header("Location: ".ENTRADA_URL); exit; } else { /** * Clears all open buffers so we can return a simple REST response. */ ob_clear_open_buffers(); $id = (int) $_GET["objective_id"]; $course_id = (int) (isset($_GET["course_id"]) ? $_GET["course_id"] : false); $event_id = (int) (isset($_GET["event_id"]) ? $_GET["event_id"] : false); $assessment_id = (int) (isset($_GET["assessment_id"]) ? $_GET["assessment_id"] : false); $org_id = (int) (isset($_GET["org_id"]) ? $_GET["org_id"] : (isset($ENTRADA_USER) && $ENTRADA_USER->getActiveOrganisation() ? $ENTRADA_USER->getActiveOrganisation() : false)); $objective_ids_string = ""; if (isset($_GET["objective_ids"]) && ($objective_ids = explode(",", $_GET["objective_ids"])) && @count($objective_ids)) { foreach ($objective_ids as $objective_id) { $objective_ids_string .= ($objective_ids_string ? ", " : "").$db->qstr($objective_id); } } $select = "a.*"; if ($course_id) { $select .= ", COALESCE(b.`cobjective_id`, 0) AS `mapped`"; } elseif ($event_id) { $select .= ", COALESCE(b.`eobjective_id`, 0) AS `mapped`"; } elseif ($assessment_id) { $select .= ", COALESCE(b.`aobjective_id`, 0) AS `mapped`"; } elseif ($objective_ids_string) { $select .= ", COALESCE(b.`objective_id`, 0) AS `mapped`"; } $qu_arr = array("SELECT ".$select." FROM `global_lu_objectives` a"); if ($course_id) { $qu_arr[1] = " LEFT JOIN `course_objectives` b ON a.`objective_id` = b.`objective_id` AND b.`course_id` = ".$db->qstr($course_id); } elseif ($event_id) { $qu_arr[1] = " LEFT JOIN `event_objectives` b ON a.`objective_id` = b.`objective_id` AND b.`event_id` = ".$db->qstr($event_id); } elseif ($assessment_id) { $qu_arr[1] = " LEFT JOIN `assessment_objectives` b ON a.`objective_id` = b.`objective_id` AND b.`assessment_id` = ".$db->qstr($assessment_id); } elseif ($objective_ids_string) { $qu_arr[1] = " LEFT JOIN `global_lu_objectives` AS b ON a.`objective_id` = b.`objective_id` AND b.`objective_id` IN (".$objective_ids_string.")"; } else { $qu_arr[1] = ""; } $qu_arr[1] .= " JOIN `objective_organisation` AS c ON a.`objective_id` = c.`objective_id` "; $qu_arr[2] = " WHERE a.`objective_parent` = ".$db->qstr($id)." AND a.`objective_active` = '1' AND c.`organisation_id` = ".$db->qstr($org_id); $qu_arr[4] = " ORDER BY a.`objective_order`"; $query = implode(" ",$qu_arr); $objectives = $db->GetAll($query); if ($objectives) { $obj_array = array(); foreach($objectives as $objective){ $fields = array( 'objective_id'=>$objective["objective_id"], 'objective_code'=>$objective["objective_code"], 'objective_name'=>$objective["objective_name"], 'objective_description'=>$objective["objective_description"] ); if ($course_id || $event_id || $assessment_id || $objective_ids_string){ $fields["mapped"] = $objective["mapped"]; if ($course_id) { $fields["child_mapped"] = course_objective_has_child_mapped($objective["objective_id"],$course_id,true); } else if ($event_id) { $fields["child_mapped"] = event_objective_parent_mapped_course($objective["objective_id"],$event_id,true); } else if ($assessment_id) { $fields["child_mapped"] = assessment_objective_parent_mapped_course($objective["objective_id"],$assessment_id,true); } } $query = " SELECT a.* FROM `global_lu_objectives` AS a JOIN `objective_organisation` AS b ON a.`objective_id` = b.`objective_id` WHERE a.`objective_parent` = ".$db->qstr($objective["objective_id"])." AND b.`organisation_id` = ".$db->qstr($org_id); $fields["has_child"] = $db->GetAll($query) ? true : false; $obj_array[] = $fields; } echo json_encode($obj_array); } else { echo json_encode(array('error'=>'No child objectives found for the selected objective.')); } exit; }
EntradaProject/entrada-1x
www-root/api/fetchobjectives.api.php
PHP
gpl-3.0
4,728
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * This program is Free Software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.grobox.transportr.data.locations; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import androidx.test.ext.junit.runners.AndroidJUnit4; import de.grobox.transportr.data.DbTest; import de.schildbach.pte.dto.Location; import de.schildbach.pte.dto.Point; import de.schildbach.pte.dto.Product; import static de.schildbach.pte.NetworkId.BVG; import static de.schildbach.pte.NetworkId.DB; import static de.schildbach.pte.dto.LocationType.ADDRESS; import static de.schildbach.pte.dto.LocationType.ANY; import static de.schildbach.pte.dto.LocationType.POI; import static de.schildbach.pte.dto.LocationType.STATION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @RunWith(AndroidJUnit4.class) public class FavoriteLocationTest extends DbTest { private LocationDao dao; @Before @Override public void createDb() throws Exception { super.createDb(); dao = db.locationDao(); } @Test public void insertFavoriteLocation() throws Exception { // no locations should exist assertNotNull(getValue(dao.getFavoriteLocations(DB))); // create a complete station location Location loc1 = new Location(STATION, "stationId", Point.from1E6(23, 42), "place", "name", Product.ALL); long uid1 = dao.addFavoriteLocation(new FavoriteLocation(DB, loc1)); // assert that location has been inserted and retrieved properly List<FavoriteLocation> locations1 = getValue(dao.getFavoriteLocations(DB)); assertEquals(1, locations1.size()); FavoriteLocation f1 = locations1.get(0); assertEquals(uid1, f1.getUid()); assertEquals(DB, f1.getNetworkId()); assertEquals(loc1.type, f1.type); assertEquals(loc1.id, f1.id); assertEquals(loc1.getLatAs1E6(), f1.lat); assertEquals(loc1.getLonAs1E6(), f1.lon); assertEquals(loc1.place, f1.place); assertEquals(loc1.name, f1.name); assertEquals(loc1.products, f1.products); // insert a second location in a different network Location loc2 = new Location(ANY, null, Point.from1E6(1337, 0), null, null, Product.fromCodes("ISB".toCharArray())); long uid2 = dao.addFavoriteLocation(new FavoriteLocation(BVG, loc2)); // assert that location has been inserted and retrieved properly List<FavoriteLocation> locations2 = getValue(dao.getFavoriteLocations(BVG)); assertEquals(1, locations2.size()); FavoriteLocation f2 = locations2.get(0); assertEquals(uid2, f2.getUid()); assertEquals(BVG, f2.getNetworkId()); assertEquals(loc2.type, f2.type); assertEquals(loc2.id, f2.id); assertEquals(loc2.getLatAs1E6(), f2.lat); assertEquals(loc2.getLonAs1E6(), f2.lon); assertEquals(loc2.place, f2.place); assertEquals(loc2.name, f2.name); assertEquals(loc2.products, f2.products); } @Test public void replaceFavoriteLocation() throws Exception { // create a complete station location Location loc1 = new Location(STATION, "stationId", Point.from1E6(23, 42), "place", "name", Product.ALL); long uid1 = dao.addFavoriteLocation(new FavoriteLocation(DB, loc1)); // retrieve favorite location List<FavoriteLocation> locations1 = getValue(dao.getFavoriteLocations(DB)); assertEquals(1, locations1.size()); FavoriteLocation f1 = locations1.get(0); assertEquals(uid1, f1.getUid()); // change the favorite location and replace it in the DB f1.place = "new place"; f1.name = "new name"; f1.products = null; uid1 = dao.addFavoriteLocation(f1); assertEquals(uid1, f1.getUid()); // retrieve favorite location again List<FavoriteLocation> locations2 = getValue(dao.getFavoriteLocations(DB)); assertEquals(1, locations2.size()); FavoriteLocation f2 = locations2.get(0); // assert that same location was retrieved and data changed assertEquals(f1.getUid(), f2.getUid()); assertEquals(f1.place, f2.place); assertEquals(f1.name, f2.name); assertEquals(f1.products, f2.products); } @Test public void twoLocationsWithoutId() throws Exception { Location loc1 = new Location(ADDRESS, null, Point.from1E6(23, 42), null, "name1", null); Location loc2 = new Location(ADDRESS, null, Point.from1E6(0, 0), null, "name2", null); dao.addFavoriteLocation(new FavoriteLocation(DB, loc1)); dao.addFavoriteLocation(new FavoriteLocation(DB, loc2)); assertEquals(2, getValue(dao.getFavoriteLocations(DB)).size()); } @Test public void twoLocationsWithSameId() throws Exception { Location loc1 = new Location(ADDRESS, "test", Point.from1E6(23, 42), null, "name1", null); Location loc2 = new Location(ADDRESS, "test", Point.from1E6(0, 0), null, "name2", null); dao.addFavoriteLocation(new FavoriteLocation(DB, loc1)); dao.addFavoriteLocation(new FavoriteLocation(DB, loc2)); // second location should override first one and don't create a new one List<FavoriteLocation> locations = getValue(dao.getFavoriteLocations(DB)); assertEquals(1, locations.size()); FavoriteLocation f = locations.get(0); assertEquals(loc2.getLatAs1E6(), f.lat); assertEquals(loc2.getLonAs1E6(), f.lon); assertEquals(loc2.name, f.name); } @Test public void twoLocationsWithSameIdDifferentNetworks() throws Exception { Location loc1 = new Location(ADDRESS, "test", Point.from1E6(23, 42), null, "name1", null); Location loc2 = new Location(ADDRESS, "test", Point.from1E6(0, 0), null, "name2", null); dao.addFavoriteLocation(new FavoriteLocation(DB, loc1)); dao.addFavoriteLocation(new FavoriteLocation(BVG, loc2)); // second location should not override first one assertEquals(1, getValue(dao.getFavoriteLocations(DB)).size()); assertEquals(1, getValue(dao.getFavoriteLocations(BVG)).size()); } @Test public void getFavoriteLocationByUid() throws Exception { // insert a minimal location Location l1 = new Location(STATION, "id", Point.from1E6(1, 1), "place", "name", null); FavoriteLocation f1 = new FavoriteLocation(DB, l1); long uid = dao.addFavoriteLocation(f1); // retrieve by UID FavoriteLocation f2 = dao.getFavoriteLocation(uid); // assert that retrieval worked assertNotNull(f2); assertEquals(uid, f2.getUid()); assertEquals(DB, f2.getNetworkId()); assertEquals(l1.type, f2.type); assertEquals(l1.id, f2.id); assertEquals(l1.getLatAs1E6(), f2.lat); assertEquals(l1.getLonAs1E6(), f2.lon); assertEquals(l1.place, f2.place); assertEquals(l1.name, f2.name); assertEquals(l1.products, f2.products); } @Test public void getFavoriteLocationByValues() { // insert a minimal location Location loc1 = new Location(ANY, null, Point.from1E6(0, 0), null, null, null); dao.addFavoriteLocation(new FavoriteLocation(DB, loc1)); // assert the exists check works assertNotNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name)); assertNull(dao.getFavoriteLocation(DB, ADDRESS, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name)); assertNull(dao.getFavoriteLocation(DB, loc1.type, "id", loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, loc1.name)); assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, 1, loc1.getLonAs1E6(), loc1.place, loc1.name)); assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), 1, loc1.place, loc1.name)); assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), "place", loc1.name)); assertNull(dao.getFavoriteLocation(DB, loc1.type, loc1.id, loc1.getLatAs1E6(), loc1.getLonAs1E6(), loc1.place, "name")); // insert a maximal location Location loc2 = new Location(STATION, "id", Point.from1E6(1, 1), "place", "name", null); dao.addFavoriteLocation(new FavoriteLocation(DB, loc2)); // assert the exists check works assertNotNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name)); assertNull(dao.getFavoriteLocation(DB, POI, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name)); assertNull(dao.getFavoriteLocation(DB, loc2.type, "oid", loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, loc2.name)); assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, 42, loc2.getLonAs1E6(), loc2.place, loc2.name)); assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), 42, loc2.place, loc2.name)); assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), "oplace", loc2.name)); assertNull(dao.getFavoriteLocation(DB, loc2.type, loc2.id, loc2.getLatAs1E6(), loc2.getLonAs1E6(), loc2.place, "oname")); } }
grote/Transportr
app/src/androidTest/java/de/grobox/transportr/data/locations/FavoriteLocationTest.java
Java
gpl-3.0
9,335
import time from datetime import datetime from pydoc import locate from unittest import SkipTest from countries_plus.models import Country from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.test import override_settings, tag from django.urls import reverse from django.utils import timezone from django.utils.timezone import make_aware from elasticsearch.client import IngestClient from elasticsearch.exceptions import ConnectionError from elasticsearch_dsl.connections import ( connections, get_connection as get_es_connection, ) from languages_plus.models import Language from rest_framework import status from rest_framework.test import APITestCase, APITransactionTestCase from ESSArch_Core.agents.models import ( Agent, AgentTagLink, AgentTagLinkRelationType, AgentType, MainAgentType, RefCode, ) from ESSArch_Core.auth.models import Group, GroupType from ESSArch_Core.configuration.models import Feature from ESSArch_Core.ip.models import InformationPackage from ESSArch_Core.maintenance.models import AppraisalJob from ESSArch_Core.search import alias_migration from ESSArch_Core.tags.documents import ( Archive, Component, File, StructureUnitDocument, ) from ESSArch_Core.tags.models import ( Structure, StructureType, StructureUnit, StructureUnitType, Tag, TagStructure, TagVersion, TagVersionType, ) User = get_user_model() def get_test_client(nowait=False): client = get_es_connection('default') # wait for yellow status for _ in range(1 if nowait else 5): try: client.cluster.health(wait_for_status="yellow") return client except ConnectionError: time.sleep(0.1) else: # timeout raise SkipTest("Elasticsearch failed to start") class ESSArchSearchBaseTestCaseMixin: @staticmethod def _get_client(): return get_test_client() @classmethod def setUpClass(cls): if cls._overridden_settings: cls._cls_overridden_context = override_settings(**cls._overridden_settings) cls._cls_overridden_context.enable() connections.configure(**settings.ELASTICSEARCH_CONNECTIONS) cls.es_client = cls._get_client() IngestClient(cls.es_client).put_pipeline(id='ingest_attachment', body={ 'description': "Extract attachment information", 'processors': [ { "attachment": { "field": "data", "indexed_chars": "-1" }, "remove": { "field": "data" } } ] }) super().setUpClass() def setUp(self): for _index_name, index_class in settings.ELASTICSEARCH_INDEXES['default'].items(): doctype = locate(index_class) alias_migration.setup_index(doctype) def tearDown(self): self.es_client.indices.delete(index="*", ignore=404) self.es_client.indices.delete_template(name="*", ignore=404) @override_settings(ELASTICSEARCH_CONNECTIONS=settings.ELASTICSEARCH_TEST_CONNECTIONS) @tag('requires-elasticsearch') class ESSArchSearchBaseTestCase(ESSArchSearchBaseTestCaseMixin, APITestCase): pass @override_settings(ELASTICSEARCH_CONNECTIONS=settings.ELASTICSEARCH_TEST_CONNECTIONS) @tag('requires-elasticsearch') class ESSArchSearchBaseTransactionTestCase(ESSArchSearchBaseTestCaseMixin, APITransactionTestCase): pass class ComponentSearchTestCase(ESSArchSearchBaseTestCase): fixtures = ['countries_data', 'languages_data'] @classmethod def setUpTestData(cls): cls.url = reverse('search-list') Feature.objects.create(name='archival descriptions', enabled=True) cls.user = User.objects.create() permission = Permission.objects.get(codename='search') cls.user.user_permissions.add(permission) org_group_type = GroupType.objects.create(codename='organization') cls.group1 = Group.objects.create(name='group1', group_type=org_group_type) cls.group1.add_member(cls.user.essauth_member) cls.group2 = Group.objects.create(name='group2', group_type=org_group_type) cls.group2.add_member(cls.user.essauth_member) cls.component_type = TagVersionType.objects.create(name='component', archive_type=False) cls.archive_type = TagVersionType.objects.create(name='archive', archive_type=True) def setUp(self): super().setUp() self.client.force_authenticate(user=self.user) @staticmethod def create_agent(): return Agent.objects.create( type=AgentType.objects.create(main_type=MainAgentType.objects.create()), ref_code=RefCode.objects.create( country=Country.objects.get(iso='SE'), repository_code='repo', ), level_of_detail=0, record_status=0, script=0, language=Language.objects.get(iso_639_1='sv'), create_date=timezone.now(), ) def test_search_component(self): component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('without archive'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) structure_type = StructureType.objects.create() structure_template = Structure.objects.create(type=structure_type, is_template=True) archive_tag = Tag.objects.create() archive_tag_version = TagVersion.objects.create( tag=archive_tag, type=self.archive_type, elastic_index="archive", ) self.group1.add_object(archive_tag_version) structure, archive_tag_structure = structure_template.create_template_instance(archive_tag) Archive.from_obj(archive_tag_version).save(refresh='true') TagStructure.objects.create(tag=component_tag, parent=archive_tag_structure, structure=structure) Component.index_documents(remove_stale=True) with self.subTest('with archive'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) with self.subTest('with archive, non-active organization'): self.user.user_profile.current_organization = self.group2 self.user.user_profile.save() res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_filter_on_component_agent(self): agent = self.create_agent() component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", ) structure_type = StructureType.objects.create() structure_template = Structure.objects.create(type=structure_type, is_template=True) archive_tag = Tag.objects.create() archive_tag_version = TagVersion.objects.create( tag=archive_tag, type=self.archive_type, elastic_index="archive", ) structure, archive_tag_structure = structure_template.create_template_instance(archive_tag) Archive.from_obj(archive_tag_version).save(refresh='true') TagStructure.objects.create(tag=component_tag, parent=archive_tag_structure, structure=structure) AgentTagLink.objects.create( agent=agent, tag=component_tag_version, type=AgentTagLinkRelationType.objects.create(), ) Component.from_obj(component_tag_version).save(refresh='true') res = self.client.get(self.url, {'agents': str(agent.pk)}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) def test_filter_on_archive_agent(self): agent = self.create_agent() component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", ) structure_type = StructureType.objects.create() structure_template = Structure.objects.create(type=structure_type, is_template=True) archive_tag = Tag.objects.create() archive_tag_version = TagVersion.objects.create( tag=archive_tag, type=self.archive_type, elastic_index="archive", ) structure, archive_tag_structure = structure_template.create_template_instance(archive_tag) Archive.from_obj(archive_tag_version).save(refresh='true') TagStructure.objects.create(tag=component_tag, parent=archive_tag_structure, structure=structure) AgentTagLink.objects.create( agent=agent, tag=archive_tag_version, type=AgentTagLinkRelationType.objects.create(), ) Component.from_obj(component_tag_version).save(refresh='true') res = self.client.get(self.url, {'agents': str(agent.pk)}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) def test_filter_appraisal_date(self): component_tag = Tag.objects.create(appraisal_date=make_aware(datetime(year=2020, month=1, day=1))) component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", ) doc = Component.from_obj(component_tag_version) doc.save(refresh='true') with self.subTest('2020-01-01 is after or equal to 2020-01-01'): res = self.client.get(self.url, data={'appraisal_date_after': '2020-01-01'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) with self.subTest('2020-01-01 not after 2020-01-02'): res = self.client.get(self.url, data={'appraisal_date_after': '2020-01-02'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('2020-01-01 not before 2019-12-31'): res = self.client.get(self.url, data={'appraisal_date_before': '2019-12-31'}) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('2020-01-01 between 2019-01-01 and 2020-01-01'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2019-01-01', 'appraisal_date_before': '2020-01-01', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) with self.subTest('2020-01-01 between 2020-01-01 and 2020-12-31'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2020-01-01', 'appraisal_date_before': '2020-12-31', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) with self.subTest('2020-01-01 not between 2020-01-02 and 2020-12-31'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2020-01-02', 'appraisal_date_before': '2020-12-31', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('2020-01-01 not between 2019-01-01 and 2019-12-31'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2019-01-01', 'appraisal_date_before': '2019-12-31', }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) with self.subTest('invalid range 2020-12-31 - 2020-01-01'): res = self.client.get(self.url, data={ 'appraisal_date_after': '2020-12-31', 'appraisal_date_before': '2020-01-01', }) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_add_results_to_appraisal(self): component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( name='foo', tag=component_tag, type=self.component_type, elastic_index="component", ) Component.from_obj(component_tag_version).save(refresh='true') component_tag2 = Tag.objects.create() component_tag_version2 = TagVersion.objects.create( name='bar', tag=component_tag2, type=self.component_type, elastic_index="component", ) Component.from_obj(component_tag_version2).save(refresh='true') # test that we don't try to add structure units matched by query to job structure = Structure.objects.create(type=StructureType.objects.create(), is_template=False) structure_unit = StructureUnit.objects.create( name='foo', structure=structure, type=StructureUnitType.objects.create(structure_type=structure.type), ) StructureUnitDocument.from_obj(structure_unit).save(refresh='true') appraisal_job = AppraisalJob.objects.create() res = self.client.get(self.url, data={ 'q': 'foo', 'add_to_appraisal': appraisal_job.pk }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertCountEqual(appraisal_job.tags.all(), [component_tag]) res = self.client.get(self.url, data={ 'add_to_appraisal': appraisal_job.pk }) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertCountEqual(appraisal_job.tags.all(), [component_tag, component_tag2]) class DocumentSearchTestCase(ESSArchSearchBaseTestCase): fixtures = ['countries_data', 'languages_data'] @classmethod def setUpTestData(cls): cls.url = reverse('search-list') Feature.objects.create(name='archival descriptions', enabled=True) org_group_type = GroupType.objects.create(codename='organization') cls.group = Group.objects.create(group_type=org_group_type) cls.component_type = TagVersionType.objects.create(name='component', archive_type=False) cls.archive_type = TagVersionType.objects.create(name='archive', archive_type=True) def setUp(self): super().setUp() permission = Permission.objects.get(codename='search') self.user = User.objects.create() self.user.user_permissions.add(permission) self.group.add_member(self.user.essauth_member) self.client.force_authenticate(user=self.user) def test_search_document_in_ip_with_other_user_responsible_without_permission_to_see_it(self): other_user = User.objects.create(username='other') self.group.add_member(other_user.essauth_member) ip = InformationPackage.objects.create(responsible=other_user) self.group.add_object(ip) document_tag = Tag.objects.create(information_package=ip) document_tag_version = TagVersion.objects.create( tag=document_tag, type=self.component_type, elastic_index="document", ) File.from_obj(document_tag_version).save(refresh='true') res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_search_document_in_ip_with_other_user_responsible_with_permission_to_see_it(self): self.user.user_permissions.add(Permission.objects.get(codename='see_other_user_ip_files')) other_user = User.objects.create(username='other') self.group.add_member(other_user.essauth_member) ip = InformationPackage.objects.create(responsible=other_user) self.group.add_object(ip) document_tag = Tag.objects.create(information_package=ip) document_tag_version = TagVersion.objects.create( tag=document_tag, type=self.component_type, elastic_index="document", ) File.from_obj(document_tag_version).save(refresh='true') res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(document_tag_version.pk)) class SecurityLevelTestCase(ESSArchSearchBaseTestCase): fixtures = ['countries_data', 'languages_data'] @classmethod def setUpTestData(cls): cls.url = reverse('search-list') Feature.objects.create(name='archival descriptions', enabled=True) cls.component_type = TagVersionType.objects.create(name='component', archive_type=False) cls.security_levels = [1, 2, 3, 4, 5] def setUp(self): super().setUp() self.user = User.objects.create() permission = Permission.objects.get(codename='search') self.user.user_permissions.add(permission) self.client.force_authenticate(user=self.user) def test_user_with_no_security_level(self): component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", security_level=None, ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('no security level'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) for lvl in self.security_levels[1:]: with self.subTest(f'security level {lvl}'): component_tag_version.security_level = lvl component_tag_version.save() Component.from_obj(component_tag_version).save(refresh='true') res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_user_with_security_level_3(self): self.user.user_permissions.add(Permission.objects.get(codename='security_level_3')) self.user = User.objects.get(pk=self.user.pk) component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", security_level=None, ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('no security level'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) for lvl in self.security_levels: with self.subTest(f'security level {lvl}'): component_tag_version.security_level = lvl component_tag_version.save() Component.from_obj(component_tag_version).save(refresh='true') if lvl == 3: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) else: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0) def test_user_with_multiple_security_levels(self): self.user.user_permissions.add( Permission.objects.get(codename='security_level_1'), Permission.objects.get(codename='security_level_3'), ) self.user = User.objects.get(pk=self.user.pk) component_tag = Tag.objects.create() component_tag_version = TagVersion.objects.create( tag=component_tag, type=self.component_type, elastic_index="component", security_level=None, ) Component.from_obj(component_tag_version).save(refresh='true') with self.subTest('no security level'): res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) for lvl in self.security_levels: with self.subTest(f'security level {lvl}'): component_tag_version.security_level = lvl component_tag_version.save() Component.from_obj(component_tag_version).save(refresh='true') if lvl in [1, 3]: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 1) self.assertEqual(res.data['hits'][0]['_id'], str(component_tag_version.pk)) else: res = self.client.get(self.url) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data['hits']), 0)
ESSolutions/ESSArch_Core
ESSArch_Core/tags/tests/test_search.py
Python
gpl-3.0
22,665
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>ActionView::Helpers::NumberHelper::InvalidNumberError</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../../css/github.css" type="text/css" media="screen" /> <script src="../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.2.0</span><br /> <h1> <span class="type">Class</span> ActionView::Helpers::NumberHelper::InvalidNumberError <span class="parent">&lt; StandardError </span> </h1> <ul class="files"> <li><a href="../../../../files/__/__/_rvm/gems/ruby-2_1_1/gems/actionview-4_2_0/lib/action_view/helpers/number_helper_rb.html">/home/rafael/.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/helpers/number_helper.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <div class="description"> <p>Raised when argument <code>number</code> param given to the helpers is invalid and the option :raise is set to <code>true</code>.</p> </div> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>N</dt> <dd> <ul> <li> <a href="#method-c-new">new</a> </li> </ul> </dd> </dl> <!-- Section attributes --> <div class="sectiontitle">Attributes</div> <table border='0' cellpadding='5'> <tr valign='top'> <td class='attr-rw'> [RW] </td> <td class='attr-name'>number</td> <td class='attr-desc'></td> </tr> </table> <!-- Methods --> <div class="sectiontitle">Class Public methods</div> <div class="method"> <div class="title method-title" id="method-c-new"> <b>new</b>(number) <a href="../../../../classes/ActionView/Helpers/NumberHelper/InvalidNumberError.html#method-c-new" name="method-c-new" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-c-new_source')" id="l_method-c-new_source">show</a> </p> <div id="method-c-new_source" class="dyn-source"> <pre><span class="ruby-comment"># File ../../.rvm/gems/ruby-2.1.1/gems/actionview-4.2.0/lib/action_view/helpers/number_helper.rb, line 22</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">initialize</span>(<span class="ruby-identifier">number</span>) <span class="ruby-ivar">@number</span> = <span class="ruby-identifier">number</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
rafaellc28/Portfolio
doc/api/classes/ActionView/Helpers/NumberHelper/InvalidNumberError.html
HTML
gpl-3.0
4,256
here is some text followed by \mycommand {here is some text \textbf {bold tex } after text } {and some \emph {emphacised } text } [and finally some \itshape {italicized } ] and some more text \textbf {bold text } and here is another command \cmh [optional ] {mandatory } after text \final {command text } and yet more text here is some text followed by \mycommand {here is some text \textbf {bold tex } after text } {and some \emph {emphacised } text } [and finally some \itshape {italicized } ] and some more text \textbf {bold text } and here is another command \cmh [optional ] {mandatory } after text \final {command text } and yet more text here is some text followed by \mycommand {here is some text \textbf {bold tex } after text } {and some \emph {emphacised } text } [and finally some \itshape {italicized } ] and some more text \textbf {bold text } and here is another command \cmh [optional ] {mandatory } after text \final {command text } and yet more text
cmhughes/latexindent.pl
test-cases/commands/commands-nested-multiple-mod47.tex
TeX
gpl-3.0
1,091
/** * Bukkit plugin which moves the mobs closer to the players. * Copyright (C) 2016 Jakub "Co0sh" Sapalski * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pl.betoncraft.hordes; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.attribute.Attribute; import org.bukkit.attribute.AttributeInstance; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; /** * Blocks the mobs from spawning in unwanted places. * * @author Jakub Sapalski */ public class Blocker implements Listener { private Hordes plugin; private Random rand = new Random(); /** * Starts the blocker. * * @param plugin * instance of the plugin */ public Blocker(Hordes plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } @EventHandler public void onSpawn(CreatureSpawnEvent event) { LivingEntity e = event.getEntity(); WorldSettings set = plugin.getWorlds().get(event.getEntity().getWorld().getName()); if (set == null) { return; } if (!set.getEntities().contains(e.getType())) { return; } if (!set.shouldExist(e)) { event.setCancelled(true); } else if (rand.nextDouble() > set.getRatio(e.getType())) { event.setCancelled(true); } else { AttributeInstance maxHealth = e.getAttribute(Attribute.GENERIC_MAX_HEALTH); maxHealth.setBaseValue(maxHealth.getBaseValue() * set.getHealth(e.getType())); e.setHealth(e.getMaxHealth()); } } }
Co0sh/Hordes
src/main/java/pl/betoncraft/hordes/Blocker.java
Java
gpl-3.0
2,168
<!DOCTYPE HTML> <html lang="zh-hans" > <!-- Start book Unity Source Book --> <head> <!-- head:start --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Transform | Unity Source Book</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="description" content=""> <meta name="generator" content="GitBook 2.6.7"> <meta name="author" content="李康"> <meta name="HandheldFriendly" content="true"/> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png"> <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon"> <link rel="stylesheet" href="../gitbook/style.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-highlight/website.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-maxiang/maxiang.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-comment/plugin.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-search/search.css"> <link rel="stylesheet" href="../gitbook/plugins/gitbook-plugin-fontsettings/website.css"> <link rel="next" href="../UnityClass/translate.html" /> <link rel="prev" href="../UnityClass/resources.html" /> <!-- head:end --> </head> <body> <!-- body:start --> <div class="book" data-level="3.5" data-chapter-title="Transform" data-filepath="UnityClass/transform.md" data-basepath=".." data-revision="Tue Apr 19 2016 08:44:49 GMT+0800 (中国标准时间)" data-innerlanguage=""> <div class="book-summary"> <nav role="navigation"> <ul class="summary"> <li class="chapter " data-level="0" data-path="index.html"> <a href="../index.html"> <i class="fa fa-check"></i> 介绍 </a> </li> <li class="chapter " data-level="1" > <span><b>1.</b> Unity基础</span> <ul class="articles"> <li class="chapter " data-level="1.1" > <span><b>1.1.</b> Unity中的主要面板</span> </li> <li class="chapter " data-level="1.2" data-path="UnityBasic/prefab.html"> <a href="../UnityBasic/prefab.html"> <i class="fa fa-check"></i> <b>1.2.</b> 预制体 </a> </li> <li class="chapter " data-level="1.3" data-path="UnityBasic/scene.html"> <a href="../UnityBasic/scene.html"> <i class="fa fa-check"></i> <b>1.3.</b> 场景搭建 </a> </li> </ul> </li> <li class="chapter " data-level="2" > <span><b>2.</b> 3D数学基础</span> <ul class="articles"> <li class="chapter " data-level="2.1" data-path="3DMath/coordinate.html"> <a href="../3DMath/coordinate.html"> <i class="fa fa-check"></i> <b>2.1.</b> 坐标系 </a> </li> <li class="chapter " data-level="2.2" data-path="3DMath/vector.html"> <a href="../3DMath/vector.html"> <i class="fa fa-check"></i> <b>2.2.</b> 向量 </a> </li> <li class="chapter " data-level="2.3" data-path="3DMath/vector_compute.html"> <a href="../3DMath/vector_compute.html"> <i class="fa fa-check"></i> <b>2.3.</b> 向量的运算 </a> </li> <li class="chapter " data-level="2.4" > <span><b>2.4.</b> 奥特曼打小怪兽</span> </li> <li class="chapter " data-level="2.5" > <span><b>2.5.</b> 矩阵</span> </li> <li class="chapter " data-level="2.6" > <span><b>2.6.</b> 计算机图形学基础</span> </li> <li class="chapter " data-level="2.7" > <span><b>2.7.</b> 四元数与旋转</span> </li> </ul> </li> <li class="chapter " data-level="3" > <span><b>3.</b> Unity中的类</span> <ul class="articles"> <li class="chapter " data-level="3.1" data-path="UnityClass/component.html"> <a href="../UnityClass/component.html"> <i class="fa fa-check"></i> <b>3.1.</b> Component </a> </li> <li class="chapter " data-level="3.2" data-path="UnityClass/monobehaviour.html"> <a href="../UnityClass/monobehaviour.html"> <i class="fa fa-check"></i> <b>3.2.</b> MonoBehaviour </a> </li> <li class="chapter " data-level="3.3" data-path="UnityClass/gameobject.html"> <a href="../UnityClass/gameobject.html"> <i class="fa fa-check"></i> <b>3.3.</b> GameObject </a> </li> <li class="chapter " data-level="3.4" data-path="UnityClass/resources.html"> <a href="../UnityClass/resources.html"> <i class="fa fa-check"></i> <b>3.4.</b> Resources </a> </li> <li class="chapter active" data-level="3.5" data-path="UnityClass/transform.html"> <a href="../UnityClass/transform.html"> <i class="fa fa-check"></i> <b>3.5.</b> Transform </a> <ul class="articles"> <li class="chapter " data-level="3.5.1" data-path="UnityClass/translate.html"> <a href="../UnityClass/translate.html"> <i class="fa fa-check"></i> <b>3.5.1.</b> 移动 </a> </li> <li class="chapter " data-level="3.5.2" data-path="UnityClass/rotate.html"> <a href="../UnityClass/rotate.html"> <i class="fa fa-check"></i> <b>3.5.2.</b> 旋转 </a> </li> <li class="chapter " data-level="3.5.3" data-path="UnityClass/scale.html"> <a href="../UnityClass/scale.html"> <i class="fa fa-check"></i> <b>3.5.3.</b> 缩放 </a> </li> <li class="chapter " data-level="3.5.4" data-path="UnityClass/parent.html"> <a href="../UnityClass/parent.html"> <i class="fa fa-check"></i> <b>3.5.4.</b> 物体间的层次关系 </a> </li> </ul> </li> <li class="chapter " data-level="3.6" data-path="UnityClass/time.html"> <a href="../UnityClass/time.html"> <i class="fa fa-check"></i> <b>3.6.</b> Time </a> </li> <li class="chapter " data-level="3.7" data-path="UnityClass/input.html"> <a href="../UnityClass/input.html"> <i class="fa fa-check"></i> <b>3.7.</b> Input </a> </li> <li class="chapter " data-level="3.8" data-path="UnityClass/object.html"> <a href="../UnityClass/object.html"> <i class="fa fa-check"></i> <b>3.8.</b> Object </a> </li> </ul> </li> <li class="chapter " data-level="4" > <span><b>4.</b> 协同</span> <ul class="articles"> <li class="chapter " data-level="4.1" data-path="Coroutine/coroutine.html"> <a href="../Coroutine/coroutine.html"> <i class="fa fa-check"></i> <b>4.1.</b> 协同 Coroutine </a> </li> <li class="chapter " data-level="4.2" data-path="Coroutine/xiang_mu_shi_6218-_ta_fang.html"> <a href="../Coroutine/xiang_mu_shi_6218-_ta_fang.html"> <i class="fa fa-check"></i> <b>4.2.</b> 项目实战-塔防 </a> </li> </ul> </li> <li class="chapter " data-level="5" > <span><b>5.</b> 物理系统</span> <ul class="articles"> <li class="chapter " data-level="5.1" data-path="Physics/rigidbody.html"> <a href="../Physics/rigidbody.html"> <i class="fa fa-check"></i> <b>5.1.</b> 刚体 Rigidbody </a> </li> <li class="chapter " data-level="5.2" data-path="Physics/constant_force.html"> <a href="../Physics/constant_force.html"> <i class="fa fa-check"></i> <b>5.2.</b> 静态力场 Constant Force </a> </li> <li class="chapter " data-level="5.3" data-path="Physics/collider.html"> <a href="../Physics/collider.html"> <i class="fa fa-check"></i> <b>5.3.</b> 碰撞体 Collider </a> </li> <li class="chapter " data-level="5.4" data-path="Physics/ray.html"> <a href="../Physics/ray.html"> <i class="fa fa-check"></i> <b>5.4.</b> 射线 Ray </a> </li> <li class="chapter " data-level="5.5" data-path="Physics/cloth.html"> <a href="../Physics/cloth.html"> <i class="fa fa-check"></i> <b>5.5.</b> 布料 Cloth </a> </li> <li class="chapter " data-level="5.6" data-path="Physics/joint.html"> <a href="../Physics/joint.html"> <i class="fa fa-check"></i> <b>5.6.</b> 关节 Joint </a> </li> <li class="chapter " data-level="5.7" data-path="Physics/character_controller.html"> <a href="../Physics/character_controller.html"> <i class="fa fa-check"></i> <b>5.7.</b> 角色控制器 Character Controller </a> </li> <li class="chapter " data-level="5.8" data-path="Physics/project-3d-hit-plane.html"> <a href="../Physics/project-3d-hit-plane.html"> <i class="fa fa-check"></i> <b>5.8.</b> 项目实战-3D打飞机 </a> </li> </ul> </li> <li class="chapter " data-level="6" data-path="Animate/readme.html"> <a href="../Animate/readme.html"> <i class="fa fa-check"></i> <b>6.</b> 动作系统 </a> <ul class="articles"> <li class="chapter " data-level="6.1" data-path="Animate/2dgame.html"> <a href="../Animate/2dgame.html"> <i class="fa fa-check"></i> <b>6.1.</b> 2D游戏开发 </a> </li> <li class="chapter " data-level="6.2" data-path="Animate/animation.html"> <a href="../Animate/animation.html"> <i class="fa fa-check"></i> <b>6.2.</b> 帧动画 </a> </li> <li class="chapter " data-level="6.3" data-path="Animate/project-angry-bird.html"> <a href="../Animate/project-angry-bird.html"> <i class="fa fa-check"></i> <b>6.3.</b> 项目实战-愤怒的小鸟 </a> </li> <li class="chapter " data-level="6.4" data-path="Animate/animator_controller.html"> <a href="../Animate/animator_controller.html"> <i class="fa fa-check"></i> <b>6.4.</b> 动画状态机 </a> </li> <li class="chapter " data-level="6.5" > <span><b>6.5.</b> 3D动画</span> </li> <li class="chapter " data-level="6.6" > <span><b>6.6.</b> 层动画</span> </li> <li class="chapter " data-level="6.7" > <span><b>6.7.</b> Blend动画</span> </li> </ul> </li> <li class="chapter " data-level="7" > <span><b>7.</b> 组件</span> <ul class="articles"> <li class="chapter " data-level="7.1" data-path="Component/camera.html"> <a href="../Component/camera.html"> <i class="fa fa-check"></i> <b>7.1.</b> 摄像机 Camera </a> </li> <li class="chapter " data-level="7.2" data-path="Component/project_observe.html"> <a href="../Component/project_observe.html"> <i class="fa fa-check"></i> <b>7.2.</b> 项目实战-观察模型 </a> </li> <li class="chapter " data-level="7.3" data-path="renderer.html"> <span><b>7.3.</b> 显示组件 Renderer</span> </li> <li class="chapter " data-level="7.4" > <span><b>7.4.</b> 粒子系统</span> </li> </ul> </li> <li class="chapter " data-level="8" > <span><b>8.</b> UI</span> </li> <li class="chapter " data-level="9" > <span><b>9.</b> 数据持久化</span> <ul class="articles"> <li class="chapter " data-level="9.1" > <span><b>9.1.</b> IO流</span> </li> <li class="chapter " data-level="9.2" > <span><b>9.2.</b> 序列化与反序列化</span> </li> <li class="chapter " data-level="9.3" > <span><b>9.3.</b> XML</span> </li> <li class="chapter " data-level="9.4" > <span><b>9.4.</b> JSON</span> </li> </ul> </li> <li class="chapter " data-level="10" > <span><b>10.</b> 网络</span> </li> <li class="chapter " data-level="11" > <span><b>11.</b> AI</span> <ul class="articles"> <li class="chapter " data-level="11.1" data-path="AI/state_controller.html"> <a href="../AI/state_controller.html"> <i class="fa fa-check"></i> <b>11.1.</b> 状态机的实现 </a> </li> </ul> </li> <li class="chapter " data-level="12" > <span><b>12.</b> 游戏框架</span> <ul class="articles"> <li class="chapter " data-level="12.1" > <span><b>12.1.</b> 模块间通信</span> </li> <li class="chapter " data-level="12.2" > <span><b>12.2.</b> 全局数据</span> </li> <li class="chapter " data-level="12.3" > <span><b>12.3.</b> 单例模式</span> </li> </ul> </li> <li class="chapter " data-level="13" > <span><b>13.</b> 常用插件</span> </li> <li class="chapter " data-level="14" data-path="项目实战/readme.html"> <span><b>14.</b> 项目实战</span> <ul class="articles"> <li class="chapter " data-level="14.1" > <span><b>14.1.</b> Unity官方案例介绍</span> </li> </ul> </li> <li class="chapter " data-level="15" data-path="Summary/readme.html"> <a href="../Summary/readme.html"> <i class="fa fa-check"></i> <b>15.</b> 总结 </a> <ul class="articles"> <li class="chapter " data-level="15.1" data-path="Summary/awesome.html"> <a href="../Summary/awesome.html"> <i class="fa fa-check"></i> <b>15.1.</b> Awesome </a> </li> <li class="chapter " data-level="15.2" > <span><b>15.2.</b> Unity中的常用快捷键及使用技巧</span> </li> <li class="chapter " data-level="15.3" > <span><b>15.3.</b> MonoDevelop中的常用快捷键及使用技巧</span> </li> <li class="chapter " data-level="15.4" > <span><b>15.4.</b> VS中的常用快捷键及使用技巧</span> </li> <li class="chapter " data-level="15.5" data-path="Summary/dui_unity_de_zheng_ti_ren_shi.html"> <a href="../Summary/dui_unity_de_zheng_ti_ren_shi.html"> <i class="fa fa-check"></i> <b>15.5.</b> 对Unity的整体认识 </a> </li> <li class="chapter " data-level="15.6" > <span><b>15.6.</b> 实现等待</span> </li> <li class="chapter " data-level="15.7" > <span><b>15.7.</b> 控制物体移动的几种方式</span> </li> <li class="chapter " data-level="15.8" > <span><b>15.8.</b> 刚体与碰撞体间的联系</span> </li> <li class="chapter " data-level="15.9" data-path="Summary/vector3forwardtransformforwardyu_wu_ti_zuo_biao_xi.html"> <a href="../Summary/vector3forwardtransformforwardyu_wu_ti_zuo_biao_xi.html"> <i class="fa fa-check"></i> <b>15.9.</b> Vector3.forward、transform.forward与坐标系间的联系 </a> </li> <li class="chapter " data-level="15.10" data-path="Summary/gameobjectyu_component_de_guan_xi.html"> <a href="../Summary/gameobjectyu_component_de_guan_xi.html"> <i class="fa fa-check"></i> <b>15.10.</b> GameObject与Component的关系 </a> </li> <li class="chapter " data-level="15.11" > <span><b>15.11.</b> 顺序加载脚本</span> </li> <li class="chapter " data-level="15.12" > <span><b>15.12.</b> 2D射线</span> </li> <li class="chapter " data-level="15.13" > <span><b>15.13.</b> 动态创建地形</span> </li> <li class="chapter " data-level="15.14" data-path="Summary/Lerp.html"> <a href="../Summary/Lerp.html"> <i class="fa fa-check"></i> <b>15.14.</b> 插值与平滑 </a> </li> <li class="chapter " data-level="15.15" data-path="Summary/coordinate.html"> <a href="../Summary/coordinate.html"> <i class="fa fa-check"></i> <b>15.15.</b> 坐标系转化 </a> </li> </ul> </li> <li class="divider"></li> <li> <a href="https://www.gitbook.com" target="blank" class="gitbook-link"> 本书使用 GitBook 发布 </a> </li> </ul> </nav> </div> <div class="book-body"> <div class="body-inner"> <div class="book-header" role="navigation"> <!-- Actions Left --> <!-- Title --> <h1> <i class="fa fa-circle-o-notch fa-spin"></i> <a href="../" >Unity Source Book</a> </h1> </div> <div class="page-wrapper" tabindex="-1" role="main"> <div class="page-inner"> <section class="normal" id="section-"> <h1 id="transform">Transform</h1> </section> </div> </div> </div> <a href="../UnityClass/resources.html" class="navigation navigation-prev " aria-label="Previous page: Resources"><i class="fa fa-angle-left"></i></a> <a href="../UnityClass/translate.html" class="navigation navigation-next " aria-label="Next page: 移动"><i class="fa fa-angle-right"></i></a> </div> </div> <script src="../gitbook/app.js"></script> <script src="../gitbook/plugins/gitbook-plugin-maxiang/maxiang.js"></script> <script src="../gitbook/plugins/gitbook-plugin-comment/plugin.js"></script> <script src="../gitbook/plugins/gitbook-plugin-search/lunr.min.js"></script> <script src="../gitbook/plugins/gitbook-plugin-search/search.js"></script> <script src="../gitbook/plugins/gitbook-plugin-sharing/buttons.js"></script> <script src="../gitbook/plugins/gitbook-plugin-fontsettings/buttons.js"></script> <script src="../gitbook/plugins/gitbook-plugin-livereload/plugin.js"></script> <script> require(["gitbook"], function(gitbook) { var config = {"comment":{"highlightCommented":true},"highlight":{},"include-codeblock":{},"maxiang":{},"search":{"maxIndexSize":1000000},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"livereload":{}}; gitbook.start(config); }); </script> <!-- body:end --> </body> <!-- End of book Unity Source Book --> </html>
li-kang/unity-concise-course
UnityClass/transform.html
HTML
gpl-3.0
31,642
<?php include(__DIR__ . '/http_move.php'); include(__DIR__ . '/security_arguments.php'); // this is it
wooygcom/mapc.me
web/mapc-system/library/_library.php
PHP
gpl-3.0
104
/* * RenderRasterize_Shader.h * Created by Clemens Unterkofler on 1/20/09. * for Aleph One * * http://www.gnu.org/licenses/gpl.html */ #ifndef _RENDERRASTERIZE_SHADER__H #define _RENDERRASTERIZE_SHADER__H #include "cseries.h" #include "map.h" #include "RenderRasterize.h" #include "OGL_FBO.h" #include "OGL_Textures.h" #include "Rasterizer_Shader.h" #include <memory> class Blur; class RenderRasterize_Shader : public RenderRasterizerClass { std::unique_ptr<Blur> blur; Rasterizer_Shader_Class *RasPtr; int objectCount; world_distance objectY; float weaponFlare; float selfLuminosity; long_vector2d leftmost_clip, rightmost_clip; protected: virtual void render_node(sorted_node_data *node, bool SeeThruLiquids, RenderStep renderStep); virtual void store_endpoint(endpoint_data *endpoint, long_vector2d& p); virtual void render_node_floor_or_ceiling( clipping_window_data *window, polygon_data *polygon, horizontal_surface_data *surface, bool void_present, bool ceil, RenderStep renderStep); virtual void render_node_side( clipping_window_data *window, vertical_surface_data *surface, bool void_present, RenderStep renderStep); virtual void render_node_object(render_object_data *object, bool other_side_of_media, RenderStep renderStep); virtual void clip_to_window(clipping_window_data *win); virtual void _render_node_object_helper(render_object_data *object, RenderStep renderStep); public: RenderRasterize_Shader(); ~RenderRasterize_Shader(); virtual void setupGL(Rasterizer_Shader_Class& Rasterizer); virtual void render_tree(void); TextureManager setupWallTexture(const shape_descriptor& Texture, short transferMode, float pulsate, float wobble, float intensity, float offset, RenderStep renderStep); TextureManager setupSpriteTexture(const rectangle_definition& rect, short type, float offset, RenderStep renderStep); }; #endif
MaddTheSane/alephone
Source_Files/RenderMain/RenderRasterize_Shader.h
C
gpl-3.0
1,903
#include <QtGui> #include <QTcpSocket> #include "phonecall.h" #include "dcc.h" DCCDialog::DCCDialog(QWidget *parent) : QDialog(parent) { QStringList list; QVBoxLayout* mainLayout = new QVBoxLayout(this); table = new QTableWidget(this); table->setColumnCount(8); list << tr("Status") << tr("File") << tr("Size") << tr("Position") << "%" << "KB/s" << "ETA" << tr("Nick"); table->setHorizontalHeaderLabels(list); mainLayout->addWidget(table); closeButton = new QPushButton(tr("Save and Close")); connect(closeButton, SIGNAL(clicked()), this, SLOT(saveAndClose())); mainLayout->addWidget(closeButton); setLayout(mainLayout); setWindowTitle(tr("File Transfers")); call = 0; } DCCDialog::~DCCDialog() { } void DCCDialog::command(const QString &cmd) { //user:ip:DCC SEND <filename> <ip> <port> <filesize> //user:ip:DCC CHAT accept <ip> <audio port> <video port> //user:ip:DCC CHAT call <ip> <audio port> <video port> //qWarning()<<"cmd: "<<cmd; QStringList list = cmd.split(':'); QString user = list.at(0); QString ip = list.at(1); QStringList params = cmd.split(' '); //qWarning()<<"params "<<params; //qWarning()<<"list "<<list; if(params.size() < 6) return; if(params.at(1).contains("SEND")) { QMessageBox msgBox; QString text = QString("%1 wants to send you a file called %2").arg(user).arg(params.at(2)); msgBox.setText(text); msgBox.setInformativeText("Do you want to accept the file transfer?"); msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if(ret == QMessageBox::Save) { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::AnyFile); dialog.selectFile(params.at(2)); if(dialog.exec()) { QStringList files = dialog.selectedFiles(); //qWarning()<<"destination = "<<files.at(0); TransferData* data = new TransferData; data->user = user; data->status = "Waiting"; data->file = params.at(2); data->destination = new QFile(files.at(0)); data->size = params.at(5).toInt(); data->position = 0; data->complete = 0; data->rate = 0; data->eta = -1; data->comms = new QTcpSocket; int currentRow = table->rowCount(); //qWarning()<<"currentRow="<<currentRow; table->insertRow(currentRow); table->setItem(currentRow, 0, new QTableWidgetItem(data->status)); table->setItem(currentRow, 1, new QTableWidgetItem(data->file)); table->setItem(currentRow, 2, new QTableWidgetItem(QString("%1kB").arg(data->size/1024))); table->setItem(currentRow, 3, new QTableWidgetItem(QString("%1").arg(data->position))); table->setItem(currentRow, 4, new QTableWidgetItem(QString("%1\%").arg(data->complete))); table->setItem(currentRow, 5, new QTableWidgetItem(QString("%1Kb/s").arg(data->rate))); table->setItem(currentRow, 6, new QTableWidgetItem(QString("%1min").arg(data->eta))); table->setItem(currentRow, 7, new QTableWidgetItem(data->user)); connect(data->comms,SIGNAL(connected()),this,SLOT(startTransfer())); connect(data->comms,SIGNAL(readyRead()),this,SLOT(processReadyRead())); transfers.append(data); table->resizeColumnsToContents(); if(table->selectedItems().isEmpty()) { table->selectRow(0); // start transfer... } } } show(); } else if(params.at(1).contains("CHAT")) { //qWarning()<<"got a CHAT message"; if(params.at(2).contains("call")) { //qWarning()<<"got a CHAT call"; // someone has requested a call QMessageBox msgBox; QString text = QString("%1 wants to talk").arg(user); msgBox.setText(text); msgBox.setInformativeText("Do you want to accept the call?"); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if(ret == QMessageBox::Ok) { // send accept message and setup for incoming. QString msg = QString("PRIVMSG %1 :\001DCC CHAT accept %2 %3 %4\001\r\n").arg(user).arg(ip).arg(AUDIO_PORT).arg(0); PhoneCallDialog* incoming = new PhoneCallDialog(this,user,ip,false); incoming->show(); emit ircMsg(msg); } } else if(params.at(2).contains("accept")) { //qWarning()<<"got a CHAT accept"; // your request has been accepted, connect to other end. //qWarning()<<"I should be able to connect to "<<ip<<QString(" on port %1").arg(AUDIO_PORT); if(call) delete call; call = new PhoneCallDialog(this,user,ip,true); call->show(); call->connectToHost(); } } } void DCCDialog::startTransfer() { //qWarning()<<"TODO:startTransfer()"; } void DCCDialog::processReadyRead() { //qWarning()<<"TODO:processReadyRead()"; } void DCCDialog::saveAndClose() { close(); }
korbatit/qtchat
dcc.cpp
C++
gpl-3.0
5,563
package cn.com.jautoitx; import org.apache.commons.lang3.StringUtils; import com.sun.jna.platform.win32.WinDef.HWND; /** * Build window title base on Advanced Window Descriptions. * * @author zhengbo.wang */ public class TitleBuilder { /** * Build window title base on Advanced Window Descriptions. * * @param bys * Selectors to build advanced window title. * @return Returns advanced window title. */ public static String by(By... bys) { StringBuilder title = new StringBuilder(); title.append('['); String separator = ""; for (int i = 0; i < bys.length; i++) { title.append(separator); String strBy = bys[i].toAdvancedTitle(); if (!strBy.isEmpty()) { title.append(strBy); separator = "; "; } } title.append(']'); return title.toString(); } /** * Build window title base on window title. * * @param title * Window title. * @return Returns advanced window title. */ public static String byTitle(String title) { return by(By.title(title)); } /** * Build window title base on the internal window classname. * * @param className * The internal window classname. * @return Returns advanced window title. */ public static String byClassName(String className) { return by(By.className(className)); } /** * Build window title base on window title using a regular expression. * * @param regexpTitle * Window title using a regular expression. * @return Returns advanced window title. */ public static String byRegexpTitle(String regexpTitle) { return by(By.regexpTitle(regexpTitle)); } /** * Build window title base on window classname using a regular expression. * * @param regexpClassName * Window classname using a regular expression. * @return Returns advanced window title. */ public static String byRegexpClassName(String regexpClassName) { return by(By.regexpClassName(regexpClassName)); } /** * Build window title base on window used in a previous AutoIt command. * * @return Returns advanced window title. */ public static String byLastWindow() { return by(By.lastWindow()); } /** * Build window title base on currently active window. * * @return Returns advanced window title. */ public static String byActiveWindow() { return by(By.activeWindow()); } /** * Build window title base on the position and size of a window. All * parameters are optional. * * @param x * Optional, the X coordinate of the window. * @param y * Optional, the Y coordinate of the window. * @param width * Optional, the width of the window. * @param height * Optional, the height of the window. * @return Returns advanced window title. */ public static String byBounds(Integer x, Integer y, Integer width, Integer height) { return by(By.bounds(x, y, width, height)); } /** * Build window title base on the position of a window. All parameters are * optional. * * @param x * Optional, the X coordinate of the window. * @param y * Optional, the Y coordinate of the window. * @return Returns advanced window title. */ public static String byPosition(Integer x, Integer y) { return by(By.position(x, y)); } /** * Build window title base on the size of a window. All parameters are * optional. * * @param width * Optional, the width of the window. * @param height * Optional, the height of the window. * @return Returns advanced window title. */ public static String bySize(Integer width, Integer height) { return by(By.size(width, height)); } /** * Build window title base on the 1-based instance when all given properties * match. * * @param instance * The 1-based instance when all given properties match. * @return Returns advanced window title. */ public static String byInstance(int instance) { return by(By.instance(instance)); } /** * Build window title base on the handle address as returned by a method * like Win.getHandle. * * @param handle * The handle address as returned by a method like Win.getHandle. * @return Returns advanced window title. */ public static String byHandle(String handle) { return by(By.handle(handle)); } /** * Build window title base on the handle address as returned by a method * like Win.getHandle_. * * @param hWnd * The handle address as returned by a method like * Win.getHandle_. * @return Returns advanced window title. */ public static String byHandle(HWND hWnd) { return by(By.handle(hWnd)); } /** * Selector to build advanced window title. * * @author zhengbo.wang */ public static abstract class By { private final String property; private final String value; public By(final String property) { this.property = property; this.value = null; } public By(final String property, final String value) { this.property = property; this.value = StringUtils.defaultString(value); } /** * @param title * Window title. * @return a By which locates window by the window title. */ public static By title(String title) { return new ByTitle(title); } /** * @param className * The internal window classname. * @return a By which locates window by the internal window classname. */ public static By className(String className) { return new ByClass(className); } /** * @param regexpTitle * Window title using a regular expression. * @return a By which locates window by the window title using a regular * expression. */ public static By regexpTitle(String regexpTitle) { return new ByRegexpTitle(regexpTitle); } /** * @param regexpClassName * Window classname using a regular expression. * @return a By which locates window by the window classname using a * regular expression. */ public static By regexpClassName(String regexpClassName) { return new ByRegexpClass(regexpClassName); } /** * @return a By which locates window used in a previous AutoIt command. */ public static By lastWindow() { return new ByLast(); } /** * @return a By which locates currently active window. */ public static By activeWindow() { return new ByActive(); } /** * All parameters are optional. * * @param x * Optional, the X coordinate of the window. * @param y * Optional, the Y coordinate of the window. * @param width * Optional, the width of the window. * @param height * Optional, the height of the window. * @return a By which locates window by the position and size of a * window. */ public static By bounds(Integer x, Integer y, Integer width, Integer height) { return new ByBounds(x, y, width, height); } /** * All parameters are optional. * * @param x * Optional, the X coordinate of the window. * @param y * Optional, the Y coordinate of the window. * @return a By which locates window by the position of a window. */ public static By position(Integer x, Integer y) { return bounds(x, y, null, null); } /** * All parameters are optional. * * @param width * Optional, the width of the window. * @param height * Optional, the height of the window. * @return a By which locates window by the size of a window. */ public static By size(Integer width, Integer height) { return bounds(null, null, width, height); } /** * @param instance * The 1-based instance when all given properties match. * @return a By which locates window by the instance when all given * properties match. */ public static By instance(int instance) { return new ByInstance(instance); } /** * @param handle * The handle address as returned by a method like * Win.getHandle. * @return a By which locates window by the handle address as returned * by a method like Win.getHandle. */ public static By handle(String handle) { return new ByHandle(handle); } /** * @param hWnd * The handle address as returned by a method like * Win.getHandle_. * @return a By which locates window by the handle address as returned * by a method like Win.getHandle. */ public static By handle(HWND hWnd) { return new ByHandle(hWnd); } public String toAdvancedTitle() { StringBuilder advancedTitle = new StringBuilder(); advancedTitle.append(property); if (value != null) { advancedTitle.append(':'); for (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); advancedTitle.append(ch); // Note: if a Value must contain a ";" it must be doubled. if (ch == ';') { advancedTitle.append(';'); } } } return advancedTitle.toString(); } @Override public String toString() { return "By." + property + ": " + value; } } /** * Window title. * * @author zhengbo.wang */ public static class ByTitle extends By { public ByTitle(String title) { super("TITLE", title); } } /** * The internal window classname. * * @author zhengbo.wang */ public static class ByClass extends By { public ByClass(String clazz) { super("CLASS", clazz); } } /** * Window title using a regular expression. * * @author zhengbo.wang */ public static class ByRegexpTitle extends By { public ByRegexpTitle(String clazz) { super("REGEXPTITLE", clazz); } } /** * Window classname using a regular expression. * * @author zhengbo.wang */ public static class ByRegexpClass extends By { public ByRegexpClass(String regexpClass) { super("REGEXPCLASS", regexpClass); } } /** * Last window used in a previous AutoIt command. * * @author zhengbo.wang */ public static class ByLast extends By { public ByLast() { super("LAST"); } } /** * Currently active window. * * @author zhengbo.wang */ public static class ByActive extends By { public ByActive() { super("ACTIVE"); } } /** * The position and size of a window. * * @author zhengbo.wang */ public static class ByBounds extends By { private final Integer x; private final Integer y; private final Integer width; private final Integer height; public ByBounds(Integer x, Integer y, Integer width, Integer height) { super("POSITION AND SIZE", String.format("%s \\ %s \\ %s \\ %s", String.valueOf(x), String.valueOf(y), String.valueOf(width), String.valueOf(height))); this.x = x; this.y = y; this.width = width; this.height = height; } @Override public String toAdvancedTitle() { // see http://www.autoitscript.com/forum/topic/90848-x-y-w-h/ StringBuilder advancedTitle = new StringBuilder(); if (x != null) { advancedTitle.append("X:").append(x); } if (y != null) { if (!advancedTitle.toString().isEmpty()) { advancedTitle.append("\\"); } advancedTitle.append("Y:").append(y); } if (width != null) { if (!advancedTitle.toString().isEmpty()) { advancedTitle.append("\\"); } advancedTitle.append("W:").append(width); } if (height != null) { if (!advancedTitle.toString().isEmpty()) { advancedTitle.append("\\"); } advancedTitle.append("H:").append(height); } return advancedTitle.toString(); } } /** * The 1-based instance when all given properties match. * * @author zhengbo.wang */ public static class ByInstance extends By { public ByInstance(int instance) { super("INSTANCE", String.valueOf(instance)); } } /** * The handle address as returned by a method like Win.getHandle or * Win.getHandle_. * * @author zhengbo.wang */ public static class ByHandle extends By { public ByHandle(String handle) { super("HANDLE", handle); } public ByHandle(HWND hWnd) { this(AutoItX.hwndToHandle(hWnd)); } } }
Pheelbert/twitchplayclient
src/cn/com/jautoitx/TitleBuilder.java
Java
gpl-3.0
12,238
\begin{lstlisting}[caption=RoR installation] # install ruby sudo apt-get install ruby ruby-dev # install sqllite sudo apt-get install sqlite3 libsqlite3-dev # install postgresql sudo apt-get install postgresql # install java script sudo apt-get install nodejs # # download and cd to gems directory # sudo ruby setup.rb # or #gem update --system # optional sudo gem install execjs sudo gem install jquery-rails sudo gem install multi_json sudo gem install jquery-turbolinks sudo gem install sprockets sudo gem install sprockets sudo gem install rails sudo gem install activemodel sudo gem install actionmailer sudo gem install coffee-rails sudo gem install coffee-script sudo gem install json_pure sudo gem install activerecord-deprecated_finders sudo gem install arel sudo gem install sqlite3 \end{lstlisting}
michaelthe/web_chatting
doc/Chapters/appendix/RoRinstallation.tex
TeX
gpl-3.0
941
package me.vadik.instaclimb.view.adapter; import android.content.Context; import android.databinding.ViewDataBinding; import android.view.LayoutInflater; import android.view.ViewGroup; import me.vadik.instaclimb.databinding.RowLayoutRouteBinding; import me.vadik.instaclimb.databinding.UserCardBinding; import me.vadik.instaclimb.model.Route; import me.vadik.instaclimb.model.User; import me.vadik.instaclimb.view.adapter.abstr.AbstractRecyclerViewWithHeaderAdapter; import me.vadik.instaclimb.viewmodel.RouteItemViewModel; import me.vadik.instaclimb.viewmodel.UserViewModel; /** * User: vadik * Date: 4/13/16 */ public class UserRecyclerViewAdapter extends AbstractRecyclerViewWithHeaderAdapter<User, Route> { public UserRecyclerViewAdapter(Context context, User user) { super(context, user); } @Override protected ViewDataBinding onCreateHeader(LayoutInflater inflater, ViewGroup parent) { return UserCardBinding.inflate(inflater, parent, false); } @Override protected ViewDataBinding onCreateItem(LayoutInflater inflater, ViewGroup parent) { return RowLayoutRouteBinding.inflate(inflater, parent, false); } @Override protected void onBindHeader(ViewDataBinding binding, User user) { ((UserCardBinding) binding).setUser(new UserViewModel(mContext, user)); } @Override protected void onBindItem(ViewDataBinding binding, Route route) { ((RowLayoutRouteBinding) binding).setRoute(new RouteItemViewModel(mContext, route)); } }
sirekanyan/instaclimb
app/src/main/java/me/vadik/instaclimb/view/adapter/UserRecyclerViewAdapter.java
Java
gpl-3.0
1,531
Ext.define('Omni.view.sizes.Explorer', { extend: 'Buildit.ux.explorer.Panel', alias: 'widget.omni-sizes-Explorer', initComponent: function() { var me = this; // EXPLORER INIT (Start) =============================================================== Ext.apply(this, { allowFind: true, store: Ext.create('Omni.store.Size'), contextMenuConfig: { xtype: 'omni-app-ExplorerContextMenu' }, newForms: [{ xtype: 'omni-sizes-Form', windowConfig: {} }], inspectorConfig: { xtype: 'omni-sizes-Inspector' } }); // EXPLORER INIT (End) // LABELS (Start) ====================================================================== Ext.applyIf(this, { size_nbrLabel: Omni.i18n.model.Size.size_nbr, size_typeLabel: Omni.i18n.model.Size.size_type, displayLabel: Omni.i18n.model.Size.display, concatenated_nameLabel: Omni.i18n.model.Size.concatenated_name, dimension_1Label: Omni.i18n.model.Size.dimension_1, dimension_2Label: Omni.i18n.model.Size.dimension_2, is_enabledLabel: Omni.i18n.model.Size.is_enabled }); // LABELS (End) // COLUMNS (Start) ===================================================================== Ext.apply(this, { columns: [{ header: this.displayLabel, dataIndex: 'display', flex: 1, sortable: false }, { header: this.concatenated_nameLabel, dataIndex: 'concatenated_name', flex: 1, sortable: false }, { header: this.dimension_1Label, dataIndex: 'dimension_1', flex: 1, sortable: false }, { header: this.dimension_2Label, dataIndex: 'dimension_2', flex: 1, sortable: false }, { header: this.size_typeLabel, dataIndex: 'size_type', flex: 1, sortable: false, renderer: Buildit.util.Format.lookupRenderer('SIZE_TYPE') }, { header: this.size_nbrLabel, dataIndex: 'size_nbr', flex: 1, sortable: false }, { header: this.is_enabledLabel, dataIndex: 'is_enabled', flex: 1, sortable: false }, ] }); // COLUMNS (End) // TITLES (Start) ====================================================================== Ext.apply(this, { title: 'Size', subtitle: 'All Product Sizes that are valid in the system' }); // TITLES (End) this.callParent(); } });
tunacasserole/omni
app/assets/javascripts/omni/view/sizes/Explorer.js
JavaScript
gpl-3.0
2,541
# Copyright (C) 2012 Statoil ASA, Norway. # # The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ERT 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 at <http://www.gnu.org/licenses/gpl.html> # for more details. from ert.cwrap import BaseCClass, CWrapper from ert.enkf import ENKF_LIB, EnkfFs, NodeId from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW from ert.enkf.enums import ErtImplType class EnkfNode(BaseCClass): def __init__(self, config_node, private=False): assert isinstance(config_node, EnkfConfigNode) if private: c_pointer = EnkfNode.cNamespace().alloc_private(config_node) else: c_pointer = EnkfNode.cNamespace().alloc(config_node) super(EnkfNode, self).__init__(c_pointer, config_node, True) def valuePointer(self): return EnkfNode.cNamespace().value_ptr(self) def asGenData(self): """ @rtype: GenData """ impl_type = EnkfNode.cNamespace().get_impl_type(self) assert impl_type == ErtImplType.GEN_DATA return GenData.createCReference(self.valuePointer(), self) def asGenKw(self): """ @rtype: GenKw """ impl_type = EnkfNode.cNamespace().get_impl_type(self) assert impl_type == ErtImplType.GEN_KW return GenKw.createCReference(self.valuePointer(), self) def asCustomKW(self): """ @rtype: CustomKW """ impl_type = EnkfNode.cNamespace().get_impl_type(self) assert impl_type == ErtImplType.CUSTOM_KW return CustomKW.createCReference(self.valuePointer(), self) def tryLoad(self, fs, node_id): """ @type fs: EnkfFS @type node_id: NodeId @rtype: bool """ assert isinstance(fs, EnkfFs) assert isinstance(node_id, NodeId) return EnkfNode.cNamespace().try_load(self, fs, node_id) def name(self): return EnkfNode.cNamespace().get_name(self) def load(self, fs, node_id): if not self.tryLoad(fs, node_id): raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step)) def save(self, fs, node_id): assert isinstance(fs, EnkfFs) assert isinstance(node_id, NodeId) EnkfNode.cNamespace().store(self, fs, True, node_id) def free(self): EnkfNode.cNamespace().free(self) cwrapper = CWrapper(ENKF_LIB) cwrapper.registerObjectType("enkf_node", EnkfNode) EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)") EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)") EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)") EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)") EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)") EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)") EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)") EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
iLoop2/ResInsight
ThirdParty/Ert/devel/python/python/ert/enkf/data/enkf_node.py
Python
gpl-3.0
3,730
package task_config import ( "github.com/sonm-io/core/proto" "github.com/sonm-io/core/util/config" ) func LoadConfig(path string) (*sonm.TaskSpec, error) { // Manual renaming from snake_case to lowercase fields here to be able to // load them directly in the protobuf. cfg := &sonm.TaskSpec{} if err := config.LoadWith(cfg, path, config.SnakeToLower); err != nil { return nil, err } if err := cfg.Validate(); err != nil { return nil, err } return cfg, nil }
sonm-io/core
cmd/cli/task_config/config.go
GO
gpl-3.0
476
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Web; using System.Xml; using System.Xml.XPath; using System.IO; using LyricsFetcher; using iTunesLib; using WMPLib; using WMFSDKWrapper; public class TestSong : Song { public TestSong(string title, string artist, string album, string genre) : base(title, artist, album, genre) { } public override string FullPath { get { return String.Empty; } } public override void Commit() { } public override void GetLyrics() { } } namespace LyricsFetcher.CommandLine { class Program { static void TestWMPLyrics() { WindowsMediaPlayer wmpPlayer = new WindowsMediaPlayer(); IWMPPlaylist playlist = wmpPlayer.mediaCollection.getByAttribute("MediaType", "audio"); IWMPMedia media = playlist.get_Item(100); Console.WriteLine(media.name); Console.WriteLine(media.getItemInfo("Lyrics")); //media.setItemInfo("Lyrics", ""); } static void TestSecondTry() { // Is it actually worthwhile doing the second or subsequent attempt? ITunesLibrary lib = new ITunesLibrary(); //lib.MaxSongsToFetch = 1000; lib.LoadSongs(); lib.WaitLoad(); List<Song> songs = lib.Songs.FindAll( delegate(Song s) { LyricsStatus status = s.LyricsStatus; return (status == LyricsStatus.Untried || status == LyricsStatus.Failed || status == LyricsStatus.Success); } ); ILyricsSource source2 = new LyricsSourceLyricsPlugin(); ILyricsSource source1 = new LyricsSourceLyrdb(); ILyricsSource source3 = new LyricsSourceLyricsFly(); Stopwatch sw1 = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); Stopwatch sw3 = new Stopwatch(); int failures = 0; int success1 = 0; int success2 = 0; int success3 = 0; foreach (Song song in songs) { sw1.Start(); string lyrics = source1.GetLyrics(song); sw1.Stop(); if (lyrics == string.Empty) { sw2.Start(); lyrics = source2.GetLyrics(song); sw2.Stop(); if (lyrics == string.Empty) { sw3.Start(); lyrics = source3.GetLyrics(song); sw3.Stop(); if (lyrics == string.Empty) failures++; else success3++; } else success2++; } else success1++; } Console.WriteLine("1st try: successes: {0} ({1}%), time: {2} ({3} each)", success1, (success1 * 100 / songs.Count), sw1.Elapsed, sw1.ElapsedMilliseconds / songs.Count); Console.WriteLine("2st try: successes: {0} ({1}%), time: {2} ({3} each)", success2, (success2 * 100 / songs.Count), sw2.Elapsed, sw2.ElapsedMilliseconds / (songs.Count - success1)); Console.WriteLine("3st try: successes: {0} ({1}%), time: {2} ({3} each)", success3, (success3 * 100 / songs.Count), sw3.Elapsed, sw3.ElapsedMilliseconds / (songs.Count - success1 - success2)); Console.WriteLine("failures: {0} ({1}%)", failures, (failures * 100 / songs.Count)); } static void TestSources() { ITunesLibrary lib = new ITunesLibrary(); lib.MaxSongsToFetch = 150; lib.LoadSongs(); lib.WaitLoad(); List<Song> songs = lib.Songs.FindAll( delegate(Song s) { LyricsStatus status = s.LyricsStatus; return (status == LyricsStatus.Untried || status == LyricsStatus.Failed || status == LyricsStatus.Success); } ); songs = songs.GetRange(0, 10); //TestOneSource(songs, new LyricsSourceLyricWiki()); //TestOneSource(songs, new LyricsSourceLyricWikiHtml()); TestOneSource(songs, new LyricsSourceLyricsPlugin()); TestOneSource(songs, new LyricsSourceLyrdb()); TestOneSource(songs, new LyricsSourceLyricsFly()); } private static void TestOneSource(List<Song> songs, ILyricsSource source) { Console.WriteLine("Testing {0}...", source.Name); int successes = 0; int failures = 0; Stopwatch sw = new Stopwatch(); sw.Start(); foreach (Song song in songs) { if (source.GetLyrics(song) == string.Empty) failures++; else successes++; } sw.Stop(); Console.WriteLine("Successes: {0}, failure: {1}, time: {2} seconds ({3} per song)", successes, failures, sw.Elapsed, sw.ElapsedMilliseconds / songs.Count); } static void lfm_StatusEvent(object sender, LyricsFetchStatusEventArgs e) { System.Diagnostics.Debug.WriteLine(e.Status); } static void TestMetaDataEditor() { string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.wma"; using (MetaDataEditor mde = new MetaDataEditor(file)) { //mde.SetFieldValue("WM/Lyrics", "These are some more of my favourite things"); //mde.SetFieldValue("WM/Genre", "80's rock"); Console.WriteLine(mde.GetFieldValue("WM/Year")); Console.WriteLine(mde.GetFieldValue("WM/Lyrics")); Console.WriteLine(mde.GetFieldValue("Genre")); Console.WriteLine(mde.GetFieldValue("WM/Publisher")); Console.WriteLine(mde.GetFieldValue("unknown")); } } static void TestMetaDataEditor2() { WindowsMediaPlayer wmpPlayer = new WindowsMediaPlayer(); IWMPPlaylist playlist = wmpPlayer.mediaCollection.getByAttribute("MediaType", "audio"); IWMPMedia media = playlist.get_Item(100); Console.WriteLine(media.name); Console.WriteLine(media.getItemInfo("WM/Genre")); Console.WriteLine("-"); using (MetaDataEditor mde = new MetaDataEditor(media.sourceURL)) { //mde.SetFieldValue("WM/Lyrics", "MORE LIKE THIS things"); //mde.SetFieldValue("WM/Genre", "80's rock"); Console.WriteLine(mde.GetFieldValue("WM/Year")); Console.WriteLine(mde.GetFieldValue("WM/Lyrics")); Console.WriteLine(mde.GetFieldValue("WM/Genre")); Console.WriteLine(mde.GetFieldValue("WM/Publisher")); Console.WriteLine(mde.GetFieldValue("unknown")); } } static void TestLyricsSource() { //ILyricsSource strategy = new LyricsSourceLyricWiki(); //ILyricsSource strategy = new LyricsSourceLyricWikiHtml(); //ILyricsSource strategy = new LyricsSourceLyrdb(); //ILyricsSource strategy = new LyricsSourceLyricsPlugin(); ILyricsSource strategy = new LyricsSourceLyricsFly(); //TestSong song = new TestSong("Lips don't hie", "Shakira", "Music of the Sun", ""); //TestSong song = new TestSong("Hips don't lie", "Shakira", "Music of the Sun", ""); //TestSong song = new TestSong("Pon de replay", "Rihanna", "Music of the Sun", ""); //TestSong song = new TestSong("I Love to Move in Here", "Moby", "Last Night", ""); TestSong song = new TestSong("Year 3000", "Busted", "", ""); Console.WriteLine(song); Console.WriteLine(strategy.GetLyrics(song)); } static void TestMetaDataLookup() { string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3"; //string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\Alanis Morissette\So-Called Chaos\01 Eight Easy Steps.mp3"; //string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\Unknown Artist\Unknown Album\16 Pump UP the jam.mp3"; //string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\Ziqo\Unknown Album\01 Vamos Embora.mp3"; MetaDataLookup req = new MetaDataLookup(); Console.WriteLine("looking up '{0}'...", file); req.Lookup(file); Console.WriteLine("puid={0}", req.MetaData.Puid); Console.WriteLine("title={0}", req.MetaData.Title); Console.WriteLine("artist={0}", req.MetaData.Artist); Console.WriteLine("genre={0}", req.MetaData.Genre); } static void TestManyMetaDataLookup() { ITunesLibrary lib = new ITunesLibrary(); lib.MaxSongsToFetch = 50; lib.LoadSongs(); lib.WaitLoad(); Stopwatch sw = new Stopwatch(); sw.Start(); try { foreach (Song song in lib.Songs) { MetaDataLookup req = new MetaDataLookup(); //MetaDataLookupOld req = new MetaDataLookupOld(); req.Lookup(song); if (req.Status == MetaDataStatus.Success) { if (song.Title == req.MetaData.Title && song.Artist == req.MetaData.Artist) System.Diagnostics.Debug.WriteLine(String.Format("same: {0}", song)); else System.Diagnostics.Debug.WriteLine(String.Format("different: {0}. title={1}, artist={2}", song, req.MetaData.Title, req.MetaData.Artist)); } else { System.Diagnostics.Debug.WriteLine(String.Format("failed: {0}", song)); } } } finally { sw.Stop(); System.Diagnostics.Debug.WriteLine(String.Format("Tried {0} song in {1} ({2} secs per song)", lib.Songs.Count, sw.Elapsed, (sw.ElapsedMilliseconds / lib.Songs.Count) / 1000)); } } static void Main(string[] args) { Console.WriteLine("start"); TestSources(); //TestManyMetaDataLookup(); //Console.WriteLine("start"); //string value = GetFieldByName(@"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3", "WM/Lyrics"); //Console.WriteLine(value); //Console.WriteLine(GetFieldByName(@"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3", "WM/Genre")); //Console.WriteLine(GetFieldByName(@"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3", "WM/Publisher")); //Console.ReadKey(); //------------------------------------------------------------ //System.Diagnostics.Debug.WriteLine("start"); //Stopwatch watch = new Stopwatch(); //SongLibrary library = new WmpLibrary(); ////SongLibrary library = new ITunesLibrary(); ////library.MaxSongsToFetch = 1000; //watch.Start(); //library.LoadSongs(); //library.WaitLoad(); //watch.Stop(); //System.Diagnostics.Debug.WriteLine(String.Format("Loaded {0} songs in {1}ms", // library.Songs.Count, watch.ElapsedMilliseconds)); //------------------------------------------------------------ //LyricsFetchManager lfm = new LyricsFetchManager(); //lfm.AutoUpdateLyrics = true; //lfm.StatusEvent += new EventHandler<FetchStatusEventArgs>(lfm_StatusEvent); //lfm.Sources.Add(new LyricsSourceLyrdb()); //lfm.Sources.Add(new LyricsSourceLyricWiki()); //System.Diagnostics.Debug.WriteLine("--------------"); //Song song = new TestSong("seconds", "u2", "Music of the Sun", ""); //lfm.Queue(song); //lfm.Start(); //lfm.WaitUntilFinished(); //System.Diagnostics.Debug.WriteLine(song); //System.Diagnostics.Debug.Write(song.Lyrics); //System.Diagnostics.Debug.WriteLine("========"); //------------------------------------------------------------ //System.Diagnostics.Debug.WriteLine(Wmp.Instance.Player.versionInfo); //SongLibrary library = new WmpLibrary(); //library.MaxSongsToFetch = 100; //foreach (Song x in library.Songs) // System.Diagnostics.Debug.WriteLine(x); //------------------------------------------------------------ //IWMPPlaylist playlist = Wmp.Instance.AllTracks; //System.Diagnostics.Debug.WriteLine(Wmp.Instance.Player.versionInfo); //for (int i = 0; i < playlist.count; i++) { // IWMPMedia media = playlist.get_Item(i); // System.Diagnostics.Debug.WriteLine(media.name); //} Console.WriteLine("done"); Console.ReadKey(); } } }
mattshall/lyricsfetcher
CommandLine/Program.cs
C#
gpl-3.0
14,295
#!/bin/sh # AwesomeTTS text-to-speech add-on for Anki # Copyright (C) 2010-Present Anki AwesomeTTS Development Team # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. addon_id="301952613" set -e if [ -z "$1" ] then echo 'Please specify your Anki addons directory.' 1>&2 echo 1>&2 echo " Usage: $0 <target>" 1>&2 echo " e.g.: $0 ~/.local/share/Anki2/addons21" 1>&2 exit 1 fi target=${1%/} case $target in */addons21) ;; *) echo 'Expected target path to end in "/addons21".' 1>&2 exit 1 esac case $target in /*) ;; *) target=$PWD/$target esac if [ ! -d "$target" ] then echo "$target is not a directory." 1>&2 exit 1 fi mkdir -p "$target/$addon_id" if [ -f "$target/$addon_id/awesometts/config.db" ] then echo 'Saving configuration...' saveConf=$(mktemp /tmp/config.XXXXXXXXXX.db) cp -v "$target/$addon_id/awesometts/config.db" "$saveConf" fi if [ -d "$target/$addon_id/awesometts/.cache" ] then echo 'Saving cache...' saveCache=$(mktemp -d /tmp/anki_cacheXXXXXXXXXX) cp -rv "$target/$addon_id/awesometts/.cache/*" "$saveCache/" fi echo 'Cleaning up...' rm -fv "$target/$addon_id/__init__.py"* rm -rfv "$target/$addon_id/awesometts" oldPwd=$PWD cd "$(dirname "$0")/.." || exit 1 echo 'Linking...' ln -sv "$PWD/$addon_id/__init__.py" "$target" ln -sv "$PWD/$addon_id/awesometts" "$target" cd "$oldPwd" || exit 1 if [ -n "$saveConf" ] then echo 'Restoring configuration...' mv -v "$saveConf" "$target/$addon_id/awesometts/config.db" fi if [ -n "$saveCache" ] then echo 'Restoring cache...' mv -rv "$saveConf/*" "$target/$addon_id/awesometts/.cache/" fi
AwesomeTTS/awesometts-anki-addon
tools/symlink.sh
Shell
gpl-3.0
2,285
#pragma once #ifndef HPTT_PARAM_PARAMETER_TRANS_H_ #define HPTT_PARAM_PARAMETER_TRANS_H_ #include <array> #include <utility> #include <unordered_map> #include <unordered_set> #include <algorithm> #include <hptt/types.h> #include <hptt/tensor.h> #include <hptt/arch/compat.h> #include <hptt/util/util_trans.h> #include <hptt/kernels/kernel_trans.h> namespace hptt { template <typename FloatType, TensorUInt ORDER> class TensorMergedWrapper : public TensorWrapper<FloatType, ORDER> { public: TensorMergedWrapper() = delete; TensorMergedWrapper(const TensorWrapper<FloatType, ORDER> &tensor, const std::unordered_set<TensorUInt> &merge_set); HPTT_INL FloatType &operator[](const TensorIdx * RESTRICT indices); HPTT_INL const FloatType &operator[]( const TensorIdx * RESTRICT indices) const; HPTT_INL FloatType &operator[](TensorIdx **indices); HPTT_INL const FloatType &operator[](const TensorIdx **indices) const; private: TensorUInt begin_order_idx_, merged_order_; TensorUInt merge_idx_(const std::unordered_set<TensorUInt> &merge_set); }; template <typename TensorType, bool UPDATE_OUT> struct ParamTrans { // Type alias and constant values using Float = typename TensorType::Float; using Deduced = DeducedFloatType<Float>; using KernelPack = KernelPackTrans<Float, UPDATE_OUT>; static constexpr auto ORDER = TensorType::TENSOR_ORDER; ParamTrans(const TensorType &input_tensor, TensorType &output_tensor, const std::array<TensorUInt, ORDER> &perm, const Deduced alpha, const Deduced beta); HPTT_INL bool is_common_leading() const; HPTT_INL void set_coef(const Deduced alpha, const Deduced beta); HPTT_INL const KernelPack &get_kernel() const; void set_lin_wrapper_loop(const TensorUInt size_kn_inld, const TensorUInt size_kn_outld); void set_sca_wrapper_loop(const TensorUInt size_kn_in_inld, const TensorUInt size_kn_in_outld, const TensorUInt size_kn_out_inld, const TensorUInt size_kn_out_outld); void reset_data(const Float *data_in, Float *data_out); private: TensorUInt merge_idx_(const TensorType &input_tensor, const TensorType &output_tensor, const std::array<TensorUInt, ORDER> &perm); // They need to be initialized before merging std::unordered_set<TensorUInt> input_merge_set_, output_merge_set_; KernelPackTrans<Float, UPDATE_OUT> kn_; public: std::array<TensorUInt, ORDER> perm; Deduced alpha, beta; TensorIdx stride_in_inld, stride_in_outld, stride_out_inld, stride_out_outld; TensorUInt begin_order_idx; const TensorUInt merged_order; // Put the merged tensors here, they must be initialized after merging TensorMergedWrapper<Float, ORDER> input_tensor, output_tensor; }; /* * Import implementation */ #include "parameter_trans.tcc" } #endif // HPTT_PARAM_PARAMETER_TRANS_H_
tongsucn/hptt
inc/hptt/param/parameter_trans.h
C
gpl-3.0
2,854
package tencentcloud.constant; /** * @author fanwh * @version v1.0 * @decription * @create on 2017/11/10 16:09 */ public class RegionConstants { /** * 北京 */ public static final String PEKING = "ap-beijing"; /** * 上海 */ public static final String SHANGHAI = "ap-shanghai"; /** * 香港 */ public static final String HONGKONG = "ap-hongkong"; /** * 多伦多 */ public static final String TORONTO = "na-toronto"; /** * 硅谷 */ public static final String SILICON_VALLEY = "na-siliconvalley"; /** * 新加坡 */ public static final String SINGAPORE = "ap-singapore"; /** * 上海金融 */ public static final String SHANGHAI_FSI = "ap-shanghai-fsi"; /** * 广州open专区 */ public static final String GUANGZHOU_OPEN = "ap-guangzhou-open"; /** * 深圳金融 */ public static final String SHENZHEN_FSI = "ap-shenzhen-fsi"; }
ghforlang/Working
Test/src/main/java/tencentcloud/constant/RegionConstants.java
Java
gpl-3.0
1,002
/* The following code was generated by JFlex 1.6.1 */ package com.jim_project.interprete.parser.previo; import com.jim_project.interprete.parser.AnalizadorLexico; /** * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.6.1 * from the specification file <tt>C:/Users/alber_000/Documents/NetBeansProjects/tfg-int-rpretes/jim/src/main/java/com/jim_project/interprete/parser/previo/lexico.l</tt> */ public class PrevioLex extends AnalizadorLexico { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\3\1\2\1\51\1\3\1\1\22\0\1\3\1\16\1\0"+ "\1\5\1\0\1\20\2\0\3\20\1\15\1\20\1\14\1\0\1\20"+ "\1\10\11\7\2\0\1\13\1\17\3\0\3\6\1\50\1\42\1\24"+ "\1\30\1\40\1\23\2\4\1\41\1\4\1\47\1\31\1\44\3\4"+ "\1\32\2\4\1\37\1\11\1\12\1\11\1\20\1\0\1\20\3\0"+ "\3\6\1\46\1\36\1\22\1\25\1\34\1\21\2\4\1\35\1\4"+ "\1\45\1\26\1\43\3\4\1\27\2\4\1\33\1\11\1\12\1\11"+ "\12\0\1\51\u1fa2\0\1\51\1\51\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\uffff\0\udfe6\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\1\0\1\1\2\2\1\1\1\2\1\3\2\4\2\5"+ "\1\1\2\6\1\1\1\6\6\1\1\3\2\1\1\3"+ "\1\7\1\3\1\5\1\10\1\11\1\12\1\0\1\13"+ "\10\7\1\14\4\7\1\15\2\7\1\16\1\7\1\17"+ "\1\7\1\20"; private static int [] zzUnpackAction() { int [] result = new int[55]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\52\0\124\0\52\0\176\0\250\0\322\0\374"+ "\0\52\0\u0126\0\176\0\u0150\0\u017a\0\u01a4\0\u01ce\0\52"+ "\0\u01f8\0\u0222\0\u024c\0\u0276\0\u02a0\0\u02ca\0\u02f4\0\u031e"+ "\0\u0348\0\u0372\0\176\0\u039c\0\u03c6\0\52\0\52\0\52"+ "\0\u03f0\0\176\0\u041a\0\u0444\0\u046e\0\u0498\0\u04c2\0\u04ec"+ "\0\u0516\0\u0540\0\52\0\u056a\0\u0594\0\u05be\0\u05e8\0\176"+ "\0\u0612\0\u063c\0\176\0\u0666\0\176\0\u0690\0\176"; private static int [] zzUnpackRowMap() { int [] result = new int[55]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = "\1\2\1\3\2\4\1\5\1\6\1\7\1\10\1\11"+ "\1\12\1\13\1\14\1\15\1\16\1\17\1\2\1\20"+ "\1\21\1\5\1\22\1\5\1\23\2\5\1\24\2\5"+ "\1\25\1\5\1\26\1\27\1\30\1\5\1\31\1\32"+ "\3\5\1\7\1\5\1\7\55\0\1\4\53\0\1\33"+ "\1\0\1\33\2\0\2\33\6\0\30\33\1\0\1\6"+ "\1\3\1\4\47\6\4\0\1\33\1\0\1\33\1\34"+ "\1\0\2\33\6\0\30\33\10\0\2\10\45\0\1\33"+ "\1\0\1\33\1\35\1\0\2\33\6\0\30\33\15\0"+ "\1\36\51\0\1\37\52\0\1\40\53\0\1\41\36\0"+ "\1\33\1\0\1\33\2\0\2\33\6\0\1\33\1\42"+ "\26\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+ "\3\33\1\42\24\33\5\0\1\33\1\0\1\33\2\0"+ "\2\33\6\0\5\33\1\43\22\33\5\0\1\33\1\0"+ "\1\33\2\0\2\33\6\0\10\33\1\44\17\33\5\0"+ "\1\33\1\0\1\33\2\0\2\33\6\0\13\33\1\45"+ "\14\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+ "\5\33\1\46\22\33\5\0\1\33\1\0\1\33\1\34"+ "\1\0\2\33\6\0\24\33\1\47\3\33\5\0\1\33"+ "\1\0\1\33\2\0\2\33\6\0\17\33\1\50\10\33"+ "\5\0\1\33\1\0\1\33\2\0\2\33\6\0\10\33"+ "\1\51\17\33\5\0\1\33\1\0\1\33\1\34\1\0"+ "\2\33\6\0\26\33\1\52\1\33\10\0\2\34\50\0"+ "\2\35\44\0\1\41\4\0\1\53\45\0\1\33\1\0"+ "\1\33\2\0\2\33\6\0\6\33\1\54\21\33\5\0"+ "\1\33\1\0\1\33\2\0\2\33\6\0\11\33\1\55"+ "\16\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+ "\1\56\27\33\5\0\1\33\1\0\1\33\2\0\2\33"+ "\6\0\5\33\1\57\22\33\5\0\1\33\1\0\1\33"+ "\2\0\2\33\6\0\25\33\1\60\2\33\5\0\1\33"+ "\1\0\1\33\2\0\2\33\6\0\2\33\1\61\25\33"+ "\5\0\1\33\1\0\1\33\2\0\2\33\6\0\10\33"+ "\1\62\17\33\5\0\1\33\1\0\1\33\2\0\2\33"+ "\6\0\27\33\1\60\5\0\1\33\1\0\1\33\2\0"+ "\2\33\6\0\5\33\1\63\22\33\5\0\1\33\1\0"+ "\1\33\2\0\2\33\6\0\10\33\1\63\17\33\5\0"+ "\1\33\1\0\1\33\2\0\2\33\6\0\14\33\1\64"+ "\13\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+ "\22\33\1\65\5\33\5\0\1\33\1\0\1\33\2\0"+ "\2\33\6\0\20\33\1\66\7\33\5\0\1\33\1\0"+ "\1\33\2\0\2\33\6\0\23\33\1\65\4\33\5\0"+ "\1\33\1\0\1\33\2\0\2\33\6\0\15\33\1\67"+ "\12\33\5\0\1\33\1\0\1\33\2\0\2\33\6\0"+ "\21\33\1\67\6\33\1\0"; private static int [] zzUnpackTrans() { int [] result = new int[1722]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; } private static int zzUnpackTrans(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); value--; do result[j++] = value; while (--count > 0); } return j; } /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unknown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\1\0\1\11\1\1\1\11\4\1\1\11\6\1\1\11"+ "\15\1\3\11\1\0\11\1\1\11\14\1"; private static int [] zzUnpackAttribute() { int [] result = new int[55]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /** * The number of occupied positions in zzBuffer beyond zzEndRead. * When a lead/high surrogate has been read from the input stream * into the final zzBuffer position, this will have a value of 1; * otherwise, it will have a value of 0. */ private int zzFinalHighSurrogate = 0; /* user code: */ private PrevioParser yyparser; /** * Constructor de clase. * @param r Referencia al lector de entrada. * @param p Referencia al analizador sintáctico. */ public PrevioLex(java.io.Reader r, PrevioParser p) { this(r); yyparser = p; } /** * Creates a new scanner * * @param in the java.io.Reader to read input from. */ public PrevioLex(java.io.Reader in) { this.zzReader = in; } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x110000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 184) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { zzEndRead += zzFinalHighSurrogate; zzFinalHighSurrogate = 0; System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length - zzFinalHighSurrogate) { /* if not: blow it up */ char newBuffer[] = new char[zzBuffer.length*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; zzEndRead += zzFinalHighSurrogate; zzFinalHighSurrogate = 0; } /* fill the buffer with new input */ int requested = zzBuffer.length - zzEndRead; int numRead = zzReader.read(zzBuffer, zzEndRead, requested); /* not supposed to occur according to specification of java.io.Reader */ if (numRead == 0) { throw new java.io.IOException("Reader returned 0 characters. See JFlex examples for workaround."); } if (numRead > 0) { zzEndRead += numRead; /* If numRead == requested, we might have requested to few chars to encode a full Unicode character. We assume that a Reader would otherwise never return half characters. */ if (numRead == requested) { if (Character.isHighSurrogate(zzBuffer[zzEndRead - 1])) { --zzEndRead; zzFinalHighSurrogate = 1; } } /* potentially more input available */ return false; } /* numRead < 0 ==> end of stream */ return true; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * <b>cannot</b> be reused (internal buffer is discarded and lost). * Lexical state is set to <tt>ZZ_INITIAL</tt>. * * Internal scan buffer is resized down to its initial length, if it has grown. * * @param reader the new input stream */ public final void yyreset(java.io.Reader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEOFDone = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; zzFinalHighSurrogate = 0; yyline = yychar = yycolumn = 0; zzLexicalState = YYINITIAL; if (zzBuffer.length > ZZ_BUFFERSIZE) zzBuffer = new char[ZZ_BUFFERSIZE]; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Contains user EOF-code, which will be executed exactly once, * when the end of file is reached */ private void zzDoEOF() throws java.io.IOException { if (!zzEOFDone) { zzEOFDone = true; yyclose(); } } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public int yylex() throws java.io.IOException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; // set up zzAction for empty match case: int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; } zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) { zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL); zzCurrentPosL += Character.charCount(zzInput); } else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = Character.codePointAt(zzBufferL, zzCurrentPosL, zzEndReadL); zzCurrentPosL += Character.charCount(zzInput); } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; zzDoEOF(); { return 0; } } else { switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 1: { yyparser.programa().error().deCaracterNoReconocido(yytext()); } case 17: break; case 2: { } case 18: break; case 3: { yyparser.yylval = new PrevioParserVal(yytext()); return PrevioParser.ETIQUETA; } case 19: break; case 4: { yyparser.yylval = new PrevioParserVal(yytext()); return PrevioParser.NUMERO; } case 20: break; case 5: { yyparser.yylval = new PrevioParserVal(yytext()); return PrevioParser.VARIABLE; } case 21: break; case 6: { return yycharat(0); } case 22: break; case 7: { yyparser.yylval = new PrevioParserVal(yytext()); return PrevioParser.IDMACRO; } case 23: break; case 8: { return PrevioParser.FLECHA; } case 24: break; case 9: { return PrevioParser.DECREMENTO; } case 25: break; case 10: { return PrevioParser.INCREMENTO; } case 26: break; case 11: { return PrevioParser.IF; } case 27: break; case 12: { return PrevioParser.DISTINTO; } case 28: break; case 13: { return PrevioParser.END; } case 29: break; case 14: { return PrevioParser.GOTO; } case 30: break; case 15: { return PrevioParser.LOOP; } case 31: break; case 16: { return PrevioParser.WHILE; } case 32: break; default: zzScanError(ZZ_NO_MATCH); } } } } }
alberh/JIM
jim/src/main/java/com/jim_project/interprete/parser/previo/PrevioLex.java
Java
gpl-3.0
20,877
#include "cdi.h" #include "mds_reader.h" #include "common.h" SessionInfo mds_ses; TocInfo mds_toc; DiscType mds_Disctype=CdRom; struct file_TrackInfo { u32 FAD; u32 Offset; u32 SectorSize; }; file_TrackInfo mds_Track[101]; FILE* fp_mdf=0; u8 mds_SecTemp[5120]; u32 mds_TrackCount; u32 mds_ReadSSect(u8* p_out,u32 sector,u32 secsz) { for (u32 i=0;i<mds_TrackCount;i++) { if (mds_Track[i+1].FAD>sector) { u32 fad_off=sector-mds_Track[i].FAD; fseek(fp_mdf,mds_Track[i].Offset+fad_off*mds_Track[i].SectorSize,SEEK_SET); fread(mds_SecTemp,mds_Track[i].SectorSize,1,fp_mdf); ConvertSector(mds_SecTemp,p_out,mds_Track[i].SectorSize,secsz,sector); return mds_Track[i].SectorSize; } } return 0; } void FASTCALL mds_DriveReadSector(u8 * buff,u32 StartSector,u32 SectorCount,u32 secsz) { // printf("MDS/NRG->Read : Sector %d , size %d , mode %d \n",StartSector,SectorCount,secsz); while(SectorCount--) { mds_ReadSSect(buff,StartSector,secsz); buff+=secsz; StartSector++; } } void mds_CreateToc() { //clear structs to 0xFF :) memset(mds_Track,0xFF,sizeof(mds_Track)); memset(&mds_ses,0xFF,sizeof(mds_ses)); memset(&mds_toc,0xFF,sizeof(mds_toc)); printf("\n--GD toc info start--\n"); int track=0; bool CD_DA=false; bool CD_M1=false; bool CD_M2=false; strack* last_track=&sessions[nsessions-1].tracks[sessions[nsessions-1].ntracks-1]; mds_ses.SessionCount=nsessions; mds_ses.SessionsEndFAD=last_track->sector+last_track->sectors+150; mds_toc.LeadOut.FAD=last_track->sector+last_track->sectors+150; mds_toc.LeadOut.Addr=0; mds_toc.LeadOut.Control=0; mds_toc.LeadOut.Session=0; printf("Last Sector : %d\n",mds_ses.SessionsEndFAD); printf("Session count : %d\n",mds_ses.SessionCount); mds_toc.FistTrack=1; for (int s=0;s<nsessions;s++) { printf("Session %d:\n",s); session* ses=&sessions[s]; printf(" Track Count: %d\n",ses->ntracks); for (int t=0;t< ses->ntracks ;t++) { strack* c_track=&ses->tracks[t]; //pre gap if (t==0) { mds_ses.SessionFAD[s]=c_track->sector+150; mds_ses.SessionStart[s]=track+1; printf(" Session start FAD: %d\n",mds_ses.SessionFAD[s]); } //verify(cdi_track->dwIndexCount==2); printf(" track %d:\n",t); printf(" Type : %d\n",c_track->mode); if (c_track->mode>=2) CD_M2=true; if (c_track->mode==1) CD_M1=true; if (c_track->mode==0) CD_DA=true; //verify((c_track->mode==236) || (c_track->mode==169)) mds_toc.tracks[track].Addr=0;//hmm is that ok ? mds_toc.tracks[track].Session=s; mds_toc.tracks[track].Control=c_track->mode>0?4:0;//mode 1 , 2 , else are data , 0 is audio :) mds_toc.tracks[track].FAD=c_track->sector+150; mds_Track[track].FAD=mds_toc.tracks[track].FAD; mds_Track[track].SectorSize=c_track->sectorsize; mds_Track[track].Offset=(u32)c_track->offset; printf(" Start FAD : %d\n",mds_Track[track].FAD); printf(" SectorSize : %d\n",mds_Track[track].SectorSize); printf(" File Offset : %d\n",mds_Track[track].Offset); //main track data track++; } } //normal CDrom : mode 1 tracks .All sectors on the track are mode 1.Mode 2 was defined on the same book , but is it ever used? if yes , how can i detect //cd XA ??? //CD Extra : session 1 is audio , session 2 is data //cd XA : mode 2 tracks.Form 1/2 are selected per sector.It allows mixing of mode1/mode2 tracks ? //CDDA : audio tracks only <- thats simple =P /* if ((CD_M1==true) && (CD_DA==false) && (CD_M2==false)) mds_Disctype = CdRom; else if (CD_M2) mds_Disctype = CdRom_XA; else if (CD_DA && CD_M1) mds_Disctype = CdRom_Extra; else mds_Disctype=CdRom;//hmm? */ if (nsessions==1 && (CD_M1 | CD_M2)) mds_Disctype = CdRom; //hack so that non selfboot stuff works on utopia else { if ((CD_M1==true) && (CD_DA==false) && (CD_M2==false)) mds_Disctype = CdRom; //is that even correct ? what if its multysessions ? ehh ? what then ??? else if (CD_M2) mds_Disctype = CdRom_XA; // XA XA ! its mode 2 wtf ? else if (CD_DA && CD_M1) mds_Disctype = CdRom_XA; //data + audio , duno wtf as@!#$ lets make it _XA since it seems to boot else if (CD_DA && !CD_M1 && !CD_M2) mds_Disctype = CdDA; //audio else mds_Disctype=CdRom_XA;//and hope for the best } /* bool data = CD_M1 | CD_M2; bool audio=CD_DA; if (data && audio) mds_Disctype = CdRom_XA; //Extra/CdRom won't boot , so meh else if (data) mds_Disctype = CdRom; //only data else mds_Disctype = CdDA; //only audio */ mds_toc.LastTrack=track; mds_TrackCount=track; printf("--GD toc info end--\n\n"); } bool mds_init(wchar* file) { wchar fn[512]=L""; bool rv=false; if (rv==false && parse_mds(file,false)) { bool found=false; if (wcslen(file)>4) { wcscpy(&fn[0],file); size_t len=wcslen(fn); wcscpy(&fn[len-4],L".mdf"); fp_mdf=_tfopen(fn,L"rb"); found=fp_mdf!=0; } if (!found) { if (GetFile(fn,L"mds images (*.mds) \0*.mdf\0\0")==1) { fp_mdf=_tfopen(fn,L"rb"); found=true; } } if (!found) return false; rv=true; } if (rv==false && parse_nrg(file,false)) { rv=true; fp_mdf=_tfopen(file,L"rb"); } if (rv==false) return false; /* for(int j=0;j<nsessions;j++) for(int i=0;i<sessions[j].ntracks;i++) { printf("Session %d Track %d mode %d/%d sector %d count %d offset %I64d\n", sessions[j].session_, sessions[j].tracks[i].track, sessions[j].tracks[i].mode, sessions[j].tracks[i].sectorsize, sessions[j].tracks[i].sector, sessions[j].tracks[i].sectors, sessions[j].tracks[i].offset); }*/ mds_CreateToc(); return true; } void mds_term() { if (fp_mdf) fclose(fp_mdf); fp_mdf=0; } u32 FASTCALL mds_DriveGetDiscType() { return mds_Disctype; } void mds_DriveGetTocInfo(TocInfo* toc,DiskArea area) { verify(area==SingleDensity); memcpy(toc,&mds_toc,sizeof(TocInfo)); } void mds_GetSessionsInfo(SessionInfo* sessions) { memcpy(sessions,&mds_ses,sizeof(SessionInfo)); } struct MDSDiskWrapper : Disc { MDSDiskWrapper() { } bool TryOpen(wchar* file) { if (mds_init(file)) { //printf("Session count %d:\n",nsessions); //s32 tr_c = 1; for (s32 s=0;s<nsessions;++s) { //printf("Session %d:\n",s); session* ses=&mds_sessions[s]; //printf(" Track Count: %d\n",ses->ntracks); Track tr; for (s32 t=0;t< ses->ntracks;++t) { strack* c_track=&ses->tracks[t]; if (t==0) { Session ts; ts.FirstTrack = t + 1;//(tr_c++); ts.StartFAD = c_track->sector+150; sessions.push_back(ts); //printf(" Session start FAD: %d\n",mds_ses.SessionFAD[s]); } tr.ADDR = 0; tr.StartFAD = c_track->sector+150; tr.EndFAD = 0; tr.CTRL = c_track->mode>0?4:0; //printf("SECTOR SIZE %u\n",c_track->sectorsize); tr.file = new RawTrackFile(fp_mdf,(u32)c_track->offset,tr.StartFAD,c_track->sectorsize,false); tracks.push_back(tr); } } type=mds_Disctype; LeadOut.ADDR=0; LeadOut.CTRL=0; LeadOut.StartFAD=549300; EndFAD=549300; return true; } return false; } ~MDSDiskWrapper() { mds_term(); } }; Disc* mds_parse(wchar* fname) { MDSDiskWrapper* dsk = new MDSDiskWrapper(); if (!dsk) { return 0; } if (dsk->TryOpen(fname)) { wprintf(L"\n\n Loaded %s\n\n",fname); } else { wprintf(L"\n\n Unable to load %s \n\n",fname); delete dsk; return 0; } return dsk; }
workhorsy/nulldc-linux
nulldc/plugins/ImgReader/mds.cpp
C++
gpl-3.0
7,400
<!DOCTYPE html> <html> <head> <title></title> <!--Import Google Icon Font--> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <!--Import jQuery before materialize.js--> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="js/materialize.min.js"></script></head> <body> <a class="btn btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a> <a class="waves-effect waves-teal btn-flat">Button</a> </body> </html>
jinoantony/Trax-it_V_1.0.7
traxit/hi.html
HTML
gpl-3.0
919
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Ksana Humanity Platform</title> <!--<script src="../node_webkit/jslib/ksanajslib.min.js"></script>//--> <script src="../node_webkit/jslib/require.js" data-main="../node_webkit/jslib/ksanajslib"></script> <link rel="stylesheet" href="../node_webkit/css/bootstrap.css"></link> <link rel="stylesheet" href="css/tags.css"></link> </head> <body style="overflow-x:hidden;"> <div class="mainview"> <div class="rows"> <div class="col-5" data-aura-widget="controller-widget"></div> <div class="col-7" data-aura-widget="tagset-widget"></div> </div> <div class="col-12" data-id="markable1" data-aura-widget="markable-widget"></div> </div> </body> </html>
ksanaforge/khp_aura
index.html
HTML
gpl-3.0
743
package visGrid.diagram.edit.parts; import java.io.File; import java.util.Collections; import java.util.List; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.transaction.RunnableWithResult; import org.eclipse.gef.AccessibleEditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Request; import org.eclipse.gef.requests.DirectEditRequest; import org.eclipse.gef.tools.DirectEditManager; import org.eclipse.gmf.runtime.common.ui.services.parser.IParser; import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus; import org.eclipse.gmf.runtime.common.ui.services.parser.ParserEditStatus; import org.eclipse.gmf.runtime.common.ui.services.parser.ParserOptions; import org.eclipse.gmf.runtime.diagram.ui.editparts.CompartmentEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.ITextAwareEditPart; import org.eclipse.gmf.runtime.diagram.ui.editpolicies.LabelDirectEditPolicy; import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry; import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants; import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager; import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter; import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; import org.eclipse.gmf.runtime.notation.FontStyle; import org.eclipse.gmf.runtime.notation.NotationPackage; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.viewers.ICellEditorValidator; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; /** * @generated */ public class Series_reactorNameEditPart extends CompartmentEditPart implements ITextAwareEditPart { /** * @generated */ public static final int VISUAL_ID = 5072; /** * @generated */ private DirectEditManager manager; /** * @generated */ private IParser parser; /** * @generated */ private List<?> parserElements; /** * @generated */ private String defaultText; /** * @generated */ public Series_reactorNameEditPart(View view) { super(view); } /** * @generated */ protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy( EditPolicy.SELECTION_FEEDBACK_ROLE, new visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy()); installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new LabelDirectEditPolicy()); installEditPolicy( EditPolicy.PRIMARY_DRAG_ROLE, new visGrid.diagram.edit.parts.GridEditPart.NodeLabelDragPolicy()); } /** * @generated */ protected String getLabelTextHelper(IFigure figure) { if (figure instanceof WrappingLabel) { return ((WrappingLabel) figure).getText(); } else { return ((Label) figure).getText(); } } /** * @generated */ protected void setLabelTextHelper(IFigure figure, String text) { if (figure instanceof WrappingLabel) { ((WrappingLabel) figure).setText(text); } else { ((Label) figure).setText(text); } } /** * @generated */ protected Image getLabelIconHelper(IFigure figure) { if (figure instanceof WrappingLabel) { return ((WrappingLabel) figure).getIcon(); } else { return ((Label) figure).getIcon(); } } /** * @generated */ protected void setLabelIconHelper(IFigure figure, Image icon) { if (figure instanceof WrappingLabel) { ((WrappingLabel) figure).setIcon(icon); } else { ((Label) figure).setIcon(icon); } } /** * @generated */ public void setLabel(WrappingLabel figure) { unregisterVisuals(); setFigure(figure); defaultText = getLabelTextHelper(figure); registerVisuals(); refreshVisuals(); } /** * @generated */ @SuppressWarnings("rawtypes") protected List getModelChildren() { return Collections.EMPTY_LIST; } /** * @generated */ public IGraphicalEditPart getChildBySemanticHint(String semanticHint) { return null; } /** * @generated */ protected EObject getParserElement() { return resolveSemanticElement(); } /** * @generated */ protected Image getLabelIcon() { EObject parserElement = getParserElement(); if (parserElement == null) { return null; } return visGrid.diagram.providers.VisGridElementTypes .getImage(parserElement.eClass()); } /** * @generated */ protected String getLabelText() { String text = null; EObject parserElement = getParserElement(); if (parserElement != null && getParser() != null) { text = getParser().getPrintString( new EObjectAdapter(parserElement), getParserOptions().intValue()); } if (text == null || text.length() == 0) { text = defaultText; } return text; } /** * @generated */ public void setLabelText(String text) { setLabelTextHelper(getFigure(), text); Object pdEditPolicy = getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (pdEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) { ((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) pdEditPolicy) .refreshFeedback(); } Object sfEditPolicy = getEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE); if (sfEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) { ((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) sfEditPolicy) .refreshFeedback(); } } /** * @generated */ public String getEditText() { if (getParserElement() == null || getParser() == null) { return ""; //$NON-NLS-1$ } return getParser().getEditString( new EObjectAdapter(getParserElement()), getParserOptions().intValue()); } /** * @generated */ protected boolean isEditable() { return getParser() != null; } /** * @generated */ public ICellEditorValidator getEditTextValidator() { return new ICellEditorValidator() { public String isValid(final Object value) { if (value instanceof String) { final EObject element = getParserElement(); final IParser parser = getParser(); try { IParserEditStatus valid = (IParserEditStatus) getEditingDomain() .runExclusive( new RunnableWithResult.Impl<IParserEditStatus>() { public void run() { setResult(parser .isValidEditString( new EObjectAdapter( element), (String) value)); } }); return valid.getCode() == ParserEditStatus.EDITABLE ? null : valid.getMessage(); } catch (InterruptedException ie) { ie.printStackTrace(); } } // shouldn't get here return null; } }; } /** * @generated */ public IContentAssistProcessor getCompletionProcessor() { if (getParserElement() == null || getParser() == null) { return null; } return getParser().getCompletionProcessor( new EObjectAdapter(getParserElement())); } /** * @generated */ public ParserOptions getParserOptions() { return ParserOptions.NONE; } /** * @generated */ public IParser getParser() { if (parser == null) { parser = visGrid.diagram.providers.VisGridParserProvider .getParser( visGrid.diagram.providers.VisGridElementTypes.Series_reactor_2032, getParserElement(), visGrid.diagram.part.VisGridVisualIDRegistry .getType(visGrid.diagram.edit.parts.Series_reactorNameEditPart.VISUAL_ID)); } return parser; } /** * @generated */ protected DirectEditManager getManager() { if (manager == null) { setManager(new TextDirectEditManager(this, TextDirectEditManager.getTextCellEditorClass(this), visGrid.diagram.edit.parts.VisGridEditPartFactory .getTextCellEditorLocator(this))); } return manager; } /** * @generated */ protected void setManager(DirectEditManager manager) { this.manager = manager; } /** * @generated */ protected void performDirectEdit() { getManager().show(); } /** * @generated */ protected void performDirectEdit(Point eventLocation) { if (getManager().getClass() == TextDirectEditManager.class) { ((TextDirectEditManager) getManager()).show(eventLocation .getSWTPoint()); } } /** * @generated */ private void performDirectEdit(char initialCharacter) { if (getManager() instanceof TextDirectEditManager) { ((TextDirectEditManager) getManager()).show(initialCharacter); } else { performDirectEdit(); } } /** * @generated */ protected void performDirectEditRequest(Request request) { final Request theRequest = request; try { getEditingDomain().runExclusive(new Runnable() { public void run() { if (isActive() && isEditable()) { if (theRequest .getExtendedData() .get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR) instanceof Character) { Character initialChar = (Character) theRequest .getExtendedData() .get(RequestConstants.REQ_DIRECTEDIT_EXTENDEDDATA_INITIAL_CHAR); performDirectEdit(initialChar.charValue()); } else if ((theRequest instanceof DirectEditRequest) && (getEditText().equals(getLabelText()))) { DirectEditRequest editRequest = (DirectEditRequest) theRequest; performDirectEdit(editRequest.getLocation()); } else { performDirectEdit(); } } } }); } catch (InterruptedException e) { e.printStackTrace(); } } /** * @generated */ protected void refreshVisuals() { super.refreshVisuals(); refreshLabel(); refreshFont(); refreshFontColor(); refreshUnderline(); refreshStrikeThrough(); refreshBounds(); } /** * @generated */ protected void refreshLabel() { setLabelTextHelper(getFigure(), getLabelText()); setLabelIconHelper(getFigure(), getLabelIcon()); Object pdEditPolicy = getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE); if (pdEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) { ((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) pdEditPolicy) .refreshFeedback(); } Object sfEditPolicy = getEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE); if (sfEditPolicy instanceof visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) { ((visGrid.diagram.edit.policies.VisGridTextSelectionEditPolicy) sfEditPolicy) .refreshFeedback(); } } /** * @generated */ protected void refreshUnderline() { FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle( NotationPackage.eINSTANCE.getFontStyle()); if (style != null && getFigure() instanceof WrappingLabel) { ((WrappingLabel) getFigure()).setTextUnderline(style.isUnderline()); } } /** * @generated */ protected void refreshStrikeThrough() { FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle( NotationPackage.eINSTANCE.getFontStyle()); if (style != null && getFigure() instanceof WrappingLabel) { ((WrappingLabel) getFigure()).setTextStrikeThrough(style .isStrikeThrough()); } } /** * @generated */ protected void refreshFont() { FontStyle style = (FontStyle) getFontStyleOwnerView().getStyle( NotationPackage.eINSTANCE.getFontStyle()); if (style != null) { FontData fontData = new FontData(style.getFontName(), style.getFontHeight(), (style.isBold() ? SWT.BOLD : SWT.NORMAL) | (style.isItalic() ? SWT.ITALIC : SWT.NORMAL)); setFont(fontData); } } /** * @generated */ protected void setFontColor(Color color) { getFigure().setForegroundColor(color); } /** * @generated */ protected void addSemanticListeners() { if (getParser() instanceof ISemanticParser) { EObject element = resolveSemanticElement(); parserElements = ((ISemanticParser) getParser()) .getSemanticElementsBeingParsed(element); for (int i = 0; i < parserElements.size(); i++) { addListenerFilter( "SemanticModel" + i, this, (EObject) parserElements.get(i)); //$NON-NLS-1$ } } else { super.addSemanticListeners(); } } /** * @generated */ protected void removeSemanticListeners() { if (parserElements != null) { for (int i = 0; i < parserElements.size(); i++) { removeListenerFilter("SemanticModel" + i); //$NON-NLS-1$ } } else { super.removeSemanticListeners(); } } /** * @generated */ protected AccessibleEditPart getAccessibleEditPart() { if (accessibleEP == null) { accessibleEP = new AccessibleGraphicalEditPart() { public void getName(AccessibleEvent e) { e.result = getLabelTextHelper(getFigure()); } }; } return accessibleEP; } /** * @generated */ private View getFontStyleOwnerView() { return getPrimaryView(); } /** * @generated */ protected void addNotationalListeners() { super.addNotationalListeners(); addListenerFilter("PrimaryView", this, getPrimaryView()); //$NON-NLS-1$ } /** * @generated */ protected void removeNotationalListeners() { super.removeNotationalListeners(); removeListenerFilter("PrimaryView"); //$NON-NLS-1$ } /** * @generated */ protected void refreshBounds() { int width = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE .getSize_Width())).intValue(); int height = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE .getSize_Height())).intValue(); Dimension size = new Dimension(width, height); int x = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE .getLocation_X())).intValue(); int y = ((Integer) getStructuralFeatureValue(NotationPackage.eINSTANCE .getLocation_Y())).intValue(); Point loc = new Point(x, y); ((GraphicalEditPart) getParent()).setLayoutConstraint(this, getFigure(), new Rectangle(loc, size)); } /** * @generated */ protected void handleNotificationEvent(Notification event) { Object feature = event.getFeature(); if (NotationPackage.eINSTANCE.getSize_Width().equals(feature) || NotationPackage.eINSTANCE.getSize_Height().equals(feature) || NotationPackage.eINSTANCE.getLocation_X().equals(feature) || NotationPackage.eINSTANCE.getLocation_Y().equals(feature)) { refreshBounds(); } if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) { Integer c = (Integer) event.getNewValue(); setFontColor(DiagramColorRegistry.getInstance().getColor(c)); } else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals( feature)) { refreshUnderline(); } else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough() .equals(feature)) { refreshStrikeThrough(); } else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals( feature) || NotationPackage.eINSTANCE.getFontStyle_FontName().equals( feature) || NotationPackage.eINSTANCE.getFontStyle_Bold() .equals(feature) || NotationPackage.eINSTANCE.getFontStyle_Italic().equals( feature)) { refreshFont(); } else { if (getParser() != null && getParser().isAffectingEvent(event, getParserOptions().intValue())) { refreshLabel(); } if (getParser() instanceof ISemanticParser) { ISemanticParser modelParser = (ISemanticParser) getParser(); if (modelParser.areSemanticElementsAffected(null, event)) { removeSemanticListeners(); if (resolveSemanticElement() != null) { addSemanticListeners(); } refreshLabel(); } } } super.handleNotificationEvent(event); } /** * @generated */ protected IFigure createFigure() { // Parent should assign one using setLabel() method return null; } }
mikesligo/visGrid
ie.tcd.gmf.visGrid.diagram/src/visGrid/diagram/edit/parts/Series_reactorNameEditPart.java
Java
gpl-3.0
16,066
#include "mainwindow.h" #include <exception> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { //setWindowFlags(Qt::CustomizeWindowHint); menuBar()->close(); setStyleSheet("QPushButton{" "background-color:gray;" "color: white;" "width:55px;" "height:55px;" "font-size: 15px;" "border-radius: 10px;" "border: 2px groove gray;" "border-style: outset;}" "QPushButton:hover{" "background-color:white;" "color: black;}" "QPushButton:pressed,QPushButton:disabled{" "color: white;" "background-color:rgb(0, 0, 0);" "border-style: inset; }"); CentralWidget=new QWidget(this); setCentralWidget(CentralWidget); setWindowTitle(tr("Calculator")); buttonsLayout = new QGridLayout(); /* * 根据BUTTONS表添加,设置按钮 */ for(int i=0; i<BUTTONS.size(); ++i) { QVector<string> row = BUTTONS.at(i); //一行按钮 for(int j=0; j<row.size(); ++j) { const string &symbol = row.at(j); //按钮上显示的字符 if(!(symbol.empty())) { PushButton *pushButton = new PushButton(QString::fromStdString(symbol)); buttons.push_back(pushButton); //保存至按钮数组 connect(pushButton,&PushButton::clicked,this,&MainWindow::setInputText); buttonsLayout->addWidget(pushButton, i, j); } } } /* * 功能键 */ functionKeyButtonClear=new QPushButton(QString::fromStdString(CLEAR)); functionKeyButtonBackspace=new QPushButton(QString::fromStdString(BACKSPACE)); functionKeyButtonAns=new QPushButton(QString::fromStdString(ANS)); functionKeyButtonShift=new QPushButton(QString::fromStdString(SHIFT)); equalButton = new QPushButton(QString::fromStdString(EQUAL)); connect(functionKeyButtonBackspace,&QPushButton::clicked,this,&MainWindow::onBackspaceClicked); connect(functionKeyButtonClear,&QPushButton::clicked,this,&MainWindow::onClearClicked); connect(functionKeyButtonAns,&QPushButton::clicked,this,&MainWindow::onAnsClicked); connect(functionKeyButtonShift,&QPushButton::clicked,this,&MainWindow::onShiftClicked); connect(equalButton, &QPushButton::clicked, this, &MainWindow::onEqualClicked); buttonsLayout->addWidget(functionKeyButtonBackspace, 1, 0); buttonsLayout->addWidget(functionKeyButtonClear, 1, 1); buttonsLayout->addWidget(functionKeyButtonAns, 1, 2); buttonsLayout->addWidget(functionKeyButtonShift, 0, 4); //将等号添加至最后一行最后两格位置 buttonsLayout->addWidget(equalButton, BUTTONS.size(), BUTTONS.at(BUTTONS.size()-1).size()-2, 1, 2); MainLayout=new QGridLayout(CentralWidget); //设置表达式输入框 inputText=new QLineEdit("0"); inputText->setAlignment(Qt::AlignRight); inputText->setReadOnly(true); inputText->setStyleSheet("QLineEdit{height: 50px;" "border-style: plain;" "border-radius: 10px;" "font-size: 30px}"); //设置等于符号 equalLabel = new QLabel("="); equalLabel->setStyleSheet("width:55px;" "height:55px;" "font-size: 30px;"); //设置结果显示框 resultText = new QLineEdit("0"); resultText->setReadOnly(true); resultText->setStyleSheet("QLineEdit{height: 50px;" "border-style: plain;" "border-radius: 10px;" "font-size: 30px}"); MainLayout->addWidget(inputText, 0, 0, 1, 5); MainLayout->addWidget(equalLabel, 1, 1); MainLayout->addWidget(resultText, 1, 2, 1, 3); MainLayout->addLayout(buttonsLayout, 2, 0, 7, 5); MainLayout->setSizeConstraint(QLayout::SetFixedSize); setFixedSize(MainLayout->sizeHint()); } MainWindow::~MainWindow() { } QString MainWindow::cal(QString s) { QString temp; expression = new Expression(transformStdExpression(s)); try { temp=QString::fromStdString(expression->getResult()); }catch(runtime_error e){ QMessageBox messagebox(QMessageBox::Warning,"错误",QString::fromStdString(e.what())); messagebox.exec(); temp = "Error"; } calcFinished = true; delete expression; return temp; } string MainWindow::transformStdExpression(QString expression) { expression = expression.replace("×", "*").replace("÷", "/").replace("√", "#").replace("°", "`"); return expression.toStdString(); } void MainWindow::setInputText(PushButton *pushButton) { QString symbol = pushButton->text(); /* * 未计算完成,还在输入中,将输入的字符直接添加至表达式输入框文本后 */ if(calcFinished==false) { inputText->setText(inputText->text()+pushButton->text()); } /* * 已经计算完成,准备开始下一次计算 * 根据输入的内容,若为数字/括号/前置运算符/可省略第一个操作数的中置运算符,则直接将输入显示在输入框中 */ else { Metacharacter m = METACHARACTERS.at(transformStdExpression(symbol)); if(m.type == 0 || m.type == 2 || (m.type==1 && (m.position == 1 || m.e == "#" || m.e == "-"))) { //如果输入的是小数点,则在其前面添加小数点 if(symbol == ".") { inputText->setText(QString("0.")); } else { inputText->setText(pushButton->text()); } } else if(m.type == 1) { inputText->setText(Ans + pushButton->text()); } historySize.clear(); //清空上次输入的历史记录 calcFinished=false; //表示正在输入过程中 } historySize.push(pushButton->text().size()); //记录输入的操作词大小 } void MainWindow::onEqualClicked() { QString temp; temp=cal(inputText->text()); if(temp=="Error") //如果计算出错 { resultText->setText(tr("Error")); Ans = "0"; return; } /* * 由于返回值为double转换的QString,字符串小数位会有一串0,需要去除,并在小数位全为0时去除小数点 */ while(temp.right(1)=="0") temp=temp.left(temp.size()-1); if(temp.right(1)==".") temp=temp.left(temp.size()-1); resultText->setText(temp); /* * 如果计算结果为负数,为Ans加上括号便于下次计算使用 */ if(temp.at(0) == '-') Ans=QString("%1%2%3").arg("(").arg(temp).arg(")"); else Ans = temp; } void MainWindow::onClearClicked() { inputText->setText("0"); historySize.clear(); calcFinished=true; } void MainWindow::onAnsClicked() { if(inputText->text()=="0"||calcFinished==true) { inputText->setText(Ans); calcFinished=false; } else inputText->setText(inputText->text()+Ans); int length = Ans.size(); while(length--) historySize.push(1); } void MainWindow::onShiftClicked() { /* * 根据shift按下状态转换sin,cos,tan和lg四个按钮 */ if(isShifting) { isShifting = false; for(int i=0; i<4; ++i) { buttons[i]->setText(QString::fromStdString(BUTTONS.at(0).at(i))); } functionKeyButtonShift->setStyleSheet("QPushButton{background-color:gray;" "font-size: 15px;" "border-style: outset;}" "QPushButton:hover{" "background-color:white;" "color: black;}" "QPushButton:pressed{" "background-color:rgb(0, 0, 0);" "border-style: inset;}"); } else { isShifting = true; for(int i=0; i<4; ++i) { buttons[i]->setText(QString::fromStdString(SHIFT_TABLE[buttons[i]->text().toStdString()])); } functionKeyButtonShift->setStyleSheet("QPushButton:pressed{background-color:gray;" "border-style: outset;}" "QPushButton:hover{" "background-color:white;" "color: black;}" "QPushButton{" "font-size: 40px;" "font-style: bold;" "background-color:rgb(0, 0, 0);" "border-style: inset;}"); } } void MainWindow::onBackspaceClicked() { QString result=inputText->text(); calcFinished = false; //计算完成时若按下删除键,重新将计算完成标记置为正在输入中 if(result.size()==1) //输入框只剩一个字符 { historySize.clear(); inputText->setText("0"); calcFinished = true; } else { int length = historySize.empty() ? 1:historySize.pop(); //兼容手动输入字符情况 inputText->setText(result.left(result.size()-length)); } }
Zix777/Complex-mathematical-expressions
Calculator/mainwindow.cpp
C++
gpl-3.0
10,051
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Thu Sep 20 14:23:56 GMT 2018 */ package uk.ac.sanger.artemis; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.junit.AfterClass; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; import static org.evosuite.shaded.org.mockito.Mockito.*; @EvoSuiteClassExclude public class EntryChangeEvent_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "uk.ac.sanger.artemis.EntryChangeEvent"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); try { initMocksToAvoidTimeoutsInTheTests(); } catch(ClassNotFoundException e) {} } @AfterClass public static void clearEvoSuiteFramework(){ Sandbox.resetDefaultSecurityManager(); java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); setSystemProperties(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { java.lang.System.setProperties((java.util.Properties) defaultProperties.clone()); java.lang.System.setProperty("file.encoding", "UTF-8"); java.lang.System.setProperty("java.awt.headless", "true"); java.lang.System.setProperty("java.io.tmpdir", "/var/folders/r3/l648tx8s7hn8ppds6z2bk5cc000h2n/T/"); java.lang.System.setProperty("user.country", "GB"); java.lang.System.setProperty("user.dir", "/Users/kp11/workspace/applications/Artemis-build-ci/Artemis"); java.lang.System.setProperty("user.home", "/Users/kp11"); java.lang.System.setProperty("user.language", "en"); java.lang.System.setProperty("user.name", "kp11"); java.lang.System.setProperty("user.timezone", ""); } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(EntryChangeEvent_ESTest_scaffolding.class.getClassLoader() , "uk.ac.sanger.artemis.io.EntryInformationException", "uk.ac.sanger.artemis.io.Location", "uk.ac.sanger.artemis.io.PublicDBStreamFeature", "uk.ac.sanger.artemis.io.DocumentEntry", "uk.ac.sanger.artemis.FeatureSegmentVector", "uk.ac.sanger.artemis.io.OutOfDateException", "uk.ac.sanger.artemis.sequence.SequenceChangeListener", "uk.ac.sanger.artemis.OptionChangeEvent", "uk.ac.sanger.artemis.FeatureSegment", "uk.ac.sanger.artemis.io.InvalidRelationException", "uk.ac.sanger.artemis.io.ComparableFeature", "uk.ac.sanger.artemis.io.Feature", "uk.ac.sanger.artemis.io.SimpleDocumentFeature", "uk.ac.sanger.artemis.io.StreamFeature", "uk.ac.sanger.artemis.io.Key", "uk.ac.sanger.artemis.sequence.BasePatternFormatException", "uk.ac.sanger.artemis.util.ReadOnlyException", "uk.ac.sanger.artemis.io.LocationParseException", "uk.ac.sanger.artemis.io.SimpleDocumentEntry", "uk.ac.sanger.artemis.io.EntryInformation", "uk.ac.sanger.artemis.EntryChangeListener", "uk.ac.sanger.artemis.EntryChangeEvent", "uk.ac.sanger.artemis.Entry", "uk.ac.sanger.artemis.sequence.MarkerChangeListener", "uk.ac.sanger.artemis.sequence.AminoAcidSequence", "uk.ac.sanger.artemis.Selectable", "uk.ac.sanger.artemis.Feature", "uk.ac.sanger.artemis.io.EmblDocumentEntry", "uk.ac.sanger.artemis.io.ReadFormatException", "uk.ac.sanger.artemis.io.DocumentFeature", "uk.ac.sanger.artemis.io.EmblStreamFeature", "uk.ac.sanger.artemis.io.Range", "uk.ac.sanger.artemis.sequence.Bases", "uk.ac.sanger.artemis.io.PublicDBDocumentEntry", "uk.ac.sanger.artemis.io.Qualifier", "uk.ac.sanger.artemis.io.Entry", "uk.ac.sanger.artemis.util.StringVector", "uk.ac.sanger.artemis.ChangeListener", "uk.ac.sanger.artemis.LastSegmentException", "uk.ac.sanger.artemis.ChangeEvent", "uk.ac.sanger.artemis.sequence.Marker", "uk.ac.sanger.artemis.util.OutOfRangeException", "uk.ac.sanger.artemis.util.Document", "uk.ac.sanger.artemis.sequence.MarkerChangeEvent", "uk.ac.sanger.artemis.io.GFFDocumentEntry", "uk.ac.sanger.artemis.io.GFFStreamFeature", "uk.ac.sanger.artemis.FeatureVector", "uk.ac.sanger.artemis.io.EMBLObject", "uk.ac.sanger.artemis.sequence.Strand", "uk.ac.sanger.artemis.sequence.NoSequenceException", "uk.ac.sanger.artemis.FeaturePredicate", "uk.ac.sanger.artemis.sequence.SequenceChangeEvent", "uk.ac.sanger.artemis.OptionChangeListener", "uk.ac.sanger.artemis.io.QualifierVector", "uk.ac.sanger.artemis.FeatureChangeListener", "uk.ac.sanger.artemis.util.FileDocument", "uk.ac.sanger.artemis.FeatureChangeEvent", "uk.ac.sanger.artemis.FeatureEnumeration", "uk.ac.sanger.artemis.io.LineGroup" ); } private static void initMocksToAvoidTimeoutsInTheTests() throws ClassNotFoundException { mock(Class.forName("uk.ac.sanger.artemis.Entry", false, EntryChangeEvent_ESTest_scaffolding.class.getClassLoader())); mock(Class.forName("uk.ac.sanger.artemis.Feature", false, EntryChangeEvent_ESTest_scaffolding.class.getClassLoader())); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(EntryChangeEvent_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "uk.ac.sanger.artemis.ChangeEvent", "uk.ac.sanger.artemis.EntryChangeEvent", "uk.ac.sanger.artemis.Feature", "uk.ac.sanger.artemis.Entry" ); } }
sanger-pathogens/Artemis
src/test/evosuite/uk/ac/sanger/artemis/EntryChangeEvent_ESTest_scaffolding.java
Java
gpl-3.0
7,735
// Copyright 2017 Ryan Wick ([email protected]) // https://github.com/rrwick/Unicycler // This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as published by the Free Software // Foundation, either version 3 of the License, or (at your option) any later version. Unicycler 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 Genral Public // License along with Unicycler. If not, see <http://www.gnu.org/licenses/>. #include "overlap_align.h" #include "string_functions.h" #include <seqan/align.h> char * overlapAlignment(char * s1, char * s2, int matchScore, int mismatchScore, int gapOpenScore, int gapExtensionScore, int guessOverlap) { std::string sequence1(s1); std::string sequence2(s2); // Trim the sequences down to a bit more than the expected overlap. This will help save time // because the non-overlapping sequence isn't informative. int trim_size = int((guessOverlap + 100) * 1.5); if (trim_size < int(sequence1.length())) sequence1 = sequence1.substr(sequence1.length() - trim_size, trim_size); if (trim_size < int(sequence2.length())) sequence2 = sequence2.substr(0, trim_size); Dna5String sequenceH(sequence1); Dna5String sequenceV(sequence2); Align<Dna5String, ArrayGaps> alignment; resize(rows(alignment), 2); assignSource(row(alignment, 0), sequenceH); assignSource(row(alignment, 1), sequenceV); Score<int, Simple> scoringScheme(matchScore, mismatchScore, gapExtensionScore, gapOpenScore); // The alignment configuration allows for overlap from s1 -> s2. AlignConfig<true, false, true, false> alignConfig; try { globalAlignment(alignment, scoringScheme, alignConfig); } catch (...) { return cppStringToCString("-1,-1"); } std::ostringstream stream1; stream1 << row(alignment, 0); std::string seq1Alignment = stream1.str(); std::ostringstream stream2; stream2 << row(alignment, 1); std::string seq2Alignment = stream2.str(); int alignmentLength = std::max(seq1Alignment.size(), seq2Alignment.size()); if (alignmentLength == 0) return cppStringToCString("-1,-1"); int seq1Pos = 0, seq2Pos = 0; int seq1PosAtSeq2Start = -1, seq2PosAtSeq1End = -1; for (int i = 0; i < alignmentLength; ++i) { char base1 = seq1Alignment[i]; char base2 = seq2Alignment[i]; if (base1 != '-') seq2PosAtSeq1End = seq2Pos + 1; if (base2 != '-' && seq1PosAtSeq2Start == -1) seq1PosAtSeq2Start = seq1Pos; if (base1 != '-') ++seq1Pos; if (base2 != '-') ++seq2Pos; } int overlap1 = seq1Pos - seq1PosAtSeq2Start; int overlap2 = seq2PosAtSeq1End; return cppStringToCString(std::to_string(overlap1) + "," + std::to_string(overlap2)); }
rrwick/Unicycler
unicycler/src/overlap_align.cpp
C++
gpl-3.0
3,185
package me.anthonybruno.soccerSim.reader; import org.apache.pdfbox.io.RandomAccessFile; import org.apache.pdfbox.pdfparser.PDFParser; import org.apache.pdfbox.text.PDFTextStripperByArea; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.IOException; /** * A class that parsers team PDF files into XML files. */ public class TeamPdfReader { private static final Rectangle2D.Double firstTeamFirstPageRegion = new Rectangle2D.Double(0, 0, 330, 550); private static final Rectangle2D.Double secondTeamFirstPageRegion = new Rectangle2D.Double(350, 0, 350, 550); private final File file; public TeamPdfReader(String fileName) { this.file = new File(fileName); } public TeamPdfReader(File file) { this.file = file; } // public String read() { //Using IText :( // try { // PdfReader pdfReader = new PdfReader(file.getAbsolutePath()); // PdfDocument pdfDocument = new PdfDocument(pdfReader); // // LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy(); // // PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy); // parser.processPageContent(pdfDocument.getFirstPage()); // return strategy.getResultantText(); // // } catch (IOException e) { // e.printStackTrace(); // } // } public void readAllTeamsToFiles() { //Using PDFBox try { PDFParser parser = new PDFParser(new RandomAccessFile(file, "r")); parser.parse(); PDFTextStripperByArea pdfTextStripperByArea = new PDFTextStripperByArea(); pdfTextStripperByArea.addRegion("First", firstTeamFirstPageRegion); pdfTextStripperByArea.addRegion("Second", secondTeamFirstPageRegion); for (int i = 0; i < parser.getPDDocument().getNumberOfPages(); i++) { pdfTextStripperByArea.extractRegions(parser.getPDDocument().getPage(i)); writeTeamToFile(pdfTextStripperByArea.getTextForRegion("First"), "teams"); writeTeamToFile(pdfTextStripperByArea.getTextForRegion("Second"), "teams"); } } catch (IOException e) { e.printStackTrace(); } } public void writeTeamToFile(String teamExtractedFromPDf, String saveDirectory) { //FIXME: Reduce size of method if (teamExtractedFromPDf.isEmpty() || !teamExtractedFromPDf.contains(" ")) { return; //reached a blank page } XmlWriter xmlWriter = new XmlWriter("UTF-8"); String text = teamExtractedFromPDf; if (text.indexOf('\n') < text.indexOf(' ')) { text = text.substring(text.indexOf('\n') + 1); } xmlWriter.createOpenTag("team"); if (text.startsWith(" ")) { text = text.substring(text.indexOf('\n') + 1); //need this for El Salvador } String name = text.substring(0, text.indexOf(" ")); text = text.substring(text.indexOf(" ") + 1); if (!Character.isDigit(text.charAt(0))) { //handles countries with two words in name name += " " + text.substring(0, text.indexOf(" ")); } xmlWriter.createTagWithValue("name", name); for (int i = 0; i < 3; i++) { //skipping stuff we don't care about text = moveToNextLine(text); } text = text.substring(text.indexOf(':') + 2); String firstHalfAttempts = text.substring(0, text.indexOf(' ')); text = text.substring(text.indexOf(' ') + 1); String secondHalfAttempts = text.substring(0, text.indexOf('\n')); text = moveToNextLine(text); xmlWriter.createTagWithValue("goalRating", text.substring(text.indexOf('-') + 1, text.indexOf('\n'))); text = moveToNextLine(text); String[] defensiveAttempts = parseHalfValues(text); text = defensiveAttempts[0]; String firstHalfDefensiveAttempts = defensiveAttempts[1]; String secondHalfDefensiveAttempts = defensiveAttempts[2]; String[] defensiveSOG = parseHalfValues(text); text = defensiveSOG[0]; String firstHalfSOG = defensiveSOG[1]; String secondHalfSOG = defensiveSOG[2]; xmlWriter.createTagWithValue("formation", text.substring(text.indexOf(':') + 2, text.indexOf('\n'))); text = moveToNextLine(text); text = text.substring(text.indexOf(':') + 2); if (text.indexOf(' ') < text.indexOf('\n')) { xmlWriter.createTagWithValue("strategy", text.substring(0, text.indexOf(' '))); //team has fair play score } else { xmlWriter.createTagWithValue("strategy", text.substring(0, text.indexOf("\n"))); } text = moveToNextLine(text); text = moveToNextLine(text); parseHalfStats(xmlWriter, "halfStats", firstHalfAttempts, firstHalfDefensiveAttempts, firstHalfSOG); parseHalfStats(xmlWriter, "halfStats", secondHalfAttempts, secondHalfDefensiveAttempts, secondHalfSOG); xmlWriter.createOpenTag("players"); while (!text.startsWith("Goalies")) { text = parsePlayer(xmlWriter, text); } text = moveToNextLine(text); parseGoalies(xmlWriter, text); xmlWriter.createCloseTag("players"); xmlWriter.createCloseTag("team"); File saveDir = new File(saveDirectory); try { saveDir.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (!saveDir.exists()) { file.mkdir(); } xmlWriter.writeToFile(new File("src/main/resources/teams/" + name + ".xml")); } private void parseGoalies(XmlWriter xmlWriter, String text) { while (!text.isEmpty()) { xmlWriter.createOpenTag("goalie"); String playerName = ""; do { playerName += text.substring(0, text.indexOf(' ')); text = text.substring(text.indexOf(' ') + 1); } while (!isNumeric(text.substring(0, text.indexOf(' ')))); xmlWriter.createTagWithValue("name", playerName); xmlWriter.createTagWithValue("rating", text.substring(0, text.indexOf(' '))); text = text.substring(text.indexOf(' ') + 1); text = text.substring(text.indexOf(' ') + 1); text = parsePlayerAttribute(xmlWriter, "injury", text); createMultiplierTag(xmlWriter, text); text = moveToNextLine(text); xmlWriter.createCloseTag("goalie"); } } private boolean isNumeric(char c) { return isNumeric(c + ""); } private boolean isNumeric(String string) { return string.matches("^[-+]?\\d+$"); } private void createMultiplierTag(XmlWriter xmlWriter, String text) { if (text.charAt(0) != '-') { xmlWriter.createTagWithValue("multiplier", text.charAt(1) + ""); } else { xmlWriter.createTagWithValue("multiplier", "0"); } } private String parsePlayer(XmlWriter xmlWriter, String text) { xmlWriter.createOpenTag("player"); text = parsePlayerName(xmlWriter, text); text = parsePlayerAttribute(xmlWriter, "shotRange", text); text = parsePlayerAttribute(xmlWriter, "goal", text); text = parsePlayerAttribute(xmlWriter, "injury", text); createMultiplierTag(xmlWriter, text); xmlWriter.createCloseTag("player"); text = moveToNextLine(text); return text; } private String parsePlayerName(XmlWriter xmlWriter, String text) { if (isNumeric(text.charAt(text.indexOf(' ') + 1))) { return parsePlayerAttribute(xmlWriter, "name", text); //Player has single name } else { String playerName = text.substring(0, text.indexOf(' ')); text = text.substring(text.indexOf(' ') + 1); while (!isNumeric(text.charAt(0))) { playerName += ' ' + text.substring(0, text.indexOf(' ')); text = text.substring(text.indexOf(' ') + 1); } xmlWriter.createTagWithValue("name", playerName); return text; } } private String parsePlayerAttribute(XmlWriter xmlWriter, String tagName, String text) { xmlWriter.createTagWithValue(tagName, text.substring(0, text.indexOf(' '))); text = text.substring(text.indexOf(' ') + 1); return text; } private String[] parseHalfValues(String text) { text = text.substring(text.indexOf(':') + 2); String firstHalf = text.substring(0, text.indexOf(' ')); text = text.substring(text.indexOf(' ') + 1); String secondHalf = text.substring(0, text.indexOf('\n')); text = moveToNextLine(text); return new String[]{text, firstHalf, secondHalf}; } private void parseHalfStats(XmlWriter xmlWriter, String halfName, String attempts, String defensiveAttempts, String defensiveShotsOnGoal) { xmlWriter.createOpenTag(halfName); xmlWriter.createTagWithValue("attempts", attempts); xmlWriter.createTagWithValue("defensiveAttempts", defensiveAttempts); xmlWriter.createTagWithValue("defensiveShotsOnGoal", defensiveShotsOnGoal); xmlWriter.createCloseTag(halfName); } private String moveToNextLine(String text) { return text.substring(text.indexOf("\n") + 1); } public static void main(String[] args) { TeamPdfReader teamPdfReader = new TeamPdfReader("src/main/resources/ruleFiles/Cards1.pdf"); teamPdfReader.readAllTeamsToFiles(); teamPdfReader = new TeamPdfReader("src/main/resources/ruleFiles/Cards2.pdf"); teamPdfReader.readAllTeamsToFiles(); } }
AussieGuy0/soccerSim
src/main/java/me/anthonybruno/soccerSim/reader/TeamPdfReader.java
Java
gpl-3.0
9,771
module TransactionChains class Lifetimes::ExpirationWarning < ::TransactionChain label 'Expiration' allow_empty def link_chain(klass, q) q.each do |obj| user = if obj.is_a?(::User) obj elsif obj.respond_to?(:user) obj.user else fail "Unable to find an owner for #{obj} of class #{klass}" end mail(:expiration_warning, { params: { object: klass.name.underscore, state: obj.object_state, }, user: user, vars: { object: obj, state: obj.current_object_state, klass.name.underscore => obj } }) if user.mailer_enabled end end end end
vpsfreecz/vpsadmin-webui
api/models/transaction_chains/lifetimes/expiration_warning.rb
Ruby
gpl-3.0
792
--- --- InternalResource provides access to static resources in the class path. ## Related components * [AudioResource](AudioResource.html) * [ImageResource](ImageResource.html) * [VideoResource](VideoResource.html) * [WImage](WImage.html) * [WApplication](WApplication.html) * [WContent](WContent.html) * [WImage](WImage.html) * [WMultiFileWidget](WMultiFileWidget.html) * [WTree](WTree.html) ## Further information * [JavaDoc](../apidocs/com/github/bordertech/wcomponents/InternalResource.html); * [List of WComponents](List-of-WComponents.html).
marksreeves/faff
docs/wiki/InternalResource.md
Markdown
gpl-3.0
552
#pragma once #include <vector> #include <boost/thread.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/bind.hpp> #include <boost/version.hpp> #include <boost/function.hpp> #include <boost/interprocess/detail/atomic.hpp> #if (BOOST_VERSION < 104800) using boost::interprocess::detail::atomic_inc32; #else using boost::interprocess::ipcdetail::atomic_inc32; #endif /* * TODO: * * - Better documentation of API * - deleting of ended thread:local memory * - by mean of Done function * - by DelThread * - Pause/Resume function * - use a barrier instead of a crappy sleep * - should this code move at the end of each blocks ? */ namespace scheduling { class Scheduler; class Thread; class Range; class Thread { public: virtual void Init() {} virtual void End() {} virtual ~Thread() {}; friend class Scheduler; friend class Range; private: static void Body(Thread* thread, Scheduler *scheduler); boost::thread thread; bool active; }; typedef boost::function<void(Range *range)> TaskType; class Scheduler { public: Scheduler(unsigned step); ~Scheduler(); void Launch(TaskType task, unsigned b_min, unsigned b_max, unsigned force_step=0); void Pause(); void Resume(); void Stop(); void Done(); void AddThread(Thread *thread); void DelThread(); unsigned ThreadCount() const { return threads.size(); } void FreeThreadLocalStorage(); friend class Thread; friend class Range; private: enum {PAUSED, RUNNING} state; TaskType GetTask(); bool EndTask(Thread* thread); std::vector<Thread*> threads; std::vector<Thread*> threads_finished; TaskType current_task; boost::mutex mutex; boost::condition_variable condition; unsigned counter; unsigned start; unsigned end; unsigned current; unsigned step; unsigned default_step; }; class Range { public: unsigned begin() { return atomic_init(); } unsigned end() { return ~0u; } unsigned next() { if(++current < max) return current; // handle pause while (scheduler->state == Scheduler::PAUSED) { boost::this_thread::sleep(boost::posix_time::seconds(1)); } return atomic_init(); } // public for thread local data access Thread *thread; friend class Thread; private: unsigned atomic_init() { if(!thread->active) return end(); unsigned new_value = scheduler->step * atomic_inc32(&scheduler->current); if(new_value < scheduler->end) { max = std::min(scheduler->end, new_value + scheduler->step); current = new_value; return new_value; } return end(); } Range(Scheduler *sched, Thread *thread_data); unsigned current; unsigned max; Scheduler *scheduler; }; }
marwan-abdellah/luxrender-lux
core/scheduler.h
C
gpl-3.0
2,656
// This file belongs to the "MiniCore" game engine. // Copyright (C) 2012 Jussi Lind <[email protected]> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301, USA. // #ifndef MCLOGGER_HH #define MCLOGGER_HH #include "mcmacros.hh" #include <cstdio> #include <sstream> /*! A logging class. A MCLogger instance flushes on destruction. * * Example initialization: * * MCLogger::init("myLog.txt"); * MCLogger::enableEchoMode(true); * * Example logging: * * MCLogger().info() << "Initialization finished."; * MCLogger().error() << "Foo happened!"; */ class MCLogger { public: //! Constructor. MCLogger(); //! Destructor. ~MCLogger(); /*! Initialize the logger. * \param fileName Log to fileName. Can be nullptr. * \param append The existing log will be appended if true. * \return false if file couldn't be opened. */ static bool init(const char * fileName, bool append = false); //! Enable/disable echo mode. //! \param enable Echo everything if true. Default is false. static void enableEchoMode(bool enable); //! Enable/disable date and time prefix. //! \param enable Prefix with date and time if true. Default is true. static void enableDateTimePrefix(bool enable); //! Get stream to the info log message. std::ostringstream & info(); //! Get stream to the warning log message. std::ostringstream & warning(); //! Get stream to the error log message. std::ostringstream & error(); //! Get stream to the fatal log message. std::ostringstream & fatal(); private: DISABLE_COPY(MCLogger); DISABLE_ASSI(MCLogger); void prefixDateTime(); static bool m_echoMode; static bool m_dateTime; static FILE * m_file; std::ostringstream m_oss; }; #endif // MCLOGGER_HH
juzzlin/DustRacing2D
src/game/MiniCore/src/Core/mclogger.hh
C++
gpl-3.0
2,473
// // tcpconnection.cpp // // This implements RFC 793 with some changes in RFC 1122 and RFC 6298. // // Non-implemented features: // dynamic receive window // URG flag and urgent pointer // delayed ACK // queueing out-of-order TCP segments // security/compartment // precedence // user timeout // // Circle - A C++ bare metal environment for Raspberry Pi // Copyright (C) 2015-2021 R. Stange <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include <circle/net/tcpconnection.h> #include <circle/macros.h> #include <circle/util.h> #include <circle/logger.h> #include <circle/net/in.h> #include <assert.h> //#define TCP_DEBUG #define TCP_MAX_CONNECTIONS 1000 // maximum number of active TCP connections #define MSS_R 1480 // maximum segment size to be received from network layer #define MSS_S 1480 // maximum segment size to be send to network layer #define TCP_CONFIG_MSS (MSS_R - 20) #define TCP_CONFIG_WINDOW (TCP_CONFIG_MSS * 10) #define TCP_CONFIG_RETRANS_BUFFER_SIZE 0x10000 // should be greater than maximum send window size #define TCP_MAX_WINDOW ((u16) -1) // without Window extension option #define TCP_QUIET_TIME 30 // seconds after crash before another connection starts #define HZ_TIMEWAIT (60 * HZ) #define HZ_FIN_TIMEOUT (60 * HZ) // timeout in FIN-WAIT-2 state #define MAX_RETRANSMISSIONS 5 struct TTCPHeader { u16 nSourcePort; u16 nDestPort; u32 nSequenceNumber; u32 nAcknowledgmentNumber; u16 nDataOffsetFlags; // following #define(s) are valid without BE() #define TCP_DATA_OFFSET(field) (((field) >> 4) & 0x0F) #define TCP_DATA_OFFSET_SHIFT 4 //#define TCP_FLAG_NONCE (1 << 0) //#define TCP_FLAG_CWR (1 << 15) //#define TCP_FLAG_ECN_ECHO (1 << 14) #define TCP_FLAG_URGENT (1 << 13) #define TCP_FLAG_ACK (1 << 12) #define TCP_FLAG_PUSH (1 << 11) #define TCP_FLAG_RESET (1 << 10) #define TCP_FLAG_SYN (1 << 9) #define TCP_FLAG_FIN (1 << 8) u16 nWindow; u16 nChecksum; u16 nUrgentPointer; u32 Options[]; } PACKED; #define TCP_HEADER_SIZE 20 // valid for normal data segments without TCP options struct TTCPOption { u8 nKind; // Data: #define TCP_OPTION_END_OF_LIST 0 // None (no length field) #define TCP_OPTION_NOP 1 // None (no length field) #define TCP_OPTION_MSS 2 // Maximum segment size (2 byte) #define TCP_OPTION_WINDOW_SCALE 3 // Shift count (1 byte) #define TCP_OPTION_SACK_PERM 4 // None #define TCP_OPTION_TIMESTAMP 8 // Timestamp value, Timestamp echo reply (2*4 byte) u8 nLength; u8 Data[]; } PACKED; #define min(n, m) ((n) <= (m) ? (n) : (m)) #define max(n, m) ((n) >= (m) ? (n) : (m)) // Modulo 32 sequence number arithmetic #define lt(x, y) ((int) ((u32) (x) - (u32) (y)) < 0) #define le(x, y) ((int) ((u32) (x) - (u32) (y)) <= 0) #define gt(x, y) lt (y, x) #define ge(x, y) le (y, x) #define bw(l, x, h) (lt ((l), (x)) && lt ((x), (h))) // between #define bwl(l, x, h) (le ((l), (x)) && lt ((x), (h))) // low border inclusive #define bwh(l, x, h) (lt ((l), (x)) && le ((x), (h))) // high border inclusive #define bwlh(l, x, h) (le ((l), (x)) && le ((x), (h))) // both borders inclusive #if !defined (NDEBUG) && defined (TCP_DEBUG) #define NEW_STATE(state) NewState (state, __LINE__); #else #define NEW_STATE(state) (m_State = state) #endif #ifndef NDEBUG #define UNEXPECTED_STATE() UnexpectedState (__LINE__) #else #define UNEXPECTED_STATE() ((void) 0) #endif unsigned CTCPConnection::s_nConnections = 0; static const char FromTCP[] = "tcp"; CTCPConnection::CTCPConnection (CNetConfig *pNetConfig, CNetworkLayer *pNetworkLayer, CIPAddress &rForeignIP, u16 nForeignPort, u16 nOwnPort) : CNetConnection (pNetConfig, pNetworkLayer, rForeignIP, nForeignPort, nOwnPort, IPPROTO_TCP), m_bActiveOpen (TRUE), m_State (TCPStateClosed), m_nErrno (0), m_RetransmissionQueue (TCP_CONFIG_RETRANS_BUFFER_SIZE), m_bRetransmit (FALSE), m_bSendSYN (FALSE), m_bFINQueued (FALSE), m_nRetransmissionCount (0), m_bTimedOut (FALSE), m_pTimer (CTimer::Get ()), m_nSND_WND (TCP_CONFIG_WINDOW), m_nSND_UP (0), m_nRCV_NXT (0), m_nRCV_WND (TCP_CONFIG_WINDOW), m_nIRS (0), m_nSND_MSS (536) // RFC 1122 section 4.2.2.6 { s_nConnections++; for (unsigned nTimer = TCPTimerUser; nTimer < TCPTimerUnknown; nTimer++) { m_hTimer[nTimer] = 0; } m_nISS = CalculateISN (); m_RTOCalculator.Initialize (m_nISS); m_nSND_UNA = m_nISS; m_nSND_NXT = m_nISS+1; if (SendSegment (TCP_FLAG_SYN, m_nISS)) { m_RTOCalculator.SegmentSent (m_nISS); NEW_STATE (TCPStateSynSent); m_nRetransmissionCount = MAX_RETRANSMISSIONS; StartTimer (TCPTimerRetransmission, m_RTOCalculator.GetRTO ()); } } CTCPConnection::CTCPConnection (CNetConfig *pNetConfig, CNetworkLayer *pNetworkLayer, u16 nOwnPort) : CNetConnection (pNetConfig, pNetworkLayer, nOwnPort, IPPROTO_TCP), m_bActiveOpen (FALSE), m_State (TCPStateListen), m_nErrno (0), m_RetransmissionQueue (TCP_CONFIG_RETRANS_BUFFER_SIZE), m_bRetransmit (FALSE), m_bSendSYN (FALSE), m_bFINQueued (FALSE), m_nRetransmissionCount (0), m_bTimedOut (FALSE), m_pTimer (CTimer::Get ()), m_nSND_WND (TCP_CONFIG_WINDOW), m_nSND_UP (0), m_nRCV_NXT (0), m_nRCV_WND (TCP_CONFIG_WINDOW), m_nIRS (0), m_nSND_MSS (536) // RFC 1122 section 4.2.2.6 { s_nConnections++; for (unsigned nTimer = TCPTimerUser; nTimer < TCPTimerUnknown; nTimer++) { m_hTimer[nTimer] = 0; } } CTCPConnection::~CTCPConnection (void) { #ifdef TCP_DEBUG CLogger::Get ()->Write (FromTCP, LogDebug, "Delete TCB"); #endif assert (m_State == TCPStateClosed); for (unsigned nTimer = TCPTimerUser; nTimer < TCPTimerUnknown; nTimer++) { StopTimer (nTimer); } // ensure no task is waiting any more m_Event.Set (); m_TxEvent.Set (); assert (s_nConnections > 0); s_nConnections--; } int CTCPConnection::Connect (void) { if (m_nErrno < 0) { return m_nErrno; } switch (m_State) { case TCPStateSynSent: case TCPStateSynReceived: m_Event.Clear (); m_Event.Wait (); break; case TCPStateEstablished: break; case TCPStateListen: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: UNEXPECTED_STATE (); // fall through case TCPStateClosed: return -1; } return m_nErrno; } int CTCPConnection::Accept (CIPAddress *pForeignIP, u16 *pForeignPort) { if (m_nErrno < 0) { return m_nErrno; } switch (m_State) { case TCPStateSynSent: UNEXPECTED_STATE (); // fall through case TCPStateClosed: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: return -1; case TCPStateListen: m_Event.Clear (); m_Event.Wait (); break; case TCPStateSynReceived: case TCPStateEstablished: break; } assert (pForeignIP != 0); pForeignIP->Set (m_ForeignIP); assert (pForeignPort != 0); *pForeignPort = m_nForeignPort; return m_nErrno; } int CTCPConnection::Close (void) { if (m_nErrno < 0) { return m_nErrno; } switch (m_State) { case TCPStateClosed: return -1; case TCPStateListen: case TCPStateSynSent: StopTimer (TCPTimerRetransmission); NEW_STATE (TCPStateClosed); break; case TCPStateSynReceived: case TCPStateEstablished: assert (!m_bFINQueued); m_StateAfterFIN = TCPStateFinWait1; m_nRetransmissionCount = MAX_RETRANSMISSIONS; m_bFINQueued = TRUE; break; case TCPStateFinWait1: case TCPStateFinWait2: break; case TCPStateCloseWait: assert (!m_bFINQueued); m_StateAfterFIN = TCPStateLastAck; // RFC 1122 section 4.2.2.20 (a) m_nRetransmissionCount = MAX_RETRANSMISSIONS; m_bFINQueued = TRUE; break; case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: return -1; } if (m_nErrno < 0) { return m_nErrno; } return 0; } int CTCPConnection::Send (const void *pData, unsigned nLength, int nFlags) { if ( nFlags != 0 && nFlags != MSG_DONTWAIT) { return -1; } if (m_nErrno < 0) { return m_nErrno; } switch (m_State) { case TCPStateClosed: case TCPStateListen: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: return -1; case TCPStateSynSent: case TCPStateSynReceived: case TCPStateEstablished: case TCPStateCloseWait: break; } unsigned nResult = nLength; assert (pData != 0); u8 *pBuffer = (u8 *) pData; while (nLength > FRAME_BUFFER_SIZE) { m_TxQueue.Enqueue (pBuffer, FRAME_BUFFER_SIZE); pBuffer += FRAME_BUFFER_SIZE; nLength -= FRAME_BUFFER_SIZE; } if (nLength > 0) { m_TxQueue.Enqueue (pBuffer, nLength); } if (!(nFlags & MSG_DONTWAIT)) { m_TxEvent.Clear (); m_TxEvent.Wait (); if (m_nErrno < 0) { return m_nErrno; } } return nResult; } int CTCPConnection::Receive (void *pBuffer, int nFlags) { if ( nFlags != 0 && nFlags != MSG_DONTWAIT) { return -1; } if (m_nErrno < 0) { return m_nErrno; } unsigned nLength; while ((nLength = m_RxQueue.Dequeue (pBuffer)) == 0) { switch (m_State) { case TCPStateClosed: case TCPStateListen: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: return -1; case TCPStateSynSent: case TCPStateSynReceived: case TCPStateEstablished: break; } if (nFlags & MSG_DONTWAIT) { return 0; } m_Event.Clear (); m_Event.Wait (); if (m_nErrno < 0) { return m_nErrno; } } return nLength; } int CTCPConnection::SendTo (const void *pData, unsigned nLength, int nFlags, CIPAddress &rForeignIP, u16 nForeignPort) { // ignore rForeignIP and nForeignPort return Send (pData, nLength, nFlags); } int CTCPConnection::ReceiveFrom (void *pBuffer, int nFlags, CIPAddress *pForeignIP, u16 *pForeignPort) { int nResult = Receive (pBuffer, nFlags); if (nResult <= 0) { return nResult; } if ( pForeignIP != 0 && pForeignPort != 0) { pForeignIP->Set (m_ForeignIP); *pForeignPort = m_nForeignPort; } return 0; } int CTCPConnection::SetOptionBroadcast (boolean bAllowed) { return 0; } boolean CTCPConnection::IsConnected (void) const { return m_State > TCPStateSynSent && m_State != TCPStateTimeWait; } boolean CTCPConnection::IsTerminated (void) const { return m_State == TCPStateClosed; } void CTCPConnection::Process (void) { if (m_bTimedOut) { m_nErrno = -1; NEW_STATE (TCPStateClosed); m_Event.Set (); return; } switch (m_State) { case TCPStateClosed: case TCPStateListen: case TCPStateFinWait2: case TCPStateTimeWait: return; case TCPStateSynSent: case TCPStateSynReceived: if (m_bSendSYN) { m_bSendSYN = FALSE; if (m_State == TCPStateSynSent) { SendSegment (TCP_FLAG_SYN, m_nISS); } else { SendSegment (TCP_FLAG_SYN | TCP_FLAG_ACK, m_nISS, m_nRCV_NXT); } m_RTOCalculator.SegmentSent (m_nISS); StartTimer (TCPTimerRetransmission, m_RTOCalculator.GetRTO ()); } return; case TCPStateEstablished: case TCPStateFinWait1: case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: if ( m_RetransmissionQueue.IsEmpty () && m_TxQueue.IsEmpty () && m_bFINQueued) { SendSegment (TCP_FLAG_FIN | TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); m_RTOCalculator.SegmentSent (m_nSND_NXT); m_nSND_NXT++; NEW_STATE (m_StateAfterFIN); m_bFINQueued = FALSE; StartTimer (TCPTimerRetransmission, m_RTOCalculator.GetRTO ()); } break; } u8 TempBuffer[FRAME_BUFFER_SIZE]; unsigned nLength; while ( m_RetransmissionQueue.GetFreeSpace () >= FRAME_BUFFER_SIZE && (nLength = m_TxQueue.Dequeue (TempBuffer)) > 0) { #ifdef TCP_DEBUG CLogger::Get ()->Write (FromTCP, LogDebug, "Transfering %u bytes into RT buffer", nLength); #endif m_RetransmissionQueue.Write (TempBuffer, nLength); } // pacing transmit if ( ( m_State == TCPStateEstablished || m_State == TCPStateCloseWait) && m_TxQueue.IsEmpty ()) { m_TxEvent.Set (); } if (m_bRetransmit) { #ifdef TCP_DEBUG CLogger::Get ()->Write (FromTCP, LogDebug, "Retransmission (nxt %u, una %u)", m_nSND_NXT-m_nISS, m_nSND_UNA-m_nISS); #endif m_bRetransmit = FALSE; m_RetransmissionQueue.Reset (); m_nSND_NXT = m_nSND_UNA; } u32 nBytesAvail; u32 nWindowLeft; while ( (nBytesAvail = m_RetransmissionQueue.GetBytesAvailable ()) > 0 && (nWindowLeft = m_nSND_UNA+m_nSND_WND-m_nSND_NXT) > 0) { nLength = min (nBytesAvail, nWindowLeft); nLength = min (nLength, m_nSND_MSS); #ifdef TCP_DEBUG CLogger::Get ()->Write (FromTCP, LogDebug, "Transfering %u bytes into TX buffer", nLength); #endif assert (nLength <= FRAME_BUFFER_SIZE); m_RetransmissionQueue.Read (TempBuffer, nLength); unsigned nFlags = TCP_FLAG_ACK; if (m_TxQueue.IsEmpty ()) { nFlags |= TCP_FLAG_PUSH; } SendSegment (nFlags, m_nSND_NXT, m_nRCV_NXT, TempBuffer, nLength); m_RTOCalculator.SegmentSent (m_nSND_NXT, nLength); m_nSND_NXT += nLength; StartTimer (TCPTimerRetransmission, m_RTOCalculator.GetRTO ()); } } int CTCPConnection::PacketReceived (const void *pPacket, unsigned nLength, CIPAddress &rSenderIP, CIPAddress &rReceiverIP, int nProtocol) { if (nProtocol != IPPROTO_TCP) { return 0; } if (nLength < sizeof (TTCPHeader)) { return -1; } assert (pPacket != 0); TTCPHeader *pHeader = (TTCPHeader *) pPacket; if (m_nOwnPort != be2le16 (pHeader->nDestPort)) { return 0; } if (m_State != TCPStateListen) { if ( m_ForeignIP != rSenderIP || m_nForeignPort != be2le16 (pHeader->nSourcePort)) { return 0; } } else { if (!(pHeader->nDataOffsetFlags & TCP_FLAG_SYN)) { return 0; } m_Checksum.SetDestinationAddress (rSenderIP); } if (m_Checksum.Calculate (pPacket, nLength) != CHECKSUM_OK) { return 0; } u16 nFlags = pHeader->nDataOffsetFlags; u32 nDataOffset = TCP_DATA_OFFSET (pHeader->nDataOffsetFlags)*4; u32 nDataLength = nLength-nDataOffset; // Current Segment Variables u32 nSEG_SEQ = be2le32 (pHeader->nSequenceNumber); u32 nSEG_ACK = be2le32 (pHeader->nAcknowledgmentNumber); u32 nSEG_LEN = nDataLength; if (nFlags & TCP_FLAG_SYN) { nSEG_LEN++; } if (nFlags & TCP_FLAG_FIN) { nSEG_LEN++; } u32 nSEG_WND = be2le16 (pHeader->nWindow); //u16 nSEG_UP = be2le16 (pHeader->nUrgentPointer); //u32 nSEG_PRC; // segment precedence value ScanOptions (pHeader); #ifdef TCP_DEBUG CLogger::Get ()->Write (FromTCP, LogDebug, "rx %c%c%c%c%c%c, seq %u, ack %u, win %u, len %u", nFlags & TCP_FLAG_URGENT ? 'U' : '-', nFlags & TCP_FLAG_ACK ? 'A' : '-', nFlags & TCP_FLAG_PUSH ? 'P' : '-', nFlags & TCP_FLAG_RESET ? 'R' : '-', nFlags & TCP_FLAG_SYN ? 'S' : '-', nFlags & TCP_FLAG_FIN ? 'F' : '-', nSEG_SEQ-m_nIRS, nFlags & TCP_FLAG_ACK ? nSEG_ACK-m_nISS : 0, nSEG_WND, nDataLength); DumpStatus (); #endif boolean bAcceptable = FALSE; // RFC 793 section 3.9 "SEGMENT ARRIVES" switch (m_State) { case TCPStateClosed: if (nFlags & TCP_FLAG_RESET) { // ignore } else if (!(nFlags & TCP_FLAG_ACK)) { m_ForeignIP.Set (rSenderIP); m_nForeignPort = be2le16 (pHeader->nSourcePort); m_Checksum.SetDestinationAddress (rSenderIP); SendSegment (TCP_FLAG_RESET | TCP_FLAG_ACK, 0, nSEG_SEQ+nSEG_LEN); } else { m_ForeignIP.Set (rSenderIP); m_nForeignPort = be2le16 (pHeader->nSourcePort); m_Checksum.SetDestinationAddress (rSenderIP); SendSegment (TCP_FLAG_RESET, nSEG_ACK); } break; case TCPStateListen: if (nFlags & TCP_FLAG_RESET) { // ignore } else if (nFlags & TCP_FLAG_ACK) { m_ForeignIP.Set (rSenderIP); m_nForeignPort = be2le16 (pHeader->nSourcePort); m_Checksum.SetDestinationAddress (rSenderIP); SendSegment (TCP_FLAG_RESET, nSEG_ACK); } else if (nFlags & TCP_FLAG_SYN) { if (s_nConnections >= TCP_MAX_CONNECTIONS) { m_ForeignIP.Set (rSenderIP); m_nForeignPort = be2le16 (pHeader->nSourcePort); m_Checksum.SetDestinationAddress (rSenderIP); SendSegment (TCP_FLAG_RESET | TCP_FLAG_ACK, 0, nSEG_SEQ+nSEG_LEN); break; } m_nRCV_NXT = nSEG_SEQ+1; m_nIRS = nSEG_SEQ; m_nSND_WND = nSEG_WND; m_nSND_WL1 = nSEG_SEQ; m_nSND_WL2 = nSEG_ACK; assert (nSEG_LEN > 0); if (nDataLength > 0) { m_RxQueue.Enqueue ((u8 *) pPacket+nDataOffset, nDataLength); } m_nISS = CalculateISN (); m_RTOCalculator.Initialize (m_nISS); m_ForeignIP.Set (rSenderIP); m_nForeignPort = be2le16 (pHeader->nSourcePort); m_Checksum.SetDestinationAddress (rSenderIP); SendSegment (TCP_FLAG_SYN | TCP_FLAG_ACK, m_nISS, m_nRCV_NXT); m_RTOCalculator.SegmentSent (m_nISS); m_nSND_NXT = m_nISS+1; m_nSND_UNA = m_nISS; NEW_STATE (TCPStateSynReceived); m_Event.Set (); } break; case TCPStateSynSent: if (nFlags & TCP_FLAG_ACK) { if (!bwh (m_nISS, nSEG_ACK, m_nSND_NXT)) { if (!(nFlags & TCP_FLAG_RESET)) { SendSegment (TCP_FLAG_RESET, nSEG_ACK); } return 1; } else if (bwlh (m_nSND_UNA, nSEG_ACK, m_nSND_NXT)) { bAcceptable = TRUE; } } if (nFlags & TCP_FLAG_RESET) { if (bAcceptable) { NEW_STATE (TCPStateClosed); m_bSendSYN = FALSE; m_nErrno = -1; m_Event.Set (); } break; } if ( (nFlags & TCP_FLAG_ACK) && !bAcceptable) { break; } if (nFlags & TCP_FLAG_SYN) { m_nRCV_NXT = nSEG_SEQ+1; m_nIRS = nSEG_SEQ; if (nFlags & TCP_FLAG_ACK) { m_RTOCalculator.SegmentAcknowledged (nSEG_ACK); if (nSEG_ACK-m_nSND_UNA > 1) { m_RetransmissionQueue.Advance (nSEG_ACK-m_nSND_UNA-1); } m_nSND_UNA = nSEG_ACK; } if (gt (m_nSND_UNA, m_nISS)) { NEW_STATE (TCPStateEstablished); m_bSendSYN = FALSE; StopTimer (TCPTimerRetransmission); // next transmission starts with this count m_nRetransmissionCount = MAX_RETRANSMISSIONS; m_Event.Set (); // RFC 1122 section 4.2.2.20 (c) m_nSND_WND = nSEG_WND; m_nSND_WL1 = nSEG_SEQ; m_nSND_WL2 = nSEG_ACK; SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); if ( (nFlags & TCP_FLAG_FIN) // other controls? || nDataLength > 0) { goto StepSix; } break; } else { NEW_STATE (TCPStateSynReceived); m_bSendSYN = FALSE; SendSegment (TCP_FLAG_SYN | TCP_FLAG_ACK, m_nISS, m_nRCV_NXT); m_RTOCalculator.SegmentSent (m_nISS); m_nRetransmissionCount = MAX_RETRANSMISSIONS; StartTimer (TCPTimerRetransmission, m_RTOCalculator.GetRTO ()); if ( (nFlags & TCP_FLAG_FIN) // other controls? || nDataLength > 0) { if (nFlags & TCP_FLAG_FIN) { SendSegment (TCP_FLAG_RESET, m_nSND_NXT); NEW_STATE (TCPStateClosed); m_nErrno = -1; m_Event.Set (); } if (nDataLength > 0) { m_RxQueue.Enqueue ((u8 *) pPacket+nDataOffset, nDataLength); } break; } } } break; case TCPStateSynReceived: case TCPStateEstablished: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: // step 1 ( check sequence number) if (m_nRCV_WND > 0) { if (nSEG_LEN == 0) { if (bwl (m_nRCV_NXT, nSEG_SEQ, m_nRCV_NXT+m_nRCV_WND)) { bAcceptable = TRUE; } } else { if ( bwl (m_nRCV_NXT, nSEG_SEQ, m_nRCV_NXT+m_nRCV_WND) || bwl (m_nRCV_NXT, nSEG_SEQ+nSEG_LEN-1, m_nRCV_NXT+m_nRCV_WND)) { bAcceptable = TRUE; } } } else { if (nSEG_LEN == 0) { if (nSEG_SEQ == m_nRCV_NXT) { bAcceptable = TRUE; } } } if ( !bAcceptable && m_State != TCPStateSynReceived) { SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); break; } // step 2 (check RST bit) if (nFlags & TCP_FLAG_RESET) { switch (m_State) { case TCPStateSynReceived: m_RetransmissionQueue.Flush (); if (!m_bActiveOpen) { NEW_STATE (TCPStateListen); return 1; } else { m_nErrno = -1; NEW_STATE (TCPStateClosed); m_Event.Set (); return 1; } break; case TCPStateEstablished: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateCloseWait: m_nErrno = -1; m_RetransmissionQueue.Flush (); m_TxQueue.Flush (); m_RxQueue.Flush (); NEW_STATE (TCPStateClosed); m_Event.Set (); return 1; case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: NEW_STATE (TCPStateClosed); m_Event.Set (); return 1; default: UNEXPECTED_STATE (); return 1; } } // step 3 (check security and precedence, not supported) // step 4 (check SYN bit) if (nFlags & TCP_FLAG_SYN) { // RFC 1122 section 4.2.2.20 (e) if ( m_State == TCPStateSynReceived && !m_bActiveOpen) { NEW_STATE (TCPStateListen); return 1; } SendSegment (TCP_FLAG_RESET, m_nSND_NXT); m_nErrno = -1; m_RetransmissionQueue.Flush (); m_TxQueue.Flush (); m_RxQueue.Flush (); NEW_STATE (TCPStateClosed); m_Event.Set (); return 1; } // step 5 (check ACK field) if (!(nFlags & TCP_FLAG_ACK)) { return 1; } switch (m_State) { case TCPStateSynReceived: if (bwlh (m_nSND_UNA, nSEG_ACK, m_nSND_NXT)) { // RFC 1122 section 4.2.2.20 (f) m_nSND_WND = nSEG_WND; m_nSND_WL1 = nSEG_SEQ; m_nSND_WL2 = nSEG_ACK; m_nSND_UNA = nSEG_ACK; // got ACK for SYN m_RTOCalculator.SegmentAcknowledged (nSEG_ACK); NEW_STATE (TCPStateEstablished); // next transmission starts with this count m_nRetransmissionCount = MAX_RETRANSMISSIONS; } else { SendSegment (TCP_FLAG_RESET, nSEG_ACK); } break; case TCPStateEstablished: case TCPStateFinWait1: case TCPStateFinWait2: case TCPStateCloseWait: case TCPStateClosing: if (bwh (m_nSND_UNA, nSEG_ACK, m_nSND_NXT)) { m_RTOCalculator.SegmentAcknowledged (nSEG_ACK); unsigned nBytesAck = nSEG_ACK-m_nSND_UNA; m_nSND_UNA = nSEG_ACK; if (nSEG_ACK == m_nSND_NXT) // all segments are acknowledged { StopTimer (TCPTimerRetransmission); // next transmission starts with this count m_nRetransmissionCount = MAX_RETRANSMISSIONS; } if ( m_State == TCPStateFinWait1 || m_State == TCPStateClosing) { nBytesAck--; // acknowledged FIN does not count m_bFINQueued = FALSE; } if ( m_State == TCPStateEstablished && nBytesAck == 1) { nBytesAck--; } if (nBytesAck > 0) { m_RetransmissionQueue.Advance (nBytesAck); } // update send window if ( lt (m_nSND_WL1, nSEG_SEQ) || ( m_nSND_WL1 == nSEG_SEQ && le (m_nSND_WL2, nSEG_ACK))) { m_nSND_WND = nSEG_WND; m_nSND_WL1 = nSEG_SEQ; m_nSND_WL2 = nSEG_ACK; } } else if (le (nSEG_ACK, m_nSND_UNA)) // RFC 1122 section 4.2.2.20 (g) { // ignore duplicate ACK ... // RFC 1122 section 4.2.2.20 (g) if (bwlh (m_nSND_UNA, nSEG_ACK, m_nSND_NXT)) { // ... but update send window if ( lt (m_nSND_WL1, nSEG_SEQ) || ( m_nSND_WL1 == nSEG_SEQ && le (m_nSND_WL2, nSEG_ACK))) { m_nSND_WND = nSEG_WND; m_nSND_WL1 = nSEG_SEQ; m_nSND_WL2 = nSEG_ACK; } } } else if (gt (nSEG_ACK, m_nSND_NXT)) { SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); return 1; } switch (m_State) { case TCPStateEstablished: case TCPStateCloseWait: break; case TCPStateFinWait1: if (nSEG_ACK == m_nSND_NXT) // if our FIN is now acknowledged { m_RTOCalculator.SegmentAcknowledged (nSEG_ACK); m_bFINQueued = FALSE; StopTimer (TCPTimerRetransmission); NEW_STATE (TCPStateFinWait2); StartTimer (TCPTimerTimeWait, HZ_FIN_TIMEOUT); } else { break; } // fall through case TCPStateFinWait2: if (m_RetransmissionQueue.IsEmpty ()) { m_Event.Set (); } break; case TCPStateClosing: if (nSEG_ACK == m_nSND_NXT) // if our FIN is now acknowledged { m_RTOCalculator.SegmentAcknowledged (nSEG_ACK); m_bFINQueued = FALSE; StopTimer (TCPTimerRetransmission); NEW_STATE (TCPStateTimeWait); StartTimer (TCPTimerTimeWait, HZ_TIMEWAIT); } break; default: UNEXPECTED_STATE (); break; } break; case TCPStateLastAck: if (nSEG_ACK == m_nSND_NXT) // if our FIN is now acknowledged { m_bFINQueued = FALSE; NEW_STATE (TCPStateClosed); m_Event.Set (); return 1; } break; case TCPStateTimeWait: if (nSEG_ACK == m_nSND_NXT) // if our FIN is now acknowledged { m_bFINQueued = FALSE; SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); StartTimer (TCPTimerTimeWait, HZ_TIMEWAIT); } break; default: UNEXPECTED_STATE (); break; } // step 6 (check URG bit, not supported) StepSix: // step 7 (process text segment) if (nSEG_LEN == 0) { return 1; } switch (m_State) { case TCPStateEstablished: case TCPStateFinWait1: case TCPStateFinWait2: if (nSEG_SEQ == m_nRCV_NXT) { if (nDataLength > 0) { m_RxQueue.Enqueue ((u8 *) pPacket+nDataOffset, nDataLength); m_nRCV_NXT += nDataLength; // m_nRCV_WND should be adjusted here (section 3.7) // following ACK could be piggybacked with data SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); if (nFlags & TCP_FLAG_PUSH) { m_Event.Set (); } } } else { SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); return 1; } break; case TCPStateSynReceived: // this state not in RFC 793 case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: case TCPStateTimeWait: break; default: UNEXPECTED_STATE (); break; } // step 8 (check FIN bit) if ( m_State == TCPStateClosed || m_State == TCPStateListen || m_State == TCPStateSynSent) { return 1; } if (!(nFlags & TCP_FLAG_FIN)) { return 1; } // connection is closing m_nRCV_NXT++; SendSegment (TCP_FLAG_ACK, m_nSND_NXT, m_nRCV_NXT); switch (m_State) { case TCPStateSynReceived: case TCPStateEstablished: NEW_STATE (TCPStateCloseWait); m_Event.Set (); break; case TCPStateFinWait1: if (nSEG_ACK == m_nSND_NXT) // if our FIN is now acknowledged { m_bFINQueued = FALSE; StopTimer (TCPTimerRetransmission); StopTimer (TCPTimerUser); NEW_STATE (TCPStateTimeWait); StartTimer (TCPTimerTimeWait, HZ_TIMEWAIT); } else { NEW_STATE (TCPStateClosing); } break; case TCPStateFinWait2: StopTimer (TCPTimerRetransmission); StopTimer (TCPTimerUser); NEW_STATE (TCPStateTimeWait); StartTimer (TCPTimerTimeWait, HZ_TIMEWAIT); break; case TCPStateCloseWait: case TCPStateClosing: case TCPStateLastAck: break; case TCPStateTimeWait: StartTimer (TCPTimerTimeWait, HZ_TIMEWAIT); break; default: UNEXPECTED_STATE (); break; } break; } return 1; } int CTCPConnection::NotificationReceived (TICMPNotificationType Type, CIPAddress &rSenderIP, CIPAddress &rReceiverIP, u16 nSendPort, u16 nReceivePort, int nProtocol) { if (nProtocol != IPPROTO_TCP) { return 0; } if (m_State < TCPStateSynSent) { return 0; } if ( m_ForeignIP != rSenderIP || m_nForeignPort != nSendPort) { return 0; } assert (m_pNetConfig != 0); if ( rReceiverIP != *m_pNetConfig->GetIPAddress () || m_nOwnPort != nReceivePort) { return 0; } m_nErrno = -1; StopTimer (TCPTimerRetransmission); NEW_STATE (TCPStateTimeWait); StartTimer (TCPTimerTimeWait, HZ_TIMEWAIT); m_Event.Set (); return 1; } boolean CTCPConnection::SendSegment (unsigned nFlags, u32 nSequenceNumber, u32 nAcknowledgmentNumber, const void *pData, unsigned nDataLength) { unsigned nDataOffset = 5; assert (nDataOffset * 4 == sizeof (TTCPHeader)); if (nFlags & TCP_FLAG_SYN) { nDataOffset++; } unsigned nHeaderLength = nDataOffset * 4; unsigned nPacketLength = nHeaderLength + nDataLength; // may wrap assert (nPacketLength >= nHeaderLength); assert (nHeaderLength <= FRAME_BUFFER_SIZE); u8 TxBuffer[FRAME_BUFFER_SIZE]; TTCPHeader *pHeader = (TTCPHeader *) TxBuffer; pHeader->nSourcePort = le2be16 (m_nOwnPort); pHeader->nDestPort = le2be16 (m_nForeignPort); pHeader->nSequenceNumber = le2be32 (nSequenceNumber); pHeader->nAcknowledgmentNumber = nFlags & TCP_FLAG_ACK ? le2be32 (nAcknowledgmentNumber) : 0; pHeader->nDataOffsetFlags = (nDataOffset << TCP_DATA_OFFSET_SHIFT) | nFlags; pHeader->nWindow = le2be16 (m_nRCV_WND); pHeader->nUrgentPointer = le2be16 (m_nSND_UP); if (nFlags & TCP_FLAG_SYN) { TTCPOption *pOption = (TTCPOption *) pHeader->Options; pOption->nKind = TCP_OPTION_MSS; pOption->nLength = 4; pOption->Data[0] = TCP_CONFIG_MSS >> 8; pOption->Data[1] = TCP_CONFIG_MSS & 0xFF; } if (nDataLength > 0) { assert (pData != 0); memcpy (TxBuffer+nHeaderLength, pData, nDataLength); } pHeader->nChecksum = 0; // must be 0 for calculation pHeader->nChecksum = m_Checksum.Calculate (TxBuffer, nPacketLength); #ifdef TCP_DEBUG CLogger::Get ()->Write (FromTCP, LogDebug, "tx %c%c%c%c%c%c, seq %u, ack %u, win %u, len %u", nFlags & TCP_FLAG_URGENT ? 'U' : '-', nFlags & TCP_FLAG_ACK ? 'A' : '-', nFlags & TCP_FLAG_PUSH ? 'P' : '-', nFlags & TCP_FLAG_RESET ? 'R' : '-', nFlags & TCP_FLAG_SYN ? 'S' : '-', nFlags & TCP_FLAG_FIN ? 'F' : '-', nSequenceNumber-m_nISS, nFlags & TCP_FLAG_ACK ? nAcknowledgmentNumber-m_nIRS : 0, m_nRCV_WND, nDataLength); #endif assert (m_pNetworkLayer != 0); return m_pNetworkLayer->Send (m_ForeignIP, TxBuffer, nPacketLength, IPPROTO_TCP); } void CTCPConnection::ScanOptions (TTCPHeader *pHeader) { assert (pHeader != 0); unsigned nDataOffset = TCP_DATA_OFFSET (pHeader->nDataOffsetFlags)*4; u8 *pHeaderEnd = (u8 *) pHeader+nDataOffset; TTCPOption *pOption = (TTCPOption *) pHeader->Options; while ((u8 *) pOption+2 <= pHeaderEnd) { switch (pOption->nKind) { case TCP_OPTION_END_OF_LIST: return; case TCP_OPTION_NOP: pOption = (TTCPOption *) ((u8 *) pOption+1); break; case TCP_OPTION_MSS: if ( pOption->nLength == 4 && (u8 *) pOption+4 <= pHeaderEnd) { u32 nMSS = (u16) pOption->Data[0] << 8 | pOption->Data[1]; // RFC 1122 section 4.2.2.6 nMSS = min (nMSS+20, MSS_S) - TCP_HEADER_SIZE - IP_OPTION_SIZE; if (nMSS >= 10) // self provided sanity check { m_nSND_MSS = (u16) nMSS; } } // fall through default: pOption = (TTCPOption *) ((u8 *) pOption+pOption->nLength); break; } } } u32 CTCPConnection::CalculateISN (void) { assert (m_pTimer != 0); return ( m_pTimer->GetTime () * HZ + m_pTimer->GetTicks () % HZ) * (TCP_MAX_WINDOW / TCP_QUIET_TIME / HZ); } void CTCPConnection::StartTimer (unsigned nTimer, unsigned nHZ) { assert (nTimer < TCPTimerUnknown); assert (nHZ > 0); assert (m_pTimer != 0); StopTimer (nTimer); m_hTimer[nTimer] = m_pTimer->StartKernelTimer (nHZ, TimerStub, (void *) (uintptr) nTimer, this); } void CTCPConnection::StopTimer (unsigned nTimer) { assert (nTimer < TCPTimerUnknown); assert (m_pTimer != 0); m_TimerSpinLock.Acquire (); if (m_hTimer[nTimer] != 0) { m_pTimer->CancelKernelTimer (m_hTimer[nTimer]); m_hTimer[nTimer] = 0; } m_TimerSpinLock.Release (); } void CTCPConnection::TimerHandler (unsigned nTimer) { assert (nTimer < TCPTimerUnknown); m_TimerSpinLock.Acquire (); if (m_hTimer[nTimer] == 0) // timer was stopped in the meantime { m_TimerSpinLock.Release (); return; } m_hTimer[nTimer] = 0; m_TimerSpinLock.Release (); switch (nTimer) { case TCPTimerRetransmission: m_RTOCalculator.RetransmissionTimerExpired (); if (m_nRetransmissionCount-- == 0) { m_bTimedOut = TRUE; break; } switch (m_State) { case TCPStateClosed: case TCPStateListen: case TCPStateFinWait2: case TCPStateTimeWait: UNEXPECTED_STATE (); break; case TCPStateSynSent: case TCPStateSynReceived: assert (!m_bSendSYN); m_bSendSYN = TRUE; break; case TCPStateEstablished: case TCPStateCloseWait: assert (!m_bRetransmit); m_bRetransmit = TRUE; break; case TCPStateFinWait1: case TCPStateClosing: case TCPStateLastAck: assert (!m_bFINQueued); m_bFINQueued = TRUE; break; } break; case TCPTimerTimeWait: NEW_STATE (TCPStateClosed); break; case TCPTimerUser: case TCPTimerUnknown: assert (0); break; } } void CTCPConnection::TimerStub (TKernelTimerHandle hTimer, void *pParam, void *pContext) { CTCPConnection *pThis = (CTCPConnection *) pContext; assert (pThis != 0); unsigned nTimer = (unsigned) (uintptr) pParam; assert (nTimer < TCPTimerUnknown); pThis->TimerHandler (nTimer); } #ifndef NDEBUG void CTCPConnection::DumpStatus (void) { CLogger::Get ()->Write (FromTCP, LogDebug, "sta %u, una %u, snx %u, swn %u, rnx %u, rwn %u, fprt %u", m_State, m_nSND_UNA-m_nISS, m_nSND_NXT-m_nISS, m_nSND_WND, m_nRCV_NXT-m_nIRS, m_nRCV_WND, (unsigned) m_nForeignPort); } TTCPState CTCPConnection::NewState (TTCPState State, unsigned nLine) { const static char *StateName[] = // must match TTCPState { "CLOSED", "LISTEN", "SYN-SENT", "SYN-RECEIVED", "ESTABLISHED", "FIN-WAIT-1", "FIN-WAIT-2", "CLOSE-WAIT", "CLOSING", "LAST-ACK", "TIME-WAIT" }; assert (m_State < sizeof StateName / sizeof StateName[0]); assert (State < sizeof StateName / sizeof StateName[0]); CLogger::Get ()->Write (FromTCP, LogDebug, "State %s -> %s at line %u", StateName[m_State], StateName[State], nLine); return m_State = State; } void CTCPConnection::UnexpectedState (unsigned nLine) { DumpStatus (); CLogger::Get ()->Write (FromTCP, LogPanic, "Unexpected state %u at line %u", m_State, nLine); } #endif
rsta2/circle
lib/net/tcpconnection.cpp
C++
gpl-3.0
34,730
# Controller generated by Typus, use it to extend admin functionality. class Admin::UserInterestsController < Admin::MasterController =begin ## # You can overwrite and extend Admin::MasterController with your methods. # # Actions have to be defined in <tt>config/typus/application.yml</tt>: # # UserInterest: # actions: # index: custom_action # edit: custom_action_for_an_item # # And you have to add permissions on <tt>config/typus/application_roles.yml</tt> # to have access to them. # # admin: # UserInterest: create, read, update, destroy, custom_action # # editor: # UserInterest: create, read, update, custom_action_for_an_item # def index end def custom_action end def custom_action_for_an_item end =end end
adamklawonn/CityCircles
app/controllers/admin/user_interests_controller.rb
Ruby
gpl-3.0
802
#include "template_components.h" #include <QtGui/QSpacerItem> TemplateComponents::TemplateComponents(const QSharedPointer<const Template>& templ, QWidget *parent) : QWidget(parent), templ(templ) { ui.setupUi(this); QList<FoodComponent> components = templ->getComponents(); for (QList<FoodComponent>::iterator i = components.begin(); i != components.end(); ++i) { componentWidgetGroups.append(ComponentWidgetGroup(i->getFoodAmount(), this)); } ui.componentLayout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding), ui.componentLayout->rowCount(), 0); } TemplateComponents::~TemplateComponents() { } QSharedPointer<FoodCollection> TemplateComponents::getCollection() const { QSharedPointer<FoodCollection> collection = FoodCollection::createFoodCollection(templ->getDisplayName()); for (QList<ComponentWidgetGroup>::const_iterator i = componentWidgetGroups.begin(); i != componentWidgetGroups.end(); ++i) { collection->addComponent(i->getFoodAmount()); } return collection; } TemplateComponents::ComponentWidgetGroup::ComponentWidgetGroup (FoodAmount foodAmount, TemplateComponents* parent) : food(foodAmount.getFood()), lblFoodName(new QLabel(parent)), txtAmount(new QLineEdit(parent)), cbUnit(new QComboBox(parent)), chkIncludeRefuse(new QCheckBox(parent)) { int row = parent->ui.componentLayout->rowCount(); parent->ui.componentLayout->addWidget(lblFoodName, row, 0); parent->ui.componentLayout->addWidget(txtAmount, row, 1); parent->ui.componentLayout->addWidget(cbUnit, row, 2); parent->ui.componentLayout->addWidget(chkIncludeRefuse, row, 3); lblFoodName->setText(food->getDisplayName()); lblFoodName->setWordWrap(true); txtAmount->setText(QString::number(foodAmount.getAmount())); txtAmount->setMinimumWidth(50); txtAmount->setMaximumWidth(80); txtAmount->setAlignment(Qt::AlignRight); QMap<QString, QSharedPointer<const Unit> > unitsToShow; QList<Unit::Dimensions::Dimension> validDimensions = food->getValidDimensions(); for (QList<Unit::Dimensions::Dimension>::const_iterator i = validDimensions.begin(); i != validDimensions.end(); ++i) { QVector<QSharedPointer<const Unit> > units = Unit::getAllUnits(*i); for (QVector<QSharedPointer<const Unit> >::const_iterator i = units.begin(); i != units.end(); ++i) { unitsToShow.insert((*i)->getName(), *i); } } for (QMap<QString, QSharedPointer<const Unit> >::iterator i = unitsToShow.begin(); i != unitsToShow.end(); ++i) { cbUnit->addItem(i.value()->getNameAndAbbreviation(), i.value()->getAbbreviation()); } cbUnit->setCurrentIndex(cbUnit->findData(foodAmount.getUnit()->getAbbreviation())); chkIncludeRefuse->setText("Including inedible parts"); chkIncludeRefuse->setChecked (foodAmount.includesRefuse() && foodAmount.getFood()->getPercentRefuse() > 0); chkIncludeRefuse->setEnabled(foodAmount.getFood()->getPercentRefuse() > 0); } FoodAmount TemplateComponents::ComponentWidgetGroup::getFoodAmount() const { return FoodAmount(food, txtAmount->text().toDouble(), Unit::getUnit(cbUnit->itemData(cbUnit->currentIndex()).toString()), !chkIncludeRefuse->isEnabled() || chkIncludeRefuse->isChecked()); }
tylermchenry/nutrition_tracker
application/src/widgets/template_components.cpp
C++
gpl-3.0
3,460
/* * Copyright (c) 2014-2016 Alex Spataru <[email protected]> * * This file is part of the QSimpleUpdater library, which is released under * the DBAD license, you can read a copy of it below: * * DON'T BE A DICK PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, * DISTRIBUTION AND MODIFICATION: * * Do whatever you like with the original work, just don't be a dick. * Being a dick includes - but is not limited to - the following instances: * * 1a. Outright copyright infringement - Don't just copy this and change the * name. * 1b. Selling the unmodified original with no work done what-so-ever, that's * REALLY being a dick. * 1c. Modifying the original work to contain hidden harmful content. * That would make you a PROPER dick. * * If you become rich through modifications, related works/services, or * supporting the original work, share the love. * Only a dick would make loads off this work and not buy the original works * creator(s) a pint. * * Code is provided with no warranty. Using somebody else's code and bitching * when it goes wrong makes you a DONKEY dick. * Fix the problem yourself. A non-dick would submit the fix back. */ #ifndef _QSIMPLEUPDATER_MAIN_H #define _QSIMPLEUPDATER_MAIN_H #include <QUrl> #include <QList> #include <QObject> #if defined (QSU_SHARED) #define QSU_DECL Q_DECL_EXPORT #elif defined (QSU_IMPORT) #define QSU_DECL Q_DECL_IMPORT #else #define QSU_DECL #endif class Updater; /** * \brief Manages the updater instances * * The \c QSimpleUpdater class manages the updater system and allows for * parallel application modules to check for updates and download them. * * The behavior of each updater can be regulated by specifying the update * definitions URL (from where we download the individual update definitions) * and defining the desired options by calling the individual "setter" * functions (e.g. \c setNotifyOnUpdate()). * * The \c QSimpleUpdater also implements an integrated downloader. * If you need to use a custom install procedure/code, just create a function * that is called when the \c downloadFinished() signal is emitted to * implement your own install procedures. * * By default, the downloader will try to open the file as if you opened it * from a file manager or a web browser (with the "file:*" url). */ class QSU_DECL QSimpleUpdater : public QObject { Q_OBJECT signals: void checkingFinished (const QString& url); void appcastDownloaded (const QString& url, const QByteArray& data); void downloadFinished (const QString& url, const QString& filepath); void installerOpened(); void updateDeclined(); public: static QSimpleUpdater* getInstance(); bool usesCustomAppcast (const QString& url) const; bool getNotifyOnUpdate (const QString& url) const; bool getNotifyOnFinish (const QString& url) const; bool getUpdateAvailable (const QString& url) const; bool getDownloaderEnabled (const QString& url) const; bool usesCustomInstallProcedures (const QString& url) const; QString getOpenUrl (const QString& url) const; QString getChangelog (const QString& url) const; QString getModuleName (const QString& url) const; QString getDownloadUrl (const QString& url) const; QString getPlatformKey (const QString& url) const; QString getLatestVersion (const QString& url) const; QString getModuleVersion (const QString& url) const; public slots: void checkForUpdates (const QString& url); void setModuleName (const QString& url, const QString& name); void setNotifyOnUpdate (const QString& url, const bool notify); void setNotifyOnFinish (const QString& url, const bool notify); void setPlatformKey (const QString& url, const QString& platform); void setModuleVersion (const QString& url, const QString& version); void setDownloaderEnabled (const QString& url, const bool enabled); void setUseCustomAppcast (const QString& url, const bool customAppcast); void setUseCustomInstallProcedures (const QString& url, const bool custom); protected: ~QSimpleUpdater(); private: Updater* getUpdater (const QString& url) const; }; #endif
cbpeckles/PXMessenger
include/QSimpleUpdater/include/QSimpleUpdater.h
C
gpl-3.0
4,307
/* ------------------------------------------------------------------------------- This file is part of the weather information collector. Copyright (C) 2018, 2019, 2020, 2021 Dirk Stolle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------------- */ #include <iostream> #include <string> #include <utility> #include "../conf/Configuration.hpp" #include "../db/mariadb/SourceMariaDB.hpp" #include "../db/mariadb/StoreMariaDB.hpp" #include "../db/mariadb/StoreMariaDBBatch.hpp" #include "../db/mariadb/Utilities.hpp" #include "../db/mariadb/client_version.hpp" #include "../db/mariadb/guess.hpp" #include "../util/SemVer.hpp" #include "../util/Strings.hpp" #include "../ReturnCodes.hpp" #include "../Version.hpp" const int defaultBatchSize = 40; void showHelp() { std::cout << "weather-information-collector-synchronizer [OPTIONS]\n" << "\n" << "Synchronizes data between two collector databases.\n" << "\n" << "options:\n" << " -? | --help - shows this help message\n" << " -v | --version - shows version information\n" << " -c1 FILE | --src-conf FILE\n" << " - sets the file name of the configuration file that\n" << " contains the database connection settings for the\n" << " source database.\n" << " -c2 FILE | --dest-conf FILE\n" << " - sets the file name of the configuration file that\n" << " contains the database connection settings for the\n" << " destination database.\n" << " -b N | --batch-size N - sets the number of records per batch insert to N.\n" << " Higher numbers mean increased performance, but it\n" << " could also result in hitting MySQL's limit for the\n" << " maximum packet size, called max_allowed_packet.\n" << " Defaults to " << defaultBatchSize << ", if no value is given.\n" << " --skip-update-check - skips the check to determine whether the databases\n" << " are up to date during program startup.\n"; } bool isLess(const wic::WeatherMeta& lhs, const wic::Weather& rhs) { return (lhs.dataTime() < rhs.dataTime()) || ((lhs.dataTime() == rhs.dataTime()) && (lhs.requestTime() < rhs.requestTime())); } bool isLess(const wic::ForecastMeta& lhs, const wic::Forecast& rhs) { return (lhs.requestTime() < rhs.requestTime()); } std::pair<int, bool> parseArguments(const int argc, char** argv, std::string& srcConfigurationFile, std::string& destConfigurationFile, int& batchSize, bool& skipUpdateCheck) { if ((argc <= 1) || (argv == nullptr)) return std::make_pair(0, false); for (int i = 1; i < argc; ++i) { if (argv[i] == nullptr) { std::cerr << "Error: Parameter at index " << i << " is null pointer!\n"; return std::make_pair(wic::rcInvalidParameter, true); } const std::string param(argv[i]); if ((param == "-v") || (param == "--version")) { wic::showVersion("weather-information-collector-synchronizer"); showMariaDbClientVersion(); return std::make_pair(0, true); } // if version else if ((param == "-?") || (param == "/?") || (param == "--help")) { showHelp(); return std::make_pair(0, true); } // if help else if ((param == "--src-conf") || (param == "-c1")) { if (!srcConfigurationFile.empty()) { std::cerr << "Error: Source configuration was already set to " << srcConfigurationFile << "!" << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } // enough parameters? if ((i+1 < argc) && (argv[i+1] != nullptr)) { srcConfigurationFile = std::string(argv[i+1]); // Skip next parameter, because it's already used as file path. ++i; } else { std::cerr << "Error: You have to enter a file path after \"" << param << "\"." << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } } // if source configuration file else if ((param == "--dest-conf") || (param == "-c2")) { if (!destConfigurationFile.empty()) { std::cerr << "Error: Destination configuration was already set to " << destConfigurationFile << "!" << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } // enough parameters? if ((i+1 < argc) && (argv[i+1] != nullptr)) { destConfigurationFile = std::string(argv[i+1]); // Skip next parameter, because it's already used as file path. ++i; } else { std::cerr << "Error: You have to enter a file path after \"" << param << "\"." << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } } // if destination configuration file else if ((param == "--batch-size") || (param == "-b")) { if (batchSize >= 0) { std::cerr << "Error: Batch size was already set to " << batchSize << "!" << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } // enough parameters? if ((i+1 < argc) && (argv[i+1] != nullptr)) { const std::string bsString = std::string(argv[i+1]); if (!wic::stringToInt(bsString, batchSize) || (batchSize <= 0)) { std::cerr << "Error: Batch size must be a positive integer!" << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } if (batchSize > 1000) { std::cout << "Info: Batch size " << batchSize << " will be reduced " << " to 1000, because too large batch sizes might cause " << "the database server to reject inserts." << std::endl; batchSize = 1000; } // Skip next parameter, because it's already used as batch size. ++i; } else { std::cerr << "Error: You have to enter a number after \"" << param << "\"." << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } } // if batch size else if ((param == "--skip-update-check") || (param == "--no-update-check")) { if (skipUpdateCheck) { std::cerr << "Error: Parameter " << param << " was already specified!" << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } skipUpdateCheck = true; } // if database update check shall be skipped else { std::cerr << "Error: Unknown parameter " << param << "!\n" << "Use --help to show available parameters." << std::endl; return std::make_pair(wic::rcInvalidParameter, true); } } // for i return std::make_pair(0, false); } int main(int argc, char** argv) { std::string srcConfigurationFile; /**< path of configuration file for source */ std::string destConfigurationFile; /**< path of configuration file for destination */ int batchSize = -1; /**< number of records per batch insert */ bool skipUpdateCheck = false; /**< whether to skip check for up to date DB */ const auto [exitCode, forceExit] = parseArguments(argc, argv, srcConfigurationFile, destConfigurationFile, batchSize, skipUpdateCheck); if (forceExit || (exitCode != 0)) return exitCode; if (srcConfigurationFile.empty()) { std::cerr << "Error: No source configuration file was specified!" << std::endl; return wic::rcInvalidParameter; } if (destConfigurationFile.empty()) { std::cerr << "Error: No destination configuration file was specified!" << std::endl; return wic::rcInvalidParameter; } // load source configuration file wic::Configuration srcConfig; if (!srcConfig.load(srcConfigurationFile, true, true)) { std::cerr << "Error: Could not load source configuration!" << std::endl; return wic::rcConfigurationError; } // load destination configuration file wic::Configuration destConfig; if (!destConfig.load(destConfigurationFile, true, true)) { std::cerr << "Error: Could not load destination configuration!" << std::endl; return wic::rcConfigurationError; } // Check that synchronization happens between different databases. const auto& srcDb = srcConfig.connectionInfo(); const auto& destDb = destConfig.connectionInfo(); if (srcDb.port() == destDb.port() && srcDb.db() == destDb.db() && wic::toLowerString(srcDb.hostname()) == wic::toLowerString(destDb.hostname())) { std::cerr << "Error: Source and destination databases are identical!" << std::endl; return wic::rcConfigurationError; } // If there is no batch size, use the default value. if (batchSize < 0) { std::cout << "Info: Using default batch size value of " << defaultBatchSize << "." << std::endl; batchSize = defaultBatchSize; } // Check whether databases are up to date. if (!skipUpdateCheck) { for (const wic::Configuration& config : { srcConfig, destConfig }) { const wic::SemVer currentVersion = wic::guessVersionFromDatabase(config.connectionInfo()); if (wic::SemVer() == currentVersion) { // Some database error must have occurred, so quit right here. std::cerr << "Error: Could not check version of database!" << std::endl; return wic::rcDatabaseError; } if (currentVersion < wic::mostUpToDateVersion) { const auto& ci = config.connectionInfo(); std::cerr << "Error: The database " << ci.db() << " at " << ci.hostname() << ":" << ci.port() << " seems to be from an older version of" << " weather-information-collector. Please run " << "weather-information-collector-update to update the database." << std::endl; std::cerr << "If this is wrong and you want to skip that check instead," << " then call this program with the parameter --skip-update-check." << " Be warned that this may result in incomplete data being " << "written to the destination database though." << std::endl; return wic::rcDatabaseError; } } // for } // if update check shall be performed else { // Give a warning to the user, so nobody can say "But why did nobody tell // me about these possible problems there?" std::cout << "Warning: Check whether the databases are up to date has been" << " skipped, as requested by user. This could possibly result" << " in incomplete data being written to the destination database" << " as well as other database errors. Only use this if you are " << " certain that both databases are up to date." << std::endl; } // else // Get list of location-API pairs that need to be synchronized. wic::SourceMariaDB dataSource = wic::SourceMariaDB(srcConfig.connectionInfo()); std::vector<std::pair<wic::Location, wic::ApiType> > locations; if (!dataSource.listWeatherLocationsWithApi(locations)) { std::cerr << "Error: Could not load locations from source database!" << std::endl; return wic::rcDatabaseError; } std::cout << "Found " << locations.size() << " locations with weather data in the database." << std::endl; for(const auto& [location, api] : locations) { std::cout << "\t" << location.toString() << ", " << wic::toString(api) << std::endl; } // for // Get available APIs in destination database. wic::SourceMariaDB dataDest = wic::SourceMariaDB(destConfig.connectionInfo()); std::map<wic::ApiType, int> apis; if (!dataDest.listApis(apis)) { std::cerr << "Error: Could not load API information from destination database!" << std::endl; return wic::rcDatabaseError; } // connection to destination database try { wic::db::mariadb::Connection conn(destConfig.connectionInfo()); std::clog << "Info: Connection attempt to destination database succeeded." << std::endl; } catch (const std::exception& ex) { std::cerr << "Could not connect to destination database: " << ex.what() << "\n"; return wic::rcDatabaseError; } // scope for synchronization of weather data { wic::StoreMariaDBBatch destinationStore(destConfig.connectionInfo(), batchSize); for(const auto& [location, api] : locations) { std::cout << "Synchronizing weather data for " << location.toString() << ", " << wic::toString(api) << "..." << std::endl; if (apis.find(api) == apis.end()) { std::cerr << "Error: Destination database has no API entry for " << wic::toString(api) << "!" << std::endl; return wic::rcDatabaseError; } const int apiId = apis[api]; std::vector<wic::Weather> sourceWeather; if (!dataSource.getCurrentWeather(api, location, sourceWeather)) { std::cerr << "Error: Could not load weather data for " << location.toString() << ", " << wic::toString(api) << " from source database!" << std::endl; return wic::rcDatabaseError; } // Get corresponding location ID in destination database. // If it does not exist, it will be created. const int locationId = dataDest.getLocationId(location); if (locationId <= 0) { std::cerr << "Error: Could find or create location " << location.toString() << ", " << wic::toString(api) << " in destination database!" << std::endl; return wic::rcDatabaseError; } // Get existing entries in destination database. std::vector<wic::WeatherMeta> destinationWeatherMeta; if (!dataDest.getMetaCurrentWeather(api, location, destinationWeatherMeta)) { std::cerr << "Error: Could not load weather data for " << location.toString() << ", " << wic::toString(api) << " from destination database!" << std::endl; return wic::rcDatabaseError; } // Iterate over data. auto sourceIterator = sourceWeather.begin(); const auto sourceEnd = sourceWeather.end(); auto destinationIterator = destinationWeatherMeta.begin(); const auto destinationEnd = destinationWeatherMeta.end(); while (sourceIterator != sourceEnd) { while (destinationIterator != destinationEnd && isLess(*destinationIterator, *sourceIterator)) { ++destinationIterator; } // while (inner) // Element was not found in destination, if we are at the end of the // container or if the dereferenced iterator is not equal to the source. if ((destinationIterator == destinationEnd) || (destinationIterator->dataTime() != sourceIterator->dataTime()) || (destinationIterator->requestTime() != sourceIterator->requestTime())) { // Insert data set. if (!destinationStore.saveCurrentWeather(apiId, locationId, *sourceIterator)) { std::cerr << "Error: Could insert weather data into destination database!" << std::endl; return wic::rcDatabaseError; } } // if ++sourceIterator; } // while } // range-based for (locations) } // scope for weather data sync // synchronize forecast data { if (!dataSource.listForecastLocationsWithApi(locations)) { std::cerr << "Error: Could not load locations from source database!" << std::endl; return wic::rcDatabaseError; } std::cout << "Found " << locations.size() << " locations with forecast data in the database." << std::endl; for(const auto& [location, api] : locations) { std::cout << "\t" << location.toString() << ", " << wic::toString(api) << std::endl; } // for for(const auto& [location, api] : locations) { std::cout << "Synchronizing forecast data for " << location.toString() << ", " << wic::toString(api) << "..." << std::endl; std::vector<wic::Forecast> sourceForecast; if (!dataSource.getForecasts(api, location, sourceForecast)) { std::cerr << "Error: Could not load forecast data for " << location.toString() << ", " << wic::toString(api) << " from source database!" << std::endl; return wic::rcDatabaseError; } // Get existing entries in destination database. std::vector<wic::ForecastMeta> destinationForecastMeta; if (!dataDest.getMetaForecasts(api, location, destinationForecastMeta)) { std::cerr << "Error: Could not load forecast data for " << location.toString() << ", " << wic::toString(api) << " from destination database!" << std::endl; return wic::rcDatabaseError; } wic::StoreMariaDB destinationStore = wic::StoreMariaDB(destConfig.connectionInfo()); // Iterate over data. auto sourceIterator = sourceForecast.begin(); const auto sourceEnd = sourceForecast.end(); auto destinationIterator = destinationForecastMeta.begin(); const auto destinationEnd = destinationForecastMeta.end(); while (sourceIterator != sourceEnd) { while (destinationIterator != destinationEnd && isLess(*destinationIterator, *sourceIterator)) { ++destinationIterator; } // while (inner) // Element was not found in destination, if we are at the end of the // container or if the dereferenced iterator is not equal to the source. if ((destinationIterator == destinationEnd) || (destinationIterator->requestTime() != sourceIterator->requestTime())) { // Insert data set. if (!destinationStore.saveForecast(api, location, *sourceIterator)) { std::cerr << "Error: Could insert forecast data into destination database!" << std::endl; return wic::rcDatabaseError; } } // if ++sourceIterator; } // while } // for (locations) } // scope for forecast data sync // All is done. std::cout << "Done." << std::endl; return 0; }
striezel/weather-information-collector
src/synchronizer/main.cpp
C++
gpl-3.0
19,214
#define BOOST_TEST_MODULE segmentize tests #include <boost/test/unit_test.hpp> #include <ostream> #include "segmentize.hpp" #include "bg_operators.hpp" using namespace std; BOOST_AUTO_TEST_SUITE(segmentize_tests) void print_result(const vector<std::pair<linestring_type_fp, bool>>& result) { cout << result; } BOOST_AUTO_TEST_CASE(abuts) { vector<pair<linestring_type_fp, bool>> ms = { {{{0,0}, {2,2}}, true}, {{{1,1}, {2,0}}, true}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 3UL); } BOOST_AUTO_TEST_CASE(x_shape) { vector<pair<linestring_type_fp, bool>> ms = { {{{0,10000}, {10000,9000}}, true}, {{{10000,10000}, {0,0}}, true}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 4UL); } BOOST_AUTO_TEST_CASE(plus_shape) { vector<pair<linestring_type_fp, bool>> ms = { {{{1,2}, {3,2}}, true}, {{{2,1}, {2,3}}, true}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 4UL); } BOOST_AUTO_TEST_CASE(touching_no_overlap) { vector<pair<linestring_type_fp, bool>> ms = { {{{1,20}, {40,50}}, true}, {{{40,50}, {80,90}}, true}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 2UL); } BOOST_AUTO_TEST_CASE(parallel_with_overlap) { vector<pair<linestring_type_fp, bool>> ms = { {{{10,10}, {0,0}}, false}, {{{9,9}, {20,20}}, true}, {{{30,30}, {15,15}}, true}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 7UL); //print_result(result); } BOOST_AUTO_TEST_CASE(parallel_with_overlap_directed) { vector<pair<linestring_type_fp, bool>> ms = { {{{10,10}, {0,0}}, true}, {{{9,9}, {20,20}}, false}, {{{30,30}, {15,15}}, false}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 7UL); //print_result(result); } BOOST_AUTO_TEST_CASE(sort_segments) { vector<pair<linestring_type_fp, bool>> ms = { {{{10,10}, {13,-4}}, true}, {{{13,-4}, {10,10}}, true}, {{{13,-4}, {10,10}}, true}, {{{10, 10}, {13, -4}}, true}, {{{10, 10}, {13, -4}}, true}, }; const auto& result = segmentize::segmentize_paths(ms); BOOST_CHECK_EQUAL(result.size(), 5UL); //print_result(result); } BOOST_AUTO_TEST_SUITE_END()
pcb2gcode/pcb2gcode
segmentize_tests.cpp
C++
gpl-3.0
2,382
<?php /** * Simple product add to cart * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ global $woocommerce, $product; if ( ! $product->is_purchasable() ) return; ?> <?php // Availability $availability = $product->get_availability(); if ($availability['availability']) : echo apply_filters( 'woocommerce_stock_html', '<p class="stock '.$availability['class'].'">'.$availability['availability'].'</p>', $availability['availability'] ); endif; ?> <?php if ( $product->is_in_stock() && is_shop_enabled() ) : ?> <?php do_action('woocommerce_before_add_to_cart_form'); ?> <form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="cart" method="post" enctype='multipart/form-data'> <?php do_action('woocommerce_before_add_to_cart_button'); ?> <?php if ( ! $product->is_sold_individually() ){ ?><label><?php _e( 'Quantity', 'yit' ) ?></label><?php woocommerce_quantity_input( array( 'min_value' => apply_filters( 'woocommerce_quantity_input_min', 1, $product ), 'max_value' => apply_filters( 'woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product ) ) ); } $label = apply_filters( 'single_simple_add_to_cart_text', yit_get_option( 'add-to-cart-text' ) ); ?> <button type="submit" class="single_add_to_cart_button button alt"><?php echo $label ?></button> <?php do_action('woocommerce_after_add_to_cart_button'); ?> </form> <?php do_action('woocommerce_after_add_to_cart_form'); ?> <?php endif; ?>
zgomotos/Bazar
woocommerce/single-product/add-to-cart/simple.php
PHP
gpl-3.0
1,617
#include <stdio.h> #include "aeb.h" #include <string.h> #include <math.h> int main() { Aeb * raiz, *esq, * dir; Aeb * arvore; double r; char s[127]; /*arvore = criaRaiz('*'); esq = criaFolha(10.0); dir = criaFolha(7.0); conectaNodos(arvore, esq, dir); raiz = criaRaiz('+'); dir = criaFolha(8.0); conectaNodos(raiz, arvore, dir); printf("Resultado: %g\n", resolveExpressao(raiz));*/ printf("\nExpressão: "); scanf("%s",s); arvore = criaArvore(s); printf("Expressão após conversão: "); mostraArvore(arvore); puts(""); r=resolveExpressao(arvore); printf("\nO resultado é= %g\n",r); }
EltonBroering/Programacao_C
Projeto7/teste.c
C
gpl-3.0
636
/** * dfs 找 LCA. 只有一次查询,所以不需要 tarjan 或者 rmq * 个人感觉 rmq 好理解一些,dfs标号一下然后转化成区间最小值。( u v 之间最短路径上深度最小的节点) */ using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *dfs(TreeNode *root, TreeNode* p, TreeNode *q) { if(!root) return NULL; if(root == p) return root; if(root == q) return root; TreeNode *u = dfs(root->left, p, q); TreeNode *v = dfs(root->right, p, q); if(u == NULL) { u = v; v = NULL; } if(v) return root; return u; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { return dfs(root, p, q); } };
ShengRang/c4f
leetcode/lowest-common-ancestor-of-a-binary-tree.cc
C++
gpl-3.0
998
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using NFluent; using SmallWorld.BusinessEntities.Football.DeedDetectors; using SmallWorld.BusinessEntities.Interfaces.Football.Agents; namespace SmallWorld.BusinessEntities.UnitTests.Football.DeedDetectors { [TestClass] public class MoveDetectorTest { [TestMethod] public void When_Detect_Then_Return_MoveDeed_For_All_SensedPlayer_With_Origin_As_Origin() { var moveDetector = new MoveDetector(); var origin = new Mock<IFootballPlayer>(); var playerOne = new Mock<IFootballPlayer>(); var playerTwo = new Mock<IFootballPlayer>(); var sensedPlayers = new List<IFootballPlayer> { playerOne.Object, playerTwo.Object }; var result = moveDetector.Detect(origin.Object, sensedPlayers); foreach (var tmpFootballDeed in result) { Check.That(tmpFootballDeed.Player).IsSameReferenceThan(origin.Object); } } } }
cerobe/SmallWorld
Tests/SmallWorld.BusinessEntities.UnitTests/Football/DeedDetectors/MoveDetectorTest.cs
C#
gpl-3.0
1,136
/* * Symphony - A modern community (forum/SNS/blog) platform written in Java. * Copyright (C) 2012-2017, b3log.org & hacpai.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.b3log.symphony.service; import java.util.List; import java.util.Locale; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Keys; import org.b3log.latke.event.Event; import org.b3log.latke.event.EventException; import org.b3log.latke.event.EventManager; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.User; import org.b3log.latke.repository.RepositoryException; import org.b3log.latke.repository.Transaction; import org.b3log.latke.repository.annotation.Transactional; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.annotation.Service; import org.b3log.latke.util.Ids; import org.b3log.symphony.event.EventTypes; import org.b3log.symphony.model.Article; import org.b3log.symphony.model.Comment; import org.b3log.symphony.model.Common; import org.b3log.symphony.model.Liveness; import org.b3log.symphony.model.Notification; import org.b3log.symphony.model.Option; import org.b3log.symphony.model.Pointtransfer; import org.b3log.symphony.model.Reward; import org.b3log.symphony.model.Role; import org.b3log.symphony.model.Tag; import org.b3log.symphony.model.UserExt; import org.b3log.symphony.repository.ArticleRepository; import org.b3log.symphony.repository.CommentRepository; import org.b3log.symphony.repository.NotificationRepository; import org.b3log.symphony.repository.OptionRepository; import org.b3log.symphony.repository.TagArticleRepository; import org.b3log.symphony.repository.TagRepository; import org.b3log.symphony.repository.UserRepository; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.Symphonys; import org.json.JSONObject; /** * Comment management service. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 2.12.10.19, Feb 2, 2017 * @since 0.2.0 */ @Service public class CommentMgmtService { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(CommentMgmtService.class.getName()); /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Tag repository. */ @Inject private TagRepository tagRepository; /** * Tag-Article repository. */ @Inject private TagArticleRepository tagArticleRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * Notification repository. */ @Inject private NotificationRepository notificationRepository; /** * Event manager. */ @Inject private EventManager eventManager; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Pointtransfer management service. */ @Inject private PointtransferMgmtService pointtransferMgmtService; /** * Reward management service. */ @Inject private RewardMgmtService rewardMgmtService; /** * Reward query service. */ @Inject private RewardQueryService rewardQueryService; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Liveness management service. */ @Inject private LivenessMgmtService livenessMgmtService; /** * Removes a comment specified with the given comment id. * * @param commentId the given comment id */ @Transactional public void removeComment(final String commentId) { try { final JSONObject comment = commentRepository.get(commentId); if (null == comment) { return; } final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID); final JSONObject article = articleRepository.get(articleId); article.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT) - 1); // Just clear latest time and commenter name, do not get the real latest comment to update article.put(Article.ARTICLE_LATEST_CMT_TIME, 0); article.put(Article.ARTICLE_LATEST_CMTER_NAME, ""); articleRepository.update(articleId, article); final String commentAuthorId = comment.optString(Comment.COMMENT_AUTHOR_ID); final JSONObject commenter = userRepository.get(commentAuthorId); commenter.put(UserExt.USER_COMMENT_COUNT, commenter.optInt(UserExt.USER_COMMENT_COUNT) - 1); userRepository.update(commentAuthorId, commenter); commentRepository.remove(comment.optString(Keys.OBJECT_ID)); final JSONObject commentCntOption = optionRepository.get(Option.ID_C_STATISTIC_CMT_COUNT); commentCntOption.put(Option.OPTION_VALUE, commentCntOption.optInt(Option.OPTION_VALUE) - 1); optionRepository.update(Option.ID_C_STATISTIC_CMT_COUNT, commentCntOption); notificationRepository.removeByDataId(commentId); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Removes a comment error [id=" + commentId + "]", e); } } /** * A user specified by the given sender id thanks the author of a comment specified by the given comment id. * * @param commentId the given comment id * @param senderId the given sender id * @throws ServiceException service exception */ public void thankComment(final String commentId, final String senderId) throws ServiceException { try { final JSONObject comment = commentRepository.get(commentId); if (null == comment) { return; } if (Comment.COMMENT_STATUS_C_INVALID == comment.optInt(Comment.COMMENT_STATUS)) { return; } final JSONObject sender = userRepository.get(senderId); if (null == sender) { return; } if (UserExt.USER_STATUS_C_VALID != sender.optInt(UserExt.USER_STATUS)) { return; } final String receiverId = comment.optString(Comment.COMMENT_AUTHOR_ID); final JSONObject receiver = userRepository.get(receiverId); if (null == receiver) { return; } if (UserExt.USER_STATUS_C_VALID != receiver.optInt(UserExt.USER_STATUS)) { return; } if (receiverId.equals(senderId)) { throw new ServiceException(langPropsService.get("thankSelfLabel")); } final int rewardPoint = Symphonys.getInt("pointThankComment"); if (rewardQueryService.isRewarded(senderId, commentId, Reward.TYPE_C_COMMENT)) { return; } final String rewardId = Ids.genTimeMillisId(); if (Comment.COMMENT_ANONYMOUS_C_PUBLIC == comment.optInt(Comment.COMMENT_ANONYMOUS)) { final boolean succ = null != pointtransferMgmtService.transfer(senderId, receiverId, Pointtransfer.TRANSFER_TYPE_C_COMMENT_REWARD, rewardPoint, rewardId, System.currentTimeMillis()); if (!succ) { throw new ServiceException(langPropsService.get("transferFailLabel")); } } final JSONObject reward = new JSONObject(); reward.put(Keys.OBJECT_ID, rewardId); reward.put(Reward.SENDER_ID, senderId); reward.put(Reward.DATA_ID, commentId); reward.put(Reward.TYPE, Reward.TYPE_C_COMMENT); rewardMgmtService.addReward(reward); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, receiverId); notification.put(Notification.NOTIFICATION_DATA_ID, rewardId); notificationMgmtService.addCommentThankNotification(notification); livenessMgmtService.incLiveness(senderId, Liveness.LIVENESS_THANK); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Thanks a comment[id=" + commentId + "] failed", e); throw new ServiceException(e); } } /** * Adds a comment with the specified request json object. * * @param requestJSONObject the specified request json object, for example, <pre> * { * "commentContent": "", * "commentAuthorId": "", * "commentOnArticleId": "", * "commentOriginalCommentId": "", // optional * "clientCommentId": "" // optional, * "commentAuthorName": "" // If from client * "commenter": { * // User model * }, * "commentIP": "", // optional, default to "" * "commentUA": "", // optional, default to "" * "commentAnonymous": int, // optional, default to 0 (public) * "userCommentViewMode": int * } * </pre>, see {@link Comment} for more details * * @return generated comment id * @throws ServiceException service exception */ public synchronized String addComment(final JSONObject requestJSONObject) throws ServiceException { final long currentTimeMillis = System.currentTimeMillis(); final JSONObject commenter = requestJSONObject.optJSONObject(Comment.COMMENT_T_COMMENTER); final String commentAuthorId = requestJSONObject.optString(Comment.COMMENT_AUTHOR_ID); final boolean fromClient = requestJSONObject.has(Comment.COMMENT_CLIENT_COMMENT_ID); final String articleId = requestJSONObject.optString(Comment.COMMENT_ON_ARTICLE_ID); final String ip = requestJSONObject.optString(Comment.COMMENT_IP); String ua = requestJSONObject.optString(Comment.COMMENT_UA); final int commentAnonymous = requestJSONObject.optInt(Comment.COMMENT_ANONYMOUS); final int commentViewMode = requestJSONObject.optInt(UserExt.USER_COMMENT_VIEW_MODE); if (currentTimeMillis - commenter.optLong(UserExt.USER_LATEST_CMT_TIME) < Symphonys.getLong("minStepCmtTime") && !Role.ROLE_ID_C_ADMIN.equals(commenter.optString(User.USER_ROLE)) && !UserExt.DEFAULT_CMTER_ROLE.equals(commenter.optString(User.USER_ROLE))) { LOGGER.log(Level.WARN, "Adds comment too frequent [userName={0}]", commenter.optString(User.USER_NAME)); throw new ServiceException(langPropsService.get("tooFrequentCmtLabel")); } final String commenterName = commenter.optString(User.USER_NAME); JSONObject article = null; try { // check if admin allow to add comment final JSONObject option = optionRepository.get(Option.ID_C_MISC_ALLOW_ADD_COMMENT); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { throw new ServiceException(langPropsService.get("notAllowAddCommentLabel")); } final int balance = commenter.optInt(UserExt.USER_POINT); if (Comment.COMMENT_ANONYMOUS_C_ANONYMOUS == commentAnonymous) { final int anonymousPoint = Symphonys.getInt("anonymous.point"); if (balance < anonymousPoint) { String anonymousEnabelPointLabel = langPropsService.get("anonymousEnabelPointLabel"); anonymousEnabelPointLabel = anonymousEnabelPointLabel.replace("${point}", String.valueOf(anonymousPoint)); throw new ServiceException(anonymousEnabelPointLabel); } } article = articleRepository.get(articleId); if (!fromClient && !TuringQueryService.ROBOT_NAME.equals(commenterName)) { int pointSum = Pointtransfer.TRANSFER_SUM_C_ADD_COMMENT; // Point final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID); if (articleAuthorId.equals(commentAuthorId)) { pointSum = Pointtransfer.TRANSFER_SUM_C_ADD_SELF_ARTICLE_COMMENT; } if (balance - pointSum < 0) { throw new ServiceException(langPropsService.get("insufficientBalanceLabel")); } } } catch (final RepositoryException e) { throw new ServiceException(e); } final int articleAnonymous = article.optInt(Article.ARTICLE_ANONYMOUS); final Transaction transaction = commentRepository.beginTransaction(); try { article.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT) + 1); article.put(Article.ARTICLE_LATEST_CMTER_NAME, commenter.optString(User.USER_NAME)); if (Comment.COMMENT_ANONYMOUS_C_ANONYMOUS == commentAnonymous) { article.put(Article.ARTICLE_LATEST_CMTER_NAME, UserExt.ANONYMOUS_USER_NAME); } article.put(Article.ARTICLE_LATEST_CMT_TIME, currentTimeMillis); final String ret = Ids.genTimeMillisId(); final JSONObject comment = new JSONObject(); comment.put(Keys.OBJECT_ID, ret); String content = requestJSONObject.optString(Comment.COMMENT_CONTENT). replace("_esc_enter_88250_", "<br/>"); // Solo client escape comment.put(Comment.COMMENT_AUTHOR_ID, commentAuthorId); comment.put(Comment.COMMENT_ON_ARTICLE_ID, articleId); if (fromClient) { comment.put(Comment.COMMENT_CLIENT_COMMENT_ID, requestJSONObject.optString(Comment.COMMENT_CLIENT_COMMENT_ID)); // Appends original commenter name final String authorName = requestJSONObject.optString(Comment.COMMENT_T_AUTHOR_NAME); content += " <i class='ft-small'>by " + authorName + "</i>"; } final String originalCmtId = requestJSONObject.optString(Comment.COMMENT_ORIGINAL_COMMENT_ID); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, originalCmtId); if (StringUtils.isNotBlank(originalCmtId)) { final JSONObject originalCmt = commentRepository.get(originalCmtId); final int originalCmtReplyCnt = originalCmt.optInt(Comment.COMMENT_REPLY_CNT); originalCmt.put(Comment.COMMENT_REPLY_CNT, originalCmtReplyCnt + 1); commentRepository.update(originalCmtId, originalCmt); } content = Emotions.toAliases(content); // content = StringUtils.trim(content) + " "; https://github.com/b3log/symphony/issues/389 content = content.replace(langPropsService.get("uploadingLabel", Locale.SIMPLIFIED_CHINESE), ""); content = content.replace(langPropsService.get("uploadingLabel", Locale.US), ""); comment.put(Comment.COMMENT_CONTENT, content); comment.put(Comment.COMMENT_CREATE_TIME, System.currentTimeMillis()); comment.put(Comment.COMMENT_SHARP_URL, "/article/" + articleId + "#" + ret); comment.put(Comment.COMMENT_STATUS, Comment.COMMENT_STATUS_C_VALID); comment.put(Comment.COMMENT_IP, ip); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { LOGGER.log(Level.WARN, "UA is too long [" + ua + "]"); ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } comment.put(Comment.COMMENT_UA, ua); comment.put(Comment.COMMENT_ANONYMOUS, commentAnonymous); final JSONObject cmtCntOption = optionRepository.get(Option.ID_C_STATISTIC_CMT_COUNT); final int cmtCnt = cmtCntOption.optInt(Option.OPTION_VALUE); cmtCntOption.put(Option.OPTION_VALUE, String.valueOf(cmtCnt + 1)); articleRepository.update(articleId, article); // Updates article comment count, latest commenter name and time optionRepository.update(Option.ID_C_STATISTIC_CMT_COUNT, cmtCntOption); // Updates global comment count // Updates tag comment count and User-Tag relation final String tagsString = article.optString(Article.ARTICLE_TAGS); final String[] tagStrings = tagsString.split(","); for (int i = 0; i < tagStrings.length; i++) { final String tagTitle = tagStrings[i].trim(); final JSONObject tag = tagRepository.getByTitle(tagTitle); tag.put(Tag.TAG_COMMENT_CNT, tag.optInt(Tag.TAG_COMMENT_CNT) + 1); tag.put(Tag.TAG_RANDOM_DOUBLE, Math.random()); tagRepository.update(tag.optString(Keys.OBJECT_ID), tag); } // Updates user comment count, latest comment time commenter.put(UserExt.USER_COMMENT_COUNT, commenter.optInt(UserExt.USER_COMMENT_COUNT) + 1); commenter.put(UserExt.USER_LATEST_CMT_TIME, currentTimeMillis); userRepository.update(commenter.optString(Keys.OBJECT_ID), commenter); comment.put(Comment.COMMENT_GOOD_CNT, 0); comment.put(Comment.COMMENT_BAD_CNT, 0); comment.put(Comment.COMMENT_SCORE, 0D); comment.put(Comment.COMMENT_REPLY_CNT, 0); // Adds the comment final String commentId = commentRepository.add(comment); // Updates tag-article relation stat. final List<JSONObject> tagArticleRels = tagArticleRepository.getByArticleId(articleId); for (final JSONObject tagArticleRel : tagArticleRels) { tagArticleRel.put(Article.ARTICLE_LATEST_CMT_TIME, currentTimeMillis); tagArticleRel.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT)); tagArticleRepository.update(tagArticleRel.optString(Keys.OBJECT_ID), tagArticleRel); } transaction.commit(); if (!fromClient && Comment.COMMENT_ANONYMOUS_C_PUBLIC == commentAnonymous && Article.ARTICLE_ANONYMOUS_C_PUBLIC == articleAnonymous && !TuringQueryService.ROBOT_NAME.equals(commenterName)) { // Point final String articleAuthorId = article.optString(Article.ARTICLE_AUTHOR_ID); if (articleAuthorId.equals(commentAuthorId)) { pointtransferMgmtService.transfer(commentAuthorId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_ADD_COMMENT, Pointtransfer.TRANSFER_SUM_C_ADD_SELF_ARTICLE_COMMENT, commentId, System.currentTimeMillis()); } else { pointtransferMgmtService.transfer(commentAuthorId, articleAuthorId, Pointtransfer.TRANSFER_TYPE_C_ADD_COMMENT, Pointtransfer.TRANSFER_SUM_C_ADD_COMMENT, commentId, System.currentTimeMillis()); } livenessMgmtService.incLiveness(commentAuthorId, Liveness.LIVENESS_COMMENT); } // Event final JSONObject eventData = new JSONObject(); eventData.put(Comment.COMMENT, comment); eventData.put(Common.FROM_CLIENT, fromClient); eventData.put(Article.ARTICLE, article); eventData.put(UserExt.USER_COMMENT_VIEW_MODE, commentViewMode); try { eventManager.fireEventAsynchronously(new Event<JSONObject>(EventTypes.ADD_COMMENT_TO_ARTICLE, eventData)); } catch (final EventException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } return ret; } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Adds a comment failed", e); throw new ServiceException(e); } } /** * Updates the specified comment by the given comment id. * * @param commentId the given comment id * @param comment the specified comment * @throws ServiceException service exception */ public void updateComment(final String commentId, final JSONObject comment) throws ServiceException { final Transaction transaction = commentRepository.beginTransaction(); try { String content = comment.optString(Comment.COMMENT_CONTENT); content = Emotions.toAliases(content); content = StringUtils.trim(content) + " "; content = content.replace(langPropsService.get("uploadingLabel", Locale.SIMPLIFIED_CHINESE), ""); content = content.replace(langPropsService.get("uploadingLabel", Locale.US), ""); comment.put(Comment.COMMENT_CONTENT, content); commentRepository.update(commentId, comment); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates a comment[id=" + commentId + "] failed", e); throw new ServiceException(e); } } }
gaozhenhong/symphony
src/main/java/org/b3log/symphony/service/CommentMgmtService.java
Java
gpl-3.0
22,223
static inline struct pthread *__pthread_self() { struct pthread *self; __asm__ ("mov %%fs:0,%0" : "=r" (self) ); return self; } #define TP_ADJ(p) (p) #define MC_PC gregs[REG_RIP]
jalembke/ProxyFS
musl/arch/x86_64/pthread_arch.h
C
gpl-3.0
184
/* * Copyright (C) 2010-2019 The ESPResSo project * * This file is part of ESPResSo. * * ESPResSo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ESPResSo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** \file * %Lattice Boltzmann implementation on GPUs. * * Implementation in lbgpu.cpp. */ #ifndef LBGPU_HPP #define LBGPU_HPP #include "config.hpp" #ifdef CUDA #include "OptionalCounter.hpp" #include <utils/Vector.hpp> #include <utils/index.hpp> #include <cstddef> #include <cstdint> #include <vector> /* For the D3Q19 model most functions have a separate implementation * where the coefficients and the velocity vectors are hardcoded * explicitly. This saves a lot of multiplications with 1's and 0's * thus making the code more efficient. */ #define LBQ 19 /** Parameters for the lattice Boltzmann system for GPU. */ struct LB_parameters_gpu { /** number density (LB units) */ float rho; /** mu (LJ units) */ float mu; /** viscosity (LJ) units */ float viscosity; /** relaxation rate of shear modes */ float gamma_shear; /** relaxation rate of bulk modes */ float gamma_bulk; /** */ float gamma_odd; float gamma_even; /** flag determining whether gamma_shear, gamma_odd, and gamma_even are * calculated from gamma_shear in such a way to yield a TRT LB with minimized * slip at bounce-back boundaries */ bool is_TRT; float bulk_viscosity; /** lattice spacing (LJ units) */ float agrid; /** time step for fluid propagation (LJ units) * Note: Has to be larger than MD time step! */ float tau; /** MD timestep */ float time_step; Utils::Array<unsigned int, 3> dim; unsigned int number_of_nodes; #ifdef LB_BOUNDARIES_GPU unsigned int number_of_boundnodes; #endif /** to calculate and print out physical values */ int calc_val; int external_force_density; Utils::Array<float, 3> ext_force_density; unsigned int reinit; // Thermal energy float kT; }; /* this structure is almost duplicated for memory efficiency. When the stress tensor element are needed at every timestep, this features should be explicitly switched on */ struct LB_rho_v_pi_gpu { /** density of the node */ float rho; /** velocity of the node */ Utils::Array<float, 3> v; /** pressure tensor */ Utils::Array<float, 6> pi; }; struct LB_node_force_density_gpu { Utils::Array<float, 3> *force_density; #if defined(VIRTUAL_SITES_INERTIALESS_TRACERS) || defined(EK_DEBUG) // We need the node forces for the velocity interpolation at the virtual // particles' position. However, LBM wants to reset them immediately // after the LBM update. This variable keeps a backup Utils::Array<float, 3> *force_density_buf; #endif }; /************************************************************/ /** \name Exported Variables */ /************************************************************/ /**@{*/ /** Switch indicating momentum exchange between particles and fluid */ extern LB_parameters_gpu lbpar_gpu; extern std::vector<LB_rho_v_pi_gpu> host_values; #ifdef ELECTROKINETICS extern LB_node_force_density_gpu node_f; extern bool ek_initialized; #endif extern OptionalCounter rng_counter_fluid_gpu; extern OptionalCounter rng_counter_coupling_gpu; /**@}*/ /************************************************************/ /** \name Exported Functions */ /************************************************************/ /**@{*/ /** Conserved quantities for the lattice Boltzmann system. */ struct LB_rho_v_gpu { /** density of the node */ float rho; /** velocity of the node */ Utils::Array<float, 3> v; }; void lb_GPU_sanity_checks(); void lb_get_device_values_pointer(LB_rho_v_gpu **pointer_address); void lb_get_boundary_force_pointer(float **pointer_address); void lb_get_para_pointer(LB_parameters_gpu **pointer_address); void lattice_boltzmann_update_gpu(); /** Perform a full initialization of the lattice Boltzmann system. * All derived parameters and the fluid are reset to their default values. */ void lb_init_gpu(); /** (Re-)initialize the derived parameters for the lattice Boltzmann system. * The current state of the fluid is unchanged. */ void lb_reinit_parameters_gpu(); /** (Re-)initialize the fluid. */ void lb_reinit_fluid_gpu(); /** Reset the forces on the fluid nodes */ void reset_LB_force_densities_GPU(bool buffer = true); void lb_init_GPU(const LB_parameters_gpu &lbpar_gpu); void lb_integrate_GPU(); void lb_get_values_GPU(LB_rho_v_pi_gpu *host_values); void lb_print_node_GPU(unsigned single_nodeindex, LB_rho_v_pi_gpu *host_print_values); #ifdef LB_BOUNDARIES_GPU void lb_init_boundaries_GPU(std::size_t n_lb_boundaries, unsigned number_of_boundnodes, int *host_boundary_node_list, int *host_boundary_index_list, float *lb_bounday_velocity); #endif void lb_set_agrid_gpu(double agrid); template <std::size_t no_of_neighbours> void lb_calc_particle_lattice_ia_gpu(bool couple_virtual, double friction); void lb_calc_fluid_mass_GPU(double *mass); void lb_calc_fluid_momentum_GPU(double *host_mom); void lb_get_boundary_flag_GPU(unsigned int single_nodeindex, unsigned int *host_flag); void lb_get_boundary_flags_GPU(unsigned int *host_bound_array); void lb_set_node_velocity_GPU(unsigned single_nodeindex, float *host_velocity); void lb_set_node_rho_GPU(unsigned single_nodeindex, float host_rho); void reinit_parameters_GPU(LB_parameters_gpu *lbpar_gpu); void lb_reinit_extern_nodeforce_GPU(LB_parameters_gpu *lbpar_gpu); void lb_reinit_GPU(LB_parameters_gpu *lbpar_gpu); void lb_gpu_get_boundary_forces(std::vector<double> &forces); void lb_save_checkpoint_GPU(float *host_checkpoint_vd); void lb_load_checkpoint_GPU(float const *host_checkpoint_vd); void lb_lbfluid_set_population(const Utils::Vector3i &, float[LBQ]); void lb_lbfluid_get_population(const Utils::Vector3i &, float[LBQ]); template <std::size_t no_of_neighbours> void lb_get_interpolated_velocity_gpu(double const *positions, double *velocities, int length); void linear_velocity_interpolation(double const *positions, double *velocities, int length); void quadratic_velocity_interpolation(double const *positions, double *velocities, int length); Utils::Array<float, 6> stress_tensor_GPU(); uint64_t lb_fluid_get_rng_state_gpu(); void lb_fluid_set_rng_state_gpu(uint64_t counter); uint64_t lb_coupling_get_rng_state_gpu(); void lb_coupling_set_rng_state_gpu(uint64_t counter); /** Calculate the node index from its coordinates */ inline unsigned int calculate_node_index(LB_parameters_gpu const &lbpar, Utils::Vector3i const &coord) { return static_cast<unsigned>( Utils::get_linear_index(coord, Utils::Vector3i(lbpar_gpu.dim))); } /**@}*/ #endif /* CUDA */ #endif /* LBGPU_HPP */
fweik/espresso
src/core/grid_based_algorithms/lbgpu.hpp
C++
gpl-3.0
7,560
/* * Copyright (C) 2000 - 2011 TagServlet Ltd * * This file is part of Open BlueDragon (OpenBD) CFML Server Engine. * * OpenBD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * Free Software Foundation,version 3. * * OpenBD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenBD. If not, see http://www.gnu.org/licenses/ * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining * it with any of the JARS listed in the README.txt (or a modified version of * (that library), containing parts covered by the terms of that JAR, the * licensors of this Program grant you additional permission to convey the * resulting work. * README.txt @ http://www.openbluedragon.org/license/README.txt * * http://openbd.org/ * * $Id: CronSetDirectory.java 1765 2011-11-04 07:55:52Z alan $ */ package org.alanwilliamson.openbd.plugin.crontab; import com.naryx.tagfusion.cfm.engine.cfArgStructData; import com.naryx.tagfusion.cfm.engine.cfBooleanData; import com.naryx.tagfusion.cfm.engine.cfData; import com.naryx.tagfusion.cfm.engine.cfSession; import com.naryx.tagfusion.cfm.engine.cfmRunTimeException; import com.naryx.tagfusion.expression.function.functionBase; public class CronSetDirectory extends functionBase { private static final long serialVersionUID = 1L; public CronSetDirectory(){ min = max = 1; setNamedParams( new String[]{ "directory" } ); } public String[] getParamInfo(){ return new String[]{ "uri directory - will be created if not exists", }; } public java.util.Map getInfo(){ return makeInfo( "system", "Sets the URI directory that the cron tasks will run from. Calling this function will enable the crontab scheduler to start. This persists across server restarts", ReturnType.BOOLEAN ); } public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException { CronExtension.setRootPath( getNamedStringParam(argStruct, "directory", null ) ); return cfBooleanData.TRUE; } }
OpenBD/openbd-core
src/org/alanwilliamson/openbd/plugin/crontab/CronSetDirectory.java
Java
gpl-3.0
2,444
package com.gentasaurus.ubahfood.inventory; import com.gentasaurus.ubahfood.init.ModBlocks; import com.gentasaurus.ubahfood.item.crafting.SCMCraftingManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.*; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class ContainerSCM extends Container { /** The crafting matrix inventory (3x3). */ public InventoryCrafting craftMatrix; public IInventory craftResult; private World worldObj; private int posX; private int posY; private int posZ; public ContainerSCM(InventoryPlayer invPlayer, World world, int x, int y, int z) { craftMatrix = new InventoryCrafting(this, 3, 1); craftResult = new InventoryCraftResult(); worldObj = world; posX = x; posY = y; posZ = z; this.addSlotToContainer(new SlotSCM(invPlayer.player, craftMatrix, craftResult, 0, 124, 35)); int i; int i1; for (i = 0; i < 3; i++) { for (i1 = 0; i1 < 1; i1++) { this.addSlotToContainer(new Slot(this.craftMatrix, i1 + i * 1, 57 + i1 * 18, 17 + i * 18)); } } for (i = 0; i < 3; ++i) { for (i1 = 0; i1 < 9; ++i1) { this.addSlotToContainer(new Slot(invPlayer, i1 + i * 9 + 9, 8 + i1 * 18, 84 + i * 18)); } } for (i = 0; i < 9; ++i) { this.addSlotToContainer(new Slot(invPlayer, i, 8 + i * 18, 142)); } this.onCraftMatrixChanged(craftMatrix); } /** * Callback for when the crafting matrix is changed. */ public void onCraftMatrixChanged(IInventory p_75130_1_) { craftResult.setInventorySlotContents(0, SCMCraftingManager.getInstance().findMatchingRecipe(craftMatrix, worldObj)); } /** * Called when the container is closed. */ public void onContainerClosed(EntityPlayer p_75134_1_) { super.onContainerClosed(p_75134_1_); if (!this.worldObj.isRemote) { for (int i = 0; i < 3; ++i) { ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i); if (itemstack != null) { p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false); } } } } public boolean canInteractWith(EntityPlayer p_75145_1_) { return this.worldObj.getBlock(this.posX, this.posY, this.posZ) != ModBlocks.snowConeMachine ? false : p_75145_1_.getDistanceSq((double)this.posX + 0.5D, (double)this.posY + 0.5D, (double)this.posZ + 0.5D) <= 64.0D; } /** * Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that. */ public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_) { return null; } public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_) { return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_); } }
gentasaurus/UbahFood
src/main/java/com/gentasaurus/ubahfood/inventory/ContainerSCM.java
Java
gpl-3.0
3,263
#ifndef __MACROS_H__ #define __MACROS_H__ #include "config.h" #define __KERNELNAME__ "code0" /* * This file is automatically included before the first line of any * source file, using gcc's -imacro command line option. Only macro * definitions will be extracted. */ #define INC_ARCH(x) <l4/arch/__ARCH__/x> #define INC_SUBARCH(x) <l4/arch/__ARCH__/__SUBARCH__/x> #define INC_CPU(x) <l4/arch/__ARCH__/__SUBARCH__/__CPU__/x> #define INC_PLAT(x) <l4/platform/__PLATFORM__/x> #define INC_API(x) <l4/api/x> #define INC_GLUE(x) <l4/glue/__ARCH__/x> #define __initdata SECTION(".init.data") /* * FIXME: Remove __CPP__ * This is defined in kernel linker.lds.in, * find some better way. */ #if !defined(__CPP__) /* use this to place code/data in a certain section */ #define SECTION(x) __attribute__((section(x))) #define ALIGN(x) __attribute__((aligned (x))) #endif /* Functions for critical path optimizations */ #if (__GNUC__ >= 3) #define unlikely(x) __builtin_expect((x), false) #define likely(x) __builtin_expect((x), true) #define likelyval(x,val) __builtin_expect((x), (val)) #else /* __GNUC__ < 3 */ #define likely(x) (x) #define unlikely(x) (x) #define likelyval(x,val) (x) #endif /* __GNUC__ < 3 */ /* This guard is needed because tests use host C library and NULL is defined */ #ifndef NULL #define NULL 0 #endif /* Convenience functions for memory sizes. */ #define SZ_1K 1024 #define SZ_2K 2048 #define SZ_4K 0x1000 #define SZ_16K 0x4000 #define SZ_32K 0x8000 #define SZ_64K 0x10000 #define SZ_1MB 0x100000 #define SZ_2MB 0x200000 #define SZ_4MB (4*SZ_1MB) #define SZ_8MB (8*SZ_1MB) #define SZ_16MB (16*SZ_1MB) #define SZ_1K_BITS 10 #define SZ_4K_BITS 12 #define SZ_16K_BITS 14 #define SZ_1MB_BITS 20 /* Per-cpu variables */ #if defined CONFIG_SMP #define DECLARE_PERCPU(type, name) \ type name[CONFIG_NCPU] #define per_cpu(val) (val)[smp_get_cpuid()] #define per_cpu_byid(val, cpu) (val)[(cpu)] #else /* Not CONFIG_SMP */ #define DECLARE_PERCPU(type, name) \ type name #define per_cpu(val) (val) #define per_cpu_byid(val, cpu) val #endif /* End of Not CONFIG_SMP */ #ifndef __ASSEMBLY__ #include <stddef.h> /* offsetof macro, defined in the `standard' way. */ #endif #define container_of(ptr, struct_type, field) \ ({ \ const typeof(((struct_type *)0)->field) *field_ptr = (ptr); \ (struct_type *)((char *)field_ptr - offsetof(struct_type, field)); \ }) /* Prefetching is noop for now */ #define prefetch(x) x #if !defined(__KERNEL__) #define printk printf #endif /* Converts an int-sized field offset in a struct into a bit offset in a word */ #define FIELD_TO_BIT(type, field) (1 << (offsetof(type, field) >> 2)) /* Functions who may either return a pointer or an error code can use these: */ #define PTR_ERR(x) ((void *)(x)) /* checks up to -1000, the rest might be valid pointers!!! E.g. 0xE0000000 */ // #define IS_ERR(x) ((((int)(x)) < 0) && (((int)(x) > -1000))) #if !defined(__ASSEMBLY__) #define IS_ERR(x) is_err((int)(x)) static inline int is_err(int x) { return x < 0 && x > -0x1000; } #endif /* TEST: Is this type of printk well tested? */ #define BUG() {do { \ printk("BUG in file: %s function: %s line: %d\n", \ __FILE__, __FUNCTION__, __LINE__); \ } while(0); \ while(1);} #define BUG_ON(x) {if (x) BUG();} #define WARN_ON(x) {if (x) printk("%s, %s, %s: Warning something is off here.\n", __FILE__, __FUNCTION__, __LINE__); } #define BUG_ON_MSG(msg, x) do { \ printk(msg); \ BUG_ON(x) \ } while(0) #define BUG_MSG(msg...) do { \ printk(msg); \ BUG(); \ } while(0) #endif /* __MACROS_H__ */
freecores/c0or1k
include/l4/macros.h
C
gpl-3.0
3,725
#include "prism/animation.h" #include <stdlib.h> #include "prism/log.h" #include "prism/datastructures.h" #include "prism/memoryhandler.h" #include "prism/system.h" #include "prism/timer.h" #include "prism/stlutil.h" using namespace std; static struct { int mIsPaused; } gPrismAnimationData; int getDurationInFrames(Duration tDuration){ return (int)(tDuration * getInverseFramerateFactor()); } int handleDurationAndCheckIfOver(Duration* tNow, Duration tDuration) { if(gPrismAnimationData.mIsPaused) return 0; (*tNow)++; return isDurationOver(*tNow, tDuration); } int isDurationOver(Duration tNow, Duration tDuration) { if (tNow >= getDurationInFrames(tDuration)) { return 1; } return 0; } int handleTickDurationAndCheckIfOver(Tick * tNow, Tick tDuration) { if (gPrismAnimationData.mIsPaused) return 0; (*tNow)++; return isTickDurationOver(*tNow, tDuration); } int isTickDurationOver(Tick tNow, Tick tDuration) { if (tNow >= tDuration) { return 1; } return 0; } AnimationResult animateWithoutLoop(Animation* tAnimation) { AnimationResult ret = ANIMATION_CONTINUING; if (handleDurationAndCheckIfOver(&tAnimation->mNow, tAnimation->mDuration)) { tAnimation->mNow = 0; tAnimation->mFrame++; if (tAnimation->mFrame >= tAnimation->mFrameAmount) { tAnimation->mFrame = tAnimation->mFrameAmount-1; tAnimation->mNow = getDurationInFrames(tAnimation->mDuration); ret = ANIMATION_OVER; } } return ret; } void animate(Animation* tAnimation) { AnimationResult ret = animateWithoutLoop(tAnimation); if(ret == ANIMATION_OVER){ resetAnimation(tAnimation); } } void resetAnimation(Animation* tAnimation) { tAnimation->mNow = 0; tAnimation->mFrame = 0; } Animation createAnimation(int tFrameAmount, Duration tDuration) { Animation ret = createEmptyAnimation(); ret.mFrameAmount = tFrameAmount; ret.mDuration = tDuration; return ret; } Animation createEmptyAnimation(){ Animation ret; ret.mFrame = 0; ret.mFrameAmount = 0; ret.mNow = 0; ret.mDuration = 1000000000; return ret; } Animation createOneFrameAnimation(){ Animation ret = createEmptyAnimation(); ret.mFrameAmount = 1; return ret; } void pauseDurationHandling() { gPrismAnimationData.mIsPaused = 1; } void resumeDurationHandling() { gPrismAnimationData.mIsPaused = 0; } double getDurationPercentage(Duration tNow, Duration tDuration) { int duration = getDurationInFrames(tDuration); return tNow / (double)duration; } static struct{ map<int, AnimationHandlerElement> mList; int mIsLoaded; } gAnimationHandler; void setupAnimationHandler(){ if(gAnimationHandler.mIsLoaded){ logWarning("Setting up non-empty animation handler; Cleaning up."); shutdownAnimationHandler(); } gAnimationHandler.mList.clear(); gAnimationHandler.mIsLoaded = 1; } static int updateAndRemoveCB(void* tCaller, AnimationHandlerElement& tData) { (void) tCaller; AnimationHandlerElement* cur = &tData; AnimationResult res = animateWithoutLoop(&cur->mAnimation); if(res == ANIMATION_OVER) { if(cur->mCB != NULL) { cur->mCB(cur->mCaller); } if(cur->mIsLooped) { resetAnimation(&cur->mAnimation); } else { return 1; } } return 0; } void updateAnimationHandler(){ stl_int_map_remove_predicate(gAnimationHandler.mList, updateAndRemoveCB); } static Position getAnimationPositionWithAllReferencesIncluded(AnimationHandlerElement* cur) { Position p = cur->mPosition; if (cur->mScreenPositionReference != NULL) { p = vecAdd(p, vecScale(*cur->mScreenPositionReference, -1)); } if (cur->mBasePositionReference != NULL) { p = vecAdd(p, *(cur->mBasePositionReference)); } return p; } static void drawAnimationHandlerCB(void* tCaller, AnimationHandlerElement& tData) { (void) tCaller; AnimationHandlerElement* cur = &tData; if (!cur->mIsVisible) return; int frame = cur->mAnimation.mFrame; Position p = getAnimationPositionWithAllReferencesIncluded(cur); if (cur->mIsRotated) { Position rPosition = cur->mRotationEffectCenter; rPosition = vecAdd(rPosition, p); setDrawingRotationZ(cur->mRotationZ, rPosition); } if(cur->mIsScaled) { Position sPosition = cur->mScaleEffectCenter; sPosition = vecAdd(sPosition, p); scaleDrawing3D(cur->mScale, sPosition); } if (cur->mHasBaseColor) { setDrawingBaseColorAdvanced(cur->mBaseColor.x, cur->mBaseColor.y, cur->mBaseColor.z); } if (cur->mHasTransparency) { setDrawingTransparency(cur->mTransparency); } Rectangle texturePos = cur->mTexturePosition; if(cur->mInversionState.x) { Position center = vecAdd(cur->mCenter, p); double deltaX = center.x - p.x; double nRightX = center.x + deltaX; double nLeftX = nRightX - abs(cur->mTexturePosition.bottomRight.x - cur->mTexturePosition.topLeft.x); p.x = nLeftX; texturePos.topLeft.x = cur->mTexturePosition.bottomRight.x; texturePos.bottomRight.x = cur->mTexturePosition.topLeft.x; } if (cur->mInversionState.y) { Position center = vecAdd(cur->mCenter, p); double deltaY = center.y - p.y; double nDownY = center.y + deltaY; double nUpY = nDownY - abs(cur->mTexturePosition.bottomRight.y - cur->mTexturePosition.topLeft.y); p.y = nUpY; texturePos.topLeft.y = cur->mTexturePosition.bottomRight.y; texturePos.bottomRight.y = cur->mTexturePosition.topLeft.y; } drawSprite(cur->mTextureData[frame], p, texturePos); if(cur->mIsScaled || cur->mIsRotated || cur->mHasBaseColor || cur->mHasTransparency) { setDrawingParametersToIdentity(); } } void drawHandledAnimations() { stl_int_map_map(gAnimationHandler.mList, drawAnimationHandlerCB); } static void emptyAnimationHandler(){ gAnimationHandler.mList.clear(); } static AnimationHandlerElement* playAnimationInternal(const Position& tPosition, TextureData* tTextures, const Animation& tAnimation, const Rectangle& tTexturePosition, AnimationPlayerCB tOptionalCB, void* tCaller, int tIsLooped){ AnimationHandlerElement e; e.mCaller = tCaller; e.mCB = tOptionalCB; e.mIsLooped = tIsLooped; e.mPosition = tPosition; e.mTexturePosition = tTexturePosition; e.mTextureData = tTextures; e.mAnimation = tAnimation; e.mScreenPositionReference = NULL; e.mBasePositionReference = NULL; e.mIsScaled = 0; e.mIsRotated = 0; e.mHasBaseColor = 0; e.mHasTransparency = 0; e.mCenter = Vector3D(0,0,0); e.mInversionState = Vector3DI(0,0,0); e.mIsVisible = 1; int id = stl_int_map_push_back(gAnimationHandler.mList, e); auto& element = gAnimationHandler.mList[id]; element.mID = id; return &element; } AnimationHandlerElement* playAnimation(const Position& tPosition, TextureData* tTextures, const Animation& tAnimation, const Rectangle& tTexturePosition, AnimationPlayerCB tOptionalCB, void* tCaller){ return playAnimationInternal(tPosition, tTextures, tAnimation, tTexturePosition, tOptionalCB, tCaller, 0); } AnimationHandlerElement* playAnimationLoop(const Position& tPosition, TextureData* tTextures, const Animation& tAnimation, const Rectangle& tTexturePosition){ return playAnimationInternal(tPosition, tTextures, tAnimation, tTexturePosition, NULL, NULL, 1); } AnimationHandlerElement* playOneFrameAnimationLoop(const Position& tPosition, TextureData* tTextures) { Animation anim = createOneFrameAnimation(); Rectangle rect = makeRectangleFromTexture(tTextures[0]); return playAnimationLoop(tPosition, tTextures, anim, rect); } void changeAnimation(AnimationHandlerElement* e, TextureData* tTextures, const Animation& tAnimation, const Rectangle& tTexturePosition) { e->mTexturePosition = tTexturePosition; e->mTextureData = tTextures; e->mAnimation = tAnimation; } void setAnimationScreenPositionReference(AnimationHandlerElement* e, Position* tScreenPositionReference) { e->mScreenPositionReference = tScreenPositionReference; } void setAnimationBasePositionReference(AnimationHandlerElement* e, Position* tBasePositionReference) { e->mBasePositionReference = tBasePositionReference; } void setAnimationScale(AnimationHandlerElement* e, const Vector3D& tScale, const Position& tCenter) { e->mIsScaled = 1; e->mScaleEffectCenter = tCenter; e->mScale = tScale; } void setAnimationSize(AnimationHandlerElement* e, const Vector3D& tSize, const Position& tCenter) { e->mIsScaled = 1; e->mScaleEffectCenter = tCenter; double dx = tSize.x / e->mTextureData[0].mTextureSize.x; double dy = tSize.y / e->mTextureData[0].mTextureSize.y; e->mScale = Vector3D(dx, dy, 1); } static void setAnimationRotationZ_internal(AnimationHandlerElement* e, double tAngle, const Vector3D& tCenter) { e->mIsRotated = 1; e->mRotationEffectCenter = tCenter; e->mRotationZ = tAngle; } void setAnimationRotationZ(AnimationHandlerElement* e, double tAngle, const Position& tCenter) { setAnimationRotationZ_internal(e, tAngle, tCenter); } static void setAnimationColor_internal(AnimationHandlerElement* e, double r, double g, double b) { e->mHasBaseColor = 1; e->mBaseColor = Vector3D(r, g, b); } void setAnimationColor(AnimationHandlerElement* e, double r, double g, double b) { setAnimationColor_internal(e, r, g, b); } void setAnimationColorType(AnimationHandlerElement* e, Color tColor) { double r, g, b; getRGBFromColor(tColor, &r, &g, &b); setAnimationColor(e, r, g, b); } void setAnimationTransparency(AnimationHandlerElement* e, double a) { e->mHasTransparency = 1; e->mTransparency = a; } void setAnimationVisibility(AnimationHandlerElement* e, int tIsVisible) { e->mIsVisible = tIsVisible; } void setAnimationCenter(AnimationHandlerElement* e, const Position& tCenter) { e->mCenter = tCenter; } void setAnimationCB(AnimationHandlerElement* e, AnimationPlayerCB tCB, void* tCaller) { e->mCB = tCB; e->mCaller = tCaller; } void setAnimationPosition(AnimationHandlerElement* e, const Position& tPosition) { e->mPosition = tPosition; } void setAnimationTexturePosition(AnimationHandlerElement* e, const Rectangle& tTexturePosition) { e->mTexturePosition = tTexturePosition; } void setAnimationLoop(AnimationHandlerElement* e, int tIsLooping) { e->mIsLooped = tIsLooping; } void removeAnimationCB(AnimationHandlerElement* e) { setAnimationCB(e, NULL, NULL); } typedef struct { AnimationHandlerElement* mElement; Vector3D mColor; Duration mDuration; } AnimationColorIncrease; static void increaseAnimationColor(void* tCaller) { AnimationColorIncrease* e = (AnimationColorIncrease*)tCaller; e->mColor = vecAdd(e->mColor, Vector3D(1.0 / e->mDuration, 1.0 / e->mDuration, 1.0 / e->mDuration)); if (e->mColor.x >= 1) e->mColor = Vector3D(1, 1, 1); setAnimationColor(e->mElement, e->mColor.x, e->mColor.y, e->mColor.z); if (e->mColor.x >= 1) { freeMemory(e); } else addTimerCB(0,increaseAnimationColor, e); } void fadeInAnimation(AnimationHandlerElement* tElement, Duration tDuration) { AnimationColorIncrease* e = (AnimationColorIncrease*)allocMemory(sizeof(AnimationColorIncrease)); e->mElement = tElement; e->mColor = Vector3D(0, 0, 0); e->mDuration = tDuration; addTimerCB(0, increaseAnimationColor, e); setAnimationColor(tElement, e->mColor.x, e->mColor.y, e->mColor.z); } void inverseAnimationVertical(AnimationHandlerElement* e) { e->mInversionState.x ^= 1; } void inverseAnimationHorizontal(AnimationHandlerElement* e) { e->mInversionState.y ^= 1; } void setAnimationVerticalInversion(AnimationHandlerElement* e, int tValue) { e->mInversionState.x = tValue; } void setAnimationHorizontalInversion(AnimationHandlerElement* e, int tValue) { e->mInversionState.y = tValue; } typedef struct { double mAngle; Vector3D mCenter; } ScreenRotationZ; static void setScreenRotationZForSingleAnimation(ScreenRotationZ* tRot, AnimationHandlerElement& tData) { AnimationHandlerElement* e = &tData; const auto p = getAnimationPositionWithAllReferencesIncluded(e); const auto center = vecSub(tRot->mCenter, p); setAnimationRotationZ_internal(e, tRot->mAngle, center); } void setAnimationHandlerScreenRotationZ(double tAngle, const Vector3D& tCenter) { ScreenRotationZ rot; rot.mAngle = tAngle; rot.mCenter = tCenter; stl_int_map_map(gAnimationHandler.mList, setScreenRotationZForSingleAnimation, &rot); } typedef struct { double r; double g; double b; } AnimationHandlerScreenTint; static void setAnimationHandlerScreenTintSingle(AnimationHandlerScreenTint* tTint, AnimationHandlerElement& tData) { AnimationHandlerElement* e = &tData; setAnimationColor_internal(e, tTint->r, tTint->g, tTint->b); } void setAnimationHandlerScreenTint(double r, double g, double b) { AnimationHandlerScreenTint tint; tint.r = r; tint.g = g; tint.b = b; stl_int_map_map(gAnimationHandler.mList, setAnimationHandlerScreenTintSingle, &tint); } void resetAnimationHandlerScreenTint() { setAnimationHandlerScreenTint(1, 1, 1); } double* getAnimationTransparencyReference(AnimationHandlerElement* e) { return &e->mTransparency; } Position* getAnimationPositionReference(AnimationHandlerElement* e) { return &e->mPosition; } void removeHandledAnimation(AnimationHandlerElement* e) { gAnimationHandler.mList.erase(e->mID); } int isHandledAnimation(AnimationHandlerElement* e) { return stl_map_contains(gAnimationHandler.mList, e->mID); } void shutdownAnimationHandler(){ emptyAnimationHandler(); gAnimationHandler.mList.clear(); gAnimationHandler.mIsLoaded = 0; }
CaptainDreamcast/libtari
animation.cpp
C++
gpl-3.0
13,226
/* * Copyright (c) 2011-2013 Lp digital system * * This file is part of BackBee. * * BackBee is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BackBee is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BackBee. If not, see <http://www.gnu.org/licenses/>. */ define(['Core', 'Core/Renderer', 'BackBone'], function (Core, Renderer, Backbone) { 'use strict'; var HiddenView = Backbone.View.extend({ initialize: function (template, formTag, element) { this.el = formTag; this.template = template; this.element = element; this.bindEvents(); }, bindEvents: function () { var self = this; Core.Mediator.subscribe('before:form:submit', function (form) { if (form.attr('id') === self.el) { var element = form.find('.element_' + self.element.getKey()), input = element.find('input[name="' + self.element.getKey() + '"]'), span = element.find('span.updated'), oldValue = self.element.value; if (input.val() !== oldValue) { span.text('updated'); } else { span.text(''); } } }); }, /** * Render the template into the DOM with the Renderer * @returns {String} html */ render: function () { return Renderer.render(this.template, {element: this.element}); } }); return HiddenView; });
ndufreche/BbCoreJs
src/tb/component/formbuilder/form/element/views/form.element.view.hidden.js
JavaScript
gpl-3.0
2,067
/* RWImporter Copyright (C) 2017 Martin Smith This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "rw_snippet.h" #include <QXmlStreamWriter> #include <QBuffer> #include <QDebug> #include <QModelIndex> #include <QMetaEnum> #include <QFile> #include <QFileInfo> #include <QMessageBox> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QCoreApplication> #include "datafield.h" #include "rw_domain.h" #include "rw_facet.h" static QMetaEnum snip_type_enum = QMetaEnum::fromType<RWFacet::SnippetType>(); static QMetaEnum snip_veracity_enum = QMetaEnum::fromType<RWContentsItem::SnippetVeracity>(); static QMetaEnum snip_style_enum = QMetaEnum::fromType<RWContentsItem::SnippetStyle>(); static QMetaEnum snip_purpose_enum = QMetaEnum::fromType<RWContentsItem::SnippetPurpose>(); const int NAME_TYPE_LENGTH = 50; const QString DEFAULT_IMAGE_NAME("image.png"); const char *DEFAULT_IMAGE_FORMAT = "PNG"; #define CONTENTS_TOKEN "contents" RWSnippet::RWSnippet(RWFacet *facet, RWContentsItem *parent) : RWContentsItem(facet, parent), facet(facet) { } static QString to_gregorian(const QString &from) { // TODO - Realm Works does not like "gregorian" fields in this format! /* Must be [Y]YYYY-MM-DD hh:mm:ss[ BCE] * year limit is 20000 */ if (from.length() >= 19) return from; // If no time in the field, then simply append midnight time */ if (from.length() == 10 || from.length() == 11) return from + " 00:00:00"; qWarning() << "INVALID DATE FORMAT:" << from << "(should be [Y]YYYY-MM-DD HH:MM:SS)"; return from; } void RWSnippet::writeToContents(QXmlStreamWriter *writer, const QModelIndex &index) const { Q_UNUSED(index); bool bold = false; // Ignore date snippets if no data available const QString start_date = startDate().valueString(index); if ((facet->snippetType() == RWFacet::Date_Game || facet->snippetType() == RWFacet::Date_Range) && start_date.isEmpty()) { return; } writer->writeStartElement("snippet"); { const QString user_text = contentsText().valueString(index); const QString gm_dir = gmDirections().valueString(index); const QVariant asset = filename().value(index); const QString finish_date = finishDate().valueString(index); QString digits = number().valueString(index); if (!structure->id().isEmpty()) writer->writeAttribute("facet_id", structure->id()); writer->writeAttribute("type", snip_type_enum.valueToKey(facet->snippetType())); if (snippetVeracity() != RWContentsItem::Truth) writer->writeAttribute("veracity", snip_veracity_enum.valueToKey(snippetVeracity())); if (snippetStyle() != RWContentsItem::Normal) writer->writeAttribute("style", snip_style_enum.valueToKey(snippetStyle())); if (snippetPurpose() != RWContentsItem::Story_Only) writer->writeAttribute("purpose", snip_purpose_enum.valueToKey(snippetPurpose())); if (isRevealed()) writer->writeAttribute("is_revealed", "true"); if (!gm_dir.isEmpty()) { RWFacet::SnippetType ft = facet->snippetType(); writer->writeAttribute("purpose", ((ft == RWFacet::Multi_Line || ft == RWFacet::Labeled_Text || ft == RWFacet::Tag_Standard || ft == RWFacet::Numeric) && user_text.isEmpty() && p_tags.valueString(index).isEmpty()) ? "Directions_Only" : "Both"); } #if 0 QString label_text = p_label_text.valueString(index); if (id().isEmpty() && facet->snippetType() == Labeled_Text && !label_text.isEmpty()) { // For locally added snippets of the Labeled_Text variety writer->writeAttribute("label", label_text); } #endif // // CHILDREN have to be in a specific order: // contents | smart_image | ext_object | game_date | date_range // annotation // gm_directions // X x (link | dlink) // X x tag_assign // Maybe an ANNOTATION or CONTENTS if (!user_text.isEmpty() || !asset.isNull() || !start_date.isEmpty() || !digits.isEmpty()) { bool check_annotation = true; switch (facet->snippetType()) { case RWFacet::Multi_Line: case RWFacet::Labeled_Text: { QString text; for (auto para: user_text.split("\n\n")) text.append(xmlParagraph(xmlSpan(para, bold))); writer->writeTextElement(CONTENTS_TOKEN, text); // No annotation for these two snippet types check_annotation = false; break; } case RWFacet::Tag_Standard: case RWFacet::Hybrid_Tag: // annotation done later break; case RWFacet::Numeric: if (!digits.isEmpty()) { bool ok; #if 1 digits.toFloat(&ok); if (!ok) qWarning() << tr("Non-numeric characters in numeric field: %1").arg(digits); else writer->writeTextElement(CONTENTS_TOKEN, digits); #else const QLocale &locale = QLocale::system(); locale.toFloat(digits, &ok); if (!ok) qWarning() << tr("Non-numeric characters in numeric field: %1").arg(digits); else { // Handle locale details: // Remove occurrences of the group character; // Replace the locale's decimal point with the ISO '.' character digits.remove(locale.groupSeparator()); digits.replace(locale.decimalPoint(),'.'); writer->writeTextElement(CONTENTS_TOKEN, digits); } #endif } break; // There are a lot of snippet types which have an ext_object child (which has an asset child) case RWFacet::Foreign: write_ext_object(writer, "Foreign", asset); break; case RWFacet::Statblock: // this might require an .rtf file? write_ext_object(writer, "Statblock", asset); break; case RWFacet::Portfolio: // requires a HeroLab portfolio write_ext_object(writer, "Portfolio", asset); break; case RWFacet::Picture: write_ext_object(writer, "Picture", asset); break; case RWFacet::Rich_Text: write_ext_object(writer, "Rich_Text", asset); break; case RWFacet::PDF: write_ext_object(writer, "PDF", asset); break; case RWFacet::Audio: write_ext_object(writer, "Audio", asset); break; case RWFacet::Video: write_ext_object(writer, "Video", asset); break; case RWFacet::HTML: write_ext_object(writer, "HTML", asset); break; case RWFacet::Smart_Image: // Slightly different format since it has a smart_image child (which has an asset child) write_smart_image(writer, asset); break; case RWFacet::Date_Game: writer->writeStartElement("game_date"); //writer->writeAttribute("canonical", start_date); writer->writeAttribute("gregorian", to_gregorian(start_date)); writer->writeEndElement(); break; case RWFacet::Date_Range: writer->writeStartElement("date_range"); //writer->writeAttribute("canonical_start", start_date); writer->writeAttribute("gregorian_start", to_gregorian(start_date)); //writer->writeAttribute("canonical_end", finish_date); writer->writeAttribute("gregorian_end", to_gregorian(finish_date)); writer->writeEndElement(); break; case RWFacet::Tag_Multi_Domain: qFatal("RWSnippet::writeToContents: invalid snippet type: %d", facet->snippetType()); } /* switch snippet type */ if (check_annotation && !user_text.isEmpty()) { writer->writeTextElement("annotation", xmlParagraph(xmlSpan(user_text, /*bold*/ false))); } } // Maybe some GM directions if (!gm_dir.isEmpty()) { writer->writeTextElement("gm_directions", xmlParagraph(xmlSpan(gm_dir, /*bold*/ false))); } // Maybe one or more TAG_ASSIGN (to be entered AFTER the contents/annotation) QString tag_names = p_tags.valueString(index); if (!tag_names.isEmpty()) { // Find the domain to use QString domain_id = structure->attributes().value("domain_id").toString(); RWDomain *domain = RWDomain::getDomainById(domain_id); if (domain) { for (auto tag_name: tag_names.split(",")) { QString tag_id = domain->tagId(tag_name.trimmed()); if (!tag_id.isEmpty()) { writer->writeStartElement("tag_assign"); writer->writeAttribute("tag_id", tag_id); writer->writeAttribute("type","Indirect"); writer->writeAttribute("is_auto_assign", "true"); writer->writeEndElement(); } else qWarning() << "No TAG defined for" << tag_name.trimmed() << "in DOMAIN" << domain->name(); } } else if (!domain_id.isEmpty()) qWarning() << "DOMAIN not found for" << domain_id << "on FACET" << structure->id(); else qWarning() << "domain_id does not exist on FACET" << structure->id(); } } writer->writeEndElement(); // snippet } void RWSnippet::write_asset(QXmlStreamWriter *writer, const QVariant &asset) const { const int FILENAME_TYPE_LENGTH = 200; // Images can be put inside immediately if (asset.type() == QVariant::Image) { QImage image = asset.value<QImage>(); writer->writeStartElement("asset"); writer->writeAttribute("filename", DEFAULT_IMAGE_NAME.right(FILENAME_TYPE_LENGTH)); QByteArray databytes; QBuffer buffer(&databytes); buffer.open(QIODevice::WriteOnly); image.save(&buffer, DEFAULT_IMAGE_FORMAT); writer->writeTextElement(CONTENTS_TOKEN, databytes.toBase64()); writer->writeEndElement(); // asset return; } QFile file(asset.toString()); QUrl url(asset.toString()); if (file.open(QFile::ReadOnly)) { QFileInfo info(file); writer->writeStartElement("asset"); writer->writeAttribute("filename", info.fileName().right(FILENAME_TYPE_LENGTH)); //writer->writeAttribute("thumbnail_size", info.fileName()); QByteArray contents = file.readAll(); writer->writeTextElement(CONTENTS_TOKEN, contents.toBase64()); //writer->writeTextElement("thumbnail", thumbnail.toBase64()); //writer->writeTextElement("summary", thing.toBase64()); //writer->writeTextElement("url", filename); writer->writeEndElement(); // asset } else if (url.isValid()) { static QNetworkAccessManager *nam = nullptr; if (nam == nullptr) { nam = new QNetworkAccessManager; nam->setRedirectPolicy(QNetworkRequest::NoLessSafeRedirectPolicy); } QNetworkRequest request(url); QNetworkReply *reply = nam->get(request); while (!reply->isFinished()) { qApp->processEvents(QEventLoop::WaitForMoreEvents); } if (reply->error() != QNetworkReply::NoError) { qWarning() << "Failed to locate URL:" << asset.toString(); } // A redirect has ContentType of "text/html; charset=UTF-8, image/png" // which is an ordered comma-separated list of types. // So we need to check the LAST type which will be for readAll() else if (reply->header(QNetworkRequest::ContentTypeHeader).toString().split(',').last().trimmed().startsWith("image/")) { QString tempname = QFileInfo(url.path()).baseName() + '.' + reply->header(QNetworkRequest::ContentTypeHeader).toString().split("/").last(); writer->writeStartElement("asset"); writer->writeAttribute("filename", tempname.right(FILENAME_TYPE_LENGTH)); QByteArray contents = reply->readAll(); writer->writeTextElement(CONTENTS_TOKEN, contents.toBase64()); //writer->writeTextElement("url", filename); writer->writeEndElement(); // asset } else { // A redirect has QPair("Content-Type","text/html; charset=UTF-8, image/png") // note the comma-separated list of content types (legal?) // the body of the message is actually PNG binary data. // QPair("Server","Microsoft-IIS/8.5, Microsoft-IIS/8.5") so maybe ISS sent wrong content type qWarning() << "Only URLs to images are supported (not" << reply->header(QNetworkRequest::ContentTypeHeader) << ")! Check source at" << asset.toString(); //if (reply->header(QNetworkRequest::ContentTypeHeader).toString().startsWith("text/")) // qWarning() << "Body =" << reply->readAll(); //qWarning() << "Raw Header List =" << reply->rawHeaderPairs(); } reply->deleteLater(); } else { #if 1 qWarning() << "File/URL does not exist:" + asset.toString(); #else QString message = "File/URL does not exist: " + asset.toString(); static QMessageBox *warning = nullptr; if (warning == nullptr) { warning = new QMessageBox; warning->setText("Issues encountered during GENERATE:\n"); } warning->setText(warning->text() + '\n' + message); warning->show(); #endif } } /** * @brief RWSnippet::write_ext_object * @param writer * @param exttype one of Foreign, Statblock, Portfolio, Picture, Rich_Text, PDF, Audio, Video, HTML * @param filename */ void RWSnippet::write_ext_object(QXmlStreamWriter *writer, const QString &exttype, const QVariant &asset) const { if (asset.isNull()) return; writer->writeStartElement("ext_object"); if (asset.type() == QVariant::String) writer->writeAttribute("name", QFileInfo(asset.toString()).fileName().right(NAME_TYPE_LENGTH)); else // What name to use for QImage? writer->writeAttribute("name", DEFAULT_IMAGE_NAME.right(NAME_TYPE_LENGTH)); writer->writeAttribute("type", exttype); write_asset(writer, asset); writer->writeEndElement(); } void RWSnippet::write_smart_image(QXmlStreamWriter *writer, const QVariant &asset) const { if (asset.isNull()) return; writer->writeStartElement("smart_image"); writer->writeAttribute("name", QFileInfo(asset.toString()).fileName().right(NAME_TYPE_LENGTH)); write_asset(writer, asset); // write_overlay (0-1) // write_subset_mask (0-1) // write_superset_mask (0-1) // write_map_pan (0+) writer->writeEndElement(); } QDataStream &operator<<(QDataStream &stream, const RWSnippet &snippet) { //qDebug() << " RWSnippet<<" << snippet.structure->name(); // write base class items stream << *dynamic_cast<const RWContentsItem*>(&snippet); // write this class items stream << snippet.p_tags; stream << snippet.p_label_text; stream << snippet.p_filename; stream << snippet.p_start_date; stream << snippet.p_finish_date; stream << snippet.p_number; return stream; } QDataStream &operator>>(QDataStream &stream, RWSnippet &snippet) { //qDebug() << " RWSnippet>>" << snippet.structure->name(); // read base class items stream >> *dynamic_cast<RWContentsItem*>(&snippet); // read this class items stream >> snippet.p_tags; stream >> snippet.p_label_text; stream >> snippet.p_filename; stream >> snippet.p_start_date; stream >> snippet.p_finish_date; stream >> snippet.p_number; return stream; }
farling42/csv2rw
rw_snippet.cpp
C++
gpl-3.0
17,289
#include "podcastclient.h" QStringList PodcastClient::getFeedsFromSettings() { QStringList resultList = settings.value("feeds").toStringList(); if(resultList.isEmpty()) { QString string = settings.value("feeds").toString(); if(!string.isEmpty()) resultList.push_back(string); } return resultList; } PodcastClient::PodcastClient(QObject *parent) : QObject(parent) { if(settings.value("NumDownloads").isNull()) settings.setValue("NumDownloads",10); if(settings.value("Dest").isNull()) settings.setValue("Dest","."); else { if(!QDir(settings.value("Dest").toString()).exists()) { settings.setValue("Dest",","); } } downloader.setMaxConnections(settings.value("NumDownloads").toInt()); foreach(QString url, getFeedsFromSettings()) { Podcast* podcast = new Podcast(QUrl(url), &downloader, this); podcast->setTargetFolder(QDir(settings.value("Dest").toString())); podcasts.push_back(podcast); connect(podcast,&Podcast::done,this,&PodcastClient::podcastDone); connect(podcast,&Podcast::writingFailed,this,&PodcastClient::podcastWritingFailed); } } bool PodcastClient::downloadAll() { if(podcasts.isEmpty()) { out << "No podcasts in list. Done." << endl; return true; } finishedCtr = 0; foreach(Podcast* podcast, podcasts) { podcast->update(); } return false; } bool PodcastClient::addPodcast(const QUrl &url, const QString &mode) { podcasts.clear(); finishedCtr = 0; if(!url.isValid()) { out << "Invalid URL." << endl; return true; } if(mode=="last" || mode.isEmpty()) { Podcast* podcast = new Podcast(url, &downloader, this); podcasts.push_back(podcast); connect(podcast,&Podcast::done,this,&PodcastClient::podcastDone); podcast->init(true); QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.push_back(url.toString()); settings.setValue("feeds",feeds); return false; } else if(mode=="all") { QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.push_back(url.toString()); settings.setValue("feeds",feeds); return true; } else if(mode=="none") { Podcast* podcast = new Podcast(url, &downloader, this); podcasts.push_back(podcast); connect(podcast,&Podcast::done,this,&PodcastClient::podcastDone); podcast->init(false); QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.push_back(url.toString()); settings.setValue("feeds",feeds); return false; } else { out << "Invalid adding mode: " << mode << endl; out << "Modes are: last, all, none" << endl; return true; } } void PodcastClient::removePodcast(const QUrl &url) { QStringList feeds; foreach(QString url, getFeedsFromSettings()) { feeds.push_back(url); } feeds.removeAll(url.toString()); if(feeds.isEmpty()) settings.remove("feeds"); else settings.setValue("feeds",feeds); } void PodcastClient::setDest(const QString &dest) { QDir dir(dest); settings.setValue("Dest",dest); settings.sync(); if(!dir.exists()) { out << "Target directory does not exist." << endl; } } QString PodcastClient::getDest() { return settings.value("Dest").toString(); } void PodcastClient::list() { foreach(QString url, getFeedsFromSettings()) { out << url << endl; } } void PodcastClient::setMaxDownloads(int num) { downloader.setMaxConnections(num); settings.setValue("NumDownloads",num); settings.sync(); } int PodcastClient::getMaxDownloads() { return downloader.getMaxConnections(); } void PodcastClient::podcastDone() { finishedCtr++; if(finishedCtr==podcasts.size()) { settings.sync(); QCoreApplication::exit(0); } } void PodcastClient::podcastWritingFailed() { out << "Aborting downloads..." << endl; foreach(Podcast* podcast, podcasts) { podcast->abort(); } }
R-Rudolph/minicatcher
podcastclient.cpp
C++
gpl-3.0
4,030