answer
stringlengths
15
1.25M
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class <API key> extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('application_files', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned()->nullable(); $table->integer('application_id')->unsigned()->nullable(); $table->string('channel')->nullable(); $table->string('path'); $table->string('type'); $table->timestamps(); $table->softDeletes(); $table->timestamp('expired_at')->nullable(); }); Schema::table('application_files', function (Blueprint $table) { // index for fast searches for the different searches we might do $table->index('user_id'); $table->index('application_id'); $table->index('channel'); $table->index(['user_id', 'application_id']); // set them null, a worker can clean up files from storage later? $table->foreign('user_id')->references('id')->on('users')->onDelete('set null'); $table->foreign('application_id')->references('id')->on('applications')->onDelete('set null'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('application_files'); } }
DOXYGEN ?= doxygen # Works with 1.8.3.1. Does not work with 1.6.1. # TODO: Determine what the true minimum version is. DOXYGEN_MIN_VERSION=1.8.0 # caddy_in_arena.png is a special case not handled automatically by Doxygen # because it is hard-coded into the title page (header.tex) all: Doxyfile <API key> reference.html html/.git $(MAKE) -C images $(DOXYGEN) $< cp images/caddy_in_arena.png latex/ $(MAKE) -C latex cp latex/refman.pdf html/caddy.pdf cp -r reference/ html/ @echo @echo '========================================================================' @echo 'Documentation generated sucessfully. Publish with:' @echo @echo 'cd html/' @echo 'git add .' @echo 'git commit -m "Update doxygen-generated documentation"' @echo 'git push origin gh-pages' @echo @echo '========================================================================' # Workaround for GitHub Pages not supporting HTML directory listings
// This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #pragma once #include "edge.hpp" #include "nodes.hpp" #include "../filter.hpp" #include "../../options/options.hpp" #include "../../utils/waiter.hpp" #include "../../utils/task_manager.hpp" #include "../../initializator/initializators.hpp" #include "../trivial/utils.hpp" namespace znn { namespace v4 { namespace parallel_network { class edges { public: struct filter_tag {}; struct dummy_tag {}; struct max_pooling_tag {}; struct real_pooling_tag {}; struct dropout_tag {}; struct crop_tag {}; struct softmax_tag {}; struct maxout_tag {}; protected: options options_; waiter waiter_ ; std::vector<std::unique_ptr<edge>> edges_ ; std::vector<std::unique_ptr<filter>> filters_; vec3i size_ ; task_manager & tm_ ; public: edges( nodes *, nodes *, options const &, vec3i const &, vec3i const &, task_manager &, filter_tag ); edges( nodes *, nodes *, options const &, task_manager &, dummy_tag ); edges( nodes *, nodes *, options const &, vec3i const &, vec3i const &, task_manager &, max_pooling_tag ); edges( nodes *, nodes *, options const &, vec3i const &, task_manager &, real_pooling_tag ); edges( nodes *, nodes *, options const &, vec3i const &, task_manager &, phase phs, dropout_tag ); edges( nodes *, nodes *, options const &, task_manager &, crop_tag ); edges( nodes *, nodes *, options const &, task_manager &, softmax_tag ); edges( nodes *, nodes *, options const &, task_manager &, maxout_tag ); std::string name() const { return options_.require_as<std::string>("name"); } // [kisuklee] // This is only temporary implementation and will be removed. void set_phase( phase phs ) { for ( auto & e: edges_ ) { e->set_phase(phs); } } void set_eta( real eta ) { if ( filters_.size() ) { options_.push("eta", eta); for ( auto & f: filters_ ) f->eta() = eta; } } void set_momentum( real mom ) { if ( filters_.size() ) { options_.push("momentum", mom); for ( auto & f: filters_ ) f->momentum() = mom; } } void set_weight_decay( real wd ) { if ( filters_.size() ) { options_.push("weight_decay", wd); for ( auto & f: filters_ ) f->weight_decay() = wd; } } void set_patch_size( real s ) { if ( filters_.size() ) { for ( auto & e: edges_ ) e->set_patch_size(s); } } options serialize() const { options ret = options_; if ( filters_.size() ) { ret.push("filters", save_filters(filters_, size_)); } return ret; } void edge_zapped() { waiter_.one_done(); } void zap() { for ( auto & e: edges_ ) { e->zap(this); } waiter_.wait(); } }; }}} // namespace znn::v4::parallel_network
package application; public interface ControllerInterface { public static void OutputText(String outputText) { Main.OutputText(outputText); } public static void OutputPicture(String picture) { Main.OutputPicture(picture); } }
/** DataCruncher.java * * @author Sunita Sarawagi * @since 1.0 * @version 1.3 */ package org.melodi.learning.iitb.Segment; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Pattern; import org.melodi.learning.iitb.CRF.DataSequence; import org.melodi.learning.iitb.CRF.Segmentation; public class DataCruncher { /** * * @param text * @param delimit A set of delimiters used by the Tokenizer. * @param impDelimit Delimiters to be retained for tagging. * @return an Array of tokens. */ protected static String[] getTokenList(String text, String delimit, String impDelimit) { text = text.toLowerCase(); StringTokenizer textTok = new StringTokenizer(text, delimit, true); //This allocates space for all tokens and delimiters, //but will make a second pass through the String unnecessary. ArrayList<String> tokenList = new ArrayList<String>(textTok.countTokens()); while (textTok.hasMoreTokens()) { String tokStr = textTok.nextToken(); if (!delimit.contains(tokStr) || impDelimit.contains(tokStr)) { tokenList.add(tokStr); } } //Finally, the storage is trimmed to the actual size. return tokenList.toArray(new String[tokenList.size()]); } /** * Reads a block of text ended by a blank line or the end of the file. * The block contains lines of tokens with a label. * @param numLabels The maximal number of labels expected * @param tin * @param tagDelimit Separator between tokens and tag number * @param delimit Used to define token boundaries * @param impDelimit Delimiters to be retained for tagging * @param t Stores the labels * @param cArray Stores the tokens * @return number of lines read * @throws IOException */ public static int readRowVarCol(int numLabels, BufferedReader tin, String tagDelimit, String delimit, String impDelimit, int[] t, String[][] cArray) throws IOException { int ptr = 0; String line; while(true) { line = tin.readLine(); StringTokenizer firstSplit=null; if (line!=null) { firstSplit=new StringTokenizer(line.toLowerCase(),tagDelimit); } if ((line==null) || (firstSplit.countTokens()<2)) { // Empty Line return ptr; } String w = firstSplit.nextToken(); int label=Integer.parseInt(firstSplit.nextToken()); t[ptr] = label; cArray[ptr++] = getTokenList(w,delimit,impDelimit); } } static int readRowFixedCol(int numLabels, BufferedReader tin, String tagDelimit, String delimit, String impDelimit, int[] t, String[][] cArray, int labels[]) throws IOException { String line=tin.readLine(); if (line == null) return 0; StringTokenizer firstSplit=new StringTokenizer(line.toLowerCase(),tagDelimit,true); int ptr = 0; for (int i = 0; (i < labels.length) && firstSplit.hasMoreTokens(); i++) { int label = labels[i]; String w = firstSplit.nextToken(); if (tagDelimit.indexOf(w)!=-1) { continue; } else { if (firstSplit.hasMoreTokens()) // read past the delimiter. firstSplit.nextToken(); } if ((label > 0) && (label <= numLabels)) { t[ptr] = label; cArray[ptr++] = getTokenList(w,delimit,impDelimit); } } return ptr; } /** * Checks, if the data are available in fixed column format, or variable * column format. * @param numLabels The maximal number of labels expected * @param tin * @param tagDelimit A character as String that acts as a delimiter between tokens and label. * @return An array with labels if the data are in fixed column format, null otherwise. * @throws IOException */ protected static int[] readHeaderInfo(int numLabels, BufferedReader tin, String tagDelimit) throws IOException { tin.mark(1000); String line = tin.readLine(); if (line == null) { throw new IOException("Header row not present in tagged file"); } if (!line.toLowerCase().startsWith("fixed-column-format")) { tin.reset(); return null; } line = tin.readLine(); Pattern delimitPattern = Pattern.compile(tagDelimit, Pattern.LITERAL); String[] parts = delimitPattern.split(line); int labels[] = new int[numLabels]; for (int i = 0, size = parts.length; i < size; ++i) { labels[i] = Integer.parseInt(parts[i]); } return labels; } public static TrainData readTagged(int numLabels, String tfile, String rfile, String delimit, String tagDelimit, String impDelimit, LabelMap labelMap) { try { ArrayList<DCTrainRecord> td = new ArrayList<DCTrainRecord>(); BufferedReader tin = new BufferedReader(new FileReader(tfile + ".tagged")); BufferedReader rin = new BufferedReader(new FileReader(rfile + ".raw")); boolean fixedColFormat = false; String rawLine; StringTokenizer rawTok; int t[] = new int[0]; String cArray[][] = new String[0][0]; int[] labels = null; // read list of columns in the header of the tag file labels = readHeaderInfo(numLabels, tin, tagDelimit); if (labels != null) { fixedColFormat = true; } while ((rawLine = rin.readLine()) != null) { rawTok = new StringTokenizer(rawLine, delimit, true); int len = rawTok.countTokens(); if (len > t.length) { t = new int[len]; cArray = new String[len][0]; } int ptr = 0; if (fixedColFormat) { ptr = readRowFixedCol(numLabels, tin, tagDelimit, delimit, impDelimit, t, cArray, labels); } else { ptr = readRowVarCol(numLabels, tin, tagDelimit, delimit, impDelimit, t, cArray); } if (ptr == 0) { break; } int at[] = new int[ptr]; String[][] c = new String[ptr][0]; for (int i = 0; i < ptr; i++) { at[i] = labelMap.map(t[i]); c[i] = cArray[i]; } td.add(new DCTrainRecord(at, c)); } return new DCTrainData(td); } catch (IOException e) { System.err.println("I/O Error" + e); System.exit(-1); } return null; } public static void readRaw(Vector<String[]> data,String file,String delimit,String impDelimit) { try { BufferedReader rin=new BufferedReader(new FileReader(file+".raw")); String line; while((line=rin.readLine())!=null) { StringTokenizer tok=new StringTokenizer(line.toLowerCase(),delimit,true); String seq[]=new String[tok.countTokens()]; int count=0; for(int i=0 ; i<seq.length ; i++) { String tokStr=tok.nextToken(); if (delimit.indexOf(tokStr)==-1 || impDelimit.indexOf(tokStr)!=-1) { seq[count++]=new String(tokStr); } } String aseq[]=new String[count]; for(int i=0 ; i<count ; i++) { aseq[i]=seq[i]; } data.add(aseq); } rin.close(); } catch(IOException e) { System.out.println("I/O Error"+e); System.exit(-1); } } /** * * @param file * @param tagDelimit A character as String that acts as a delimiter between tokens and label. */ public static void createRaw(String file, String tagDelimit) { BufferedReader in = null; PrintWriter out = null; try { in = new BufferedReader(new FileReader(file + ".tagged")); out = new PrintWriter(new FileOutputStream(file + ".raw")); String line; StringBuilder rawLine; rawLine = new StringBuilder(200); while((line=in.readLine())!=null) { StringTokenizer t=new StringTokenizer(line,tagDelimit); if(t.countTokens()<2) { out.println(rawLine); rawLine.setLength(0); } else { rawLine.append(" "); rawLine.append(t.nextToken()); } } out.println(rawLine); } catch (IOException e) { System.out.println("I/O Error" + e); System.exit(-1); } finally { if (in != null) { try { in.close();} catch (IOException e) {} } if (out != null) { out.close(); } } } }
using UnityEngine; using System.Collections; public class <API key> : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_33) on Fri Aug 03 11:43:01 PDT 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class com.hp.hpl.jena.sparql.sse.builders.BuilderGraph (Apache Jena ARQ) </TITLE> <META NAME="date" CONTENT="2012-08-03"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hp.hpl.jena.sparql.sse.builders.BuilderGraph (Apache Jena ARQ)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../com/hp/hpl/jena/sparql/sse/builders/BuilderGraph.html" title="class in com.hp.hpl.jena.sparql.sse.builders"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?com/hp/hpl/jena/sparql/sse/builders//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="BuilderGraph.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <CENTER> <H2> <B>Uses of Class<br>com.hp.hpl.jena.sparql.sse.builders.BuilderGraph</B></H2> </CENTER> No usage of com.hp.hpl.jena.sparql.sse.builders.BuilderGraph <P> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../com/hp/hpl/jena/sparql/sse/builders/BuilderGraph.html" title="class in com.hp.hpl.jena.sparql.sse.builders"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../../index.html?com/hp/hpl/jena/sparql/sse/builders//<API key>.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="BuilderGraph.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Licenced under the Apache License, Version 2.0 </BODY> </HTML>
<!DOCTYPE html> <html xmlns="http: <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Sistem Informasi Akademik Man Cibadak</title> <!-- DATETIMEPICKER--> <link href="<?php echo base_url('datetimepicker/bootstrap/css/bootstrap.min.css') ?>" rel="stylesheet" media="screen"> <link href="<?php echo base_url('datetimepicker/css/<API key>.min.css') ?>" rel="stylesheet" media="screen"> <!-- BOOTSTRAP STYLES--> <link href="<?php echo base_url('assets/backend/css/bootstrap.css') ?>" rel="stylesheet" /> <!-- FONTAWESOME STYLES--> <link href="<?php echo base_url('assets/backend/css/font-awesome.css') ?>" rel="stylesheet" /> <!-- CUSTOM STYLES--> <link href="<?php echo base_url('assets/backend/css/custom.css') ?>" rel="stylesheet" /> <!-- GOOGLE FONTS--> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> </head> <body> <div id="wrapper"> <?php include "menuatas.php"; ?> <!-- /. NAV TOP --> <?php include "menu.php"; ?> <!-- /. NAV SIDE --> <div id="page-wrapper" > <div id="page-inner"> <div class="row"> <div class="col-md-12"> <h2>Madrasah Aliyah Negeri Cibadak</h2> <h5>Sistem Informasi Akademik</h5> </div> </div> <!-- /. ROW --> <hr /> <div class="row"> <div class="col-md-12"> <!-- Form Elements --> <div class="panel panel-default"> <div class="panel-heading"> Input Data Kelas </div> <div class="panel-body"> <div class="row"> <div class="col-md-6"> <form action="<?php echo base_url().'index.php/kelas_c/addkelas' ?>" enctype="multipart/form-data" method="post" role="form"> <div class="form-group has-warning"> <label class="control-label" for="inputWarning"><?php echo $this->session->flashdata('error');?></label> <label class="control-label" for="inputWarning"><?php echo $this->session->flashdata('succes');?></label> </div> <div class="form-group"> <label>Nama Kelas</label> <input class="form-control" placeholder="PLease Enter Keyword" name="nama_kelas" onkeyup="this.value = this.value.toUpperCase()" /> </div> <div class="form-group"> <label>Program Kelas</label> <div class="radio"> <label> <input type="radio" name="program_kelas" id="optionsRadios1" value="Program IPS" />Program IPS </label> </div> <div class="radio"> <label> <input type="radio" name="program_kelas" id="optionsRadios2" value="Program IPA"/>Program IPA </label> </div> <div class="radio"> <label> <input type="radio" name="program_kelas" id="optionsRadios3" value="Program Bahasa"/>Program Bahasa </label> </div> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" name="daftar" value="Simpan" /> <input class="btn btn-default" type="reset" name="reset" value="Reset" /> </div> </form> </div> </div> </div> <!-- End Form Elements --> </div> </div> </div> <!-- /. ROW --> <div class="row"> <div class="col-md-12"> </div> </div> <!-- /. ROW --> </div> <!-- /. PAGE INNER --> </div> <!-- /. PAGE WRAPPER --> </div> <!-- /. WRAPPER --> <!-- SCRIPTS -AT THE BOTOM TO REDUCE THE LOAD TIME--> <!-- DATETIMEPICKER JQUERY SCRIPTS --> <script type="text/javascript" src="<?php echo base_url('datetimepicker/jquery/jquery-1.8.3.min.js') ?>" charset="UTF-8"></script> <script type="text/javascript" src="<?php echo base_url('datetimepicker/bootstrap/js/bootstrap.min.js') ?>"></script> <script type="text/javascript" src="<?php echo base_url('datetimepicker/js/<API key>.js') ?>" charset="UTF-8"></script> <script type="text/javascript" src="<?php echo base_url('datetimepicker/js/locales/<API key>.id.js') ?>" charset="UTF-8"></script> <script type="text/javascript"> $('.form_datetime').datetimepicker({ //language: 'fr', weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 2, forceParse: 0, showMeridian: 1 }); $('.form_date').datetimepicker({ language: 'id', weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 2, minView: 2, forceParse: 0 }); $('.form_time').datetimepicker({ language: 'id', weekStart: 1, todayBtn: 1, autoclose: 1, todayHighlight: 1, startView: 1, minView: 0, maxView: 1, forceParse: 0 }); </script> <!-- JQUERY SCRIPTS --> <script src="<?php echo base_url('assets/backend/js/jquery-1.10.2.js') ?>"></script> <!-- BOOTSTRAP SCRIPTS --> <script src="<?php echo base_url('assets/backend/js/bootstrap.min.js') ?>"></script> <!-- METISMENU SCRIPTS --> <script src="<?php echo base_url('assets/backend/js/jquery.metisMenu.js') ?>"></script> <!-- CUSTOM SCRIPTS --> <script src="<?php echo base_url('assets/backend/js/custom.js') ?>"></script> </body> </html>
import os import unittest from copyright import Walk class TestWalk(unittest.TestCase): DIRS = [ './tmp/dir1/dir2', './tmp/dir3' ] FILES = [ './tmp/f', './tmp/dir1/f1', './tmp/dir3/f3', './tmp/dir1/dir2/f2' ] def setUp(self): for d in self.DIRS: os.makedirs(d) for p in self.FILES: with open(p, 'w') as f: pass def tearDown(self): for p in self.FILES: if os.path.exists(p): os.remove(p) for d in self.DIRS: if os.path.exists(d): os.removedirs(d) def test_default(self): files = [] for f in Walk(): files.append(f) for f in self.FILES: self.assertTrue(f in files) def test_exclude(self): files = [] exclude = ['f1', 'f2'] for f in Walk(exclude=exclude): files.append(f) self.assertTrue(self.FILES[0] in files) self.assertTrue(self.FILES[2] in files) self.assertFalse(self.FILES[1] in files) self.assertFalse(self.FILES[3] in files) def test_include(self): files = [] include = ['*1', 'dir2'] for f in Walk(include=include): files.append(f) self.assertFalse(self.FILES[0] in files) self.assertTrue(self.FILES[1] in files) self.assertFalse(self.FILES[2] in files) self.assertTrue(self.FILES[3] in files) def test_include_regex(self): files = [] include = ['f[\d]$'] for f in Walk(include=include, regex=True): files.append(f) self.assertTrue(self.FILES[1] in files) self.assertTrue(self.FILES[2] in files) self.assertTrue(self.FILES[3] in files) self.assertFalse(self.FILES[0] in files) def test_path(self): files = [] for f in Walk(path='./tmp'): files.append(f) for f in self.FILES: self.assertTrue(f in files) if '__main__' == __name__: unittest.main(verbosity=2)
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is free software; you can redistribute it and/or modify # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class <API key>(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="CellRendererCombo Example") self.set_default_size(200, 200) <API key> = Gtk.ListStore(str) manufacturers = ["Sony", "LG", "Panasonic", "Toshiba", "Nokia", "Samsung"] for item in manufacturers: <API key>.append([item]) self.liststore_hardware = Gtk.ListStore(str, str) self.liststore_hardware.append(["Television", "Samsung"]) self.liststore_hardware.append(["Mobile Phone", "LG"]) self.liststore_hardware.append(["DVD Player", "Sony"]) treeview = Gtk.TreeView(model=self.liststore_hardware) renderer_text = Gtk.CellRendererText() column_text = Gtk.TreeViewColumn("Text", renderer_text, text=0) treeview.append_column(column_text) renderer_combo = Gtk.CellRendererCombo() renderer_combo.set_property("editable", True) renderer_combo.set_property("model", <API key>) renderer_combo.set_property("text-column", 0) renderer_combo.set_property("has-entry", False) renderer_combo.connect("edited", self.on_combo_changed) column_combo = Gtk.TreeViewColumn("Combo", renderer_combo, text=1) treeview.append_column(column_combo) self.add(treeview) def on_combo_changed(self, widget, path, text): self.liststore_hardware[path][1] = text win = <API key>() win.connect("destroy", Gtk.main_quit) win.show_all() Gtk.main()
package de.clusteval.paramOptimization; import java.io.File; import java.io.<API key>; import java.util.ArrayList; import java.util.Map; import junit.framework.Assert; import junitx.framework.ArrayAssert; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import utils.ArraysExt; import ch.qos.logback.classic.Level; import de.clusteval.data.DataConfig; import de.clusteval.framework.<API key>; import de.clusteval.framework.repository.<API key>; import de.clusteval.framework.repository.RegisterException; import de.clusteval.framework.repository.Repository; import de.clusteval.framework.repository.<API key>; import de.clusteval.framework.repository.config.<API key>; import de.clusteval.framework.repository.config.<API key>; import de.clusteval.program.ProgramConfig; import de.clusteval.program.ProgramParameter; import de.clusteval.quality.QualityMeasure; import de.clusteval.quality.QualityMeasureValue; import de.clusteval.quality.QualitySet; import de.clusteval.quality.<API key>; import de.clusteval.run.<API key>; import de.clusteval.run.Run; import de.clusteval.run.result.<API key>; import de.clusteval.utils.<API key>; /** * @author Christian Wiwie * */ public class <API key> { /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws SecurityException * @throws <API key> * @throws RegisterException */ @Test public void testLayered() throws <API key>, <API key>, <API key>, <API key>, <API key>, SecurityException, <API key>, RegisterException { <API key>.logLevel(Level.INFO); Repository repo = new Repository( new File("repository").getAbsolutePath(), null); repo.initialize(); int[] iters = ArraysExt.rep((int) Math.pow(100, 0.5), 2); <API key> method = new <API key>( repo, false, System.currentTimeMillis(), new File("bla"), null, null, null, null, null, iters, false); method.<API key> = 100; Assert.assertEquals(100, method.<API key>); Assert.assertEquals(100, method.<API key>()); int[] newIterations = method.<API key>(); ArrayAssert.assertEquals(new int[]{5, 5}, newIterations); Assert.assertEquals(75, method.<API key>); newIterations = method.<API key>(); ArrayAssert.assertEquals(new int[]{5, 5}, newIterations); Assert.assertEquals(50, method.<API key>); newIterations = method.<API key>(); ArrayAssert.assertEquals(new int[]{5, 5}, newIterations); Assert.assertEquals(25, method.<API key>); newIterations = method.<API key>(); ArrayAssert.assertEquals(new int[]{5, 5}, newIterations); Assert.assertEquals(0, method.<API key>); } /** * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws SecurityException * @throws <API key> * @throws RegisterException * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> */ @Test public void testLayered2() throws <API key>, <API key>, <API key>, <API key>, <API key>, SecurityException, <API key>, RegisterException, <API key>, <API key>, <API key>, <API key>, <API key> { <API key>.logLevel(Level.INFO); Repository repo = new Repository( new File("repository").getAbsolutePath(), null); repo.initialize(); ProgramConfig programConfig = repo .<API key>("gedevo.config"); DataConfig dataConfig = repo .<API key>("rashid_merge.dataconfig"); Run run = new <API key>(repo, null, 0, new File("bla"), new ArrayList<ProgramConfig>(), new ArrayList<DataConfig>(), new ArrayList<QualityMeasure>(), new ArrayList<Map<ProgramParameter<?>, String>>(), null, new ArrayList<<API key>>()); int[] iters = ArraysExt.rep((int) Math.pow(100, 0.5), 2); <API key> method = new <API key>( repo, false, System.currentTimeMillis(), new File("bla"), (<API key>) run, programConfig, dataConfig, programConfig.<API key>(), QualityMeasure.parseFromString(repo, "<API key>"), iters, false); method.reset(new File("repository").getAbsoluteFile()); QualitySet qualSet = new QualitySet(); qualSet.put(QualityMeasure.parseFromString(repo, "<API key>"), QualityMeasureValue .getForDouble(0.0)); qualSet.put(QualityMeasure.parseFromString(repo, "<API key>"), QualityMeasureValue .getForDouble(0.0)); qualSet.put(QualityMeasure.parseFromString(repo, "<API key>"), QualityMeasureValue .getForDouble(0.0)); Assert.assertEquals(100, method.<API key>()); Assert.assertEquals(3, method.layerCount); Assert.assertEquals(100, method.<API key>); // first layer method.next(); method.giveQualityFeedback(qualSet); Assert.assertEquals(25, method.<API key>.<API key>()); while (method.currentCount < 25) { Assert.assertEquals(true, method.hasNext()); method.next(); method.giveQualityFeedback(qualSet); System.out.println(method.currentCount); } // second layer Assert.assertEquals(25, method.<API key>.<API key>()); while (method.currentCount < 50) { Assert.assertEquals(true, method.hasNext()); method.next(); method.giveQualityFeedback(qualSet); System.out.println(method.currentCount); } // third layer Assert.assertEquals(49, method.<API key>.<API key>()); while (method.currentCount < 98) { Assert.assertEquals(true, method.hasNext()); method.next(); method.giveQualityFeedback(qualSet); System.out.println(method.currentCount); } // last iteration is a skipping iteration Assert.assertEquals(true, method.hasNext()); try { method.next(); } catch (<API key> e) { } method.giveQualityFeedback(qualSet); System.out.println(method.currentCount); Assert.assertEquals(0, method.<API key>); } /** * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws SecurityException * @throws <API key> * @throws RegisterException * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> * @throws <API key> */ @Test public void <API key>() throws <API key>, <API key>, <API key>, <API key>, <API key>, SecurityException, <API key>, RegisterException, <API key>, <API key>, <API key>, <API key>, <API key> { <API key>.logLevel(Level.INFO); Repository repo = new Repository( new File("repository").getAbsolutePath(), null); repo.initialize(); ProgramConfig programConfig = repo .<API key>("spinal.config"); DataConfig dataConfig = repo .<API key>("rashid_merge.dataconfig"); Run run = new <API key>(repo, null, 0, new File("bla"), new ArrayList<ProgramConfig>(), new ArrayList<DataConfig>(), new ArrayList<QualityMeasure>(), new ArrayList<Map<ProgramParameter<?>, String>>(), null, new ArrayList<<API key>>()); int[] iters = ArraysExt.rep((int) Math.pow(100, 0.5), 2); <API key> method = new <API key>( repo, false, System.currentTimeMillis(), new File("bla"), (<API key>) run, programConfig, dataConfig, programConfig.<API key>(), QualityMeasure.parseFromString(repo, "<API key>"), iters, false); method.reset(new File("repository").getAbsoluteFile()); Assert.assertEquals(20, method.<API key>()); for (ProgramParameter<?> param : method.parameterValues.keySet()) ArraysExt.print(method.parameterValues.get(param)); ArraysExt.print(method.<API key>); } }
package com.atlauncher.gui.components; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.JPanel; import com.atlauncher.App; import com.atlauncher.LogManager; import com.atlauncher.data.Constants; import com.atlauncher.data.Language; import com.atlauncher.evnt.listener.<API key>; import com.atlauncher.evnt.manager.<API key>; import com.atlauncher.thread.PasteUpload; public class ConsoleBottomBar extends BottomBar implements <API key> { private final JPanel leftSide = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 10)); private final JButton clearButton = new JButton("Clear"); private final JButton copyLogButton = new JButton("Copy Log"); private final JButton uploadLogButton = new JButton("Upload Log"); private final JButton killMinecraftButton = new JButton("Kill Minecraft"); public ConsoleBottomBar() { this.addActionListeners(); // Setup Action Listeners this.leftSide.add(this.clearButton); this.leftSide.add(this.copyLogButton); this.leftSide.add(this.uploadLogButton); this.leftSide.add(this.killMinecraftButton); this.killMinecraftButton.setVisible(false); this.add(this.leftSide, BorderLayout.WEST); <API key>.addListener(this); } /** * Sets up the action listeners on the buttons */ private void addActionListeners() { clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { App.settings.clearConsole(); LogManager.info("Console Cleared"); } }); copyLogButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { App.TOASTER.pop("Copied Log to clipboard"); LogManager.info("Copied Log to clipboard"); StringSelection text = new StringSelection(App.settings.getLog()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(text, null); } }); uploadLogButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String result = App.TASKPOOL.submit(new PasteUpload()).get(); if (result.contains(Constants.PASTE_CHECK_URL)) { App.TOASTER.pop("Log uploaded and link copied to clipboard"); LogManager.info("Log uploaded and link copied to clipboard: " + result); StringSelection text = new StringSelection(result); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(text, null); } else { App.TOASTER.popError("Log failed to upload!"); LogManager.error("Log failed to upload: " + result); } } catch (Exception ex) { ex.printStackTrace(System.err); } } }); killMinecraftButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int ret = JOptionPane.showConfirmDialog(App.settings.getParent(), "<html><p align=\"center\">" + Language.INSTANCE.localizeWithReplace("console.killsure", "<br/><br/>") + "</p></html>", Language.INSTANCE.localize("console.kill"), JOptionPane.YES_NO_OPTION); if (ret == JOptionPane.YES_OPTION) { App.settings.killMinecraft(); killMinecraftButton.setVisible(false); } } }); } public void showKillMinecraft() { killMinecraftButton.setVisible(true); } public void hideKillMinecraft() { killMinecraftButton.setVisible(false); } public void setupLanguage() { this.onRelocalization(); } @Override public void onRelocalization() { clearButton.setText(Language.INSTANCE.localize("console.clear")); copyLogButton.setText(Language.INSTANCE.localize("console.copy")); uploadLogButton.setText(Language.INSTANCE.localize("console.upload")); killMinecraftButton.setText(Language.INSTANCE.localize("console.kill")); } }
<?php class <API key> extends <API key> { public function <API key>() { $attachment = $this->_createAttachment($this->_createHeaderSet(), $this->_createEncoder(), $this->_createCache() ); $this->assertEquals( <API key>::LEVEL_MIXED, $attachment->getNestingLevel() ); } public function <API key>() { /* -- RFC 2183, 2.1, 2.2. */ $disposition = $this->_createHeader('Content-Disposition', 'attachment'); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $this->assertEquals('attachment', $attachment->getDisposition()); } public function <API key>() { $disposition = $this->_createHeader('Content-Disposition', 'attachment', array(), false ); $disposition->shouldReceive('setFieldBodyModel') ->once() ->with('inline'); $disposition->shouldReceive('setFieldBodyModel') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $attachment->setDisposition('inline'); } public function <API key>() { $headers = $this->_createHeaderSet(array(), false); $headers->shouldReceive('<API key>') ->once() ->with('Content-Disposition', 'inline'); $headers->shouldReceive('<API key>') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($headers, $this->_createEncoder(), $this->_createCache() ); $attachment->setDisposition('inline'); } public function <API key>() { $headers = $this->_createHeaderSet(array(), false); $headers->shouldReceive('<API key>') ->once() ->with('Content-Disposition', 'attachment'); $headers->shouldReceive('<API key>') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($headers, $this->_createEncoder(), $this->_createCache() ); } public function <API key>() { $cType = $this->_createHeader('Content-Type', '', array(), false ); $cType->shouldReceive('setFieldBodyModel') ->once() ->with('application/octet-stream'); $cType->shouldReceive('setFieldBodyModel') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Type' => $cType,)), $this->_createEncoder(), $this->_createCache() ); } public function <API key>() { /* -- RFC 2183, 2.3. */ $disposition = $this->_createHeader('Content-Disposition', 'attachment', array('filename' => 'foo.txt') ); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $this->assertEquals('foo.txt', $attachment->getFilename()); } public function <API key>() { $disposition = $this->_createHeader('Content-Disposition', 'attachment', array('filename' => 'foo.txt'), false ); $disposition->shouldReceive('setParameter') ->once() ->with('filename', 'bar.txt'); $disposition->shouldReceive('setParameter') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $attachment->setFilename('bar.txt'); } public function <API key>() { /* This is a legacy requirement which isn't covered by up-to-date RFCs. */ $cType = $this->_createHeader('Content-Type', 'text/plain', array(), false ); $cType->shouldReceive('setParameter') ->once() ->with('name', 'bar.txt'); $cType->shouldReceive('setParameter') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Type' => $cType,)), $this->_createEncoder(), $this->_createCache() ); $attachment->setFilename('bar.txt'); } public function <API key>() { /* -- RFC 2183, 2.7. */ $disposition = $this->_createHeader('Content-Disposition', 'attachment', array('size' => 1234) ); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $this->assertEquals(1234, $attachment->getSize()); } public function <API key>() { $disposition = $this->_createHeader('Content-Disposition', 'attachment', array(), false ); $disposition->shouldReceive('setParameter') ->once() ->with('size', 12345); $disposition->shouldReceive('setParameter') ->zeroOrMoreTimes(); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $attachment->setSize(12345); } public function <API key>() { $file = $this->_createFileStream('/bar/file.ext', ''); $disposition = $this->_createHeader('Content-Disposition', 'attachment', array('filename' => 'foo.txt'), false ); $disposition->shouldReceive('setParameter') ->once() ->with('filename', 'file.ext'); $attachment = $this->_createAttachment($this->_createHeaderSet(array( 'Content-Disposition' => $disposition,)), $this->_createEncoder(), $this->_createCache() ); $attachment->setFile($file); } public function <API key>() { $file = $this->_createFileStream('/bar/file.ext', ''); $disposition = $this->_createHeader('Content-Disposition', 'attachment', array('filename' => 'foo.txt'), false ); $disposition->shouldReceive('setParameter') ->once() ->with('filename', 'file.ext'); $ctype = $this->_createHeader('Content-Type', 'text/plain', array(), false); $ctype->shouldReceive('setFieldBodyModel') ->once() ->with('text/html'); $ctype->shouldReceive('setFieldBodyModel') ->zeroOrMoreTimes(); $headers = $this->_createHeaderSet(array( 'Content-Disposition' => $disposition, 'Content-Type' => $ctype, )); $attachment = $this->_createAttachment($headers, $this->_createEncoder(), $this->_createCache() ); $attachment->setFile($file, 'text/html'); } public function <API key>() { $file = $this->_createFileStream('/bar/file.zip', ''); $disposition = $this->_createHeader('Content-Disposition', 'attachment', array('filename' => 'foo.zip'), false ); $disposition->shouldReceive('setParameter') ->once() ->with('filename', 'file.zip'); $ctype = $this->_createHeader('Content-Type', 'text/plain', array(), false); $ctype->shouldReceive('setFieldBodyModel') ->once() ->with('application/zip'); $ctype->shouldReceive('setFieldBodyModel') ->zeroOrMoreTimes(); $headers = $this->_createHeaderSet(array( 'Content-Disposition' => $disposition, 'Content-Type' => $ctype, )); $attachment = $this->_createAttachment($headers, $this->_createEncoder(), $this->_createCache(), array('zip' => 'application/zip', 'txt' => 'text/plain') ); $attachment->setFile($file); } public function <API key>() { $file = $this->_createFileStream('/foo/file.ext', '<some data>'); $attachment = $this->_createAttachment($this->_createHeaderSet(), $this->_createEncoder(), $this->_createCache() ); $attachment->setFile($file); $this->assertEquals('<some data>', $attachment->getBody()); } public function testFluidInterface() { $attachment = $this->_createAttachment($this->_createHeaderSet(), $this->_createEncoder(), $this->_createCache() ); $this->assertSame($attachment, $attachment ->setContentType('application/pdf') ->setEncoder($this->_createEncoder()) ->setId('foo@bar') ->setDescription('my pdf') ->setMaxLineLength(998) ->setBody('xx') ->setBoundary('xyz') ->setChildren(array()) ->setDisposition('inline') ->setFilename('afile.txt') ->setSize(123) ->setFile($this->_createFileStream('foo.txt', '')) ); } // -- Private helpers protected function _createEntity($headers, $encoder, $cache) { return $this->_createAttachment($headers, $encoder, $cache); } protected function _createAttachment($headers, $encoder, $cache, $mimeTypes = array()) { return new <API key>($headers, $encoder, $cache, new Swift_Mime_Grammar(), $mimeTypes); } protected function _createFileStream($path, $data, $stub = true) { $file = $this->getMockery('Swift_FileStream'); $file->shouldReceive('getPath') ->zeroOrMoreTimes() ->andReturn($path); $file->shouldReceive('read') ->zeroOrMoreTimes() ->andReturnUsing(function () use ($data) { static $first = true; if (!$first) { return false; } $first = false; return $data; }); $file->shouldReceive('setReadPointer') ->zeroOrMoreTimes(); return $file; } }
<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 --> - [Preface](#preface) - [Chapter 1](#chapter-1) - [General features](#general-features) - [Theorey of value](#theorey-of-value) - [Microeconomics](#microeconomics) - [Chapter 2](#chapter-2) - [Derivates](#derivates) - [first order derivatives](#<API key>) - [Second order derivatives](#<API key>) - [Function with several variable](#<API key>) - [Utility function](#utility-function) - [Partial derivatives](#partial-derivatives) - [Total Differential](#total-differential) - [Constrained Maximisation, Lagrangian](#<API key>) - [$\lambda$ - Economic interpretation](#<API key>) - [Implicit function theorem: $g(x, y) = 0$, how $x,y$ are related](#<API key>) - [The Envelope theorem](#<API key>) - [Homogeneous Functions](#<API key>) - [Euler's Theorem](#eulers-theorem) <!-- /TOC --> # Preface * Midterms 10/25, 11/17 in class, 1hr 15 mins - 1st midterm chapter 1-4 - 10 Mul Choice + 2 long question - Scantron 882-E * Final 12/8 11:30-2:30 * Problems set will be graded due in one week * HW 10% * Exam 90% * 30/30/30, when final is lower than midterm * 50% higher midterm, 40% final, when final is higher than midterm. <br/> # Chapter 1 ## General features * the **ceteris paribus** assumption, meaning other things stay same. * Optimization assumptions, maximize the profits. * positive - normative distinction * positive = real world; * normative = how things shoule be like. ## Theorey of value * Determine Equilibrium price, set quantity demanded = quantity supplied, $q_D=q_S$ * Production possibility frontier, * No free luch, oppotunity cost; * Oppotunity cost depends on how much each goods is produced. <br/> ## Microeconomics `Behavior of individual decision makers (consumers and firms)` * Maximizing behaviours. `e.g.` stay bed/go to class, bacon/cereals, * Price elasticity / Income effect. `e.g.` bus/car to school * Price is not only the money you pay. Psychological cost (do not want to risk/ waste time). `e.g.` bank/parent loan/ investments (bonds, stocks) * Marginal rate of substation. (cost of behavior), maximizing behavior. `e.g.` listen to the lecture/doze off, history/econ/job <br/> # Chapter 2 * Mathematics of Optimization. * Consumers attempt to maximize their welfare/utility when making decision. * Firms attempt to maximizing their profit when choosing input and outputs. * Profits $\pi$ = total revenue - total cost * Total revenue = $p*q$, $p$ is the price and $q$ is the quantity. ## Derivates first order derivatives $f(x) = Q, ~ Q ~ is ~ a ~ constant, ~ f'(x) = 0$ $f(x) = Q*x, ~ f'(x) = a$ $f(x) = a*g(x),~ f'(x) = a ~ d ~ of ~ g(x)$ $f(x) = x^b, ~ b ~ is ~ constant, ~ f'(x) = b x^{(b-1)}$ $f(x) = a x^b = a g(x) ~ f'(x) = a*b*x^{(b-1)}$ $f(x) = ln(x) ~ f'(x) = \frac {1}{x}$ > $e = ruler's~number~ \approx ~ 2.72$ > $ln(e^{x}) = x$ > $ln(e) =1$ > $ln(a*b) = ln(a) + ln(b)$ > $ln(\frac {a}{b}) = ln(a) - ln(b)$ > $ln(b^a) = a*ln(b)$ $f(x) = a^x ~ f'(x) = ln(a) * a^x$ $f(x) = e^x ~ f'(x) = e^x$ $f(x) = g(x) + h(x) ~ f'(x) = g'(x) + h'(x)$ $f(x) = g(x) * h(x) ~ f'(x) = g'(x)h(x) + h'(x)g(x)$ $f(x) = \frac {g(x)}{h(x)} ~ f'(x) = \frac {[g'(x)h(x) - h'(x)g(x)]} {g^{2}(x)}$ $f(x) = g[h(x)] ~ f'(x) = \frac {dg}{dh} * \frac {dh}{dx} ~~~ chain ~ rule$ <br/> Second order derivatives * first order condition max of a function with one variable, the derivative at that point is 0; * second order condition to make sure the critical point is the max ( second derivative is negative). critical point is min when second derivative is positive. * MAX: "mountain shape", **concave** * MIN: "smile face", **convex** <br/> **Example**: $\pi = f(q) = 11q - 8 - q - q^2, ~ find ~ max:$ 1. write down $f.o.c ~ \Rightarrow ~ f'(q) = 0$ $f'(q) = 11 - 0 - 1 -2q = 10 - 2q$ $~~~~~~~~~and ~ set$ $10 - 2q = 0, ~ \rightarrow ~ q* = 5$ 2. check s.o.c $f''(q) \lt 0$ $f''(q) = - 2 \lt 0$ 3. &there4; $f(q)$ is the maximum when $q = 5$. <br/> **Example**: Max of $ln(15x) - 2x^2$, $\displaystyle derivative \frac {1}{15x} * 15 - 4x = 0$ $\displaystyle \Rightarrow \frac {1}{x} = 4x$ $\displaystyle \Rightarrow x^* =\frac{1}{2}, (the \, critical \, point)$ <br/> ## Function with several variable Utility function > x<sub>1</sub> = Food consumption, x<sub>2</sub> = Transportation, x<sub>3</sub> = Housing , ... , x<sub>n</sub> = leisure > $U =f (x_1 , x_2 , x_3 , \cdots , x_n )$ > and real problem is to solve the max of U. because of Budget constraint ( limited sources and unlimited wants). > set p<sub>1</sub> = price of x<sub>1</sub>, p<sub>2</sub> x<sub>2</sub>, p<sub>3</sub> x<sub>3</sub> ... p<sub>n</sub> = Price Leisure I = income > $I = p_1x_1 + p_2x_2 + p_3x_3 +, \cdots, p_nx_n;$ > $\rightarrow max ~ f(x_1, x_2, x_3, \ldots, x_n)$ <br/> Partial derivatives * $f(x_1, x_2) = ax_1^2 + bx_1x_2 + cx_2^2$ $f'(x_1) = \frac {\partial f}{\partial x_1} = 2ax_1 + bx_2$ $f'(x_2) = \frac {\partial f}{\partial x_2} = bx_1 + 2cx_2$ * $f(x_1, x_2) = e^{ax_1 +bx_2} = g(h(x_1, x_2))$ $g(h) = e^h, ~ h(x_1, x_2) = ax_1 +bx_2$ $f'(x_1) = (\frac{\partial f}{\partial h}) * (\frac{\partial h}{\partial x_1}) = a2^{ax_1+bx_2}$ $f'(x_2) = (\frac{\partial f}{\partial h}) * (\frac{\partial h}{\partial x_2}) = b2^{ax_1+bx_2}$ * $\frac{[\partial(\cfrac{\partial f}{\partial x_1})]}{\partial x_2} = f_{ij}$ <br/> Total Differential * Consider $U=f(x_1,x_2,x_3, \cdots, x_n)$, How much f changes if all variable by a small amount ($dx_1, dx_2, dx_3, \ldots, dx_n$) ? * Set $du = df = (\frac{\partial f}{\partial x_1}) * dx_1 + (\frac{\partial f}{\partial x_2}) * dx_2 + (\frac{\partial f}{\partial x_3}) * dx_3 + \ldots + (\frac{\partial f}{\partial x_n}) * dx_n$ * **First order conditions**, a necessary condition for a maximum (or a minimum ) of the function $f(x_1, x_2, x_3, \ldots, x_n)$, is that $du = 0$, for any combination of small changes in the $x's(dx_1, dx_2, dx_3, \ldots, dx_n)$ the only way for this to be true is if $f_1 = f_2 = f_3 = \ldots = f_n = 0;$ ## Constrained Maximisation, **Lagrangian** * $L(x)$ is the function we want to maximise, $G(x)$ is the conditions * $max = L(x_1, x_2) + \lambda G(x_1, x_2)$ * λ is called a **Lagrangian multiplier**, often called **Lagrangian** * Find the first order conditions of the new objective function L; `assume the answer is max/min, what the question asks for, no need to check second order derivative. ` **Example 1**: $c_1$ = consumption of food, $c_2$ = consumption of other goods; $p_1$ = the price of $c_1$, $p_2$ = the price of $c_2$; $U = f(c_1, c_2) = 2ln(c_1) + (1-\alpha)ln(c_2)$ <br/> **Example 2, Find the max** $\alpha ln(c_1) + (1-\alpha)ln(c_2)$ under condition of $I = p_1c_1 + p_2c_2$ therefore, $I - p_1 * c_1- p_2 * c_2 = 0$ $L = 2ln(c_1) + (1-\alpha)ln(c_2) + \lambda(I - p_1 * c_1 + p_2 * c_2)$; <br/> $\frac{\partial L}{\partial c_1} = \frac {\alpha}{c_1} - \lambda * p_1 = 0$ $\frac{\partial L}{\partial c_2} = \frac {1- \alpha}{c_2} - \lambda * p_2 = 0$ $\frac{\partial L}{\partial \lambda} = I - p_1 * c_1 + p_2 * c_2 = 0$ $\frac {2}{c_1} = \lambda * p_2$ $\frac {1-\alpha}{c_2} = \lambda * p_2$ $I - p_1 * c_1 + p_2 * c_2 = 0$, Divided both side $\frac {c_1}{c_2} = \frac {1-\alpha}{\alpha} * \frac {p_1}{p_2}$; $c_1^{ * } = \alpha \frac {I}{p_1}$ $c_2^{ * } = (1-\alpha) \frac {I}{p_2}$ $\lambda^{ * } = \frac {1}{I}$ if $p_1$ increases, $\alpha \frac {I}{p_1} >0$. <br/> **Example 3, Profit, Cost, and Revenue, Second Order Condition**: > $\displaystyle R = 6x_1 + \frac{99}{4}x_2$ > $\displaystyle C = \frac{x_1x_2}{4} + ln(\frac{1}{x_{1}^{1/8}}) + \frac{x_2^2}{2}$ > $\displaystyle max(x_1, x_2) = R - C$ > $\displaystyle \max_{x_1, x_2} \left.(6x_1 + \frac{99}{4}x_2 - \frac{x_1x_2}{4} + \frac{1}{8}\ln(x_1) - \frac{x_2^2}{2})\right.$ > &rarr; FIRST ORDER > $\displaystyle \frac{\partial \pi}{\partial x_1} = 6 - \frac{x_2}{4} + \frac{1}{8x_1} = 0$ > $\displaystyle \frac{\partial \pi}{\partial x_2} = \frac{99}{4} - \frac{x_1}{4} = x_2$ > &rarr; REPLACE $x_2$ > \[ \begin{align} \displaystyle 6 - \frac{1}{4}(\frac{99}{4} - \frac{x_1}{4}) + \frac{1}{8x_1} & = 0 \\ \frac{1}{16x_1}(x_1^2 - 3x_1 + 2) & = 0 \\ x_1 & = \frac{3 \pm \sqrt{9-8}}{2} \end{align} \] > &rarr;Find the critical points > $\displaystyle x_1 = 2 ~ or ~ x_1 = 1, (x_1, x_2) = (2, \frac{97}{4}) ~ or ~ (1, \frac{49}{2})$ > &rarr;SECOND ORDER FOR MAX > $\displaystyle \frac{\partial^2 F}{\partial x_1^2} \lt 0, \frac{\partial^2 F}{\partial x_2^2} \lt 0$ > $\displaystyle \frac{\partial^2 F}{\partial x_1^2} * \frac{\partial^2 F}{\partial x_2^2} \gt (\frac{\partial^2 F}{\partial x_1 \partial x_2})^2$ > $\displaystyle \frac{\partial^2 \pi}{\partial x_1^2} = -\frac{1}{8x_1^2}$ > $\displaystyle \frac{\partial^2 \pi}{\partial x_2^2} = -\frac{1}{}$ > $\displaystyle \frac{\partial^2 \pi}{\partial x_1 \partial x_2} = -\frac{1}{4}$ > &rarr;FOR $\displaystyle x_1 = 2, x_2 = \frac{97}{4}$ > $\displaystyle \frac{\partial^2\pi}{\partial x_1^2} < 0$ > $\displaystyle \frac{1}{32} < \frac{1}{16}$ > This is not a MAX. > &rarr; FOR $\displaystyle x_1 = 1, x_2 = \frac{49}{2}$ > $\displaystyle \frac{1}{8} \gt \frac{1}{16}$ > This is the only MAX. $\lambda$ - Economic interpretation meaning How much we can increase the objective function $f$ if the constraint is relaxed slightly. * a HIGH value of $\lambda$ indicates that the utility could be increased substantially by relaxing the constraint (poor people ); * a LOW value of $\lambda$ indicates that there is not much to be gained by relaxing the constraint (rich people); * $\lambda = 0$ implies that the constraint is not binding; ## Implicit function theorem: $g(x, y) = 0$, how $x,y$ are related * total differential is $dg = 0$, how much the function changes $$g_y dy + g_x dx = 0;$$ * we solve for $dy$ and divide by $dx$, we get the implicit derivate; $$\rightarrow \frac{dy}{dx} = -\frac{g_x}{g_y}, ~ when ~ g_y ~ is ~ not ~ zero.$$ * conditions are always satisfied in this class. ## The Envelope theorem $$ U = f(c_1, c_2, \alpha) = \alpha ln(c_1) + (1-\alpha)ln(c_2) + \lambda(I - p_1 * c_1+ p_2 * c_2);$$ **Example of consumer problem, Envelope method** To find max of $\displaystyle x_1^{2/5} x_2^{3/5}$, such that > $\displaystyle p_1x_1 + p_2x_2 = I$ > $\displaystyle max(x_1, x_2, \lambda):x_1^{2/5}x_2^{3/5} + \lambda(I - p_1x_1 + p_2x_2);$ > $\displaystyle \frac{2x_2}{3x_1} = \frac{p_1}{p_2} \rightarrow x_2 = \frac{3x_1p_1}{2p_2}$ > &rarr; Replace in constraint: $\displaystyle x_1^* = \frac{2I}{5p_1}, x_2^* = \frac{3I}{5p_2}$ > $\displaystyle \frac{\partial x_1^* }{\partial p_2} = 0$ > &rarr; NO CHANGE WHEN $P_2$ CHANGES > $\displaystyle \frac{\partial x_1^* }{\partial I} = \frac{2}{5p_1} \gt 0$ > $\displaystyle \frac{\partial x_1^* }{\partial p_1} = -\frac{2I}{5p_1^2} \lt 0$ > &rarr; The value of the function: > $\displaystyle V(x_1^* ,x_2^* ) = (\frac{2I}{5p_1})^{\frac{2}{5}} * (\frac{3I}{5p_2})^{\frac{3}{5}}$ > &rarr; Change in well-being when I changes, $\displaystyle \frac{\partial V(x_1^* ,x_2^* )}{\partial I}$ <br/> * The definition of envelope theorem: Derivative of the value of the function = $$\displaystyle \frac{\partial L(x_1^* ,x_2^* , \lambda)}{\partial I} = (chain ~ rule) = \frac{\partial L}{\partial I} + \frac{\partial L}{\partial x_1} * \frac{\partial x_1}{\partial I} + \frac{\partial L}{\partial x_2} * \frac{\partial x_2}{\partial I} + \frac{\partial L}{\partial \lambda} * \frac{\partial \lambda}{\partial I}$$ Then plug in the value of $x_1^* ,x_2^* ~ and ~ \lambda$. * a formula to compute , at the optimum , the derivative of $U$ with respect to parameter in the maximisation problem: $\frac {dU}{d\alpha} = f_{\alpha}$ <br/> ## Homogeneous Functions called Homogeneous of degree K, if $f(tx_1,tx_2,\cdots, tx_n) = t^{k} f(x_1, x_2, \cdots, x_n)$ <br/> ## Euler's Theorem Special relationship between value of function and the partial derivatives of the function.
<?php // Moodle is free software: you can redistribute it and/or modify // (at your option) any later version. // Moodle is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the defined('MOODLE_INTERNAL') || die(); class <API key> { /** * The course context * @var stdClass */ protected $context; /** * The course we are managing enrolments for * @var stdClass */ protected $course = null; /** * Limits the focus of the manager to one enrolment plugin instance * @var string */ protected $instancefilter = null; /** * The total number of users enrolled in the course * Populated by <API key>::get_total_users * @var int */ protected $totalusers = null; /** * An array of users currently enrolled in the course * Populated by <API key>::get_users * @var array */ protected $users = array(); /** * An array of users who have roles within this course but who have not * been enrolled in the course * @var array */ protected $otherusers = array(); /** * The total number of users who hold a role within the course but who * arn't enrolled. * @var int */ protected $totalotherusers = null; /** * The current moodle_page object * @var moodle_page */ protected $moodlepage = null; /**#@+ * These variables are used to cache the information this class uses * please never use these directly instead use their get_ counterparts. * @access private * @var array */ private $_instancessql = null; private $_instances = null; private $_inames = null; private $_plugins = null; private $_roles = null; private $_assignableroles = null; private $<API key> = null; private $_groups = null; /** * Constructs the course enrolment manager * * @param moodle_page $moodlepage * @param stdClass $course * @param string $instancefilter */ public function __construct(moodle_page $moodlepage, $course, $instancefilter = null) { $this->moodlepage = $moodlepage; $this->context = <API key>(CONTEXT_COURSE, $course->id); $this->course = $course; $this->instancefilter = $instancefilter; } /** * Returns the current moodle page * @return moodle_page */ public function get_moodlepage() { return $this->moodlepage; } /** * Returns the total number of enrolled users in the course. * * If a filter was specificed this will be the total number of users enrolled * in this course by means of that instance. * * @global moodle_database $DB * @return int */ public function get_total_users() { global $DB; if ($this->totalusers === null) { list($instancessql, $params, $filter) = $this->get_instance_sql(); $sqltotal = "SELECT COUNT(DISTINCT u.id) FROM {user} u JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql) JOIN {enrol} e ON (e.id = ue.enrolid)"; $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params); } return $this->totalusers; } /** * Returns the total number of enrolled users in the course. * * If a filter was specificed this will be the total number of users enrolled * in this course by means of that instance. * * @global moodle_database $DB * @return int */ public function <API key>() { global $DB; if ($this->totalotherusers === null) { list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx'); $params['courseid'] = $this->course->id; $sql = "SELECT COUNT(DISTINCT u.id) FROM {role_assignments} ra JOIN {user} u ON u.id = ra.userid JOIN {context} ctx ON ra.contextid = ctx.id LEFT JOIN ( SELECT ue.id, ue.userid FROM {user_enrolments} ue LEFT JOIN {enrol} e ON e.id=ue.enrolid WHERE e.courseid = :courseid ) ue ON ue.userid=u.id WHERE ctx.id $ctxcondition AND ue.id IS NULL"; $this->totalotherusers = (int)$DB->count_records_sql($sql, $params); } return $this->totalotherusers; } /** * Gets all of the users enrolled in this course. * * If a filter was specified this will be the users who were enrolled * in this course by means of that instance. * * @global moodle_database $DB * @param string $sort * @param string $direction ASC or DESC * @param int $page First page should be 0 * @param int $perpage Defaults to 25 * @return array */ public function get_users($sort, $direction='ASC', $page=0, $perpage=25) { global $DB; if ($direction !== 'ASC') { $direction = 'DESC'; } $key = md5("$sort-$direction-$page-$perpage"); if (!array_key_exists($key, $this->users)) { list($instancessql, $params, $filter) = $this->get_instance_sql(); $extrafields = <API key>($this->get_context()); $extrafields[] = 'lastaccess'; $ufields = user_picture::fields('u', $extrafields); $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen FROM {user} u JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql) JOIN {enrol} e ON (e.id = ue.enrolid) LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)"; if ($sort === 'firstname') { $sql .= " ORDER BY u.firstname $direction, u.lastname $direction"; } else if ($sort === 'lastname') { $sql .= " ORDER BY u.lastname $direction, u.firstname $direction"; } else if ($sort === 'email') { $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction"; } else if ($sort === 'lastseen') { $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction"; } $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage); } return $this->users[$key]; } /** * Gets and array of other users. * * Other users are users who have been assigned roles or inherited roles * within this course but who have not been enrolled in the course * * @global moodle_database $DB * @param string $sort * @param string $direction * @param int $page * @param int $perpage * @return array */ public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) { global $DB; if ($direction !== 'ASC') { $direction = 'DESC'; } $key = md5("$sort-$direction-$page-$perpage"); if (!array_key_exists($key, $this->otherusers)) { list($ctxcondition, $params) = $DB->get_in_or_equal(get_parent_contexts($this->context, true), SQL_PARAMS_NAMED, 'ctx'); $params['courseid'] = $this->course->id; $params['cid'] = $this->course->id; $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen FROM {role_assignments} ra JOIN {user} u ON u.id = ra.userid JOIN {context} ctx ON ra.contextid = ctx.id LEFT JOIN ( SELECT ue.id, ue.userid, ul.timeaccess AS lastseen FROM {user_enrolments} ue LEFT JOIN {enrol} e ON e.id=ue.enrolid LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid) WHERE e.courseid = :courseid ) ue ON ue.userid=u.id WHERE ctx.id $ctxcondition AND ue.id IS NULL ORDER BY u.$sort $direction, ctx.depth DESC"; $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage); } return $this->otherusers[$key]; } /** * Gets an array of the users that can be enrolled in this course. * * @global moodle_database $DB * @param int $enrolid * @param string $search * @param bool $searchanywhere * @param int $page Defaults to 0 * @param int $perpage Defaults to 25 * @return array Array(totalusers => int, users => array) */ public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25) { global $DB, $CFG; // Add some additional sensible conditions $tests = array("id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1'); $params = array('guestid' => $CFG->siteguest); if (!empty($search)) { $conditions = <API key>($this->get_context()); $conditions[] = $DB->sql_concat('u.firstname', "' '", 'u.lastname'); if ($searchanywhere) { $searchparam = '%' . $search . '%'; } else { $searchparam = $search . '%'; } $i = 0; foreach ($conditions as $key=>$condition) { $conditions[$key] = $DB->sql_like($condition,":con{$i}00", false); $params["con{$i}00"] = $searchparam; $i++; } $tests[] = '(' . implode(' OR ', $conditions) . ')'; } $wherecondition = implode(' AND ', $tests); $extrafields = <API key>($this->get_context(), array('username', 'lastaccess')); $extrafields[] = 'username'; $extrafields[] = 'lastaccess'; $ufields = user_picture::fields('u', $extrafields); $fields = 'SELECT '.$ufields; $countfields = 'SELECT COUNT(1)'; $sql = " FROM {user} u WHERE $wherecondition AND u.id NOT IN (SELECT ue.userid FROM {user_enrolments} ue JOIN {enrol} e ON (e.id = ue.enrolid AND e.id = :enrolid))"; $order = ' ORDER BY u.lastname ASC, u.firstname ASC'; $params['enrolid'] = $enrolid; $totalusers = $DB->count_records_sql($countfields . $sql, $params); $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage); return array('totalusers'=>$totalusers, 'users'=>$availableusers); } /** * Searches other users and returns paginated results * * @global moodle_database $DB * @param string $search * @param bool $searchanywhere * @param int $page Starting at 0 * @param int $perpage * @return array */ public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) { global $DB, $CFG; // Add some additional sensible conditions $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1'); $params = array('guestid'=>$CFG->siteguest); if (!empty($search)) { $conditions = array('u.firstname','u.lastname'); if ($searchanywhere) { $searchparam = '%' . $search . '%'; } else { $searchparam = $search . '%'; } $i = 0; foreach ($conditions as $key=>$condition) { $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false); $params["con{$i}00"] = $searchparam; $i++; } $tests[] = '(' . implode(' OR ', $conditions) . ')'; } $wherecondition = implode(' AND ', $tests); $fields = 'SELECT '.user_picture::fields('u', array('username','lastaccess')); $countfields = 'SELECT COUNT(u.id)'; $sql = " FROM {user} u WHERE $wherecondition AND u.id NOT IN ( SELECT u.id FROM {role_assignments} r, {user} u WHERE r.contextid = :contextid AND u.id = r.userid)"; $order = ' ORDER BY lastname ASC, firstname ASC'; $params['contextid'] = $this->context->id; $totalusers = $DB->count_records_sql($countfields . $sql, $params); $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage); return array('totalusers'=>$totalusers, 'users'=>$availableusers); } /** * Gets an array containing some SQL to user for when selecting, params for * that SQL, and the filter that was used in constructing the sql. * * @global moodle_database $DB * @return string */ protected function get_instance_sql() { global $DB; if ($this->_instancessql === null) { $instances = $this-><API key>(); $filter = $this-><API key>(); if ($filter && array_key_exists($filter, $instances)) { $sql = " = :ifilter"; $params = array('ifilter'=>$filter); } else { $filter = 0; if ($instances) { list($sql, $params) = $DB->get_in_or_equal(array_keys($this-><API key>()), SQL_PARAMS_NAMED); } else { // no enabled instances, oops, we should probably say something $sql = "= :never"; $params = array('never'=>-1); } } $this->instancefilter = $filter; $this->_instancessql = array($sql, $params, $filter); } return $this->_instancessql; } /** * Returns all of the enrolment instances for this course. * * @return array */ public function <API key>() { if ($this->_instances === null) { $this->_instances = enrol_get_instances($this->course->id, true); } return $this->_instances; } /** * Returns the names for all of the enrolment instances for this course. * * @return array */ public function <API key>() { if ($this->_inames === null) { $instances = $this-><API key>(); $plugins = $this-><API key>(); foreach ($instances as $key=>$instance) { if (!isset($plugins[$instance->enrol])) { // weird, some broken stuff in plugin unset($instances[$key]); continue; } $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance); } } return $this->_inames; } /** * Gets all of the enrolment plugins that are active for this course. * * @return array */ public function <API key>() { if ($this->_plugins === null) { $this->_plugins = enrol_get_plugins(true); } return $this->_plugins; } /** * Gets all of the roles this course can contain. * * @return array */ public function get_all_roles() { if ($this->_roles === null) { $this->_roles = role_fix_names(get_all_roles(), $this->context); } return $this->_roles; } /** * Gets all of the assignable roles for this course. * * @return array */ public function <API key>($otherusers = false) { if ($this->_assignableroles === null) { $this->_assignableroles = <API key>($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too } if ($otherusers) { if (!is_array($this-><API key>)) { $this-><API key> = array(); list($courseviewroles, $ignored) = <API key>($this->context, 'moodle/course:view'); foreach ($this->_assignableroles as $roleid=>$role) { if (isset($courseviewroles[$roleid])) { $this-><API key>[$roleid] = $role; } } } return $this-><API key>; } else { return $this->_assignableroles; } } /** * Gets all of the groups for this course. * * @return array */ public function get_all_groups() { if ($this->_groups === null) { $this->_groups = <API key>($this->course->id); foreach ($this->_groups as $gid=>$group) { $this->_groups[$gid]->name = format_string($group->name); } } return $this->_groups; } /** * Unenrols a user from the course given the users ue entry * * @global moodle_database $DB * @param stdClass $ue * @return bool */ public function unenrol_user($ue) { global $DB; list ($instance, $plugin) = $this-><API key>($ue); if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) { $plugin->unenrol_user($instance, $ue->userid); return true; } return false; } /** * Given a user enrolment record this method returns the plugin and enrolment * instance that relate to it. * * @param stdClass|int $userenrolment * @return array array($instance, $plugin) */ public function <API key>($userenrolment) { global $DB; if (is_numeric($userenrolment)) { $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment)); } $instances = $this-><API key>(); $plugins = $this-><API key>(); if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) { return array(false, false); } $instance = $instances[$userenrolment->enrolid]; $plugin = $plugins[$instance->enrol]; return array($instance, $plugin); } /** * Removes an assigned role from a user. * * @global moodle_database $DB * @param int $userid * @param int $roleid * @return bool */ public function <API key>($userid, $roleid) { global $DB; require_capability('moodle/role:assign', $this->context); $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST); try { role_unassign($roleid, $user->id, $this->context->id, '', NULL); } catch (Exception $e) { if (defined('AJAX_SCRIPT')) { throw $e; } return false; } return true; } /** * Assigns a role to a user. * * @param int $roleid * @param int $userid * @return int|false */ public function assign_role_to_user($roleid, $userid) { require_capability('moodle/role:assign', $this->context); if (!array_key_exists($roleid, $this-><API key>())) { if (defined('AJAX_SCRIPT')) { throw new moodle_exception('invalidrole'); } return false; } return role_assign($roleid, $userid, $this->context->id, '', NULL); } /** * Adds a user to a group * * @param stdClass $user * @param int $groupid * @return bool */ public function add_user_to_group($user, $groupid) { require_capability('moodle/course:managegroups', $this->context); $group = $this->get_group($groupid); if (!$group) { return false; } return groups_add_member($group->id, $user->id); } /** * Removes a user from a group * * @global moodle_database $DB * @param StdClass $user * @param int $groupid * @return bool */ public function <API key>($user, $groupid) { global $DB; require_capability('moodle/course:managegroups', $this->context); $group = $this->get_group($groupid); if (!$group) { return false; } return <API key>($group, $user); } /** * Gets the requested group * * @param int $groupid * @return stdClass|int */ public function get_group($groupid) { $groups = $this->get_all_groups(); if (!array_key_exists($groupid, $groups)) { return false; } return $groups[$groupid]; } /** * Edits an enrolment * * @param stdClass $userenrolment * @param stdClass $data * @return bool */ public function edit_enrolment($userenrolment, $data) { //Only allow editing if the user has the appropriate capability //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere list($instance, $plugin) = $this-><API key>($userenrolment); if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) { if (!isset($data->status)) { $data->status = $userenrolment->status; } $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend); return true; } return false; } /** * Returns the current enrolment filter that is being applied by this class * @return string */ public function <API key>() { return $this->instancefilter; } /** * Gets the roles assigned to this user that are applicable for this course. * * @param int $userid * @return array */ public function get_user_roles($userid) { $roles = array(); $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC'); foreach ($ras as $ra) { if ($ra->contextid != $this->context->id) { if (!array_key_exists($ra->roleid, $roles)) { $roles[$ra->roleid] = null; } // higher ras, course always takes precedence continue; } if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) { continue; } $roles[$ra->roleid] = ($ra->itemid == 0 and $ra->component === ''); } return $roles; } /** * Gets the enrolments this user has in the course * * @global moodle_database $DB * @param int $userid * @return array */ public function get_user_enrolments($userid) { global $DB; list($instancessql, $params, $filter) = $this->get_instance_sql(); $params['userid'] = $userid; $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params); $instances = $this-><API key>(); $plugins = $this-><API key>(); $inames = $this-><API key>(); foreach ($userenrolments as &$ue) { $ue->enrolmentinstance = $instances[$ue->enrolid]; $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol]; $ue-><API key> = $inames[$ue->enrolmentinstance->id]; } return $userenrolments; } /** * Gets the groups this user belongs to * * @param int $userid * @return array */ public function get_user_groups($userid) { return <API key>($this->course->id, $userid, 0, 'g.id'); } /** * Retursn an array of params that would go into the URL to return to this * exact page. * * @return array */ public function get_url_params() { $args = array( 'id' => $this->course->id ); if (!empty($this->instancefilter)) { $args['ifilter'] = $this->instancefilter; } return $args; } /** * Returns the course this object is managing enrolments for * * @return stdClass */ public function get_course() { return $this->course; } /** * Returns the course context * * @return stdClass */ public function get_context() { return $this->context; } /** * Gets an array of other users in this course ready for display. * * Other users are users who have been assigned or inherited roles within this * course but have not been enrolled. * * @param core_enrol_renderer $renderer * @param moodle_url $pageurl * @param string $sort * @param string $direction ASC | DESC * @param int $page Starting from 0 * @param int $perpage * @return array */ public function <API key>(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) { $userroles = $this->get_other_users($sort, $direction, $page, $perpage); $roles = $this->get_all_roles(); $context = $this->get_context(); $now = time(); $extrafields = <API key>($context); $users = array(); foreach ($userroles as $userrole) { if(($userrole->contextlevel == CONTEXT_COURSECAT OR $userrole->contextlevel == CONTEXT_SYSTEM) AND !has_capability('moodle/site:config', $context)) { continue; // ecastro ULPGC do not show hidden role asssigns } if (!array_key_exists($userrole->id, $users)) { $users[$userrole->id] = $this-><API key>($userrole, $extrafields, $now); } $a = new stdClass; $a->role = $roles[$userrole->roleid]->localname; $changeable = ($userrole->component == ''); if ($userrole->contextid == $this->context->id) { $roletext = get_string('rolefromthiscourse', 'enrol', $a); } else { $changeable = false; switch ($userrole->contextlevel) { case CONTEXT_COURSE : // Meta course $roletext = get_string('rolefrommetacourse', 'enrol', $a); break; case CONTEXT_COURSECAT : $roletext = get_string('rolefromcategory', 'enrol', $a); break; case CONTEXT_SYSTEM: default: $roletext = get_string('rolefromsystem', 'enrol', $a); break; } } $users[$userrole->id]['roles'] = array(); $users[$userrole->id]['roles'][$userrole->roleid] = array( 'text' => $roletext, 'unchangeable' => !$changeable ); } return $users; } /** * Gets an array of users for display, this includes minimal user information * as well as minimal information on the users roles, groups, and enrolments. * * @param core_enrol_renderer $renderer * @param moodle_url $pageurl * @param int $sort * @param string $direction ASC or DESC * @param int $page * @param int $perpage * @return array */ public function <API key>(<API key> $manager, $sort, $direction, $page, $perpage) { $pageurl = $manager->get_moodlepage()->url; $users = $this->get_users($sort, $direction, $page, $perpage); $now = time(); $straddgroup = get_string('addgroup', 'group'); $strunenrol = get_string('unenrol', 'enrol'); $stredit = get_string('edit'); $allroles = $this->get_all_roles(); $assignable = $this-><API key>(); $allgroups = $this->get_all_groups(); $context = $this->get_context(); $canmanagegroups = has_capability('moodle/course:managegroups', $context); $url = new moodle_url($pageurl, $this->get_url_params()); $extrafields = <API key>($context); $userdetails = array(); foreach ($users as $user) { $details = $this-><API key>($user, $extrafields, $now); // Roles $details['roles'] = array(); foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) { $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>(!$rassignable || !isset($assignable[$rid]))); } // Users $usergroups = $this->get_user_groups($user->id); $details['groups'] = array(); foreach($usergroups as $gid=>$unused) { $details['groups'][$gid] = $allgroups[$gid]->name; } // Enrolments $details['enrolments'] = array(); foreach ($this->get_user_enrolments($user->id) as $ue) { if ($ue->timestart and $ue->timeend) { $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend))); $periodoutside = ($ue->timestart && $ue->timeend && $now < $ue->timestart && $now > $ue->timeend); } else if ($ue->timestart) { $period = get_string('periodstart', 'enrol', userdate($ue->timestart)); $periodoutside = ($ue->timestart && $now < $ue->timestart); } else if ($ue->timeend) { $period = get_string('periodend', 'enrol', userdate($ue->timeend)); $periodoutside = ($ue->timeend && $now > $ue->timeend); } else { $period = ''; $periodoutside = false; } $details['enrolments'][$ue->id] = array( 'text' => $ue-><API key>, 'period' => $period, 'dimmed' => ($periodoutside || $ue->status != ENROL_USER_ACTIVE), 'actions' => $ue->enrolmentplugin-><API key>($manager, $ue) ); } $userdetails[$user->id] = $details; } return $userdetails; } /** * Prepare a user record for display * * This function is called by both {@link <API key>} and {@link <API key>} to correctly * prepare user fields for display * * Please note that this function does not check capability for moodle/coures:<API key> * * @param object $user The user record * @param array $extrafields The list of fields as returned from <API key> used to determine which * additional fields may be displayed * @param int $now The time used for lastaccess calculation * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any * additional fields from $extrafields */ private function <API key>($user, $extrafields, $now) { $details = array( 'userid' => $user->id, 'courseid' => $this->get_course()->id, 'picture' => new user_picture($user), 'firstname' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())), 'lastseen' => get_string('never'), ); foreach ($extrafields as $field) { $details[$field] = $user->{$field}; } if ($user->lastaccess) { $details['lastseen'] = format_time($now - $user->lastaccess); } return $details; } public function <API key>() { $plugins = $this-><API key>(); $buttons = array(); foreach ($plugins as $plugin) { $newbutton = $plugin-><API key>($this); if (is_array($newbutton)) { $buttons += $newbutton; } else if ($newbutton instanceof enrol_user_button) { $buttons[] = $newbutton; } } return $buttons; } public function has_instance($enrolpluginname) { // Make sure manual enrolments instance exists foreach ($this-><API key>() as $instance) { if ($instance->enrol == $enrolpluginname) { return true; } } return false; } /** * Returns the enrolment plugin that the course manager was being filtered to. * * If no filter was being applied then this function returns false. * * @return enrol_plugin */ public function <API key>() { $instances = $this-><API key>(); $plugins = $this-><API key>(); if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) { return false; } $instance = $instances[$this->instancefilter]; return $plugins[$instance->enrol]; } /** * Returns and array of users + enrolment details. * * Given an array of user id's this function returns and array of user enrolments for those users * as well as enough user information to display the users name and picture for each enrolment. * * @global moodle_database $DB * @param array $userids * @return array */ public function <API key>(array $userids) { global $DB; $instances = $this-><API key>(); $plugins = $this-><API key>(); if (!empty($this->instancefilter)) { $instancesql = ' = :instanceid'; $instanceparams = array('instanceid' => $this->instancefilter); } else { list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000'); } $userfields = user_picture::fields('u'); list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000'); $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields FROM {user_enrolments} ue LEFT JOIN {user} u ON u.id = ue.userid WHERE ue.enrolid $instancesql AND u.id $idsql ORDER BY u.firstname ASC, u.lastname ASC"; $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams); $users = array(); foreach ($rs as $ue) { $user = user_picture::unalias($ue); $ue->id = $ue->ueid; unset($ue->ueid); if (!array_key_exists($user->id, $users)) { $user->enrolments = array(); $users[$user->id] = $user; } $ue->enrolmentinstance = $instances[$ue->enrolid]; $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol]; $users[$user->id]->enrolments[$ue->id] = $ue; } $rs->close(); return $users; } } class enrol_user_button extends single_button { /** * An array containing JS YUI modules required by this button * @var array */ protected $jsyuimodules = array(); /** * An array containing JS initialisation calls required by this button * @var array */ protected $jsinitcalls = array(); /** * An array strings required by JS for this button * @var array */ protected $jsstrings = array(); /** * Initialises the new enrol_user_button * * @staticvar int $count The number of enrol user buttons already created * @param moodle_url $url * @param string $label The text to display in the button * @param string $method Either post or get */ public function __construct(moodle_url $url, $label, $method = 'post') { static $count = 0; $count ++; parent::__construct($url, $label, $method); $this->class = 'singlebutton enrolusersbutton'; $this->formid = 'enrolusersbutton-'.$count; } /** * Adds a YUI module call that will be added to the page when the button is used. * * @param string|array $modules One or more modules to require * @param string $function The JS function to call * @param array $arguments An array of arguments to pass to the function * @param string $galleryversion The YUI gallery version of any modules required * @param bool $ondomready If true the call is postponed until the DOM is finished loading */ public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = '2010.04.08-12-35', $ondomready = false) { $js = new stdClass; $js->modules = (array)$modules; $js->function = $function; $js->arguments = $arguments; $js->galleryversion = $galleryversion; $js->ondomready = $ondomready; $this->jsyuimodules[] = $js; } /** * Adds a JS initialisation call to the page when the button is used. * * @param string $function The function to call * @param array $extraarguments An array of arguments to pass to the function * @param bool $ondomready If true the call is postponed until the DOM is finished loading * @param array $module A module definition */ public function <API key>($function, array $extraarguments = null, $ondomready = false, array $module = null) { $js = new stdClass; $js->function = $function; $js->extraarguments = $extraarguments; $js->ondomready = $ondomready; $js->module = $module; $this->jsinitcalls[] = $js; } /** * Requires strings for JS that will be loaded when the button is used. * * @param type $identifiers * @param string $component * @param mixed $a */ public function strings_for_js($identifiers, $component = 'moodle', $a = null) { $string = new stdClass; $string->identifiers = (array)$identifiers; $string->component = $component; $string->a = $a; $this->jsstrings[] = $string; } /** * Initialises the JS that is required by this button * * @param moodle_page $page */ public function initialise_js(moodle_page $page) { foreach ($this->jsyuimodules as $js) { $page->requires->yui_module($js->modules, $js->function, $js->arguments, $js->galleryversion, $js->ondomready); } foreach ($this->jsinitcalls as $js) { $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module); } foreach ($this->jsstrings as $string) { $page->requires->strings_for_js($string->identifiers, $string->component, $string->a); } } } class <API key> implements renderable { /** * The icon to display for the action * @var pix_icon */ protected $icon; /** * The title for the action * @var string */ protected $title; /** * The URL to the action * @var moodle_url */ protected $url; /** * An array of HTML attributes * @var array */ protected $attributes = array(); /** * Constructor * @param pix_icon $icon * @param string $title * @param moodle_url $url * @param array $attributes */ public function __construct(pix_icon $icon, $title, $url, array $attributes = null) { $this->icon = $icon; $this->title = $title; $this->url = new moodle_url($url); if (!empty($attributes)) { $this->attributes = $attributes; } $this->attributes['title'] = $title; } /** * Returns the icon for this action * @return pix_icon */ public function get_icon() { return $this->icon; } /** * Returns the title for this action * @return string */ public function get_title() { return $this->title; } /** * Returns the URL for this action * @return moodle_url */ public function get_url() { return $this->url; } /** * Returns the attributes to use for this action * @return array */ public function get_attributes() { return $this->attributes; } } class <API key> extends moodle_exception { /** * Constructor * @param string $errorcode The name of the string from error.php to print * @param string $module name of module * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page. * @param object $a Extra words and phrases that might be required in the error string * @param string $debuginfo optional debugging information */ public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) { parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo); } } abstract class <API key> { /** * The course enrolment manager * @var <API key> */ protected $manager; /** * The enrolment plugin to which this operation belongs * @var enrol_plugin */ protected $plugin; /** * Contructor * @param <API key> $manager * @param stdClass $plugin */ public function __construct(<API key> $manager, enrol_plugin $plugin = null) { $this->manager = $manager; $this->plugin = $plugin; } /** * Returns a moodleform used for this operation, or false if no form is required and the action * should be immediatly processed. * * @param moodle_url|string $defaultaction * @param mixed $defaultcustomdata * @return <API key>|moodleform|false */ public function get_form($defaultaction = null, $defaultcustomdata = null) { return false; } /** * Returns the title to use for this bulk operation * * @return string */ abstract public function get_title(); /** * Returns the identifier for this bulk operation. * This should be the same identifier used by the plugins function when returning * all of its bulk operations. * * @return string */ abstract public function get_identifier(); /** * Processes the bulk operation on the given users * * @param <API key> $manager * @param array $users * @param stdClass $properties */ abstract public function process(<API key> $manager, array $users, stdClass $properties); }
package ucl.silver.d3d.gui; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import ucl.silver.d3d.core.*; public class Panel2D extends JPanel { public Grid grid2D = null; JPanel jPanelTop = new JPanel(); JPanel jPanelLeft = new JPanel(); JPanel jPanelLeft1 = new JPanel(); JPanel jPanelLeft2 = new JPanel(); JPanel jPanelBottom = new JPanel(); JPanel jPanelGrid = new JPanel(); JPanel jPanelSpacer1 = new JPanel(); JPanel jPanelSpacer2 = new JPanel(); JLabel labelDisplay = new JLabel(); JComboBox <String> comboDisplayMode = new JComboBox<String>(); JButton buttonColor = new JButton(); JLabel labelPlane = new JLabel(); JSpinner spinnerPlane = new JSpinner(); JSlider sliderPlane = new JSlider(); JRadioButton radioAxisMode = new JRadioButton(); JButton buttonSwitch = new JButton(); JLabel labelZoom = new JLabel(); JSlider sliderZoom = new JSlider(); JRadioButton cross = new JRadioButton(); JRadioButton voxelGrid = new JRadioButton(); JRadioButton symmetry4 = new JRadioButton(); JTextField xCoord = new JTextField(); JTextField yCoord = new JTextField(); JTextField zCoord = new JTextField(); JTextField vCoord = new JTextField(); JRadioButton coordDim = new JRadioButton(); JRadioButton coordClick = new JRadioButton(); JScrollPane jScrollPaneGrid = new JScrollPane(); private String comboEditString = "Diffusant.0"; // All"; private boolean controlsOff = true; public Panel2D() { try { jbInit(); } catch (Exception ex) { //ex.printStackTrace(); } } final void jbInit() throws Exception { int ydim = 25; jPanelLeft.setMinimumSize(new Dimension(170, 250)); jPanelLeft.setPreferredSize(new Dimension(170, 250)); jPanelLeft1.setBorder(BorderFactory.createEtchedBorder()); jPanelLeft1.setMinimumSize(new Dimension(130, 255)); jPanelLeft1.setPreferredSize(new Dimension(130, 255)); jPanelLeft1.setLayout(new FlowLayout()); jPanelLeft2.setLayout(new FlowLayout()); jPanelLeft2.setBorder(BorderFactory.createEtchedBorder()); jPanelLeft2.setMinimumSize(new Dimension(130, 260)); jPanelLeft2.setPreferredSize(new Dimension(130, 260)); jPanelBottom.setLayout(new FlowLayout(FlowLayout.CENTER)); jPanelSpacer1.setMinimumSize(new Dimension(100, 5)); jPanelSpacer1.setPreferredSize(new Dimension(100, 5)); jPanelSpacer2.setMinimumSize(new Dimension(140, 5)); jPanelSpacer2.setPreferredSize(new Dimension(140, 5)); jPanelGrid.setAlignmentY((float) 0.5); //jPanelGrid.setMinimumSize(new Dimension(100, 100)); //jPanelGrid.setPreferredSize(new Dimension(100, 100)); labelDisplay.setText("DISPLAY"); labelDisplay.setFont(new Font("Arial", Font.BOLD, 12)); labelDisplay.setPreferredSize(new Dimension(100, ydim)); labelDisplay.setMaximumSize(new Dimension(100, ydim)); labelDisplay.<API key>(JLabel.CENTER); comboDisplayMode.setToolTipText("select what to edit"); comboDisplayMode.addItemListener(new <API key>(this)); comboDisplayMode.setPreferredSize(new Dimension(100, ydim)); buttonColor.setToolTipText("set display color"); buttonColor.setPreferredSize(new Dimension(100, ydim)); buttonColor.setText("Color"); buttonColor.addMouseListener(new <API key>(this)); labelPlane.setText("PLANE"); labelPlane.setFont(new Font("Arial", Font.BOLD, 12)); labelPlane.setPreferredSize(new Dimension(100, ydim)); labelPlane.setMaximumSize(new Dimension(100, ydim)); labelPlane.<API key>(JLabel.CENTER); spinnerPlane.setToolTipText("plane number"); spinnerPlane.addChangeListener(new <API key>(this)); spinnerPlane.setPreferredSize(new Dimension(60, ydim)); sliderPlane.setToolTipText("plane number"); sliderPlane.addChangeListener(new <API key>(this)); sliderPlane.setPreferredSize(new Dimension(100, ydim)); radioAxisMode.setToolTipText("xyz plane orientation selector"); radioAxisMode.<API key>(SwingConstants.CENTER); radioAxisMode.setText("xy plane"); radioAxisMode.addActionListener(new <API key>(this)); radioAxisMode.setMaximumSize(new Dimension(100, ydim)); radioAxisMode.setPreferredSize(new Dimension(100, ydim)); buttonSwitch.setToolTipText("rotate/switch axes"); buttonSwitch.setPreferredSize(new Dimension(100, ydim)); buttonSwitch.setText("Rotate"); buttonSwitch.addMouseListener(new <API key>(this)); labelZoom.setText("Zoom"); labelZoom.setPreferredSize(new Dimension(30, ydim)); sliderZoom.setToolTipText("zoom"); sliderZoom.setName("Zoom"); sliderZoom.addChangeListener(new <API key>(this)); sliderZoom.setPreferredSize(new Dimension(70, ydim)); cross.setText("0 cross"); cross.addActionListener(new <API key>(this)); cross.setMaximumSize(new Dimension(100, ydim)); cross.setPreferredSize(new Dimension(100, ydim)); voxelGrid.setText("grid"); voxelGrid.addActionListener(new <API key>(this)); voxelGrid.setMaximumSize(new Dimension(100, ydim)); voxelGrid.setPreferredSize(new Dimension(100, ydim)); symmetry4.setText("4 symmetry"); symmetry4.addActionListener(new <API key>(this)); symmetry4.setMaximumSize(new Dimension(100, ydim)); symmetry4.setPreferredSize(new Dimension(100, ydim)); xCoord.setText(""); xCoord.setPreferredSize(new Dimension(100, ydim)); yCoord.setText(""); yCoord.setPreferredSize(new Dimension(100, ydim)); zCoord.setText(""); zCoord.setPreferredSize(new Dimension(100, ydim)); vCoord.setText(""); vCoord.setPreferredSize(new Dimension(100, ydim)); coordDim.addActionListener(new <API key>(this)); coordDim.setMaximumSize(new Dimension(80, ydim)); coordDim.setPreferredSize(new Dimension(80, ydim)); coordClick.addActionListener(new <API key>(this)); coordClick.setMaximumSize(new Dimension(120, ydim)); coordClick.setPreferredSize(new Dimension(120, ydim)); setLayout(new BorderLayout()); <API key>(new <API key>(this)); jPanelLeft1.add(labelDisplay, null); jPanelLeft1.add(comboDisplayMode, null); jPanelLeft1.add(buttonColor, null); jPanelLeft1.add(cross, null); jPanelLeft1.add(voxelGrid, null); jPanelLeft1.add(symmetry4, null); jPanelLeft1.add(labelZoom, null); jPanelLeft1.add(sliderZoom, null); jPanelLeft2.add(labelPlane, null); jPanelLeft2.add(spinnerPlane, null); jPanelLeft2.add(sliderPlane, null); jPanelLeft2.add(radioAxisMode, null); jPanelLeft2.add(buttonSwitch, null); jPanelLeft.add(jPanelLeft1, null); jPanelLeft.add(jPanelSpacer1, null); jPanelLeft.add(jPanelLeft2, null); jPanelBottom.add(jPanelSpacer2, null); jPanelBottom.add(xCoord, null); jPanelBottom.add(yCoord, null); jPanelBottom.add(zCoord, null); jPanelBottom.add(vCoord, null); jPanelBottom.add(coordDim, null); jPanelBottom.add(coordClick, null); jPanelLeft.setOpaque(true); jPanelLeft.setLayout(new FlowLayout()); grid2D = new Grid(1000, 800, this); jPanelGrid.add(jScrollPaneGrid, null); add(jPanelGrid, BorderLayout.CENTER); add(jPanelTop, BorderLayout.NORTH); add(jPanelLeft, BorderLayout.WEST); add(jPanelBottom, BorderLayout.SOUTH); jScrollPaneGrid.getViewport().add(grid2D); } public void updateControls() { grid2D.adjustGridSize(); cross.setSelected(grid2D.cross); voxelGrid.setSelected(grid2D.voxelGrid); symmetry4.setSelected(grid2D.sym4); displayModeUpdate(); displayModeSet(comboEditString); objectColorUpdate(); zoomSliderUpdate(); gridPlaneUpdate(); axesModeUpdate(); <API key>(); <API key>(); controlsOff = false; } public void displayModeUpdate() { int numDiffusants = Master.project.numDiffusants(); int numSources = Master.project.numSources(); int numDetectors = Master.project.numDetectors(); int items = comboDisplayMode.getItemCount(); controlsOff = true; // turn off because the following changes cause a state change if (items == 0) { comboDisplayMode.addItem("All"); comboDisplayMode.addItem(" comboDisplayMode.addItem("Geometry"); } else if (items > 0) { for (int i = items - 1; i > 2; i comboDisplayMode.removeItemAt(i); } } if (numDiffusants > 0) { comboDisplayMode.addItem(" if (numDiffusants > 1) { comboDisplayMode.addItem("Diffusant.all"); } for (int i = 0; i < numDiffusants; i++) { comboDisplayMode.addItem("Diffusant." + i); } } if (numSources > 0) { comboDisplayMode.addItem(" if (numSources > 1) { comboDisplayMode.addItem("Source.all"); } for (int i = 0; i < numSources; i++) { comboDisplayMode.addItem("Source." + i); } } if (numDetectors > 0) { comboDisplayMode.addItem(" if (numDetectors > 1) { comboDisplayMode.addItem("Detector.all"); } for (int i = 0; i < numDetectors; i++) { comboDisplayMode.addItem("Detector." + i); } } comboDisplayMode.setSelectedItem(comboEditString); controlsOff = false; } public void displayModeSet(String eSelect) { if (controlsOff) { return; } int emode = displayModeGet(eSelect); int anum = displayModeNum(eSelect); if ((emode >= 0) && (emode <= 4)) { comboEditString = eSelect; grid2D.setViewMode(emode); grid2D.setViewArrayNum(anum); } else { comboEditString = "Diffusant.0"; grid2D.setViewMode(1); grid2D.setViewArrayNum(0); } objectColorUpdate(); grid2D.repaint(); } public int displayModeGet(String s) { s = displayModePrefix(s); if (s.compareToIgnoreCase("Geometry") == 0) { return 0; } else if (s.compareToIgnoreCase("Diffusant") == 0) { return 1; } else if (s.compareToIgnoreCase("Source") == 0) { return 2; } else if (s.compareToIgnoreCase("Detector") == 0) { return 3; } else if (s.compareToIgnoreCase("All") == 0) { return 4; } return -1; } public String displayModePrefix(String item) { int i = item.lastIndexOf("."); if (i > 0) { return item.substring(0, i); } else { return item; } } public int displayModeNum(String item) { int i = item.lastIndexOf("."); int j = 0; String n; if ((i > 0) && (i + 1 < item.length())) { n = item.substring(i + 1, item.length()); try { j = Integer.parseInt(n); return j; } catch (<API key> e) { return -1; } } else { return -1; } } public void objectColorUpdate() { String colorStr = grid2D.getCurrentColor(); if (ColorD3D.isColorScale(colorStr)) { buttonColor.setText("Color Scale"); } else { buttonColor.setText("Color"); } if (colorStr == null) { buttonColor.setBackground(Color.white); buttonColor.setEnabled(false); } else { buttonColor.setBackground(ColorD3D.string2color(colorStr)); buttonColor.setEnabled(true); } } public void objectColorSet() { String colorStr = grid2D.getCurrentColor(); if ((colorStr == null) || (colorStr.length() == 0)) { return; // no color to change } colorStr = ColorD3D.promptColorOrScale(colorStr); if ((colorStr == null) || (colorStr.length() == 0)) { return; // cancel } grid2D.setCurrentColor(colorStr); objectColorUpdate(); } public void zoomSliderUpdate() { controlsOff = true; sliderZoom.setMinimum(grid2D.pixelsPerVoxelMin); sliderZoom.setMaximum(grid2D.pixelsPerVoxelMax); sliderZoom.setValue(grid2D.pixelsPerVoxel); controlsOff = false; } public void resetVoxelWidth() { grid2D.initVoxelWidth(-1, -1); zoomSliderUpdate(); grid2D.repaint(); } public void gridPlaneUpdate() { controlsOff = true; spinnerPlane.setValue(grid2D.kVoxel); sliderPlane.setMinimum(0); sliderPlane.setMaximum(grid2D.kVoxels() - 1); sliderPlane.setValue(grid2D.kVoxel); controlsOff = false; } public void gridPlaneSet(int i) { if (controlsOff) { return; } int max = grid2D.kVoxels() - 1; if (i < 0) { i = 0; } if (i > max) { i = max; } spinnerPlane.setValue(i); sliderPlane.setValue(i); grid2D.setGridPlane(i); } public void axesModeUpdate() { String xyz = ""; switch(grid2D.axesMode) { case 0: if (grid2D.ijSwitch) { xyz = "yx"; } else { xyz = "xy"; } labelPlane.setText("z-stack"); break; case 1: if (grid2D.ijSwitch) { xyz = "zy"; } else { xyz = "yz"; } labelPlane.setText("x-stack"); break; case 2: if (grid2D.ijSwitch) { xyz = "xz"; } else { xyz = "zx"; } labelPlane.setText("y-stack"); break; } radioAxisMode.setText(xyz + " plane"); radioAxisMode.setSelected(true); } public void axesModeSet(int m) { if (controlsOff) { return; } switch (m) { case 0: case 1: case 2: break; default: m = 0; } grid2D.setAxesMode(m); axesModeUpdate(); gridPlaneUpdate(); } public void coordinatesSet(String xc, String yc, String zc, String vc) { if (controlsOff) { return; } xCoord.setText(xc); yCoord.setText(yc); zCoord.setText(zc); vCoord.setText(vc); } public void <API key>() { if (grid2D.coordVoxels) { coordDim.setText("voxels"); } else { coordDim.setText(Master.project.spaceUnits); } coordDim.setSelected(true); } public void <API key>() { if (controlsOff) { return; } if (grid2D.coordVoxels) { grid2D.coordVoxels = false; } else { grid2D.coordVoxels = true; } <API key>(); } public void <API key>() { if (grid2D.coordClick) { coordClick.setText("mouse click"); } else { coordClick.setText("mouse move"); } coordClick.setSelected(true); } public void <API key>() { if (controlsOff) { return; } if (grid2D.coordClick) { grid2D.coordClick = false; } else { grid2D.coordClick = true; } <API key>(); } void <API key>(ChangeEvent e) { Integer v = (Integer) spinnerPlane.getValue(); gridPlaneSet(v.intValue()); } void <API key>(ChangeEvent e) { Integer v = (Integer) sliderPlane.getValue(); gridPlaneSet(v.intValue()); } void <API key>(ActionEvent e) { axesModeSet(grid2D.axesMode+1); } void <API key>(MouseEvent e) { grid2D.switchAxesToggle(); axesModeUpdate(); } void <API key>(ItemEvent e) { JComboBox cb = (JComboBox) e.getSource(); String item = (String) cb.getSelectedItem(); displayModeSet(item); } void <API key>(MouseEvent e) { objectColorSet(); } void <API key>(ActionEvent e) { <API key>(); } void <API key>(ActionEvent e) { <API key>(); } void <API key>(ComponentEvent e) { grid2D.revalidate(); jScrollPaneGrid.setPreferredSize(new Dimension(jPanelGrid.getWidth(), jPanelGrid.getHeight())); jScrollPaneGrid.revalidate(); } void <API key>(ChangeEvent e) { Integer v = (Integer) sliderZoom.getValue(); grid2D.setVoxelWidth(v.intValue()); } void crossLinesToggle() { grid2D.setCross(!grid2D.cross); cross.setSelected(grid2D.cross); } void voxelGridToggle() { grid2D.setVoxelGrid(!grid2D.voxelGrid); voxelGrid.setSelected(grid2D.voxelGrid); } void sym4toggle() { grid2D.setSym4(!grid2D.sym4); symmetry4.setSelected(grid2D.sym4); } } class <API key> implements java.awt.event.ItemListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == 2) { adaptee.<API key>(e); } } } class <API key> extends java.awt.event.MouseAdapter { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } @Override public void mouseClicked(MouseEvent e) { adaptee.<API key>(e); } } class <API key> implements javax.swing.event.ChangeListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void stateChanged(ChangeEvent e) { adaptee.<API key>(e); } } class <API key> implements javax.swing.event.ChangeListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void stateChanged(ChangeEvent e) { adaptee.<API key>(e); } } class <API key> implements java.awt.event.ActionListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.<API key>(e); } } class <API key> extends java.awt.event.MouseAdapter { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } @Override public void mouseClicked(MouseEvent e) { adaptee.<API key>(e); } } class <API key> implements javax.swing.event.ChangeListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void stateChanged(ChangeEvent e) { adaptee.<API key>(e); } } class <API key> implements java.awt.event.ActionListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.crossLinesToggle(); } } class <API key> implements java.awt.event.ActionListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.voxelGridToggle(); } } class <API key> implements java.awt.event.ActionListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.sym4toggle(); } } class <API key> implements java.awt.event.ActionListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.<API key>(e); } } class <API key> implements java.awt.event.ActionListener { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } public void actionPerformed(ActionEvent e) { adaptee.<API key>(e); } } class <API key> extends java.awt.event.ComponentAdapter { Panel2D adaptee; <API key>(Panel2D adaptee) { this.adaptee = adaptee; } @Override public void componentResized(ComponentEvent e) { adaptee.<API key>(e); } }
#define MY_DLL_EXPORT #include "<API key>.h" #include "raster_pitremove.h" #include "extentrectangle.h" #include "rasterarray.h" #include "raster_gutpolygon.h" #include "histogramsclass.h" #include <stdio.h> #include "extentrectangle.h" #include "rastermanager.h" #include "raster.h" #include "gdal_priv.h" #include <limits> #include <math.h> #include <string> #include <algorithm> #include <iostream> namespace RasterManager { RM_DLL_API const char * GetLibVersion(){ return RMLIBVERSION; } RM_DLL_API const char * GetMinGDALVersion(){ return MINGDAL; } RM_DLL_API GDALDataset * CreateOutputDS(const char * pOutputRaster, GDALDataType eDataType, bool bHasNoData, double fNoDataValue, int nCols, int nRows, double * newTransform, const char * projectionRef, const char * unit){ RasterMeta pInputMeta(newTransform[3], newTransform[0], nRows, nCols, &newTransform[5], &newTransform[1], &fNoDataValue, NULL, &eDataType, projectionRef, unit); if (bHasNoData){ } return CreateOutputDS(pOutputRaster, &pInputMeta); } RM_DLL_API GDALDataset * CreateOutputDS(QString sOutputRaster, RasterMeta * pTemplateRasterMeta){ const QByteArray qbFileName = sOutputRaster.toLocal8Bit(); return CreateOutputDS(qbFileName.data(), pTemplateRasterMeta); } RM_DLL_API GDALDataset * CreateOutputDS(const char * pOutputRaster, RasterMeta * pTemplateRastermeta){ // Make sure the file doesn't exist. Throws an exception if it does. CheckFile(pOutputRaster, false); /* Create the new dataset. Determine the driver from the output file extension. * Enforce LZW compression for TIFs. The predictor 3 is used for floating point prediction. * Not using this value defaults the LZW to prediction to 1 which causes striping. */ char **papszOptions = NULL; GDALDriver * pDR = NULL; // Always set the driver to the output Raster name (tiff, tif, img) pDR = <API key>()->GetDriverByName(<API key>(pOutputRaster)); if (strcmp( pDR->GetDescription() , "GTiff") == 0){ papszOptions = CSLSetNameValue(papszOptions, "COMPRESS", "LZW"); } else { papszOptions = CSLSetNameValue(papszOptions, "COMPRESS", "PACKBITS"); } GDALDataset * pDSOutput = pDR->Create(pOutputRaster, pTemplateRastermeta->GetCols(), pTemplateRastermeta->GetRows(), 1, *pTemplateRastermeta->GetGDALDataType(), papszOptions); CSLDestroy( papszOptions ); if (pDSOutput == NULL) return NULL; if (pTemplateRastermeta->HasNoDataValue()) { CPLErr er = pDSOutput->GetRasterBand(1)->SetNoDataValue(pTemplateRastermeta->GetNoDataValue()); if (er == CE_Failure || er == CE_Fatal) return NULL; } else{ CPLErr er = pDSOutput->GetRasterBand(1)->SetNoDataValue(0); if (er) { } } double * newTransform = pTemplateRastermeta->GetGeoTransform(); char * projectionRef = pTemplateRastermeta->GetProjectionRef(); // Fill the new raster set with nodatavalue pDSOutput->GetRasterBand(1)->Fill(pTemplateRastermeta->GetNoDataValue()); if (newTransform != NULL) pDSOutput->SetGeoTransform(newTransform); if (projectionRef != NULL) pDSOutput->SetProjection(projectionRef); return pDSOutput; } extern "C" RM_DLL_API int DeleteDataset(const char * pOutputRaster, char * sErr){ InitCInterfaceError(sErr); try { return Raster::Delete(pOutputRaster); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API void RegisterGDAL() { GDALAllRegister();} extern "C" RM_DLL_API void DestroyGDAL() { <API key>();} extern "C" RM_DLL_API int BasicMath(const char * psRaster1, const char * psRaster2, const double dNumericArg, const char * psOperation, const char * psOutput, char * sErr) { InitCInterfaceError(sErr); try { return Raster::RasterMath(psRaster1, psRaster2, &dNumericArg, psOperation, psOutput); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int RasterInvert(const char * psRaster1, const char * psRaster2, double dValue, char * sErr) { InitCInterfaceError(sErr); try { return Raster::InvertRaster( psRaster1, psRaster2, dValue); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int RasterFilter( const char * psOperation, const char * psInputRaster, const char * psOutputRaster, int nWidth, int nHeight, char * sErr) { InitCInterfaceError(sErr); try { return Raster::FilterRaster( psOperation, psInputRaster, psOutputRaster, nWidth, nHeight); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int Uniform(const char * psInputRaster, const char * psOutputRaster, double dValue, char * sErr) { InitCInterfaceError(sErr); try { Raster theRaster(psInputRaster); return theRaster.Uniform(psOutputRaster, dValue); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int <API key>(const char * sCSVSourcePath, const char * psOutput, const char * sRasterTemplate, const char * sXField, const char * sYField, const char * sDataField, char * sErr){ InitCInterfaceError(sErr); try { return RasterManager::Raster::CSVtoRaster(sCSVSourcePath, psOutput, sRasterTemplate, sXField, sYField, sDataField ); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int RasterToCSV(const char * sRasterSourcePath, const char * sOutputCSVPath, char * sErr){ InitCInterfaceError(sErr); try { return RasterManager::Raster::RasterToCSV(sRasterSourcePath, sOutputCSVPath); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int <API key>(const char * psRasterPath, const char * psHistogramPath, int nNumBins, char * sErr) { int eResult = PROCESS_OK; InitCInterfaceError(sErr); try { RasterManager::HistogramsClass theHisto(psRasterPath,nNumBins); theHisto.writeCSV(psHistogramPath); eResult = PROCESS_OK; } catch (<API key> ex) { SetCInterfaceError(ex, sErr); eResult = ex.GetErrorCode(); } return eResult; } extern "C" RM_DLL_API int CalcHistograms(const char * psRasterPath, const char * psHistogramPath, int nNumBins, int nMinimumBin, double fBinSize, double fBinIncrement, char * sErr) { int eResult = PROCESS_OK; InitCInterfaceError(sErr); try { RasterManager::HistogramsClass theHisto(psRasterPath,nNumBins, nMinimumBin, fBinSize, fBinIncrement); theHisto.writeCSV(psHistogramPath); eResult = PROCESS_OK; } catch (<API key> ex) { SetCInterfaceError(ex, sErr); eResult = ex.GetErrorCode(); } return eResult; } extern "C" RM_DLL_API int <API key>(const char * sCSVSourcePath, const char * sOutput, double dTop, double dLeft, int nRows, int nCols, double dCellWidth, double dNoDataVal, const char * sXField, const char * sYField, const char * sDataField, char * sErr){ InitCInterfaceError(sErr); try { return RasterManager::Raster::CSVtoRaster(sCSVSourcePath, sOutput, dTop, dLeft, nRows, nCols, dCellWidth, dNoDataVal, sXField, sYField, sDataField); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int ExtractRasterPoints(const char * sCSVInputSourcePath, const char * <API key>, const char * sCSVOutputPath, const char * sXField, const char * sYField, const char * sNodata, char * sErr) { InitCInterfaceError(sErr); try { return Raster::ExtractPoints( sCSVInputSourcePath, <API key>, sCSVOutputPath, QString(sXField), QString(sYField), QString(sNodata) ); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int RasterNormalize(const char * psRaster1, const char * psRaster2, char * sErr) { InitCInterfaceError(sErr); try { return Raster::NormalizeRaster( psRaster1, psRaster2); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int <API key>(const char * psInput, const char * psOutput, const char * psUnits, char * sErr) { InitCInterfaceError(sErr); try { return Raster::EuclideanDistance( psInput, psOutput, psUnits); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int CreateHillshade(const char * psInputRaster, const char * psOutputHillshade, char * sErr) { InitCInterfaceError(sErr); try { Raster pDemRaster (psInputRaster); return pDemRaster.Hillshade(psOutputHillshade); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int CreateSlope(const char * psInputRaster, const char * psOutputSlope, const char * psSlopeType, char * sErr) { InitCInterfaceError(sErr); try{ Raster pDemRaster (psInputRaster); return pDemRaster.Slope(psOutputSlope, psSlopeType); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int Mask(const char * psInputRaster, const char * psMaskRaster, const char * psOutput, char * sErr) { InitCInterfaceError(sErr); try{ return Raster::RasterMask(psInputRaster, psMaskRaster, psOutput); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int MaskValue(const char * psInputRaster, const char * psOutput, double dMaskValue, char * sErr) { InitCInterfaceError(sErr); try{ return Raster::RasterMaskValue(psInputRaster, psOutput, dMaskValue); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int LinearThreshold(const char * psInputRaster, const char * psOutputRaster, double dLowThresh, double dLowThreshVal, double dHighThresh, double dHighThreshVal, int nKeepNodata, char * sErr){ InitCInterfaceError(sErr); try{ return Raster::LinearThreshold(psInputRaster, psOutputRaster, dLowThresh, dLowThreshVal, dHighThresh, dHighThreshVal, nKeepNodata); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int AreaThreshold(const char * psInputRaster, const char * psOutputRaster, double dAreaThresh, char * sErr){ InitCInterfaceError(sErr); try{ RasterArray raRaster(psInputRaster); return raRaster.AreaThresholdRaster(psOutputRaster, dAreaThresh); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int SmoothEdges(const char * psInputRaster, const char * psOutputRaster, int nCells, char * sErr){ InitCInterfaceError(sErr); try{ RasterArray raRaster(psInputRaster); return raRaster.SmoothEdge(psOutputRaster, nCells); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int SetNull(const char * psInputRaster, const char * psOutputRaster, const char * psOperator, double dThreshVal1, double dThreshVal2, char * sErr){ InitCInterfaceError(sErr); try{ Raster raRaster(psInputRaster); return raRaster.SetNull(psOutputRaster, psOperator, dThreshVal1, dThreshVal2); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int RootSumSquares(const char * psRaster1, const char * psRaster2, const char * psOutput, char * sErr) { InitCInterfaceError(sErr); try{ return Raster::<API key>(psRaster1, psRaster2, psOutput); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int Mosaic(const char * csRasters, const char * psOutput, char * sErr) { InitCInterfaceError(sErr); try{ return Raster::RasterMosaic(csRasters, psOutput); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int Combine(const char * csRasters, const char * psOutput, const char * psMethod, char * sErr) { InitCInterfaceError(sErr); try{ return Raster::CombineRaster(csRasters, psOutput, psMethod); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int vector2raster(const char * sVectorSourcePath, const char * sRasterOutputPath, const char * sRasterTemplate, double dCellWidth, const char * psFieldName, char * sErr) { InitCInterfaceError(sErr); try{ if (dCellWidth) return Raster::VectortoRaster(sVectorSourcePath, sRasterOutputPath, dCellWidth, psFieldName); else return Raster::VectortoRaster(sVectorSourcePath, sRasterOutputPath, sRasterTemplate, psFieldName); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int Fill(const char * sRasterInput, const char * sRasterOutput, char * sErr){ InitCInterfaceError(sErr); try{ // Mincost is the default FillMode nMethod = FILL_MINCOST; RasterPitRemoval rasterPitRemove( sRasterInput, sRasterOutput, nMethod ); return rasterPitRemove.Run(); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int CreateDrain(const char * sRasterInput, const char * sRasterOutput, char * sErr){ InitCInterfaceError(sErr); try{ RasterArray raInpu(sRasterInput); return raInpu.CreateDrain(sRasterOutput); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int AddGut(const char *psShpFile, const char *psInput, const char *tier1, const char *tier2, char * sErr) { InitCInterfaceError(sErr); try{ return Raster2Polygon::AddGut(psShpFile, psInput, tier1, tier2); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int IsConcurrent(const char * csRaster1, const char * csRaster2, char * sErr) { InitCInterfaceError(sErr); try{ RasterManager::RasterMeta rmRaster1(csRaster1); RasterManager::RasterMeta rmRaster2(csRaster2); return rmRaster1.IsConcurrent(&rmRaster2); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int MakeConcurrent(const char * csRasters, const char * csRasterOutputs, char * sErr) { InitCInterfaceError(sErr); try{ return Raster::<API key>(csRasters, csRasterOutputs); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int GetRasterProperties(const char * ppszRaster, double & fCellHeight, double & fCellWidth, double & fLeft, double & fTop, int & nRows, int & nCols, double & fNoData, int & bHasNoData, int & nDataType, char * psUnit, char * psProjection, char * sErr) { InitCInterfaceError(sErr); try{ RasterManager::Raster r(ppszRaster); fCellHeight = r.GetCellHeight(); fCellWidth = r.GetCellWidth(); fLeft = r.GetLeft(); fTop = r.GetTop(); nRows = r.GetRows(); nCols = r.GetCols(); fNoData = r.GetNoDataValue(); bHasNoData = (int) r.HasNoDataValue(); nDataType = (int) *r.GetGDALDataType(); const char * ccProjectionRef = r.GetProjectionRef(); const char * ccUnit = r.GetUnit(); strncpy(psProjection, ccProjectionRef, ERRBUFFERSIZE); strncpy(psUnit, ccUnit, ERRBUFFERSIZE); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } return PROCESS_OK; } extern "C" RM_DLL_API int RasterCompare(const char * ppszRaster1, const char * ppszRaster2, char * sErr){ InitCInterfaceError(sErr); try{ RasterManager::RasterArray rRasterArray1(ppszRaster1); RasterManager::RasterArray rRasterArray2(ppszRaster2); if (rRasterArray1 != rRasterArray2) return RASTER_COMPARISON; } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } return PROCESS_OK; } extern "C" RM_DLL_API void <API key>(const char * ppszRaster) { try{ double fCellWidth = 0; double fCellHeight = 0; double fLeft = 0; double fTop = 0; double fBottom = 0; double fRight = 0; int nRows = 0; int nCols = 0; double fNoData = 0; double dRasterMax = 0; double dRasterMin = 0; int bHasNoData = 0; int divisible = 0; int nDataType; RasterManager::Raster r(ppszRaster); std::string projection = r.GetProjectionRef(); std::string unit = r.GetUnit(); fCellHeight = r.GetCellHeight(); fCellWidth = r.GetCellWidth(); fLeft = r.GetLeft(); fRight = r.GetRight(); fTop = r.GetTop(); fBottom = r.GetBottom(); nRows = r.GetRows(); nCols = r.GetCols(); dRasterMax = r.GetMaximum(); dRasterMin = r.GetMinimum(); divisible = r.IsDivisible(); fNoData = r.GetNoDataValue(); bHasNoData = (int) r.HasNoDataValue(); nDataType = (int) *r.GetGDALDataType(); printLine( QString(" Raster: %1").arg(ppszRaster)); int leftPrec = GetPrecision(fLeft); int rightPrec = GetPrecision(fRight); int bottomPrec = GetPrecision(fBottom); int topPrec = GetPrecision(fTop); int cellWidthPrec = GetPrecision(fCellWidth); printLine( QString(" Left: %1 Right: %2").arg(fLeft, 0, 'f', leftPrec).arg(fRight, 0, 'f', rightPrec)); printLine( QString(" Top: %1 Bottom: %2").arg(fTop, 0, 'f', topPrec).arg(fBottom, 0, 'f', bottomPrec)); printLine( QString(" Rows: %1 Cols: %2").arg(nRows).arg(nCols)); printLine( QString(" ")); printLine( QString(" Cell Width: %1").arg(fCellWidth, 0, 'f', cellWidthPrec)); printLine( QString(" Min: %1 Max: %2").arg(dRasterMin, 0, 'f', 2).arg(dRasterMax, 0, 'f', 2)); if (divisible == 1 ){ printLine( QString(" Divisible: True" ) ); } else { printLine( QString(" Divisible: False" ) ); } std::cout << "\n"; switch (nDataType) { // Note 0 = unknown; case 1: std::cout << "\n Data Type: 1, GDT_Byte, Eight bit unsigned integer"; break; case 2: std::cout << "\n Data Type: 2, GDT_UInt16, Sixteen bit unsigned integer"; break; case 3: std::cout << "\n Data Type: 3, GDT_Int16, Sixteen bit signed integer"; break; case 4: std::cout << "\n Data Type: 4, GDT_UInt32, Thirty two bit unsigned integer"; break; case 5: std::cout << "\n Data Type: 5, GDT_Int32, Thirty two bit signed integer"; break; case 6: std::cout << "\n Data Type: 6, GDT_Float32, Thirty two bit floating point"; break; case 7: std::cout << "\n Data Type: 7, GDT_Float64, Sixty four bit floating point"; break; case 8: std::cout << "\n Data Type: 8, GDT_CInt16, Complex Int16"; break; case 9: std::cout << "\n Data Type: 9, GDT_CInt32, Complex Int32"; break; case 10: std::cout << "\n Data Type: 10, GDT_CFloat32, Complex Float32"; break; case 11: std::cout << "\n Data Type: 11, GDT_CFloat64, Complex Float64"; break; default: std::cout << "\n Data Type: Unknown"; break; } if (bHasNoData) std::cout << "\n No Data: " << fNoData; else std::cout << "\n No Data: none"; std::cout << "\n Projection: " << projection.substr(0,70) << "..."; std::cout << "\n Unit: " << unit; std::cout << "\n "; } catch (<API key> e){ //e.GetErrorCode(); } } extern "C" RM_DLL_API int RasterGetStat(const char * psOperation, double * pdValue, const char * psInputRaster, char * sErr){ InitCInterfaceError(sErr); try { RasterManager::Raster rRaster(psInputRaster); int eResult = rRaster.RasterStat( (<API key>) GetStatFromString(psOperation), pdValue); return eResult; } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } /******************************************************************************************************* * Raster copy and resample methods */ extern "C" RM_DLL_API int Copy(const char * ppszOriginalRaster, const char *ppszOutputRaster, double fNewCellSize, double fLeft, double fTop, int nRows, int nCols, char * sErr) { InitCInterfaceError(sErr); try{ RasterManager::Raster ra(ppszOriginalRaster); return ra.Copy(ppszOutputRaster, &fNewCellSize, fLeft, fTop, nRows, nCols, NULL, NULL); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int ExtendedCopy(const char * ppszOriginalRaster, const char *ppszOutputRaster, double fLeft, double fTop, int nRows, int nCols, const char * psRef, const char * psUnit, char * sErr) { InitCInterfaceError(sErr); try{ RasterManager::Raster ra(ppszOriginalRaster); double fNewCellSize = ra.GetCellWidth(); return ra.Copy(ppszOutputRaster, &fNewCellSize, fLeft, fTop, nRows, nCols, psRef, psUnit); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int <API key>(const char * psDS1, const char * psDS2, int & result, char * sErr) { InitCInterfaceError(sErr); try{ OGRSpatialReference ref1 = RasterManager::Raster::getDSRef(psDS1); OGRSpatialReference ref2 = RasterManager::Raster::getDSRef(psDS2); result = int (ref1.IsSame(&ref2)); return PROCESS_OK; } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API int BiLinearResample(const char * ppszOriginalRaster, const char *ppszOutputRaster, double fNewCellSize, double fLeft, double fTop, int nRows, int nCols, char * sErr) { InitCInterfaceError(sErr); try{ RasterManager::Raster ra(ppszOriginalRaster); return ra.ReSample(ppszOutputRaster, fNewCellSize, fLeft, fTop, nRows, nCols); } catch (<API key> e){ SetCInterfaceError(e, sErr); return e.GetErrorCode(); } } extern "C" RM_DLL_API const char * ExtractFileExt(const char * FileName) { for (int i = strlen(FileName); i >= 0; i if (FileName[i] == '.' ){ return &FileName[i]; } } return NULL; } extern "C" RM_DLL_API const char * <API key>(const char * FileName) { const char * pSuffix = ExtractFileExt(FileName); if (pSuffix == NULL) return NULL; else { if (strcmp(pSuffix, ".tif") == 0) { return "GTiff"; } else if (strcmp(pSuffix, ".img") == 0) return "HFA"; else return NULL; } } extern "C" RM_DLL_API const char * <API key>(const char * psFileName) { if (EndsWith(psFileName, ".tif")) { return "GTiff"; } else if (EndsWith(psFileName, ".img")) { return "HFA"; } else throw std::runtime_error("Unhandled raster format without a GDAL driver specification."); } bool EndsWith(const char * psFullString, const char * psEnding) { std::string sFullString(psFullString); std::string sEnding(psEnding); // Ensure both strings are lower case std::transform(sFullString.begin(), sFullString.end(), sFullString.begin(), ::tolower); std::transform(sEnding.begin(), sEnding.end(), sEnding.begin(), ::tolower); if (sFullString.length() >= sEnding.length()) { return (0 == sFullString.compare (sFullString.length() - sEnding.length(), sEnding.length(), sEnding)); } else { return false; } } extern "C" RM_DLL_API int <API key>(const char * psStyle) { QString sStyle(psStyle); if (QString::compare(sStyle , "DEM", Qt::CaseInsensitive) == 0) return GSS_DEM; else if (QString::compare(sStyle , "DoD", Qt::CaseInsensitive) == 0) return GSS_DoD; else if (QString::compare(sStyle , "Error", Qt::CaseInsensitive) == 0) return GSS_Error; else if (QString::compare(sStyle , "HillShade", Qt::CaseInsensitive) == 0) return GSS_Hlsd; else if (QString::compare(sStyle , "PointDensity", Qt::CaseInsensitive) == 0) return GSS_PtDens; else if (QString::compare(sStyle , "SlopeDeg", Qt::CaseInsensitive) == 0) return GSS_SlopeDeg; else if (QString::compare(sStyle , "SlopePC", Qt::CaseInsensitive) == 0) return GSS_SlopePer; else return -1; } extern "C" RM_DLL_API int <API key>(const char * psStats) { QString sStyle(psStats); if (QString::compare(sStyle , "mean", Qt::CaseInsensitive) == 0) return STATS_MEAN; else if (QString::compare(sStyle , "majority", Qt::CaseInsensitive) == 0) return STATS_MEDIAN; else if (QString::compare(sStyle , "maximum", Qt::CaseInsensitive) == 0) return STATS_MAJORITY; else if (QString::compare(sStyle , "median", Qt::CaseInsensitive) == 0) return STATS_MINORITY; else if (QString::compare(sStyle , "minimum", Qt::CaseInsensitive) == 0) return STATS_MAXIMUM; else if (QString::compare(sStyle , "minority", Qt::CaseInsensitive) == 0) return STATS_MINIMUM; else if (QString::compare(sStyle , "range", Qt::CaseInsensitive) == 0) return STATS_STD; else if (QString::compare(sStyle , "std", Qt::CaseInsensitive) == 0) return STATS_SUM; else if (QString::compare(sStyle , "sum", Qt::CaseInsensitive) == 0) return STATS_VARIETY; else if (QString::compare(sStyle , "variety", Qt::CaseInsensitive) == 0) return STATS_RANGE; else return -1; } extern "C" RM_DLL_API int <API key>(const char * psMethod) { QString sMethod(psMethod); if (QString::compare(sMethod , "mincost", Qt::CaseInsensitive) == 0) return FILL_MINCOST; else if (QString::compare(sMethod , "bal", Qt::CaseInsensitive) == 0) return FILL_BAL; else if (QString::compare(sMethod , "cut", Qt::CaseInsensitive) == 0) return FILL_CUT; else return -1; } extern "C" RM_DLL_API int GetMathOpFromString(const char * psOp) { QString sOp(psOp); if (QString::compare(sOp , "add", Qt::CaseInsensitive) == 0) return RM_BASIC_MATH_ADD; else if (QString::compare(sOp , "subtract", Qt::CaseInsensitive) == 0) return <API key>; else if (QString::compare(sOp , "multiply", Qt::CaseInsensitive) == 0) return <API key>; else if (QString::compare(sOp , "divide", Qt::CaseInsensitive) == 0) return <API key>; else if (QString::compare(sOp , "sqrt", Qt::CaseInsensitive) == 0) return RM_BASIC_MATH_SQRT; else if (QString::compare(sOp , "power", Qt::CaseInsensitive) == 0) return RM_BASIC_MATH_POWER; else if (QString::compare(sOp , "std", Qt::CaseInsensitive) == 0) return STATS_STD; else if (QString::compare(sOp, "threshproperr", Qt::CaseInsensitive) == 0) return <API key>; else return -1; } extern "C" RM_DLL_API int GetStatFromString(const char * psStat) { QString sMethod(psStat); if (QString::compare(sMethod , "mean", Qt::CaseInsensitive) == 0) return STATS_MEAN; else if (QString::compare(sMethod , "median", Qt::CaseInsensitive) == 0) return STATS_MEDIAN; else if (QString::compare(sMethod , "majority", Qt::CaseInsensitive) == 0) return STATS_MAJORITY; else if (QString::compare(sMethod , "minority", Qt::CaseInsensitive) == 0) return STATS_MINORITY; else if (QString::compare(sMethod , "maximum", Qt::CaseInsensitive) == 0) return STATS_MAXIMUM; else if (QString::compare(sMethod , "minimum", Qt::CaseInsensitive) == 0) return STATS_MINIMUM; else if (QString::compare(sMethod , "std", Qt::CaseInsensitive) == 0) return STATS_STD; else if (QString::compare(sMethod , "sum", Qt::CaseInsensitive) == 0) return STATS_SUM; else if (QString::compare(sMethod , "variety", Qt::CaseInsensitive) == 0) return STATS_VARIETY; else if (QString::compare(sMethod , "range", Qt::CaseInsensitive) == 0) return STATS_RANGE; else return -1; } extern "C" RM_DLL_API void <API key>(unsigned int eErrorCode, char * sErr) { const char * pRMErr = <API key>::<API key>(eErrorCode); strncpy(sErr, pRMErr, ERRBUFFERSIZE); sErr[ ERRBUFFERSIZE - 1 ] = 0; } void RM_DLL_API printLine(QString theString) { std::string sString = theString.toStdString(); std::cout << "\n" << sString; } RM_DLL_API void InitCInterfaceError(char * sErr){ strncpy(sErr, "\0", ERRBUFFERSIZE);; // Set the string to NULL. } RM_DLL_API void SetCInterfaceError(<API key> e, char * sErr){ QString qsErr = e.<API key>(); const QByteArray qbErr = qsErr.toLocal8Bit(); strncpy(sErr, qbErr.data(), ERRBUFFERSIZE); sErr[ ERRBUFFERSIZE - 1 ] = 0; } } // namespace
module Shared::OutlaysHelper def <API key>(response, klass, length = 60) list = response.projects.sort_by{ |p| p.name }.collect do |u| [ truncate(u.name, :length => length), u.id ] end list = list.insert(0,["<Automatically create a project for me>", -1]) list = list.insert(1,["<No project>", nil]) if klass == "OtherCost" [['Select a project...', '']] + list end end
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Order</title> </head> <body> </body> </html>
// <auto-generated> // This code was generated by a tool. // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> namespace Abide.HaloLibrary.Halo2.Retail.Tag.Generated { using System; using Abide.HaloLibrary; using Abide.HaloLibrary.Halo2.Retail.Tag; <summary> Represents the generated <API key> tag block. </summary> public sealed class <API key> : Block { <summary> Initializes a new instance of the <see cref="<API key>"/> class. </summary> public <API key>() { this.Fields.Add(new RealField("weight")); this.Fields.Add(new RealRgbColorField("color lower bound")); this.Fields.Add(new RealRgbColorField("color upper bound")); this.Fields.Add(new StringIdField("variant name#if empty, may be used by any model variant")); } <summary> Gets and returns the name of the <API key> tag block. </summary> public override string BlockName { get { return "<API key>"; } } <summary> Gets and returns the display name of the <API key> tag block. </summary> public override string DisplayName { get { return "<API key>"; } } <summary> Gets and returns the maximum number of elements allowed of the <API key> tag block. </summary> public override int MaximumElementCount { get { return 32; } } <summary> Gets and returns the alignment of the <API key> tag block. </summary> public override int Alignment { get { return 4; } } } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Sun Nov 02 19:47:31 CST 2014 --> <title>Condition</title> <meta name="date" content="2014-11-02"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Condition"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Condition.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/numenta/nupic/util/ArrayUtilsTest.html" title="class in org.numenta.nupic.util"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/numenta/nupic/util/Condition.Adapter.html" title="class in org.numenta.nupic.util"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/numenta/nupic/util/Condition.html" target="_top">Frames</a></li> <li><a href="Condition.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#<API key>">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">org.numenta.nupic.util</div> <h2 title="Interface Condition" class="title">Interface Condition&lt;T&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../org/numenta/nupic/util/Condition.Adapter.html" title="class in org.numenta.nupic.util">Condition.Adapter</a></dd> </dl> <hr> <br> <pre>public interface <span class="strong">Condition&lt;T&gt;</span></pre> <div class="block">Implemented to be used as arguments in other operations. see <a href="../../../../org/numenta/nupic/util/ArrayUtils.html#retainLogicalAnd(int[], org.numenta.nupic.util.Condition[])"><code>ArrayUtils.retainLogicalAnd(int[], Condition[])</code></a>; <a href="../../../../org/numenta/nupic/util/ArrayUtils.html#retainLogicalAnd(double[], org.numenta.nupic.util.Condition[])"><code>ArrayUtils.retainLogicalAnd(double[], Condition[])</code></a>.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="<API key>"> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Interface and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../org/numenta/nupic/util/Condition.Adapter.html" title="class in org.numenta.nupic.util">Condition.Adapter</a>&lt;<a href="../../../../org/numenta/nupic/util/Condition.Adapter.html" title="type parameter in Condition.Adapter">T</a>&gt;</strong></code> <div class="block">Convenience adapter to remove verbosity</div> </td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/numenta/nupic/util/Condition.html#eval(double)">eval</a></strong>(double&nbsp;d)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/numenta/nupic/util/Condition.html#eval(int)">eval</a></strong>(int&nbsp;n)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../org/numenta/nupic/util/Condition.html#eval(T)">eval</a></strong>(<a href="../../../../org/numenta/nupic/util/Condition.html" title="type parameter in Condition">T</a>&nbsp;t)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="eval(int)"> </a> <ul class="blockList"> <li class="blockList"> <h4>eval</h4> <pre>boolean&nbsp;eval(int&nbsp;n)</pre> </li> </ul> <a name="eval(double)"> </a> <ul class="blockList"> <li class="blockList"> <h4>eval</h4> <pre>boolean&nbsp;eval(double&nbsp;d)</pre> </li> </ul> <a name="eval(java.lang.Object)"> </a><a name="eval(T)"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>eval</h4> <pre>boolean&nbsp;eval(<a href="../../../../org/numenta/nupic/util/Condition.html" title="type parameter in Condition">T</a>&nbsp;t)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Condition.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/numenta/nupic/util/ArrayUtilsTest.html" title="class in org.numenta.nupic.util"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../org/numenta/nupic/util/Condition.Adapter.html" title="class in org.numenta.nupic.util"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/numenta/nupic/util/Condition.html" target="_top">Frames</a></li> <li><a href="Condition.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#<API key>">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
import { ClarioGridsService } from './../../_services/clario-grids.service'; import { Location } from '@angular/common'; import { MatDialogRef } from '@angular/material'; import { Feature } from './../../feature'; import { Component, OnInit, AfterContentChecked } from '@angular/core'; @Component({ selector: '<API key>', templateUrl: './quantity-options.component.html', styleUrls: ['../../options/options.component.css', './quantity-options.component.css'] }) export class <API key> implements OnInit, AfterContentChecked { title = 'Order By Quantity'; constructor( public feature: Feature, public dialogRef: MatDialogRef<<API key>>, public location: Location, public clarioGrids: ClarioGridsService ) {} ngOnInit() {} <API key>() { const featureType = this.<API key>(this.feature.feature_type); this.title = featureType !== 'hush' ? `${featureType} Tiles By Quantity` : `${featureType} Blocks By Quantity`; } gridSizeChanged(selection) { this.clarioGrids.gridSizeSelected(selection); } tileSizeChanged(selection) { this.clarioGrids.tileSizeSelected(selection); this.clarioGrids.<API key>(); } goToLanding() { this.dialogRef.close('cancel'); this.feature.navToLanding(); } validateOptions() { let valid = !!this.feature.design_name; if (this.feature.feature_type === 'clario') { valid = valid && !!this.feature.grid_type && !!this.clarioGrids.selectedTileSize; } return valid; } <API key>(string) { return string.charAt(0).toUpperCase() + string.slice(1); } }
import sys import re import numpy as np import pandas as pd import librosa import argparse argparser = argparse.ArgumentParser(''' Utility for computing sound power metrics from the Natural Stories audio stimuli ''') argparser.add_argument('files', nargs='+', help='Paths to audio files for processing') argparser.add_argument('-I', '--interval', type=float, default=None, help='Interval step at which to extract sound power measures (used for deconvolving sound power using DTSR). If unspecified, extract at each word onset. If speficied, power measures are rescaled by interval value to ensure valid convolution.') argparser.add_argument('-c', '--convolve', action='store_true', help='Generate an additional column for sound power convolved with the canonical HRF') args = argparser.parse_args() DEBUG = False if DEBUG: from matplotlib import pyplot as plt name = re.compile('^.*/?([^ /])+\.wav *$') ix2name = ['Boar', 'Aqua', 'MatchstickSeller', 'KingOfBirds', 'Elvis', 'MrSticky', 'HighSchool', 'Roswell', 'Tulips', 'Tourettes'] df = pd.read_csv(sys.stdin, sep=' ', skipinitialspace=True) ix2docid = df.docid.unique() docid2ix = {} for i in range(len(ix2docid)): docid2ix[ix2docid[i]] = i if args.interval: keys = [] for x in ['subject', 'docid', 'fROI']: if x in df.columns: keys.append(x) power = {} max_len = 0 for i in range(len(args.files)): path = args.files[i] n = ix2name[int(name.match(path).group(1)) - 1] sys.stderr.write('\rProcessing audio file "%s" (%d/%d) ' %(n, i + 1, len(args.files))) y, sr = librosa.load(path) # Newer versions of librosa (e.g., 0.7.1) use "rms" rather than "rmse" if hasattr(librosa.feature, 'rms'): rmse = librosa.feature.rms(y, hop_length=50) else: rmse = librosa.feature.rmse(y, hop_length=50) rmse = rmse[0] power[n] = rmse max_len = max(max_len, len(rmse)) if DEBUG: wav, = plt.plot(y[:500000]) power, = plt.plot(np.arange(0, 500000, 50), rmse[0,:10000]) # plt.legend([wav, power], ['WAV form', 'Sound power']) # plt.show(block=False) # raw_input() # plt.clf() sys.stderr.write('\n') if args.interval: df = df[keys].drop_duplicates() intervals = [] for docid in ix2name: ix = (np.arange(len(power[docid])) / (441. * args.interval)).astype(int) splits = np.where(ix[1:] != ix[:-1])[0] + 1 time = splits.astype(float) / 441. chunks = np.array([x.mean() for x in np.split(power[docid], splits)][1:]) intervals_cur = pd.DataFrame({'time': time, 'soundPower%sms' % int(args.interval * 1000): chunks}) intervals_cur['docid'] = docid intervals.append(intervals_cur) intervals = pd.concat(intervals, axis=0) df = df.merge(intervals, on='docid', how='left') power_ix = (df.time * 441).astype('int') # At a sampling rate of 22050 Hz, there are 441 rmse measurements within a 1 second sampling window power_ix = np.array(power_ix) docid = df.docid docid_ix = df.docid.map(docid2ix) if args.convolve: # HRF convolved sound power from mvpa2.misc.data_generators import double_gamma_hrf as hrf power_padded = [] tau_padded = [] for docid in ix2docid: power_padded_cur = np.zeros(max_len) tau_padded_cur = np.zeros(max_len) if docid in power: power_padded_cur[-len(power[docid]):] = power[docid] tau_padded_cur[-len(power[docid]):] = np.arange(len(power[docid]), dtype='float') / 441. power_padded.append(power_padded_cur) tau_padded.append(tau_padded_cur) power_padded = np.stack(power_padded, axis=0) tau_padded = np.stack(tau_padded, axis=0) step = 5000 t = np.array(df.time)[..., None] sys.stderr.write('Convolving sound power with canonical HRF...\n') soundPowerHRF = [] for i in range(0, len(t), step): sys.stderr.write('\rRows completed: %d/%d' %(i, len(t))) sys.stderr.flush() doc_ix_cur = docid_ix[i:i+step] soundPowerHRF_cur = np.zeros((doc_ix_cur.shape[0],)) impulse = power_padded[doc_ix_cur] tau = tau_padded[doc_ix_cur] t_cur = t[i:i+step] valid = np.where(tau.sum(axis=1) > 0) impulse = impulse[valid] tau = tau[valid] t_cur = t_cur[valid] soundPowerHRF_cur[valid] = np.nan_to_num(impulse * hrf(t_cur - tau)).sum(axis=1) / 441. soundPowerHRF.append(soundPowerHRF_cur) soundPowerHRF = np.concatenate(soundPowerHRF, axis=0) sys.stderr.write('\n') df['soundPowerHRF'] = soundPowerHRF df.to_csv(sys.stdout, sep=' ', na_rep='NaN', index=False)
<html xmlns="http: <head> <title>Release Notes: SeaDAS 7.3</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link rel="stylesheet" href="../style.css"> </head> <body> <table class="header" width="100%"> <tr class="header"> <td class="header">&nbsp; SeaDAS 7.3 Release Notes </td> <td class="header" align="right"><a href="../visat/index.html"><img src="../images/SeaDASHeader.png" border=0></a></td> </tr> </table> <p> <b>Release Date: </b> Dec 23, 2015<br><br> </p> The SeaDAS development team is pleased to announce the release of SeaDAS 7.3, which is built atop a slightly modified BEAM 5.0.1 version.<br><br> The science processing code has been updated to reflect changes recently implemented in production, provide bug fixes and support for the R2014.0 reprocessing for SeaWiFS. <br> <hr> <p class="sectionTitle">GUI Interface</p> <p class="subSectionTitle">Features/ Modifications</p> <pre> GPT operator added - Write Image Operator. This command line operator enables the export of images. It includes parameters for including gridlines, contour lines, color bar, and text annotation on the image. Bowtie correction for VIIRS has been improved to better handle the aggregation zones. Color Palettes - Universal palette (color blind compliant) added along with associated color scheme default configurations. - Chlorophyll Blue-Green palette and scheme added. - Palette export now sorts entries in the exported text file. - User can now remove the default color palettes. RGB Profile - User can now edit any of the rgb profile text files. - Added 2 new generic rgb profiles (linear and log). Land Mask & Coastline Tool - Defaults changed * Super sampling default set to 3 - takes longer to run but is a much more accurate reprojection of the land data into the image view. * Coastline mask color set to black. * Land mask color set to dark grey. Icons Added - Reprojection Tool. - RGB Tool. - Import Field Measurements (SeaBASS format). Icons Modified - Filtered Band Tool. - Window synchronization (Navigation Controls). - Cursor synchronization (Navigation Controls). Folder renamed - Renamed "Bands (Products)" folder to "Rasters". Rationale: a more simple, generic name - this folder contains raster data which may include but is not limited to: oceancolor data products, latitude and longitude data, flagcodings, rgb virtual bands, and any number of user created virtual and real bands. </pre> <p class="subSectionTitle">Bug Fixes</p> <pre> Version 7.3 fixes the following bugs: - incorrect geolocation for MODIS 250 and 500m resolution data. - geometries could not be exported from a loaded smi image. - sessions could not be saved and reloaded if colorbar layer present. - no-data layer sometimes toggled to top of the layer stack. </pre> <br> <hr> <p class="sectionTitle">Science Processing Code</p> <p class="subSectionTitle">Features/ Modifications</p> <pre> l2gen: - modified BRDF function to allow LUT files to be netCDF format. - added a user-contributed chlorophyll algorithm, (ABI: chl_abi; Shanmugam, 2011). - added support for NASA-formatted VIIRS L1 products. - added new flag for VIIRS bow-tie deleted pixels. - added support for SST products for VIIRS. - added new triple-window SST algorithm for VIIRS. - modified Landsat OLI reader to use reflectance scaling rather than radiance scaling. - generalized NDVI algorithm. - added "slot" product for GOCI. l1info: - additional output added (e.g. Orbit_Number). l3mapgen: - redesigned to improve speed. - added RGB support. - added support for outputting: variance, standard deviation, number of observations, number of scenes, observation time and bin number. - added ability to output more than one product per file (netCDF). - added the ability to output 2 files of different formats. - added ability to use SMI file as input. multilevel processor: - added capability to process tarred VIIRS SVM files. - made modification that allow processing to continue when a corrupt data file is encountered. - fixed several bugs. </pre> <p class="subSectionTitle">Bug Fixes (Science Processing Code)</p> <pre> l2gen: - fixed issues with primary productivity algorithms (opp_XXX) - fixed bug in Es output l3bindump: - fixed bug that affected full globe output l3mapgen: - fixed reporting of latitudes in netCDF output </pre> <br> <hr> <p class="sectionTitle">Useful Notes</p> <p class="h3better">Help Pages</p> <p> Some of the help pages internal to SeaDAS 7.3 have not been revised to match the current version so there can be some wording discrepancies as well as feature description differences. However, we regularly produce video help tutorials <b>(https://seadas.gsfc.nasa.gov/tutorial)</b>. We feel this to be the best, most functional way to enable the user of SeaDAS to get the most out of the software. In additional we regularly respond to SeaDAS issues on the our user forum <b>(https://oceancolor.gsfc.nasa.gov/forum/oceancolor/forum_show.pl).</b> Questions posted on the forum help aid us in determining aspects of SeaDAS which may benefit by refinement, as well as give us ideas for topics to be used in future tutorial videos. Also note that these internal help pages are alos made available at <b>(https://seadas.gsfc.nasa.gov/help/)</b> </p> <p class="h3better">Notes on Upgrading your SeaDAS version</p> <p> <b> If you already have SeaDAS version 7 or higher installed:</b><br> In your home directory there is a directory titled '.seadas'. This contains version-specific preferences and defaults. This directory also contains any custom color palettes and rgb-profiles which you may have created. Because of this, a seadas installation will automically move and rename the previous '.seadas' directory putting it in your home directory. When seadas is launched and does not find this '.seadas' directory, it will automically create this directory and initialize it with the package settings and defaults. You can then manually copy any of your custom color palettes and rgb-profiles from the backed up copy of your previous version's '.seadas' directory over into the '.seadas' directory. </p> </body> </html>
<?php /** * The template for image attachments * * @subpackage Travel Planet * @since Travel Planet 1.2 */ get_header(); ?> <div id="container" class="alignleft" role="main"> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'trvlplnt-posts round shadow' ); ?>> <header> <h2 class="wrap capitalize"><?php the_title() ?></h2> <p class="postmetadata"> <?php $metadata = <API key>(); _e( 'Posted on', 'travel-planet' ); ?> <span> <time datetime="<?php echo get_the_date(); ?>"> <a href="<?php echo esc_url( get_month_link( get_the_time( 'Y' ), get_the_time( 'm' ) ) ); ?>" title="<?php echo get_the_date(); ?>"><?php echo get_the_date(); ?></a> </time> </span> <?php _e( 'at', 'travel-planet' ); ?> <a href="<?php echo esc_url( <API key>() ); ?>" title="<?php _e( 'Link to full-size image', 'travel-planet' ); ?>"> <?php echo $metadata['width']; ?> &times; <?php echo $metadata['height']; ?> </a> <?php _e( 'in', 'travel-planet' ); ?> <a href="<?php echo esc_url( get_permalink( $post->post_parent ) ); ?>" title="<?php _e( 'Return to', 'travel-planet' ); echo '&nbsp' . esc_attr( strip_tags( get_the_title( $post->post_parent ) ) ); ?>" rel="gallery"> <?php echo get_the_title( $post->post_parent ) . '.'; ?> </a> </p> </header> <div class="trvlplnt-text"> <div class="entry-attachment"> <div class="attachment center"> <?php /** * Grab the IDs of all the image attachments in a gallery so we can get the URL of the next adjacent image in a gallery, * or the first image (if we're looking at the last image in a gallery), or, in a gallery of one, just the link to that image file */ $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID', ) ) ); foreach ( $attachments as $m => $attachment ) : if ( $attachment->ID == $post->ID ) { break; } endforeach; $m ++; // If there is more than 1 attachment in a gallery if ( count( $attachments ) > 1 ) : if ( isset( $attachments[ $m ] ) ) : // get the URL of the next image attachment $next_attachment_url = get_attachment_link( $attachments[ $m ]->ID ); else : // or get the URL of the first image attachment $next_attachment_url = get_attachment_link( $attachments[0]->ID ); endif; else : // or, if there's only 1 image, get the URL of the image $next_attachment_url = <API key>(); endif; ?> <a href="<?php echo esc_url( $next_attachment_url ); ?>" title="<?php the_title_attribute(); ?>" rel="attachment"> <?php /** * Filter the image attachment size to use. * * @param array $size { * * @type int The attachment height in pixels. * @type int The attachment width in pixels. * } */ $attachment_size = apply_filters( '<API key>', array( 540, 400, true ) ); echo <API key>( $post->ID, $attachment_size ); ?> </a> <?php if ( ! empty( $post->post_excerpt ) ) : ?> <div class="wp-caption-text"> <?php the_excerpt(); ?> </div> <?php endif; ?> </div><!-- .attachment --> </div><!-- .entry-attachment --> <nav id="<API key>" class=".<API key>" role="navigation"> <span class="<API key> wrap"><?php previous_image_link( false, '&lsaquo;&lsaquo;&nbsp;' . __( 'Previous', 'travel-planet' ) ); ?></span> <span class="trvlplnt-nav-next wrap"><?php next_image_link( false, __( 'Next', 'travel-planet' ) . '&nbsp;&rsaquo;&rsaquo;' ); ?></span> </nav> <!-- #<API key> --> <div class="entry-description"> <?php the_content(); edit_post_link( __( 'Edit', 'travel-planet' ), '<p>', '</p>' ); ?> </div><!-- .entry-description --> </div><!-- .trvlplnt-text --> </article><!-- #post --> <?php comments_template(); endwhile; // end of the loop. ?> </div><!-- #container --> <?php get_sidebar(); get_footer();
// Project ProjectForge Community Edition // This community edition is free software; you can redistribute it and/or // This community edition is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General package org.projectforge.plugins.eed; import org.apache.wicket.Page; import org.projectforge.business.fibu.EmployeeDao; import org.projectforge.business.user.UserRightId; import org.projectforge.business.user.UserRightValue; import org.projectforge.continuousdb.UpdateEntry; import org.projectforge.framework.persistence.database.DatabaseService; import org.projectforge.menu.builder.MenuItemDef; import org.projectforge.menu.builder.MenuItemDefId; import org.projectforge.plugins.core.AbstractPlugin; import org.projectforge.plugins.eed.wicket.*; import org.projectforge.web.plugin.<API key>; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static org.projectforge.framework.persistence.api.UserRightService.READONLY_READWRITE; /** * @author Florian Blumenstein */ public class <API key> extends AbstractPlugin { public static final String ID = "extendemployeedata"; public static final String <API key> = "<API key>"; // The order of the entities is important for xml dump and imports as well as for test cases (order for deleting objects at the end of // each test). // The entities are inserted in ascending order and deleted in descending order. private static final Class<?>[] PERSISTENT_ENTITIES = new Class<?>[]{}; @Autowired private <API key> <API key>; @Autowired private EmployeeDao employeeDao; @Autowired private DatabaseService databaseService; public <API key>() { super("extendemployeedata", "ExtendEmployeeData", "PlugIn for extended employee data"); } /** * @see org.projectforge.plugins.core.AbstractPlugin#initialize() */ @Override protected void initialize() { <API key>.databaseService = databaseService; // Register it: register(EmployeeDao.class, employeeDao, "plugins.extendemployeedata"); // Register the web part: <API key>.registerWeb(ID); // Register the menu entry as sub menu entry of the misc menu: register("eed_listcare", "plugins.eed.menu.listcare", <API key>.class, UserRightId.HR_EMPLOYEE, READONLY_READWRITE); register("eed_listcareimport", "plugins.eed.menu.listcareimport", <API key>.class, UserRightId.HR_EMPLOYEE, READONLY_READWRITE); register("eed_export", "plugins.eed.menu.export", ExportDataPage.class, UserRightId.HR_EMPLOYEE_SALARY, READONLY_READWRITE); register("eed_import", "plugins.eed.menu.import", <API key>.class, UserRightId.HR_EMPLOYEE_SALARY, UserRightValue.READWRITE); register("eed_config", "plugins.eed.menu.config", <API key>.class, UserRightId.HR_EMPLOYEE_SALARY, READONLY_READWRITE); // Define the access management: registerRight(new <API key>(accessChecker)); // All the i18n stuff: addResourceBundle(<API key>); } private void register(String menuId, String i18nKey, Class<? extends Page> pageClass, UserRightId userRightId, UserRightValue... userRightValues) { MenuItemDef menuEntry = MenuItemDef.create(menuId, i18nKey); menuEntry.<API key>(userRightId); menuEntry.<API key>(userRightValues); <API key>.registerMenuItem(MenuItemDefId.HR, menuEntry, pageClass); } /** * @see org.projectforge.plugins.core.AbstractPlugin#<API key>() */ @Override public UpdateEntry <API key>() { return <API key>.<API key>(); } /** * @see org.projectforge.plugins.core.AbstractPlugin#getUpdateEntries() */ @Override public List<UpdateEntry> getUpdateEntries() { return <API key>.getUpdateEntries(); } }
package com.bookstore.BL; import com.bookstore.model.Item; import com.bookstore.utility.<API key>; import java.io.Serializable; import java.util.List; import javax.ejb.Remote; /** * ItemBean interface for CRUD access for item. * @author kazim and bipin */ @Remote public interface ItemBeanRemote extends Serializable{ /** * create Item for user. * @param item */ public void create(Item item); /** * get item for ItemId. * @param id. * @return item. */ public Item getItem(String id); /** * get item list for user. * @param username. * @return list of item for user. */ public List<Item> getList(String username); /** * delete item. * @param itemId */ public void delete(String itemId); /** * Retrieve a list of all Items. * @return the list of all items */ public List<Item> getAllList(); /** * Updates the item currently based on version property. * @param item * @return the updated item. * @throws <API key> if the item has been concurrently updated. */ public Item updateItem(Item item) throws <API key>; }
<?php /** * Base class for buildings and technologies */ abstract class <API key> extends <API key> { private $maximumLevel = -1; private $minimumLevel = 0; private $level = null; private $effects = array(); public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); return $this->getBaseIronCosts() * $level; } public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); return $this-><API key>() * $level; } public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); return $this->getBaseEnergyCosts() * $level; } public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); return $this->getBasePeopleCosts() * $level; } public function getTimeCosts($level = null) { if ($level === null) $level = $this->getLevel(); $costs = round($this->getBaseTimeCosts() * $level / <API key>); if ($costs < 1) $costs = 1; return $costs; } /** * @return int amount of ressources repayed when removing this item */ public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); $divider = 2; if (Rakuun_User_Manager::isSitting()) $divider *= <API key>::<API key>; return round($this-><API key>($level) / $divider); } /** * @return int amount of ressources repayed when removing this item */ public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); $divider = 2; if (Rakuun_User_Manager::isSitting()) $divider *= <API key>::<API key>; return round($this-><API key>($level) / $divider); } /** * @return int amount of ressources repayed when removing this item */ public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); $divider = 2; if (Rakuun_User_Manager::isSitting()) $divider *= <API key>::<API key>; return round($this-><API key>($level) / $divider); } /** * @return int amount of ressources repayed when removing this item */ public function <API key>($level = null) { if ($level === null) $level = $this->getLevel(); $divider = 2; if (Rakuun_User_Manager::isSitting()) $divider *= <API key>::<API key>; return round($this-><API key>($level) / $divider); } /** * @return true if all prerequisites needed to produce this item are met */ public function canBuild() { return (!$this->reachedMaximumLevel() && $this->gotEnoughRessources() && $this-><API key>()); } public function <API key>() { return $this->getLevel() + $this->getFutureLevels() + 1; } public function reachedMaximumLevel() { $nextBuildableLevel = $this-><API key>(); return ($nextBuildableLevel > $this->getMaximumLevel() && $this->getMaximumLevel() > 0); } public function gotEnoughRessources() { $nextBuildableLevel = $this-><API key>(); $ressources = $this->getUser()->ressources; return ($this-><API key>($nextBuildableLevel) <= $ressources->iron && $this-><API key>($nextBuildableLevel) <= $ressources->beryllium && $this-><API key>($nextBuildableLevel) <= $ressources->energy && $this-><API key>($nextBuildableLevel) <= $ressources->people); } public function getLevel() { if ($this->level === null) { $dataSource = $this->getDataSource(); return $dataSource->{Text::<API key>($this->getInternalName())}; } else { return $this->level; } } public function setLevel($level) { $this->level = $level; } /** * Returns the amount of levels that are currently being build. */ public abstract function getFutureLevels(); /** * Implement this function to define effects for this item. */ protected function defineEffects() { } /** * Returns the maximum buildable level. */ public function getMaximumLevel() { return $this->maximumLevel; } public function setMaximumLevel($maximumLevel) { $this->maximumLevel = $maximumLevel; } /** * Returns the minimum level this item can reach. */ public function getMinimumLevel() { return $this->minimumLevel; } public function setMinimumLevel($minimumLevel) { $this->minimumLevel = $minimumLevel; } public function getEffects() { if (!$this->effects) $this->defineEffects(); return $this->effects; } /** * Adds an effect. This is just a text string that is being displayed in this * items' description. E.g.: "Raises amount of storable iron by 5000" */ public function addEffect($effect) { $this->effects[] = $effect; } } ?>
// This program is free software: you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #pragma once #include <stddef.h> #include <vector> #include <memory> #include <thread> #include <mutex> #include <condition_variable> #include "r_defs.h" #include "d_player.h" extern cycle_t FrameCycles; namespace swrenderer { extern cycle_t WallCycles, PlaneCycles, MaskedCycles, DrawerWaitCycles; class RenderThread; class RenderScene { public: RenderScene(); ~RenderScene(); void Deinit(); void SetClearColor(int color); void RenderView(player_t *player, DCanvas *target, void *videobuffer, int bufferpitch); void RenderViewToCanvas(AActor *actor, DCanvas *canvas, int x, int y, int width, int height, bool dontmaplines = false); bool DontMapLines() const { return dontmaplines; } RenderThread *MainThread() { return Threads.front().get(); } private: void RenderActorView(AActor *actor,bool renderplayersprite, bool dontmaplines); void RenderThreadSlices(); void RenderThreadSlice(RenderThread *thread); void RenderPSprites(); void StartThreads(size_t numThreads); void StopThreads(); bool dontmaplines = false; int clearcolor = 0; std::vector<std::unique_ptr<RenderThread>> Threads; std::mutex start_mutex; std::condition_variable start_condition; bool shutdown_flag = false; int run_id = 0; std::mutex end_mutex; std::condition_variable end_condition; size_t finished_threads = 0; }; }
//jshint esnext:true angular.module('debitos'). factory('debitosService', function($q) { return { getDebitos: function() { return $q(function(resolve, reject) { var lista = []; var sql = 'SELECT nombre,apellido,direccion,cuil,iddonante, ' + ' debito.id as iddebito,cbu,activo,entidad,fvenc,falta,monto ' + ' FROM debito INNER JOIN donante ON iddonante=donante.id ' + ' WHERE activo=1'; Database.db.all( sql, function (err, rows) { if (err) {console.log("Error en obtener los debitos"); reject(err);} resolve(rows); } ); }); }, getDebito: function(id) { return $q(function(resolve, reject) { var sql = 'SELECT nombre,apellido,direccion,cuil,iddonante ' + ',debito.id as iddebito,cbu,activo,entidad,fvenc,falta,monto ' + ' FROM debito INNER JOIN donante ON iddonante=donante.id ' + ` WHERE activo=1 AND debito.id=${id} `; Database.db.get(sql, function (err, row) { if (err) {console.log("Error en obtener los debitos"); reject(err);} resolve(row); } ); }); }, create: function(path) { Database.create('app/BaseDebitos.db'); }, addDebito: function (debito) { return $q(function(resolve, reject) { var sql = " INSERT INTO donante (nombre, apellido, cuil, direccion) " + ` VALUES ("${debito.nombre}", "${debito.apellido}", "${debito.cuil}", "${debito.direccion}") `; Database.db.run(sql, [], function(error) { if (error) { reject(error); return; } else { var sql = " INSERT INTO debito (cbu, activo, iddonante, entidad, fvenc, falta, monto) " + ` VALUES ("${debito.cbu}", 1, ${this.lastID}, "${debito.entidad}", ` + ` ${debito.fvenc.valueOf()}, ${debito.falta.valueOf()}, ${debito.monto}) `; Database.db.run(sql, [], function(error) { if (error) { reject(error); return; } else { resolve(this.lastID); } }); } }); }); }, updateDebito: function(debito) { return $q(function(resolve, reject) { var sql = " UPDATE donante SET " + ` nombre="${debito.nombre}", apellido="${debito.apellido}", ` + ` cuil="${debito.cuil}", direccion="${debito.direccion}" ` + ` WHERE id=${debito.iddonante}`; Database.db.run(sql, [], function(error) { if (error) { reject(error); return; } else { var sql = " UPDATE debito SET " + ` cbu="${debito.cbu}", entidad="${debito.entidad}", ` + ` fvenc=${debito.fvenc.valueOf()}, falta=${debito.falta.valueOf()}, monto=${debito.monto} ` + ` WHERE id=${debito.iddebito}`; console.log(sql); Database.db.run(sql, [], function(error) { if (error) { reject(error); return; } else { resolve(this.lastID); } }); } }); }); }, deleteDebito: function (id) { return $q(function(resolve, reject) { var sql = `UPDATE debito SET activo=0 WHERE id=${id}`; Database.db.run(sql, [], function(error) { if (error) { reject(error); return; } resolve(this.lastID); }); }); }, importDB: function (src) { return $q(function(resolve, reject) { FileAPI.import(src, 'app/BaseDebitos.db') .then(function() { resolve(); }) .catch(function() { reject(); }); }); }, exportarArchivo: function (entidad) { var self = this; return $q(function(resolve,reject) { self.getDebitos() .then(function(listadebitos) { var inicial = "D"+entidad.cuit.replace(/-/g,"")+" "+" ".repeat(10-(entidad.prestacion.length))+entidad.prestacion, importeTotalBPN = 0, importeTotalOtros = 0, cantRegBPN = 0, cantRegOtros = 0, fechaProceso = moment(new Date(entidad.fecha)), nombreArchivo = 'app/resources/tmp/' + 'ORI' + fechaProceso.format('DDMMYYYY'), fecha = moment(new Date(entidad.vencimiento)), fechaVto= fecha.format('DDMMYYYY'); //Se crean los dos archivos FileAPI.create(nombreArchivo + '1'); //Archivo BPN FileAPI.create(nombreArchivo + '2'); //Archivo Otras entidades for(var i=0,l;i< listadebitos.length;i++) { console.log(listadebitos[i]); var cbubloque1 = listadebitos[i].cbu.substring(0,8), cbubloque2 = listadebitos[i].cbu.substring(8,22), doc = listadebitos[i].cuil.replace(/-/g,""), idCliente = " ".repeat(22-(doc.length)) + doc, idDebito = listadebitos[i].iddebito.toString(), refdebito = " ".repeat(15-(idDebito.length)) + idDebito, importe = parseFloat(listadebitos[i].monto).toFixed(2), importeStr = ((importe.toString().replace(".",'')).replace(",",'')), importeDebito = ("0".repeat(10-(importeStr.length))) + importeStr, campo13 = "80", campo19 = " ", campoFinal = " ".repeat(22) + campo19 + "0".repeat(10) + "0".repeat(10) + " ".repeat(54); var linea = inicial + fechaVto + cbubloque1 + "000" + cbubloque2 + idCliente + fechaVto + refdebito + importeDebito + campo13 + fechaVto + importeDebito + fechaVto + importeDebito + campoFinal + "\n"; if (listadebitos[i].cbu.substring(0,3) == "097") { //Se trata de un debito del BPN console.log(listadebitos[i].cbu.substring(0,3)); cantRegBPN= cantRegBPN + 1; importeTotalBPN = importeTotalBPN + importe; FileAPI.append(nombreArchivo + '1', linea); } else { cantRegOtros = cantRegOtros +1; importeTotalOtros = importeTotalOtros + importe; FileAPI.append(nombreArchivo + '2', linea); } } var trailer = "", cantRegStr = "", totalImporteStr; if (cantRegBPN>0){ //Se escribe el trailer para el archivo BPN cantRegStr = parseInt(cantRegBPN).toString(); totalImporteStr = parseFloat(importeTotalBPN).toFixed(2); totalImporteStr = ((totalImporteStr.toString().replace(".",'')).replace(",",'')); trailer = "T" + (("0".repeat(10-(cantRegStr.length))) + cantRegStr) + (("0".repeat(7-(cantRegStr.length))) + cantRegStr) + "0".repeat(7) + fechaProceso.format('DDMMYYYY') + " ".repeat(70) + (("0".repeat(10-(totalImporteStr.length))) + totalImporteStr) + " ".repeat(137) + "\n"; FileAPI.append(nombreArchivo + '1', trailer); } if (cantRegOtros>0){ //Se escribe el trailer para el archivo de otra entidad cantRegStr = parseInt(cantRegOtros).toString(); totalImporteStr = parseFloat(importeTotalOtros).toFixed(2); totalImporteStr = ((totalImporteStr.toString().replace(".",'')).replace(",",'')); trailer = "T" + (("0".repeat(10-(cantRegStr.length))) + cantRegStr) + (("0".repeat(7-(cantRegStr.length))) + cantRegStr) + "0".repeat(7) + fechaProceso.format('DDMMYYYY') + " ".repeat(70) + (("0".repeat(10-(totalImporteStr.length))) + totalImporteStr) + " ".repeat(137) + "\n" ; FileAPI.append(nombreArchivo + '2', trailer); } resolve(); }) .catch(function(error) { reject(error); }); }); } }; });
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. __docformat__ = "reStructuredText" import zope.interface import zope.schema import zope.testing.doctest class IRegister(zope.interface.Interface): """Trivial sample registry.""" id = zope.schema.Id( title=u"Identifier", description=u"Some identifier that can be checked.", required=True, ) registry = [] def register(context, id): context.action(discriminator=('Register', id), callable=registry.append, args=(id,) ) def test_suite(): return zope.testing.doctest.DocTestSuite()
package ru.net.serbis.dbmanager.result; import android.content.*; import android.util.*; import android.view.*; import android.widget.*; import java.util.*; import ru.net.serbis.dbmanager.*; import ru.net.serbis.dbmanager.util.*; public class Row extends LinearLayout { public static final int MARGIN = 2; public static final int PADDING = 5; private static final int SHIFT = 100; private List<String> cells; private Width width; private int color = R.color.row; private int colorFirstCell = R.color.rowFirstCell; private int colorOtherCell = R.color.rowOtherCell; private int colorSelected = R.color.rowSelected; private boolean columnsInit = false; public Row(Context context) { super(context); init(context); } public Row(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public Row(Context context, AttributeSet attrs, int style) { super(context, attrs, style); init(context); } public void setCells(List<String> cells) { this.cells = cells; } public List<String> getCells() { return cells; } public List<String> getEditCells() { return getEditCells(cells); } public static List<String> getEditCells(List<String> cells) { return new ArrayList<String>(cells.subList(1, cells.size())); } public void setWidth(Width width) { this.width = width; } private void init(Context context) { setOrientation(LinearLayout.HORIZONTAL); } public void setColors(int color, int colorFirstCell, int colorOtherCell) { this.color = color; this.colorFirstCell = colorFirstCell; this.colorOtherCell = colorOtherCell; } public void update() { update(false); } public void update(boolean selected) { if (!columnsInit) { createContent(); columnsInit = true; } updateWidth(cells); updateBackground(selected); setWidths(); } public void updateWidth(List<String> cells) { int i = 0; int[] widths = width.getNewWidths(); for (String cell : cells) { widths[i] = getTextWidth(cell) + MARGIN + PADDING + PADDING; i ++; } width.setWidths(widths); } private void setWidths() { int i = 0; for (String cell : cells) { TextView text = Utils.findView(this, i + SHIFT); text.setText(cell); setWidth(text, width.getWidth(i), MARGIN, PADDING); i ++; } } private void createContent() { <API key>(color); for (int i = 0; i < cells.size(); i ++) { TextView text = new TextView(getContext()); if (i == 0) { setBackground(text, i, false); } text.setId(i + SHIFT); addView(text); } } public void setWidth(View view, int width) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.width = width; view.setLayoutParams(params); } public void setWidth(View view, int width, int margin, int padding) { LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); params.width = width; params.setMargins(0, 0, margin, 0); view.setPadding(padding, 0, padding, 0); view.setLayoutParams(params); } private int getTextWidth(String text) { TextView view = new TextView(getContext()); view.setText(text); view.measure(0, 0); return view.getMeasuredWidth(); } public void updateBackground(boolean selected) { for (int i = 1; i < cells.size(); i++) { TextView text = Utils.findView(this, i + SHIFT); setBackground(text, i, selected); } } private void setBackground(TextView view, int column, boolean selected) { view.<API key>( column == 0 ? colorFirstCell : (selected ? colorSelected : colorOtherCell)); } }
<?php if(!empty($_SESSION['login'])){ $klantId = $_SESSION['login'][0]; $klantNaam = $_SESSION['login'][1]; $klantRolId = $_SESSION['login'][2]; function isKlant($klantRolId){ if($klantRolId === 1 || $klantRolId === 5){ return true; }else{ return false; } } function isGeblokkeerd($klantRolId){ if($klantRolId === 5){ return true; }else{ return false; } } if(isKlant($klantRolId)){ $stmt = DB::conn()->prepare("SELECT id, naam, adres, postcode, woonplaats, telefoonnummer, email FROM `Persoon` WHERE id=?"); $stmt->bind_param('i', $klantId); $stmt->execute(); $stmt->bind_result($id, $naam, $adres, $postcode, $woonplaats, $telefoonnummer, $email); $stmt->fetch(); $stmt->close(); if(!empty($_GET['action'])){ $code = $_GET['code']; $action = $_GET['action']; $edit = true; }else{ $edit = false; } ?> <div class="panel panel-default"> <div class="panel-body"> <div class="btn-group admin"> <a href="/klant/overzicht" class="btn btn-primary admin_menu klant_menu actief">OVERZICHT</a> <a href="/klant/klacht_indienen" class="btn btn-primary admin_menu klant_menu">KLACHT INDIENEN</a> </div> <?php if(isGeblokkeerd($klantRolId)){ echo "<div class='blocked'><b>UW ACCOUNT IS GEBLOKKEERD</b></div>"; } ?> <h1>OVERZICHT</h1> <?php if(!empty($_GET)){ if($_GET['action'] == 'ok_verleng'){ ?> <div class='succes'><b>UW ORDER IS MET SUCCES VERLENGD MET <?php echo $_POST['aantalDagen']; if($_POST['aantalDagen'] == 1){ echo ' DAG'; }else{ echo ' DAGEN'; } ?> </b> <div class="terug_order"> <a href="/klant/overzicht"><button class="btn bestel">TERUG NAAR UW OVERZICHT</button></a> </div> </div> <?php } } ?> <h3><b><?php echo $naam ?></b></h3> <hr></hr> <div class="left"> <?php if(!empty($_GET)){ if($edit == true && $code == $id && $action == 'edit'){ ?> <h4><b>INFORMATIE</b></h4> <div class="info"> <form method="post" action=?action=save&code=<?php echo $id ?>> <h5>ALGEMENE INFORMATIE</h5> <ul class="list-group"> <li class="list-group-item"><b>Klantnummer: </b><?php echo $id ?></li> <li class="list-group-item"><b>Naam: </b><input type="text" class="form-control" name="naam" value="<?php echo $naam ?>" required></li> </ul> <h5>CONTACT INFORMATIE</h5> <ul class="list-group"> <li class="list-group-item"><b>Email: </b><input type="email" class="form-control" name="email" value="<?php echo $email ?>" required></li> <li class="list-group-item"><b>Telefoonnummer: </b><input type="text" class="form-control" name="telefoonnummer" value="<?php echo $telefoonnummer ?>" required></li> </ul> <h5>ADRES INFORMATIE</h5> <ul class="list-group"> <li class="list-group-item"><b>Adres: </b><input type="text" class="form-control" name="adres" value="<?php echo $adres ?>" required></li> <li class="list-group-item"><b>Postcode: </b><input type="text" class="form-control" name="postcode" value="<?php echo $postcode ?>" required></li> <li class="list-group-item"><b>Woonplaats: </b><input type="text" class="form-control" name="woonplaats" value="<?php echo $woonplaats ?>" required></li> </ul> <form method="post" action="?action=edit&code=<?php echo $id ?>"> <button type="submit" class="btn btn-success bestel"><li class="fa fa-floppy-o"></li> OPSLAAN</button> </form> </div> <?php }elseif($action == 'save'){ $stmt = DB::conn()->prepare("UPDATE `Persoon` SET `naam`=?, `email`=?, `telefoonnummer`=?, `adres`=?, `postcode`=?, `woonplaats`=? WHERE id=?"); $stmt->bind_param("ssssssi", $_POST['naam'], $_POST['email'], $_POST['telefoonnummer'], $_POST['adres'], $_POST['postcode'], $_POST['woonplaats'], $code); $stmt->execute(); $stmt->close(); header("Refresh:0; url=/klant/overzicht"); }elseif($action == 'verleng'){ ?> <h3>VERLENG HUUR VAN ORDER #<?php echo $code ?></h3> <?php $stmt = DB::conn()->prepare("SELECT ophaaldatum, ophaaltijd FROM `Order` WHERE id=?"); $stmt->bind_param('i', $code); $stmt->execute(); $stmt->bind_result($ophaalD, $ophaalT); $stmt->fetch(); $stmt->close(); ?> <hr></hr> <h4>ORIGINELE OPHAAL DATA</h4> <h4><b>OPHAALDATUM:</b> <?php echo $ophaalD ?></h4> <h4><b>OPHAALTIJD:</b> <?php echo $ophaalT ?></h4> <hr></hr> <h4>NIEUWE OPHAAL DATA</h4> <h4><b>OPHAALDATUM:</b></h4> <form method="post" action="?action=ophaalTijd"> <select class="form-control" name="ophaalDatum"> <?php $ophaalDatum = date($ophaalD); $ophaalDatum = date('d-m-Y', strtotime($ophaalDatum."+1 day")); for($x=0; $x <= 6; $x++){ $date = date('d-m-Y', strtotime($ophaalDatum.'+'.$x. 'days')); ?> <option value="<?php echo $date ?>"><?php echo $date ?></option> <?php } ?> </select> <input type="submit" class="btn btn-success bestel verlengbtn" value="SELECTEER NIEUWE OPHAALTIJD"> <input type="hidden" name="id" value="<?php echo $code ?>"> </form> <?php }elseif($action == 'ophaalTijd'){ $order_id = $_POST['id']; $ophaalDatum = $_POST['ophaalDatum']; ?> <h3>VERLENG HUUR VAN ORDER #<?php echo $order_id ?></h3> <hr></hr> <?php $stmt = DB::conn()->prepare("SELECT ophaaldatum, ophaaltijd FROM `Order` WHERE id=?"); $stmt->bind_param('i', $order_id); $stmt->execute(); $stmt->bind_result($ophaalD, $ophaalT); $stmt->fetch(); $stmt->close(); $stmt = DB::conn()->prepare("SELECT exemplaarid FROM `Orderregel` WHERE orderid=?"); $stmt->bind_param('i', $order_id); $stmt->execute(); $stmt->bind_result($exemplaar); $exmplaars = array(); while($stmt->fetch()){ $exemplaars[] = $exemplaar; } $stmt->close(); $aantalFilmsInOrder = count($exemplaars); $<API key> = strtotime($ophaalD); $nieuweOphaalDatum = strtotime($ophaalDatum); //Bereken het aantal dagen tussen de aflever en ophaal datum $diff = $nieuweOphaalDatum - $<API key>; $days = floor($diff / (60*60*24) ); //Seconden naar dagen omrekenen if($days == 7){ $extraKosten = 6 * $aantalFilmsInOrder; }else{ $extraKosten = $days * $aantalFilmsInOrder; } ?> <h4>ORIGINELE OPHAAL DATA</h4> <h4><b>OPHAALDATUM:</b> <?php echo $ophaalD ?></h4> <h4><b>OPHAALTIJD:</b> <?php echo $ophaalT ?></h4> <hr></hr> <h4><b>HUUR VERLENGEN MET: </b> <?php echo $days; if($days == 1){ echo ' dag'; }else{ echo ' dagen'; } ?> </h4> <h4><b>Extra kosten:</b> €<?php echo $extraKosten ?></h4> <hr></hr> <h4>NIEUWE OPHAAL DATA</h4> <h4><b>OPHAALDATUM:</b> <?php echo $ophaalDatum ?></h4> <h4><b>OPHAALTIJD:</b></h4> <?php $ophaalDatum = $_POST['ophaalDatum']; $stmt = DB::conn()->prepare("SELECT `ophaaltijd` FROM `Order` WHERE ophaaldatum=?"); $stmt->bind_param('s', $ophaalDatum); $stmt->execute(); $bezetteOphaalTijd = array(); $stmt->bind_result($f); while($stmt->fetch()){ $bezetteOphaalTijd[] = $f; } $stmt->close(); ?> <form method="post" action="?action=ok_verleng"> <select name="ophaalTijd" class="form-control"> <?php for($x=0; $x <= 120; $x=$x+10){ $ophaalTime = strtotime('14:00'); $ophaalTime = Date('H:i', strtotime("+".$x. " minutes", $ophaalTime)); if(!in_array($ophaalTime, $bezetteOphaalTijd)){ ?> <option value="<?php echo $ophaalTime ?>"><?php echo $ophaalTime ?></option> <?php } } ?> </select> <input type="submit" class="btn btn-success bestel verlengbtn" value="VERLENG"> <input type="hidden" name="ophaalDatum" value="<?php echo $ophaalDatum?>"> <input type="hidden" name="id" value="<?php echo $order_id?>"> <input type="hidden" name="aantalDagen" value="<?php echo $days ?>"> <input type="hidden" name="extraKosten" value="<?php echo $extraKosten?>"> </form> <?php }elseif($action == 'ok_verleng'){ $order_id = $_POST['id']; $ophaalDatum = $_POST['ophaalDatum']; $ophaalTijd = $_POST['ophaalTijd']; $days = $_POST['aantalDagen']; $extraKosten = $_POST['extraKosten']; ?> <h3>VERLENG HUUR VAN ORDER #<?php echo $order_id ?></h3> <hr></hr> <?php $stmt = DB::conn()->prepare("SELECT ophaaldatum, ophaaltijd FROM `Order` WHERE id=?"); $stmt->bind_param('i', $order_id); $stmt->execute(); $stmt->bind_result($ophaalD, $ophaalT); $stmt->fetch(); $stmt->close(); ?> <h4>ORIGINELE OPHAAL DATA</h4> <h4><b>OPHAALDATUM:</b> <?php echo $ophaalD ?></h4> <h4><b>OPHAALTIJD:</b> <?php echo $ophaalT ?></h4> <hr></hr> <h4><b>HUUR VERLENGEN MET: </b> <?php echo $days; if($days == 1){ echo ' dag'; }else{ echo ' dagen'; } ?> </h4> <h4><b>Extra kosten:</b> €<?php echo $extraKosten ?></h4> <hr></hr> <h4><b> <h4>NIEUWE OPHAAL DATA</h4> <h4><b>OPHAALDATUM:</b> <?php echo $ophaalDatum ?></h4> <h4><b>OPHAALTIJD:</b> <?php echo $ophaalTijd?></h4> <?php $stmt = DB::conn()->prepare("UPDATE `Order` SET ophaaldatum=?, ophaaltijd=?, openbedrag=? WHERE id=?"); $stmt->bind_param('ssdi', $ophaalDatum, $ophaalTijd, $extraKosten, $order_id); $stmt->execute(); $stmt->close(); } }else{ ?> <h4><b>INFORMATIE</b></h4> <div class="info"> <h5>ALGEMENE INFORMATIE</h5> <ul class="list-group"> <li class="list-group-item"><b>Klantnummer: </b><?php echo $id ?></li> <li class="list-group-item"><b>Naam: </b><?php echo $naam?></li> <li class="list-group-item"><b></b></li> </ul> <h5>CONTACT INFORMATIE</h5> <ul class="list-group"> <li class="list-group-item"><b>Email: </b><?php echo $email ?></li> <li class="list-group-item"><b>Telefoonnummer: </b><?php echo $telefoonnummer ?></li> </ul> <h5>ADRES INFORMATIE</h5> <ul class="list-group"> <li class="list-group-item"><b>Adres: </b><?php echo $adres ?></li> <li class="list-group-item"><b>Postcode: </b><?php echo $postcode ?></li> <li class="list-group-item"><b>Woonplaats: </b><?php echo $woonplaats ?></li> </ul> <form method="post" action="?action=edit&code=<?php echo $id ?>"> <?php if(isGeblokkeerd($klantRolId)){ ?> <input type="submit" class="btn btn-success bestel" value="PAS INFORMATIE AAN" disabled> <?php }else{ ?> <input type="submit" class="btn btn-success bestel" value="PAS INFORMATIE AAN"> <?php } ?> </form> </div> <?php } ?> </div> <div class="klant_right"> <h4><b>ORDERS</b></h4> <?php //Haal id op van Order op $stmt = DB::conn()->prepare("SELECT id FROM `Order` WHERE klantid=? AND besteld=1"); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($order_id); $orderIdResult = array(); while($stmt->fetch()){ $orderIdResult[] = $order_id; } $stmt->close(); $u_orderIdResult = array_unique($orderIdResult); if(!empty($u_orderIdResult)){ foreach($u_orderIdResult as $i){ $stmt = DB::conn()->prepare("SELECT afleverdatum, ophaaldatum, orderdatum, openbedrag FROM `Order` WHERE id=?"); $stmt->bind_param('i', $i); $stmt->execute(); $stmt->bind_result($afleverdatum, $ophaaldatum, $orderdatum, $openBedrag); $stmt->fetch(); $stmt->close(); $stmt = DB::conn()->prepare("SELECT exemplaarid FROM Orderregel WHERE orderid=?"); $stmt->bind_param('i', $i); $stmt->execute(); $stmt->bind_result($exmid); $exemplaren = array(); while($stmt->fetch()){ $exemplaren[] =$exmid; } $stmt->close(); $films = array(); foreach($exemplaren as $e){ $stmt = DB::conn()->prepare("SELECT filmid FROM Exemplaar WHERE id=?"); $stmt->bind_param('i', $e); $stmt->execute(); $stmt->bind_result($filmid); while($stmt->fetch()){ $films[] = $filmid; } $stmt->close(); } ?> <div class="order"> <p class="order_info" data-toggle="collapse" data-target="#<?php echo $i ?>"><?php echo $orderdatum ?> | #<?php echo $i ?><i class="fa fa-arrow-down neer" aria-hidden="true"></i></p> <div id="<?php echo $i ?>" class="collapse order_collapse"> <h3>FILMS</h3> <table class="table"> <thead> <th><b>FOTO</b></th> <th><b>TITEL</b></th> </thead> <tbody> <?php foreach($films as $f){ $stmt = DB::conn()->prepare("SELECT titel, img FROM Film WHERE id=?"); $stmt->bind_param('i', $f); $stmt->execute(); $stmt->bind_result($titel, $img); $stmt->fetch(); $stmt->close(); $cover = "/cover/" . $img; $URL = "/film/" . $f; $titel = strtoupper($titel); $titel = str_replace('_', ' ', $titel); ?> <tr> <td><a href="<?php echo $url ?>"><img src="<?php echo $cover ?>" class="winkelmand_img"></a></td> <td><?php echo $titel ?></td> </tr> <?php } ?> </tbody> </table> <h4><b>AFLEVERDATUM:</b> <?php echo $afleverdatum ?></h4> <h4><b>OPHAALDATUM:</b> <?php echo $ophaaldatum ?></h4> <?php $ophaalDatumCheck = strtotime($ophaaldatum); $vandaag = strtotime("today"); if($ophaalDatumCheck > $vandaag && $openBedrag == 0){ ?> <form method="post" action="?action=verleng&code=<?php echo $i ?>"> <input type="submit" class="btn bestel" value="VERLENG HUUR"> </form> <?php } ?> </div> </div> <?php } }else{ echo "<div class='warning'><b>U HEEFT NOG GEEN FILMS BESTELD</b></div>"; } ?> </div> </div> </div> <?php } DB::conn()->close(); }else{ header("Refresh:0; url=/login"); }
import bpy from bpy.props import * from ... events import <API key> from ... base_types.node import AnimationNode from ... utils.fcurve import <API key> frameTypeItems = [ ("OFFSET", "Offset", ""), ("ABSOLUTE", "Absolute", "") ] class <API key>(bpy.types.Node, AnimationNode): bl_idname = "<API key>" bl_label = "Object Transforms Input" bl_width_default = 165 def <API key>(self, context): self.updateFrameSocket() <API key>() <API key> = BoolProperty( name = "Use Current Transforms", default = True, update = <API key>) frameType = EnumProperty( name = "Frame Type", default = "OFFSET", items = frameTypeItems, update = <API key>) def create(self): self.newInput("Object", "Object", "object", defaultDrawType = "PROPERTY_ONLY") self.newOutput("Vector", "Location", "location") self.newOutput("Euler", "Rotation", "rotation") self.newOutput("Vector", "Scale", "scale") self.newOutput("Quaternion", "Quaternion", "quaternion", hide = True) def updateFrameSocket(self): if self.<API key>: if "Frame" in self.inputs: self.inputs["Frame"].remove() else: if "Frame" not in self.inputs: self.newInput("an_FloatSocket", "Frame", "frame") def draw(self, layout): if not self.<API key>: layout.prop(self, "frameType") def drawAdvanced(self, layout): layout.prop(self, "<API key>") col = layout.column() col.active = not self.<API key> col.prop(self, "frameType") self.invokeFunction(layout, "<API key>", text = "Create Execution Trigger") def getExecutionCode(self): isLinked = self.<API key>() if not any(isLinked.values()): return yield "try:" if self.<API key>: if isLinked["location"]: yield " location = object.location" if isLinked["rotation"]: yield " rotation = object.rotation_euler" if isLinked["scale"]: yield " scale = object.scale" if isLinked["quaternion"]: yield " quaternion = object.rotation_quaternion" else: if self.frameType == "OFFSET": yield " evaluationFrame = frame + self.nodeTree.scene.frame_current_final" else: yield " evaluationFrame = frame" if isLinked["location"]: yield " location = Vector(animation_nodes.utils.fcurve.<API key>(object, 'location', evaluationFrame))" if isLinked["rotation"]: yield " rotation = Euler(animation_nodes.utils.fcurve.<API key>(object, 'rotation_euler', evaluationFrame))" if isLinked["scale"]: yield " scale = Vector(animation_nodes.utils.fcurve.<API key>(object, 'scale', evaluationFrame))" if isLinked["quaternion"]: yield " quaternion = Quaternion(animation_nodes.utils.fcurve.<API key>(object, 'rotation_quaternion', evaluationFrame, arraySize = 4))" yield "except:" yield " location = Vector((0, 0, 0))" yield " rotation = Euler((0, 0, 0))" yield " scale = Vector((0, 0, 0))" yield " quaternion = Quaternion((1, 0, 0, 0))" def <API key>(self): isLinked = self.<API key>() customTriggers = self.nodeTree.autoExecution.customTriggers objectName = self.inputs["Object"].objectName if isLinked["location"]: customTriggers.new("MONITOR_PROPERTY", idType = "OBJECT", dataPath = "location", idObjectName = objectName) if isLinked["rotation"]: customTriggers.new("MONITOR_PROPERTY", idType = "OBJECT", dataPath = "rotation_euler", idObjectName = objectName) if isLinked["scale"]: customTriggers.new("MONITOR_PROPERTY", idType = "OBJECT", dataPath = "scale", idObjectName = objectName) if isLinked["quaternion"]: customTriggers.new("MONITOR_PROPERTY", idType = "OBJECT", dataPath = "rotation_quaternion", idObjectName = objectName)
package Controllers.Tools; /** * * @author HSOTELO */ public enum TypeUpdate { FILE_QUERY_CLEAR, FILE_FIELDS, QUERY_FIELDS }
Base, shared Vue components used throughout. These components are often used as building blocks for specific applets.
package microtrafficsim.core.simulation.core; import microtrafficsim.core.simulation.builder.ScenarioBuilder; import microtrafficsim.core.simulation.scenarios.Scenario; import java.util.Timer; /** * <p> * A simulation setup consists of three major parts: <br> * &bull; {@link Simulation}: the executor of simulation steps <br> * &bull; {@link Scenario}: the definition of routes etc. <br> * &bull; {@link ScenarioBuilder}: the scenario builder; e.g. pre-calculating routes by a * given scenario * * <p> * The simulation serves methods to execute a scenario after a builder * prepared it. It serves methods for starting and pausing the simulation. * * @author Dominic Parga Cacheiro */ public interface Simulation { default boolean hasScenario() { return getScenario() != null; } /** * @return Currently executed scenario */ Scenario getScenario(); /** * <p> * Sets the scenario being executed. The simulation should be paused for this call. The scenario is initialized * by updating all graph nodes, so the scenario has to be prepared for this. Furthermore, this simulation adds * the scenario as step listener. * * <p> * If another scenario is already added, the old scenario is getting removed from this simulation and the given * scenario is added. * * @param scenario This scenario is being executed */ void <API key>(Scenario scenario); /** * Removes the current scenario from this simulation. */ void <API key>(); /** * @param stepListener This listener gets informed when this simulation has done a complete simulation step */ void addStepListener(StepListener stepListener); /** * @param stepListener This listener gets informed when this simulation has done a complete simulation step */ void removeStepListener(StepListener stepListener); /** * @return Number of finished simulation steps. */ int getAge(); /** * <p> * This method starts calling the simulation steps repeatedly. Nothing will * be done if the simulation is already running. * * <p> * The repeated simulation steps are started by a {@link Timer}. You can * stop it by calling {@link #cancel()}. You can call {@link #isPaused()} to * ask if the simulation is paused. */ void run(); /** * <p> * This method is called before each simulation step. The default * implementation does nothing. */ default void willRunOneStep() {} /** * Does the same as {@link #doRunOneStep()} but only if the simulation is paused * ({@link #isPaused()} {@code == true}). Nothing will be done if the simulation is already running. */ void runOneStep(); /** * <p> * This method does one simulation step. The simulation has to be prepared for this. This method does not check * this condition. * * <p> * Calls {@link #willRunOneStep()} before a step and {@link #didRunOneStep()} after it. */ void doRunOneStep(); /** * <p> * This method is called after each simulation step. The default * implementation does nothing. */ default void didRunOneStep() {} /** * This method should stop iterating the simulation steps after the * currently running simulation step and letting {@link #isPaused()} * returning true. One way could be using {@link Timer#cancel()} of * {@link Timer}. */ void cancel(); /** * @return True, if the simulation does nothing; False if it is running. */ boolean isPaused(); }
#ifndef REMOTE_PROXY_BASE_H #define REMOTE_PROXY_BASE_H #include <proxybase_exports.h> #include <Xfer.h> #include <KeepAliveRPC.h> #include <QuitRPC.h> #include <ConnectCallback.h> #include <LaunchProfile.h> #include <MachineProfile.h> #include <string> // Forward declaration. class RemoteProcess; // Class: RemoteProxyBase // Purpose: // This class serves as a base class for our remote process proxies. // Notes: // Programmer: Brad Whitlock // Creation: Fri May 2 14:12:55 PST 2003 // Modifications: // Jeremy Meredith, Tue Jun 17 11:55:51 PDT 2003 // Added parallel functions that were only needed for the engine but // that are helpful to have in the base class. // Jeremy Meredith, Thu Oct 9 14:04:37 PDT 2003 // Added ability to manually specify a client host name or to have it // parsed from the SSH_CLIENT (or related) environment variables. Added // ability to specify an SSH port. // Brad Whitlock, Thu Mar 11 12:44:23 PDT 2004 // I added KeepAliveRPC so we don't lose connections to remote components // whose connections have been idle for a long time. // Brad Whitlock, Thu Aug 5 09:59:11 PDT 2004 // Added AddProfileArguments from another class. // Jeremy Meredith, Thu May 24 10:20:32 EDT 2007 // Added SSH tunneling argument to Create. // Brad Whitlock, Wed Nov 21 11:41:52 PST 2007 // Added methods to access the RemoteProcess's connections. // Brad Whitlock, Fri Dec 7 16:58:33 PST 2007 // Added SetupAllRPCs and GetXfer. // Jeremy Meredith, Thu Feb 18 15:25:27 EST 2010 // Split HostProfile int MachineProfile and LaunchProfile. // Eric Brugger, Mon May 2 16:41:53 PDT 2011 // I added the ability to use a gateway machine when connecting to a // remote host. // Brad Whitlock, Tue Jun 5 17:30:06 PDT 2012 // Change Create method so it takes a MachineProfile instead of a bunch // of separate options. class PROXYBASE_API RemoteProxyBase { public: RemoteProxyBase(const std::string &componentName); virtual ~RemoteProxyBase(); void SetProgressCallback(bool (*cb)(void *, int), void *data); void AddArgument(const std::string &arg); void AddProfileArguments(const MachineProfile &machine, bool addParallelArgs); virtual void Create(const MachineProfile &profile, ConnectCallback *connectCallback = 0, void *connectCallbackData = 0, bool createAsThoughLocal = false); void Close(); virtual void SendKeepAlive(); virtual bool Parallel() const; virtual std::string GetComponentName() const = 0; virtual void SetNumProcessors(int) { } virtual void SetNumNodes(int) { } virtual void SetLoadBalancing(int) { } Connection *GetReadConnection(int i=0) const; Connection *GetWriteConnection(int i=0) const; // This method should rarely need to be used. const Xfer &GetXfer(); protected: void SetupAllRPCs(); virtual void SetupComponentRPCs() = 0; std::string GetVisItString() const; virtual void AddExtraArguments(); std::string componentName; RemoteProcess *component; Xfer xfer; bool rpcSetup; QuitRPC quitRPC; KeepAliveRPC keepAliveRPC; int nWrite; int nRead; // Extra command line arguments to pass to the remote process. stringVector argv; bool (*progressCallback)(void *, int); void *<API key>; }; #endif
/** * This turns your displayObjects to grayscale. * @class Gray * @contructor */ Phaser.Filter.Gray = function (game) { Phaser.Filter.call(this, game); this.uniforms.gray = { type: '1f', value: 1.0 }; this.fragmentSrc = [ "precision mediump float;", "varying vec2 vTextureCoord;", "varying vec4 vColor;", "uniform sampler2D uSampler;", "uniform float gray;", "void main(void) {", "gl_FragColor = texture2D(uSampler, vTextureCoord);", "gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.2126 * gl_FragColor.r + 0.7152 * gl_FragColor.g + 0.0722 * gl_FragColor.b), gray);", "}" ]; }; Phaser.Filter.Gray.prototype = Object.create(Phaser.Filter.prototype); Phaser.Filter.Gray.prototype.constructor = Phaser.Filter.Gray; /** * The strength of the gray. 1 will make the object black and white, 0 will make the object its normal color * @property gray */ Object.defineProperty(Phaser.Filter.Gray.prototype, 'gray', { get: function () { return this.uniforms.gray.value; }, set: function (value) { this.uniforms.gray.value = value; } });
// MediaInfo_Internal - All info about media files // This library is free software: you can redistribute it and/or modify it // any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // For user: you can disable or enable it //#define MEDIAINFO_DEBUG // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "MediaInfo/Setup.h" #include "MediaInfo/Reader/Reader_File.h" #include "MediaInfo/File__Analyze.h" #include "ZenLib/FileName.h" #ifdef WINDOWS #undef __TEXT #include "Windows.h" #endif //WINDOWS using namespace ZenLib; using namespace std; // Debug stuff #ifdef MEDIAINFO_DEBUG int64u Reader_File_Offset=0; int64u <API key>=0; int64u <API key>=0; int64u Reader_File_Count=1; #include <iostream> #endif // MEDIAINFO_DEBUG namespace MediaInfoLib { const size_t Buffer_NoJump=128*1024; size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name) { //std::cout<<Ztring(File_Name).To_Local().c_str()<<std::endl; #if MEDIAINFO_EVENTS { struct <API key> Event; Event.EventCode=<API key>(<API key>, <API key>, 0); Event.Stream_Size=File::Size_Get(File_Name); MI->Config.Event_Send((const int8u*)&Event, sizeof(<API key>)); } #endif //MEDIAINFO_EVENTS //With Parser MultipleParsing /* MI->Open_Buffer_Init((int64u)-1, File_Name); if (<API key>(MI, File_Name)) return 1; return 0; //There is a problem */ //Get the Extension Ztring Extension=FileName::Extension_Get(File_Name); Extension.MakeLowerCase(); //Search the theorical format from extension InfoMap &FormatList=MediaInfoLib::Config.Format_Get(); InfoMap::iterator Format=FormatList.end(); if (!MI->Config.<API key>().empty()) Format=FormatList.find(MI->Config.<API key>()); if (Format==FormatList.end()) { Format=FormatList.begin(); while (Format!=FormatList.end()) { const Ztring &Extensions=FormatList.Get(Format->first, <API key>); if (Extensions.find(Extension)!=Error) { if(Extension.size()==Extensions.size()) break; //Only one extenion in the list if(Extensions.find(Extension+__T(" "))!=Error || Extensions.find(__T(" ")+Extension)!=Error) break; } ++Format; } } if (Format!=FormatList.end()) { const Ztring &Parser=Format->second(InfoFormat_Parser); if (MI->SelectFromExtension(Parser)) { //Test the theorical format if (<API key>(MI, File_Name)>0) return 1; } } size_t ToReturn=MI->ListFormats(File_Name); return ToReturn; } size_t Reader_File::<API key>(MediaInfo_Internal* MI, const String &File_Name) { //Opening the file F.Open(File_Name); if (!F.Opened_Get()) return 0; //Info Status=0; MI->Config.File_Size=F.Size_Get(); MI->Config.File_Current_Offset=0; MI->Config.File_Current_Size=MI->Config.File_Size; MI->Config.File_Sizes.clear(); MI->Config.File_Sizes.push_back(MI->Config.File_Size); if (MI->Config.File_Names.size()>1) { for (size_t Pos=1; Pos<MI->Config.File_Names.size(); Pos++) { int64u Size=File::Size_Get(MI->Config.File_Names[Pos]); MI->Config.File_Sizes.push_back(Size); MI->Config.File_Size+=Size; } } //Partial file handling Ztring <API key>=MI->Config.<API key>(); if (!<API key>.empty() && <API key>[0]>=__T('0') && <API key>[0]<=__T('9')) { if (<API key>.find(__T('%'))==<API key>.size()-1) Partial_Begin=float64_int64s(MI->Config.File_Size*<API key>.To_float64()/100); else Partial_Begin=<API key>.To_int64u(); if (Partial_Begin) F.GoTo(Partial_Begin); } else Partial_Begin=0; Ztring Config_Partial_End=MI->Config.<API key>(); if (!Config_Partial_End.empty() && Config_Partial_End[0]>=__T('0') && Config_Partial_End[0]<=__T('9')) { if (Config_Partial_End.find(__T('%'))==Config_Partial_End.size()-1) Partial_End=float64_int64s(MI->Config.File_Size*Config_Partial_End.To_float64()/100); else Partial_End=Config_Partial_End.To_int64u(); } else Partial_End=(int64u)-1; if (Partial_Begin>MI->Config.File_Size) Partial_Begin=0; //Wrong value if (Partial_Begin>Partial_End) Partial_Begin=0; //Wrong value //Parser MI->Open_Buffer_Init((Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size)-Partial_Begin, File_Name); //Buffer MI->Option(__T("<API key>"), Ztring::ToZtring((size_t)(&MI->Config.<API key>))); MI->Config.<API key>=true; //Test the format with buffer return <API key>(MI); } size_t Reader_File::<API key> (MediaInfo_Internal* MI) { bool StopAfterFilled=MI->Config.<API key>(); bool ShouldContinue=true; //Previous data if (MI->Config.File_Buffer_Repeat) { MI->Config.File_Buffer_Repeat=false; #if MEDIAINFO_DEMUX MI->Config.Demux_EventWasSent=false; #endif //MEDIAINFO_DEMUX Status=MI-><API key>(MI->Config.File_Buffer, MI->Config.File_Buffer_Size); #if MEDIAINFO_DEMUX //Demux if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX //Threading if (MI->IsTerminating()) return 1; //Termination is requested if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])) ShouldContinue=false; } #if MEDIAINFO_DEMUX //PerPacket if (ShouldContinue && MI->Config.Demux_EventWasSent) { MI->Config.Demux_EventWasSent=false; Status=MI-><API key>(NULL, 0); //Demux if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately //Threading if (MI->IsTerminating()) return 1; //Termination is requested if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])) ShouldContinue=false; } #endif //MEDIAINFO_DEMUX if (ShouldContinue) { //Test the format with buffer while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))) { //Seek (if needed) if (MI-><API key>()!=(int64u)-1) { #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+<API key><<" : "<<std::dec<<<API key><<" bytes"<<std::endl; Reader_File_Offset=MI-><API key>(); <API key>=0; Reader_File_Count++; #endif //MEDIAINFO_DEBUG int64u GoTo=Partial_Begin+MI-><API key>(); MI->Config.File_Current_Offset=0; int64u Buffer_NoJump_Temp=Buffer_NoJump; if (MI->Config.File_Names.size()>1) { size_t Pos; for (Pos=0; Pos<MI->Config.File_Sizes.size(); Pos++) { if (GoTo>=MI->Config.File_Sizes[Pos]) { GoTo-=MI->Config.File_Sizes[Pos]; MI->Config.File_Current_Offset+=MI->Config.File_Sizes[Pos]; } else break; } if (Pos>=MI->Config.File_Sizes.size()) break; if (Pos!=MI->Config.File_Names_Pos) { F.Close(); F.Open(MI->Config.File_Names[Pos]); MI->Config.File_Names_Pos=Pos+1; MI->Config.File_Current_Size=MI->Config.File_Current_Offset+F.Size_Get(); Buffer_NoJump_Temp=0; } } if (GoTo>=F.Size_Get()) break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this if (!(GoTo>F.Position_Get() && GoTo<F.Position_Get()+Buffer_NoJump_Temp)) //No smal jumps { if (!F.GoTo(GoTo)) break; //File is not seekable MI->Open_Buffer_Init((int64u)-1, MI->Config.File_Current_Offset+F.Position_Get()-Partial_Begin); } } //Handling of hints if (MI->Config.<API key>==0) break; //Problem while config if (MI->Config.<API key>>MI->Config.<API key>) { delete[] MI->Config.File_Buffer; if (MI->Config.<API key>==0) MI->Config.<API key>=1; while (MI->Config.<API key>>MI->Config.<API key>) MI->Config.<API key>*=2; MI->Config.File_Buffer=new int8u[MI->Config.<API key>]; } MI->Config.File_Buffer_Size=F.Read(MI->Config.File_Buffer, (F.Position_Get()+MI->Config.<API key><(Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size))?MI->Config.<API key>:((size_t)((Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size)-F.Position_Get()))); //Testing growing files if (!MI->Config.File_IsGrowing && F.Position_Get()>=MI->Config.File_Size) { if (MediaInfoLib::Config.ParseSpeed_Get()>=1.0) //Only if full parsing { int64u FileSize_New=F.Size_Get(); if (MI->Config.File_Size!=FileSize_New) MI->Config.File_IsGrowing=true; } } if (MI->Config.<API key>) { MI->Config.File_Current_Size=MI->Config.File_Size=F.Size_Get(); MI->Open_Buffer_Init(MI->Config.File_Size, F.Position_Get()-MI->Config.File_Buffer_Size); MI->Config.File_IsGrowing=false; MI->Config.<API key>=false; } if (MI->Config.File_IsGrowing && F.Position_Get()>=MI->Config.File_Size) { for (size_t CountOfSeconds=0; CountOfSeconds<(size_t)MI->Config.<API key>(); CountOfSeconds++) { int64u FileSize_New=F.Size_Get(); if (MI->Config.File_Size!=FileSize_New) { MI->Config.File_Current_Size=MI->Config.File_Size=FileSize_New; MI->Open_Buffer_Init(MI->Config.File_Size, F.Position_Get()-MI->Config.File_Buffer_Size); break; } #ifdef WINDOWS Sleep(1000); #endif //WINDOWS } } #ifdef MEDIAINFO_DEBUG <API key>+=MI->Config.File_Buffer_Size; <API key>+=MI->Config.File_Buffer_Size; #endif //MEDIAINFO_DEBUG //Parser Status=MI-><API key>(MI->Config.File_Buffer, MI->Config.File_Buffer_Size); //Testing multiple file per stream if (F.Position_Get()>=F.Size_Get()) { if (MI->Config.File_Names_Pos<MI->Config.File_Names.size()) { MI->Config.File_Current_Offset+=F.Size_Get(); F.Close(); F.Open(MI->Config.File_Names[MI->Config.File_Names_Pos]); MI->Config.File_Names_Pos++; MI->Config.File_Current_Size+=F.Size_Get(); } } if (MI->Config.File_Buffer_Size==0) { #if MEDIAINFO_EVENTS MediaInfoLib::Config.Log_Send(0xC0, 0xFF, 0xF0F00101, "File read error"); #endif //MEDIAINFO_EVENTS break; } #if MEDIAINFO_DEMUX if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX //Threading if (MI->IsTerminating()) break; //Termination is requested } } #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+<API key><<" : "<<std::dec<<<API key><<" bytes"<<std::endl; std::cout<<"Total: "<<std::dec<<<API key><<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl; #endif //MEDIAINFO_DEBUG if (MI==NULL || !MI->Config.File_KeepInfo_Get()) { //File F.Close(); } //Is this file detected? if (!Status[File__Analyze::IsAccepted]) return 0; MI-><API key>(); #if MEDIAINFO_DEMUX if (MI->Config.Demux_EventWasSent) return 2; //Must return immediately #endif //MEDIAINFO_DEMUX return 1; } #if MEDIAINFO_SEEK size_t Reader_File::<API key> (MediaInfo_Internal* MI, size_t Method, int64u Value, int64u ID) { size_t ToReturn=MI->Open_Buffer_Seek(Method, Value, ID); if (ToReturn==0 || ToReturn==1) { //Reset Status=0; } return ToReturn; } #endif //MEDIAINFO_SEEK } //NameSpace
# Queue - require "thread" puts "SizedQuee Test" queue = Queue.new producer = Thread.new() do 3.times do |i| sleep rand(i) queue << i puts "#{i} produced" end end consumer = Thread.new do 3.times do |i| value = queue.pop sleep rand(i/2) puts "consumed #{value}" end end consumer.join
#ifndef overview_formH #define overview_formH #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Buttons.hpp> #include <ComCtrls.hpp> #include <ToolWin.hpp> class TDBWFRM; class TOverviewForm : public TForm { __published: // IDE-managed Components TToolBar *Toolbar; TSpeedButton *SBZoomOut; TSpeedButton *SBZoomIn; TToolButton *ToolButton1; TToolButton *ToolButton2; TSpeedButton *SBPrint; TSpeedButton *SBGrid; TSpeedButton *SBClose; void __fastcall FormPaint(TObject *Sender); void __fastcall FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall SBZoomOutClick(TObject *Sender); void __fastcall SBZoomInClick(TObject *Sender); void __fastcall SBPrintClick(TObject *Sender); void __fastcall SBCloseClick(TObject *Sender); void __fastcall SBGridClick(TObject *Sender); private: // User declarations TDBWFRM* frm; int zoom; bool grid; // Druckdaten int gw; int gh; int mleft; int mright; int mtop; int mbottom; int pwidth; int pheight; int maxi; int maxj; void __fastcall CalcPrintDimensions(); void __fastcall LoadLanguage(); public: // User declarations __fastcall TOverviewForm(TComponent* Owner, TDBWFRM* _frm); }; #endif
<?php ?> <!-- BEGIN PHP TEMPLATE STOCKCORRECTION.TPL.PHP --> <?php $productref = ''; if ($object->element == 'product') $productref = $object->ref; $langs->load("productbatch"); if (empty($id)) $id = $object->id; print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { function init_price() { if (jQuery("#mouvement").val() == \'0\') jQuery("#unitprice").removeAttr("disabled"); else jQuery("#unitprice").prop("disabled", true); } init_price(); jQuery("#mouvement").change(function() { init_price(); }); }); </script>'; print load_fiche_titre($langs->trans("StockCorrection"),'','title_generic.png'); print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$id.'" method="post">'."\n"; print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'; print '<input type="hidden" name="action" value="correct_stock">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; print '<table class="border" width="100%">'; // Warehouse or product print '<tr>'; if ($object->element == 'product') { print '<td width="20%" class="fieldrequired" colspan="2">'.$langs->trans("Warehouse").'</td>'; print '<td width="20%">'; print $formproduct->selectWarehouses((GETPOST("dwid")?GETPOST("dwid",'int'):(GETPOST('id_entrepot')?GETPOST('id_entrepot','int'):'ifone')), 'id_entrepot', 'warehouseopen,warehouseinternal', 1, 0, 0, '', 0, 0, null, 'minwidth100'); print '</td>'; } if ($object->element == 'stock') { print '<td width="20%" class="fieldrequired" colspan="2">'.$langs->trans("Product").'</td>'; print '<td width="20%">'; print $form->select_produits(GETPOST('product_id'), 'product_id', (empty($conf->global-><API key>)?'0':''), 20, 0, -1); print '</td>'; } print '<td width="20%">'; print '<select name="mouvement" id="mouvement" class="flat">'; print '<option value="0">'.$langs->trans("Add").'</option>'; print '<option value="1"'.(GETPOST('mouvement')?' selected="selected"':'').'>'.$langs->trans("Delete").'</option>'; print '</select></td>'; print '<td width="20%" class="fieldrequired">'.$langs->trans("NumberOfUnit").'</td><td width="20%"><input class="flat" name="nbpiece" id="nbpiece" size="10" value="'.GETPOST("nbpiece").'"></td>'; print '</tr>'; // Purchase price print '<tr>'; print '<td width="20%" colspan="2">'.$langs->trans("UnitPurchaseValue").'</td>'; print '<td colspan="'.(!empty($conf->projet->enabled) ? '2' : '4').'"><input class="flat" name="unitprice" id="unitprice" size="10" value="'.GETPOST("unitprice").'"></td>'; if (! empty($conf->projet->enabled)) { print '<td>'.$langs->trans('Project').'</td>'; print '<td>'; $formproject->select_projects(); print '</td>'; } print '</tr>'; // Serial / Eat-by date if (! empty($conf->productbatch->enabled) && (($object->element == 'product' && $object->hasbatch()) || ($object->element == 'stock')) ) { print '<tr>'; print '<td colspan="2"'.($object->element == 'stock'?'': ' class="fieldrequired"').'>'.$langs->trans("batch_number").'</td><td colspan="4">'; print '<input type="text" name="batch_number" size="40" value="'.GETPOST("batch_number").'">'; print '</td>'; print '</tr><tr>'; print '<td colspan="2">'.$langs->trans("EatByDate").'</td><td>'; $eatbyselected=dol_mktime(0, 0, 0, GETPOST('eatbymonth'), GETPOST('eatbyday'), GETPOST('eatbyyear')); $form->select_date($eatbyselected,'eatby','','',1,""); print '</td>'; print '<td></td>'; print '<td>'.$langs->trans("SellByDate").'</td><td>'; $sellbyselected=dol_mktime(0, 0, 0, GETPOST('sellbymonth'), GETPOST('sellbyday'), GETPOST('sellbyyear')); $form->select_date($sellbyselected,'sellby','','',1,""); print '</td>'; print '</tr>'; } // Label of mouvement of id of inventory $valformovementlabel=((GETPOST("label") && (GETPOST('label') != $langs->trans("<API key>",''))) ? GETPOST("label") : $langs->trans("<API key>", $productref)); print '<tr>'; print '<td width="20%" colspan="2">'.$langs->trans("MovementLabel").'</td>'; print '<td colspan="2">'; print '<input type="text" name="label" size="60" value="'.$valformovementlabel.'">'; print '</td>'; print '<td width="20%">'.$langs->trans("InventoryCode").'</td><td width="20%"><input class="flat <API key>" name="inventorycode" id="inventorycode" value="'.GETPOST("inventorycode").'"></td>'; print '</tr>'; print '</table>'; print '<div class="center">'; print '<input type="submit" class="button" name="save" value="'.dol_escape_htmltag($langs->trans('Save')).'">'; print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">'; print '</div>'; print '</form>'; ?> <!-- END PHP STOCKCORRECTION.TPL.PHP -->
# This file is part of <API key>. # <API key> is free software: you can redistribute it and/or # (at your option) any later version. # <API key> is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # along with <API key>. If not, see import logging import datetime import os import re from pylons import config from pylons import request, response, session, app_globals, tmpl_context as c from pylons import url from pylons.controllers.util import abort, redirect, forward from pylons.decorators import validate from pylons.decorators.rest import restrict import webhelpers.paginate as paginate from formencode.schema import Schema from formencode.validators import Invalid, FancyValidator from formencode.validators import Int, DateConverter, UnicodeString, OneOf, Regex from formencode import variabledecode from formencode import htmlfill from formencode.foreach import ForEach from formencode.api import NoDefault from sqlalchemy.sql import or_, not_ from <API key>.lib.base import BaseController, render import <API key>.model as model import <API key>.model.meta as meta import <API key>.lib.helpers as h from <API key>.lib.oldMarkup import <API key>, linkToOLDEntitites, embedFiles from sqlalchemy import desc try: import json except ImportError: import simplejson as json log = logging.getLogger(__name__) class NewCollectionForm(Schema): """NewCollectionForm is a Schema for validating the data entered at the Add Collection page.""" allow_extra_fields = True filter_extra_fields = True title = UnicodeString(not_empty=True) url = Regex('[a-zA-Z0-9_/-]+') type = UnicodeString() description = UnicodeString() speaker = UnicodeString() elicitor = UnicodeString() source = UnicodeString() dateElicited = DateConverter(month_style='mm/dd/yyyy') contents = UnicodeString() class NewCollectionFormDM(NewCollectionForm): dateElicited = DateConverter(month_style='dd/mm/yyyy') class <API key>(NewCollectionForm): ID = UnicodeString() class <API key>(<API key>): dateElicited = DateConverter(month_style='dd/mm/yyyy') class RestrictorStruct(Schema): location = UnicodeString() containsNot = UnicodeString() allAnyOf = UnicodeString options = ForEach(UnicodeString()) class <API key>(Schema): location = UnicodeString() relation = UnicodeString() date = DateConverter(month_style='mm/dd/yyyy') class <API key>(Schema): allow_extra_fields = True filter_extra_fields = True location = UnicodeString() relation = UnicodeString() integer = Regex(r'^ *[0-9]+(\.[0-9]+)? *$') class <API key>(Schema): """SearchCollection is a Schema for validating the search terms entered at the Search Collections page. """ allow_extra_fields = True filter_extra_fields = True pre_validators = [variabledecode.NestedVariables()] searchTerm1 = UnicodeString() searchType1 = UnicodeString() searchLocation1 = UnicodeString() searchTerm2 = UnicodeString() searchType2 = UnicodeString() searchLocation2 = UnicodeString() andOrNot = UnicodeString() restrictors = ForEach(RestrictorStruct()) dateRestrictors = ForEach(<API key>()) integerRestrictors = ForEach(<API key>()) orderByColumn = UnicodeString() orderByDirection = UnicodeString() class <API key>(Schema): allow_extra_fields = True filter_extra_fields = True fileID = Regex(r'^ *[1-9]+[0-9]* *( *, *[1-9]+[0-9]* *)*$', not_empty=True) def renderAddCollection(values=None, errors=None, addUpdate='add'): """Function is called by both the add and update actions to create the Add Collection and Update Collection HTML forms. The create and save actions can also call this function if any errors are present in the input. """ # if addUpdate is set to 'update', render update.html instead of add.html if addUpdate == 'add': html = render('/derived/collection/add.html') else: html = render('/derived/collection/update.html') return htmlfill.render(html, defaults=values, errors=errors) def <API key>(collection, result, createOrSave): """Given a (SQLAlchemy) Collection object and a result dictionary populated by user-entered data, this function populates the appropriate attributes with the appropriate values. This function is called by both create and save actions. """ # User-entered Data collection.title = h.NFD(result['title']) collection.type = h.NFD(result['type']) collection.url = h.NFD(result['url']) collection.description = h.NFD(result['description']) if result['speaker']: collection.speaker = meta.Session.query(model.Speaker).get(int(result['speaker'])) if result['elicitor']: collection.elicitor = meta.Session.query(model.User).get(int(result['elicitor'])) if result['source']: collection.source = meta.Session.query(model.Source).get(int(result['source'])) if result['dateElicited']: collection.dateElicited = result['dateElicited'] # OLD-generated Data now = datetime.datetime.utcnow() collection.datetimeModified = now if createOrSave == 'create': collection.datetimeEntered = now # Add the Enterer as the current user collection.enterer = meta.Session.query(model.User).get( int(session['user_id'])) # Extract component Forms from the collection objects contents field and # append them to collection.forms collection.forms = [] collection.contents = h.NFD(result['contents']) patt = re.compile('[Ff]orm\[([0-9]+)\]') formIDs = patt.findall(collection.contents) for formID in formIDs: form = meta.Session.query(model.Form).get(int(formID)) if form: collection.forms.append(form) return collection def backupCollection(collection): """When a Collection is being updated or deleted, it is first added to the collectionbackup table. """ # transform nested data structures to JSON for storage in a # relational database unicode text column collectionBackup = model.CollectionBackup() user = json.dumps({ 'id': session['user_id'], 'firstName': session['user_firstName'], 'lastName': session['user_lastName'] }) collectionBackup.toJSON(collection, user) meta.Session.add(collectionBackup) def getExampleTable(enumerator, match, formID): """This function returns an HTML table for displaying a linguistic example form. The Form embedding reference expression (e.g., 'form[88]') is left unaltered. This function simply wraps it in an HTML table for display as an example in a Collection contents field. Argument explanation: - enumerator is an int representing the example number, e.g., 2 - match is the string matching the pattern, e.g., 'form[88]' - formID is an int: the ID of the form, e.g., 88 """ temp = u'\n\n<table class="igt">\n <tr>\n <td class="enumerator">' temp += u'<a href="%s" title="View this Form">(%s)</a></td>\n <td>%s</td>\n' % ( url(controller='form', action='view', id=formID), str(enumerator), match ) temp += u'</tr>\n</table>\n\n' return temp def getEnumerator(formID2Enumerator, key): try: return formID2Enumerator[key] except KeyError: return '???' def getFormFromID(formsDict, formID): try: return formsDict[formID] except KeyError: return 'THERE IS NO FORM WITH ID %s\n\n<br /><br />\n\n' % str(formID) def getFormAsHTMLTable(match, formsDict): """getFormAsHTMLTable uses the form method getIGTHTMLTable (see lib/oldCoreObjects.py to return an HTML representation of the Form. """ form = getFormFromID(formsDict, int(match.group(2))) try: return '%s\n\n<br />\n\n' % form.<API key>(forCollection=True) # AttributeError means getFormFromID gave us an error string, so pass it on except AttributeError: return form def <API key>(collection): """This function formats the contents of a Collection as HTML. It assumes the contents text is written in reStructuredText. """ contents = collection.contents # formID2Enumerator example: {'9': '4'} means that the first Form with ID=9 # occurs as the fourth example (i.e., enumerator = '4') in the Collection formID2Enumerator = {} # enumerator gives example numbers to embedded forms enumerator = 1 # c.formsDict will be used by template to get the correct Form c.formsDict = dict([(form.id, form) for form in collection.forms]) # Replace each embedding reference to a Collection with its contents # (verbatim). Do this first so that the subsequent rst2html conversion will # convert the composite collection in one go. This seems easier than doing # rst2html(collection.contents) for each embedded Collection... contents = <API key>(contents) # Convert collection's contents to HTML using rst2html contents = h.rst2html(contents) # Replace "form[X]" with an example table, i.e., enumerator in first cell, # form data in second: # (23) blah blahblah x # blah blah-blah x # xyz xyz-xyz-33 # zyz3 3 ayaazy883 patt = re.compile('([Ff]orm\[([0-9]+)\])') <API key> = [] contentsLinesList = patt.sub('\n\\1\n', contents).split('\n') for line in contentsLinesList: if patt.search(line): # Update formID2Enumerator only if this is this form's first occurrence if patt.search(line).group(2) not in formID2Enumerator: formID2Enumerator[patt.search(line).group(2)] = str(enumerator) # Replace each match with an example table with an enumerator <API key>.append( patt.sub( lambda x: getExampleTable( enumerator, x.group(1), int(x.group(2))), line ) ) enumerator += 1 else: <API key>.append(line) contents = '\n'.join(<API key>) # Replace "ref[x]" with the enumerator of the first occurrence of the Form # with id=x that is embedded in this Collection's content refPatt = re.compile('([Rr]ef\[([0-9]+)\])') contents = refPatt.sub( lambda x: getEnumerator(formID2Enumerator, x.group(2)), contents) # Replace each embedding reference to a Form with a representation of that # Form. contents = patt.sub( lambda x: getFormAsHTMLTable(x, c.formsDict), contents ) # Embed OLD Files contents = embedFiles(contents) # Replace each linking reference to an OLD entity with an HTML link contents = linkToOLDEntitites(contents) return contents class <API key>(BaseController): """Collection Controller contains actions about OLD Collections. Authorization and authentication are implemented by the helper decorators authenticate and authorize which can be found in lib/auth.py.""" @h.authenticate def browse(self): """Browse through all Collections in the system. """ c.collections = {} for cType in app_globals.collectionTypes: c.collections[cType] = meta.Session.query(model.Collection).filter( model.Collection.type==cType).order_by( model.Collection.title).all() c.collectionCount = sum([len(c.collections[x]) for x in c.collections]) c.browsing = True c.<API key> = meta.Session.query(model.Collection).filter( not_(model.Collection.type.in_(app_globals.collectionTypes))).order_by( model.Collection.title).all() return render('/derived/collection/results.html') @h.authenticate def view(self, id, option=None): """View a BLD Collection. Requires a Collection ID as input. """ # Get the Collection with id=id if id is None: abort(404) collection_q = meta.Session.query(model.Collection) try: c.collection = collection_q.get(int(id)) except ValueError: abort(404) if c.collection is None: abort(404) # Convert the Collection contents (assumed to be in reStructuredText # with OLDMarkup) to HTML c.contents = <API key>(c.collection) return render('/derived/collection/view.html') @h.authenticate @h.authorize(['administrator', 'contributor']) def add(self): """Display HTML form for adding a new BLD Collection. HTML form calls create action.""" return renderAddCollection() @h.authenticate def search(self, values=None, errors=None): """Display HTML form for searching for BLD Collections. HTML form calls query action. """ # if no user-entered defaults are set, make gloss the default for searchLocation2 if not values: values = {'searchLocation2': u'description'} values['orderByColumn'] = 'id' # By default, the additional search restrictors are hidden c.viewRestrictors = False # Get today in MM/DD/YYYY collection c.today = datetime.date.today().strftime('%m/%d/%Y') html = render('/derived/collection/search.html') return htmlfill.render(html, defaults=values, errors=errors) @h.authenticate @h.authorize(['administrator', 'contributor']) @restrict('POST') def create(self): """Enter BLD Collection data into the database. This is the action referenced by the HTML form rendered by the add action. """ dateFormat = session.get('userSettings').get('dateFormat') if dateFormat == 'DD/MM/YYYY': schema = NewCollectionFormDM() else: schema = NewCollectionForm() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: return renderAddCollection( values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ) ) else: # Create a new Collection SQLAlchemy Object and populate its attributes with the results collection = model.Collection() collection = <API key>(collection, result, 'create') # Enter the data meta.Session.add(collection) meta.Session.commit() # Issue an HTTP redirect redirect(url(controller='collection', action='view', id=collection.id)) @h.authenticate @h.authorize(['administrator', 'contributor']) def getmemory(self): """Insert references to Forms in Memory into the content field of the Collection being added or updated.""" values = dict(request.params) # Get all Forms that user has memorized ordered by Form ID # by using the 'memorizers' backreference user = meta.Session.query(model.User).filter(model.User.id==session['user_id']).first() rememberedForms = meta.Session.query(model.Form).order_by(model.Form.id).filter(model.Form.memorizers.contains(user)).all() rememberedFormIDs = ['form[%s]' % form.id for form in rememberedForms] return '\n'.join(rememberedFormIDs) @h.authenticate @restrict('POST') def query(self): """Query action validates the search input values; if valid, query stores the search input values in the session and redirects to results; if invalid, query redirect to search action (though I don't think it's possible to enter an invalid query...). Query is the action referenced by the HTML form rendered by the search action. """ schema = <API key>() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: return self.search( values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ) ) else: # result is a Python dict nested structure representing the user's # query. We put result into session['<API key>'] so # that the results action can use it to build the SQLAlchemy query session['<API key>'] = result session.save() # Issue an HTTP redirect response.status_int = 302 response.headers['location'] = url( controller='collection', action='results') return "Moved temporarily" @h.authenticate def results(self): """Results action uses the filterSearchQuery helper function to build a query based on the values entered by the user in the search collection. """ collection_q = meta.Session.query(model.Collection) if '<API key>' in session: result = session['<API key>'] collection_q = h.filterSearchQuery( result, collection_q, 'Collection') c.paginator = paginate.Page( collection_q, page=int(request.params.get('page', 1)), items_per_page = app_globals.<API key> ) return render('/derived/collection/results.html') @h.authenticate @h.authorize(['administrator', 'contributor']) def update(self, id=None): """Displays an HTML form for updating a BLD Collection. HTML form calls save action. """ if id is None: abort(404) collection_q = meta.Session.query(model.Collection) collection = collection_q.filter_by(id=id).first() if collection is None: abort(404) c.collection = collection values = { 'ID': collection.id, 'title': collection.title, 'type': collection.type, 'url': collection.url, 'description': collection.description, 'elicitor': collection.elicitor_id, 'speaker': collection.speaker_id, 'source': collection.source_id, 'contents': collection.contents } if collection.dateElicited: dateFormat = session.get('userSettings').get('dateFormat') if dateFormat == 'DD/MM/YYYY': values['dateElicited'] = collection.dateElicited.strftime( '%d/%m/%Y') else: values['dateElicited'] = collection.dateElicited.strftime( '%m/%d/%Y') return renderAddCollection(values, None, 'update') @h.authenticate @h.authorize(['administrator', 'contributor']) @restrict('POST') def save(self): """Updates existing BLD Collection. This is the action referenced by the HTML form rendered by the update action. """ dateFormat = session.get('userSettings').get('dateFormat') if dateFormat == 'DD/MM/YYYY': schema = <API key>() else: schema = <API key>() values = dict(request.params) try: result = schema.to_python(dict(request.params), c) except Invalid, e: id = int(values['ID']) collection_q = meta.Session.query(model.Collection) collection = collection_q.filter_by(id=id).first() c.collection = collection c.id = values['ID'] return renderAddCollection( values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False ), addUpdate='update' ) else: # Get the Collection object with ID from hidden field in update.html collection_q = meta.Session.query(model.Collection) collection = collection_q.filter_by(id=result['ID']).first() # Backup the Collection to the collectionbackup table backupCollection(collection) # Populate the Collection's attributes with the data from the user-entered result dict collection = <API key>(collection, result, 'save') # Commit the update meta.Session.commit() # Issue an HTTP redirect response.status_int = 302 response.headers['location'] = url(controller='collection', action='view', id=collection.id) return "Moved temporarily" @h.authenticate @h.authorize(['administrator', 'contributor']) def delete(self, id): """Delete the BLD collection with ID=id.""" if id is None: abort(404) collection_q = meta.Session.query(model.Collection) collection = collection_q.get(int(id)) if collection is None: abort(404) # Back up Form to formbackup table backupCollection(collection) # Delete Collection info in database meta.Session.delete(collection) meta.Session.commit() # Create the flash message session['flash'] = "Collection %s has been deleted" % id session.save() redirect(url(controller='collection', action='results')) @h.authenticate @h.authorize(['administrator', 'contributor']) def associate(self, id): """Display the page for associating a BLD Collection with id=id to a BLD File. The HTML form in the rendered page ultimately references the link action.""" if id is None: abort(404) c.collection = meta.Session.query(model.Collection).get(int(id)) if c.collection is None: abort(404) return render('/derived/collection/associate.html') @h.authenticate @h.authorize(['administrator', 'contributor']) @restrict('POST') @validate(schema=<API key>(), form='associate') def link(self, id): """Associate BLD Collection with id=id to a BLD File. The ID of the File is passed via a POST form. This "ID" may in fact be a comma-separated list of File IDs.""" # Get the Form if id is None: abort(404) collection = meta.Session.query(model.Collection).get(int(id)) if collection is None: abort(404) # Get the File(s) fileID = self.form_result['fileID'] patt = re.compile('^[0-9 ]+$') fileIDs = [ID.strip().replace(' ', '') for ID in fileID.split(',') if patt.match(ID)] file_q = meta.Session.query(model.File) filterString = 'or_(' + ', '.join(['model.File.id==%s' % ID for ID in fileIDs]) + ')' filterString = 'file_q.filter(%s)' % filterString cmd = "file_q = eval('%s' % filterString)" exec(cmd) files = file_q.all() if files: for file in files: if file in collection.files: if 'flash' in session: session['flash'] += 'File %s is already associated to Collection %s ' % (file.id, collection.id) else: session['flash'] = 'File %s is already associated to Collection %s ' % (file.id, collection.id) else: collection.files.append(file) meta.Session.commit() session.save() else: session['flash'] = u'Sorry, no Files have any of the following IDs: %s' % fileID session.save() return redirect(url(controller='collection', action='view', id=collection.id)) @h.authenticate @h.authorize(['administrator', 'contributor']) def disassociate(self, id, otherID): """Disassociate BLD Collection id from BLD File otherID. """ if id is None or otherID is None: abort(404) collection = meta.Session.query(model.Collection).get(int(id)) file = meta.Session.query(model.File).get(int(otherID)) if file is None: if collection is None: abort(404) else: session['flash'] = 'There is no File with ID %s' % otherID if file in collection.files: collection.files.remove(file) meta.Session.commit() session['flash'] = 'File %s disassociated' % otherID else: session['flash'] = 'Collection %s was never associated to File %s' % (id, otherID) session.save() redirect(url(controller='collection', action='view', id=id)) @h.authenticate def export(self, id=None): return 'NO COLLECTION EXPORT YET' def redirectfromurl(self, URL=None): """This method catches all urls that are not caught by the Routes in config/routing.py. It then searches through the Collections for a Collection.url=url match and returns the appropriate Collection or an error page. """ collection = meta.Session.query(model.Collection).filter_by( url=URL).first() if collection: #redirect(url( # controller='collection', action='view', id=collection.id) return self.view(collection.id) else: abort(404)
/* Written by James Youngman <jay@gnu.org>. */ #if !defined BUGREPORTS_H # define BUGREPORTS_H # include <stdio.h> /* Interpreetation of the return code is as for fprintf. */ int <API key> (FILE *f, const char *program_name); #endif
package helper.Entity; import org.apache.http.Header; import org.apache.http.HttpEntity; import java.io.<API key>; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Random; public class MultipartEntity implements HttpEntity { private final static char[] MULTIPART_CHARS = "-<API key>".toCharArray(); private final String NEW_LINE_STR = "\r\n"; private final String CONTENT_TYPE = "Content-Type: "; private final String CONTENT_DISPOSITION = "Content-Disposition: "; private final String TYPE_TEXT_CHARSET = "text/plain; charset=UTF-8"; private final String TYPE_OCTET_STREAM = "application/octet-stream"; private final byte[] BINARY_ENCODING = "<API key>: binary\r\n\r\n".getBytes(); private final byte[] BIT_ENCODING = "<API key>: 8bit\r\n\r\n".getBytes(); private String mBoundary = null; <API key> mOutputStream = new <API key>(); public MultipartEntity() { this.mBoundary = generateBoundary(); } private final String generateBoundary() { StringBuilder sb = new StringBuilder(); Random random = new Random(); for (int i = 0 ;i<30;i++){ sb.append(MULTIPART_CHARS[random.nextInt(MULTIPART_CHARS.length)]); } return sb.toString(); } private void writeFirstBoundary() { } public void addStringPart(final String paramName, final String value) { } public void writeToOutputStream(String paramName, byte[] rawData, String type, byte[] encodingBytes, String fileName) { } public void addBinaryPart(String paranName,final byte[] rawData){ } public void addFilePart(final String key,final File file){ } private void closeSilently(Closeable closeable){ } private byte[] <API key>(String paramName,String fileName){ } @Override public boolean isRepeatable() { return false; } @Override public boolean isChunked() { return false; } @Override public long getContentLength() { return 0; } @Override public Header getContentType() { return null; } @Override public Header getContentEncoding() { return null; } @Override public InputStream getContent() throws IOException, <API key> { return null; } @Override public void writeTo(OutputStream outputStream) throws IOException { } @Override public boolean isStreaming() { return false; } @Override public void consumeContent() throws IOException { } }
Pacman === Pacman COSC2451 Programming Techniques Copyright 2014 Ly Quoc Hung (s3426511), Ly Quan Liem (s3426110), Nguyen Vinh Linh (s3410595), Doan Hai Dang (s3425475) RMIT International University Vietnam This assignment includes software developed by the above mentioned students. Assignment description: The classic Pacman game based on the one made by Namco in 1980 with level editor and individual AI for each of the 4 ghosts. This program is the assignment for "Programming Techniques" course (COSC2451) at RMIT International University Vietnam. 2. Game features a. Players can choose the difficulty of game, the higher difficulty, the faster game is, and also, the more intelligent ghosts are. b. This game has high score broad which will save ten highest scores and player names. c. Because of the difficulty of this game, we also offer cheat codes for gamers. There are two cheat codes, first is for god mode, second is for live cheat code: + god mode: UP UP DOWN DOWN LEFT RIGHT LEFT RIGHT b a + extra lifes: UP UP DOWN DOWN LEFT LEFT RIGHT RIGHT LEFT RIGHT d. During gameplay, you can pause game by pressing "ESC" e. After pausing game, you can resume game, save game or load game. NOTE: It seems that the program may display the map incorrectly sometimes. This program can simply fixed by quit game and restart. Pause game may even solve this program. Dang's ghost does not have proper memory allocation which may cause memory leak sometimes. It also seems to cause segmentation fault and crash the program. Linh's ghost seldom access unexist variable (using valgrind to check). However, this problem is not critical and does not crash the program 3. Map editor The program use a command line interface to display the current loaded map on the screen. The program ad two mode: edit mode and command mode: Edit mode: In this mode user can move around the map the create by default or by command and edit the current character at the cursor with: q/Q: add an upper left corner character e/E: add an upper right corner character z/Z: add a lower left corner character c/C: add a lower right corner character w/x: add a vertical bar character a/d: add a horizontal bar character s: add a small pellet character S: add a power pellet character f/F: add a fruit spawn point character g/G: add a ghost spawn point character p/P: add a pacman spawn point character ' ' (space): erase the current character Additionally, user can switch from edit mode to command mode by pressing ":" (colon) key. All the above command will take effect immediately after the respect key is pressed. Command mode: This mode provide user with an vi/vim like command mode to manipulate the map file. The command for this mode are: w [filename]: save the current loaded map with the file name specify in the [filename] field. Note: This command will check if the end of the [filename] is ended with ".pac" or not. If [filename] end with ".pac" then it will use this file name, otherwise ".pac" will be automatically added to the end of [filename]. This command will overridden any file that already exist on the disk with the same file name after appending the ".pac". w: save the current loaded map with the file name specify in the "Map file name" field on the screen. Regarding the file name, this command will treat it the same way as the "w [filename]" command. q: quit the program without saving any change made. wq [filename]: quit the program saving all change in the file with the file name specify in the [filename] field. Regarding the file name, this command will treat it the same way as the "w [filename]" command. wq: quit the program saving all change in the file with the file name specify in the "Map file name" field on the screen. Regarding the file name, this command will treat it the same way as the "w [filename]" command. r [filename]: read a map in the "levels" directory with the name specify in the [filename]. This command will return an error if no such file with [filename] found in the directory. This command will read the file with the exact name provided with or without ".pac". E.g.: it will read the file "example" instead of "example.pac". n [filename] [row] [col]: create a new map with file name specify in [filename] and with size specify in the [row] and [col]. This command will return an error if not enough arguments are provided or there is an error in the argument. The size limit of the map will be dynamic and based on the current size of the program terminal. a [author(s)]: modify the author of the current loaded map. The author is displayed in the "Author" field on the screen and will saved in the map file. The author must had the format [name] <[email]>, there can be many authors but each author must have the above format and separate by a ',' (comma). t [maptittle]: modify the tittle of the current loaded map. The tittle is displayed in the "Map tittle" field on the screen and will be saved in the map file. auto: automatically add small pellet character to all the possible place where a pacman can reach based on the pacman spawn point. This function only work if there is at least 1 pacman spawn point (p/P in edit mode) on the map and it will based on that spawn point. If there are more than one spawn points then the first one (if you read the map from left to right and top to bottom) will be used. All the above command only work after hitting "Enter" button. User can exit command mode any time by pressing "Escape" key and it will work immediately. NOTE: If you maximize the program window (using the maximize window button) and then create a map that fit the size of the window (number of row larger that 22 and number of column larger than 64) and then restore the window to its original size (using minimize button) then the map will not display correctly. Its is recommended to not switch to maximize and minimize continuously, you should choose only one window size (maximize or normal) and stck with it. There is a case of where our program can read other people map and save it normally but other people while they CAN read map produced by our program but their program will crash (segmentation fault) while attempting to save the map although there is no change made. Their program can read and write other people map normally though. More detail of the problem: People can read map file produced by our program normally without any problem. If they try to write that file back to disk with the same or different name their program will crash giving "segmentation fault" error. Our program can read map file produced by others programs and it can save the file normally. If we open a map file that produced by others programs and that file is working correctly (no crash while saving), if we save that file without doing any modification to the file then the problem appear on the others programs. There is no difference in the file as we can tell while open by a text editor and while checking the file using a program that compare the original and newly saved file in binary mode (compare the bits). We suspect that our program had written some strange characters in the file but our write function only write character in the array, integer for map height and width and "\n" character so we have yet to find out the cause of the problem. Third party resources: NCURSES This software uses the NCURSES library package, which is under MIT License. This package can be redistributed free of charge in any forms. Some methods implemented in the program are found on: http://stackoverflow.com/questions/4770985/<API key> http://stackoverflow.com/questions/744766/<API key> http://en.chys.info/2009/09/esdelay-ncurses/ http://stackoverflow.com/questions/4204666/<API key> http://rosettacode.org/wiki/Dijkstra's_algorithm http://stackoverflow.com/questions/1910724/<API key> http://web.mit.edu/eranki/www/tutorials/search/
package main import ( "context" "fmt" "github.com/pharosnet/logs" "runtime" "time" ) func main() { runtime.GOMAXPROCS(8) logs.DefaultLog().Infof("some info %v", time.Now()) logs.DefaultLog().Debugf("some debug %v", time.Now()) logs.DefaultLog().Warnf("some warn %v", time.Now()) logs.DefaultLog().Errorf("some error %v", time.Now()) fmt.Println("close", logs.DefaultLog().Close(context.Background())) }
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class <API key> : resStreamedResource { [Ordinal(1)] [RED("neighborGroups")] public CArray<CArray<CUInt16>> NeighborGroups { get; set; } public <API key>(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
<?php return array( 'user1' => array( 'id' => '1', 'username' => 'user1', 'first_name' => 'firstname1', 'last_name' => 'lastname1', 'email' => 'user1@mail.ru', // $password = 'qwertyu'; 'password' => 'pbkdf2_sha256$10000$VnMBMpzVtq39$/<API key>+uoGA5nFisfZPcvUJw=', 'is_active' => '1', 'last_login' => '2013-01-14 11:41:06', 'date_joined' => '2012-06-30 00:35:47', ), 'user2' => array('id' => '2','username' => 'user2','first_name' => 'Тестовый юзер','last_name' => '','email' => 'user2@mail.ru','password' => 'pbkdf2_sha256$10000$VnMBMpzVtq39$/<API key>+uoGA5nFisfZPcvUJw=','is_active' => '1','last_login' => '2013-05-17 11:03:15','date_joined' => '2013-05-17 11:03:15') );
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0) on Sat Jul 30 16:24:39 CEST 2011 --> <title>Uses of Class ch.intertec.storybook.jasper.ExportReport</title> <meta name="date" content="2011-07-30"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class ch.intertec.storybook.jasper.ExportReport"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?ch/intertec/storybook/jasper//<API key>.html" target="_top">Frames</a></li> <li><a href="ExportReport.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class ch.intertec.storybook.jasper.ExportReport" class="title">Uses of Class<br>ch.intertec.storybook.jasper.ExportReport</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#ch.intertec.storybook.jasper">ch.intertec.storybook.jasper</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="ch.intertec.storybook.jasper"> </a> <h3>Uses of <a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a> in <a href="../../../../../ch/intertec/storybook/jasper/package-summary.html">ch.intertec.storybook.jasper</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../ch/intertec/storybook/jasper/package-summary.html">ch.intertec.storybook.jasper</a> that return types with arguments of type <a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a>&gt;</code></td> <td class="colLast"><span class="strong">ExportManager.</span><code><strong><a href="../../../../../ch/intertec/storybook/jasper/ExportManager.html#getReportList()">getReportList</a></strong>()</code> <div class="block">Returns all of the loaded reports.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a>&gt;</code></td> <td class="colLast"><span class="strong">ConfigLoader.</span><code><strong><a href="../../../../../ch/intertec/storybook/jasper/ConfigLoader.html#getReports()">getReports</a></strong>()</code> <div class="block">Returns all of the <a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper"><code>ExportReport</code></a> objects defined.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../ch/intertec/storybook/jasper/package-summary.html">ch.intertec.storybook.jasper</a> with parameters of type <a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static java.lang.String</code></td> <td class="colLast"><span class="strong">ExportManager.</span><code><strong><a href="../../../../../ch/intertec/storybook/jasper/ExportManager.html#export(java.lang.String, ch.intertec.storybook.jasper.ExportReport)">export</a></strong>(java.lang.String&nbsp;key, <a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a>&nbsp;er)</code> <div class="block">Exports the report into the given place in the given format.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><span class="strong">ExportManager.</span><code><strong><a href="../../../../../ch/intertec/storybook/jasper/ExportManager.html#fillReport(ch.intertec.storybook.jasper.ExportReport)">fillReport</a></strong>(<a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">ExportReport</a>&nbsp;er)</code> <div class="block">Runs the requested report through Jasper.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../ch/intertec/storybook/jasper/ExportReport.html" title="class in ch.intertec.storybook.jasper">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?ch/intertec/storybook/jasper//<API key>.html" target="_top">Frames</a></li> <li><a href="ExportReport.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> </body> </html>
// File: debugoff.hpp // #pragma once #undef Verify #undef Warn #undef Check_Signature #undef Check_Pointer #undef Mem_Copy #undef Str_Copy #undef Str_Cat #undef Check #undef Cast_Pointer #undef Cast_Object #undef Spew #undef USE_TIME_ANALYSIS // trace time statistics #undef USE_TRACE_LOG // logging functions #undef <API key> // event statistics #if defined(LAB_ONLY) && !defined(NO_ANALYSIS) #define USE_TIME_ANALYSIS #define USE_TRACE_LOG #define <API key> #endif #define Verify(c) ((void)0) #define Warn(c) ((void)0) #define Check_Pointer(p) ((void)0) #define Mem_Copy(destination, source, length, available)\ memcpy(destination, source, length) #define Str_Copy(destination, source, available)\ strcpy(destination, source) #define Str_Cat(destination, source, available)\ strcat(destination, source) #define Check_Object(p) ((void)0) #define Check_Signature(p) ((void)0) #define Cast_Pointer(type, ptr) reinterpret_cast<type>(ptr) #define Cast_Object(type, ptr) static_cast<type>(ptr) #define Spew(x,y) ((void)0)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Class: Notification</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif] <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Class: Notification</h1> <section> <header> <h2> Notification </h2> </header> <article> <div class="container-overview"> <dt> <h4 class="name" id="Notification"><span class="type-signature"></span>new Notification<span class="signature">(opts<span class="<API key>">opt</span>)</span><span class="type-signature"></span></h4> </dt> <dd> <div class="description"> Notification </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Attributes</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>opts</code></td> <td class="type"> <span class="param-type">Object</span> </td> <td class="attributes"> &lt;optional><br> </td> <td class="description last"></td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="notification.js.html">notification.js</a>, <a href="notification.js.html#line11">line 11</a> </li></ul></dd> </dl> </dd> </div> <h3 class="subsection-title">Members</h3> <dl> <dt> <h4 class="name" id="inspect"><span class="type-signature"></span>inspect<span class="type-signature"></span></h4> </dt> <dd> <div class="description"> Get the Notification JSON Object </div> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"><ul class="dummy"><li> <a href="notification.js.html">notification.js</a>, <a href="notification.js.html#line31">line 31</a> </li></ul></dd> </dl> </dd> </dl> </article> </section> </div> <nav> <h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="Action.html">Action</a></li><li><a href="Layout.html">Layout</a></li><li><a href="Notification.html">Notification</a></li><li><a href="Pin.html">Pin</a></li><li><a href="Reminder.html">Reminder</a></li><li><a href="Timeline.html">Timeline</a></li></ul><h3><a href="global.html">Global</a></h3> </nav> <br clear="both"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.0-alpha9</a> on Thu Mar 19 2015 12:49:52 GMT-0700 (PDT) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>
package org.uag.netsim.core.device; import java.io.Serializable; public interface <API key> extends Runnable,Serializable { }
#!/usr/bin/env python import os, sys from Bio import SeqIO from Bio.Blast import NCBIWWW from time import sleep from helpers import parse_fasta, get_opts def usage(): print """Usage: blast_fasta.py [OPTIONS] seqs.fasta Options: -t blast_type blastn, blastp, blastx, tblastn, tblastx, default: blastn -o out_dir output directory, default: current directory -p out_prefix prefix for output file names, default: blast_ """ def run_blast(seq, blast_type='blastn'): delay = 2 while True: try: result = NCBIWWW.qblast(blast_type, 'nr', seq.format('fasta')).getvalue() sleep(delay) return result except urllib2.HTTPError: # something went wrong, increase delay and try again delay *= 2 if __name__=='__main__': try: opts = get_opts(sys.argv[1:], 't:o:p:') fasta_path = opts[1][0] opts = dict(opts[0]) except: usage() exit(1) blast_type = opts.get('-t', 'blastn') out_dir = opts.get('-o', os.getcwd()) out_prefix = opts.get('-p', 'blast_') seqs = parse_fasta(fasta_path) if not os.path.exists(out_dir): os.makedirs(out_dir) for seq in seqs: print 'Running BLAST for ' + seq.id + '... ', blast_xml_str = run_blast(seq, blast_type) with open(os.path.join(out_dir, out_prefix + seq.id + '.xml'), 'w') as f: f.write(blast_xml_str) print 'completed'
import Ember from 'ember'; export default Ember.View.extend({ classNames:['container'] });
package org.hsh.bfr.db.gui.dbtable.sorter; import java.util.Comparator; /** * @author Armin * */ public class MyStringSorter implements Comparator<String> { @Override public int compare(String o1, String o2) { //System.out.println("MyStringSorter"); if (o1 == null && o2 == null) return 0; else if (o1 == null) return 1; else if (o2 == null) return -1; else return o1.trim().compareToIgnoreCase(o2.trim()); } }
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #define bufsize 32768 char buf[bufsize]; void error(char *s, int e); int main(argc,argv) int argc; char **argv; { int s; int i; int e; struct sockaddr_in addr; int fdmask; struct timeval tv; int addrsize = sizeof(struct sockaddr_in); char *hostname = "nick"; struct hostent *h; int total; if( argc > 1 ) hostname = argv[1]; s = socket(AF_INET,SOCK_STREAM,0); if( s < 0 ) error("socket",s); h = gethostbyname(hostname); addr.sin_family = AF_INET; addr.sin_port = htons(1235); addr.sin_addr.s_addr = *(u_long *)h->h_addr; e = connect(s,&addr,addrsize); if( e < 0 ) error("connect",e); for( i = 0; i < bufsize; i++ ) buf[i] = i&0xff; e = bufsize; setsockopt(s,SOL_SOCKET,SO_SNDBUF,&e,4); Delay(1000000); while( (e = write(s,buf,bufsize)) > 0) { total += e; if( (total % (1024*1024)) == 0 ) IOdebug("TX %d",total); } /* e = write(s,buf,bufsize); IOdebug("TX %d",e); */ if( e < 0 ) error("write",e); close(s); } void error(char *s, int e) { printf("TX error %s: %d %d %x\n",s,e,errno,oserr); exit(1); }
package org.parsers.commons; public interface GlobalConstants { String EMPTY_TEXT = ""; }
#ifndef ATTITUDE_PID_H_ #define ATTITUDE_PID_H_ /* STL Headers */ #include <string> /* Boost Headers */ #include <boost/thread.hpp> #include <boost/math/constants/constants.hpp> #include <boost/numeric/ublas/vector.hpp> namespace blas = boost::numeric::ublas; /* Project Headers */ #include "Parameter.h" #include "pid_channel.h" #include "ControllerInterface.h" /** * @brief track pilot reference attitude * This class computes control signals using PID to track the pilot stick reference. * The angular velocity reference is assumed to be zero. * @author Bryan Godbolt <godbolt@ece.ualberta.ca> * @date October 26, 2011 * @date February 10, 2012: Refactored into separate file and cleaned up */ class attitude_pid : public ControllerInterface { public: attitude_pid(); attitude_pid(const attitude_pid& other); /** * @brief Performs the control computation. The control attempts to * regulate the reference orientation with zero angular velocity. * @param reference roll pitch reference values in radians. */ void operator()(const blas::vector<double>& reference) throw(bad_control); threadsafe get control_effort inline blas::vector<double> get_control_effort() const {boost::mutex::scoped_lock lock(control_effort_lock); return control_effort;} reset the integrator error states void reset(); /** * Return a list of parameters for transmission to QGC. These parameters are only the ones * specific to this controller. */ std::vector<Parameter> getParameters(); /* Define some constants for parameter names */ static const std::string PARAM_ROLL_KP; static const std::string PARAM_ROLL_KD; static const std::string PARAM_ROLL_KI; static const std::string PARAM_PITCH_KP; static const std::string PARAM_PITCH_KD; static const std::string PARAM_PITCH_KI; static const std::string PARAM_ROLL_TRIM; static const std::string PARAM_PITCH_TRIM; /** Set the roll channel proportional gain * @param kp new proportional gain value * This function is threadsafe. */ void <API key>(double kp); /** set the roll channel derivative gain * @param kd new derivative gain value * This function is threadsafe. */ void set_roll_derivative(double kd); /** set the roll channel integral gain * @param ki new integral channel gain value * This function is threadsafe. */ void set_roll_integral(double ki); /** Set the pitch channel proportional gain * @param kp new proportional gain value * This function is threadsafe. */ void <API key>(double kp); /** Set the pitch channel derivative gain * @param kd new derivative gain value * This function is threadsafe. */ void <API key>(double kd); /** * Set the pitch channel integral gain * @param ki new integral gain value * This function is threadsafe. */ void set_pitch_integral(double ki); /** * Outputs the controller parameters as an xml tree * @param doc xml document in which to allocate the memory * @returns pointer to xml node which contatins pid params */ rapidxml::xml_node<>* get_xml_node(rapidxml::xml_document<>& doc); /** * Parses a pid parameter xml tree * @param pid_params pointer to root of pid params xml tree */ void parse_pid(rapidxml::xml_node<> *pid_params); /** set the roll trim point. threadsafe * @param trim roll trim in radians */ inline void <API key>(double trim) {boost::mutex::scoped_lock lock(roll_trim_lock); roll_trim = trim;} /** get the roll trim point. threadsafe * @returns roll trim in radians */ inline double <API key>() {boost::mutex::scoped_lock lock(roll_trim_lock); return roll_trim;} /** set the roll trim point. threadsafe * @param trim roll trim in degrees */ void <API key>(double trim_degrees); /** get the roll trim point. threadsafe * @returns roll trim in degress */ inline double <API key>() {boost::mutex::scoped_lock lock(roll_trim_lock); return roll_trim * 180 / boost::math::constants::pi<double>();} /** set the pitch trim point. threadsafe * @param trim pitch trim in radians */ inline void <API key>(double trim) {boost::mutex::scoped_lock lock(pitch_trim_lock); pitch_trim = trim;} /** get the pitch trim point. threadsafe * @returns pitch trim in radians */ inline double <API key>() {boost::mutex::scoped_lock lock(pitch_trim_lock); return pitch_trim;} /** set the pitch trim point. threadsafe * @param trim pitch trim in degrees */ void <API key>(double trim_degrees); /** get the pitch trim point. threadsafe * @returns pitch trim in degress */ inline double <API key>() {boost::mutex::scoped_lock lock(pitch_trim_lock); return pitch_trim * 180 / boost::math::constants::pi<double>();} threadsafe get runnable inline bool runnable() const {return _runnable;} private: pid_channel roll; mutable boost::mutex roll_lock; pid_channel pitch; mutable boost::mutex pitch_lock; store the current normalized servo commands blas::vector<double> control_effort; serialize access to control_effort mutable boost::mutex control_effort_lock; threadsafe set control_effort inline void set_control_effort(const blas::vector<double>& control_effort) {boost::mutex::scoped_lock lock(control_effort_lock); this->control_effort = control_effort;} trim point regulated by the controller. it is stored in radians double roll_trim; serialize access to roll_trim boost::mutex roll_trim_lock; trim point regulated by the control. stored in radians double pitch_trim; serialize access to pitch_trim boost::mutex pitch_trim_lock; is this controller runnable? bool _runnable; serialize access to runnable mutable boost::mutex runnable_lock; threadsafe clear _runnable inline void clear_runnable() {boost::mutex::scoped_lock lock(runnable_lock); _runnable = false;} threadsafe _runnable inline void set_runnable() {boost::mutex::scoped_lock lock(runnable_lock); _runnable = true;} }; #endif
package app.niklascarlsson.cv; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class AboutFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_about, container, false); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setText(); } public void setText() { TextView view = (TextView) getView().findViewById(R.id.textViewAbout); view.setText("Min vision är att vara en positiv kraft för mina medmänniskor. Att stå på de svagas sida och värna om väl människor som miljön."); } }
// C++ standard includes // Falltergeist includes #include "../../Logger.h" #include "../../VM/Handlers/Opcode814CHandler.h" #include "../../VM/VM.h" #include "../../Game/Game.h" #include "../../State/Location.h" #include "../../PathFinding/HexagonGrid.h" #include "../../PathFinding/Hexagon.h" // Third party includes namespace Falltergeist { Opcode814CHandler::Opcode814CHandler(VM* vm) : OpcodeHandler(vm) { } void Opcode814CHandler::_run() { Logger::debug("SCRIPT") << "[814C] [=] int rotation_to_tile(int srcTile, int destTile)" << std::endl; // TODO: error checking auto to_index = _vm->dataStack()->popInteger(); auto from_index =_vm->dataStack()->popInteger(); auto grid = Game::getInstance()->locationState()->hexagonGrid(); auto from_hex = grid->at(from_index); auto to_hex = grid->at(to_index); auto rotation = from_hex->orientationTo(to_hex); _vm->dataStack()->push(rotation); } }
<?php # proNET Online-Tool # The following tool can help you make sense of the knowledge, skills and competences developed during your university study # and help you decide about your further educational path. # Rollnerstr. 14, 90408 Nuremberg, Germany # This file is part of proNET Online-Tool. # proNET Online-Tool is free software: you can redistribute it and/or modify # (at your option) any later version. # proNET Online-Tool is distributed in the hope that it will be useful, # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /** * @filesource: src/AppBundle/Repository/<API key>.php */ namespace AppBundle\Repository; class <API key> extends \Doctrine\ORM\EntityRepository { public function getResultByUser($user) { $em = $this->getEntityManager(); $query = $em->createQuery('SELECT ahe FROM AppBundle:<API key> ahe WHERE ahe.user='.$user->getId()); $result = $query->getArrayResult(); $sum = 0; foreach($result[0] as $k=>$v) { if($k!='id') { $sum += $v; } } return $sum; } public function <API key>($userId) { $em = $this->getEntityManager(); $sql = $em->getConnection()->prepare('SHOW COLUMNS FROM <API key>'); $sql->execute(); $columns = $sql->fetchAll(); $count = 0; $arr = array(); foreach($columns as $k=>$v) { if($v['Field']!='id' AND $v['Field']!='user_id') { $query = $em->getConnection()->prepare('SELECT ' .$v['Field']. ' as value FROM <API key> WHERE user_id='.$userId); $query->execute(); $val = $query->fetchAll(); if($val!=null AND $val[0]['value'] != null) { $arr[$count++] = $val[0]['value']; } } } $anzahl = count($arr); return $anzahl;; } }
package dk.itu.eyedroid.io.protocols; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import dk.itu.eyedroid.Constants; import dk.itu.eyedroid.io.NetClientConfig; import dk.itu.spcl.jlpf.common.Bundle; import dk.itu.spcl.jlpf.io.IOProtocolWriter; /** * Generic TCP/IP output protocol implementation. Used to send processed bundle * results to a connected client. Sends X and Y gaze position coordinates as * result. */ public class OutputTCPNet implements IOProtocolWriter { private final int mPort; // Server port private ServerSocket serverSocket; // Server socket for new incomming connections private Socket mSocket; // Client socket private OutputStream mOutput; // Spcket output stream private AtomicBoolean isConnectionSet; // Client connection status private boolean <API key>; // Server waiting for client status private boolean <API key>; // Server socket was intentionally closed. private static final int <API key> = 10; /** * Deafult constructor * * @param port * Server listener port */ public OutputTCPNet(int port) { mPort = port; isConnectionSet = new AtomicBoolean(); isConnectionSet.set(false); } /** * Initialize server and wait for incoming connections. When a client * connects, close server socket. If non-intentional error ocurrs, throw it * to a higher level. */ @Override public void init() throws IOException { try { if (!<API key> && !isConnectionSet.get()) { <API key> = true; serverSocket = new ServerSocket(mPort); serverSocket.setSoTimeout(<API key>); } } catch (IOException e) { <API key> = false; isConnectionSet.set(false); if (!<API key>) throw e; else <API key> = false; } } private void acceptClient() { try { mSocket = serverSocket.accept(); mOutput = mSocket.getOutputStream(); serverSocket.close(); <API key> = false; isConnectionSet.set(true); } catch (IOException e) { // do nothing will be handled from cleanup } } /** * Send result to client. In case of error throw an exception in order to * restart the protocol. */ @Override public void write(Bundle bundle) throws IOException { if (bundle != null && isConnectionSet.get()) { int x = (Integer) bundle.get(Constants.PUPIL_COORDINATES_X); int y = (Integer) bundle.get(Constants.PUPIL_COORDINATES_Y); if (x != -1 && y != -1) { byte[] output = generateOutput(x, y); synchronized (mSocket) { mOutput.write(output); mOutput.flush(); } } } else { init(); acceptClient(); } bundle = null; } /** * Close server and connected client socket in case they are open. */ @Override public void cleanup() { isConnectionSet.set(false); try { if (serverSocket != null) { if (!serverSocket.isClosed()) { <API key> = true; serverSocket.close(); } } if (mSocket != null) { synchronized (mSocket) { if (!mSocket.isClosed()) { mSocket.close(); } } } } catch (IOException e) { e.printStackTrace(); } } /** * Create byte[] output containing the gaze position coordinates. * @param x X coordinate * @param y Y coordinate * @return Byte array. */ private byte[] generateOutput(int x, int y) { ByteBuffer b = ByteBuffer.allocate(NetClientConfig.MSG_SIZE); if (NetClientConfig.USE_HMGT) b.putInt(0, NetClientConfig.TO_CLIENT_GAZE_HMGT); else b.putInt(0, NetClientConfig.TO_CLIENT_GAZE_RGT); b.putInt(4, x); b.putInt(8, y); return b.array(); } }
; ; sprintf ; ; Copyright (c) 2017, Cytlan, Shibesoft AS ; ; This is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http: ; ; .autoimport on .include "macros.inc" .include "memory.asm" .segment "CODE" .export sprintf ; ; fmt string pointer in lptr1 ; destination pointer in lptr2 ; Arguments pushed to stack. ; .proc sprintf ; Local aliases FMT=lptr1 DEST=lptr2 DP=lptr3 RETADDR=ptr1 INDEX_8 ACC_16 pla sta RETADDR ACC_8 @loop: lda [FMT] beq @loopend ; If we hit a null-terminator, end the loop cmp beq @mode ; Not a control code, copy as-is @copychar: sta [DEST] ACC_16 inc FMT inc DEST ACC_8 jmp @loop @mode: ACC_16 inc FMT ACC_8 jmp @modeloop ; ; Mode decoding ; @modeloop: lda [FMT] cmp beq @modestring cmp beq @modepercent ;cmp ;beq @modehexlow ; Nothing matches, jump out @modeend: ACC_16 inc FMT ACC_8 jmp @loop ; ; %x mode ; @modehexlow: ; Fetch value ;pla ;clc ;sbc ;tax ;lda str_hex_upper,x ;sta [DEST] sta DP+2 ACC_16 pla sta DP ; ; %% mode ; @modepercent: sta [DEST] ACC_16 inc DEST ACC_8 jmp @modeend ; ; %s mode ; @modestring: ; Fetch string pointer ACC_8 pla sta DP+2 ACC_16 pla sta DP @modestringloop: lda [DP] beq @modeend sta [DEST] ACC_16 inc DP inc DEST ACC_8 jmp @modestringloop @loopend: lda sta [FMT] ACC_16 lda RETADDR pha rts .endproc
// C++ standard includes // Falltergeist includes #include "MiscObject.h" // Third party includes namespace Falltergeist { namespace Game { GameMiscObject::GameMiscObject() : GameObject() { _type = TYPE_MISC; } GameMiscObject::~GameMiscObject() { } } }
#ifndef NATS_H_ #define NATS_H_ #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <inttypes.h> #include <stdio.h> #include "status.h" #include "version.h" /** \def NATS_EXTERN * \brief Needed for shared library. * * Based on the platform this is compiled on, it will resolve to * the appropriate instruction so that objects are properly exported * when building the shared library. */ #if defined(_WIN32) #include <winsock2.h> #if defined(nats_EXPORTS) #define NATS_EXTERN __declspec(dllexport) #elif defined(nats_IMPORTS) #define NATS_EXTERN __declspec(dllimport) #else #define NATS_EXTERN #endif typedef SOCKET natsSock; #else #define NATS_EXTERN typedef int natsSock; #endif #ifdef __cplusplus extern "C" { #endif /** \brief The default `NATS Server` URL. * * This is the default URL a `NATS Server`, running with default listen * port, can be reached at. */ #define NATS_DEFAULT_URL "nats://localhost:4222" // Types. /** \defgroup typesGroup Types * * NATS Types. * @{ */ /** \brief A connection to a `NATS Server`. * * A #natsConnection represents a bare connection to a `NATS Server`. It will * send and receive byte array payloads. */ typedef struct __natsConnection natsConnection; /** \brief Statistics of a #natsConnection * * Tracks various statistics received and sent on a connection, * including counts for messages and bytes. */ typedef struct __natsStatistics natsStatistics; /** \brief Interest on a given subject. * * A #natsSubscription represents interest in a given subject. */ typedef struct __natsSubscription natsSubscription; /** \brief A structure holding a subject, optional reply and payload. * * #natsMsg is a structure used by Subscribers and * #<API key>(). */ typedef struct __natsMsg natsMsg; /** \brief Way to configure a #natsConnection. * * Options can be used to create a customized #natsConnection. */ typedef struct __natsOptions natsOptions; /** \brief Unique subject often used for point-to-point communication. * * This can be used as the reply for a request. Inboxes are meant to be * unique so that replies can be sent to a specific subscriber. That * being said, inboxes can be shared across multiple subscribers if * desired. */ typedef char natsInbox; // end of typesGroup // Callbacks. /** \defgroup callbacksGroup Callbacks * * NATS Callbacks. * @{ */ /** \brief Callback used to deliver messages to the application. * * This is the callback that one provides when creating an asynchronous * subscription. The library will invoke this callback for each message * arriving through the subscription's connection. * * @see <API key>() * @see <API key>() */ typedef void (*natsMsgHandler)( natsConnection *nc, natsSubscription *sub, natsMsg *msg, void *closure); /** \brief Callback used to notify the user of asynchronous connection events. * * This callback is used for asynchronous events such as disconnected * and closed connections. * * @see <API key>() * @see <API key>() * @see <API key>() * * \warning Such callback is invoked from a dedicated thread and the state * of the connection that triggered the event may have changed since * that event was generated. */ typedef void (*<API key>)( natsConnection *nc, void *closure); /** \brief Callback used to notify the user of errors encountered while processing * inbound messages. * * This callback is used to process asynchronous errors encountered while processing * inbound messages, such as #NATS_SLOW_CONSUMER. */ typedef void (*natsErrHandler)( natsConnection *nc, natsSubscription *subscription, natsStatus err, void *closure); /** \brief Attach this connection to the external event loop. * * After a connection has (re)connected, this callback is invoked. It should * perform the necessary work to start polling the given socket for READ events. * * @param userData location where the adapter implementation will store the * object it created and that will later be passed to all other callbacks. If * `*userData` is not `NULL`, this means that this is a reconnect event. * @param loop the event loop (as a generic void*) this connection is being * attached to. * @param nc the connection being attached to the event loop. * @param socket the socket to poll for read/write events. */ typedef natsStatus (*natsEvLoop_Attach)( void **userData, void *loop, natsConnection *nc, int socket); /** \brief Read event needs to be added or removed. * * The `NATS` library will invoked this callback to indicate if the event * loop should start (`add is `true`) or stop (`add` is `false`) polling * for read events on the socket. * * @param userData the pointer to an user object created in #natsEvLoop_Attach. * @param add `true` if the event library should start polling, `false` otherwise. */ typedef natsStatus (*<API key>)( void *userData, bool add); /** \brief Write event needs to be added or removed. * * The `NATS` library will invoked this callback to indicate if the event * loop should start (`add is `true`) or stop (`add` is `false`) polling * for write events on the socket. * * @param userData the pointer to an user object created in #natsEvLoop_Attach. * @param add `true` if the event library should start polling, `false` otherwise. */ typedef natsStatus (*<API key>)( void *userData, bool add); /** \brief Detach from the event loop. * * The `NATS` library will invoked this callback to indicate that the connection * no longer needs to be attached to the event loop. User can cleanup some state. * * @param userData the pointer to an user object created in #natsEvLoop_Attach. */ typedef natsStatus (*natsEvLoop_Detach)( void *userData); // end of callbacksGroup // Functions. /** \defgroup funcGroup Functions * * NATS Functions. * @{ */ /** \defgroup libraryGroup Library * * Library and helper functions. * @{ */ /** \brief Initializes the library. * * This initializes the library. * * It is invoked automatically when creating a connection, using a default * spin count. However, you can call this explicitly before creating the very * first connection in order for your chosen spin count to take effect. * * @param lockSpinCount The number of times the library will spin trying to * lock a mutex object. */ NATS_EXTERN natsStatus nats_Open(int64_t lockSpinCount); /** \brief Returns the Library's version * * Returns the version of the library your application is linked with. */ NATS_EXTERN const char* nats_GetVersion(void); /** \brief Returns the Library's version as a number. * * The version is returned as an hexadecimal number. For instance, if the * string version is "1.2.3", the value returned will be: * * > 0x010203 */ NATS_EXTERN uint32_t <API key>(void); #ifdef BUILD_IN_DOXYGEN /** \brief Check that the header is compatible with the library. * * The version of the header you used to compile your application may be * incompatible with the library the application is linked with. * * This function will check that the two are compatibles. If they are not, * a message is printed and the application will exit. * * @return `true` if the header and library are compatibles, otherwise the * application exits. * * @see nats_GetVersion * @see <API key> */ NATS_EXTERN bool <API key>(void); #else #define <API key>() <API key>(<API key>, \ NATS_VERSION_NUMBER, \ NATS_VERSION_STRING) NATS_EXTERN bool <API key>(uint32_t reqVerNumber, uint32_t verNumber, const char *verString); #endif /** \brief Gives the current time in milliseconds. * * Gives the current time in milliseconds. */ NATS_EXTERN int64_t nats_Now(void); /** \brief Gives the current time in nanoseconds. * * Gives the current time in nanoseconds. When such granularity is not * available, the time returned is still expressed in nanoseconds. */ NATS_EXTERN int64_t <API key>(void); /** \brief Sleeps for a given number of milliseconds. * * Causes the current thread to be suspended for at least the number of * milliseconds. * * @param sleepTime the number of milliseconds. */ NATS_EXTERN void nats_Sleep(int64_t sleepTime); /** \brief Returns the calling thread's last known error. * * Returns the calling thread's last known error. This can be useful when * #<API key> fails. Since no connection object is returned, * you would not be able to call #<API key>. * * @param status if not `NULL`, this function will store the last error status * in there. * @return the thread local error string. * * \warning Do not free the string returned by this function. */ NATS_EXTERN const char* nats_GetLastError(natsStatus *status); /** \brief Returns the calling thread's last known error stack. * * Copies the calling thread's last known error stack into the provided buffer. * If the buffer is not big enough, #<API key> is returned. * * @param buffer the buffer into the stack is copied. * @param bufLen the size of the buffer */ NATS_EXTERN natsStatus <API key>(char *buffer, size_t bufLen); NATS_EXTERN void <API key>(FILE *file); /** \brief Sets the maximum size of the global message delivery thread pool. * * Normally, each asynchronous subscriber that is created has its own * message delivery thread. The advantage is that it reduces lock * contentions, therefore improving performance.<br> * However, if an application creates many subscribers, this is not scaling * well since the process would use too many threads. * * The library has a thread pool that can perform message delivery. If * a connection is created with the proper option set * (#<API key>), then this thread pool * will be responsible for delivering the messages. The thread pool is * lazily initialized, that is, no thread is used as long as no subscriber * (requiring global message delivery) is created. * * Each subscriber will be attached to a given worker on the pool so that * message delivery order is guaranteed. * * This call allows you to set the maximum size of the pool. * * \note At this time, a pool does not shrink, but the caller will not get * an error when calling this function with a size smaller than the current * size. * * @see <API key>() * @see \ref envVariablesGroup * * @param max the maximum size of the pool. */ NATS_EXTERN natsStatus <API key>(int max); /** \brief Tear down the library. * * Releases memory used by the library. * * \note For this to take effect, all NATS objects that you have created * must first be destroyed. */ NATS_EXTERN void nats_Close(void); // end of libraryGroup /** \defgroup statusGroup Status * * Functions related to #natsStatus. * @{ */ /** \brief Get the text corresponding to a #natsStatus. * * Returns the static string corresponding to the given status. * * \warning The returned string is a static string, do not attempt to free * it. * * @param s status to get the text representation from. */ NATS_EXTERN const char* natsStatus_GetText(natsStatus s); // end of statusGroup /** \defgroup statsGroup Statistics * * Statistics Functions. * @{ */ /** \brief Creates a #natsStatistics object. * * Creates a statistics object that can be passed to #<API key>(). * * \note The object needs to be destroyed when no longer needed. * * @see #<API key>() * * @param newStats the location where to store the pointer to the newly created * #natsStatistics object. */ NATS_EXTERN natsStatus <API key>(natsStatistics **newStats); /** \brief Extracts the various statistics values. * * Gets the counts out of the statistics object. * * \note You can pass `NULL` to any of the count your are not interested in * getting. * * @see <API key>() * * @param stats the pointer to the #natsStatistics object to get the values from. * @param inMsgs total number of inbound messages. * @param inBytes total size (in bytes) of inbound messages. * @param outMsgs total number of outbound messages. * @param outBytes total size (in bytes) of outbound messages. * @param reconnects total number of times the client has reconnected. */ NATS_EXTERN natsStatus <API key>(natsStatistics *stats, uint64_t *inMsgs, uint64_t *inBytes, uint64_t *outMsgs, uint64_t *outBytes, uint64_t *reconnects); /** \brief Destroys the #natsStatistics object. * * Destroys the statistics object, freeing up memory. * * @param stats the pointer to the #natsStatistics object to destroy. */ NATS_EXTERN void <API key>(natsStatistics *stats); // end of statsGroup /** \defgroup optsGroup Options * * NATS Options. * @{ */ /** \brief Creates a #natsOptions object. * * Creates a #natsOptions object. This object is used when one wants to set * specific options prior to connecting to the `NATS Server`. * * After making the appropriate natsOptions_Set calls, this object is passed * to the #<API key>() call, which will clone this object. After * <API key>() returns, modifications to the options object * will not affect the connection. * * \note The object needs to be destroyed when no longer needed.* * * @see <API key>() * @see natsOptions_Destroy() * * @param newOpts the location where store the pointer to the newly created * #natsOptions object. */ NATS_EXTERN natsStatus natsOptions_Create(natsOptions **newOpts); /** \brief Sets the URL to connect to. * * Sets the URL of the `NATS Server` the client should try to connect to. * The URL can contain optional user name and password. * * Some valid URLS: * * - nats://localhost:4222 * - nats://user\@localhost:4222 * - nats://user:password\@localhost:4222 * * @see <API key> * @see <API key> * @see <API key> * * @param opts the pointer to the #natsOptions object. * @param url the string representing the URL the connection should use * to connect to the server. * */ /* * The above is for doxygen. The proper syntax for username/password * is without the '\' character: * * nats://localhost:4222 * nats://user@localhost:4222 * nats://user:password@localhost:4222 */ NATS_EXTERN natsStatus natsOptions_SetURL(natsOptions *opts, const char *url); /** \brief Set the list of servers to try to (re)connect to. * * This specifies a list of servers to try to connect (or reconnect) to. * Note that if you call #natsOptions_SetURL() too, the actual list will contain * the one from #natsOptions_SetURL() and the ones specified in this call. * * @see natsOptions_SetURL * @see <API key> * @see <API key> * * @param opts the pointer to the #natsOptions object. * @param servers the array of strings representing the server URLs. * @param serversCount the size of the array. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char** servers, int serversCount); /** \brief Sets the user name/password to use when not specified in the URL. * * Credentials are usually provided through the URL in the form: * <c>nats://foo:bar\@localhost:4222</c>.<br> * Until now, you could specify URLs in two ways, with #<API key> * or #<API key>. The client library would connect (or reconnect) * only to this given list of URLs, so if any of the server in the list required * authentication, you were responsible for providing the appropriate credentials * in the URLs.<br> * <br> * However, with cluster auto-discovery, the client library asynchronously receives * URLs of servers in the cluster. These URLs do not contain any embedded credentials. * <br> * You need to use this function (or #<API key>) to instruct the client * library to use those credentials when connecting to a server that requires * authentication and for which there is no embedded credentials in the URL. * * @see <API key> * @see natsOptions_SetURL * @see <API key> * * @param opts the pointer to the #natsOptions object. * @param user the user name to send to the server during connect. * @param password the password to send to the server during connect. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char *user, const char *password); /** \brief Sets the token to use when not specified in the URL. * * Tokens are usually provided through the URL in the form: * <c>nats://mytoken\@localhost:4222</c>.<br> * Until now, you could specify URLs in two ways, with #<API key> * or #<API key>. The client library would connect (or reconnect) * only to this given list of URLs, so if any of the server in the list required * authentication, you were responsible for providing the appropriate token * in the URLs.<br> * <br> * However, with cluster auto-discovery, the client library asynchronously receives * URLs of servers in the cluster. These URLs do not contain any embedded tokens. * <br> * You need to use this function (or #<API key>) to instruct the client * library to use this token when connecting to a server that requires * authentication and for which there is no embedded token in the URL. * * @see <API key> * @see natsOptions_SetURL * @see <API key> * * @param opts the pointer to the #natsOptions object. * @param token the token to send to the server during connect. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char *token); /** \brief Indicate if the servers list should be randomized. * * If 'noRandomize' is true, then the list of server URLs is used in the order * provided by #natsOptions_SetURL() + #<API key>(). Otherwise, the * list is formed in a random order. * * @param opts the pointer to the #natsOptions object. * @param noRandomize if `true`, the list will be used as-is. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool noRandomize); /** \brief Sets the (re)connect process timeout. * * This timeout, expressed in milliseconds, is used to interrupt a (re)connect * attempt to a `NATS Server`. This timeout is used both for the low level TCP * connect call, and for timing out the response from the server to the client's * initial `PING` protocol. * * @param opts the pointer to the #natsOptions object. * @param timeout the time, in milliseconds, allowed for an individual connect * (or reconnect) to complete. * */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int64_t timeout); /** \brief Sets the name. * * This name is sent as part of the `CONNECT` protocol. There is no default name. * * @param opts the pointer to the #natsOptions object. * @param name the name to set. */ NATS_EXTERN natsStatus natsOptions_SetName(natsOptions *opts, const char *name); /** \brief Sets the secure mode. * * Indicates to the server if the client wants a secure (SSL/TLS) connection. * * The default is `false`. * * @param opts the pointer to the #natsOptions object. * @param secure `true` for a secure connection, `false` otherwise. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool secure); /** \brief Loads the trusted CA certificates from a file. * * Loads the trusted CA certificates from a file. * * Note that the certificates * are added to a SSL context for this #natsOptions object at the time of * this call, so possible errors while loading the certificates will be * reported now instead of when a connection is created. You can get extra * information by calling #nats_GetLastError. * * @param opts the pointer to the #natsOptions object. * @param fileName the file containing the CA certificates. * */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char *fileName); /** \brief Loads the certificate chain from a file, using the given key. * * The certificates must be in PEM format and must be sorted starting with * the subject's certificate, followed by intermediate CA certificates if * applicable, and ending at the highest level (root) CA. * * The private key file format supported is also PEM. * * See #<API key> regarding error reports. * * @param opts the pointer to the #natsOptions object. * @param certsFileName the file containing the client certificates. * @param keyFileName the file containing the client private key. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char *certsFileName, const char *keyFileName); NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char *ciphers); /** \brief Sets the server certificate's expected hostname. * * If set, the library will check that the hostname in the server * certificate matches the given `hostname`. This will occur when a connection * is created, not at the time of this call. * * @param opts the pointer to the #natsOptions object. * @param hostname the expected server certificate hostname. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, const char *hostname); /** \brief Switch server certificate verification. * * By default, the server certificate is verified. You can disable the verification * by passing <c>true</c> to this function. * * \warning This is fine for tests but use with caution since this is not secure. * * @param opts the pointer to the #natsOptions object. * @param skip set it to <c>true</c> to disable - or skip - server certificate verification. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool skip); /** \brief Sets the verbose mode. * * Sets the verbose mode. If `true`, sends are echoed by the server with * an `OK` protocol message. * * The default is `false`. * * @param opts the pointer to the #natsOptions object. * @param verbose `true` for a verbose protocol, `false` otherwise. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool verbose); /** \brief Sets the pedantic mode. * * Sets the pedantic mode. If `true` some extra checks will be performed * by the server. * * The default is `false` * * @param opts the pointer to the #natsOptions object. * @param pedantic `true` for a pedantic protocol, `false` otherwise. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool pedantic); /** \brief Sets the ping interval. * * Interval, expressed in milliseconds, in which the client sends `PING` * protocols to the `NATS Server`. * * @param opts the pointer to the #natsOptions object. * @param interval the interval, in milliseconds, at which the connection * will send `PING` protocols to the server. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int64_t interval); /** \brief Sets the limit of outstanding `PING`s without corresponding `PONG`s. * * Specifies the maximum number of `PING`s without corresponding `PONG`s (which * should be received from the server) before closing the connection with * the #<API key> status. If reconnection is allowed, the client * library will try to reconnect. * * @param opts the pointer to the #natsOptions object. * @param maxPingsOut the maximum number of `PING`s without `PONG`s * (positive number). */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int maxPingsOut); /** \brief Indicates if the connection will be allowed to reconnect. * * Specifies whether or not the client library should try to reconnect when * losing the connection to the `NATS Server`. * * The default is `true`. * * @param opts the pointer to the #natsOptions object. * @param allow `true` if the connection is allowed to reconnect, `false` * otherwise. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool allow); /** \brief Sets the maximum number of reconnect attempts. * * Specifies the maximum number of reconnect attempts. * * @param opts the pointer to the #natsOptions object. * @param maxReconnect the maximum number of reconnects (positive number). */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int maxReconnect); /** \brief Sets the time between reconnect attempts. * * Specifies how long to wait between two reconnect attempts from the same * server. This means that if you have a list with S1,S2 and are currently * connected to S1, and get disconnected, the library will immediately * attempt to connect to S2. If this fails, it will go back to S1, and this * time will wait for `reconnectWait` milliseconds since the last attempt * to connect to S1. * * @param opts the pointer to the #natsOptions object. * @param reconnectWait the time, in milliseconds, to wait between attempts * to reconnect to the same server. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int64_t reconnectWait); /** \brief Sets the size of the backing buffer used during reconnect. * * Sets the size, in bytes, of the backing buffer holding published data * while the library is reconnecting. Once this buffer has been exhausted, * publish operations will return the #<API key> error. * If not specified, or the value is 0, the library will use a default value, * currently set to 8MB. * * @param opts the pointer to the #natsOptions object. * @param reconnectBufSize the size, in bytes, of the backing buffer for * write operations during a reconnect. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int reconnectBufSize); /** \brief Sets the maximum number of pending messages per subscription. * * Specifies the maximum number of inbound messages that can be buffered in the * library, for each subscription, before inbound messages are dropped and * #NATS_SLOW_CONSUMER status is reported to the #natsErrHandler callback (if * one has been set). * * @see <API key>() * * @param opts the pointer to the #natsOptions object. * @param maxPending the number of messages allowed to be buffered by the * library before triggering a slow consumer scenario. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, int maxPending); /** \brief Sets the error handler for asynchronous events. * * Specifies the callback to invoke when an asynchronous error * occurs. This is used by applications having only asynchronous * subscriptions that would not know otherwise that a problem with the * connection occurred. * * @see natsErrHandler * * @param opts the pointer to the #natsOptions object. * @param errHandler the error handler callback. * @param closure a pointer to an user object that will be passed to * the callback. `closure` can be `NULL`. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, natsErrHandler errHandler, void *closure); /** \brief Sets the callback to be invoked when a connection to a server * is permanently lost. * * Specifies the callback to invoke when a connection is terminally closed, * that is, after all reconnect attempts have failed (when reconnection is * allowed). * * @param opts the pointer to the #natsOptions object. * @param closedCb the callback to be invoked when the connection is closed. * @param closure a pointer to an user object that will be passed to * the callback. `closure` can be `NULL`. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, <API key> closedCb, void *closure); /** \brief Sets the callback to be invoked when the connection to a server is * lost. * * Specifies the callback to invoke when a connection to the `NATS Server` * is lost. There could be two instances of the callback when reconnection * is allowed: one before attempting the reconnect attempts, and one when * all reconnect attempts have failed and the connection is going to be * permanently closed. * * \warning Invocation of this callback is asynchronous, which means that * the state of the connection may have changed when this callback is * invoked. * * @param opts the pointer to the #natsOptions object. * @param disconnectedCb the callback to be invoked when a connection to * a server is lost * @param closure a pointer to an user object that will be passed to * the callback. `closure` can be `NULL`. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, <API key> disconnectedCb, void *closure); /** \brief Sets the callback to be invoked when the connection has reconnected. * * Specifies the callback to invoke when the client library has successfully * reconnected to a `NATS Server`. * * \warning Invocation of this callback is asynchronous, which means that * the state of the connection may have changed when this callback is * invoked. * * @param opts the pointer to the #natsOptions object. * @param reconnectedCb the callback to be invoked when the connection to * a server has been re-established. * @param closure a pointer to an user object that will be passed to * the callback. `closure` can be `NULL`. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, <API key> reconnectedCb, void *closure); /** \brief Sets the external event loop and associated callbacks. * * If you want to use an external event loop, the `NATS` library will not * create a thread to read data from the socket, and will not directly write * data to the socket. Instead, the library will invoke those callbacks * for various events. * * @param opts the pointer to the #natsOptions object. * @param loop the `void*` pointer to the external event loop. * @param attachCb the callback invoked after the connection is connected, * or reconnected. * @param readCb the callback invoked when the event library should start or * stop polling for read events. * @param writeCb the callback invoked when the event library should start or * stop polling for write events. * @param detachCb the callback invoked when a connection is closed. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, void *loop, natsEvLoop_Attach attachCb, <API key> readCb, <API key> writeCb, natsEvLoop_Detach detachCb); /** \brief Switch on/off the use of a central message delivery thread pool. * * Normally, each asynchronous subscriber that is created has its own * message delivery thread. The advantage is that it reduces lock * contentions, therefore improving performance.<br> * However, if an application creates many subscribers, this is not scaling * well since the process would use too many threads. * * When a connection is created from a `nats_Options` that has enabled * global message delivery, asynchronous subscribers from this connection * will use a shared thread pool responsible for message delivery. * * \note The message order per subscription is still guaranteed. * * @see <API key>() * @see \ref envVariablesGroup * * @param opts the pointer to the #natsOptions object. * @param global if `true`, uses the global message delivery thread pool, * otherwise, each asynchronous subscriber will create their own message * delivery thread. */ NATS_EXTERN natsStatus <API key>(natsOptions *opts, bool global); NATS_EXTERN natsStatus <API key>(natsOptions *opts, int order); /** \brief Destroys a #natsOptions object. * * Destroys the natsOptions object, freeing used memory. See the note in * the natsOptions_Create() call. * * @param opts the pointer to the #natsOptions object to destroy. */ NATS_EXTERN void natsOptions_Destroy(natsOptions *opts); // end of optsGroup /** \defgroup inboxGroup Inboxes * * NATS Inboxes. * @{ */ /** \brief Creates an inbox. * * Returns an inbox string which can be used for directed replies from * subscribers. These are guaranteed to be unique, but can be shared * and subscribed to by others. * * \note The inbox needs to be destroyed when no longer needed. * * @see #natsInbox_Destroy() * * @param newInbox the location where to store a pointer to the newly * created #natsInbox. */ NATS_EXTERN natsStatus natsInbox_Create(char **newInbox); /** \brief Destroys the inbox. * * Destroys the inbox. * * @param inbox the pointer to the #natsInbox object to destroy. */ NATS_EXTERN void natsInbox_Destroy(char *inbox); // end of inboxGroup /** \defgroup msgGroup Message * * NATS Message. * @{ */ /** \brief Creates a #natsMsg object. * * Creates a #natsMsg object. This is used by the subscription related calls * and by #<API key>(). * * \note Messages need to be destroyed with #natsMsg_Destroy() when no * longer needed. * * @see natsMsg_Destroy() * * @param newMsg the location where to store the pointer to the newly created * #natsMsg object. * @param subj the subject this message will be sent to. Cannot be `NULL`. * @param reply the optional reply for this message. * @param data the optional message payload. * @param dataLen the size of the payload. */ NATS_EXTERN natsStatus natsMsg_Create(natsMsg **newMsg, const char *subj, const char *reply, const char *data, int dataLen); /** \brief Returns the subject set in this message. * * Returns the subject set on that message. * * \warning The string belongs to the message and must not be freed. * Copy it if needed. * @param msg the pointer to the #natsMsg object. */ NATS_EXTERN const char* natsMsg_GetSubject(natsMsg *msg); /** \brief Returns the reply set in this message. * * Returns the reply, possibly `NULL`. * * \warning The string belongs to the message and must not be freed. * Copy it if needed. * * @param msg the pointer to the #natsMsg object. */ NATS_EXTERN const char* natsMsg_GetReply(natsMsg *msg); /** \brief Returns the message payload. * * Returns the message payload, possibly `NULL`. * * Note that although the data sent and received from the server is not `NULL` * terminated, the NATS C Client does add a `NULL` byte to the received payload. * If you expect the received data to be a "string", then this conveniently * allows you to call #natsMsg_GetData() without having to copy the returned * data to a buffer to add the `NULL` byte at the end. * * \warning The string belongs to the message and must not be freed. * Copy it if needed. * * @param msg the pointer to the #natsMsg object. */ NATS_EXTERN const char* natsMsg_GetData(natsMsg *msg); /** \brief Returns the message length. * * Returns the message's payload length, possibly 0. * * @param msg the pointer to the #natsMsg object. */ NATS_EXTERN int <API key>(natsMsg *msg); /** \brief Destroys the message object. * * Destroys the message, freeing memory. * * @param msg the pointer to the #natsMsg object to destroy. */ NATS_EXTERN void natsMsg_Destroy(natsMsg *msg); // end of msgGroup /** \defgroup connGroup Connection * * NATS Connection * @{ */ /** \defgroup connMgtGroup Management * * Functions related to connection management. * @{ */ /** \brief Connects to a `NATS Server` using the provided options. * * Attempts to connect to a `NATS Server` with multiple options. * * This call is cloning the #natsOptions object. Once this call returns, * changes made to the `options` will not have an effect to this * connection. The `options` can however be changed prior to be * passed to another #<API key>() call if desired. * * @see #natsOptions * @see #<API key>() * * @param nc the location where to store the pointer to the newly created * #natsConnection object. * @param options the options to use for this connection. If `NULL` * this call is equivalent to #<API key>() with #NATS_DEFAULT_URL. * */ NATS_EXTERN natsStatus <API key>(natsConnection **nc, natsOptions *options); /** \brief Process a read event when using external event loop. * * When using an external event loop, and the callback indicating that * the socket is ready for reading, this call will read data from the * socket and process it. * * @param nc the pointer to the #natsConnection object. * * \warning This API is reserved for external event loop adapters. */ NATS_EXTERN void <API key>(natsConnection *nc); /** \brief Process a write event when using external event loop. * * When using an external event loop, and the callback indicating that * the socket is ready for writing, this call will write data to the * socket. * * @param nc the pointer to the #natsConnection object. * * \warning This API is reserved for external event loop adapters. */ NATS_EXTERN void <API key>(natsConnection *nc); /** \brief Connects to a `NATS Server` using any of the URL from the given list. * * Attempts to connect to a `NATS Server`. * * This call supports multiple comma separated URLs. If more than one is * specified, it behaves as if you were using a #natsOptions object and * called #<API key>() with the equivalent array of URLs. * The list is randomized before the connect sequence starts. * * @see #<API key>() * @see #<API key>() * * @param nc the location where to store the pointer to the newly created * #natsConnection object. * @param urls the URL to connect to, or the list of URLs to chose from. */ NATS_EXTERN natsStatus <API key>(natsConnection **nc, const char *urls); /** \brief Test if connection has been closed. * * Tests if connection has been closed. * * @param nc the pointer to the #natsConnection object. */ NATS_EXTERN bool <API key>(natsConnection *nc); /** \brief Test if connection is reconnecting. * * Tests if connection is reconnecting. * * @param nc the pointer to the #natsConnection object. */ NATS_EXTERN bool <API key>(natsConnection *nc); /** \brief Returns the current state of the connection. * * Returns the current state of the connection. * * @see #natsConnStatus * * @param nc the pointer to the #natsConnection object. */ NATS_EXTERN natsConnStatus <API key>(natsConnection *nc); /** \brief Returns the number of bytes to be sent to the server. * * When calling any of the publish functions, data is not necessarily * immediately sent to the server. Some buffering occurs, allowing * for better performance. This function indicates if there is any * data not yet transmitted to the server. * * @param nc the pointer to the #natsConnection object. * @return the number of bytes to be sent to the server, or -1 if the * connection is closed. */ NATS_EXTERN int <API key>(natsConnection *nc); /** \brief Flushes the connection. * * Performs a round trip to the server and return when it receives the * internal reply. * * Note that if this call occurs when the connection to the server is * lost, the `PING` will not be echoed even if the library can connect * to a new (or the same) server. Therefore, in such situation, this * call will fail with the status #<API key>. * * If the connection is closed while this call is in progress, then the * status #CLOSED would be returned instead. * * @param nc the pointer to the #natsConnection object. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc); /** \brief Flushes the connection with a given timeout. * * Performs a round trip to the server and return when it receives the * internal reply, or if the call times-out (timeout is expressed in * milliseconds). * * See possible failure case described in #<API key>(). * * @param nc the pointer to the #natsConnection object. * @param timeout in milliseconds, is the time allowed for the flush * to complete before #NATS_TIMEOUT error is returned. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, int64_t timeout); /** \brief Returns the maximum message payload. * * Returns the maximum message payload accepted by the server. The * information is gathered from the `NATS Server` when the connection is * first established. * * @param nc the pointer to the #natsConnection object. * @return the maximum message payload. */ NATS_EXTERN int64_t <API key>(natsConnection *nc); /** \brief Gets the connection statistics. * * Copies in the provided statistics structure, a snapshot of the statistics for * this connection. * * @param nc the pointer to the #natsConnection object. * @param stats the pointer to a #natsStatistics object in which statistics * will be copied. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, natsStatistics *stats); /** \brief Gets the URL of the currently connected server. * * Copies in the given buffer, the connected server's Url. If the buffer is * too small, an error is returned. * * @param nc the pointer to the #natsConnection object. * @param buffer the buffer in which the URL is copied. * @param bufferSize the size of the buffer. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, char *buffer, size_t bufferSize); /** \brief Gets the server Id. * * Copies in the given buffer, the connected server's Id. If the buffer is * too small, an error is returned. * * @param nc the pointer to the #natsConnection object. * @param buffer the buffer in which the server id is copied. * @param bufferSize the size of the buffer. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, char *buffer, size_t bufferSize); /** \brief Returns the list of server URLs known to this connection. * * Returns the list of known servers, including additional servers * discovered after a connection has been established (with servers * version 0.9.2 and above). * * No credential information is included in any of the server URLs * returned by this call.<br> * If you want to use any of these URLs to connect to a server that * requires authentication, you will need to use #<API key> * or #<API key>. * * \note The user is responsible for freeing the memory of the returned array. * * @param nc the pointer to the #natsConnection object. * @param servers the location where to store the pointer to the array * of server URLs. * @param count the location where to store the number of elements of the * returned array. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, char ***servers, int *count); /** \brief Returns the list of discovered server URLs. * * Unlike #<API key>, this function only returns * the list of servers that have been discovered after the a connection * has been established (with servers version 0.9.2 and above). * * No credential information is included in any of the server URLs * returned by this call.<br> * If you want to use any of these URLs to connect to a server that * requires authentication, you will need to use #<API key> * or #<API key>. * * \note The user is responsible for freeing the memory of the returned array. * * @param nc the pointer to the #natsConnection object. * @param servers the location where to store the pointer to the array * of server URLs. * @param count the location where to store the number of elements of the * returned array. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, char ***servers, int *count); /** \brief Gets the last connection error. * * Returns the last known error as a 'natsStatus' and the location to the * null-terminated error string. * * \warning The returned string is owned by the connection object and * must not be freed. * * @param nc the pointer to the #natsConnection object. * @param lastError the location where the pointer to the connection's last * error string is copied. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, const char **lastError); /** \brief Closes the connection. * * Closes the connection to the server. This call will release all blocking * calls, such as #<API key>() and #<API key>(). * The connection object is still usable until the call to * #<API key>(). * * @param nc the pointer to the #natsConnection object. */ NATS_EXTERN void <API key>(natsConnection *nc); /** \brief Destroys the connection object. * * Destroys the connection object, freeing up memory. * If not already done, this call first closes the connection to the server. * * @param nc the pointer to the #natsConnection object. */ NATS_EXTERN void <API key>(natsConnection *nc); // end of connMgtGroup /** \defgroup connPubGroup Publishing * * Publishing functions * @{ */ /** \brief Publishes data on a subject. * * Publishes the data argument to the given subject. The data argument is left * untouched and needs to be correctly interpreted on the receiver. * * @param nc the pointer to the #natsConnection object. * @param subj the subject the data is sent to. * @param data the data to be sent, can be `NULL`. * @param dataLen the length of the data to be sent. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, const char *subj, const void *data, int dataLen); /** \brief Publishes a string on a subject. * * Convenient function to publish a string. This call is equivalent to: * * \code{.c} * const char* myString = "hello"; * * <API key>(nc, subj, (const void*) myString, (int) strlen(myString)); * \endcode * * @param nc the pointer to the #natsConnection object. * @param subj the subject the data is sent to. * @param str the string to be sent. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, const char *subj, const char *str); /** \brief Publishes a message on a subject. * * Publishes the #natsMsg, which includes the subject, an optional reply and * optional data. * * @see #natsMsg_Create() * * @param nc the pointer to the #natsConnection object. * @param msg the pointer to the #natsMsg object to send. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, natsMsg *msg); /** \brief Publishes data on a subject expecting replies on the given reply. * * Publishes the data argument to the given subject expecting a response on * the reply subject. Use #<API key>() for automatically waiting * for a response inline. * * @param nc the pointer to the #natsConnection object. * @param subj the subject the request is sent to. * @param reply the reply on which resonses are expected. * @param data the data to be sent, can be `NULL`. * @param dataLen the length of the data to be sent. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, const char *subj, const char *reply, const void *data, int dataLen); /** \brief Publishes a string on a subject expecting replies on the given reply. * * Convenient function to publish a request as a string. This call is * equivalent to: * * \code{.c} * const char* myString = "hello"; * * natsPublishRequest(nc, subj, reply, (const void*) myString, (int) strlen(myString)); * \endcode * * @param nc the pointer to the #natsConnection object. * @param subj the subject the request is sent to. * @param reply the reply on which resonses are expected. * @param str the string to send. */ NATS_EXTERN natsStatus <API key>(natsConnection *nc, const char *subj, const char *reply, const char *str); /** \brief Sends a request and waits for a reply. * * Creates a #natsInbox and performs a #<API key>() call * with the reply set to that inbox. Returns the first reply received. * This is optimized for the case of multiple responses. * * @param replyMsg the location where to store the pointer to the received * #natsMsg reply. * @param nc the pointer to the #natsConnection object. * @param subj the subject the request is sent to. * @param data the data of the request, can be `NULL`. * @param dataLen the length of the data to send. * @param timeout in milliseconds, before this call returns #NATS_TIMEOUT * if no response is received in this alloted time. */ NATS_EXTERN natsStatus <API key>(natsMsg **replyMsg, natsConnection *nc, const char *subj, const void *data, int dataLen, int64_t timeout); /** \brief Sends a request (as a string) and waits for a reply. * * Convenient function to send a request as a string. This call is * equivalent to: * * \code{.c} * const char* myString = "hello"; * * <API key>(replyMsg, nc, subj, (const void*) myString, (int) strlen(myString)); * \endcode * * @param replyMsg the location where to store the pointer to the received * #natsMsg reply. * @param nc the pointer to the #natsConnection object. * @param subj the subject the request is sent to. * @param str the string to send. * @param timeout in milliseconds, before this call returns #NATS_TIMEOUT * if no response is received in this alloted time. */ NATS_EXTERN natsStatus <API key>(natsMsg **replyMsg, natsConnection *nc, const char *subj, const char *str, int64_t timeout); // end of connPubGroup /** \defgroup connSubGroup Subscribing * * Subscribing functions. * @{ */ /** \brief Creates an asynchronous subscription. * * Expresses interest in the given subject. The subject can have wildcards * (see \ref wildcardsGroup). Messages will be delivered to the associated * #natsMsgHandler. * * @param sub the location where to store the pointer to the newly created * #natsSubscription object. * @param nc the pointer to the #natsConnection object. * @param subject the subject this subscription is created for. * @param cb the #natsMsgHandler callback. * @param cbClosure a pointer to an user defined object (can be `NULL`). See * the #natsMsgHandler prototype. */ NATS_EXTERN natsStatus <API key>(natsSubscription **sub, natsConnection *nc, const char *subject, natsMsgHandler cb, void *cbClosure); /** \brief Creates an asynchronous subscription with a timeout. * * Expresses interest in the given subject. The subject can have wildcards * (see \ref wildcardsGroup). Messages will be delivered to the associated * #natsMsgHandler. * * If no message is received by the given timeout (in milliseconds), the * message handler is invoked with a `NULL` message.<br> * You can then destroy the subscription in the callback, or simply * return, in which case, the message handler will fire again when a * message is received or the subscription times-out again. * * \note Receiving a message reset the timeout. Until all pending messages * are processed, no timeout will occur. The timeout starts when the * message handler for the last pending message returns. * * \warning If you re-use message handler code between subscriptions with * and without timeouts, keep in mind that the message passed in the * message handler may be `NULL`. * * @param sub the location where to store the pointer to the newly created * #natsSubscription object. * @param nc the pointer to the #natsConnection object. * @param subject the subject this subscription is created for. * @param timeout the interval (in milliseconds) after which, if no message * is received, the message handler is invoked with a `NULL` message. * @param cb the #natsMsgHandler callback. * @param cbClosure a pointer to an user defined object (can be `NULL`). See * the #natsMsgHandler prototype. */ NATS_EXTERN natsStatus <API key>(natsSubscription **sub, natsConnection *nc, const char *subject, int64_t timeout, natsMsgHandler cb, void *cbClosure); /** \brief Creates a synchronous subcription. * * Similar to #<API key>, but creates a synchronous subscription * that can be polled via #<API key>(). * * @param sub the location where to store the pointer to the newly created * #natsSubscription object. * @param nc the pointer to the #natsConnection object. * @param subject the subject this subscription is created for. */ NATS_EXTERN natsStatus <API key>(natsSubscription **sub, natsConnection *nc, const char *subject); /** \brief Creates an asynchronous queue subscriber. * * Creates an asynchronous queue subscriber on the given subject. * All subscribers with the same queue name will form the queue group and * only one member of the group will be selected to receive any given * message asynchronously. * * @param sub the location where to store the pointer to the newly created * #natsSubscription object. * @param nc the pointer to the #natsConnection object. * @param subject the subject this subscription is created for. * @param queueGroup the name of the group. * @param cb the #natsMsgHandler callback. * @param cbClosure a pointer to an user defined object (can be `NULL`). See * the #natsMsgHandler prototype. * */ NATS_EXTERN natsStatus <API key>(natsSubscription **sub, natsConnection *nc, const char *subject, const char *queueGroup, natsMsgHandler cb, void *cbClosure); /** \brief Creates an asynchronous queue subscriber with a timeout. * * Creates an asynchronous queue subscriber on the given subject. * All subscribers with the same queue name will form the queue group and * only one member of the group will be selected to receive any given * message asynchronously. * * If no message is received by the given timeout (in milliseconds), the * message handler is invoked with a `NULL` message.<br> * You can then destroy the subscription in the callback, or simply * return, in which case, the message handler will fire again when a * message is received or the subscription times-out again. * * \note Receiving a message reset the timeout. Until all pending messages * are processed, no timeout will occur. The timeout starts when the * message handler for the last pending message returns. * * \warning If you re-use message handler code between subscriptions with * and without timeouts, keep in mind that the message passed in the * message handler may be `NULL`. * * @param sub the location where to store the pointer to the newly created * #natsSubscription object. * @param nc the pointer to the #natsConnection object. * @param subject the subject this subscription is created for. * @param queueGroup the name of the group. * @param timeout the interval (in milliseconds) after which, if no message * is received, the message handler is invoked with a `NULL` message. * @param cb the #natsMsgHandler callback. * @param cbClosure a pointer to an user defined object (can be `NULL`). See * the #natsMsgHandler prototype. */ NATS_EXTERN natsStatus <API key>(natsSubscription **sub, natsConnection *nc, const char *subject, const char *queueGroup, int64_t timeout, natsMsgHandler cb, void *cbClosure); /** \brief Creates a synchronous queue subscriber. * * Similar to #<API key>, but creates a synchronous * subscription that can be polled via #<API key>(). * * @param sub the location where to store the pointer to the newly created * #natsSubscription object. * @param nc the pointer to the #natsConnection object. * @param subject the subject this subscription is created for. * @param queueGroup the name of the group. */ NATS_EXTERN natsStatus <API key>(natsSubscription **sub, natsConnection *nc, const char *subject, const char *queueGroup); // end of connSubGroup // end of connGroup /** \defgroup subGroup Subscription * * NATS Subscriptions. * @{ */ /** \brief Enables the No Delivery Delay mode. * * By default, messages that arrive are not immediately delivered. This * generally improves performance. However, in case of request-reply, * this delay has a negative impact. In such case, call this function * to have the subscriber be notified immediately each time a message * arrives. * * @param sub the pointer to the #natsSubscription object. * * \deprecated No longer needed. Will be removed in the future. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub); /** \brief Returns the next available message. * * Return the next message available to a synchronous subscriber or block until * one is available. * A timeout (expressed in milliseconds) can be used to return when no message * has been delivered. If the value is zero, then this call will not wait and * return the next message that was pending in the client, and #NATS_TIMEOUT * otherwise. * * @param nextMsg the location where to store the pointer to the next availabe * message. * @param sub the pointer to the #natsSubscription object. * @param timeout time, in milliseconds, after which this call will return * #NATS_TIMEOUT if no message is available. */ NATS_EXTERN natsStatus <API key>(natsMsg **nextMsg, natsSubscription *sub, int64_t timeout); /** \brief Unsubscribes. * * Removes interest on the subject. Asynchronous subscription may still have * a callback in progress, in that case, the subscription will still be valid * until the callback returns. * * @param sub the pointer to the #natsSubscription object. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub); /** \brief Auto-Unsubscribes. * * This call issues an automatic #<API key> that is * processed by the server when 'max' messages have been received. * This can be useful when sending a request to an unknown number * of subscribers. * * @param sub the pointer to the #natsSubscription object. * @param max the maximum number of message you want this subscription * to receive. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int max); /** \brief Gets the number of pending messages. * * Returns the number of queued messages in the client for this subscription. * * \deprecated Use #<API key> instead. * * @param sub the pointer to the #natsSubscription object. * @param queuedMsgs the location where to store the number of queued messages. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, uint64_t *queuedMsgs); /** \brief Sets the limit for pending messages and bytes. * * Specifies the maximum number and size of incoming messages that can be * buffered in the library for this subscription, before new incoming messages are * dropped and #NATS_SLOW_CONSUMER status is reported to the #natsErrHandler * callback (if one has been set). * * If no limit is set at the subscription level, the limit set by #<API key> * before creating the connection will be used. * * \note If no option is set, there is still a default of `65536` messages and * `65536 * 1024` bytes. * * @see <API key> * @see <API key> * * @param sub he pointer to the #natsSubscription object. * @param msgLimit the limit in number of messages that the subscription can hold. * @param bytesLimit the limit in bytes that the subscription can hold. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int msgLimit, int bytesLimit); /** \brief Returns the current limit for pending messages and bytes. * * Regardless if limits have been explicitly set with #<API key>, * this call will store in the provided memory locations, the limits set for * this subscription. * * \note It is possible for `msgLimit` and/or `bytesLimits` to be `NULL`, in which * case the corresponding value is obviously not stored, but the function will * not return an error. * * @see <API key> * @see <API key> * * @param sub the pointer to the #natsSubscription object. * @param msgLimit if not `NULL`, the memory location where to store the maximum * number of pending messages for this subscription. * @param bytesLimit if not `NULL`, the memory location where to store the maximum * size of pending messages for this subscription. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int *msgLimit, int *bytesLimit); /** \brief Returns the number of pending messages and bytes. * * Returns the total number and size of pending messages on this subscription. * * \note It is possible for `msgs` and `bytes` to be NULL, in which case the * corresponding values are obviously not stored, but the function will not return * an error. * * @param sub the pointer to the #natsSubscription object. * @param msgs if not `NULL`, the memory location where to store the number of * pending messages. * @param bytes if not `NULL`, the memory location where to store the total size of * pending messages. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int *msgs, int *bytes); /** \brief Returns the number of delivered messages. * * Returns the number of delivered messages for this subscription. * * @param sub the pointer to the #natsSubscription object. * @param msgs the memory location where to store the number of * delivered messages. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int64_t *msgs); /** \brief Returns the number of dropped messages. * * Returns the number of known dropped messages for this subscription. This happens * when a consumer is not keeping up and the library starts to drop messages * when the maximum number (and/or size) of pending messages has been reached. * * \note If the server declares the connection a slow consumer, this number may * not be valid. * * @see <API key> * @see <API key> * * @param sub the pointer to the #natsSubscription object. * @param msgs the memory location where to store the number of dropped messages. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int64_t *msgs); /** \brief Returns the maximum number of pending messages and bytes. * * Returns the maximum of pending messages and bytes seen so far. * * \note `msgs` and/or `bytes` can be NULL. * * @param sub the pointer to the #natsSubscription object. * @param msgs if not `NULL`, the memory location where to store the maximum * number of pending messages seen so far. * @param bytes if not `NULL`, the memory location where to store the maximum * number of bytes pending seen so far. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int *msgs, int *bytes); /** \brief Clears the statistics regarding the maximum pending values. * * Clears the statistics regarding the maximum pending values. * * @param sub the pointer to the #natsSubscription object. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub); /** \brief Get various statistics from this subscription. * * This is a convenient function to get several subscription's statistics * in one call. * * \note Any or all of the statistics pointers can be `NULL`. * * @see <API key> * @see <API key> * @see <API key> * @see <API key> * * @param sub the pointer to the #natsSubscription object. * @param pendingMsgs if not `NULL`, memory location where to store the * number of pending messages. * @param pendingBytes if not `NULL`, memory location where to store the * total size of pending messages. * @param maxPendingMsgs if not `NULL`, memory location where to store the * maximum number of pending messages seen so far. * @param maxPendingBytes if not `NULL`, memory location where to store the * maximum total size of pending messages seen so far. * @param deliveredMsgs if not `NULL`, memory location where to store the * number of delivered messages. * @param droppedMsgs if not `NULL`, memory location where to store the * number of dropped messages. */ NATS_EXTERN natsStatus <API key>(natsSubscription *sub, int *pendingMsgs, int *pendingBytes, int *maxPendingMsgs, int *maxPendingBytes, int64_t *deliveredMsgs, int64_t *droppedMsgs); /** \brief Checks the validity of the subscription. * * Returns a boolean indicating whether the subscription is still active. * This will return false if the subscription has already been closed, * or auto unsubscribed. * * @param sub the pointer to the #natsSubscription object. */ NATS_EXTERN bool <API key>(natsSubscription *sub); /** \brief Destroys the subscription. * * Destroys the subscription object, freeing up memory. * If not already done, this call will removes interest on the subject. * * @param sub the pointer to the #natsSubscription object to destroy. */ NATS_EXTERN void <API key>(natsSubscription *sub); // end of subGroup // end of funcGroup /** \defgroup wildcardsGroup Wildcards * @{ * Use of wildcards. There are two type of wildcards: `*` for partial, * and `>` for full. * * A subscription on subject `foo.*` would receive messages sent to: * - `foo.bar` * - `foo.baz` * * but not on: * * - `foo.bar.baz` (too many elements) * - `bar.foo`. (does not start with `foo`). * * A subscription on subject `foo.>` would receive messages sent to: * - `foo.bar` * - `foo.baz` * - `foo.bar.baz` * * but not on: * - `foo` (only one element, needs at least two) * - `bar.baz` (does not start with `foo`). ** @} */ #ifdef __cplusplus } #endif #endif /* NATS_H_ */
class <API key> < ActiveRecord::Migration def change add_index :<API key>, :is_active end end
<?php /** * The class that holds all deactivation functionality. * * @since 1.0.0 * @package Foyer * @subpackage Foyer/includes * @author Menno Luitjes <menno@mennoluitjes.nl> */ class Foyer_Deactivator { /** * Does some housekeeping at plugin deactivation. * * Fired during plugin deactivation. Though when network activated only for the primary site. * * @since 1.0.0 * @since 1.5.3 Flushes the rewrite rules to make sure our rewrite rules are removed. * * @return void */ public static function deactivate() { // Our custom post types are not registered at this point // Re-building rewrite rules, excluding those for our custom post types flush_rewrite_rules(); } }
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <queues/task_queue.h> #ifdef HAVE_THREADS #include <rthreads/rthreads.h> #endif typedef struct { retro_task_t *front; retro_task_t *back; } task_queue_t; struct retro_task_impl { void (*push_running)(retro_task_t *); void (*cancel)(void *); void (*reset)(void); void (*wait)(void); void (*gather)(void); bool (*find)(retro_task_finder_t, void*); void (*retrieve)(<API key> *data); void (*init)(void); void (*deinit)(void); }; static task_queue_t tasks_running = {NULL, NULL}; static task_queue_t tasks_finished = {NULL, NULL}; #ifndef RARCH_INTERNAL static void task_queue_msg_push(unsigned prio, unsigned duration, bool flush, const char *fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); /* print something here */ } void <API key>(retro_task_t *task) { if (task->title) { if (task->finished) { if (task->error) task_queue_msg_push(1, 60, true, "%s: %s", "Task failed\n", task->title); else task_queue_msg_push(1, 60, true, "100%%: %s", task->title); } else { if (task->progress >= 0 && task->progress <= 100) task_queue_msg_push(1, 60, true, "%i%%: %s", task->progress, task->title); else task_queue_msg_push(1, 60, true, "%s...", task->title); } } } #endif static void task_queue_put(task_queue_t *queue, retro_task_t *task) { task->next = NULL; if (queue->front) queue->back->next = task; else queue->front = task; queue->back = task; } static retro_task_t *task_queue_get(task_queue_t *queue) { retro_task_t *task = queue->front; if (task) { queue->front = task->next; task->next = NULL; } return task; } static void <API key>(void) { retro_task_t *task = NULL; while ((task = task_queue_get(&tasks_finished)) != NULL) { <API key>(task); if (task->callback) task->callback(task->task_data, task->user_data, task->error); if (task->error) free(task->error); if (task->title) free(task->title); free(task); } } static void <API key>(retro_task_t *task) { task_queue_put(&tasks_running, task); } static void <API key>(void *task) { retro_task_t *t = (retro_task_t*)task; t->cancelled = true; } static void <API key>(void) { retro_task_t *task = NULL; retro_task_t *queue = NULL; retro_task_t *next = NULL; while ((task = task_queue_get(&tasks_running)) != NULL) { task->next = queue; queue = task; } for (task = queue; task; task = next) { next = task->next; task->handler(task); <API key>(task); if (task->finished) task_queue_put(&tasks_finished, task); else <API key>(task); } <API key>(); } static void <API key>(void) { while (tasks_running.front) <API key>(); } static void <API key>(void) { retro_task_t *task = tasks_running.front; for (; task; task = task->next) task->cancelled = true; } static void <API key>(void) { } static void <API key>(void) { } static bool <API key>(retro_task_finder_t func, void *user_data) { retro_task_t *task = tasks_running.front; for (; task; task = task->next) { if (func(task, user_data)) return true; } return false; } static void <API key>(<API key> *data) { retro_task_t *task; <API key> *info; <API key> *tail = NULL; /* Parse all running tasks and handle matching handlers */ for (task = tasks_running.front; task != NULL; task = task->next) if (task->handler == data->handler) { /* Create new link */ info = (<API key>*)malloc(sizeof(<API key>)); info->data = malloc(data->element_size); info->next = NULL; /* Call retriever function and fill info-specific data */ if (!data->func(task, info->data)) { free(info->data); free(info); continue; } /* Add link to list */ if (data->list == NULL) { data->list = info; tail = data->list; } else { tail->next = info; tail = tail->next; } } } static struct retro_task_impl impl_regular = { <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key> }; #ifdef HAVE_THREADS static slock_t *running_lock = NULL; static slock_t *finished_lock = NULL; static scond_t *worker_cond = NULL; static sthread_t *worker_thread = NULL; static bool worker_continue = true; /* use running_lock when touching it */ static void task_queue_remove(task_queue_t *queue, retro_task_t *task) { retro_task_t *t = NULL; /* Remove first element if needed */ if (task == queue->front) { queue->front = task->next; task->next = NULL; return; } /* Parse queue */ t = queue->front; while (t && t->next) { /* Remove task and update queue */ if (t->next == task) { t->next = task->next; task->next = NULL; break; } /* Update iterator */ t = t->next; } } static void <API key>(retro_task_t *task) { slock_lock(running_lock); task_queue_put(&tasks_running, task); scond_signal(worker_cond); slock_unlock(running_lock); } static void <API key>(void *task) { retro_task_t *t; slock_lock(running_lock); for (t = tasks_running.front; t; t = t->next) { if (t == task) { t->cancelled = true; break; } } slock_unlock(running_lock); } static void <API key>(void) { retro_task_t *task = NULL; slock_lock(running_lock); for (task = tasks_running.front; task; task = task->next) <API key>(task); slock_unlock(running_lock); slock_lock(finished_lock); <API key>(); slock_unlock(finished_lock); } static void <API key>(void) { bool wait = false; do { <API key>(); slock_lock(running_lock); wait = (tasks_running.front != NULL); slock_unlock(running_lock); } while (wait); } static void <API key>(void) { retro_task_t *task = NULL; slock_lock(running_lock); for (task = tasks_running.front; task; task = task->next) task->cancelled = true; slock_unlock(running_lock); } static bool <API key>( retro_task_finder_t func, void *user_data) { retro_task_t *task = NULL; bool result = false; slock_lock(running_lock); for (task = tasks_running.front; task; task = task->next) { if (func(task, user_data)) { result = true; break; } } slock_unlock(running_lock); return result; } static void <API key>(<API key> *data) { /* Protect access to running tasks */ slock_lock(running_lock); /* Call regular retrieve function */ <API key>(data); /* Release access to running tasks */ slock_unlock(running_lock); } static void threaded_worker(void *userdata) { (void)userdata; for (;;) { retro_task_t *task = NULL; if (!worker_continue) break; /* should we keep running until all tasks finished? */ slock_lock(running_lock); /* Get first task to run */ task = tasks_running.front; if (task == NULL) { scond_wait(worker_cond, running_lock); slock_unlock(running_lock); continue; } slock_unlock(running_lock); task->handler(task); slock_lock(running_lock); task_queue_remove(&tasks_running, task); slock_unlock(running_lock); /* Update queue */ if (!task->finished) { /* Re-add task to running queue */ <API key>(task); } else { /* Add task to finished queue */ slock_lock(finished_lock); task_queue_put(&tasks_finished, task); slock_unlock(finished_lock); } #if 0 retro_sleep(10); #endif } slock_unlock(running_lock); } static void <API key>(void) { running_lock = slock_new(); finished_lock = slock_new(); worker_cond = scond_new(); slock_lock(running_lock); worker_continue = true; slock_unlock(running_lock); worker_thread = sthread_create(threaded_worker, NULL); } static void <API key>(void) { slock_lock(running_lock); worker_continue = false; scond_signal(worker_cond); slock_unlock(running_lock); sthread_join(worker_thread); scond_free(worker_cond); slock_free(running_lock); slock_free(finished_lock); worker_thread = NULL; worker_cond = NULL; running_lock = NULL; finished_lock = NULL; } static struct retro_task_impl impl_threaded = { <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key> }; #endif bool task_queue_ctl(enum <API key> state, void *data) { static struct retro_task_impl *impl_current = NULL; static bool <API key> = false; switch (state) { case <API key>: if (impl_current) impl_current->deinit(); impl_current = NULL; break; case <API key>: <API key> = true; break; case <API key>: <API key> = false; break; case <API key>: return <API key>; case TASK_QUEUE_CTL_INIT: { #ifdef HAVE_THREADS bool *boolean_val = (bool*)data; #endif impl_current = &impl_regular; #ifdef HAVE_THREADS if (boolean_val && *boolean_val) { task_queue_ctl(<API key>, NULL); impl_current = &impl_threaded; } #endif impl_current->init(); } break; case TASK_QUEUE_CTL_FIND: { task_finder_data_t *find_data = (task_finder_data_t*)data; if (!impl_current->find(find_data->func, find_data->userdata)) return false; } break; case <API key>: impl_current->retrieve((<API key>*)data); break; case <API key>: { #ifdef HAVE_THREADS bool current_threaded = (impl_current == &impl_threaded); bool want_threaded = task_queue_ctl(<API key>, NULL); if (want_threaded != current_threaded) task_queue_ctl(<API key>, NULL); if (!impl_current) task_queue_ctl(TASK_QUEUE_CTL_INIT, NULL); #endif impl_current->gather(); } break; case TASK_QUEUE_CTL_PUSH: { /* The lack of NULL checks in the following functions * is proposital to ensure correct control flow by the users. */ retro_task_t *task = (retro_task_t*)data; impl_current->push_running(task); break; } case <API key>: impl_current->reset(); break; case TASK_QUEUE_CTL_WAIT: impl_current->wait(); break; case <API key>: impl_current->cancel(data); break; case TASK_QUEUE_CTL_NONE: default: break; } return true; } void <API key>(void *task) { task_queue_ctl(<API key>, task); } void *<API key>(<API key> **link) { void *data = NULL; /* Grab data and move to next link */ if (*link) { data = (*link)->data; *link = (*link)->next; } return data; } void <API key>(<API key> *list) { <API key> *info; /* Free links including retriever-specific data */ while (list) { info = list->next; free(list->data); free(list); list = info; } }
using System; using <API key>.Contracts; using <API key>.Data.Helpers; using <API key>.Models; namespace <API key>.Data { <summary> Order Processing unit of work </summary> public class OrderProcessingUow : IOrderProcessingUow { private readonly DBConnectionString _dbConnectionString; // Track whether Dispose has been called. private bool disposed; public OrderProcessingUow(IRepositoryProvider repositoryProvider, DBConnectionString dbConnectionString) { _dbConnectionString = dbConnectionString; CreateDbContext(); repositoryProvider.DbContext = DbContext; RepositoryProvider = repositoryProvider; } protected IRepositoryProvider RepositoryProvider { get; set; } private <API key> DbContext { get; set; } // Repositories public IRepository<Order> Orders => GetStandardRepo<Order>(); public IRepository<Client> Clients => GetStandardRepo<Client>(); public IRepository<Item> Items => GetStandardRepo<Item>(); public IRepository<ClientType> ClientTypes => GetStandardRepo<ClientType>(); public IRepository<OrderStage> OrderStages => GetStandardRepo<OrderStage>(); <summary> Save pending changes to the database </summary> public void Commit() { //System.Diagnostics.Debug.WriteLine("Committed"); DbContext.SaveChanges(); } protected void CreateDbContext() { DbContext = new <API key>(_dbConnectionString.ConnectionString); // Do NOT enable proxied entities, else serialization fails DbContext.Configuration.<API key> = false; // Load navigation properties explicitly (avoid serialization trouble) DbContext.Configuration.LazyLoadingEnabled = false; // Because Web API will perform validation, we don't need/want EF to do so DbContext.Configuration.<API key> = false; } private IRepository<T> GetStandardRepo<T>() where T : class { return RepositoryProvider.<API key><T>(); } private T GetRepo<T>() where T : class { return RepositoryProvider.GetRepository<T>(); } #region Implementation of IDisposable // Implement IDisposable. // Do not make this method virtual. // A derived class should not be able to override this method. public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } // Dispose(bool disposing) executes in two distinct scenarios. // If disposing equals true, the method has been called directly // or indirectly by a user's code. Managed and unmanaged resources // can be disposed. // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. protected virtual void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) DbContext.Dispose(); // Call the appropriate methods to clean up // unmanaged resources here. // If disposing is false, // only the following code is executed. // Note disposing has been done. disposed = true; } } #endregion Implementation of IDisposable } }
package jmanager.VICODE.dialogs; import jmanager.VICODE.BuilderGUI; /** * * @author jesus */ public abstract class <API key> extends javax.swing.JDialog { protected BuilderGUI builderGUI; /** Creates new form <API key> */ public <API key>() { builderGUI = BuilderGUI.getInstance(); initComponents(); <API key>(null); setModal(false); setTitle("Create New Node"); msgLabel.setText(""); setVisible(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { newTypeNodeLabel = new javax.swing.JLabel(); idLabel = new javax.swing.JLabel(); idTextField = new javax.swing.JTextField(); cancelButton = new javax.swing.JButton(); createButton = new javax.swing.JButton(); msgLabel = new javax.swing.JLabel(); <API key>(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); newTypeNodeLabel.<API key>(javax.swing.SwingConstants.CENTER); newTypeNodeLabel.setText("New Item"); newTypeNodeLabel.setName("newTypeNodeLabel"); // NOI18N idLabel.setText("Id:"); idLabel.setName("idLabel"); // NOI18N idTextField.setText("NoName"); idTextField.setName("idTextField"); // NOI18N cancelButton.setText("cancel"); cancelButton.setName("cancelButton"); // NOI18N cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); createButton.setText("create"); createButton.setName("createButton"); // NOI18N createButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { <API key>(evt); } }); msgLabel.<API key>(javax.swing.SwingConstants.CENTER); msgLabel.setText("msgLabel"); msgLabel.setName("msgLabel"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addGap(15, 15, 15) .addComponent(newTypeNodeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(msgLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.<API key>() .addGap(67, 67, 67) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.<API key>() .addComponent(cancelButton) .addGap(12, 12, 12) .addComponent(createButton)) .addGroup(layout.<API key>() .addComponent(idLabel) .addGap(18, 18, 18) .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(22, 22, 22)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.<API key>() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(msgLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(newTypeNodeLabel)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(idTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(idLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(cancelButton) .addComponent(createButton)) .addGap(15, 15, 15)) ); pack(); }// </editor-fold>//GEN-END:initComponents protected abstract void <API key>(java.awt.event.ActionEvent evt);//GEN-FIRST:<API key> //GEN-LAST:<API key> private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:<API key> //Si se cierra la ventana en la X, //quita el texto que hubiera en la etiqueta de "Alredy exists". msgLabel.setText(""); }//GEN-LAST:<API key> private void <API key>(java.awt.event.ActionEvent evt) {//GEN-FIRST:<API key> msgLabel.setText(""); setVisible(false); builderGUI.<API key>(); }//GEN-LAST:<API key> // Variables declaration - do not modify//GEN-BEGIN:variables protected javax.swing.JButton cancelButton; protected javax.swing.JButton createButton; private javax.swing.JLabel idLabel; protected javax.swing.JTextField idTextField; protected javax.swing.JLabel msgLabel; protected javax.swing.JLabel newTypeNodeLabel; // End of variables declaration//GEN-END:variables }
#ifndef <API key> #define <API key> #include "asn_application.h" /* Including external dependencies */ #include "<API key>.h" #include "<API key>.h" #include "constr_SEQUENCE.h" #ifdef __cplusplus extern "C" { #endif /* <API key> */ typedef struct <API key> { <API key> high; <API key> low; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } <API key>; /* Implementation */ extern <API key> <API key>; #ifdef __cplusplus } #endif #endif /* <API key> */ #include "asn_internal.h"
TARGET = :clang ARCHS = armv7 armv7s arm64 include $(THEOS)/makefiles/common.mk BUNDLE_NAME = empyreal empyreal_FILES = empyreal.mm <API key> = /Library/PreferenceBundles empyreal_FRAMEWORKS = UIKit Social Foundation empyreal_LIBRARIES = applist <API key> = Preferences empyreal_CFLAGS = -fobjc-arc include $(THEOS_MAKE_PATH)/bundle.mk internal-stage:: $(ECHO_NOTHING)mkdir -p $(THEOS_STAGING_DIR)/Library/PreferenceLoader/Preferences$(ECHO_END) $(ECHO_NOTHING)cp entry.plist $(THEOS_STAGING_DIR)/Library/PreferenceLoader/Preferences/empyreal.plist$(ECHO_END)
import os from ConfigParser import SafeConfigParser addrs = os.environ.get('<API key>', '').split(',') addr_tuples = [] if addrs: for addr in addrs: addr = addr.split(':') if len(addr) == 2: addr_tuples.append((addr[0], int(addr[1]))) <API key> = addr_tuples if addr_tuples else [("0.0.0.0", 31889)] <API key> = os.environ.get('<API key>', "") import os.path, sys """MAIN DIR is a path to openbci main directory.""" MAIN_DIR = ''.join([os.path.split( os.path.realpath(os.path.dirname(__file__)))[0], '/']) def current_appliance(): """Return string defining current bci-ssvep appliance. Correct values: dummy, appliance1, appliance2 app = 'dummy'""" try: parser = SafeConfigParser() parser.read('/etc/default/openbci') app = parser.get('diodes', 'appliance') except: app = 'dummy' return app def module_abs_path(): """This method returns absolute path to directory containing a module that imported and fired the method. Eg. having module /x/y/z/ugm/ugm.py with: ugm.py: import settings print(settings.module_abs_path()) firing python z/ugm/ugm.py while being in y dir, will print out /x/y/z/ugm/ path. """ return ''.join([ os.path.realpath(os.path.dirname(sys.argv[0])), os.path.sep ]) def executable_abs_path(): """This method returns absolute path to directory containing a script that excecuted python interpreter. Eg. having module /x/y/z/ugm/ugm.py with: ugm.py: import settings print(settings.executable_abs_path()) firing python z/ugm/ugm.py while being in y dir, will print out /x/y/ path. """ return ''.join([os.getcwd(), os.path.sep])
#!/usr/bin/python ''' Cytostream LeftDock Adam Richards adamricha@gmail.com ''' import sys,os from PyQt4 import QtGui,QtCore if hasattr(sys,'frozen'): baseDir = os.path.dirname(sys.executable) baseDir = re.sub("MacOS","Resources",baseDir) else: baseDir = os.path.dirname(__file__) sys.path.append(os.path.join(baseDir,'..')) #from FileControls import * from gdiqt4 import get_gene_list_names from gdiqt4.qtlib import GeneListSelector from gdiqt4.qtlib.InitialDock1 import InitialDock1 from gdiqt4.qtlib import PipelineDock def add_pipeline_dock(mainWindow): btnCallBacks = [lambda a=mainWindow:mainWindow.<API key>(a), lambda a=mainWindow:mainWindow.<API key>(a), lambda a=mainWindow:mainWindow.<API key>(a)] mainWindow.pDock = PipelineDock(parent=mainWindow.mainDockWidget,eSize=mainWindow.eSize,btnCallBacks=btnCallBacks) def remove_left_dock(mainWindow): mainWindow.removeDockWidget(mainWindow.mainDockWidget) def add_left_dock(mainWindow): if mainWindow.dockWidget != None: remove_left_dock(mainWindow) if mainWindow.controller.homeDir == None: noProject = True mainWindow.mainDockWidget = QtGui.QDockWidget('no project loaded', mainWindow) else: noProject = False allGeneLists = get_gene_list_names(mainWindow.controller.homeDir) mainWindow.mainDockWidget = QtGui.QDockWidget(mainWindow.controller.projectID, mainWindow) mainWindow.mainDockWidget.setObjectName("MainDockWidget") mainWindow.mainDockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea) mainWindow.dockWidget = QtGui.QWidget(mainWindow) palette = mainWindow.dockWidget.palette() role = mainWindow.dockWidget.backgroundRole() palette.setColor(role, QtGui.QColor('black')) mainWindow.dockWidget.setPalette(palette) mainWindow.dockWidget.<API key>(True) # setup alignments masterBox = QtGui.QVBoxLayout(mainWindow.dockWidget) vbox1 = QtGui.QVBoxLayout() vbox1.setAlignment(QtCore.Qt.AlignTop) hbox1 = QtGui.QHBoxLayout() hbox1.setAlignment(QtCore.Qt.AlignCenter) vbox2 = QtGui.QVBoxLayout() vbox2.setAlignment(QtCore.Qt.AlignBottom) hbox2 = QtGui.QHBoxLayout() hbox2.setAlignment(QtCore.Qt.AlignCenter) widgetWidth = 0.15 * mainWindow.screenWidth mainWindow.dockWidget.setMaximumWidth(widgetWidth) mainWindow.dockWidget.setMinimumWidth(widgetWidth) if mainWindow.log.log['currentState'] == 'initial': mainWindow.dock1 = InitialDock1(contBtnFn=False,addBtnFn=False,speciesFn=False,message="To begin select 'file' \nand create/load a project") mainWindow.dock1.<API key>(True) hbox1.addWidget(mainWindow.dock1) elif mainWindow.log.log['currentState'] == 'Data Processing': mainWindow.dock1 = InitialDock1(contBtnFn=False,addBtnFn=mainWindow.<API key>) mainWindow.dock1.<API key>(True) hbox1.addWidget(mainWindow.dock1) ## add the pipeline dock add_pipeline_dock(mainWindow) hbox2.addWidget(mainWindow.pDock) ## finalize alignments vbox1.addLayout(hbox1) vbox2.addLayout(hbox2) masterBox.addLayout(vbox1) masterBox.addLayout(vbox2) #vbox.addLayout(vbl3) mainWindow.mainDockWidget.setWidget(mainWindow.dockWidget) mainWindow.addDockWidget(QtCore.Qt.LeftDockWidgetArea, mainWindow.mainDockWidget) ## file selector ''' if mainWindow.log.log['currentState'] in ['Data Processing','Quality Assurance','Model','Results Navigation']: mainWindow.fileSelector = GeneListSelector(fileList,parent=mainWindow.dockWidget, selectionFn=mainWindow.set_selected_file, fileDefault=mainWindow.log.log['selectedFile'], showModelSelector=showModelSelector,modelsRun=modelsRun) mainWindow.fileSelector.<API key>(True) subsamplingDefault = mainWindow.log.log['subsample'] vbl1.addWidget(mainWindow.fileSelector) ## data processing if mainWindow.log.log['currentState'] == "Data Processing": mainWindow.dock1 = DataProcessingDock1(masterChannelList,transformList,compensationList,subsetList,parent=mainWindow.dockWidget, contBtnFn=None,subsetDefault=subsamplingDefault) callBackfn = mainWindow.<API key> mainWindow.dock2 = DataProcessingDock2(callBackfn,parent=mainWindow.dockWidget,default=mainWindow.log.log['<API key>']) mainWindow.dock1.<API key>(True) mainWindow.dock2.<API key>(True) hbl2.addWidget(mainWindow.dock2) hbl3.addWidget(mainWindow.dock1) ## quality assurance elif mainWindow.log.log['currentState'] == "Quality Assurance": check to see if fileList needs adjusting #if type(mainWindow.log.log['excludedFiles']) == type([]) and len(mainWindow.log.log['excludedFiles']) > 0: # for f in mainWindow.log.log['excludedFiles']: # fileList.remove(f) # print 'removeing file %s in leftdock'%f mainWindow.dock = <API key>(fileList,masterChannelList,transformList,compensationList,subsetList,parent=mainWindow.dockWidget, contBtnFn=None,subsetDefault=subsamplingDefault,viewAllFn=mainWindow.display_thumbnails) vbl3.addWidget(mainWindow.dock) mainWindow.dock.<API key>(True) ## model elif mainWindow.log.log['currentState'] == "Model": modelList = ['DPMM','K-means'] mainWindow.dock = ModelDock(modelList,parent=mainWindow.dockWidget,componentsFn=mainWindow.set_num_components) mainWindow.dock.<API key>(True) vbl3.addWidget(mainWindow.dock) ## results navigation elif mainWindow.log.log['currentState'] == "Results Navigation": mainWindow.dock = <API key>(mainWindow.resultsModeList,masterChannelList,parent=mainWindow.dockWidget, resultsModeFn=mainWindow.<API key>, resultsModeDefault=mainWindow.log.log['resultsMode'],viewAllFn=mainWindow.display_thumbnails, infoBtnFn=mainWindow.show_model_log_info) mainWindow.dock.<API key>(True) vbl3.addWidget(mainWindow.dock) ## one dimensional viewer if mainWindow.log.log['currentState'] == 'OneDimViewer': mainWindow.dock = OneDimViewerDock(fileList,masterChannelList,callBack=mainWindow.odv.paint) mainWindow.dock.<API key>(True) vbl1.addWidget(mainWindow.dock) ## stages with thumbnails if mainWindow.log.log['currentState'] in ['Quality Assurance', 'Results Navigation']: mainWindow.fileSelector.<API key>(mainWindow.display_thumbnails) '''
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Mon Jun 16 17:36:03 PDT 2014 --> <title>Uses of Class java.awt.Graphics2D (Java Platform SE 8 )</title> <meta name="date" content="2014-06-16"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class java.awt.Graphics2D (Java Platform SE 8 )"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/awt/class-use/Graphics2D.html" target="_top">Frames</a></li> <li><a href="Graphics2D.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h2 title="Uses of Class java.awt.Graphics2D" class="title">Uses of Class<br>java.awt.Graphics2D</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#java.awt">java.awt</a></td> <td class="colLast"> <div class="block">Contains all of the classes for creating user interfaces and for painting graphics and images.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#java.awt.font">java.awt.font</a></td> <td class="colLast"> <div class="block">Provides classes and interface relating to fonts.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#java.awt.image">java.awt.image</a></td> <td class="colLast"> <div class="block">Provides classes for creating and modifying images.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#javax.swing">javax.swing</a></td> <td class="colLast"> <div class="block">Provides a set of &quot;lightweight&quot; (all-Java language) components that, to the maximum degree possible, work the same on all platforms.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#javax.swing.plaf.nimbus">javax.swing.plaf.nimbus</a></td> <td class="colLast"> <div class="block">Provides user interface objects built according to the cross-platform Nimbus look and feel.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="java.awt"> </a> <h3>Uses of <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a> in <a href="../../../java/awt/package-summary.html">java.awt</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/awt/package-summary.html">java.awt</a> that return <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></code></td> <td class="colLast"><span class="typeNameLabel">SplashScreen.</span><code><span class="memberNameLink"><a href="../../../java/awt/SplashScreen.html#createGraphics--">createGraphics</a></span>()</code> <div class="block">Creates a graphics context (as a <a href="../../../java/awt/Graphics2D.html" title="class in java.awt"><code>Graphics2D</code></a> object) for the splash screen overlay image, which allows you to draw over the splash screen.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>abstract <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></code></td> <td class="colLast"><span class="typeNameLabel">GraphicsEnvironment.</span><code><span class="memberNameLink"><a href="../../../java/awt/GraphicsEnvironment.html#createGraphics-java.awt.image.BufferedImage-">createGraphics</a></span>(<a href="../../../java/awt/image/BufferedImage.html" title="class in java.awt.image">BufferedImage</a>&nbsp;img)</code> <div class="block">Returns a <code>Graphics2D</code> object for rendering into the specified <a href="../../../java/awt/image/BufferedImage.html" title="class in java.awt.image"><code>BufferedImage</code></a>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="java.awt.font"> </a> <h3>Uses of <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a> in <a href="../../../java/awt/font/package-summary.html">java.awt.font</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/awt/font/package-summary.html">java.awt.font</a> with parameters of type <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../java/awt/font/<API key>.html#draw-java.awt.<API key>-">draw</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;graphics, float&nbsp;x, float&nbsp;y)</code> <div class="block">Renders this <code>GraphicAttribute</code> at the specified location.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../java/awt/font/<API key>.html#draw-java.awt.<API key>-">draw</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;graphics, float&nbsp;x, float&nbsp;y)</code> <div class="block">Renders this <code>GraphicAttribute</code> at the specified location.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>abstract void</code></td> <td class="colLast"><span class="typeNameLabel">GraphicAttribute.</span><code><span class="memberNameLink"><a href="../../../java/awt/font/GraphicAttribute.html#draw-java.awt.<API key>-">draw</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;graphics, float&nbsp;x, float&nbsp;y)</code> <div class="block">Renders this <code>GraphicAttribute</code> at the specified location.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">TextLayout.</span><code><span class="memberNameLink"><a href="../../../java/awt/font/TextLayout.html#draw-java.awt.<API key>-">draw</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;g2, float&nbsp;x, float&nbsp;y)</code> <div class="block">Renders this <code>TextLayout</code> at the specified location in the specified <a href="../../../java/awt/Graphics2D.html" title="class in java.awt"><code>Graphics2D</code></a> context.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="java.awt.image"> </a> <h3>Uses of <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a> in <a href="../../../java/awt/image/package-summary.html">java.awt.image</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../java/awt/image/package-summary.html">java.awt.image</a> that return <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>abstract <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></code></td> <td class="colLast"><span class="typeNameLabel">VolatileImage.</span><code><span class="memberNameLink"><a href="../../../java/awt/image/VolatileImage.html#createGraphics--">createGraphics</a></span>()</code> <div class="block">Creates a <code>Graphics2D</code>, which can be used to draw into this <code>VolatileImage</code>.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></code></td> <td class="colLast"><span class="typeNameLabel">BufferedImage.</span><code><span class="memberNameLink"><a href="../../../java/awt/image/BufferedImage.html#createGraphics--">createGraphics</a></span>()</code> <div class="block">Creates a <code>Graphics2D</code>, which can be used to draw into this <code>BufferedImage</code>.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="javax.swing"> </a> <h3>Uses of <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a> in <a href="../../../javax/swing/package-summary.html">javax.swing</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../javax/swing/package-summary.html">javax.swing</a> with parameters of type <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel">Painter.</span><code><span class="memberNameLink"><a href="../../../javax/swing/Painter.html#paint-java.awt.<API key>-">paint</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;g, <a href="../../../javax/swing/Painter.html" title="type parameter in Painter">T</a>&nbsp;object, int&nbsp;width, int&nbsp;height)</code> <div class="block">Renders to the given <a href="../../../java/awt/Graphics2D.html" title="class in java.awt"><code>Graphics2D</code></a> object.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="javax.swing.plaf.nimbus"> </a> <h3>Uses of <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a> in <a href="../../../javax/swing/plaf/nimbus/package-summary.html">javax.swing.plaf.nimbus</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../javax/swing/plaf/nimbus/package-summary.html">javax.swing.plaf.nimbus</a> with parameters of type <a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../javax/swing/plaf/nimbus/<API key>.html#<API key>.awt.Graphics2D-">configureGraphics</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;g)</code> <div class="block">Configures the given Graphics2D.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected abstract void</code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../javax/swing/plaf/nimbus/<API key>.html#doPaint-java.awt.Graphics2D-javax.swing.<API key>.lang.Object:A-">doPaint</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;g, <a href="../../../javax/swing/JComponent.html" title="class in javax.swing">JComponent</a>&nbsp;c, int&nbsp;width, int&nbsp;height, <a href="../../../java/lang/Object.html" title="class in java.lang">Object</a>[]&nbsp;extendedCacheKeys)</code> <div class="block">Actually performs the painting operation.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="typeNameLabel"><API key>.</span><code><span class="memberNameLink"><a href="../../../javax/swing/plaf/nimbus/<API key>.html#paint-java.awt.Graphics2D-javax.swing.JComponent-int-int-">paint</a></span>(<a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Graphics2D</a>&nbsp;g, <a href="../../../javax/swing/JComponent.html" title="class in javax.swing">JComponent</a>&nbsp;c, int&nbsp;w, int&nbsp;h)</code> <div class="block">Renders to the given <a href="../../../java/awt/Graphics2D.html" title="class in java.awt"><code>Graphics2D</code></a> object.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../java/awt/Graphics2D.html" title="class in java.awt">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><strong>Java&trade;&nbsp;Platform<br>Standard&nbsp;Ed.&nbsp;8</strong></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?java/awt/class-use/Graphics2D.html" target="_top">Frames</a></li> <li><a href="Graphics2D.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> <p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Copyright & </body> </html>
#ifndef WITH_CMAKE #include "ester-config.h" #endif #include "utils.h" #include "symbolic.h" #include <cstdlib> #include <typeinfo> using namespace std; sym::sym() { expr=new sym_num(0); context=NULL; } sym::~sym() { if(expr!=NULL) delete expr; } sym::sym(const sym &s) { context=s.context; expr=s.expr->clone(); } sym::sym(const double &q) { context=NULL; expr=new sym::sym_num(q); } sym::sym(const int &q) { context=NULL; expr=new sym::sym_num(q); } sym::sym(const rational &q) { context=NULL; expr=new sym::sym_num(q.eval()); } sym &sym::operator=(const sym &s) { context=s.context; delete expr; expr=s.expr->clone(); return *this; } ostream& operator<<(ostream& os, const sym &s) { return os<<*s.expr; } sym trig_simplify(const sym &s) { sym snew(s); bool temp=symbolic::trig_simplify; symbolic::trig_simplify=true; snew.expr=snew.expr->reduce(); symbolic::trig_simplify=temp; return snew; } sym_vec trig_simplify(const sym_vec &v) { sym_vec w; for(int i=0;i<3;i++) w(i)=trig_simplify(v(i)); return w; } sym_tens trig_simplify(const sym_tens &v) { sym_tens w; for(int i=0;i<3;i++) for(int j=0;j<3;j++) w(i,j)=trig_simplify(v(i,j)); return w; } symbolic *sym::check_context() const { if(context==NULL) { cerr<<"Symbolic: sym object not initialized"<<endl; exit(1); } return context; } symbolic *sym::check_context(const sym &s) const { symbolic *c; bool allow_null_1=typeid(*expr)==typeid(sym::sym_num); bool allow_null_2=typeid(*(s.expr))==typeid(sym::sym_num); if(this->context==NULL&&s.context==NULL&&allow_null_1&&allow_null_2) { return NULL; } if(this->context==NULL&&allow_null_1) { return s.check_context(); } if(s.context==NULL&&allow_null_2) { return check_context(); } c=check_context(); if(c!=s.check_context()) { cerr<<"Symbolic: Wrong context"<<endl; exit(1); } return c; } symbolic *sym::check_context(const sym_vec &s) const { symbolic *c; bool allow_null=typeid(*expr)==typeid(sym::sym_num); if(context==NULL&&allow_null) { return s.check_context(); } c=check_context(); if(c!=s.check_context()) { cerr<<"Symbolic: Wrong context"<<endl; exit(1); } return c; } symbolic *sym::check_context(const sym_tens &s) const { symbolic *c; bool allow_null=typeid(*expr)==typeid(sym::sym_num); if(context==NULL&&allow_null) { return s.check_context(); } c=check_context(); if(c!=s.check_context()) { cerr<<"Symbolic: Wrong context"<<endl; exit(1); } return c; } sym operator+(const sym &s1,const sym &s2) { sym snew; snew.context=s1.check_context(s2); delete snew.expr; snew.expr=s1.expr->clone(); snew.expr=snew.expr->add(*s2.expr)->reduce(); return snew; } sym operator*(const sym &s1,const sym &s2) { sym snew; snew.context=s1.check_context(s2); delete snew.expr; snew.expr=s1.expr->clone(); snew.expr=snew.expr->mult(*s2.expr)->reduce(); return snew; } sym pow(const sym &s,const rational &q) { if(typeid(*s.expr)==typeid(sym::sym_num)) return sym(pow(((sym::sym_num *)s.expr)->value,q.eval())); sym snew; snew.context=s.check_context(); delete snew.expr; snew.expr=s.expr->clone(); snew.expr=snew.expr->pow(q)->reduce(); return snew; } sym sin(const sym &s) { sym snew; snew.context=s.check_context(); delete snew.expr; snew.expr=s.expr->clone(); snew.expr=snew.expr->sin()->reduce(); return snew; } sym cos(const sym &s) { sym snew; snew.context=s.check_context(); delete snew.expr; snew.expr=s.expr->clone(); snew.expr=snew.expr->cos()->reduce(); return snew; } sym tan(const sym &s) { return sin(s)/cos(s); } sym exp(const sym &s) { sym snew; snew.context=s.check_context(); delete snew.expr; snew.expr=s.expr->clone(); snew.expr=snew.expr->exp()->reduce(); return snew; } sym log(const sym &s) { sym snew; snew.context=s.check_context(); delete snew.expr; snew.expr=s.expr->clone(); snew.expr=snew.expr->log()->reduce(); return snew; } sym pow(const sym &s,const sym &ex) { return exp(ex*log(s)); } sym pow(const double &n,const sym &ex) { return exp(ex*log(n)); } sym diff(const sym &f,const sym &x) { if(typeid(*x.expr)==typeid(sym::symbol)) { if(((sym::symbol *)x.expr)->is_indep) { return jacobian(f,x); } } ester_err("Error (symbolic): Can derive only respect to independent symbols"); } sym jacobian(const sym &f,const sym &a) { if(typeid(*a.expr)!=typeid(sym::symbol)&&typeid(*a.expr)!=typeid(sym::sym_deriv)) { ester_err("Error (symbolic): Can calculate jacobian only with respect to a symbol or a derivative of a symbol"); } sym snew; snew.context=f.check_context(a); delete snew.expr; snew.expr=f.expr->clone(); snew.expr=snew.expr->derive(*a.expr)->reduce(); return snew; } bool sym::operator==(const sym &s) const {return *expr==*s.expr;} matrix sym::eval() const { return expr->eval(); } void sym::add(solver *op,std::string eq_name,std::string var_name) const {check_context()->add(*this,op,0,"in",eq_name,var_name,ones(1,1));} void sym::add(solver *op,std::string eq_name,std::string var_name,const matrix &d) const {check_context()->add(*this,op,0,"in",eq_name,var_name,d);} void sym::add_ex(solver *op,int n,std::string eq_name,std::string var_name) const {check_context()->add(*this,op,n,"ex",eq_name,var_name,ones(1,1));} void sym::add_ex(solver *op,int n,std::string eq_name,std::string var_name,const matrix &d) const {check_context()->add(*this,op,n,"ex",eq_name,var_name,d);} void sym::bc_top1_add(solver *op,int n,std::string eq_name,std::string var_name) const {check_context()->add_bc(*this,op,n,"top1",eq_name,var_name,ones(1,1));} void sym::bc_top2_add(solver *op,int n,std::string eq_name,std::string var_name) const {check_context()->add_bc(*this,op,n,"top2",eq_name,var_name,ones(1,1));} void sym::bc_bot1_add(solver *op,int n,std::string eq_name,std::string var_name) const {check_context()->add_bc(*this,op,n,"bot1",eq_name,var_name,ones(1,1));} void sym::bc_bot2_add(solver *op,int n,std::string eq_name,std::string var_name) const {check_context()->add_bc(*this,op,n,"bot2",eq_name,var_name,ones(1,1));} void sym::bc_top1_add(solver *op,int n,std::string eq_name,std::string var_name,const matrix &d) const {check_context()->add_bc(*this,op,n,"top1",eq_name,var_name,d);} void sym::bc_top2_add(solver *op,int n,std::string eq_name,std::string var_name,const matrix &d) const {check_context()->add_bc(*this,op,n,"top2",eq_name,var_name,d);} void sym::bc_bot1_add(solver *op,int n,std::string eq_name,std::string var_name,const matrix &d) const {check_context()->add_bc(*this,op,n,"bot1",eq_name,var_name,d);} void sym::bc_bot2_add(solver *op,int n,std::string eq_name,std::string var_name,const matrix &d) const {check_context()->add_bc(*this,op,n,"bot2",eq_name,var_name,d);} std::ostream& sym::print(std::ostream& os) const { this->expr->print(os); return os; }
/* Error: File to import not found or unreadable: compass. on line 1 of theme8.scss 1: @import 'compass'; 2: @import 'bootstrap_lib/_variables'; 3: 4: $header-background: #333; 5: $color-style1: #43bebd; 6: $color1-style1: #fff; Backtrace: theme8.scss:1 C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/import_node.rb:67:in `rescue in import' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/import_node.rb:45:in `import' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/import_node.rb:28:in `imported_file' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/import_node.rb:37:in `css_import?' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:311:in `visit_import' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/base.rb:36:in `visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:158:in `block in visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/stack.rb:79:in `block in with_base' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/stack.rb:115:in `with_frame' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/stack.rb:79:in `with_base' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:158:in `visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/base.rb:52:in `block in visit_children' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/base.rb:52:in `map' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/base.rb:52:in `visit_children' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:167:in `block in visit_children' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:179:in `with_environment' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:166:in `visit_children' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/base.rb:36:in `block in visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:186:in `visit_root' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/base.rb:36:in `visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:157:in `visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/visitors/perform.rb:8:in `visit' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/root_node.rb:36:in `css_tree' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/tree/root_node.rb:29:in `<API key>' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/engine.rb:378:in `<API key>' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/engine.rb:295:in `<API key>' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/plugin/compiler.rb:490:in `update_stylesheet' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/plugin/compiler.rb:215:in `block in update_stylesheets' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/plugin/compiler.rb:209:in `each' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/plugin/compiler.rb:209:in `update_stylesheets' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/plugin.rb:82:in `update_stylesheets' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/exec/sass_scss.rb:363:in `watch_or_update' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/exec/sass_scss.rb:51:in `process_result' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/exec/base.rb:52:in `parse' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/lib/sass/exec/base.rb:19:in `parse!' C:/Ruby22/lib/ruby/gems/2.2.0/gems/sass-3.4.21/bin/scss:13:in `<top (required)>' C:/Ruby22/bin/scss:23:in `load' C:/Ruby22/bin/scss:23:in `<main>' */ body:before { white-space: pre; font-family: monospace; content: "Error: File to import not found or unreadable: compass.\A on line 1 of theme8.scss\A \A 1: @import 'compass';\A 2: @import 'bootstrap_lib/_variables';\A 3: \A 4: $header-background: #333;\A 5: $color-style1: #43bebd;\A 6: $color1-style1: #fff;"; }
package serviceaccess import ( "github.com/cloudfoundry/cli/cf/actors" "github.com/cloudfoundry/cli/cf/api/authentication" "github.com/cloudfoundry/cli/cf/commandregistry" "github.com/cloudfoundry/cli/cf/configuration/coreconfig" "github.com/cloudfoundry/cli/cf/flags" . "github.com/cloudfoundry/cli/cf/i18n" "github.com/cloudfoundry/cli/cf/requirements" "github.com/cloudfoundry/cli/cf/terminal" ) type <API key> struct { ui terminal.UI config coreconfig.Reader actor actors.ServicePlanActor tokenRefresher authentication.TokenRefresher } func init() { commandregistry.Register(&<API key>{}) } func (cmd *<API key>) MetaData() commandregistry.CommandMetadata { fs := make(map[string]flags.FlagSet) fs["p"] = &flags.StringFlag{ShortName: "p", Usage: T("Disable access to a specified service plan")} fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Disable access for a specified organization")} return commandregistry.CommandMetadata{ Name: "<API key>", Description: T("Disable access to a service or service plan for one or all orgs"), Usage: []string{ "CF_NAME <API key> SERVICE [-p PLAN] [-o ORG]", }, Flags: fs, } } func (cmd *<API key>) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) []requirements.Requirement { if len(fc.Args()) != 1 { cmd.ui.Failed(T("Incorrect Usage. Requires an argument\n\n") + commandregistry.Commands.CommandUsage("<API key>")) } reqs := []requirements.Requirement{ requirementsFactory.NewLoginRequirement(), } return reqs } func (cmd *<API key>) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command { cmd.ui = deps.UI cmd.config = deps.Config cmd.actor = deps.ServicePlanHandler cmd.tokenRefresher = deps.RepoLocator.Get<API key>() return cmd } func (cmd *<API key>) Execute(c flags.FlagContext) error { _, err := cmd.tokenRefresher.RefreshAuthToken() if err != nil { return err } serviceName := c.Args()[0] planName := c.String("p") orgName := c.String("o") if planName != "" && orgName != "" { err = cmd.<API key>(serviceName, planName, orgName) } else if planName != "" { err = cmd.<API key>(serviceName, planName) } else if orgName != "" { err = cmd.<API key>(serviceName, orgName) } else { err = cmd.<API key>(serviceName) } if err != nil { return err } cmd.ui.Ok() return nil } func (cmd *<API key>) <API key>(serviceName string) error { cmd.ui.Say(T("Disabling access to all plans of service {{.ServiceName}} for all orgs as {{.UserName}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceName), "UserName": terminal.EntityNameColor(cmd.config.Username()), }, )) return cmd.actor.<API key>(serviceName, false) } func (cmd *<API key>) <API key>(serviceName string, planName string, orgName string) error { cmd.ui.Say(T("Disabling access to plan {{.PlanName}} of service {{.ServiceName}} for org {{.OrgName}} as {{.Username}}...", map[string]interface{}{ "PlanName": terminal.EntityNameColor(planName), "ServiceName": terminal.EntityNameColor(serviceName), "OrgName": terminal.EntityNameColor(orgName), "Username": terminal.EntityNameColor(cmd.config.Username()), }, )) return cmd.actor.<API key>(serviceName, planName, orgName, false) } func (cmd *<API key>) <API key>(serviceName string, planName string) error { cmd.ui.Say(T("Disabling access of plan {{.PlanName}} for service {{.ServiceName}} as {{.Username}}...", map[string]interface{}{ "PlanName": terminal.EntityNameColor(planName), "ServiceName": terminal.EntityNameColor(serviceName), "Username": terminal.EntityNameColor(cmd.config.Username()), }, )) return cmd.actor.<API key>(serviceName, planName, false) } func (cmd *<API key>) <API key>(serviceName string, orgName string) error { cmd.ui.Say(T("Disabling access to all plans of service {{.ServiceName}} for the org {{.OrgName}} as {{.Username}}...", map[string]interface{}{ "ServiceName": terminal.EntityNameColor(serviceName), "OrgName": terminal.EntityNameColor(orgName), "Username": terminal.EntityNameColor(cmd.config.Username()), }, )) return cmd.actor.UpdateOrgForService(serviceName, orgName, false) }
#include <iostream> #include <string> #include <sstream> #include <cmath> #include <cstdio> #define maxI 99999999 #define min(a,b) ((a) < (b) ? (a) : (b)) using namespace std; int dp[305]; int weight[101]; int value[101]; int M; int main() { double temp; int cases = 1; while(cin >> temp) { weight[0] = 1; value[0] = round(temp*100); cin >> M; int num; for(int i = 1 ; i <= M;++i) { cin >> num >> temp; weight[i] = num; value[i] = round(temp*100); } for(int i = 0 ; i < 305;++i) { dp[i] = maxI; } dp[0] = 0; for(int i = 0 ; i <= M;++i) { for(int j = 0 ; j < 305;++j) { if(dp[j] != maxI) { if(j+weight[i] < 305) { dp[j+weight[i]] = min(dp[j+weight[i]] ,dp[j]+value[i]); } } } } getchar(); string s; getline(cin,s); stringstream ss; ss << s; int target; cout << "Case " << cases++ << ":\n"; while(ss >> target) { int minN = maxI; for(int i = target;i< 305;++i) { minN = min(minN,dp[i]); } printf("Buy %d for $%d.%.2d\n",target,minN/100,minN%100); } } return 0; }
package co.paralleluniverse.actors; import co.paralleluniverse.common.test.TestUtil; import co.paralleluniverse.common.util.Debug; import co.paralleluniverse.common.util.Exceptions; import co.paralleluniverse.fibers.Fiber; import co.paralleluniverse.fibers.<API key>; import co.paralleluniverse.fibers.FiberScheduler; import co.paralleluniverse.fibers.SuspendExecution; import co.paralleluniverse.strands.Strand; import co.paralleluniverse.strands.<API key>; import co.paralleluniverse.strands.channels.Channel; import co.paralleluniverse.strands.channels.Channels; import co.paralleluniverse.strands.channels.SendPort; import com.google.common.base.Function; import com.google.common.base.Predicate; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.rules.TestRule; /** * * @author pron */ public class ActorTest { @Rule public TestName name = new TestName(); @Rule public TestRule watchman = TestUtil.WATCHMAN; @BeforeClass public static void beforeClass() { Debug.dumpAfter(10000); } static final MailboxConfig mailboxConfig = new MailboxConfig(10, Channels.OverflowPolicy.THROW); private FiberScheduler scheduler; public ActorTest() { scheduler = new <API key>("test", 4, null, false); } private <Message, V> Actor<Message, V> spawnActor(Actor<Message, V> actor) { Fiber fiber = new Fiber("actor", scheduler, actor); fiber.<API key>(new Strand.<API key>() { @Override public void uncaughtException(Strand s, Throwable e) { e.printStackTrace(); throw Exceptions.rethrow(e); } }); fiber.start(); return actor; } @Test public void <API key>() throws Exception { Actor<Message, Integer> actor = spawnActor(new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { throw new RuntimeException("foo"); } }); try { actor.get(); fail(); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(RuntimeException.class)); assertThat(e.getCause().getMessage(), is("foo")); } } @Test public void <API key>() throws Exception { Actor<Message, Integer> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { throw new RuntimeException("foo"); } }; actor.spawnThread(); try { actor.get(); fail(); } catch (ExecutionException e) { assertThat(e.getCause(), instanceOf(RuntimeException.class)); assertThat(e.getCause().getMessage(), is("foo")); } } @Test public void <API key>() throws Exception { Actor<Message, Integer> actor = spawnActor(new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { return 42; } }); assertThat(actor.get(), is(42)); } @Test public void <API key>() throws Exception { Actor<Message, Integer> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { return 42; } }; actor.spawnThread(); assertThat(actor.get(), is(42)); } @Test public void testReceive() throws Exception { ActorRef<Message> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { Message m = receive(); return m.num; } }.spawn(); actor.send(new Message(15)); assertThat(LocalActor.<Integer>get(actor), is(15)); } @Test public void <API key>() throws Exception { ActorRef<Message> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { Message m = receive(); return m.num; } }.spawnThread(); actor.send(new Message(15)); assertThat(LocalActor.<Integer>get(actor), is(15)); } @Test public void <API key>() throws Exception { ActorRef<Message> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { Message m1 = receive(); Message m2 = receive(); return m1.num + m2.num; } }.spawn(); actor.send(new Message(25)); Thread.sleep(200); actor.send(new Message(17)); assertThat(LocalActor.<Integer>get(actor), is(42)); } @Test public void <API key>() throws Exception { ActorRef<Message> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { Message m1 = receive(); Message m2 = receive(); return m1.num + m2.num; } }.spawnThread(); actor.send(new Message(25)); Thread.sleep(200); actor.send(new Message(17)); assertThat(LocalActor.<Integer>get(actor), is(42)); } private class TypedReceiveA { }; private class TypedReceiveB { }; @Test public void testTypedReceive() throws Exception { Actor<Object, List<Object>> actor = spawnActor(new BasicActor<Object, List<Object>>(mailboxConfig) { @Override protected List<Object> doRun() throws <API key>, SuspendExecution { List<Object> list = new ArrayList<>(); list.add(receive(TypedReceiveA.class)); list.add(receive(TypedReceiveB.class)); return list; } }); final TypedReceiveB typedReceiveB = new TypedReceiveB(); final TypedReceiveA typedReceiveA = new TypedReceiveA(); actor.ref().send(typedReceiveB); Thread.sleep(2); actor.ref().send(typedReceiveA); assertThat(actor.get(500, TimeUnit.MILLISECONDS), equalTo(Arrays.asList(typedReceiveA, typedReceiveB))); } @Test public void <API key>() throws Exception { Actor<ComplexMessage, List<Integer>> actor = spawnActor(new BasicActor<ComplexMessage, List<Integer>>(mailboxConfig) { @Override protected List<Integer> doRun() throws SuspendExecution, <API key> { final List<Integer> list = new ArrayList<>(); for (int i = 0; i < 2; i++) { receive(new MessageProcessor<ComplexMessage, ComplexMessage>() { public ComplexMessage process(ComplexMessage m) throws SuspendExecution, <API key> { switch (m.type) { case FOO: list.add(m.num); receive(new MessageProcessor<ComplexMessage, ComplexMessage>() { public ComplexMessage process(ComplexMessage m) throws SuspendExecution, <API key> { switch (m.type) { case BAZ: list.add(m.num); return m; default: return null; } } }); return m; case BAR: list.add(m.num); return m; case BAZ: fail(); default: return null; } } }); } return list; } }); actor.ref().send(new ComplexMessage(ComplexMessage.Type.FOO, 1)); actor.ref().send(new ComplexMessage(ComplexMessage.Type.BAR, 2)); actor.ref().send(new ComplexMessage(ComplexMessage.Type.BAZ, 3)); assertThat(actor.get(), equalTo(Arrays.asList(1, 3, 2))); } @Test public void <API key>() throws Exception { Actor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Message m; m = receive(100, TimeUnit.MILLISECONDS); assertThat(m.num, is(1)); m = receive(100, TimeUnit.MILLISECONDS); assertThat(m.num, is(2)); m = receive(100, TimeUnit.MILLISECONDS); assertThat(m, is(nullValue())); return null; } }); actor.ref().send(new Message(1)); Thread.sleep(20); actor.ref().send(new Message(2)); Thread.sleep(200); actor.ref().send(new Message(3)); actor.join(); } @Test public void <API key>() throws Exception { Actor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { try { receive(100, TimeUnit.MILLISECONDS, new MessageProcessor<Message, Message>() { public Message process(Message m) throws SuspendExecution, <API key> { fail(); return m; } }); fail(); } catch (TimeoutException e) { } return null; } }); Thread.sleep(150); actor.ref().send(new Message(1)); actor.join(); } @Test public void testSendSync() throws Exception { final Actor<Message, Void> actor1 = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Message m; m = receive(); assertThat(m.num, is(1)); m = receive(); assertThat(m.num, is(2)); m = receive(); assertThat(m.num, is(3)); return null; } }); final Actor<Message, Void> actor2 = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Fiber.sleep(20); actor1.ref().send(new Message(1)); Fiber.sleep(10); actor1.sendSync(new Message(2)); actor1.ref().send(new Message(3)); return null; } }); actor1.join(); actor2.join(); } @Test public void testLink() throws Exception { Actor<Message, Void> actor1 = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Fiber.sleep(100); return null; } }); Actor<Message, Void> actor2 = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { try { for (;;) { receive(); } } catch (LifecycleException e) { } return null; } }); actor1.link(actor2.ref()); actor1.join(); actor2.join(); } @Test public void testWatch() throws Exception { Actor<Message, Void> actor1 = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Fiber.sleep(100); return null; } }); final AtomicBoolean handlerCalled = new AtomicBoolean(false); Actor<Message, Void> actor2 = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Message m = receive(200, TimeUnit.MILLISECONDS); assertThat(m, is(nullValue())); return null; } @Override protected Message <API key>(LifecycleMessage m) { super.<API key>(m); handlerCalled.set(true); return null; } }); actor2.watch(actor1.ref()); actor1.join(); actor2.join(); assertThat(handlerCalled.get(), is(true)); } @Test public void testWatchGC() throws Exception { Assume.assumeFalse(Debug.isDebug()); final Actor<Message, Void> actor = spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Fiber.sleep(120000); return null; } }); System.out.println("actor1 is " + actor); WeakReference wrActor2 = new WeakReference(spawnActor(new BasicActor<Message, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { Fiber.sleep(10); final Object watch = watch(actor.ref()); // unwatch(actor, watch); return null; } })); System.out.println("actor2 is " + wrActor2.get()); for (int i = 0; i < 10; i++) { Thread.sleep(10); System.gc(); } Thread.sleep(2000); assertEquals(null, wrActor2.get()); } @Test public void <API key>() throws Exception { final ActorRef<Integer> actor = new BasicActor<Integer, Void>(mailboxConfig) { @Override protected Void doRun() throws SuspendExecution, <API key> { return null; } }.spawn(); SendPort<Integer> ch1 = Channels.filterSend(actor, new Predicate<Integer>() { @Override public boolean apply(Integer input) { return input % 2 == 0; } }); SendPort<Integer> ch2 = Channels.mapSend(actor, new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input + 10; } }); assertTrue(ch1.equals(actor)); assertTrue(actor.equals(ch1)); assertTrue(ch2.equals(actor)); assertTrue(actor.equals(ch2)); } @Test public void <API key>() throws Exception { final AtomicBoolean run = new AtomicBoolean(false); Actor<Message, Integer> actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { run.set(true); return 3; } }; ActorRef a = actor.spawn(new <API key>().setFiber(null).setNameFormat("my-fiber-%d").build()); Strand s = LocalActor.getStrand(a); assertTrue(s.isFiber()); assertThat(s.getName(), equalTo("my-fiber-0")); assertThat((Integer) LocalActor.get(a), equalTo(3)); assertThat(run.get(), is(true)); run.set(false); actor = new BasicActor<Message, Integer>(mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { run.set(true); return 3; } }; a = actor.spawn(new <API key>().setThread(false).setNameFormat("my-thread-%d").build()); s = LocalActor.getStrand(a); assertTrue(!s.isFiber()); assertThat(s.getName(), equalTo("my-thread-0")); LocalActor.join(a); assertThat(run.get(), is(true)); run.set(false); Actor<Message, Integer> actor2 = new BasicActor<Message, Integer>("coolactor", mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { run.set(true); return 3; } }; a = actor2.spawn(new <API key>().setFiber(null).setNameFormat("my-fiber-%d").build()); s = LocalActor.getStrand(a); assertTrue(s.isFiber()); assertThat(s.getName(), equalTo("coolactor")); assertThat((Integer) LocalActor.get(a), equalTo(3)); assertThat(run.get(), is(true)); run.set(false); actor2 = new BasicActor<Message, Integer>("coolactor", mailboxConfig) { @Override protected Integer doRun() throws SuspendExecution, <API key> { run.set(true); return 3; } }; a = actor2.spawn(new <API key>().setThread(false).setNameFormat("my-thread-%d").build()); s = LocalActor.getStrand(a); assertTrue(!s.isFiber()); assertThat(s.getName(), equalTo("coolactor")); LocalActor.join(a); assertThat(run.get(), is(true)); run.set(false); } static class Message { final int num; public Message(int num) { this.num = num; } } static class ComplexMessage { enum Type { FOO, BAR, BAZ, WAT } final Type type; final int num; public ComplexMessage(Type type, int num) { this.type = type; this.num = num; } } }
// ChildView.cpp : CChildView #include "stdafx.h" #include "painter.h" #include "ChildView.h" #include "MainFrm.h" #include "Dialog.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CChildView IMPLEMENT_DYNCREATE(CChildView, CScrollView) BEGIN_MESSAGE_MAP(CChildView, CScrollView) ON_COMMAND(ID_FILE_PRINT, &CScrollView::OnFilePrint) ON_COMMAND(<API key>, &CScrollView::OnFilePrint) ON_COMMAND(<API key>, &CScrollView::OnFilePrintPreview) ON_WM_SETCURSOR() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_LBUTTONDBLCLK() ON_WM_RBUTTONUP() ON_WM_KILLFOCUS() ON_WM_SETFOCUS() ON_COMMAND(ID_EDIT_UNDO, &CChildView::OnEditUndo) ON_COMMAND(ID_EDIT_SIZE, &CChildView::OnEditSize) ON_COMMAND(ID_EDIT_CLEAR, &CChildView::OnEditClear) ON_COMMAND(ID_EDIT_PEN, &CChildView::OnEditPen) ON_COMMAND(ID_EDIT_LINE, &CChildView::OnEditLine) ON_COMMAND(ID_EDIT_RECT, &CChildView::OnEditRect) ON_COMMAND(ID_EDIT_ROUNDRECT, &CChildView::OnEditRoundrect) ON_COMMAND(ID_EDIT_ELLIPSE, &CChildView::OnEditEllipse) ON_COMMAND(ID_EDIT_POLYGON, &CChildView::OnEditPolygon) ON_COMMAND(ID_EDIT_BEZIER, &CChildView::OnEditBezier) ON_COMMAND(ID_EDIT_COLOR, &CChildView::OnEditColor) ON_COMMAND(ID_EDIT_NOTFILLING, &CChildView::OnEditNotfilling) ON_COMMAND(<API key>, &CChildView::OnEditErasefilling) ON_COMMAND(ID_EDIT_FULLFILLING, &CChildView::OnEditFullfilling) ON_COMMAND(ID_EDIT_ROUNDDEGREE, &CChildView::OnEditRounddegree) <API key>(ID_EDIT_UNDO, &CChildView::OnUpdateEditUndo) <API key>(ID_EDIT_NOTFILLING, &CChildView::<API key>) <API key>(<API key>, &CChildView::<API key>) <API key>(ID_EDIT_FULLFILLING, &CChildView::<API key>) <API key>(ID_EDIT_PEN, &CChildView::OnUpdateEditPen) <API key>(ID_EDIT_LINE, &CChildView::OnUpdateEditLine) <API key>(ID_EDIT_RECT, &CChildView::OnUpdateEditRect) <API key>(ID_EDIT_ROUNDRECT, &CChildView::<API key>) <API key>(ID_EDIT_ELLIPSE, &CChildView::OnUpdateEditEllipse) <API key>(ID_EDIT_POLYGON, &CChildView::OnUpdateEditPolygon) <API key>(ID_EDIT_BEZIER, &CChildView::OnUpdateEditBezier) <API key>(ID_EDIT_ROUNDDEGREE, &CChildView::<API key>) ON_COMMAND(ID_PAINTFILE_OPEN, &CChildView::OnPaintFileOpen) ON_COMMAND(ID_PAINTFILE_SAVE, &CChildView::OnPaintFileSave) ON_COMMAND(ID_EDIT_OPTION, &CChildView::OnEditOption) ON_COMMAND(ID_EDIT_PENSIZE, &CChildView::OnEditPensize) ON_COMMAND(ID_IMAGE_UDREVERSE, &CChildView::OnImageUdreverse) ON_COMMAND(ID_IMAGE_LRREVERSE, &CChildView::OnImageLrreverse) ON_COMMAND(ID_IMAGE_CORREVERSE, &CChildView::OnImageCorreverse) END_MESSAGE_MAP() // CChildView / CChildView::CChildView() { currentColor=RGB(0,0,0); currentWidth=1; //mouseCur=AfxGetApp()->LoadCursor(IDC_CURSOR1); drawType=LINE; drawMode=NOTFILLING; mouseLDown=CPoint(0,0); mouseLUp=CPoint(0,0); pCBitmap=NULL; hBitmap=NULL; tmpBitmap=NULL; DDBSize=CSize(800,600); //800x600 bFlag=FALSE; bDrawDrag=FALSE; DragDC=NULL; MemDC=NULL; DragPen=NULL; DragBrush=NULL; percentX=0.20; percentY=0.20; bDrawPolygon=FALSE; isUndo=FALSE; bTracePolygon=FALSE; WndportCenter=CPoint(0,0); ViewportOrg=CPoint(0,0); DragBezier=FALSE; DragBezierPos=NULL; DragBezierLoc=4; m_pDocument=NULL; } CChildView::~CChildView() { if (DragPen) { delete DragPen; DragPen=NULL; } if (DragBrush) { delete DragBrush; DragBrush=NULL; } if (DragDC) { delete DragDC; DragDC=NULL; } if (MemDC) { delete MemDC; MemDC=NULL; } if (pCBitmap) { delete pCBitmap; pCBitmap=NULL; } m_pDocument=NULL; } BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs) { if (!CScrollView::PreCreateWindow(cs)) return FALSE; //mouseCur=::LoadCursor(NULL,IDC_ARROW); mouseCur=AfxGetApp()->LoadCursor(IDC_CURSOR1); cs.dwExStyle |= WS_EX_CLIENTEDGE; cs.style &= ~WS_BORDER; //:(COLOR_WINDOW+12) cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, mouseCur, reinterpret_cast<HBRUSH>(COLOR_WINDOW+12), NULL); return TRUE; } void CChildView::OnInitialUpdate() { CScrollView::OnInitialUpdate(); SetScrollSizes(MM_TEXT, DDBSize); } // CChildView void CChildView::OnDraw(CDC *pDC) { WndportCenter=returnDrawRect().CenterPoint(); ViewportOrg=CPoint(0,0); pDC->DPtoLP(&ViewportOrg); if (!bFlag) { bFlag=TRUE; if (hBitmap!=NULL) { ::DeleteObject(hBitmap); } hBitmap = ::<API key>(pDC->m_hDC,DDBSize.cx,DDBSize.cy); if (tmpBitmap==NULL) tmpBitmap = ::<API key>(pDC->m_hDC,DDBSize.cx,DDBSize.cy); CDC dcToDDB; dcToDDB.CreateCompatibleDC(pDC); ::SelectObject(dcToDDB.m_hDC,hBitmap); ClearCanvas(&dcToDDB); pDC->BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,&dcToDDB,0,0,SRCCOPY); //::BitBlt(dcToDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dc.m_hDC,returnDrawRect().left,returnDrawRect().top,SRCCOPY); dcToDDB.DeleteDC(); //CBitmap *pBufferDDB = CBitmap::FromHandle(hBitmap); } else { //bufferDDB CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); CDC dcFromDDB; dcFromDDB.CreateCompatibleDC(pDC); dcFromDDB.SelectObject(pBufferDDB); pDC->BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,&dcFromDDB,0,0,SRCCOPY); //::BitBlt(dc.m_hDC,returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,dcFromDDB.m_hDC,0,0,SRCCOPY); dcFromDDB.DeleteDC(); } } // CChildView BOOL CChildView::OnPreparePrinting(CPrintInfo* pInfo) { return DoPreparePrinting(pInfo); } void CChildView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { } void CChildView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { } //dc2logiclogic2dc void CChildView::dc2logic(CPoint &cPoint) { int x,y; x= cPoint.x-WndportCenter.x; y=-cPoint.y+WndportCenter.y; cPoint=CPoint(x,y); } void CChildView::logic2dc(CPoint &cPoint) { int x,y; x= cPoint.x+WndportCenter.x; y=-cPoint.y+WndportCenter.y; cPoint=CPoint(x,y); } CPoint CChildView::logic2virtualDC(CPoint cPoint) { int x,y; x= cPoint.x+DDBSize.cx/2; y=-cPoint.y+DDBSize.cy/2; return CPoint(x,y); } CPoint CChildView::dc2virtualDC(CPoint cPoint) { int x,y; x= cPoint.x-WndportCenter.x+DDBSize.cx/2; y= cPoint.y-WndportCenter.y+DDBSize.cy/2; return CPoint(x,y); } CPoint CChildView::view2logic(CPoint cPoint) { int x,y; x= cPoint.x+ViewportOrg.x-WndportCenter.x; y=-cPoint.y-ViewportOrg.y+WndportCenter.y; return CPoint(x,y); } BOOL CChildView::HitCtrlPoint(CPoint HitPoint) { BOOL NotHit=FALSE; if (!PointList.IsEmpty()) { //PointListTRUE POSITION pos; pos=PointList.GetHeadPosition(); for (int i=0;i<4;i++) { if (pos!=NULL) { CPoint ctrlpoint; DragBezierPos=pos; DragBezierLoc=i; ctrlpoint=PointList.GetNext(pos); //pos if ((abs(HitPoint.x-ctrlpoint.x)<=2)&&(abs(HitPoint.y-ctrlpoint.y)<=2)) { return TRUE; } } } } DragBezierPos=NULL; DragBezierLoc=4; return NotHit; } void CChildView::OnLButtonDown(UINT nFlags,CPoint point) { CScrollView::OnLButtonDown(nFlags,point); bDrawDrag=TRUE; if (DragPen) { delete DragPen; DragPen=NULL; } if (DragBrush) { delete DragBrush; DragBrush=NULL; } if (DragDC) { delete DragDC; DragDC=NULL; } if (MemDC) { delete MemDC; MemDC=NULL; } if (pCBitmap) { delete pCBitmap; pCBitmap=NULL; } DragDC = new CClientDC(this); CScrollView::OnPrepareDC(DragDC); DragDC->DPtoLP(&point); mouseLDown=point; mouseLUp=point; DragDC->SetROP2(R2_NOTXORPEN); DragBrush = new CBrush(); if (drawMode==NOTFILLING) DragBrush->CreateStockObject(NULL_BRUSH); else if (drawMode==ERASEFILLING) DragBrush->CreateSolidBrush(RGB(255,255,255)); else if (drawMode==FULLFILLING) DragBrush->CreateSolidBrush(currentColor); else DragBrush->CreateStockObject(NULL_BRUSH); DragPen= new CPen(PS_SOLID,currentWidth,currentColor); switch (drawType) { case PEN: //SetPixelWindows DragDC->SetROP2(R2_COPYPEN); DragDC->SelectObject(DragPen); DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); break; case LINE: DragDC->SelectObject(DragPen); DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); break; case RECTANGLE: DragDC->SelectObject(DragBrush); DragDC->SelectObject(DragPen); DragDC->Rectangle(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); break; case ROUNDRECT: DragDC->SelectObject(DragBrush); DragDC->SelectObject(DragPen); DragDC->RoundRect(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y,(int)(mouseLDown.x-mouseLUp.x)*percentX,(int)(mouseLDown.y-mouseLUp.y)*percentY); break; case ELLIPSE: DragDC->SelectObject(DragBrush); DragDC->SelectObject(DragPen); DragDC->Ellipse(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); break; case POLYGON: if (PointList.IsEmpty()) { dc2logic(point); PointList.AddTail(point); logic2dc(point); } DragDC->SelectObject(DragPen); mouseLDown=PointList.GetTail(); logic2dc(mouseLDown); DragDC->MoveTo(mouseLDown); DragDC->LineTo(point); break; case BEZIER: if (PointList.GetSize()==4) { dc2logic(point); if (HitCtrlPoint(point)) { DragBezier=TRUE; CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dcFromTmpDDB; dcFromTmpDDB.CreateCompatibleDC(DragDC); dcFromTmpDDB.SelectObject(pTmpBitmap); DragDC->BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,&dcFromTmpDDB,0,0,SRCCOPY); dcFromTmpDDB.DeleteDC(); pTmpBitmap=NULL; //vector DragDC->SetROP2(R2_COPYPEN); PointSets.clear(); POSITION dPOS; dPOS=PointList.GetHeadPosition(); for (int j=0;j<4;j++) { if (dPOS!=NULL) DrawControlPoint(DragDC,PointList.GetNext(dPOS)); } DragDC->SetROP2(R2_NOTXORPEN); DrawPolyBezier(DragDC,RGB(192,192,192)); } logic2dc(point); } break; default: break; } SetCapture(); //::SetCapture(HWND); } void CChildView::OnMouseMove(UINT nFlags,CPoint point) { CScrollView::OnMouseMove(nFlags,point); if (bDrawDrag) { DragDC->DPtoLP(&point); switch (drawType) { case PEN: mouseLDown=mouseLUp; mouseLUp=point; DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); if (!MemDC) { if (!pCBitmap) { pCBitmap=new CBitmap; pCBitmap-><API key>(DragDC,DDBSize.cx,DDBSize.cy); } MemDC = new CDC; MemDC->CreateCompatibleDC(DragDC); MemDC->SelectObject(pCBitmap); MemDC->SelectObject(DragPen); CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); CDC dcFromDDB; dcFromDDB.CreateCompatibleDC(DragDC); dcFromDDB.SelectObject(pBufferDDB); MemDC->BitBlt(0,0,DDBSize.cx,DDBSize.cy,&dcFromDDB,0,0,SRCCOPY); dcFromDDB.DeleteDC(); pBufferDDB=NULL; } MemDC->MoveTo(dc2virtualDC(mouseLDown)); MemDC->LineTo(dc2virtualDC(mouseLUp)); break; case LINE: DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); mouseLUp=point; DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); break; case RECTANGLE: DragDC->Rectangle(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); mouseLUp=point; DragDC->Rectangle(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); break; case ROUNDRECT: DragDC->RoundRect(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y,(int)(mouseLDown.x-mouseLUp.x)*percentX,(int)(mouseLDown.y-mouseLUp.y)*percentY); mouseLUp=point; DragDC->RoundRect(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y,(int)(mouseLDown.x-mouseLUp.x)*percentX,(int)(mouseLDown.y-mouseLUp.y)*percentY); break; case ELLIPSE: DragDC->Ellipse(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); mouseLUp=point; DragDC->Ellipse(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); break; case POLYGON: DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); mouseLUp=point; DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); break; case BEZIER: if (DragBezier) { if (DragBezierLoc==4) break; if (DragBezierPos==NULL) break; DrawPolyBezier(DragDC,RGB(192,192,192)); dc2logic(point); PointList.SetAt(DragBezierPos,point); DrawPolyBezier(DragDC,RGB(192,192,192)); logic2dc(point); } break; default: break; } DragDC->LPtoDP(&point); } CPoint logicPoint=view2logic(point); //CMainFrame *pFrame = (CMainFrame*)this->GetParentFrame(); //CWnd CMainFrame *pFrame = (CMainFrame*)::AfxGetApp()->GetMainWnd(); pFrame->ShowCoordinate(logicPoint); } void CChildView::OnLButtonUp(UINT nFlags, CPoint point) { CScrollView::OnLButtonUp(nFlags,point); if (bDrawDrag) { CDC dcToTmpDDB,dcDDB; dcToTmpDDB.CreateCompatibleDC(DragDC); dcDDB.CreateCompatibleDC(DragDC); CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); dcToTmpDDB.SelectObject(pTmpBitmap); dcDDB.SelectObject(pBufferDDB); if (!bDrawPolygon) ::BitBlt(dcToTmpDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dcDDB.m_hDC,0,0,SRCCOPY); else { if (!bTracePolygon) ::BitBlt(dcToTmpDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dcDDB.m_hDC,0,0,SRCCOPY); bTracePolygon=TRUE; } dcToTmpDDB.DeleteDC(); pTmpBitmap=NULL; if (MemDC) { dcDDB.BitBlt(0,0,DDBSize.cx,DDBSize.cy,MemDC,0,0,SRCCOPY); delete MemDC; MemDC=NULL; delete pCBitmap; pCBitmap=NULL; } dcDDB.DeleteDC(); MemDC = new CDC; MemDC->CreateCompatibleDC(DragDC); MemDC->SelectObject(pBufferDDB); MemDC->SelectObject(DragPen); MemDC->SelectObject(DragBrush); DragDC->DPtoLP(&point); CPoint vmouseLDown,vmouseLUp; switch (drawType) { case PEN: mouseLDown=mouseLUp; mouseLUp=point; DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); MemDC->MoveTo(dc2virtualDC(mouseLDown)); MemDC->LineTo(dc2virtualDC(mouseLUp)); break; case LINE: DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); mouseLUp=point; DragDC->SetROP2(R2_COPYPEN); DragDC->MoveTo(mouseLDown); DragDC->LineTo(mouseLUp); MemDC->MoveTo(dc2virtualDC(mouseLDown)); MemDC->LineTo(dc2virtualDC(mouseLUp)); break; case RECTANGLE: DragDC->Rectangle(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); mouseLUp=point; DragDC->SetROP2(R2_COPYPEN); DragDC->Rectangle(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); vmouseLDown=dc2virtualDC(mouseLDown); vmouseLUp=dc2virtualDC(mouseLUp); MemDC->Rectangle(vmouseLDown.x,vmouseLDown.y,vmouseLUp.x,vmouseLUp.y); break; case ROUNDRECT: DragDC->RoundRect(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y,(int)(mouseLDown.x-mouseLUp.x)*percentX,(mouseLDown.y-mouseLUp.y)*percentY); mouseLUp=point; DragDC->SetROP2(R2_COPYPEN); DragDC->RoundRect(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y,(int)(mouseLDown.x-mouseLUp.x)*percentX,(mouseLDown.y-mouseLUp.y)*percentY); vmouseLDown=dc2virtualDC(mouseLDown); vmouseLUp=dc2virtualDC(mouseLUp); MemDC->RoundRect(vmouseLDown.x,vmouseLDown.y,vmouseLUp.x,vmouseLUp.y,(int)(vmouseLDown.x-vmouseLUp.x)*percentX,(vmouseLDown.y-vmouseLUp.y)*percentY); break; case ELLIPSE: DragDC->Ellipse(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); mouseLUp=point; DragDC->SetROP2(R2_COPYPEN); DragDC->Ellipse(mouseLDown.x,mouseLDown.y,mouseLUp.x,mouseLUp.y); vmouseLDown=dc2virtualDC(mouseLDown); vmouseLUp=dc2virtualDC(mouseLUp); MemDC->Ellipse(vmouseLDown.x,vmouseLDown.y,vmouseLUp.x,vmouseLUp.y); break; case POLYGON: mouseLUp=point; MemDC->MoveTo(dc2virtualDC(mouseLDown)); MemDC->LineTo(dc2virtualDC(mouseLUp)); dc2logic(mouseLUp); PointList.AddTail(mouseLUp); logic2dc(mouseLUp); break; case BEZIER: mouseLUp=point; DragDC->SetROP2(R2_COPYPEN); if (DragBezier) { if (DragBezierLoc==4) break; if (DragBezierPos==NULL) break; PointSet recPoints; recPoints=PointSets[DragBezierLoc]; logic2dc(recPoints.center); DragDC->SetPixel(recPoints.center.x-1,recPoints.center.y-1,recPoints.p1); DragDC->SetPixel(recPoints.center.x ,recPoints.center.y-1,recPoints.p2); DragDC->SetPixel(recPoints.center.x+1,recPoints.center.y-1,recPoints.p3); DragDC->SetPixel(recPoints.center.x-1,recPoints.center.y ,recPoints.p4); DragDC->SetPixel(recPoints.center.x ,recPoints.center.y ,recPoints.p5); DragDC->SetPixel(recPoints.center.x+1,recPoints.center.y ,recPoints.p6); DragDC->SetPixel(recPoints.center.x-1,recPoints.center.y+1,recPoints.p7); DragDC->SetPixel(recPoints.center.x ,recPoints.center.y+1,recPoints.p8); DragDC->SetPixel(recPoints.center.x+1,recPoints.center.y+1,recPoints.p9); recPoints.center=point; dc2logic(recPoints.center); recPoints.p1=DragDC->GetPixel(point.x-1,point.y-1); recPoints.p2=DragDC->GetPixel(point.x ,point.y-1); recPoints.p3=DragDC->GetPixel(point.x+1,point.y-1); recPoints.p4=DragDC->GetPixel(point.x-1,point.y ); recPoints.p5=DragDC->GetPixel(point.x ,point.y ); recPoints.p6=DragDC->GetPixel(point.x+1,point.y ); recPoints.p7=DragDC->GetPixel(point.x-1,point.y+1); recPoints.p8=DragDC->GetPixel(point.x ,point.y+1); recPoints.p9=DragDC->GetPixel(point.x+1,point.y+1); PointSets[DragBezierLoc]=recPoints; COLORREF pColor=RGB(192,192,192); DragDC->SetPixel(point.x-1,point.y-1,pColor); DragDC->SetPixel(point.x ,point.y-1,pColor); DragDC->SetPixel(point.x+1,point.y-1,pColor); DragDC->SetPixel(point.x-1,point.y ,pColor); DragDC->SetPixel(point.x ,point.y ,pColor); DragDC->SetPixel(point.x+1,point.y ,pColor); DragDC->SetPixel(point.x-1,point.y+1,pColor); DragDC->SetPixel(point.x ,point.y+1,pColor); DragDC->SetPixel(point.x+1,point.y+1,pColor); DragDC->SetROP2(R2_NOTXORPEN); DrawPolyBezier(DragDC,RGB(192,192,192)); DragDC->SetROP2(R2_COPYPEN); dc2logic(point); PointList.SetAt(DragBezierPos,point); logic2dc(point); pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dcFromTmpDDB; dcFromTmpDDB.CreateCompatibleDC(DragDC); dcFromTmpDDB.SelectObject(pTmpBitmap); MemDC->BitBlt(0,0,DDBSize.cx,DDBSize.cy,&dcFromTmpDDB,0,0,SRCCOPY); dcFromTmpDDB.DeleteDC(); pTmpBitmap=NULL; POSITION dPOS=PointList.GetHeadPosition(); for (int j=0;j<4;j++) { if (dPOS!=NULL) DrawVirControlPoint(MemDC,PointList.GetNext(dPOS)); } } if((int)PointList.GetSize()<4) { dc2logic(mouseLUp); DrawVirControlPoint(MemDC,mouseLUp); DrawControlPoint(DragDC,mouseLUp); PointList.AddTail(mouseLUp); logic2dc(mouseLUp); } if ((int)PointList.GetSize()==4) { DrawPolyBezier(DragDC,RGB(192,192,192)); DrawPolyBezier(MemDC,RGB(192,192,192),TRUE); } break; default: break; } delete DragBrush; DragBrush=NULL; delete DragPen; DragPen=NULL; delete DragDC; delete MemDC; DragDC=NULL; MemDC=NULL; if (pCBitmap) { delete pCBitmap; pCBitmap=NULL; } bDrawDrag=FALSE; ReleaseCapture(); isUndo=TRUE; DragBezier=FALSE; DragBezierPos=NULL; DragBezierLoc=4; } } void CChildView::OnLButtonDblClk(UINT nFlags, CPoint point) { CScrollView::OnLButtonDblClk(nFlags, point); if (bDrawPolygon) { CClientDC dc(this); CScrollView::OnPrepareDC(&dc); dc.DPtoLP(&point); CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); CDC dcToDDB; dcToDDB.CreateCompatibleDC(&dc); dcToDDB.SelectObject(pBufferDDB); dc2logic(point); PointList.AddTail(point); logic2dc(point); if (drawType==POLYGON) { CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dcFromTmpDDB; dcFromTmpDDB.CreateCompatibleDC(&dc); dcFromTmpDDB.SelectObject(pTmpBitmap); dcToDDB.BitBlt(0,0,DDBSize.cx,DDBSize.cy,&dcFromTmpDDB,0,0,SRCCOPY); dcFromTmpDDB.DeleteDC(); DrawPolygon(&dcToDDB); } else if (drawType==BEZIER) { CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dcFromTmpDDB; dcFromTmpDDB.CreateCompatibleDC(&dc); dcFromTmpDDB.SelectObject(pTmpBitmap); dcToDDB.BitBlt(0,0,DDBSize.cx,DDBSize.cy,&dcFromTmpDDB,0,0,SRCCOPY); dcFromTmpDDB.DeleteDC(); PointSets.clear(); DrawPolyBezier(&dcToDDB,currentColor,TRUE); } dc.BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,&dcToDDB,0,0,SRCCOPY); dcToDDB.DeleteDC(); bTracePolygon=FALSE; DragBezier=FALSE; DragBezierPos=NULL; DragBezierLoc=4; PointList.RemoveAll(); } } void CChildView::OnKillFocus(CWnd* pNewWnd) { CScrollView::OnKillFocus(pNewWnd); if (bDrawDrag) { CBitmap *pBufferDDB = CBitmap::FromHandle(hBitmap); if (MemDC) { delete MemDC; MemDC=NULL; } MemDC = new CDC; MemDC->CreateCompatibleDC(DragDC); MemDC->SelectObject(pBufferDDB); DragDC->BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,MemDC,0,0,SRCCOPY); delete MemDC; MemDC=NULL; pBufferDDB=NULL; delete DragBrush; DragBrush=NULL; delete DragPen; DragPen=NULL; delete DragDC; DragDC=NULL; if (pCBitmap) { delete pCBitmap; pCBitmap=NULL; } bDrawDrag=FALSE; ReleaseCapture(); DragBezier=FALSE; DragBezierPos=NULL; DragBezierLoc=4; if ((drawType==POLYGON)||(drawType==BEZIER)) { bTracePolygon=FALSE; PointList.RemoveAll(); PointSets.clear(); } } } void CChildView::OnSetFocus(CWnd* pOldWnd) { CScrollView::OnSetFocus(pOldWnd); CWnd::Invalidate(TRUE); CWnd::UpdateWindow(); } //OnSetCursor BOOL CChildView::OnSetCursor(CWnd *pWnd, UINT nHitTest, UINT message) { BOOL apiRet; apiRet=CScrollView::OnSetCursor(pWnd,nHitTest,message); if ((apiRet==FALSE)&&(nHitTest==HTCLIENT)) ::SetCursor(mouseCur); return apiRet; } void CChildView::OnEditPen() { drawType=PEN; bDrawPolygon=FALSE; } void CChildView::OnEditLine() { drawType=LINE; bDrawPolygon=FALSE; } void CChildView::OnEditRect() { drawType=RECTANGLE; bDrawPolygon=FALSE; } void CChildView::OnEditRoundrect() { drawType=ROUNDRECT; bDrawPolygon=FALSE; } void CChildView::OnEditEllipse() { drawType=ELLIPSE; bDrawPolygon=FALSE; } void CChildView::OnEditPolygon() { drawType=POLYGON; bTracePolygon=FALSE; bDrawPolygon=TRUE; PointList.RemoveAll(); } void CChildView::OnEditBezier() { drawType=BEZIER; DragBezierPos=NULL; DragBezierLoc=4; bDrawPolygon=TRUE; bTracePolygon=FALSE; DragBezier=FALSE; PointList.RemoveAll(); PointSets.clear(); } void CChildView::OnEditColor() { COLORREF theColor; CColorDialog selectColor; if (selectColor.DoModal() == IDOK) { theColor=selectColor.GetColor(); currentColor=theColor; } } void CChildView::OnEditNotfilling() { drawMode=NOTFILLING; } void CChildView::OnEditErasefilling() { drawMode=ERASEFILLING; } void CChildView::OnEditFullfilling() { drawMode=FULLFILLING; } void CChildView::OnEditClear() { bFlag=FALSE; isUndo=TRUE; CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dc; dc.Attach(::GetDC(NULL)); CDC dcFromDDB,dcToTmpDDB; dcFromDDB.CreateCompatibleDC(&dc); dcFromDDB.SelectObject(pBufferDDB); dcToTmpDDB.CreateCompatibleDC(&dc); dcToTmpDDB.SelectObject(pTmpBitmap); ::BitBlt(dcToTmpDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dcFromDDB.m_hDC,0,0,SRCCOPY); dcToTmpDDB.DeleteDC(); dcFromDDB.DeleteDC(); ::ReleaseDC(NULL,dc.Detach()); if ((drawType==POLYGON)||(drawType==BEZIER)) { bTracePolygon=FALSE; PointList.RemoveAll(); PointSets.clear(); } CWnd::Invalidate(TRUE); //WM_PAINT } CRect CChildView::returnDrawRect() { CRect CanvasArea; GetClientRect(&CanvasArea); CPoint center; center=CanvasArea.CenterPoint(); if (CanvasArea.Width()<DDBSize.cx) { center.x=DDBSize.cx*0.5; } if (CanvasArea.Height()<DDBSize.cy) { center.y=DDBSize.cy*0.5; } CanvasArea=CRect(CPoint(center.x-(LONG)(DDBSize.cx*0.5),center.y-(LONG)(DDBSize.cy*0.5)),DDBSize); //800*600 return CanvasArea; } void CChildView::ClearCanvas(CDC *pDC) { CBrush brush(RGB(255,255,255)); CPen pen; pen.CreatePen(PS_SOLID,1,RGB(255,255,255)); pDC->SelectObject(&brush); pDC->SelectObject(&pen); pDC->Rectangle(0,0,DDBSize.cx,DDBSize.cy); brush.DeleteObject(); pen.DeleteObject(); } void CChildView::DrawPolygon(CDC *pDC) { if (!PointList.IsEmpty()) { CPen pen; pen.CreatePen(PS_SOLID,currentWidth,currentColor); pDC->SelectObject(&pen); CBrush brush; if (drawMode==NOTFILLING) brush.CreateStockObject(NULL_BRUSH); else if (drawMode==ERASEFILLING) brush.CreateSolidBrush(RGB(255,255,255)); else if (drawMode==FULLFILLING) brush.CreateSolidBrush(currentColor); else brush.CreateStockObject(NULL_BRUSH); pDC->SelectObject(&brush); //PointList int nCount; nCount=PointList.GetSize(); CPoint *pPoint = new CPoint[nCount]; POSITION pos; pos=PointList.GetHeadPosition(); for (int i=0;i<nCount;i++) { pPoint[i]=PointList.GetNext(pos); pPoint[i]=logic2virtualDC(pPoint[i]); } pDC->Polygon(pPoint,nCount); pen.DeleteObject(); brush.DeleteObject(); delete []pPoint; pPoint=NULL; } } //PointListy void CChildView::DrawPolyBezier(CDC *pDC,COLORREF theColor,BOOL bVirtualDC) { if (!PointList.IsEmpty()) { CPen pen; pen.CreatePen(PS_SOLID,currentWidth,theColor); pDC->SelectObject(&pen); //PointList CPoint *pPoint = new CPoint[4]; POSITION pos; pos=PointList.GetHeadPosition(); for (int i=0;i<4;i++) { if (pos!=NULL) { pPoint[i]=PointList.GetNext(pos); if (!bVirtualDC) logic2dc(pPoint[i]); else pPoint[i]=logic2virtualDC(pPoint[i]); } else pPoint[i]=pPoint[i-1]; } pDC->PolyBezier(pPoint,4); pen.DeleteObject(); delete []pPoint; pPoint=NULL; } } //ctrlPoint void CChildView::DrawControlPoint(CDC *pDC,CPoint ctrlPoint) { logic2dc(ctrlPoint); int x,y; x=ctrlPoint.x; y=ctrlPoint.y; dc2logic(ctrlPoint); PointSet coverPoints; coverPoints.center=ctrlPoint; coverPoints.p1=pDC->GetPixel(x-1,y-1); coverPoints.p2=pDC->GetPixel(x, y-1); coverPoints.p3=pDC->GetPixel(x+1,y-1); coverPoints.p4=pDC->GetPixel(x-1,y); coverPoints.p5=pDC->GetPixel(x, y); coverPoints.p6=pDC->GetPixel(x+1,y); coverPoints.p7=pDC->GetPixel(x-1,y+1); coverPoints.p8=pDC->GetPixel(x, y+1); coverPoints.p9=pDC->GetPixel(x+1,y+1); PointSets.push_back(coverPoints); COLORREF pColor=RGB(192,192,192); pDC->SetPixel(x-1,y-1,pColor); pDC->SetPixel(x, y-1,pColor); pDC->SetPixel(x+1,y-1,pColor); pDC->SetPixel(x-1,y, pColor); pDC->SetPixel(x, y, pColor); pDC->SetPixel(x+1,y, pColor); pDC->SetPixel(x-1,y+1,pColor); pDC->SetPixel(x, y+1,pColor); pDC->SetPixel(x+1,y+1,pColor); } void CChildView::DrawVirControlPoint(CDC *pDC, CPoint ctrlPoint) { CPoint vPoint=logic2virtualDC(ctrlPoint); int x,y; x=vPoint.x; y=vPoint.y; COLORREF pColor=RGB(192,192,192); pDC->SetPixel(x-1,y-1,pColor); pDC->SetPixel(x, y-1,pColor); pDC->SetPixel(x+1,y-1,pColor); pDC->SetPixel(x-1,y, pColor); pDC->SetPixel(x, y, pColor); pDC->SetPixel(x+1,y, pColor); pDC->SetPixel(x-1,y+1,pColor); pDC->SetPixel(x, y+1,pColor); pDC->SetPixel(x+1,y+1,pColor); } void CChildView::ChangeCanvasSize(CSize *newsize) { bFlag=TRUE; isUndo=FALSE; if ((drawType==POLYGON)||(drawType==BEZIER)) { bTracePolygon=FALSE; PointList.RemoveAll(); PointSets.clear(); } CDC dc; dc.Attach(::GetDC(NULL)); CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); if (tmpBitmap!=NULL) ::DeleteObject(tmpBitmap); tmpBitmap = ::<API key>(dc.m_hDC,newsize->cx,newsize->cy); CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dcFromDDB,dcTmpDDB; dcFromDDB.CreateCompatibleDC(&dc); dcFromDDB.SelectObject(pBufferDDB); dcTmpDDB.CreateCompatibleDC(&dc); dcTmpDDB.SelectObject(pTmpBitmap); CBrush brush(RGB(255,255,255)); CPen pen; pen.CreatePen(PS_SOLID,1,RGB(255,255,255)); dcTmpDDB.SelectObject(&brush); dcTmpDDB.SelectObject(&pen); dcTmpDDB.Rectangle(0,0,newsize->cx,newsize->cy); brush.DeleteObject(); pen.DeleteObject(); ::BitBlt(dcTmpDDB.m_hDC,0,0,((DDBSize.cx>newsize->cx)?newsize->cx:DDBSize.cx), ((DDBSize.cy>newsize->cy)?newsize->cy:DDBSize.cy),dcFromDDB.m_hDC,0,0,SRCCOPY); dcFromDDB.DeleteDC(); DDBSize.cx=newsize->cx; DDBSize.cy=newsize->cy; pBufferDDB=NULL; ::DeleteObject(hBitmap); hBitmap = ::<API key>(dc.m_hDC,DDBSize.cx,DDBSize.cy); pBufferDDB=CBitmap::FromHandle(hBitmap); CDC dcToDDB; dcToDDB.CreateCompatibleDC(&dc); dcToDDB.SelectObject(pBufferDDB); ::BitBlt(dcToDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dcTmpDDB.m_hDC,0,0,SRCCOPY); dcToDDB.DeleteDC(); dcTmpDDB.DeleteDC(); ::ReleaseDC(NULL,dc.Detach()); SetScrollSizes(MM_TEXT, DDBSize); CWnd::Invalidate(TRUE); } void CChildView::OnEditUndo() { if (isUndo) { CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CClientDC dc(this); CScrollView::OnPrepareDC(&dc); CDC dcToDDB,dcFromTmpDDB; dcToDDB.CreateCompatibleDC(&dc); dcToDDB.SelectObject(pBufferDDB); dcFromTmpDDB.CreateCompatibleDC(&dc); dcFromTmpDDB.SelectObject(pTmpBitmap); ::BitBlt(dcToDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dcFromTmpDDB.m_hDC,0,0,SRCCOPY); dc.BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,&dcFromTmpDDB,0,0,SRCCOPY); dcToDDB.DeleteDC(); dcFromTmpDDB.DeleteDC(); isUndo=FALSE; if ((drawType==POLYGON)||(drawType==BEZIER)) { bTracePolygon=FALSE; PointList.RemoveAll(); PointSets.clear(); } } } void CChildView::OnEditSize() { DialogPageTwo m_page2; m_page2.m_width = DDBSize.cx; m_page2.m_height = DDBSize.cy; DialogSheet sheet(this); sheet.AddPage(&m_page2); sheet.SetActivePage(0); if (sheet.DoModal() == IDOK) { CSize newSize; newSize.cx=m_page2.m_width; newSize.cy=m_page2.m_height; if (DDBSize != newSize) ChangeCanvasSize(&newSize); } } void CChildView::OnUpdateEditUndo(CCmdUI *pCmdUI) { if (isUndo) pCmdUI->Enable(TRUE); else pCmdUI->Enable(FALSE); } void CChildView::<API key>(CCmdUI *pCmdUI) { if (drawMode==NOTFILLING) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::<API key>(CCmdUI *pCmdUI) { if (drawMode==ERASEFILLING) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::<API key>(CCmdUI *pCmdUI) { if (drawMode==FULLFILLING) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnUpdateEditPen(CCmdUI *pCmdUI) { if (drawType==PEN) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnUpdateEditLine(CCmdUI *pCmdUI) { if (drawType==LINE) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnUpdateEditRect(CCmdUI *pCmdUI) { if (drawType==RECTANGLE) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::<API key>(CCmdUI *pCmdUI) { if (drawType==ROUNDRECT) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnUpdateEditEllipse(CCmdUI *pCmdUI) { if (drawType==ELLIPSE) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnUpdateEditPolygon(CCmdUI *pCmdUI) { if (drawType==POLYGON) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnUpdateEditBezier(CCmdUI *pCmdUI) { if (drawType==BEZIER) pCmdUI->SetCheck(TRUE); else pCmdUI->SetCheck(FALSE); } void CChildView::OnRButtonUp(UINT nFlags, CPoint point) { CScrollView::OnRButtonUp(nFlags, point); CMenu menu; menu.LoadMenu(IDR_FLOATMENU); CMenu *pM=menu.GetSubMenu(0); if (isUndo) pM->EnableMenuItem(ID_EDIT_UNDO,MF_ENABLED); else pM->EnableMenuItem(ID_EDIT_UNDO,MF_GRAYED); if (drawType==PEN) pM->CheckMenuItem(ID_EDIT_PEN,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_PEN,MF_UNCHECKED); if (drawType==LINE) pM->CheckMenuItem(ID_EDIT_LINE,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_LINE,MF_UNCHECKED); if (drawType==RECTANGLE) pM->CheckMenuItem(ID_EDIT_RECT,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_RECT,MF_UNCHECKED); if (drawType==ROUNDRECT) { pM->CheckMenuItem(ID_EDIT_ROUNDRECT,MF_CHECKED); pM->EnableMenuItem(ID_EDIT_ROUNDDEGREE,MF_ENABLED); } else { pM->CheckMenuItem(ID_EDIT_ROUNDRECT,MF_UNCHECKED); pM->EnableMenuItem(ID_EDIT_ROUNDDEGREE,MF_GRAYED); } if (drawType==ELLIPSE) pM->CheckMenuItem(ID_EDIT_ELLIPSE,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_ELLIPSE,MF_UNCHECKED); if (drawType==POLYGON) pM->CheckMenuItem(ID_EDIT_POLYGON,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_POLYGON,MF_UNCHECKED); if (drawType==BEZIER) pM->CheckMenuItem(ID_EDIT_BEZIER,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_BEZIER,MF_UNCHECKED); if (drawMode==NOTFILLING) pM->CheckMenuItem(ID_EDIT_NOTFILLING,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_NOTFILLING,MF_UNCHECKED); if (drawMode==ERASEFILLING) pM->CheckMenuItem(<API key>,MF_CHECKED); else pM->CheckMenuItem(<API key>,MF_UNCHECKED); if (drawMode==FULLFILLING) pM->CheckMenuItem(ID_EDIT_FULLFILLING,MF_CHECKED); else pM->CheckMenuItem(ID_EDIT_FULLFILLING,MF_UNCHECKED); CPoint pt; GetCursorPos(&pt); pM->TrackPopupMenu(TPM_LEFTALIGN,pt.x,pt.y,this); /* CMenu pMenu; pMenu.LoadMenu(IDR_MAINFRAME); CMenu *pSubMenu=pMenu.GetSubMenu(1); CPoint mpt; GetCursorPos(&mpt); pSubMenu->TrackPopupMenu(TPM_LEFTALIGN,mpt.x,mpt.y,this); */ } void CChildView::OnEditRounddegree() { DialogPageOne m_page1; m_page1.m_x=percentX; m_page1.m_y=percentY; DialogSheet sheet(this); sheet.AddPage(&m_page1); sheet.SetActivePage(0); if (sheet.DoModal() == IDOK) { percentX=m_page1.m_x; percentY=m_page1.m_y; } } void CChildView::<API key>(CCmdUI *pCmdUI) { if (drawType==ROUNDRECT) pCmdUI->Enable(TRUE); else pCmdUI->Enable(FALSE); } void CChildView::OnPaintFileOpen() { CFileDialog openFile(TRUE,L"*.bmp",NULL,OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST,L"(*.bmp)|*.bmp||"); if (openFile.DoModal() == IDOK) { FileName = openFile.GetPathName(); CFile openFile; if (!openFile.Open(FileName,CFile::modeRead|CFile::shareDenyWrite)) { openFile.Close(); ::AfxMessageBox(L"",MB_OK); return; } BITMAPFILEHEADER bHead; openFile.Read(&bHead,sizeof(bHead)); if (bHead.bfType!=0x4d42) { //BMP openFile.Close(); ::AfxMessageBox(L"",MB_OK); return; } if (openFile.GetLength()!=bHead.bfSize) { openFile.Close(); ::AfxMessageBox(L"",MB_OK); return; } BITMAPINFOHEADER bi; openFile.Read(&bi,sizeof(bi)); int numQuad=0; //1532K if(bi.biBitCount<15) { numQuad=1<<bi.biBitCount; } /* switch (bi.biBitCount) { case 1: numQuad=2; break; case 4: numQuad=16; break; case 8: numQuad=256; break; } */ BITMAPINFO *pbi; RGBQUAD *quad; BYTE *lpBits; pbi=(BITMAPINFO*)HeapAlloc(GetProcessHeap(),0,sizeof(BITMAPINFOHEADER)+numQuad*sizeof(RGBQUAD)); memcpy(pbi,&bi,sizeof(bi)); quad=(RGBQUAD*)((BYTE*)pbi+sizeof(BITMAPINFOHEADER)); if(numQuad!=0) { openFile.Read(quad,sizeof(RGBQUAD)*numQuad); } bi.biSizeImage=bHead.bfSize-bHead.bfOffBits; lpBits=(BYTE*)HeapAlloc(GetProcessHeap(),0,bi.biSizeImage); openFile.Read(lpBits,bi.biSizeImage); openFile.Close(); CClientDC dc(this); CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); CBitmap *pTmpBitmap=CBitmap::FromHandle(tmpBitmap); CDC dcToDDB,dcToTmpDDB; dcToDDB.CreateCompatibleDC(&dc); dcToDDB.SelectObject(pBufferDDB); dcToTmpDDB.CreateCompatibleDC(&dc); dcToTmpDDB.SelectObject(pTmpBitmap); isUndo=TRUE; ::BitBlt(dcToTmpDDB.m_hDC,0,0,DDBSize.cx,DDBSize.cy,dcToDDB.m_hDC,0,0,SRCCOPY); dcToTmpDDB.DeleteDC(); //hBitmap ClearCanvas(&dcToDDB); //hBitmap ::SetDIBitsToDevice(dcToDDB.m_hDC,0,0, ((bi.biWidth>DDBSize.cx)?DDBSize.cx:bi.biWidth), ((bi.biHeight>DDBSize.cy)?DDBSize.cy:bi.biHeight), 0,0,((bi.biHeight>DDBSize.cy)?DDBSize.cy-bi.biHeight:0),bi.biHeight,lpBits,pbi,DIB_RGB_COLORS); HeapFree(GetProcessHeap(),0,pbi); HeapFree(GetProcessHeap(),0,lpBits); CScrollView::OnPrepareDC(&dc); dc.BitBlt(returnDrawRect().left,returnDrawRect().top,DDBSize.cx,DDBSize.cy,&dcToDDB,0,0,SRCCOPY); dcToDDB.DeleteDC(); if ((drawType==POLYGON)||(drawType==BEZIER)) { bTracePolygon=FALSE; PointList.RemoveAll(); PointSets.clear(); } } } void CChildView::OnPaintFileSave() { CFileDialog saveFile(FALSE,L"*.bmp",NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_PATHMUSTEXIST,L"(*.bmp)|*.bmp||"); if (saveFile.DoModal() == IDOK) { FileName = saveFile.GetPathName(); CFile saveBmp; if (!saveBmp.Open(FileName,CFile::modeCreate|CFile::modeWrite|CFile::shareExclusive|CFile::typeBinary)) { ::AfxMessageBox(L"",MB_OK); return; } int bitsperPixel; WORD bitCount=1; //148162432 DWORD PaletteSize=0; DWORD BitmapSize=0; CClientDC dc(this); bitsperPixel=dc.GetDeviceCaps(BITSPIXEL)*dc.GetDeviceCaps(PLANES); switch (bitsperPixel) { case 1: bitCount=1; break; case 2: bitCount=4; break; case 4: bitCount=4; break; case 8: bitCount=8; break; case 15: bitCount=16; break; case 16: bitCount=16; break; case 24: bitCount=24; break; case 32: //32b bitCount=32; break; } /* if (bitsperPixel<=1) bitCount=1; else if (bitsperPixel<=4) bitCount=4; else if (bitsperPixel<=8) bitCount=8; else if (bitsperPixel<=16) bitCount=16; else if (bitsperPixel<=24) bitCount=24; else bitCount=32; */ if(bitCount<=8) PaletteSize=1<<bitCount; //DDB CBitmap *pBufferDDB=CBitmap::FromHandle(hBitmap); BITMAP Bitmap; ::GetObject(hBitmap,sizeof(BITMAP),(LPSTR)&Bitmap); BitmapSize=((Bitmap.bmWidth*bitCount+31)/32)*4*Bitmap.bmHeight; /* BitmapSize=(Bitmap.bmWidth*bitCount+7)/8; //88 BitmapSize=(BitmapSize+3)/4; //4 BitmapSize=BitmapSize*4 //BitmapSizeBmp4 BitmapSize=BitmapSize*Bitmap.bmHeight; */ BITMAPFILEHEADER bitmapfileheader; bitmapfileheader.bfType=0x4d42; bitmapfileheader.bfReserved1=bitmapfileheader.bfReserved2=0; bitmapfileheader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+PaletteSize*sizeof(RGBQUAD); bitmapfileheader.bfSize=bitmapfileheader.bfOffBits+BitmapSize; BITMAPINFO *lpBitmapInfo; lpBitmapInfo=(BITMAPINFO*)new char[sizeof(BITMAPINFOHEADER)+PaletteSize*sizeof(RGBQUAD)]; lpBitmapInfo->bmiHeader.biSize=sizeof(BITMAPINFOHEADER); lpBitmapInfo->bmiHeader.biWidth=Bitmap.bmWidth; lpBitmapInfo->bmiHeader.biHeight=Bitmap.bmHeight; lpBitmapInfo->bmiHeader.biPlanes=1; lpBitmapInfo->bmiHeader.biBitCount=bitCount; lpBitmapInfo->bmiHeader.biCompression=BI_RGB;
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <title>Checkers</title> <link rel="stylesheet" href="default.css"> <script> var usersTurn = false; var piece = []; var game = ""; function updateBoard(data){ var arr = data.split(""); for(var index = 0; index < 32; index++){ var div = document.createElement("div"); var square = document.getElementById((index + 1).toString()); if(arr[index] === "1"){//player one div.className = "p1"; div.setAttribute('onclick', 'clicked(this)'); square.appendChild(div); }else if(arr[index] === "2"){//player two div.className = "p2"; div.setAttribute('onclick', 'clicked(this)'); square.appendChild(div); }else{ div.className = "p0"; div.setAttribute('onclick', 'clicked(this)'); square.appendChild(div); } } } function updateMove(){ document.getElementById("move").innerHTML = "Move: " + (piece[0] === undefined ? "" : piece[0]); for(var i = 1; i < piece.length; i++){ document.getElementById("move").innerHTML += " to " + piece[i]; } document.getElementById("formMove").value = (piece[0] === undefined ? "" : piece[0]); for(i = 1; i < piece.length; i++){ //"a" will be used to seperate numbers, so 1 and 5 won't be confused as 15 document.getElementById("formMove").value += "a" + piece[i]; } } function clicked(div){ //it's okay if it's not their piece, because the verification function checks that if(piece[piece.length - 1] === div.parentElement.id){ piece.pop(); updateMove(); }else{ piece.push(div.parentElement.id); updateMove(); } } </script> </head> <body> <div class="header"> <!--All may be changed later <span class="header"><a href="<?php if(!isset($_SESSION["username"])){ ?>login.php">Login<?php }else{ ?>game.php"><?php echo htmlspecialchars($_SESSION["username"]); } ?></a></span> <span class="header"><a href="<?php if(!isset($_SESSION["username"])){ ?>register.php">Register<?php }else{ ?>signout.php">Logout<?php } ?></a></span> <span class="header"><a href="main.php">Home</a></span> <span class="header"><a href="https://github.com/superreg/checkers/issues">Feedback</a></span> <span class="header"><a href="https://github.com/superreg/checkers/blob/master/README.md">About</a></span> </div> <?php require "functions.php"; //need to be logged in if(!isset($_SESSION["username"])){ echo "<p class=\"error\">You are not logged in! Click <a href=\"login.php\">here</a> to login.</p>"; }else{ $db = mysqli_connect("localhost", "checkers", "PASSWORD", "checkers"); if(<API key>($db)){ echo "<p class=\"error\">" . <API key>($db) . "</p>"; }else{ //check if a game is selected if(!isset($_GET["game"]) && !isset($_GET["formMove"])){ //TODO: figure out better formatting $games = getGames($db); if($games !== 1){//success foreach($games as $game){ echo "<a href=\"game.php?game=" . $game . "\">" . $game . "</a></br>"; } }elseif($games === array()){//no games echo "You have no games started! Click <a href=\"create.php\">here</a> to start a game."; }else{//failure //TODO: figure gotos } }elseif(isset($_GET["formMove"])){ $board = getBoard($db, $_GET["game"]); if($board === 1 || $board === 0){ exit; } $canPerformMove = true; $locations = explode("a", $_GET["formMove"]); $piece = $locations[0]; array_shift($locations); setType($piece, "int"); for($i = 0; $i < count($locations); $i++){ setType($locations[$i], "int"); if($locations[$i] > 32 || $piece < 1) $canPerformMove = false; } //make sure $locations and $piece are ok to be passed to validate for($i = 0; $i < count($locations); $i++) $locations[$i] $piece if($piece > 31 || $piece < 0) $canPerformMove = false; if(count($locations) < 1) $canPerformMove = false; if($canPerformMove) $canPerformMove = verifyMove($board, $piece, (int)whichPlayer($db, $_GET["game"]), $locations); if($canPerformMove){ if($_SESSION["id"] !== getTurn($db, $_GET["game"])){ echo "It is not your turn!"; exit; } if(!executeMove($db, $board, $piece, whichPlayer($db, $_GET["game"]), $locations, $_GET["game"])){ echo "<p class=\"error\">An error occurred. Please try again.</p>"; exit; } echo "You have successfully moved."; }else{ echo "That is an invalid move."; goto board; } }else{//game selected board: $board = getBoard($db, $_GET["game"]); if($board === 1){//TODO: gotos }elseif($board === 0){ echo "<p class=\"error\">That game doesn't exist!</p>"; $games = getGames($db); if($games !== 1){//success foreach($games as $game){ echo "<a href=\"game.php?game=" . $game . "\">" . $game . "</a></br>"; } }elseif($games === array()){//no games echo "You have no games started! Click <a href=\"create.php\">here</a> to start a game."; }else{//failure //TODO: figure gotos } }else{//display board $turnId = getTurn($db, $_GET["game"]); $playerNum = 0; if($turnId === $_SESSION["id"]){//is players turn ?> <script> usersTurn = true; </script> <?php } $playerNum = whichPlayer($db, $_GET["game"]); ?> <p id="move">Move:</p> <p>You are player <span id="player" style="font-weight:bold"></span>.</p> <p>It is <span id="turn"></span> your turn.</p> <form action="game.php" method="get"> <input type="hidden" value="" name="formMove" id="formMove"> <input type="hidden" value="" name="game" id="game"> <input type="submit" value="Move"> </form> <table id="board"> <tr> <td id="1" class="y"></td> <td class="n"></td> <td id="2" class="y"></td> <td class="n"></td> <td id="3" class="y"></td> <td class="n"></td> <td id="4" class="y"></td> <td class="n"></td> </tr> <tr> <td class="n"></td> <td id="5" class="y"></td> <td class="n"></td> <td id="6" class="y"></td> <td class="n"></td> <td id="7" class="y"></td> <td class="n"></td> <td id="8" class="y"></td> </tr> <tr> <td id="9" class="y"></td> <td class="n"></td> <td id="10" class="y"></td> <td class="n"></td> <td id="11" class="y"></td> <td class="n"></td> <td id="12" class="y"></td> <td class="n"></td> </tr> <tr> <td class="n"></td> <td id="13" class="y"></td> <td class="n"></td> <td id="14" class="y"></td> <td class="n"></td> <td id="15" class="y"></td> <td class="n"></td> <td id="16" class="y"></td> </tr> <tr> <td id="17" class="y"></td> <td class="n"></td> <td id="18" class="y"></td> <td class="n"></td> <td id="19" class="y"></td> <td class="n"></td> <td id="20" class="y"></td> <td class="n"></td> </tr> <tr> <td class="n"></td> <td id="21" class="y"></td> <td class="n"></td> <td id="22" class="y"></td> <td class="n"></td> <td id="23" class="y"></td> <td class="n"></td> <td id="24" class="y"></td> </tr> <tr> <td id="25" class="y"></td> <td class="n"></td> <td id="26" class="y"></td> <td class="n"></td> <td id="27" class="y"></td> <td class="n"></td> <td id="28" class="y"></td> <td class="n"></td> </tr> <tr> <td class="n"></td> <td id="29" class="y"></td> <td class="n"></td> <td id="30" class="y"></td> <td class="n"></td> <td id="31" class="y"></td> <td class="n"></td> <td id="32" class="y"></td> </tr> </table> <script> var data =<?php echo "\"" . $board . "\";";?> updateBoard(data); document.getElementById("game").value = "<?php echo $_GET["game"];?>"; document.getElementById("player").innerHTML = "<?php echo $playerNum;?>"; if(usersTurn) document.getElementById("turn").innerHTML = "currently"; else document.getElementById("turn").innerHTML = "not currently"; </script> <?php } } } } ?> </body> </html>
{- Author: Ka Wai Cheng Maintainer: Ka Wai Cheng Email: <mail.kawai.cheng@gmail.com> License: GPL 3.0 File: ProofChecker.hs Description: checks given proof tree is correct and shows unsatisfiability -} module ProofChecker where import Proof import Signature import ProofUtils import Data.List {- Called by other modules to check a proof tree Checks initial set of concepts and gamma before checking the proof -} checkProof :: ProofTree -> [Concept] -> (String, Bool) checkProof prooftree gamma | length (nub cs) /= length cs = ("Initial concepts must not contain duplicate concepts", False) | length (nub gamma) /= glength = ("Gamma must not contain duplicate concepts", False) | not $ all isNNF cs = ("Initial concepts are not in negation normal form", False) | not $ all isNNF gamma = ("Concepts in gamma are not in negation normal form", False) | length (gamma `intersect` cs) /= glength = ("Concepts in gamma are not in the initial set of concepts", False) | otherwise = checkTree prooftree gamma where cs = getConcepts prooftree glength = length gamma {- Checks a proof tree shows unsatisfiability and returns true if so Else returns messages of incorrect steps at point in proof tree & false Pre: Gamma and initial set of concepts do not contain duplicates -} checkTree :: ProofTree -> [Concept] -> (String, Bool) checkTree (NodeZero step) gamma | not success = (msg, False) | cs /= [] = ("Proof tree is not complete, applying the " ++ rule ++ " rule to {" ++ showConceptList initialconcepts ++ "} produces {" ++ showResults cs ++ "}", False) | otherwise = ("", True) where (msg, success, cs) = checkProofStep step gamma (initialconcepts, rule, _) = step checkTree (NodeOne step tree) gamma | not $ rule `elem` ["and", "exists"] = ("Applying the " ++ rule ++ " rule to {" ++ showConceptList initialconcepts ++ "} should not give 1 resulting set of concepts", False) | not success = (msg, False) | length cs /= 1 = ("There should be 1 resulting set of concepts for applying the " ++ rule ++ " rule to {" ++ showConceptList initialconcepts ++ "}", False) | conceptEquals (head cs) (getConcepts tree) = checkTree tree gamma | otherwise = ("Next step's concepts {" ++ showConceptList (getConcepts tree) ++ "} do not match the result of applying " ++ rule ++ " rule to {" ++ showConceptList initialconcepts ++ "}", False) where (msg, success, cs) = checkProofStep step gamma (initialconcepts, rule, _) = step checkTree (NodeTwo step t1 t2) gamma | rule /= "or" = ("Applying the " ++ rule ++ " rule to {" ++ showConceptList initialconcepts ++ "} should not give 2 resulting sets of concepts", False) | not success = (msg, False) | length cs /= 2 = ("There should be 2 resulting sets of concepts for applying the or rule to {" ++ showConceptList initialconcepts ++ "}", False) | conceptEquals (head cs) (getConcepts t1) && conceptEquals (cs !! 1) (getConcepts t2) || conceptEquals (cs !! 1) (getConcepts t1) && conceptEquals (head cs) (getConcepts t2) = (msg1 ++ msg2, tsuccess1 && tsuccess2) | otherwise = ("Next step's set of concepts {" ++ showConceptList (getConcepts t1) ++ "} and {" ++ showConceptList (getConcepts t2) ++ "} do not match the results of applying the or rule to {" ++ showConceptList initialconcepts ++ "}", False) where (msg, success, cs) = checkProofStep step gamma (msg1, tsuccess1) = checkTree t1 gamma (msg2, tsuccess2) = checkTree t2 gamma (initialconcepts, rule, _) = step {- Returns a string of sets of concepts WARNING: only accepts a maximum of 2 results -} showResults :: [[Concept]] -> String showResults [] = "Empty" showResults [cs] = showConceptList cs showResults [c1,c2] = showConceptList c1 ++ "} and {" ++ showConceptList c2 showResults _ = "There should not be more than 2 results" {- Checks a single proof step, returns true and resulting concepts if correct Else returns error message, false and given list of concepts of the step Pre: set of concept in proofstep and gamma contain no duplicates Post: lists of concepts returned contain no duplicates -} checkProofStep :: ProofStep -> [Concept] -> (String, Bool, [[Concept]]) checkProofStep (cs, "bottom", Atom a) _ | Atom a `elem` cs && Neg (Atom a) `elem` cs = ("", True, []) | otherwise = (showConcept (Atom a) ++ " and " ++ showConcept (Neg (Atom a)) ++ " do not both exist in the set of concepts {" ++ showConceptList cs ++ "}", False, [cs]) checkProofStep (cs, rule, c) gamma | c `elem` cs = checkRule (cs, rule, c) gamma | otherwise = (showConcept c ++ " does not exist in the set of concepts {" ++ showConceptList cs ++ "}", False, [cs]) {- Checks the proof rule can be applied, returns true and resulting concepts if correct Else returns error message, false and given list of concepts of the step Pre: ProofStep concept exists -} checkRule :: ProofStep -> [Concept] -> (String, Bool, [[Concept]]) checkRule (cs, "", Neg T) _ = ("", True, []) checkRule (cs, "", _) _ = ("This proof tree does not show unsatisfiability", False, [cs]) checkRule (cs, "and", And l r) _ = ("", True, [nub $ delete (And l r) (l:r:cs)]) checkRule (cs, "or", Or l r) _ = ("", True, [nub (l:result), nub (r:result)]) where result = delete (Or l r) cs checkRule (cs, "exists", Exists r c) gamma = ("", True, [nub $ c:fsuccs ++ gamma]) where fsuccs = [successor | Forall relation successor <- cs, relation == r] checkRule (cs, rule, c) _ = (rule ++ " rule cannot be applied to " ++ showConcept c ++ "", False, [cs])
<?php // Heading $_['heading_title'] = 'Metode Pembayaran'; // Text $_['text_account'] = 'Akun'; $_['text_payment'] = 'Pembayaran'; $_['text_your_payment'] = 'Informasi Pembayaran'; $_['text_your_password'] = 'Password Anda'; $_['text_cheque'] = 'Cek'; $_['text_paypal'] = 'PayPal'; $_['text_bank'] = 'Transfer Bank'; $_['text_success'] = 'Sukses: Account Anda berhasil diperbarui.'; // Entry $_['entry_tax'] = 'NPWP:'; $_['entry_payment'] = 'Metode Pembayaran:'; $_['entry_cheque'] = 'Nama Pada Cek:'; $_['entry_paypal'] = 'Email Account PayPal:'; $_['entry_bank_name'] = 'Nama Bank:'; $_['<API key>'] = 'No ABA/BSB (No. Cabang) Bank:'; $_['<API key>'] = 'Kode SWIFT Bank:'; $_['<API key>'] = 'Nama di Rekening:'; $_['<API key>'] = 'No. Rekening:'; ?>
<!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"> <link rel="shortcut icon" href="../img/favicon.ico"> <title>User - Beacon API</title> <link href="../css/bootstrap-custom.min.css" rel="stylesheet"> <link href="../css/font-awesome-4.5.0.css" rel="stylesheet"> <link href="../css/base.css" rel="stylesheet"> <link rel="stylesheet" href="../css/highlight.css"> <!-- 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] <script src="../js/jquery-1.10.2.min.js"></script> <script src="../js/bootstrap-3.0.3.min.js"></script> <script src="../js/highlight.pack.js"></script> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <!-- Collapsed navigation --> <div class="navbar-header"> <!-- Expander button --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="..">Beacon API</a> </div> <!-- Expanded navigation --> <div class="navbar-collapse collapse"> <!-- Main navigation --> <ul class="nav navbar-nav"> <li > <a href="..">Home</a> </li> <li class="dropdown active"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Objects <b class="caret"></b></a> <ul class="dropdown-menu"> <li > <a href="../document/">Document</a> </li> <li > <a href="../engram/">Engram</a> </li> <li > <a href="../mod/">Mod</a> </li> <li class="active"> <a href="./">User</a> </li> </ul> </li> <li > <a href="../authenticating/">Authenticating</a> </li> <li > <a href="../pull_api/">Pull API</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li> <a href="#" data-toggle="modal" data-target="#mkdocs_search_modal"> <i class="fa fa-search"></i> Search </a> </li> <li > <a rel="next" href="../mod/"> <i class="fa fa-arrow-left"></i> Previous </a> </li> <li > <a rel="prev" href="../authenticating/"> Next <i class="fa fa-arrow-right"></i> </a> </li> </ul> </div> </div> </div> <div class="container"> <div class="col-md-3"><div class="bs-sidebar hidden-print affix well" role="complementary"> <ul class="nav bs-sidenav"> <li class="main active"><a href="#the-user-object">The User Object</a></li> <li><a href="#user-structure">User Structure</a></li> <li><a href="#get">GET</a></li> <li><a href="#post">POST</a></li> <li><a href="#delete">DELETE</a></li> </ul> </div></div> <div class="col-md-9" role="main"> <h1 id="the-user-object">The User Object</h1> <p>The User object represents the extremely minimal data available about a user. Users can be created, queried, and deleted.</p> <p>The endpoint is https://api.usebeacon.app/v1/user.php</p> <h3 id="user-structure">User Structure</h3> <pre><code class="json">{ &quot;user_id&quot;: &quot;<API key>&quot;, &quot;public_key&quot;: &quot; } </code></pre> <h2 id="get">GET</h2> <p>Authentication is not required. Must supply one or more user UUIDs as the final path component. Listing users is not allowed and will result in a 405 result code. UUIDs are not case sensitive.</p> <pre><code class="http">GET /beacon/api/user.php/<API key> HTTP/1.1 Host: usebeacon.app HTTP/1.1 200 OK Content-Type: text/plain { user structure } </code></pre> <p>If none of the users were found, a 404 result code will be returned. If a single user is found, the result will be a JSON struct. If multiple users are found, the result will be an JSON array of structs.</p> <h2 id="post">POST</h2> <p>Authentication is not required to create a user. POST body must contain one or more complete user structures. Content-Type header must be application/json. A 400 error will be returned if these rules are violated or the user already exists.</p> <pre><code class="http">POST /beacon/api/user.php/<API key> HTTP/1.1 Host: usebeacon.app Authorization: Basic QTcwRjNENjAtQTI4MS00QzQ1LTgwQTAtQUQ2OUI3MzhENTY4OjRCQzQ3NTY2RjZDQjlBNjdBMTA5QTMzMThCMEVFQ0FGMUE0MTZCQkM0NkQwQTNCMzVEMkYzRjEzRTFFNDRERjMxREUwRDU0QTIwNUFCRjgxODlGMTEyRUE5MkQzOUI1REE5NTVDMjI3MkY2MDZCRTdBMjJENTAxNEFGNkY3NERGNEY4NkQ1RDZFNTI2MjJERDNBODZBMzNDOTNFNEZGOUU3NTcwOEUzNUYwMTkwQjY2OTc0RDkwRDk0RTZEODgzN0M5ODQzRTRDRDMxMjU5MUY3NTc1QjVEMDczQjRFMUJBRTYwMjIwRDZGOEVDQTBFNkRBNjMxRkQ5NkM1QjI5MTY5NUFFMzFCRkU0RTFFNjI3QTc2Nzk2MDQzRDg0MUUwQ0U4OUVBNDlCQTc0ODI2N0Q0MjYwNjcxNTM2NzU4MURCMjZFRkY1OTVGQUVDRjQyMDU1MjAxMzJCQzdERjUxNTEwOTVERjUyNjk0NUY1MTQ1NjBDRDIyQ0ZCODhGQTRBQzFBNzRENUZGMzhDQzE5QTEwNkQxMDc5MkZFQjA2QTFEM0E5RDQ1NTRGMTBEMkE1QTFDQkQ1MjhDQUU2QkIwMzc2QzVFRjBFOURGMEIzQUVGMjRDQTUwN0NEOEE1MzNERjFFODhCRkExQUEwMzBEM0JCN0QzOTNBMUYxQTUzNTAx Content-Type: application/json {&quot;user_id&quot;:&quot;<API key>&quot;,&quot;public_key&quot;:&quot;30820120300D06092A864886F70D01010105000382010D00308201080282010100DD03A7736A369F47DC484E95F929A69D1417AC22629FBAC445C218166772B1E88D7B9CA4830F12E625C70767D33BEF2673450106D3EC04AE164391C0C5D1555F7764A2A34798C172F05EE313C55FE6A4D69B0CC1593E49E751059E275303E99113FC91B0CD2825D203830D92C84D4625F0A5D026E886B244B5197A90AE6F2B354670951F1D0FE68C37DF5B25FDF131A2E58591B288CA60B4967BDC4B4E8056DBB923774360EFCAAD4548716A758F3EB574E21A66ED37B885FE3E5A5E0531DEF99600C474775E15ADF903511AC097CDCCD294670CAB1E980B9317CBC920B7FD59C365C9AEF9EE40C3F192A83DEAB357839DECE395994665181C351208F0110057020111&quot;} HTTP/1.1 200 OK </code></pre> <h2 id="delete">DELETE</h2> <p>Authentication is required. Final path component must be the authenticated user's UUID. Deleting other users is not possible. Deleting a user will remove all documents, mods, and engrams.</p> <pre><code class="http">DELETE /beacon/api/user.php/<API key> HTTP/1.1 Host: usebeacon.app Authorization: Basic QTcwRjNENjAtQTI4MS00QzQ1LTgwQTAtQUQ2OUI3MzhENTY4Ojg0QzIyMjJCMEJCRjFGMzlBMUMyNkM3OTNDQTc4NzFFM0NFM0I4Mjc1REIwNUEyRjBCQjY5NEU0QUVBQ0Y4ODcwOTQ2QzQ1RjdDOTE2RDU4QkFEODY5QUUyMzUzQTc1MjM0Q0I0NTM0ODM0QkQ0OEExMzMzRTdGMjdFOEM3OEYzNjJEMUZFM0IyNjczRDc1ODQ5NDkxQTEwRTNFNjQzMzNGRTFGRDhGM0E4Nzc1OUYzQ0UxMzJCODkzNTc4NkQyNDdGOTNENTE4REIzQ0ExNEIwRkI5OEFGMTg2NDE3OURCMTcxODQ3NjRFMzhCOTI3Q0RENjUwRjZGMEM4NzE2Q0UxNUE3NTcyMkUxMTFDOThDRUU5Mjg5ODQzRTJFRjJDQjBGOEQ0MURGNTA4ODk4QTYzQjdDRjJERjYyNkM3RUE5MThDMzhGQkY4QzMxMEQ2QTNCNjg2N0E2QTAzQTY5NzJDOTNEMEI1RERDODk2MjNFQUI2MEU2QzlDREUwM0VCN0Y0RDc5ODZCQTVCMEJDNDM4NkQxM0EzMEFGN0VENDhBQUM1QUE3OTE0MDg1QTJCQzE2MTE0QjBEQzZBMzhENDNENjBBQjUzOTE2QTk0MzU3RkE5ODAxQjEzMjNGNTg3MEYzM0M1MzdCNUFGQjdDODI2MEZDMTVDNzBBOTM4Q0FD HTTP/1.1 200 OK </code></pre></div> </div> <footer class="col-md-12"> <hr> <p>Documentation built with <a href="http: </footer> <script>var base_url = '..';</script> <script data-main="../mkdocs/js/search.js" src="../mkdocs/js/require.js"></script> <script src="../js/base.js"></script><div class="modal" id="mkdocs_search_modal" tabindex="-1" role="dialog" aria-labelledby="Search Modal" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title" id="exampleModalLabel">Search</h4> </div> <div class="modal-body"> <p> From here you can search these documents. Enter your search terms below. </p> <form role="form"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search..." id="mkdocs-search-query"> </div> </form> <div id="<API key>"></div> </div> <div class="modal-footer"> </div> </div> </div> </div> </body> </html>
#!/usr/bin/perl -w ($] >= 5.004) || die "version is $] -- need perl 5.004 or greater"; # -*- perl -*- use lib "$ENV{CRAIG_HOME}/perl/lib"; use Organism; use Contig; use Getopt::Long; use Gene; use strict; use enum qw(STRAND_FWD=0 STRAND_COMP=1); my $contigFile; my $usage = "usage : $0 -ctg contigFile < locations > newLocations\nFilters genes which are contiguosly occuring over DNA - without intergenic material in the middle\n"; &GetOptions( "-ctg=s" => \$contigFile, ); (defined($contigFile) && length($contigFile) > 0) || die "Contig File must be specified. ".$usage; my $org = Organism->new(); open(CONTIG, "<$contigFile") || die "file $contigFile not found\n"; my %contigs = % {$org->loadContigs(\*CONTIG)}; close(CONTIG); my %genes = % { $org->loadGenes(\*STDIN)}; for my $c (keys %contigs) { my @genes = sort {&Gene::compareTo($a, $b);} (values %{ $contigs{$c}->{'Features'}->{'TRAIN'}}); my $j = 0; my $gene; for(; $j < scalar(@genes); $j++) { $gene = $genes[$j]; my $i = $j + 1; my $remove = 0; while($i < scalar(@genes) && $genes[$i]->lowestCoord() <= $gene->highestCoord() + 1) { if($genes[$i]->lowestCoord() == $gene->highestCoord() + 1) { print STDERR "$gene->{'Id'} $genes[$i]->{'Id'} transcripts\n"; if(scalar(@{$gene->{'3UTRExons'}})) { undef(@{$gene->{'3UTRExons'}}); } elsif(scalar(@{$genes[$i]->{'5UTRExons'}})) { undef(@{$genes[$i]->{'5UTRExons'}}); } else { $remove = 1; print STDERR "$gene->{'Id'} removed ", $gene->contigId(), "\n"; } } $i++; } if(!$remove) { $gene->dump(\*STDOUT, undef, 1); } } }
var camera, scene, renderer; var geometry, material, mesh; function buildAxis(src, dst, colorHex, dashed) { var geom = new THREE.Geometry(), mat; if (dashed) { mat = new THREE.LineDashedMaterial({ linewidth: 3, color: colorHex, dashSize: 3, gapSize: 3 }); } else { mat = new THREE.LineBasicMaterial({ linewidth: 3, color: colorHex }); } geom.vertices.push(src.clone()); geom.vertices.push(dst.clone()); geom.<API key>(); // This one is SUPER important, otherwise dashed lines will appear as simple plain lines var axis = new THREE.Line(geom, mat, THREE.LinePieces); return axis; } function buildAxes(length) { var axes = new THREE.Object3D(); axes.add(buildAxis(new THREE.Vector3(0, 0, 0), new THREE.Vector3(length, 0, 0), 0xFF0000, false)); axes.add(buildAxis(new THREE.Vector3(0, 0, 0), new THREE.Vector3(-length, 0, 0), 0xFF0000, true)); axes.add(buildAxis(new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, length, 0), 0x00FF00, false)); axes.add(buildAxis(new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, -length, 0), 0x00FF00, true)); axes.add(buildAxis(new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, length), 0x0000FF, false)); axes.add(buildAxis(new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 0, -length), 0x0000FF, true)); return axes; } function init() { camera = new THREE.PerspectiveCamera(100, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.z = 3 camera.position.y = 3 camera.position.x = 3 var gui = new dat.GUI(); var f1 = gui.addFolder('Camera Position'); f1.add(camera.position, 'x', -10, 10); f1.add(camera.position, 'y', -10, 10); f1.add(camera.position, 'z', -10, 10); camera.rotation.x = -Math.PI scene = new THREE.Scene(); geometry = new THREE.BoxGeometry(1, 0.1, 2); material = new THREE.MeshBasicMaterial({ color: 0xfff999fff, wireframe: true }) mesh = new THREE.Mesh(geometry, material); scene.add(mesh); // var geometry = new THREE.PlaneGeometry( 1000, 1000, 1, 1 ); // var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } ); // var floor = new THREE.Mesh( geometry, material ); // floor.material.side = THREE.DoubleSide; // floor.rotation.x = 90*0.0174533; // scene.add( floor ); axes = buildAxes(100); scene.add(axes) renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); animation(); } function animation() { window.<API key>(animation); camera.lookAt(new THREE.Vector3(0, 0, 0)); // mesh.rotation.x = Date.now() * 0.00005; // mesh.rotation.y = Date.now() * 0.0001; renderer.render(scene, camera); }
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 5.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by the Perl program only. The format and even # the name or existence of this file are subject to change without notice. # Don't use it directly. # This file returns the 146 code points in Unicode Version 5.2.0 that match # any of the following regular expression constructs: # \p{Script=Khmer} # \p{Sc=Khmr} # \p{Is_Script=Khmer} # \p{Is_Sc=Khmr} # \p{Khmer} # \p{Is_Khmer} # \p{Khmr} # \p{Is_Khmr} # Note that contrary to what you might expect, the above is NOT the same # as \p{Block=Khmer} # perluniprops.pod should be consulted for the syntax rules for any of these, # including if adding or subtracting white space, underscore, and hyphen # characters matters or doesn't matter, and other permissible syntactic # variants. Upper/lower case distinctions never matter. # A colon can be substituted for the equals sign, and anything to the left of # the equals (or colon) can be combined with anything to the right. Thus, # for example, # \p{Is_Sc: Khmer} # is also valid. # The format of the lines of this file is: START\tSTOP\twhere START is the # starting code point of the range, in hex; STOP is the ending point, or if # omitted, the range has just one code point. Numbers in comments in # [brackets] indicate how many code points are in the range. return <<'END'; 1780 17DD 17E0 17E9 17F0 17F9 19E0 19FF END
#include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "grub_lib.h" #include "gbk.h" #include <grub/dl.h> #include <grub/env.h> #include <grub/parser.h> #include <grub/command.h> #include <grub/normal.h> #include <grub/term.h> #include <grub/file.h> #include <grub/menu.h> #include <grub/misc.h> #include <grub/device.h> #include <grub/i18n.h> #include <grub/lib/crc.h> #include <grub/lib/hexdump.h> #include <grub/video.h> #include <grub/bitmap.h> #include <grub/time.h> #include <grub/gfxmenu_view.h> #ifdef ENABLE_LUA_PCI #include <grub/pci.h> #endif #define UTF_MAX 8 #define DBCS_MAX 2 /* Updates the globals grub_errno and grub_msg, leaving their values on the top of the stack, and clears grub_errno. When grub_errno is zero, grub_msg is not left on the stack. The value returned is the number of values left on the stack. */ static int push_result (lua_State *state) { int saved_errno; int num_results; saved_errno = grub_errno; grub_errno = 0; /* Push once for setfield, and again to leave on the stack */ lua_pushinteger (state, saved_errno); lua_pushinteger (state, saved_errno); lua_setfield (state, LUA_GLOBALSINDEX, "grub_errno"); if (saved_errno) { /* Push once for setfield, and again to leave on the stack */ lua_pushstring (state, grub_errmsg); lua_pushstring (state, grub_errmsg); num_results = 2; } else { lua_pushnil (state); num_results = 1; } lua_setfield (state, LUA_GLOBALSINDEX, "grub_errmsg"); return num_results; } /* Updates the globals grub_errno and grub_msg ( without leaving them on the stack ), clears grub_errno, and returns the value of grub_errno before it was cleared. */ static int save_errno (lua_State *state) { int saved_errno; saved_errno = grub_errno; lua_pop(state, push_result(state)); return saved_errno; } static unsigned from_utf8(unsigned uni_code) { const unsigned short *page = from_uni[(uni_code >> 8) & 0xFF]; return page == NULL ? DBCS_DEFAULT_CODE : page[uni_code & 0xFF]; } static unsigned to_utf8(unsigned cp_code) { const unsigned short *page = to_uni[(cp_code >> 8) & 0xFF]; return page == NULL ? UNI_INVALID_CODE : page[cp_code & 0xFF]; } static size_t utf8_encode(char *s, unsigned ch) { if (ch < 0x80) { s[0] = (char)ch; return 1; } if (ch <= 0x7FF) { s[1] = (char) ((ch | 0x80) & 0xBF); s[0] = (char) ((ch >> 6) | 0xC0); return 2; } if (ch <= 0xFFFF) { three: s[2] = (char) ((ch | 0x80) & 0xBF); s[1] = (char) (((ch >> 6) | 0x80) & 0xBF); s[0] = (char) ((ch >> 12) | 0xE0); return 3; } if (ch <= 0x1FFFFF) { s[3] = (char) ((ch | 0x80) & 0xBF); s[2] = (char) (((ch >> 6) | 0x80) & 0xBF); s[1] = (char) (((ch >> 12) | 0x80) & 0xBF); s[0] = (char) ((ch >> 18) | 0xF0); return 4; } if (ch <= 0x3FFFFFF) { s[4] = (char) ((ch | 0x80) & 0xBF); s[3] = (char) (((ch >> 6) | 0x80) & 0xBF); s[2] = (char) (((ch >> 12) | 0x80) & 0xBF); s[1] = (char) (((ch >> 18) | 0x80) & 0xBF); s[0] = (char) ((ch >> 24) | 0xF8); return 5; } if (ch <= 0x7FFFFFFF) { s[5] = (char) ((ch | 0x80) & 0xBF); s[4] = (char) (((ch >> 6) | 0x80) & 0xBF); s[3] = (char) (((ch >> 12) | 0x80) & 0xBF); s[2] = (char) (((ch >> 18) | 0x80) & 0xBF); s[1] = (char) (((ch >> 24) | 0x80) & 0xBF); s[0] = (char) ((ch >> 30) | 0xFC); return 6; } /* fallback */ ch = 0xFFFD; goto three; } static size_t utf8_decode(const char *s, const char *e, unsigned *pch) { unsigned ch; if (s >= e) { *pch = 0; return 0; } ch = (unsigned char)s[0]; if (ch < 0xC0) goto fallback; if (ch < 0xE0) { if (s+1 >= e || (s[1] & 0xC0) != 0x80) goto fallback; *pch = ((ch & 0x1F) << 6) | (s[1] & 0x3F); return 2; } if (ch < 0xF0) { if (s+2 >= e || (s[1] & 0xC0) != 0x80 || (s[2] & 0xC0) != 0x80) goto fallback; *pch = ((ch & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F); return 3; } { int count = 0; /* to count number of continuation bytes */ unsigned res = 0; while ((ch & 0x40) != 0) { /* still have continuation bytes? */ int cc = (unsigned char)s[++count]; if ((cc & 0xC0) != 0x80) /* not a continuation byte? */ goto fallback; /* invalid byte sequence, fallback */ res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */ ch <<= 1; /* to test next bit */ } if (count > 5) goto fallback; /* invalid byte sequence */ res |= ((ch & 0x7F) << (count * 5)); /* add first byte */ *pch = res; return count+1; } fallback: *pch = ch; return 1; } static void add_utf8char(luaL_Buffer *b, unsigned ch) { char buff[UTF_MAX]; size_t n = utf8_encode(buff, ch); luaL_addlstring(b, buff, n); } static size_t dbcs_decode(const char *s, const char *e, unsigned *pch) { unsigned ch; if (s >= e) { *pch = 0; return 0; } ch = s[0] & 0xFF; if (to_uni_00[ch] != UNI_INVALID_CODE) { *pch = ch; return 1; } *pch = (ch << 8) | (s[1] & 0xFF); return 2; } static void add_dbcschar(luaL_Buffer *b, unsigned ch) { if (ch < 0x7F) luaL_addchar(b, ch); else { luaL_addchar(b, (ch >> 8) & 0xFF); luaL_addchar(b, ch & 0xFF); } } static size_t dbcs_length(const char *s, const char *e) { size_t dbcslen = 0; while (s < e) { if ((unsigned char)(*s++) > 0x7F) ++s; ++dbcslen; } return dbcslen; } /* dbcs module interface */ static const char *check_dbcs(lua_State *L, int idx, const char **pe) { size_t len; const char *s = luaL_checklstring(L, idx, &len); if (pe != NULL) *pe = s + len; return s; } static int posrelat(int pos, size_t len) { if (pos >= 0) return (size_t)pos; else if (0u - (size_t)pos > len) return 0; else return len - ((size_t)-pos) + 1; } static int string_from_utf8(lua_State *L) { const char *e, *s = check_dbcs(L, 1, &e); luaL_Buffer b; luaL_buffinit(L, &b); while (s < e) { unsigned ch; s += utf8_decode(s, e, &ch); add_dbcschar(&b, from_utf8(ch)); } luaL_pushresult(&b); return 1; } static int string_to_utf8(lua_State *L) { const char *e, *s = check_dbcs(L, 1, &e); luaL_Buffer b; luaL_buffinit(L, &b); while (s < e) { unsigned ch; s += dbcs_decode(s, e, &ch); add_utf8char(&b, to_utf8(ch)); } luaL_pushresult(&b); return 1; } static int grub_lua_run (lua_State *state) { int n; char **args; const char *s; s = luaL_checkstring (state, 1); if ((! <API key> (s, 0, 0, &n, &args)) && (n >= 0)) { grub_command_t cmd; cmd = grub_command_find (args[0]); if (cmd) (cmd->func) (cmd, n-1, &args[1]); else grub_error (<API key>, "command not found"); grub_free (args[0]); grub_free (args); } return push_result (state); } static int grub_lua_getenv (lua_State *state) { int n, i; n = lua_gettop (state); for (i = 1; i <= n; i++) { const char *name, *value; name = luaL_checkstring (state, i); value = grub_env_get (name); if (value) lua_pushstring (state, value); else lua_pushnil (state); } return n; } static int grub_lua_setenv (lua_State *state) { const char *name, *value; name = luaL_checkstring (state, 1); value = luaL_checkstring (state, 2); if (name[0]) grub_env_set (name, value); return 0; } static int grub_lua_exportenv (lua_State *state) { const char *name, *value; name = luaL_checkstring (state, 1); value = luaL_checkstring (state, 2); if (name[0]) { grub_env_export (name); if (value[0]) grub_env_set (name, value); } return 0; } /* Helper for <API key>. */ static int <API key> (const char *name, void *data) { lua_State *state = data; int result; grub_device_t dev; result = 0; dev = grub_device_open (name); if (dev) { grub_fs_t fs; fs = grub_fs_probe (dev); if (fs) { lua_pushvalue (state, 1); lua_pushstring (state, name); lua_pushstring (state, fs->name); if (! fs->uuid) lua_pushnil (state); else { int err; char *uuid; err = fs->uuid (dev, &uuid); if (err) { grub_errno = 0; lua_pushnil (state); } else { lua_pushstring (state, uuid); grub_free (uuid); } } if (! fs->label) lua_pushnil (state); else { int err; char *label = NULL; err = fs->label (dev, &label); if (err) { grub_errno = 0; lua_pushnil (state); } else { if (label == NULL) { lua_pushnil (state); } else { lua_pushstring (state, label); } grub_free (label); } } lua_call (state, 4, 1); result = lua_tointeger (state, -1); lua_pop (state, 1); } else grub_errno = 0; grub_device_close (dev); } else grub_errno = 0; return result; } static int <API key> (lua_State *state) { luaL_checktype (state, 1, LUA_TFUNCTION); grub_device_iterate (<API key>, state); return push_result (state); } static int enum_file (const char *name, const struct grub_dirhook_info *info, void *data) { int result; lua_State *state = data; lua_pushvalue (state, 1); lua_pushstring (state, name); lua_pushinteger (state, info->dir != 0); lua_call (state, 2, 1); result = lua_tointeger (state, -1); lua_pop (state, 1); return result; } static int grub_lua_enum_file (lua_State *state) { char *device_name; const char *arg; grub_device_t dev; luaL_checktype (state, 1, LUA_TFUNCTION); arg = luaL_checkstring (state, 2); device_name = <API key> (arg); dev = grub_device_open (device_name); if (dev) { grub_fs_t fs; const char *path; fs = grub_fs_probe (dev); path = grub_strchr (arg, ')'); if (! path) path = arg; else path++; if (fs) { (fs->dir) (dev, path, enum_file, state); } grub_device_close (dev); } grub_free (device_name); return push_result (state); } #ifdef ENABLE_LUA_PCI /* Helper for grub_lua_enum_pci. */ static int <API key> (grub_pci_device_t dev, grub_pci_id_t pciid, void *data) { lua_State *state = data; int result; grub_pci_address_t addr; grub_uint32_t class; lua_pushvalue (state, 1); lua_pushinteger (state, grub_pci_get_bus (dev)); lua_pushinteger (state, grub_pci_get_device (dev)); lua_pushinteger (state, <API key> (dev)); lua_pushinteger (state, pciid); addr = <API key> (dev, GRUB_PCI_REG_CLASS); class = grub_pci_read (addr); lua_pushinteger (state, class); lua_call (state, 5, 1); result = lua_tointeger (state, -1); lua_pop (state, 1); return result; } static int grub_lua_enum_pci (lua_State *state) { luaL_checktype (state, 1, LUA_TFUNCTION); grub_pci_iterate (<API key>, state); return push_result (state); } #endif static int grub_lua_file_open (lua_State *state) { grub_file_t file; const char *name; name = luaL_checkstring (state, 1); file = grub_file_open (name); save_errno (state); if (! file) return 0; <API key> (state, file); return 1; } static int grub_lua_file_close (lua_State *state) { grub_file_t file; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); grub_file_close (file); return push_result (state); } static int grub_lua_file_seek (lua_State *state) { grub_file_t file; grub_off_t offset; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); offset = luaL_checkinteger (state, 2); offset = grub_file_seek (file, offset); save_errno (state); lua_pushinteger (state, offset); return 1; } static int grub_lua_file_read (lua_State *state) { grub_file_t file; luaL_Buffer b; int n; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); n = luaL_checkinteger (state, 2); luaL_buffinit (state, &b); while (n) { char *p; int nr; nr = (n > LUAL_BUFFERSIZE) ? LUAL_BUFFERSIZE : n; p = luaL_prepbuffer (&b); nr = grub_file_read (file, p, nr); if (nr <= 0) break; luaL_addsize (&b, nr); n -= nr; } save_errno (state); luaL_pushresult (&b); return 1; } static int <API key> (lua_State *state) { grub_file_t file; char *line; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); line = grub_file_getline (file); save_errno (state); if (! line) return 0; lua_pushstring (state, line); grub_free (line); return 1; } static int <API key> (lua_State *state) { grub_file_t file; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); lua_pushinteger (state, file->size); return 1; } static int <API key> (lua_State *state) { grub_file_t file; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); lua_pushinteger (state, file->offset); return 1; } static int grub_lua_file_eof (lua_State *state) { grub_file_t file; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); lua_pushboolean (state, file->offset >= file->size); return 1; } static int grub_lua_file_exist (lua_State *state) { grub_file_t file; const char *name; int result; result = 0; name = luaL_checkstring (state, 1); file = grub_file_open (name); if (file) { result++; grub_file_close (file); } else grub_errno = 0; lua_pushboolean (state, result); return 1; } static int grub_lua_file_crc32 (lua_State *state) { grub_file_t file; const char *name; int crc; char crcstr[10]; char buf[<API key>]; grub_ssize_t size; name = luaL_checkstring (state, 1); file = grub_file_open (name); if (file) { crc = 0; while ((size = grub_file_read (file, buf, sizeof (buf))) > 0) crc = grub_getcrc32c (crc, buf, size); grub_snprintf (crcstr, 10, "%08x", crc); lua_pushstring (state, crcstr); } return 1; } //file, skip, length static int grub_lua_hexdump (lua_State *state) { grub_file_t file; char buf[<API key> * 4]; grub_ssize_t size, length; grub_disk_addr_t skip; grub_size_t var_len; char *var_buf = NULL; char *var_hex = NULL; char *p = NULL; char *s = NULL; luaL_checktype (state, 1, LUA_TLIGHTUSERDATA); file = lua_touserdata (state, 1); skip = luaL_checkinteger (state, 2); length = luaL_checkinteger (state, 3); var_len = length + 1; var_buf = (char *) grub_malloc (var_len); var_hex = (char *) grub_malloc (3 * var_len); if (var_buf) p = var_buf; if (var_hex) s = var_hex; if (file) { file->offset = skip; while ((size = grub_file_read (file, buf, sizeof (buf))) > 0) { unsigned long len; len = ((length) && (size > length)) ? length : size; grub_memcpy (p, buf, len); p += len; skip += len; if (length) { length -= len; if (!length) break; } } grub_size_t i; *p = 0; *s = 0; for (i = 0; i < var_len - 1; i++) { var_hex = grub_xasprintf ("%s %02x", var_hex, (unsigned char) var_buf[i]); var_buf[i] = ((var_buf[i] >= 32) && (var_buf[i] < 127)) ? var_buf[i] : '.'; } lua_pushstring (state, var_buf); lua_pushstring (state, var_hex); return 2; } return 0; } static int grub_lua_add_menu (lua_State *state) { int n; const char *source; source = luaL_checklstring (state, 1, 0); n = lua_gettop (state) - 1; if (n > 0) { const char **args; char *p; int i; args = grub_malloc (n * sizeof (args[0])); if (!args) return push_result (state); for (i = 0; i < n; i++) args[i] = luaL_checkstring (state, 2 + i); p = grub_strdup (source); if (! p) return push_result (state); <API key> (n, args, NULL, NULL, NULL, NULL, NULL, p, 0, 0); } else { lua_pushstring (state, "not enough parameter"); lua_error (state); } return push_result (state); } static int grub_lua_clear_menu (lua_State *state __attribute__ ((unused))) { grub_menu_t menu = grub_env_get_menu(); menu->entry_list = NULL; menu->size=0; return 0; } static int <API key> (lua_State *state) { int n; const char *source; source = luaL_checklstring (state, 2, 0); n = lua_gettop (state) - 2; if (n > 0) { const char **args; char *p; int i; char **class = NULL; class = grub_malloc (sizeof (class[0])); class[0] = grub_strdup (luaL_checklstring (state, 1, 0)); class[1] = NULL; args = grub_malloc (n * sizeof (args[0])); if (!args) return push_result (state); for (i = 0; i < n; i++) args[i] = luaL_checkstring (state, 3 + i); p = grub_strdup (source); if (! p) return push_result (state); <API key> (n, args, class, NULL, NULL, NULL, NULL, p, 0, 0); } else { lua_pushstring (state, "not enough parameter"); lua_error (state); } return push_result (state); } static int <API key> (lua_State *state) { int n; const char *source; source = luaL_checklstring (state, 2, 0); n = lua_gettop (state) - 2; if (n > 0) { const char **args; char *p; int i; const char *hotkey; args = grub_malloc (n * sizeof (args[0])); if (!args) return push_result (state); for (i = 0; i < n; i++) args[i] = luaL_checkstring (state, 3 + i); p = grub_strdup (source); if (! p) return push_result (state); hotkey = grub_strdup (luaL_checklstring (state, 1, 0)); <API key> (n, args, NULL, NULL, NULL, hotkey, NULL, p, 0, 1); } else { lua_pushstring (state, "not enough parameter"); lua_error (state); } return push_result (state); } static int grub_lua_read_byte (lua_State *state) { grub_addr_t addr; addr = luaL_checkinteger (state, 1); lua_pushinteger (state, *((grub_uint8_t *) addr)); return 1; } static int grub_lua_read_word (lua_State *state) { grub_addr_t addr; addr = luaL_checkinteger (state, 1); lua_pushinteger (state, *((grub_uint16_t *) addr)); return 1; } static int grub_lua_read_dword (lua_State *state) { grub_addr_t addr; addr = luaL_checkinteger (state, 1); lua_pushinteger (state, *((grub_uint32_t *) addr)); return 1; } static int grub_lua_write_byte (lua_State *state) { grub_addr_t addr; addr = luaL_checkinteger (state, 1); *((grub_uint8_t *) addr) = luaL_checkinteger (state, 2); return 1; } static int grub_lua_write_word (lua_State *state) { grub_addr_t addr; addr = luaL_checkinteger (state, 1); *((grub_uint16_t *) addr) = luaL_checkinteger (state, 2); return 1; } static int <API key> (lua_State *state) { grub_addr_t addr; addr = luaL_checkinteger (state, 1); *((grub_uint32_t *) addr) = luaL_checkinteger (state, 2); return 1; } static int grub_lua_cls (lua_State *state __attribute__ ((unused))) { grub_cls (); return 0; } static int <API key> (lua_State *state) { grub_setcolorstate (luaL_checkinteger (state, 1)); return 0; } static int grub_lua_refresh (lua_State *state __attribute__ ((unused))) { grub_refresh (); return 0; } static int grub_lua_read (lua_State *state __attribute__ ((unused))) { int i; char *line; char *tmp; char c; i = 0; line = grub_malloc (1 + i + sizeof('\0')); if (! line) return 0; while (1) { c = grub_getkey (); if ((c == '\n') || (c == '\r')) break; line[i] = c; if (grub_isprint (c)) grub_printf ("%c", c); i++; tmp = grub_realloc (line, 1 + i + sizeof('\0')); if (! tmp) { grub_free (line); return 0; } line = tmp; } line[i] = '\0'; lua_pushstring (state, line); return 1; } static int grub_lua_gettext (lua_State *state) { const char *translation; translation = luaL_checkstring (state, 1); lua_pushstring (state, grub_gettext (translation)); return 1; } luaL_Reg grub_lua_lib[] = { {"run", grub_lua_run}, {"getenv", grub_lua_getenv}, {"setenv", grub_lua_setenv}, {"exportenv", grub_lua_exportenv}, {"enum_device", <API key>}, {"enum_file", grub_lua_enum_file}, #ifdef ENABLE_LUA_PCI {"enum_pci", grub_lua_enum_pci}, #endif {"file_open", grub_lua_file_open}, {"file_close", grub_lua_file_close}, {"file_seek", grub_lua_file_seek}, {"file_read", grub_lua_file_read}, {"file_getline", <API key>}, {"file_getsize", <API key>}, {"file_getpos", <API key>}, {"file_eof", grub_lua_file_eof}, {"file_exist", grub_lua_file_exist}, {"file_crc32", grub_lua_file_crc32}, {"hexdump", grub_lua_hexdump}, {"add_menu", grub_lua_add_menu}, {"add_icon_menu", <API key>}, {"add_hidden_menu", <API key>}, {"clear_menu", grub_lua_clear_menu}, {"read_byte", grub_lua_read_byte}, {"read_word", grub_lua_read_word}, {"read_dword", grub_lua_read_dword}, {"write_byte", grub_lua_write_byte}, {"write_word", grub_lua_write_word}, {"write_dword", <API key>}, {"cls", grub_lua_cls}, {"setcolorstate", <API key>}, {"refresh", grub_lua_refresh}, {"read", grub_lua_read}, {"gettext", grub_lua_gettext}, {0, 0} }; /* Lua function: get_time_ms() : returns the time in milliseconds. */ static int lua_sys_get_time_ms (lua_State *state) { lua_pushinteger (state, grub_get_time_ms ()); return 1; } static int lua_sys_random (lua_State *state) { uint16_t r = grub_get_time_ms (); uint16_t m; m = luaL_checkinteger (state, 1); r = ((r * 7621) + 1) % 32768; lua_pushinteger (state, r % m); return 1; } static int lua_input_read (lua_State *state) { char *line = grub_getline (); if (! line) lua_pushnil(state); else lua_pushstring (state, line); grub_free (line); return 1; } /* Lua function: input.getkey() : returns { ASCII char, scan code }. */ static int lua_input_getkey (lua_State *state) { int c = grub_getkey(); lua_pushinteger (state, c & 0xFF); /* Push ASCII character code. */ lua_pushinteger (state, (c >> 8) & 0xFF); /* Push the scan code. */ return 2; } static int <API key> (lua_State *state __attribute__ ((unused))) { int c = grub_getkey_noblock (); lua_pushinteger (state, c & 0xFF); /* Push ASCII character code. */ lua_pushinteger (state, (c >> 8) & 0xFF); /* Push the scan code. */ return 2; } /* Lua function: video.swap_buffers(). */ static int <API key> (lua_State *state) { if (<API key> () != GRUB_ERR_NONE) return luaL_error (state, "Error swapping video buffers: %s", grub_errmsg); return 0; } static grub_video_color_t check_grub_color (lua_State *state, int narg) { /* Get the color components. */ luaL_argcheck (state, lua_istable (state, narg), narg, "should be a color"); lua_getfield (state, narg, "r"); lua_getfield (state, narg, "g"); lua_getfield (state, narg, "b"); lua_getfield (state, narg, "a"); grub_video_color_t color; color = grub_video_map_rgba (luaL_checkint (state, -4), luaL_checkint (state, -3), luaL_checkint (state, -2), luaL_optint (state, -1, 255)); lua_pop (state, 4); return color; } /* Lua function: video.fill_rect(color, x, y, width, height). */ static int lua_video_fill_rect (lua_State *state) { grub_video_color_t color = check_grub_color (state, 1); int x = luaL_checkint (state, 2); int y = luaL_checkint (state, 3); int w = luaL_checkint (state, 4); int h = luaL_checkint (state, 5); if (<API key> (color, x, y, w, h) != GRUB_ERR_NONE) return luaL_error (state, "Error filling rectangle: %s", grub_errmsg); return 0; } /* Lua function: video.draw_string(text, font, color, x, y). */ static int <API key> (lua_State *state) { <API key> (luaL_checkstring (state, 1), grub_font_get (luaL_checkstring (state, 2)), check_grub_color (state, 3), luaL_checkint (state, 4), luaL_checkint (state, 5)); return 0; } struct hook_ctx { unsigned int len; char* data; }; static int hook (const struct <API key> *info, void *hook_arg) { unsigned int len; struct hook_ctx *ctx = hook_arg; char buf[24]; if (info->mode_type & <API key>) return 0; grub_snprintf (buf, sizeof(buf), "%dx%dx%d ", info->width, info->height, info->bpp); len = grub_strlen(buf); if (ctx->data) { grub_strcpy(ctx->data + ctx->len, buf); } ctx->len += len; return 0; } /* Lua function: video.info(). */ static int lua_video_info (lua_State *state __attribute__ ((unused))) { <API key> adapter; <API key> id; struct hook_ctx ctx; #ifdef GRUB_MACHINE_PCBIOS grub_dl_load ("vbe"); #endif id = <API key> (); FOR_VIDEO_ADAPTERS (adapter) { if (! adapter->iterate || (adapter->id != id && (id != <API key> || adapter->init() != GRUB_ERR_NONE))) { continue; } ctx.data = NULL; ctx.len = 0; adapter->iterate (hook, &ctx); ctx.data = grub_malloc(ctx.len+1); ctx.data[0] = '\0'; ctx.len = 0; adapter->iterate (hook, &ctx); if (adapter->id != id) adapter->fini(); if (id != <API key> || ctx.len) { lua_pushstring (state, ctx.data); grub_free(ctx.data); break; } else grub_free(ctx.data); } return 1; } static int lua_gbk_len (lua_State *state) { const char *e, *s = check_dbcs(state, 1, &e); lua_pushinteger(state, dbcs_length(s, e)); return 1; } static int lua_gbk_byte(lua_State *state) { const char *e, *s = check_dbcs(state, 1, &e); size_t len = dbcs_length(s, e); int posi = posrelat((int)luaL_optinteger(state, 2, 1), len); int pose = posrelat((int)luaL_optinteger(state, 3, posi), len); const char *start = s; int i, n; if (posi < 1) posi = 1; if (pose > (int)len) pose = len; n = (int)(pose - posi + 1); if (posi + n <= pose) /* (size_t -> int) overflow? */ return luaL_error(state, "string slice too long"); luaL_checkstack(state, n, "string slice too long"); for (i = 0; i < posi; ++i) { unsigned ch; start += dbcs_decode(start, e, &ch); } for (i = 0; i < n; ++i) { unsigned ch; start += dbcs_decode(start, e, &ch); lua_pushinteger(state, ch); } return n; } static int lua_gbk_char(lua_State *state) { luaL_Buffer b; int i, top = lua_gettop(state); luaL_buffinit(state, &b); for (i = 1; i <= top; ++i) add_dbcschar(&b, (unsigned)luaL_checkinteger(state, i)); luaL_pushresult(&b); return 1; } static int lua_gbk_fromutf8(lua_State *state) { int i, top; switch (lua_type(state, 1)) { case LUA_TSTRING: return string_from_utf8(state); case LUA_TNUMBER: top = lua_gettop(state); for (i = 1; i <= top; ++i) { unsigned code = (unsigned)luaL_checkinteger(state, i); lua_pushinteger(state, (lua_Integer)from_utf8(code)); lua_replace(state, i); } return top; } return luaL_error(state, "string/number expected, got %s", luaL_typename(state, 1)); } static int lua_gbk_toutf8(lua_State *state) { int i, top; switch (lua_type(state, 1)) { case LUA_TSTRING: return string_to_utf8(state); case LUA_TNUMBER: top = lua_gettop(state); for (i = 1; i <= top; ++i) { unsigned code = (unsigned)luaL_checkinteger(state, i); lua_pushinteger(state, to_utf8(code)); lua_replace(state, i); } return top; } return luaL_error(state, "string/number expected, got %s", luaL_typename(state, 1)); } luaL_Reg syslib[] = { {"get_time_ms", lua_sys_get_time_ms}, {"random", lua_sys_random}, {0, 0} }; luaL_Reg inputlib[] = { {"getkey", lua_input_getkey}, {"getkey_noblock", <API key>}, {"read", lua_input_read}, {0, 0} }; luaL_Reg videolib[] = { {"swap_buffers", <API key>}, {"fill_rect", lua_video_fill_rect}, {"draw_string", <API key>}, {"info", lua_video_info}, {0, 0} }; luaL_Reg gbklib[] = { {"len", lua_gbk_len}, {"byte", lua_gbk_byte}, {"char", lua_gbk_char}, {"fromutf8", lua_gbk_fromutf8}, {"toutf8", lua_gbk_toutf8}, {0, 0} };
@echo off REM The directory where Madsonic will create files. Make sure it is writable. set MADSONIC_HOME=c:\madsonic REM The host name or IP address on which to bind Madsonic. Only relevant if you have REM multiple network interfaces and want to make Madsonic available on only one of them. REM The default value 0.0.0.0 will bind Madsonic to all available network interfaces. set MADSONIC_HOST=0.0.0.0 REM The port on which Madsonic will listen for incoming HTTP traffic. set MADSONIC_PORT=4040 REM The port on which Madsonic will listen for incoming HTTPS traffic (0 to disable). set MADSONIC_HTTPS_PORT=0 REM The context path (i.e., the last part of the Madsonic URL). Typically "/" or "/madsonic". set <API key>=/ REM The directory for music set <API key>=c:\media\Artists REM The directory for upload set <API key>=c:\media\Incoming REM The directory for Podcast set <API key>=c:\media\Podcast REM The directory for Playlist set <API key>=c:\media\playlist-Import REM The directory for Playlist-export set <API key>=c:\media\playlist-Export REM The memory limit (max Java heap size) in megabytes. set MAX_MEMORY=350 REM The memory initial size (Init Java heap size) in megabytes. set INIT_MEMORY=200 java -Xms%INIT_MEMORY%m -Xmx%MAX_MEMORY%m -Dsubsonic.home=%MADSONIC_HOME% -Dsubsonic.host=%MADSONIC_HOST% -Dsubsonic.port=%MADSONIC_PORT% -Dsubsonic.httpsPort=%MADSONIC_HTTPS_PORT% -Dsubsonic.contextPath=%<API key>% -Dsubsonic.defaultMusicFolder=%<API key>% -Dsubsonic.defaultUploadFolder=%<API key>% -Dsubsonic.<API key>=%<API key>% -Dsubsonic.<API key>=%<API key>% -Dsubsonic.<API key>=%<API key>% -jar madsonic-booter.jar
package fundamentals.bagsQueueStack; import util.api.StdIn; import util.api.StdOut; import java.util.Arrays; import java.util.Iterator; import java.util.<API key>; public class ResizingArrayQueue<I> implements Iterable<I> { private final static int INITCAPACITY = 1000; private I[] array; // the queue arrays private int size; // number of element in the queue private int first; // index of first element of queue private int last; // index of last element of queue /** * Initializes a empty queue with initializable capacity */ public ResizingArrayQueue(){ array = (I[])new Object[INITCAPACITY]; size = first = last = 0; } /** * Returns whether is empty or not * @return {@code true} if not empty * {@code false} otherwise */ public boolean isEmpty(){ return size == 0; } /** * Returns the number of items in the queue * @return the number of items in the queue */ public int size(){ return size; } /** * Returns the the first item in the queue * * @return the first item * @throws <API key> if the queue is empty */ public I peek(){ if(isEmpty()) throw new <API key>("Queue is empty"); return array[first]; } /** * Returns and remove the first item in the queue * * @return the first item in the queue * @throws <API key> if the queue is empty */ public I pop(){ if(isEmpty()) throw new <API key>("Queue is empty"); I item = array[first]; array[first++] = null; --size; return item; } /** * Add an item into the queue * * @param item the item */ public void enqueue(I item){ if(size == array.length) ensureCapacity(array.length * 2); array[last++] = item; if(last == array.length) last = 0; //wrap-around size ++; } /** * Removes and returns the item on this queue that was least recently added. * @return the item on this queue that was least recently added * @throws <API key> if this queue is empty */ public I dequeue() { if (isEmpty()) throw new <API key>("Queue underflow"); I item = array[first]; array[first] = null; // to avoid loitering size first++; if (first == array.length) first = 0; // wrap-around // shrink size of array if necessary if (size > 0 && size == array.length/4) ensureCapacity(array.length/2); return item; } @Override public Iterator<I> iterator() { return new ReverseArrayQueue(); } //resize the underlying array private void ensureCapacity(int newCapacity){ assert newCapacity >= size; this.array = Arrays.copyOf(array, newCapacity); first = 0; last = size; } private class ReverseArrayQueue implements Iterator<I>{ private int n = 0; @Override public boolean hasNext() { return n < size; } @Override public I next() { if(!hasNext()) throw new <API key>("The Queue is empty"); I item = array[(n + first) % array.length]; n ++; return item; } @Override public void remove() { throw new <API key>("Unsupport this Operation"); } } /** * Unit tests the {@code ResizingArrayQueue} data type. * * @param args the command-line arguments */ public static void main(String[] args){ ResizingArrayQueue<String> queue = new ResizingArrayQueue<String>(); while (!StdIn.isEmpty()) { String item = StdIn.readString(); if (!item.equals("-")) queue.enqueue(item); else if (!queue.isEmpty()) StdOut.print(queue.dequeue() + " "); } StdOut.println("(" + queue.size() + " left on queue)"); } }
<?php class <API key> { public static function generatePage(&$tpl, &$session, &$account, &$perso) { $dbMgr = DbManager::getInstance(); //Instancier le gestionnaire $db = $dbMgr->getConn('game'); //Demander la connexion existante $errorUrl = '?popup=1&amp;m=<API key>'; if (!$perso->isNormal()) return fctErrorMSG('Vous n\'êtes pas en état d\'effectuer cette action.', $errorUrl); if ($perso->getMenotte()) return fctErrorMSG('Vous ne pouvez pas travailler en étant menotté.'); if(!isset($_POST['pa']) || !is_numeric($_POST['pa'])) return fctErrorMSG('Vous devez sélectionner des PA.', $errorUrl); $pa = (int)$_POST['pa']; //Trouver les informations sur le producteur $query = 'SELECT *' . ' FROM `' . DB_PREFIX . 'producteur`' . ' WHERE lieuId=:lieuId;'; $prep = $db->prepare($query); $prep->bindValue(':lieuId', $perso->getLieu()->getId(), PDO::PARAM_INT); $prep->executePlus($db, __FILE__, __LINE__); $arr = $prep->fetch(); $prep->closeCursor(); $prep = NULL; if($arr === false) return fctErrorMSG('Ce lieu n\'est pas un producteur.', $errorUrl); //Validations if($perso->getPa() <= $pa) return fctErrorMSG('Vous n\'avez pas assez de PA pour effectuer cette action.', $errorUrl); if($arr['cash'] < $pa * $arr['pa_cash_ratio']) return fctErrorMSG('Le producteur n\'a soudainement plus besoin de vos services.', $errorUrl); //Travailler $cash = $pa * $arr['pa_cash_ratio']; $cashBonus = $cash * 0.1; //10% de bonus $cash = rand($cash - $cashBonus, $cash + $cashBonus); $cash = round($cash); $perso->changePa('-', $_POST['pa']); $perso->changeCash('+', $cash); $query = 'UPDATE ' . DB_PREFIX . 'producteur' . ' SET cash = cash-:cash,' . ' total_pa = total_pa+:pa' . ' WHERE id=:id' . ' LIMIT 1;'; $prep = $db->prepare($query); $prep->bindValue(':cash', $cash, PDO::PARAM_INT); $prep->bindValue(':pa', $pa, PDO::PARAM_INT); $prep->bindValue(':id', $arr['id'], PDO::PARAM_INT); $prep->executePlus($db, __FILE__, __LINE__); $prep->closeCursor(); $prep = NULL; $perso->setPa(); $perso->setCash(); $msg ='Vous travaillez pendant ' . $pa . ' Pa et obtenez une paie de ' . $cash . ' Cr. '; $msg .= $perso->setStat(array('AGI' => '-01', 'DEX' => '-02', 'FOR' => '+03' )); //Ajouter le message au HE Member_He::add('System', $perso->getId(), 'etude', $msg); //Rafraichir le HE return $tpl->fetch($account-><API key>() . 'html/Member/herefresh.htm',__FILE__,__LINE__); } }
#ifndef PROXYSTYLE_H #define PROXYSTYLE_H #include <QProxyStyle> class ProxyStyle : public QProxyStyle { public: void drawItemText(QPainter *painter, const QRect &rect, int flags, const QPalette &pal, bool enabled, const QString &text, QPalette::ColorRole textRole) const; int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const; }; #endif // PROXYSTYLE_H
#include <CustomEventWidget.h> #include <GUIConf.h> #include <<API key>.cpp> CustomEventWidget::CustomEventWidget(QWidget *parent) : QWidget(parent) { init(true, true); upperOutLayer->setText(<API key>); middleLayer->setText(<API key>); bottomOutLayer->setText(<API key>); upperIndicator->setText(<API key>); middleIndicator->setText(<API key>); bottomIndicator->setText(<API key>); QObject::connect(upperOutLayer, SIGNAL(textChanged()), this, SIGNAL(eventContentChanged())); QObject::connect(middleLayer, SIGNAL(textChanged()), this, SIGNAL(eventContentChanged())); QObject::connect(bottomOutLayer, SIGNAL(textChanged()), this, SIGNAL(eventContentChanged())); } void CustomEventWidget::init(bool showContent, bool showInstruction) { gridLayout = new QGridLayout(this); if (showContent) { initContent(); } if (showInstruction) { initInstruction(); } if (showContent && showInstruction) { gridLayout->setColumnStretch(0, 9); gridLayout->setColumnStretch(1, 1); } if (showContent || showInstruction) { gridLayout->setRowStretch(0, 2); gridLayout->setRowStretch(1, 6); gridLayout->setRowStretch(2, 2); } gridLayout->setContentsMargins(0, 0, 0, 0); gridLayout->setSpacing(0); } void CustomEventWidget::initContent() { upperOutLayer = new QTextEdit(this); middleLayer = new QTextEdit(this); bottomOutLayer = new QTextEdit(this); gridLayout->addWidget(upperOutLayer, 0, 0); gridLayout->addWidget(middleLayer, 1, 0); gridLayout->addWidget(bottomOutLayer, 2, 0); } void CustomEventWidget::initInstruction() { upperIndicator = new QTextBrowser(this); middleIndicator = new QTextBrowser(this); bottomIndicator = new QTextBrowser(this); gridLayout->addWidget(upperIndicator, 0, 1); gridLayout->addWidget(middleIndicator, 1, 1); gridLayout->addWidget(bottomIndicator, 2, 1); } CustomEventWidget::CustomEventWidget(const CustomEventWidget *eventWidget) { init(true, false); upperOutLayer->setReadOnly(true); middleLayer->setReadOnly(true); bottomOutLayer->setReadOnly(true); upperOutLayer->setText(eventWidget->getEventHead()); middleLayer->setText(eventWidget->getEventBody()); bottomOutLayer->setText(eventWidget->getEventTail()); } void CustomEventWidget::loadConf(XMLElement *eventConf) { auto headConf = eventConf->FirstChildElement(EVENT_HEAD_TAG); auto bodyConf = eventConf->FirstChildElement(EVENT_BODY_TAG); auto tailConf = eventConf->FirstChildElement(EVENT_TAIL_TAG); if (headConf) upperOutLayer->setText(headConf->GetText()); if (bodyConf) middleLayer->setText(bodyConf->GetText()); if (tailConf) bottomOutLayer->setText(tailConf->GetText()); } void CustomEventWidget::saveConf(XMLElement *eventConf) { XMLElement *headElement = eventConf->GetDocument()->NewElement(EVENT_HEAD_TAG); XMLElement *bodyElement = eventConf->GetDocument()->NewElement(EVENT_BODY_TAG); XMLElement *tailElement = eventConf->GetDocument()->NewElement(EVENT_TAIL_TAG); headElement->SetText(upperOutLayer->toPlainText().toStdString().c_str()); bodyElement->SetText(middleLayer->toPlainText().toStdString().c_str()); tailElement->SetText(bottomOutLayer->toPlainText().toStdString().c_str()); eventConf->InsertEndChild(headElement); eventConf->InsertEndChild(bodyElement); eventConf->InsertEndChild(tailElement); } QString CustomEventWidget::text() { return upperOutLayer->toPlainText() + '\n' + middleLayer->toPlainText() + '\n' + bottomOutLayer->toPlainText(); } QString CustomEventWidget::getEventHead() const { return upperOutLayer->toPlainText(); } QString CustomEventWidget::getEventBody() const { return middleLayer->toPlainText(); } QString CustomEventWidget::getEventTail() const { return bottomOutLayer->toPlainText(); }
package br.org.otus.security.api; import br.org.otus.response.builders.ResponseBuild; import br.org.otus.response.exception.<API key>; import br.org.otus.response.info.Authorization; import br.org.otus.security.dtos.*; import br.org.otus.security.services.SecurityService; import org.bson.types.ObjectId; import org.ccem.otus.exceptions.webservice.common.<API key>; import org.ccem.otus.exceptions.webservice.common.<API key>; import org.ccem.otus.exceptions.webservice.security.<API key>; import org.ccem.otus.exceptions.webservice.security.TokenException; import javax.inject.Inject; public class SecurityFacade { @Inject private SecurityService securityService; public <API key> userAuthentication(AuthenticationDto authenticationDto, String requestAddress) { try { authenticationDto.setRequestAddress(requestAddress); return securityService.authenticate(authenticationDto); } catch (<API key> | TokenException e) { throw new <API key>(ResponseBuild.Security.Authorization.build()); } } public String <API key>(<API key> <API key>, String requestAddress) { try { <API key>.setRequestAddress(requestAddress); return securityService.projectAuthenticate(<API key>); } catch (<API key> | TokenException e) { throw new <API key>(ResponseBuild.Security.Authorization.build()); } } public void invalidate(String token) { securityService.invalidate(token); } public void <API key>(<API key> <API key>) { try { securityService.<API key>(<API key>); } catch (TokenException | <API key> e) { throw new <API key>(ResponseBuild.Security.Validation.build(e.getCause().getMessage())); } } public void <API key>(<API key> <API key>) { try { securityService.<API key>(<API key>); } catch (TokenException | <API key> e) { throw new <API key>(ResponseBuild.Security.Validation.build(e.getCause().getMessage())); } } public void <API key>(String token) { try { securityService.<API key>(token); } catch (TokenException e) { throw new <API key>(ResponseBuild.Security.Validation.build("Invalid token")); } } public void <API key>(String email) { securityService.<API key>(email); } public String getRequestEmail(String token) { try { return securityService.getRequestEmail(token); } catch (<API key> e) { throw new <API key>(ResponseBuild.Security.Validation.build(e.getMessage())); } } public <API key> <API key>(AuthenticationDto authenticationDto) { try { return securityService.<API key>(authenticationDto); } catch (<API key> | TokenException e) { throw new <API key>(ResponseBuild.Security.Authorization.build()); } } public void validateToken(String token) { try { securityService.validateToken(token); } catch (<API key> | TokenException e) { throw new <API key>(ResponseBuild.Security.Authorization.build()); } } public void <API key>(String token, String activityId) { try { securityService.<API key>(token, activityId); } catch(<API key> e){ throw new <API key>(ResponseBuild.Security.Authorization.build(e.getMessage())); } catch (TokenException e) { throw new <API key>(ResponseBuild.Security.Validation.build()); } } public void <API key>(String email, String token) { securityService.<API key>(email, token); } }
-- Name: <API key>(character varying, character varying, character varying, character varying, numeric, character varying, numeric); Type: FUNCTION; Schema: deapp; Owner: - CREATE FUNCTION <API key>(trial_id character varying, top_node character varying, data_type character varying DEFAULT 'R'::character varying, source_cd character varying DEFAULT 'STD'::character varying, log_base numeric DEFAULT 2, secure_study character varying DEFAULT NULL::character varying, currentjobid numeric DEFAULT 0, OUT rtn_code numeric) RETURNS numeric LANGUAGE plpgsql AS $_$ DECLARE -- The input file columns are mapped to the following table columns. This is done so that the javascript for the advanced workflows -- selects the correct data for the dropdowns. -- tissue_type => sample_type -- attribute_1 => tissue_type -- atrribute_2 => timepoint TrialID varchar(100); RootNode varchar(2000); root_level integer; topNode varchar(2000); topLevel integer; tPath varchar(2000); study_name varchar(100); sourceCd varchar(50); secureStudy varchar(1); dataType varchar(10); sqlText varchar(1000); tText varchar(1000); gplTitle varchar(1000); pExists bigint; partTbl bigint; partExists bigint; sampleCt bigint; idxExists bigint; logBase bigint; pCount integer; sCount integer; tablespaceName varchar(200); v_bio_experiment_id bigint; --Audit variables newJobFlag integer(1); databaseName varchar(100); procedureName varchar(100); jobID bigint; stepCt bigint; --unmapped_patients exception; missing_platform exception; missing_tissue EXCEPTION; unmapped_platform exception; multiple_platform exception; no_probeset_recs exception; addNodes CURSOR FOR SELECT distinct t.leaf_node ,t.node_name from wt_RNA_SEQ_nodes t where not exists (select 1 from i2b2 x where t.leaf_node = x.c_fullname); -- cursor to define the path for delete_one_node this will delete any nodes that are hidden after <API key> delNodes CURSOR FOR SELECT distinct c_fullname from i2b2 where c_fullname like topNode || '%' and substring(c_visualattributes from 2 for 1) = 'H'; --and c_visualattributes like '_H_'; BEGIN TrialID := upper(trial_id); secureStudy := upper(secure_study); if (secureStudy not in ('Y','N') ) then secureStudy := 'Y'; end if; topNode := REGEXP_REPLACE('\' || top_node || '\','(\\){2,}', '\'); PERFORM length(topNode)-length(replace(topNode,'\','')) into topLevel ; if coalesce(data_type::text, '') = '' then dataType := 'R'; else if data_type in ('R','T','L') then dataType := data_type; else dataType := 'R'; end if; end if; logBase := log_base; sourceCd := upper(coalesce(source_cd,'STD')); --Set Audit Parameters newJobFlag := 0; -- False (Default) jobID := currentJobID; PERFORM sys_context('USERENV', 'CURRENT_SCHEMA') INTO databaseName ; procedureName := $$PLSQL_UNIT; --Audit JOB Initialization --If Job ID does not exist, then this is a single procedure run and we need to create it IF(coalesce(jobID::text, '') = '' or jobID < 1) THEN newJobFlag := 1; -- True cz_start_audit (procedureName, databaseName, jobID); END IF; stepCt := 0; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Starting <API key>',0,stepCt,'Done'); -- Get count of records in <API key> select count(*) into sCount from <API key>; -- check if all subject_sample map records have a platform, If not, abort run select count(*) into pCount from <API key> where coalesce(platform::text, '') = ''; if pCount > 0 then raise missing_platform; end if; /*select count(*) into pCount from DE_gpl_info where platform in (select distinct m.platform from <API key> m); */ /*if PCOUNT = 0 then RAISE UNMAPPED_platform; end if;*/ -- check if all subject_sample map records have a tissue_type, If not, abort run select count(*) into pCount from <API key> where coalesce(tissue_type::text, '') = ''; if pCount > 0 then raise missing_tissue; end if; -- check if there are multiple platforms, if yes, then platform must be supplied in lt_src_RNA_SEQ_data select count(*) into pCount from (select sample_cd from <API key> group by sample_cd GROUP BY xd.concept_Cd having Max(xf.valtype_cd) = 'N'); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName, HAVING count(distinct platform) > 1); if pCount > 0 then raise multiple_platform; end if; -- Get root_node from topNode PERFORM parse_nth_value(topNode, 2, '\') into RootNode ; select count(*) into pExists from table_access where c_name = rootNode; if pExists = 0 then i2b2_add_root_node(rootNode, jobId); end if; select c_hlevel into root_level from i2b2 where c_name = RootNode; -- Get study name from topNode PERFORM parse_nth_value(topNode, topLevel, '\') into study_name ; -- Add any upper level nodes as needed tPath := REGEXP_REPLACE(replace(top_node,study_name,null),'(\\){2,}', '\'); PERFORM length(tPath) - length(replace(tPath,'\',null)) into pCount ; if pCount > 2 then i2b2_fill_in_tree(null, tPath, jobId); end if; -- uppercase study_id in <API key> in case curator forgot update <API key> set trial_name=upper(trial_name); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Uppercase trial_name in <API key>',SQL%ROWCOUNT,stepCt,'Done'); commit; -- create records in patient_dimension for subject_ids if they do not exist -- format of sourcesystem_cd: trial:[site:]subject_cd insert into patient_dimension ( patient_num, sex_cd, age_in_years_num, race_cd, update_date, download_date, import_date, sourcesystem_cd ) PERFORM nextval('seq_patient_num') ,x.sex_cd ,x.age_in_years_num ,x.race_cd ,LOCALTIMESTAMP ,LOCALTIMESTAMP ,LOCALTIMESTAMP ,x.sourcesystem_cd from (select distinct 'Unknown' as sex_cd, 0 as age_in_years_num, null as race_cd, regexp_replace(TrialID || ':' || s.site_id || ':' || s.subject_id,'(::){1,}', ':') as sourcesystem_cd from <API key> s -- ,de_gpl_info g where (s.subject_id IS NOT NULL AND s.subject_id::text <> '') and s.trial_name = TrialID and s.source_cd = sourceCD -- and s.platform = g.platform --and upper(g.marker_type) = 'GENE EXPRESSION' and not exists (select 1 from patient_dimension x where x.sourcesystem_cd = regexp_replace(TrialID || ':' || s.site_id || ':' || s.subject_id,'(::){1,}', ':')) ) x; pCount := SQL%ROWCOUNT; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert subjects to patient_dimension',pCount,stepCt,'Done'); commit; <API key>(TrialId, secureStudy, jobID); -- Delete existing observation_fact data, will be repopulated delete from observation_fact obf where obf.concept_cd in (select distinct x.concept_code from <API key> x where x.trial_name = TrialId and coalesce(x.source_cd,'STD') = sourceCD and x.platform = 'RNA_AFFYMETRIX'); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Delete data from observation_fact',SQL%ROWCOUNT,stepCt,'Done'); commit; select count(*) into pExists from all_tables where table_name = 'DE_SUBJECT_RNA_DATA' and partitioned = 'YES'; if pExists = 0 then -- dataset is not partitioned so must delete delete from de_subject_rna_data where trial_source = TrialId || ':' || sourceCd; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Delete data from de_subject_rna_data',SQL%ROWCOUNT,stepCt,'Done'); commit; else -- Create partition in de_subject_RNA_data if it doesn't exist else truncate partition select count(*) into pExists from all_tab_partitions where table_name = 'DE_SUBJECT_RNA_DATA' and partition_name = TrialId || ':' || sourceCd; --10/30/2013 //modified if pExists = 0 then -- needed to add partition to de_subject_RNA_data sqlText := 'alter table deapp.de_subject_rna_data add PARTITION "' || TrialID || ':' || sourceCd || '" VALUES (' || '''' || TrialID || ':' || sourceCd || '''' || ') ' || 'NOLOGGING COMPRESS TABLESPACE "TRANSMART" '; EXECUTE(sqlText); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Adding partition to de_subject_rna_data',0,stepCt,'Done'); else sqlText := 'alter table deapp.de_subject_rna_data truncate partition "' || TrialID || ':' || sourceCd || '"'; EXECUTE(sqlText); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Truncating partition in de_subject_rna_data',0,stepCt,'Done'); end if; end if; -- Cleanup any existing data in <API key>. delete from <API key> where trial_name = TrialID and coalesce(source_cd,'STD') = sourceCd and platform = 'RNA_AFFYMETRIX'; --Making sure only RNA_sequencing data is deleted stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Delete trial from DEAPP <API key>',SQL%ROWCOUNT,stepCt,'Done'); commit; -- truncate tmp node table EXECUTE('truncate table tm_wz.wt_RNA_SEQ_nodes'); -- load temp table with leaf node path, use temp table with distinct sample_type, ATTR2, platform, and title this was faster than doing subselect -- from <API key> EXECUTE('truncate table tm_wz.<API key>'); insert into <API key> (category_cd ,platform ,tissue_type ,attribute_1 ,attribute_2 ,title ) PERFORM distinct a.category_cd ,coalesce(a.platform,'GPL570') ,coalesce(a.tissue_type,'Unspecified Tissue Type') ,a.attribute_1 ,a.attribute_2 ,''--g.title from <API key> a -- ,de_gpl_info g where a.trial_name = TrialID -- and nvl(a.platform,'GPL570') = g.platform and a.source_cd = sourceCD -- and a.platform = g.platform -- and upper(g.marker_type) = 'GENE EXPRESSION' -- and g.title = (select min(x.title) from de_gpl_info x where nvl(a.platform,'GPL570') = x.platform) -- and upper(g.organism) = 'HOMO SAPIENS' ; -- and decode(dataType,'R',sign(a.intensity_value),1) = 1; -- take all values when dataType T, only >0 for dataType R stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert node values into DEAPP <API key>',SQL%ROWCOUNT,stepCt,'Done'); commit; insert into wt_RNA_SEQ_nodes (leaf_node ,category_cd ,platform ,tissue_type ,attribute_1 ,attribute_2 ,node_type ) PERFORM distinct topNode || regexp_replace(replace(replace(replace(replace(replace(replace( category_cd,'PLATFORM',title),'ATTR1',attribute_1),'ATTR2',attribute_2),'TISSUETYPE',tissue_type),'+','\'),'_',' ') || '\','(\\){2,}', '\') ,category_cd ,platform as platform ,tissue_type ,attribute_1 as attribute_1 ,attribute_2 as attribute_2 ,'LEAF' from <API key>; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Create leaf nodes in DEAPP tmp_RNA_SEQ_nodes',SQL%ROWCOUNT,stepCt,'Done'); commit; -- insert for platform node so platform concept can be populated insert into wt_RNA_SEQ_nodes (leaf_node ,category_cd ,platform ,tissue_type ,attribute_1 ,attribute_2 ,node_type ) PERFORM distinct topNode || regexp_replace(replace(replace(replace(replace(replace(replace( substr(category_cd,1,instr(category_cd,'PLATFORM')+8),'PLATFORM',title),'ATTR1',attribute_1),'ATTR2',attribute_2),'TISSUETYPE',tissue_type),'+','\'),'_',' ') || '\', '(\\){2,}', '\') ,substr(category_cd,1,instr(category_cd,'PLATFORM')+8) ,platform as platform ,case when instr(substr(category_cd,1,instr(category_cd,'PLATFORM')+8),'TISSUETYPE') > 1 then tissue_type else null end as tissue_type ,case when instr(substr(category_cd,1,instr(category_cd,'PLATFORM')+8),'ATTR1') > 1 then attribute_1 else null end as attribute_1 ,case when instr(substr(category_cd,1,instr(category_cd,'PLATFORM')+8),'ATTR2') > 1 then attribute_2 else null end as attribute_2 ,'PLATFORM' from <API key>; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Create platform nodes in wt_RNA_SEQ_nodes',SQL%ROWCOUNT,stepCt,'Done'); commit; -- insert for ATTR1 node so ATTR1 concept can be populated in tissue_type_cd insert into wt_RNA_SEQ_nodes (leaf_node ,category_cd ,platform ,tissue_type ,attribute_1 ,attribute_2 ,node_type ) PERFORM distinct topNode || regexp_replace(replace(replace(replace(replace(replace(replace( substr(category_cd,1,instr(category_cd,'ATTR1')+5),'PLATFORM',title),'ATTR1',attribute_1),'ATTR2',attribute_2),'TISSUETYPE',tissue_type),'+','\'),'_',' ') || '\', '(\\){2,}', '\') ,substr(category_cd,1,instr(category_cd,'ATTR1')+5) ,case when instr(substr(category_cd,1,instr(category_cd,'ATTR1')+5),'PLATFORM') > 1 then platform else null end as platform ,case when instr(substr(category_cd,1,instr(category_cd,'ATTR1')+5),'TISSUETYPE') > 1 then tissue_type else null end as tissue_type ,attribute_1 as attribute_1 ,case when instr(substr(category_cd,1,instr(category_cd,'ATTR1')+5),'ATTR2') > 1 then attribute_2 else null end as attribute_2 ,'ATTR1' from <API key> where category_cd like '%ATTR1%' and (attribute_1 IS NOT NULL AND attribute_1::text <> ''); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Create ATTR1 nodes in wt_RNA_SEQ_nodes',SQL%ROWCOUNT,stepCt,'Done'); commit; -- insert for ATTR2 node so ATTR2 concept can be populated in timepoint_cd insert into wt_RNA_SEQ_nodes (leaf_node ,category_cd ,platform ,tissue_type ,attribute_1 ,attribute_2 ,node_type ) PERFORM distinct topNode || regexp_replace(replace(replace(replace(replace(replace(replace( substr(category_cd,1,instr(category_cd,'ATTR2')+5),'PLATFORM',title),'ATTR1',attribute_1),'ATTR2',attribute_2),'TISSUETYPE',tissue_type),'+','\'),'_',' ') || '\', '(\\){2,}', '\') ,substr(category_cd,1,instr(category_cd,'ATTR2')+5) ,case when instr(substr(category_cd,1,instr(category_cd,'ATTR2')+5),'PLATFORM') > 1 then platform else null end as platform ,case when instr(substr(category_cd,1,instr(category_cd,'ATTR1')+5),'TISSUETYPE') > 1 then tissue_type else null end as tissue_type ,case when instr(substr(category_cd,1,instr(category_cd,'ATTR2')+5),'ATTR1') > 1 then attribute_1 else null end as attribute_1 ,attribute_2 as attribute_2 ,'ATTR2' from <API key> where category_cd like '%ATTR2%' and (attribute_2 IS NOT NULL AND attribute_2::text <> ''); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Create ATTR2 nodes in wt_RNA_SEQ_nodes',SQL%ROWCOUNT,stepCt,'Done'); commit; -- insert for tissue_type node so sample_type_cd can be populated insert into wt_RNA_SEQ_nodes (leaf_node ,category_cd ,platform ,tissue_type ,attribute_1 ,attribute_2 ,node_type ) PERFORM distinct topNode || regexp_replace(replace(replace(replace(replace(replace(replace( substr(category_cd,1,instr(category_cd,'TISSUETYPE')+10),'PLATFORM',title),'ATTR1',attribute_1),'ATTR2',attribute_2),'TISSUETYPE',tissue_type),'+','\'),'_',' ') || '\', '(\\){2,}', '\') ,substr(category_cd,1,instr(category_cd,'TISSUETYPE')+10) ,case when instr(substr(category_cd,1,instr(category_cd,'TISSUETYPE')+10),'PLATFORM') > 1 then platform else null end as platform ,tissue_type as tissue_type ,case when instr(substr(category_cd,1,instr(category_cd,'TISSUETYPE')+10),'ATTR1') > 1 then attribute_1 else null end as attribute_1 ,case when instr(substr(category_cd,1,instr(category_cd,'TISSUETYPE')+10),'ATTR2') > 1 then attribute_2 else null end as attribute_2 ,'TISSUETYPE' from <API key> where category_cd like '%TISSUETYPE%'; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Create ATTR2 nodes in wt_RNA_SEQ_nodes',SQL%ROWCOUNT,stepCt,'Done'); commit; update wt_RNA_SEQ_nodes set node_name=parse_nth_value(leaf_node,length(leaf_node)-length(replace(leaf_node,'\',null)),'\'); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Updated node_name in DEAPP tmp_RNA_SEQ_nodes',SQL%ROWCOUNT,stepCt,'Done'); commit; -- add leaf nodes for RNA_sequencing data The cursor will only add nodes that do not already exist. FOR r_addNodes in addNodes Loop --Add nodes for all types (ALSO DELETES EXISTING NODE) i2b2_add_node(TrialID, r_addNodes.leaf_node, r_addNodes.node_name, jobId); stepCt := stepCt + 1; tText := 'Added Leaf Node: ' || r_addNodes.leaf_node || ' Name: ' || r_addNodes.node_name; cz_write_audit(jobId,databaseName,procedureName,tText,SQL%ROWCOUNT,stepCt,'Done'); i2b2_fill_in_tree(TrialId, r_addNodes.leaf_node, jobID); END LOOP; -- update concept_cd for nodes, this is done to make the next insert easier update wt_RNA_SEQ_nodes t set concept_cd=(select c.concept_cd from concept_dimension c where c.concept_path = t.leaf_node ) where exists (select 1 from concept_dimension x where x.concept_path = t.leaf_node ) and coalesce(t.concept_cd::text, '') = ''; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Update wt_RNA_SEQ_nodes with newly created concept_cds',SQL%ROWCOUNT,stepCt,'Done'); commit; --Load the <API key> from <API key> --PATIENT_ID = PATIENT_ID (SAME AS ID ON THE PATIENT_DIMENSION) --SITE_ID = site_id --SUBJECT_ID = subject_id --SUBJECT_TYPE = NULL --CONCEPT_CODE = from LEAF records in wt_RNA_SEQ_nodes --SAMPLE_TYPE = TISSUE_TYPE --SAMPLE_TYPE_CD = concept_cd from TISSUETYPE records in wt_RNA_SEQ_nodes --TRIAL_NAME = TRIAL_NAME --TIMEPOINT = attribute_2 --TIMEPOINT_CD = concept_cd from ATTR2 records in wt_RNA_SEQ_nodes --TISSUE_TYPE = attribute_1 --TISSUE_TYPE_CD = concept_cd from ATTR1 records in wt_RNA_SEQ_nodes --PLATFORM = <API key> - this is required by ui code --PLATFORM_CD = concept_cd from PLATFORM records in wt_RNA_SEQ_nodes --DATA_UID = concatenation of <API key> --GPL_ID = platform from <API key> --CATEGORY_CD = category_cd that generated ontology --SAMPLE_ID = id of sample (trial:S:[site_id]:subject_id:sample_cd) from patient_dimension, may be the same as patient_num --SAMPLE_CD = sample_cd --SOURCE_CD = sourceCd --ASSAY_ID = generated by trigger insert into <API key> (patient_id ,site_id ,subject_id ,subject_type ,concept_code ,assay_id ,sample_type ,sample_type_cd ,trial_name ,timepoint ,timepoint_cd ,tissue_type ,tissue_type_cd ,platform ,platform_cd ,data_uid ,gpl_id ,sample_id ,sample_cd ,category_cd ,source_cd ,omic_source_study ,omic_patient_id ) PERFORM t.patient_id ,t.site_id ,t.subject_id ,t.subject_type ,t.concept_code ,deapp.nextval('seq_assay_id') ,t.sample_type ,t.sample_type_cd ,t.trial_name ,t.timepoint ,t.timepoint_cd ,t.tissue_type ,t.tissue_type_cd ,t.platform ,t.platform_cd ,t.data_uid ,t.gpl_id ,t.sample_id ,t.sample_cd ,t.category_cd ,t.source_cd ,t.omic_source_study ,t.omic_patient_id from (select distinct b.patient_num as patient_id ,a.site_id ,a.subject_id ,null as subject_type ,ln.concept_cd as concept_code ,a.tissue_type as sample_type ,ttp.concept_cd as sample_type_cd ,a.trial_name ,a.attribute_2 as timepoint ,a2.concept_cd as timepoint_cd ,a.attribute_1 as tissue_type ,a1.concept_cd as tissue_type_cd ,'RNA_AFFYMETRIX' as platform ,pn.concept_cd as platform_cd ,ln.concept_cd || '-' || to_char(b.patient_num) as data_uid ,a.platform as gpl_id ,coalesce(sid.patient_num,b.patient_num) as sample_id ,a.sample_cd ,coalesce(a.category_cd,'Biomarker_Data+RNA_SEQ+PLATFORM+TISSUETYPE+ATTR1+ATTR2') as category_cd ,a.source_cd ,TrialId as omic_source_study ,b.patient_num as omic_patient_id from <API key> a --Joining to Pat_dim to ensure the ID's match. If not I2B2 won't work. inner join patient_dimension b on regexp_replace(TrialID || ':' || a.site_id || ':' || a.subject_id,'(::){1,}', ':') = b.sourcesystem_cd inner join wt_RNA_SEQ_nodes ln on a.platform = ln.platform and a.tissue_type = ln.tissue_type and coalesce(a.attribute_1,'@') = coalesce(ln.attribute_1,'@') and coalesce(a.attribute_2,'@') = coalesce(ln.attribute_2,'@') and ln.node_type = 'LEAF' inner join wt_RNA_SEQ_nodes pn on a.platform = pn.platform and case when instr(substr(a.category_cd,1,instr(a.category_cd,'PLATFORM')+8),'TISSUETYPE') > 1 then a.tissue_type else '@' end = coalesce(pn.tissue_type,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'PLATFORM')+8),'ATTR1') > 1 then a.attribute_1 else '@' end = coalesce(pn.attribute_1,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'PLATFORM')+8),'ATTR2') > 1 then a.attribute_2 else '@' end = coalesce(pn.attribute_2,'@') and pn.node_type = 'PLATFORM' left outer join wt_RNA_SEQ_nodes ttp on a.tissue_type = ttp.tissue_type and case when instr(substr(a.category_cd,1,instr(a.category_cd,'TISSUETYPE')+10),'PLATFORM') > 1 then a.platform else '@' end = coalesce(ttp.platform,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'TISSUETYPE')+10),'ATTR1') > 1 then a.attribute_1 else '@' end = coalesce(ttp.attribute_1,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'TISSUETYPE')+10),'ATTR2') > 1 then a.attribute_2 else '@' end = coalesce(ttp.attribute_2,'@') and ttp.node_type = 'TISSUETYPE' left outer join wt_RNA_SEQ_nodes a1 on a.attribute_1 = a1.attribute_1 and case when instr(substr(a.category_cd,1,instr(a.category_cd,'ATTR1')+5),'PLATFORM') > 1 then a.platform else '@' end = coalesce(a1.platform,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'ATTR1')+5),'TISSUETYPE') > 1 then a.tissue_type else '@' end = coalesce(a1.tissue_type,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'ATTR1')+5),'ATTR2') > 1 then a.attribute_2 else '@' end = coalesce(a1.attribute_2,'@') and a1.node_type = 'ATTR1' left outer join wt_RNA_SEQ_nodes a2 on a.attribute_2 = a1.attribute_2 and case when instr(substr(a.category_cd,1,instr(a.category_cd,'ATTR2')+5),'PLATFORM') > 1 then a.platform else '@' end = coalesce(a2.platform,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'ATTR2')+5),'TISSUETYPE') > 1 then a.tissue_type else '@' end = coalesce(a2.tissue_type,'@') and case when instr(substr(a.category_cd,1,instr(a.category_cd,'ATTR2')+5),'ATTR1') > 1 then a.attribute_1 else '@' end = coalesce(a2.attribute_1,'@') and a2.node_type = 'ATTR2' left outer join patient_dimension sid on regexp_replace(TrialId || 'S:' || a.site_id || ':' || a.subject_id || ':' || a.sample_cd, '(::){1,}', ':') = sid.sourcesystem_cd where a.trial_name = TrialID and a.source_cd = sourceCD and (ln.concept_cd IS NOT NULL AND ln.concept_cd::text <> '')) t; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert trial into DEAPP <API key>',SQL%ROWCOUNT,stepCt,'Done'); commit; -- recreate <API key> indexes --execute immediate('create index <API key> on <API key>(timepoint, patient_id, trial_name) parallel nologging'); --execute immediate('create index <API key> on <API key>(patient_id, timepoint_cd, platform_cd, assay_id, trial_name) parallel nologging'); --execute immediate('create bitmap index <API key> on <API key>(sample_type_cd) parallel nologging'); --execute immediate('create index <API key> on <API key>(gpl_id) parallel nologging'); --execute immediate('create index <API key> on <API key>(platform, gpl_id) parallel nologging'); --stepCt := stepCt + 1; --cz_write_audit(jobId,databaseName,procedureName,'Recreate indexes on DEAPP <API key>',0,stepCt,'Done'); -- Insert records for patients and samples into observation_fact insert into observation_fact (patient_num ,concept_cd ,modifier_cd ,valtype_cd ,tval_char ,nval_num ,sourcesystem_cd ,import_date ,valueflag_cd ,provider_id ,location_cd ,units_cd ,INSTANCE_NUM ) PERFORM distinct m.patient_id ,m.concept_code ,'@' ,'T' -- Text data type ,'E' --Stands for Equals for Text Types ,null -- not numeric for RNA_sequencing ,m.trial_name ,LOCALTIMESTAMP ,'@' ,'@' ,'@' ,'' -- no units available ,1 from <API key> m where m.trial_name = TrialID and m.source_cd = sourceCD and m.platform = 'RNA_AFFYMETRIX'; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert patient facts into I2B2DEMODATA observation_fact',SQL%ROWCOUNT,stepCt,'Done'); commit; -- Insert sample facts insert into observation_fact (patient_num ,concept_cd ,modifier_cd ,valtype_cd ,tval_char ,nval_num ,sourcesystem_cd ,import_date ,valueflag_cd ,provider_id ,location_cd ,units_cd ,INSTANCE_NUM ) PERFORM distinct m.sample_id ,m.concept_code ,m.trial_name ,'T' -- Text data type ,'E' --Stands for Equals for Text Types ,null -- not numeric for RNA_sequencing ,m.trial_name ,LOCALTIMESTAMP ,'@' ,'@' ,'@' ,'' -- no units available ,1 from <API key> m where m.trial_name = TrialID and m.source_cd = sourceCd and m.platform = 'RNA_AFFYMETRIX' and m.patient_id != m.sample_id; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert sample facts into I2B2DEMODATA observation_fact',SQL%ROWCOUNT,stepCt,'Done'); commit; --Update I2b2 for correct data type update i2b2 t set c_columndatatype = 'T', c_metadataxml = null, c_visualattributes='FA' where t.c_basecode in (select distinct x.concept_cd from wt_RNA_SEQ_nodes x); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Initialize data_type and xml in i2b2',SQL%ROWCOUNT,stepCt,'Done'); commit; update i2b2 SET c_columndatatype = 'N', --Static XML String c_metadataxml = '<?xml version="1.0"?><ValueMetadata><Version>3.02</Version><CreationDateTime>08/14/2008 01:22:59</CreationDateTime><TestID></TestID><TestName></TestName><DataType>PosFloat</DataType><CodeType></CodeType><Loinc></Loinc><Flagstouse></Flagstouse><Oktousevalues>Y</Oktousevalues><MaxStringLength></MaxStringLength><LowofLowValue>0</LowofLowValue><HighofLowValue>0</HighofLowValue><LowofHighValue>100</LowofHighValue>100<HighofHighValue>100</HighofHighValue><LowofToxicValue></LowofToxicValue><HighofToxicValue></HighofToxicValue><EnumValues></EnumValues><<API key>><Com></Com></<API key>><UnitValues><NormalUnits>ratio</NormalUnits><EqualUnits></EqualUnits><ExcludingUnits></ExcludingUnits><ConvertingUnits><Units></Units><MultiplyingFactor></MultiplyingFactor></ConvertingUnits></UnitValues><Analysis><Enums /><Counts /><New /></Analysis></ValueMetadata>' where c_basecode IN ( SELECT xd.concept_cd from wt_RNA_SEQ_nodes xd ,observation_fact xf where xf.concept_cd = xd.concept_cd procedureName,'Update c_columndatatype and c_metadataxml for numeric data types in I2B2METADATA i2b2',SQL%ROWCOUNT,stepCt,'Done'); commit; /* --UPDATE VISUAL ATTRIBUTES for Leaf Active (Default is folder) update i2b2 a set c_visualattributes = 'LA' where 1 = ( select count(*) from i2b2 b where b.c_fullname like (a.c_fullname || '%')) and c_fullname like '%' || topNode || '%'; */ --UPDATE VISUAL ATTRIBUTES for Leaf Active (Default is folder) update i2b2 a set c_visualattributes = 'LAH' where a.c_basecode in (select distinct x.concept_code from <API key> x where x.trial_name = TrialId and x.platform = 'RNA_AFFYMETRIX' and (x.concept_code IS NOT NULL AND x.concept_code::text <> '')); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Update visual attributes for leaf nodes in I2B2METADATA i2b2',SQL%ROWCOUNT,stepCt,'Done'); COMMIT; insert into probeset_deapp ( probeset, platform )select distinct s.probeset ,m.platform from lt_src_rna_seq_data s, <API key> m where s.trial_name=m.trial_name and not exists (select 1 from probeset_deapp x where m.platform = x.platform and s.probeset = x.probeset); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert new probesets into probeset_deapp',SQL%ROWCOUNT,stepCt,'Done'); --Build concept Counts --Also marks any i2B2 records with no underlying data as Hidden, need to do at Trial level because there may be multiple platform and there is no longer -- a unique top-level node for RNA_sequencing data <API key>(topNode ,jobID ); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Create concept counts',0,stepCt,'Done'); -- delete each node that is hidden FOR r_delNodes in delNodes Loop -- deletes hidden nodes for a trial one at a time i2b2_delete_1_node(r_delNodes.c_fullname); stepCt := stepCt + 1; tText := 'Deleted node: ' || r_delNodes.c_fullname; cz_write_audit(jobId,databaseName,procedureName,tText,SQL%ROWCOUNT,stepCt,'Done'); END LOOP; --Reload Security: Inserts one record for every I2B2 record into the security table <API key>(jobId); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Load security data',0,stepCt,'Done'); -- tag data with probeset_id from reference.probeset_deapp EXECUTE ('truncate table tm_wz.<API key>'); -- note: assay_id represents a unique subject/site/sample insert into <API key> (probeset_id -- ,expr_id ,intensity_value ,patient_id -- ,sample_cd -- ,subject_id ,trial_name ,assay_id ) select md.probeset -- ,sd.sample_cd , avg(md.intensity_value) as intensity_value ,sd.patient_id -- ,sd.sample_cd -- ,sd.subject_id ,TrialId as trial_name ,sd.assay_id from <API key> sd ,lt_src_RNA_SEQ_data md ,probeset_deapp gs where sd.sample_cd = md.expr_id and sd.platform = 'RNA_AFFYMETRIX' and sd.trial_name = TrialId and sd.source_cd = sourceCd -- and sd.gpl_id = gs.platform and md.probeset = gs.probeset and decode(dataType,'R',sign(md.intensity_value),1) = 1 -- take only >0 for dataType R --and rownum = 1 group by md.probeset -- ,sd.sample_cd ,sd.patient_id -- ,sd.sample_cd -- ,sd.subject_id ,sd.assay_id; pExists := SQL%ROWCOUNT; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert into DEAPP <API key>',SQL%ROWCOUNT,stepCt,'Done'); commit; /*if pExists = 0 then raise no_probeset_recs; end if;*/ -- insert into de_subject_rna_data when dataType is T (transformed) if dataType = 'T' then insert into de_subject_rna_data (trial_source ,probeset_id ,assay_id ,patient_id --,sample_id --,subject_id ,trial_name ,zscore ) PERFORM TrialId || ':' || sourceCd ,probeset_id ,assay_id ,patient_id --,sample_id --,subject_id ,trial_name ,case when intensity_value < -2.5 then -2.5 when intensity_value > 2.5 then 2.5 else intensity_value end as zscore from <API key> where trial_name = TrialID; stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Insert transformed into DEAPP de_subject_rna_data',SQL%ROWCOUNT,stepCt,'Done'); commit; else -- Calculate ZScores and insert data into de_subject_rna_data. The 'L' parameter indicates that the RNA_sequencing data will be selected from -- <API key> as part of a Load. if dataType = 'R' or dataType = 'L' then <API key>(TrialID,'L',jobId,dataType,logBase,sourceCD); stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'Calculate Z-Score',0,stepCt,'Done'); commit; end if; end if; Cleanup OVERALL JOB if this proc is being run standalone stepCt := stepCt + 1; cz_write_audit(jobId,databaseName,procedureName,'End <API key>',0,stepCt,'Done'); IF newJobFlag = 1 THEN cz_end_audit (jobID, 'SUCCESS'); END IF; PERFORM 0 into rtn_code ; EXCEPTION --when unmapped_patients then -- cz_write_audit(jobId,databasename,procedurename,'No site_id/subject_id mapped to patient_dimension',1,stepCt,'ERROR'); -- cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); -- cz_end_audit (jobId,'FAIL'); when missing_platform then cz_write_audit(jobId,databasename,procedurename,'Platform data missing from one or more subject_sample mapping records',1,stepCt,'ERROR'); cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); cz_end_audit (jobId,'FAIL'); PERFORM 161 into rtn_code ; when missing_tissue then cz_write_audit(jobId,databasename,procedurename,'Tissue Type data missing from one or more subject_sample mapping records',1,stepCt,'ERROR'); cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); CZ_END_AUDIT (JOBID,'FAIL'); PERFORM 162 into rtn_code ; /*when unmapped_platform then cz_write_audit(jobId,databasename,procedurename,'Platform not found in de_RNA_annotation',1,stepCt,'ERROR'); cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); cz_end_audit (jobId,'FAIL'); select 163 into rtn_code from dual;*/ when multiple_platform then cz_write_audit(jobId,databasename,procedurename,'Multiple platforms for sample_cd in <API key>',1,stepCt,'ERROR'); cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); cz_end_audit (jobId,'FAIL'); PERFORM 164 into rtn_code ; /*when no_probeset_recs then cz_write_audit(jobId,databasename,procedurename,'Unable to match probesets to platform in probeset_deapp',1,stepCt,'ERROR'); cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); cz_end_audit (jobId,'FAIL'); select 165 into rtn_code from dual;*/ WHEN OTHERS THEN --Handle errors. cz_error_handler(jobId, procedureName, SQLSTATE, SQLERRM); --End Proc cz_end_audit (jobID, 'FAIL'); PERFORM 166 into rtn_code ; END; $_$;
"use strict"; var MapperGame = function(htmlElements) { this.displayCanvas = htmlElements.mainCanvas; this.displayContext; this.bufferCanvas; this.bufferContext; this.diagCostText = htmlElements.diagCostText; this.critPointOptCheck = htmlElements.critPointOptCheck; this.wallCostText = htmlElements.wallCost; this.width = this.displayCanvas.width; this.height = this.displayCanvas.height; this.spiderIcon; this.spider; this.flyIcon; this.flies = []; this.maze; this.grid; this.path = []; this.initialize = function() { this.loadImages(this.initializeObjects.bind(this)); }; /* Must wait for the images to be loaded, or the dimensions * will return a 0 while constructing objects */ this.loadImages = function(cb) { this.flyIcon = loadImage('fly.png', undefined); this.spiderIcon = loadImage('spider.png', cb); }; this.initializeObjects = function() { this.bufferCanvas = document.createElement('canvas'); this.bufferCanvas.width = this.width; this.bufferCanvas.height = this.height; this.displayContext = this.displayCanvas.getContext("2d"); this.bufferContext = this.bufferCanvas.getContext("2d"); this.spider = new Spider(this.bufferContext, this.spiderIcon, this.width, this.height); this.maze = new Maze(this.bufferContext, this.width, this.height); this.grid = new Grid(this.width, this.height); document.onkeydown = this.checkKeyDown.bind(this); document.onkeyup = this.checkKeyUp.bind(this); this.displayCanvas.onmousedown = this.checkMouseDown.bind(this); // Controls this.diagCostText.oninput = this.checkDiagCost.bind(this); this.checkDiagCost(null); this.critPointOptCheck.onchange = this.checkCritPointOpt.bind(this); this.checkCritPointOpt(null); this.wallCostText.oninput = this.checkWallCost.bind(this); this.checkWallCost(null); // Disable the right click context menu this.displayCanvas.oncontextmenu = function(){return false;}; this.grid.initializeGrid(); this.renderLoop(); }; this.renderLoop = function() { var idx; // Prep offscreen buffer this.bufferContext.clearRect(0,0,this.width, this.height); // Game logic this.spider.move(); this.checkWallCollision(); for (idx = 0; idx < this.flies.length; idx++) { if (this.flies[idx].checkCollision(this.spider.location)) { this.flies.splice(idx, 1); idx } } // Draw code this.maze.render(); this.grid.render(this.bufferContext); for (idx = 0; idx < this.flies.length; idx++) { this.flies[idx].render(); } this.spider.render(); this.drawPath(); // Screen flip this.displayContext.clearRect(0,0,this.width, this.height); this.displayContext.drawImage(this.bufferCanvas, 0, 0); <API key>(this.renderLoop.bind(this)); }; this.checkWallCollision = function() { var walls = this.maze.walls; var diffX, diffY; var idx; for (idx = 0; idx < walls.length; idx++) { diffX = Math.abs(this.spider.location.x - walls[idx].location.x); diffY = Math.abs(this.spider.location.y - walls[idx].location.y); if (diffX < (walls[idx].halfSide + this.spider.halfWidth) && diffY < (walls[idx].halfSide + this.spider.halfHeight)) { if (diffX > diffY) { this.spider.velocity.x = 0; if (this.spider.location.x > walls[idx].location.x) { this.spider.location.x = walls[idx].location.x + walls[idx].halfSide + this.spider.halfWidth; } else { this.spider.location.x = walls[idx].location.x - walls[idx].halfSide - this.spider.halfWidth; } } else { this.spider.velocity.y = 0; if (this.spider.location.y > walls[idx].location.y) { this.spider.location.y = walls[idx].location.y + walls[idx].halfSide + this.spider.halfHeight; } else { this.spider.location.y = walls[idx].location.y - walls[idx].halfSide - this.spider.halfHeight; } } } } }; this.drawPath = function() { var idx; if (this.grid.pathFound) { this.bufferContext.beginPath(); this.bufferContext.lineWidth="5"; this.bufferContext.strokeStyle="red"; this.bufferContext.moveTo(this.grid.path[0].x, this.grid.path[0].y); for (idx = 1; idx < this.grid.path.length; idx++) { this.bufferContext.lineTo(this.grid.path[idx].x, this.grid.path[idx].y); } this.bufferContext.stroke(); // Draw it } }; this.checkKeyDown = function(e) { var dispatch = {'38':this.spider.upArrowDown.bind(this.spider), // Up Arrow '87':this.spider.upArrowDown.bind(this.spider), '40':this.spider.downArrowDown.bind(this.spider), // Down Arrow '83':this.spider.downArrowDown.bind(this.spider), '37':this.spider.leftArrowDown.bind(this.spider), // Left Arrow '65':this.spider.leftArrowDown.bind(this.spider), '39':this.spider.rightArrowDown.bind(this.spider), // Right Arrow '68':this.spider.rightArrowDown.bind(this.spider) }; e = e || window.event; if (dispatch[e.keyCode]) { dispatch[e.keyCode](); } }; this.checkKeyUp = function(e) { var dispatch = {'38':this.spider.upArrowUp.bind(this.spider), // Up Arrow '87':this.spider.upArrowUp.bind(this.spider), '40':this.spider.downArrowUp.bind(this.spider), // Down Arrow '83':this.spider.downArrowUp.bind(this.spider), '37':this.spider.leftArrowUp.bind(this.spider), // Left Arrow '65':this.spider.leftArrowUp.bind(this.spider), '39':this.spider.rightArrowUp.bind(this.spider), // Right Arrow '68':this.spider.rightArrowUp.bind(this.spider) }; e = e || window.event; if (dispatch[e.keyCode]) { dispatch[e.keyCode](); } }; this.checkMouseDown = function(e) { var clickLocation = new Vector2D(e.offsetX, e.offsetY); var idx; var goalLocations = []; var wallLocations = []; e = e || window.event; clickLocation = clickLocation.round(); if (e.button === 0) { this.flies.push(new Fly(this.bufferContext, clickLocation, this.flyIcon)); for (idx = 0; idx < this.flies.length; idx++) { goalLocations.push(this.flies[idx].location); } this.grid.<API key>(this.spider.location.round(), goalLocations); } else if (e.button === 2) { this.maze.processClick(clickLocation); this.maze.render(); this.grid.<API key>(); for (idx = 0; idx < this.maze.walls.length; idx++) { wallLocations.push(this.maze.walls[idx].location); } this.grid.<API key>(wallLocations); } }; this.checkDiagCost = function(evt) { var idx; var wallLocations = []; var textStr = this.diagCostText.value; var patt = /^([0-9]+\.[0-9]+|[0-9]+)$/; if (patt.test(textStr)) { this.grid.diagonalCost = parseFloat(textStr); this.grid.initializeGrid(); for (idx = 0; idx < this.maze.walls.length; idx++) { wallLocations.push(this.maze.walls[idx].location); } this.grid.<API key>(wallLocations); } }; this.checkCritPointOpt = function(evt) { this.grid.criticalPointOpt = this.critPointOptCheck.checked; }; this.checkWallCost = function(evt) { var idx; var wallLocations = []; var textStr = this.wallCostText.value; var patt = /^([0-9]+\.[0-9]+|[0-9]+)$/; if (patt.test(textStr)) { this.grid.wallCost = parseFloat(textStr); this.grid.initializeGrid(); for (idx = 0; idx < this.maze.walls.length; idx++) { wallLocations.push(this.maze.walls[idx].location); } this.grid.<API key>(wallLocations); } }; }; function loadImage(src, cb) { var img1 = false; if (document.images) { img1 = new Image(); img1.onload = cb; img1.src = src; } return img1; } /* TODO: Critical node optimization sometimes adds a critical node it passes by * TODO: Accounting for motion * TODO: Find shortest path to all flies * TODO: Move spider to flies * TODO: A* optimization */
// 2008 Irene Ruengeler // 2009 Thomas Dreibholz // This program is free software; you can redistribute it and/or // as published by the Free Software Foundation; either version 2 // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #ifndef __TCPDUMP_H #define __TCPDUMP_H #include <omnetpp.h> #include <assert.h> #include "IPAddress.h" //#include "IPDatagram_m.h" #include "IPDatagram.h" #include "SCTPMessage.h" #include "TCPSegment.h" #include "IPv6Datagram_m.h" #define PCAP_MAGIC 0xa1b2c3d4 #define RBUFFER_SIZE 65535 /* "libpcap" file header (minus magic number). */ struct pcap_hdr { uint32 magic; /* magic */ uint16 version_major; /* major version number */ uint16 version_minor; /* minor version number */ uint32 thiszone; /* GMT to local correction */ uint32 sigfigs; /* accuracy of timestamps */ uint32 snaplen; /* max length of captured packets, in octets */ uint32 network; /* data link type */ }; /* "libpcap" record header. */ struct pcaprec_hdr { int32 ts_sec; /* timestamp seconds */ uint32 ts_usec; /* timestamp microseconds */ uint32 incl_len; /* number of octets of packet saved in file */ uint32 orig_len; /* actual length of packet */ }; typedef struct { uint8 dest_addr[6]; uint8 src_addr[6]; uint16 l3pid; } hdr_ethernet_t; /* T.D. 22.09.09: commented this out, since it is not used anywhere. static hdr_ethernet_t HDR_ETHERNET = { {0x02, 0x02, 0x02, 0x02, 0x02, 0x02}, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, 0}; */ /** * Dumps SCTP packets in tcpdump format. */ class TCPDumper { protected: int32 seq; std::ostream *outp; public: TCPDumper(std::ostream& o); ~TCPDumper(); inline void setVerbosity(const int32 verbosityLevel) { verbosity = verbosityLevel; } void ipDump(const char *label, IPDatagram *dgram, const char *comment=NULL); void sctpDump(const char *label, SCTPMessage *sctpmsg, const std::string& srcAddr, const std::string& destAddr, const char *comment=NULL); // dumps arbitary text void dump(const char *label, const char *msg); void tcpDump(bool l2r, const char *label, IPDatagram *dgram, const char *comment=NULL); void tcpDump(bool l2r, const char *label, TCPSegment *tcpseg, const std::string& srcAddr, const std::string& destAddr, const char *comment=NULL); void dumpIPv6(bool l2r, const char *label, IPv6Datagram_Base *dgram, const char *comment=NULL);//FIXME: Temporary hack void udpDump(bool l2r, const char *label, IPDatagram *dgram, const char *comment); const char* intToChunk(int32 type); FILE *dumpfile; private: int verbosity; }; /** * Dumps every packet using the TCPDumper class */ class INET_API TCPDump : public cSimpleModule { protected: unsigned char* ringBuffer[RBUFFER_SIZE]; TCPDumper tcpdump; unsigned int snaplen; unsigned long first, last, space; public: TCPDump(); ~TCPDump(); virtual void handleMessage(cMessage *msg); virtual void initialize(); virtual void finish(); }; #endif