code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application RailsFrance::Application.initialize!
nicolasleger/railsfrance.org
config/environment.rb
Ruby
agpl-3.0
155
package functionaltests.job; import java.io.Serializable; import org.ow2.proactive.scheduler.common.Scheduler; import org.ow2.proactive.scheduler.common.job.JobId; import org.ow2.proactive.scheduler.common.job.JobState; import org.ow2.proactive.scheduler.common.job.TaskFlowJob; import org.ow2.proactive.scheduler.common.task.JavaTask; import org.ow2.proactive.scheduler.common.task.TaskResult; import org.ow2.proactive.scheduler.common.task.TaskStatus; import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable; import org.junit.Test; import functionaltests.utils.SchedulerFunctionalTest; import static org.junit.Assert.*; /** * Test provokes scenario when task gets 'NOT_RESTARTED' status: * - task is submitted and starts execution * - user requests to restart task with some delay * - before task was restarted job is killed * */ public class TestTaskNotRestarted extends SchedulerFunctionalTest { public static class TestJavaTask extends JavaExecutable { @Override public Serializable execute(TaskResult... results) throws Throwable { Thread.sleep(Long.MAX_VALUE); return "OK"; } } @Test public void test() throws Exception { Scheduler scheduler = schedulerHelper.getSchedulerInterface(); JobId jobId = scheduler.submit(createJob()); JobState jobState; schedulerHelper.waitForEventTaskRunning(jobId, "task1"); jobState = scheduler.getJobState(jobId); assertEquals(1, jobState.getTasks().size()); assertEquals(TaskStatus.RUNNING, jobState.getTasks().get(0).getStatus()); scheduler.restartTask(jobId, "task1", Integer.MAX_VALUE); jobState = scheduler.getJobState(jobId); assertEquals(1, jobState.getTasks().size()); assertEquals(TaskStatus.WAITING_ON_ERROR, jobState.getTasks().get(0).getStatus()); scheduler.killJob(jobId); jobState = scheduler.getJobState(jobId); assertEquals(1, jobState.getTasks().size()); assertEquals(TaskStatus.NOT_RESTARTED, jobState.getTasks().get(0).getStatus()); } private TaskFlowJob createJob() throws Exception { TaskFlowJob job = new TaskFlowJob(); job.setName(this.getClass().getSimpleName()); JavaTask javaTask = new JavaTask(); javaTask.setExecutableClassName(TestJavaTask.class.getName()); javaTask.setName("task1"); javaTask.setMaxNumberOfExecution(10); job.addTask(javaTask); return job; } }
sandrineBeauche/scheduling
scheduler/scheduler-server/src/test/java/functionaltests/job/TestTaskNotRestarted.java
Java
agpl-3.0
2,532
body { padding: 50px; } .room-actions { margin-right: -14px; } .room-actions .btn { margin: -17px 0 1px; padding: 5px 4px; font-size:10px; }
plugorgau/eventstreamr-frontend
public/stylesheets/style.css
CSS
agpl-3.0
153
/*! Chosen, a Select Box Enhancer for jQuery and Prototype by Patrick Filler for Harvest, http://getharvest.com Version 1.2.0 Full source at https://github.com/harvesthq/chosen Copyright (c) 2011-2014 Harvest http://getharvest.com MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md This file is generated by `grunt build`, do not edit it by hand. */ /* @group Base */ .chosen-container { position: relative; display: inline-block; vertical-align: middle; /*font-size: 13px;*/ zoom: 1; *display: inline; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .chosen-container * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .chosen-container .chosen-drop { position: absolute; top: 100%; left: -9999px; z-index: 1010; width: 100%; border: 1px solid #aaa; border-top: 0; background: #fff; box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15); } .chosen-container.chosen-with-drop .chosen-drop { left: 0; } .chosen-container a { cursor: pointer; } /* @end */ /* @group Single Chosen */ .chosen-container-single .chosen-single { position: relative; display: block; overflow: hidden; padding: 0 0 0 8px; height: 25px; border: 1px solid #aaa; border-radius: 5px; background-color: #fff; background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #ffffff), color-stop(50%, #f6f6f6), color-stop(52%, #eeeeee), color-stop(100%, #f4f4f4)); background: -webkit-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: -moz-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: -o-linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background: linear-gradient(top, #ffffff 20%, #f6f6f6 50%, #eeeeee 52%, #f4f4f4 100%); background-clip: padding-box; box-shadow: 0 0 3px white inset, 0 1px 1px rgba(0, 0, 0, 0.1); color: #444; text-decoration: none; white-space: nowrap; line-height: 24px; } .chosen-container-single .chosen-default { color: #999; } .chosen-container-single .chosen-single span { display: block; overflow: hidden; margin-right: 26px; text-overflow: ellipsis; white-space: nowrap; } .chosen-container-single .chosen-single-with-deselect span { margin-right: 38px; } .chosen-container-single .chosen-single abbr { position: absolute; top: 6px; right: 26px; display: block; width: 12px; height: 12px; background: url('chosen-sprite.png') -42px 1px no-repeat; font-size: 1px; } .chosen-container-single .chosen-single abbr:hover { background-position: -42px -10px; } .chosen-container-single.chosen-disabled .chosen-single abbr:hover { background-position: -42px -10px; } .chosen-container-single .chosen-single div { position: absolute; top: 0; right: 0; display: block; width: 18px; height: 100%; } .chosen-container-single .chosen-single div b { display: block; width: 100%; height: 100%; background: url('chosen-sprite.png') no-repeat 0px 2px; } .chosen-container-single .chosen-search { position: relative; z-index: 1010; margin: 0; padding: 3px 4px; white-space: nowrap; } .chosen-container-single .chosen-search input[type="text"] { margin: 1px 0; padding: 4px 20px 4px 5px; width: 100%; height: auto; outline: 0; border: 1px solid #aaa; background: white url('chosen-sprite.png') no-repeat 100% -20px; background: url('chosen-sprite.png') no-repeat 100% -20px; font-size: 1em; font-family: sans-serif; line-height: normal; border-radius: 0; } .chosen-container-single .chosen-drop { margin-top: -1px; border-radius: 0 0 4px 4px; background-clip: padding-box; } .chosen-container-single.chosen-container-single-nosearch .chosen-search { position: absolute; left: -9999px; } /* @end */ /* @group Results */ .chosen-container .chosen-results { color: #444; position: relative; overflow-x: hidden; overflow-y: auto; margin: 0 4px 4px 0; padding: 0 0 0 4px; max-height: 240px; -webkit-overflow-scrolling: touch; } .chosen-container .chosen-results li { display: none; margin: 0; padding: 5px 6px; list-style: none; line-height: 15px; word-wrap: break-word; -webkit-touch-callout: none; } .chosen-container .chosen-results li.active-result { display: list-item; cursor: pointer; } .chosen-container .chosen-results li.disabled-result { display: list-item; color: #ccc; cursor: default; } .chosen-container .chosen-results li.highlighted { background-color: #3875d7; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc)); background-image: -webkit-linear-gradient(#3875d7 20%, #2a62bc 90%); background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%); background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%); background-image: linear-gradient(#3875d7 20%, #2a62bc 90%); color: #fff; } .chosen-container .chosen-results li.no-results { color: #777; display: list-item; background: #f4f4f4; } .chosen-container .chosen-results li.group-result { display: list-item; font-weight: bold; cursor: default; } .chosen-container .chosen-results li.group-option { padding-left: 15px; } .chosen-container .chosen-results li em { font-style: normal; text-decoration: underline; } /* @end */ /* @group Multi Chosen */ .chosen-container-multi .chosen-choices { position: relative; overflow: hidden; margin: 0; padding: 0 5px; width: 100%; height: auto !important; height: 1%; border: 1px solid #aaa; background-color: #fff; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(1%, #eeeeee), color-stop(15%, #ffffff)); background-image: -webkit-linear-gradient(#eeeeee 1%, #ffffff 15%); background-image: -moz-linear-gradient(#eeeeee 1%, #ffffff 15%); background-image: -o-linear-gradient(#eeeeee 1%, #ffffff 15%); background-image: linear-gradient(#eeeeee 1%, #ffffff 15%); cursor: text; } .chosen-container-multi .chosen-choices li { float: left; list-style: none; } .chosen-container-multi .chosen-choices li.search-field { margin: 0; padding: 0; white-space: nowrap; } .chosen-container-multi .chosen-choices li.search-field input[type="text"] { margin: 1px 0; padding: 0; height: 25px; outline: 0; border: 0 !important; background: transparent !important; box-shadow: none; color: #999; font-size: 100%; font-family: sans-serif; line-height: normal; border-radius: 0; } .chosen-container-multi .chosen-choices li.search-choice { position: relative; margin: 3px 5px 3px 0; padding: 3px 20px 3px 5px; border: 1px solid #aaa; max-width: 100%; border-radius: 3px; background-color: #eeeeee; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee)); background-image: -webkit-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -moz-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -o-linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: linear-gradient(#f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-size: 100% 19px; background-repeat: repeat-x; background-clip: padding-box; box-shadow: 0 0 2px white inset, 0 1px 0 rgba(0, 0, 0, 0.05); color: #333; line-height: 13px; cursor: default; } .chosen-container-multi .chosen-choices li.search-choice span { word-wrap: break-word; } .chosen-container-multi .chosen-choices li.search-choice .search-choice-close { position: absolute; top: 4px; right: 3px; display: block; width: 12px; height: 12px; background: url('chosen-sprite.png') -42px 1px no-repeat; font-size: 1px; } .chosen-container-multi .chosen-choices li.search-choice .search-choice-close:hover { background-position: -42px -10px; } .chosen-container-multi .chosen-choices li.search-choice-disabled { padding-right: 5px; border: 1px solid #ccc; background-color: #e4e4e4; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #f4f4f4), color-stop(50%, #f0f0f0), color-stop(52%, #e8e8e8), color-stop(100%, #eeeeee)); background-image: -webkit-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -moz-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: -o-linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); background-image: linear-gradient(top, #f4f4f4 20%, #f0f0f0 50%, #e8e8e8 52%, #eeeeee 100%); color: #666; } .chosen-container-multi .chosen-choices li.search-choice-focus { background: #d4d4d4; } .chosen-container-multi .chosen-choices li.search-choice-focus .search-choice-close { background-position: -42px -10px; } .chosen-container-multi .chosen-results { margin: 0; padding: 0; } .chosen-container-multi .chosen-drop .result-selected { display: list-item; color: #ccc; cursor: default; } /* @end */ /* @group Active */ .chosen-container-active .chosen-single { border: 1px solid #5897fb; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); } .chosen-container-active.chosen-with-drop .chosen-single { border: 1px solid #aaa; -moz-border-radius-bottomright: 0; border-bottom-right-radius: 0; -moz-border-radius-bottomleft: 0; border-bottom-left-radius: 0; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #eeeeee), color-stop(80%, #ffffff)); background-image: -webkit-linear-gradient(#eeeeee 20%, #ffffff 80%); background-image: -moz-linear-gradient(#eeeeee 20%, #ffffff 80%); background-image: -o-linear-gradient(#eeeeee 20%, #ffffff 80%); background-image: linear-gradient(#eeeeee 20%, #ffffff 80%); box-shadow: 0 1px 0 #fff inset; } .chosen-container-active.chosen-with-drop .chosen-single div { border-left: none; background: transparent; } .chosen-container-active.chosen-with-drop .chosen-single div b { background-position: -18px 2px; } .chosen-container-active .chosen-choices { border: 1px solid #5897fb; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); } .chosen-container-active .chosen-choices li.search-field input[type="text"] { color: #222 !important; } /* @end */ /* @group Disabled Support */ .chosen-disabled { opacity: 0.5 !important; cursor: default; } .chosen-disabled .chosen-single { cursor: default; } .chosen-disabled .chosen-choices .search-choice .search-choice-close { cursor: default; } /* @end */ /* @group Right to Left */ .chosen-rtl { text-align: right; } .chosen-rtl .chosen-single { overflow: visible; padding: 0 8px 0 0; } .chosen-rtl .chosen-single span { margin-right: 0; margin-left: 26px; direction: rtl; } .chosen-rtl .chosen-single-with-deselect span { margin-left: 38px; } .chosen-rtl .chosen-single div { right: auto; left: 3px; } .chosen-rtl .chosen-single abbr { right: auto; left: 26px; } .chosen-rtl .chosen-choices li { float: right; } .chosen-rtl .chosen-choices li.search-field input[type="text"] { direction: rtl; } .chosen-rtl .chosen-choices li.search-choice { margin: 3px 5px 3px 0; padding: 3px 5px 3px 19px; } .chosen-rtl .chosen-choices li.search-choice .search-choice-close { right: auto; left: 4px; } .chosen-rtl.chosen-container-single-nosearch .chosen-search, .chosen-rtl .chosen-drop { left: 9999px; } .chosen-rtl.chosen-container-single .chosen-results { margin: 0 0 4px 4px; padding: 0 4px 0 0; } .chosen-rtl .chosen-results li.group-option { padding-right: 15px; padding-left: 0; } .chosen-rtl.chosen-container-active.chosen-with-drop .chosen-single div { border-right: none; } .chosen-rtl .chosen-search input[type="text"] { padding: 4px 5px 4px 20px; background: white url('chosen-sprite.png') no-repeat -30px -20px; background: url('chosen-sprite.png') no-repeat -30px -20px; direction: rtl; } .chosen-rtl.chosen-container-single .chosen-single div b { background-position: 6px 2px; } .chosen-rtl.chosen-container-single.chosen-with-drop .chosen-single div b { background-position: -12px 2px; } /* @end */ /* @group Retina compatibility */ @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-resolution: 144dpi) { .chosen-rtl .chosen-search input[type="text"], .chosen-container-single .chosen-single abbr, .chosen-container-single .chosen-single div b, .chosen-container-single .chosen-search input[type="text"], .chosen-container-multi .chosen-choices .search-choice .search-choice-close, .chosen-container .chosen-results-scroll-down span, .chosen-container .chosen-results-scroll-up span { background-image: url('chosen-sprite@2x.png') !important; background-size: 52px 37px !important; background-repeat: no-repeat !important; } } select.form-control + .chosen-container.chosen-container-single .chosen-single { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.428571429; color: #555; vertical-align: middle; background-color: #fff; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; background-image:none; } select.form-control + .chosen-container.chosen-container-single .chosen-single div { top:4px; color:#000; } select.form-control + .chosen-container .chosen-drop { background-color: #FFF; border: 1px solid #CCC; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 4px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); background-clip: padding-box; margin: 2px 0 0; } select.form-control + .chosen-container .chosen-search input[type=text] { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.428571429; color: #555; vertical-align: middle; background-color: #FFF; border: 1px solid #CCC; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; background-image:none; } select.form-control + .chosen-container .chosen-results { margin: 2px 0 0; padding: 5px 0; font-size: 14px; list-style: none; background-color: #fff; margin-bottom: 5px; } select.form-control + .chosen-container .chosen-results li , select.form-control + .chosen-container .chosen-results li.active-result { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 1.428571429; color: #333; white-space: nowrap; background-image:none; } select.form-control + .chosen-container .chosen-results li:hover, select.form-control + .chosen-container .chosen-results li.active-result:hover, select.form-control + .chosen-container .chosen-results li.highlighted { color: #FFF; text-decoration: none; background-color: #428BCA; background-image:none; } select.form-control + .chosen-container-multi .chosen-choices { display: block; width: 100%; min-height: 34px; padding: 6px; font-size: 14px; line-height: 1.428571429; color: #555; vertical-align: middle; background-color: #FFF; border: 1px solid #CCC; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; background-image:none; } select.form-control + .chosen-container-multi .chosen-choices li.search-field input[type="text"] { height:auto; padding:5px 0; } select.form-control + .chosen-container-multi .chosen-choices li.search-choice { background-image: none; padding: 3px 24px 3px 5px; margin: 0 6px 0 0; font-size: 14px; font-weight: normal; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; border: 1px solid #ccc; border-radius: 4px; color: #333; background-color: #FFF; border-color: #CCC; } select.form-control + .chosen-container-multi .chosen-choices li.search-choice .search-choice-close { top:8px; right:6px; } select.form-control + .chosen-container-multi.chosen-container-active .chosen-choices, select.form-control + .chosen-container.chosen-container-single.chosen-container-active .chosen-single, select.form-control + .chosen-container .chosen-search input[type=text]:focus{ border-color: #66AFE9; outline: 0; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6); } /* @end */
CorporacioDigital/iMovers
plugins/tpv_informatica/chosen.css
CSS
agpl-3.0
17,365
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <head> <link rel="stylesheet" type="text/css" href="./../docs/css/style.css"/> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="author" value="JMeter developers"> <meta name="email" value="dev AT jmeter.apache.org"> <title>Apache JMeter - Changes</title> </head> <body bgcolor="#ffffff" text="#000000" link="#525D76"> <table border="0" cellspacing="0"> <tr> <td align="left"> <a href="http://www.apache.org"><img title="Apache Software Foundation" width="387" height="100" src="./../docs/images/asf-logo.gif" border="0"/></a> </td> <td align="right"> <a href="http://jmeter.apache.org/"><img width="221" height="102" src="./../docs/images/logo.jpg" alt="Apache JMeter" title="Apache JMeter" border="0"></a> </td> </tr> </table> <table border="0" cellspacing="4"> <tr><td> <hr noshade size="1"> </td></tr> <tr> <td align="left" valign="top"> <br> <table border="0" cellspacing="0" cellpadding="2" width="100%"> <tr><td bgcolor="#525D76"> <font color="#ffffff" face="arial,helvetica,sanserif"> <strong>Changes</strong></font> </td></tr> <tr><td> <blockquote> <p><table border="1" bgcolor="#bbbb00" width="50%" cellspacing="0" cellpadding="2"> <tr><td> <b> This page details the changes made in the current version only. </b> <br> Earlier changes are detailed in the <a href="changes_history.html"> History of Previous Changes </a> . </td></tr> </table></p> <h1> Version 2.7 </h1> <h2> New and Noteworthy </h2> <h3> OS Process Sampler </h3> <p> A new System Sampler that can be used to execute commands on the local machine. <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='629' height='497' src="./../docs/images/screenshots/changes/2.7/01_os_process_sampler.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> OS Process Sampler results example with DNS lookup command 'dig' <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='877' height='470' src="./../docs/images/screenshots/changes/2.7/02_os_process_example_results.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> JMS Samplers improvements </h3> <p> Addition of a "Non Persistent Delivery" option to send "Non-Persistent" (Guaranteed to be delivered at most once. Message loss is not a concern.) JMS messages <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='953' height='336' src="./../docs/images/screenshots/changes/2.7/11_jms_non_persistent_delivery_mode.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> Support sending of JMS Object Messages to enable sending Objects unmarshalled from XML by XStream <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='808' height='726' src="./../docs/images/screenshots/changes/2.7/12_jms_sending_objects.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> Enable setting JMS Properties through JMS Publisher sampler <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1029' height='470' src="./../docs/images/screenshots/changes/2.7/13_jms_properties.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Test Action sampler </h3> <p> Allow premature exit from a loop <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='862' height='167' src="./../docs/images/screenshots/changes/2.7/07_test_action_next_iter.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Webservice Sampler improvements </h3> <p> Add a jmeter property soap.document_cache to control size of Document Cache <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='270' height='59' src="./../docs/images/screenshots/changes/2.7/14_ws_document_cache.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> Make Maintain HTTP Session configurable <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='833' height='505' src="./../docs/images/screenshots/changes/2.7/15_ws_maintain_session.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Aggregate graph: Clustered Bar char with average, median, 90% line, min and max columns </h3> <p> Aggregate graph changes to Clustered Bar chart, add more columns (median, 90% line, min, max) and options, fixed some bugs. <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1177' height='503' src="./../docs/images/screenshots/changes/2.7/03_aggregate_graph_with_new_cols.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> New settings for aggregate graph <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1173' height='433' src="./../docs/images/screenshots/changes/2.7/04_aggregate_graph_parameters.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Improvements of HTML report design generated by JMeter Ant task in extras folder </h3> <p> HTML report example <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1264' height='506' src="./../docs/images/screenshots/changes/2.7/05_jmeter_ant_task_report_success.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> HTML report example with some assertion errors <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='1267' height='550' src="./../docs/images/screenshots/changes/2.7/06_jmeter_ant_task_report_errors.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Mailer Visualizer </h3> <p> <ul> <li> Enable authentication, and connection security with SSL or TLS </li> <li> Improve GUI design </li> <li> Add internationalisation (i18n) support </li> </ul> <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='860' height='403' src="./../docs/images/screenshots/changes/2.7/10_mailer_visualizer_gui.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> New Visual Indicator of number of ERROR/FATAL messages in logs </h3> <p> Indicator shows number of ERROR/FATAL messsages in logs, it can be clicked to toggle Log Viewer panel <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='815' height='633' src="./../docs/images/screenshots/changes/2.7/16_log_errors_counter.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Dialog box to show detail of a parameter row </h3> <p> Add a detail button on parameters table to show detail of a Row <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='824' height='165' src="./../docs/images/screenshots/changes/2.7/08_param_button_detail.png"><br> <font size="-1"></font></td></tr></table></p> </p> <p> Detail box example <p><table border="0" cellspacing="0" cellpadding="0"><tr><td><img width='702' height='454' src="./../docs/images/screenshots/changes/2.7/09_detail_box.png"><br> <font size="-1"></font></td></tr></table></p> </p> <h3> Plugin writers </h3> <p> New interface org.apache.jmeter.engine.util.ConfigMergabilityIndicator has been introduced to tell whether a ConfigTestElement can be merged in Sampler (see Bug 53042): <br> <pre> public boolean applies(ConfigTestElement configElement); </pre> </p> <p> New interface org.apache.jmeter.protocol.http.proxy.SamplerCreator to allow plugging HTTP based samplers that differ from default HTTP Samplers through Proxy during Recording Phase (see Bug 52674): <br> <pre> public String[] getManagedContentTypes(); </pre> <pre> public HTTPSamplerBase createSampler(HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings); </pre> <pre> public void populateSampler(HTTPSamplerBase sampler, HttpRequestHdr request, Map<String, String> pageEncodings, Map<String, String> formEncodings) throws Exception; </pre> </p> <h2> Known bugs </h2> <p> The Once Only controller behaves correctly under a Thread Group or Loop Controller, but otherwise its behaviour is not consistent (or clearly specified). </p> <p> Listeners don't show iteration counts when a If Controller has a condition which is always false from the first iteration (see Bug 52496). A workaround is to add a sampler at the same level as (or superior to) the If Controller. For example a Test Action sampler with 0 wait time (which doesn't generate a sample), or a Debug Sampler with all fields set to False (to reduce the sample size). </p> <h2> Incompatible changes </h2> <p> When doing replacement of User Defined Variables, Proxy will not substitute partial values anymore when "Regexp matching" is used. It will use Perl 5 word matching ("\b") </p> <p> In User Defined Variables, Test Plan, HTTP Sampler Arguments Table, Java Request Defaults, JMS Sampler and Publisher, LDAP Request Defaults and LDAP Extended Request Defaults, rows with empty Name and Value are no more saved. </p> <p> JMeter now expands the Test Plan tree to the testplan level and no further and selects the root of the tree. Furthermore default value of onload.expandtree is false. </p> <p> Graph Full Results Listener has been removed. </p> <p> When calling "Clear All" command, if Log Viewer is displayed its content will be cleared. </p> <h2> Bug fixes </h2> <h3> HTTP Samplers and Proxy </h3> <ul> <li> Bug 52613 - Using Raw Post Body option, text gets encoded </li> <li> Bug 52781 - Content-Disposition header garbled even if browser compatible headers is checked (HC4) </li> <li> Bug 52796 - MonitorHandler fails to clear variables when starting a new parse </li> <li> Bug 52871 - Multiple Certificates not working with HTTP Client 4 </li> <li> Bug 52885 - Proxy : Recording issues with HTTPS, cookies starting with secure are partly truncated </li> <li> Bug 52886 - Proxy : Recording issues with HTTPS when spoofing is on, secure cookies are not always changed </li> <li> Bug 52897 - HTTPSampler : Using PUT method with HTTPClient4 and empty Content Encoding and sending files leads to NullPointerException </li> <li> Bug 53145 - HTTP Sampler - function in path evaluated too early </li> </ul> <h3> Other Samplers </h3> <ul> <li> Bug 51737 - TCPSampler : Packet gets converted/corrupted </li> <li> Bug 52868 - BSF language list should be sorted </li> <li> Bug 52869 - JSR223 language list currently uses BSF list which is wrong </li> <li> Bug 52932 - JDBC Sampler : Sampler is not marked in error in an Exception which is not of class IOException, SQLException, IOException occurs </li> <li> Bug 52916 - JDBC Exception if there is an empty user defined variable </li> <li> Bug 52937 - Webservice Sampler : Clear Soap Documents Cache at end of Test </li> <li> Bug 53027 - Jmeter starts throwing exceptions while using SMTP Sample in a test plan with HTTP Cookie Mngr or HTTP Request Defaults </li> <li> Bug 53072 - JDBC PREPARED SELECT statements should return results in variables like non prepared SELECT </li> </ul> <h3> Controllers </h3> <ul> <li> Bug 52968 - Option Start Next Loop in Thread Group does not mark parent Transaction Sampler in error when an error occurs </li> <li> Bug 50898 - IncludeController : NullPointerException loading script in non-GUI mode if Includers use same element name </li> </ul> <h3> Listeners </h3> <ul> <li> Bug 43450 - Listeners/Savers assume SampleResult count is always 1; fixed Generate Summary Results </li> </ul> <h3> Assertions </h3> <ul> <li> Bug 52848 - NullPointer in "XPath Assertion" </li> </ul> <h3> Functions </h3> <ul> </ul> <h3> I18N </h3> <ul> <li> Bug 52551 - Function Helper Dialog does not switch language correctly </li> <li> Bug 52552 - Help reference only works in English </li> </ul> <h3> General </h3> <ul> <li> Bug 52639 - JSplitPane divider for log panel should be hidden if log is not activated </li> <li> Bug 52672 - Change Controller action deletes all but one child samplers </li> <li> Bug 52694 - Deadlock in GUI related to non AWT Threads updating GUI </li> <li> Bug 52678 - Proxy : When doing replacement of UserDefinedVariables, partial values should not be substituted </li> <li> Bug 52728 - CSV Data Set Config element cannot coexist with BSF Sampler in same Thread Plan </li> <li> Bug 52762 - Problem with multiples certificates: first index not used until indexes are restarted </li> <li> Bug 52741 - TestBeanGUI default values do not work at second time or later </li> <li> Bug 52783 - oro.patterncache.size property never used due to early init </li> <li> Bug 52789 - Proxy with Regexp Matching can fail with NullPointerException in Value Replacement if value is null </li> <li> Bug 52645 - Recording with Proxy leads to OutOfMemory </li> <li> Bug 52679 - User Parameters columns narrow </li> <li> Bug 52843 - Sample headerSize and bodySize not being accumulated for subsamples </li> <li> Bug 52967 - The function __P() couldn't use default value when running with remote server in GUI mode. </li> <li> Bug 50799 - Having a non-HTTP sampler in a http test plan prevents multiple header managers from working </li> <li> Bug 52997 - Jmeter should not exit without saving Test Plan if saving before exit fails </li> <li> Bug 53136 - Catching Throwable needs to be carefully handled </li> </ul> <h2> Improvements </h2> <h3> HTTP Samplers </h3> <ul> </ul> <h3> Other samplers </h3> <ul> <li> Bug 52775 - JMS Publisher : Add Non Persistent Delivery option </li> <li> Bug 52810 - Enable setting JMS Properties through JMS Publisher sampler </li> <li> Bug 52938 - Webservice Sampler : Add a jmeter property soap.document_cache to control size of Document Cache </li> <li> Bug 52939 - Webservice Sampler : Make MaintainSession configurable </li> <li> Bug 53073 - Allow to assign the OUT result of a JDBC CALLABLE to JMeter variables </li> <li> Bug 53164 - New System Sampler </li> <li> Bug 53172 - OS Process Sampler - allow specification of Environment Variables </li> <li> Bug 52936 - JMS Publisher : Support sending of JMS Object Messages </li> </ul> <h3> Controllers </h3> <ul> </ul> <h3> Listeners </h3> <ul> <li> Bug 52603 - MailerVisualizer : Enable SSL , TLS and Authentication </li> <li> Bug 52698 - Remove Graph Full Results Listener </li> <li> Bug 53070 - Change Aggregate graph to Clustered Bar chart, add more columns (median, 90% line, min, max) and options, fixed some bugs </li> <li> Bug 53246 - Mailer Visualizer: improve GUI design and I18N </li> </ul> <h3> Timers, Assertions, Config, Pre- & Post-Processors </h3> <ul> </ul> <h3> Functions </h3> <ul> </ul> <h3> I18N </h3> <ul> <li> Mailer Visualizer has been internationalized. French translation added. (see Bug 53246) </li> </ul> <h3> General </h3> <ul> <li> Bug 45839 - Test Action : Allow premature exit from a loop </li> <li> Bug 52614 - MailerModel.sendMail has strange way to calculate debug setting </li> <li> Bug 52782 - Add a detail button on parameters table to show detail of a Row </li> <li> Bug 52674 - Proxy : Add a Sampler Creator to allow plugging HTTP based samplers using potentially non textual POST Body (AMF, Silverlight...) and customizing them for others </li> <li> Bug 52934 - GUI : Open Test plan with the tree expanded to the testplan level and no further and select the root of the tree </li> <li> Bug 52941 - Improvements of HTML report design generated by JMeter Ant task extra </li> <li> Bug 53042 - Introduce a new method in Sampler interface to allow Sampler to decide wether a config element applies to Sampler </li> <li> Bug 52771 - Documentation : Added RSS feed on JMeter Home page under link "Subscribe to What's New" </li> <li> Bug 42784 - Show the number of errors logged in the GUI </li> <li> Bug 53256 - Make Clear All command clean LogViewer content </li> <li> Bug 53261 - Make "Error/fatal" counter added in Bug 42784 open Log Viewer panel when Warn Indicator is clicked </li> </ul> <h2> Non-functional changes </h2> <ul> <li> Upgraded to rhino 1.7R3 (was js-1.7R2.jar). Note: the Maven coordinates for the jar were changed from rhino:js to org.mozilla:rhino. This does not affect JMeter directly, but might cause problems if using JMeter in a Maven project with other code that depends on an earlier version of the Rhino Javascript jar. </li> <li> Bug 52675 - Refactor Proxy and HttpRequestHdr to allow Sampler Creation by Proxy </li> <li> Bug 52680 - Mention version in which function was introduced </li> <li> Bug 52788 - HttpRequestHdr : Optimize code to avoid useless work </li> <li> JMeter Ant (ant-jmeter-1.1.1.jar) task was upgraded from 1.0.9 to 1.1.1 </li> <li> Updated to commons-io 2.2 (from 2.1) </li> <li> Bug 53129 - Upgrade XStream from 1.3.1 to 1.4.2 </li> <li> Updated to httpcomponents-client 4.1.3 (from 4.1.2) </li> <li> Updated JMeter distributed testing guide (jmeter_distributed_testing_step_by_step.pdf). Changes source format to OpenOffice odt (from sxw) </li> </ul> </blockquote> </p> </td></tr> <tr><td><br></td></tr> </table> <br> </td> </tr> <tr><td> <hr noshade size="1"> </td></tr> <tr> <td> <table width=100%> <tr> <td align="center"> <font color="#525D76" size="-1"><em> Copyright &copy; 1999-2012, Apache Software Foundation </em></font> </td> </tr> <tr><td colspan="2"> <div align="center"><font color="#525D76" size="-1"> Apache, Apache JMeter, JMeter, the Apache feather, and the Apache JMeter logo are trademarks of the Apache Software Foundation. </font> </div> </td></tr> </table> </td> </tr> </table> </body> </html>
telefonicaid/notification_server
test/jmeter/apache-jmeter-2.7/printable_docs/changes.html
HTML
agpl-3.0
18,325
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.File; /** * This file isn't long for this world. It's just something I've been using * to debug multi-process rejoin stuff. * */ public class VLog { static File m_logfile = new File("vlog.txt"); public synchronized static void setPortNo(int portNo) { m_logfile = new File(String.format("vlog-%d.txt", portNo)); } public synchronized static void log(String str) { // turn off this stupid thing for now /*try { FileWriter log = new FileWriter(m_logfile, true); log.write(str + "\n"); log.flush(); log.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } public static void log(String format, Object... args) { log(String.format(format, args)); } }
migue/voltdb
src/frontend/org/voltdb/VLog.java
Java
agpl-3.0
1,623
<!-- title: Earning Type --> <div class="dev-header"> <a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;"> Version 6.7.7</a> <a class="btn btn-default btn-sm" href="https://github.com/frappe/erpnext/tree/develop/erpnext/hr/doctype/earning_type" target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a> </div> <p><b>Table Name:</b> <code>tabEarning Type</code></p> <h3>Fields</h3> <table class="table table-bordered" style="table-layout: fixed;"> <thead> <tr> <th style="width: 5%">Sr</th> <th style="width: 25%">Fieldname</th> <th style="width: 20%">Type</th> <th style="width: 25%">Label</th> <th style="width: 25%">Options</th> </tr> </thead> <tbody> <tr > <td>1</td> <td class="danger" title="Mandatory"><code>earning_name</code></td> <td > Data</td> <td > Name </td> <td></td> </tr> <tr > <td>2</td> <td ><code>description</code></td> <td > Small Text</td> <td > Description </td> <td></td> </tr> </tbody> </table> <hr> <h3>Controller</h3> <h4>erpnext.hr.doctype.earning_type.earning_type</h4> <h3 style="font-weight: normal;">Class <b>EarningType</b></h3> <p style="padding-left: 30px;"><i>Inherits from frappe.model.document.Document</i></h4> <div class="docs-attr-desc"><p></p> </div> <div style="padding-left: 30px;"> </div> <hr> <h4>Linked In:</h4> <ul> <li> <a href="https://frappe.github.io/erpnext/current/models/hr/salary_slip_earning">Salary Slip Earning</a> </li> <li> <a href="https://frappe.github.io/erpnext/current/models/hr/salary_structure_earning">Salary Structure Earning</a> </li> </ul> <!-- autodoc --> <!-- jinja --> <!-- static -->
indictranstech/trufil-erpnext
erpnext/docs/current/models/hr/earning_type.html
HTML
agpl-3.0
2,253
// Generated by CoffeeScript 1.10.0 var api, baseOVHKonnector, connector, name, slug; baseOVHKonnector = require('../lib/base_ovh_konnector'); name = 'Kimsufi EU'; slug = 'kimsufi_eu'; api = { endpoint: 'kimsufi-eu', appKey: '', appSecret: '' }; connector = module.exports = baseOVHKonnector.createNew(api, name, slug);
frankrousseau/konnectors
build/server/konnectors/kimsufi_eu.js
JavaScript
agpl-3.0
331
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2022 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.enums; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ public enum BeaconIndexType implements EnumAsString { LOG("Log"), STATE("State"); private String value; BeaconIndexType(String value) { this.value = value; } @Override public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public static BeaconIndexType get(String value) { if(value == null) { return null; } // goes over BeaconIndexType defined values and compare the inner value with the given one: for(BeaconIndexType item: values()) { if(item.getValue().equals(value)) { return item; } } // in case the requested value was not found in the enum values, we return the first item as default. return BeaconIndexType.values().length > 0 ? BeaconIndexType.values()[0]: null; } }
kaltura/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/enums/BeaconIndexType.java
Java
agpl-3.0
2,312
package NonameTV::Importer::TV2; use strict; use warnings; =pod Import data from Viasat's press-site. The data is downloaded in tab-separated text-files. Features: Proper episode and season fields. The episode-field contains a number that is relative to the start of the series, not to the start of this season. program_type =cut use DateTime; use Date::Parse; use Encode; use NonameTV qw/MyGet expand_entities AddCategory norm/; use NonameTV::DataStore::Helper; use NonameTV::Log qw/progress error/; use NonameTV::Importer::BaseWeekly; use base 'NonameTV::Importer::BaseWeekly'; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = $class->SUPER::new( @_ ); bless ($self, $class); defined( $self->{UrlRoot} ) or die "You must specify UrlRoot"; my $dsh = NonameTV::DataStore::Helper->new( $self->{datastore}, "Europe/Oslo" ); $self->{datastorehelper} = $dsh; return $self; } sub ImportContent { my $self = shift; my( $batch_id, $cref, $chd ) = @_; #my $ds = $self->{datastore}; my $dsh = $self->{datastorehelper}; # Decode the string into perl's internal format. # see perldoc Encode # my $str = decode( "utf-8", $$cref ); my $str = decode( "iso-8859-1", $$cref ); my @rows = split("\n", $str ); if( scalar( @rows < 2 ) ) { error( "$batch_id: No data found" ); return 0; } my $columns = [ split( "\t", $rows[0] ) ]; my $date = ""; my $olddate = ""; #print ( $batch_id ); for ( my $i = 1; $i < scalar @rows; $i++ ) { my $inrow = $self->row_to_hash($batch_id, $rows[$i], $columns ); $date = $inrow->{'SENDEDATO'}; if ($date ne $olddate) { my $ymd = parseDate(fq( $date )); #print "\n>>>STARTING NEW DATE $ymd <<<\n"; $dsh->StartDate( $ymd ); } $olddate = $date; #$date = substr( $date, 0, 10 ); #$date =~ s/\./-/; #if ( exists($inrow->{'Date'}) ) #{ # $dsh->StartDate( $inrow->{'Date'} ); #} my $start = $inrow->{'SENDETID'}; #my ($date, $time) = split(/ /, $start); #$date =~ s/\./-/; #$time =~ s/\./:/; #$date = turnDate($date); #$start = "$date $time"; #print norm($start); $start = parseStart(fq($start)); #my $start = $inrow->{'Start time'}; #my $start = $starttime; my $title = norm( $inrow->{'NORSKTITTEL'} ); $title = fq($title); my $description = fq( norm( $inrow->{'EPISODESYNOPSIS'} )); if ($description eq "") { $description = fq( norm( $inrow->{'GENERELL_SYNOPSIS'} )); } my $subtitle = fq( norm ($inrow->{'EPISODETITTEL'})); if ($subtitle eq "") { $subtitle = fq( norm( $inrow->{'OVERSKRIFT'})) } #$description = norm( $description ); #$description = fq( $description ); # Episode info in xmltv-format #my $ep_nr = norm(fq($inrow->{'EPISODENUMMER'})) || 0; #my $ep_se = norm(fq($inrow->{'SESONGNUMMER'})) || 0; #my $episode = undef; # #if( ($ep_nr > 0) and ($ep_se > 0) ) #{ # $episode = sprintf( "%d . %d .", $ep_se-1, $ep_nr-1 ); #} #elsif( $ep_nr > 0 ) #{ # $episode = sprintf( ". %d .", $ep_nr-1 ); #} my $ce = { channel_id => $chd->{id}, title => $title, description => $description, subtitle => $subtitle, start_time => $start, #episode => $episode, }; if( defined( $inrow->{'PRODUKSJONSAARKOPI'} ) and $inrow->{'PRODUKSJONSAARKOPI'} =~ /(\d\d\d\d)/ ) { $ce->{production_date} = "$1-01-01"; } my $cast = norm( $inrow->{'ROLLEBESKRIVELSE'} ); $cast = fq( $cast ); if( $cast =~ /\S/ ) { # Remove all variants of m.fl. $cast =~ s/\s*m[\. ]*fl\.*\b//; # Remove trailing '.' $cast =~ s/\.$//; my @actors = split( /\s*,\s*/, $cast ); foreach (@actors) { # The character name is sometimes given in parentheses. Remove it. # The Cast-entry is sometimes cutoff, which means that the # character name might be missing a trailing ). s/\s*\(.*$//; } $ce->{actors} = join( ", ", grep( /\S/, @actors ) ); } my $director = norm( $inrow->{'REGI'} ); $director = fq( $director ); if( $director =~ /\S/ ) { # Remove all variants of m.fl. $director =~ s/\s*m[\. ]*fl\.*\b//; # Remove trailing '.' $director =~ s/\.$//; my @directors = split( /\s*,\s*/, $director ); $ce->{directors} = join( ", ", grep( /\S/, @directors ) ); } #$self->extract_extra_info( $ce ); $dsh->AddProgramme( $ce ); } # Success return 1; } sub FetchDataFromSite { my $self = shift; my( $batch_id, $data ) = @_; my( $year, $week ) = ( $batch_id =~ /(\d+)-(\d+)$/ ); my $url = sprintf( "%s_%01d_%s_%02d.xls", $self->{UrlRoot}, $week, $data->{grabber_info}, $year); my( $content, $code ) = MyGet( $url ); return( $content, $code ); } sub row_to_hash { my $self = shift; my( $batch_id, $row, $columns ) = @_; $row =~ s/\t.$//; # if $(row) my @coldata = split( "\t", $row ); my %res; if( scalar( @coldata ) > scalar( @{$columns} ) ) { error( "$batch_id: Too many data columns " . scalar( @coldata ) . " > " . scalar( @{$columns} ) ); } for( my $i=0; $i<scalar(@coldata) and $i<scalar(@{$columns}); $i++ ) { $res{$columns->[$i]} = norm($coldata[$i]) if $coldata[$i] =~ /\S/; } return \%res; } sub parseStart { my ($string) = @_; #my $string = @$in[0]; #print "PARSESTART: $string\n"; my $day = substr( $string, 0, 2 ); my $mnt = substr( $string, 3, 2 ); my $yr = substr( $string, 6, 4 ); my $hr = substr( $string, 11, 2 ); my $min = substr( $string, 14, 2 ); return ( "$hr:$min:00"); } sub parseDate { my ($string) = @_; my $day = substr( $string, 0, 2 ); my $mnt = substr( $string, 3, 2 ); my $year = substr( $string, 6, 4 ); return ("$year-$mnt-$day"); } sub fq { # Remove quotes from strings my ($string) = @_; $string =~ s/^"//; $string =~ s/"$//; return $string; } 1;
mattiash/nonametv
lib/NonameTV/Importer/TV2.pm
Perl
agpl-3.0
6,211
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.admin.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Cornel Ventuneac */ public class ConfigLocationLiteVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.admin.vo.ConfigLocationLiteVo copy(ims.admin.vo.ConfigLocationLiteVo valueObjectDest, ims.admin.vo.ConfigLocationLiteVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_Location(valueObjectSrc.getID_Location()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // Name valueObjectDest.setName(valueObjectSrc.getName()); // Type valueObjectDest.setType(valueObjectSrc.getType()); // isActive valueObjectDest.setIsActive(valueObjectSrc.getIsActive()); // Address valueObjectDest.setAddress(valueObjectSrc.getAddress()); // IsVirtual valueObjectDest.setIsVirtual(valueObjectSrc.getIsVirtual()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects. */ public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.Set domainObjectSet) { return createConfigLocationLiteVoCollectionFromLocation(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects. */ public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.Set domainObjectSet) { ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) iterator.next(); ims.admin.vo.ConfigLocationLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects. */ public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.List domainObjectList) { return createConfigLocationLiteVoCollectionFromLocation(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects. */ public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.List domainObjectList) { ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) domainObjectList.get(i); ims.admin.vo.ConfigLocationLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.resource.place.domain.objects.Location set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection) { return extractLocationSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i); ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.resource.place.domain.objects.Location list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection) { return extractLocationList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i); ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.resource.place.domain.objects.Location object. * @param domainObject ims.core.resource.place.domain.objects.Location */ public static ims.admin.vo.ConfigLocationLiteVo create(ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.resource.place.domain.objects.Location object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.admin.vo.ConfigLocationLiteVo create(DomainObjectMap map, ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.admin.vo.ConfigLocationLiteVo valueObject = (ims.admin.vo.ConfigLocationLiteVo) map.getValueObject(domainObject, ims.admin.vo.ConfigLocationLiteVo.class); if ( null == valueObject ) { valueObject = new ims.admin.vo.ConfigLocationLiteVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.resource.place.domain.objects.Location */ public static ims.admin.vo.ConfigLocationLiteVo insert(ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.resource.place.domain.objects.Location */ public static ims.admin.vo.ConfigLocationLiteVo insert(DomainObjectMap map, ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_Location(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // Name valueObject.setName(domainObject.getName()); // Type ims.domain.lookups.LookupInstance instance2 = domainObject.getType(); if ( null != instance2 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance2.getImage() != null) { img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath()); } color = instance2.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.LocationType voLookup2 = new ims.core.vo.lookups.LocationType(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color); ims.core.vo.lookups.LocationType parentVoLookup2 = voLookup2; ims.domain.lookups.LookupInstance parent2 = instance2.getParent(); while (parent2 != null) { if (parent2.getImage() != null) { img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() ); } else { img = null; } color = parent2.getColor(); if (color != null) color.getValue(); parentVoLookup2.setParent(new ims.core.vo.lookups.LocationType(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color)); parentVoLookup2 = parentVoLookup2.getParent(); parent2 = parent2.getParent(); } valueObject.setType(voLookup2); } // isActive valueObject.setIsActive( domainObject.isIsActive() ); // Address valueObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.create(map, domainObject.getAddress()) ); // IsVirtual valueObject.setIsVirtual( domainObject.isIsVirtual() ); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject) { return extractLocation(domainFactory, valueObject, new HashMap()); } public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_Location(); ims.core.resource.place.domain.objects.Location domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject); } // ims.admin.vo.ConfigLocationLiteVo ID_Location field is unknown domainObject = new ims.core.resource.place.domain.objects.Location(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location()); if (domMap.get(key) != null) { return (ims.core.resource.place.domain.objects.Location)domMap.get(key); } domainObject = (ims.core.resource.place.domain.objects.Location) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_Location()); //This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly //Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least. if (valueObject.getName() != null && valueObject.getName().equals("")) { valueObject.setName(null); } domainObject.setName(valueObject.getName()); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value2 = null; if ( null != valueObject.getType() ) { value2 = domainFactory.getLookupInstance(valueObject.getType().getID()); } domainObject.setType(value2); domainObject.setIsActive(valueObject.getIsActive()); // SaveAsRefVO - treated as a refVo in extract methods ims.core.generic.domain.objects.Address value4 = null; if ( null != valueObject.getAddress() ) { if (valueObject.getAddress().getBoId() == null) { if (domMap.get(valueObject.getAddress()) != null) { value4 = (ims.core.generic.domain.objects.Address)domMap.get(valueObject.getAddress()); } } else { value4 = (ims.core.generic.domain.objects.Address)domainFactory.getDomainObject(ims.core.generic.domain.objects.Address.class, valueObject.getAddress().getBoId()); } } domainObject.setAddress(value4); domainObject.setIsVirtual(valueObject.getIsVirtual()); return domainObject; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/admin/vo/domain/ConfigLocationLiteVoAssembler.java
Java
agpl-3.0
19,428
require 'test_helper' class PolitizacaosControllerTest < ActionController::TestCase setup do @politizacao = politizacaos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:politizacaos) end test "should get new" do get :new assert_response :success end test "should create politizacao" do assert_difference('Politizacao.count') do post :create, politizacao: { body: @politizacao.body, title: @politizacao.title } end assert_redirected_to politizacao_path(assigns(:politizacao)) end test "should show politizacao" do get :show, id: @politizacao assert_response :success end test "should get edit" do get :edit, id: @politizacao assert_response :success end test "should update politizacao" do patch :update, id: @politizacao, politizacao: { body: @politizacao.body, title: @politizacao.title } assert_redirected_to politizacao_path(assigns(:politizacao)) end test "should destroy politizacao" do assert_difference('Politizacao.count', -1) do delete :destroy, id: @politizacao end assert_redirected_to politizacaos_path end end
ricardopoppi/politiquese
test/controllers/politizacaos_controller_test.rb
Ruby
agpl-3.0
1,198
delete from configuration_settings where key = 'VACCINE_DASHBOARD_DEFAULT_PRODUCT'; INSERT INTO configuration_settings (key, name, groupname, description, value, valueType, displayOrder) values ('VACCINE_DASHBOARD_DEFAULT_PRODUCT', 'Configure Default vaccine product', 'Dashboard', '','2412', 'TEXT', 1); delete from configuration_settings where key = 'VACCINE_DASHBOARD_DEFAULT_PERIOD_TREND'; INSERT INTO configuration_settings (key, name, groupname, description, value, valueType, displayOrder) values ('VACCINE_DASHBOARD_DEFAULT_PERIOD_TREND', 'Configure Default vaccine period trend', 'Dashboard', '','4', 'NUMBER', 1);
kelvinmbwilo/open_elmis
modules/migration/src/main/resources/db/migration/archive/vaccine/reports/conf/V658__add_vaccine_dashboard_default_values.sql
SQL
agpl-3.0
637
/* Taken from a very informative blogpost by Eldar Djafarov: * http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/ */ (function() { 'use strict'; module.exports = { /* Forces an update when the underlying Backbone model instance has * changed. Users will have to implement getBackboneModels(). * Also requires that React is loaded with addons. */ __syncedModels: [], componentDidMount: function() { // Whenever there may be a change in the Backbone data, trigger a reconcile. this.getBackboneModels().forEach(this.injectModel, this); }, componentWillUnmount: function() { // Ensure that we clean up any dangling references when the component is // destroyed. this.__syncedModels.forEach(function(model) { model.off(null, model.__updater, this); }, this); }, injectModel: function(model){ if(!~this.__syncedModels.indexOf(model)){ var updater = function() { try { this.forceUpdate(); } catch(e) { // This means the component is already being updated somewhere // else, so we just silently go on with our business. // This is most likely due to some AJAX callback that already // updated the model at the same time or slightly earlier. } }.bind(this, null); model.__updater = updater; model.on('add change remove', updater, this); } }, bindTo: function(model, key){ /* Allows for two-way databinding for Backbone models. * Use by passing it as a 'valueLink' property, e.g.: * valueLink={this.bindTo(model, attribute)} */ return { value: model.get(key), requestChange: function(value){ model.set(key, value); }.bind(this) }; } }; })();
jbaiter/spreads
spreadsplug/web/client/lib/backbonemixin.js
JavaScript
agpl-3.0
1,858
<?php use_helper('Text') ?> <?php if (QubitTerm::REFERENCE_ID == $usageType): ?> <?php if (isset($link)): ?> <?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('app_ui_label_digitalobject'))))), $link) ?> <?php else: ?> <?php echo image_tag($representation->getFullPath(), array('alt' => '')) ?> <?php endif; ?> <?php else: ?> <?php if ($iconOnly): ?> <?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('app_ui_label_digitalobject'))))), $link) ?> <?php else: ?> <div style="width: 100px; text-align: center"/> <?php if (isset($link)): ?> <?php echo link_to(image_tag($representation->getFullPath(), array('alt' => __('Open original %1%', array('%1%' => sfConfig::get('app_ui_label_digitalobject'))))), $link) ?> <?php else: ?> <?php echo image_tag($representation->getFullPath(), array('alt' => '')) ?> <?php endif; ?> <?php echo wrap_text($digitalObject->name, 15) ?> </div> <?php endif; ?> <?php endif; ?>
Surfrdan/atom
apps/qubit/modules/digitalobject/templates/_showDownload.php
PHP
agpl-3.0
1,149
<? // The source code packaged with this file is Free Software, Copyright (C) 2005 by // Ricardo Galli <gallir at uib dot es>. // It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise. // You can get copies of the licenses here: // http://www.affero.org/oagpl.html // AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING". function send_recover_mail ($user) { global $site_key, $globals; require_once(mnminclude.'user.php'); $now = time(); $key = md5($user->id.$user->pass.$now.$site_key.get_server_name()); $url = 'http://'.get_server_name().$globals['base_url'].'profile.php?login='.$user->username.'&t='.$now.'&k='.$key; //echo "$user->username, $user->email, $url<br />"; $to = $user->email; $subject = _('Recuperación o verificación de la contraseña de '). get_server_name(); $message = $to . _(': para poder acceder sin la clave, conéctate a la siguiente dirección en menos de dos horas:') . "\n\n$url\n\n"; $message .= _('Pasado este tiempo puedes volver a solicitar acceso en: ') . "\nhttp://".get_server_name().$globals['base_url']."login.php?op=recover\n\n"; $message .= _('Una vez en tu perfil, puedes cambiar la clave de acceso.') . "\n" . "\n"; $message .= "\n\n". _('Este mensaje ha sido enviado a solicitud de la dirección: ') . $globals['user_ip'] . "\n\n"; $message .= "-- \n " . _('el equipo de menéame'); $message = wordwrap($message, 70); $headers = 'Content-Type: text/plain; charset="utf-8"'."\n" . 'X-Mailer: meneame.net/PHP/' . phpversion(). "\n". 'From: meneame.net <web@'.get_server_name().">\n"; //$pars = '-fweb@'.get_server_name(); mail($to, $subject, $message, $headers); echo '<p><strong>' ._ ('Correo enviado, mira tu buzón, allí están las instrucciones. Mira también en la carpeta de spam.') . '</strong></p>'; return true; } ?>
brainsqueezer/fffff
branches/version2/www/libs/mail.php
PHP
agpl-3.0
1,852
<?php class BAInitiativeParser extends RISParser { private static $MAX_OFFSET = 5500; private static $MAX_OFFSET_UPDATE = 200; public function parse($antrag_id) { $antrag_id = IntVal($antrag_id); if (SITE_CALL_MODE != "cron") echo "- Initiative $antrag_id\n"; if ($antrag_id == 0) { RISTools::report_ris_parser_error("Fehler BAInitiativeParser", "Initiative-ID 0\n" . print_r(debug_backtrace(), true)); return; } $html_details = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen_details.jsp?Id=$antrag_id"); $html_dokumente = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen_dokumente.jsp?Id=$antrag_id"); //$html_ergebnisse = load_file(RIS_BA_BASE_URL . "/RII/RII/ris_antrag_ergebnisse.jsp?risid=" . $antrag_id); $daten = new Antrag(); $daten->id = $antrag_id; $daten->datum_letzte_aenderung = new CDbExpression('NOW()'); $daten->typ = Antrag::$TYP_BA_INITIATIVE; $dokumente = []; //$ergebnisse = array(); preg_match("/<h3.*>.* +(.*)<\/h3/siU", $html_details, $matches); if (count($matches) == 2) $daten->antrags_nr = Antrag::cleanAntragNr($matches[1]);; $dat_details = explode("<h3 class=\"introheadline\">BA-Initiativen-Nummer", $html_details); $dat_details = explode("<div class=\"formularcontainer\">", $dat_details[1]); preg_match_all("/class=\"detail_row\">.*detail_label\">(.*)<\/d.*detail_div\">(.*)<\/div/siU", $dat_details[0], $matches); $betreff_gefunden = false; for ($i = 0; $i < count($matches[1]); $i++) switch (trim($matches[1][$i])) { case "Betreff:": $betreff_gefunden = true; $daten->betreff = html_entity_decode($this->text_simple_clean($matches[2][$i]), ENT_COMPAT, "UTF-8"); break; case "Status:": $daten->status = $this->text_simple_clean($matches[2][$i]); break; case "Bearbeitung:": $daten->bearbeitung = trim(strip_tags($matches[2][$i])); break; } if (!$betreff_gefunden) { RISTools::report_ris_parser_error("Fehler BAInitiativeParser", "Kein Betreff\n" . $html_details); throw new Exception("Betreff nicht gefunden"); } $dat_details = explode("<div class=\"detailborder\">", $html_details); $dat_details = explode("<!-- seitenfuss -->", $dat_details[1]); preg_match_all("/<span class=\"itext\">(.*)<\/span.*detail_div_(left|right|left_long)\">(.*)<\/div/siU", $dat_details[0], $matches); for ($i = 0; $i < count($matches[1]); $i++) if ($matches[3][$i] != "&nbsp;") switch ($matches[1][$i]) { case "Zust&auml;ndiges Referat:": $daten->referat = $matches[3][$i]; break; case "Gestellt am:": $daten->gestellt_am = $this->date_de2mysql($matches[3][$i]); break; case "Wahlperiode:": $daten->wahlperiode = $matches[3][$i]; break; case "Bearbeitungsfrist:": $daten->bearbeitungsfrist = $this->date_de2mysql($matches[3][$i]); break; case "Registriert am:": $daten->registriert_am = $this->date_de2mysql($matches[3][$i]); break; case "Bezirksausschuss:": $daten->ba_nr = IntVal($matches[3][$i]); break; case "Typ:": $daten->antrag_typ = strip_tags($matches[3][$i]); break; case "TO aufgenommen am:": $daten->initiative_to_aufgenommen = $this->date_de2mysql($matches[3][$i]); break; } if ($daten->wahlperiode == "") $daten->wahlperiode = "?"; preg_match_all("/<li><span class=\"iconcontainer\">.*title=\"([^\"]+)\"[^>]+href=\"(.*)\".*>(.*)<\/a>/siU", $html_dokumente, $matches); for ($i = 0; $i < count($matches[1]); $i++) { $dokumente[] = [ "url" => $matches[2][$i], "name" => $matches[3][$i], "name_title" => $matches[1][$i], ]; } /* $dat_ergebnisse = explode("<!-- tabellenkopf -->", $html_ergebnisse); $dat_ergebnisse = explode("<!-- tabellenfuss -->", $dat_ergebnisse[1]); preg_match_all("<tr>.*bghell tdborder\"><a.*\">(.*)<\/a>.* */ if ($daten->ba_nr == 0) { echo "BA-Initiative $antrag_id: " . "Keine BA-Angabe"; $GLOBALS["RIS_PARSE_ERROR_LOG"][] = "Keine BA-Angabe (Initiative): $antrag_id"; return; } $aenderungen = ""; /** @var Antrag $alter_eintrag */ $alter_eintrag = Antrag::model()->findByPk($antrag_id); $changed = true; if ($alter_eintrag) { $changed = false; if ($alter_eintrag->betreff != $daten->betreff) $aenderungen .= "Betreff: " . $alter_eintrag->betreff . " => " . $daten->betreff . "\n"; if ($alter_eintrag->bearbeitungsfrist != $daten->bearbeitungsfrist) $aenderungen .= "Bearbeitungsfrist: " . $alter_eintrag->bearbeitungsfrist . " => " . $daten->bearbeitungsfrist . "\n"; if ($alter_eintrag->status != $daten->status) $aenderungen .= "Status: " . $alter_eintrag->status . " => " . $daten->status . "\n"; if ($alter_eintrag->fristverlaengerung != $daten->fristverlaengerung) $aenderungen .= "Fristverlängerung: " . $alter_eintrag->fristverlaengerung . " => " . $daten->fristverlaengerung . "\n"; if ($alter_eintrag->initiative_to_aufgenommen != $daten->initiative_to_aufgenommen) $aenderungen .= "In TO Aufgenommen: " . $alter_eintrag->initiative_to_aufgenommen . " => " . $daten->initiative_to_aufgenommen . "\n"; if ($aenderungen != "") $changed = true; if ($alter_eintrag->wahlperiode == "") $alter_eintrag->wahlperiode = "?"; } if ($changed) { if ($aenderungen == "") $aenderungen = "Neu angelegt\n"; echo "BA-Initiative $antrag_id: Verändert: " . $aenderungen . "\n"; if ($alter_eintrag) { $alter_eintrag->copyToHistory(); $alter_eintrag->setAttributes($daten->getAttributes()); if (!$alter_eintrag->save()) { var_dump($alter_eintrag->getErrors()); die("Fehler"); } $daten = $alter_eintrag; } else { if (!$daten->save()) { var_dump($daten->getErrors()); die("Fehler"); } } $daten->resetPersonen(); } foreach ($dokumente as $dok) { $aenderungen .= Dokument::create_if_necessary(Dokument::$TYP_BA_INITIATIVE, $daten, $dok); } if ($aenderungen != "") { $aend = new RISAenderung(); $aend->ris_id = $daten->id; $aend->ba_nr = $daten->ba_nr; $aend->typ = RISAenderung::$TYP_BA_INITIATIVE; $aend->datum = new CDbExpression("NOW()"); $aend->aenderungen = $aenderungen; $aend->save(); /** @var Antrag $antrag */ $antrag = Antrag::model()->findByPk($antrag_id); $antrag->datum_letzte_aenderung = new CDbExpression('NOW()'); // Auch bei neuen Dokumenten $antrag->save(); $antrag->rebuildVorgaenge(); } } public function parseSeite($seite, $first) { if (SITE_CALL_MODE != "cron") echo "BA-Initiativen Seite $seite\n"; $text = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen.jsp?Trf=n&Start=$seite"); $txt = explode("<!-- tabellenkopf -->", $text); $txt = explode("<div class=\"ergebnisfuss\">", $txt[1]); preg_match_all("/ba_initiativen_details\.jsp\?Id=([0-9]+)[\"'& ]/siU", $txt[0], $matches); if ($first && count($matches[1]) > 0) RISTools::report_ris_parser_error("BA-Initiativen VOLL", "Erste Seite voll: $seite"); for ($i = count($matches[1]) - 1; $i >= 0; $i--) try { $this->parse($matches[1][$i]); } catch (Exception $e) { echo " EXCEPTION! " . $e . "\n"; } return $matches[1]; } public function parseAlle() { $anz = static::$MAX_OFFSET; $first = true; for ($i = $anz; $i >= 0; $i -= 10) { if (SITE_CALL_MODE != "cron") echo ($anz - $i) . " / $anz\n"; $this->parseSeite($i, $first); $first = false; } } public function parseUpdate() { echo "Updates: BA-Initiativen\n"; $loaded_ids = []; $anz = static::$MAX_OFFSET_UPDATE; for ($i = $anz; $i >= 0; $i -= 10) { $ids = $this->parseSeite($i, false); $loaded_ids = array_merge($loaded_ids, array_map("IntVal", $ids)); } } public function parseQuickUpdate() { } }
codeformunich/Muenchen-Transparent
protected/RISParser/BAInitiativeParser.php
PHP
agpl-3.0
9,264
# # Copyright (C) 2019 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require "spec_helper" describe Messages::AssignmentSubmitted::TwitterPresenter do let(:course) { course_model(name: "MATH-101") } let(:assignment) { course.assignments.create!(name: "Introductions", due_at: 1.day.ago) } let(:teacher) { course_with_teacher(course: course, active_all: true).user } let(:student) do course_with_user("StudentEnrollment", course: course, name: "Adam Jones", active_all: true).user end let(:submission) do @submission = assignment.submit_homework(student) assignment.grade_student(student, grade: 5, grader: teacher) @submission.reload end before :once do PostPolicy.enable_feature! end describe "Presenter instance" do let(:message) { Message.new(context: submission, user: teacher) } let(:presenter) { Messages::AssignmentSubmitted::TwitterPresenter.new(message) } context "when the assignment is not anonymously graded" do it "#body includes the name of the student" do expect(presenter.body).to include("Adam Jones") end it "#link is a url for the submission" do expect(presenter.link).to eql( message.course_assignment_submission_url(course, assignment, submission.user_id) ) end end context "when the assignment is anonymously graded" do before(:each) do assignment.update!(anonymous_grading: true) end context "when grades have not been posted" do it "#body excludes the name of the student" do expect(presenter.body).not_to include("Adam Jones") end it "#link is a url to SpeedGrader" do expect(presenter.link).to eq( message.speed_grader_course_gradebook_url(course, assignment_id: assignment.id, anonymous_id: submission.anonymous_id) ) end end context "when grades have been posted" do before(:each) do submission assignment.unmute! end it "#body includes the name of the student" do expect(presenter.body).to include("Adam Jones") end it "#link is a url for the submission" do expect(presenter.link).to eql( message.course_assignment_submission_url(course, assignment, submission.user_id) ) end end end end describe "generated message" do let(:message) { generate_message(:assignment_submitted, :twitter, submission, {}) } let(:presenter) do msg = Message.new(context: submission, user: teacher) Messages::AssignmentSubmitted::TwitterPresenter.new(msg) end context "when the assignment is not anonymously graded" do it "#body includes the name of the student" do expect(message.body).to include("Adam Jones") end it "#url is a url for the submission" do expect(message.url).to include(presenter.link) end end context "when the assignment is anonymously graded" do before(:each) do assignment.update!(anonymous_grading: true) end context "when grades have not been posted" do it "#body excludes the name of the student" do expect(message.body).not_to include("Adam Jones") end it "#url is a url to SpeedGrader" do expect(message.url).to include(presenter.link) end end context "when grades have been posted" do before(:each) do submission assignment.unmute! end it "#body includes the name of the student" do expect(message.body).to include("Adam Jones") end it "#url is a url for the submission" do expect(message.url).to include(presenter.link) end end end end end
djbender/canvas-lms
spec/models/messages/assignment_submitted/twitter_presenter_spec.rb
Ruby
agpl-3.0
4,430
# # Copyright (C) 2015 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. require 'spec_helper' require_dependency "users/creation_notify_policy" module Users describe CreationNotifyPolicy do describe "#is_self_registration?" do it "is true when forced" do policy = CreationNotifyPolicy.new(false, {force_self_registration: '1'}) expect(policy.is_self_registration?).to be(true) end it "is opposite the management ability provide" do policy = CreationNotifyPolicy.new(false, {}) expect(policy.is_self_registration?).to be(true) policy = CreationNotifyPolicy.new(true, {}) expect(policy.is_self_registration?).to be(false) end end describe "#dispatch!" do let(:user){ double() } let(:pseudonym) { double() } let(:channel){ double() } context "for self_registration" do let(:policy){ CreationNotifyPolicy.new(true, {force_self_registration: true}) } before{ allow(channel).to receive_messages(has_merge_candidates?: false) } it "sends confirmation notification" do allow(user).to receive_messages(pre_registered?: true) expect(pseudonym).to receive(:send_confirmation!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(true) end it "sends the registration notification if the user is pending or registered" do allow(user).to receive_messages(pre_registered?: false, registered?: false) expect(pseudonym).to receive(:send_registration_notification!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(true) end end context "when the user isn't yet registered" do before do allow(user).to receive_messages(registered?: false) allow(channel).to receive_messages(has_merge_candidates?: false) end it "sends the registration notification if should notify" do policy = CreationNotifyPolicy.new(true, {send_confirmation: '1'}) expect(pseudonym).to receive(:send_registration_notification!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(true) end it "doesnt send the registration notification if shouldnt notify" do policy = CreationNotifyPolicy.new(true, {send_confirmation: '0'}) expect(pseudonym).to receive(:send_registration_notification!).never result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(false) end end context "when the user is registered" do before{ allow(user).to receive_messages(registered?: true) } let(:policy){ CreationNotifyPolicy.new(true, {}) } it "sends the merge notification if there are merge candidates" do allow(channel).to receive_messages(has_merge_candidates?: true) expect(channel).to receive(:send_merge_notification!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(false) end it "does nothing without merge candidates" do allow(channel).to receive_messages(has_merge_candidates?: false) expect(channel).to receive(:send_merge_notification!).never result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(false) end end end end end
venturehive/canvas-lms
spec/models/users/creation_notify_policy_spec.rb
Ruby
agpl-3.0
4,064
<? session_start(); // Modificado Junio 2009 /** * Original en la SSPD en el año 2003 * * Se añadio compatibilidad con variables globales en Off * @autor Jairo Losada 2009-05 * @licencia GNU/GPL */ foreach ($_GET as $key => $valor) ${$key} = $valor; foreach ($_POST as $key => $valor) ${$key} = $valor; define('ADODB_ASSOC_CASE', 1); $krd = $_SESSION["krd"]; $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; $codusuario = $_SESSION["codusuario"]; $tip3Nombre=$_SESSION["tip3Nombre"]; $tip3desc = $_SESSION["tip3desc"]; $tip3img =$_SESSION["tip3img"]; $verrad = ""; $ruta_raiz = ".."; /*************************************************************************************/ /* ORFEO GPL:Sistema de Gestion Documental http://www.orfeogpl.org */ /* Idea Original de la SUPERINTENDENCIA DE SERVICIOS PUBLICOS DOMICILIARIOS */ /* COLOMBIA TEL. (57) (1) 6913005 orfeogpl@gmail.com */ /* =========================== */ /* */ /* Este programa es software libre. usted puede redistribuirlo y/o modificarlo */ /* bajo los terminos de la licencia GNU General Public publicada por */ /* la "Free Software Foundation"; Licencia version 2. */ /* */ /* Copyright (c) 2005 por : */ /* SSPS "Superintendencia de Servicios Publicos Domiciliarios" */ /* Jairo Hernan Losada jlosada@gmail.com Desarrollador */ /* Sixto Angel Pinz�n L�pez --- angel.pinzon@gmail.com Desarrollador */ /* C.R.A. "COMISION DE REGULACION DE AGUAS Y SANEAMIENTO AMBIENTAL" */ /* Liliana Gomez lgomezv@gmail.com Desarrolladora */ /* Lucia Ojeda lojedaster@gmail.com Desarrolladora */ /* D.N.P. "Departamento Nacional de Planeaci�n" */ /* Hollman Ladino hladino@gmail.com Desarrollador */ /* */ /* Colocar desde esta lInea las Modificaciones Realizadas Luego de la Version 3.5 */ /* Nombre Desarrollador Correo Fecha Modificacion */ /*************************************************************************************/ $ruta_raiz = ".."; $verrad = ""; include_once "$ruta_raiz/include/db/ConnectionHandler.php"; $db = new ConnectionHandler($ruta_raiz); if(!$tipo_archivo) $tipo_archivo = 0; //Para la consulta a archivados /********************************************************************************* * Filename: prestamo.php * Modificado: * 1/3/2006 IIAC Basado en pedido.php. Facilita la b�squeda de los * registros de pr�stamo. *********************************************************************************/ //=============================== // prestamo begin //=============================== // Inicializa, oculta o presenta los par�metros de b�squeda dependiendo de la opci�n del men� de pr�stamos seleccionada // prestamo CustomIncludes begin include ("common.php"); // Save Page and File Name available into variables $sFileName = "prestamo.php"; // Variables de control $opcionMenu=strip($_POST["opcionMenu"]); //opci�n seleccionada del men� $pageAnt=strip($_POST["sFileName"]); $ver=$_POST["s_sql"]; //consulta // HTML Page layout ?> <html> <head> <title>Prestamos ORFEO</title> <link rel="stylesheet" href="<?=$ruta_raiz?>/estilos/orfeo.css" type="text/css"> <!--Necesario para hacer visible el calendario --> <script src="<?=$ruta_raiz?>/js/popcalendar.js"></script> <div id="spiffycalendar" class="text"></div> <link rel="stylesheet" type="text/css" href="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.css"> </head> <body class="PageBODY"> <div align="center"> <table> <tr> <td valign="top"><?php Search_Show(); ?></td> </tr> </table> <table> <tr> <td valign="top"><?php if($ver=="") Pedidos_Show(); ?></td> </tr> </table> </div> </body> </html> <?php //=============================== // prestamo end //=============================== //=============================== // Search_Show begin //=============================== function Search_Show(){ // De sesi�n global $db; global $ruta_raiz; // Control de visualizaci�n $sFileName = $_POST["sFileName"]; $opcionMenu = $_POST["opcionMenu"]; // Valores $fechaFinal = $_POST["fechaFinal"]; $fechaInicial = $_POST["fechaInicial"]; foreach ($_GET as $key => $valor) ${$key} = $valor; foreach ($_POST as $key => $valor) ${$key} = $valor; $krd = $_SESSION["krd"]; $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; // Inicializaci�n de la fecha a partir de la cual se cancelan las solicitudes if ($fechaInicial=="") { $hastaXDias=strtotime("-30 day"); $fechaInicial=date("Y-m-d",$hastaXDias); } if ($fechaFinal=="") { if ($opcionMenu==3) { $query="select PARAM_VALOR,PARAM_NOMB from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_DIAS_CANC'"; $rs = $db->conn->query($query); if(!$rs->EOF) { $x = $rs->fields("PARAM_VALOR"); // d�as por defecto $haceXDias = strtotime("-".$x." day"); $fechaFinal=date("Y-m-d",$haceXDias); } if ($pageAnt!=$sFileName) { // inicializaci�n del tiempo $v_hora_limite=date("h"); $v_minuto_limite=date("i"); $v_meridiano=date("A"); } } else{ $fechaFinal=date("Y-m-d"); } } // Set variables with search parameters $flds_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]); $flds_RADI_NUME_RADI=strip($_POST["s_RADI_NUME_RADI"]); $flds_USUA_LOGIN =strip($_POST["s_USUA_LOGIN"]); if ($opcionMenu==4) { $flds_USUA_LOGIN=$krd; } // Inicializa el usuario para el caso en que el ingresa por la opci�n de SOLICITADOS $flds_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]); $flds_USUA_NOMB =strip($_POST["s_USUA_NOMB"]); $flds_PRES_REQUERIMIENTO=strip($_POST["s_PRES_REQUERIMIENTO"]); if ($v_hora_limite=="") { $v_hora_limite =strip($_POST["s_hora_limite"]); } if ($v_minuto_limite==""){ $v_minuto_limite=strip($_POST["s_minuto_limite"]); } if ($v_meridiano=="") { $v_meridiano =strip($_POST["s_meridiano"]); } // Inicializa el titulo y la visibilidad de los criterios de b�squeda include_once "inicializarForm.inc"; // Form display ?> <form method="post" action="prestamo.php" name="busqueda"> <!-- de sesi�n !--> <input type="hidden" value=" " name="radicado"> <input type="hidden" value="" name="s_sql"> <!-- control de visualizaci�n !--> <input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>"> <input type="hidden" name="sFileName" value=""> <!-- orden de presentaci�n del resultado !--> <input type="hidden" name="FormPedidos_Sorting" value="1"> <input type="hidden" name="FormPedidos_Sorted" value="0"> <input type="hidden" name="s_Direction" value=" DESC "> <!-- control de paginaci�n !--> <input type="hidden" name="FormPedidos_Page" value="1"> <input type="hidden" name="FormStarPage" value="1"> <input type="hidden" name="FormSiguiente" value="0"> <script> //Inicializa el formulario function limpiar() { document.busqueda.action="menu_prestamo.php"; document.busqueda.submit(); } //Presenta los usuarios segun la dependencia seleccionada var codUsuaSel="<?=$flds_USUA_NOMB?>"; </script> <!--Calendario--> <script language="JavaScript" src="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.js"></script> <script language="javascript"> setRutaRaiz ('<?=$ruta_raiz?>'); </script> <table border=0 cellpadding=0 cellspacing=2 class='borde_tab'> <tr> <td class="titulos4" colspan="2"><a name="Search"><?=$sFormTitle[$opcionMenu]; ?> </a></td> </tr> <tr id="b0" style="display:<?= $tipoBusqueda[$opcionMenu][0]; ?>"> <td class="titulos3"><p align="left">Radicado</p></td> <td class="listado5"><input type="text" name="s_RADI_NUME_RADI" maxlength="15" value="<?= $flds_RADI_NUME_RADI; ?>" size="25" class="tex_area"></td> </tr> <tr id="b1" style="display:<?= $tipoBusqueda[$opcionMenu][1]; ?>"> <td class="titulos3"><p align="left">Login de Usuario</p></td> <td class="listado5"><input type="text" name="s_USUA_LOGIN" maxlength="15" value="<?= $flds_USUA_LOGIN; ?>" size="25" class="tex_area"></td> </tr> <tr id="b2" style="display:<?= $tipoBusqueda[$opcionMenu][2]; ?>"> <td class="titulos3"><p align="left">Dependencia</p></td> <td class="listado5"><select name="s_DEPE_NOMB" class="select" onChange=" document.busqueda.s_sql.value='no'; document.busqueda.submit(); "> <option value="">- TODAS LAS DEPENDENCIAS -</option> <? $lookup_s = db_fill_array("select DEPE_CODI,DEPE_NOMB from DEPENDENCIA order by 2"); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_DEPE_NOMB) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"$key\">".strtoupper($value)."</option>"; } } ?> </select></td> </tr> <tr id="b3" style="display:<?= $tipoBusqueda[$opcionMenu][3]; ?>"> <td class="titulos3"><p align="left">Usuario</p></td> <td class="listado5"><select name="s_USUA_NOMB" class=select> <option value="">- TODOS LOS USUARIOS -</option> <? $validUsuaActiv=""; // Modificado Infom�trika 14-Julio-2009 // Compatibilidad con PostgreSQL 8.3 // Cambi� USUA_ESTA=1 por USUA_ESTA='1' para listar los usuarios activos. if ($opcionMenu==1) { $validUsuaActiv=" USUA_ESTA='1' "; }ELSE { $validUsuaActiv=" USUA_LOGIN IS NOT NULL "; } //Verifica que el usuario se encuentre activo para hacer el prEstamo if ($flds_DEPE_NOMB != "") $tmp = " AND DEPE_CODI= ".$flds_DEPE_NOMB; else $tmp = ""; $lookup_s = db_fill_array("select USUA_LOGIN,USUA_NOMB from USUARIO where ".$validUsuaActiv.$tmp); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_USUA_NOMB) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"$key\">".strtoupper($value)."</option>"; } } ?> </select></td> </tr> <tr id="b4" style="display:<?= $tipoBusqueda[$opcionMenu][4]; ?>"> <td class="titulos3"><p align="left">Requerimiento</p></td> <td class="listado5"><select name="s_PRES_REQUERIMIENTO" class=select> <option value="">- TODOS LOS TIPOS -</option> <? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_REQUERIMIENTO' order by PARAM_VALOR desc"); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_PRES_REQUERIMIENTO) $option="<option SELECTED value=\"$key\">".strtoupper($value)."</option>"; else $option="<option value=\"$key\">".strtoupper($value)."</option>"; echo $option; } } ?> </select></td> </tr> <tr id="b5" style="display:<?= $tipoBusqueda[$opcionMenu][5]; ?>"> <td class="titulos3"><p align="left">Estado</p></td> <td class="listado5"><select name="s_PRES_ESTADO" class=select> <option value="">- TODOS LOS ESTADOS -</option> <? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_ESTADO' order by PARAM_VALOR"); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_PRES_ESTADO) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"$key\">".strtoupper($value)."</option>"; } } if($flds_PRES_ESTADO == -1) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"-1\">VENCIDO</option>"; ?> </select></td> </tr> <tr id="b6" style="display:<?= $tipoBusqueda[$opcionMenu][6]; ?>"> <td class="titulos3"><p align="left">Fecha inicial<br>&nbsp;&nbsp;(aaaa-mm-dd)</p></td> <td class="listado5"><script language="javascript"> var dateAvailable1 = new ctlSpiffyCalendarBox("dateAvailable1", "busqueda","fechaInicial","btnDate1","<?=$fechaInicial?>",scBTNMODE_CUSTOMBLUE); dateAvailable1.writeControl(); dateAvailable1.dateFormat="yyyy-MM-dd"; </script></td> </tr> <tr id="b7" style="display:<?= $tipoBusqueda[$opcionMenu][7]; ?>"> <td class="titulos3"><p align="left">Fecha final<br>&nbsp;&nbsp;(aaaa-mm-dd)</p></td> <td class="listado5"><script language="javascript"> var dateAvailable2 = new ctlSpiffyCalendarBox("dateAvailable2", "busqueda","fechaFinal","btnDate2","<?=$fechaFinal?>",scBTNMODE_CUSTOMBLUE); dateAvailable2.writeControl(); dateAvailable2.dateFormat="yyyy-MM-dd"; </script> </td> </tr> <tr id="b8" style="display:<?= $tipoBusqueda[$opcionMenu][8]; ?>"> <td class="titulos3"><p align="left">Hora l&iacute;mite<br>&nbsp;&nbsp;(hh:mm m)</p></td> <td class="listado5"><select name="s_hora_limite" class=select> <? for ($i=1; $i<=12; $i++) { if ($i<=9) { $h="0".$i; } else { $h="".$i; } $seleccion=""; if ($h==$v_hora_limite) { $seleccion="SELECTED"; } ?> <option <?= $seleccion; ?> value="<?= $h;?>"><?= $h;?></option> <? } ?> </select>&nbsp;:&nbsp; <select name="s_minuto_limite" class=select> <? for ($i=0; $i<=59; $i++) { if ($i<=9) { $h="0".$i; } else { $h="".$i; } $seleccion=""; if ($h==$v_minuto_limite) { $seleccion="SELECTED"; } ?> <option <?= $seleccion; ?> value="<?= $h;?>"> <?= $h;?></option> <? } ?> </select>&nbsp;:&nbsp; <select name="s_meridiano" class=select> <? if ($v_meridiano=="AM") {?> <option value="AM" selected>am</option> <option value="PM">pm</option> <? } else {?> <option value="AM">am</option> <option value="PM" selected>pm</option> <? } ?> </select> </tr> <tr> <td class="titulos3" colspan="2"> <? if ($opcionMenu==0 || $opcionMenu==4) {?> <input type="reset" class='botones' value="Limpiar" onClick="javascript: limpiar();"> <input type="submit" class='botones' value="Generar"> <? } else {?> <input type="submit" class='botones' value="Buscar"> <? }?> </td> </tr> </table> </form> <? } //end function //=============================== // Search_Show end //=============================== //=============================== // Pedidos_Show begin //=============================== function Pedidos_Show(){ // De sesi�n global $db; global $ruta_raiz; // Control de visualizaci�n global $sFileName; global $opcionMenu; global $pageAnt; // Pagina de la cual viene // Valores $sFileName = $_POST["sFileName"]; $opcionMenu = $_POST["opcionMenu"]; // Valores $fechaFinal = $_POST["fechaFinal"]; $fechaInicial = $_POST["fechaInicial"]; $krd = $_SESSION["krd"]; $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; // Set variables with search parameters $ps_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]); $ps_RADI_NUME_RADI=strip(trim($_POST["s_RADI_NUME_RADI"])); // Modificado Infom�trika 14-Julio-2009 // A la variable $ps_USUA_LOGIN se le asigna el valor de $_POST["s_USUA_LOGIN"] para // realizar la consulta, por Login de Usuario, de los radicados solicitados para pr�stamo. //$ps_USUA_LOGIN =$krd; $ps_USUA_LOGIN = strip($_POST['s_USUA_LOGIN']); ; $ps_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]); $ps_USUA_NOMB =strip($_POST["s_USUA_NOMB"]); $ps_hora_limite =strip($_POST["s_hora_limite"]); $ps_minuto_limite =strip($_POST["s_minuto_limite"]); $ps_meridiano =strip($_POST["s_meridiano"]); $ps_PRES_REQUERIMIENTO=strip($_POST["s_PRES_REQUERIMIENTO"]); if (strlen($pageAnt)==0){ // Build SQL include_once $ruta_raiz."/include/query/prestamo/builtSQL1.inc"; include_once $ruta_raiz."/include/query/prestamo/builtSQL2.inc"; include_once $ruta_raiz."/include/query/prestamo/builtSQL3.inc"; // Build ORDER statement $iSort=strip(get_param("FormPedidos_Sorting")); if(!$iSort) $iSort =20; $iSorted=strip(get_param("FormPedidos_Sorted")); $sDirection=strip(get_param("s_Direction")); if ($iSorted!=$iSort){ $sDirection=" DESC ";} else { if(strcasecmp($sDirection," DESC ")==0){ $sDirection=" ASC "; } else { $sDirection=" DESC "; } } $sOrder=" order by ".$iSort.$sDirection.",PRESTAMO_ID"; // Inicializa el titulo y la visibilidad de los resultados include_once "inicializarRTA.inc"; // Execute SQL statement $db->conn->SetFetchMode(ADODB_FETCH_ASSOC); $rs=$db->query($sSQL.$sOrder); $db->conn->SetFetchMode(ADODB_FETCH_NUM); // Process empty recordset if(!$rs || $rs->EOF) { ?> <p align="center" class="titulosError2">NO HAY REGISTROS SELECCIONADOS</p> <? return; } // Build parameters for order $form_params_search = "s_RADI_NUME_RADI=".tourl($ps_RADI_NUME_RADI)."&s_USUA_LOGIN=".tourl($ps_USUA_LOGIN). "&s_DEPE_NOMB=".tourl($ps_DEPE_NOMB)."&s_USUA_NOMB=".tourl($ps_USUA_NOMB)."&s_PRES_REQUERIMIENTO=". tourl($ps_PRES_REQUERIMIENTO)."&s_PRES_ESTADO=".tourl($ps_PRES_ESTADO)."&fechaInicial=". tourl($fechaInicial)."&fechaFinal=".tourl($fechaFinal)."&s_hora_limite=".tourl($ps_hora_limite). "&s_minuto_limite=".tourl($ps_minuto_limite)."&s_meridiano=".tourl($ps_meridiano); $form_params_page = "&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0"; $form_params=$form_params_search.$form_params_page."&opcionMenu=".tourl($opcionMenu)."&krd=".tourl($krd). "&FormPedidos_Sorted=".tourl($iSort)."&s_Direction=".tourl($sDirection)."&FormPedidos_Sorting="; // HTML column prestamo headers ?> <form method="post" action="prestamo.php" name="rta"> <input type="hidden" value='<?=$krd?>' name="krd"> <input type="hidden" value=" " name="radicado"> <input type="hidden" value="" name="prestado"> <input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>"> <!-- orden de presentaci�n del resultado en el formulario de envio !--> <input type="hidden" name="FormPedidos_Sorting" value="<?=$iSort?>"> <input type="hidden" name="FormPedidos_Sorted" value="<?=$iSorted?>"> <input type="hidden" name="s_Direction" value="<?=$sDirection?>"> <table border=0 cellpadding=0 cellspacing=2 class='borde_tab' width="100%"> <tr> <td class="titulos4" colspan="<?=$numCol?>"><a name="Search"><?= $tituloRespuesta[$opcionMenu]?></a></td> </tr> <?PHP // Titulos de las columnas include_once "inicializarTabla.inc"; //---------------------- // Process page scroller //---------------------- // Initialize records per page $iRecordsPerPage = 15; // Inicializa el valor de la pagina actual $iPage=intval(get_param("FormPedidos_Page")); // Inicializa los registros a presentar seg�n la p�gina actual $iCounter = 0; $ant=""; if($iPage > 1) { do{ $new=$rs->fields["PRESTAMO_ID"]; if ($new!=$ant) { $iCounter++; $ant=$new; } $rs->MoveNext(); }while ($iCounter < ($iPage - 1) * $iRecordsPerPage && !$rs->EOF); } $iCounterIni=$iCounter; // Display grid based on recordset $y=0; // Cantidad de registros presentados include_once "getRtaSQLAntIn.inc"; //Une en un solo campo los expedientes while($rs && !$rs->EOF && $y<$iRecordsPerPage) { // Inicializa las variables con los resultados include "getRtaSQL.inc"; if ($antfldPRESTAMO_ID!=$fldPRESTAMO_ID) { //Une en un solo campo los expedientes if ($y!=0) { include "cuerpoTabla.inc"; } // Fila de la tabla con los resultados include "getRtaSQLAnt.inc"; $y++; } else { if ($antfldEXP!=""){ $antfldEXP.="<br>"; $antfldARCH.="<br>"; } $antfldEXP.=$fldEXP; if ($fldARCH=='SI') { $encabARCH = session_name()."=".session_id()."&buscar_exp=".tourl($fldEXP)."&krd=$krd&tipo_archivo=&nomcarpeta="; $antfldARCH.="<a href='".$ruta_raiz."/expediente/datos_expediente.php?".$encabARCH."&num_expediente=".tourl($fldEXP)."&nurad=".tourl($antfldRADICADO)."' class='vinculos'>".$fldARCH."</a>"; } else { $antfldARCH.=$fldARCH; } } $rs->MoveNext(); } if ($y!=0) { include "cuerpoTabla.inc"; // Fila de la tabla con lso resultados $y++; } $cantRegPorPagina=$y; $iCounter=$iCounter+$y; ?> <script> // Inicializa el arreglo con los radicados a procesar var cantRegPorPagina=<?=$cantRegPorPagina-1?>; // Marca todas las casillas si la del titulo es marcada function seleccionarRta() { valor=document.rta.rta_.checked; <? for ($j=0; $j<$cantRegPorPagina; $j++) { ?> document.rta.rta_<?=$j?>.checked=valor; <? } ?> } // Valida y envia el formulario function enviar() { var cant=0; for (i=0; i<cantRegPorPagina; i++) { if (eval('document.rta.rta_'+i+'.checked')==true){ cant=1; break; } } if (cant==0) { alert("Debe seleccionar al menos un radicado"); } else { document.rta.prestado.value=cantRegPorPagina; document.rta.action="formEnvio.php"; document.rta.submit(); } } // Regresa al men� de pr�stamos function regresar() { document.rta.opcionMenu.value=""; document.rta.action="menu_prestamo.php"; document.rta.submit(); } </script> <? // Build parameters for page if (strcasecmp($sDirection," DESC ")==0){ $sDirectionPages=" ASC "; } else { $sDirectionPages=" DESC "; } $form_params_page = $form_params_search."&opcionMenu=".tourl($opcionMenu)."&FormPedidos_Sorted=".tourl($iSort). "&s_Direction=".tourl($sDirectionPages)."&krd=".tourl($krd)."&FormPedidos_Sorting=".tourl($iSort); // N�mero total de registros $ant=$antfldPRESTAMO_ID; while($rs && !$rs->EOF) { $new=$rs->fields["PRESTAMO_ID"]; //para el manejo de expedientes if ($new!=$ant) { $ant=$new; $iCounter++; } $rs->MoveNext(); } $iCounter--; // Inicializa p�ginas visualizables $iNumberOfPages=10; // Inicializa cantidad de p�ginas $iHasPages=intval($iCounter/$iRecordsPerPage); if ($iCounter%$iRecordsPerPage!=0) { $iHasPages++; } // Determina la p�gina inicial del intervalo $iStartPages=1; $FormSiguiente=get_param("FormSiguiente"); //Indica si (1) el n�mero de p�ginas es mayor al visualizable if($FormSiguiente==0) { $iStartPages=get_param("FormStarPage"); } elseif($FormSiguiente==-1){ $iStartPages=$iPage; } else { if($iPage>$iNumberOfPages) { $iStartPages=$iPage-$iNumberOfPages+1; } } // Genera las p�ginas visualizables $sPages= ""; if($iHasPages>$iNumberOfPages) { if($iStartPages==1){ $sPages.="|< << "; } else{ $sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0&\"> <font class=\"ColumnFONT\" title=\"Ver la primera p&aacute;gina\">|<</font></a>&nbsp;"; $sPages.="&nbsp;<a href=\"$sFileName?$form_params_page&FormPedidos_Page=".tourl($iStartPages-1)."&FormStarPage=". tourl($iStartPages-1)."&FormSiguiente=-1&\"><font class=\"ColumnFONT\" title=\"Ver la p&aacute;gina ". ($iStartPages-1)."\"><<</font></a>&nbsp;&nbsp;&nbsp;"; } } for($iPageCount=$iStartPages; $iPageCount<($iStartPages+$iNumberOfPages); $iPageCount++) { if ($iPageCount<=$iHasPages) { $sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages)."&FormSiguiente=0&\"> <font class=\"ColumnFONT\" title=\"Ver la p&aacute;gina ".$iPageCount."\">".$iPageCount."</font></a>&nbsp;"; } else { break; } } if($iHasPages>$iNumberOfPages) { if($iPageCount-1<$iHasPages){ $sPages.="...&nbsp;&nbsp;<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages). "&FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la p&aacute;gina ".$iPageCount."\">>></font></a>&nbsp;&nbsp;"; $sPages.="&nbsp;<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iHasPages&FormStarPage=tourl($iStartPages) &FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la &uacute;ltima p&aacute;gina\">>|</font></a>"; } else { $sPages.=" >> >|"; } } ?> <tr class="titulos5" align="center"> <td class="leidos" colspan="<?=($numCol+1);?>"><center><br><?=$sPages?><br><br>P&aacute;gina <?=$iPage?>/<?=$iHasPages?><br> Total de Registros: <?=$iCounter?><br>&nbsp;</center></td> </tr> <? // Botones para procesar if ($tipoRespuesta[$opcionMenu][$numRtaMax]=="") {?> <tr class="titulos4" align="center"> <td class="listado1" colspan="<?=($numCol+1);?>" align="center"><center> <input type="button" class='botones' value="<?=$tituloSubmitRta[$opcionMenu]?>" onClick="javascript:enviar();"> <input type="button" class='botones' value="Cancelar" title="Regresa al men&uacute; de pr&eacute;stamo y control de documentos" onClick="javascript:regresar();"></center> </td> </tr> <? }?> </table> </form> <? } //fin if } //fin function //=============================== // Pedidos_Show end //=============================== ?>
cejebuto/OrfeoWind
prestamo/prestamo.php
PHP
agpl-3.0
30,604
package org.ownprofile.boundary.owner.client; public class Result<T> { private boolean isSuccess; private T successValue; private Fail fail; public static Result<Void> success() { return success(null); } public static <S> Result<S> success(S successValue) { return new Result<S>(successValue); } public static <S> Result<S> fail(String message) { return fail((Throwable)null, "%s", message); } public static <S> Result<S> fail(Throwable cause, String message) { return fail(cause, "%s", message); } public static <S> Result<S> fail(String format, Object... args) { return fail(null, format, args); } public static <S> Result<S> fail(Throwable cause, String format, Object... args) { final Fail f = new Fail(cause, format, args); return new Result<S>(f); } private Result(T successValue) { this.isSuccess = true; this.successValue = successValue; } private Result(Fail fail) { this.isSuccess = false; this.fail = fail; } public boolean isSuccess() { return isSuccess; } public boolean isFail() { return !isSuccess; } public T getSuccessValue() { if (isSuccess) { return successValue; } else { throw new IllegalStateException(String.format("Result is Fail: %s", fail)); } } public Fail getFail() { if (isSuccess) { throw new IllegalStateException(String.format("Result is Success")); } else { return fail; } } @Override public String toString() { return String.format("%s: %s", isSuccess ? "SUCCESS" : "FAIL", isSuccess ? successValue : fail); } // ------------------------------ public static class Fail { private String message; private Throwable cause; private Fail(Throwable cause, String message) { this.cause = cause; this.message = message; } private Fail(Throwable cause, String format, Object... args) { this(cause, String.format(format, args)); } public String getMessage() { return message; } public Throwable getCause() { return cause; } @Override public String toString() { return String.format("%s - %s", message, cause); } } }
mchlrch/ownprofile
org.ownprofile.node/src/main/java/org/ownprofile/boundary/owner/client/Result.java
Java
agpl-3.0
2,101
<?php use Illuminate\Database\Migrations\Migration; class AddDomainIdToBusinessesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('businesses', function ($table) { $table->integer('domain_id')->unsigned()->nullable()->after('category_id'); $table->foreign('domain_id')->references('id')->on('domains')->onDelete('set null'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('businesses', function ($table) { $table->dropForeign('businesses_domain_id_foreign'); $table->dropColumn('domain_id'); }); } }
timegridio/timegrid
database/migrations/2015_12_20_014958_add_domain_id_to_businesses_table.php
PHP
agpl-3.0
763
# -*- coding: utf-8 -*- from .base import BaseHandler class TestRoute(BaseHandler): def get(self, file): return self.render(str(file) + '.jade', show_h1=1)
web-izmerenie/avto-lux161
avto-lux/app/core/routes/testroute.py
Python
agpl-3.0
162
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. module AWS module Core class PageResult < Array # @return [Collection] Returns the collection that was used to # populated this page of results. attr_reader :collection # @return [Integer] Returns the maximum number of results per page. # The final page in a collection may return fewer than +:per_page+ # items (e.g. +:per_page+ is 10 and there are only 7 items). attr_reader :per_page # @return [String] An opaque token that can be passed the #page method # of the collection that returned this page of results. This next # token behaves as a pseudo offset. If +next_token+ is +nil+ then # there are no more results for the collection. attr_reader :next_token # @param [Collection] collection The collection that was used to # request this page of results. The collection should respond to # #page and accept a :next_token option. # # @param [Array] items An array of result items that represent a # page of results. # # @param [Integer] per_page The number of requested items for this # page of results. If the count of items is smaller than +per_page+ # then this is the last page of results. # # @param [String] next_token (nil) A token that can be passed to the # def initialize collection, items, per_page, next_token @collection = collection @per_page = per_page @next_token = next_token super(items) end # @return [PageResult] # @raise [RuntimeError] Raises a runtime error when called against # a collection that has no more results (i.e. #last_page? == true). def next_page if last_page? raise 'unable to get the next page, already at the last page' end collection.page(:per_page => per_page, :next_token => next_token) end # @return [Boolean] Returns +true+ if this is the last page of results. def last_page? next_token.nil? end # @return [Boolean] Returns +true+ if there are more pages of results. def more? !!next_token end end end end
usmschuck/canvas
vendor/bundle/ruby/1.9.1/gems/aws-sdk-1.8.3.1/lib/aws/core/page_result.rb
Ruby
agpl-3.0
2,790
# FlareDNS-client Synchronize your App dynamic IP with your CloudFlare DNS A records. Use this package if: * You use [CloudFlare](https://cloudflare.com "CloudFlare"). * You run your Laravel App on a server with a Dynamic IP or your IP changes often. ## Installation ``` composer require thinkingcircles/flaredns-client ``` ```php // config/app.php 'providers' => [ // Other service providers... ThinkingCircles\FlareDNSClient\FlareDNSClientServiceProvider::class, ] ``` ``` php artisan vendor:publish --provider="ThinkingCircles\FlareDNSClient\FlareDNSClientServiceProvider" ``` ## Get CloudFlare api keys ## Configuration ```php // .env cloudflare_zone_id= cloudflare_global_api_key= cloudflare_api_email= ``` :or ```php // config/flaredns-client.php <?php return [ 'cloudflare_api_account' => [ 'cloudflare_zone_id' => 'ZONE-ID', 'cloudflare_global_api_key' => 'API-KEY', 'cloudflare_api_email' => 'API-EMAIL', 'dns_records' => [ //will match id or name ['id'=>null, 'name'=>'domain.net'], ['id'=>'CloudFlare-API-Record-ID', 'name'=>null] ] ] ]; ``` ## Cron Setup - [Laravel 5.4 - Scheduling](https://laravel.com/docs/5.4/scheduling) ``` // Cron if you have not setup already * * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1 ``` ## Usage ```php // App/Console/Kernel.php protected function schedule(Schedule $schedule) { $schedule->command('flarednsclient:ipsync')->everyFiveMinutes(); } ``` ## Todo - [x] Debug - [ ] Clean up code - [ ] Improve logic - [ ] Make UI [FlareDNS Management UI](https://www.github.com/ThinkingCircles/FlareDNS "FlareDNS Management UI")
thinkingcircles/test
README.md
Markdown
agpl-3.0
1,736
<?php /** * DAO tbMovimentacaoBancaria * @author emanuel.sampaio - Politec * @since 17/02/2011 * @version 1.0 * @package application * @subpackage application.model * @copyright © 2011 - Ministério da Cultura - Todos os direitos reservados. * @link http://www.cultura.gov.br */ class tbMovimentacaoBancaria extends GenericModel { /* dados da tabela */ protected $_banco = "SAC"; protected $_schema = "dbo"; protected $_name = "tbMovimentacaoBancaria"; /** * Método para buscar * @access public * @param string $pronac * @param boolean $conta_rejeitada * @param array $periodo * @param array $operacao * @return object */ public function buscarDados($pronac = null, $conta_rejeitada = null, $periodo = null, $operacao = null ,$tamanho=-1, $inicio=-1, $count = null) { $select = $this->select(); $select->setIntegrityCheck(false); if(isset($count)){ $select->from( array("mi" => "tbMovimentacaoBancariaItem"), array("total" => "count(*)")); } else { $select->from( array("mi" => "tbMovimentacaoBancariaItem") ,array("m.nrBanco" ,"CONVERT(CHAR(10), m.dtInicioMovimento, 103) AS dtInicioMovimento" ,"CONVERT(CHAR(10), m.dtFimMovimento, 103) AS dtFimMovimento" ,"mi.idMovimentacaoBancaria" ,"mi.tpRegistro" ,"mi.nrAgencia" ,"mi.nrDigitoConta" ,"mi.nmTituloRazao" ,"mi.nmAbreviado" ,"CONVERT(CHAR(10), mi.dtAberturaConta, 103) AS dtAberturaConta" ,"mi.nrCNPJCPF" ,"n.Descricao AS Proponente" ,"mi.vlSaldoInicial" ,"mi.tpSaldoInicial" ,"mi.vlSaldoFinal" ,"mi.tpSaldoFinal" ,"CONVERT(CHAR(10), mi.dtMovimento, 103) AS dtMovimento" ,"mi.cdHistorico" ,"mi.dsHistorico" ,"mi.nrDocumento" ,"mi.vlMovimento" ,"mi.cdMovimento" ,"mi.idMovimentacaoBancariaItem" ,"ti.idTipoInconsistencia" ,"ti.dsTipoInconsistencia" ,"(p.AnoProjeto+p.Sequencial) AS pronac" ,"p.NomeProjeto" ,"bc.Descricao AS nmBanco") ); } $select->joinInner( array("m" => $this->_name) ,"m.idMovimentacaoBancaria = mi.idMovimentacaoBancaria" ,array() ); if(!empty($conta_rejeitada) && $conta_rejeitada){ $select->joinInner( array("mx" => "tbMovimentacaoBancariaItemxTipoInconsistencia") ,"mi.idMovimentacaoBancariaItem = mx.idMovimentacaoBancariaItem" ,array() ); $select->joinInner( array("ti" => "tbTipoInconsistencia") ,"ti.idTipoInconsistencia = mx.idTipoInconsistencia" ,array() ); } else { $select->joinLeft( array("mx" => "tbMovimentacaoBancariaItemxTipoInconsistencia") ,"mi.idMovimentacaoBancariaItem = mx.idMovimentacaoBancariaItem" ,array() ); $select->joinLeft( array("ti" => "tbTipoInconsistencia") ,"ti.idTipoInconsistencia = mx.idTipoInconsistencia" ,array() ); } $select->joinLeft( array("c" => "ContaBancaria") ,"mi.nrAgencia = c.Agencia AND (mi.nrDigitoConta = c.ContaBloqueada OR mi.nrDigitoConta = c.ContaLivre)" ,array() ); $select->joinLeft( array("p" => "Projetos") ,"c.AnoProjeto = p.AnoProjeto AND c.Sequencial = p.Sequencial" ,array() ); $select->joinLeft( array("bc" => "bancos") ,"m.nrBanco = bc.Codigo" ,array() ,"AGENTES.dbo" ); $select->joinLeft( array("a" => "Agentes") ,"mi.nrCNPJCPF = a.CNPJCPF" ,array() ,"AGENTES.dbo" ); $select->joinLeft( array("n" => "Nomes") ,"a.idAgente = n.idAgente" ,array() ,"AGENTES.dbo" ); // $select->where("mi.vlSaldoInicial > 0.00"); //$select->where("mi.vlSaldoFinal > 0.00"); // busca pelo pronac if (!empty($pronac)) { $select->where("(c.AnoProjeto+c.Sequencial) = ?", $pronac); } // filtra por contas rejeitadas if (!empty($conta_rejeitada) && $conta_rejeitada) { $select->where("mx.idMovimentacaoBancariaItem IS NOT NULL"); $select->where("mx.idTipoInconsistencia IS NOT NULL"); } else { $select->where("mx.idMovimentacaoBancariaItem IS NULL"); $select->where("mx.idTipoInconsistencia IS NULL"); } // busca pelo período if (!empty($periodo)) { if ($periodo[0] == "A") // Hoje { $select->where("CONVERT(DATE, m.dtInicioMovimento) = CONVERT(DATE, GETDATE()) OR CONVERT(DATE, m.dtFimMovimento) = CONVERT(DATE, GETDATE()) OR CONVERT(DATE, mi.dtMovimento) = CONVERT(DATE, GETDATE())"); } if ($periodo[0] == "B") // Ontem { $select->where("CONVERT(DATE, m.dtInicioMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "C") // Últimos 7 dias { $select->where("CONVERT(DATE, m.dtInicioMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "D") // Semana passada (seg-dom) { $select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) END)"); } if ($periodo[0] == "E") // Última semana (seg-sex) { $select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) END)"); } if ($periodo[0] == "F") // Este mês { $select->where("DATEPART(MONTH, m.dtInicioMovimento) + DATEPART(YEAR, m.dtInicioMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE()) OR DATEPART(MONTH, m.dtFimMovimento) + DATEPART(YEAR, m.dtFimMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE()) OR DATEPART(MONTH, mi.dtMovimento) + DATEPART(YEAR, mi.dtMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())"); } if ($periodo[0] == "G") // Ano passado { $select->where("DATEPART(YEAR, m.dtInicioMovimento) = (DATEPART(YEAR, GETDATE()) - 1) OR DATEPART(YEAR, m.dtFimMovimento) = (DATEPART(YEAR, GETDATE()) - 1) OR DATEPART(YEAR, mi.dtMovimento) = (DATEPART(YEAR, GETDATE()) - 1)"); } if ($periodo[0] == "H") // Últimos 12 meses { $select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "I") // Últimos 6 meses { $select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "J") // Últimos 3 meses { $select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "K") // filtra conforme uma data inicial e uma data final { if (!empty($periodo[1]) && !empty($periodo[2])) { $select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00"); $select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59"); } else { if (!empty($periodo[1])) { $select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00"); } if (!empty($periodo[2])) { $select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59"); } } } } // fecha if periodo // filtra pelo tipo de operação if (!empty($operacao)) { $select->where("mi.tpSaldoInicial = ? OR mi.tpSaldoInicial IS NULL", $operacao); $select->where("mi.tpSaldoFinal = ? OR mi.tpSaldoFinal IS NULL", $operacao); $select->where("mi.cdMovimento = ? OR mi.cdMovimento IS NULL", $operacao); } /*if(is_null($count)){ /*$select->order("mi.tpRegistro"); $select->order("(p.AnoProjeto+p.Sequencial)"); $select->order("m.dtInicioMovimento"); $select->order("m.dtFimMovimento"); $select->order("mi.dtMovimento"); $select->order(array(5,26,2,3,17)); }*/ //paginacao if ($tamanho > -1) { $tmpInicio = 0; if ($inicio > -1) { $tmpInicio = $inicio; } $select->limit($tamanho, $tmpInicio); } //x($select->assemble()); return $this->fetchAll($select); } // fecha método buscarDados() /** * Método para cadastrar * @access public * @param array $dados * @return integer (retorna o último id cadastrado) */ public function cadastrarDados($dados) { return $this->insert($dados); } // fecha método cadastrarDados() /** * Método para alterar * @access public * @param array $dados * @param integer $where * @return integer (quantidade de registros alterados) */ public function alterarDados($dados, $where) { $where = "idMovimentacaoBancaria = " . $where; return $this->update($dados, $where); } // fecha método alterarDados() /** * Método para excluir * @access public * @param integer $where * @return integer (quantidade de registros excluídos) */ public function excluirDados($where) { $where = "idMovimentacaoBancaria = " . $where; return $this->delete($where); } // fecha método excluirDados() } // fecha class
hackultura/novosalic
application/model/tbMovimentacaoBancaria.php
PHP
agpl-3.0
17,407
/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ #ifndef STATSSOURCE_H_ #define STATSSOURCE_H_ #include "common/tabletuple.h" #include "common/ids.h" #include "boost/scoped_ptr.hpp" #include <string> #include <vector> #include <map> namespace voltdb { class Table; class TableFactory; class TupleSchema; class TableTuple; /** * Abstract superclass of all sources of statistical information inside the EE. Statistics are currently represented as a single * row table that is updated every time it is retrieved. */ class StatsSource { public: /** * Generates the list of column names that are present for every * stats table. Derived classes should implement their own static * methods to generate their column names and call this method * within it to populate the column name vector before adding * their stat-specific column names. */ static std::vector<std::string> generateBaseStatsColumnNames(); /** * Populates the other schema information which is present for * every stats table. Usage by derived classes takes the same * pattern as generateBaseStatsColumnNames. */ static void populateBaseSchema(std::vector<voltdb::ValueType>& types, std::vector<int32_t>& columnLengths, std::vector<bool>& allowNull, std::vector<bool>& inBytes); /* * Do nothing constructor that initializes statTable_ and schema_ to NULL. */ StatsSource(); /** * Configure a StatsSource superclass for a set of statistics. Since this class is only used in the EE it can be assumed that * it is part of an Execution Site and that there is a site Id. * @parameter name Name of this set of statistics * @parameter hostId id of the host this partition is on * @parameter hostname name of the host this partition is on * @parameter siteId this stat source is associated with * @parameter partitionId this stat source is associated with * @parameter databaseId Database this source is associated with */ void configure( std::string name, voltdb::CatalogId databaseId); /* * Destructor that frees tupleSchema_, and statsTable_ */ virtual ~StatsSource(); /** * Retrieve table containing the latest statistics available. An updated stat is requested from the derived class by calling * StatsSource::updateStatsTuple * @param interval Return counters since the beginning or since this method was last invoked * @param now Timestamp to return with each row * @return Pointer to a table containing the statistics. */ voltdb::Table* getStatsTable(bool interval, int64_t now); /* * Retrieve tuple containing the latest statistics available. An updated stat is requested from the derived class by calling * StatsSource::updateStatsTuple * @param interval Whether to return counters since the beginning or since the last time this was called * @param Timestamp to embed in each row * @return Pointer to a table tuple containing the latest version of the statistics. */ voltdb::TableTuple* getStatsTuple(bool interval, int64_t now); /** * Retrieve the name of this set of statistics * @return Name of statistics */ std::string getName(); /** * String representation of the statistics. Default implementation is to print the stats table. * @return String representation */ virtual std::string toString(); protected: /** * Update the stats tuple with the latest statistics available to this StatsSource. Implemented by derived classes. * @parameter tuple TableTuple pointing to a row in the stats table. */ virtual void updateStatsTuple(voltdb::TableTuple *tuple) = 0; /** * Generates the list of column names that will be in the statTable_. Derived classes must override this method and call * the parent class's version to obtain the list of columns contributed by ancestors and then append the columns they will be * contributing to the end of the list. */ virtual std::vector<std::string> generateStatsColumnNames(); /** * Same pattern as generateStatsColumnNames except the return value is used as an offset into the tuple schema instead of appending to * end of a list. */ virtual void populateSchema(std::vector<voltdb::ValueType> &types, std::vector<int32_t> &columnLengths, std::vector<bool> &allowNull, std::vector<bool> &inBytes); /** * Map describing the mapping from column names to column indices in the stats tuple. Necessary because classes in the * inheritance hierarchy can vary the number of columns they contribute. This removes the dependency between them. */ std::map<std::string, int> m_columnName2Index; bool interval() { return m_interval; } private: /** * Table containing the stat information. Shared pointer used as a substitute for scoped_ptr due to forward * declaration. */ boost::scoped_ptr<voltdb::Table> m_statsTable; /** * Tuple used to modify the stat table. */ voltdb::TableTuple m_statsTuple; /** * Name of this set of statistics. */ std::string m_name; /** * CatalogId of the partition this StatsSource is associated with. */ voltdb::CatalogId m_partitionId; int64_t m_siteId; voltdb::CatalogId m_hostId; voltdb::NValue m_hostname; bool m_interval; }; } #endif /* STATSCONTAINER_H_ */
eoneil1942/voltdb-4.7fix
src/ee/stats/StatsSource.h
C
agpl-3.0
6,316
import sys import time import sys num = 1000 print_granularity = 1000 count = 0 first = True start = 0 gran_start = 0 min = 0 max = 0 avg = 0 sum = 0 total = 0 def set_print_granularity(p): global print_granularity print_granularity = p print("%s: print granularity = %s" % (sys.argv[0], print_granularity)) def loop_count(): global min, max, avg, total, gran_start, sum, start, first, count now = round(time.time() * 1000) if not first: elapsed = now - start if elapsed < min: min = elapsed if elapsed > max: max = elapsed sum = sum + elapsed start = now count = count + 1 total = total + 1 if count % print_granularity == 0 and not first: gran_elapsed = now - gran_start gran_start = now avg = sum / print_granularity print("%s: last %s run stats in msec \t\t elapsed = %s \t min = %s \t max = %s \t avg = %s \t\t total loops = %s" % (sys.argv[0], print_granularity, sum, min, max, avg, total)) # sys.stdout.write("-") # sys.stdout.flush() if first or count % print_granularity == 0: gran_start = now min = 10e10 max = -10e10 avg = 0 sum = 0 first = False
scalien/keyspace
test/concurrency/common.py
Python
agpl-3.0
1,105
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.vitalsignstprbp; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkLegendValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnViewClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onRadioButtongrpShowByValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnPrintClick() throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { onFormOpen(); } }); this.form.chkLegend().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkLegendValueChanged(); } }); this.form.btnView().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnViewClick(); } }); this.form.grpShowBy().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onRadioButtongrpShowByValueChanged(); } }); this.form.btnPrint().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnPrintClick(); } }); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIEngine engine; protected GenForm form; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignstprbp/Handlers.java
Java
agpl-3.0
4,321
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo.beans; public class PatientDiagnosisStatusForReferralCodingVoBean extends ims.vo.ValueObjectBean { public PatientDiagnosisStatusForReferralCodingVoBean() { } public PatientDiagnosisStatusForReferralCodingVoBean(ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean(); } public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo = null; if(map != null) vo = (ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo)map.getValueObject(this); if(vo == null) { vo = new ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.vo.LookupInstanceBean getStatus() { return this.status; } public void setStatus(ims.vo.LookupInstanceBean value) { this.status = value; } private Integer id; private int version; private ims.vo.LookupInstanceBean status; }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/refman/vo/beans/PatientDiagnosisStatusForReferralCodingVoBean.java
Java
agpl-3.0
3,988
<?php // Database Restore $locale['400'] = "Восстановление БД"; $locale['401'] = "Ошибка"; $locale['402'] = "Неверный формат файла резервной копии"; $locale['403'] = "Закрыть"; // Backup File Information $locale['410'] = "Данные о файле резервной копии"; $locale['411'] = "Данные о файле для восстановления"; $locale['412'] = "Имя файла копии:"; $locale['413'] = "Дата создания:"; $locale['414'] = "Имя базы данных:"; $locale['415'] = "Префикс таблиц ядра:"; $locale['416'] = "Таблицы:"; $locale['417'] = "Посмотреть"; $locale['418'] = "отмена"; $locale['419'] = "таблиц"; // Database Restore $locale['430'] = "Параметры восстановления"; $locale['431'] = "Имя файла:"; $locale['432'] = "Создан:"; $locale['433'] = "Создать таблицы:"; $locale['434'] = "Заполнить таблицы:"; $locale['435'] = "Выбрать:"; $locale['436'] = "все"; $locale['437'] = "ничего"; $locale['438'] = "Восстановить из резервной копии"; $locale['439'] = "Отмена"; $locale['440'] = "Поддерживаемые типы файлов:"; // Database Backup $locale['450'] = "Резервирование БД"; $locale['451'] = "Информация о базе данных"; $locale['452'] = "Общий размер таблиц:"; $locale['453'] = "Размер таблиц ядра:"; $locale['454'] = "Параметры резервирования:"; $locale['455'] = "Тип резервной копии:"; $locale['456'] = "(сжатая)"; $locale['457'] = "Таблицы БД"; $locale['458'] = "ядро"; $locale['459'] = "Создать резервную копию"; $locale['460'] = "Админпароль:"; $locale['460b'] = "Пожалуйста, введите Ваш админпароль"; $locale['461'] = "Требуемая информация"; // Backup List $locale['480'] = "Восстановить из резервной копии"; $locale['481'] = "Имя файла:"; $locale['481b'] = "Пожалуйста, укажите имя файла"; ?>
dialektika/PHP-Fusion
locale/Russian/admin/db-backup.php
PHP
agpl-3.0
2,275
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using Chraft.Entity.Items; using Chraft.Utilities.Blocks; using Chraft.World.Blocks.Base; namespace Chraft.World.Blocks { class BlockStone : BlockBase { public BlockStone() { Name = "Stone"; Type = BlockData.Blocks.Stone; IsSolid = true; var item = ItemHelper.GetInstance(BlockData.Blocks.Cobblestone); item.Count = 1; LootTable.Add(item); } } }
chraft/c-raft
Chraft/World/Blocks/BlockStone.cs
C#
agpl-3.0
1,214
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (c) 2015 Odoo S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api class StockPicking(models.Model): _inherit = 'stock.picking' carrier_price = fields.Float(string="Shipping Cost", readonly=True) delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True) @api.multi def do_transfer(self): res = super(StockPicking, self).do_transfer() if self.carrier_id and self.carrier_id.delivery_type != 'grid': self.send_to_shipper() return res # Signature due to strange old api methods @api.model def _prepare_shipping_invoice_line(self, picking, invoice): picking.ensure_one() invoice.ensure_one() carrier = picking.carrier_id # No carrier if not carrier: return None # Carrier already invoiced on the sale order if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids): return None # Classic carrier if carrier.delivery_type == 'grid': return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice) # Shipping provider price = picking.carrier_price account_id = carrier.product_id.property_account_income.id if not account_id: account_id = carrier.product_id.categ_id.property_account_income_categ.id taxes = carrier.product_id.taxes_id taxes_ids = taxes.ids # Apply original SO fiscal position if picking.sale_id.fiscal_position_id: fpos = picking.sale_id.fiscal_position_id account_id = fpos.map_account(account_id) taxes_ids = fpos.map_tax(taxes).ids res = { 'name': carrier.name, 'invoice_id': invoice.id, 'uos_id': carrier.product_id.uos_id.id, 'product_id': carrier.product_id.id, 'account_id': account_id, 'price_unit': price, 'quantity': 1, 'invoice_line_tax_ids': [(6, 0, taxes_ids)], } return res @api.one def send_to_shipper(self): res = self.carrier_id.send_shipping(self)[0] self.carrier_price = res['exact_price'] self.carrier_tracking_ref = res['tracking_number'] msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref) self.message_post(body=msg) @api.multi def open_website_url(self): self.ensure_one() client_action = {'type': 'ir.actions.act_url', 'name': "Shipment Tracking Page", 'target': 'new', 'url': self.carrier_id.get_tracking_link(self)[0] } return client_action @api.one def cancel_shipment(self): self.carrier_id.cancel_shipment(self) msg = "Shipment %s cancelled" % self.carrier_tracking_ref self.message_post(body=msg) self.carrier_tracking_ref = False
tvtsoft/odoo8
addons/delivery/models/stock_picking.py
Python
agpl-3.0
4,025
<!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/html; charset=utf-8" /> <title>Search &mdash; Paver 1.2.1 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '1.2.1', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/searchtools.js"></script> <link rel="top" title="Paver 1.2.1 documentation" href="index.html" /> <script type="text/javascript"> jQuery(function() { Search.loadIndex("searchindex.js"); }); </script> <script type="text/javascript" id="searchindexloader"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">Paver 1.2.1 documentation</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1 id="search-documentation">Search</h1> <div id="fallback" class="admonition warning"> <script type="text/javascript">$('#fallback').hide();</script> <p> Please activate JavaScript to enable the search functionality. </p> </div> <p> From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. </p> <form action="" method="get"> <input type="text" name="q" value="" /> <input type="submit" value="search" /> <span id="search-progress" style="padding-left: 10px"></span> </form> <div id="search-results"> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="index.html">Paver 1.2.1 documentation</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2008, SitePen, Inc.. Last updated on Jun 02, 2013. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2b1. </div> </body> </html>
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/paver/docs/search.html
HTML
agpl-3.0
3,455
<?php $this->applyTemplateHook('settings-nav','before'); ?> <nav id="panel-settings-nav" class="sidebar-panel"> <?php $this->applyTemplateHook('settings-nav','begin'); ?> <?php $this->applyTemplateHook('settings-nav','end'); ?> </nav> <?php $this->applyTemplateHook('settings-nav','after'); ?>
secultce/mapasculturais
src/protected/application/themes/BaseV1/layouts/parts/panel-settings-nav.php
PHP
agpl-3.0
306
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.ctp.server.notification; /** * * @version $Id: NotificationProviderException.java,v 1.2 2007-11-28 11:26:16 nichele Exp $ */ public class NotificationProviderException extends Exception { /** * Creates a new instance of <code>NotificationProviderException</code> without * detail message. */ public NotificationProviderException() { super(); } /** * Constructs an instance of <code>NotificationProviderException</code> with the * specified detail message. * * @param message the detail message. */ public NotificationProviderException(String message) { super(message); } /** * Constructs an instance of <code>NotificationProviderException</code> with the * specified detail message and the given cause. * * @param message the detail message. * @param cause the cause. */ public NotificationProviderException(String message, Throwable cause) { super(message, cause); } /** * Constructs an instance of <code>NotificationProviderException</code> with the * specified cause. * * @param cause the cause. */ public NotificationProviderException(Throwable cause) { super(cause); } }
accesstest3/cfunambol
ctp/ctp-server/src/main/java/com/funambol/ctp/server/notification/NotificationProviderException.java
Java
agpl-3.0
3,078
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.spinalinjuries.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseSharedNewConcernImpl extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatesaveConcern(ims.core.vo.PatientCurrentConcernVo concern, ims.core.vo.PatientShort patient) { } @SuppressWarnings("unused") public void validatelistHcps(ims.core.vo.HcpFilter filter) { } @SuppressWarnings("unused") public void validatelistProbsOnAdmission(ims.core.vo.CareContextShortVo coClinicalContactShort) { } @SuppressWarnings("unused") public void validategetConcern(ims.core.clinical.vo.PatientConcernRefVo concernId) { } }
open-health-hub/openmaxims-linux
openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/domain/base/impl/BaseSharedNewConcernImpl.java
Java
agpl-3.0
2,507
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Cornel Ventuneac */ public class TrackingLiteVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.TrackingLiteVo copy(ims.emergency.vo.TrackingLiteVo valueObjectDest, ims.emergency.vo.TrackingLiteVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_Tracking(valueObjectSrc.getID_Tracking()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // CurrentArea valueObjectDest.setCurrentArea(valueObjectSrc.getCurrentArea()); // isPrimaryCare valueObjectDest.setIsPrimaryCare(valueObjectSrc.getIsPrimaryCare()); // isDischarged valueObjectDest.setIsDischarged(valueObjectSrc.getIsDischarged()); // LastMovementDateTime valueObjectDest.setLastMovementDateTime(valueObjectSrc.getLastMovementDateTime()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createTrackingLiteVoCollectionFromTracking(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.Set domainObjectSet) { return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) iterator.next(); ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.List domainObjectList) { return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) domainObjectList.get(i); ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.Tracking set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection) { return extractTrackingSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i); ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.Tracking list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection) { return extractTrackingList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i); ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.Tracking object. * @param domainObject ims.emergency.domain.objects.Tracking */ public static ims.emergency.vo.TrackingLiteVo create(ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.Tracking object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.TrackingLiteVo create(DomainObjectMap map, ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.TrackingLiteVo valueObject = (ims.emergency.vo.TrackingLiteVo) map.getValueObject(domainObject, ims.emergency.vo.TrackingLiteVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.TrackingLiteVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.Tracking */ public static ims.emergency.vo.TrackingLiteVo insert(ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.Tracking */ public static ims.emergency.vo.TrackingLiteVo insert(DomainObjectMap map, ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_Tracking(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // CurrentArea if (domainObject.getCurrentArea() != null) { if(domainObject.getCurrentArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCurrentArea(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1)); } else { valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getCurrentArea().getId(), domainObject.getCurrentArea().getVersion())); } } // isPrimaryCare valueObject.setIsPrimaryCare( domainObject.isIsPrimaryCare() ); // isDischarged valueObject.setIsDischarged( domainObject.isIsDischarged() ); // LastMovementDateTime java.util.Date LastMovementDateTime = domainObject.getLastMovementDateTime(); if ( null != LastMovementDateTime ) { valueObject.setLastMovementDateTime(new ims.framework.utils.DateTime(LastMovementDateTime) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject) { return extractTracking(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_Tracking(); ims.emergency.domain.objects.Tracking domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.Tracking)domMap.get(valueObject); } // ims.emergency.vo.TrackingLiteVo ID_Tracking field is unknown domainObject = new ims.emergency.domain.objects.Tracking(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Tracking()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.Tracking)domMap.get(key); } domainObject = (ims.emergency.domain.objects.Tracking) domainFactory.getDomainObject(ims.emergency.domain.objects.Tracking.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_Tracking()); ims.emergency.configuration.domain.objects.TrackingArea value1 = null; if ( null != valueObject.getCurrentArea() ) { if (valueObject.getCurrentArea().getBoId() == null) { if (domMap.get(valueObject.getCurrentArea()) != null) { value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getCurrentArea()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getCurrentArea(); } else { value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getCurrentArea().getBoId()); } } domainObject.setCurrentArea(value1); domainObject.setIsPrimaryCare(valueObject.getIsPrimaryCare()); domainObject.setIsDischarged(valueObject.getIsDischarged()); ims.framework.utils.DateTime dateTime4 = valueObject.getLastMovementDateTime(); java.util.Date value4 = null; if ( dateTime4 != null ) { value4 = dateTime4.getJavaDate(); } domainObject.setLastMovementDateTime(value4); return domainObject; } }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/TrackingLiteVoAssembler.java
Java
agpl-3.0
17,855
<!-- This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details --> <div id="webapp-editor-templates" class="hide"> <!-- Template for the entire editor, both tabs and the actual content --> <div class="webapp-editor"> <div class="row"> <div class="col-xs-12"> <!-- The editor content gets displayed here --> <div class="webapp-editor-content"> </div> </div> </div> </div> <!-- Template for the tab at the top of the editor with filename and an x --> <ul> <!-- ul so is valid html --> <li class="super-menu webapp-editor-filename-pill"> <div class="webapp-editor-close-button-x pull-right lighten"><i class="fa fa-times"></i></div> <a> <span class="webapp-editor-tab-filename"></span> </a> </li> </ul> <!-- Template for the codemirror text editor --> <div class="webapp-editor-codemirror smc-vfill"> <textarea class="webapp-editor-textarea-0 hide"></textarea> <textarea class="webapp-editor-textarea-1 hide"></textarea> <div class="webapp-editor-codemirror-content smc-vfill"> <div class="webapp-editor-codemirror-button-row"> <div class="webapp-editor-codemirror-button-container"> <div class="hidden-xs webapp-editor-chat-title webapp-editor-write-only pull-right"> <div class="smc-users-viewing-document"> <!--to be filled with react component for users viewing the document--> </div> </div> <div class="smc-editor-file-info-dropdown" style="float:left;"></div> <span class="visible-xs"> <span class="btn-group"> <!-- <a href="#close" class="btn btn-default btn-lg"><i class="fa fa-toggle-up"></i> <span>Files...</span></a>--> <a href="#save" class="btn btn-success btn-lg"><i class="fa fa-save"></i> Save</a> <a href="#goto-line" class="btn btn-default btn-lg"><i class="fa fa-bolt"> </i></a> </span> <span class="btn-group webapp-editor-codemirror-worksheet-buttons hide"> <a href="#execute" class="btn btn-success btn-lg"> <i class="fa fa-play"></i> Run</a> <a href="#interrupt" class="btn btn-warning btn-lg"> <i class="fa fa-stop"></i></a> <a href="#kill" class="btn btn-warning btn-lg"><i class="fa fa-refresh"></i></a> <a href="#tab" class="btn btn-info btn-lg"> <i class="fa fa-step-forward"></i></a> </span> <span class="btn-group"> <a href="#decrease-font" class="btn btn-default btn-lg"><i class="fa fa-font" style="font-size:8pt"> </i> </a> <a href="#increase-font" class="btn btn-default btn-lg"><i class="fa fa-font" style="font-size:13pt"> </i> </a> </span> <a class="btn btn-primary btn-lg hide" href="#copy-to-another-project"><i class="fa fa-paper-plane"> </i> <span>Copy To Your Project...</span></a> </span> <span class="btn-group webapp-editor-write-only"> <a href="#save" class="hidden-xs btn btn-success webapp-editor-save-group" data-toggle="tooltip" data-placement="bottom" title="Save file to disk."> <i class="fa fa-save primary-icon"></i> <i class="fa fa-cocalc-ring hide"></i> Save <span class="smc-uncommitted hide" data-toggle="tooltip" data-placement="bottom" title="DANGER: File NOT sent to server and not saved to disk. You will lose work if you close this file."> NOT saved!</span> </a> <a href="#history" class="hidden-xs btn btn-info webapp-editor-history-button hide" data-toggle="tooltip" data-placement="bottom" title="View the history of this file."> <i class="fa fa-history"></i> <span class="hidden-sm">TimeTravel</span> </a> </span> <span class="hidden-xs"> <span class="webapp-editor-codemirror-worksheet-buttons hide"> <span class="btn-group webapp-editor-write-only"> <a href="#execute" class="btn btn-default " data-toggle="tooltip" data-placement="bottom" title="Execute current or selected cells (unless input hidden)."><i class="fa fa-play"></i> &nbsp;Run</a> <a href="#tab" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tab completion."> <i class="fa fa-step-forward"></i> <span class="hidden-sm hidden-md">Tab</span></a> <a href="#interrupt" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Stop the running calculation."><i class="fa fa-stop"></i> <span class="hidden-sm hidden-md">Stop</span></a> <a href="#kill" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Restart the running Sage process (all variables reset)."><i class="fa fa-refresh"></i> <span class="hidden-sm hidden-md">Restart</span></a> </span> <span class="btn-group webapp-editor-write-only hidden-sm"> <a href="#toggle-input" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Toggle display of input of selected cells."><i class="fa fa-toggle-on"></i> <span class="hidden-sm hidden-md">in</span></a> <a href="#toggle-output" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Toggle display of output of selected cells."><i class="fa fa-toggle-on"></i> <span class="hidden-sm hidden-md">out</span></a> <a href="#delete-output" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Delete output of selected cells (unless input hidden)."><i class="fa fa-times-circle"></i></a> </span> </span> </span> <span class="hidden-xs btn-group editor-btn-group"> <a href="#vim-mode-toggle" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Toggle VIM mode" style="width:4em">esc</a> <a href="#autoindent" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Autoindent selected text"><i class="fa fa-indent"></i></a> <a href="#undo" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Undo"><i class="fa fa-undo"></i></a> <a href="#redo" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Redo"><i class="fa fa-repeat"></i></a> <a href="#search" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Search"><i class="fa fa-search"></i></a> <!-- <a href="#prev" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Previous"><i class="fa fa-chevron-up"></i></a> <a href="#next" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Next"><i class="fa fa-chevron-down"></i></a>--> <a href="#replace" class="btn btn-default webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Replace"><i class="fa fa-exchange"></i></a> <a href="#split-view" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Split view of document"> <i class="fa fa-horizontal-split webapp-editor-layout-0 hide"></i> <i class="fa fa-vertical-split webapp-editor-layout-1 hide"></i> <i class="fa fa-window-maximize webapp-editor-layout-2 hide" style="font-size: 12pt;"></i> </a> <a href="#decrease-font" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Decrease text size"><i class="fa fa-font" style="font-size:7pt"> </i> </a> <a href="#increase-font" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Increase text size"><i class="fa fa-font" style="font-size:11pt"> </i> </a> <a href="#goto-line" class="btn btn-default btn-history" data-toggle="tooltip" data-placement="bottom" title="Go to line"><i class="fa fa-bolt"> </i> </a> <a href="#copy" class="btn btn-default btn-history webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Copy"><i class="fa fa-copy"> </i> </a> <a href="#paste" class="btn btn-default btn-history webapp-editor-write-only" data-toggle="tooltip" data-placement="bottom" title="Paste"><i class="fa fa-paste"> </i> </a> <a href="#sagews2pdf" class="hidden-sm btn btn-default webapp-editor-write-only hide" data-toggle="tooltip" data-placement="bottom" title="Convert to PDF"><i class="fa fa-file-pdf-o"> </i> </a> <a href="#print" class=" hidden-sm btn btn-default webapp-editor-write-only hide" data-toggle="tooltip" data-placement="bottom" title="Print"><i class="fa fa-print"> </i> <i class="fa fa-cocalc-ring hide"></i></a> </a> <a href="#sagews2ipynb" class="hidden-sm btn btn-default webapp-editor-write-only hide" data-toggle="tooltip" data-placement="bottom" title="Convert to ipynb"><i class="fa fa-ipynb"> </i> <span class="hidden-sm hidden-md">Jupyter</span></a> </span> <span class="btn-group webapp-editor-read-only hide"> <a href="#readonly" class="hidden-xs btn btn-success webapp-editor-save-group disabled" data-toggle="tooltip" data-placement="bottom" title="File is read only."> <i class="fa fa-save"></i> <span class="hidden-sm">Readonly</span> </a> <a href="#history" class="hidden-xs btn btn-info webapp-editor-history-button hide" data-toggle="tooltip" data-placement="bottom" title="View the history of this file."> <i class="fa fa-history"></i> <span class="hidden-sm hidden-md">TimeTravel</span> </a> </span> <span class="hidden-xs"> <a class="btn btn-primary hide" href="#copy-to-another-project"><i class="fa fa-paper-plane"> </i> <span>Copy To Your Project...</span></a> <!--<a class="btn btn-success" href="#download-file"><i class="fa fa-cloud-download"> </i> <span class="hidden-sm">Download</span></a>--> </span> <span class="webapp-editor-codemirror-loading hide"> <i class="fa fa-cocalc-ring"></i> load… </span> <span class="webapp-editor-codemirror-sync"> <span class="webapp-editor-codemirror-not-synced hide"><i class="fa fa-cocalc-ring"></i> sync…</span> <span class="webapp-editor-codemirror-synced hide"><i class="fa fa-check"></i></span> </span> <span class="webapp-editor-codemirror-message"></span> <span class="webapp-editor-codemirror-filename pull-right"></span> </div> <div class="webapp-editor-buttonbars webapp-editor-write-only"> <div class="webapp-editor-latex-buttonbar hide"></div> <div class="webapp-editor-codemirror-textedit-buttons hide visible-sm-block visible-md-block visible-lg-block"> <code class="webapp-editor-codeedit-buttonbar-mode pull-right hide"></code> <span class="react-target"></span> <span class="webapp-editor-codeedit-buttonbar-assistant pull-right hide"> <a href="#assistant" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert examples"> <i class="fa fa-magic"></i> <span class="hidden-sm">Snippets</span> </a> </span> </div> <div class="webapp-editor-codemirror-worksheet-editable-buttons hide"> <span class="btn-group"> <a href="#bold" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Bold"><i class="fa fa-bold"></i></a> <a href="#italic" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Italic"><i class="fa fa-italic"></i></a> <a href="#underline" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Underline"><i class="fa fa-underline"></i></a> <a href="#strikethrough" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Strike through"><i class="fa fa-strikethrough"></i></a> <a href="#subscript" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Subscript (use LaTeX for serious equations)"><i class="fa fa-subscript"></i></a> <a href="#superscript" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Superscript"><i class="fa fa-superscript"></i></a> </span> <span class="btn-group"> <a href="#equation" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Inline equation..."> $ </a> <a href="#display_equation" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Displayed equation..."> $$ </a> <a href="#insertunorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert unordered list"><i class="fa fa-list"></i></a> <a href="#insertorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert ordered list"><i class="fa fa-list-ol"></i></a> <a href="#link" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert link..."><i class="fa fa-link"></i></a> <a href="#image" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Insert image..."><i class="fa fa-image"></i></a> <!-- <a href="#insertHorizontalRule" class="btn btn-default">&lt;hr&gt;</a> --> </span> <span class="btn-group"> <a href="#justifyleft" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Left justify"><i class="fa fa-align-left"></i></a> <a href="#justifycenter" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Justify center"><i class="fa fa-align-center"></i></a> <a href="#justifyright" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Right justify"><i class="fa fa-align-right"></i></a> <a href="#justifyfull" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Justify full"><i class="fa fa-align-justify"></i></a> <a href="#outdent" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Outdent"><i class="fa fa-outdent"></i></a> <a href="#indent" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Indent"><i class="fa fa-indent"></i></a> </span> <span class="btn-group"> <a href="#undo" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Undo"><i class="fa fa-undo"></i></a> <a href="#redo" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Redo"><i class="fa fa-repeat"></i></a> </span> <span class="btn-group"> <span class="btn-group sagews-output-editor-font smc-tooltip" data-toggle="tooltip" data-placement="top" title="Fonts"> <span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Font"> <i class="fa fa-font"></i> <b class="caret"></b> </span> <ul class="dropdown-menu"> </ul> </span> <span class="btn-group sagews-output-editor-font-size smc-tooltip" data-toggle="tooltip" data-placement="top" title="Font size"> <span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Text height"> <i class="fa fa-text-height"></i> <b class="caret"></b> </span> <ul class="dropdown-menu"> </ul> </span> <span class="btn-group sagews-output-editor-block-type smc-tooltip" data-toggle="tooltip" data-placement="top" title="Format type"> <span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Header"> <i class="fa fa-header"></i> <b class="caret"></b> </span> <ul class="dropdown-menu"> </ul> </span> </span> <span class="btn-group"> <!-- not implemented yet --> <span class="sagews-output-editor-foreground-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="top" title="Text color"> <input type="text" style="cursor:pointer" class="form-control"> <span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span> </span> </span> <span class="btn-group"> <!-- not implemented yet --> <span class="sagews-output-editor-background-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="top" title="Text background highlight color"> <input type="text" style="cursor:pointer" class="form-control"> <span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span> </span> </span> </div> </div> </div> <div class="webapp-editor-codemirror-input-container-layout-0 hide" style="flex: 1; display: flex; flex-direction: column;"> <!-- See https://github.com/codemirror/CodeMirror/issues/3679 for why we do this nesting (to work around a chrome bug, and/or avoid major slowdown doing layout?) --> <div class="webapp-editor-codemirror-input-box" style="display: flex; flex-direction: column; position:relative;"> <div style="position:absolute; height:100%; width:100%"> </div> </div> <div class="webapp-editor-codemirror-input-box-1 hide"> <div> </div> </div> </div> <div class="webapp-editor-codemirror-input-container-layout-1 hide" style="flex: 1; display: flex; flex-direction: column;"> <!-- See https://github.com/codemirror/CodeMirror/issues/3679 for why we do this nesting (to work around a chrome bug, and/or avoid major slowdown doing layout?) --> <div class="webapp-editor-codemirror-input-box" style="display: flex; flex-direction: column; position:relative;"> <div style="position:absolute; height:100%; width:100%"> </div> </div> <div class="webapp-editor-resize-bar-layout-1"> </div> <!-- flex: 1 so expands to what is left after editor above is placed. --> <div class="webapp-editor-codemirror-input-box-1" style="flex: 1; display: flex; flex-direction: column; position:relative;"> <div style="position:absolute; height:100%; width:100%"> </div> </div> </div> <div class="webapp-editor-codemirror-input-container-layout-2 hide" style="flex: 1; display: flex; flex-direction: row;"> <!-- See https://github.com/codemirror/CodeMirror/issues/3679 for why we do this nesting (to work around a chrome bug, and/or avoid major slowdown doing layout?) --> <div class="webapp-editor-codemirror-input-box" style="display: flex; flex-direction: column; position:relative;"> <div style="position:absolute; height:100%; width:100%"> </div> </div> <div class="webapp-editor-resize-bar-layout-2"> </div> <!-- flex: 1 so expands to what is left after editor above is placed. --> <div class="webapp-editor-codemirror-input-box-1" style="flex: 1; display: flex; flex-direction: column; position:relative;"> <div style="position:absolute; height:100%; width:100%"> </div> </div> </div> </div> <div class="webapp-editor-codemirror-startup-message alert alert-warning hide" role='alert'> </div> </div> <!-- Template for the codemirror text editor other user cursors --> <div class="webapp-editor-codemirror-cursor"><span class="webapp-editor-codemirror-cursor-label"></span><div class="webapp-editor-codemirror-cursor-inside">&nbsp;&nbsp;&nbsp;</div></div> <div class="smc-editor-codemirror-cursor"><span class="smc-editor-codemirror-cursor-label"></span><div class="smc-editor-codemirror-cursor-inside">&nbsp;&nbsp;&nbsp;</div></div> <!-- Static HTML viewer --> <div class="webapp-editor-static-html"> <div class="webapp-editor-static-html-content"> <iframe style="width:100%;border:0px;"> </iframe> </div> </div> <!-- Templates for the png-based PDF previewer; this is designed for the pdf changes in little ways locally. --> <div class="webapp-editor-pdf-preview smc-vfill"> <div class="webapp-editor-pdf-preview-spinner hide"></div> <div class="webapp-editor-pdf-preview-highlight hide"></div> <div class="webapp-editor-pdf-preview-buttons"> <span class="btn-group"> <a href="#zoom-preview-out" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom out some"><i class="fa fa-search-minus"></i></a> <a href="#zoom-preview-in" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom in some"><i class="fa fa-search-plus"></i></a> <a href="#zoom-preview-fullpage" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom so page width matches viewport"><i class="fa fa-file-o"></i></a> <a href="#zoom-preview-width" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Zoom in close"><i class="fa fa-arrows-alt"></i></a> <a href="#preview-resolution" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Change the preview resolution"><i class="fa fa-th"></i></a> <a href="#pdf-download" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="Download the PDF file"><i class="fa fa-download"></i></a> </span> <span class="btn-group pull-right"> <a href="#toggle-preview" class="btn btn-sm btn-default" data-toggle="tooltip" data-placement="bottom" title="If enabled, the LaTeX file is compiled and a preview is rendered."> <i class="fa fa-check-square-o"></i> Build preview </a> </span> </div> <div style="flex:1;overflow-y:auto;overflow-x:auto" class="webapp-editor-pdf-preview-output"> <div class="webapp-editor-pdf-preview-page"> </div> <div class="webapp-editor-pdf-preview-message hide"> </div> </div> </div> <!-- Templates for the embedded PDF previewer: just uses the built-in renderer; can't cope with file updates, inverse search, etc. --> <div class="webapp-editor-pdf-preview-embed smc-vfill"> <div class="webapp-editor-codemirror-button-row"> <span class="webapp-editor-pdf-preview-embed-spinner hide"></span> <span class="btn-group"> <a class="btn btn-default btn-lg visible-xs" href="#close" ><i class="fa fa-toggle-up"></i> <span class="hidden-xs">Files...</span></a> <a class="btn btn-default btn-lg visible-xs" href="#refresh"><i class="fa fa-refresh"></i> <span class="hidden-xs"> Refresh</span></a> <a class="btn btn-default hidden-xs" href="#refresh"><i class="fa fa-refresh"></i> <span class="hidden-xs"> Refresh</span></a> </span> <span class="btn-group pull-right"> <a class="btn btn-default webapp-editor-pdf-title hidden-xs"> <i class="fa fa-external-link"></i> <span></span> </a> </span> </div> <div class="webapp-editor-pdf-preview-embed-page smc-vfill"> <iframe frameborder="0" scrolling="no" style="width:100%;height:100%"> <br> <br> &nbsp;&nbsp;&nbsp;Your browser doesn't support embedded PDF's, but you can <a target='_blank'>download <span></span></a>... </iframe> </div> </div> <div class="webapp-editor-history smc-vfill"> <div class="webapp-editor-history-controls" style="display:flex; padding-left: 10px; padding-right: 10px; border-bottom: 1px solid lightgrey; background-color:#efefef"> <span style="color:#666; font-size:14pt; font-weight: bold; margin-right:1em"> <i class="fa fa-history"></i> TimeTravel </span> <span> <a href="#show-diff" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Show changes"><i class="fa fa-square-o"></i> Changes</a> <a href="#hide-diff" class="btn btn-default hide" data-toggle="tooltip" data-placement="bottom" title="Show what changed"><i class="fa fa-check-square-o"></i> Changes</a> </span> <span class="webapp-editor-history-control-button-container btn-group smc-btn-group-nobreak" style="margin-left:1em"> <a href="#back" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Back"><i class="fa fa-step-backward"></i></a> <a href="#forward" class="btn btn-default disabled" data-toggle="tooltip" data-placement="bottom" title="Forward"><i class="fa fa-step-forward"></i></a> </span> <span class="btn-group smc-btn-group-nobreak"> <a href="#file" class="btn btn-info " style="margin-left:1em" data-toggle="tooltip" data-placement="bottom" title="Show full file"><i class="fa fa-file-code-o"></i> Open File</a> <a href="#revert" class="btn btn-warning hide" data-toggle="tooltip" data-placement="bottom" title="Revert the live file to the displayed revision"><i class="fa fa-undo"></i> Revert live version to this &nbsp;</a> <a href="#snapshots" class="btn btn-default"> <i class="fa fa-life-saver"></i> <span class="hidden-sm" style="font-size: 12px;">Backups</span> </a> <a href="#all" class="btn btn-default hide" data-toggle="tooltip" data-placement="bottom" title="Load complete history"><i class="fa fa-floppy-o"></i> Load All History </a> <a href="#export" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Export to file"><i class="fa fa-file-export"></i> Export</a> </span> <div style="color:#666; margin-left: 1em"> <span class="webapp-editor-history-revision-time" style="font-weight: bold; font-size:12pt"></span><span class="webapp-editor-history-diff-mode hide">&nbsp;&nbsp; to&nbsp;&nbsp; </span><span class="hide webapp-editor-history-diff-mode webapp-editor-history-revision-time2" style="font-weight: bold; font-size:12pt"></span><span class="webapp-editor-history-revision-number"> </span> </div> </div> <div style="margin-top:7px; margin-right:15px;"> &nbsp; <span class="webapp-editor-history-revision-user lighten pull-right"></span> </div> <div class="webapp-editor-history-sliders" style="border-bottom: 1px solid lightgrey;"> <div class="webapp-editor-history-slider webapp-editor-history-slider-style"> </div> <div class="webapp-editor-history-diff-slider hide webapp-editor-history-slider-style"> </div> </div> <div class="webapp-editor-history-no-viewer hide" style="margin-left:15px"> <b>WARNING: </b> History viewer for this file type not implemented, so showing underlying raw file instead. </div> <div class="webapp-editor-history-history_editor smc-vfill"></div> </div> <span class="sagews-input"> <span class="sagews-input-hr sagews-input-eval-state"></span> <span class="sagews-input-hr sagews-input-run-state"></span> <span class="sagews-input-hr sagews-input-newcell"></span> </span> <span class="sagews-output"> <span class="sagews-output-container"> <span class="sagews-output-messages"></span> </span> </span> <div class="webapp-ipython-notebook"> <!--<h3 style="margin-left:1em">IPython Notebook: <span class="webapp-ipython-filename"></span></h3>--> <div class="webapp-ipython-notebook-buttons hidden-xs"> <span class="webapp-ipython-notebook-status-messages lighten"> </span> <span class="hide webapp-ipython-notebook-danger">DANGER: Users on this VM could connect unless you stop your ipython-notebook server (they would have to know secret internal project-id).</span> <span class="btn-group"> <a href="#save" class="btn btn-sm btn-success" data-toggle="tooltip" data-placement="bottom" title="Save .ipynb file to disk (file is constantly sync'd with server)."> <i class="fa fa-save primary-icon"></i><i class="fa fa-cocalc-ring hide"></i> Save </a> <a href="#history" class="btn btn-sm btn-info webapp-editor-history-button hide" data-toggle="tooltip" data-placement="bottom" title="View the history of this file."> <i class="fa fa-history"></i> <span class="hidden-sm">TimeTravel</span> </a> <a href="#reload" class="btn btn-sm btn-warning" data-toggle="tooltip" data-placement="bottom" title="Reload this Notebook; use if the IPython server is killed or restarted on another port"> <i class="fa fa-refresh"></i> Reload</a> <a href="#publish" class="btn btn-primary btn-sm" data-toggle="tooltip" data-placement="bottom" title="Publish this notebook for anybody to see"> <i class="fa fa-refresh fa-spin hide"> </i> <i class="fa fa-share-square"></i> Publish</a> <a href="#info" class="btn btn-sm btn-info" data-toggle="tooltip" data-placement="bottom" title="Extra information about the IPython notebook"> <i class="fa fa-info-circle"></i> About </a> </span> </div> <div class="visible-xs"> <span class="btn-group"> <a href="#save" class="btn btn-success btn-lg"> <i class="fa fa-save"></i> Save</a> </span> <span class="btn-group webapp-editor-codemirror-worksheet-buttons hide"> <a href="#execute" class="btn btn-default btn-lg"> <i class="fa fa-play"></i> <span>Run</span> </a> <a href="#interrupt" class="btn btn-default btn-lg"> <i class="fa fa-stop"></i> <span>Stop</span> </a> <a href="#tab" class="btn btn-default btn-lg"> <i class="fa fa-info-circle"></i> <span>Tab</span> </a> </span> <span class="btn-group"> <a href="#reload" class="btn btn-warning btn-lg"> <i class="fa fa-refresh"></i> Reload</a> <a href="#info" class="btn btn-info btn-lg"> <i class="fa fa-info-circle"></i> </a> </span> </div> <h3 class="webapp-ipython-notebook-connecting hide" style="margin-left:2em">Opening...</h3> <div class="webapp-ipython-notebook-notebook"></div> </div> <div class="modal webapp-file-print-dialog" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close btn-close" aria-hidden="true"> <span style="font-size:20pt;">×</span> </button> <h3><i class="fa fa-print"> </i> Printable PDF version of <span class="webapp-file-print-filename"></span></h3> </div> <div class="well"> <h4>Heading <span class="lighten">(click to edit)</span></h4> <div class="well" style="background-color:white; text-align:center"> <h4 class="webapp-file-print-title" contenteditable="true"></h4> <h5 class="webapp-file-print-author" contenteditable="true"></h5> <h5 class="webapp-file-print-date" contenteditable="true"></h5> </div> <div class="webapp-file-options-sagews hide"> <h4>Worksheet Options</h4> <div class="well" style="background-color:white"> <div class="checkbox"> <label class="" rel="tooltip" title="Table of contents"> <input type="checkbox" class="webapp-file-print-contents" rel="tooltip">Table of contents </label> </div> <div class="checkbox"> <label class="" rel="tooltip" title="Keep generated files"> <input type="checkbox" class="webapp-file-print-keepfiles" rel="tooltip">Keep generated files in a sub-directory. This is useful for debugging printing issues or additional editing. <div class="smc-file-printing-tempdir hide"></div> </label> </div> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-close pull-left btn-default btn-lg">Close</button> <button class="btn btn-primary btn-submit pull-left btn-lg"><i class="fa fa-bolt primary-icon"> </i> <i class="fa fa-cocalc-ring hide"></i> Generate PDF</button> <span class="webapp-file-printing-progress hide">Preparing PDF version...</span> <a class="webapp-file-printing-link hide" target="_blank">link to PDF version</a> </div> </div> </div> </div> <div class="modal webapp-goto-line-dialog" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close btn-close" aria-hidden="true"> <span style="font-size:20pt;">×</span> </button> <h3><i class="fa fa-bolt"> </i> Goto Line</h3> </div> <div class="well" style="margin:1em"> <div class="lighten">Enter <span class="webapp-goto-line-range"></span></div> <input class="webapp-goto-line-input form-control" style="width:95%; margin-top: 1ex;" type="text" placeholder=""> </div> <div class="modal-footer"> <button class="btn btn-close btn-default">Cancel</button> <button class="btn btn-primary btn-submit">OK</button> </div> </div> </div> </div> <div class="webapp-editor-textedit-buttonbar"> <span class="btn-group"> <a href="#bold" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Bold"><i class="fa fa-bold"></i></a> <a href="#italic" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Italic"><i class="fa fa-italic"></i></a> <a href="#underline" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Underline"><i class="fa fa-underline"></i></a> <a href="#strikethrough" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Strike through"><i class="fa fa-strikethrough"></i></a> <a href="#subscript" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Subscript (use LaTeX for serious equations)"><i class="fa fa-subscript"></i></a> <a href="#superscript" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Superscript"><i class="fa fa-superscript"></i></a> <a href="#comment" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Comment out selection"><i class="fa fa-comment-o"></i></a> </span> <span class="btn-group"> <a href="#equation" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Inline equation..."> $ </a> <a href="#display_equation" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Displayed equation..."> $$ </a> <a href="#insertunorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert unordered list"><i class="fa fa-list"></i></a> <a href="#insertorderedlist" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert ordered list"><i class="fa fa-list-ol"></i></a> <a href="#link" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert link..."><i class="fa fa-link"></i></a> <a href="#image" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert image..."><i class="fa fa-image"></i></a> <a href="#table" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert table"><i class="fa fa-table"></i></a> <a href="#horizontalRule" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert horizontal line">&mdash;</a> <a href="#SpecialChar" data-args="special" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Insert Special Character ...">&Omega;</a> </span> <span class="btn-group"> <a href="#justifyleft" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Left justify"><i class="fa fa-align-left"></i></a> <a href="#justifycenter" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Justify center"><i class="fa fa-align-center"></i></a> <a href="#justifyright" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Right justify"><i class="fa fa-align-right"></i></a> <a href="#justifyfull" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Justify full"><i class="fa fa-align-justify"></i></a> <a href="#indent" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Indent/quote selected text"><i class="fa fa-indent"></i></a> <a href="#unformat" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Remove formatting"><i class="fa fa-remove"></i></a> <a href="#clean" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Make selected HTML valid"><i class="fa fa-code"></i></a> </span> <span class="btn-group"> <span class="btn-group sagews-output-editor-font-face smc-tooltip" data-toggle="tooltip" data-placement="bottom" title="Fonts"> <span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Font"> <i class="fa fa-font"></i> <b class="caret"></b> </span> <ul class="dropdown-menu"> </ul> </span> <span class="btn-group sagews-output-editor-font-size smc-tooltip" data-toggle="tooltip" data-placement="bottom" title="Font size"> <span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Text height"> <i class="fa fa-text-height"></i> <b class="caret"></b> </span> <ul class="dropdown-menu"> </ul> </span> <span class="btn-group sagews-output-editor-block-type smc-tooltip" data-toggle="tooltip" data-placement="bottom" title="Format type"> <span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Header"> <i class="fa fa-header"></i> <b class="caret"></b> </span> <ul class="dropdown-menu"> </ul> </span> </span> <!-- color menus disabled/broken: see https://github.com/sagemathinc/cocalc/issues/1167 for re-implementing them --> <span class="btn-group"> <span class="hide sagews-output-editor-foreground-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="bottom" title="Text color"> <input type="text" style="cursor:pointer" class="form-control"> <span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span> </span> </span> <span class="btn-group"> <span class="hide sagews-output-editor-background-color-selector input-group color smc-tooltip" data-color-format="rgb" data-toggle="tooltip" data-placement="bottom" title="Text background highlight color"> <input type="text" style="cursor:pointer" class="form-control"> <span class="input-group-addon" style="padding: 3px;"><i class="fa fa-font" style="height: 16px; width: 16px"></i><b class="caret"></b></span> </span> </span> </div> <div class="webapp-editor-codeedit-buttonbar hide" style="margin: 2px"> <!-- buttonbar.coffee populates all entries --> </div> <div class="webapp-editor-redit-buttonbar hide" style="margin: 2px"> <!-- buttonbar.coffee populates the entries --> </div> <div class="webapp-editor-julia-edit-buttonbar hide" style="margin: 2px"> <!-- buttonbar.coffee populates the entries --> </div> <div class="webapp-editor-sh-edit-buttonbar hide" style="margin: 2px"> <!-- buttonbar.coffee populates the entries --> </div> <div class="webapp-editor-fricas-edit-buttonbar hide" style="margin: 2px"> <!-- buttonbar.coffee populates the entries --> </div> <div class="webapp-editor-fallback-edit-buttonbar hide" style="margin: 2px"> <a class="btn btn-default" href="#todo">&hellip;</a> </div> <div class='sagews-output-raw_input'> <div class="form-inline"> <div class="form-group"> <label class="sagews-output-raw_input-prompt" style="margin-right: 10px;"> </label> <div class="input-group"> <input class="sagews-output-raw_input-value form-control"> <span class="input-group-btn"> <button class="btn btn-success sagews-output-raw_input-submit" type="button"> <i class="fa fa-check"></i> </button> </span> </div> </div> </div> </div> </div>
DrXyzzy/cocalc
src/packages/frontend/editor.html
HTML
agpl-3.0
46,940
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\FinishRequestEvent; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Routing\RequestContextAwareInterface; /** * Initializes the locale based on the current request. * * This listener works in 2 modes: * * * 2.3 compatibility mode where you must call setRequest whenever the Request changes. * * 2.4+ mode where you must pass a RequestStack instance in the constructor. * * @author Fabien Potencier <fabien@symfony.com> */ class LocaleListener implements EventSubscriberInterface { private $router; private $defaultLocale; private $requestStack; /** * RequestStack will become required in 3.0. */ public function __construct($defaultLocale = 'en', RequestContextAwareInterface $router = null, RequestStack $requestStack = null) { $this->defaultLocale = $defaultLocale; $this->requestStack = $requestStack; $this->router = $router; } public static function getSubscribedEvents() { return array( // must be registered after the Router to have access to the _locale KernelEvents::REQUEST => array( array( 'onKernelRequest', 16 ) ), KernelEvents::FINISH_REQUEST => array( array( 'onKernelFinishRequest', 0 ) ), ); } /** * Sets the current Request. * * This method was used to synchronize the Request, but as the HttpKernel * is doing that automatically now, you should never call it directly. * It is kept public for BC with the 2.3 version. * * @param Request|null $request A Request instance * * @deprecated Deprecated since version 2.4, to be removed in 3.0. */ public function setRequest(Request $request = null) { if (null === $request) { return; } $this->setLocale($request); $this->setRouterContext($request); } private function setLocale( Request $request ) { if ($locale = $request->attributes->get( '_locale' )) { $request->setLocale( $locale ); } } private function setRouterContext( Request $request ) { if (null !== $this->router) { $this->router->getContext()->setParameter( '_locale', $request->getLocale() ); } } public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); $request->setDefaultLocale($this->defaultLocale); $this->setLocale($request); $this->setRouterContext($request); } public function onKernelFinishRequest(FinishRequestEvent $event) { if (null === $this->requestStack) { return; // removed when requestStack is required } if (null !== $parentRequest = $this->requestStack->getParentRequest()) { $this->setRouterContext($parentRequest); } } }
KWZwickau/KREDA-Sphere
Library/MOC-V/Component/Router/Vendor/Symfony/Component/HttpKernel/EventListener/LocaleListener.php
PHP
agpl-3.0
3,436
package com.sapienter.jbilling.client.jspc.payment; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import com.sapienter.jbilling.client.util.Constants; public final class review_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.AnnotationProcessor _jsp_annotationprocessor; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.release(); _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.release(); _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"); if (_jspx_meth_sess_005fexistsAttribute_005f0(_jspx_page_context)) return; out.write('\r'); out.write('\n'); if (_jspx_meth_sess_005fexistsAttribute_005f1(_jspx_page_context)) return; out.write("\r\n\r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_sess_005fexistsAttribute_005f0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // sess:existsAttribute org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f0 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class); _jspx_th_sess_005fexistsAttribute_005f0.setPageContext(_jspx_page_context); _jspx_th_sess_005fexistsAttribute_005f0.setParent(null); // /payment/review.jsp(30,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_sess_005fexistsAttribute_005f0.setName("jsp_is_refund"); // /payment/review.jsp(30,0) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_sess_005fexistsAttribute_005f0.setValue(false); int _jspx_eval_sess_005fexistsAttribute_005f0 = _jspx_th_sess_005fexistsAttribute_005f0.doStartTag(); if (_jspx_eval_sess_005fexistsAttribute_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n "); if (_jspx_meth_tiles_005finsert_005f0(_jspx_th_sess_005fexistsAttribute_005f0, _jspx_page_context)) return true; out.write('\r'); out.write('\n'); int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_sess_005fexistsAttribute_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0); return true; } _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0); return false; } private boolean _jspx_meth_tiles_005finsert_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // tiles:insert org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f0 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class); _jspx_th_tiles_005finsert_005f0.setPageContext(_jspx_page_context); _jspx_th_tiles_005finsert_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f0); // /payment/review.jsp(31,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f0.setDefinition("payment.review"); // /payment/review.jsp(31,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f0.setFlush(true); int _jspx_eval_tiles_005finsert_005f0 = _jspx_th_tiles_005finsert_005f0.doStartTag(); if (_jspx_th_tiles_005finsert_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0); return true; } _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0); return false; } private boolean _jspx_meth_sess_005fexistsAttribute_005f1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // sess:existsAttribute org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f1 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class); _jspx_th_sess_005fexistsAttribute_005f1.setPageContext(_jspx_page_context); _jspx_th_sess_005fexistsAttribute_005f1.setParent(null); // /payment/review.jsp(33,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_sess_005fexistsAttribute_005f1.setName("jsp_is_refund"); int _jspx_eval_sess_005fexistsAttribute_005f1 = _jspx_th_sess_005fexistsAttribute_005f1.doStartTag(); if (_jspx_eval_sess_005fexistsAttribute_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n "); if (_jspx_meth_tiles_005finsert_005f1(_jspx_th_sess_005fexistsAttribute_005f1, _jspx_page_context)) return true; out.write('\r'); out.write('\n'); int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_sess_005fexistsAttribute_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1); return true; } _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1); return false; } private boolean _jspx_meth_tiles_005finsert_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f1, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // tiles:insert org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f1 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class); _jspx_th_tiles_005finsert_005f1.setPageContext(_jspx_page_context); _jspx_th_tiles_005finsert_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f1); // /payment/review.jsp(34,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f1.setDefinition("refund.review"); // /payment/review.jsp(34,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f1.setFlush(true); int _jspx_eval_tiles_005finsert_005f1 = _jspx_th_tiles_005finsert_005f1.doStartTag(); if (_jspx_th_tiles_005finsert_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1); return true; } _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1); return false; } }
maduhu/knx-jbilling2.2.0
build/jsp-classes/com/sapienter/jbilling/client/jspc/payment/review_jsp.java
Java
agpl-3.0
11,647
/*@author Jvlaple *Crystal of Roots */ var status = 0; var PQItems = Array(4001087, 4001088, 4001089, 4001090, 4001091, 4001092, 4001093); importPackage(net.sf.odinms.client); function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (status >= 0 && mode == 0) { cm.sendOk("Ok, keep preservering!"); cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0 ) { cm.sendYesNo("Hello I'm the Dungeon Exit NPC. Do you wish to go out from here?"); } else if (status == 1) { var eim = cm.getPlayer().getEventInstance(); cm.warp(100000000, 0); if (eim != null) { eim.unregisterPlayer(cm.getPlayer()); }cm.dispose(); } } }
ZenityMS/forgottenstorysource
scripts/npc/2111005.js
JavaScript
agpl-3.0
1,027
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.notificationdialog; public interface IFormUILogicCode { // No methods yet. }
open-health-hub/openmaxims-linux
openmaxims_workspace/Core/src/ims/core/forms/notificationdialog/IFormUILogicCode.java
Java
agpl-3.0
1,804
// Copyright 2014 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package v4 var ( BundleCharms = (*Handler).bundleCharms ParseSearchParams = parseSearchParams DefaultIcon = defaultIcon ArchiveCacheVersionedMaxAge = &archiveCacheVersionedMaxAge ArchiveCacheNonVersionedMaxAge = &archiveCacheNonVersionedMaxAge ParamsLogLevels = paramsLogLevels ParamsLogTypes = paramsLogTypes ProcessIcon = processIcon UsernameAttr = usernameAttr GroupsAttr = groupsAttr GetPromulgatedURL = (*Handler).getPromulgatedURL )
mhilton/charmstore
internal/v4/export_test.go
GO
agpl-3.0
699
# frozen_string_literal: true require "test_helper" module GobiertoAdmin class UserFormTest < ActiveSupport::TestCase def valid_user_form @valid_user_form ||= UserForm.new( id: user.id, name: user.name, bio: user.bio, email: user.email ) end def invalid_user_form @invalid_user_form ||= UserForm.new( name: nil, email: nil ) end def user @user ||= users(:reed) end def test_save_with_valid_attributes assert valid_user_form.save end def test_save_with_invalid_attributes refute invalid_user_form.save end def test_error_messages_with_invalid_attributes invalid_user_form.save assert_equal 1, invalid_user_form.errors.messages[:name].size assert_equal 1, invalid_user_form.errors.messages[:email].size end def test_confirmation_email_delivery_when_changing_email email_changing_form = UserForm.new( id: user.id, email: "wadus@gobierto.dev", name: "Wadus" ) assert_difference "ActionMailer::Base.deliveries.size", 1 do email_changing_form.save end end def test_confirmation_email_delivery_when_not_changing_email assert_no_difference "ActionMailer::Base.deliveries.size" do valid_user_form.save end end end end
PopulateTools/gobierto-dev
test/forms/gobierto_admin/user_form_test.rb
Ruby
agpl-3.0
1,372
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import pytest from django.conf import settings from shuup.core.models import Shipment, ShippingStatus, StockBehavior from shuup.testing.factories import ( add_product_to_order, create_empty_order, create_product, get_default_shop, get_default_supplier ) from shuup.utils.excs import Problem @pytest.mark.django_db def test_shipment_identifier(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): shipment = order.create_shipment({line.product: 1}, supplier=supplier) expected_key_start = "%s/%s" % (order.pk, i) assert shipment.identifier.startswith(expected_key_start) assert order.shipments.count() == int(line.quantity) assert order.shipping_status == ShippingStatus.FULLY_SHIPPED # Check that order is now fully shipped assert not order.can_edit() @pytest.mark.django_db def test_shipment_creation_from_unsaved_shipment(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): unsaved_shipment = Shipment(order=order, supplier=supplier) shipment = order.create_shipment({line.product: 1}, shipment=unsaved_shipment) expected_key_start = "%s/%s" % (order.pk, i) assert shipment.identifier.startswith(expected_key_start) assert order.shipments.count() == int(line.quantity) @pytest.mark.django_db def test_shipment_creation_without_supplier_and_shipment(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): with pytest.raises(AssertionError): order.create_shipment({line.product: 1}) assert order.shipments.count() == 0 @pytest.mark.django_db def test_shipment_creation_with_invalid_unsaved_shipment(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) second_order = create_empty_order(shop=shop) second_order.full_clean() second_order.save() product_lines = order.lines.exclude(product_id=None) for line in product_lines: for i in range(0, int(line.quantity)): with pytest.raises(AssertionError): unsaved_shipment = Shipment(supplier=supplier, order=second_order) order.create_shipment({line.product: 1}, shipment=unsaved_shipment) assert order.shipments.count() == 0 @pytest.mark.django_db def test_partially_shipped_order_status(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) assert order.can_edit() first_product_line = order.lines.exclude(product_id=None).first() assert first_product_line.quantity > 1 order.create_shipment({first_product_line.product: 1}, supplier=supplier) assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED assert not order.can_edit() @pytest.mark.django_db def test_shipment_delete(): shop = get_default_shop() supplier = get_default_supplier() order = _get_order(shop, supplier) assert order.can_edit() first_product_line = order.lines.exclude(product_id=None).first() assert first_product_line.quantity > 1 shipment = order.create_shipment({first_product_line.product: 1}, supplier=supplier) assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED assert order.shipments.all().count() == 1 # Test shipment delete shipment.soft_delete() assert order.shipments.all().count() == 1 assert order.shipments.all_except_deleted().count() == 0 # Check the shipping status update assert order.shipping_status == ShippingStatus.NOT_SHIPPED @pytest.mark.django_db def test_shipment_with_insufficient_stock(): if "shuup.simple_supplier" not in settings.INSTALLED_APPS: pytest.skip("Need shuup.simple_supplier in INSTALLED_APPS") from shuup_tests.simple_supplier.utils import get_simple_supplier shop = get_default_shop() supplier = get_simple_supplier() order = _get_order(shop, supplier, stocked=True) product_line = order.lines.products().first() product = product_line.product assert product_line.quantity == 15 supplier.adjust_stock(product.pk, delta=10) stock_status = supplier.get_stock_status(product.pk) assert stock_status.physical_count == 10 order.create_shipment({product: 5}, supplier=supplier) assert order.shipping_status == ShippingStatus.PARTIALLY_SHIPPED assert order.shipments.all().count() == 1 with pytest.raises(Problem): order.create_shipment({product: 10}, supplier=supplier) # Should be fine after adding more stock supplier.adjust_stock(product.pk, delta=5) order.create_shipment({product: 10}, supplier=supplier) def _get_order(shop, supplier, stocked=False): order = create_empty_order(shop=shop) order.full_clean() order.save() for product_data in _get_product_data(stocked): quantity = product_data.pop("quantity") product = create_product( sku=product_data.pop("sku"), shop=shop, supplier=supplier, default_price=3.33, **product_data) add_product_to_order(order, supplier, product, quantity=quantity, taxless_base_unit_price=1) order.cache_prices() order.check_all_verified() order.save() return order def _get_product_data(stocked=False): return [ { "sku": "sku1234", "net_weight": decimal.Decimal("1"), "gross_weight": decimal.Decimal("43.34257"), "quantity": decimal.Decimal("15"), "stock_behavior": StockBehavior.STOCKED if stocked else StockBehavior.UNSTOCKED } ]
hrayr-artunyan/shuup
shuup_tests/core/test_shipments.py
Python
agpl-3.0
6,394
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Silviu Checherita using IMS Development Environment (version 1.80 build 5567.19951) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. package ims.scheduling.domain.impl; import java.util.ArrayList; import java.util.List; import ims.domain.DomainFactory; import ims.domain.lookups.LookupInstance; import ims.scheduling.domain.base.impl.BaseReasonTextDialogImpl; import ims.scheduling.vo.lookups.CancelAppointmentReason; import ims.scheduling.vo.lookups.CancelAppointmentReasonCollection; import ims.scheduling.vo.lookups.Status_Reason; public class ReasonTextDialogImpl extends BaseReasonTextDialogImpl { private static final long serialVersionUID = 1L; //WDEV-21736 public CancelAppointmentReasonCollection listReasons() { DomainFactory factory = getDomainFactory(); ArrayList markers = new ArrayList(); ArrayList values = new ArrayList(); String hql = "SELECT r FROM CancellationTypeReason AS t LEFT JOIN t.cancellationReason as r WHERE t.cancellationType.id = :cancellationType AND r.active = 1"; markers.add("cancellationType"); values.add(Status_Reason.HOSPITALCANCELLED.getID()); List results = factory.find(hql.toString(), markers,values); if (results == null) return null; CancelAppointmentReasonCollection col = new CancelAppointmentReasonCollection(); for (int i=0; i<results.size(); i++) { CancelAppointmentReason reason = new CancelAppointmentReason(((LookupInstance) results.get(i)).getId(), ((LookupInstance) results.get(i)).getText(), ((LookupInstance) results.get(i)).isActive()); col.add(reason); } return col; } //WDEV-21736 ends here }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/domain/impl/ReasonTextDialogImpl.java
Java
agpl-3.0
3,583
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.oncology.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class GradeofDifferentation extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public GradeofDifferentation() { super(); } public GradeofDifferentation(int id) { super(id, "", true); } public GradeofDifferentation(int id, String text, boolean active) { super(id, text, active, null, null, null); } public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image) { super(id, text, active, parent, image); } public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color) { super(id, text, active, parent, image, color); } public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static GradeofDifferentation buildLookup(ims.vo.LookupInstanceBean bean) { return new GradeofDifferentation(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (GradeofDifferentation)super.getParentInstance(); } public GradeofDifferentation getParent() { return (GradeofDifferentation)super.getParentInstance(); } public void setParent(GradeofDifferentation parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); GradeofDifferentation[] typedChildren = new GradeofDifferentation[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (GradeofDifferentation)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof GradeofDifferentation) { super.addChild((GradeofDifferentation)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof GradeofDifferentation) { super.removeChild((GradeofDifferentation)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { GradeofDifferentationCollection result = new GradeofDifferentationCollection(); return result; } public static GradeofDifferentation[] getNegativeInstances() { return new GradeofDifferentation[] {}; } public static String[] getNegativeInstanceNames() { return new String[] {}; } public static GradeofDifferentation getNegativeInstance(String name) { if(name == null) return null; // No negative instances found return null; } public static GradeofDifferentation getNegativeInstance(Integer id) { if(id == null) return null; // No negative instances found return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1251032; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/lookups/GradeofDifferentation.java
Java
agpl-3.0
5,476
""" Test cases to cover Accounts-related behaviors of the User API application """ import datetime import hashlib import json from copy import deepcopy from unittest import mock import ddt import pytz from django.conf import settings from django.test.testcases import TransactionTestCase from django.test.utils import override_settings from django.urls import reverse from edx_name_affirmation.api import create_verified_name from edx_name_affirmation.statuses import VerifiedNameStatus from rest_framework import status from rest_framework.test import APIClient, APITestCase from common.djangoapps.student.models import PendingEmailChange, UserProfile from common.djangoapps.student.tests.factories import TEST_PASSWORD, RegistrationFactory, UserFactory from openedx.core.djangoapps.oauth_dispatch.jwt import create_jwt_for_user from openedx.core.djangoapps.user_api.accounts import ACCOUNT_VISIBILITY_PREF_KEY from openedx.core.djangoapps.user_api.models import UserPreference from openedx.core.djangoapps.user_api.preferences.api import set_user_preference from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms from .. import ALL_USERS_VISIBILITY, CUSTOM_VISIBILITY, PRIVATE_VISIBILITY TEST_PROFILE_IMAGE_UPLOADED_AT = datetime.datetime(2002, 1, 9, 15, 43, 1, tzinfo=pytz.UTC) # this is used in one test to check the behavior of profile image url # generation with a relative url in the config. TEST_PROFILE_IMAGE_BACKEND = deepcopy(settings.PROFILE_IMAGE_BACKEND) TEST_PROFILE_IMAGE_BACKEND['options']['base_url'] = '/profile-images/' TEST_BIO_VALUE = "Tired mother of twins" TEST_LANGUAGE_PROFICIENCY_CODE = "hi" class UserAPITestCase(APITestCase): """ The base class for all tests of the User API """ VERIFIED_NAME = "Verified User" def setUp(self): super().setUp() self.anonymous_client = APIClient() self.different_user = UserFactory.create(password=TEST_PASSWORD) self.different_client = APIClient() self.staff_user = UserFactory(is_staff=True, password=TEST_PASSWORD) self.staff_client = APIClient() self.user = UserFactory.create(password=TEST_PASSWORD) # will be assigned to self.client by default def login_client(self, api_client, user): """Helper method for getting the client and user and logging in. Returns client. """ client = getattr(self, api_client) user = getattr(self, user) client.login(username=user.username, password=TEST_PASSWORD) return client def send_post(self, client, json_data, content_type='application/json', expected_status=201): """ Helper method for sending a post to the server, defaulting to application/json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.post(self.url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response def send_patch(self, client, json_data, content_type="application/merge-patch+json", expected_status=200): """ Helper method for sending a patch to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.patch(self.url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response def post_search_api(self, client, json_data, content_type='application/json', expected_status=200): """ Helper method for sending a post to the server, defaulting to application/merge-patch+json content_type. Verifies the expected status and returns the response. """ # pylint: disable=no-member response = client.post(self.search_api_url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response def send_get(self, client, query_parameters=None, expected_status=200): """ Helper method for sending a GET to the server. Verifies the expected status and returns the response. """ url = self.url + '?' + query_parameters if query_parameters else self.url # pylint: disable=no-member response = client.get(url) assert expected_status == response.status_code return response # pylint: disable=no-member def send_put(self, client, json_data, content_type="application/json", expected_status=204): """ Helper method for sending a PUT to the server. Verifies the expected status and returns the response. """ response = client.put(self.url, data=json.dumps(json_data), content_type=content_type) assert expected_status == response.status_code return response # pylint: disable=no-member def send_delete(self, client, expected_status=204): """ Helper method for sending a DELETE to the server. Verifies the expected status and returns the response. """ response = client.delete(self.url) assert expected_status == response.status_code return response def create_mock_profile(self, user): """ Helper method that creates a mock profile for the specified user :return: """ legacy_profile = UserProfile.objects.get(id=user.id) legacy_profile.country = "US" legacy_profile.state = "MA" legacy_profile.level_of_education = "m" legacy_profile.year_of_birth = 2000 legacy_profile.goals = "world peace" legacy_profile.mailing_address = "Park Ave" legacy_profile.gender = "f" legacy_profile.bio = TEST_BIO_VALUE legacy_profile.profile_image_uploaded_at = TEST_PROFILE_IMAGE_UPLOADED_AT legacy_profile.language_proficiencies.create(code=TEST_LANGUAGE_PROFICIENCY_CODE) legacy_profile.phone_number = "+18005555555" legacy_profile.save() def create_mock_verified_name(self, user): """ Helper method to create an approved VerifiedName entry in name affirmation. """ legacy_profile = UserProfile.objects.get(id=user.id) create_verified_name(user, self.VERIFIED_NAME, legacy_profile.name, status=VerifiedNameStatus.APPROVED) def create_user_registration(self, user): """ Helper method that creates a registration object for the specified user """ RegistrationFactory(user=user) def _verify_profile_image_data(self, data, has_profile_image): """ Verify the profile image data in a GET response for self.user corresponds to whether the user has or hasn't set a profile image. """ template = '{root}/{filename}_{{size}}.{extension}' if has_profile_image: url_root = 'http://example-storage.com/profile-images' filename = hashlib.md5(('secret' + self.user.username).encode('utf-8')).hexdigest() file_extension = 'jpg' template += '?v={}'.format(TEST_PROFILE_IMAGE_UPLOADED_AT.strftime("%s")) else: url_root = 'http://testserver/static' filename = 'default' file_extension = 'png' template = template.format(root=url_root, filename=filename, extension=file_extension) assert data['profile_image'] == {'has_image': has_profile_image, 'image_url_full': template.format(size=50), 'image_url_small': template.format(size=10)} @ddt.ddt @skip_unless_lms class TestOwnUsernameAPI(CacheIsolationTestCase, UserAPITestCase): """ Unit tests for the Accounts API. """ ENABLED_CACHES = ['default'] def setUp(self): super().setUp() self.url = reverse("own_username_api") def _verify_get_own_username(self, queries, expected_status=200): """ Internal helper to perform the actual assertion """ with self.assertNumQueries(queries): response = self.send_get(self.client, expected_status=expected_status) if expected_status == 200: data = response.data assert 1 == len(data) assert self.user.username == data['username'] def test_get_username(self): """ Test that a client (logged in) can get her own username. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self._verify_get_own_username(17) def test_get_username_inactive(self): """ Test that a logged-in client can get their username, even if inactive. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.user.is_active = False self.user.save() self._verify_get_own_username(17) def test_get_username_not_logged_in(self): """ Test that a client (not logged in) gets a 401 when trying to retrieve their username. """ # verify that the endpoint is inaccessible when not logged in self._verify_get_own_username(13, expected_status=401) @ddt.ddt @skip_unless_lms @mock.patch('openedx.core.djangoapps.user_api.accounts.image_helpers._PROFILE_IMAGE_SIZES', [50, 10]) @mock.patch.dict( 'django.conf.settings.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'small': 10}, clear=True ) class TestAccountsAPI(CacheIsolationTestCase, UserAPITestCase): """ Unit tests for the Accounts API. """ ENABLED_CACHES = ['default'] TOTAL_QUERY_COUNT = 27 FULL_RESPONSE_FIELD_COUNT = 30 def setUp(self): super().setUp() self.url = reverse("accounts_api", kwargs={'username': self.user.username}) self.search_api_url = reverse("accounts_search_emails_api") def _set_user_age_to_10_years(self, user): """ Sets the given user's age to 10. Returns the calculated year of birth. """ legacy_profile = UserProfile.objects.get(id=user.id) current_year = datetime.datetime.now().year year_of_birth = current_year - 10 legacy_profile.year_of_birth = year_of_birth legacy_profile.save() return year_of_birth def _verify_full_shareable_account_response(self, response, account_privacy=None, badges_enabled=False): """ Verify that the shareable fields from the account are returned """ data = response.data assert 12 == len(data) # public fields (3) assert account_privacy == data['account_privacy'] self._verify_profile_image_data(data, True) assert self.user.username == data['username'] # additional shareable fields (8) assert TEST_BIO_VALUE == data['bio'] assert 'US' == data['country'] assert data['date_joined'] is not None assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies'] assert 'm' == data['level_of_education'] assert data['social_links'] is not None assert data['time_zone'] is None assert badges_enabled == data['accomplishments_shared'] def _verify_private_account_response(self, response, requires_parental_consent=False): """ Verify that only the public fields are returned if a user does not want to share account fields """ data = response.data assert 3 == len(data) assert PRIVATE_VISIBILITY == data['account_privacy'] self._verify_profile_image_data(data, not requires_parental_consent) assert self.user.username == data['username'] def _verify_full_account_response(self, response, requires_parental_consent=False, year_of_birth=2000): """ Verify that all account fields are returned (even those that are not shareable). """ data = response.data assert self.FULL_RESPONSE_FIELD_COUNT == len(data) # public fields (3) expected_account_privacy = ( PRIVATE_VISIBILITY if requires_parental_consent else UserPreference.get_value(self.user, 'account_privacy') ) assert expected_account_privacy == data['account_privacy'] self._verify_profile_image_data(data, not requires_parental_consent) assert self.user.username == data['username'] # additional shareable fields (8) assert TEST_BIO_VALUE == data['bio'] assert 'US' == data['country'] assert data['date_joined'] is not None assert data['last_login'] is not None assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies'] assert 'm' == data['level_of_education'] assert data['social_links'] is not None assert UserPreference.get_value(self.user, 'time_zone') == data['time_zone'] assert data['accomplishments_shared'] is not None assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] # additional admin fields (13) assert self.user.email == data['email'] assert self.user.id == data['id'] assert self.VERIFIED_NAME == data['verified_name'] assert data['extended_profile'] is not None assert 'MA' == data['state'] assert 'f' == data['gender'] assert 'world peace' == data['goals'] assert data['is_active'] assert 'Park Ave' == data['mailing_address'] assert requires_parental_consent == data['requires_parental_consent'] assert data['secondary_email'] is None assert data['secondary_email_enabled'] is None assert year_of_birth == data['year_of_birth'] def test_anonymous_access(self): """ Test that an anonymous client (not logged in) cannot call GET or PATCH. """ self.send_get(self.anonymous_client, expected_status=401) self.send_patch(self.anonymous_client, {}, expected_status=401) def test_unsupported_methods(self): """ Test that DELETE, POST, and PUT are not supported. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) assert 405 == self.client.put(self.url).status_code assert 405 == self.client.post(self.url).status_code assert 405 == self.client.delete(self.url).status_code @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_get_account_unknown_user(self, api_client, user): """ Test that requesting a user who does not exist returns a 404. """ client = self.login_client(api_client, user) response = client.get(reverse("accounts_api", kwargs={'username': "does_not_exist"})) assert 404 == response.status_code @ddt.data( ("client", "user"), ) @ddt.unpack def test_regsitration_activation_key(self, api_client, user): """ Test that registration activation key has a value. UserFactory does not auto-generate registration object for the test users. It is created only for users that signup via email/API. Therefore, activation key has to be tested manually. """ self.create_user_registration(self.user) client = self.login_client(api_client, user) response = self.send_get(client) assert response.data["activation_key"] is not None def test_successful_get_account_by_email(self): """ Test that request using email by a staff user successfully retrieves Account Info. """ api_client = "staff_client" user = "staff_user" client = self.login_client(api_client, user) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = self.send_get(client, query_parameters=f'email={self.user.email}') self._verify_full_account_response(response) def test_unsuccessful_get_account_by_email(self): """ Test that request using email by a normal user fails to retrieve Account Info. """ api_client = "client" user = "user" client = self.login_client(api_client, user) self.create_mock_profile(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = self.send_get( client, query_parameters=f'email={self.user.email}', expected_status=status.HTTP_403_FORBIDDEN ) assert response.data.get('detail') == 'You do not have permission to perform this action.' def test_successful_get_account_by_user_id(self): """ Test that request using lms user id by a staff user successfully retrieves Account Info. """ api_client = "staff_client" user = "staff_user" url = reverse("accounts_detail_api") client = self.login_client(api_client, user) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = client.get(url + f'?lms_user_id={self.user.id}') assert response.status_code == status.HTTP_200_OK response.data = response.data[0] self._verify_full_account_response(response) def test_unsuccessful_get_account_by_user_id(self): """ Test that requesting using lms user id by a normal user fails to retrieve Account Info. """ api_client = "client" user = "user" url = reverse("accounts_detail_api") client = self.login_client(api_client, user) self.create_mock_profile(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = client.get(url + f'?lms_user_id={self.user.id}') assert response.status_code == status.HTTP_403_FORBIDDEN assert response.data.get('detail') == 'You do not have permission to perform this action.' @ddt.data('abc', '2f', '1.0', "2/8") def test_get_account_by_user_id_non_integer(self, non_integer_id): """ Test that request using a non-integer lms user id by a staff user fails to retrieve Account Info. """ api_client = "staff_client" user = "staff_user" url = reverse("accounts_detail_api") client = self.login_client(api_client, user) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, PRIVATE_VISIBILITY) response = client.get(url + f'?lms_user_id={non_integer_id}') assert response.status_code == status.HTTP_400_BAD_REQUEST def test_search_emails(self): client = self.login_client('staff_client', 'staff_user') json_data = {'emails': [self.user.email]} response = self.post_search_api(client, json_data=json_data) assert response.data == [{'email': self.user.email, 'id': self.user.id, 'username': self.user.username}] def test_search_emails_with_non_staff_user(self): client = self.login_client('client', 'user') json_data = {'emails': [self.user.email]} response = self.post_search_api(client, json_data=json_data, expected_status=404) assert response.data == { 'developer_message': "not_found", 'user_message': "Not Found" } def test_search_emails_with_non_existing_email(self): client = self.login_client('staff_client', 'staff_user') json_data = {"emails": ['non_existant_email@example.com']} response = self.post_search_api(client, json_data=json_data) assert response.data == [] def test_search_emails_with_invalid_param(self): client = self.login_client('staff_client', 'staff_user') json_data = {'invalid_key': [self.user.email]} response = self.post_search_api(client, json_data=json_data, expected_status=400) assert response.data == { 'developer_message': "'emails' field is required", 'user_message': "'emails' field is required" } # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @mock.patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "all_users"}) def test_get_account_different_user_visible(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "all_users". """ self.different_client.login(username=self.different_user.username, password=TEST_PASSWORD) self.create_mock_profile(self.user) with self.assertNumQueries(self.TOTAL_QUERY_COUNT): response = self.send_get(self.different_client) self._verify_full_shareable_account_response(response, account_privacy=ALL_USERS_VISIBILITY) # Note: using getattr so that the patching works even if there is no configuration. # This is needed when testing CMS as the patching is still executed even though the # suite is skipped. @mock.patch.dict(getattr(settings, "ACCOUNT_VISIBILITY_CONFIGURATION", {}), {"default_visibility": "private"}) def test_get_account_different_user_private(self): """ Test that a client (logged in) can only get the shareable fields for a different user. This is the case when default_visibility is set to "private". """ self.different_client.login(username=self.different_user.username, password=TEST_PASSWORD) self.create_mock_profile(self.user) with self.assertNumQueries(self.TOTAL_QUERY_COUNT): response = self.send_get(self.different_client) self._verify_private_account_response(response) @mock.patch.dict(settings.FEATURES, {'ENABLE_OPENBADGES': True}) @ddt.data( ("client", "user", PRIVATE_VISIBILITY), ("different_client", "different_user", PRIVATE_VISIBILITY), ("staff_client", "staff_user", PRIVATE_VISIBILITY), ("client", "user", ALL_USERS_VISIBILITY), ("different_client", "different_user", ALL_USERS_VISIBILITY), ("staff_client", "staff_user", ALL_USERS_VISIBILITY), ) @ddt.unpack def test_get_account_private_visibility(self, api_client, requesting_username, preference_visibility): """ Test the return from GET based on user visibility setting. """ def verify_fields_visible_to_all_users(response): """ Confirms that private fields are private, and public/shareable fields are public/shareable """ if preference_visibility == PRIVATE_VISIBILITY: self._verify_private_account_response(response) else: self._verify_full_shareable_account_response(response, ALL_USERS_VISIBILITY, badges_enabled=True) client = self.login_client(api_client, requesting_username) # Update user account visibility setting. set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, preference_visibility) self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) response = self.send_get(client) if requesting_username == "different_user": verify_fields_visible_to_all_users(response) else: self._verify_full_account_response(response) # Verify how the view parameter changes the fields that are returned. response = self.send_get(client, query_parameters='view=shared') verify_fields_visible_to_all_users(response) response = self.send_get(client, query_parameters=f'view=shared&username={self.user.username}') verify_fields_visible_to_all_users(response) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ("different_client", "different_user"), ) @ddt.unpack def test_custom_visibility_over_age(self, api_client, requesting_username): self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) # set user's custom visibility preferences set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, CUSTOM_VISIBILITY) shared_fields = ("bio", "language_proficiencies", "name") for field_name in shared_fields: set_user_preference(self.user, f"visibility.{field_name}", ALL_USERS_VISIBILITY) # make API request client = self.login_client(api_client, requesting_username) response = self.send_get(client) # verify response if requesting_username == "different_user": data = response.data assert 6 == len(data) # public fields assert self.user.username == data['username'] assert UserPreference.get_value(self.user, 'account_privacy') == data['account_privacy'] self._verify_profile_image_data(data, has_profile_image=True) # custom shared fields assert TEST_BIO_VALUE == data['bio'] assert [{'code': TEST_LANGUAGE_PROFICIENCY_CODE}] == data['language_proficiencies'] assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] else: self._verify_full_account_response(response) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ("different_client", "different_user"), ) @ddt.unpack def test_custom_visibility_under_age(self, api_client, requesting_username): self.create_mock_profile(self.user) self.create_mock_verified_name(self.user) year_of_birth = self._set_user_age_to_10_years(self.user) # set user's custom visibility preferences set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, CUSTOM_VISIBILITY) shared_fields = ("bio", "language_proficiencies") for field_name in shared_fields: set_user_preference(self.user, f"visibility.{field_name}", ALL_USERS_VISIBILITY) # make API request client = self.login_client(api_client, requesting_username) response = self.send_get(client) # verify response if requesting_username == "different_user": self._verify_private_account_response(response, requires_parental_consent=True) else: self._verify_full_account_response( response, requires_parental_consent=True, year_of_birth=year_of_birth, ) def test_get_account_default(self): """ Test that a client (logged in) can get her own account information (using default legacy profile information, as created by the test UserFactory). """ def verify_get_own_information(queries): """ Internal helper to perform the actual assertions """ with self.assertNumQueries(queries): response = self.send_get(self.client) data = response.data assert self.FULL_RESPONSE_FIELD_COUNT == len(data) assert self.user.username == data['username'] assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] for empty_field in ("year_of_birth", "level_of_education", "mailing_address", "bio"): assert data[empty_field] is None assert data['country'] is None assert data['state'] is None assert 'm' == data['gender'] assert 'Learn a lot' == data['goals'] assert self.user.email == data['email'] assert self.user.id == data['id'] assert data['date_joined'] is not None assert data['last_login'] is not None assert self.user.is_active == data['is_active'] self._verify_profile_image_data(data, False) assert data['requires_parental_consent'] assert [] == data['language_proficiencies'] assert PRIVATE_VISIBILITY == data['account_privacy'] assert data['time_zone'] is None # Badges aren't on by default, so should not be present. assert data['accomplishments_shared'] is False self.client.login(username=self.user.username, password=TEST_PASSWORD) verify_get_own_information(25) # Now make sure that the user can get the same information, even if not active self.user.is_active = False self.user.save() verify_get_own_information(17) def test_get_account_empty_string(self): """ Test the conversion of empty strings to None for certain fields. """ legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.country = "" legacy_profile.state = "" legacy_profile.level_of_education = "" legacy_profile.gender = "" legacy_profile.bio = "" legacy_profile.save() self.client.login(username=self.user.username, password=TEST_PASSWORD) with self.assertNumQueries(25): response = self.send_get(self.client) for empty_field in ("level_of_education", "gender", "country", "state", "bio",): assert response.data[empty_field] is None @ddt.data( ("different_client", "different_user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_disallowed_user(self, api_client, user): """ Test that a client cannot call PATCH on a different client's user account (even with is_staff access). """ client = self.login_client(api_client, user) self.send_patch(client, {}, expected_status=403) @ddt.data( ("client", "user"), ("staff_client", "staff_user"), ) @ddt.unpack def test_patch_account_unknown_user(self, api_client, user): """ Test that trying to update a user who does not exist returns a 403. """ client = self.login_client(api_client, user) response = client.patch( reverse("accounts_api", kwargs={'username': "does_not_exist"}), data=json.dumps({}), content_type="application/merge-patch+json" ) assert 403 == response.status_code @ddt.data( ("gender", "f", "not a gender", '"not a gender" is not a valid choice.'), ("level_of_education", "none", "ȻħȺɍłɇs", '"ȻħȺɍłɇs" is not a valid choice.'), ("country", "GB", "XY", '"XY" is not a valid choice.'), ("state", "MA", "PY", '"PY" is not a valid choice.'), ("year_of_birth", 2009, "not_an_int", "A valid integer is required."), ("name", "bob", "z" * 256, "Ensure this field has no more than 255 characters."), ("name", "ȻħȺɍłɇs", " ", "The name field must be at least 1 character long."), ("goals", "Smell the roses"), ("mailing_address", "Sesame Street"), # Note that we store the raw data, so it is up to client to escape the HTML. ( "bio", "<html>Lacrosse-playing superhero 壓是進界推日不復女</html>", "z" * 301, "The about me field must be at most 300 characters long." ), ("account_privacy", ALL_USERS_VISIBILITY), ("account_privacy", PRIVATE_VISIBILITY), # Note that email is tested below, as it is not immediately updated. # Note that language_proficiencies is tested below as there are multiple error and success conditions. ) @ddt.unpack def test_patch_account(self, field, value, fails_validation_value=None, developer_validation_message=None): """ Test the behavior of patch, when using the correct content_type. """ client = self.login_client("client", "user") if field == 'account_privacy': # Ensure the user has birth year set, and is over 13, so # account_privacy behaves normally legacy_profile = UserProfile.objects.get(id=self.user.id) legacy_profile.year_of_birth = 2000 legacy_profile.save() response = self.send_patch(client, {field: value}) assert value == response.data[field] if fails_validation_value: error_response = self.send_patch(client, {field: fails_validation_value}, expected_status=400) expected_user_message = 'This value is invalid.' if field == 'bio': expected_user_message = "The about me field must be at most 300 characters long." assert expected_user_message == error_response.data['field_errors'][field]['user_message'] assert "Value '{value}' is not valid for field '{field}': {messages}".format( value=fails_validation_value, field=field, messages=[developer_validation_message] ) == error_response.data['field_errors'][field]['developer_message'] elif field != "account_privacy": # If there are no values that would fail validation, then empty string should be supported; # except for account_privacy, which cannot be an empty string. response = self.send_patch(client, {field: ""}) assert '' == response.data[field] def test_patch_inactive_user(self): """ Verify that a user can patch her own account, even if inactive. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.user.is_active = False self.user.save() response = self.send_patch(self.client, {"goals": "to not activate account"}) assert 'to not activate account' == response.data['goals'] @ddt.unpack def test_patch_account_noneditable(self): """ Tests the behavior of patch when a read-only field is attempted to be edited. """ client = self.login_client("client", "user") def verify_error_response(field_name, data): """ Internal helper to check the error messages returned """ assert 'This field is not editable via this API' == data['field_errors'][field_name]['developer_message'] assert "The '{}' field cannot be edited.".format( field_name ) == data['field_errors'][field_name]['user_message'] for field_name in ["username", "date_joined", "is_active", "profile_image", "requires_parental_consent"]: response = self.send_patch(client, {field_name: "will_error", "gender": "o"}, expected_status=400) verify_error_response(field_name, response.data) # Make sure that gender did not change. response = self.send_get(client) assert 'm' == response.data['gender'] # Test error message with multiple read-only items response = self.send_patch(client, {"username": "will_error", "date_joined": "xx"}, expected_status=400) assert 2 == len(response.data['field_errors']) verify_error_response("username", response.data) verify_error_response("date_joined", response.data) def test_patch_bad_content_type(self): """ Test the behavior of patch when an incorrect content_type is specified. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_patch(self.client, {}, content_type="application/json", expected_status=415) self.send_patch(self.client, {}, content_type="application/xml", expected_status=415) def test_patch_account_empty_string(self): """ Tests the behavior of patch when attempting to set fields with a select list of options to the empty string. Also verifies the behaviour when setting to None. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) for field_name in ["gender", "level_of_education", "country", "state"]: response = self.send_patch(self.client, {field_name: ""}) # Although throwing a 400 might be reasonable, the default DRF behavior with ModelSerializer # is to convert to None, which also seems acceptable (and is difficult to override). assert response.data[field_name] is None # Verify that the behavior is the same for sending None. response = self.send_patch(self.client, {field_name: ""}) assert response.data[field_name] is None def test_patch_name_metadata(self): """ Test the metadata stored when changing the name field. """ def get_name_change_info(expected_entries): """ Internal method to encapsulate the retrieval of old names used """ legacy_profile = UserProfile.objects.get(id=self.user.id) name_change_info = legacy_profile.get_meta()["old_names"] assert expected_entries == len(name_change_info) return name_change_info def verify_change_info(change_info, old_name, requester, new_name): """ Internal method to validate name changes """ assert 3 == len(change_info) assert old_name == change_info[0] assert f'Name change requested through account API by {requester}' == change_info[1] assert change_info[2] is not None # Verify the new name was also stored. get_response = self.send_get(self.client) assert new_name == get_response.data['name'] self.client.login(username=self.user.username, password=TEST_PASSWORD) legacy_profile = UserProfile.objects.get(id=self.user.id) assert {} == legacy_profile.get_meta() old_name = legacy_profile.name # First change the name as the user and verify meta information. self.send_patch(self.client, {"name": "Mickey Mouse"}) name_change_info = get_name_change_info(1) verify_change_info(name_change_info[0], old_name, self.user.username, "Mickey Mouse") # Now change the name again and verify meta information. self.send_patch(self.client, {"name": "Donald Duck"}) name_change_info = get_name_change_info(2) verify_change_info(name_change_info[0], old_name, self.user.username, "Donald Duck", ) verify_change_info(name_change_info[1], "Mickey Mouse", self.user.username, "Donald Duck") @mock.patch.dict( 'django.conf.settings.PROFILE_IMAGE_SIZES_MAP', {'full': 50, 'medium': 30, 'small': 10}, clear=True ) def test_patch_email(self): """ Test that the user can request an email change through the accounts API. Full testing of the helper method used (do_email_change_request) exists in the package with the code. Here just do minimal smoke testing. """ client = self.login_client("client", "user") old_email = self.user.email new_email = "newemail@example.com" response = self.send_patch(client, {"email": new_email, "goals": "change my email"}) # Since request is multi-step, the email won't change on GET immediately (though goals will update). assert old_email == response.data['email'] assert 'change my email' == response.data['goals'] # Now call the method that will be invoked with the user clicks the activation key in the received email. # First we must get the activation key that was sent. pending_change = PendingEmailChange.objects.filter(user=self.user) assert 1 == len(pending_change) activation_key = pending_change[0].activation_key confirm_change_url = reverse( "confirm_email_change", kwargs={'key': activation_key} ) response = self.client.post(confirm_change_url) assert 200 == response.status_code get_response = self.send_get(client) assert new_email == get_response.data['email'] @ddt.data( ("not_an_email",), ("",), (None,), ) @ddt.unpack def test_patch_invalid_email(self, bad_email): """ Test a few error cases for email validation (full test coverage lives with do_email_change_request). """ client = self.login_client("client", "user") # Try changing to an invalid email to make sure error messages are appropriately returned. error_response = self.send_patch(client, {"email": bad_email}, expected_status=400) field_errors = error_response.data["field_errors"] assert "Error thrown from validate_new_email: 'Valid e-mail address required.'" == \ field_errors['email']['developer_message'] assert 'Valid e-mail address required.' == field_errors['email']['user_message'] @mock.patch('common.djangoapps.student.views.management.do_email_change_request') def test_patch_duplicate_email(self, do_email_change_request): """ Test that same success response will be sent to user even if the given email already used. """ existing_email = "same@example.com" UserFactory.create(email=existing_email) client = self.login_client("client", "user") # Try changing to an existing email to make sure no error messages returned. response = self.send_patch(client, {"email": existing_email}) assert 200 == response.status_code # Verify that no actual request made for email change assert not do_email_change_request.called def test_patch_language_proficiencies(self): """ Verify that patching the language_proficiencies field of the user profile completely overwrites the previous value. """ client = self.login_client("client", "user") # Patching language_proficiencies exercises the # `LanguageProficiencySerializer.get_identity` method, which compares # identifies language proficiencies based on their language code rather # than django model id. for proficiencies in ([{"code": "en"}, {"code": "fr"}, {"code": "es"}], [{"code": "fr"}], [{"code": "aa"}], []): response = self.send_patch(client, {"language_proficiencies": proficiencies}) self.assertCountEqual(response.data["language_proficiencies"], proficiencies) @ddt.data( ( "not_a_list", {'non_field_errors': ['Expected a list of items but got type "unicode".']} ), ( ["not_a_JSON_object"], [{'non_field_errors': ['Invalid data. Expected a dictionary, but got unicode.']}] ), ( [{}], [{'code': ['This field is required.']}] ), ( [{"code": "invalid_language_code"}], [{'code': ['"invalid_language_code" is not a valid choice.']}] ), ( [{"code": "kw"}, {"code": "el"}, {"code": "kw"}], ['The language_proficiencies field must consist of unique languages.'] ), ) @ddt.unpack def test_patch_invalid_language_proficiencies(self, patch_value, expected_error_message): """ Verify we handle error cases when patching the language_proficiencies field. """ expected_error_message = str(expected_error_message).replace('unicode', 'str') client = self.login_client("client", "user") response = self.send_patch(client, {"language_proficiencies": patch_value}, expected_status=400) assert response.data['field_errors']['language_proficiencies']['developer_message'] == \ f"Value '{patch_value}' is not valid for field 'language_proficiencies': {expected_error_message}" @mock.patch('openedx.core.djangoapps.user_api.accounts.serializers.AccountUserSerializer.save') def test_patch_serializer_save_fails(self, serializer_save): """ Test that AccountUpdateErrors are passed through to the response. """ serializer_save.side_effect = [Exception("bummer"), None] self.client.login(username=self.user.username, password=TEST_PASSWORD) error_response = self.send_patch(self.client, {"goals": "save an account field"}, expected_status=400) assert "Error thrown when saving account updates: 'bummer'" == error_response.data['developer_message'] assert error_response.data['user_message'] is None @override_settings(PROFILE_IMAGE_BACKEND=TEST_PROFILE_IMAGE_BACKEND) def test_convert_relative_profile_url(self): """ Test that when TEST_PROFILE_IMAGE_BACKEND['base_url'] begins with a '/', the API generates the full URL to profile images based on the URL of the request. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) response = self.send_get(self.client) assert response.data['profile_image'] == \ {'has_image': False, 'image_url_full': 'http://testserver/static/default_50.png', 'image_url_small': 'http://testserver/static/default_10.png'} @ddt.data( ("client", "user", True), ("different_client", "different_user", False), ("staff_client", "staff_user", True), ) @ddt.unpack def test_parental_consent(self, api_client, requesting_username, has_full_access): """ Verifies that under thirteens never return a public profile. """ client = self.login_client(api_client, requesting_username) year_of_birth = self._set_user_age_to_10_years(self.user) set_user_preference(self.user, ACCOUNT_VISIBILITY_PREF_KEY, ALL_USERS_VISIBILITY) # Verify that the default view is still private (except for clients with full access) response = self.send_get(client) if has_full_access: data = response.data assert self.FULL_RESPONSE_FIELD_COUNT == len(data) assert self.user.username == data['username'] assert ((self.user.first_name + ' ') + self.user.last_name) == data['name'] assert self.user.email == data['email'] assert self.user.id == data['id'] assert year_of_birth == data['year_of_birth'] for empty_field in ("country", "level_of_education", "mailing_address", "bio", "state",): assert data[empty_field] is None assert 'm' == data['gender'] assert 'Learn a lot' == data['goals'] assert data['is_active'] assert data['date_joined'] is not None assert data['last_login'] is not None self._verify_profile_image_data(data, False) assert data['requires_parental_consent'] assert PRIVATE_VISIBILITY == data['account_privacy'] else: self._verify_private_account_response(response, requires_parental_consent=True) # Verify that the shared view is still private response = self.send_get(client, query_parameters='view=shared') self._verify_private_account_response(response, requires_parental_consent=True) @skip_unless_lms class TestAccountAPITransactions(TransactionTestCase): """ Tests the transactional behavior of the account API """ def setUp(self): super().setUp() self.client = APIClient() self.user = UserFactory.create(password=TEST_PASSWORD) self.url = reverse("accounts_api", kwargs={'username': self.user.username}) @mock.patch('common.djangoapps.student.views.do_email_change_request') def test_update_account_settings_rollback(self, mock_email_change): """ Verify that updating account settings is transactional when a failure happens. """ # Send a PATCH request with updates to both profile information and email. # Throw an error from the method that is used to process the email change request # (this is the last thing done in the api method). Verify that the profile did not change. mock_email_change.side_effect = [ValueError, "mock value error thrown"] self.client.login(username=self.user.username, password=TEST_PASSWORD) old_email = self.user.email json_data = {"email": "foo@bar.com", "gender": "o"} response = self.client.patch(self.url, data=json.dumps(json_data), content_type="application/merge-patch+json") assert 400 == response.status_code # Verify that GET returns the original preferences response = self.client.get(self.url) data = response.data assert old_email == data['email'] assert 'm' == data['gender'] @ddt.ddt class NameChangeViewTests(UserAPITestCase): """ NameChangeView tests """ def setUp(self): super().setUp() self.url = reverse('name_change') def test_request_succeeds(self): """ Test that a valid name change request succeeds. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post(self.client, {'name': 'New Name'}) def test_unauthenticated(self): """ Test that a name change request fails for an unauthenticated user. """ self.send_post(self.client, {'name': 'New Name'}, expected_status=401) def test_empty_request(self): """ Test that an empty request fails. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post(self.client, {}, expected_status=400) def test_blank_name(self): """ Test that a blank name string fails. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post(self.client, {'name': ''}, expected_status=400) @ddt.data('<html>invalid name</html>', 'https://invalid.com') def test_fails_validation(self, invalid_name): """ Test that an invalid name will return an error. """ self.client.login(username=self.user.username, password=TEST_PASSWORD) self.send_post( self.client, {'name': invalid_name}, expected_status=400 ) @ddt.ddt @mock.patch('django.conf.settings.USERNAME_REPLACEMENT_WORKER', 'test_replace_username_service_worker') class UsernameReplacementViewTests(APITestCase): """ Tests UsernameReplacementView """ SERVICE_USERNAME = 'test_replace_username_service_worker' def setUp(self): super().setUp() self.service_user = UserFactory(username=self.SERVICE_USERNAME) self.url = reverse("username_replacement") def build_jwt_headers(self, user): """ Helper function for creating headers for the JWT authentication. """ token = create_jwt_for_user(user) headers = {'HTTP_AUTHORIZATION': f'JWT {token}'} return headers def call_api(self, user, data): """ Helper function to call API with data """ data = json.dumps(data) headers = self.build_jwt_headers(user) return self.client.post(self.url, data, content_type='application/json', **headers) def test_auth(self): """ Verify the endpoint only works with the service worker """ data = { "username_mappings": [ {"test_username_1": "test_new_username_1"}, {"test_username_2": "test_new_username_2"} ] } # Test unauthenticated response = self.client.post(self.url) assert response.status_code == 401 # Test non-service worker random_user = UserFactory() response = self.call_api(random_user, data) assert response.status_code == 403 # Test service worker response = self.call_api(self.service_user, data) assert response.status_code == 200 @ddt.data( [{}, {}], {}, [{"test_key": "test_value", "test_key_2": "test_value_2"}] ) def test_bad_schema(self, mapping_data): """ Verify the endpoint rejects bad data schema """ data = { "username_mappings": mapping_data } response = self.call_api(self.service_user, data) assert response.status_code == 400 def test_existing_and_non_existing_users(self): """ Tests a mix of existing and non existing users """ random_users = [UserFactory() for _ in range(5)] fake_usernames = ["myname_" + str(x) for x in range(5)] existing_users = [{user.username: user.username + '_new'} for user in random_users] non_existing_users = [{username: username + '_new'} for username in fake_usernames] data = { "username_mappings": existing_users + non_existing_users } expected_response = { 'failed_replacements': [], 'successful_replacements': existing_users + non_existing_users } response = self.call_api(self.service_user, data) assert response.status_code == 200 assert response.data == expected_response
edx/edx-platform
openedx/core/djangoapps/user_api/accounts/tests/test_views.py
Python
agpl-3.0
53,614
div.rename-database-overlay { position: absolute; top: 0%; left: 0%; width: 100%; height: 100%; background-color: black; z-index:1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80); } div.rename-database-content { position: absolute; top: 25%; left: 25%; width: 50%; height: 50%; -webkit-border-radius: 10px; -webkit-box-shadow: 3px 3px 4px #000; -moz-border-radius: 10px; -moz-box-shadow: 3px 3px 4px #000; padding: 20px; background-color: white; z-index:1002; overflow: auto; text-align: center; background-color: #EFF5FB; } span.rename-database-welcome { font-size: 32px; font-weight: bold; color: #424242; } span.rename-database-name { font-size: 20px; color: #424242; } input.rename-database-input { font-size: 20px; text-align: center; width: 300px; color: #424242; } button.rename-database-button { -webkit-border-radius: 10px; -webkit-box-shadow: 3px 3px 4px #000; -moz-border-radius: 10px; -moz-box-shadow: 3px 3px 4px #000; font-size: 20px; background-color: #045FB4; color: white; width: 150px; } button.rename-database-button[disabled] { background-color: #ddd; }
timoc/scaliendb
webadmin/renameDatabase.css
CSS
agpl-3.0
1,138
<div data-role="header"> <h1>Prijave problema koje nisu poslate</h1> </div> <div data-role="content" role="main"> <div id="existing_report"> <% if ( title ) { %> <h3><%= title %></h3> <% } %> <div class="meta"> <p> <% if ( category && category != '-- Izaberite kategoriju --' ) { %> Saved in the <%= category %> category <% } %> </p> <p><% print( moment( created ).fromNow() ) %></p> </div> <% if ( file ) { %> <div class="photo" style="background-image: url(<%= file %>)"></div> <% } %> <% if ( details ) { %> <div class="details"><div><%= details %></div></div> <% } %> </div> <div class="right"> <input id="use_report" type="button" value="Završite prijavu sada" data-role="button" data-theme="a" /> <input id="save_report" type="button" value="Sačuvaj za kasnije" data-role="button" data-theme="a" /> <input id="discard" type="button" value="Odbaci" data-role="button" data-theme="a" /> </div> </div>
altinukshini/fixmystreet-mobile
www/templates/sr/existing.html
HTML
agpl-3.0
1,085
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapid_i.deployment.update.client; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.rapid_i.deployment.update.client.listmodels.AbstractPackageListModel; import com.rapidminer.deployment.client.wsimport.PackageDescriptor; import com.rapidminer.deployment.client.wsimport.UpdateService; import com.rapidminer.gui.RapidMinerGUI; import com.rapidminer.gui.tools.ExtendedJScrollPane; import com.rapidminer.gui.tools.ProgressThread; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.dialogs.ButtonDialog; import com.rapidminer.gui.tools.dialogs.ConfirmDialog; import com.rapidminer.io.process.XMLTools; import com.rapidminer.tools.FileSystemService; import com.rapidminer.tools.I18N; import com.rapidminer.tools.LogService; import com.rapidminer.tools.ParameterService; import com.rapidminer.tools.XMLException; /** * The Dialog is eventually shown at the start of RapidMiner, if the user purchased extensions online but haven't installed them yet. * * @author Dominik Halfkann */ public class PendingPurchasesInstallationDialog extends ButtonDialog { private static final long serialVersionUID = 1L; private final PackageDescriptorCache packageDescriptorCache = new PackageDescriptorCache(); private AbstractPackageListModel purchasedModel = new PurchasedNotInstalledModel(packageDescriptorCache); JCheckBox neverAskAgain = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.not_check_on_startup")); private final List<String> packages; private boolean isConfirmed; private LinkedList<PackageDescriptor> installablePackageList; private JButton remindNeverButton; private JButton remindLaterButton; private JButton okButton; private class PurchasedNotInstalledModel extends AbstractPackageListModel { private static final long serialVersionUID = 1L; public PurchasedNotInstalledModel(PackageDescriptorCache cache) { super(cache, "gui.dialog.update.tab.no_packages"); } @Override public List<String> handleFetchPackageNames() { return packages; } } public PendingPurchasesInstallationDialog(List<String> packages) { super("purchased_not_installed"); this.packages = packages; remindNeverButton = remindNeverButton(); remindLaterButton = remindLaterButton(); okButton = makeOkButton("install_purchased"); layoutDefault(makeContentPanel(), NORMAL, okButton, remindNeverButton, remindLaterButton); this.setPreferredSize(new Dimension(404, 430)); this.setMaximumSize(new Dimension(404, 430)); this.setMinimumSize(new Dimension(404, 300)); this.setSize(new Dimension(404, 430)); } private JPanel makeContentPanel() { BorderLayout layout = new BorderLayout(12, 12); JPanel panel = new JPanel(layout); panel.setBorder(new EmptyBorder(0, 12, 8, 12)); panel.add(createExtensionListScrollPane(purchasedModel), BorderLayout.CENTER); purchasedModel.update(); JPanel southPanel = new JPanel(new BorderLayout(0, 7)); JLabel question = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.should_install")); southPanel.add(question, BorderLayout.CENTER); southPanel.add(neverAskAgain, BorderLayout.SOUTH); panel.add(southPanel, BorderLayout.SOUTH); return panel; } private JScrollPane createExtensionListScrollPane(AbstractPackageListModel model) { final JList updateList = new JList(model); updateList.setCellRenderer(new UpdateListCellRenderer(true)); JScrollPane extensionListScrollPane = new ExtendedJScrollPane(updateList); extensionListScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); return extensionListScrollPane; } private JButton remindLaterButton() { Action Action = new ResourceAction("ask_later") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { wasConfirmed = false; checkNeverAskAgain(); close(); } }; getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "CLOSE"); getRootPane().getActionMap().put("CLOSE", Action); JButton button = new JButton(Action); getRootPane().setDefaultButton(button); return button; } private JButton remindNeverButton() { Action Action = new ResourceAction("ask_never") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { wasConfirmed = false; checkNeverAskAgain(); neverRemindAgain(); close(); } }; JButton button = new JButton(Action); getRootPane().setDefaultButton(button); return button; } @Override protected void ok() { checkNeverAskAgain(); startUpdate(getPackageDescriptorList()); dispose(); } public List<PackageDescriptor> getPackageDescriptorList() { List<PackageDescriptor> packageList = new ArrayList<PackageDescriptor>(); for (int a = 0; a < purchasedModel.getSize(); a++) { Object listItem = purchasedModel.getElementAt(a); if (listItem instanceof PackageDescriptor) { packageList.add((PackageDescriptor) listItem); } } return packageList; } public void startUpdate(final List<PackageDescriptor> downloadList) { final UpdateService service; try { service = UpdateManager.getService(); } catch (Exception e) { SwingTools.showSimpleErrorMessage("failed_update_server", e, UpdateManager.getBaseUrl()); return; } new ProgressThread("resolving_dependencies", true) { @Override public void run() { try { getProgressListener().setTotal(100); remindLaterButton.setEnabled(false); remindNeverButton.setEnabled(false); final HashMap<PackageDescriptor, HashSet<PackageDescriptor>> dependency = UpdateDialog.resolveDependency(downloadList, packageDescriptorCache); getProgressListener().setCompleted(30); installablePackageList = UpdateDialog.getPackagesforInstallation(dependency); final HashMap<String, String> licenseNameToLicenseTextMap = UpdateDialog.collectLicenses(installablePackageList,getProgressListener(),100,30,100); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { isConfirmed = ConfirmLicensesDialog.confirm(dependency, licenseNameToLicenseTextMap); new ProgressThread("installing_updates", true) { @Override public void run() { try { if (isConfirmed) { getProgressListener().setTotal(100); getProgressListener().setCompleted(20); UpdateService service = UpdateManager.getService(); UpdateManager um = new UpdateManager(service); List<PackageDescriptor> installedPackages = um.performUpdates(installablePackageList, getProgressListener()); getProgressListener().setCompleted(40); if (installedPackages.size() > 0) { int confirmation = SwingTools.showConfirmDialog((installedPackages.size() == 1 ? "update.complete_restart" : "update.complete_restart1"), ConfirmDialog.YES_NO_OPTION, installedPackages.size()); if (confirmation == ConfirmDialog.YES_OPTION) { RapidMinerGUI.getMainFrame().exit(true); } else if (confirmation == ConfirmDialog.NO_OPTION) { if (installedPackages.size() == installablePackageList.size()) { dispose(); } } } getProgressListener().complete(); } } catch (Exception e) { SwingTools.showSimpleErrorMessage("error_installing_update", e, e.getMessage()); } finally { getProgressListener().complete(); } } }.start(); } }); remindLaterButton.setEnabled(true); remindNeverButton.setEnabled(true); getProgressListener().complete(); } catch (Exception e) { SwingTools.showSimpleErrorMessage("error_resolving_dependencies", e, e.getMessage()); } } }.start(); } private void checkNeverAskAgain() { if (neverAskAgain.isSelected()) { ParameterService.setParameterValue(RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_PURCHASED_NOT_INSTALLED_CHECK, "false"); ParameterService.saveParameters(); } } private void neverRemindAgain() { LogService.getRoot().log(Level.CONFIG, "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file"); Document doc; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.creating_xml_document_error", e), e); return; } Element root = doc.createElement(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME); doc.appendChild(root); for (String i : purchasedModel.fetchPackageNames()) { Element entryElem = doc.createElement("extension_name"); entryElem.setTextContent(i); root.appendChild(entryElem); } File file = FileSystemService.getUserConfigFile(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME); try { XMLTools.stream(doc, file, null); } catch (XMLException e) { LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file_error", e), e); } } }
rapidminer/rapidminer-5
src/com/rapid_i/deployment/update/client/PendingPurchasesInstallationDialog.java
Java
agpl-3.0
11,249
def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func
feroda/lessons-python4beginners
students/2016-09-04/simone-cosma/fibonacci.py
Python
agpl-3.0
1,035
package rpcclient import ( "context" "encoding/json" "net" "net/http" "net/http/httptest" "sync" "testing" "time" "github.com/gorilla/websocket" "github.com/stretchr/testify/require" "github.com/tendermint/tmlibs/log" types "github.com/tendermint/tendermint/rpc/lib/types" ) type myHandler struct { closeConnAfterRead bool mtx sync.RWMutex } var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { panic(err) } defer conn.Close() for { messageType, _, err := conn.ReadMessage() if err != nil { return } h.mtx.RLock() if h.closeConnAfterRead { conn.Close() } h.mtx.RUnlock() res := json.RawMessage(`{}`) emptyRespBytes, _ := json.Marshal(types.RPCResponse{Result: &res}) if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil { return } } } func TestWSClientReconnectsAfterReadFailure(t *testing.T) { var wg sync.WaitGroup // start server h := &myHandler{} s := httptest.NewServer(h) defer s.Close() c := startClient(t, s.Listener.Addr()) defer c.Stop() wg.Add(1) go callWgDoneOnResult(t, c, &wg) h.mtx.Lock() h.closeConnAfterRead = true h.mtx.Unlock() // results in WS read error, no send retry because write succeeded call(t, "a", c) // expect to reconnect almost immediately time.Sleep(10 * time.Millisecond) h.mtx.Lock() h.closeConnAfterRead = false h.mtx.Unlock() // should succeed call(t, "b", c) wg.Wait() } func TestWSClientReconnectsAfterWriteFailure(t *testing.T) { var wg sync.WaitGroup // start server h := &myHandler{} s := httptest.NewServer(h) c := startClient(t, s.Listener.Addr()) defer c.Stop() wg.Add(2) go callWgDoneOnResult(t, c, &wg) // hacky way to abort the connection before write c.conn.Close() // results in WS write error, the client should resend on reconnect call(t, "a", c) // expect to reconnect almost immediately time.Sleep(10 * time.Millisecond) // should succeed call(t, "b", c) wg.Wait() } func TestWSClientReconnectFailure(t *testing.T) { // start server h := &myHandler{} s := httptest.NewServer(h) c := startClient(t, s.Listener.Addr()) defer c.Stop() go func() { for { select { case <-c.ResponsesCh: case <-c.Quit: return } } }() // hacky way to abort the connection before write c.conn.Close() s.Close() // results in WS write error // provide timeout to avoid blocking ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() c.Call(ctx, "a", make(map[string]interface{})) // expect to reconnect almost immediately time.Sleep(10 * time.Millisecond) done := make(chan struct{}) go func() { // client should block on this call(t, "b", c) close(done) }() // test that client blocks on the second send select { case <-done: t.Fatal("client should block on calling 'b' during reconnect") case <-time.After(5 * time.Second): t.Log("All good") } } func TestNotBlockingOnStop(t *testing.T) { timeout := 2 * time.Second s := httptest.NewServer(&myHandler{}) c := startClient(t, s.Listener.Addr()) c.Call(context.Background(), "a", make(map[string]interface{})) // Let the readRoutine get around to blocking time.Sleep(time.Second) passCh := make(chan struct{}) go func() { // Unless we have a non-blocking write to ResponsesCh from readRoutine // this blocks forever ont the waitgroup c.Stop() passCh <- struct{}{} }() select { case <-passCh: // Pass case <-time.After(timeout): t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?", timeout.Seconds()) } } func startClient(t *testing.T, addr net.Addr) *WSClient { c := NewWSClient(addr.String(), "/websocket") _, err := c.Start() require.Nil(t, err) c.SetLogger(log.TestingLogger()) return c } func call(t *testing.T, method string, c *WSClient) { err := c.Call(context.Background(), method, make(map[string]interface{})) require.NoError(t, err) } func callWgDoneOnResult(t *testing.T, c *WSClient, wg *sync.WaitGroup) { for { select { case resp := <-c.ResponsesCh: if resp.Error != nil { t.Fatalf("unexpected error: %v", resp.Error) } if *resp.Result != nil { wg.Done() } case <-c.Quit: return } } }
adrianbrink/tendereum
vendor/github.com/tendermint/tendermint/rpc/lib/client/ws_client_test.go
GO
agpl-3.0
4,402
// Generated by CoffeeScript 1.10.0 var Bill, baseKonnector, filterExisting, linkBankOperation, ovhFetcher, saveDataAndFile; ovhFetcher = require('../lib/ovh_fetcher'); filterExisting = require('../lib/filter_existing'); saveDataAndFile = require('../lib/save_data_and_file'); linkBankOperation = require('../lib/link_bank_operation'); baseKonnector = require('../lib/base_konnector'); Bill = require('../models/bill'); module.exports = { createNew: function(ovhApi, name, slug) { var connector, fetchBills, fileOptions, logger, ovhFetcherInstance; fileOptions = { vendor: slug, dateFormat: 'YYYYMMDD' }; logger = require('printit')({ prefix: name, date: true }); ovhFetcherInstance = ovhFetcher["new"](ovhApi, slug, logger); fetchBills = function(requiredFields, entries, body, next) { return ovhFetcherInstance.fetchBills(requiredFields, entries, body, next); }; return connector = baseKonnector.createNew({ name: name, fields: { loginUrl: "link", token: "hidden", folderPath: "folder" }, models: [Bill], fetchOperations: [ fetchBills, filterExisting(logger, Bill), saveDataAndFile(logger, Bill, fileOptions, ['bill']), linkBankOperation({ log: logger, model: Bill, identifier: slug, dateDelta: 4, amountDelta: 0.1 }) ] }); } };
frankrousseau/konnectors
build/server/lib/base_ovh_konnector.js
JavaScript
agpl-3.0
1,438
class SubscribersController < ApplicationController def create @subscriber = Subscriber.new(params[:subscriber]) if @subscriber.save flash[:notice] = "Success! You have been sent a subscription email. Please click the confirmation link in that email to confirm your subscription."\ else flash[:error] = "We're having trouble with that email address. Either it's invalid or you have already signed up to watch this story." end redirect_to :back end def confirm @subscriber = Subscriber.find_by_invite_token(params[:id]) @subscriber.subscribe if @subscriber end def cancel @subscriber = Subscriber.find_by_invite_token(params[:id]) @subscriber.cancel if @subscriber end end
chandresh/spot-us
app/controllers/subscribers_controller.rb
Ruby
agpl-3.0
752
""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine)
emilydolson/forestcat
pyrobot/plugins/brains/BraitenbergVehicle2b.py
Python
agpl-3.0
789
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:25 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Florin Blindu */ public class EDPartialAdmissionForDischargeDetailOutcomeVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo copy(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectDest, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_EDPartialAdmission(valueObjectSrc.getID_EDPartialAdmission()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // DecisionToAdmitDateTime valueObjectDest.setDecisionToAdmitDateTime(valueObjectSrc.getDecisionToAdmitDateTime()); // Specialty valueObjectDest.setSpecialty(valueObjectSrc.getSpecialty()); // AllocatedStatus valueObjectDest.setAllocatedStatus(valueObjectSrc.getAllocatedStatus()); // AllocatedBedType valueObjectDest.setAllocatedBedType(valueObjectSrc.getAllocatedBedType()); // AuthoringInfo valueObjectDest.setAuthoringInfo(valueObjectSrc.getAuthoringInfo()); // AllocatedDateTime valueObjectDest.setAllocatedDateTime(valueObjectSrc.getAllocatedDateTime()); // AdmittingConsultant valueObjectDest.setAdmittingConsultant(valueObjectSrc.getAdmittingConsultant()); // AccomodationRequestedType valueObjectDest.setAccomodationRequestedType(valueObjectSrc.getAccomodationRequestedType()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.Set domainObjectSet) { return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) iterator.next(); ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.List domainObjectList) { return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainObjectList.get(i); ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.EDPartialAdmission set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection) { return extractEDPartialAdmissionSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i); ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.EDPartialAdmission list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection) { return extractEDPartialAdmissionList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i); ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object. * @param domainObject ims.emergency.domain.objects.EDPartialAdmission */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(DomainObjectMap map, ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject = (ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo) map.getValueObject(domainObject, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.EDPartialAdmission */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.EDPartialAdmission */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(DomainObjectMap map, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_EDPartialAdmission(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // DecisionToAdmitDateTime java.util.Date DecisionToAdmitDateTime = domainObject.getDecisionToAdmitDateTime(); if ( null != DecisionToAdmitDateTime ) { valueObject.setDecisionToAdmitDateTime(new ims.framework.utils.DateTime(DecisionToAdmitDateTime) ); } // Specialty ims.domain.lookups.LookupInstance instance2 = domainObject.getSpecialty(); if ( null != instance2 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance2.getImage() != null) { img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath()); } color = instance2.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.Specialty voLookup2 = new ims.core.vo.lookups.Specialty(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color); ims.core.vo.lookups.Specialty parentVoLookup2 = voLookup2; ims.domain.lookups.LookupInstance parent2 = instance2.getParent(); while (parent2 != null) { if (parent2.getImage() != null) { img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() ); } else { img = null; } color = parent2.getColor(); if (color != null) color.getValue(); parentVoLookup2.setParent(new ims.core.vo.lookups.Specialty(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color)); parentVoLookup2 = parentVoLookup2.getParent(); parent2 = parent2.getParent(); } valueObject.setSpecialty(voLookup2); } // AllocatedStatus ims.domain.lookups.LookupInstance instance3 = domainObject.getAllocatedStatus(); if ( null != instance3 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance3.getImage() != null) { img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath()); } color = instance3.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.AllocationStatus voLookup3 = new ims.emergency.vo.lookups.AllocationStatus(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color); ims.emergency.vo.lookups.AllocationStatus parentVoLookup3 = voLookup3; ims.domain.lookups.LookupInstance parent3 = instance3.getParent(); while (parent3 != null) { if (parent3.getImage() != null) { img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() ); } else { img = null; } color = parent3.getColor(); if (color != null) color.getValue(); parentVoLookup3.setParent(new ims.emergency.vo.lookups.AllocationStatus(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color)); parentVoLookup3 = parentVoLookup3.getParent(); parent3 = parent3.getParent(); } valueObject.setAllocatedStatus(voLookup3); } // AllocatedBedType ims.domain.lookups.LookupInstance instance4 = domainObject.getAllocatedBedType(); if ( null != instance4 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance4.getImage() != null) { img = new ims.framework.utils.ImagePath(instance4.getImage().getImageId(), instance4.getImage().getImagePath()); } color = instance4.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.AllocatedBedType voLookup4 = new ims.emergency.vo.lookups.AllocatedBedType(instance4.getId(),instance4.getText(), instance4.isActive(), null, img, color); ims.emergency.vo.lookups.AllocatedBedType parentVoLookup4 = voLookup4; ims.domain.lookups.LookupInstance parent4 = instance4.getParent(); while (parent4 != null) { if (parent4.getImage() != null) { img = new ims.framework.utils.ImagePath(parent4.getImage().getImageId(), parent4.getImage().getImagePath() ); } else { img = null; } color = parent4.getColor(); if (color != null) color.getValue(); parentVoLookup4.setParent(new ims.emergency.vo.lookups.AllocatedBedType(parent4.getId(),parent4.getText(), parent4.isActive(), null, img, color)); parentVoLookup4 = parentVoLookup4.getParent(); parent4 = parent4.getParent(); } valueObject.setAllocatedBedType(voLookup4); } // AuthoringInfo valueObject.setAuthoringInfo(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInfo()) ); // AllocatedDateTime java.util.Date AllocatedDateTime = domainObject.getAllocatedDateTime(); if ( null != AllocatedDateTime ) { valueObject.setAllocatedDateTime(new ims.framework.utils.DateTime(AllocatedDateTime) ); } // AdmittingConsultant valueObject.setAdmittingConsultant(ims.core.vo.domain.HcpMinVoAssembler.create(map, domainObject.getAdmittingConsultant()) ); // AccomodationRequestedType ims.domain.lookups.LookupInstance instance8 = domainObject.getAccomodationRequestedType(); if ( null != instance8 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance8.getImage() != null) { img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath()); } color = instance8.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.AccomodationRequestedType voLookup8 = new ims.core.vo.lookups.AccomodationRequestedType(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color); ims.core.vo.lookups.AccomodationRequestedType parentVoLookup8 = voLookup8; ims.domain.lookups.LookupInstance parent8 = instance8.getParent(); while (parent8 != null) { if (parent8.getImage() != null) { img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() ); } else { img = null; } color = parent8.getColor(); if (color != null) color.getValue(); parentVoLookup8.setParent(new ims.core.vo.lookups.AccomodationRequestedType(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color)); parentVoLookup8 = parentVoLookup8.getParent(); parent8 = parent8.getParent(); } valueObject.setAccomodationRequestedType(voLookup8); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject) { return extractEDPartialAdmission(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_EDPartialAdmission(); ims.emergency.domain.objects.EDPartialAdmission domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(valueObject); } // ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo ID_EDPartialAdmission field is unknown domainObject = new ims.emergency.domain.objects.EDPartialAdmission(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EDPartialAdmission()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(key); } domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainFactory.getDomainObject(ims.emergency.domain.objects.EDPartialAdmission.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_EDPartialAdmission()); ims.framework.utils.DateTime dateTime1 = valueObject.getDecisionToAdmitDateTime(); java.util.Date value1 = null; if ( dateTime1 != null ) { value1 = dateTime1.getJavaDate(); } domainObject.setDecisionToAdmitDateTime(value1); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value2 = null; if ( null != valueObject.getSpecialty() ) { value2 = domainFactory.getLookupInstance(valueObject.getSpecialty().getID()); } domainObject.setSpecialty(value2); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value3 = null; if ( null != valueObject.getAllocatedStatus() ) { value3 = domainFactory.getLookupInstance(valueObject.getAllocatedStatus().getID()); } domainObject.setAllocatedStatus(value3); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value4 = null; if ( null != valueObject.getAllocatedBedType() ) { value4 = domainFactory.getLookupInstance(valueObject.getAllocatedBedType().getID()); } domainObject.setAllocatedBedType(value4); // SaveAsRefVO - treated as a refVo in extract methods ims.core.clinical.domain.objects.AuthoringInformation value5 = null; if ( null != valueObject.getAuthoringInfo() ) { if (valueObject.getAuthoringInfo().getBoId() == null) { if (domMap.get(valueObject.getAuthoringInfo()) != null) { value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domMap.get(valueObject.getAuthoringInfo()); } } else { value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domainFactory.getDomainObject(ims.core.clinical.domain.objects.AuthoringInformation.class, valueObject.getAuthoringInfo().getBoId()); } } domainObject.setAuthoringInfo(value5); ims.framework.utils.DateTime dateTime6 = valueObject.getAllocatedDateTime(); java.util.Date value6 = null; if ( dateTime6 != null ) { value6 = dateTime6.getJavaDate(); } domainObject.setAllocatedDateTime(value6); // SaveAsRefVO - treated as a refVo in extract methods ims.core.resource.people.domain.objects.Hcp value7 = null; if ( null != valueObject.getAdmittingConsultant() ) { if (valueObject.getAdmittingConsultant().getBoId() == null) { if (domMap.get(valueObject.getAdmittingConsultant()) != null) { value7 = (ims.core.resource.people.domain.objects.Hcp)domMap.get(valueObject.getAdmittingConsultant()); } } else { value7 = (ims.core.resource.people.domain.objects.Hcp)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Hcp.class, valueObject.getAdmittingConsultant().getBoId()); } } domainObject.setAdmittingConsultant(value7); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value8 = null; if ( null != valueObject.getAccomodationRequestedType() ) { value8 = domainFactory.getLookupInstance(valueObject.getAccomodationRequestedType().getID()); } domainObject.setAccomodationRequestedType(value8); return domainObject; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.java
Java
agpl-3.0
28,003
/* * opencog/embodiment/Control/OperationalAvatarController/HCTestAgent.h * * Copyright (C) 2002-2009 Novamente LLC * All Rights Reserved * Author(s): Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef HCTESTAGENT_H #define HCTESTAGENT_H #include <opencog/server/Agent.h> #include "MessageSender.h" namespace opencog { namespace oac { using namespace opencog; /** * That class is in charge of executing a scenario to test hillclimbing * hosted by LS */ class HCTestAgent : public Agent { enum HCTestMode { HCT_IDLE, HCT_INIT, HCT_WAIT1, HCT_WAIT2, HCT_WAIT3, HCT_WAIT4 }; private: HCTestMode mode; unsigned long cycle; std::string schemaName; std::vector<std::string> schemaArguments; std::string avatarId; std::string ownerId; AtomSpace* atomSpace; MessageSender* sender; unsigned int learning_time1; unsigned int learning_time2; unsigned long max_cycle; public: virtual const ClassInfo& classinfo() const { return info(); } static const ClassInfo& info() { static const ClassInfo _ci("OperationalAvatarController::HCTestAgent"); return _ci; } HCTestAgent(); /** * @param lt1 Time (in second) to wait for the first learning iteration * @param lt2 Time (in second) to wait for the second learning iteration * @param mc Maximum number of cycles to run */ void init(std::string sn, std::vector<std::string> schemaArgs, std::string b, std::string a, AtomSpace* as, MessageSender* s, unsigned int lt1 = 10, unsigned int lt2 = 100, unsigned long mc = 10000); ~HCTestAgent(); void run(opencog::CogServer* ne); void setWait2() { mode = HCT_WAIT2; } void setWait4() { mode = HCT_WAIT4; } }; // class } } // namespace opencog::oac #endif
rkarlberg/opencog
opencog/embodiment/Control/OperationalAvatarController/HCTestAgent.h
C
agpl-3.0
2,617
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Datea Backend"> <meta name="author" content="Datea"> <link rel="shortcut icon" href="{{SITE_STATIC}}/ico/favicon.png"> <title>{% block "page_title" %}{% endblock %} | DATEA</title> <!-- Bootstrap core CSS --> <link href="{{STATIC_URL}}bstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{{STATIC_URL}}bstrap/css/jumbotron-narrow.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> </head> <body> {% block "body" %}{% endblock %} </body> </html>
lafactura/datea-api
datea_api/templates/base.html
HTML
agpl-3.0
1,048
<form class="form fields" action="#/" onsubmit="return false;" data-bind="command: registerCommand"> <div class="fieldset"> <div class="row name" data-bind="css: {'focused': nameFocus(), 'filled': name().length > 0}"> <label for="name" class="title placeholder" data-i18n="LOGIN/LABEL_NAME" data-bind="i18n: 'text'"></label> <span class="value"> <input id="name" class="input" type="text" spellcheck="false" autocomplete="off" data-bind="value: name, hasfocus: nameFocus, valueUpdate: 'afterkeydown'" /> </span> </div> <div class="row login" data-bind="css: {'focused': loginFocus(), 'filled': login().length > 0}"> <label for="reg_login" class="title placeholder" data-i18n="LOGIN/LABEL_LOGIN" data-bind="i18n: 'text'"></label> <span class="value"> <input id="reg_login" class="input" autocomplete="off" spellcheck="false" type="text" data-bind="value: login, hasfocus: loginFocus, valueUpdate: 'afterkeydown'" /> </span> <span class="value suffix" data-bind="visible: domains().length > 0"> <span class="text">@</span> <span class="text" data-bind="text: domain, visible: domains().length === 1"></span> <select data-bind="visible: domains().length > 1, options: domains, value: selectedDomain"></select> </span> </div> <div class="row password" data-bind="css: {'focused': passwordFocus(), 'filled': password().length > 0}"> <label for="reg_password" class="title placeholder" data-i18n="LOGIN/LABEL_NEW_PASSWORD" data-bind="i18n: 'text'"></label> <span class="value"> <input id="reg_password" class="input" autocomplete="off" spellcheck="false" type="password" data-bind="value: password, hasfocus: passwordFocus, valueUpdate: 'afterkeydown'" /> </span> </div> <div class="row password" data-bind="css: {'focused': confirmPasswordFocus(), 'filled': confirmPassword().length > 0}"> <label for="reg_confirm_password" class="title placeholder" data-i18n="LOGIN/LABEL_CONFIRM_PASSWORD" data-bind="i18n: 'text'"></label> <span class="value"> <input id="reg_confirm_password" class="input" autocomplete="off" spellcheck="false" type="password" data-bind="value: confirmPassword, hasfocus: confirmPasswordFocus, valueUpdate: 'afterkeydown'" /> </span> </div> <!-- ko if: allowQuestionPart --> <div class="row question" data-bind="css: {'focused': questionFocus(), 'filled': question().length > 0}"> <label class="title placeholder" data-i18n="LOGIN/LABEL_SELECT_QUESTION" data-bind="i18n: 'text'"></label> <span class="value"> <span class="custom_selector input" data-bind="customSelect: {'control': false, 'expand': 'expand', 'expandState': questionFocus, 'options': registrationQuestions, value: question, optionsText: 'text', optionsValue: 'value'}"> <span class="name" data-bind="text: question"></span> <span class="control"> <span class="icon"></span> </span> <span class="dropdown"> <span class="dropdown_helper"> <span class="dropdown_arrow"><span></span></span> <span class="dropdown_content"> </span> </span> </span> </span> </span> </div> <div class="row answer" data-bind="visible: visibleYourQuestion, css: {'focused': yourQuestionFocus(), 'filled': yourQuestion().length > 0}"> <label for="reg_your_question" class="title placeholder" data-i18n="LOGIN/LABEL_YOUR_QUESTION" data-bind="i18n: 'text'"></label> <span class="value"> <input id="reg_your_question" class="input" autocomplete="off" spellcheck="false" type="text" data-bind="value: yourQuestion, hasfocus: yourQuestionFocus, valueUpdate: 'afterkeydown'" /> </span> </div> <div class="row answer" data-bind="css: {'focused': answerFocus(), 'filled': answer().length > 0}"> <label for="reg_answer" class="title placeholder" data-i18n="LOGIN/LABEL_ANSWER_QUESTION" data-bind="i18n: 'text'"></label> <span class="value"> <input id="reg_answer" class="input" autocomplete="off" spellcheck="false" type="text" data-bind="value: answer, hasfocus: answerFocus, valueUpdate: 'afterkeydown'" /> </span> </div> <!-- /ko --> </div> {%INCLUDE-START/Register-Before-Submit-Button/INCLUDE-END%} <div class="row buttons"> <button type="submit" class="button login" data-bind="text: registerButtonText, command: registerCommand"></button> </div> <div class="row links"> <div class="forgot"> <span class="link" data-bind="click: function () {$parent.gotoRegister(false);}, i18n: 'text'" data-i18n="LOGIN/LINK_BACK"></span> </div> </div> </form>
ArcherSys/ArrowHeadMail
templates/views/Login/RegisterViewModel.html
HTML
agpl-3.0
4,527
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> */ #include "GameObjectAI.h" //GameObjectAI::GameObjectAI(GameObject* g) : go(g) {} int GameObjectAI::Permissible(const GameObject* go) { if (go->GetAIName() == "GameObjectAI") return PERMIT_BASE_SPECIAL; return PERMIT_BASE_NO; } NullGameObjectAI::NullGameObjectAI(GameObject* g) : GameObjectAI(g) {}
DantestyleXD/azerothcore-wotlk
src/game/AI/CoreAI/GameObjectAI.cpp
C++
agpl-3.0
609
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="generator" content="ApiGen 2.8.0"> <title>Class forma_pago</title> <script type="text/javascript" src="resources/combined.js?3770084987"></script> <script type="text/javascript" src="elementlist.js?553530925"></script> <link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360"> </head> <body> <div id="left"> <div id="menu"> <a href="index.html" title="Overview"><span>Overview</span></a> <div id="groups"> </div> <div id="elements"> <h3>Classes</h3> <ul> <li><a href="class-agente.html">agente</a></li> <li><a href="class-albaran_cliente.html">albaran_cliente</a></li> <li><a href="class-albaran_proveedor.html">albaran_proveedor</a></li> <li><a href="class-almacen.html">almacen</a></li> <li><a href="class-articulo.html">articulo</a></li> <li><a href="class-asiento.html">asiento</a></li> <li><a href="class-asiento_factura.html">asiento_factura</a></li> <li><a href="class-balance.html">balance</a></li> <li><a href="class-balance_cuenta.html">balance_cuenta</a></li> <li><a href="class-balance_cuenta_a.html">balance_cuenta_a</a></li> <li><a href="class-banco.html">banco</a></li> <li><a href="class-caja.html">caja</a></li> <li><a href="class-cliente.html">cliente</a></li> <li><a href="class-concepto_partida.html">concepto_partida</a></li> <li><a href="class-cuenta.html">cuenta</a></li> <li><a href="class-cuenta_banco.html">cuenta_banco</a></li> <li><a href="class-cuenta_banco_cliente.html">cuenta_banco_cliente</a></li> <li><a href="class-cuenta_banco_proveedor.html">cuenta_banco_proveedor</a></li> <li><a href="class-cuenta_especial.html">cuenta_especial</a></li> <li><a href="class-direccion_cliente.html">direccion_cliente</a></li> <li><a href="class-direccion_proveedor.html">direccion_proveedor</a></li> <li><a href="class-divisa.html">divisa</a></li> <li><a href="class-ejercicio.html">ejercicio</a></li> <li><a href="class-empresa.html">empresa</a></li> <li><a href="class-epigrafe.html">epigrafe</a></li> <li><a href="class-factura_cliente.html">factura_cliente</a></li> <li><a href="class-factura_proveedor.html">factura_proveedor</a></li> <li><a href="class-familia.html">familia</a></li> <li class="active"><a href="class-forma_pago.html">forma_pago</a></li> <li><a href="class-fs_access.html">fs_access</a></li> <li><a href="class-fs_button.html">fs_button</a></li> <li><a href="class-fs_button_img.html">fs_button_img</a></li> <li><a href="class-fs_cache.html">fs_cache</a></li> <li><a href="class-fs_controller.html">fs_controller</a></li> <li><a href="class-fs_db.html">fs_db</a></li> <li><a href="class-fs_default_items.html">fs_default_items</a></li> <li><a href="class-fs_extension.html">fs_extension</a></li> <li><a href="class-fs_log.html">fs_log</a></li> <li><a href="class-fs_model.html">fs_model</a></li> <li><a href="class-fs_mysql.html">fs_mysql</a></li> <li><a href="class-fs_page.html">fs_page</a></li> <li><a href="class-fs_pdf.html">fs_pdf</a></li> <li><a href="class-fs_postgresql.html">fs_postgresql</a></li> <li><a href="class-fs_printer.html">fs_printer</a></li> <li><a href="class-fs_user.html">fs_user</a></li> <li><a href="class-fs_var.html">fs_var</a></li> <li><a href="class-grupo_clientes.html">grupo_clientes</a></li> <li><a href="class-grupo_epigrafes.html">grupo_epigrafes</a></li> <li><a href="class-impuesto.html">impuesto</a></li> <li><a href="class-linea_albaran_cliente.html">linea_albaran_cliente</a></li> <li><a href="class-linea_albaran_proveedor.html">linea_albaran_proveedor</a></li> <li><a href="class-linea_factura_cliente.html">linea_factura_cliente</a></li> <li><a href="class-linea_factura_proveedor.html">linea_factura_proveedor</a></li> <li><a href="class-linea_iva_factura_cliente.html">linea_iva_factura_cliente</a></li> <li><a href="class-linea_iva_factura_proveedor.html">linea_iva_factura_proveedor</a></li> <li><a href="class-pais.html">pais</a></li> <li><a href="class-partida.html">partida</a></li> <li><a href="class-proveedor.html">proveedor</a></li> <li><a href="class-regularizacion_iva.html">regularizacion_iva</a></li> <li><a href="class-secuencia.html">secuencia</a></li> <li><a href="class-secuencia_contabilidad.html">secuencia_contabilidad</a></li> <li><a href="class-secuencia_ejercicio.html">secuencia_ejercicio</a></li> <li><a href="class-serie.html">serie</a></li> <li><a href="class-stock.html">stock</a></li> <li><a href="class-subcuenta.html">subcuenta</a></li> <li><a href="class-subcuenta_cliente.html">subcuenta_cliente</a></li> <li><a href="class-subcuenta_proveedor.html">subcuenta_proveedor</a></li> <li><a href="class-sucursal.html">sucursal</a></li> <li><a href="class-tarifa.html">tarifa</a></li> <li><a href="class-tarifa_articulo.html">tarifa_articulo</a></li> </ul> <h3>Functions</h3> <ul> <li><a href="function-bround.html">bround</a></li> <li><a href="function-require_model.html">require_model</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <form id="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <input type="text" name="q" class="text"> <input type="submit" value="Search"> </form> <div id="navigation"> <ul> <li> <a href="index.html" title="Overview"><span>Overview</span></a> </li> <li class="active"> <span>Class</span> </li> </ul> <ul> <li> <a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a> </li> </ul> <ul> </ul> </div> <div id="content" class="class"> <h1>Class forma_pago</h1> <div class="description"> <p>Forma de pago de una factura.</p> </div> <dl class="tree"> <dd style="padding-left:0px"> <a href="class-fs_model.html"><span>fs_model</span></a> </dd> <dd style="padding-left:30px"> <img src="resources/inherit.png" alt="Extended by"> <b><span>forma_pago</span></b> </dd> </dl> <div class="info"> <b>Located at</b> <a href="source-class-forma_pago.html#22-145" title="Go to source code">forma_pago.php</a><br> </div> <table class="summary" id="methods"> <caption>Methods summary</caption> <tr data-order="__construct" id="___construct"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#___construct">#</a> <code><a href="source-class-forma_pago.html#33-52" title="Go to source code">__construct</a>( <span>type <var>$f</var> = <span class="php-keyword1">FALSE</span></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> <h4>Parameters</h4> <div class="list"><dl> <dt><var>$f</var></dt> <dd><code>type</code><br>$name nombre de la tabla de la base de datos.</dd> </dl></div> <h4>Overrides</h4> <div class="list"><code><a href="class-fs_model.html#___construct">fs_model::__construct()</a></code></div> </div> </div></td> </tr> <tr data-order="install" id="_install"> <td class="attributes"><code> protected </code> </td> <td class="name"><div> <a class="anchor" href="#_install">#</a> <code><a href="source-class-forma_pago.html#54-58" title="Go to source code">install</a>( )</code> <div class="description short"> <p>Esta función es llamada al crear una tabla. Permite insertar valores en la tabla.</p> </div> <div class="description detailed hidden"> <p>Esta función es llamada al crear una tabla. Permite insertar valores en la tabla.</p> </div> </div></td> </tr> <tr data-order="url" id="_url"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_url">#</a> <code><a href="source-class-forma_pago.html#60-63" title="Go to source code">url</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="is_default" id="_is_default"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_is_default">#</a> <code><a href="source-class-forma_pago.html#65-68" title="Go to source code">is_default</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="get" id="_get"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_get">#</a> <code><a href="source-class-forma_pago.html#70-77" title="Go to source code">get</a>( <span>mixed <var>$cod</var></span> )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="exists" id="_exists"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_exists">#</a> <code><a href="source-class-forma_pago.html#79-85" title="Go to source code">exists</a>( )</code> <div class="description short"> <p>Esta función devuelve TRUE si los datos del objeto se encuentran en la base de datos.</p> </div> <div class="description detailed hidden"> <p>Esta función devuelve TRUE si los datos del objeto se encuentran en la base de datos.</p> </div> </div></td> </tr> <tr data-order="test" id="_test"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_test">#</a> <code><a href="source-class-forma_pago.html#87-91" title="Go to source code">test</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="save" id="_save"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_save">#</a> <code><a href="source-class-forma_pago.html#93-117" title="Go to source code">save</a>( )</code> <div class="description short"> <p>Esta función sirve tanto para insertar como para actualizar los datos del objeto en la base de datos.</p> </div> <div class="description detailed hidden"> <p>Esta función sirve tanto para insertar como para actualizar los datos del objeto en la base de datos.</p> </div> </div></td> </tr> <tr data-order="delete" id="_delete"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_delete">#</a> <code><a href="source-class-forma_pago.html#119-123" title="Go to source code">delete</a>( )</code> <div class="description short"> <p>Esta función sirve para eliminar los datos del objeto de la base de datos</p> </div> <div class="description detailed hidden"> <p>Esta función sirve para eliminar los datos del objeto de la base de datos</p> </div> </div></td> </tr> <tr data-order="all" id="_all"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_all">#</a> <code><a href="source-class-forma_pago.html#130-144" title="Go to source code">all</a>( )</code> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> </table> <table class="summary inherited"> <caption>Methods inherited from <a href="class-fs_model.html#methods">fs_model</a></caption> <tr> <td><code> <a href="class-fs_model.html#_bin2str">bin2str()</a>, <a href="class-fs_model.html#_check_table">check_table()</a>, <a href="class-fs_model.html#_clean_checked_tables">clean_checked_tables()</a>, <a href="class-fs_model.html#_date_range">date_range()</a>, <a href="class-fs_model.html#_escape_string">escape_string()</a>, <a href="class-fs_model.html#_floatcmp">floatcmp()</a>, <a href="class-fs_model.html#_floatcmp3">floatcmp3()</a>, <a href="class-fs_model.html#_get_errors">get_errors()</a>, <a href="class-fs_model.html#_get_xml_table">get_xml_table()</a>, <a href="class-fs_model.html#_intval">intval()</a>, <a href="class-fs_model.html#_new_error_msg">new_error_msg()</a>, <a href="class-fs_model.html#_no_html">no_html()</a>, <a href="class-fs_model.html#_random_string">random_string()</a>, <a href="class-fs_model.html#_str2bin">str2bin()</a>, <a href="class-fs_model.html#_str2bool">str2bool()</a>, <a href="class-fs_model.html#_var2str">var2str()</a>, <a href="class-fs_model.html#_var2timesince">var2timesince()</a> </code></td> </tr> </table> <table class="summary" id="properties"> <caption>Properties summary</caption> <tr data-order="codpago" id="$codpago"> <td class="attributes"><code> public mixed </code></td> <td class="name"> <a href="source-class-forma_pago.html#27" title="Go to source code"><var>$codpago</var></a> </td> <td class="value"><code></code></td> <td class="description"><div> <a href="#$codpago" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="descripcion" id="$descripcion"> <td class="attributes"><code> public mixed </code></td> <td class="name"> <a href="source-class-forma_pago.html#28" title="Go to source code"><var>$descripcion</var></a> </td> <td class="value"><code></code></td> <td class="description"><div> <a href="#$descripcion" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="genrecibos" id="$genrecibos"> <td class="attributes"><code> public mixed </code></td> <td class="name"> <a href="source-class-forma_pago.html#29" title="Go to source code"><var>$genrecibos</var></a> </td> <td class="value"><code></code></td> <td class="description"><div> <a href="#$genrecibos" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="codcuenta" id="$codcuenta"> <td class="attributes"><code> public mixed </code></td> <td class="name"> <a href="source-class-forma_pago.html#30" title="Go to source code"><var>$codcuenta</var></a> </td> <td class="value"><code></code></td> <td class="description"><div> <a href="#$codcuenta" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> <tr data-order="domiciliado" id="$domiciliado"> <td class="attributes"><code> public mixed </code></td> <td class="name"> <a href="source-class-forma_pago.html#31" title="Go to source code"><var>$domiciliado</var></a> </td> <td class="value"><code></code></td> <td class="description"><div> <a href="#$domiciliado" class="anchor">#</a> <div class="description short"> </div> <div class="description detailed hidden"> </div> </div></td> </tr> </table> <table class="summary inherited"> <caption>Properties inherited from <a href="class-fs_model.html#properties">fs_model</a></caption> <tr> <td><code> <a href="class-fs_model.html#$base_dir"><var>$base_dir</var></a>, <a href="class-fs_model.html#$cache"><var>$cache</var></a>, <a href="class-fs_model.html#$db"><var>$db</var></a>, <a href="class-fs_model.html#$default_items"><var>$default_items</var></a>, <a href="class-fs_model.html#$table_name"><var>$table_name</var></a> </code></td> </tr> </table> </div> <div id="footer"> API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a> </div> </div> </div> </body> </html>
CorporacioDigital/iMovers
doc/class-forma_pago.html
HTML
agpl-3.0
16,426
class AddNameIndexToGames < ActiveRecord::Migration[4.2] def change add_index :games, :name end end
BatedUrGonnaDie/splits-io
db/migrate/20140925231311_add_name_index_to_games.rb
Ruby
agpl-3.0
108
package com.sapienter.jbilling.client.jspc.user; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import com.sapienter.jbilling.client.util.Constants; public final class listProcessSuccessfulUsersTop_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.AnnotationProcessor _jsp_annotationprocessor; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.release(); _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.release(); _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.release(); _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"); out.write("\r\n\r\n"); // html:messages org.apache.struts.taglib.html.MessagesTag _jspx_th_html_005fmessages_005f0 = (org.apache.struts.taglib.html.MessagesTag) _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.get(org.apache.struts.taglib.html.MessagesTag.class); _jspx_th_html_005fmessages_005f0.setPageContext(_jspx_page_context); _jspx_th_html_005fmessages_005f0.setParent(null); // /user/listProcessSuccessfulUsersTop.jsp(30,0) name = message type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_html_005fmessages_005f0.setMessage("true"); // /user/listProcessSuccessfulUsersTop.jsp(30,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_html_005fmessages_005f0.setId("myMessage"); int _jspx_eval_html_005fmessages_005f0 = _jspx_th_html_005fmessages_005f0.doStartTag(); if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { java.lang.String myMessage = null; if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.pushBody(); _jspx_th_html_005fmessages_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out); _jspx_th_html_005fmessages_005f0.doInitBody(); } myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage"); do { out.write("\r\n\t<p>"); if (_jspx_meth_bean_005fwrite_005f0(_jspx_th_html_005fmessages_005f0, _jspx_page_context)) return; out.write("</p>\r\n"); int evalDoAfterBody = _jspx_th_html_005fmessages_005f0.doAfterBody(); myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage"); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) { out = _jspx_page_context.popBody(); } } if (_jspx_th_html_005fmessages_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0); return; } _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0); out.write("\r\n\r\n"); out.write('\r'); out.write('\n'); // bean:define org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f0 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class); _jspx_th_bean_005fdefine_005f0.setPageContext(_jspx_page_context); _jspx_th_bean_005fdefine_005f0.setParent(null); // /user/listProcessSuccessfulUsersTop.jsp(36,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f0.setId("forward_from"); // /user/listProcessSuccessfulUsersTop.jsp(36,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f0.setValue(Constants.FORWARD_USER_VIEW); // /user/listProcessSuccessfulUsersTop.jsp(36,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f0.setToScope("session"); int _jspx_eval_bean_005fdefine_005f0 = _jspx_th_bean_005fdefine_005f0.doStartTag(); if (_jspx_th_bean_005fdefine_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0); return; } _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0); java.lang.String forward_from = null; forward_from = (java.lang.String) _jspx_page_context.findAttribute("forward_from"); out.write("\r\n\r\n"); // bean:define org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f1 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class); _jspx_th_bean_005fdefine_005f1.setPageContext(_jspx_page_context); _jspx_th_bean_005fdefine_005f1.setParent(null); // /user/listProcessSuccessfulUsersTop.jsp(40,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f1.setId("forward_to"); // /user/listProcessSuccessfulUsersTop.jsp(40,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f1.setValue(Constants.FORWARD_USER_VIEW); // /user/listProcessSuccessfulUsersTop.jsp(40,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fdefine_005f1.setToScope("session"); int _jspx_eval_bean_005fdefine_005f1 = _jspx_th_bean_005fdefine_005f1.doStartTag(); if (_jspx_th_bean_005fdefine_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1); return; } _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1); java.lang.String forward_to = null; forward_to = (java.lang.String) _jspx_page_context.findAttribute("forward_to"); out.write("\r\n\r\n"); // jbilling:genericList com.sapienter.jbilling.client.list.GenericListTag _jspx_th_jbilling_005fgenericList_005f0 = (com.sapienter.jbilling.client.list.GenericListTag) _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.get(com.sapienter.jbilling.client.list.GenericListTag.class); _jspx_th_jbilling_005fgenericList_005f0.setPageContext(_jspx_page_context); _jspx_th_jbilling_005fgenericList_005f0.setParent(null); // /user/listProcessSuccessfulUsersTop.jsp(44,0) name = setup type = java.lang.Boolean reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_jbilling_005fgenericList_005f0.setSetup(new Boolean(true)); // /user/listProcessSuccessfulUsersTop.jsp(44,0) name = type type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_jbilling_005fgenericList_005f0.setType(Constants.LIST_TYPE_PROCESS_RUN_SUCCESSFULL_USERS); int _jspx_eval_jbilling_005fgenericList_005f0 = _jspx_th_jbilling_005fgenericList_005f0.doStartTag(); if (_jspx_th_jbilling_005fgenericList_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0); return; } _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0); out.write(" \r\n \r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_bean_005fwrite_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_005fmessages_005f0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // bean:write org.apache.struts.taglib.bean.WriteTag _jspx_th_bean_005fwrite_005f0 = (org.apache.struts.taglib.bean.WriteTag) _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.get(org.apache.struts.taglib.bean.WriteTag.class); _jspx_th_bean_005fwrite_005f0.setPageContext(_jspx_page_context); _jspx_th_bean_005fwrite_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_005fmessages_005f0); // /user/listProcessSuccessfulUsersTop.jsp(31,4) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_bean_005fwrite_005f0.setName("myMessage"); int _jspx_eval_bean_005fwrite_005f0 = _jspx_th_bean_005fwrite_005f0.doStartTag(); if (_jspx_th_bean_005fwrite_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0); return true; } _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0); return false; } }
maduhu/knx-jbilling2.2.0
build/jsp-classes/com/sapienter/jbilling/client/jspc/user/listProcessSuccessfulUsersTop_jsp.java
Java
agpl-3.0
13,697
--- logohandle: egeriarocks sort: egeria title: Egeria twitter: EgeriaPlanning website: 'https://egeria.rocks/' ---
fileformat/vectorlogozone
www/logos/egeriarocks/index.md
Markdown
agpl-3.0
116
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ /** * @param array $params * @param $template * * @return bool|mixed|string */ function smarty_function_flink($params, $template) { $file = $params['file']; $request = Shopware()->Front()->Request(); $docPath = Shopware()->Container()->getParameter('shopware.app.rootdir'); // Check if we got an URI or a local link if (!empty($file) && strpos($file, '/') !== 0 && strpos($file, '://') === false) { $useIncludePath = $template->smarty->getUseIncludePath(); /** @var string[] $templateDirs */ $templateDirs = $template->smarty->getTemplateDir(); // Try to find the file on the filesystem foreach ($templateDirs as $dir) { if (file_exists($dir . $file)) { $file = Enlight_Loader::realpath($dir) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $file); break; } if ($useIncludePath) { if ($dir === '.' . DIRECTORY_SEPARATOR) { $dir = ''; } if (($result = Enlight_Loader::isReadable($dir . $file)) !== false) { $file = $result; break; } } } // Some cleanup code if (strpos($file, $docPath) === 0) { $file = substr($file, strlen($docPath)); } // Make sure we have the right separator for the web context if (DIRECTORY_SEPARATOR !== '/') { $file = str_replace(DIRECTORY_SEPARATOR, '/', $file); } if (strpos($file, './') === 0) { $file = substr($file, 2); } if ($request !== null) { $file = $request->getBasePath() . '/' . ltrim($file, '/'); } } if (empty($file) && $request !== null) { $file = $request->getBasePath() . '/'; } if ($request !== null && !empty($params['fullPath']) && strpos($file, '/') === 0) { $file = $request->getScheme() . '://' . $request->getHttpHost() . $file; } return $file; }
simkli/shopware
engine/Library/Enlight/Template/Plugins/function.flink.php
PHP
agpl-3.0
3,003
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import VueBootstrap from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.use(VueBootstrap) // HTTP Client we use. import Axios from 'axios' // TODO: Set these during build time. Axios.defaults.baseURL = 'http://localhost:8080' Axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
praelatus/backend
client/src/main.js
JavaScript
agpl-3.0
761
{% extends 'newhpc/english/english_base.html' %} {% load staticfiles %} {% block title %}Registration | HPC 2020{% endblock %} {% block style %} .listitem44 { display: inline-block; font-size: 1.5em; list-style-type: none; padding: 1em; text-transform: uppercase; } .listitem44 span { display: block; font-size: 4.5rem; } #title { font-size: 32px; color: #9d0051; } .sub-title { font-size: 26px!important; } .hpc-text { color: #242b2c!important; margin-top: 30px; text-align: justify; text-align-last: center; } {% endblock %} {% block lang %} {% url 'newhpc:riy_ar_registration' event_city='riyadh' %} {% endblock %} {% block lang2 %} {% url 'newhpc:riy_ar_registration' event_city='riyadh' %} {% endblock %} {% block active_register %}c-active{% endblock %} {% block content %} <div class="c-layout-page"> <!-- BEGIN: PAGE CONTENT --> <!-- BEGIN: CONTENT/STATS/COUNTER-1 --> <div class="c-content-box c-size-md c-bg-white"> <div class="container"> <div class="c-content-counter-1 c-opt-1"> <div class="c-content-title-1"> <h3 class="c-center c-font-uppercase c-font-bold" id="title">HPC Programs</h3> <div class="c-line-center"></div> </div> <div class="row"> <div class="col-md-4"> <img src="{% static 'newhpc/images/icons/registration/general-icon.png' %}" style="width: 200px;margin-bottom: 20px"> <h3 class="c-title c-first c-font-uppercase c-font-bold sub-title">General Program</h3> <p class="c-content hpc-text">The General Programs aims through its lectures, panel discussions and workshops to offer topics that concern all healthcare professionals and students. It also aims to discuss the National Transformation Program 2020 in the health field and its effort to accomplish vision 2030.</p> </div> <div class="col-md-4"> <img src="{% static 'newhpc/images/icons/registration/research-icon.png' %}" style="width: 200px;margin-bottom: 20px"> <h3 class="c-title c-font-uppercase c-font-bold sub-title">Research Program</h3> <p class="c-content hpc-text">Research is the basis upon which healthcare grows. An imperative area to the success, quality, and advancement of healthcare. Research provides opportunities that help individuals to pursue and enhance their knowledge in different aspects of the healthcare field. Health Profession Conference 2020 provides variety of workshops and lectures on how to conduct and build a scientific paper through the Research Program</p> </div> <div class="col-md-4"> <img src="{% static 'newhpc/images/icons/registration/colleges-icon.png' %}" style="width: 200px;margin-bottom: 20px"> <h3 class="c-title c-font-uppercase c-font-bold sub-title">Collages’ Programs</h3> <p class="c-content hpc-text">Pursuing power in health leadership and in solidarity with National Transformation Program. We offer our collages’ programs that will host series of lectures and workshops that will touch the essence of each specialty (Collage of Medicine, Collage of Dentistry, Collage of Pharmacy, Collage of Applied Medical Sciences, Collage of Nursing and Collage of Public Health).</p> </div> </div> </div> </div> </div> <!-- END: CONTENT/STATS/COUNTER-1 --> <!-- BEGIN: CONTENT/BARS/BAR-4 --> <div class="c-content-box c-size-md c-bg-parallax" style="background-color: #242b2c "> <div class="container"> <div class="c-content-bar-4"> <h3 class="c-font-uppercase c-font-bold" id="head" style="margin: 0px!important;border: 0px!important;direction: ltr!important;">HPC 2020 Countdown</h3> <ul style="color: white!important;padding: 0px!important;font-weight: 700!important;margin-top: -15px!important;direction: ltr!important;"> <li class="listitem44"><span id="days"></span>Days</li> <li class="listitem44"><span id="hours"></span>Hours</li> <li class="listitem44"><span id="minutes"></span>Minutes</li> <li class="listitem44"><span id="seconds"></span>Seconds</li> </ul> </div> </div> </div> <!-- END: CONTENT/BARS/BAR-4 --> </div> {% endblock %} {% block script %} const second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24; let countDown = new Date('Jan 28, 2020 00:00:00').getTime(), x = setInterval(function() { let now = new Date().getTime(), distance = countDown - now; document.getElementById('days').innerText = Math.floor(distance / (day)), document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)), document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)), document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second); //do something later when date is reached //if (distance < 0) { // clearInterval(x); // 'IT'S MY BIRTHDAY!; //} }, second) {% endblock %}
enjaz/enjaz
newhpc/templates/newhpc/english/riy_en_registeration.html
HTML
agpl-3.0
5,898
/* * Concept profile generation tool suite * Copyright (C) 2015 Biosemantics Group, Erasmus University Medical Center, * Rotterdam, The Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package JochemBuilder.KEGGcompound; import org.erasmusmc.ontology.OntologyFileLoader; import org.erasmusmc.ontology.OntologyStore; import org.erasmusmc.ontology.ontologyutilities.OntologyCurator; import org.erasmusmc.utilities.StringUtilities; import JochemBuilder.SharedCurationScripts.CasperForJochem; import JochemBuilder.SharedCurationScripts.CurateUsingManualCurationFile; import JochemBuilder.SharedCurationScripts.RemoveDictAndCompanyNamesAtEndOfTerm; import JochemBuilder.SharedCurationScripts.RewriteFurther; import JochemBuilder.SharedCurationScripts.SaveOnlyCASandInchiEntries; public class KEGGcompoundImport { public static String date = "110809"; public static String home = "/home/khettne/Projects/Jochem"; public static String keggcImportFile = home+"/KEGG/Compound/compound"; public static String compoundToDrugMappingOutFile = home+"/KEGG/Compound/compoundToDrugMapping"; public static String keggcToInchiMappingFile = home+"/KEGG/Compound/compound.inchi"; public static String keggcDictionariesLog = home+"/KEGG/Compound/KEGGc_dictionaries_"+date+".log"; public static String keggcRewriteLog = home+"/KEGG/Compound/KEGGcCAS_casperFiltered_"+date+".log"; public static String keggcLowerCaseLog = home+"/KEGG/Compound/KEGGcCAS_lowerCase_"+date+".log"; public static String termsToRemove = "keggcTermsToRemove.txt"; public static String keggcCuratedOntologyPath = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".ontology"; public static String keggcCuratedLog = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".log"; public static void main(String[] args) { OntologyStore ontology = new OntologyStore(); OntologyFileLoader loader = new OntologyFileLoader(); //Make unprocessed thesaurus ChemicalsFromKEGGcompound keggchem = new ChemicalsFromKEGGcompound(); ontology = keggchem.run(keggcImportFile, compoundToDrugMappingOutFile); RemoveDictAndCompanyNamesAtEndOfTerm remove = new RemoveDictAndCompanyNamesAtEndOfTerm(); ontology = remove.run(ontology, keggcDictionariesLog); MapKEGGc2InChI mapOntology = new MapKEGGc2InChI(); ontology = mapOntology.map(ontology, keggcToInchiMappingFile); // CAS and InChI SaveOnlyCASandInchiEntries make = new SaveOnlyCASandInchiEntries(); ontology = make.run(ontology); //Rewrite CasperForJochem casper = new CasperForJochem(); casper.run(ontology, keggcRewriteLog); // Make some entries lower case and filter further RewriteFurther rewrite = new RewriteFurther(); ontology = rewrite.run(ontology, keggcLowerCaseLog); //Remove terms based on medline frequency CurateUsingManualCurationFile curate = new CurateUsingManualCurationFile(); ontology = curate.run(ontology, keggcCuratedLog,termsToRemove); //Set default flags and save ontology OntologyCurator curator = new OntologyCurator(); curator.curateAndPrepare(ontology); loader.save(ontology,keggcCuratedOntologyPath); System.out.println("Done! " + StringUtilities.now()); } }
BiosemanticsDotOrg/GeneDiseasePlosBio
java/DataImport/src/JochemBuilder/KEGGcompound/KEGGcompoundImport.java
Java
agpl-3.0
3,807
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QWIZARD_WIN_P_H #define QWIZARD_WIN_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #ifndef QT_NO_WIZARD #ifndef QT_NO_STYLE_WINDOWSVISTA #include <qt_windows.h> #include <qobject.h> #include <qwidget.h> #include <qabstractbutton.h> #include <QtGui/private/qwidget_p.h> QT_BEGIN_NAMESPACE class QVistaBackButton : public QAbstractButton { public: QVistaBackButton(QWidget *widget); QSize sizeHint() const; inline QSize minimumSizeHint() const { return sizeHint(); } void enterEvent(QEvent *event); void leaveEvent(QEvent *event); void paintEvent(QPaintEvent *event); }; class QWizard; class QVistaHelper : public QObject { public: QVistaHelper(QWizard *wizard); ~QVistaHelper(); enum TitleBarChangeType { NormalTitleBar, ExtendedTitleBar }; bool setDWMTitleBar(TitleBarChangeType type); void setTitleBarIconAndCaptionVisible(bool visible); void mouseEvent(QEvent *event); bool handleWinEvent(MSG *message, long *result); void resizeEvent(QResizeEvent *event); void paintEvent(QPaintEvent *event); QVistaBackButton *backButton() const { return backButton_; } void disconnectBackButton() { if (backButton_) backButton_->disconnect(); } void hideBackButton() { if (backButton_) backButton_->hide(); } void setWindowPosHack(); QColor basicWindowFrameColor(); enum VistaState { VistaAero, VistaBasic, Classic, Dirty }; static VistaState vistaState(); static int titleBarSize() { return frameSize() + captionSize(); } static int topPadding() { return 8; } static int topOffset() { return titleBarSize() + (vistaState() == VistaAero ? 13 : 3); } private: static HFONT getCaptionFont(HANDLE hTheme); bool drawTitleText(QPainter *painter, const QString &text, const QRect &rect, HDC hdc); static bool drawBlackRect(const QRect &rect, HDC hdc); static int frameSize() { return GetSystemMetrics(SM_CYSIZEFRAME); } static int captionSize() { return GetSystemMetrics(SM_CYCAPTION); } static int backButtonSize() { return 31; } // ### should be queried from back button itself static int iconSize() { return 16; } // Standard Aero static int padding() { return 7; } // Standard Aero static int leftMargin() { return backButtonSize() + padding(); } static int glowSize() { return 10; } int titleOffset(); bool resolveSymbols(); void drawTitleBar(QPainter *painter); void setMouseCursor(QPoint pos); void collapseTopFrameStrut(); bool winEvent(MSG *message, long *result); void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); bool eventFilter(QObject *obj, QEvent *event); static bool is_vista; static VistaState cachedVistaState; static bool isCompositionEnabled(); static bool isThemeActive(); enum Changes { resizeTop, movePosition, noChange } change; QPoint pressedPos; bool pressed; QRect rtTop; QRect rtTitle; QWizard *wizard; QVistaBackButton *backButton_; }; QT_END_NAMESPACE #endif // QT_NO_STYLE_WINDOWSVISTA #endif // QT_NO_WIZARD #endif // QWIZARD_WIN_P_H
igor-sfdc/qt-wk
src/gui/dialogs/qwizard_win_p.h
C
lgpl-2.1
4,873
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.objects; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.xpn.xwiki.web.Utils; /** * @version $Id$ */ // TODO: shouldn't this be abstract? toFormString and toText // will never work unless getValue is overriden public class BaseProperty extends BaseElement implements PropertyInterface, Serializable, Cloneable { private BaseCollection object; private int id; /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#getObject() */ public BaseCollection getObject() { return this.object; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#setObject(com.xpn.xwiki.objects.BaseCollection) */ public void setObject(BaseCollection object) { this.object = object; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.BaseElement#equals(java.lang.Object) */ @Override public boolean equals(Object el) { // Same Java object, they sure are equal if (this == el) { return true; } // I hate this.. needed for hibernate to find the object // when loading the collections.. if ((this.object == null) || ((BaseProperty) el).getObject() == null) { return (hashCode() == el.hashCode()); } if (!super.equals(el)) { return false; } return (getId() == ((BaseProperty) el).getId()); } public int getId() { // I hate this.. needed for hibernate to find the object // when loading the collections.. if (this.object == null) { return this.id; } else { return getObject().getId(); } } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#setId(int) */ public void setId(int id) { // I hate this.. needed for hibernate to find the object // when loading the collections.. this.id = id; } /** * {@inheritDoc} * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { // I hate this.. needed for hibernate to find the object // when loading the collections.. return ("" + getId() + getName()).hashCode(); } public String getClassType() { return getClass().getName(); } public void setClassType(String type) { } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.BaseElement#clone() */ @Override public Object clone() { BaseProperty property = (BaseProperty) super.clone(); property.setObject(getObject()); return property; } public Object getValue() { return null; } public void setValue(Object value) { } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#toXML() */ public Element toXML() { Element el = new DOMElement(getName()); Object value = getValue(); el.setText((value == null) ? "" : value.toString()); return el; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#toFormString() */ public String toFormString() { return Utils.formEncode(toText()); } public String toText() { Object value = getValue(); return (value == null) ? "" : value.toString(); } public String toXMLString() { Document doc = new DOMDocument(); doc.setRootElement(toXML()); OutputFormat outputFormat = new OutputFormat("", true); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return toXMLString(); } public Object getCustomMappingValue() { return getValue(); } }
xwiki-contrib/sankoreorg
xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/objects/BaseProperty.java
Java
lgpl-2.1
5,379
// --------------------------------------------------------------------- // // Copyright (C) 1999 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- //TODO: Do neighbors for dx and povray smooth triangles ////////////////////////////////////////////////////////////////////// // Remarks on the implementations // // Variable names: in most functions, variable names have been // standardized in the following way: // // n1, n2, ni Number of points in coordinate direction 1, 2, i // will be 1 if i>=dim // // i1, i2, ii Loop variable running up to ni // // d1, d2, di Multiplicators for ii to find positions in the // array of nodes. ////////////////////////////////////////////////////////////////////// #include <deal.II/base/data_out_base.h> #include <deal.II/base/utilities.h> #include <deal.II/base/parameter_handler.h> #include <deal.II/base/thread_management.h> #include <deal.II/base/memory_consumption.h> #include <deal.II/base/std_cxx11/shared_ptr.h> #include <deal.II/base/mpi.h> #include <cstring> #include <algorithm> #include <iomanip> #include <ctime> #include <cmath> #include <set> #include <sstream> #include <fstream> // we use uint32_t and uint8_t below, which are declared here: #include <stdint.h> #ifdef DEAL_II_WITH_ZLIB # include <zlib.h> #endif #ifdef DEAL_II_WITH_HDF5 #include <hdf5.h> #endif DEAL_II_NAMESPACE_OPEN // we need the following exception from a global function, so can't declare it // in the usual way inside a class namespace { DeclException2 (ExcUnexpectedInput, std::string, std::string, << "Unexpected input: expected line\n <" << arg1 << ">\nbut got\n <" << arg2 << ">"); } namespace { #ifdef DEAL_II_WITH_ZLIB // the functions in this namespace are // taken from the libb64 project, see // http://sourceforge.net/projects/libb64 // // libb64 has been placed in the public // domain namespace base64 { typedef enum { step_A, step_B, step_C } base64_encodestep; typedef struct { base64_encodestep step; char result; } base64_encodestate; void base64_init_encodestate(base64_encodestate *state_in) { state_in->step = step_A; state_in->result = 0; } inline char base64_encode_value(char value_in) { static const char *encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; if (value_in > 63) return '='; return encoding[(int)value_in]; } int base64_encode_block(const char *plaintext_in, int length_in, char *code_out, base64_encodestate *state_in) { const char *plainchar = plaintext_in; const char *const plaintextend = plaintext_in + length_in; char *codechar = code_out; char result; char fragment; result = state_in->result; switch (state_in->step) { while (1) { case step_A: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_A; return codechar - code_out; } fragment = *plainchar++; result = (fragment & 0x0fc) >> 2; *codechar++ = base64_encode_value(result); result = (fragment & 0x003) << 4; case step_B: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_B; return codechar - code_out; } fragment = *plainchar++; result |= (fragment & 0x0f0) >> 4; *codechar++ = base64_encode_value(result); result = (fragment & 0x00f) << 2; case step_C: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_C; return codechar - code_out; } fragment = *plainchar++; result |= (fragment & 0x0c0) >> 6; *codechar++ = base64_encode_value(result); result = (fragment & 0x03f) >> 0; *codechar++ = base64_encode_value(result); } } /* control should not reach here */ return codechar - code_out; } int base64_encode_blockend(char *code_out, base64_encodestate *state_in) { char *codechar = code_out; switch (state_in->step) { case step_B: *codechar++ = base64_encode_value(state_in->result); *codechar++ = '='; *codechar++ = '='; break; case step_C: *codechar++ = base64_encode_value(state_in->result); *codechar++ = '='; break; case step_A: break; } *codechar++ = '\0'; return codechar - code_out; } } /** * Do a base64 encoding of the given data. * * The function allocates memory as * necessary and returns a pointer to * it. The calling function must release * this memory again. */ char * encode_block (const char *data, const int data_size) { base64::base64_encodestate state; base64::base64_init_encodestate(&state); char *encoded_data = new char[2*data_size+1]; const int encoded_length_data = base64::base64_encode_block (data, data_size, encoded_data, &state); base64::base64_encode_blockend (encoded_data + encoded_length_data, &state); return encoded_data; } #endif #ifdef DEAL_II_WITH_ZLIB /** * Do a zlib compression followed * by a base64 encoding of the * given data. The result is then * written to the given stream. */ template <typename T> void write_compressed_block (const std::vector<T> &data, std::ostream &output_stream) { if (data.size() != 0) { // allocate a buffer for compressing // data and do so uLongf compressed_data_length = compressBound (data.size() * sizeof(T)); char *compressed_data = new char[compressed_data_length]; int err = compress2 ((Bytef *) compressed_data, &compressed_data_length, (const Bytef *) &data[0], data.size() * sizeof(T), Z_BEST_COMPRESSION); (void)err; Assert (err == Z_OK, ExcInternalError()); // now encode the compression header const uint32_t compression_header[4] = { 1, /* number of blocks */ (uint32_t)(data.size() * sizeof(T)), /* size of block */ (uint32_t)(data.size() * sizeof(T)), /* size of last block */ (uint32_t)compressed_data_length }; /* list of compressed sizes of blocks */ char *encoded_header = encode_block ((char *)&compression_header[0], 4 * sizeof(compression_header[0])); output_stream << encoded_header; delete[] encoded_header; // next do the compressed // data encoding in base64 char *encoded_data = encode_block (compressed_data, compressed_data_length); delete[] compressed_data; output_stream << encoded_data; delete[] encoded_data; } } #endif } // some declarations of functions and locally used classes namespace DataOutBase { namespace { /** * Class holding the data of one cell of a patch in two space * dimensions for output. It is the projection of a cell in * three-dimensional space (two coordinates, one height value) to * the direction of sight. */ class SvgCell { public: // Center of the cell (three-dimensional) Point<3> center; /** * Vector of vertices of this cell (three-dimensional) */ Point<3> vertices[4]; /** * Depth into the picture, which is defined as the distance from * an observer at an the origin in direction of the line of sight. */ float depth; /** * Vector of vertices of this cell (projected, two-dimensional). */ Point<2> projected_vertices[4]; // Center of the cell (projected, two-dimensional) Point<2> projected_center; /** * Comparison operator for sorting. */ bool operator < (const SvgCell &) const; }; bool SvgCell::operator < (const SvgCell &e) const { // note the "wrong" order in // which we sort the elements return depth > e.depth; } /** * Class holding the data of one cell of a patch in two space * dimensions for output. It is the projection of a cell in * three-dimensional space (two coordinates, one height value) to * the direction of sight. */ class EpsCell2d { public: /** * Vector of vertices of this cell. */ Point<2> vertices[4]; /** * Data value from which the actual colors will be computed by the * colorization function stated in the <tt>EpsFlags</tt> class. */ float color_value; /** * Depth into the picture, which is defined as the distance from * an observer at an the origin in direction of the line of sight. */ float depth; /** * Comparison operator for sorting. */ bool operator < (const EpsCell2d &) const; }; /** * This is a helper function for the write_gmv() function. There, * the data in the patches needs to be copied around as output is * one variable globally at a time, rather than all data on each * vertex at a time. This copying around can be done detached from * the main thread, and is thus moved into this separate function. * * Note that because of the similarity of the formats, this function * is also used by the Vtk and Tecplot output functions. */ template <int dim, int spacedim> void write_gmv_reorder_data_vectors (const std::vector<Patch<dim,spacedim> > &patches, Table<2,double> &data_vectors) { // unlike in the main function, we // don't have here the data_names // field, so we initialize it with // the number of data sets in the // first patch. the equivalence of // these two definitions is checked // in the main function. // we have to take care, however, whether the // points are appended to the end of the // patch->data table const unsigned int n_data_sets =patches[0].points_are_available ? (patches[0].data.n_rows() - spacedim) : patches[0].data.n_rows(); Assert (data_vectors.size()[0] == n_data_sets, ExcInternalError()); // loop over all patches unsigned int next_value = 0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; (void)n_subdivisions; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert ((n_data_sets == 0) || (patch->data.n_cols() == Utilities::fixed_power<dim>(n_subdivisions+1)), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); for (unsigned int i=0; i<patch->data.n_cols(); ++i, ++next_value) for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) data_vectors[data_set][next_value] = patch->data(data_set,i); } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) Assert (data_vectors[data_set].size() == next_value, ExcInternalError()); } } } //----------------------------------------------------------------------// // DataOutFilter class member functions //----------------------------------------------------------------------// template<int dim> void DataOutBase::DataOutFilter::write_point(const unsigned int &index, const Point<dim> &p) { Map3DPoint::const_iterator it; unsigned int internal_ind; Point<3> int_pt; for (int d=0; d<3; ++d) int_pt(d) = (d < dim ? p(d) : 0); node_dim = dim; it = existing_points.find(int_pt); // If the point isn't in the set, or we're not filtering duplicate points, add it if (it == existing_points.end() || !flags.filter_duplicate_vertices) { internal_ind = existing_points.size(); existing_points.insert(std::make_pair(int_pt, internal_ind)); } else { internal_ind = it->second; } // Now add the index to the list of filtered points filtered_points[index] = internal_ind; } void DataOutBase::DataOutFilter::internal_add_cell(const unsigned int &cell_index, const unsigned int &pt_index) { filtered_cells[cell_index] = filtered_points[pt_index]; } void DataOutBase::DataOutFilter::fill_node_data(std::vector<double> &node_data) const { Map3DPoint::const_iterator it; node_data.resize(existing_points.size()*node_dim); for (it=existing_points.begin(); it!=existing_points.end(); ++it) { for (int d=0; d<node_dim; ++d) node_data[node_dim*it->second+d] = it->first(d); } } void DataOutBase::DataOutFilter::fill_cell_data(const unsigned int &local_node_offset, std::vector<unsigned int> &cell_data) const { std::map<unsigned int, unsigned int>::const_iterator it; cell_data.resize(filtered_cells.size()); for (it=filtered_cells.begin(); it!=filtered_cells.end(); ++it) { cell_data[it->first] = it->second+local_node_offset; } } template<int dim> void DataOutBase::DataOutFilter::write_cell( unsigned int index, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { unsigned int base_entry = index * GeometryInfo<dim>::vertices_per_cell; n_cell_verts = GeometryInfo<dim>::vertices_per_cell; internal_add_cell(base_entry+0, start); internal_add_cell(base_entry+1, start+d1); if (dim>=2) { internal_add_cell(base_entry+2, start+d2+d1); internal_add_cell(base_entry+3, start+d2); if (dim>=3) { internal_add_cell(base_entry+4, start+d3); internal_add_cell(base_entry+5, start+d3+d1); internal_add_cell(base_entry+6, start+d3+d2+d1); internal_add_cell(base_entry+7, start+d3+d2); } } } void DataOutBase::DataOutFilter::write_data_set(const std::string &name, const unsigned int &dimension, const unsigned int &set_num, const Table<2,double> &data_vectors) { unsigned int num_verts = existing_points.size(); unsigned int i, r, d, new_dim; // HDF5/XDMF output only supports 1D or 3D output, so force rearrangement if needed if (flags.xdmf_hdf5_output && dimension != 1) new_dim = 3; else new_dim = dimension; // Record the data set name, dimension, and allocate space for it data_set_names.push_back(name); data_set_dims.push_back(new_dim); data_sets.push_back(std::vector<double>(new_dim*num_verts)); // TODO: averaging, min/max, etc for merged vertices for (i=0; i<filtered_points.size(); ++i) { for (d=0; d<new_dim; ++d) { r = filtered_points[i]; if (d < dimension) data_sets.back()[r*new_dim+d] = data_vectors(set_num+d, i); else data_sets.back()[r*new_dim+d] = 0; } } } //----------------------------------------------------------------------// //Auxiliary data //----------------------------------------------------------------------// namespace { const char *gmv_cell_type[4] = { "", "line 2", "quad 4", "hex 8" }; const char *ucd_cell_type[4] = { "", "line", "quad", "hex" }; const char *tecplot_cell_type[4] = { "", "lineseg", "quadrilateral", "brick" }; #ifdef DEAL_II_HAVE_TECPLOT const unsigned int tecplot_binary_cell_type[4] = { 0, 0, 1, 3 }; #endif // NOTE: The dimension of the array is choosen to 5 to allow the choice // DataOutBase<deal_II_dimension,deal_II_dimension+1> in general // Wolfgang supposed that we don't need it in general, but however this // choice avoids a -Warray-bounds check warning const unsigned int vtk_cell_type[5] = { 0, 3, 9, 12, static_cast<unsigned int>(-1) }; //----------------------------------------------------------------------// //Auxiliary functions //----------------------------------------------------------------------// //For a given patch, compute the node interpolating the corner nodes //linearly at the point (xstep, ystep, zstep)*1./n_subdivisions. //If the points are saved in the patch->data member, return the //saved point instead //TODO: Make this function return its value, rather than using a reference // as first argument; take a reference for 'patch', not a pointer template <int dim, int spacedim> inline void compute_node( Point<spacedim> &node, const DataOutBase::Patch<dim,spacedim> *patch, const unsigned int xstep, const unsigned int ystep, const unsigned int zstep, const unsigned int n_subdivisions) { if (patch->points_are_available) { unsigned int point_no=0; // note: switch without break ! switch (dim) { case 3: Assert (zstep<n_subdivisions+1, ExcIndexRange(zstep,0,n_subdivisions+1)); point_no+=(n_subdivisions+1)*(n_subdivisions+1)*zstep; case 2: Assert (ystep<n_subdivisions+1, ExcIndexRange(ystep,0,n_subdivisions+1)); point_no+=(n_subdivisions+1)*ystep; case 1: Assert (xstep<n_subdivisions+1, ExcIndexRange(xstep,0,n_subdivisions+1)); point_no+=xstep; // break here for dim<=3 break; default: Assert (false, ExcNotImplemented()); } for (unsigned int d=0; d<spacedim; ++d) node[d]=patch->data(patch->data.size(0)-spacedim+d,point_no); } else { // perform a dim-linear interpolation const double stepsize=1./n_subdivisions, xfrac=xstep*stepsize; node = (patch->vertices[1] * xfrac) + (patch->vertices[0] * (1-xfrac)); if (dim>1) { const double yfrac=ystep*stepsize; node*= 1-yfrac; node += ((patch->vertices[3] * xfrac) + (patch->vertices[2] * (1-xfrac))) * yfrac; if (dim>2) { const double zfrac=zstep*stepsize; node *= (1-zfrac); node += (((patch->vertices[5] * xfrac) + (patch->vertices[4] * (1-xfrac))) * (1-yfrac) + ((patch->vertices[7] * xfrac) + (patch->vertices[6] * (1-xfrac))) * yfrac) * zfrac; } } } } template<int dim, int spacedim> static void compute_sizes(const std::vector<DataOutBase::Patch<dim, spacedim> > &patches, unsigned int &n_nodes, unsigned int &n_cells) { n_nodes = 0; n_cells = 0; for (typename std::vector<DataOutBase::Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { n_nodes += Utilities::fixed_power<dim>(patch->n_subdivisions+1); n_cells += Utilities::fixed_power<dim>(patch->n_subdivisions); } } /** * Class for writing basic * entities in @ref * SoftwareOpenDX format, * depending on the flags. */ class DXStream { public: /** * Constructor, storing * persistent values for * later use. */ DXStream (std::ostream &stream, const DataOutBase::DXFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,2,1,3] * <li> [0,4,2,6,1,5,3,7] * </ol> */ template <int dim> void write_cell (const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Write a complete set of * data for a single node. * * The index given as first * argument indicates the * number of a data set, as * some output formats require * this number to be printed. */ template<typename data> void write_dataset (const unsigned int index, const std::vector<data> &values); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::DXFlags flags; }; /** * Class for writing basic * entities in @ref SoftwareGMV * format, depending on the * flags. */ class GmvStream { public: /** * Constructor, storing * persistent values for * later use. */ GmvStream (std::ostream &stream, const DataOutBase::GmvFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,1,3,2] * <li> [0,1,3,2,4,5,7,6] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); /** * Since GMV reads the x, y * and z coordinates in * separate fields, we enable * write() to output only a * single selected component * at once and do this dim * times for the whole set of * nodes. This integer can be * used to select the * component written. */ unsigned int selected_component; private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::GmvFlags flags; }; /** * Class for writing basic * entities in @ref * SoftwareTecplot format, * depending on the flags. */ class TecplotStream { public: /** * Constructor, storing * persistent values for * later use. */ TecplotStream (std::ostream &stream, const DataOutBase::TecplotFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,1,3,2] * <li> [0,1,3,2,4,5,7,6] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); /** * Since TECPLOT reads the x, y * and z coordinates in * separate fields, we enable * write() to output only a * single selected component * at once and do this dim * times for the whole set of * nodes. This integer can be * used to select the * component written. */ unsigned int selected_component; private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::TecplotFlags flags; }; /** * Class for writing basic * entities in UCD format for * @ref SoftwareAVS, depending on * the flags. */ class UcdStream { public: /** * Constructor, storing * persistent values for * later use. */ UcdStream (std::ostream &stream, const DataOutBase::UcdFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The additional offset 1 is * added inside this * function. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,1,3,2] * <li> [0,1,5,4,2,3,7,6] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Write a complete set of * data for a single node. * * The index given as first * argument indicates the * number of a data set, as * some output formats require * this number to be printed. */ template<typename data> void write_dataset (const unsigned int index, const std::vector<data> &values); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::UcdFlags flags; }; /** * Class for writing basic * entities in @ref SoftwareVTK * format, depending on the * flags. */ class VtkStream { public: /** * Constructor, storing * persistent values for * later use. */ VtkStream (std::ostream &stream, const DataOutBase::VtkFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [] * <li> [] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::VtkFlags flags; }; class VtuStream { public: /** * Constructor, storing * persistent values for * later use. */ VtuStream (std::ostream &stream, const DataOutBase::VtkFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [] * <li> [] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); /** * Forwarding of output stream. * * If libz was found during * configuration, this operator * compresses and encodes the * entire data * block. Otherwise, it simply * writes it element by * element. */ template <typename T> std::ostream &operator<< (const std::vector<T> &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::VtkFlags flags; /** * A list of vertices and * cells, to be used in case we * want to compress the data. * * The data types of these * arrays needs to match what * we print in the XML-preamble * to the respective parts of * VTU files (e.g. Float64 and * Int32) */ std::vector<double> vertices; std::vector<int32_t> cells; }; //----------------------------------------------------------------------// DXStream::DXStream(std::ostream &out, const DataOutBase::DXFlags f) : stream(out), flags(f) {} template<int dim> void DXStream::write_point (const unsigned int, const Point<dim> &p) { if (flags.coordinates_binary) { float data[dim]; for (unsigned int d=0; d<dim; ++d) data[d] = p(d); stream.write(reinterpret_cast<const char *>(data), dim * sizeof(*data)); } else { for (unsigned int d=0; d<dim; ++d) stream << p(d) << '\t'; stream << '\n'; } } void DXStream::flush_points () {} template<int dim> void DXStream::write_cell( unsigned int, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { int nodes[1<<dim]; nodes[GeometryInfo<dim>::dx_to_deal[0]] = start; nodes[GeometryInfo<dim>::dx_to_deal[1]] = start+d1; if (dim>=2) { // Add shifted line in y direction nodes[GeometryInfo<dim>::dx_to_deal[2]] = start+d2; nodes[GeometryInfo<dim>::dx_to_deal[3]] = start+d2+d1; if (dim>=3) { // Add shifted quad in z direction nodes[GeometryInfo<dim>::dx_to_deal[4]] = start+d3; nodes[GeometryInfo<dim>::dx_to_deal[5]] = start+d3+d1; nodes[GeometryInfo<dim>::dx_to_deal[6]] = start+d3+d2; nodes[GeometryInfo<dim>::dx_to_deal[7]] = start+d3+d2+d1; } } if (flags.int_binary) stream.write(reinterpret_cast<const char *>(nodes), (1<<dim) * sizeof(*nodes)); else { const unsigned int final = (1<<dim) - 1; for (unsigned int i=0; i<final ; ++i) stream << nodes[i] << '\t'; stream << nodes[final] << '\n'; } } void DXStream::flush_cells () {} template<typename data> inline void DXStream::write_dataset(const unsigned int /*index*/, const std::vector<data> &values) { if (flags.data_binary) { stream.write(reinterpret_cast<const char *>(&values[0]), values.size()*sizeof(data)); } else { for (unsigned int i=0; i<values.size(); ++i) stream << '\t' << values[i]; stream << '\n'; } } //----------------------------------------------------------------------// GmvStream::GmvStream (std::ostream &out, const DataOutBase::GmvFlags f) : selected_component(numbers::invalid_unsigned_int), stream(out), flags(f) {} template<int dim> void GmvStream::write_point (const unsigned int, const Point<dim> &p) { Assert(selected_component != numbers::invalid_unsigned_int, ExcNotInitialized()); stream << p(selected_component) << ' '; } void GmvStream::flush_points () {} template<int dim> void GmvStream::write_cell( unsigned int, unsigned int s, unsigned int d1, unsigned int d2, unsigned int d3) { // Vertices are numbered starting // with one. const unsigned int start=s+1; stream << gmv_cell_type[dim] << '\n'; stream << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; } void GmvStream::flush_cells () {} //----------------------------------------------------------------------// TecplotStream::TecplotStream(std::ostream &out, const DataOutBase::TecplotFlags f) : selected_component(numbers::invalid_unsigned_int), stream(out), flags(f) {} template<int dim> void TecplotStream::write_point (const unsigned int, const Point<dim> &p) { Assert(selected_component != numbers::invalid_unsigned_int, ExcNotInitialized()); stream << p(selected_component) << '\n'; } void TecplotStream::flush_points () {} template<int dim> void TecplotStream::write_cell( unsigned int, unsigned int s, unsigned int d1, unsigned int d2, unsigned int d3) { const unsigned int start = s+1; stream << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; } void TecplotStream::flush_cells () {} //----------------------------------------------------------------------// UcdStream::UcdStream(std::ostream &out, const DataOutBase::UcdFlags f) : stream(out), flags(f) {} template<int dim> void UcdStream::write_point (const unsigned int index, const Point<dim> &p) { stream << index+1 << " "; // write out coordinates for (unsigned int i=0; i<dim; ++i) stream << p(i) << ' '; // fill with zeroes for (unsigned int i=dim; i<3; ++i) stream << "0 "; stream << '\n'; } void UcdStream::flush_points () {} template<int dim> void UcdStream::write_cell( unsigned int index, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { int nodes[1<<dim]; nodes[GeometryInfo<dim>::ucd_to_deal[0]] = start; nodes[GeometryInfo<dim>::ucd_to_deal[1]] = start+d1; if (dim>=2) { // Add shifted line in y direction nodes[GeometryInfo<dim>::ucd_to_deal[2]] = start+d2; nodes[GeometryInfo<dim>::ucd_to_deal[3]] = start+d2+d1; if (dim>=3) { // Add shifted quad in z direction nodes[GeometryInfo<dim>::ucd_to_deal[4]] = start+d3; nodes[GeometryInfo<dim>::ucd_to_deal[5]] = start+d3+d1; nodes[GeometryInfo<dim>::ucd_to_deal[6]] = start+d3+d2; nodes[GeometryInfo<dim>::ucd_to_deal[7]] = start+d3+d2+d1; } } // Write out all cells and remember // that all indices must be shifted // by one. stream << index+1 << "\t0 " << ucd_cell_type[dim]; const unsigned int final = (1<<dim); for (unsigned int i=0; i<final ; ++i) stream << '\t' << nodes[i]+1; stream << '\n'; } void UcdStream::flush_cells () {} template<typename data> inline void UcdStream::write_dataset(const unsigned int index, const std::vector<data> &values) { stream << index+1; for (unsigned int i=0; i<values.size(); ++i) stream << '\t' << values[i]; stream << '\n'; } //----------------------------------------------------------------------// VtkStream::VtkStream(std::ostream &out, const DataOutBase::VtkFlags f) : stream(out), flags(f) {} template<int dim> void VtkStream::write_point (const unsigned int, const Point<dim> &p) { // write out coordinates stream << p; // fill with zeroes for (unsigned int i=dim; i<3; ++i) stream << " 0"; stream << '\n'; } void VtkStream::flush_points () {} template<int dim> void VtkStream::write_cell( unsigned int, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { stream << GeometryInfo<dim>::vertices_per_cell << '\t' << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; } void VtkStream::flush_cells () {} VtuStream::VtuStream(std::ostream &out, const DataOutBase::VtkFlags f) : stream(out), flags(f) {} template<int dim> void VtuStream::write_point (const unsigned int, const Point<dim> &p) { #if !defined(DEAL_II_WITH_ZLIB) // write out coordinates stream << p; // fill with zeroes for (unsigned int i=dim; i<3; ++i) stream << " 0"; stream << '\n'; #else // if we want to compress, then // first collect all the data in // an array for (unsigned int i=0; i<dim; ++i) vertices.push_back(p[i]); for (unsigned int i=dim; i<3; ++i) vertices.push_back(0); #endif } void VtuStream::flush_points () { #ifdef DEAL_II_WITH_ZLIB // compress the data we have in // memory and write them to the // stream. then release the data *this << vertices << '\n'; vertices.clear (); #endif } template<int dim> void VtuStream::write_cell( unsigned int, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { #if !defined(DEAL_II_WITH_ZLIB) stream << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; #else cells.push_back (start); cells.push_back (start+d1); if (dim>=2) { cells.push_back (start+d2+d1); cells.push_back (start+d2); if (dim>=3) { cells.push_back (start+d3); cells.push_back (start+d3+d1); cells.push_back (start+d3+d2+d1); cells.push_back (start+d3+d2); } } #endif } void VtuStream::flush_cells () { #ifdef DEAL_II_WITH_ZLIB // compress the data we have in // memory and write them to the // stream. then release the data *this << cells << '\n'; cells.clear (); #endif } template <typename T> std::ostream & VtuStream::operator<< (const std::vector<T> &data) { #ifdef DEAL_II_WITH_ZLIB // compress the data we have in // memory and write them to the // stream. then release the data write_compressed_block (data, stream); #else for (unsigned int i=0; i<data.size(); ++i) stream << data[i] << ' '; #endif return stream; } template <typename T> std::ostream & DXStream::operator<< (const T &t) { stream << t; return stream; } template <typename T> std::ostream & GmvStream::operator<< (const T &t) { stream << t; return stream; } template <typename T> std::ostream & UcdStream::operator<< (const T &t) { stream << t; return stream; } template <typename T> std::ostream & VtkStream::operator<< (const T &t) { stream << t; return stream; } } //----------------------------------------------------------------------// namespace DataOutBase { template <int dim, int spacedim> const unsigned int Patch<dim,spacedim>::space_dim; const unsigned int Deal_II_IntermediateFlags::format_version; template <int dim, int spacedim> const unsigned int Patch<dim,spacedim>::no_neighbor; template <int dim, int spacedim> Patch<dim,spacedim>::Patch () : patch_index(no_neighbor), n_subdivisions (1), points_are_available(false) // all the other data has a // constructor of its own, except // for the "neighbors" field, which // we set to invalid values. { for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) neighbors[i] = no_neighbor; Assert (dim<=spacedim, ExcIndexRange(dim,0,spacedim)); Assert (spacedim<=3, ExcNotImplemented()); } template <int dim, int spacedim> bool Patch<dim,spacedim>::operator == (const Patch &patch) const { //TODO: make tolerance relative const double epsilon=3e-16; for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i) if (vertices[i].distance(patch.vertices[i]) > epsilon) return false; for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) if (neighbors[i] != patch.neighbors[i]) return false; if (patch_index != patch.patch_index) return false; if (n_subdivisions != patch.n_subdivisions) return false; if (points_are_available != patch.points_are_available) return false; if (data.n_rows() != patch.data.n_rows()) return false; if (data.n_cols() != patch.data.n_cols()) return false; for (unsigned int i=0; i<data.n_rows(); ++i) for (unsigned int j=0; j<data.n_cols(); ++j) if (data[i][j] != patch.data[i][j]) return false; return true; } template <int dim, int spacedim> std::size_t Patch<dim,spacedim>::memory_consumption () const { return (sizeof(vertices) / sizeof(vertices[0]) * MemoryConsumption::memory_consumption(vertices[0]) + MemoryConsumption::memory_consumption(n_subdivisions) + MemoryConsumption::memory_consumption(data) + MemoryConsumption::memory_consumption(points_are_available)); } UcdFlags::UcdFlags (const bool write_preamble) : write_preamble (write_preamble) {} PovrayFlags::PovrayFlags (const bool smooth, const bool bicubic_patch, const bool external_data) : smooth (smooth), bicubic_patch(bicubic_patch), external_data(external_data) {} DataOutFilterFlags::DataOutFilterFlags (const bool filter_duplicate_vertices, const bool xdmf_hdf5_output) : filter_duplicate_vertices(filter_duplicate_vertices), xdmf_hdf5_output(xdmf_hdf5_output) {} void DataOutFilterFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Filter duplicate vertices", "false", Patterns::Bool(), "Whether to remove duplicate vertex values."); prm.declare_entry ("XDMF HDF5 output", "false", Patterns::Bool(), "Whether the data will be used in an XDMF/HDF5 combination."); } void DataOutFilterFlags::parse_parameters (const ParameterHandler &prm) { filter_duplicate_vertices = prm.get_bool ("Filter duplicate vertices"); xdmf_hdf5_output = prm.get_bool ("XDMF HDF5 output"); } std::size_t DataOutFilterFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } DXFlags::DXFlags (const bool write_neighbors, const bool int_binary, const bool coordinates_binary, const bool data_binary) : write_neighbors(write_neighbors), int_binary(int_binary), coordinates_binary(coordinates_binary), data_binary(data_binary), data_double(false) {} void DXFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Write neighbors", "true", Patterns::Bool(), "A boolean field indicating whether neighborship " "information between cells is to be written to the " "OpenDX output file"); prm.declare_entry ("Integer format", "ascii", Patterns::Selection("ascii|32|64"), "Output format of integer numbers, which is " "either a text representation (ascii) or binary integer " "values of 32 or 64 bits length"); prm.declare_entry ("Coordinates format", "ascii", Patterns::Selection("ascii|32|64"), "Output format of vertex coordinates, which is " "either a text representation (ascii) or binary " "floating point values of 32 or 64 bits length"); prm.declare_entry ("Data format", "ascii", Patterns::Selection("ascii|32|64"), "Output format of data values, which is " "either a text representation (ascii) or binary " "floating point values of 32 or 64 bits length"); } void DXFlags::parse_parameters (const ParameterHandler &prm) { write_neighbors = prm.get_bool ("Write neighbors"); //TODO:[GK] Read the new parameters } std::size_t DXFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } void UcdFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Write preamble", "true", Patterns::Bool(), "A flag indicating whether a comment should be " "written to the beginning of the output file " "indicating date and time of creation as well " "as the creating program"); } void UcdFlags::parse_parameters (const ParameterHandler &prm) { write_preamble = prm.get_bool ("Write preamble"); } std::size_t UcdFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } GnuplotFlags::GnuplotFlags () : dummy (0) {} void GnuplotFlags::declare_parameters (ParameterHandler &/*prm*/) {} void GnuplotFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} size_t GnuplotFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } SvgFlags::SvgFlags (const unsigned int height_vector, const int azimuth_angle, const int polar_angle, const unsigned int line_thickness, const bool margin, const bool draw_colorbar) : height(4000), width(0), height_vector(height_vector), azimuth_angle(azimuth_angle), polar_angle(polar_angle), line_thickness(line_thickness), margin(margin), draw_colorbar(draw_colorbar) {} std::size_t SvgFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } void PovrayFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Use smooth triangles", "false", Patterns::Bool(), "A flag indicating whether POVRAY should use smoothed " "triangles instead of the usual ones"); prm.declare_entry ("Use bicubic patches", "false", Patterns::Bool(), "Whether POVRAY should use bicubic patches"); prm.declare_entry ("Include external file", "true", Patterns::Bool (), "Whether camera and lightling information should " "be put into an external file \"data.inc\" or into " "the POVRAY input file"); } void PovrayFlags::parse_parameters (const ParameterHandler &prm) { smooth = prm.get_bool ("Use smooth triangles"); bicubic_patch = prm.get_bool ("Use bicubic patches"); external_data = prm.get_bool ("Include external file"); } std::size_t PovrayFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } EpsFlags::EpsFlags (const unsigned int height_vector, const unsigned int color_vector, const SizeType size_type, const unsigned int size, const double line_width, const double azimut_angle, const double turn_angle, const double z_scaling, const bool draw_mesh, const bool draw_cells, const bool shade_cells, const ColorFunction color_function) : height_vector(height_vector), color_vector(color_vector), size_type(size_type), size(size), line_width(line_width), azimut_angle(azimut_angle), turn_angle(turn_angle), z_scaling(z_scaling), draw_mesh(draw_mesh), draw_cells(draw_cells), shade_cells(shade_cells), color_function(color_function) {} EpsFlags::RgbValues EpsFlags::default_color_function (const double x, const double xmin, const double xmax) { RgbValues rgb_values = { 0,0,0 }; // A difficult color scale: // xmin = black (1) // 3/4*xmin+1/4*xmax = blue (2) // 1/2*xmin+1/2*xmax = green (3) // 1/4*xmin+3/4*xmax = red (4) // xmax = white (5) // Makes the following color functions: // // red green blue // __ // / /\ / /\ / // ____/ __/ \/ / \__/ // { 0 (1) - (3) // r = { ( 4*x-2*xmin+2*xmax)/(xmax-xmin) (3) - (4) // { 1 (4) - (5) // // { 0 (1) - (2) // g = { ( 4*x-3*xmin- xmax)/(xmax-xmin) (2) - (3) // { (-4*x+ xmin+3*xmax)/(xmax-xmin) (3) - (4) // { ( 4*x- xmin-3*xmax)/(xmax-xmin) (4) - (5) // // { ( 4*x-4*xmin )/(xmax-xmin) (1) - (2) // b = { (-4*x+2*xmin+2*xmax)/(xmax-xmin) (2) - (3) // { 0 (3) - (4) // { ( 4*x- xmin-3*xmax)/(xmax-xmin) (4) - (5) double sum = xmax+ xmin; double sum13 = xmin+3*xmax; double sum22 = 2*xmin+2*xmax; double sum31 = 3*xmin+ xmax; double dif = xmax-xmin; double rezdif = 1.0/dif; int where; if (x<(sum31)/4) where = 0; else if (x<(sum22)/4) where = 1; else if (x<(sum13)/4) where = 2; else where = 3; if (dif!=0) { switch (where) { case 0: rgb_values.red = 0; rgb_values.green = 0; rgb_values.blue = (x-xmin)*4.*rezdif; break; case 1: rgb_values.red = 0; rgb_values.green = (4*x-3*xmin-xmax)*rezdif; rgb_values.blue = (sum22-4.*x)*rezdif; break; case 2: rgb_values.red = (4*x-2*sum)*rezdif; rgb_values.green = (xmin+3*xmax-4*x)*rezdif; rgb_values.blue = 0; break; case 3: rgb_values.red = 1; rgb_values.green = (4*x-xmin-3*xmax)*rezdif; rgb_values.blue = (4.*x-sum13)*rezdif; default: break; } } else // White rgb_values.red = rgb_values.green = rgb_values.blue = 1; return rgb_values; } EpsFlags::RgbValues EpsFlags::grey_scale_color_function (const double x, const double xmin, const double xmax) { EpsFlags::RgbValues rgb_values; rgb_values.red = rgb_values.blue = rgb_values.green = (x-xmin)/(xmax-xmin); return rgb_values; } EpsFlags::RgbValues EpsFlags::reverse_grey_scale_color_function (const double x, const double xmin, const double xmax) { EpsFlags::RgbValues rgb_values; rgb_values.red = rgb_values.blue = rgb_values.green = 1-(x-xmin)/(xmax-xmin); return rgb_values; } bool EpsCell2d::operator < (const EpsCell2d &e) const { // note the "wrong" order in // which we sort the elements return depth > e.depth; } void EpsFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Index of vector for height", "0", Patterns::Integer(), "Number of the input vector that is to be used to " "generate height information"); prm.declare_entry ("Index of vector for color", "0", Patterns::Integer(), "Number of the input vector that is to be used to " "generate color information"); prm.declare_entry ("Scale to width or height", "width", Patterns::Selection ("width|height"), "Whether width or height should be scaled to match " "the given size"); prm.declare_entry ("Size (width or height) in eps units", "300", Patterns::Integer(), "The size (width or height) to which the eps output " "file is to be scaled"); prm.declare_entry ("Line widths in eps units", "0.5", Patterns::Double(), "The width in which the postscript renderer is to " "plot lines"); prm.declare_entry ("Azimut angle", "60", Patterns::Double(0,180), "Angle of the viewing position against the vertical " "axis"); prm.declare_entry ("Turn angle", "30", Patterns::Double(0,360), "Angle of the viewing direction against the y-axis"); prm.declare_entry ("Scaling for z-axis", "1", Patterns::Double (), "Scaling for the z-direction relative to the scaling " "used in x- and y-directions"); prm.declare_entry ("Draw mesh lines", "true", Patterns::Bool(), "Whether the mesh lines, or only the surface should be " "drawn"); prm.declare_entry ("Fill interior of cells", "true", Patterns::Bool(), "Whether only the mesh lines, or also the interior of " "cells should be plotted. If this flag is false, then " "one can see through the mesh"); prm.declare_entry ("Color shading of interior of cells", "true", Patterns::Bool(), "Whether the interior of cells shall be shaded"); prm.declare_entry ("Color function", "default", Patterns::Selection ("default|grey scale|reverse grey scale"), "Name of a color function used to colorize mesh lines " "and/or cell interiors"); } void EpsFlags::parse_parameters (const ParameterHandler &prm) { height_vector = prm.get_integer ("Index of vector for height"); color_vector = prm.get_integer ("Index of vector for color"); if (prm.get ("Scale to width or height") == "width") size_type = width; else size_type = height; size = prm.get_integer ("Size (width or height) in eps units"); line_width = prm.get_double ("Line widths in eps units"); azimut_angle = prm.get_double ("Azimut angle"); turn_angle = prm.get_double ("Turn angle"); z_scaling = prm.get_double ("Scaling for z-axis"); draw_mesh = prm.get_bool ("Draw mesh lines"); draw_cells = prm.get_bool ("Fill interior of cells"); shade_cells = prm.get_bool ("Color shading of interior of cells"); if (prm.get("Color function") == "default") color_function = &default_color_function; else if (prm.get("Color function") == "grey scale") color_function = &grey_scale_color_function; else if (prm.get("Color function") == "reverse grey scale") color_function = &reverse_grey_scale_color_function; else // we shouldn't get here, since // the parameter object should // already have checked that the // given value is valid Assert (false, ExcInternalError()); } std::size_t EpsFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } GmvFlags::GmvFlags () {} void GmvFlags::declare_parameters (ParameterHandler &/*prm*/) {} void GmvFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t GmvFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } TecplotFlags:: TecplotFlags (const char *tecplot_binary_file_name, const char *zone_name) : tecplot_binary_file_name(tecplot_binary_file_name), zone_name(zone_name) {} void TecplotFlags::declare_parameters (ParameterHandler &/*prm*/) {} void TecplotFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t TecplotFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } VtkFlags::VtkFlags (const double time, const unsigned int cycle, const bool print_date_and_time) : time (time), cycle (cycle), print_date_and_time (print_date_and_time) {} void VtkFlags::declare_parameters (ParameterHandler &/*prm*/) {} void VtkFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t VtkFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } Deal_II_IntermediateFlags::Deal_II_IntermediateFlags () : dummy (0) {} void Deal_II_IntermediateFlags::declare_parameters (ParameterHandler &/*prm*/) {} void Deal_II_IntermediateFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t Deal_II_IntermediateFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } OutputFormat parse_output_format (const std::string &format_name) { if (format_name == "none") return none; if (format_name == "dx") return dx; if (format_name == "ucd") return ucd; if (format_name == "gnuplot") return gnuplot; if (format_name == "povray") return povray; if (format_name == "eps") return eps; if (format_name == "gmv") return gmv; if (format_name == "tecplot") return tecplot; if (format_name == "tecplot_binary") return tecplot_binary; if (format_name == "vtk") return vtk; if (format_name == "vtu") return vtu; if (format_name == "deal.II intermediate") return deal_II_intermediate; if (format_name == "hdf5") return hdf5; AssertThrow (false, ExcMessage ("The given file format name is not recognized: <" + format_name + ">")); // return something invalid return OutputFormat(-1); } std::string get_output_format_names () { return "none|dx|ucd|gnuplot|povray|eps|gmv|tecplot|tecplot_binary|vtk|vtu|hdf5|svg|deal.II intermediate"; } std::string default_suffix (const OutputFormat output_format) { switch (output_format) { case none: return ""; case dx: return ".dx"; case ucd: return ".inp"; case gnuplot: return ".gnuplot"; case povray: return ".pov"; case eps: return ".eps"; case gmv: return ".gmv"; case tecplot: return ".dat"; case tecplot_binary: return ".plt"; case vtk: return ".vtk"; case vtu: return ".vtu"; case deal_II_intermediate: return ".d2"; case hdf5: return ".h5"; case svg: return ".svg"; default: Assert (false, ExcNotImplemented()); return ""; } } //----------------------------------------------------------------------// template <int dim, int spacedim, typename STREAM> void write_nodes (const std::vector<Patch<dim,spacedim> > &patches, STREAM &out) { Assert (dim<=3, ExcNotImplemented()); unsigned int count = 0; // We only need this point below, // but it does not harm to declare // it here. Point<spacedim> node; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all // dimensions. If a dimension // is not used, a loop of // length one will do the job. const unsigned int n1 = (dim>0) ? n : 1; const unsigned int n2 = (dim>1) ? n : 1; const unsigned int n3 = (dim>2) ? n : 1; for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { compute_node(node, &*patch, i1, i2, i3, n_subdivisions); out.write_point(count++, node); } } out.flush_points (); } template <int dim, int spacedim, typename STREAM> void write_cells (const std::vector<Patch<dim,spacedim> > &patches, STREAM &out) { Assert (dim<=3, ExcNotImplemented()); unsigned int count = 0; unsigned int first_vertex_of_patch = 0; // Array to hold all the node // numbers of a cell. 8 is // sufficient for 3D for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all dimensons const unsigned int n1 = (dim>0) ? n_subdivisions : 1; const unsigned int n2 = (dim>1) ? n_subdivisions : 1; const unsigned int n3 = (dim>2) ? n_subdivisions : 1; // Offsets of outer loops unsigned int d1 = 1; unsigned int d2 = n; unsigned int d3 = n*n; for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { const unsigned int offset = first_vertex_of_patch+i3*d3+i2*d2+i1*d1; // First write line in x direction out.template write_cell<dim>(count++, offset, d1, d2, d3); } // finally update the number // of the first vertex of this patch first_vertex_of_patch += Utilities::fixed_power<dim>(n_subdivisions+1); } out.flush_cells (); } template <int dim, int spacedim, class STREAM> void write_data ( const std::vector<Patch<dim,spacedim> > &patches, unsigned int n_data_sets, const bool double_precision, STREAM &out) { Assert (dim<=3, ExcNotImplemented()); unsigned int count = 0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch = patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all dimensions Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n), ExcInvalidDatasetSize (patch->data.n_cols(), n)); std::vector<float> floats(n_data_sets); std::vector<double> doubles(n_data_sets); // Data is already in // lexicographic ordering for (unsigned int i=0; i<Utilities::fixed_power<dim>(n); ++i, ++count) if (double_precision) { for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) doubles[data_set] = patch->data(data_set, i); out.write_dataset(count, doubles); } else { for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) floats[data_set] = patch->data(data_set, i); out.write_dataset(count, floats); } } } namespace { /** * This function projects a three-dimensional point (Point<3> point) * onto a two-dimensional image plane, specified by the position of * the camera viewing system (Point<3> camera_position), camera * direction (Point<3> camera_position), camera horizontal (Point<3> * camera_horizontal, necessary for the correct alignment of the * later images), and the focus of the camera (float camera_focus). */ Point<2> svg_project_point(Point<3> point, Point<3> camera_position, Point<3> camera_direction, Point<3> camera_horizontal, float camera_focus) { Point<3> camera_vertical; camera_vertical[0] = camera_horizontal[1] * camera_direction[2] - camera_horizontal[2] * camera_direction[1]; camera_vertical[1] = camera_horizontal[2] * camera_direction[0] - camera_horizontal[0] * camera_direction[2]; camera_vertical[2] = camera_horizontal[0] * camera_direction[1] - camera_horizontal[1] * camera_direction[0]; float phi; phi = camera_focus; phi /= (point[0] - camera_position[0]) * camera_direction[0] + (point[1] - camera_position[1]) * camera_direction[1] + (point[2] - camera_position[2]) * camera_direction[2]; Point<3> projection; projection[0] = camera_position[0] + phi * (point[0] - camera_position[0]); projection[1] = camera_position[1] + phi * (point[1] - camera_position[1]); projection[2] = camera_position[2] + phi * (point[2] - camera_position[2]); Point<2> projection_decomposition; projection_decomposition[0] = (projection[0] - camera_position[0] - camera_focus * camera_direction[0]) * camera_horizontal[0]; projection_decomposition[0] += (projection[1] - camera_position[1] - camera_focus * camera_direction[1]) * camera_horizontal[1]; projection_decomposition[0] += (projection[2] - camera_position[2] - camera_focus * camera_direction[2]) * camera_horizontal[2]; projection_decomposition[1] = (projection[0] - camera_position[0] - camera_focus * camera_direction[0]) * camera_vertical[0]; projection_decomposition[1] += (projection[1] - camera_position[1] - camera_focus * camera_direction[1]) * camera_vertical[1]; projection_decomposition[1] += (projection[2] - camera_position[2] - camera_focus * camera_direction[2]) * camera_vertical[2]; return projection_decomposition; } /** * Function to compute the gradient parameters for a triangle with * given values for the vertices. */ Point<6> svg_get_gradient_parameters(Point<3> points[]) { Point<3> v_min, v_max, v_inter; // Use the Bubblesort algorithm to sort the points with respect to the third coordinate for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2-i; ++j) { if (points[j][2] > points[j + 1][2]) { Point<3> temp = points[j]; points[j] = points[j+1]; points[j+1] = temp; } } } // save the related three-dimensional vectors v_min, v_inter, and v_max v_min = points[0]; v_inter = points[1]; v_max = points[2]; Point<2> A[2]; Point<2> b, gradient; // determine the plane offset c A[0][0] = v_max[0] - v_min[0]; A[0][1] = v_inter[0] - v_min[0]; A[1][0] = v_max[1] - v_min[1]; A[1][1] = v_inter[1] - v_min[1]; b[0] = - v_min[0]; b[1] = - v_min[1]; double x, sum; bool col_change = false; if (A[0][0] == 0) { col_change = true; A[0][0] = A[0][1]; A[0][1] = 0; double temp = A[1][0]; A[1][0] = A[1][1]; A[1][1] = temp; } for (unsigned int k = 0; k < 1; k++) { for (unsigned int i = k+1; i < 2; i++) { x = A[i][k] / A[k][k]; for (unsigned int j = k+1; j < 2; j++) A[i][j] = A[i][j] - A[k][j] * x; b[i] = b[i] - b[k]*x; } } b[1] = b[1] / A[1][1]; for (int i = 0; i >= 0; i--) { sum = b[i]; for (unsigned int j = i+1; j < 2; j++) sum = sum - A[i][j] * b[j]; b[i] = sum / A[i][i]; } if (col_change) { double temp = b[0]; b[0] = b[1]; b[1] = temp; } double c = b[0] * (v_max[2] - v_min[2]) + b[1] * (v_inter[2] - v_min[2]) + v_min[2]; // Determine the first entry of the gradient (phi, cf. documentation) A[0][0] = v_max[0] - v_min[0]; A[0][1] = v_inter[0] - v_min[0]; A[1][0] = v_max[1] - v_min[1]; A[1][1] = v_inter[1] - v_min[1]; b[0] = 1.0 - v_min[0]; b[1] = - v_min[1]; col_change = false; if (A[0][0] == 0) { col_change = true; A[0][0] = A[0][1]; A[0][1] = 0; double temp = A[1][0]; A[1][0] = A[1][1]; A[1][1] = temp; } for (unsigned int k = 0; k < 1; k++) { for (unsigned int i = k+1; i < 2; i++) { x = A[i][k] / A[k][k]; for (unsigned int j = k+1; j < 2; j++) A[i][j] = A[i][j] - A[k][j] * x; b[i] = b[i] - b[k] * x; } } b[1]=b[1] / A[1][1]; for (int i = 0; i >= 0; i--) { sum = b[i]; for (unsigned int j = i+1; j < 2; j++) sum = sum - A[i][j]*b[j]; b[i] = sum / A[i][i]; } if (col_change) { double temp = b[0]; b[0] = b[1]; b[1] = temp; } gradient[0] = b[0] * (v_max[2] - v_min[2]) + b[1] * (v_inter[2] - v_min[2]) - c + v_min[2]; // determine the second entry of the gradient A[0][0] = v_max[0] - v_min[0]; A[0][1] = v_inter[0] - v_min[0]; A[1][0] = v_max[1] - v_min[1]; A[1][1] = v_inter[1] - v_min[1]; b[0] = - v_min[0]; b[1] = 1.0 - v_min[1]; col_change = false; if (A[0][0] == 0) { col_change = true; A[0][0] = A[0][1]; A[0][1] = 0; double temp = A[1][0]; A[1][0] = A[1][1]; A[1][1] = temp; } for (unsigned int k = 0; k < 1; k++) { for (unsigned int i = k+1; i < 2; i++) { x = A[i][k] / A[k][k]; for (unsigned int j = k+1; j < 2; j++) A[i][j] = A[i][j] - A[k][j] * x; b[i] = b[i] - b[k] * x; } } b[1] = b[1] / A[1][1]; for (int i = 0; i >= 0; i--) { sum = b[i]; for (unsigned int j = i+1; j < 2; j++) sum = sum - A[i][j] * b[j]; b[i] = sum / A[i][i]; } if (col_change) { double temp = b[0]; b[0] = b[1]; b[1] = temp; } gradient[1] = b[0] * (v_max[2] - v_min[2]) + b[1] * (v_inter[2] - v_min[2]) - c + v_min[2]; // normalize the gradient double gradient_norm = sqrt(pow(gradient[0], 2.0) + pow(gradient[1], 2.0)); gradient[0] /= gradient_norm; gradient[1] /= gradient_norm; double lambda = - gradient[0] * (v_min[0] - v_max[0]) - gradient[1] * (v_min[1] - v_max[1]); Point<6> gradient_parameters(true); gradient_parameters[0] = v_min[0]; gradient_parameters[1] = v_min[1]; gradient_parameters[2] = v_min[0] + lambda * gradient[0]; gradient_parameters[3] = v_min[1] + lambda * gradient[1]; gradient_parameters[4] = v_min[2]; gradient_parameters[5] = v_max[2]; return gradient_parameters; } } template <int dim, int spacedim> void write_ucd (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const UcdFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int n_data_sets = data_names.size(); UcdStream ucd_out(out, flags); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim> (patches, n_nodes, n_cells); /////////////////////// // preamble if (flags.write_preamble) { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "# This file was generated by the deal.II library." << '\n' << "# Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << "# Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "#" << '\n' << "# For a description of the UCD format see the AVS Developer's guide." << '\n' << "#" << '\n'; } // start with ucd data out << n_nodes << ' ' << n_cells << ' ' << n_data_sets << ' ' << 0 << ' ' // no cell data at present << 0 // no model data << '\n'; write_nodes(patches, ucd_out); out << '\n'; write_cells(patches, ucd_out); out << '\n'; ///////////////////////////// // now write data if (n_data_sets != 0) { out << n_data_sets << " "; // number of vectors for (unsigned int i=0; i<n_data_sets; ++i) out << 1 << ' '; // number of components; // only 1 supported presently out << '\n'; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << data_names[data_set] << ",dimensionless" // no units supported at present << '\n'; write_data(patches, n_data_sets, true, ucd_out); } // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_dx (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const DXFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif // Stream with special features for dx output DXStream dx_out(out, flags); // Variable counting the offset of // binary data. unsigned int offset = 0; const unsigned int n_data_sets = data_names.size(); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // start with vertices order is // lexicographical, x varying // fastest out << "object \"vertices\" class array type float rank 1 shape " << spacedim << " items " << n_nodes; if (flags.coordinates_binary) { out << " lsb ieee data 0" << '\n'; offset += n_nodes * spacedim * sizeof(float); } else { out << " data follows" << '\n'; write_nodes(patches, dx_out); } /////////////////////////////// // first write the coordinates of all vertices ///////////////////////////////////////// // write cells out << "object \"cells\" class array type int rank 1 shape " << GeometryInfo<dim>::vertices_per_cell << " items " << n_cells; if (flags.int_binary) { out << " lsb binary data " << offset << '\n'; offset += n_cells * sizeof (int); } else { out << " data follows" << '\n'; write_cells(patches, dx_out); out << '\n'; } out << "attribute \"element type\" string \""; if (dim==1) out << "lines"; if (dim==2) out << "quads"; if (dim==3) out << "cubes"; out << "\"" << '\n' << "attribute \"ref\" string \"positions\"" << '\n'; //TODO:[GK] Patches must be of same size! ///////////////////////////// // write neighbor information if (flags.write_neighbors) { out << "object \"neighbors\" class array type int rank 1 shape " << GeometryInfo<dim>::faces_per_cell << " items " << n_cells << " data follows"; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n = patch->n_subdivisions; const unsigned int n1 = (dim>0) ? n : 1; const unsigned int n2 = (dim>1) ? n : 1; const unsigned int n3 = (dim>2) ? n : 1; unsigned int cells_per_patch = Utilities::fixed_power<dim>(n); unsigned int dx = 1; unsigned int dy = n; unsigned int dz = n*n; const unsigned int patch_start = patch->patch_index * cells_per_patch; for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { const unsigned int nx = i1*dx; const unsigned int ny = i2*dy; const unsigned int nz = i3*dz; out << '\n'; // Direction -x // Last cell in row // of other patch if (i1==0) { const unsigned int nn = patch->neighbors[0]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+ny+nz+dx*(n-1)); else out << "-1"; } else { out << '\t' << patch_start+nx-dx+ny+nz; } // Direction +x // First cell in row // of other patch if (i1 == n-1) { const unsigned int nn = patch->neighbors[1]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+ny+nz); else out << "-1"; } else { out << '\t' << patch_start+nx+dx+ny+nz; } if (dim<2) continue; // Direction -y if (i2==0) { const unsigned int nn = patch->neighbors[2]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+nz+dy*(n-1)); else out << "-1"; } else { out << '\t' << patch_start+nx+ny-dy+nz; } // Direction +y if (i2 == n-1) { const unsigned int nn = patch->neighbors[3]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+nz); else out << "-1"; } else { out << '\t' << patch_start+nx+ny+dy+nz; } if (dim<3) continue; // Direction -z if (i3==0) { const unsigned int nn = patch->neighbors[4]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+ny+dz*(n-1)); else out << "-1"; } else { out << '\t' << patch_start+nx+ny+nz-dz; } // Direction +z if (i3 == n-1) { const unsigned int nn = patch->neighbors[5]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+ny); else out << "-1"; } else { out << '\t' << patch_start+nx+ny+nz+dz; } } out << '\n'; } } ///////////////////////////// // now write data if (n_data_sets != 0) { out << "object \"data\" class array type float rank 1 shape " << n_data_sets << " items " << n_nodes; if (flags.data_binary) { out << " lsb ieee data " << offset << '\n'; offset += n_data_sets * n_nodes * ((flags.data_double) ? sizeof(double) : sizeof(float)); } else { out << " data follows" << '\n'; write_data(patches, n_data_sets, flags.data_double, dx_out); } // loop over all patches out << "attribute \"dep\" string \"positions\"" << '\n'; } else { out << "object \"data\" class constantarray type float rank 0 items " << n_nodes << " data follows" << '\n' << '0' << '\n'; } // no model data out << "object \"deal data\" class field" << '\n' << "component \"positions\" value \"vertices\"" << '\n' << "component \"connections\" value \"cells\"" << '\n' << "component \"data\" value \"data\"" << '\n'; if (flags.write_neighbors) out << "component \"neighbors\" value \"neighbors\"" << '\n'; if (true) { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "attribute \"created\" string \"" << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << ' ' << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '"' << '\n'; } out << "end" << '\n'; // Write all binary data now if (flags.coordinates_binary) write_nodes(patches, dx_out); if (flags.int_binary) write_cells(patches, dx_out); if (flags.data_binary) write_data(patches, n_data_sets, flags.data_double, dx_out); // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_gnuplot (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const GnuplotFlags &/*flags*/, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int n_data_sets = data_names.size(); // write preamble if (true) { // block this to have local // variables destroyed after // use const std::time_t time1= std::time (0); const std::tm *time = std::localtime(&time1); out << "# This file was generated by the deal.II library." << '\n' << "# Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << "# Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "#" << '\n' << "# For a description of the GNUPLOT format see the GNUPLOT manual." << '\n' << "#" << '\n' << "# "; switch (spacedim) { case 1: out << "<x> "; break; case 2: out << "<x> <y> "; break; case 3: out << "<x> <y> <z> "; break; default: Assert (false, ExcNotImplemented()); } for (unsigned int i=0; i<data_names.size(); ++i) out << '<' << data_names[i] << "> "; out << '\n'; } // loop over all patches for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all dimensions const unsigned int n1 = (dim>0) ? n : 1; const unsigned int n2 = (dim>1) ? n : 1; const unsigned int n3 = (dim>2) ? n : 1; unsigned int d1 = 1; unsigned int d2 = n; unsigned int d3 = n*n; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); Point<spacedim> this_point; Point<spacedim> node; if (dim<3) { for (unsigned int i2=0; i2<n2; ++i2) { for (unsigned int i1=0; i1<n1; ++i1) { // compute coordinates for // this patch point compute_node(node, &*patch, i1, i2, 0, n_subdivisions); out << node << ' '; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << patch->data(data_set,i1*d1+i2*d2) << ' '; out << '\n'; } // end of row in patch if (dim>1) out << '\n'; } // end of patch if (dim==1) out << '\n'; out << '\n'; } else if (dim==3) { // for all grid points: draw // lines into all positive // coordinate directions if // there is another grid point // there for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { // compute coordinates for // this patch point compute_node(this_point, &*patch, i1, i2, i3, n_subdivisions); // line into positive x-direction // if possible if (i1 < n_subdivisions) { // write point here // and its data out << this_point; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+i2*d2+i3*d3); out << '\n'; // write point there // and its data compute_node(node, &*patch, i1+1, i2, i3, n_subdivisions); out << node; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,(i1+1)*d1+i2*d2+i3*d3); out << '\n'; // end of line out << '\n' << '\n'; } // line into positive y-direction // if possible if (i2 < n_subdivisions) { // write point here // and its data out << this_point; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set, i1*d1+i2*d2+i3*d3); out << '\n'; // write point there // and its data compute_node(node, &*patch, i1, i2+1, i3, n_subdivisions); out << node; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+(i2+1)*d2+i3*d3); out << '\n'; // end of line out << '\n' << '\n'; } // line into positive z-direction // if possible if (i3 < n_subdivisions) { // write point here // and its data out << this_point; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+i2*d2+i3*d3); out << '\n'; // write point there // and its data compute_node(node, &*patch, i1, i2, i3+1, n_subdivisions); out << node; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+i2*d2+(i3+1)*d3); out << '\n'; // end of line out << '\n' << '\n'; } } } else Assert (false, ExcNotImplemented()); } // make sure everything now gets to // disk out.flush (); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_povray (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const PovrayFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif Assert (dim==2, ExcNotImplemented()); // only for 2-D surfaces on a 2-D plane Assert (spacedim==2, ExcNotImplemented()); const unsigned int n_data_sets = data_names.size(); (void)n_data_sets; // write preamble if (true) { // block this to have local // variables destroyed after use const std::time_t time1= std::time (0); const std::tm *time = std::localtime(&time1); out << "/* This file was generated by the deal.II library." << '\n' << " Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << " Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << '\n' << " For a description of the POVRAY format see the POVRAY manual." << '\n' << "*/ " << '\n'; // include files out << "#include \"colors.inc\" " << '\n' << "#include \"textures.inc\" " << '\n'; // use external include file for textures, // camera and light if (flags.external_data) out << "#include \"data.inc\" " << '\n'; else // all definitions in data file { // camera out << '\n' << '\n' << "camera {" << '\n' << " location <1,4,-7>" << '\n' << " look_at <0,0,0>" << '\n' << " angle 30" << '\n' << "}" << '\n'; // light out << '\n' << "light_source {" << '\n' << " <1,4,-7>" << '\n' << " color Grey" << '\n' << "}" << '\n'; out << '\n' << "light_source {" << '\n' << " <0,20,0>" << '\n' << " color White" << '\n' << "}" << '\n'; } } // max. and min. heigth of solution Assert(patches.size()>0, ExcInternalError()); double hmin=patches[0].data(0,0); double hmax=patches[0].data(0,0); for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n_subdivisions+1), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); for (unsigned int i=0; i<n_subdivisions+1; ++i) for (unsigned int j=0; j<n_subdivisions+1; ++j) { const int dl = i*(n_subdivisions+1)+j; if (patch->data(0,dl)<hmin) hmin=patch->data(0,dl); if (patch->data(0,dl)>hmax) hmax=patch->data(0,dl); } } out << "#declare HMIN=" << hmin << ";" << '\n' << "#declare HMAX=" << hmax << ";" << '\n' << '\n'; if (!flags.external_data) { // texture with scaled niveau lines // 10 lines in the surface out << "#declare Tex=texture{" << '\n' << " pigment {" << '\n' << " gradient y" << '\n' << " scale y*(HMAX-HMIN)*" << 0.1 << '\n' << " color_map {" << '\n' << " [0.00 color Light_Purple] " << '\n' << " [0.95 color Light_Purple] " << '\n' << " [1.00 color White] " << '\n' << "} } }" << '\n' << '\n'; } if (!flags.bicubic_patch) { // start of mesh header out << '\n' << "mesh {" << '\n'; } // loop over all patches for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; const unsigned int d1=1; const unsigned int d2=n; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); std::vector<Point<spacedim> > ver(n*n); for (unsigned int i2=0; i2<n; ++i2) for (unsigned int i1=0; i1<n; ++i1) { // compute coordinates for // this patch point, storing in ver compute_node(ver[i1*d1+i2*d2], &*patch, i1, i2, 0, n_subdivisions); } if (!flags.bicubic_patch) { // approximate normal // vectors in patch std::vector<Point<3> > nrml; // only if smooth triangles are used if (flags.smooth) { nrml.resize(n*n); // These are // difference // quotients of // the surface // mapping. We // take them // symmetric // inside the // patch and // one-sided at // the edges Point<3> h1,h2; // Now compute normals in every point for (unsigned int i=0; i<n; ++i) for (unsigned int j=0; j<n; ++j) { const unsigned int il = (i==0) ? i : (i-1); const unsigned int ir = (i==n_subdivisions) ? i : (i+1); const unsigned int jl = (j==0) ? j : (j-1); const unsigned int jr = (j==n_subdivisions) ? j : (j+1); h1(0)=ver[ir*d1+j*d2](0) - ver[il*d1+j*d2](0); h1(1)=patch->data(0,ir*d1+j*d2)- patch->data(0,il*d1+j*d2); h1(2)=ver[ir*d1+j*d2](1) - ver[il*d1+j*d2](1); h2(0)=ver[i*d1+jr*d2](0) - ver[i*d1+jl*d2](0); h2(1)=patch->data(0,i*d1+jr*d2)- patch->data(0,i*d1+jl*d2); h2(2)=ver[i*d1+jr*d2](1) - ver[i*d1+jl*d2](1); nrml[i*d1+j*d2](0)=h1(1)*h2(2)-h1(2)*h2(1); nrml[i*d1+j*d2](1)=h1(2)*h2(0)-h1(0)*h2(2); nrml[i*d1+j*d2](2)=h1(0)*h2(1)-h1(1)*h2(0); // normalize Vector double norm=std::sqrt( std::pow(nrml[i*d1+j*d2](0),2.)+ std::pow(nrml[i*d1+j*d2](1),2.)+ std::pow(nrml[i*d1+j*d2](2),2.)); if (nrml[i*d1+j*d2](1)<0) norm*=-1.; for (unsigned int k=0; k<3; ++k) nrml[i*d1+j*d2](k)/=norm; } } // setting up triangles for (unsigned int i=0; i<n_subdivisions; ++i) for (unsigned int j=0; j<n_subdivisions; ++j) { // down/left vertex of triangle const int dl = i*d1+j*d2; if (flags.smooth) { // writing smooth_triangles // down/right triangle out << "smooth_triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">, <" << nrml[dl](0) << ", " << nrml[dl](1) << ", " << nrml[dl](2) << ">," << '\n'; out << " \t<" << ver[dl+d1](0) << "," << patch->data(0,dl+d1) << "," << ver[dl+d1](1) << ">, <" << nrml[dl+d1](0) << ", " << nrml[dl+d1](1) << ", " << nrml[dl+d1](2) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">, <" << nrml[dl+d1+d2](0) << ", " << nrml[dl+d1+d2](1) << ", " << nrml[dl+d1+d2](2) << ">}" << '\n'; // upper/left triangle out << "smooth_triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">, <" << nrml[dl](0) << ", " << nrml[dl](1) << ", " << nrml[dl](2) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">, <" << nrml[dl+d1+d2](0) << ", " << nrml[dl+d1+d2](1) << ", " << nrml[dl+d1+d2](2) << ">," << '\n'; out << "\t<" << ver[dl+d2](0) << "," << patch->data(0,dl+d2) << "," << ver[dl+d2](1) << ">, <" << nrml[dl+d2](0) << ", " << nrml[dl+d2](1) << ", " << nrml[dl+d2](2) << ">}" << '\n'; } else { // writing standard triangles // down/right triangle out << "triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">," << '\n'; out << "\t<" << ver[dl+d1](0) << "," << patch->data(0,dl+d1) << "," << ver[dl+d1](1) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">}" << '\n'; // upper/left triangle out << "triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">," << '\n'; out << "\t<" << ver[dl+d2](0) << "," << patch->data(0,dl+d2) << "," << ver[dl+d2](1) << ">}" << '\n'; } } } else { // writing bicubic_patch Assert (n_subdivisions==3, ExcDimensionMismatch(n_subdivisions,3)); out << '\n' << "bicubic_patch {" << '\n' << " type 0" << '\n' << " flatness 0" << '\n' << " u_steps 0" << '\n' << " v_steps 0" << '\n'; for (int i=0; i<16; ++i) { out << "\t<" << ver[i](0) << "," << patch->data(0,i) << "," << ver[i](1) << ">"; if (i!=15) out << ","; out << '\n'; } out << " texture {Tex}" << '\n' << "}" << '\n'; } } if (!flags.bicubic_patch) { // the end of the mesh out << " texture {Tex}" << '\n' << "}" << '\n' << '\n'; } // make sure everything now gets to // disk out.flush (); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_eps (const std::vector<Patch<dim,spacedim> > &/*patches*/, const std::vector<std::string> &/*data_names*/, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const EpsFlags &/*flags*/, std::ostream &/*out*/) { // not implemented, see the documentation of the function AssertThrow (dim==2, ExcNotImplemented()); } template <int spacedim> void write_eps (const std::vector<Patch<2,spacedim> > &patches, const std::vector<std::string> &/*data_names*/, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const EpsFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int old_precision = out.precision(); // set up an array of cells to be // written later. this array holds the // cells of all the patches as // projected to the plane perpendicular // to the line of sight. // // note that they are kept sorted by // the set, where we chose the value // of the center point of the cell // along the line of sight as value // for sorting std::multiset<EpsCell2d> cells; // two variables in which we // will store the minimum and // maximum values of the field // to be used for colorization // // preset them by 0 to calm down the // compiler; they are initialized later double min_color_value=0, max_color_value=0; // Array for z-coordinates of points. // The elevation determined by a function if spacedim=2 // or the z-cooridate of the grid point if spacedim=3 double heights[4] = { 0, 0, 0, 0 }; // compute the cells for output and // enter them into the set above // note that since dim==2, we // have exactly four vertices per // patch and per cell for (typename std::vector<Patch<2,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; const unsigned int d1 = 1; const unsigned int d2 = n; for (unsigned int i2=0; i2<n_subdivisions; ++i2) for (unsigned int i1=0; i1<n_subdivisions; ++i1) { Point<spacedim> points[4]; compute_node(points[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(points[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(points[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(points[3], &*patch, i1+1, i2+1, 0, n_subdivisions); switch (spacedim) { case 2: Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); heights[0] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,i1*d1 + i2*d2) * flags.z_scaling : 0; heights[1] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,(i1+1)*d1 + i2*d2) * flags.z_scaling : 0; heights[2] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,i1*d1 + (i2+1)*d2) * flags.z_scaling : 0; heights[3] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,(i1+1)*d1 + (i2+1)*d2) * flags.z_scaling : 0; break; case 3: // Copy z-coordinates into the height vector for (unsigned int i=0; i<4; ++i) heights[i] = points[i](2); break; default: Assert(false, ExcNotImplemented()); } // now compute the projection of // the bilinear cell given by the // four vertices and their heights // and write them to a proper // cell object. note that we only // need the first two components // of the projected position for // output, but we need the value // along the line of sight for // sorting the cells for back-to- // front-output // // this computation was first written // by Stefan Nauber. please no-one // ask me why it works that way (or // may be not), especially not about // the angles and the sign of // the height field, I don't know // it. EpsCell2d eps_cell; const double pi = numbers::PI; const double cx = -std::cos(pi-flags.azimut_angle * 2*pi / 360.), cz = -std::cos(flags.turn_angle * 2*pi / 360.), sx = std::sin(pi-flags.azimut_angle * 2*pi / 360.), sz = std::sin(flags.turn_angle * 2*pi / 360.); for (unsigned int vertex=0; vertex<4; ++vertex) { const double x = points[vertex](0), y = points[vertex](1), z = -heights[vertex]; eps_cell.vertices[vertex](0) = - cz*x+ sz*y; eps_cell.vertices[vertex](1) = -cx*sz*x-cx*cz*y-sx*z; // ( 1 0 0 ) // D1 = ( 0 cx -sx ) // ( 0 sx cx ) // ( cy 0 sy ) // Dy = ( 0 1 0 ) // (-sy 0 cy ) // ( cz -sz 0 ) // Dz = ( sz cz 0 ) // ( 0 0 1 ) // ( cz -sz 0 )( 1 0 0 )(x) ( cz*x-sz*(cx*y-sx*z)+0*(sx*y+cx*z) ) // Dxz = ( sz cz 0 )( 0 cx -sx )(y) = ( sz*x+cz*(cx*y-sx*z)+0*(sx*y+cx*z) ) // ( 0 0 1 )( 0 sx cx )(z) ( 0*x+ *(cx*y-sx*z)+1*(sx*y+cx*z) ) } // compute coordinates of // center of cell const Point<spacedim> center_point = (points[0] + points[1] + points[2] + points[3]) / 4; const double center_height = -(heights[0] + heights[1] + heights[2] + heights[3]) / 4; // compute the depth into // the picture eps_cell.depth = -sx*sz*center_point(0) -sx*cz*center_point(1) +cx*center_height; if (flags.draw_cells && flags.shade_cells) { Assert ((flags.color_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.color_vector, 0, patch->data.n_rows())); const double color_values[4] = { patch->data.n_rows() != 0 ? patch->data(flags.color_vector,i1 *d1 + i2 *d2) : 1, patch->data.n_rows() != 0 ? patch->data(flags.color_vector,(i1+1)*d1 + i2 *d2) : 1, patch->data.n_rows() != 0 ? patch->data(flags.color_vector,i1 *d1 + (i2+1)*d2) : 1, patch->data.n_rows() != 0 ? patch->data(flags.color_vector,(i1+1)*d1 + (i2+1)*d2) : 1 }; // set color value to average of the value // at the vertices eps_cell.color_value = (color_values[0] + color_values[1] + color_values[3] + color_values[2]) / 4; // update bounds of color // field if (patch == patches.begin()) min_color_value = max_color_value = eps_cell.color_value; else { min_color_value = (min_color_value < eps_cell.color_value ? min_color_value : eps_cell.color_value); max_color_value = (max_color_value > eps_cell.color_value ? max_color_value : eps_cell.color_value); } } // finally add this cell cells.insert (eps_cell); } } // find out minimum and maximum x and // y coordinates to compute offsets // and scaling factors double x_min = cells.begin()->vertices[0](0); double x_max = x_min; double y_min = cells.begin()->vertices[0](1); double y_max = y_min; for (typename std::multiset<EpsCell2d>::const_iterator cell=cells.begin(); cell!=cells.end(); ++cell) for (unsigned int vertex=0; vertex<4; ++vertex) { x_min = std::min (x_min, cell->vertices[vertex](0)); x_max = std::max (x_max, cell->vertices[vertex](0)); y_min = std::min (y_min, cell->vertices[vertex](1)); y_max = std::max (y_max, cell->vertices[vertex](1)); } // scale in x-direction such that // in the output 0 <= x <= 300. // don't scale in y-direction to // preserve the shape of the // triangulation const double scale = (flags.size / (flags.size_type==EpsFlags::width ? x_max - x_min : y_min - y_max)); const Point<2> offset(x_min, y_min); // now write preamble if (true) { // block this to have local // variables destroyed after // use std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "%!PS-Adobe-2.0 EPSF-1.2" << '\n' << "%%Title: deal.II Output" << '\n' << "%%Creator: the deal.II library" << '\n' << "%%Creation Date: " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " - " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "%%BoundingBox: " // lower left corner << "0 0 " // upper right corner << static_cast<unsigned int>( (x_max-x_min) * scale + 0.5) << ' ' << static_cast<unsigned int>( (y_max-y_min) * scale + 0.5) << '\n'; // define some abbreviations to keep // the output small: // m=move turtle to // l=define a line // s=set rgb color // sg=set gray value // lx=close the line and plot the line // lf=close the line and fill the interior out << "/m {moveto} bind def" << '\n' << "/l {lineto} bind def" << '\n' << "/s {setrgbcolor} bind def" << '\n' << "/sg {setgray} bind def" << '\n' << "/lx {lineto closepath stroke} bind def" << '\n' << "/lf {lineto closepath fill} bind def" << '\n'; out << "%%EndProlog" << '\n' << '\n'; // set fine lines out << flags.line_width << " setlinewidth" << '\n'; // allow only five digits // for output (instead of the // default six); this should suffice // even for fine grids, but reduces // the file size significantly out << std::setprecision (5); } // check if min and max // values for the color are // actually different. If // that is not the case (such // things happen, for // example, in the very first // time step of a time // dependent problem, if the // initial values are zero), // all values are equal, and // then we can draw // everything in an arbitrary // color. Thus, change one of // the two values arbitrarily if (max_color_value == min_color_value) max_color_value = min_color_value+1; // now we've got all the information // we need. write the cells. // note: due to the ordering, we // traverse the list of cells // back-to-front for (typename std::multiset<EpsCell2d>::const_iterator cell=cells.begin(); cell!=cells.end(); ++cell) { if (flags.draw_cells) { if (flags.shade_cells) { const EpsFlags::RgbValues rgb_values = (*flags.color_function) (cell->color_value, min_color_value, max_color_value); // write out color if (rgb_values.is_grey()) out << rgb_values.red << " sg "; else out << rgb_values.red << ' ' << rgb_values.green << ' ' << rgb_values.blue << " s "; } else out << "1 sg "; out << (cell->vertices[0]-offset) * scale << " m " << (cell->vertices[1]-offset) * scale << " l " << (cell->vertices[3]-offset) * scale << " l " << (cell->vertices[2]-offset) * scale << " lf" << '\n'; } if (flags.draw_mesh) out << "0 sg " // draw lines in black << (cell->vertices[0]-offset) * scale << " m " << (cell->vertices[1]-offset) * scale << " l " << (cell->vertices[3]-offset) * scale << " l " << (cell->vertices[2]-offset) * scale << " lx" << '\n'; } out << "showpage" << '\n'; // make sure everything now gets to // disk out << std::setprecision(old_precision); out.flush (); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_gmv (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const GmvFlags &flags, std::ostream &out) { Assert(dim<=3, ExcNotImplemented()); AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif GmvStream gmv_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); /////////////////////// // preamble out << "gmvinput ascii" << '\n' << '\n'; // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // in gmv format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates // // note that we have to print // 3 dimensions out << "nodes " << n_nodes << '\n'; for (unsigned int d=0; d<spacedim; ++d) { gmv_out.selected_component = d; write_nodes(patches, gmv_out); out << '\n'; } gmv_out.selected_component = numbers::invalid_unsigned_int; for (unsigned int d=spacedim; d<3; ++d) { for (unsigned int i=0; i<n_nodes; ++i) out << "0 "; out << '\n'; } ///////////////////////////////// // now for the cells. note that // vertices are counted from 1 onwards out << "cells " << n_cells << '\n'; write_cells(patches, gmv_out); /////////////////////////////////////// // data output. out << "variable" << '\n'; // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. // the '1' means: node data (as opposed // to cell data, which we do not // support explicitly here) for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) { out << data_names[data_set] << " 1" << '\n'; std::copy (data_vectors[data_set].begin(), data_vectors[data_set].end(), std::ostream_iterator<double>(out, " ")); out << '\n' << '\n'; } // end of variable section out << "endvars" << '\n'; // end of output out << "endgmv" << '\n'; // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_tecplot (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const TecplotFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif TecplotStream tecplot_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); /////////// // preamble { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "# This file was generated by the deal.II library." << '\n' << "# Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << "# Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "#" << '\n' << "# For a description of the Tecplot format see the Tecplot documentation." << '\n' << "#" << '\n'; out << "Variables="; switch (spacedim) { case 1: out << "\"x\""; break; case 2: out << "\"x\", \"y\""; break; case 3: out << "\"x\", \"y\", \"z\""; break; default: Assert (false, ExcNotImplemented()); } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ", \"" << data_names[data_set] << "\""; out << '\n'; out << "zone "; if (flags.zone_name) out << "t=\"" << flags.zone_name << "\" "; out << "f=feblock, n=" << n_nodes << ", e=" << n_cells << ", et=" << tecplot_cell_type[dim] << '\n'; } // in Tecplot FEBLOCK format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates for (unsigned int d=0; d<spacedim; ++d) { tecplot_out.selected_component = d; write_nodes(patches, tecplot_out); out << '\n'; } /////////////////////////////////////// // data output. // // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) { std::copy (data_vectors[data_set].begin(), data_vectors[data_set].end(), std::ostream_iterator<double>(out, "\n")); out << '\n'; } write_cells(patches, tecplot_out); // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } //--------------------------------------------------------------------------- // Macros for handling Tecplot API data #ifdef DEAL_II_HAVE_TECPLOT namespace { class TecplotMacros { public: TecplotMacros(const unsigned int n_nodes = 0, const unsigned int n_vars = 0, const unsigned int n_cells = 0, const unsigned int n_vert = 0); ~TecplotMacros(); float &nd(const unsigned int i, const unsigned int j); int &cd(const unsigned int i, const unsigned int j); std::vector<float> nodalData; std::vector<int> connData; private: unsigned int n_nodes; unsigned int n_vars; unsigned int n_cells; unsigned int n_vert; }; inline TecplotMacros::TecplotMacros(const unsigned int n_nodes, const unsigned int n_vars, const unsigned int n_cells, const unsigned int n_vert) : n_nodes(n_nodes), n_vars(n_vars), n_cells(n_cells), n_vert(n_vert) { nodalData.resize(n_nodes*n_vars); connData.resize(n_cells*n_vert); } inline TecplotMacros::~TecplotMacros() {} inline float &TecplotMacros::nd (const unsigned int i, const unsigned int j) { return nodalData[i*n_nodes+j]; } inline int &TecplotMacros::cd (const unsigned int i, const unsigned int j) { return connData[i+j*n_vert]; } } #endif //--------------------------------------------------------------------------- template <int dim, int spacedim> void write_tecplot_binary (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const TecplotFlags &flags, std::ostream &out) { #ifndef DEAL_II_HAVE_TECPLOT // simply call the ASCII output // function if the Tecplot API // isn't present write_tecplot (patches, data_names, vector_data_ranges, flags, out); return; #else // Tecplot binary output only good // for 2D & 3D if (dim == 1) { write_tecplot (patches, data_names, vector_data_ranges, flags, out); return; } // if the user hasn't specified a // file name we should call the // ASCII function and use the // ostream @p{out} instead of doing // something silly later char *file_name = (char *) flags.tecplot_binary_file_name; if (file_name == NULL) { // At least in debug mode we // should tell users why they // don't get tecplot binary // output Assert(false, ExcMessage("Specify the name of the tecplot_binary" " file through the TecplotFlags interface.")); write_tecplot (patches, data_names, vector_data_ranges, flags, out); return; } AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // local variables only needed to write Tecplot // binary output files const unsigned int vars_per_node = (spacedim+n_data_sets), nodes_per_cell = GeometryInfo<dim>::vertices_per_cell; TecplotMacros tm(n_nodes, vars_per_node, n_cells, nodes_per_cell); int is_double = 0, tec_debug = 0, cell_type = tecplot_binary_cell_type[dim]; std::string tec_var_names; switch (spacedim) { case 2: tec_var_names = "x y"; break; case 3: tec_var_names = "x y z"; break; default: Assert(false, ExcNotImplemented()); } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) { tec_var_names += " "; tec_var_names += data_names[data_set]; } // in Tecplot FEBLOCK format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates for (unsigned int d=1; d<=spacedim; ++d) { unsigned int entry=0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; switch (dim) { case 2: { for (unsigned int j=0; j<n_subdivisions+1; ++j) for (unsigned int i=0; i<n_subdivisions+1; ++i) { const double x_frac = i * 1./n_subdivisions, y_frac = j * 1./n_subdivisions; tm.nd((d-1),entry) = static_cast<float>( (((patch->vertices[1](d-1) * x_frac) + (patch->vertices[0](d-1) * (1-x_frac))) * (1-y_frac) + ((patch->vertices[3](d-1) * x_frac) + (patch->vertices[2](d-1) * (1-x_frac))) * y_frac) ); entry++; } break; } case 3: { for (unsigned int j=0; j<n_subdivisions+1; ++j) for (unsigned int k=0; k<n_subdivisions+1; ++k) for (unsigned int i=0; i<n_subdivisions+1; ++i) { const double x_frac = i * 1./n_subdivisions, y_frac = k * 1./n_subdivisions, z_frac = j * 1./n_subdivisions; // compute coordinates for // this patch point tm.nd((d-1),entry) = static_cast<float>( ((((patch->vertices[1](d-1) * x_frac) + (patch->vertices[0](d-1) * (1-x_frac))) * (1-y_frac) + ((patch->vertices[3](d-1) * x_frac) + (patch->vertices[2](d-1) * (1-x_frac))) * y_frac) * (1-z_frac) + (((patch->vertices[5](d-1) * x_frac) + (patch->vertices[4](d-1) * (1-x_frac))) * (1-y_frac) + ((patch->vertices[7](d-1) * x_frac) + (patch->vertices[6](d-1) * (1-x_frac))) * y_frac) * z_frac) ); entry++; } break; } default: Assert (false, ExcNotImplemented()); } } } /////////////////////////////////////// // data output. // reorder_task.join (); // then write data. for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) for (unsigned int entry=0; entry<data_vectors[data_set].size(); entry++) tm.nd((spacedim+data_set),entry) = static_cast<float>(data_vectors[data_set][entry]); ///////////////////////////////// // now for the cells. note that // vertices are counted from 1 onwards unsigned int first_vertex_of_patch = 0; unsigned int elem=0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; const unsigned int d1=1; const unsigned int d2=n; const unsigned int d3=n*n; // write out the cells making // up this patch switch (dim) { case 2: { for (unsigned int i2=0; i2<n_subdivisions; ++i2) for (unsigned int i1=0; i1<n_subdivisions; ++i1) { tm.cd(0,elem) = first_vertex_of_patch+(i1 )*d1+(i2 )*d2+1; tm.cd(1,elem) = first_vertex_of_patch+(i1+1)*d1+(i2 )*d2+1; tm.cd(2,elem) = first_vertex_of_patch+(i1+1)*d1+(i2+1)*d2+1; tm.cd(3,elem) = first_vertex_of_patch+(i1 )*d1+(i2+1)*d2+1; elem++; } break; } case 3: { for (unsigned int i3=0; i3<n_subdivisions; ++i3) for (unsigned int i2=0; i2<n_subdivisions; ++i2) for (unsigned int i1=0; i1<n_subdivisions; ++i1) { // note: vertex indices start with 1! tm.cd(0,elem) = first_vertex_of_patch+(i1 )*d1+(i2 )*d2+(i3 )*d3+1; tm.cd(1,elem) = first_vertex_of_patch+(i1+1)*d1+(i2 )*d2+(i3 )*d3+1; tm.cd(2,elem) = first_vertex_of_patch+(i1+1)*d1+(i2+1)*d2+(i3 )*d3+1; tm.cd(3,elem) = first_vertex_of_patch+(i1 )*d1+(i2+1)*d2+(i3 )*d3+1; tm.cd(4,elem) = first_vertex_of_patch+(i1 )*d1+(i2 )*d2+(i3+1)*d3+1; tm.cd(5,elem) = first_vertex_of_patch+(i1+1)*d1+(i2 )*d2+(i3+1)*d3+1; tm.cd(6,elem) = first_vertex_of_patch+(i1+1)*d1+(i2+1)*d2+(i3+1)*d3+1; tm.cd(7,elem) = first_vertex_of_patch+(i1 )*d1+(i2+1)*d2+(i3+1)*d3+1; elem++; } break; } default: Assert (false, ExcNotImplemented()); } // finally update the number // of the first vertex of this patch first_vertex_of_patch += Utilities::fixed_power<dim>(n); } { int ierr = 0, num_nodes = static_cast<int>(n_nodes), num_cells = static_cast<int>(n_cells); char dot[2] = {'.', 0}; // Unfortunately, TECINI takes a // char *, but c_str() gives a // const char *. As we don't do // anything else with // tec_var_names following // const_cast is ok char *var_names=const_cast<char *> (tec_var_names.c_str()); ierr = TECINI (NULL, var_names, file_name, dot, &tec_debug, &is_double); Assert (ierr == 0, ExcErrorOpeningTecplotFile(file_name)); char FEBLOCK[] = {'F','E','B','L','O','C','K',0}; ierr = TECZNE (NULL, &num_nodes, &num_cells, &cell_type, FEBLOCK, NULL); Assert (ierr == 0, ExcTecplotAPIError()); int total = (vars_per_node*num_nodes); ierr = TECDAT (&total, &tm.nodalData[0], &is_double); Assert (ierr == 0, ExcTecplotAPIError()); ierr = TECNOD (&tm.connData[0]); Assert (ierr == 0, ExcTecplotAPIError()); ierr = TECEND (); Assert (ierr == 0, ExcTecplotAPIError()); } #endif } template <int dim, int spacedim> void write_vtk (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const VtkFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif VtkStream vtk_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); /////////////////////// // preamble { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "# vtk DataFile Version 3.0" << '\n' << "#This file was generated by the deal.II library"; if (flags.print_date_and_time) out << " on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec; else out << "."; out << '\n' << "ASCII" << '\n'; // now output the data header out << "DATASET UNSTRUCTURED_GRID\n" << '\n'; } // if desired, output time and cycle of the simulation, following // the instructions at // http://www.visitusers.org/index.php?title=Time_and_Cycle_in_VTK_files { const unsigned int n_metadata = ((flags.cycle != std::numeric_limits<unsigned int>::min() ? 1 : 0) + (flags.time != std::numeric_limits<double>::min() ? 1 : 0)); if (n_metadata > 0) out << "FIELD FieldData " << n_metadata << "\n"; if (flags.cycle != std::numeric_limits<unsigned int>::min()) { out << "CYCLE 1 1 int\n" << flags.cycle << "\n"; } if (flags.time != std::numeric_limits<double>::min()) { out << "TIME 1 1 double\n" << flags.time << "\n"; } } // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // in gmv format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates // // note that we have to print // d=1..3 dimensions out << "POINTS " << n_nodes << " double" << '\n'; write_nodes(patches, vtk_out); out << '\n'; ///////////////////////////////// // now for the cells out << "CELLS " << n_cells << ' ' << n_cells*(GeometryInfo<dim>::vertices_per_cell+1) << '\n'; write_cells(patches, vtk_out); out << '\n'; // next output the types of the // cells. since all cells are // the same, this is simple out << "CELL_TYPES " << n_cells << '\n'; for (unsigned int i=0; i<n_cells; ++i) out << ' ' << vtk_cell_type[dim]; out << '\n'; /////////////////////////////////////// // data output. // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. the // 'POINT_DATA' means: node data // (as opposed to cell data, which // we do not support explicitly // here). all following data sets // are point data out << "POINT_DATA " << n_nodes << '\n'; // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over std::vector<bool> data_set_written (n_data_sets, false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) + 1 - std_cxx11::get<0>(vector_data_ranges[n_th_vector]) <= 3, ExcMessage ("Can't declare a vector with more than 3 components " "in VTK")); // mark these components as already written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << "VECTORS "; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << " double" << '\n'; // now write data. pad all // vectors to have three // components for (unsigned int n=0; n<n_nodes; ++n) { switch (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) - std_cxx11::get<0>(vector_data_ranges[n_th_vector])) { case 0: out << data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n) << " 0 0" << '\n'; break; case 1: out << data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n) << ' '<< data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n) << " 0" << '\n'; break; case 2: out << data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n) << ' '<< data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n) << ' '<< data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+2, n) << '\n'; break; default: // VTK doesn't // support // anything else // than vectors // with 1, 2, or // 3 components Assert (false, ExcInternalError()); } } } // now do the left over scalar data sets for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) if (data_set_written[data_set] == false) { out << "SCALARS " << data_names[data_set] << " double 1" << '\n' << "LOOKUP_TABLE default" << '\n'; std::copy (data_vectors[data_set].begin(), data_vectors[data_set].end(), std::ostream_iterator<double>(out, " ")); out << '\n'; } // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } void write_vtu_header (std::ostream &out, const VtkFlags &flags) { AssertThrow (out, ExcIO()); std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "<?xml version=\"1.0\" ?> \n"; out << "<!-- \n"; out << "# vtk DataFile Version 3.0" << '\n' << "#This file was generated by the deal.II library"; if (flags.print_date_and_time) out << " on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec; else out << "."; out << "\n-->\n"; out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\""; #ifdef DEAL_II_WITH_ZLIB out << " compressor=\"vtkZLibDataCompressor\""; #endif #ifdef DEAL_II_WORDS_BIGENDIAN out << " byte_order=\"BigEndian\""; #else out << " byte_order=\"LittleEndian\""; #endif out << ">"; out << '\n'; out << "<UnstructuredGrid>"; out << '\n'; } void write_vtu_footer (std::ostream &out) { AssertThrow (out, ExcIO()); out << " </UnstructuredGrid>\n"; out << "</VTKFile>\n"; } template <int dim, int spacedim> void write_vtu (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const VtkFlags &flags, std::ostream &out) { write_vtu_header(out, flags); write_vtu_main (patches, data_names, vector_data_ranges, flags, out); write_vtu_footer(out); out << std::flush; } template <int dim, int spacedim> void write_vtu_main (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const VtkFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) { // we still need to output a valid vtu file, because other CPUs // might output data. This is the minimal file that is accepted by paraview and visit. // if we remove the field definitions, visit is complaining. out << "<Piece NumberOfPoints=\"0\" NumberOfCells=\"0\" >\n" << "<Cells>\n" << "<DataArray type=\"UInt8\" Name=\"types\"></DataArray>\n" << "</Cells>\n" << " <PointData Scalars=\"scalars\">\n"; std::vector<bool> data_set_written (data_names.size(), false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { // mark these components as already // written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << " <DataArray type=\"Float64\" Name=\""; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << "\" NumberOfComponents=\"3\"></DataArray>\n"; } for (unsigned int data_set=0; data_set<data_names.size(); ++data_set) if (data_set_written[data_set] == false) { out << " <DataArray type=\"Float64\" Name=\"" << data_names[data_set] << "\"></DataArray>\n"; } out << " </PointData>\n"; out << "</Piece>\n"; out << std::flush; return; } #endif // first up: metadata // // if desired, output time and cycle of the simulation, following // the instructions at // http://www.visitusers.org/index.php?title=Time_and_Cycle_in_VTK_files { const unsigned int n_metadata = ((flags.cycle != std::numeric_limits<unsigned int>::min() ? 1 : 0) + (flags.time != std::numeric_limits<double>::min() ? 1 : 0)); if (n_metadata > 0) out << "<FieldData>\n"; if (flags.cycle != std::numeric_limits<unsigned int>::min()) { out << "<DataArray type=\"Float32\" Name=\"CYCLE\" NumberOfTuples=\"1\" format=\"ascii\">" << flags.cycle << "</DataArray>\n"; } if (flags.time != std::numeric_limits<double>::min()) { out << "<DataArray type=\"Float32\" Name=\"TIME\" NumberOfTuples=\"1\" format=\"ascii\">" << flags.time << "</DataArray>\n"; } if (n_metadata > 0) out << "</FieldData>\n"; } VtuStream vtu_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); #ifdef DEAL_II_WITH_ZLIB const char *ascii_or_binary = "binary"; #else const char *ascii_or_binary = "ascii"; #endif // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // in gmv format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates // // note that according to the standard, we // have to print d=1..3 dimensions, even if // we are in reality in 2d, for example out << "<Piece NumberOfPoints=\"" << n_nodes <<"\" NumberOfCells=\"" << n_cells << "\" >\n"; out << " <Points>\n"; out << " <DataArray type=\"Float64\" NumberOfComponents=\"3\" format=\"" << ascii_or_binary << "\">\n"; write_nodes(patches, vtu_out); out << " </DataArray>\n"; out << " </Points>\n\n"; ///////////////////////////////// // now for the cells out << " <Cells>\n"; out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"" << ascii_or_binary << "\">\n"; write_cells(patches, vtu_out); out << " </DataArray>\n"; // XML VTU format uses offsets; this is // different than the VTK format, which // puts the number of nodes per cell in // front of the connectivity list. out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"" << ascii_or_binary << "\">\n"; std::vector<int32_t> offsets (n_cells); for (unsigned int i=0; i<n_cells; ++i) offsets[i] = (i+1)*GeometryInfo<dim>::vertices_per_cell; vtu_out << offsets; out << "\n"; out << " </DataArray>\n"; // next output the types of the // cells. since all cells are // the same, this is simple out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"" << ascii_or_binary << "\">\n"; { // uint8_t might be a typedef to unsigned // char which is then not printed as // ascii integers #ifdef DEAL_II_WITH_ZLIB std::vector<uint8_t> cell_types (n_cells, static_cast<uint8_t>(vtk_cell_type[dim])); #else std::vector<unsigned int> cell_types (n_cells, vtk_cell_type[dim]); #endif // this should compress well :-) vtu_out << cell_types; } out << "\n"; out << " </DataArray>\n"; out << " </Cells>\n"; /////////////////////////////////////// // data output. // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. the // 'POINT_DATA' means: node data // (as opposed to cell data, which // we do not support explicitly // here). all following data sets // are point data out << " <PointData Scalars=\"scalars\">\n"; // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over std::vector<bool> data_set_written (n_data_sets, false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) + 1 - std_cxx11::get<0>(vector_data_ranges[n_th_vector]) <= 3, ExcMessage ("Can't declare a vector with more than 3 components " "in VTK")); // mark these components as already // written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << " <DataArray type=\"Float64\" Name=\""; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << "\" NumberOfComponents=\"3\" format=\"" << ascii_or_binary << "\">\n"; // now write data. pad all // vectors to have three // components std::vector<double> data; data.reserve (n_nodes*dim); for (unsigned int n=0; n<n_nodes; ++n) { switch (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) - std_cxx11::get<0>(vector_data_ranges[n_th_vector])) { case 0: data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n)); data.push_back (0); data.push_back (0); break; case 1: data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n)); data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n)); data.push_back (0); break; case 2: data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n)); data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n)); data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+2, n)); break; default: // VTK doesn't // support // anything else // than vectors // with 1, 2, or // 3 components Assert (false, ExcInternalError()); } } vtu_out << data; out << " </DataArray>\n"; } // now do the left over scalar data sets for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) if (data_set_written[data_set] == false) { out << " <DataArray type=\"Float64\" Name=\"" << data_names[data_set] << "\" format=\"" << ascii_or_binary << "\">\n"; std::vector<double> data (data_vectors[data_set].begin(), data_vectors[data_set].end()); vtu_out << data; out << " </DataArray>\n"; } out << " </PointData>\n"; // Finish up writing a valid XML file out << " </Piece>\n"; // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_svg (const std::vector<Patch<dim,spacedim> > &, const std::vector<std::string> &, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const SvgFlags &, std::ostream &) { Assert (false, ExcNotImplemented()); } template <int spacedim> void write_svg (const std::vector<Patch<2,spacedim> > &patches, const std::vector<std::string> &/*data_names*/, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &/*vector_data_ranges*/, const SvgFlags &flags, std::ostream &out) { const int dim = 2; const unsigned int height = flags.height; unsigned int width = flags.width; // margin around the plotted area unsigned int margin_in_percent = 0; if (flags.margin) margin_in_percent = 5; // determine the bounding box in the model space double x_dimension, y_dimension, z_dimension; typename std::vector<Patch<dim,spacedim> >::const_iterator patch = patches.begin(); unsigned int n_subdivisions = patch->n_subdivisions; unsigned int n = n_subdivisions + 1; const unsigned int d1 = 1; const unsigned int d2 = n; Point<spacedim> projected_point; Point<spacedim> projected_points[4]; Point<2> projection_decomposition; Point<2> projection_decompositions[4]; compute_node(projected_point, &*patch, 0, 0, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); double x_min = projected_point[0]; double x_max = x_min; double y_min = projected_point[1]; double y_max = y_min; double z_min = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,0) : 0; double z_max = z_min; // iterate over the patches for (; patch != patches.end(); ++patch) { n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; for (unsigned int i2 = 0; i2 < n_subdivisions; ++i2) { for (unsigned int i1 = 0; i1 < n_subdivisions; ++i1) { compute_node(projected_points[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(projected_points[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(projected_points[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(projected_points[3], &*patch, i1+1, i2+1, 0, n_subdivisions); x_min = std::min(x_min, (double)projected_points[0][0]); x_min = std::min(x_min, (double)projected_points[1][0]); x_min = std::min(x_min, (double)projected_points[2][0]); x_min = std::min(x_min, (double)projected_points[3][0]); x_max = std::max(x_max, (double)projected_points[0][0]); x_max = std::max(x_max, (double)projected_points[1][0]); x_max = std::max(x_max, (double)projected_points[2][0]); x_max = std::max(x_max, (double)projected_points[3][0]); y_min = std::min(y_min, (double)projected_points[0][1]); y_min = std::min(y_min, (double)projected_points[1][1]); y_min = std::min(y_min, (double)projected_points[2][1]); y_min = std::min(y_min, (double)projected_points[3][1]); y_max = std::max(y_max, (double)projected_points[0][1]); y_max = std::max(y_max, (double)projected_points[1][1]); y_max = std::max(y_max, (double)projected_points[2][1]); y_max = std::max(y_max, (double)projected_points[3][1]); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); z_min = std::min(z_min, (double)patch->data(flags.height_vector, i1*d1 + i2*d2)); z_min = std::min(z_min, (double)patch->data(flags.height_vector, (i1+1)*d1 + i2*d2)); z_min = std::min(z_min, (double)patch->data(flags.height_vector, i1*d1 + (i2+1)*d2)); z_min = std::min(z_min, (double)patch->data(flags.height_vector, (i1+1)*d1 + (i2+1)*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, i1*d1 + i2*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, (i1+1)*d1 + i2*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, i1*d1 + (i2+1)*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, (i1+1)*d1 + (i2+1)*d2)); } } } x_dimension = x_max - x_min; y_dimension = y_max - y_min; z_dimension = z_max - z_min; // set initial camera position Point<3> camera_position(true); Point<3> camera_direction(true); Point<3> camera_horizontal(true); float camera_focus = 0; // translate camera from the origin to the initial position camera_position[0] = 0.; camera_position[1] = 0.; camera_position[2] = z_min + 2. * z_dimension; camera_direction[0] = 0.; camera_direction[1] = 0.; camera_direction[2] = - 1.; camera_horizontal[0] = 1.; camera_horizontal[1] = 0.; camera_horizontal[2] = 0.; camera_focus = .5 * z_dimension; Point<3> camera_position_temp; Point<3> camera_direction_temp; Point<3> camera_horizontal_temp; const float angle_factor = 3.14159265 / 180.; // (I) rotate the camera to the chosen polar angle camera_position_temp[1] = cos(angle_factor * flags.polar_angle) * camera_position[1] - sin(angle_factor * flags.polar_angle) * camera_position[2]; camera_position_temp[2] = sin(angle_factor * flags.polar_angle) * camera_position[1] + cos(angle_factor * flags.polar_angle) * camera_position[2]; camera_direction_temp[1] = cos(angle_factor * flags.polar_angle) * camera_direction[1] - sin(angle_factor * flags.polar_angle) * camera_direction[2]; camera_direction_temp[2] = sin(angle_factor * flags.polar_angle) * camera_direction[1] + cos(angle_factor * flags.polar_angle) * camera_direction[2]; camera_horizontal_temp[1] = cos(angle_factor * flags.polar_angle) * camera_horizontal[1] - sin(angle_factor * flags.polar_angle) * camera_horizontal[2]; camera_horizontal_temp[2] = sin(angle_factor * flags.polar_angle) * camera_horizontal[1] + cos(angle_factor * flags.polar_angle) * camera_horizontal[2]; camera_position[1] = camera_position_temp[1]; camera_position[2] = camera_position_temp[2]; camera_direction[1] = camera_direction_temp[1]; camera_direction[2] = camera_direction_temp[2]; camera_horizontal[1] = camera_horizontal_temp[1]; camera_horizontal[2] = camera_horizontal_temp[2]; // (II) rotate the camera to the chosen azimuth angle camera_position_temp[0] = cos(angle_factor * flags.azimuth_angle) * camera_position[0] - sin(angle_factor * flags.azimuth_angle) * camera_position[1]; camera_position_temp[1] = sin(angle_factor * flags.azimuth_angle) * camera_position[0] + cos(angle_factor * flags.azimuth_angle) * camera_position[1]; camera_direction_temp[0] = cos(angle_factor * flags.azimuth_angle) * camera_direction[0] - sin(angle_factor * flags.azimuth_angle) * camera_direction[1]; camera_direction_temp[1] = sin(angle_factor * flags.azimuth_angle) * camera_direction[0] + cos(angle_factor * flags.azimuth_angle) * camera_direction[1]; camera_horizontal_temp[0] = cos(angle_factor * flags.azimuth_angle) * camera_horizontal[0] - sin(angle_factor * flags.azimuth_angle) * camera_horizontal[1]; camera_horizontal_temp[1] = sin(angle_factor * flags.azimuth_angle) * camera_horizontal[0] + cos(angle_factor * flags.azimuth_angle) * camera_horizontal[1]; camera_position[0] = camera_position_temp[0]; camera_position[1] = camera_position_temp[1]; camera_direction[0] = camera_direction_temp[0]; camera_direction[1] = camera_direction_temp[1]; camera_horizontal[0] = camera_horizontal_temp[0]; camera_horizontal[1] = camera_horizontal_temp[1]; // (III) translate the camera camera_position[0] = x_min + .5 * x_dimension; camera_position[1] = y_min + .5 * y_dimension; camera_position[0] += (z_min + 2. * z_dimension) * sin(angle_factor * flags.polar_angle) * sin(angle_factor * flags.azimuth_angle); camera_position[1] -= (z_min + 2. * z_dimension) * sin(angle_factor * flags.polar_angle) * cos(angle_factor * flags.azimuth_angle); // determine the bounding box on the projection plane double x_min_perspective, y_min_perspective; double x_max_perspective, y_max_perspective; double x_dimension_perspective, y_dimension_perspective; patch = patches.begin(); n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; Point<3> point(true); compute_node(projected_point, &*patch, 0, 0, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); point[0] = projected_point[0]; point[1] = projected_point[1]; point[2] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector, 0) : 0; projection_decomposition = svg_project_point(point, camera_position, camera_direction, camera_horizontal, camera_focus); x_min_perspective = projection_decomposition[0]; x_max_perspective = projection_decomposition[0]; y_min_perspective = projection_decomposition[1]; y_max_perspective = projection_decomposition[1]; // iterate over the patches for (; patch != patches.end(); ++patch) { n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; for (unsigned int i2 = 0; i2 < n_subdivisions; ++i2) { for (unsigned int i1 = 0; i1 < n_subdivisions; ++i1) { Point<spacedim> projected_vertices[4]; Point<3> vertices[4]; compute_node(projected_vertices[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(projected_vertices[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(projected_vertices[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(projected_vertices[3], &*patch, i1+1, i2+1, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); vertices[0][0] = projected_vertices[0][0]; vertices[0][1] = projected_vertices[0][1]; vertices[0][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + i2*d2) : 0; vertices[1][0] = projected_vertices[1][0]; vertices[1][1] = projected_vertices[1][1]; vertices[1][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + i2*d2) : 0; vertices[2][0] = projected_vertices[2][0]; vertices[2][1] = projected_vertices[2][1]; vertices[2][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + (i2+1)*d2) : 0; vertices[3][0] = projected_vertices[3][0]; vertices[3][1] = projected_vertices[3][1]; vertices[3][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + (i2+1)*d2) : 0; projection_decompositions[0] = svg_project_point(vertices[0], camera_position, camera_direction, camera_horizontal, camera_focus); projection_decompositions[1] = svg_project_point(vertices[1], camera_position, camera_direction, camera_horizontal, camera_focus); projection_decompositions[2] = svg_project_point(vertices[2], camera_position, camera_direction, camera_horizontal, camera_focus); projection_decompositions[3] = svg_project_point(vertices[3], camera_position, camera_direction, camera_horizontal, camera_focus); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[0][0]); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[1][0]); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[2][0]); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[3][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[0][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[1][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[2][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[3][0]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[0][1]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[1][1]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[2][1]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[3][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[0][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[1][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[2][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[3][1]); } } } x_dimension_perspective = x_max_perspective - x_min_perspective; y_dimension_perspective = y_max_perspective - y_min_perspective; std::multiset<SvgCell> cells; // iterate over the patches for (patch = patches.begin(); patch != patches.end(); ++patch) { n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; for (unsigned int i2 = 0; i2 < n_subdivisions; ++i2) { for (unsigned int i1 = 0; i1 < n_subdivisions; ++i1) { Point<spacedim> projected_vertices[4]; SvgCell cell; compute_node(projected_vertices[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(projected_vertices[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(projected_vertices[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(projected_vertices[3], &*patch, i1+1, i2+1, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); cell.vertices[0][0] = projected_vertices[0][0]; cell.vertices[0][1] = projected_vertices[0][1]; cell.vertices[0][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + i2*d2) : 0; cell.vertices[1][0] = projected_vertices[1][0]; cell.vertices[1][1] = projected_vertices[1][1]; cell.vertices[1][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + i2*d2) : 0; cell.vertices[2][0] = projected_vertices[2][0]; cell.vertices[2][1] = projected_vertices[2][1]; cell.vertices[2][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + (i2+1)*d2) : 0; cell.vertices[3][0] = projected_vertices[3][0]; cell.vertices[3][1] = projected_vertices[3][1]; cell.vertices[3][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + (i2+1)*d2) : 0; cell.projected_vertices[0] = svg_project_point(cell.vertices[0], camera_position, camera_direction, camera_horizontal, camera_focus); cell.projected_vertices[1] = svg_project_point(cell.vertices[1], camera_position, camera_direction, camera_horizontal, camera_focus); cell.projected_vertices[2] = svg_project_point(cell.vertices[2], camera_position, camera_direction, camera_horizontal, camera_focus); cell.projected_vertices[3] = svg_project_point(cell.vertices[3], camera_position, camera_direction, camera_horizontal, camera_focus); cell.center = .25 * (cell.vertices[0] + cell.vertices[1] + cell.vertices[2] + cell.vertices[3]); cell.projected_center = svg_project_point(cell.center, camera_position, camera_direction, camera_horizontal, camera_focus); cell.depth = cell.center.distance(camera_position); cells.insert(cell); } } } // write the svg file if (width==0) width = static_cast<unsigned int>(.5 + height * (x_dimension_perspective / y_dimension_perspective)); unsigned int additional_width = 0; if (flags.draw_colorbar) additional_width = static_cast<unsigned int>(.5 + height * .3); // additional width for colorbar // basic svg header and background rectangle out << "<svg width=\"" << width + additional_width << "\" height=\"" << height << "\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">" << '\n' << " <rect width=\"" << width + additional_width << "\" height=\"" << height << "\" style=\"fill:white\"/>" << '\n' << '\n'; unsigned int triangle_counter = 0; // write the cells in the correct order for (typename std::multiset<SvgCell>::const_iterator cell = cells.begin(); cell != cells.end(); ++cell) { Point<3> points3d_triangle[3]; for (unsigned int triangle_index = 0; triangle_index < 4; triangle_index++) { switch (triangle_index) { case 0: points3d_triangle[0] = cell->vertices[0], points3d_triangle[1] = cell->vertices[1], points3d_triangle[2] = cell->center; break; case 1: points3d_triangle[0] = cell->vertices[1], points3d_triangle[1] = cell->vertices[3], points3d_triangle[2] = cell->center; break; case 2: points3d_triangle[0] = cell->vertices[3], points3d_triangle[1] = cell->vertices[2], points3d_triangle[2] = cell->center; break; case 3: points3d_triangle[0] = cell->vertices[2], points3d_triangle[1] = cell->vertices[0], points3d_triangle[2] = cell->center; break; default: break; } Point<6> gradient_param = svg_get_gradient_parameters(points3d_triangle); double start_h = .667 - ((gradient_param[4] - z_min) / z_dimension) * .667; double stop_h = .667 - ((gradient_param[5] - z_min) / z_dimension) * .667; unsigned int start_r = 0; unsigned int start_g = 0; unsigned int start_b = 0; unsigned int stop_r = 0; unsigned int stop_g = 0; unsigned int stop_b = 0; unsigned int start_i = static_cast<unsigned int>(start_h * 6.); unsigned int stop_i = static_cast<unsigned int>(stop_h * 6.); double start_f = start_h * 6. - start_i; double start_q = 1. - start_f; double stop_f = stop_h * 6. - stop_i; double stop_q = 1. - stop_f; switch (start_i % 6) { case 0: start_r = 255, start_g = static_cast<unsigned int>(.5 + 255. * start_f); break; case 1: start_r = static_cast<unsigned int>(.5 + 255. * start_q), start_g = 255; break; case 2: start_g = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_f); break; case 3: start_g = static_cast<unsigned int>(.5 + 255. * start_q), start_b = 255; break; case 4: start_r = static_cast<unsigned int>(.5 + 255. * start_f), start_b = 255; break; case 5: start_r = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_q); break; default: break; } switch (stop_i % 6) { case 0: stop_r = 255, stop_g = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 1: stop_r = static_cast<unsigned int>(.5 + 255. * stop_q), stop_g = 255; break; case 2: stop_g = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 3: stop_g = static_cast<unsigned int>(.5 + 255. * stop_q), stop_b = 255; break; case 4: stop_r = static_cast<unsigned int>(.5 + 255. * stop_f), stop_b = 255; break; case 5: stop_r = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_q); break; default: break; } Point<3> gradient_start_point_3d, gradient_stop_point_3d; gradient_start_point_3d[0] = gradient_param[0]; gradient_start_point_3d[1] = gradient_param[1]; gradient_start_point_3d[2] = gradient_param[4]; gradient_stop_point_3d[0] = gradient_param[2]; gradient_stop_point_3d[1] = gradient_param[3]; gradient_stop_point_3d[2] = gradient_param[5]; Point<2> gradient_start_point = svg_project_point(gradient_start_point_3d, camera_position, camera_direction, camera_horizontal, camera_focus); Point<2> gradient_stop_point = svg_project_point(gradient_stop_point_3d, camera_position, camera_direction, camera_horizontal, camera_focus); // define linear gradient out << " <linearGradient id=\"" << triangle_counter << "\" gradientUnits=\"userSpaceOnUse\" " << "x1=\"" << static_cast<unsigned int>(.5 + ((gradient_start_point[0] - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << "\" " << "y1=\"" << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((gradient_start_point[1] - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << "\" " << "x2=\"" << static_cast<unsigned int>(.5 + ((gradient_stop_point[0] - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << "\" " << "y2=\"" << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((gradient_stop_point[1] - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << "\"" << ">" << '\n' << " <stop offset=\"0\" style=\"stop-color:rgb(" << start_r << "," << start_g << "," << start_b << ")\"/>" << '\n' << " <stop offset=\"1\" style=\"stop-color:rgb(" << stop_r << "," << stop_g << "," << stop_b << ")\"/>" << '\n' << " </linearGradient>" << '\n'; // draw current triangle double x1 = 0, y1 = 0, x2 = 0, y2 = 0; double x3 = cell->projected_center[0]; double y3 = cell->projected_center[1]; switch (triangle_index) { case 0: x1 = cell->projected_vertices[0][0], y1 = cell->projected_vertices[0][1], x2 = cell->projected_vertices[1][0], y2 = cell->projected_vertices[1][1]; break; case 1: x1 = cell->projected_vertices[1][0], y1 = cell->projected_vertices[1][1], x2 = cell->projected_vertices[3][0], y2 = cell->projected_vertices[3][1]; break; case 2: x1 = cell->projected_vertices[3][0], y1 = cell->projected_vertices[3][1], x2 = cell->projected_vertices[2][0], y2 = cell->projected_vertices[2][1]; break; case 3: x1 = cell->projected_vertices[2][0], y1 = cell->projected_vertices[2][1], x2 = cell->projected_vertices[0][0], y2 = cell->projected_vertices[0][1]; break; default: break; } out << " <path d=\"M " << static_cast<unsigned int>(.5 + ((x1 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y1 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << " L " << static_cast<unsigned int>(.5 + ((x2 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y2 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << " L " << static_cast<unsigned int>(.5 + ((x3 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y3 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << " L " << static_cast<unsigned int>(.5 + ((x1 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y1 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << "\" style=\"stroke:black; fill:url(#" << triangle_counter << "); stroke-width:" << flags.line_thickness << "\"/>" << '\n'; triangle_counter++; } } // draw the colorbar if (flags.draw_colorbar) { out << '\n' << " <!-- colorbar -->" << '\n'; unsigned int element_height = static_cast<unsigned int>(((height/100.) * (71. - 2.*margin_in_percent)) / 4); unsigned int element_width = static_cast<unsigned int>(.5 + (height/100.) * 2.5); additional_width = 0; if (!flags.margin) additional_width = static_cast<unsigned int>(.5 + (height/100.) * 2.5); for (unsigned int index = 0; index < 4; index++) { double start_h = .667 - ((index+1) / 4.) * .667; double stop_h = .667 - (index / 4.) * .667; unsigned int start_r = 0; unsigned int start_g = 0; unsigned int start_b = 0; unsigned int stop_r = 0; unsigned int stop_g = 0; unsigned int stop_b = 0; unsigned int start_i = static_cast<unsigned int>(start_h * 6.); unsigned int stop_i = static_cast<unsigned int>(stop_h * 6.); double start_f = start_h * 6. - start_i; double start_q = 1. - start_f; double stop_f = stop_h * 6. - stop_i; double stop_q = 1. - stop_f; switch (start_i % 6) { case 0: start_r = 255, start_g = static_cast<unsigned int>(.5 + 255. * start_f); break; case 1: start_r = static_cast<unsigned int>(.5 + 255. * start_q), start_g = 255; break; case 2: start_g = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_f); break; case 3: start_g = static_cast<unsigned int>(.5 + 255. * start_q), start_b = 255; break; case 4: start_r = static_cast<unsigned int>(.5 + 255. * start_f), start_b = 255; break; case 5: start_r = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_q); break; default: break; } switch (stop_i % 6) { case 0: stop_r = 255, stop_g = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 1: stop_r = static_cast<unsigned int>(.5 + 255. * stop_q), stop_g = 255; break; case 2: stop_g = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 3: stop_g = static_cast<unsigned int>(.5 + 255. * stop_q), stop_b = 255; break; case 4: stop_r = static_cast<unsigned int>(.5 + 255. * stop_f), stop_b = 255; break; case 5: stop_r = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_q); break; default: break; } // define gradient out << " <linearGradient id=\"colorbar_" << index << "\" gradientUnits=\"userSpaceOnUse\" " << "x1=\"" << width + additional_width << "\" " << "y1=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29)) + (3-index) * element_height << "\" " << "x2=\"" << width + additional_width << "\" " << "y2=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29)) + (4-index) * element_height << "\"" << ">" << '\n' << " <stop offset=\"0\" style=\"stop-color:rgb(" << start_r << "," << start_g << "," << start_b << ")\"/>" << '\n' << " <stop offset=\"1\" style=\"stop-color:rgb(" << stop_r << "," << stop_g << "," << stop_b << ")\"/>" << '\n' << " </linearGradient>" << '\n'; // draw box corresponding to the gradient above out << " <rect" << " x=\"" << width + additional_width << "\" y=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29)) + (3-index) * element_height << "\" width=\"" << element_width << "\" height=\"" << element_height << "\" style=\"stroke:black; stroke-width:2; fill:url(#colorbar_" << index << ")\"/>" << '\n'; } for (unsigned int index = 0; index < 5; index++) { out << " <text x=\"" << width + additional_width + static_cast<unsigned int>(1.5 * element_width) << "\" y=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29) + (4.-index) * element_height + 30.) << "\"" << " style=\"text-anchor:start; font-size:80; font-family:Helvetica"; if (index == 0 || index == 4) out << "; font-weight:bold"; out << "\">" << (float)(((int)((z_min + index * (z_dimension / 4.))*10000))/10000.); if (index == 4) out << " max"; if (index == 0) out << " min"; out << "</text>" << '\n'; } } // finalize the svg file out << '\n' << "</svg>"; out.flush(); } template <int dim, int spacedim> void write_deal_II_intermediate (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const Deal_II_IntermediateFlags &/*flags*/, std::ostream &out) { AssertThrow (out, ExcIO()); // first write tokens indicating the // template parameters. we need this in // here because we may want to read in data // again even if we don't know in advance // the template parameters, see step-19 out << dim << ' ' << spacedim << '\n'; // then write a header out << "[deal.II intermediate format graphics data]" << '\n' << "[written by " << DEAL_II_PACKAGE_NAME << " " << DEAL_II_PACKAGE_VERSION << "]" << '\n' << "[Version: " << Deal_II_IntermediateFlags::format_version << "]" << '\n'; out << data_names.size() << '\n'; for (unsigned int i=0; i<data_names.size(); ++i) out << data_names[i] << '\n'; out << patches.size() << '\n'; for (unsigned int i=0; i<patches.size(); ++i) out << patches[i] << '\n'; out << vector_data_ranges.size() << '\n'; for (unsigned int i=0; i<vector_data_ranges.size(); ++i) out << std_cxx11::get<0>(vector_data_ranges[i]) << ' ' << std_cxx11::get<1>(vector_data_ranges[i]) << '\n' << std_cxx11::get<2>(vector_data_ranges[i]) << '\n'; out << '\n'; // make sure everything now gets to // disk out.flush (); } std::pair<unsigned int, unsigned int> determine_intermediate_format_dimensions (std::istream &input) { AssertThrow (input, ExcIO()); unsigned int dim, spacedim; input >> dim >> spacedim; return std::make_pair (dim, spacedim); } } // namespace DataOutBase /* --------------------------- class DataOutInterface ---------------------- */ template <int dim, int spacedim> DataOutInterface<dim,spacedim>::DataOutInterface () : default_subdivisions(1) {} template <int dim, int spacedim> DataOutInterface<dim,spacedim>::~DataOutInterface () {} template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_dx (std::ostream &out) const { DataOutBase::write_dx (get_patches(), get_dataset_names(), get_vector_data_ranges(), dx_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_ucd (std::ostream &out) const { DataOutBase::write_ucd (get_patches(), get_dataset_names(), get_vector_data_ranges(), ucd_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_gnuplot (std::ostream &out) const { DataOutBase::write_gnuplot (get_patches(), get_dataset_names(), get_vector_data_ranges(), gnuplot_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_povray (std::ostream &out) const { DataOutBase::write_povray (get_patches(), get_dataset_names(), get_vector_data_ranges(), povray_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_eps (std::ostream &out) const { DataOutBase::write_eps (get_patches(), get_dataset_names(), get_vector_data_ranges(), eps_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_gmv (std::ostream &out) const { DataOutBase::write_gmv (get_patches(), get_dataset_names(), get_vector_data_ranges(), gmv_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_tecplot (std::ostream &out) const { DataOutBase::write_tecplot (get_patches(), get_dataset_names(), get_vector_data_ranges(), tecplot_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_tecplot_binary (std::ostream &out) const { DataOutBase::write_tecplot_binary (get_patches(), get_dataset_names(), get_vector_data_ranges(), tecplot_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_vtk (std::ostream &out) const { DataOutBase::write_vtk (get_patches(), get_dataset_names(), get_vector_data_ranges(), vtk_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_vtu (std::ostream &out) const { DataOutBase::write_vtu (get_patches(), get_dataset_names(), get_vector_data_ranges(), vtk_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_svg (std::ostream &out) const { DataOutBase::write_svg (get_patches(), get_dataset_names(), get_vector_data_ranges(), svg_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_vtu_in_parallel (const char *filename, MPI_Comm comm) const { #ifndef DEAL_II_WITH_MPI //without MPI fall back to the normal way to write a vtu file: (void)comm; std::ofstream f(filename); write_vtu (f); #else int myrank, nproc, err; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm, &nproc); MPI_Info info; MPI_Info_create(&info); MPI_File fh; err = MPI_File_open(comm, const_cast<char *>(filename), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &fh); AssertThrow(err==0, ExcMessage("Unable to open file with MPI_File_open!")); MPI_File_set_size(fh, 0); // delete the file contents // this barrier is necessary, because otherwise others might already // write while one core is still setting the size to zero. MPI_Barrier(comm); MPI_Info_free(&info); unsigned int header_size; //write header if (myrank==0) { std::stringstream ss; DataOutBase::write_vtu_header(ss, vtk_flags); header_size = ss.str().size(); MPI_File_write(fh, const_cast<char *>(ss.str().c_str()), header_size, MPI_CHAR, MPI_STATUS_IGNORE); } MPI_Bcast(&header_size, 1, MPI_INT, 0, comm); MPI_File_seek_shared( fh, header_size, MPI_SEEK_SET ); { std::stringstream ss; DataOutBase::write_vtu_main (get_patches(), get_dataset_names(), get_vector_data_ranges(), vtk_flags, ss); MPI_File_write_ordered(fh, const_cast<char *>(ss.str().c_str()), ss.str().size(), MPI_CHAR, MPI_STATUS_IGNORE); } //write footer if (myrank==0) { std::stringstream ss; DataOutBase::write_vtu_footer(ss); unsigned int footer_size = ss.str().size(); MPI_File_write_shared(fh, const_cast<char *>(ss.str().c_str()), footer_size, MPI_CHAR, MPI_STATUS_IGNORE); } MPI_File_close( &fh ); #endif } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_pvd_record (std::ostream &out, const std::vector<std::pair<double,std::string> > &times_and_names) const { AssertThrow (out, ExcIO()); out << "<?xml version=\"1.0\"?>\n"; std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "<!--\n"; out << "#This file was generated by the deal.II library on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << "\n-->\n"; out << "<VTKFile type=\"Collection\" version=\"0.1\" ByteOrder=\"LittleEndian\">\n"; out << " <Collection>\n"; for (unsigned int i=0; i<times_and_names.size(); ++i) out << " <DataSet timestep=\"" << times_and_names[i].first << "\" group=\"\" part=\"0\" file=\"" << times_and_names[i].second << "\"/>\n"; out << " </Collection>\n"; out << "</VTKFile>\n"; out.flush(); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_pvtu_record (std::ostream &out, const std::vector<std::string> &piece_names) const { AssertThrow (out, ExcIO()); const std::vector<std::string> data_names = get_dataset_names(); const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > vector_data_ranges = get_vector_data_ranges(); const unsigned int n_data_sets = data_names.size(); out << "<?xml version=\"1.0\"?>\n"; std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "<!--\n"; out << "#This file was generated by the deal.II library on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << "\n-->\n"; out << "<VTKFile type=\"PUnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n"; out << " <PUnstructuredGrid GhostLevel=\"0\">\n"; out << " <PPointData Scalars=\"scalars\">\n"; // We need to output in the same order as // the write_vtu function does: std::vector<bool> data_set_written (n_data_sets, false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) + 1 - std_cxx11::get<0>(vector_data_ranges[n_th_vector]) <= 3, ExcMessage ("Can't declare a vector with more than 3 components " "in VTK")); // mark these components as already // written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << " <PDataArray type=\"Float64\" Name=\""; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << "\" NumberOfComponents=\"3\" format=\"ascii\"/>\n"; } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) if (data_set_written[data_set] == false) { out << " <PDataArray type=\"Float64\" Name=\"" << data_names[data_set] << "\" format=\"ascii\"/>\n"; } out << " </PPointData>\n"; out << " <PPoints>\n"; out << " <PDataArray type=\"Float64\" NumberOfComponents=\"3\"/>\n"; out << " </PPoints>\n"; for (unsigned int i=0; i<piece_names.size(); ++i) out << " <Piece Source=\"" << piece_names[i] << "\"/>\n"; out << " </PUnstructuredGrid>\n"; out << "</VTKFile>\n"; out.flush(); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_visit_record (std::ostream &out, const std::vector<std::string> &piece_names) const { out << "!NBLOCKS " << piece_names.size() << '\n'; for (unsigned int i=0; i<piece_names.size(); ++i) out << piece_names[i] << '\n'; out << std::flush; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_visit_record (std::ostream &out, const std::vector<std::vector<std::string> > &piece_names) const { AssertThrow (out, ExcIO()); if (piece_names.size() == 0) return; const double nblocks = piece_names[0].size(); Assert(nblocks > 0, ExcMessage("piece_names should be a vector of nonempty vectors.") ) out << "!NBLOCKS " << nblocks << '\n'; for (std::vector<std::vector<std::string> >::const_iterator domain = piece_names.begin(); domain != piece_names.end(); ++domain) { Assert(domain->size() == nblocks, ExcMessage("piece_names should be a vector of equal sized vectors.") ) for (std::vector<std::string>::const_iterator subdomain = domain->begin(); subdomain != domain->end(); ++subdomain) out << *subdomain << '\n'; } out << std::flush; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_deal_II_intermediate (std::ostream &out) const { DataOutBase::write_deal_II_intermediate (get_patches(), get_dataset_names(), get_vector_data_ranges(), deal_II_intermediate_flags, out); } template <int dim, int spacedim> XDMFEntry DataOutInterface<dim,spacedim>:: create_xdmf_entry (const DataOutBase::DataOutFilter &data_filter, const std::string &h5_filename, const double cur_time, MPI_Comm comm) const { return create_xdmf_entry(data_filter, h5_filename, h5_filename, cur_time, comm); } template <int dim, int spacedim> XDMFEntry DataOutInterface<dim,spacedim>:: create_xdmf_entry (const DataOutBase::DataOutFilter &data_filter, const std::string &h5_mesh_filename, const std::string &h5_solution_filename, const double cur_time, MPI_Comm comm) const { unsigned int local_node_cell_count[2], global_node_cell_count[2]; int myrank; #ifndef DEAL_II_WITH_HDF5 // throw an exception, but first make // sure the compiler does not warn about // the now unused function arguments (void)data_filter; (void)h5_mesh_filename; (void)h5_solution_filename; (void)cur_time; (void)comm; AssertThrow(false, ExcMessage ("XDMF support requires HDF5 to be turned on.")); #endif AssertThrow(dim == 2 || dim == 3, ExcMessage ("XDMF only supports 2 or 3 dimensions.")); local_node_cell_count[0] = data_filter.n_nodes(); local_node_cell_count[1] = data_filter.n_cells(); // And compute the global total #ifdef DEAL_II_WITH_MPI MPI_Comm_rank(comm, &myrank); MPI_Allreduce(local_node_cell_count, global_node_cell_count, 2, MPI_UNSIGNED, MPI_SUM, comm); #else myrank = 0; global_node_cell_count[0] = local_node_cell_count[0]; global_node_cell_count[1] = local_node_cell_count[1]; #endif // Output the XDMF file only on the root process if (myrank == 0) { XDMFEntry entry(h5_mesh_filename, h5_solution_filename, cur_time, global_node_cell_count[0], global_node_cell_count[1], dim); unsigned int n_data_sets = data_filter.n_data_sets(); // The vector names generated here must match those generated in the HDF5 file unsigned int i; for (i=0; i<n_data_sets; ++i) { entry.add_attribute(data_filter.get_data_set_name(i), data_filter.get_data_set_dim(i)); } return entry; } else { return XDMFEntry(); } } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_xdmf_file (const std::vector<XDMFEntry> &entries, const std::string &filename, MPI_Comm comm) const { int myrank; #ifdef DEAL_II_WITH_MPI MPI_Comm_rank(comm, &myrank); #else (void)comm; myrank = 0; #endif // Only rank 0 process writes the XDMF file if (myrank == 0) { std::ofstream xdmf_file(filename.c_str()); std::vector<XDMFEntry>::const_iterator it; xdmf_file << "<?xml version=\"1.0\" ?>\n"; xdmf_file << "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"; xdmf_file << "<Xdmf Version=\"2.0\">\n"; xdmf_file << " <Domain>\n"; xdmf_file << " <Grid Name=\"CellTime\" GridType=\"Collection\" CollectionType=\"Temporal\">\n"; // Write out all the entries indented for (it=entries.begin(); it!=entries.end(); ++it) xdmf_file << it->get_xdmf_content(3); xdmf_file << " </Grid>\n"; xdmf_file << " </Domain>\n"; xdmf_file << "</Xdmf>\n"; xdmf_file.close(); } } /* * Get the XDMF content associated with this entry. * If the entry is not valid, this returns an empty string. */ std::string XDMFEntry::get_xdmf_content(const unsigned int indent_level) const { std::stringstream ss; std::map<std::string, unsigned int>::const_iterator it; if (!valid) return ""; ss << indent(indent_level+0) << "<Grid Name=\"mesh\" GridType=\"Uniform\">\n"; ss << indent(indent_level+1) << "<Time Value=\"" << entry_time << "\"/>\n"; ss << indent(indent_level+1) << "<Geometry GeometryType=\"" << (dimension == 2 ? "XY" : "XYZ" ) << "\">\n"; ss << indent(indent_level+2) << "<DataItem Dimensions=\"" << num_nodes << " " << dimension << "\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n"; ss << indent(indent_level+3) << h5_mesh_filename << ":/nodes\n"; ss << indent(indent_level+2) << "</DataItem>\n"; ss << indent(indent_level+1) << "</Geometry>\n"; // If we have cells defined, use a quadrilateral (2D) or hexahedron (3D) topology if (num_cells > 0) { ss << indent(indent_level+1) << "<Topology TopologyType=\"" << (dimension == 2 ? "Quadrilateral" : "Hexahedron") << "\" NumberOfElements=\"" << num_cells << "\">\n"; ss << indent(indent_level+2) << "<DataItem Dimensions=\"" << num_cells << " " << (2 << (dimension-1)) << "\" NumberType=\"UInt\" Format=\"HDF\">\n"; ss << indent(indent_level+3) << h5_mesh_filename << ":/cells\n"; ss << indent(indent_level+2) << "</DataItem>\n"; ss << indent(indent_level+1) << "</Topology>\n"; } else { // Otherwise, we assume the points are isolated in space and use a Polyvertex topology ss << indent(indent_level+1) << "<Topology TopologyType=\"Polyvertex\" NumberOfElements=\"" << num_nodes << "\">\n"; ss << indent(indent_level+1) << "</Topology>\n"; } for (it=attribute_dims.begin(); it!=attribute_dims.end(); ++it) { ss << indent(indent_level+1) << "<Attribute Name=\"" << it->first << "\" AttributeType=\"" << (it->second > 1 ? "Vector" : "Scalar") << "\" Center=\"Node\">\n"; // Vectors must have 3 elements even for 2D models ss << indent(indent_level+2) << "<DataItem Dimensions=\"" << num_nodes << " " << (it->second > 1 ? 3 : 1) << "\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n"; ss << indent(indent_level+3) << h5_sol_filename << ":/" << it->first << "\n"; ss << indent(indent_level+2) << "</DataItem>\n"; ss << indent(indent_level+1) << "</Attribute>\n"; } ss << indent(indent_level+0) << "</Grid>\n"; return ss.str(); } /* * Write the data in this DataOutInterface to a DataOutFilter object. * Filtering is performed based on the DataOutFilter flags. */ template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_filtered_data (DataOutBase::DataOutFilter &filtered_data) const { DataOutBase::write_filtered_data(get_patches(), get_dataset_names(), get_vector_data_ranges(), filtered_data); } template <int dim, int spacedim> void DataOutBase::write_filtered_data (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, DataOutBase::DataOutFilter &filtered_data) { const unsigned int n_data_sets = data_names.size(); unsigned int n_node, n_cell; Table<2,double> data_vectors; Threads::Task<> reorder_task; #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #endif compute_sizes<dim,spacedim>(patches, n_node, n_cell); data_vectors = Table<2,double> (n_data_sets, n_node); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &DataOutBase::template write_gmv_reorder_data_vectors<dim,spacedim>; reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); // Write the nodes/cells to the DataOutFilter object. write_nodes(patches, filtered_data); write_cells(patches, filtered_data); // Ensure reordering is done before we output data set values reorder_task.join (); // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over unsigned int i, n_th_vector, data_set, pt_data_vector_dim; std::string vector_name; for (n_th_vector=0,data_set=0; data_set<n_data_sets;) { // Advance n_th_vector to at least the current data set we are on while (n_th_vector < vector_data_ranges.size() && std_cxx11::get<0>(vector_data_ranges[n_th_vector]) < data_set) n_th_vector++; // Determine the dimension of this data if (n_th_vector < vector_data_ranges.size() && std_cxx11::get<0>(vector_data_ranges[n_th_vector]) == data_set) { // Multiple dimensions pt_data_vector_dim = std_cxx11::get<1>(vector_data_ranges[n_th_vector]) - std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1; // Ensure the dimensionality of the data is correct AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); // Determine the vector name // Concatenate all the // component names with double // underscores unless a vector // name has been specified if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") { vector_name = std_cxx11::get<2>(vector_data_ranges[n_th_vector]); } else { vector_name = ""; for (i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) vector_name += data_names[i] + "__"; vector_name += data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } } else { // One dimension pt_data_vector_dim = 1; vector_name = data_names[data_set]; } // Write data to the filter object filtered_data.write_data_set(vector_name, pt_data_vector_dim, data_set, data_vectors); // Advance the current data set data_set += pt_data_vector_dim; } } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_hdf5_parallel (const DataOutBase::DataOutFilter &data_filter, const std::string &filename, MPI_Comm comm) const { DataOutBase::write_hdf5_parallel(get_patches(), data_filter, filename, comm); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_hdf5_parallel (const DataOutBase::DataOutFilter &data_filter, const bool write_mesh_file, const std::string &mesh_filename, const std::string &solution_filename, MPI_Comm comm) const { DataOutBase::write_hdf5_parallel(get_patches(), data_filter, write_mesh_file, mesh_filename, solution_filename, comm); } template <int dim, int spacedim> void DataOutBase::write_hdf5_parallel (const std::vector<Patch<dim,spacedim> > &patches, const DataOutBase::DataOutFilter &data_filter, const std::string &filename, MPI_Comm comm) { write_hdf5_parallel(patches, data_filter, true, filename, filename, comm); } template <int dim, int spacedim> void DataOutBase::write_hdf5_parallel (const std::vector<Patch<dim,spacedim> > &/*patches*/, const DataOutBase::DataOutFilter &data_filter, const bool write_mesh_file, const std::string &mesh_filename, const std::string &solution_filename, MPI_Comm comm) { #ifndef DEAL_II_WITH_HDF5 // throw an exception, but first make // sure the compiler does not warn about // the now unused function arguments (void)data_filter; (void)write_mesh_file; (void)mesh_filename; (void)solution_filename; (void)comm; AssertThrow(false, ExcMessage ("HDF5 support is disabled.")); #else #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (data_filter.n_nodes() > 0, ExcNoPatches()); #else hid_t h5_mesh_file_id=-1, h5_solution_file_id, file_plist_id, plist_id; hid_t node_dataspace, node_dataset, node_file_dataspace, node_memory_dataspace; hid_t cell_dataspace, cell_dataset, cell_file_dataspace, cell_memory_dataspace; hid_t pt_data_dataspace, pt_data_dataset, pt_data_file_dataspace, pt_data_memory_dataspace; herr_t status; unsigned int local_node_cell_count[2], global_node_cell_count[2], global_node_cell_offsets[2]; hsize_t count[2], offset[2], node_ds_dim[2], cell_ds_dim[2]; std::vector<double> node_data_vec; std::vector<unsigned int> cell_data_vec; // If HDF5 is not parallel and we're using multiple processes, abort #ifndef H5_HAVE_PARALLEL # ifdef DEAL_II_WITH_MPI int world_size; MPI_Comm_size(comm, &world_size); AssertThrow (world_size <= 1, ExcMessage ("Serial HDF5 output on multiple processes is not yet supported.")); # endif #endif local_node_cell_count[0] = data_filter.n_nodes(); local_node_cell_count[1] = data_filter.n_cells(); // Create file access properties file_plist_id = H5Pcreate(H5P_FILE_ACCESS); AssertThrow(file_plist_id != -1, ExcIO()); // If MPI is enabled *and* HDF5 is parallel, we can do parallel output #ifdef DEAL_II_WITH_MPI #ifdef H5_HAVE_PARALLEL // Set the access to use the specified MPI_Comm object status = H5Pset_fapl_mpio(file_plist_id, comm, MPI_INFO_NULL); AssertThrow(status >= 0, ExcIO()); #endif #endif // Compute the global total number of nodes/cells // And determine the offset of the data for this process #ifdef DEAL_II_WITH_MPI MPI_Allreduce(local_node_cell_count, global_node_cell_count, 2, MPI_UNSIGNED, MPI_SUM, comm); MPI_Scan(local_node_cell_count, global_node_cell_offsets, 2, MPI_UNSIGNED, MPI_SUM, comm); global_node_cell_offsets[0] -= local_node_cell_count[0]; global_node_cell_offsets[1] -= local_node_cell_count[1]; #else global_node_cell_offsets[0] = global_node_cell_offsets[1] = 0; #endif // Create the property list for a collective write plist_id = H5Pcreate(H5P_DATASET_XFER); AssertThrow(plist_id >= 0, ExcIO()); #ifdef DEAL_II_WITH_MPI #ifdef H5_HAVE_PARALLEL status = H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); AssertThrow(status >= 0, ExcIO()); #endif #endif if (write_mesh_file) { // Overwrite any existing files (change this to an option?) h5_mesh_file_id = H5Fcreate(mesh_filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, file_plist_id); AssertThrow(h5_mesh_file_id >= 0, ExcIO()); // Create the dataspace for the nodes and cells node_ds_dim[0] = global_node_cell_count[0]; node_ds_dim[1] = dim; node_dataspace = H5Screate_simple(2, node_ds_dim, NULL); AssertThrow(node_dataspace >= 0, ExcIO()); cell_ds_dim[0] = global_node_cell_count[1]; cell_ds_dim[1] = GeometryInfo<dim>::vertices_per_cell; cell_dataspace = H5Screate_simple(2, cell_ds_dim, NULL); AssertThrow(cell_dataspace >= 0, ExcIO()); // Create the dataset for the nodes and cells #if H5Gcreate_vers == 1 node_dataset = H5Dcreate(h5_mesh_file_id, "nodes", H5T_NATIVE_DOUBLE, node_dataspace, H5P_DEFAULT); #else node_dataset = H5Dcreate(h5_mesh_file_id, "nodes", H5T_NATIVE_DOUBLE, node_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif AssertThrow(node_dataset >= 0, ExcIO()); #if H5Gcreate_vers == 1 cell_dataset = H5Dcreate(h5_mesh_file_id, "cells", H5T_NATIVE_UINT, cell_dataspace, H5P_DEFAULT); #else cell_dataset = H5Dcreate(h5_mesh_file_id, "cells", H5T_NATIVE_UINT, cell_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif AssertThrow(cell_dataset >= 0, ExcIO()); // Close the node and cell dataspaces since we're done with them status = H5Sclose(node_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(cell_dataspace); AssertThrow(status >= 0, ExcIO()); // Create the data subset we'll use to read from memory count[0] = local_node_cell_count[0]; count[1] = dim; offset[0] = global_node_cell_offsets[0]; offset[1] = 0; node_memory_dataspace = H5Screate_simple(2, count, NULL); AssertThrow(node_memory_dataspace >= 0, ExcIO()); // Select the hyperslab in the file node_file_dataspace = H5Dget_space(node_dataset); AssertThrow(node_file_dataspace >= 0, ExcIO()); status = H5Sselect_hyperslab(node_file_dataspace, H5S_SELECT_SET, offset, NULL, count, NULL); AssertThrow(status >= 0, ExcIO()); // And repeat for cells count[0] = local_node_cell_count[1]; count[1] = GeometryInfo<dim>::vertices_per_cell; offset[0] = global_node_cell_offsets[1]; offset[1] = 0; cell_memory_dataspace = H5Screate_simple(2, count, NULL); AssertThrow(cell_memory_dataspace >= 0, ExcIO()); cell_file_dataspace = H5Dget_space(cell_dataset); AssertThrow(cell_file_dataspace >= 0, ExcIO()); status = H5Sselect_hyperslab(cell_file_dataspace, H5S_SELECT_SET, offset, NULL, count, NULL); AssertThrow(status >= 0, ExcIO()); // And finally, write the node data data_filter.fill_node_data(node_data_vec); status = H5Dwrite(node_dataset, H5T_NATIVE_DOUBLE, node_memory_dataspace, node_file_dataspace, plist_id, &node_data_vec[0]); AssertThrow(status >= 0, ExcIO()); node_data_vec.clear(); // And the cell data data_filter.fill_cell_data(global_node_cell_offsets[0], cell_data_vec); status = H5Dwrite(cell_dataset, H5T_NATIVE_UINT, cell_memory_dataspace, cell_file_dataspace, plist_id, &cell_data_vec[0]); AssertThrow(status >= 0, ExcIO()); cell_data_vec.clear(); // Close the file dataspaces status = H5Sclose(node_file_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(cell_file_dataspace); AssertThrow(status >= 0, ExcIO()); // Close the memory dataspaces status = H5Sclose(node_memory_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(cell_memory_dataspace); AssertThrow(status >= 0, ExcIO()); // Close the datasets status = H5Dclose(node_dataset); AssertThrow(status >= 0, ExcIO()); status = H5Dclose(cell_dataset); AssertThrow(status >= 0, ExcIO()); // If the filenames are different, we need to close the mesh file if (mesh_filename != solution_filename) { status = H5Fclose(h5_mesh_file_id); AssertThrow(status >= 0, ExcIO()); } } // If the filenames are identical, continue with the same file if (mesh_filename == solution_filename && write_mesh_file) { h5_solution_file_id = h5_mesh_file_id; } else { // Otherwise we need to open a new file h5_solution_file_id = H5Fcreate(solution_filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, file_plist_id); AssertThrow(h5_solution_file_id >= 0, ExcIO()); } // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over unsigned int i, pt_data_vector_dim; std::string vector_name; for (i=0; i<data_filter.n_data_sets(); ++i) { // Allocate space for the point data // Must be either 1D or 3D pt_data_vector_dim = data_filter.get_data_set_dim(i); vector_name = data_filter.get_data_set_name(i); // Create the dataspace for the point data node_ds_dim[0] = global_node_cell_count[0]; node_ds_dim[1] = pt_data_vector_dim; pt_data_dataspace = H5Screate_simple(2, node_ds_dim, NULL); AssertThrow(pt_data_dataspace >= 0, ExcIO()); #if H5Gcreate_vers == 1 pt_data_dataset = H5Dcreate(h5_solution_file_id, vector_name.c_str(), H5T_NATIVE_DOUBLE, pt_data_dataspace, H5P_DEFAULT); #else pt_data_dataset = H5Dcreate(h5_solution_file_id, vector_name.c_str(), H5T_NATIVE_DOUBLE, pt_data_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif AssertThrow(pt_data_dataset >= 0, ExcIO()); // Create the data subset we'll use to read from memory count[0] = local_node_cell_count[0]; count[1] = pt_data_vector_dim; offset[0] = global_node_cell_offsets[0]; offset[1] = 0; pt_data_memory_dataspace = H5Screate_simple(2, count, NULL); AssertThrow(pt_data_memory_dataspace >= 0, ExcIO()); // Select the hyperslab in the file pt_data_file_dataspace = H5Dget_space(pt_data_dataset); AssertThrow(pt_data_file_dataspace >= 0, ExcIO()); status = H5Sselect_hyperslab(pt_data_file_dataspace, H5S_SELECT_SET, offset, NULL, count, NULL); AssertThrow(status >= 0, ExcIO()); // And finally, write the data status = H5Dwrite(pt_data_dataset, H5T_NATIVE_DOUBLE, pt_data_memory_dataspace, pt_data_file_dataspace, plist_id, data_filter.get_data_set(i)); AssertThrow(status >= 0, ExcIO()); // Close the dataspaces status = H5Sclose(pt_data_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(pt_data_memory_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(pt_data_file_dataspace); AssertThrow(status >= 0, ExcIO()); // Close the dataset status = H5Dclose(pt_data_dataset); AssertThrow(status >= 0, ExcIO()); } // Close the file property list status = H5Pclose(file_plist_id); AssertThrow(status >= 0, ExcIO()); // Close the parallel access status = H5Pclose(plist_id); AssertThrow(status >= 0, ExcIO()); // Close the file status = H5Fclose(h5_solution_file_id); AssertThrow(status >= 0, ExcIO()); #endif #endif } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write (std::ostream &out, const DataOutBase::OutputFormat output_format_) const { DataOutBase::OutputFormat output_format = output_format_; if (output_format == DataOutBase::default_format) output_format = default_fmt; switch (output_format) { case DataOutBase::none: break; case DataOutBase::dx: write_dx (out); break; case DataOutBase::ucd: write_ucd (out); break; case DataOutBase::gnuplot: write_gnuplot (out); break; case DataOutBase::povray: write_povray (out); break; case DataOutBase::eps: write_eps (out); break; case DataOutBase::gmv: write_gmv (out); break; case DataOutBase::tecplot: write_tecplot (out); break; case DataOutBase::tecplot_binary: write_tecplot_binary (out); break; case DataOutBase::vtk: write_vtk (out); break; case DataOutBase::vtu: write_vtu (out); break; case DataOutBase::svg: write_svg (out); break; case DataOutBase::deal_II_intermediate: write_deal_II_intermediate (out); break; default: Assert (false, ExcNotImplemented()); } } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_default_format(const DataOutBase::OutputFormat fmt) { Assert (fmt != DataOutBase::default_format, ExcNotImplemented()); default_fmt = fmt; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::DXFlags &flags) { dx_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::UcdFlags &flags) { ucd_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::GnuplotFlags &flags) { gnuplot_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::PovrayFlags &flags) { povray_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::EpsFlags &flags) { eps_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::GmvFlags &flags) { gmv_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::TecplotFlags &flags) { tecplot_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::VtkFlags &flags) { vtk_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::SvgFlags &flags) { svg_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::Deal_II_IntermediateFlags &flags) { deal_II_intermediate_flags = flags; } template <int dim, int spacedim> std::string DataOutInterface<dim,spacedim>:: default_suffix (const DataOutBase::OutputFormat output_format) const { if (output_format == DataOutBase::default_format) return DataOutBase::default_suffix (default_fmt); else return DataOutBase::default_suffix (output_format); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Output format", "gnuplot", Patterns::Selection (DataOutBase::get_output_format_names ()), "A name for the output format to be used"); prm.declare_entry("Subdivisions", "1", Patterns::Integer(), "Number of subdivisions of each mesh cell"); prm.enter_subsection ("DX output parameters"); DataOutBase::DXFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("UCD output parameters"); DataOutBase::UcdFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gnuplot output parameters"); DataOutBase::GnuplotFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Povray output parameters"); DataOutBase::PovrayFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Eps output parameters"); DataOutBase::EpsFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gmv output parameters"); DataOutBase::GmvFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Tecplot output parameters"); DataOutBase::TecplotFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Vtk output parameters"); DataOutBase::VtkFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("deal.II intermediate output parameters"); DataOutBase::Deal_II_IntermediateFlags::declare_parameters (prm); prm.leave_subsection (); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::parse_parameters (ParameterHandler &prm) { const std::string &output_name = prm.get ("Output format"); default_fmt = DataOutBase::parse_output_format (output_name); default_subdivisions = prm.get_integer ("Subdivisions"); prm.enter_subsection ("DX output parameters"); dx_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("UCD output parameters"); ucd_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gnuplot output parameters"); gnuplot_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Povray output parameters"); povray_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Eps output parameters"); eps_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gmv output parameters"); gmv_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Tecplot output parameters"); tecplot_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Vtk output parameters"); vtk_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("deal.II intermediate output parameters"); deal_II_intermediate_flags.parse_parameters (prm); prm.leave_subsection (); } template <int dim, int spacedim> std::size_t DataOutInterface<dim,spacedim>::memory_consumption () const { return (sizeof (default_fmt) + MemoryConsumption::memory_consumption (dx_flags) + MemoryConsumption::memory_consumption (ucd_flags) + MemoryConsumption::memory_consumption (gnuplot_flags) + MemoryConsumption::memory_consumption (povray_flags) + MemoryConsumption::memory_consumption (eps_flags) + MemoryConsumption::memory_consumption (gmv_flags) + MemoryConsumption::memory_consumption (tecplot_flags) + MemoryConsumption::memory_consumption (vtk_flags) + MemoryConsumption::memory_consumption (svg_flags) + MemoryConsumption::memory_consumption (deal_II_intermediate_flags)); } template <int dim, int spacedim> std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > DataOutInterface<dim,spacedim>::get_vector_data_ranges () const { return std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> >(); } // ---------------------------------------------- DataOutReader ---------- template <int dim, int spacedim> void DataOutReader<dim,spacedim>::read (std::istream &in) { AssertThrow (in, ExcIO()); // first empty previous content { std::vector<typename dealii::DataOutBase::Patch<dim,spacedim> > tmp; tmp.swap (patches); } { std::vector<std::string> tmp; tmp.swap (dataset_names); } { std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > tmp; tmp.swap (vector_data_ranges); } // then check that we have the // correct header of this // file. both the first and second // real lines have to match, as // well as the dimension // information written before that // and the Version information // written in the third line { std::pair<unsigned int, unsigned int> dimension_info = DataOutBase::determine_intermediate_format_dimensions (in); AssertThrow ((dimension_info.first == dim) && (dimension_info.second == spacedim), ExcIncompatibleDimensions (dimension_info.first, dim, dimension_info.second, spacedim)); // read to the end of the line std::string tmp; getline (in, tmp); } { std::string header; getline (in, header); std::ostringstream s; s << "[deal.II intermediate format graphics data]"; Assert (header == s.str(), ExcUnexpectedInput(s.str(),header)); } { std::string header; getline (in, header); std::ostringstream s; s << "[written by " << DEAL_II_PACKAGE_NAME << " " << DEAL_II_PACKAGE_VERSION << "]"; Assert (header == s.str(), ExcUnexpectedInput(s.str(),header)); } { std::string header; getline (in, header); std::ostringstream s; s << "[Version: " << dealii::DataOutBase::Deal_II_IntermediateFlags::format_version << "]"; Assert (header == s.str(), ExcMessage("Invalid or incompatible file format. Intermediate format " "files can only be read by the same deal.II version as they " "are written by.")); } // then read the rest of the data unsigned int n_datasets; in >> n_datasets; dataset_names.resize (n_datasets); for (unsigned int i=0; i<n_datasets; ++i) in >> dataset_names[i]; unsigned int n_patches; in >> n_patches; patches.resize (n_patches); for (unsigned int i=0; i<n_patches; ++i) in >> patches[i]; unsigned int n_vector_data_ranges; in >> n_vector_data_ranges; vector_data_ranges.resize (n_vector_data_ranges); for (unsigned int i=0; i<n_vector_data_ranges; ++i) { in >> std_cxx11::get<0>(vector_data_ranges[i]) >> std_cxx11::get<1>(vector_data_ranges[i]); // read in the name of that vector // range. because it is on a separate // line, we first need to read to the // end of the previous line (nothing // should be there any more after we've // read the previous two integers) and // then read the entire next line for // the name std::string name; getline(in, name); getline(in, name); std_cxx11::get<2>(vector_data_ranges[i]) = name; } AssertThrow (in, ExcIO()); } template <int dim, int spacedim> void DataOutReader<dim,spacedim>:: merge (const DataOutReader<dim,spacedim> &source) { typedef typename dealii::DataOutBase::Patch<dim,spacedim> Patch; const std::vector<Patch> source_patches = source.get_patches (); Assert (patches.size () != 0, ExcNoPatches ()); Assert (source_patches.size () != 0, ExcNoPatches ()); // check equality of component // names Assert (get_dataset_names() == source.get_dataset_names(), ExcIncompatibleDatasetNames()); // check equality of the vector data // specifications Assert (get_vector_data_ranges().size() == source.get_vector_data_ranges().size(), ExcMessage ("Both sources need to declare the same components " "as vectors.")); for (unsigned int i=0; i<get_vector_data_ranges().size(); ++i) { Assert (std_cxx11::get<0>(get_vector_data_ranges()[i]) == std_cxx11::get<0>(source.get_vector_data_ranges()[i]), ExcMessage ("Both sources need to declare the same components " "as vectors.")); Assert (std_cxx11::get<1>(get_vector_data_ranges()[i]) == std_cxx11::get<1>(source.get_vector_data_ranges()[i]), ExcMessage ("Both sources need to declare the same components " "as vectors.")); Assert (std_cxx11::get<2>(get_vector_data_ranges()[i]) == std_cxx11::get<2>(source.get_vector_data_ranges()[i]), ExcMessage ("Both sources need to declare the same components " "as vectors.")); } // make sure patches are compatible Assert (patches[0].n_subdivisions == source_patches[0].n_subdivisions, ExcIncompatiblePatchLists()); Assert (patches[0].data.n_rows() == source_patches[0].data.n_rows(), ExcIncompatiblePatchLists()); Assert (patches[0].data.n_cols() == source_patches[0].data.n_cols(), ExcIncompatiblePatchLists()); // merge patches. store old number // of elements, since we need to // adjust patch numbers, etc // afterwards const unsigned int old_n_patches = patches.size(); patches.insert (patches.end(), source_patches.begin(), source_patches.end()); // adjust patch numbers for (unsigned int i=old_n_patches; i<patches.size(); ++i) patches[i].patch_index += old_n_patches; // adjust patch neighbors for (unsigned int i=old_n_patches; i<patches.size(); ++i) for (unsigned int n=0; n<GeometryInfo<dim>::faces_per_cell; ++n) if (patches[i].neighbors[n] != dealii::DataOutBase::Patch<dim,spacedim>::no_neighbor) patches[i].neighbors[n] += old_n_patches; } template <int dim, int spacedim> const std::vector<typename dealii::DataOutBase::Patch<dim,spacedim> > & DataOutReader<dim,spacedim>::get_patches () const { return patches; } template <int dim, int spacedim> std::vector<std::string> DataOutReader<dim,spacedim>::get_dataset_names () const { return dataset_names; } template <int dim, int spacedim> std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > DataOutReader<dim,spacedim>::get_vector_data_ranges () const { return vector_data_ranges; } namespace DataOutBase { template <int dim, int spacedim> std::ostream & operator << (std::ostream &out, const Patch<dim,spacedim> &patch) { // write a header line out << "[deal.II intermediate Patch<" << dim << ',' << spacedim << ">]" << '\n'; // then write all the data that is // in this patch for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i) out << patch.vertices[GeometryInfo<dim>::ucd_to_deal[i]] << ' '; out << '\n'; for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) out << patch.neighbors[i] << ' '; out << '\n'; out << patch.patch_index << ' ' << patch.n_subdivisions << '\n'; out << patch.points_are_available<<'\n'; out << patch.data.n_rows() << ' ' << patch.data.n_cols() << '\n'; for (unsigned int i=0; i<patch.data.n_rows(); ++i) for (unsigned int j=0; j<patch.data.n_cols(); ++j) out << patch.data[i][j] << ' '; out << '\n'; out << '\n'; return out; } template <int dim, int spacedim> std::istream & operator >> (std::istream &in, Patch<dim,spacedim> &patch) { AssertThrow (in, ExcIO()); // read a header line and compare // it to what we usually // write. skip all lines that // contain only blanks at the start { std::string header; do { getline (in, header); while ((header.size() != 0) && (header[header.size()-1] == ' ')) header.erase(header.size()-1); } while ((header == "") && in); std::ostringstream s; s << "[deal.II intermediate Patch<" << dim << ',' << spacedim << ">]"; Assert (header == s.str(), ExcUnexpectedInput(s.str(),header)); } // then read all the data that is // in this patch for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i) in >> patch.vertices[GeometryInfo<dim>::ucd_to_deal[i]]; for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) in >> patch.neighbors[i]; in >> patch.patch_index >> patch.n_subdivisions; in >> patch.points_are_available; unsigned int n_rows, n_cols; in >> n_rows >> n_cols; patch.data.reinit (n_rows, n_cols); for (unsigned int i=0; i<patch.data.n_rows(); ++i) for (unsigned int j=0; j<patch.data.n_cols(); ++j) in >> patch.data[i][j]; AssertThrow (in, ExcIO()); return in; } } // explicit instantiations #include "data_out_base.inst" DEAL_II_NAMESPACE_CLOSE
mtezzele/dealii
source/base/data_out_base.cc
C++
lgpl-2.1
265,443
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "subdirsprojectwizard.h" #include "subdirsprojectwizarddialog.h" #include <projectexplorer/projectexplorerconstants.h> #include <coreplugin/icore.h> #include <QIcon> namespace Qt4ProjectManager { namespace Internal { SubdirsProjectWizard::SubdirsProjectWizard() : QtWizard(QLatin1String("U.Qt4Subdirs"), QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY), QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY), tr("Subdirs Project"), tr("Creates a qmake-based subdirs project. This allows you to group " "your projects in a tree structure."), QIcon(QLatin1String(":/wizards/images/gui.png"))) { } QWizard *SubdirsProjectWizard::createWizardDialog(QWidget *parent, const Core::WizardDialogParameters &wizardDialogParameters) const { SubdirsProjectWizardDialog *dialog = new SubdirsProjectWizardDialog(displayName(), icon(), parent, wizardDialogParameters); dialog->setProjectName(SubdirsProjectWizardDialog::uniqueProjectName(wizardDialogParameters.defaultPath())); const QString buttonText = dialog->wizardStyle() == QWizard::MacStyle ? tr("Done && Add Subproject") : tr("Finish && Add Subproject"); dialog->setButtonText(QWizard::FinishButton, buttonText); return dialog; } Core::GeneratedFiles SubdirsProjectWizard::generateFiles(const QWizard *w, QString * /*errorMessage*/) const { const SubdirsProjectWizardDialog *wizard = qobject_cast< const SubdirsProjectWizardDialog *>(w); const QtProjectParameters params = wizard->parameters(); const QString projectPath = params.projectPath(); const QString profileName = Core::BaseFileWizard::buildFileName(projectPath, params.fileName, profileSuffix()); Core::GeneratedFile profile(profileName); profile.setAttributes(Core::GeneratedFile::OpenProjectAttribute | Core::GeneratedFile::OpenEditorAttribute); profile.setContents(QLatin1String("TEMPLATE = subdirs\n")); return Core::GeneratedFiles() << profile; } bool SubdirsProjectWizard::postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &files, QString *errorMessage) { const SubdirsProjectWizardDialog *wizard = qobject_cast< const SubdirsProjectWizardDialog *>(w); if (QtWizard::qt4ProjectPostGenerateFiles(wizard, files, errorMessage)) { const QtProjectParameters params = wizard->parameters(); const QString projectPath = params.projectPath(); const QString profileName = Core::BaseFileWizard::buildFileName(projectPath, params.fileName, profileSuffix()); QVariantMap map; map.insert(QLatin1String(ProjectExplorer::Constants::PREFERED_PROJECT_NODE), profileName); map.insert(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS), QVariant::fromValue(wizard->selectedKits())); Core::ICore::showNewItemDialog(tr("New Subproject", "Title of dialog"), Core::IWizard::wizardsOfKind(Core::IWizard::ProjectWizard), wizard->parameters().projectPath(), map); } else { return false; } return true; } Core::FeatureSet SubdirsProjectWizard::requiredFeatures() const { return Core::FeatureSet(); } } // namespace Internal } // namespace Qt4ProjectManager
mornelon/QtCreator_compliments
src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp
C++
lgpl-2.1
4,911
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdesigner_formwindow.h" #include "qdesigner_workbench.h" #include "formwindowbase_p.h" // sdk #include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerFormEditorInterface> #include <QtDesigner/QDesignerPropertySheetExtension> #include <QtDesigner/QDesignerPropertyEditorInterface> #include <QtDesigner/QDesignerFormWindowManagerInterface> #include <QtDesigner/QDesignerTaskMenuExtension> #include <QtDesigner/QExtensionManager> #include <QtCore/QEvent> #include <QtCore/QFile> #include <QtGui/QAction> #include <QtGui/QCloseEvent> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtGui/QPushButton> #include <QtGui/QVBoxLayout> #include <QtGui/QUndoCommand> #include <QtGui/QWindowStateChangeEvent> QT_BEGIN_NAMESPACE QDesignerFormWindow::QDesignerFormWindow(QDesignerFormWindowInterface *editor, QDesignerWorkbench *workbench, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags), m_editor(editor), m_workbench(workbench), m_action(new QAction(this)), m_initialized(false), m_windowTitleInitialized(false) { Q_ASSERT(workbench); setMaximumSize(0xFFF, 0xFFF); QDesignerFormEditorInterface *core = workbench->core(); if (m_editor) { m_editor->setParent(this); } else { m_editor = core->formWindowManager()->createFormWindow(this); } QVBoxLayout *l = new QVBoxLayout(this); l->setMargin(0); l->addWidget(m_editor); m_action->setCheckable(true); connect(m_editor->commandHistory(), SIGNAL(indexChanged(int)), this, SLOT(updateChanged())); connect(m_editor, SIGNAL(geometryChanged()), this, SLOT(geometryChanged())); qdesigner_internal::FormWindowBase::setupDefaultAction(m_editor); } QDesignerFormWindow::~QDesignerFormWindow() { if (workbench()) workbench()->removeFormWindow(this); } QAction *QDesignerFormWindow::action() const { return m_action; } void QDesignerFormWindow::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::WindowTitleChange: m_action->setText(windowTitle().remove(QLatin1String("[*]"))); break; case QEvent::WindowIconChange: m_action->setIcon(windowIcon()); break; case QEvent::WindowStateChange: { const QWindowStateChangeEvent *wsce = static_cast<const QWindowStateChangeEvent *>(e); const bool wasMinimized = Qt::WindowMinimized & wsce->oldState(); const bool isMinimizedNow = isMinimized(); if (wasMinimized != isMinimizedNow ) emit minimizationStateChanged(m_editor, isMinimizedNow); } break; default: break; } QWidget::changeEvent(e); } QRect QDesignerFormWindow::geometryHint() const { const QPoint point(0, 0); // If we have a container, we want to be just as big. // QMdiSubWindow attempts to resize its children to sizeHint() when switching user interface modes. if (QWidget *mainContainer = m_editor->mainContainer()) return QRect(point, mainContainer->size()); return QRect(point, sizeHint()); } QDesignerFormWindowInterface *QDesignerFormWindow::editor() const { return m_editor; } QDesignerWorkbench *QDesignerFormWindow::workbench() const { return m_workbench; } void QDesignerFormWindow::firstShow() { // Set up handling of file name changes and set initial title. if (!m_windowTitleInitialized) { m_windowTitleInitialized = true; if (m_editor) { connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString))); updateWindowTitle(m_editor->fileName()); } } show(); } int QDesignerFormWindow::getNumberOfUntitledWindows() const { const int totalWindows = m_workbench->formWindowCount(); if (!totalWindows) return 0; int maxUntitled = 0; // Find the number of untitled windows excluding ourselves. // Do not fall for 'untitled.ui', match with modified place holder. // This will cause some problems with i18n, but for now I need the string to be "static" QRegExp rx(QLatin1String("untitled( (\\d+))?\\[\\*\\]")); for (int i = 0; i < totalWindows; ++i) { QDesignerFormWindow *fw = m_workbench->formWindow(i); if (fw != this) { const QString title = m_workbench->formWindow(i)->windowTitle(); if (rx.indexIn(title) != -1) { if (maxUntitled == 0) ++maxUntitled; if (rx.captureCount() > 1) { const QString numberCapture = rx.cap(2); if (!numberCapture.isEmpty()) maxUntitled = qMax(numberCapture.toInt(), maxUntitled); } } } } return maxUntitled; } void QDesignerFormWindow::updateWindowTitle(const QString &fileName) { if (!m_windowTitleInitialized) { m_windowTitleInitialized = true; if (m_editor) connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString))); } QString fileNameTitle; if (fileName.isEmpty()) { fileNameTitle = QLatin1String("untitled"); if (const int maxUntitled = getNumberOfUntitledWindows()) { fileNameTitle += QLatin1Char(' '); fileNameTitle += QString::number(maxUntitled + 1); } } else { fileNameTitle = QFileInfo(fileName).fileName(); } if (const QWidget *mc = m_editor->mainContainer()) { setWindowIcon(mc->windowIcon()); setWindowTitle(tr("%1 - %2[*]").arg(mc->windowTitle()).arg(fileNameTitle)); } else { setWindowTitle(fileNameTitle); } } void QDesignerFormWindow::closeEvent(QCloseEvent *ev) { if (m_editor->isDirty()) { raise(); QMessageBox box(QMessageBox::Information, tr("Save Form?"), tr("Do you want to save the changes to this document before closing?"), QMessageBox::Discard | QMessageBox::Cancel | QMessageBox::Save, m_editor); box.setInformativeText(tr("If you don't save, your changes will be lost.")); box.setWindowModality(Qt::WindowModal); static_cast<QPushButton *>(box.button(QMessageBox::Save))->setDefault(true); switch (box.exec()) { case QMessageBox::Save: { bool ok = workbench()->saveForm(m_editor); ev->setAccepted(ok); m_editor->setDirty(!ok); break; } case QMessageBox::Discard: m_editor->setDirty(false); // Not really necessary, but stops problems if we get close again. ev->accept(); break; case QMessageBox::Cancel: ev->ignore(); break; } } } void QDesignerFormWindow::updateChanged() { // Sometimes called after form window destruction. if (m_editor) { setWindowModified(m_editor->isDirty()); updateWindowTitle(m_editor->fileName()); } } void QDesignerFormWindow::resizeEvent(QResizeEvent *rev) { if(m_initialized) { m_editor->setDirty(true); setWindowModified(true); } m_initialized = true; QWidget::resizeEvent(rev); } void QDesignerFormWindow::geometryChanged() { // If the form window changes, re-update the geometry of the current widget in the property editor. // Note that in the case of layouts, non-maincontainer widgets must also be updated, // so, do not do it for the main container only const QDesignerFormEditorInterface *core = m_editor->core(); QObject *object = core->propertyEditor()->object(); if (object == 0 || !object->isWidgetType()) return; static const QString geometryProperty = QLatin1String("geometry"); const QDesignerPropertySheetExtension *sheet = qt_extension<QDesignerPropertySheetExtension*>(core->extensionManager(), object); const int geometryIndex = sheet->indexOf(geometryProperty); if (geometryIndex == -1) return; core->propertyEditor()->setPropertyValue(geometryProperty, sheet->property(geometryIndex)); } QT_END_NAMESPACE
igor-sfdc/qt-wk
tools/designer/src/designer/qdesigner_formwindow.cpp
C++
lgpl-2.1
9,680
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <boost/python.hpp> #include <mapnik/datasource_cache.hpp> namespace { using namespace boost::python; boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d) { bool bind=true; mapnik::parameters params; boost::python::list keys=d.keys(); for (int i=0; i<len(keys); ++i) { std::string key = extract<std::string>(keys[i]); object obj = d[key]; if (key == "bind") { bind = extract<bool>(obj)(); continue; } extract<std::string> ex0(obj); extract<int> ex1(obj); extract<double> ex2(obj); if (ex0.check()) { params[key] = ex0(); } else if (ex1.check()) { params[key] = ex1(); } else if (ex2.check()) { params[key] = ex2(); } } return mapnik::datasource_cache::instance().create(params, bind); } void register_datasources(std::string const& path) { mapnik::datasource_cache::instance().register_datasources(path); } std::vector<std::string> plugin_names() { return mapnik::datasource_cache::instance().plugin_names(); } std::string plugin_directories() { return mapnik::datasource_cache::instance().plugin_directories(); } } void export_datasource_cache() { using mapnik::datasource_cache; class_<datasource_cache, boost::noncopyable>("DatasourceCache",no_init) .def("create",&create_datasource) .staticmethod("create") .def("register_datasources",&register_datasources) .staticmethod("register_datasources") .def("plugin_names",&plugin_names) .staticmethod("plugin_names") .def("plugin_directories",&plugin_directories) .staticmethod("plugin_directories") ; }
ake-koomsin/mapnik_nvpr
bindings/python/mapnik_datasource_cache.cpp
C++
lgpl-2.1
2,838
// // Miscellaneous small items related to message sinks // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Loyc { /// <summary>This interface allows an object to declare its "location".</summary> /// <remarks>For example, <see cref="Loyc.Syntax.LNode"/> implements this /// interface so that when a compiler error refers to a source code construct, /// the error message contains the location of that source code rather than the /// code itself. /// <para/> /// Given a context object that may or may not implement this interface, it's /// handy to use <see cref="MessageSink.ContextToString"/> to convert the /// "context" of a message into a string, or <see cref="MessageSink.LocationOf(object)"/> /// to unwrap objects that implement IHasLocation. /// </remarks> public interface IHasLocation { object Location { get; } } /// <summary>This is the method signature of <c>IMessageSink.Write()</c>. You /// can convert from one of these delegates to <see cref="IMessageSink"/> by /// calling <see cref="MessageSink.FromDelegate"/>.</summary> /// <param name="type">Severity or importance of the message; widely-used /// types include Error, Warning, Note, Debug, and Verbose. The special /// type Detail is intended to provide more information about a previous /// message.</param> /// <param name="context">An object that represents the location that the /// message applies to, a string that indicates what the program was doing /// when the message was generated, or any other relevant context information. /// See also <see cref="MessageSink.ContextToString"/>().</param> /// <param name="format">A message to display. If there are additional /// arguments, placeholders such as {0} and {1} refer to these arguments.</param> /// <param name="args">Optional arguments to fill in placeholders in the format /// string.</param> public delegate void WriteMessageFn(Severity type, object context, string format, params object[] args); /// <summary>An exception that includes a "context" object as part of a /// <see cref="LogMessage"/> structure, typically used to indicate where an /// error occurred.</summary> public class LogException : Exception { public LogException(object context, string format, params object[] args) : this(Severity.Error, context, format, args) {} public LogException(Severity severity, object context, string format, params object[] args) : this(new LogMessage(severity, context, format, args)) {} public LogException(LogMessage msg) { Msg = msg; try { Data["Severity"] = msg.Severity; // Disabled because members of the Data dictionary must be serializable, // but msg.Context might not be. We could convert to string, but is it // worth the performance cost? Loyc code isn't really using Data anyway. //Data["Context"] = msg.Context; } catch { } } /// <summary>Contains additional information about the error that occurred.</summary> public LogMessage Msg { get; private set; } public override string Message { get { return Msg.Formatted; } } } }
loycnet/ecsharp
Core/Loyc.Essentials/MessageSinks/Misc.cs
C#
lgpl-2.1
3,135
<!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.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Azure.BlobStorage.TableStorageStore.Update</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="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </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/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.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="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">2.1</span> </div> <div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <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,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classCqrs_1_1Azure_1_1BlobStorage_1_1TableStorageStore_a869eba77358b10fc298f8e13fb21d628.html','');}); </script> <div id="doc-content"> <!-- 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 class="contents"> <a id="a869eba77358b10fc298f8e13fb21d628"></a> <h2 class="memtitle"><span class="permalink"><a href="#a869eba77358b10fc298f8e13fb21d628">&#9670;&nbsp;</a></span>Update() <span class="overload">[2/2]</span></h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">override void <a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableStorageStore.html">Cqrs.Azure.BlobStorage.TableStorageStore</a>&lt; TData, TCollectionItemData &gt;.Update </td> <td>(</td> <td class="paramtype">TData&#160;</td> <td class="paramname"><em>data</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1StorageStore_ae9ca8bfe30040f77e349a4d47b31da70.html#ae9ca8bfe30040f77e349a4d47b31da70">Cqrs.Azure.BlobStorage.StorageStore&lt; TData, CloudTable &gt;</a>.</p> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure.html">Azure</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Azure_1_1BlobStorage.html">BlobStorage</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Azure_1_1BlobStorage_1_1TableStorageStore.html">TableStorageStore</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/2.1/html/classCqrs_1_1Azure_1_1BlobStorage_1_1TableStorageStore_a869eba77358b10fc298f8e13fb21d628.html
HTML
lgpl-2.1
5,505
namespace("JSTools.Event"); /// <class> /// Provides an interface for attaching and detaching Observer objects. Any number of /// Observer objects may observe a subject. /// </class> JSTools.Event.Subject = function() { //------------------------------------------------------------------------ // Declarations //------------------------------------------------------------------------ this.InitType(arguments, "JSTools.Event.Subject"); var _this = this; var _observers = null; //------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------ /// <constructor> /// Creates a new JSTools.Event.Subject instance. /// </constructor> function Init() { _this.Clear(); } //------------------------------------------------------------------------ // Methods //------------------------------------------------------------------------ /// <method> /// Removes all registered observer object. /// </method> function Clear() { _observers = [ ]; } this.Clear = Clear; /// <method> /// Attaches the given observer function to this subject. /// </method> /// <param name="objIObserver" type="JSTools.Event.IObserver">Observer to attach.</param> /// <returns type="Integer">Returns the index, at which the observer object has been added. /// Returns -1 if the given observer object is invalid and not added.</returns> function Attach(objIObserver) { if (objIObserver && typeof(objIObserver) == 'object' && objIObserver.IsTypeOf(JSTools.Event.IObserver)) { _observers.Add(objIObserver); return _observers.length - 1; } return -1; } this.Attach = Attach; /// <method> /// Detaches the given observer object from this subject. /// </method> /// <param name="objIObserverToDetach" type="JSTools.Event.IObserver">Observer to detach.</param> function Detach(objIObserverToDetach) { _observers.Remove(objIObserverToDetach); } this.Detach = Detach; /// <method> /// Detaches an observer at the given index from this subject. /// </method> /// <param name="intIndex" type="Integer">Index to detach.</param> function DetachByIndex(intIndex) { _observers.RemoveAt(intIndex); } this.DetachByIndex = DetachByIndex; /// <method> /// Notifies the observer about an update. /// </method> /// <param name="objEvent" type="Object">An object instance, which represents the event argument.</param> function Notify(objEvent) { for (var i = 0; i < _observers.length; ++i) { _observers[i].Update(objEvent); } } this.Notify = Notify; Init(); }
sgeh/JSTools.net
Branches/JSTools 0.41/JSTools.JavaScript/JSTools/Event/Subject.js
JavaScript
lgpl-2.1
2,624
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2016, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------- * Effect3D.java * ------------- * (C) Copyright 2002-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 05-Nov-2002 : Version 1 (DG); * 14-Nov-2002 : Modified to have independent x and y offsets (DG); * */ package org.jfree.chart; /** * An interface that should be implemented by renderers that use a 3D effect. * This allows the axes to mirror the same effect by querying the renderer. */ public interface Effect3D { /** * Returns the x-offset (in Java2D units) for the 3D effect. * * @return The offset. */ public double getXOffset(); /** * Returns the y-offset (in Java2D units) for the 3D effect. * * @return The offset. */ public double getYOffset(); }
simon04/jfreechart
src/main/java/org/jfree/chart/Effect3D.java
Java
lgpl-2.1
2,135
// // NotificationQueue.cpp // // $Id: //poco/1.4/Foundation/src/NotificationQueue.cpp#1 $ // // Library: Foundation // Package: Notifications // Module: NotificationQueue // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/NotificationQueue.h" #include "Poco/NotificationCenter.h" #include "Poco/Notification.h" #include "Poco/SingletonHolder.h" namespace Poco { NotificationQueue::NotificationQueue() { } NotificationQueue::~NotificationQueue() { clear(); } void NotificationQueue::enqueueNotification(Notification::Ptr pNotification) { poco_check_ptr (pNotification); FastMutex::ScopedLock lock(_mutex); if (_waitQueue.empty()) { _nfQueue.push_back(pNotification); } else { WaitInfo* pWI = _waitQueue.front(); _waitQueue.pop_front(); pWI->pNf = pNotification; pWI->nfAvailable.set(); } } void NotificationQueue::enqueueUrgentNotification(Notification::Ptr pNotification) { poco_check_ptr (pNotification); FastMutex::ScopedLock lock(_mutex); if (_waitQueue.empty()) { _nfQueue.push_front(pNotification); } else { WaitInfo* pWI = _waitQueue.front(); _waitQueue.pop_front(); pWI->pNf = pNotification; pWI->nfAvailable.set(); } } Notification* NotificationQueue::dequeueNotification() { FastMutex::ScopedLock lock(_mutex); return dequeueOne().duplicate(); } Notification* NotificationQueue::waitDequeueNotification() { Notification::Ptr pNf; WaitInfo* pWI = 0; { FastMutex::ScopedLock lock(_mutex); pNf = dequeueOne(); if (pNf) return pNf.duplicate(); pWI = new WaitInfo; _waitQueue.push_back(pWI); } pWI->nfAvailable.wait(); pNf = pWI->pNf; delete pWI; return pNf.duplicate(); } Notification* NotificationQueue::waitDequeueNotification(long milliseconds) { Notification::Ptr pNf; WaitInfo* pWI = 0; { FastMutex::ScopedLock lock(_mutex); pNf = dequeueOne(); if (pNf) return pNf.duplicate(); pWI = new WaitInfo; _waitQueue.push_back(pWI); } if (pWI->nfAvailable.tryWait(milliseconds)) { pNf = pWI->pNf; } else { FastMutex::ScopedLock lock(_mutex); pNf = pWI->pNf; for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) { if (*it == pWI) { _waitQueue.erase(it); break; } } } delete pWI; return pNf.duplicate(); } void NotificationQueue::dispatch(NotificationCenter& notificationCenter) { FastMutex::ScopedLock lock(_mutex); Notification::Ptr pNf = dequeueOne(); while (pNf) { notificationCenter.postNotification(pNf); pNf = dequeueOne(); } } void NotificationQueue::wakeUpAll() { FastMutex::ScopedLock lock(_mutex); for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) { (*it)->nfAvailable.set(); } _waitQueue.clear(); } bool NotificationQueue::empty() const { FastMutex::ScopedLock lock(_mutex); return _nfQueue.empty(); } int NotificationQueue::size() const { FastMutex::ScopedLock lock(_mutex); return static_cast<int>(_nfQueue.size()); } void NotificationQueue::clear() { FastMutex::ScopedLock lock(_mutex); _nfQueue.clear(); } bool NotificationQueue::hasIdleThreads() const { FastMutex::ScopedLock lock(_mutex); return !_waitQueue.empty(); } Notification::Ptr NotificationQueue::dequeueOne() { Notification::Ptr pNf; if (!_nfQueue.empty()) { pNf = _nfQueue.front(); _nfQueue.pop_front(); } return pNf; } namespace { static SingletonHolder<NotificationQueue> sh_nfq; } NotificationQueue& NotificationQueue::defaultQueue() { return *sh_nfq.get(); } } // namespace Poco
tjizep/treestore1
src/poco-1.4.6p1-all/Foundation/src/NotificationQueue.cpp
C++
lgpl-2.1
5,144
// // ZipDataInfo.h // // $Id: //poco/1.4/Zip/include/Poco/Zip/ZipDataInfo.h#1 $ // // Library: Zip // Package: Zip // Module: ZipDataInfo // // Definition of the ZipDataInfo class. // // Copyright (c) 2007, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Zip_ZipDataInfo_INCLUDED #define Zip_ZipDataInfo_INCLUDED #include "Poco/Zip/Zip.h" #include "Poco/Zip/ZipCommon.h" #include "Poco/Zip/ZipUtil.h" namespace Poco { namespace Zip { class Zip_API ZipDataInfo /// A ZipDataInfo stores a Zip data descriptor { public: static const char HEADER[ZipCommon::HEADER_SIZE]; ZipDataInfo(); /// Creates a header with all fields (except the header field) set to 0 ZipDataInfo(std::istream& in, bool assumeHeaderRead); /// Creates the ZipDataInfo. ~ZipDataInfo(); /// Destroys the ZipDataInfo. bool isValid() const; Poco::UInt32 getCRC32() const; void setCRC32(Poco::UInt32 crc); Poco::UInt32 getCompressedSize() const; void setCompressedSize(Poco::UInt32 size); Poco::UInt32 getUncompressedSize() const; void setUncompressedSize(Poco::UInt32 size); static Poco::UInt32 getFullHeaderSize(); const char* getRawHeader() const; private: enum { HEADER_POS = 0, CRC32_POS = HEADER_POS + ZipCommon::HEADER_SIZE, CRC32_SIZE = 4, COMPRESSED_POS = CRC32_POS + CRC32_SIZE, COMPRESSED_SIZE = 4, UNCOMPRESSED_POS = COMPRESSED_POS + COMPRESSED_SIZE, UNCOMPRESSED_SIZE = 4, FULLHEADER_SIZE = UNCOMPRESSED_POS + UNCOMPRESSED_SIZE }; char _rawInfo[FULLHEADER_SIZE]; bool _valid; }; inline const char* ZipDataInfo::getRawHeader() const { return _rawInfo; } inline bool ZipDataInfo::isValid() const { return _valid; } inline Poco::UInt32 ZipDataInfo::getCRC32() const { return ZipUtil::get32BitValue(_rawInfo, CRC32_POS); } inline void ZipDataInfo::setCRC32(Poco::UInt32 crc) { return ZipUtil::set32BitValue(crc, _rawInfo, CRC32_POS); } inline Poco::UInt32 ZipDataInfo::getCompressedSize() const { return ZipUtil::get32BitValue(_rawInfo, COMPRESSED_POS); } inline void ZipDataInfo::setCompressedSize(Poco::UInt32 size) { return ZipUtil::set32BitValue(size, _rawInfo, COMPRESSED_POS); } inline Poco::UInt32 ZipDataInfo::getUncompressedSize() const { return ZipUtil::get32BitValue(_rawInfo, UNCOMPRESSED_POS); } inline void ZipDataInfo::setUncompressedSize(Poco::UInt32 size) { return ZipUtil::set32BitValue(size, _rawInfo, UNCOMPRESSED_POS); } inline Poco::UInt32 ZipDataInfo::getFullHeaderSize() { return FULLHEADER_SIZE; } } } // namespace Poco::Zip #endif // Zip_ZipDataInfo_INCLUDED
tjizep/treestore1
src/poco-1.4.6p1-all/Zip/include/Poco/Zip/ZipDataInfo.h
C
lgpl-2.1
4,090
/* * Created on 17-dic-2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package org.herac.tuxguitar.app.actions.layout; import org.herac.tuxguitar.app.actions.Action; import org.herac.tuxguitar.app.actions.ActionData; import org.herac.tuxguitar.graphics.control.TGLayout; /** * @author julian * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class SetTablatureEnabledAction extends Action{ public static final String NAME = "action.view.layout-set-tablature-enabled"; public SetTablatureEnabledAction() { super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE); } protected int execute(ActionData actionData){ TGLayout layout = getEditor().getTablature().getViewLayout(); layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_TABLATURE ) ); if((layout.getStyle() & TGLayout.DISPLAY_TABLATURE) == 0 && (layout.getStyle() & TGLayout.DISPLAY_SCORE) == 0 ){ layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_SCORE ) ); } updateTablature(); return 0; } }
yuan39/TuxGuitar
TuxGuitar/src/org/herac/tuxguitar/app/actions/layout/SetTablatureEnabledAction.java
Java
lgpl-2.1
1,189
/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2011 Sandro Santilli <strk@keybit.net> * Copyright (C) 2007 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/buffer/OffsetSegmentString.java r378 (JTS-1.12) * **********************************************************************/ #ifndef GEOS_OP_BUFFER_OFFSETSEGMENTSTRING_H #define GEOS_OP_BUFFER_OFFSETSEGMENTSTRING_H #include <geos/geom/Coordinate.h> // for inlines #include <geos/geom/CoordinateSequence.h> // for inlines #include <geos/geom/CoordinateArraySequence.h> // for composition #include <geos/geom/PrecisionModel.h> // for inlines #include <vector> #include <memory> #include <cassert> namespace geos { namespace operation { // geos.operation namespace buffer { // geos.operation.buffer /// A dynamic list of the vertices in a constructed offset curve. // /// Automatically removes close vertices /// which are closer than a given tolerance. /// /// @author Martin Davis /// class OffsetSegmentString { private: geom::CoordinateArraySequence* ptList; const geom::PrecisionModel* precisionModel; /** \brief * The distance below which two adjacent points on the curve * are considered to be coincident. * * This is chosen to be a small fraction of the offset distance. */ double minimumVertexDistance; /** \brief * Tests whether the given point is redundant relative to the previous * point in the list (up to tolerance) * * @param pt * @return true if the point is redundant */ bool isRedundant(const geom::Coordinate& pt) const { if (ptList->size() < 1) return false; const geom::Coordinate& lastPt = ptList->back(); double ptDist = pt.distance(lastPt); if (ptDist < minimumVertexDistance) return true; return false; } public: friend std::ostream& operator<< (std::ostream& os, const OffsetSegmentString& node); OffsetSegmentString() : ptList(new geom::CoordinateArraySequence()), precisionModel(NULL), minimumVertexDistance (0.0) { } ~OffsetSegmentString() { delete ptList; } void reset() { if ( ptList ) ptList->clear(); else ptList = new geom::CoordinateArraySequence(); precisionModel = NULL; minimumVertexDistance = 0.0; } void setPrecisionModel(const geom::PrecisionModel* nPrecisionModel) { precisionModel = nPrecisionModel; } void setMinimumVertexDistance(double nMinVertexDistance) { minimumVertexDistance = nMinVertexDistance; } void addPt(const geom::Coordinate& pt) { assert(precisionModel); geom::Coordinate bufPt = pt; precisionModel->makePrecise(bufPt); // don't add duplicate (or near-duplicate) points if (isRedundant(bufPt)) { return; } // we ask to allow repeated as we checked this ourself // (JTS uses a vector for ptList, not a CoordinateSequence, // we should do the same) ptList->add(bufPt, true); } void addPts(const geom::CoordinateSequence& pts, bool isForward) { if ( isForward ) { for (size_t i=0, n=pts.size(); i<n; ++i) { addPt(pts[i]); } } else { for (size_t i=pts.size(); i>0; --i) { addPt(pts[i-1]); } } } /// Check that points are a ring // /// add the startpoint again if they are not void closeRing() { if (ptList->size() < 1) return; const geom::Coordinate& startPt = ptList->front(); const geom::Coordinate& lastPt = ptList->back(); if (startPt.equals(lastPt)) return; // we ask to allow repeated as we checked this ourself ptList->add(startPt, true); } /// Get coordinates by taking ownership of them // /// After this call, the coordinates reference in /// this object are dropped. Calling twice will /// segfault... /// /// FIXME: refactor memory management of this /// geom::CoordinateSequence* getCoordinates() { closeRing(); geom::CoordinateSequence* ret = ptList; ptList = 0; return ret; } inline int size() const { return ptList ? ptList->size() : 0 ; } }; inline std::ostream& operator<< (std::ostream& os, const OffsetSegmentString& lst) { if ( lst.ptList ) { os << *(lst.ptList); } else { os << "empty (consumed?)"; } return os; } } // namespace geos.operation.buffer } // namespace geos.operation } // namespace geos #endif // ndef GEOS_OP_BUFFER_OFFSETSEGMENTSTRING_H
Uli1/geos
include/geos/operation/buffer/OffsetSegmentString.h
C
lgpl-2.1
4,706
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsystemlibrary_p.h" #include <QtCore/qvarlengtharray.h> #include <QtCore/qstringlist.h> #include <QtCore/qfileinfo.h> /*! \internal \class QSystemLibrary The purpose of this class is to load only libraries that are located in well-known and trusted locations on the filesystem. It does not suffer from the security problem that QLibrary has, therefore it will never search in the current directory. The search order is the same as the order in DLL Safe search mode Windows, except that we don't search: * The current directory * The 16-bit system directory. (normally c:\windows\system) * The Windows directory. (normally c:\windows) This means that the effective search order is: 1. Application path. 2. System libraries path. 3. Trying all paths inside the PATH environment variable. Note, when onlySystemDirectory is true it will skip 1) and 3). DLL Safe search mode is documented in the "Dynamic-Link Library Search Order" document on MSDN. Since library loading code is sometimes shared between Windows and WinCE, this class can also be used on WinCE. However, its implementation just calls the LoadLibrary() function. This is ok since it is documented as not loading from the current directory on WinCE. This behaviour is documented in the documentation for LoadLibrary for Windows CE at MSDN. (http://msdn.microsoft.com/en-us/library/ms886736.aspx) */ QT_BEGIN_NAMESPACE #if defined(Q_OS_WINCE) HINSTANCE QSystemLibrary::load(const wchar_t *libraryName, bool onlySystemDirectory /* = true */) { return ::LoadLibrary(libraryName); } #else #if !defined(QT_BOOTSTRAPPED) extern QString qAppFileName(); #endif static QString qSystemDirectory() { QVarLengthArray<wchar_t, MAX_PATH> fullPath; UINT retLen = ::GetSystemDirectory(fullPath.data(), MAX_PATH); if (retLen > MAX_PATH) { fullPath.resize(retLen); retLen = ::GetSystemDirectory(fullPath.data(), retLen); } // in some rare cases retLen might be 0 return QString::fromWCharArray(fullPath.constData(), int(retLen)); } HINSTANCE QSystemLibrary::load(const wchar_t *libraryName, bool onlySystemDirectory /* = true */) { QStringList searchOrder; #if !defined(QT_BOOTSTRAPPED) if (!onlySystemDirectory) searchOrder << QFileInfo(qAppFileName()).path(); #endif searchOrder << qSystemDirectory(); if (!onlySystemDirectory) { const QString PATH(QLatin1String(qgetenv("PATH").constData())); searchOrder << PATH.split(QLatin1Char(';'), QString::SkipEmptyParts); } QString fileName = QString::fromWCharArray(libraryName); fileName.append(QLatin1String(".dll")); // Start looking in the order specified for (int i = 0; i < searchOrder.count(); ++i) { QString fullPathAttempt = searchOrder.at(i); if (!fullPathAttempt.endsWith(QLatin1Char('\\'))) { fullPathAttempt.append(QLatin1Char('\\')); } fullPathAttempt.append(fileName); HINSTANCE inst = ::LoadLibrary((const wchar_t *)fullPathAttempt.utf16()); if (inst != 0) return inst; } return 0; } #endif //Q_OS_WINCE QT_END_NAMESPACE
prapin/qmake-iphone
src/corelib/plugin/qsystemlibrary.cpp
C++
lgpl-2.1
5,180
/*! * \file definition_structure.hpp * \brief Headers of the main subroutines used by SU2_EDU. * The subroutines and functions are in the <i>definition_structure.cpp</i> file. * \author Aerospace Design Laboratory (Stanford University). * \version 1.2.0 * * SU2 EDU, Copyright (C) 2014 Aerospace Design Laboratory (Stanford University). * * SU2 EDU is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * SU2 EDU is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with SU2 EDU. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <ctime> #include "solver_structure.hpp" #include "integration_structure.hpp" #include "output_structure.hpp" #include "numerics_structure.hpp" #include "geometry_structure.hpp" #include "config_structure.hpp" using namespace std; /*! * \brief Gets the number of zones in the mesh file. * \param[in] val_mesh_filename - Name of the file with the grid information. * \param[in] val_format - Format of the file with the grid information. * \param[in] config - Definition of the particular problem. * \return Total number of zones in the grid file. */ unsigned short GetnZone(string val_mesh_filename, unsigned short val_format, CConfig *config); /*! * \brief Gets the number of dimensions in the mesh file * \param[in] val_mesh_filename - Name of the file with the grid information. * \param[in] val_format - Format of the file with the grid information. * \return Total number of domains in the grid file. */ unsigned short GetnDim(string val_mesh_filename, unsigned short val_format); /*! * \brief Definition and allocation of all solution classes. * \param[in] solver_container - Container vector with all the solutions. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] iZone - Index of the zone. */ void Solver_Preprocessing(CSolver ***solver_container, CGeometry **geometry, CConfig *config); /*! * \brief Definition and allocation of all integration classes. * \param[in] integration_container - Container vector with all the integration methods. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] iZone - Index of the zone. */ void Integration_Preprocessing(CIntegration **integration_container, CGeometry **geometry, CConfig *config); /*! * \brief Definition and allocation of all solver classes. * \param[in] numerics_container - Description of the numerical method (the way in which the equations are solved). * \param[in] solver_container - Container vector with all the solutions. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] iZone - Index of the zone. */ void Numerics_Preprocessing(CNumerics ****numerics_container, CSolver ***solver_container, CGeometry **geometry, CConfig *config); /*! * \brief Do the geometrical preprocessing. * \param[in] geometry - Geometrical definition of the problem. * \param[in] config - Definition of the particular problem. * \param[in] val_nZone - Total number of zones. */ void Geometrical_Preprocessing(CGeometry **geometry, CConfig *config);
shivajimedida/SU2_EDU
include/definition_structure.hpp
C++
lgpl-2.1
3,735
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { getElementFromPosition } from '../caret/CaretUtils'; import NodeType from '../dom/NodeType'; import { CaretPosition } from '../caret/CaretPosition'; import { Insert, Element } from '@ephox/sugar'; import { Option, Fun } from '@ephox/katamari'; const insertTextAtPosition = (text: string, pos: CaretPosition): Option<CaretPosition> => { const container = pos.container(); const offset = pos.offset(); if (NodeType.isText(container)) { container.insertData(offset, text); return Option.some(CaretPosition(container, offset + text.length)); } else { return getElementFromPosition(pos).map((elm) => { const textNode = Element.fromText(text); if (pos.isAtEnd()) { Insert.after(elm, textNode); } else { Insert.before(elm, textNode); } return CaretPosition(textNode.dom(), text.length); }); } }; const insertNbspAtPosition = Fun.curry(insertTextAtPosition, '\u00a0'); const insertSpaceAtPosition = Fun.curry(insertTextAtPosition, ' '); export { insertTextAtPosition, insertNbspAtPosition, insertSpaceAtPosition };
danielpunkass/tinymce
src/core/main/ts/caret/InsertText.ts
TypeScript
lgpl-2.1
1,351
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #ifndef TARGET_H #define TARGET_H #include "projectconfiguration.h" #include "projectexplorer_export.h" QT_FORWARD_DECLARE_CLASS(QIcon) namespace Utils { class Environment; } namespace ProjectExplorer { class RunConfiguration; class ToolChain; class BuildConfiguration; class DeployConfiguration; class IBuildConfigurationFactory; class DeployConfigurationFactory; class IRunConfigurationFactory; class Project; class BuildConfigWidget; class TargetPrivate; class PROJECTEXPLORER_EXPORT Target : public ProjectConfiguration { Q_OBJECT public: virtual ~Target(); virtual BuildConfigWidget *createConfigWidget() = 0; Project *project() const; // Build configuration void addBuildConfiguration(BuildConfiguration *configuration); bool removeBuildConfiguration(BuildConfiguration *configuration); QList<BuildConfiguration *> buildConfigurations() const; BuildConfiguration *activeBuildConfiguration() const; void setActiveBuildConfiguration(BuildConfiguration *configuration); virtual IBuildConfigurationFactory *buildConfigurationFactory() const = 0; // DeployConfiguration void addDeployConfiguration(DeployConfiguration *dc); bool removeDeployConfiguration(DeployConfiguration *dc); QList<DeployConfiguration *> deployConfigurations() const; DeployConfiguration *activeDeployConfiguration() const; void setActiveDeployConfiguration(DeployConfiguration *configuration); QStringList availableDeployConfigurationIds(); QString displayNameForDeployConfigurationId(const QString &id); DeployConfiguration *createDeployConfiguration(const QString &id); // Running QList<RunConfiguration *> runConfigurations() const; void addRunConfiguration(RunConfiguration *runConfiguration); void removeRunConfiguration(RunConfiguration *runConfiguration); RunConfiguration *activeRunConfiguration() const; void setActiveRunConfiguration(RunConfiguration *runConfiguration); // Returns whether this target is actually available at he time // of the call. A target may become unavailable e.g. when a Qt version // is removed. // // Note: Enabled state is not saved! bool isEnabled() const; QIcon icon() const; void setIcon(QIcon icon); QIcon overlayIcon() const; void setOverlayIcon(QIcon icon); QString toolTip() const; void setToolTip(const QString &text); virtual QList<ToolChain *> possibleToolChains(BuildConfiguration *) const; virtual ToolChain *preferredToolChain(BuildConfiguration *) const; virtual QVariantMap toMap() const; signals: void targetEnabled(bool); void iconChanged(); void overlayIconChanged(); void toolTipChanged(); // TODO clean up signal names // might be better to also have aboutToRemove signals void removedRunConfiguration(ProjectExplorer::RunConfiguration *); void addedRunConfiguration(ProjectExplorer::RunConfiguration *); void activeRunConfigurationChanged(ProjectExplorer::RunConfiguration *); void removedBuildConfiguration(ProjectExplorer::BuildConfiguration *bc); void addedBuildConfiguration(ProjectExplorer::BuildConfiguration *bc); void activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration *); void removedDeployConfiguration(ProjectExplorer::DeployConfiguration *dc); void addedDeployConfiguration(ProjectExplorer::DeployConfiguration *dc); void activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration *dc); /// convenience signal, emitted if either the active buildconfiguration emits /// environmentChanged() or if the active build configuration changes void environmentChanged(); /// convenience signal, emitted if either the active configuration emits /// enabledChanged() or if the active build configuration changes void buildConfigurationEnabledChanged(); void deployConfigurationEnabledChanged(); void runConfigurationEnabledChanged(); protected: Target(Project *parent, const QString &id); void setEnabled(bool); virtual bool fromMap(const QVariantMap &map); private slots: void changeEnvironment(); void changeBuildConfigurationEnabled(); void changeDeployConfigurationEnabled(); void changeRunConfigurationEnabled(); private: TargetPrivate *d; }; class PROJECTEXPLORER_EXPORT ITargetFactory : public QObject { Q_OBJECT public: explicit ITargetFactory(QObject *parent = 0); virtual QStringList supportedTargetIds() const = 0; virtual bool supportsTargetId(const QString &id) const = 0; // used to translate the types to names to display to the user virtual QString displayNameForId(const QString &id) const = 0; virtual bool canCreate(Project *parent, const QString &id) const = 0; virtual Target *create(Project *parent, const QString &id) = 0; virtual bool canRestore(Project *parent, const QVariantMap &map) const = 0; virtual Target *restore(Project *parent, const QVariantMap &map) = 0; signals: void canCreateTargetIdsChanged(); }; } // namespace ProjectExplorer Q_DECLARE_METATYPE(ProjectExplorer::Target *) #endif // TARGET_H
azat/qtcreator
src/plugins/projectexplorer/target.h
C
lgpl-2.1
6,454
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Restricts the number of statements per line to one. * <p> * Rationale: It's very difficult to read multiple statements on one line. * </p> * <p> * In the Java programming language, statements are the fundamental unit of * execution. All statements except blocks are terminated by a semicolon. * Blocks are denoted by open and close curly braces. * </p> * <p> * OneStatementPerLineCheck checks the following types of statements: * variable declaration statements, empty statements, assignment statements, * expression statements, increment statements, object creation statements, * 'for loop' statements, 'break' statements, 'continue' statements, * 'return' statements, import statements. * </p> * <p> * The following examples will be flagged as a violation: * </p> * <pre> * //Each line causes violation: * int var1; int var2; * var1 = 1; var2 = 2; * int var1 = 1; int var2 = 2; * var1++; var2++; * Object obj1 = new Object(); Object obj2 = new Object(); * import java.io.EOFException; import java.io.BufferedReader; * ;; //two empty statements on the same line. * * //Multi-line statements: * int var1 = 1 * ; var2 = 2; //violation here * int o = 1, p = 2, * r = 5; int t; //violation here * </pre> * * @author Alexander Jesse * @author Oliver Burn * @author Andrei Selkin */ public final class OneStatementPerLineCheck extends Check { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "multiple.statements.line"; /** * Hold the line-number where the last statement ended. */ private int lastStatementEnd = -1; /** * Hold the line-number where the last 'for-loop' statement ended. */ private int forStatementEnd = -1; /** * The for-header usually has 3 statements on one line, but THIS IS OK. */ private boolean inForHeader; @Override public int[] getDefaultTokens() { return getAcceptableTokens(); } @Override public int[] getAcceptableTokens() { return new int[]{ TokenTypes.SEMI, TokenTypes.FOR_INIT, TokenTypes.FOR_ITERATOR, }; } @Override public int[] getRequiredTokens() { return getAcceptableTokens(); } @Override public void beginTree(DetailAST rootAST) { inForHeader = false; lastStatementEnd = -1; forStatementEnd = -1; } @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.SEMI: DetailAST currentStatement = ast; if (isMultilineStatement(currentStatement)) { currentStatement = ast.getPreviousSibling(); } if (isOnTheSameLine(currentStatement, lastStatementEnd, forStatementEnd) && !inForHeader) { log(ast, MSG_KEY); } break; case TokenTypes.FOR_ITERATOR: forStatementEnd = ast.getLineNo(); break; default: inForHeader = true; break; } } @Override public void leaveToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.SEMI: lastStatementEnd = ast.getLineNo(); forStatementEnd = -1; break; case TokenTypes.FOR_ITERATOR: inForHeader = false; break; default: break; } } /** * Checks whether two statements are on the same line. * @param ast token for the current statement. * @param lastStatementEnd the line-number where the last statement ended. * @param forStatementEnd the line-number where the last 'for-loop' * statement ended. * @return true if two statements are on the same line. */ private static boolean isOnTheSameLine(DetailAST ast, int lastStatementEnd, int forStatementEnd) { return lastStatementEnd == ast.getLineNo() && forStatementEnd != ast.getLineNo(); } /** * Checks whether statement is multiline. * @param ast token for the current statement. * @return true if one statement is distributed over two or more lines. */ private static boolean isMultilineStatement(DetailAST ast) { final boolean multiline; if (ast.getPreviousSibling() == null) { multiline = false; } else { final DetailAST prevSibling = ast.getPreviousSibling(); multiline = prevSibling.getLineNo() != ast.getLineNo() && ast.getParent() != null; } return multiline; } }
jasonchaffee/checkstyle
src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck.java
Java
lgpl-2.1
6,201
#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify import sys if __name__ == '__main__': if not pynotify.init("XY"): sys.exit(1) n = pynotify.Notification("X, Y Test", "This notification should point to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): print "Failed to send notification" sys.exit(1)
Distrotech/notify-python
tests/test-xy.py
Python
lgpl-2.1
418
/** * \file * * Copyright (c) 2014-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \asf_license_stop * */ /* * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #ifndef _SAM3S_ADC_INSTANCE_ #define _SAM3S_ADC_INSTANCE_ /* ========== Register definition for ADC peripheral ========== */ #if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) #define REG_ADC_CR (0x40038000U) /**< \brief (ADC) Control Register */ #define REG_ADC_MR (0x40038004U) /**< \brief (ADC) Mode Register */ #define REG_ADC_SEQR1 (0x40038008U) /**< \brief (ADC) Channel Sequence Register 1 */ #define REG_ADC_SEQR2 (0x4003800CU) /**< \brief (ADC) Channel Sequence Register 2 */ #define REG_ADC_CHER (0x40038010U) /**< \brief (ADC) Channel Enable Register */ #define REG_ADC_CHDR (0x40038014U) /**< \brief (ADC) Channel Disable Register */ #define REG_ADC_CHSR (0x40038018U) /**< \brief (ADC) Channel Status Register */ #define REG_ADC_LCDR (0x40038020U) /**< \brief (ADC) Last Converted Data Register */ #define REG_ADC_IER (0x40038024U) /**< \brief (ADC) Interrupt Enable Register */ #define REG_ADC_IDR (0x40038028U) /**< \brief (ADC) Interrupt Disable Register */ #define REG_ADC_IMR (0x4003802CU) /**< \brief (ADC) Interrupt Mask Register */ #define REG_ADC_ISR (0x40038030U) /**< \brief (ADC) Interrupt Status Register */ #define REG_ADC_OVER (0x4003803CU) /**< \brief (ADC) Overrun Status Register */ #define REG_ADC_EMR (0x40038040U) /**< \brief (ADC) Extended Mode Register */ #define REG_ADC_CWR (0x40038044U) /**< \brief (ADC) Compare Window Register */ #define REG_ADC_CGR (0x40038048U) /**< \brief (ADC) Channel Gain Register */ #define REG_ADC_COR (0x4003804CU) /**< \brief (ADC) Channel Offset Register */ #define REG_ADC_CDR (0x40038050U) /**< \brief (ADC) Channel Data Register */ #define REG_ADC_ACR (0x40038094U) /**< \brief (ADC) Analog Control Register */ #define REG_ADC_WPMR (0x400380E4U) /**< \brief (ADC) Write Protect Mode Register */ #define REG_ADC_WPSR (0x400380E8U) /**< \brief (ADC) Write Protect Status Register */ #define REG_ADC_RPR (0x40038100U) /**< \brief (ADC) Receive Pointer Register */ #define REG_ADC_RCR (0x40038104U) /**< \brief (ADC) Receive Counter Register */ #define REG_ADC_RNPR (0x40038110U) /**< \brief (ADC) Receive Next Pointer Register */ #define REG_ADC_RNCR (0x40038114U) /**< \brief (ADC) Receive Next Counter Register */ #define REG_ADC_PTCR (0x40038120U) /**< \brief (ADC) Transfer Control Register */ #define REG_ADC_PTSR (0x40038124U) /**< \brief (ADC) Transfer Status Register */ #else #define REG_ADC_CR (*(WoReg*)0x40038000U) /**< \brief (ADC) Control Register */ #define REG_ADC_MR (*(RwReg*)0x40038004U) /**< \brief (ADC) Mode Register */ #define REG_ADC_SEQR1 (*(RwReg*)0x40038008U) /**< \brief (ADC) Channel Sequence Register 1 */ #define REG_ADC_SEQR2 (*(RwReg*)0x4003800CU) /**< \brief (ADC) Channel Sequence Register 2 */ #define REG_ADC_CHER (*(WoReg*)0x40038010U) /**< \brief (ADC) Channel Enable Register */ #define REG_ADC_CHDR (*(WoReg*)0x40038014U) /**< \brief (ADC) Channel Disable Register */ #define REG_ADC_CHSR (*(RoReg*)0x40038018U) /**< \brief (ADC) Channel Status Register */ #define REG_ADC_LCDR (*(RoReg*)0x40038020U) /**< \brief (ADC) Last Converted Data Register */ #define REG_ADC_IER (*(WoReg*)0x40038024U) /**< \brief (ADC) Interrupt Enable Register */ #define REG_ADC_IDR (*(WoReg*)0x40038028U) /**< \brief (ADC) Interrupt Disable Register */ #define REG_ADC_IMR (*(RoReg*)0x4003802CU) /**< \brief (ADC) Interrupt Mask Register */ #define REG_ADC_ISR (*(RoReg*)0x40038030U) /**< \brief (ADC) Interrupt Status Register */ #define REG_ADC_OVER (*(RoReg*)0x4003803CU) /**< \brief (ADC) Overrun Status Register */ #define REG_ADC_EMR (*(RwReg*)0x40038040U) /**< \brief (ADC) Extended Mode Register */ #define REG_ADC_CWR (*(RwReg*)0x40038044U) /**< \brief (ADC) Compare Window Register */ #define REG_ADC_CGR (*(RwReg*)0x40038048U) /**< \brief (ADC) Channel Gain Register */ #define REG_ADC_COR (*(RwReg*)0x4003804CU) /**< \brief (ADC) Channel Offset Register */ #define REG_ADC_CDR (*(RoReg*)0x40038050U) /**< \brief (ADC) Channel Data Register */ #define REG_ADC_ACR (*(RwReg*)0x40038094U) /**< \brief (ADC) Analog Control Register */ #define REG_ADC_WPMR (*(RwReg*)0x400380E4U) /**< \brief (ADC) Write Protect Mode Register */ #define REG_ADC_WPSR (*(RoReg*)0x400380E8U) /**< \brief (ADC) Write Protect Status Register */ #define REG_ADC_RPR (*(RwReg*)0x40038100U) /**< \brief (ADC) Receive Pointer Register */ #define REG_ADC_RCR (*(RwReg*)0x40038104U) /**< \brief (ADC) Receive Counter Register */ #define REG_ADC_RNPR (*(RwReg*)0x40038110U) /**< \brief (ADC) Receive Next Pointer Register */ #define REG_ADC_RNCR (*(RwReg*)0x40038114U) /**< \brief (ADC) Receive Next Counter Register */ #define REG_ADC_PTCR (*(WoReg*)0x40038120U) /**< \brief (ADC) Transfer Control Register */ #define REG_ADC_PTSR (*(RoReg*)0x40038124U) /**< \brief (ADC) Transfer Status Register */ #endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */ #endif /* _SAM3S_ADC_INSTANCE_ */
sgso/RIOT
cpu/sam3s/include/instance/instance_adc.h
C
lgpl-2.1
7,130
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: wikiplugin_titlesearch.php 41425 2012-05-11 02:02:22Z lindonb $ require_once "lib/wiki/pluginslib.php"; function wikiplugin_titlesearch_info() { return array( 'name' => tra('Title Search'), 'documentation' => 'PluginTitleSearch', 'description' => tra('Search pages by title'), 'prefs' => array( 'feature_wiki', 'wikiplugin_titlesearch' ), 'icon' => 'img/icons/page_find.png', 'params' => array( 'search' => array( 'required' => true, 'name' => tra('Search Criteria'), 'description' => tra('Portion of a page name.'), 'default' => '', ), 'info' => array( 'required' => false, 'name' => tra('Information'), 'description' => tra('Also show page hits or user'), 'default' => '', 'options' => array( array('text' => '', 'value' => ''), array('text' => tra('Hits'), 'value' => 'hits'), array('text' => tra('User'), 'value' => 'user') ) ), 'exclude' => array( 'required' => false, 'name' => tra('Exclude'), 'description' => tra('Pipe-separated list of page names to exclude from results.'), 'default' => '', ), 'noheader' => array( 'required' => false, 'name' => tra('No Header'), 'description' => tra('Set to 1 (Yes) to have no header for the search results.'), 'default' => 0, 'options' => array( array('text' => '', 'value' => ''), array('text' => tra('Yes'), 'value' => 1), array('text' => tra('No'), 'value' => 0) ) ), ), ); } class WikiPluginTitleSearch extends PluginsLib { var $expanded_params = array("exclude", "info"); function getDescription() { return wikiplugin_titlesearch_help(); } function getDefaultArguments() { return array('exclude' => '' , 'noheader' => 0, 'info' => false, 'search' => false, 'style' => 'table' ); } function getName() { return "TitleSearch"; } function getVersion() { return preg_replace("/[Revision: $]/", '', "\$Revision: 1.25 $"); } function run ($data, $params) { global $wikilib; include_once('lib/wiki/wikilib.php'); global $tikilib; $aInfoPreset = array_keys($this->aInfoPresetNames); $params = $this->getParams($params, true); extract($params, EXTR_SKIP); if (!$search) { return $this->error("You have to define a search"); } // no additional infos in list output if (isset($style) && $style == 'list') $info = false; // ///////////////////////////////// // Create a valid list for $info ///////////////////////////////// // if ($info) { $info_temp = array(); foreach ($info as $sInfo) { if (in_array(trim($sInfo), $aInfoPreset)) { $info_temp[] = trim($sInfo); } $info = $info_temp?$info_temp: false; } } else { $info = false; } // ///////////////////////////////// // Process pages ///////////////////////////////// // $sOutput = ""; $aPages = $tikilib->list_pages(0, -1, 'pageName_desc', $search, null, false); foreach ($aPages["data"] as $idPage => $aPage) { if (in_array($aPage["pageName"], $exclude)) { unset($aPages["data"][$idPage]); $aPages["cant"]--; } } // ///////////////////////////////// // Start of Output ///////////////////////////////// // if (isset($noheader) && !$noheader) { // Create header $count = $aPages["cant"]; if (!$count) { $sOutput .= tra("No pages found for title search")." '__".$search."__'"; } elseif ($count == 1) { $sOutput .= tra("One page found for title search")." '__".$search."__'"; } else { $sOutput = "$count ".tra("pages found for title search")." '__".$search."__'"; } $sOutput .= "\n"; } if (isset($style) && $style == 'list') { $sOutput.=PluginsLibUtil::createList($aPages["data"]); } else { $sOutput.=PluginsLibUtil::createTable($aPages["data"], $info); } return $sOutput; } } function wikiplugin_titlesearch($data, $params) { $plugin = new WikiPluginTitleSearch(); return $plugin->run($data, $params); }
railfuture/tiki-website
lib/wiki-plugins/wikiplugin_titlesearch.php
PHP
lgpl-2.1
4,226
/* Swfdec * Copyright (C) 2007-2008 Benjamin Otte <otte@gnome.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "swfdec_video.h" #include "swfdec_as_internal.h" #include "swfdec_as_strings.h" #include "swfdec_debug.h" #include "swfdec_net_stream.h" #include "swfdec_player_internal.h" #include "swfdec_sandbox.h" SWFDEC_AS_NATIVE (667, 1, swfdec_video_attach_video) void swfdec_video_attach_video (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; SwfdecAsObject *o; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, "O", &o); if (o == NULL || !SWFDEC_IS_VIDEO_PROVIDER (o->relay)) { SWFDEC_WARNING ("calling attachVideo without a NetStream object"); swfdec_video_movie_set_provider (video, NULL); return; } swfdec_video_movie_set_provider (video, SWFDEC_VIDEO_PROVIDER (o->relay)); } SWFDEC_AS_NATIVE (667, 2, swfdec_video_clear) void swfdec_video_clear (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, ""); swfdec_video_movie_clear (video); } static void swfdec_video_get_width (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; guint w; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, ""); if (video->provider) { w = swfdec_video_provider_get_width (video->provider); } else { w = 0; } *rval = swfdec_as_value_from_integer (cx, w); } static void swfdec_video_get_height (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; guint h; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, ""); if (video->provider) { h = swfdec_video_provider_get_height (video->provider); } else { h = 0; } *rval = swfdec_as_value_from_integer (cx, h); } static void swfdec_video_get_deblocking (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.deblocking (get)"); *rval = swfdec_as_value_from_integer (cx, 0); } static void swfdec_video_set_deblocking (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.deblocking (set)"); } static void swfdec_video_get_smoothing (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.smoothing (get)"); SWFDEC_AS_VALUE_SET_BOOLEAN (rval, TRUE); } static void swfdec_video_set_smoothing (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.smoothing (set)"); } void swfdec_video_movie_init_properties (SwfdecAsContext *cx) { SwfdecAsValue val; SwfdecAsObject *video, *proto; // FIXME: We should only initialize if the prototype Object has not been // initialized by any object's constructor with native properties // (TextField, TextFormat, XML, XMLNode at least) g_return_if_fail (SWFDEC_IS_AS_CONTEXT (cx)); swfdec_as_object_get_variable (cx->global, SWFDEC_AS_STR_Video, &val); if (!SWFDEC_AS_VALUE_IS_OBJECT (val)) return; video = SWFDEC_AS_VALUE_GET_OBJECT (val); swfdec_as_object_get_variable (video, SWFDEC_AS_STR_prototype, &val); if (!SWFDEC_AS_VALUE_IS_OBJECT (val)) return; proto = SWFDEC_AS_VALUE_GET_OBJECT (val); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_width, swfdec_video_get_width, NULL); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_height, swfdec_video_get_height, NULL); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_deblocking, swfdec_video_get_deblocking, swfdec_video_set_deblocking); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_smoothing, swfdec_video_get_smoothing, swfdec_video_set_smoothing); }
freedesktop-unofficial-mirror/swfdec__swfdec
swfdec/swfdec_video_movie_as.c
C
lgpl-2.1
4,812
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package org.kurento.tutorial.player; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.kurento.client.EndOfStreamEvent; import org.kurento.client.EventListener; import org.kurento.client.FaceOverlayFilter; import org.kurento.client.HttpGetEndpoint; import org.kurento.client.MediaPipeline; import org.kurento.client.PlayerEndpoint; import org.kurento.client.KurentoClient; /** * HTTP Player with Kurento; the media pipeline is composed by a PlayerEndpoint * connected to a filter (FaceOverlay) and an HttpGetEnpoint; the default * desktop web browser is launched to play the video. * * @author Micael Gallego (micael.gallego@gmail.com) * @author Boni Garcia (bgarcia@gsyc.es) * @since 5.0.0 */ public class KurentoHttpPlayer { public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException { // Connecting to Kurento Server KurentoClient kurento = KurentoClient .create("ws://localhost:8888/kurento"); // Creating media pipeline MediaPipeline pipeline = kurento.createMediaPipeline(); // Creating media elements PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, "http://files.kurento.org/video/fiwarecut.mp4").build(); FaceOverlayFilter filter = new FaceOverlayFilter.Builder(pipeline) .build(); filter.setOverlayedImage( "http://files.kurento.org/imgs/mario-wings.png", -0.2F, -1.1F, 1.6F, 1.6F); HttpGetEndpoint http = new HttpGetEndpoint.Builder(pipeline).build(); // Connecting media elements player.connect(filter); filter.connect(http); // Reacting to events player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { System.out.println("The playing has finished"); System.exit(0); } }); // Playing media and opening the default desktop browser player.play(); String videoUrl = http.getUrl(); Desktop.getDesktop().browse(new URI(videoUrl)); // Setting a delay to wait the EndOfStream event, previously subscribed Thread.sleep(60000); } }
oclab/howto-callme
kurento-http-player/src/main/java/org/kurento/tutorial/player/KurentoHttpPlayer.java
Java
lgpl-2.1
2,724
<!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.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Repositories.Queries.QueryPredicateExtensions.GetValue&lt; TResult &gt;</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="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </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/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.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="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">2.4</span> </div> <div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <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,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classCqrs_1_1Repositories_1_1Queries_1_1QueryPredicateExtensions_a185f34dfbcf58429fc407b594c55f511.html','');}); </script> <div id="doc-content"> <!-- 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 class="contents"> <a id="a185f34dfbcf58429fc407b594c55f511"></a> <h2 class="memtitle"><span class="permalink"><a href="#a185f34dfbcf58429fc407b594c55f511">&#9670;&nbsp;</a></span>GetValue< TResult >() <span class="overload">[4/7]</span></h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">static TResult Cqrs.Repositories.Queries.QueryPredicateExtensions.GetValue&lt; TResult &gt; </td> <td>(</td> <td class="paramtype">this <a class="el" href="classCqrs_1_1Repositories_1_1Queries_1_1QueryParameter.html">QueryParameter</a>&#160;</td> <td class="paramname"><em>queryParameter</em></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">static</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Gets the value from the provided <em>queryParameter</em> cast to <em>TResult</em> . </p> <p>Gets the <a class="el" href="classCqrs_1_1Repositories_1_1Queries_1_1QueryParameter_a0d1c69ffc864aeda2eb515a9e57fbd7a.html#a0d1c69ffc864aeda2eb515a9e57fbd7a" title="The value of the parameter. ">QueryParameter.ParameterValue</a> cast to <em>TResult</em> . </p> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Repositories.html">Repositories</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Repositories_1_1Queries.html">Queries</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Repositories_1_1Queries_1_1QueryPredicateExtensions.html">QueryPredicateExtensions</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/2.4/html/classCqrs_1_1Repositories_1_1Queries_1_1QueryPredicateExtensions_a185f34dfbcf58429fc407b594c55f511.html
HTML
lgpl-2.1
5,766
<!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.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Events.SqlEventStoreDataContext.New</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="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </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/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.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="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">2.4</span> </div> <div id="projectbrief">A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <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,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classCqrs_1_1Events_1_1SqlEventStoreDataContext_ae059fb99b1100d4d7fb917b635c1be5d.html','');}); </script> <div id="doc-content"> <!-- 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 class="contents"> <a id="ae059fb99b1100d4d7fb917b635c1be5d"></a> <h2 class="memtitle"><span class="permalink"><a href="#ae059fb99b1100d4d7fb917b635c1be5d">&#9670;&nbsp;</a></span>New() <span class="overload">[1/2]</span></h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">static <a class="el" href="classCqrs_1_1Events_1_1SqlEventStoreDataContext.html">SqlEventStoreDataContext</a> Cqrs.Events.SqlEventStoreDataContext.New </td> <td>(</td> <td class="paramtype">Type&#160;</td> <td class="paramname"><em>rowType</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">string&#160;</td> <td class="paramname"><em>tableName</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">string&#160;</td> <td class="paramname"><em>fileOrServerOrConnection</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">static</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Instantiates a new instance of the <a class="el" href="classCqrs_1_1Events_1_1SqlEventStoreDataContext.html" title="A custom DataContext that supports specifying a table name. ">SqlEventStoreDataContext</a> class by referencing a file source. </p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramname">rowType</td><td>The Type of the entity the table hold data for.</td></tr> <tr><td class="paramname">tableName</td><td>The name of the table.</td></tr> <tr><td class="paramname">fileOrServerOrConnection</td><td>This argument can be any one of the following: The name of a file where a SQL Server Express database resides. The name of a server where a database is present. In this case the provider uses the default database for a user. A complete connection string. LINQ to SQL just passes the string to the provider without modification. </td></tr> </table> </dd> </dl> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Events.html">Events</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Events_1_1SqlEventStoreDataContext.html">SqlEventStoreDataContext</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
Chinchilla-Software-Com/CQRS
wiki/docs/2.4/html/classCqrs_1_1Events_1_1SqlEventStoreDataContext_ae059fb99b1100d4d7fb917b635c1be5d.html
HTML
lgpl-2.1
6,563
// --------------------------------------------------------------------- // // Copyright (C) 2007 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/numerics/fe_field_function.templates.h> #include <deal.II/multigrid/mg_dof_handler.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/dofs/dof_accessor.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/block_vector.h> #include <deal.II/lac/parallel_vector.h> #include <deal.II/lac/parallel_block_vector.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #include <deal.II/lac/trilinos_block_vector.h> DEAL_II_NAMESPACE_OPEN namespace Functions { # include "fe_field_function.inst" } DEAL_II_NAMESPACE_CLOSE
flow123d/dealii
source/numerics/fe_field_function.cc
C++
lgpl-2.1
1,304
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: mod-func-breadcrumbs.php 44444 2013-01-05 21:24:24Z changi67 $ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } /** * @return array */ function module_breadcrumbs_info() { return array( 'name' => tra('Breadcrumbs'), 'description' => tra('A hierarchy of where you are. Ex.: Home > Section1 > Subsection C.'), 'prefs' => array('feature_breadcrumbs'), 'params' => array( 'label' => array( 'name' => tra('Label'), 'description' => tra('Label preceding the crumbs.'), 'filter' => 'text', 'default' => 'Location : ', ), 'menuId' => array( 'name' => tra('Menu Id'), 'description' => tra('Menu to take the crumb trail from.'), 'filter' => 'int', 'default' => 0, ), 'menuStartLevel' => array( 'name' => tra('Menu Start Level'), 'description' => tra('Lowest level of the menu to display.'), 'filter' => 'int', 'default' => null, ), 'menuStopLevel' => array( 'name' => tra('Menu Stop Level'), 'description' => tra('Highest level of the menu to display.'), 'filter' => 'int', 'default' => null, ), 'showFirst' => array( 'name' => tra('Show Site Crumb'), 'description' => tra('Display the first crumb, usually the site, when using menu crumbs.'), 'filter' => 'alpha', 'default' => 'y', ), 'showLast' => array( 'name' => tra('Show Page Crumb'), 'description' => tra('Display the last crumb, usually the page, when using menu crumbs.'), 'filter' => 'alpha', 'default' => 'y', ), 'showLinks' => array( 'name' => tra('Show Crumb Links'), 'description' => tra('Display links on the crumbs.'), 'filter' => 'alpha', 'default' => 'y', ), ), ); } /** * @param $mod_reference * @param $module_params */ function module_breadcrumbs($mod_reference, $module_params) { global $prefs, $smarty, $crumbs; if (!isset($module_params['label'])) { if ($prefs['feature_siteloclabel'] === 'y') { $module_params['label'] = 'Location : '; } } $binfo = module_breadcrumbs_info(); $defaults = array(); foreach ($binfo['params'] as $k => $v) { $defaults[$k] = $v['default']; } $module_params = array_merge($defaults, $module_params); if (!empty($module_params['menuId'])) { include_once('lib/breadcrumblib.php'); $newCrumbs = breadcrumb_buildMenuCrumbs($crumbs, $module_params['menuId'], $module_params['menuStartLevel'], $module_params['menuStopLevel']); if ($newCrumbs !== $crumbs) { $crumbs = $newCrumbs; } } if ($module_params['showFirst'] === 'n') { $crumbs[0]->hidden = true; } if ($module_params['showLast'] === 'n' && ($module_params['showFirst'] === 'n' || count($crumbs) > 1)) { $crumbs[count($crumbs) - 1]->hidden = true; } $hide = true; foreach ($crumbs as $crumb) { if (!$crumb->hidden) { $hide = false; } } $smarty->assign('crumbs_all_hidden', $hide); $smarty->assign_by_ref('trail', $crumbs); $smarty->assign('module_params', $module_params); }
arildb/tiki-azure
modules/mod-func-breadcrumbs.php
PHP
lgpl-2.1
3,358
module IB module SimpleStop extend OrderPrototype class << self def defaults super.merge order_type: :stop end def aliases super.merge aux_price: :price end def requirements super.merge aux_price: 'Price where the action is triggert. Aliased as :price' end def summary <<-HERE A Stop order is an instruction to submit a buy or sell market order if and when the user-specified stop trigger price is attained or penetrated. A Stop order is not guaranteed a specific execution price and may execute significantly away from its stop price. A Sell Stop order is always placed below the current market price and is typically used to limit a loss or protect a profit on a long stock position. A Buy Stop order is always placed above the current market price. It is typically used to limit a loss or help protect a profit on a short sale. HERE end end end module StopLimit extend OrderPrototype class << self def defaults super.merge order_type: :stop_limit end def aliases Limit.aliases.merge aux_price: :stop_price end def requirements Limit.requirements.merge aux_price: 'Price where the action is triggert. Aliased as :stop_price' end def summary <<-HERE A Stop-Limit order is an instruction to submit a buy or sell limit order when the user-specified stop trigger price is attained or penetrated. The order has two basic components: the stop price and the limit price. When a trade has occurred at or through the stop price, the order becomes executable and enters the market as a limit order, which is an order to buy or sell at a specified price or better. HERE end end end module StopProtected extend OrderPrototype class << self def defaults super.merge order_type: :stop_protected end def aliases SimpleStop.aliases end def requirements SimpleStop.requirements end def summary <<-HERE US-Futures only ---------------------------- A Stop with Protection order combines the functionality of a stop limit order with a market with protection order. The order is set to trigger at a specified stop price. When the stop price is penetrated, the order is triggered as a market with protection order, which means that it will fill within a specified protected price range equal to the trigger price +/- the exchange-defined protection point range. Any portion of the order that does not fill within this protected range is submitted as a limit order at the exchange-defined trigger price +/- the protection points. HERE end end end # module OrderPrototype module TrailingStop extend OrderPrototype class << self def defaults super.merge order_type: :trailing_stop , tif: :day end def aliases super.merge trail_stop_price: :price, aux_price: :trailing_amount end def requirements ## usualy the trail_stop_price is the market-price minus(plus) the trailing_amount super.merge trail_stop_price: 'Price to trigger the action, aliased as :price' end def alternative_parameters { aux_price: 'Trailing distance in absolute terms, aliased as :trailing_amount', trailing_percent: 'Trailing distance in relative terms'} end def summary <<-HERE A "Sell" trailing stop order sets the stop price at a fixed amount below the market price with an attached "trailing" amount. As the market price rises, the stop price rises by the trail amount, but if the stock price falls, the stop loss price doesn't change, and a market order is submitted when the stop price is hit. This technique is designed to allow an investor to specify a limit on the maximum possible loss, without setting a limit on the maximum possible gain. "Buy" trailing stop orders are the mirror image of sell trailing stop orders, and are most appropriate for use in falling markets. Note that Trailing Stop orders can have the trailing amount specified as a percent, or as an absolute amount which is specified in the auxPrice field. HERE end # summary end # class self end # module module TrailingStopLimit extend OrderPrototype class << self def defaults super.merge order_type: :trailing_limit , tif: :day end def aliases Limit.aliases end def requirements super.merge trail_stop_price: 'Price to trigger the action', limit_price_offset: 'a pRICE' end def alternative_parameters { aux_price: 'Trailing distance in absolute terms', trailing_percent: 'Trailing distance in relative terms'} end def summary <<-HERE A trailing stop limit order is designed to allow an investor to specify a limit on the maximum possible loss, without setting a limit on the maximum possible gain. A SELL trailing stop limit moves with the market price, and continually recalculates the stop trigger price at a fixed amount below the market price, based on the user-defined "trailing" amount. The limit order price is also continually recalculated based on the limit offset. As the market price rises, both the stop price and the limit price rise by the trail amount and limit offset respectively, but if the stock price falls, the stop price remains unchanged, and when the stop price is hit a limit order is submitted at the last calculated limit price. A "Buy" trailing stop limit order is the mirror image of a sell trailing stop limit, and is generally used in falling markets. Products: BOND, CFD, CASH, FUT, FOP, OPT, STK, WAR HERE end end # def TrailingStopLimit(action:str, quantity:float, lmtPriceOffset:float, # trailingAmount:float, trailStopPrice:float): # # # ! [trailingstoplimit] # order = Order() # order.action = action # order.orderType = "TRAIL LIMIT" # order.totalQuantity = quantity # order.trailStopPrice = trailStopPrice # order.lmtPriceOffset = lmtPriceOffset # order.auxPrice = trailingAmount # # ! [trailingstoplimit] # return order # # end end
ib-ruby/ib-ruby
lib/ib/order_prototypes/stop.rb
Ruby
lgpl-2.1
6,301
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2016, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------- * MeanAndStandardDeviation.java * ----------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 05-Feb-2002 : Version 1 (DG); * 05-Feb-2005 : Added equals() method and implemented Serializable (DG); * 02-Oct-2007 : Added getMeanValue() and getStandardDeviationValue() methods * for convenience, and toString() method for debugging (DG); * */ package org.jfree.data.statistics; import java.io.Serializable; import org.jfree.util.ObjectUtilities; /** * A simple data structure that holds a mean value and a standard deviation * value. This is used in the * {@link org.jfree.data.statistics.DefaultStatisticalCategoryDataset} class. */ public class MeanAndStandardDeviation implements Serializable { /** For serialization. */ private static final long serialVersionUID = 7413468697315721515L; /** The mean. */ private Number mean; /** The standard deviation. */ private Number standardDeviation; /** * Creates a new mean and standard deviation record. * * @param mean the mean. * @param standardDeviation the standard deviation. */ public MeanAndStandardDeviation(double mean, double standardDeviation) { this(new Double(mean), new Double(standardDeviation)); } /** * Creates a new mean and standard deviation record. * * @param mean the mean ({@code null} permitted). * @param standardDeviation the standard deviation ({@code null} * permitted. */ public MeanAndStandardDeviation(Number mean, Number standardDeviation) { this.mean = mean; this.standardDeviation = standardDeviation; } /** * Returns the mean. * * @return The mean. */ public Number getMean() { return this.mean; } /** * Returns the mean as a double primitive. If the underlying mean is * {@code null}, this method will return {@code Double.NaN}. * * @return The mean. * * @see #getMean() * * @since 1.0.7 */ public double getMeanValue() { double result = Double.NaN; if (this.mean != null) { result = this.mean.doubleValue(); } return result; } /** * Returns the standard deviation. * * @return The standard deviation. */ public Number getStandardDeviation() { return this.standardDeviation; } /** * Returns the standard deviation as a double primitive. If the underlying * standard deviation is {@code null}, this method will return * {@code Double.NaN}. * * @return The standard deviation. * * @since 1.0.7 */ public double getStandardDeviationValue() { double result = Double.NaN; if (this.standardDeviation != null) { result = this.standardDeviation.doubleValue(); } return result; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MeanAndStandardDeviation)) { return false; } MeanAndStandardDeviation that = (MeanAndStandardDeviation) obj; if (!ObjectUtilities.equal(this.mean, that.mean)) { return false; } if (!ObjectUtilities.equal( this.standardDeviation, that.standardDeviation) ) { return false; } return true; } /** * Returns a string representing this instance. * * @return A string. * * @since 1.0.7 */ @Override public String toString() { return "[" + this.mean + ", " + this.standardDeviation + "]"; } }
simon04/jfreechart
src/main/java/org/jfree/data/statistics/MeanAndStandardDeviation.java
Java
lgpl-2.1
5,489