repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
smtech/advisor-dashboard
account/rename-advisory-groups.php
2704
<?php require_once('common.inc.php'); use Battis\BootstrapSmarty\NotificationMessage; $STEP_INSTRUCTIONS = 1; $STEP_RENAME = 2; $step = (empty($_REQUEST['step']) ? $STEP_INSTRUCTIONS : $_REQUEST['step']); switch ($step) { case $STEP_RENAME: try { $updated = 0; $unchanged = 0; $courses = $toolbox->api_get("accounts/{$_REQUEST['account']}/courses", [ 'enrollment_term_id' => $_REQUEST['term'], 'with_enrollments' => 'true' ]); foreach ($courses as $course) { $teachers = $toolbox->api_get("/courses/{$course['id']}/enrollments", [ 'type' => 'TeacherEnrollment' ]); if ($teacher = $teachers[0]['user']) { $nameParts = explode(',', $teacher['sortable_name']); $courseName = trim($nameParts[0]) . ' Advisory Group'; $toolbox->api_put("courses/{$course['id']}", [ 'course[name]' => $courseName, 'course[course_code]' => $courseName ]); $sections = $toolbox->api_get("courses/{$course['id']}/sections"); foreach ($sections as $section) { if ($section['name'] == $course['name']) { $toolbox->api_put("sections/{$sections[0]['id']}", [ 'course_section[name]' => $courseName ]); } } $updated++; } else { $unchanged++; } } } catch (Exception $e) { $toolbox->smarty_addMessage('Error ' . $e->getCode(), $e->getMessage(), NotificationMessage::DANGER); } $courses = $toolbox->api_get("accounts/{$_REQUEST['account']}/courses", [ 'enrollment_term_id' => $_REQUEST['term'], 'with_enrollments' => 'true', 'published' => 'true' ]); $toolbox->smarty_addMessage( 'Renamed advisory courses', "$updated courses were renamed, and $unchanged were left unchanged.", NotificationMessage::SUCCESS ); /* fall through into $STEP_INSTRUCTIONS */ case $STEP_INSTRUCTIONS: default: $toolbox->smarty_assign([ 'terms' => $toolbox->getTermList(), 'formHidden' => [ 'step' => $STEP_RENAME, 'account' => $_SESSION['accountId'] ] ]); $toolbox->smarty_display(basename(__FILE__, '.php') . '/instructions.tpl'); }
gpl-3.0
esprange/kleistad
includes/class-shortcode.php
12032
<?php /** * De abstracte class voor shortcodes. * * @link https://www.kleistad.nl * @since 4.0.87 * * @package Kleistad * @subpackage Kleistad/includes */ namespace Kleistad; use WP_Error; use WP_REST_Request; use WP_REST_Response; use Exception; use ReflectionClass; /** * De abstract class voor shortcodes */ abstract class Shortcode { const STANDAARD_ACTIE = 'overzicht'; /** * De shortcode. * * @var string shortcode (zonder kleistad-) */ protected string $shortcode; /** * De data die gebruikt wordt voor display. * * @var array shortcode data */ protected array $data = []; /** * Controle array om te voorkomen dat shortcodes meerdere keren voorkomen. * * @var array shortcode tags */ protected static array $tags = []; /** * Actie welke bepaald welke informatie getoond moet worden. * * @var string $display_actie De uit te voeren actie. */ protected string $display_actie = ''; /** * File download resource. * * @var resource $filehandle File handle voor output. */ protected $filehandle; /** * Maak de uit te voeren html aan * * @since 4.5.1 * * @return string html tekst. */ public function display() : string { $this->enqueue(); $this->bepaal_actie(); try { $ontvangen = new Ontvangen(); $betaal_result = $ontvangen->controleer(); if ( is_string( $betaal_result ) ) { // Er is een succesvolle betaling, toon het bericht. return $this->status( $betaal_result ) . $this->goto_home(); } if ( is_wp_error( $betaal_result ) ) { // Er is een betaling maar niet succesvol. return $this->status( $betaal_result ) . $this->prepare(); } return $this->prepare(); // Er is geen betaling, toon de reguliere inhoud van de shortcode. } catch ( Exception $exceptie ) { fout( __CLASS__, $exceptie->getMessage() ); return $this->status( new WP_Error( 'exceptie', 'Er is een onbekende fout opgetreden' ) ); } } /** * Toon de status van de het resultaat * * @since 5.7.0 * * @param string | array | WP_Error $result Het resultaat dat getoond moet worden. * @return string Html tekst. */ public function status( string|array|WP_Error $result ) : string { $html = ''; if ( is_wp_error( $result ) ) { foreach ( $result->get_error_messages() as $error ) { $html .= melding( 0, $error ); } return $html; } $succes = $result['status'] ?? ( is_string( $result ) ? $result : '' ); if ( ! empty( $succes ) ) { $html = melding( 1, $succes ); } return $html; } /** * Toon een OK button in het midden van het scherm * * @since 5.7.0 * @return string */ public function goto_home() : string { $html_objectclass = get_class( $this ) . '_Display'; if ( ! class_exists( $html_objectclass ) ) { fout( __CLASS__, "Display object $html_objectclass niet aanwezig" ); return ''; } $dummy = []; $display = new $html_objectclass( $dummy, '' ); ob_start(); $display->home(); return ob_get_clean(); } /** * De constructor * * @since 4.0.87 * * @param string $shortcode Shortcode (zonder kleistad- ). * @param array $attributes Shortcode parameters. */ protected function __construct( string $shortcode, array $attributes ) { foreach ( $attributes as $att_key => $attribute ) { $this->data[ $att_key ] = htmlspecialchars_decode( $attribute ); } $this->shortcode = $shortcode; } /** * Basis prepare functie om te bepalen wat er getoond moet worden. * Als er geen acties zijn, dan kan de prepare functie overschreven worden. * * @return string */ protected function prepare() : string { $method = 'prepare_' . $this->display_actie; if ( method_exists( $this, $method ) ) { return $this->$method(); } fout( __CLASS__, "method $method ontbreekt" ); return $this->status( new WP_Error( 'intern', 'Er is een onbekende fout opgetreden' ) ); } /** * Enqueue the scripts and styles for the shortcode. */ protected function enqueue() { $reflect = new ReflectionClass( $this ); $script = 'kleistad-' . substr( strtolower( $reflect->getShortName() ), strlen( 'public-' ) ); if ( wp_script_is( $script, 'registered' ) ) { wp_enqueue_script( $script ); } if ( ! wp_script_is( 'kleistad' ) ) { wp_enqueue_script( 'kleistad' ); } } /** * Haal de tekst van de shortcode op. * * @return string */ protected function content() : string { $display_class = get_class( $this ) . '_Display'; $display = new $display_class( $this->data, $this->display_actie ); return $display->render(); } /** * Singleton handler * * @param string $shortcode_tag Shortcode (zonder kleistad- ). * @param array $attributes Shortcode parameters. * @return Shortcode | null * @throws Kleistad_Exception Als er de shortcode meer dat eens op de pagina voorkomt. */ public static function get_instance( string $shortcode_tag, array $attributes ) : ?Shortcode { // Het onderstaande voorkomt dat pagina edits gezien worden als een dubbel voorkomende shortcode. $backend = ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || is_admin(); if ( in_array( $shortcode_tag, self::$tags, true ) && ! $backend ) { throw new Kleistad_Exception( "De shortcode kleistad_$shortcode_tag mag maar éénmaal per pagina gebruikt worden" ); } self::$tags[] = $shortcode_tag; $shortcode_class = self::get_class_name( $shortcode_tag ); return new $shortcode_class( $shortcode_tag, $attributes ); } /** * Geef de class naam behorende bij de shortcode * * @param string $shortcode_tag Shortcode (zonder kleistad- ). * * @return string */ public static function get_class_name( string $shortcode_tag ) : string { return '\\' . __NAMESPACE__ . '\\Public_' . ucwords( $shortcode_tag, '_' ); } /** * Register rest URI's. * * @since 5.7.0 */ public static function register_rest_routes() { register_rest_route( KLEISTAD_API, '/getitem', // /(?P<id>\d+)', [ 'methods' => 'GET', 'callback' => [ __CLASS__, 'callback_getitem' ], 'permission_callback' => function( WP_REST_Request $request ) { $shortcode = $request->get_param( 'tag' ) ?: ''; $shortcodes = new ShortCodes(); return $shortcodes->check_access( $shortcode ); }, ] ); register_rest_route( KLEISTAD_API, '/getitems', [ 'methods' => 'GET', 'callback' => [ __CLASS__, 'callback_getitem' ], 'permission_callback' => function( WP_REST_Request $request ) { $shortcode = $request->get_param( 'tag' ) ?: ''; $shortcodes = new ShortCodes(); return $shortcodes->check_access( $shortcode ); }, ] ); register_rest_route( KLEISTAD_API, '/download', [ 'methods' => 'GET', 'callback' => [ __CLASS__, 'callback_download' ], 'permission_callback' => function( WP_REST_Request $request ) { $shortcode = $request->get_param( 'tag' ) ?: ''; $shortcodes = new ShortCodes(); return $shortcodes->check_access( $shortcode ); }, ] ); } /** * Get an item and display it. * * @param WP_REST_Request $request De informatie vanuit de client of het weer te geven item. * @return WP_REST_Response De response. * @throws Exception Onbekend object. */ public static function callback_getitem( WP_REST_Request $request ) : WP_REST_Response { $shortcode = self::get_shortcode( $request ); try { if ( ! is_a( $shortcode, __CLASS__ ) ) { throw new Exception( 'callback_formsubmit voor onbekend object' ); } if ( ! is_null( $request->get_param( 'id' ) ) ) { $shortcode->data['id'] = is_numeric( $request->get_param( 'id' ) ) ? absint( $request->get_param( 'id' ) ) : sanitize_text_field( $request->get_param( 'id' ) ); } return new WP_REST_Response( [ 'content' => $shortcode->display() ] ); } catch ( Kleistad_Exception $exceptie ) { return new WP_REST_Response( [ 'status' => $shortcode->status( new WP_Error( $exceptie->getMessage() ) ) ] ); } catch ( Exception $exceptie ) { fout( __CLASS__, $exceptie->GetMessage() ); return new WP_REST_Response( [ 'status' => $shortcode->status( new WP_Error( 'Er is een onbekende fout opgetreden' ) ) ] ); } } /** * Get an item and display it. * * @param WP_REST_Request $request De informatie vanuit de client of het weer te geven item. * @return WP_REST_Response de response. * @throws Exception Onbekend object. */ public static function callback_download( WP_REST_Request $request ) : WP_REST_Response { $shortcode = self::get_shortcode( $request ); try { if ( ! is_a( $shortcode, __CLASS__ ) ) { throw new Exception( 'callback_download voor onbekend object' ); } $functie = $request->get_param( 'actie' ) ?? ''; if ( method_exists( $shortcode, $functie ) ) { return new WP_REST_Response( self::download( $shortcode, $functie ) ); } throw new Exception( 'callback_download voor onbekende method' ); } catch ( Kleistad_Exception $exceptie ) { return new WP_REST_Response( [ 'status' => $shortcode->status( new WP_Error( $exceptie->getMessage() ) ) ] ); } catch ( Exception $exceptie ) { fout( __CLASS__, $exceptie->GetMessage() ); return new WP_REST_Response( [ 'status' => $shortcode->status( new WP_Error( 'Er is een onbekende fout opgetreden' ) ) ] ); } } /** * Ruim eventuele download files op. */ public static function cleanup_downloads() { $upload_dir = wp_upload_dir(); $files = glob( $upload_dir['basedir'] . '/kleistad_tmp_*.csv' ); $now = time(); foreach ( $files as $file ) { if ( is_file( $file ) ) { if ( $now - filemtime( $file ) >= DAY_IN_SECONDS ) { unlink( $file ); } } } } /** * Helper functie, geef het object terug of een foutboodschap. * * @param WP_REST_Request $request De informatie vanuit de client of het weer te geven item. * @return Shortcode | null De response of false. */ protected static function get_shortcode( WP_REST_Request $request ) : ?Shortcode { $tag = $request->get_param( 'tag' ) ?? ''; $class = '\\' . __NAMESPACE__ . '\\Public_' . ucwords( $tag, '_' ); if ( class_exists( $class ) ) { $atts = json_decode( $request->get_param( 'atts' ) ?? '[]', true ); $attributes = is_array( $atts ) ? $atts : [ $atts ]; return new $class( $tag, $attributes, opties() ); } return null; } /** * Maak een tijdelijk bestand aan voor download. * * @param Shortcode $shortcode De shortcode waarvoor de download plaatsvindt. * @param string $functie De shortcode functie die aangeroepen moet worden. * * @return array */ private static function download( Shortcode $shortcode, string $functie ) : array { if ( str_starts_with( $functie, 'url_' ) ) { return [ 'file_uri' => $shortcode->$functie() ]; } $upload_dir = wp_upload_dir(); $file = '/kleistad_tmp_' . uniqid() . '.csv'; $shortcode->filehandle = fopen( $upload_dir['basedir'] . $file, 'w' ); if ( false !== $shortcode->filehandle ) { fwrite( $shortcode->filehandle, "\xEF\xBB\xBF" ); $result = $shortcode->$functie(); fclose( $shortcode->filehandle ); if ( empty( $result ) ) { return [ 'file_uri' => $upload_dir['baseurl'] . $file ]; } unlink( $upload_dir['basedir'] . $file ); return [ 'file_uri' => $result ]; } return [ 'status' => $shortcode->status( new WP_Error( 'intern', 'bestand kon niet aangemaakt worden' ) ), 'content' => $shortcode->goto_home(), ]; } /** * Bepaal de display actie. * prio 1: actie via de url * prio 2: actie al aanwezig in de data (afkomstig callback functie) * prio 3: actie vanuit de actie parameter in de tag * prio 4: de default actie */ private function bepaal_actie() { foreach ( [ filter_input( INPUT_GET, 'actie', FILTER_SANITIZE_STRING ), $this->data['actie'] ?? null, self::STANDAARD_ACTIE ] as $actie ) { if ( ! empty( $actie ) ) { $this->display_actie = $actie; return; } } } }
gpl-3.0
agoode/escape-java
src/org/spacebar/escape/common/Player.java
277
package org.spacebar.escape.common; public class Player extends Entity { public Player(int x, int y, byte d) { super(x, y, d); iAmPlayer(); iCanTeleport(); iPushBots(); iGetHeartFramers(); type = B_PLAYER; } }
gpl-3.0
PinkBweezel/fabiano-swagger-of-doom
HealTest/Program.cs
593
using System; using Common; namespace HealTest { internal class Program { private static readonly GeometricSeries gs = new GeometricSeries(10, 1.0224); private static void Main(string[] args) { for (int i = 0; i < 100; i++) { Console.WriteLine($"Level {i}: {gs.GetTerm(i, true)}"); } Console.ReadLine(); } private static int exp_incr(double initial, double growth, int time) { return (int)Math.Round(initial * (Math.Exp(growth * time))); } } }
gpl-3.0
damiancom/garantia
frontEnd/src/main/java/ar/com/mutual/frontEnd/reportes/view/ReporteSiniestrosView.java
1541
package ar.com.mutual.frontEnd.reportes.view; import javax.annotation.PostConstruct; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import ar.com.mutual.bean.seguridad.Usuario; import ar.com.mutual.frontEnd.customComponent.LayoutPrincipal; import ar.com.mutual.frontEnd.reportes.ReporteSiniestro; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.UIScope; @SpringView(name = ReporteSiniestrosView.VIEW_NAME) @UIScope public class ReporteSiniestrosView extends LayoutPrincipal implements View { /** * */ private static final long serialVersionUID = -2995872555666131750L; public static final String VIEW_NAME = "reporteSiniestrosView"; private static final Logger log = Logger.getLogger(ReporteSiniestrosView.class); //Variables de la pantalla String titulo = "Reporte Siniestros"; @Autowired private ReporteSiniestro reporteSiniestros; @PostConstruct public void init() { super.init(); setTitulo(this.titulo); setBody(reporteSiniestros.getLayout()); } @Override public void enter(ViewChangeEvent event) { if (event.getNavigator().getUI().getSession().getAttribute("usuario") != null) { setUsuario((Usuario) event.getNavigator().getUI().getSession().getAttribute("usuario")); setMenu(); } else { regresoLogin(event.getNavigator().getUI()); } } }
gpl-3.0
giessweinapps/TfsDashboard
TfsDashboard.Library/TfsDashboardSummary.cs
572
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TfsDashboard.Library { public class TfsDashboardSummary { public IEnumerable<TfsBuildSummary> LastBuilds { get; set; } public dynamic LastCheckins { get; set; } public TfsBuildSummary LastBuild { get; set; } public int CheckinsToday { get; set; } public IEnumerable<TfsCheckinStatistic> CheckinStatistic { get; set; } public int? LastWarningCount { get; set; } public string Name { get; set; } } }
gpl-3.0
kuros/random-jpa
src/main/java/com/github/kuros/random/jpa/log/LogFactory.java
2530
package com.github.kuros.random.jpa.log; import com.github.kuros.random.jpa.exception.RandomJPAException; import java.lang.reflect.Constructor; /* * Copyright (c) 2015 Kumar Rohit * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License or 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Logging functionality provided by OpenPojo (http://openpojo.com) */ public class LogFactory { private static final String[] PROVIDED_LOGGERS = { "com.github.kuros.random.jpa.log.providers.Slf4JProvider", "com.github.kuros.random.jpa.log.providers.Log4JProvider", "com.github.kuros.random.jpa.log.providers.DefaultProvider"}; private static Class<?> activeLogger; public static Logger getLogger(final Class<?> clazz) { try { return instantiateLogger(activeLogger, clazz); } catch (Exception e) { e.printStackTrace(); } throw new RandomJPAException("Unable to instantiate Logger"); } static { activeLogger = getLoggerClass(); } private static Class<?> getLoggerClass() { for (String providedLogger : PROVIDED_LOGGERS) { try { final Class<?> aClass = Class.forName(providedLogger); instantiateLogger(aClass, LogFactory.class); return aClass; } catch (final Exception e) { //Do nothing } } throw new RandomJPAException("Unable to find suitable Logger"); } private static Logger instantiateLogger(final Class<?> loggerClass, final Class<?> clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { final Constructor<?> declaredConstructor = loggerClass.getDeclaredConstructor(Class.class); declaredConstructor.setAccessible(true); return (Logger) declaredConstructor.newInstance(clazz); } }
gpl-3.0
jindrapetrik/jpexs-decompiler
src/com/jpexs/decompiler/flash/gui/generictageditors/NumberEditor.java
7389
/* * Copyright (C) 2010-2021 JPEXS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jpexs.decompiler.flash.gui.generictageditors; import com.jpexs.decompiler.flash.types.BasicType; import com.jpexs.decompiler.flash.types.annotations.SWFType; import com.jpexs.helpers.ReflectionTools; import java.awt.Component; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.lang.reflect.Field; import java.text.DecimalFormat; import java.text.ParseException; import javax.swing.JFormattedTextField; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; import javax.swing.text.DefaultFormatter; /** * * @author JPEXS */ public class NumberEditor extends JSpinner implements GenericTagEditor { private final Object obj; private final Field field; private final int index; private final Class<?> type; private final SWFType swfType; private String fieldName; @Override public BaselineResizeBehavior getBaselineResizeBehavior() { return Component.BaselineResizeBehavior.CONSTANT_ASCENT; } @Override public int getBaseline(int width, int height) { return 0; } @Override public void added() { } public NumberEditor(String fieldName, Object obj, Field field, int index, Class<?> type, SWFType swfType) { setSize(100, getSize().height); setMaximumSize(getSize()); this.obj = obj; this.field = field; this.index = index; this.type = type; this.swfType = swfType; this.fieldName = fieldName; reset(); ((JSpinner.NumberEditor) getEditor()).getFormat().setGroupingUsed(false); JFormattedTextField jtf = ((JSpinner.NumberEditor) getEditor()).getTextField(); DefaultFormatter formatter = (DefaultFormatter) jtf.getFormatter(); formatter.setCommitsOnValidEdit(true); } @Override public void reset() { try { Object value = ReflectionTools.getValue(obj, field, index); setModel(getModel(swfType, value)); } catch (IllegalArgumentException | IllegalAccessException ex) { // ignore } } @Override public void save() { try { Object value = getChangedValue(); if (value != null) { ReflectionTools.setValue(obj, field, index, value); } } catch (IllegalArgumentException | IllegalAccessException ex) { // ignore } } private SpinnerModel getModel(SWFType swfType, Object value) { SpinnerNumberModel m = null; BasicType basicType = swfType == null ? BasicType.NONE : swfType.value(); switch (basicType) { case UI8: m = new SpinnerNumberModel(toInt(value), 0, 0xff, 1); break; case UI16: m = new SpinnerNumberModel(toInt(value), 0, 0xffff, 1); break; case UB: { long max = 1; if (swfType.count() > 0) { max <<= swfType.count(); } else { max <<= 31; } m = new SpinnerNumberModel((Number) toLong(value), 0L, (long) max - 1, 1L); } break; case UI32: case EncodedU32: case NONE: m = new SpinnerNumberModel((Number) toLong(value), 0L, 0xffffffffL, 1L); break; case SI8: m = new SpinnerNumberModel(toInt(value), -0x80, 0x7f, 1); break; case SI16: case FLOAT16: m = new SpinnerNumberModel(toInt(value), -0x8000, 0x7fff, 1); break; case FB: case SB: { long max = 1; if (swfType.count() > 0) { max <<= (swfType.count() - 1); } else { max <<= 30; } m = new SpinnerNumberModel((Number) toLong(value), (long) (-max), (long) max - 1, 1L); } break; case SI32: m = new SpinnerNumberModel(toDouble(value), -0x80000000, 0x7fffffff, 1); break; case FLOAT: case FIXED: case FIXED8: m = new SpinnerNumberModel(toDouble(value), -0x80000000, 0x7fffffff, 0.01); break; } return m; } private double toDouble(Object value) { if (value instanceof Float) { return (double) (Float) value; } if (value instanceof Double) { return (double) (Double) value; } return 0; } private int toInt(Object value) { if (value instanceof Short) { return (int) (Short) value; } if (value instanceof Integer) { return (int) (Integer) value; } return 0; } private long toLong(Object value) { if (value instanceof Short) { return (long) (Short) value; } if (value instanceof Integer) { return (long) (Integer) value; } if (value instanceof Long) { return (long) (Long) value; } return 0; } @Override public void addChangeListener(final ChangeListener l) { final GenericTagEditor t = this; addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { l.change(t); } }); } @Override public void validateValue() { } @Override public Object getChangedValue() { Object value = null; if (type.equals(int.class) || type.equals(Integer.class)) { value = Integer.parseInt(getValue().toString()); } else if (type.equals(short.class) || type.equals(Short.class)) { value = Short.parseShort(getValue().toString()); } else if (type.equals(long.class) || type.equals(Long.class)) { value = Long.parseLong(getValue().toString()); } else if (type.equals(double.class) || type.equals(Double.class)) { value = Double.parseDouble(getValue().toString()); } else if (type.equals(float.class) || type.equals(Float.class)) { value = Float.parseFloat(getValue().toString()); } return value; } @Override public String getFieldName() { return fieldName; } @Override public Field getField() { return field; } @Override public String getReadOnlyValue() { return getChangedValue().toString(); } }
gpl-3.0
s20121035/rk3288_android5.1_repo
packages/apps/ContactsCommon/src/com/android/contacts/common/model/RawContact.java
12159
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.common.model; import android.content.ContentValues; import android.content.Context; import android.content.Entity; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import com.android.contacts.common.model.AccountTypeManager; import com.android.contacts.common.model.account.AccountType; import com.android.contacts.common.model.account.AccountWithDataSet; import com.android.contacts.common.model.dataitem.DataItem; import com.google.common.base.Objects; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; /** * RawContact represents a single raw contact in the raw contacts database. * It has specialized getters/setters for raw contact * items, and also contains a collection of DataItem objects. A RawContact contains the information * from a single account. * * This allows RawContact objects to be thought of as a class with raw contact * fields (like account type, name, data set, sync state, etc.) and a list of * DataItem objects that represent contact information elements (like phone * numbers, email, address, etc.). */ final public class RawContact implements Parcelable { private AccountTypeManager mAccountTypeManager; private final ContentValues mValues; private final ArrayList<NamedDataItem> mDataItems; final public static class NamedDataItem implements Parcelable { public final Uri mUri; // This use to be a DataItem. DataItem creation is now delayed until the point of request // since there is no benefit to storing them here due to the multiple inheritance. // Eventually instanceof still has to be used anyways to determine which sub-class of // DataItem it is. And having parent DataItem's here makes it very difficult to serialize or // parcelable. // // Instead of having a common DataItem super class, we should refactor this to be a generic // Object where the object is a concrete class that no longer relies on ContentValues. // (this will also make the classes easier to use). // Since instanceof is used later anyways, having a list of Objects won't hurt and is no // worse than having a DataItem. public final ContentValues mContentValues; public NamedDataItem(Uri uri, ContentValues values) { this.mUri = uri; this.mContentValues = values; } public NamedDataItem(Parcel parcel) { this.mUri = parcel.readParcelable(Uri.class.getClassLoader()); this.mContentValues = parcel.readParcelable(ContentValues.class.getClassLoader()); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(mUri, i); parcel.writeParcelable(mContentValues, i); } public static final Parcelable.Creator<NamedDataItem> CREATOR = new Parcelable.Creator<NamedDataItem>() { @Override public NamedDataItem createFromParcel(Parcel parcel) { return new NamedDataItem(parcel); } @Override public NamedDataItem[] newArray(int i) { return new NamedDataItem[i]; } }; @Override public int hashCode() { return Objects.hashCode(mUri, mContentValues); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final NamedDataItem other = (NamedDataItem) obj; return Objects.equal(mUri, other.mUri) && Objects.equal(mContentValues, other.mContentValues); } } public static RawContact createFrom(Entity entity) { final ContentValues values = entity.getEntityValues(); final ArrayList<Entity.NamedContentValues> subValues = entity.getSubValues(); RawContact rawContact = new RawContact(values); for (Entity.NamedContentValues subValue : subValues) { rawContact.addNamedDataItemValues(subValue.uri, subValue.values); } return rawContact; } /** * A RawContact object can be created with or without a context. */ public RawContact() { this(new ContentValues()); } public RawContact(ContentValues values) { mValues = values; mDataItems = new ArrayList<NamedDataItem>(); } /** * Constructor for the parcelable. * * @param parcel The parcel to de-serialize from. */ private RawContact(Parcel parcel) { mValues = parcel.readParcelable(ContentValues.class.getClassLoader()); mDataItems = Lists.newArrayList(); parcel.readTypedList(mDataItems, NamedDataItem.CREATOR); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(mValues, i); parcel.writeTypedList(mDataItems); } /** * Create for building the parcelable. */ public static final Parcelable.Creator<RawContact> CREATOR = new Parcelable.Creator<RawContact>() { @Override public RawContact createFromParcel(Parcel parcel) { return new RawContact(parcel); } @Override public RawContact[] newArray(int i) { return new RawContact[i]; } }; public AccountTypeManager getAccountTypeManager(Context context) { if (mAccountTypeManager == null) { mAccountTypeManager = AccountTypeManager.getInstance(context); } return mAccountTypeManager; } public ContentValues getValues() { return mValues; } /** * Returns the id of the raw contact. */ public Long getId() { return getValues().getAsLong(RawContacts._ID); } /** * Returns the account name of the raw contact. */ public String getAccountName() { return getValues().getAsString(RawContacts.ACCOUNT_NAME); } /** * Returns the account type of the raw contact. */ public String getAccountTypeString() { return getValues().getAsString(RawContacts.ACCOUNT_TYPE); } /** * Returns the data set of the raw contact. */ public String getDataSet() { return getValues().getAsString(RawContacts.DATA_SET); } public boolean isDirty() { return getValues().getAsBoolean(RawContacts.DIRTY); } public String getSourceId() { return getValues().getAsString(RawContacts.SOURCE_ID); } public String getSync1() { return getValues().getAsString(RawContacts.SYNC1); } public String getSync2() { return getValues().getAsString(RawContacts.SYNC2); } public String getSync3() { return getValues().getAsString(RawContacts.SYNC3); } public String getSync4() { return getValues().getAsString(RawContacts.SYNC4); } public boolean isDeleted() { return getValues().getAsBoolean(RawContacts.DELETED); } public long getContactId() { return getValues().getAsLong(Contacts.Entity.CONTACT_ID); } public boolean isStarred() { return getValues().getAsBoolean(Contacts.STARRED); } public AccountType getAccountType(Context context) { return getAccountTypeManager(context).getAccountType(getAccountTypeString(), getDataSet()); } /** * Sets the account name, account type, and data set strings. * Valid combinations for account-name, account-type, data-set * 1) null, null, null (local account) * 2) non-null, non-null, null (valid account without data-set) * 3) non-null, non-null, non-null (valid account with data-set) */ private void setAccount(String accountName, String accountType, String dataSet) { final ContentValues values = getValues(); if (accountName == null) { if (accountType == null && dataSet == null) { // This is a local account values.putNull(RawContacts.ACCOUNT_NAME); values.putNull(RawContacts.ACCOUNT_TYPE); values.putNull(RawContacts.DATA_SET); return; } } else { if (accountType != null) { // This is a valid account, either with or without a dataSet. values.put(RawContacts.ACCOUNT_NAME, accountName); values.put(RawContacts.ACCOUNT_TYPE, accountType); if (dataSet == null) { values.putNull(RawContacts.DATA_SET); } else { values.put(RawContacts.DATA_SET, dataSet); } return; } } throw new IllegalArgumentException( "Not a valid combination of account name, type, and data set."); } public void setAccount(AccountWithDataSet accountWithDataSet) { setAccount(accountWithDataSet.name, accountWithDataSet.type, accountWithDataSet.dataSet); } public void setAccountToLocal() { setAccount(null, null, null); } /** * Creates and inserts a DataItem object that wraps the content values, and returns it. */ public void addDataItemValues(ContentValues values) { addNamedDataItemValues(Data.CONTENT_URI, values); } public NamedDataItem addNamedDataItemValues(Uri uri, ContentValues values) { final NamedDataItem namedItem = new NamedDataItem(uri, values); mDataItems.add(namedItem); return namedItem; } public ArrayList<ContentValues> getContentValues() { final ArrayList<ContentValues> list = Lists.newArrayListWithCapacity(mDataItems.size()); for (NamedDataItem dataItem : mDataItems) { if (Data.CONTENT_URI.equals(dataItem.mUri)) { list.add(dataItem.mContentValues); } } return list; } public List<DataItem> getDataItems() { final ArrayList<DataItem> list = Lists.newArrayListWithCapacity(mDataItems.size()); for (NamedDataItem dataItem : mDataItems) { if (Data.CONTENT_URI.equals(dataItem.mUri)) { list.add(DataItem.createFrom(dataItem.mContentValues)); } } return list; } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("RawContact: ").append(mValues); for (RawContact.NamedDataItem namedDataItem : mDataItems) { sb.append("\n ").append(namedDataItem.mUri); sb.append("\n -> ").append(namedDataItem.mContentValues); } return sb.toString(); } @Override public int hashCode() { return Objects.hashCode(mValues, mDataItems); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; RawContact other = (RawContact) obj; return Objects.equal(mValues, other.mValues) && Objects.equal(mDataItems, other.mDataItems); } }
gpl-3.0
miccio-dk/BobsShop
BobsShop/src/controller/Device.java
1021
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controller; /** * <pre> * * The Device class * encapsulates all functionality * related to the Device attributes. * </pre> * * @version 1.0 * @author Miccio, reviewed and documented by Yin. * @see controller * @todo add to report */ public class Device { private String portNumber; private String id; /** * * @param portNumber * @param id */ public Device(String portNumber, String id) { this.portNumber = portNumber; this.id = id; } /** * @return the portNumber */ public String getPortNumber() { return portNumber; } /** * @return the source */ public String getId() { return id; } /** * @param portNumber the portNumber to set */ public void setPortNumber(String portNumber) { this.portNumber = portNumber; } /** * @param source the source to set */ public void setSource(String source) { this.id = source; } }
gpl-3.0
TGAC/statsdb
python/parse_tag_count.py
855
import QCAnalysis import TagCount, DB, RunTable import os.sys sys.path.append('/usr/users/ga002/shrestha/Dropbox/') parser=optparse.OptionParser() parser.add_option("-i", "--input", action="store", type="string", dest="input") parser.add_option("--db_config", action="store", type="string", dest="db_config") (options, args) = parser.parse_args() #gets the arguments and options print "Input: " + options['input'] + "\n" print "DB configuration: " + options['db_config'] + "\n" input=options['input'] line=""; module=""; status=""; config=options['db_config'] db=QCAnalysis.DB() analysis=QCAnalysis.RunTable.parse_file(input) db.connect() for each in analysis: print "Analysis: " + each fast_qc_file = each.get_property("path_to_counts") QCAnalysis.TagCount.parse_file(fast_qc_file, each) db.insert_analysis(each) db.disconnect()
gpl-3.0
vedderb/rise_sdvp
Linux/Car_Client/utility.cpp
14732
/* Copyright 2016 - 2018 Benjamin Vedder benjamin@vedder.se This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "utility.h" #include <cmath> #include <QDateTime> #include <QEventLoop> #include <QTimer> namespace { inline double roundDouble(double x) { return x < 0.0 ? ceil(x - 0.5) : floor(x + 0.5); } const unsigned short crc16_tab[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; } namespace utility { #define FE_WGS84 (1.0/298.257223563) // earth flattening (WGS84) #define RE_WGS84 6378137.0 // earth semimajor axis (WGS84) (m) void buffer_append_int64(uint8_t *buffer, int64_t number, int32_t *index) { buffer[(*index)++] = number >> 56; buffer[(*index)++] = number >> 48; buffer[(*index)++] = number >> 40; buffer[(*index)++] = number >> 32; buffer[(*index)++] = number >> 24; buffer[(*index)++] = number >> 16; buffer[(*index)++] = number >> 8; buffer[(*index)++] = number; } void buffer_append_uint64(uint8_t *buffer, uint64_t number, int32_t *index) { buffer[(*index)++] = number >> 56; buffer[(*index)++] = number >> 48; buffer[(*index)++] = number >> 40; buffer[(*index)++] = number >> 32; buffer[(*index)++] = number >> 24; buffer[(*index)++] = number >> 16; buffer[(*index)++] = number >> 8; buffer[(*index)++] = number; } void buffer_append_int32(uint8_t* buffer, int32_t number, int32_t *index) { buffer[(*index)++] = number >> 24; buffer[(*index)++] = number >> 16; buffer[(*index)++] = number >> 8; buffer[(*index)++] = number; } void buffer_append_uint32(uint8_t* buffer, uint32_t number, int32_t *index) { buffer[(*index)++] = number >> 24; buffer[(*index)++] = number >> 16; buffer[(*index)++] = number >> 8; buffer[(*index)++] = number; } void buffer_append_int16(uint8_t* buffer, int16_t number, int32_t *index) { buffer[(*index)++] = number >> 8; buffer[(*index)++] = number; } void buffer_append_uint16(uint8_t* buffer, uint16_t number, int32_t *index) { buffer[(*index)++] = number >> 8; buffer[(*index)++] = number; } void buffer_append_double16(uint8_t* buffer, double number, double scale, int32_t *index) { buffer_append_int16(buffer, (int16_t)(roundDouble(number * scale)), index); } void buffer_append_double32(uint8_t* buffer, double number, double scale, int32_t *index) { buffer_append_int32(buffer, (int32_t)(roundDouble(number * scale)), index); } void buffer_append_double64(uint8_t* buffer, double number, double scale, int32_t *index) { buffer_append_int64(buffer, (int64_t)(roundDouble(number * scale)), index); } void buffer_append_double32_auto(uint8_t *buffer, double number, int32_t *index) { int e = 0; float sig = frexpf(number, &e); float sig_abs = fabsf(sig); uint32_t sig_i = 0; if (sig_abs >= 0.5) { sig_i = (uint32_t)((sig_abs - 0.5f) * 2.0f * 8388608.0f); e += 126; } uint32_t res = ((e & 0xFF) << 23) | (sig_i & 0x7FFFFF); if (sig < 0) { res |= 1 << 31; } buffer_append_uint32(buffer, res, index); } int16_t buffer_get_int16(const uint8_t *buffer, int32_t *index) { int16_t res = ((uint16_t) buffer[*index]) << 8 | ((uint16_t) buffer[*index + 1]); *index += 2; return res; } uint16_t buffer_get_uint16(const uint8_t *buffer, int32_t *index) { uint16_t res = ((uint16_t) buffer[*index]) << 8 | ((uint16_t) buffer[*index + 1]); *index += 2; return res; } int32_t buffer_get_int32(const uint8_t *buffer, int32_t *index) { int32_t res = ((uint32_t) buffer[*index]) << 24 | ((uint32_t) buffer[*index + 1]) << 16 | ((uint32_t) buffer[*index + 2]) << 8 | ((uint32_t) buffer[*index + 3]); *index += 4; return res; } uint32_t buffer_get_uint32(const uint8_t *buffer, int32_t *index) { uint32_t res = ((uint32_t) buffer[*index]) << 24 | ((uint32_t) buffer[*index + 1]) << 16 | ((uint32_t) buffer[*index + 2]) << 8 | ((uint32_t) buffer[*index + 3]); *index += 4; return res; } int64_t buffer_get_int64(const uint8_t *buffer, int32_t *index) { int64_t res = ((uint64_t) buffer[*index]) << 56 | ((uint64_t) buffer[*index + 1]) << 48 | ((uint64_t) buffer[*index + 2]) << 40 | ((uint64_t) buffer[*index + 3]) << 32 | ((uint64_t) buffer[*index + 4]) << 24 | ((uint64_t) buffer[*index + 5]) << 16 | ((uint64_t) buffer[*index + 6]) << 8 | ((uint64_t) buffer[*index + 7]); *index += 8; return res; } uint64_t buffer_get_uint64(const uint8_t *buffer, int32_t *index) { uint64_t res = ((uint64_t) buffer[*index]) << 56 | ((uint64_t) buffer[*index + 1]) << 48 | ((uint64_t) buffer[*index + 2]) << 40 | ((uint64_t) buffer[*index + 3]) << 32 | ((uint64_t) buffer[*index + 4]) << 24 | ((uint64_t) buffer[*index + 5]) << 16 | ((uint64_t) buffer[*index + 6]) << 8 | ((uint64_t) buffer[*index + 7]); *index += 8; return res; } double buffer_get_double16(const uint8_t *buffer, double scale, int32_t *index) { return (double)buffer_get_int16(buffer, index) / scale; } double buffer_get_double32(const uint8_t *buffer, double scale, int32_t *index) { return (double)buffer_get_int32(buffer, index) / scale; } double buffer_get_double64(const uint8_t *buffer, double scale, int32_t *index) { return (double)buffer_get_int64(buffer, index) / scale; } double map(double x, double in_min, double in_max, double out_min, double out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } void llhToXyz(double lat, double lon, double height, double *x, double *y, double *z) { double sinp = sin(lat * M_PI / 180.0); double cosp = cos(lat * M_PI / 180.0); double sinl = sin(lon * M_PI / 180.0); double cosl = cos(lon * M_PI / 180.0); double e2 = FE_WGS84 * (2.0 - FE_WGS84); double v = RE_WGS84 / sqrt(1.0 - e2 * sinp * sinp); *x = (v + height) * cosp * cosl; *y = (v + height) * cosp * sinl; *z = (v * (1.0 - e2) + height) * sinp; } void xyzToLlh(double x, double y, double z, double *lat, double *lon, double *height) { double e2 = FE_WGS84 * (2.0 - FE_WGS84); double r2 = x * x + y * y; double za = z; double zk = 0.0; double sinp = 0.0; double v = RE_WGS84; while (fabs(za - zk) >= 1E-4) { zk = za; sinp = za / sqrt(r2 + za * za); v = RE_WGS84 / sqrt(1.0 - e2 * sinp * sinp); za = z + v * e2 * sinp; } *lat = (r2 > 1E-12 ? atan(za / sqrt(r2)) : (z > 0.0 ? M_PI / 2.0 : -M_PI / 2.0)) * 180.0 / M_PI; *lon = (r2 > 1E-12 ? atan2(y, x) : 0.0) * 180.0 / M_PI; *height = sqrt(r2 + za * za) - v; } void createEnuMatrix(double lat, double lon, double *enuMat) { double so = sin(lon * M_PI / 180.0); double co = cos(lon * M_PI / 180.0); double sa = sin(lat * M_PI / 180.0); double ca = cos(lat * M_PI / 180.0); // ENU enuMat[0] = -so; enuMat[1] = co; enuMat[2] = 0.0; enuMat[3] = -sa * co; enuMat[4] = -sa * so; enuMat[5] = ca; enuMat[6] = ca * co; enuMat[7] = ca * so; enuMat[8] = sa; // NED // enuMat[0] = -sa * co; // enuMat[1] = -sa * so; // enuMat[2] = ca; // enuMat[3] = -so; // enuMat[4] = co; // enuMat[5] = 0.0; // enuMat[6] = -ca * co; // enuMat[7] = -ca * so; // enuMat[8] = -sa; } void llhToEnu(const double *iLlh, const double *llh, double *xyz) { double ix, iy, iz; llhToXyz(iLlh[0], iLlh[1], iLlh[2], &ix, &iy, &iz); double x, y, z; llhToXyz(llh[0], llh[1], llh[2], &x, &y, &z); double enuMat[9]; createEnuMatrix(iLlh[0], iLlh[1], enuMat); double dx = x - ix; double dy = y - iy; double dz = z - iz; xyz[0] = enuMat[0] * dx + enuMat[1] * dy + enuMat[2] * dz; xyz[1] = enuMat[3] * dx + enuMat[4] * dy + enuMat[5] * dz; xyz[2] = enuMat[6] * dx + enuMat[7] * dy + enuMat[8] * dz; } void enuToLlh(const double *iLlh, const double *xyz, double *llh) { double ix, iy, iz; llhToXyz(iLlh[0], iLlh[1], iLlh[2], &ix, &iy, &iz); double enuMat[9]; createEnuMatrix(iLlh[0], iLlh[1], enuMat); double x = enuMat[0] * xyz[0] + enuMat[3] * xyz[1] + enuMat[6] * xyz[2] + ix; double y = enuMat[1] * xyz[0] + enuMat[4] * xyz[1] + enuMat[7] * xyz[2] + iy; double z = enuMat[2] * xyz[0] + enuMat[5] * xyz[1] + enuMat[8] * xyz[2] + iz; xyzToLlh(x, y, z, &llh[0], &llh[1], &llh[2]); } double logn(double base, double number) { return log(number) / log(base); } double buffer_get_double32_auto(const uint8_t *buffer, int32_t *index) { uint32_t res = buffer_get_uint32(buffer, index); int e = (res >> 23) & 0xFF; uint32_t sig_i = res & 0x7FFFFF; bool neg = res & (1 << 31); float sig = 0.0; if (e != 0 || sig_i != 0) { sig = (float)sig_i / (8388608.0 * 2.0) + 0.5; e -= 126; } if (neg) { sig = -sig; } return ldexpf(sig, e); } unsigned short crc16(const unsigned char *buf, unsigned int len) { unsigned int i; unsigned short cksum = 0; for (i = 0; i < len; i++) { cksum = crc16_tab[(((cksum >> 8) ^ *buf++) & 0xFF)] ^ (cksum << 8); } return cksum; } int getTimeUtcToday() { QDateTime date = QDateTime::currentDateTime(); QTime current = QTime::currentTime().addSecs(-date.offsetFromUtc()); return current.msecsSinceStartOfDay(); } void stepTowards(double *value, double goal, double step) { if (*value < goal) { if ((*value + step) < goal) { *value += step; } else { *value = goal; } } else if (*value > goal) { if ((*value - step) > goal) { *value -= step; } else { *value = goal; } } } double sign(double x) { return x >= 0 ? 1.0 : -1.0; } int truncateNumber(double *number, double min, double max) { int did_trunc = 0; if (*number > max) { *number = max; did_trunc = 1; } else if (*number < min) { *number = min; did_trunc = 1; } return did_trunc; } void normAngle(double *angle) { while (*angle < -180.0) { *angle += 360.0; } while (*angle > 180.0) { *angle -= 360.0; } } bool waitSignal(QObject *sender, const char *signal, int timeoutMs) { QEventLoop loop; QTimer timeoutTimer; timeoutTimer.setSingleShot(true); timeoutTimer.start(timeoutMs); auto conn1 = QObject::connect(sender, signal, &loop, SLOT(quit())); auto conn2 = QObject::connect(&timeoutTimer, SIGNAL(timeout()), &loop, SLOT(quit())); loop.exec(); QObject::disconnect(conn1); QObject::disconnect(conn2); return timeoutTimer.isActive(); } }
gpl-3.0
tanvirfahim15/Javaball---OOP-project---2nd-year
BasicGame/src/home/searchstartThread.java
715
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package home; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Tanvir */ public class searchstartThread extends Thread { public void run(){ home.Main.frame.setVisible(false); String []args=null; try { search.Search.main(args); } catch (FileNotFoundException ex) { Logger.getLogger(searchstartThread.class.getName()).log(Level.SEVERE, null, ex); } } }
gpl-3.0
mosra/kompas-plugins
src/WorldMap1630RasterModel/WorldMap1630RasterModel.cpp
1502
/* Copyright © 2007, 2008, 2009, 2010, 2011 Vladimír Vondruš <mosra@centrum.cz> This file is part of Kompas. Kompas is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, as published by the Free Software Foundation. Kompas is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License version 3 for more details. */ #include "WorldMap1630RasterModel.h" #include "constants.h" using namespace std; PLUGIN_REGISTER(Kompas::Plugins::WorldMap1630RasterModel, "cz.mosra.Kompas.Core.AbstractRasterModel/0.2") namespace Kompas { namespace Plugins { WorldMap1630RasterModel::WorldMap1630RasterModel(PluginManager::AbstractPluginManager* manager, const string& plugin): KompasRasterModel(manager, plugin), areaOnline(0, 0, 1, 1) { /* width: 1600 height: 1124 left: 38 top: 195, 199 => 197 right: 1566 bottom: 966, 970 => 968 gap: 0 */ _projection.setCentralMeridian(-20); _projection.setShift(Coords<double>(38/1600.0, 197/1124.0)); _projection.setStretch(Coords<double>((1566-38)/1600.0, (968-197)/1124.0)); /* All zoom levels and layers for online map */ zoomLevelsOnline.insert(0); layersOnline.push_back("base"); } }}
gpl-3.0
sfrancis1970/EpochX
common/src/main/java/org/epochx/epox/lang/Seq3.java
1743
/* * Copyright 2007-2013 * Licensed under GNU Lesser General Public License * * This file is part of EpochX: genetic programming software for research * * EpochX is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * EpochX is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with EpochX. If not, see <http://www.gnu.org/licenses/>. * * The latest version is available from: http://www.epochx.org */ package org.epochx.epox.lang; import org.epochx.epox.Node; /** * A node which chains three nodes together in sequence, called <code>SEQ3</code> * * @since 2.0 */ public class Seq3 extends SeqN { public static final String IDENTIFIER = "SEQ3"; /** * Constructs a Seq3Function with three <code>null</code> children. */ public Seq3() { this(null, null, null); } /** * Constructs a <code>Seq3Function</code> with three child nodes * * @param child1 the first child node * @param child2 the second child node * @param child3 the third child node */ public Seq3(Node child1, Node child2, Node child3) { super(child1, child2, child3); } /** * Returns the identifier of this function which is <code>SEQ3</code> * * @return this node's identifier */ @Override public String getIdentifier() { return IDENTIFIER; } }
gpl-3.0
smlx/archivr
archivr.rb
18384
#!/usr/bin/env ruby # encoding: utf-8 # This file is part of: # Archivr - a file archive manipulation utility. # Copyright 2012 Scott Leggett. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. require 'Qt4' require 'libarchive_rs' require 'fileutils' module Archivr AppTitle = 'Archivr' Version = '0.0.1' About = { :text => "#{AppTitle} - a file archive manipulation utility.", :informative_text => "#{AppTitle} is built using libarchive, Ruby and Qt " + "and disributed under the terms of the GNU GPLv3.\n\n" + "Copyright 2012 Scott Leggett." } Fields = { :methods => [:name, :size, :type, :mtime, :atime, :mode, :uname, :uid, :gname, :gid, :pathname], :labels => ["Name", "Size", "Type", "Modified", "Accessed", "Permissions", "User", "UID", "Group", "GID", "Path"] } # an abstraction class encapsulating Archive::Entry class Entry def initialize entry @entry = entry end def path @entry.pathname end def name @name ||= File::basename(@entry.pathname) + (@entry.directory? ? '/' : '') end def size if @entry.file? case when @entry.size > YiB "#{@entry.size/YiB} YiB" when @entry.size > ZiB "#{@entry.size/ZiB} ZiB" when @entry.size > EiB "#{@entry.size/EiB} EiB" when @entry.size > PiB "#{@entry.size/PiB} PiB" when @entry.size > TiB "#{@entry.size/TiB} TiB" when @entry.size > GiB "#{@entry.size/GiB} GiB" when @entry.size > MiB "#{@entry.size/MiB} MiB" when @entry.size > KiB "#{@entry.size/KiB} KiB" else "#{@entry.size} B" end end end def type case when @entry.directory? "Directory" when @entry.fifo? "FIFO" when @entry.file? "File" when @entry.hardlink? "Hard Link" when @entry.block_special? "Block Special" when @entry.character_special? "Character Special" when @entry.socket? "Socket" when @entry.symbolic_link? "Symbolic Link" end end def mtime Time::at(@entry.mtime).to_s end def atime Time::at(@entry.atime).to_s end def mode @entry.mode.to_s(8)[-4,4] end def uid @entry.uid.to_s end def gid @entry.gid.to_s end private # any methods not explicitly defined in this class are passed to the # underlying Archive::Entry def method_missing method, *args, &block @entry.send method, *args, &block end KiB,MiB,GiB,TiB,PiB,EiB,ZiB,YiB = (1..8).map{|e| 1024**e} end class TreeEntry attr_reader :path, :entry attr_accessor :children, :parent def initialize parent=nil, path='.', entry=nil @parent,@path,@entry = parent,path,entry @children = {} end def add_child path_section, entry child = TreeEntry.new(self, File.join(@path,path_section), entry) @children[child.path] = child end def has_child_dir dir return @children[File.join(@path,dir)] end def is_directory @entry.nil? || @entry.directory? end end class MainWindow < Qt::MainWindow def initialize super # utilities @icon_provider = Qt::FileIconProvider.new @settings = Qt::Settings.new(AppTitle) # construct window set_window_title AppTitle build_main_menu set_central_widget @tree_widget = MainWidget.new(self) # get previously saved settings read_settings # set the application to initial state reset_app show end protected # re-implemented, must use camelCase def closeEvent event write_settings event.accept end private Menus = { "&File" => [ ["&Open", :open_file, Qt::KeySequence::Open], ["&Extract all...", [:extract, :all]], ["&Quit", :close, Qt::KeySequence::Quit] ], "&Help" => [ ["&About", :show_about_box, Qt::KeySequence::HelpContents] ]} OverwriteButtons = Qt::MessageBox::Yes | Qt::MessageBox::YesToAll | Qt::MessageBox::No | Qt::MessageBox::Abort def read_settings @settings.begin_group 'Columns' columns = Hash[ @tree_widget.header_labels.keys.map do |label| [label,@settings.value(label,Qt::Variant.from_value(true)).value == 'true'] end ] @settings.end_group @tree_widget.set_visible_columns columns end def write_settings @settings.begin_group 'Columns' @tree_widget.header_labels.each do |label,visible| @settings.set_value(label,Qt::Variant.from_value(visible)) end @settings.end_group end def build_main_menu @main_actions = {} Menus.each do |title,items| menu = menu_bar.addMenu title @main_actions[title] = items.map do |string, method, shortcut| Qt::Action.new(string, self) do set_shortcuts(shortcut) connect(SIGNAL :triggered){parent.send(*method)} end end.each{|a| menu.add_action a} end end def show_about_box Qt::MessageBox.new(self) do set_window_title "About #{AppTitle}" set_text About[:text] set_informative_text About[:informative_text] set_icon_pixmap window_icon.pixmap(128,128) show end end # this function resets the application back to the state it starts in def reset_app @current_file = nil; @entries = []; @root = TreeEntry.new refresh_display end def enable_menu_items bool @main_actions['&File'][1].set_enabled bool end def open_file if file = Qt::FileDialog::get_open_file_name reset_app @current_file = file load_file end end def load_file begin entries = [] Archive.read_open_filename(@current_file) do |archive| while entry = archive.next_header entries << Entry.new(entry) end end entries.each{|e| add_path_to_tree e.path, e} refresh_display rescue Archive::Error => e report_archive_error e reset_app end end def add_path_to_tree path, entry path_array = [] parent_dir = path until parent_dir == '.' parent_dir,base_name = File.split parent_dir path_array.unshift base_name end # search down into the existing tree, adding nodes as we go if missing current_node = @root path_array.each_with_index do |dir,i| unless child = current_node.has_child_dir(dir) child = current_node.add_child dir,(i == path_array.size-1 ? entry : nil) end current_node = child end end def build_item_tree node, parent_item items = [] node.children.values.each do |child| item = Qt::TreeWidgetItem.new(parent_item) do Fields[:methods].each_with_index do |f,i| set_text(i, if child.entry.nil? case f when :pathname child.path[2..-1] when :name File::basename child.path end else child.entry.send(f) end ) end end if child.is_directory item.set_icon(0, @icon_provider.icon(Qt::FileIconProvider::Folder)) else item.set_icon(0, @icon_provider.icon(Qt::FileIconProvider::File)) end items << item items << build_item_tree(child, item) @items_paths[item] = child.path end items end def refresh_display if @current_file.nil? @tree_widget.clear @tree_widget.enable_context_menu false enable_menu_items false else @tree_widget.enable_context_menu true enable_menu_items true # generate the tree structure @items_paths = {} @tree_widget.insert_top_level_items(0, build_item_tree(@root, @tree_widget)) @tree_widget.resize_columns_to_contents end end def view_selected extract_dir,paths = extract :view paths.each{|p| Process.detach(spawn %Q{xdg-open "#{File.join(extract_dir,p)}"})} end def get_paths items paths = [] items.each do |item| # ensure that the './' is stripped from the paths, so that the # comparison in extract() works as expected. paths << @items_paths[item][2..-1] item.child_count.times do |n| paths += get_paths([item.child(n)]) end end paths.flatten end # choice can be :all, :selected, :view def extract choice case choice when :selected, :view paths = get_paths @tree_widget.selected_items num_entries = paths.size Dir.mkdir(extract_dir = "/tmp/#{AppTitle}-#{rand(36**6).to_s(36)}") if choice == :view else num_entries = @entries.size end if extract_dir ||= Qt::FileDialog::get_existing_directory(self, 'Extract to...') begin Archive.read_open_filename(@current_file) do |archive| overwrite = false progress = Qt::ProgressDialog.new("Extracting...", "Abort", 0, num_entries, self) do set_window_modality(Qt::WindowModal) show end count = 0 while entry = archive.next_header if [:selected, :view].include? choice next unless paths.include?(entry.pathname) end break if progress.was_canceled path = File.join(extract_dir,entry.pathname) if !overwrite && File.exist?(path) case Qt::MessageBox::warning(self, AppTitle, "Overwrite path #{path} ?", OverwriteButtons) when Qt::MessageBox::YesToAll overwrite = true when Qt::MessageBox::No next when Qt::MessageBox::Abort break end end begin case when entry.file? file_dir = File::dirname path FileUtils.mkdir_p file_dir unless File.exist? file_dir File.open(path, 'w+') do |fp| archive.read_data(1024) {|data| fp.write(data)} end when entry.directory? FileUtils.mkdir_p path unless File.exist? path when entry.symbolic_link? File.symlink entry.symlink, path when entry.hardlink? File.link entry.hardlink, path end File.chmod(entry.mode, path) unless entry.symbolic_link? rescue => e $stderr.puts e.message cancel,okay = Qt::MessageBox::Cancel,Qt::MessageBox::Ok break if cancel == Qt::MessageBox::warning(self, AppTitle, "#{e.message}\nContinue?", cancel | okay ) end progress.set_value(count+=1) end progress.reset end rescue Archive::Error => e report_archive_error e end end [extract_dir,paths] # return end def report_archive_error e $stderr.puts e.message Qt::MessageBox::warning(self, AppTitle, e.message) end end class MainWidget < Qt::TreeWidget attr_reader :header_labels def initialize(parent) super build_context_menu @header_labels = Hash[Fields[:labels].map{|i| [i,true]}] set_header_labels @header_labels.keys refresh_headers header.set_context_menu_policy Qt::CustomContextMenu header.connect(SIGNAL 'customContextMenuRequested(QPoint)'){header_context_menu} set_selection_mode(Qt::AbstractItemView::ExtendedSelection) set_context_menu_policy Qt::CustomContextMenu connect(SIGNAL 'customContextMenuRequested(QPoint)'){@context_menu.exec Qt::Cursor.pos} connect(SIGNAL 'itemExpanded(QTreeWidgetItem*)'){resize_columns_to_contents} connect(SIGNAL 'itemCollapsed(QTreeWidgetItem*)'){resize_columns_to_contents} end def resize_columns_to_contents column_count.times do |c| resize_column_to_contents c end end def toggle_column label @header_labels[label] = !@header_labels[label] refresh_headers end def set_visible_columns columns # don't hide all the columns if columns.values.include? true columns.each do |label,visible| @header_labels[label] = visible end end refresh_headers end def enable_context_menu bool @context_actions.each{|a| a.set_enabled bool} end private def header_context_menu # don't allow hiding the last column. last_column = (@header_labels.values.count(true) == 1) actions = @header_labels.map do |label,visible| Qt::Action.new(self) do set_text label set_checkable true set_checked visible set_enabled false if last_column && visible connect(SIGNAL :triggered){ parent.toggle_column(label) } end end Qt::Menu.new(self) do actions.each{|a| add_action a} exec(Qt::Cursor.pos) end end def build_context_menu @context_actions ||= [ ['&Extract selected...', [:extract, :selected]], ['&View selected...', :view_selected] ].map! do |label, method| Qt::Action.new(self) do set_text label connect(SIGNAL :triggered){ parent.parent.send(*method) } end end @context_menu = Qt::Menu.new(self) @context_actions.each{|a| @context_menu.add_action a} end def refresh_headers @header_labels.values.each_with_index{|v,i| set_column_hidden(i,!v)} end end end Qt::Application.new(ARGV) do set_window_icon(Qt::Icon.new( File.join(File.dirname(__FILE__),"#{Archivr::AppTitle.downcase}.png"))) Archivr::MainWindow.new exec end
gpl-3.0
Ell-i/Runtime
stm32/emulator/src/Register_GPIO_AFR.cpp
950
/* * Copyright (c) 2014 ELL-i co-operative. * * This is part of ELL-i software. * * ELL-i software 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. * * ELL-i software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ELL-i software. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Asif Sardar <engr.asif.sardar@gmail.com> 2014 */ #include "Register_GPIO_AFR.h" uint32_t Register_GPIO_AFR::operator = (uint32_t arg) { printout("=", arg); return value_ = arg; }
gpl-3.0
ckaestne/CIDE
CIDE_generateAST/test/generated/Unit1.java
735
package generated; import cide.gast.*; import cide.gparser.*; import cide.greferences.*; import java.util.*; public class Unit1 extends Unit { public Unit1(ASTStringNode string_literal, Token firstToken, Token lastToken) { super(new Property[] { new PropertyOne<ASTStringNode>("string_literal", string_literal) }, firstToken, lastToken); } public Unit1(Property[] properties, IToken firstToken, IToken lastToken) { super(properties,firstToken,lastToken); } public ASTNode deepCopy() { return new Unit1(cloneProperties(),firstToken,lastToken); } public ASTStringNode getString_literal() { return ((PropertyOne<ASTStringNode>)getProperty("string_literal")).getValue(); } }
gpl-3.0
matteoparlato/Project-Neptune
Project Nirvash/Dialogs/DownloadAttachment.xaml.cs
2449
using Microsoft.AppCenter.Analytics; using Project_Nirvash.Helpers; using System; using System.Collections.Generic; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Helpers; namespace Project_Nirvash.Dialogs { /// <summary> /// Classe DownloadAttachment /// </summary> public sealed partial class DownloadAttachment : ContentDialog { private readonly string _fileName; private readonly Uri _url; /// <summary> /// Costruttore senza parametri della classe DownloadAttachment. /// </summary> /// <param name="url">L'URL del file da scaricare</param> /// <param name="fileName">Il nome del file da scaricare</param> public DownloadAttachment(Uri url, string fileName) { InitializeComponent(); FileNameRun.Text = _fileName = fileName; _url = url; ErrorRelativePanel.Visibility = Visibility.Collapsed; } /// <summary> /// Metodo invocato una volta completato il caricamento del ContentDialog. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ContentDialog_Opened(ContentDialog sender, ContentDialogOpenedEventArgs args) { try { await ClientExtensions.DownloadFile(_url); Hide(); } catch (Exception ex) { Analytics.TrackEvent(ex.Message, new Dictionary<string, string> { { "exception", ex.ToString() } }); Title = "Attenzione"; PrimaryButtonText = "Chiudi"; DownloadRelativePanel.Visibility = Visibility.Collapsed; ErrorRelativePanel.Visibility = Visibility.Visible; } UIExtensions.HideProgressStatusBar(); } /// <summary> /// Metodo invocato alla pressione di PrimaryButton. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { if(PrimaryButtonText.Equals("Esegui in background")) { UIExtensions.ShowProgressStatusBar(string.Format("Download di {0} in corso...", _fileName)); } Hide(); } } }
gpl-3.0
lingcarzy/v5cart
admin/controller/error/not_found.php
886
<?php class ControllerErrorNotFound extends Controller { public function index() { $this->language->load('error/not_found'); $this->document->setTitle(L('heading_title')); $this->data['heading_title'] = L('heading_title'); $this->data['text_not_found'] = L('text_not_found'); $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => L('text_home'), 'href' => UA('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => L('heading_title'), 'href' => UA('error/not_found', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => ' :: ' ); $this->children = array( 'common/header', 'common/footer' ); $this->display('error/not_found.tpl'); } } ?>
gpl-3.0
vtexier/duniter-python-api
duniterpy/key/encryption_key.py
1634
""" duniter public and private keys @author: inso """ import libnacl.public from pylibscrypt import scrypt from .base58 import Base58Encoder from .signing_key import _ensure_bytes SEED_LENGTH = 32 # Length of the key crypto_sign_BYTES = 64 SCRYPT_PARAMS = {'N': 4096, 'r': 16, 'p': 1 } class SecretKey(libnacl.public.SecretKey): def __init__(self, salt, password): salt = _ensure_bytes(salt) password = _ensure_bytes(password) seed = scrypt(password, salt, SCRYPT_PARAMS['N'], SCRYPT_PARAMS['r'], SCRYPT_PARAMS['p'], SEED_LENGTH) super().__init__(seed) self.public_key = PublicKey(Base58Encoder.encode(self.pk)) def encrypt(self, pubkey, noonce, text): text_bytes = _ensure_bytes(text) noonce_bytes = _ensure_bytes(noonce) recipient_pubkey = PublicKey(pubkey) crypt_bytes = libnacl.public.Box(self, recipient_pubkey).encrypt(text_bytes, noonce_bytes) return Base58Encoder.encode(crypt_bytes[24:]) def decrypt(self, pubkey, noonce, text): sender_pubkey = PublicKey(pubkey) noonce_bytes = _ensure_bytes(noonce) encrypt_bytes = Base58Encoder.decode(text) decrypt_bytes = libnacl.public.Box(self, sender_pubkey).decrypt(encrypt_bytes, noonce_bytes) return decrypt_bytes.decode('utf-8') class PublicKey(libnacl.public.PublicKey): def __init__(self, pubkey): key = Base58Encoder.decode(pubkey) super().__init__(key) def base58(self): return Base58Encoder.encode(self.pk)
gpl-3.0
maxnitze/football_homepage
app/controllers/user_role_permissions_controller.rb
2426
class UserRolePermissionsController < ApplicationController before_action :set_user_role_permission, only: [:show, :edit, :update, :destroy] # GET /user_role_permissions # GET /user_role_permissions.json def index @user_role_permissions = UserRolePermission.all end # GET /user_role_permissions/1 # GET /user_role_permissions/1.json def show end # GET /user_role_permissions/new def new @user_role_permission = UserRolePermission.new end # GET /user_role_permissions/1/edit def edit end # POST /user_role_permissions # POST /user_role_permissions.json def create @user_role_permission = UserRolePermission.new(user_role_permission_params) respond_to do |format| if @user_role_permission.save format.html { redirect_to @user_role_permission, notice: [ t('user_role_permissions.flash.create.success') ] } format.json { render :show, status: :created, location: @user_role_permission } else format.html { render :new } format.json { render json: @user_role_permission.errors, status: :unprocessable_entity } end end end # PATCH/PUT /user_role_permissions/1 # PATCH/PUT /user_role_permissions/1.json def update respond_to do |format| if @user_role_permission.update(user_role_permission_params) format.html { redirect_to @user_role_permission, notice: [ t('user_role_permissions.flash.update.success') ] } format.json { render :show, status: :ok, location: @user_role_permission } else format.html { render :edit } format.json { render json: @user_role_permission.errors, status: :unprocessable_entity } end end end # DELETE /user_role_permissions/1 # DELETE /user_role_permissions/1.json def destroy @user_role_permission.destroy respond_to do |format| format.html { redirect_to user_role_permissions_url, notice: [ t('user_role_permissions.flash.destroy.success') ] } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_user_role_permission @user_role_permission = UserRolePermission.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_role_permission_params params.require(:user_role_permission).permit(:symbol, :description) end end
gpl-3.0
projectestac/alexandria
html/langpacks/es/tool_xmldb.php
18337
<?php // This file is part of Moodle - https://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <https://www.gnu.org/licenses/>. /** * Strings for component 'tool_xmldb', language 'es', version '3.11'. * * @package tool_xmldb * @category string * @copyright 1999 Martin Dougiamas and contributors * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['actual'] = 'Real'; $string['addpersistent'] = 'Agregar campos persistentes obligatorios'; $string['aftertable'] = 'Después de la tabla:'; $string['back'] = 'Atrás'; $string['backtomainview'] = 'Volver al principal'; $string['cannotuseidfield'] = 'No se puede insertar el campo "id". Es una columna autonumerada'; $string['change'] = 'Cambiar'; $string['charincorrectlength'] = 'Longitud incorrecta para campo char'; $string['check_bigints'] = 'Buscar enteros DB incorrectos'; $string['check_defaults'] = 'Buscar valores por defecto inconsistentes'; $string['check_foreign_keys'] = 'Buscar violaciones de la clave foránea'; $string['check_indexes'] = 'Busque los índices de base de datos que faltan'; $string['check_oracle_semantics'] = 'Buscar longitud de semántica incorrecta'; $string['checkbigints'] = 'Comprobar enteros'; $string['checkdefaults'] = 'Comprobar valores por defecto'; $string['checkforeignkeys'] = 'Comprobar las claves foráneas'; $string['checkindexes'] = 'Comprobar índices'; $string['checkoraclesemantics'] = 'Comprobar la semántica'; $string['completelogbelow'] = '(ver abajo el registro completo de la búsqueda)'; $string['confirmcheckbigints'] = 'Esta funcionalidad buscará <a href="http://tracker.moodle.org/browse/MDL-11038">potential wrong integer fields</a> en su servidor Moodle, generando (¡pero no ejecutando!) automáticamente las acciones SQL necesarias para tener todos los enteros de su base de datos adecuadamente definidos.<br /><br /> Una vez generados, puede copiarlas y ejecutarlas con seguridad en su interfaz SQL preferida (no olvide hacer una copia de seguridad de sus datos antes de hacerlo).<br /><br />Se recomienda ejecutar la última (+) versión de Moodle disponible (1.8, 1.9, 2.x ...) antes de llevar a cabo la búsqueda de enteros erróneos.<br /><br />Esta funcionalidad no ejecuta ninguna acción contra la BD (únicamente la lee), de modo que puede ser realizada con seguridad en cualquier momento.'; $string['confirmcheckdefaults'] = 'Esta funcionalidad buscará valores por defecto inconsistentes en su servidor Moodle, y generará (pero no ejecutará) los comandos SQL necesarios para hacer que todos los valores por defecto se definan apropiadamente.<br /><br />Una vez generados, puede copiar tales comandos y ejecutarlos con seguridad en su interfaz SQL favorita (no olvide hacer una copia de sus datos antes).<br /><br />Es muy recomendable ejecutar la última versión (+version) disponible de Moodle (1.8, 1.9, 2x...) antes de ejecutar la búsqueda de valores por defecto inconsistentes.<br /><br /> Esta funcionalidad no ejecuta ninguna acción contra la base de datos (simplemente la lee), de modo que puede ejecutarse con seguridad en cualquier momento.'; $string['confirmcheckforeignkeys'] = 'Esta funcionalidad buscará posibles violaciones de las claves externas defindas en install.xml. (Moodle no generan actualmente restricciones de clave externa en la base de datos, por lo que datos no válidos pueden estar presentes.) <br /> <br /> Es muy recomendable que se ejecuta la última (+ versión) disponible en su versión de Moodle ( 1.8, 1.9, 2.x ...) antes de ejecutar la búsqueda de índices perdidos. <br /> <br /> Esta funcionalidad no realiza ninguna acción contra la Base de Datos (sólo lee de ella), por lo que se puede ejecutar de forma segura en cualquier momento.'; $string['confirmcheckindexes'] = 'Esta funcionalidad buscará potenciales índices ausentes en su servidor Moodle, generando (no ejecutando) automáticamente los comandos SQL necesarios para mantener todo actualizado. Una vez generados, puede copiar los comandos y ejecutarlos con seguridad con su interfaz SQL favorita.<br /><br /> Es muy recomendable ejecutar la última versión disponible de Moodle (1.8, 1.9, 2.x ...) antes de llevar a cabo la búsqueda de los índices ausentes.<br /><br /> Esta funcionalidad no ejecuta ninguna acción contra la BD (simplemente lee en ella), de modo que puede ejecutarse con seguridad en cualquier momento.'; $string['confirmcheckoraclesemantics'] = 'Esta funcionalidad buscará <a href="https://tracker.moodle.org/browse/MDL-29322">columnas Oracle varchar2 usando semántica BYTE</a> en su servidor Moodle, generando (¡pero no ejecutándose!) automáticamente las sentencias SQL necesarias para que todas las columnas se conviertan para usar semántica CHAR en su lugar (mejor para compatibilidad entre bases de datos y mayor longitud máxima de contenido). Una vez generadas, puede copiar dichas declaraciones y ejecutarlas de forma segura con su interfaz SQL favorita (no olvide hacer una copia de seguridad de sus datos antes de hacerlo). Se recomienda encarecidamente ejecutar la última (+ versión) disponible de su versión de Moodle antes de ejecutar la búsqueda de la semántica de BYTE. Esta funcionalidad no realiza ninguna acción contra la base de datos (solo la lee), por lo que se puede ejecutar de forma segura en cualquier momento.'; $string['confirmdeletefield'] = '¿Está totalmente seguro que quiere eliminar el campo:'; $string['confirmdeleteindex'] = '¿Está totalmente seguro de que quiere eliminar el índice:'; $string['confirmdeletekey'] = '¿Está totalmente seguro de que quiere eliminar la clave:'; $string['confirmdeletetable'] = '¿Está totalmente seguro de que quiere eliminar la tabla:'; $string['confirmdeletexmlfile'] = '¿Está totalmente seguro de que quiere eliminar el archivo:'; $string['confirmrevertchanges'] = '¿Está totalmente seguro de que quiere revertir los cambios realizados sobre:'; $string['create'] = 'Crear'; $string['createtable'] = 'Crear tabla:'; $string['defaultincorrect'] = 'Valor por defecto incorrecto'; $string['delete'] = 'Eliminar'; $string['delete_field'] = 'Eliminar campo'; $string['delete_index'] = 'Eliminar índice'; $string['delete_key'] = 'Eliminar clave'; $string['delete_table'] = 'Eliminar tabla'; $string['delete_xml_file'] = 'Eliminar archivo XML'; $string['doc'] = 'Doc'; $string['docindex'] = 'Índice de la documentación:'; $string['documentationintro'] = 'Esta documentación es generada automáticamente a partir de la definición de la base de datos XMLDB. Sólo está disponible en inglés.'; $string['down'] = 'Abajo'; $string['duplicate'] = 'Duplicar'; $string['duplicatefieldname'] = 'Ya existe otro campo con ese nombre'; $string['duplicatefieldsused'] = 'Campos duplicados usados'; $string['duplicateindexname'] = 'Duplicar nombre del índice'; $string['duplicatekeyname'] = 'Ya existe otra clave con ese nombre'; $string['duplicatetablename'] = 'Ya existe otra tabla con ese nombre'; $string['edit'] = 'Edición'; $string['edit_field'] = 'Editar campo'; $string['edit_field_save'] = 'Guardar campo'; $string['edit_index'] = 'Editar índice'; $string['edit_index_save'] = 'Guardar índice'; $string['edit_key'] = 'Editar clave'; $string['edit_key_save'] = 'Guardar clave'; $string['edit_table'] = 'Editar tabla'; $string['edit_table_save'] = 'Guardar tabla'; $string['edit_xml_file'] = 'Editar archivo XML'; $string['enumvaluesincorrect'] = 'Valores incorrectos para el campo enum'; $string['expected'] = 'Esperado'; $string['extensionrequired'] = 'Lo sentimos, la extensión de PHP \'{$a}\' es necesaria para esta acción. Instale la extensión si desea utilizar esta función.'; $string['extraindexesfound'] = 'Se encontraron índices adicionales'; $string['field'] = 'Campo'; $string['fieldnameempty'] = 'Nombre del campo vacío'; $string['fields'] = 'Campos'; $string['fieldsnotintable'] = 'El campo no existe en la tabla'; $string['fieldsusedinindex'] = 'Este campo se usa como índice.'; $string['fieldsusedinkey'] = 'Este campo se usa como clave.'; $string['filemodifiedoutfromeditor'] = 'Atención: El archivo se ha modificado localmente usando el editor de XMLDB. Guardar sobrescribirá los cambios locales.'; $string['filenotwriteable'] = 'Archivo no editable'; $string['fkunknownfield'] = 'La clave foránea {$a->keyname} de la tabla {$a->tablename} apunta a un campo inexistente {$a->reffield} en la tabla referenciada {$a->reftable}.'; $string['fkunknowntable'] = 'La clave forántea {$a->keyname} de la tabla {$a->tablename} apunta a una tabla que no existe {$a->reftable}.'; $string['fkviolationdetails'] = 'La clave foránea {$a->keyname} de la tabla {$a->tablename} es violada por {$a->numviolations} de un total de {$a->numrows} filas.'; $string['float2numbernote'] = 'Aviso: A pesar de que los campos "float" están completamente soportados por XMLDB, se recomienda migrar a campos de tipo "número" en su lugar.'; $string['floatincorrectdecimals'] = 'Número incorrecto de decimales del campo float'; $string['floatincorrectlength'] = 'Longitud incorrecta del campo float'; $string['generate_all_documentation'] = 'Toda la documentación'; $string['generate_documentation'] = 'Documentación'; $string['gotolastused'] = 'Ir al último archivo usado'; $string['incorrectfieldname'] = 'Nombre incorrecto'; $string['incorrectindexname'] = 'Nombre del índice incorrecto'; $string['incorrectkeyname'] = 'Nombre de la clave incorrecto'; $string['incorrecttablename'] = 'Nombre de la tabla incorrecto'; $string['index'] = 'Índice'; $string['indexes'] = 'Índices'; $string['indexnameempty'] = 'Nombre del índice vacío.'; $string['integerincorrectlength'] = 'Longitud incorrecta del campo integer'; $string['key'] = 'Clave'; $string['keynameempty'] = 'El nombre clave no puede estar vacío.'; $string['keys'] = 'Claves'; $string['listreservedwords'] = 'Lista de palabras reservadas <br />(utilizada para mantener <a href="https://docs.moodle.org/en/XMLDB_reserved_words" target="_blank">palabras reservadas de XMLDB </a> actualizadas)'; $string['load'] = 'Cargar'; $string['main_view'] = 'Vista principal'; $string['masterprimaryuniqueordernomatch'] = 'Los campos de la clave externa deben aparecer en el mismo orden en que se enumeran en la CLAVE ÚNICA de la tabla de referencia.'; $string['missing'] = 'Falta'; $string['missingindexes'] = 'Se han encontrado índices que faltan'; $string['mustselectonefield'] = '¡Debe seleccionar un campo para ver las acciones relacionadas con el campo!'; $string['mustselectoneindex'] = '¡Debe seleccionar un índice para ver las acciones relacionadas con el índice!'; $string['mustselectonekey'] = '¡Debe seleccionar una clave para ver las acciones relacionadas con la clave!'; $string['new_table_from_mysql'] = 'Nueva tabla desde MySQL'; $string['newfield'] = 'Nuevo campo'; $string['newindex'] = 'Nuevo índice'; $string['newkey'] = 'Nueva clave'; $string['newtable'] = 'Nueva tabla'; $string['newtablefrommysql'] = 'Nueva tabla desde MySQL'; $string['nofieldsspecified'] = 'No se ha especificado ningún campo'; $string['nomasterprimaryuniquefound'] = 'La(s) columna(s) a las que hace referencia su clave externa deben ser incluidas en una clave principal o única en la tabla de referencia. Tenga en cuenta que la columna que está en un índice único no es suficientemente buena.'; $string['nomissingorextraindexesfound'] = 'No se han encontrado índices faltantes o adicionales, por lo que no es necesario realizar ninguna otra acción.'; $string['noreffieldsspecified'] = 'No se han especificado campos de referencia'; $string['noreftablespecified'] = 'La tabla de referencia especificada no se encontró'; $string['noviolatedforeignkeysfound'] = 'No se han encontrado claves foráneas violadas'; $string['nowrongdefaultsfound'] = 'No se han encontrado valores por defecto inconsistentes, su base de datos no necesita acciones adicionales.'; $string['nowrongintsfound'] = 'No se han encontrado enteros erróneos, su base de datos no necesita acciones adicionales.'; $string['nowrongoraclesemanticsfound'] = 'No se han encontrado columnas Oracle que utilicen la semántica BYTE. Su base de datos no necesita acciones adicionales.'; $string['numberincorrectdecimals'] = 'Número incorrecto de decimales en el campo numérico'; $string['numberincorrectlength'] = 'Longitud incorrecta para campo numérico'; $string['numberincorrectwholepart'] = 'Parte entera del número demasiado grande para el campo numérico'; $string['pendingchanges'] = 'Nota: Ha realizado cambios en este archivo. Se pueden guardar en cualquier momento.'; $string['pendingchangescannotbesaved'] = '¡Hay cambios en este archivo pero no se pueden guardar! Verifique que tanto el directorio como el archivo "install.xml" dentro de él tengan permisos de escritura para el servidor web.'; $string['pendingchangescannotbesavedreload'] = '¡Hay cambios en este archivo pero no se pueden guardar! Verifique que tanto el directorio como el archivo "install.xml" dentro de él tengan permisos de escritura para el servidor web. Luego, vuelva a cargar esta página y debería poder guardar esos cambios.'; $string['persistentfieldscomplete'] = 'Se han añadido los siguientes campos:'; $string['persistentfieldsconfirm'] = 'Quiere añadir los siguientes campos:'; $string['persistentfieldsexist'] = 'Los siguientes campos ya existen:'; $string['pluginname'] = 'Editor XMLDB'; $string['primarykeyonlyallownotnullfields'] = 'Las claves primarias no pueden ser nulas'; $string['privacy:metadata'] = 'El complemento de editor XMLDB no almacena ningún dato personal.'; $string['reserved'] = 'Reservado'; $string['reservedwords'] = 'Palabras reservadas'; $string['revert'] = 'Revertir'; $string['revert_changes'] = 'Revertir cambios'; $string['save'] = 'Guardar'; $string['searchresults'] = 'Resultados de la búsqueda'; $string['selectaction'] = 'Seleccionar acción:'; $string['selectdb'] = 'Seleccionar base de datos:'; $string['selectfieldkeyindex'] = 'Seleccionar campo/clave/índice:'; $string['selectonecommand'] = 'Por favor, seleccione una acción de la lista para ver el código PHP'; $string['selectonefieldkeyindex'] = 'Por favor, seleccione un campo/clave/índice de la lista para ver el código PHP'; $string['selecttable'] = 'Seleccionar tabla:'; $string['table'] = 'Tabla'; $string['tablenameempty'] = 'El nombre de la tabla no puede estar vacío'; $string['tables'] = 'Tablas'; $string['unknownfield'] = 'Hace referencia a un campo desconocido'; $string['unknowntable'] = 'Hace referencia a una tabla desconocida'; $string['unload'] = 'Descargar'; $string['up'] = 'Arriba'; $string['view'] = 'Ver'; $string['view_reserved_words'] = 'Ver palabras reservadas'; $string['view_structure_php'] = 'Ver estructura PHP'; $string['view_structure_sql'] = 'Ver estructura SQL'; $string['view_table_php'] = 'Ver tabla PHP'; $string['view_table_sql'] = 'Ver tabla SQL'; $string['viewedited'] = 'Ver editados'; $string['vieworiginal'] = 'Ver original'; $string['viewphpcode'] = 'Ver código PHP'; $string['viewsqlcode'] = 'Ver código SQL'; $string['viewxml'] = 'XML'; $string['violatedforeignkeys'] = 'Claves externas violadas'; $string['violatedforeignkeysfound'] = 'Se han encontrado claves externas violadas'; $string['violations'] = 'Violaciones'; $string['wrong'] = 'Erróneo'; $string['wrongdefaults'] = 'Se encontraron valores por defecto erróneos'; $string['wrongints'] = 'Se han encontrado enteros erróneos'; $string['wronglengthforenum'] = 'Longitud incorrecta del campo enum'; $string['wrongnumberofreffields'] = 'Número incorrecto de campos de referencia'; $string['wrongoraclesemantics'] = 'Se ha encontrado semántica incorrecta de Oracle BYTE'; $string['wrongreservedwords'] = 'Palabras reservadas utilizadas actualmente <br /> (tenga en cuenta que los nombres de las tablas no son importantes si se usa el prefijo $CFG->)'; $string['yesextraindexesfound'] = 'Se encontraron los siguientes índices adicionales.'; $string['yesmissingindexesfound'] = '<p>Se han detectado que faltan algunos índices en su base de datos. Aquí están sus detalles y las instrucciones SQL necesarias para ser ejecutadas con su interfaz SQL favorita para crear todos. ¡Recuerde hacer antes una copia de seguridad de sus datos!</p> <p>Después de hacer eso, es muy recomendable ejecutar esta utilidad de nuevo para verificar que no se encuentren más índices que falten.</p>'; $string['yeswrongdefaultsfound'] = 'En su base de datos se han encontrado algunos valores por defecto inconsistentes. Aquí se presentan los detalles y las acciones SQL que deben ejecutarse en su interfaz SQL favorita para crearlos (no olvide hacer una copia de seguridad de sus datos).<br /><br />Una vez realizado, se recomienda ejecutar de nuevo esta utilidad para comprobar que no se encuentran más valores por defecto inconsistentes.'; $string['yeswrongintsfound'] = 'Se han encontrado algunos enteros erróneos en su BD. Aquí se presentan los detalles y las acciones SQL que deben ejecutarse en su interfaz SQL favorita para crearlos (no olvide hacer una copia de seguridad de sus datos).<br /><br />Una vez realizado, se recomienda ejecutar de nuevo esta utilidad para comprobar que no se encuentran más enteros erróneos.'; $string['yeswrongoraclesemanticsfound'] = '<p>Se han encontrado algunas columnas de Oracle que utilizan semántica BYTE en su base de datos. Aquí están sus detalles y las declaraciones SQL necesarias para ser ejecutadas con su interfaz SQL favorita para convertirlas todas. ¡Recuerde hacer una copia de seguridad de sus datos antes!</p> <p>Después de hacer eso, es muy recomendable ejecutar esta utilidad nuevamente para verificar que no se encuentren más semánticas incorrectas.</p>';
gpl-3.0
VoidDragonOfMars/pixelware
instantweatherapplication/src/main/java/com/weatherapp/services/UserServiceImpl.java
826
package com.weatherapp.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.weatherapp.model.dao.UserDaoInterface; import com.weatherapp.model.entities.User; @Service("userService") public class UserServiceImpl implements UserService { @Autowired private UserDaoInterface userDao; public User getUserByNameAndPass(String name, String pass) { return userDao.getUserByNameAndPass(name, pass); } public User getUserById(int id) { return userDao.getUserById(id); } public int updateUser(User user) { return userDao.updateUser(user); } public int createUser(User user) { return userDao.createUser(user); } public int deleteUser(int id) { return userDao.deleteUser(id); } }
gpl-3.0
gouyuwang/private
work/shop/php/application/common/model/User.php
236
<?php namespace app\common\model; class User extends BaseModel { /** * TODO 加密 * @param $passwrod * @return string */ public function gen_password($passwrod) { return sha1($passwrod); } }
gpl-3.0
yaacov/miq-scripts
set-miq-metric.rb
2661
#!/usr/bin/env ruby # Load Rails ENV['RAILS_ENV'] = ARGV[0] || 'development' begin require './manageiq/config/environment' rescue LoadError DIR = File.dirname(__FILE__) require DIR + '/../manageiq/config/environment' end # -------------------- # functions and consts # -------------------- def push_metric (prov, timestamp, interval = "daily") prov.metric_rollups << MetricRollup.create( :capture_interval_name => interval, :timestamp => timestamp, :time_profile => TimeProfile.first, :cpu_usage_rate_average => rand(100), :mem_usage_absolute_average => rand(100), :derived_vm_numvcpus => 4, :net_usage_rate_average => rand(1000), :derived_memory_available => 8192, :derived_memory_used => rand(8192), :stat_container_group_create_rate => rand(100), :stat_container_group_delete_rate => rand(50), :stat_container_image_registration_rate => rand(25) ) end def push_nodes_metric (prov, timestamp) prov.container_nodes.each do |node| node.metric_rollups << MetricRollup.create( :capture_interval_name => "hourly", :timestamp => timestamp, :cpu_usage_rate_average => rand(100), :mem_usage_absolute_average => rand(100), :derived_vm_numvcpus => 4, :net_usage_rate_average => rand(1000), :derived_memory_available => 8192, :derived_memory_used => rand(8192)) end end def push_container_metric (prov, timestamp) prov.containers.each do |node| node.metric_rollups << MetricRollup.create( :capture_interval_name => "hourly", :timestamp => timestamp, :cpu_usage_rate_average => rand(100), :mem_usage_absolute_average => rand(100), :derived_vm_numvcpus => 4, :net_usage_rate_average => rand(1000), :derived_memory_available => 8192, :derived_memory_used => rand(8192)) end end def push_last_30_days(prov) (0 .. 30).each { |x| push_metric(prov, x.days.ago, "daily") } end def push_last_24_hours(prov) (0 .. 24).each { |x| push_metric(prov, x.hours.ago, "hourly") } (0 .. 24).each { |x| push_nodes_metric(prov, x.hours.ago) } (0 .. 24).each { |x| push_container_metric(prov, x.hours.ago) } end # -------------------- # push metric data # -------------------- ManageIQ::Providers::ContainerManager.all.each do |prov| push_last_30_days(prov) push_last_24_hours(prov) end ContainerProject.all.each do |prov| push_last_30_days(prov) push_last_24_hours(prov) end
gpl-3.0
rleal/opencartLang
admin/language/spanish/payment/pp_express.php
1390
<?php // Heading $_['heading_title'] = 'PayPal Express'; // Text $_['text_payment'] = 'Pago'; $_['text_success'] = 'Has modificado los detalles de cuenta de PayPal Express Checkout con éxito'; $_['text_pp_express'] = '<a onclick="window.open(\'https://www.paypal.com/uk/mrb/pal=W9TBB5DTD6QJW\');"><img src="view/image/payment/paypal.png" alt="PayPal" title="PayPal" style="border: 1px solid #EEEEEE;" /></a>'; $_['text_authorization'] = 'Autorización'; $_['text_sale'] = 'Venta'; // Entry $_['entry_username'] = 'Usuario API :'; $_['entry_password'] = 'Contraseña API :'; $_['entry_signature'] = 'Firma API :'; $_['entry_test'] = 'Modo test:'; $_['entry_method'] = 'Método Transacción :'; $_['entry_total'] = 'Total:<br /><span class="help">El total del pedido debe alcanzar esta cantidad para que la forma de pago se active.</span>'; $_['entry_order_status'] = 'Estado del pedido:'; $_['entry_geo_zone'] = 'Geo zona:'; $_['entry_status'] = 'Estado:'; $_['entry_sort_order'] = 'Orden:'; // Error $_['error_permission'] = 'Atención: No tienes permisos para modificar payment PayPal Express Checkout!'; $_['error_username'] = 'Usuario API obligatorio!'; $_['error_password'] = 'Contraseña API obligatoria!'; $_['error_signature'] = 'Firma API obligatoria!'; ?>
gpl-3.0
kbalk/booklist
tests/test_catalog.py
3310
"""Test cases related to the CatalogSearch class""" from datetime import datetime import logging import pytest from booklist.catalog import CatalogSearch, CatalogSearchError #pylint: disable=missing-docstring,redefined-outer-name @pytest.fixture def catalog_url(scope='module'): #pylint: disable=unused-argument return 'https://catalog.library.loudoun.gov' @pytest.fixture def sue_grafton_publications(scope='module'): #pylint: disable=unused-argument # The following are the 2015 publications for Sue Grafton: return { 'Large Print': [ '"J" is for judgment', '"K" is for killer : a Kinsey Millhone mystery', '"L" is for lawless', '"M" is for malice : a Kinsey Millhone mystery', '"N" is for noose a Kinsey Millhone mystery', '"O" is for outlaw', '"X"' ], 'Book': ['X'], 'Book on CD': ['X'], 'eAudioBook': [ '"X" is for', '"X"' ], 'eBook': ['"X" is for'] } def test_good_init(catalog_url): assert isinstance(CatalogSearch(catalog_url), CatalogSearch) def test_good_init_with_logger(catalog_url): logger = logging.getLogger() assert isinstance(CatalogSearch(catalog_url, logger), CatalogSearch) def test_no_url_in_init(): with pytest.raises(CatalogSearchError) as excinfo: empty_url = None CatalogSearch(empty_url) assert 'argument' in str(excinfo.value) def test_get_year_filter(catalog_url): catalog = CatalogSearch(catalog_url) assert catalog.year_filter == datetime.now().year def test_set_year_filter(catalog_url): catalog = CatalogSearch(catalog_url) new_year = '2020' catalog.year_filter = new_year assert catalog.year_filter == new_year def test_good_search(catalog_url, sue_grafton_publications): catalog = CatalogSearch(catalog_url) catalog.year_filter = '2015' results = catalog.search('Grafton, Sue', 'Book') print(results) books = sue_grafton_publications['Book'] large_prints = sue_grafton_publications['Large Print'] assert len(results) == len(books) + len(large_prints) for result in results: assert result[1] in books or result[1] in large_prints def test_good_search_by_media(catalog_url, sue_grafton_publications): catalog = CatalogSearch(catalog_url) catalog.year_filter = '2015' results = catalog.search('Grafton, Sue', 'Book on CD') cd_books = sue_grafton_publications['Book on CD'] assert len(results) == len(cd_books) for result in results: assert result[1] in cd_books def test_bad_url(): catalog = CatalogSearch('http://nosuchurl.com') with pytest.raises(CatalogSearchError) as excinfo: catalog.search('Grafton, Sue', 'Book') assert 'Response to' in str(excinfo.value) def test_bad_search_by_media(catalog_url): catalog = CatalogSearch(catalog_url) with pytest.raises(CatalogSearchError) as excinfo: catalog.search('Grafton, Sue', 'bad media') assert 'Media type' in str(excinfo.value) def test_bad_search_no_media(catalog_url): catalog = CatalogSearch(catalog_url) with pytest.raises(CatalogSearchError) as excinfo: catalog.search('Grafton, Sue', '') assert 'Arguments' in str(excinfo.value)
gpl-3.0
cassiuschen/bdfzer-sso
config/initializers/session_store.rb
143
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :redis_store #, key: '_BDFZer-sso_session'
gpl-3.0
alexholehouse/SBMLIntegrator
libsbml-5.0.0/src/bindings/csharp/csharp-files-win/Priority.cs
16307
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace libsbml { using System; using System.Runtime.InteropServices; /** * LibSBML implementation of %SBML Level 3's %Priority construct * for Event. * * The Priority object class (which was introduced in SBML Level&nbsp;3 * Version&nbsp;1), like Delay, is derived from SBase and contains a MathML * formula stored in the element 'math'. This formula is used to compute a * dimensionless numerical value that influences the order in which a * simulator is to perform the assignments of two or more events that * happen to be executed simultaneously. The formula may evaluate to any * @c double value (and thus may be a positive or negative number, or * zero), with positive numbers taken to signifying a higher priority than * zero or negative numbers. If no Priority object is present on a given * Event object, no priority is defined for that event. * * @section priority-interp The interpretation of priorities on events in a model * * For the purposes of SBML, <em>simultaneous event execution</em> is * defined as the situation in which multiple events have identical * times of execution. The time of execution is calculated as the * sum of the time at which a given event's Trigger is <em>triggered</em> * plus its Delay duration, if any. Here, <em>identical times</em> means * <em>mathematically equal</em> instants in time. (In practice, * simulation software adhering to this specification may have to * rely on numerical equality instead of strict mathematical * equality; robust models will ensure that this difference will not * cause significant discrepancies from expected behavior.) * * If no Priority subobjects are defined for two or more Event objects, * then those events are still executed simultaneously but their order of * execution is <em>undefined by the SBML Level&nbsp;3 Version&nbsp;1 * specification</em>. A software implementation may choose to execute * such simultaneous events in any order, as long as each event is executed * only once and the requirements of checking the 'persistent' attribute * (and acting accordingly) are satisfied. * * If Priority subobjects are defined for two or more * simultaneously-triggered events, the order in which those particular * events must be executed is dictated by their Priority objects, * as follows. If the values calculated using the two Priority * objects' 'math' expressions differ, then the event having * the higher priority value must be executed before the event with * the lower value. If, instead, the two priority values are * mathematically equal, then the two events must be triggered in a * <em>random</em> order. It is important to note that a <em>random * order is not the same as an undefined order</em>: given multiple * runs of the same model with identical conditions, an undefined * ordering would permit a system to execute the events in (for * example) the same order every time (according to whatever scheme * may have been implemented by the system), whereas the explicit * requirement for random ordering means that the order of execution * in different simulation runs depends on random chance. In other * words, given two events <em>A</em> and <em>B</em>, a randomly-determined * order must lead to an equal chance of executing <em>A</em> first or * <em>B</em> first, every time those two events are executed * simultaneously. * * A model may contain a mixture of events, some of which have * Priority subobjects and some do not. Should a combination of * simultaneous events arise in which some events have priorities * defined and others do not, the set of events with defined * priorities must trigger in the order determined by their Priority * objects, and the set of events without Priority objects must be * executed in an <em>undefined</em> order with respect to each other * and with respect to the events with Priority subobjects. (Note * that <em>undefined order</em> does not necessarily mean random * order, although a random ordering would be a valid implementation * of this requirement.) * * The following example may help further clarify these points. * Suppose a model contains four events that should be executed * simultaneously, with two of the events having Priority objects * with the same value and the other two events having Priority * objects with the same, but different, value. The two events with * the higher priorities must be executed first, in a random order * with respect to each other, and the remaining two events must be * executed after them, again in a random order, for a total of four * possible and equally-likely event executions: A-B-C-D, A-B-D-C, * B-A-C-D, and B-A-D-C. If, instead, the model contains four events * all having the same Priority values, there are 4! or 24 * possible orderings, each of which must be equally likely to be * chosen. Finally, if none of the four events has a Priority * subobject defined, or even if exactly one of the four events has a * defined Priority, there are again 24 possible orderings, but the * likelihood of choosing any particular ordering is undefined; the * simulator can choose between events as it wishes. (The SBML * specification only defines the effects of priorities on Event * objects with respect to <em>other</em> Event objects with * priorities. Putting a priority on a <em>single</em> Event object * in a model does not cause it to fall within that scope.) * * @section priority-eval Evaluation of Priority expressions * * An event's Priority object 'math' expression must be * evaluated at the time the Event is to be <em>executed</em>. During * a simulation, all simultaneous events have their Priority values * calculated, and the event with the highest priority is selected for * next execution. Note that it is possible for the execution of one * Event object to cause the Priority value of another * simultaneously-executing Event object to change (as well as to * trigger other events, as already noted). Thus, after executing * one event, and checking whether any other events in the model have * been triggered, all remaining simultaneous events that * <em>either</em> (i) have Trigger objects with attributes * 'persistent'=@c false <em>or</em> (ii) have Trigger * expressions that did not transition from @c true to * @c false, must have their Priority expression reevaluated. * The highest-priority remaining event must then be selected for * execution next. * * @section priority-units Units of Priority object's mathematical expressions * * The unit associated with the value of a Priority object's * 'math' expression should be @c dimensionless. This is * because the priority expression only serves to provide a relative * ordering between different events, and only has meaning with * respect to other Priority object expressions. The value of * Priority objects is not comparable to any other kind of object in * an SBML model. * * @note The Priority construct exists only in SBML Level&nbsp;3; it cannot * be used in SBML Level&nbsp;2 or Level&nbsp;1 models. * * @see Event * @see Delay * @see EventAssignment * @if java @see EventAssignment@endif */ public class Priority : SBase { private HandleRef swigCPtr; internal Priority(IntPtr cPtr, bool cMemoryOwn) : base(libsbmlPINVOKE.Priority_SWIGUpcast(cPtr), cMemoryOwn) { //super(libsbmlPINVOKE.PriorityUpcast(cPtr), cMemoryOwn); swigCPtr = new HandleRef(this, cPtr); } internal static HandleRef getCPtr(Priority obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } internal static HandleRef getCPtrAndDisown (Priority obj) { HandleRef ptr = new HandleRef(null, IntPtr.Zero); if (obj != null) { ptr = obj.swigCPtr; obj.swigCMemOwn = false; } return ptr; } ~Priority() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; libsbmlPINVOKE.delete_Priority(swigCPtr); } swigCPtr = new HandleRef(null, IntPtr.Zero); } GC.SuppressFinalize(this); base.Dispose(); } } /** * Creates a new Priority object using the given SBML @p level and @p * version values. * * @param level a long integer, the SBML Level to assign to this Priority * * @param version a long integer, the SBML Version to assign to this * Priority * * @note Upon the addition of a Priority object to an Event (e.g., using * Event::setPriority(@if java Priority d@endif)), the SBML Level, SBML Version * and XML namespace of the document @em override the values used when * creating the Priority object via this constructor. This is necessary to * ensure that an SBML document is a consistent structure. Nevertheless, * the ability to supply the values at the time of creation of a Priority is * an important aid to producing valid SBML. Knowledge of the intented * SBML Level and Version determine whether it is valid to assign a * particular value to an attribute, or whether it is valid to add a * particular Priority object to an existing Event.<br><br> * * @note The Priority construct exists only in SBML Level&nbsp;3; it * cannot be used in SBML Level&nbsp;2 or Level&nbsp;1 models. */ public Priority(long level, long version) : this(libsbmlPINVOKE.new_Priority__SWIG_0(level, version), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates a new Priority object using the given SBMLNamespaces object * @p sbmlns. * * The SBMLNamespaces object encapsulates SBML Level/Version/namespaces * information. It is used to communicate the SBML Level, Version, and * (in Level&nbsp;3) packages used in addition to SBML Level&nbsp;3 Core. * A common approach to using this class constructor is to create an * SBMLNamespaces object somewhere in a program, once, then pass it to * object constructors such as this one when needed. * * @param sbmlns an SBMLNamespaces object. * * @note Upon the addition of a Priority object to an Event (e.g., using * Event::setPriority(@if java Priority d@endif)), the SBML XML namespace of * the document @em overrides the value used when creating the Priority * object via this constructor. This is necessary to ensure that an SBML * document is a consistent structure. Nevertheless, the ability to * supply the values at the time of creation of a Priority is an important * aid to producing valid SBML. Knowledge of the intented SBML Level and * Version determine whether it is valid to assign a particular value to * an attribute, or whether it is valid to add a particular Priority object * to an existing Event.<br><br> * * @note The Priority construct exists only in SBML Level&nbsp;3; it * cannot be used in SBML Level&nbsp;2 or Level&nbsp;1 models. */ public Priority(SBMLNamespaces sbmlns) : this(libsbmlPINVOKE.new_Priority__SWIG_1(SBMLNamespaces.getCPtr(sbmlns)), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Copy constructor; creates a copy of this Priority. */ public Priority(Priority orig) : this(libsbmlPINVOKE.new_Priority__SWIG_2(Priority.getCPtr(orig)), true) { if (libsbmlPINVOKE.SWIGPendingException.Pending) throw libsbmlPINVOKE.SWIGPendingException.Retrieve(); } /** * Creates and returns a deep copy of this Priority. * * @return a (deep) copy of this Priority. */ public new Priority clone() { IntPtr cPtr = libsbmlPINVOKE.Priority_clone(swigCPtr); Priority ret = (cPtr == IntPtr.Zero) ? null : new Priority(cPtr, true); return ret; } /** * Get the mathematical formula for the priority and return it * as an AST. * * @return the math of this Priority. */ public ASTNode getMath() { IntPtr cPtr = libsbmlPINVOKE.Priority_getMath(swigCPtr); ASTNode ret = (cPtr == IntPtr.Zero) ? null : new ASTNode(cPtr, false); return ret; } /** * Predicate to test whether the formula for this delay is set. * * @return @c true if the formula (meaning the @c math subelement) of * this Priority is set, @c false otherwise. */ public bool isSetMath() { bool ret = libsbmlPINVOKE.Priority_isSetMath(swigCPtr); return ret; } /** * Sets the math expression of this Priority instance to a copy of the given * ASTNode. * * @param math an ASTNode representing a formula tree. * * @return integer value indicating success/failure of the * function. @if clike The value is drawn from the * enumeration #OperationReturnValues_t. @endif The possible values * returned by this function are: * @li @link libsbmlcs.libsbml.LIBSBML_OPERATION_SUCCESS LIBSBML_OPERATION_SUCCESS @endlink * @li @link libsbmlcs.libsbml.LIBSBML_INVALID_OBJECT LIBSBML_INVALID_OBJECT @endlink */ public int setMath(ASTNode math) { int ret = libsbmlPINVOKE.Priority_setMath(swigCPtr, ASTNode.getCPtr(math)); return ret; } /** * Returns the libSBML type code of this object instance. * * @if clike LibSBML attaches an identifying code to every kind of SBML * object. These are known as <em>SBML type codes</em>. The set of * possible type codes is defined in the enumeration #SBMLTypeCode_t. * The names of the type codes all begin with the characters @c * SBML_. @endif@if java LibSBML attaches an identifying code to every * kind of SBML object. These are known as <em>SBML type codes</em>. In * other languages, the set of type codes is stored in an enumeration; in * the Java language interface for libSBML, the type codes are defined as * static integer constants in the interface class {@link * libsbmlcs.libsbml}. The names of the type codes all begin with the * characters @c SBML_. @endif@if python LibSBML attaches an identifying * code to every kind of SBML object. These are known as <em>SBML type * codes</em>. In the Python language interface for libSBML, the type * codes are defined as static integer constants in the interface class * @link libsbml@endlink. The names of the type codes all begin with the * characters @c SBML_. @endif@if csharp LibSBML attaches an identifying * code to every kind of SBML object. These are known as <em>SBML type * codes</em>. In the C# language interface for libSBML, the type codes * are defined as static integer constants in the interface class @link * libsbmlcs.libsbml@endlink. The names of the type codes all begin with * the characters @c SBML_. @endif * * @return the SBML type code for this object, or @link libsbmlcs.libsbml.SBML_UNKNOWN SBML_UNKNOWN@endlink (default). * * @see getElementName() */ public new int getTypeCode() { int ret = libsbmlPINVOKE.Priority_getTypeCode(swigCPtr); return ret; } /** * Returns the XML element name of this object, which for Priority, is * always @c 'priority'. * * @return the name of this element, i.e., @c 'priority'. * * @see getTypeCode() */ public new string getElementName() { string ret = libsbmlPINVOKE.Priority_getElementName(swigCPtr); return ret; } /** * Predicate returning @c true if * all the required elements for this Priority object * have been set. * * @note The required elements for a Priority object are: * math * * @return a bool value indicating whether all the required * elements for this object have been defined. */ public new bool hasRequiredElements() { bool ret = libsbmlPINVOKE.Priority_hasRequiredElements(swigCPtr); return ret; } } }
gpl-3.0
jyavu/jytsu
jytsu-demo/src/main/java/com/jyavu/jytsu/jytsu_demo/client/main_page/MainPageView.java
196
package com.jyavu.jytsu.jytsu_demo.client.main_page; import com.google.gwt.user.client.ui.IsWidget; /** * Created by gammagec on 4/24/14. */ public interface MainPageView extends IsWidget { }
gpl-3.0
rilwen/open-quantum-systems
protein_chain/evolver_runge_kutta.cpp
1879
#include "evolver_runge_kutta.h" #include <cassert> #include <cmath> EvolverRungeKutta::EvolverRungeKutta(const Eigen::MatrixXcd& hamiltonian, double timeStep) : EvolverStepping(timeStep), m_M(hamiltonian*std::complex<double>(0.0,-1.0)) { assert(m_M.rows() == m_M.cols()); for (unsigned int k = 0; k < m_order; ++k) { m_k[k].resize(m_M.rows()); } } // Coefficients of the 4th order RK method for linear ODEs from "Runge-Kutta method for Linear Ordinary Differential Equations", D. W. Zingg and T. T. Chisholm const boost::array<double,EvolverRungeKutta::m_order> EvolverRungeKutta::m_b = { 0.07801567728325, 0.04708870117112, 0.47982272993855, 0.39507289160708 }; const boost::array<double,EvolverRungeKutta::m_order> EvolverRungeKutta::m_c = { 0, 0.69631521002413, 0.29441651741, 0.82502163765 }; const boost::array<double,1> EvolverRungeKutta::m_a1 = { m_c[0] }; const boost::array<double,2> EvolverRungeKutta::m_a2 = { m_b[0], 0.21640084013679 }; const boost::array<double,3> EvolverRungeKutta::m_a3 = { m_b[0], m_b[1], 0.69991725920066 }; void EvolverRungeKutta::step(const double step_size, Eigen::VectorXcd& state) { /* // Euler: state += step_size*m_M*state; */ m_k[0].noalias() = m_M*state; m_k[1].noalias() = m_M*(state + step_size*m_a1[0]*m_k[0]); m_k[2].noalias() = m_M*(state + step_size*(m_a2[0]*m_k[0] + m_a2[1]*m_k[1])); m_k[3].noalias() = m_M*(state + step_size*(m_a3[0]*m_k[0] + m_a3[1]*m_k[1] + m_a3[2]*m_k[2])); for (unsigned int i = 0; i < m_order; ++i) { state.noalias() += (step_size*m_b[i])*m_k[i]; } } void EvolverRungeKutta::step(const double step_size, Eigen::MatrixXcd& states) { Eigen::VectorXcd state(states.rows()); for (unsigned int i = 0; i < static_cast<unsigned int>(states.cols()); ++i) { state = states.col(i); step(step_size, state); states.col(i) = state; } }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-68.js
893
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-68.js * @description Object.defineProperty - desc.value and name.value are two strings with different values (8.12.9 step 6) */ function testcase() { var obj = {}; obj.foo = "abcd"; // default value of attributes: writable: true, configurable: true, enumerable: true Object.defineProperty(obj, "foo", { value: "fghj" }); return dataPropertyAttributesAreCorrect(obj, "foo", "fghj", true, true, true); } runTestCase(testcase);
gpl-3.0
avdata99/SIAT
siat-1.0-SOURCE/src/buss/src/ar/gov/rosario/siat/gde/buss/bean/HistGesJud.java
3915
//Copyright (c) 2011 Municipalidad de Rosario and Coop. de Trabajo Tecso Ltda. //This file is part of SIAT. SIAT is licensed under the terms //of the GNU General Public License, version 3. //See terms in COPYING file or <http://www.gnu.org/licenses/gpl.txt> package ar.gov.rosario.siat.gde.buss.bean; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import ar.gov.rosario.siat.gde.buss.dao.GdeDAOFactory; import coop.tecso.demoda.buss.bean.BaseBO; /** * Bean correspondiente al historico de la gestion judicial. * * @author tecso */ @Entity @Table(name = "gde_histGesJud") public class HistGesJud extends BaseBO { private static final long serialVersionUID = 1L; public static final String NAME = "hisGesJud"; public static final String LOG_CREADA = "Creación de la Gestión Judicial"; public static final String LOG_MODIFICADA = "Modificación de datos de la Gestión Judicial"; public static final String LOG_DEUDA_ELIMINADA = "Eliminación de Deuda de la Gestión Judicial"; public static final String LOG_INCLUSION_DEUDAS = "Inclusión de Deuda a la Gestión Judicial"; public static final String LOG_INCLUSION_EVENTO = "Registración de Evento en la Gestión Judicial"; public static final String LOG_MODIFICACION_DEUDA_INCLUIDA = "Modificación de Deuda incluida en la Gestión Judicial"; public static final String LOG_REG_CADUCIDAD ="registración de Caducidad de la Gestión Judicial"; public static final String LOG_EVENTO_ELIMINADO = "Eliminación de Evento de la Gestión Judicial"; public static final String LOG_INCLUSION_EVENTO_ARCHIVO = "Registración de Evento en la Gestión Judicial por importación de archivo"; @ManyToOne(optional=false, fetch=FetchType.LAZY) @JoinColumn(name="idGesJud") private GesJud gesJud; // NOT NULL @Column(name = "fecha") private Date fecha; // DATETIME YEAR TO DAY @Column(name = "descripcion") private String descripcion; // VARCHAR(100) // Constructores public HistGesJud(){ super(); } // Getters y Setters public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public GesJud getGesJud() { return gesJud; } public void setGesJud(GesJud gesJud) { this.gesJud = gesJud; } // Metodos de Clase public static HistGesJud getById(Long id) { return (HistGesJud) GdeDAOFactory.getHistGesJudDAO().getById(id); } public static HistGesJud getByIdNull(Long id) { return (HistGesJud) GdeDAOFactory.getHistGesJudDAO().getByIdNull(id); } public static List<HistGesJud> getList() { return (ArrayList<HistGesJud>) GdeDAOFactory.getHistGesJudDAO().getList(); } public static List<HistGesJud> getListActivos() { return (ArrayList<HistGesJud>) GdeDAOFactory.getHistGesJudDAO().getListActiva(); } // Metodos de Instancia // Validaciones public boolean validateCreate() throws Exception { //limpiamos la lista de errores clearError(); if (!this.validate()) { return false; } // Validaciones de Negocio return true; } public boolean validateUpdate() throws Exception { //limpiamos la lista de errores clearError(); if (!this.validate()) { return false; } // Validaciones de Negocio return true; } public boolean validateDelete() { //limpiamos la lista de errores clearError(); if (hasError()) { return false; } return true; } private boolean validate() throws Exception { // validaciones comunes if (hasError()) { return false; } return true; } // Metodos de negocio }
gpl-3.0
lntn/esport-website
app/Repositories/MasterListRepository.php
515
<?php /** * Created by PhpStorm. * User: Nam * Date: 02/09/2016 * Time: 23:20 */ namespace App\Repositories; use App\Models\MasterList; class MasterListRepository { public static function get($key) { return MasterList::where('key', $key)->first(); } public static function set($key, $value) { $list_item = MasterList::where('key', $key)->first(); if (!empty($list_item)) { $list_item->value = $value; $list_item->save(); } } }
gpl-3.0
kremi151/MinaMod
src/main/java/lu/kremi151/minamod/client/GuiAmuletInventory.java
1881
package lu.kremi151.minamod.client; import org.lwjgl.opengl.GL11; import lu.kremi151.minamod.MinaMod; import lu.kremi151.minamod.container.ContainerAmuletInventory; import lu.kremi151.minamod.proxy.ClientProxy; import lu.kremi151.minamod.util.MinaUtils; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.translation.I18n; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class GuiAmuletInventory extends GuiContainer { private static final ResourceLocation guiTextures = new ResourceLocation(MinaMod.MODID, "textures/gui/amulets/default.png"); private ContainerAmuletInventory ct; public GuiAmuletInventory(ContainerAmuletInventory container) { super(container); this.ct = container; this.ySize = 176; } @Override protected void drawGuiContainerForegroundLayer(int param1, int param2) { fontRenderer.drawString( I18n.translateToLocal("container.amulets.inventory"), 8, 10, 4210752); fontRenderer.drawString( I18n.translateToLocal("container.inventory"), 8, ySize - 96 + 2, 4210752); fontRenderer.drawString(ClientProxy.KEY_AMULET_1.getDisplayName(), 72, 26, 4210752); fontRenderer.drawString(ClientProxy.KEY_AMULET_2.getDisplayName(), 90, 44, 4210752); fontRenderer.drawString(ClientProxy.KEY_AMULET_3.getDisplayName(), 108, 62, 4210752); } @Override protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) { // draw your Gui here, only thing you need to change is the path GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.mc.renderEngine.bindTexture(guiTextures); int x = (width - xSize) / 2; int y = (height - ySize) / 2; this.drawTexturedModalRect(x, y, 0, 0, xSize, ySize); } }
gpl-3.0
zeddarn/yinoerp
_protected/common/modules/session/controllers/DefaultController.php
349
<?php namespace common\modules\session\controllers; use yii\web\Controller; /** * Default controller for the `session` module */ class DefaultController extends Controller { /** * Renders the index view for the module * @return string */ public function actionIndex() { return $this->render('index'); } }
gpl-3.0
Angerona/angerona-framework
fw/src/main/java/com/github/angerona/fw/serialize/BeliefbaseConfigImport.java
1945
package com.github.angerona.fw.serialize; import java.io.File; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Root; import org.simpleframework.xml.core.Resolve; /** * An implementation of the belief base configuration file as a reference to another file. * It uses the following form: * * <beliefbase-config source="filename.xml" /> * * It is used by simple xml internally to load the * belief base configuration file. * * @author Tim Janus */ @Root(name="beliefbase-config") public class BeliefbaseConfigImport implements BeliefbaseConfig { @Attribute(name="source") protected File source; @Resolve public BeliefbaseConfig substitute() throws Exception { return SerializeHelper.get().loadXml(BeliefbaseConfigReal.class, source); } @Override public String getBeliefbaseClassName() { throw new IllegalStateException("Method not supported."); } @Override public String getName() { throw new IllegalStateException("Method not supported."); } @Override public OperationSetConfig getReasoners() { throw new IllegalStateException("Method not supported."); } @Override public OperationSetConfig getChangeOperators() { throw new IllegalStateException("Method not supported."); } @Override public OperationSetConfig getTranslators() { throw new IllegalStateException("Method not supported."); } @Override public String getViewOn() { throw new IllegalStateException("Method not supported."); } @Override public String getDescription() { throw new IllegalStateException("Method not supported."); } @Override public String getResourceType() { throw new IllegalStateException("Method not supported."); } @Override public String getCategory() { throw new IllegalStateException("Method not supported."); } @Override public BeliefOperatorFamilyConfig getBeliefOperatorFamily() { throw new IllegalStateException("Method not supported."); } }
gpl-3.0
athrane/bassebombecraft
src/main/java/bassebombecraft/operator/Operators2.java
3624
package bassebombecraft.operator; import static bassebombecraft.BassebombeCraft.getBassebombeCraft; import static bassebombecraft.ModConstants.MOD_PKG_NAME; import static java.util.Arrays.asList; import java.util.function.Function; import org.apache.logging.log4j.Logger; /** * Class for execution of operator. */ public class Operators2 { static final String OPERATORS2_CLASS = "bassebombecraft.operator.Operators2"; /** * Execute operator. * * @param ports input ports * @param opertor operator to execute. */ public static void run(Ports ports, Operator2 operator) { try { if (ports.isDebugEnabled()) logInvocation(operator, ports); operator.run(ports); } catch (Exception e) { getBassebombeCraft().reportAndLogException(e); } } /** * Execute operators. * * Operators are executed in sequence. * * If an executed operator set the result port to failed (i.e. false) then the * execution of the sequence is aborted. * * @param ports input ports * @param opertor operators executed in sequence. */ public static void run(Ports ports, Operator2... operators) { for (Operator2 op : operators) { run(ports, op); if (!ports.getResult()) break; } } /** * Validates that object isn't null. Intended to be use to value operator input * parameter: <blockquote> * * <pre> * Entity source = fnGetSource.apply(ports); * Operators2.validateNotNull(source); * </pre> * * </blockquote> * * @param obj the object reference to check for nullity * @param <T> the type of the reference * @param ports the ports * * @return {@code obj} if not {@code null} * * @throws UndefinedOperatorInputException if {@code obj} is {@code null} */ public static <T> T validateNotNull(T obj, Function<? extends Ports, T> fn, Ports ports) { if (obj == null) { // create message StringBuilder builder = new StringBuilder(); builder.append("Validation failed for function: "); builder.append(fn.toString()); builder.append(" "); builder.append(ports.toString()); // throw exception throw new UndefinedOperatorInputException(builder.toString()); } return obj; } /** * Apply function and validate returned values isn't null. * * @param <T> the type of the return value of the function. * @param fn function which is applied. * @param ports ports which is used as input to the function. * * @return return value of the applied function * * @throws UndefinedOperatorInputException if function returns null. */ public static <T> T applyV(Function<Ports, T> fn, Ports ports) { T retVal = fn.apply(ports); validateNotNull(retVal, fn, ports); return retVal; } /** * Logs method prior to operator invocation. * Information is logged with debug log statements. * * @param operator invoked operator. * @param ports ports object used to invoke function. */ public static void logInvocation(Operator2 operator, Ports ports) { Logger logger = getBassebombeCraft().getLogger(); logger.debug(""); logger.debug("OPERATOR: " + operator); logger.debug("-> Call sequence:"); // log invoked operators StackTraceElement[] ste = Thread.currentThread().getStackTrace(); asList(ste).stream().filter(e -> e.getClassName().contains(MOD_PKG_NAME)) .filter(e -> !e.getClassName().contains(OPERATORS2_CLASS)).forEach(logger::debug); // log ports logger.debug("-> Ports: " + ports.toString()); } }
gpl-3.0
doricke/IBio
db/migrate/20131217194535_create_ancestries.rb
391
class CreateAncestries < ActiveRecord::Migration def change create_table :ancestries do |t| t.integer :individual_id t.integer :instrument_id t.integer :itype_id t.integer :ethnic_id t.float :percent end # do end # change def self.up add_index :ancestries, [:individual_id], :name => :idx_ancestries_individual end # up end # class
gpl-3.0
palibaacsi/ask
wp-content/plugins/admin-page-framework/library/apf/factory/_common/form/field_type/AdminPageFramework_FieldType_default.php
980
<?php /** Admin Page Framework v3.7.15 by Michael Uno Generated by PHP Class Files Script Generator <https://github.com/michaeluno/PHP-Class-Files-Script-Generator> <http://en.michaeluno.jp/admin-page-framework> Copyright (c) 2013-2016, Michael Uno; Licensed under MIT <http://opensource.org/licenses/MIT> */ class AdminPageFramework_FieldType_default extends AdminPageFramework_FieldType { public $aDefaultKeys = array(); public function _replyToGetField($aField) { return $aField['before_label'] . "<div class='admin-page-framework-input-label-container'>" . "<label for='{$aField['input_id']}'>" . $aField['before_input'] . ($aField['label'] && !$aField['repeatable'] ? "<span class='admin-page-framework-input-label-string' style='min-width:" . $this->sanitizeLength($aField['label_min_width']) . ";'>" . $aField['label'] . "</span>" : "") . $aField['value'] . $aField['after_input'] . "</label>" . "</div>" . $aField['after_label']; } }
gpl-3.0
EasyinnovaSL/DPFManager
src/main/java/dpfmanager/shell/modules/server/core/HttpServerInitializer.java
2021
/** * <h1>HttpServerInitializer.java</h1> <p> This program is free software: you can redistribute it * and/or modify it under the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any later version; or, * at your choice, under the terms of the Mozilla Public License, v. 2.0. SPDX GPL-3.0+ or MPL-2.0+. * </p> <p> 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 and the Mozilla Public License for more details. </p> * <p> You should have received a copy of the GNU General Public License and the Mozilla Public * License along with this program. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a> * and at <a href="http://mozilla.org/MPL/2.0">http://mozilla.org/MPL/2.0</a> . </p> <p> NB: for the * © statement, include Easy Innova SL or other company/Person contributing the code. </p> <p> © * 2015 Easy Innova, SL </p> * * @author Adria Llorens * @version 1.0 * @since 23/7/2015 */ package dpfmanager.shell.modules.server.core; import dpfmanager.shell.core.context.DpfContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.ssl.SslContext; public class HttpServerInitializer extends ChannelInitializer<SocketChannel> { private final SslContext sslCtx; private DpfContext context; public HttpServerInitializer(SslContext sslCtx, DpfContext context) { this.sslCtx = sslCtx; this.context = context; } @Override public void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); if (sslCtx != null) { pipeline.addLast(sslCtx.newHandler(ch.alloc())); } // Decider handler pipeline.addLast(new HttpServerHandler(context)); } }
gpl-3.0
DanielNinov/CSharp-OOP-Basics
CSharp OOP Basics - Encapsulation/Lab-1/Properties/AssemblyInfo.cs
1381
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Lab-1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Lab-1")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("447b2702-cc43-4d3e-ad42-e53eefca8d4a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
gpl-3.0
EverCraft/EverAPI
src/main/java/fr/evercraft/everapi/command/sub/EATest.java
12838
/* * This file is part of EverAPI. * * EverAPI 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. * * EverAPI 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 EverAPI. If not, see <http://www.gnu.org/licenses/>. */ package fr.evercraft.everapi.command.sub; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import fr.evercraft.everapi.EACommand; import fr.evercraft.everapi.EAPermissions; import fr.evercraft.everapi.EverAPI; import fr.evercraft.everapi.plugin.command.ESubCommand; import fr.evercraft.everapi.registers.ScoreType; import fr.evercraft.everapi.server.player.EPlayer; public class EATest extends ESubCommand<EverAPI> { public EATest(final EverAPI plugin, final EACommand command) { super(plugin, command, "test"); } public boolean testPermission(final CommandSource source) { return source.hasPermission(EAPermissions.TEST.get()); } public Text description(final CommandSource source) { return Text.of("Commande de test"); } public Collection<String> tabCompleter(final CommandSource source, final List<String> args) throws CommandException { return Arrays.asList(); } public Text help(final CommandSource source) { return Text.builder("/" + this.getName()) .onClick(TextActions.suggestCommand("/" + this.getName())) .color(TextColors.RED) .build(); } public CompletableFuture<Boolean> execute(final CommandSource source, final List<String> args) { EPlayer player = (EPlayer) source; Sponge.getRegistry().getAllOf(ScoreType.class).stream() .forEach(color -> player.sendMessage(color.getId() + " : " + color.getName())); /* Text replace = Text.builder(player.getName()) .onHover(TextActions.showText(TextSerializers.FORMATTING_CODE.deserialize("&cExample"))) .build(); player.sendMessage(Text.builder().append(TextSerializers.FORMATTING_CODE.deserialize("&cHello &a"), replace).build()); TextTemplate template = TextTemplate.of(TextSerializers.FORMATTING_CODE.deserialize("&cHello &a"), TextTemplate.arg("player")); player.sendMessage(template.apply(ImmutableMap.of("player", replace)).build()); String message = "&cHello &a{player}"; player.sendMessage(EFormatString.apply(message, ImmutableMap.of(Pattern.compile("\\{player}"), EReplace.of(replace)))); EAMessages.PLUGINS_URL.sender().replace("{url}", "test &atest").sendTo(player);*/ /*ItemStack skull = ItemStack.of(ItemTypes.SKULL, 1); player.sendMessage("SKULL_TYPE : " + skull.offer(Keys.SKULL_TYPE, SkullTypes.PLAYER).isSuccessful()); player.sendMessage("SKULL_TYPE : " + skull.get(Keys.SKULL_TYPE)); player.sendMessage("REPRESENTED_PLAYER : " + skull.offer(Keys.REPRESENTED_PLAYER, player.getProfile()).isSuccessful());*/ /* player.getWorld().setBiome(player.getLocation().getChunkPosition(), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(0, 0, 0).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(1, 0, 0).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(0, 0, 1).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(1, 0, 1).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(-1, 0, 0).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(0, 0, -1).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(-1, 0, -1).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(1, 0, -1).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.getWorld().setBiome(player.getLocation().getPosition().toInt().add(-1, 0, -1).mul(1, 0, 1), BiomeTypes.ICE_PLAINS); player.sendMessage("EntityTemplate : "); Sponge.getRegistry().getAllOf(EntityTemplate.class).stream() .forEach(flag -> player.sendMessage(" - " + flag.getId() + " : " + flag.getName())); player.sendMessage("EntityTemplate.Property : "); Sponge.getRegistry().getAllOf(EntityTemplate.Property.class).stream() .forEach(flag -> player.sendMessage(" - " + flag.getId() + " : " + flag.getName())); player.sendMessage("FireType : "); Sponge.getRegistry().getAllOf(FireType.class).stream() .forEach(flag -> player.sendMessage(" - " + flag.getId() + " : " + flag.getName()));*/ /*Entity entity = player.getWorld().createEntity(EntityTypes.OCELOT, player.getLocation().getPosition()); if(player.getWorld().spawnEntity(entity, Cause.source(player).build())) { if(entity.offer(Keys.TAMED_OWNER, Optional.of(player.getUniqueId())).isSuccessful()) { player.sendMessage("&aSpawn entity : " + entity.get(Keys.TAMED_OWNER)); } else { player.sendMessage("&4Error : offer"); } } else { player.sendMessage("&4Error : spawn entity"); }*/ /* Sponge.getRegistry().getAllOf(Flag.class).stream() .forEach(color -> player.sendMessage(color.getId() + " : " + color.getName())); player.sendMessage(Text.of(ItemTypes.APPLE.getTranslation())); player.sendMessage(Text.of(ItemTypes.APPLE.getName())); player.sendMessage(Text.of(ItemTypes.APPLE.getId())); player.sendMessage(UtilsItemStack.getName(ItemTypes.APPLE.getTemplate().createStack())); player.sendMessage(EChat.getButtomItem(ItemTypes.APPLE.getTemplate().createStack()));*/ /*player.getWorld().getEntities(entity -> entity.getType().equals(EntityTypes.WOLF)).forEach(entity -> { System.out.println("Angry : " + entity.offer(Keys.DYE_COLOR, DyeColors.GREEN).isSuccessful()); });*/ if (args.size() == 3) { /*Optional<Vector3i> block = player.getViewBlock(); if (!block.isPresent()) { EAMessages.PLAYER_NO_LOOK_BLOCK.sendTo(player); } else { ItemStack item = ItemStack.of(ItemTypes.LOG, 1); item.offer(Keys.TREE_TYPE, TreeTypes.JUNGLE); player.sendMessage(Text.of("item2 : ", item.getItem().getId())); player.giveItem(item); }*/ /*Text text = EChat.of("&aSalut"); player.sendMessage(Text.of("text : ", text)); player.sendMessage(Text.of("plain : ", text.toPlain())); player.sendMessage(Text.of("serialize : ", EChat.serialize(text))); player.sendMessage(Text.of("color : " + text.getColor())); player.sendMessage(Text.of("size : " + text.getChildren().size())); player.sendMessage(Text.of("subtext : ", text.getChildren().get(0))); player.sendMessage(Text.of("subplain : ", text.getChildren().get(0).toPlain())); player.sendMessage(Text.of("subserialize : ", EChat.serialize(text.getChildren().get(0)))); player.sendMessage(Text.of("subcolor : " + text.getChildren().get(0).getColor())); player.sendMessage(Text.of("subsize : " + text.getChildren().get(0).getChildren().size()));*/ /*EPlayer player = (EPlayer) source; EMessageFormat message = EMessageFormat.builder() .chatMessage(new EFormatString("&4chatMessage")) .actionbarStay(60*1000) .actionbarMessage(new EFormatString("&4action Message")) .bossbarStay(60*1000) .bossbarMessage(new EFormatString("&4bossbar Message")) .titleMessage(new EFormatString("&4title Message")) .titleSubMessage(new EFormatString("&4title SubMessage")) .titleStay(60*1000) .build(); player.sendMessage("message.getTitle().isPresent() : " + message.getTitle().isPresent()); if (message.getTitle().isPresent()) { player.sendMessage("Title : " + message.getTitle().get().getMessage().toText()); player.sendMessage("SubTitle : " + message.getTitle().get().getMessage().toText()); } message.sender().sendTo(player);*/ } //source.sendMessage(this.help(source)); return CompletableFuture.completedFuture(false); } /* private boolean commandTest(final EPlayer player) { this.area = (AreaEffectCloud) player.getWorld().createEntity(EntityTypes.AREA_EFFECT_CLOUD, player.getLocation().getPosition()); area.offer(Keys.DISPLAY_NAME, EChat.of("&4Test")); area.offer(Keys.CUSTOM_NAME_VISIBLE, true); area.offer(Keys.AREA_EFFECT_CLOUD_COLOR, Color.GREEN); area.offer(Keys.AREA_EFFECT_CLOUD_RADIUS, 3D); area.offer(Keys.AREA_EFFECT_CLOUD_PARTICLE_TYPE, ParticleTypes.MOB_SPELL); area.offer(Keys.AREA_EFFECT_CLOUD_WAIT_TIME, 0); this.area.offer(Keys.AREA_EFFECT_CLOUD_DURATION, 5000); area.offer(Keys.POTION_EFFECTS, Arrays.asList(PotionEffect.builder().potionType(PotionEffectTypes.JUMP_BOOST).duration(3000).amplifier(3).build())); if(player.getWorld().spawnEntity(area, Cause.source(player).build())) { player.sendMessage("&aSpawn entity"); } else { player.sendMessage("&4Error : spawn entity"); } return false; } private boolean commandTest(final EPlayer player, String name) { if (this.area == null) { this.commandTest(player); } if (name.equals("0")) { player.sendMessage("teleport debut : " + this.area.getLocation().getBlockPosition()); this.area.setTransform(player.getTransform()); player.sendMessage("teleport fin : " + this.area.getLocation().getBlockPosition()); } else if (name.equals("d")) { player.sendMessage("AREA_EFFECT_CLOUD_DURATION : " + this.area.get(Keys.AREA_EFFECT_CLOUD_DURATION).get()); } else if (name.equals("-1")) { player.sendMessage("AREA_EFFECT_CLOUD_DURATION_ON_USE debut : " + this.area.get(Keys.AREA_EFFECT_CLOUD_DURATION_ON_USE).get()); this.area.offer(Keys.AREA_EFFECT_CLOUD_DURATION_ON_USE, 20); player.sendMessage("AREA_EFFECT_CLOUD_DURATION_ON_USE fin : " + this.area.get(Keys.AREA_EFFECT_CLOUD_DURATION_ON_USE).get()); } else if (name.equals("1")) { player.sendMessage("AREA_EFFECT_CLOUD_RADIUS debut : " + this.area.get(Keys.AREA_EFFECT_CLOUD_RADIUS).get()); this.area.offer(Keys.AREA_EFFECT_CLOUD_RADIUS, this.area.get(Keys.AREA_EFFECT_CLOUD_RADIUS).get() + 10); player.sendMessage("AREA_EFFECT_CLOUD_RADIUS fin : " + this.area.get(Keys.AREA_EFFECT_CLOUD_RADIUS).get()); } else if (name.equals("2")) { player.sendMessage("AREA_EFFECT_CLOUD_RADIUS debut : " + this.area.get(Keys.AREA_EFFECT_CLOUD_RADIUS).get()); this.area.offer(Keys.AREA_EFFECT_CLOUD_RADIUS, this.area.get(Keys.AREA_EFFECT_CLOUD_RADIUS).get() - 1); player.sendMessage("AREA_EFFECT_CLOUD_RADIUS fin : " + this.area.get(Keys.AREA_EFFECT_CLOUD_RADIUS).get()); } else if (name.equals("3")) { player.sendMessage("COLOR : RED"); this.area.offer(Keys.COLOR, Color.RED); } else if (name.equals("4")) { player.sendMessage("COLOR : GREEN"); this.area.offer(Keys.COLOR, Color.GREEN); } else if (name.equals("5")) { player.sendMessage("AREA_EFFECT_CLOUD_DURATION : 5000"); this.area.offer(Keys.AREA_EFFECT_CLOUD_DURATION, 5000); } else if (name.equals("6")) { player.sendMessage("AREA_EFFECT_CLOUD_DURATION : 40"); this.area.offer(Keys.AREA_EFFECT_CLOUD_DURATION, 40); } else if (name.equals("7")) { player.sendMessage("POTION_EFFECTS : 5000"); this.area.offer(Keys.POTION_EFFECTS, Arrays.asList(PotionEffect.builder().potionType(PotionEffectTypes.JUMP_BOOST).duration(3000).amplifier(3).build())); } else if (name.equals("8")) { player.sendMessage("POTION_EFFECTS : 40"); this.area.offer(Keys.POTION_EFFECTS, Arrays.asList(PotionEffect.builder().potionType(PotionEffectTypes.GLOWING).duration(3000).amplifier(3).build())); } else if (name.equals("9")) { player.sendMessage("AREA_EFFECT_CLOUD_PARTICLE_TYPE : LAVA"); area.offer(Keys.AREA_EFFECT_CLOUD_PARTICLE_TYPE, ParticleTypes.LAVA); } else if (name.equals("10")) { player.sendMessage("AREA_EFFECT_CLOUD_PARTICLE_TYPE : MOB_SPELL"); area.offer(Keys.AREA_EFFECT_CLOUD_PARTICLE_TYPE, ParticleTypes.MOB_SPELL); } return true; }*/ }
gpl-3.0
TamuGeoInnovation/Tamu.GeoInnovation.GeoReferences.DataImporters.Census
src/Main/Tiger2015/FileLayouts/CountryFiles/Implementations/Cbsa2015File.cs
1901
using USC.GISResearchLab.Common.Census.Tiger2015.FileLayouts.CountryFiles.AbstractClasses; namespace USC.GISResearchLab.Common.Census.Tiger2015.FileLayouts.CountryFiles.Implementations { public class Cbsa2015File : AbstractTiger2015ShapefileCountryFileLayout { public Cbsa2015File(string stateName) : base(stateName) { FileName = "cbsa10.zip"; SQLCreateTable += "CREATE TABLE [" + OutputTableName + "] ("; SQLCreateTable += "csaFp10 varchar(3) DEFAULT NULL,"; SQLCreateTable += "cbsaFp10 varchar(5) DEFAULT NULL,"; SQLCreateTable += "geoId10 varchar(10) DEFAULT NULL,"; SQLCreateTable += "Name10 varchar(100) DEFAULT NULL,"; SQLCreateTable += "NameLsad10 varchar(100) DEFAULT NULL,"; SQLCreateTable += "Lsad10 varchar(2) DEFAULT NULL,"; SQLCreateTable += "memi10 varchar(1) DEFAULT NULL,"; SQLCreateTable += "Mtfcc10 varchar(5) DEFAULT NULL,"; SQLCreateTable += "aLand10 varchar(14) DEFAULT NULL,"; SQLCreateTable += "aWater10 varchar(14) DEFAULT NULL,"; SQLCreateTable += "intPtLat10 varchar(11) DEFAULT NULL,"; SQLCreateTable += "intPtLon10 varchar(12) DEFAULT NULL,"; SQLCreateTable += "shapeType varchar(55), "; SQLCreateTable += "shapeGeog geography,"; SQLCreateTable += "shapeGeom geometry,"; SQLCreateTable += "PRIMARY KEY (geoId10)"; SQLCreateTable += ");"; SQLCreateTableIndexes += " CREATE NONCLUSTERED INDEX [IDX_" + OutputTableName + "geoId10] ON [dbo].[" + OutputTableName + "] (geoId10) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY];"; } } }
gpl-3.0
yujikiriki/rolling_forecast
webapp/test/spec/services/crearproducto.js
367
'use strict'; describe('Service: Crearproducto', function () { // load the service's module beforeEach(module('frontendApp')); // instantiate service var Crearproducto; beforeEach(inject(function (_Crearproducto_) { Crearproducto = _Crearproducto_; })); it('should do something', function () { expect(!!Crearproducto).toBe(true); }); });
gpl-3.0
cb0/LiskPHP
src/lib/Api/Peer/GetPeerVersionResponse.php
1538
<?php /** * LiskPhp - A PHP wrapper for the LISK API * Copyright (c) 2017 Marcus Puchalla <cb0@0xcb0.com> * * LiskPhp 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. * * LiskPhp 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 LiskPhp. If not, see <http://www.gnu.org/licenses/>. */ namespace Lisk\Api\Peer; use Lisk\AbstractResponse; class GetPeerVersionResponse extends AbstractResponse { private $version; private $build; /** * @return mixed */ public function getVersion() { return $this->version; } /** * @param mixed $version */ public function setVersion($version) { $this->version = $version; } /** * @return mixed */ public function getBuild() { return $this->build; } /** * @param mixed $build */ public function setBuild($build) { $this->build = $build; } public function success($jsonResponse) { $this->version = $jsonResponse['version']; $this->build = $jsonResponse['build']; } }
gpl-3.0
SuperSimpleGuy/dytenjin
Dytenjin/src/core/geography/GeographicalLocation.java
7038
/* * Dytenjin is an engine for making dynamic text-based java games. * Copyright (C) 2012 SuperSimpleGuy * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package core.geography; import java.util.HashMap; import core.entities.Entity; import core.management.game.IHasUniqueId; import core.management.game.UniqueId; import core.management.ingame.AspectManager; /** * Represents a geographical location that entities can occupy and own. * Has certain aspects depending on the kind of location a subclass * instantiates. * @author SuperSimpleGuy */ public abstract class GeographicalLocation implements IHasUniqueId { private GeographicalRegion parent; private UniqueId id; private String name; private AspectManager aspMan; private int xCoord; private int yCoord; protected HashMap<Integer, LocationLink> paths; protected Entity owner; /** * The constructor for a geographical location, completely * isolated (containing no adjacent links), with a name, a * unique id, an x and y coordinate of this location, * predefined aspects and a parent GeographicalRegion. It * starts off with no owning Entity. * @param name the name of this Geo Location * @param id the unique id of this Geo Location * @param xCoord the x coordinate of this Geo Location * @param yCoord the y coordinate of this Geo Location * @param aspMan the AspectManager for this Geo Location * @param parent the parent Geo Region for this Geo Location */ public GeographicalLocation(String name, UniqueId id, int xCoord, int yCoord, AspectManager aspMan, GeographicalRegion parent) { this.id = id; this.xCoord = xCoord; this.yCoord = yCoord; this.setName(name); this.aspMan = aspMan; this.setParent(parent); paths = new HashMap<Integer, LocationLink>(); owner = null; } /** * Given a link id, returns the cardinal direction towards * that LocationLink * @param id the id of the Location Link * @return the CardinalDirection towards that LocationLink */ public CardinalDirection getDirToPath(int id) { LocationLink temp = this.paths.get(id); if (temp != null) { return temp.getDirFromGeoLoc(this); } else { return CardinalDirection.ERR; } } /** * Given a link id, returns the cardinal direction from * that LocationLink * @param id the id of the Location Link * @return the CardinalDirection from that LocationLink */ public CardinalDirection getDirFromPath(int id) { LocationLink temp = this.paths.get(id); if (temp != null) { return temp.getDirToGeoLoc(this); } else { return CardinalDirection.ERR; } } /** * Removes a link with the unique id passed as a parameter, * returning the link or null if none was found * @param id the id of the link to remove * @return the link with the unique id, or null if no link * was found */ public LocationLink unregisterLocationLink(int id) { return paths.remove(id); } /** * Returns a location link from its unique id, or null if no * entry exists for that id * @param id the unique id of the LocationLink * @return the LocationLink object with the unique id, or null * if no id was found */ public LocationLink getPathById(int id) { return paths.get(id); } /** * Adds a location link, returning true if the addition * was successful and false otherwise * @param l the link to add * @return true if the link was successfully added, false * otherwise */ public boolean registerLocationLink(LocationLink l) { if (!paths.containsKey(l.getUniqueId().getId())) { paths.put(l.getUniqueId().getId(), l); return true; } return false; } /** * Returns this location's regional parent * @return the GeographicalRegion parent */ public GeographicalRegion getParent() { return parent; } /** * The GeographicalLocation will call upon its parent * to remove itself, which will also remove any linking * LocationLinks from the parent as well */ public void removeSelfFromParent() { for (LocationLink l : paths.values()) { l.removeSelfFromParent(); this.unregisterLocationLink(l.getUniqueId().getId()); } if (parent != null) { parent.unregisterChildLoc(this.getUniqueId().getId()); } } /** * Sets this location's regional parent * @param parent the new GeographicalRegion parent */ public void setParent(GeographicalRegion parent) { this.parent = parent; } /** * Returns the name of this location * @return the name of this location */ public String getName() { return name; } /** * Sets the name of this location * @param name the new name of this location */ public void setName(String name) { this.name = name; } /** * Returns this location's aspects * @return the AspectManager for this location */ public AspectManager getAspect() { return aspMan; } /** * Returns a HashMap of links connecting this location * to other locations * @return the HashMap of connected links */ public HashMap<Integer, LocationLink> getPaths() { return paths; } /** * Returns the current owning entity of this location * @return the current owning entity of this location */ public Entity getOwner() { return owner; } /** * Sets the current owning entity of this location * @param owner the new owning entity of this location */ public void setOwner(Entity owner) { this.owner = owner; } @Override public UniqueId getUniqueId() { return id; } /** * Returns this location's x coordinate * @return this location's x coordinate */ public int getxCoord() { return xCoord; } /** * Returns this location's y coordinate * @return this location's y coordinate */ public int getyCoord() { return yCoord; } @Override public boolean equals(Object other) { if (!(other instanceof GeographicalLocation)) { return false; } GeographicalLocation gL = (GeographicalLocation)other; return this.id.equals(gL.getUniqueId()); } /** * Sets the coordinates for this GeographicalLocation, which * then updates the lengths of all adjacent paths. * @param newXCoord the new x coordinate for this location * @param newYCoord the new y coordinate for this location */ public void setCoords(int newXCoord, int newYCoord) { this.xCoord = newXCoord; this.yCoord = newYCoord; for (LocationLink rL : paths.values()) { rL.resetDirectionAndLength(); } } }
gpl-3.0
MarkusHackspacher/PythonFarmGame
farmlib/__init__.py
806
from __future__ import absolute_import import os import pygame from farmlib.dictmapper import DictMapper from farmlib.pluginsystem import base_plugin_system as PluginSystem # SETTINGS rules = DictMapper() rules.load(os.path.join("data", "rules.json")) images = DictMapper() images.load(os.path.join("data", "images.json")) __VERSION__ = rules["VERSION"] # init plugin system pygame.font.init() pygame.mixer.init() filename = os.path.join("data", "sounds", "click.wav") if os.path.isfile(filename): clickfilename = filename elif os.path.isfile(os.path.join('..', filename)): clickfilename = os.path.join('..', filename) else: # handle error in a way that doesn't make sphinx crash print("ERROR: No such file: '{}'".format(filename)) clicksound = pygame.mixer.Sound(clickfilename)
gpl-3.0
mojo2012/factorio-mojo-resource-processing
prototypes/item/ore-processing/ore-zinc.lua
1130
require("ore-general") -- item definitions data:extend({ { type= "item", name= "ore-zinc-crushed", icon = "__mojo-resource-processing__/graphics/icons/ore-zinc/crushed-ore-zinc.png", flags= { "goes-to-main-inventory" }, subgroup = "zinc", order = "f[ore-zinc-crushed]", stack_size= 50, }, { type= "item", name= "ore-zinc-pulverized", icon = "__mojo-resource-processing__/graphics/icons/ore-zinc/pulverized-ore-zinc.png", flags= { "goes-to-main-inventory" }, subgroup = "zinc", order = "f[ore-zinc-pulverized]", stack_size= 50, } }) -- item subgroup definition data:extend({ { type = "item-subgroup", name = "zinc", group = "intermediate-products", order = "b2" } }) data.raw.item["zinc-ore"].subgroup = "zinc" -- Minable ressources data.raw["resource"]["zinc-ore"].minable.result = nil data.raw["resource"]["zinc-ore"].minable.results = { ressourceItemMinMaxProb("zinc-ore", 1, 1, 0.9), -- 1 item at percentage 0.9 -- ressourceItemMinMaxProb("gravel", 1, 1, 0.45), ressourceItemMinMaxProb("dirt", 1, 1, 0.4) }
gpl-3.0
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtcharts/examples/charts/zoomlinechart/main.cpp
2399
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Charts module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "chart.h" #include "chartview.h" #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> #include <QtCore/QtMath> #include <QtCharts/QLineSeries> #include <QtCharts/QValueAxis> QT_CHARTS_USE_NAMESPACE int main(int argc, char *argv[]) { QApplication a(argc, argv); //![1] QLineSeries *series = new QLineSeries(); for (int i = 0; i < 500; i++) { QPointF p((qreal) i, qSin(M_PI / 50 * i) * 100); p.ry() += qrand() % 20; *series << p; } //![1] Chart *chart = new Chart(); chart->addSeries(series); chart->setTitle("Zoom in/out example"); chart->setAnimationOptions(QChart::SeriesAnimations); chart->legend()->hide(); chart->createDefaultAxes(); ChartView *chartView = new ChartView(chart); chartView->setRenderHint(QPainter::Antialiasing); QMainWindow window; window.setCentralWidget(chartView); window.resize(400, 300); window.grabGesture(Qt::PanGesture); window.grabGesture(Qt::PinchGesture); window.show(); return a.exec(); }
gpl-3.0
d/ballin-octo-shame
Yo_test.cc
145
// // Created by Pivotal Data on 3/23/15. // #include "Yo.h" #include "gtest/gtest.h" TEST(YoTest, BarIsZero) { EXPECT_EQ(0, Yo().Bar()); }
gpl-3.0
xvusrmqj/algorithms
JavaInterview/src/java基础/GUI/TestSwing.java
1068
package java基础.GUI; import java.awt.BorderLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextField; public class TestSwing { public static void main(String[] args) { createDialogUseJOptionPane(); } private static void createWindow(){ JFrame f = new JFrame("jframe..."); String currentPath = TestSwing.class.getResource("").getPath(); Icon icon = new ImageIcon(currentPath+"true.png" );//FIXME 不知道为什么这里设置icon不起作用 JButton b = new JButton("btn", icon); f.add(b,BorderLayout.NORTH); f.add(new JButton("btn"),BorderLayout.CENTER); f.add(new JTextField("textfield"),BorderLayout.SOUTH); f.setBounds(30,30,250,250); f.setVisible(true); } private static void createDialogUseJOptionPane(){ String msg = JOptionPane.showInputDialog("pleaseInput"); JOptionPane.showMessageDialog(null, msg); JOptionPane.showConfirmDialog(null, "1+1=2? please confirm"); } }
gpl-3.0
lczech/genesis
lib/genesis/population/formats/variant_parallel_input_iterator.cpp
29469
/* Genesis - A toolkit for working with phylogenetic data. Copyright (C) 2014-2021 Lucas Czech This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Lucas Czech <lczech@carnegiescience.edu> Department of Plant Biology, Carnegie Institution For Science 260 Panama Street, Stanford, CA 94305, USA */ /** * @brief * * @file * @ingroup population */ #include "genesis/population/formats/variant_parallel_input_iterator.hpp" #include <algorithm> #include <cassert> #include <iterator> #include <numeric> #include <stdexcept> namespace genesis { namespace population { // ================================================================================================= // Iterator Constructors and Rule of Five // ================================================================================================= VariantParallelInputIterator::Iterator::Iterator( VariantParallelInputIterator* generator ) : generator_(generator) { // We use the generator as a check if this Iterator is intended // to be a begin() or end() iterator. // We could also just use the default constructor to create end() iterators, // this would have the same effect. if( ! generator_ ) { return; } // If the generator is valid, initialize our input sources and start iterating them. // Init the iterators and variant storage. iterators_.reserve( generator_->inputs_.size() ); variant_sizes_.reserve( generator_->inputs_.size() ); for( size_t i = 0; i < generator_->inputs_.size(); ++i ) { iterators_.emplace_back( generator_->inputs_[i].begin() ); // We now have stored the iterator and called its begin() function, // which in the LambdaIterator already obtains the first element. // We use this to get the number of BaseCounts objects in the Variant. // We will later need this to default-construct that many BaseCounts // for positions where this iterator does not have data. // If the iterator does not have any data at all, we store that as well. if( iterators_[i] ) { variant_sizes_.push_back( iterators_[i]->samples.size() ); // Let's make sure that the first position is a valid chromosome and // position. Later, when we advance the iterator, we repeat the check // for every locus we go to as well, just to be sure. assert_correct_chr_and_pos_( iterators_[i] ); } else { variant_sizes_.push_back( 0 ); } } // We use the sum of all to allocate memory for effciency. Let's compute that sum once. variant_size_sum_ = std::accumulate( variant_sizes_.begin(), variant_sizes_.end(), decltype( variant_sizes_ )::value_type( 0 ) ); // Init with default constructed Variants. variants_.resize( generator_->inputs_.size() ); // Make sure all have the same size. assert( iterators_.size() == generator_->inputs_.size() ); assert( iterators_.size() == variants_.size() ); assert( iterators_.size() == variant_sizes_.size() ); // Lastly, start with the additional carrying loci. carrying_locus_it_ = generator_->carrying_loci_.cbegin(); // Now go to the first locus we want. advance_(); } // ================================================================================================= // Iterator Accessors // ================================================================================================= Variant VariantParallelInputIterator::Iterator::joined_variant( bool allow_ref_base_mismatches, bool allow_alt_base_mismatches, bool move_samples ) { assert( iterators_.size() == variants_.size() ); assert( iterators_.size() == variant_sizes_.size() ); assert( iterators_.size() == generator_->inputs_.size() ); // Prepare the result. Variant res; res.chromosome = current_locus_.chromosome; res.position = current_locus_.position; res.samples.reserve( variant_size_sum_ ); // Special edge case: No inputs at all. if( variants_.empty() ) { return res; } assert( variants_.size() > 0 ); assert( variant_sizes_.size() > 0 ); // Not all variants might have data; some might be the empty optional. // We hence need to keep track of whether we already initialized our result or not. // This only concernes the ref and alt base fields. bool bases_init = false; // Go through all variants, and for those that have data, check the data correctness, // and add them to the result. for( size_t i = 0; i < variants_.size(); ++i ) { // If the variant has data, use it. if( variants_[i] ) { // We already check all of the below when adding the data to variants_. // Still, assert that this is all good. assert( variants_[i]->chromosome == res.chromosome ); assert( variants_[i]->position == res.position ); assert( variants_[i]->samples.size() == variant_sizes_[i] ); // Set and check the ref and alt bases. // This is the first input that has data here. Use it to initialize the bases. if( ! bases_init ) { res.reference_base = variants_[i]->reference_base; res.alternative_base = variants_[i]->alternative_base; bases_init = true; } // Now check that all inputs have the same bases. if( res.reference_base != variants_[i]->reference_base ) { if( allow_ref_base_mismatches ) { res.reference_base = 'N'; } else { throw std::runtime_error( "Mismatching reference bases while iterating input sources in parallel at " + current_locus_.to_string() + ". Some sources have base '" + std::string( 1, res.reference_base ) + "' while others have '" + std::string( 1, variants_[i]->reference_base ) + "'." ); } } if( res.alternative_base != variants_[i]->alternative_base ) { if( allow_alt_base_mismatches ) { res.alternative_base = 'N'; } else { throw std::runtime_error( "Mismatching alternative bases while iterating input sources in parallel at " + current_locus_.to_string() + ". Some sources have base '" + std::string( 1, res.alternative_base ) + "' while others have '" + std::string( 1, variants_[i]->alternative_base ) + "'." ); } } // Now move or copy the samples. The reserve calls in the following are not necessary, // as we already allocate enough capacity above. We keep them here for future reference. if( move_samples ) { // res.samples.reserve( res.samples.size() + variants_[i]->samples.size() ); std::move( std::begin( variants_[i]->samples ), std::end( variants_[i]->samples ), std::back_inserter( res.samples ) ); variants_[i]->samples.clear(); } else { // res.samples.reserve( res.samples.size() + variants_[i]->samples.size() ); std::copy( std::begin( variants_[i]->samples ), std::end( variants_[i]->samples ), std::back_inserter( res.samples ) ); } } else { // If the variant has no data, put as many dummy samples with empty BaseCounts // into the result as the input source has samples in its data positions. // res.samples.reserve( res.samples.size() + variant_sizes_[i].size() ); for( size_t k = 0; k < variant_sizes_[i]; ++k ) { res.samples.emplace_back(); } } } // If none of the input sources had data, that means that we are currently at an // additional carrying locus. Check this. We do not need to do anything else, // as the resulting Variant already contains all the information that we have at hand. assert( bases_init || ( carrying_locus_it_ != generator_->carrying_loci_.cend() && locus_equal( *carrying_locus_it_, current_locus_ ) ) ); // Make sure that the number of samples is the same as the sum of all sample sizes // in the variant_sizes_ vector combined. assert( res.samples.size() == variant_size_sum_ ); // Done. Return the merged result. return res; } // ================================================================================================= // Iterator Internal Members // ================================================================================================= // ------------------------------------------------------------------------- // advance_using_carrying_() // ------------------------------------------------------------------------- void VariantParallelInputIterator::Iterator::advance_using_carrying_() { // Candidate locus. We look for the earliest position of the carrying iterators, // as this is the next one we want to go to. GenomeLocus cand_loc; // Go through all carrying iterators and find the earliest next position of any of them. assert( iterators_.size() == generator_->selections_.size() ); for( size_t i = 0; i < iterators_.size(); ++i ) { auto& iterator = iterators_[i]; if( ! iterator || generator_->selections_[i] != ContributionType::kCarrying ) { continue; } // In all iterators, we already have moved on to at least the current position. // This assumes that all of the inputs are properly sorted. We check this in // increment_iterator_() // This also works for the very first time this function is called (in the iterator // constructor), as the iterator will then also compare greater than the // current_locus_, which is empty at this point. assert( locus_greater_or_equal( iterator->chromosome, iterator->position, current_locus_ )); // If this iterator is currently one of the ones that contain the current // position, it's time to move on now. If not, we already asserted that it is // greater, which means, it it still waiting for its turn, so nothing to do now. if( locus_equal( iterator->chromosome, iterator->position, current_locus_ )) { increment_iterator_( iterator ); // We might now be done with this input source. if( ! iterator ) { continue; } } // Now comes the part where we find the earliest position that we want to stop at. // Stop at the earliest postion of any iterator of type carrying (all of its positions // need to be included), or if we are in the first iteration of the loop. if( cand_loc.empty() || locus_less( iterator->chromosome, iterator->position, cand_loc ) ) { cand_loc = GenomeLocus{ iterator->chromosome, iterator->position }; } } // If there are additional carrying loci, use them to find the candidate as well. assert( generator_ ); if( carrying_locus_it_ != generator_->carrying_loci_.cend() ) { // All the assertions from above apply here as well. assert( ! carrying_locus_it_->empty() ); assert( locus_greater_or_equal( *carrying_locus_it_, current_locus_ ) ); // If the carrying locus is at the current locus, we need to move it forward, // same as above. if( locus_equal( *carrying_locus_it_, current_locus_ ) ) { ++carrying_locus_it_; } // Now, if it still is not at its end, we can use it as a candidate as well, // if it is earlier than the current input source based candidate (of it the candidate // is empty, which for example happens if all input sources are following, or if all // inputs have already reached their end). if( carrying_locus_it_ != generator_->carrying_loci_.cend() && ( cand_loc.empty() || locus_less( *carrying_locus_it_, cand_loc ) ) ) { cand_loc = *carrying_locus_it_; } } // If we have not set any candidate locus, that means that all carrying iterators // are at their end. Time to wrap up then. if( cand_loc.empty() ) { assert( generator_ ); assert( generator_->has_carrying_input_ ); // Assert that indeed all carrying iterators are at their end. assert( [&](){ for( size_t i = 0; i < iterators_.size(); ++i ) { if( generator_->selections_[i] == ContributionType::kCarrying && iterators_[i] ) { return false; } } return true; }() ); // Also, we must have reached the end of the additional carrying loci, // otherwise we would have found a candidate from there. assert( carrying_locus_it_ == generator_->carrying_loci_.cend() ); // We are done here. generator_ = nullptr; return; } // We have found a new locus. It needs to be further down from the current // (again this also works in the first call of this function, when current is empty). assert( cand_loc > current_locus_ ); // Now that we found the next position to go to, move _all_ iterators to it // (or the next one beyond, if it does not have that position). for( size_t i = 0; i < iterators_.size(); ++i ) { auto& iterator = iterators_[i]; // Nothing to do if the iterator is already at its end. if( ! iterator ) { continue; } // Same assertion as above, this time for all of them, just to be sure. assert( locus_greater_or_equal( iterator->chromosome, iterator->position, current_locus_ )); // Now move the iterator until we reach the candidate, or one beyond. // For carrying iterators, this loop can only get called once at max (or not at all, // if this source is already at or beyond the candidate from the loop above), // as we never want to skip anything in a carrying iterator. Assert this. size_t cnt = 0; while( iterator && locus_less( iterator->chromosome, iterator->position, cand_loc )) { increment_iterator_( iterator ); ++cnt; } (void) cnt; assert( generator_->selections_[i] != ContributionType::kCarrying || cnt <= 1 ); } // Finally, update the current locus, and set the variants according to the iterators. // The order of these is imporant, as the latter needs the former to be set. current_locus_ = cand_loc; update_variants_(); } // ------------------------------------------------------------------------- // advance_using_only_following_() // ------------------------------------------------------------------------- void VariantParallelInputIterator::Iterator::advance_using_only_following_() { // If this function is called, we only have following iterators, // so there are no addtional carrying loci given. assert( carrying_locus_it_ == generator_->carrying_loci_.cend() ); assert( generator_->carrying_loci_.empty() ); // Once one of the iterators reaches its end, we are done, as then there cannot // be any more intersections. bool one_at_end = false; // If this is not the first call of this function (the one that is done in the constructor // of the iterator), move all iterators at least once, to get away from the current locus. assert( iterators_.size() == generator_->selections_.size() ); if( ! current_locus_.empty() ) { for( size_t i = 0; i < iterators_.size(); ++i ) { auto& iterator = iterators_[i]; // This function is only ever called if all inputs are of type following. assert( generator_->selections_[i] == ContributionType::kFollowing ); // As we are doing the intersection of all iterators here, none of them can be at the // end right now. If one were, we would already have reached the end of our // parallel iteration before, and never entered this function. assert( iterator ); // In all iterators, we must be at the current locus, as this is only intersections. // So now, it's time to move on once. Then, go to the next iterator. // The rest of this loop is not needed in this first round. assert( locus_equal( iterator->chromosome, iterator->position, current_locus_ )); increment_iterator_( iterator ); // Check if we are done with this iterator. If so, we are completely done, // no need to do anything else here. if( ! iterator ) { one_at_end = true; break; } } } // Candidate locus. We look for the earliest locus that all inputs share. GenomeLocus cand_loc; // Loop until we have found a locus that all iterators share, // or until one of them is at the end (in which case, there won't be any more intersections // and we are done with the parallel iteration). bool found_locus = false; while( ! found_locus && ! one_at_end ) { // Assume that we are done. Below, we will reset these if we are not in fact done. found_locus = true; // Try to find the candidate in all inputs. for( size_t i = 0; i < iterators_.size(); ++i ) { auto& iterator = iterators_[i]; // This function is only ever called if all inputs are of type following. assert( generator_->selections_[i] == ContributionType::kFollowing ); // If the iterator is already at its end, we are done here. // This case can here only occur if we have an empty input source, // in which case the call to adanvance_() made from the constructor lead us here. // We assert that this is indeed the first call of this function by using the // current_element_ as a check. if( ! iterator ) { assert( current_locus_.empty() ); one_at_end = true; break; } // Init the candidate. This happens in the first iteration of the for loop. if( cand_loc.empty() ) { assert( i == 0 ); cand_loc = GenomeLocus{ iterator->chromosome, iterator->position }; } // If the iterator is behind the candidate, move it forward until it either catches // up, or overshoots the locus, or reaches its end. while( iterator && locus_less( iterator->chromosome, iterator->position, cand_loc )) { increment_iterator_( iterator ); } // If the iterator reached its end now, we are done here. // No more intersections can occur, we can leave the whole thing. if( ! iterator ) { one_at_end = true; break; } // If we have an overshoot, the candidate is not good, as this means that not all // inputs have that locus (as exemplified by that overshoot). In that case, // we store the new candidate, and leave the loop. It does not really matter here // if we go on to the next input, or just start the whole outer loop again. // Let's keep the pace and continue with the next input. assert( iterator ); if( locus_greater( iterator->chromosome, iterator->position, cand_loc )) { cand_loc = GenomeLocus{ iterator->chromosome, iterator->position }; found_locus = false; continue; // or break for the alternative loop order } // If we are here, we have reached the candidate locus. assert( iterator ); assert( locus_equal( iterator->chromosome, iterator->position, cand_loc )); } } // Only one of the exit conditions can be true (unless there is no input at all). assert( iterators_.size() == 0 || ( found_locus ^ one_at_end )); // If we have not found any locus, that means that at least one of the iterators is at its end. // No more intersections can occur. Time to wrap up then. if( one_at_end ) { assert( ! generator_->has_carrying_input_ ); generator_ = nullptr; // Assert that exactly one is at its end. Theoretically, in our search, other iterators // might also have been about to reach their end, but as we immediately exit the above // loop once we find an end, these are not incremented to their end yet. assert( [&](){ size_t at_end_cnt = 0; for( size_t i = 0; i < iterators_.size(); ++i ) { if( ! iterators_[i] ) { ++at_end_cnt; } } return at_end_cnt == 1; }() ); // We have indicated our end by nulling generator_. Nothing more to do. return; } // If we are here, we have found a good new locus. It needs to be further down from the current // (again this also works in the first call of this function, when current is empty). assert( iterators_.size() == 0 || cand_loc > current_locus_ ); // Assert that all are at the given locus, and not at their end. assert( iterators_.size() == 0 || found_locus ); assert( [&](){ for( size_t i = 0; i < iterators_.size(); ++i ) { auto const& iterator = iterators_[i]; if( ! iterator || ! locus_equal( iterator->chromosome, iterator->position, cand_loc )) { return false; } } return true; }() ); // Finally, update the current locus, and set the variants according to the iterators. // The order of these is imporant, as the latter needs the former to be set. current_locus_ = cand_loc; update_variants_(); } // ------------------------------------------------------------------------- // increment_iterator_() // ------------------------------------------------------------------------- void VariantParallelInputIterator::Iterator::increment_iterator_( VariantInputIterator::Iterator& iterator ) { // If we already reached the end, do nothing. // if( ! iterator ) { // return; // } // // Nope, this function should never be called on a finished iterator. assert( iterator ); // We here check that the iterator is in chrom/pos order. This is also already done // by default in most of our file format iterators, and we here need an expensive // string copy just for this one check, but it feels like this is necessary to be // on the safe side. After all, this parallel iterator here is a bit tricky anyway, // so we have to live with that cost. auto const prev_loc = GenomeLocus{ iterator->chromosome, iterator->position }; // Now do the increment and check whether we are done with this source. ++iterator; if( ! iterator ) { return; } // Check that it is has a valid chromosome and position, and // make sure that the input is sorted. assert_correct_chr_and_pos_( iterator ); if( locus_less_or_equal( iterator->chromosome, iterator->position, prev_loc )) { throw std::runtime_error( "Cannot iterate multiple input sources in parallel, as (at least) " "one of them is not sorted by chromosome and position. " "Offending input source: " + iterator.data().source_name + " at " + iterator->chromosome + ":" + std::to_string( iterator->position ) ); } } // ------------------------------------------------------------------------- // assert_correct_chr_and_pos_() // ------------------------------------------------------------------------- void VariantParallelInputIterator::Iterator::assert_correct_chr_and_pos_( VariantInputIterator::Iterator const& iterator ) { assert( iterator ); // This is checked already in our file format iterators, but we heavily depend // on this here, so let's check it. if( iterator->chromosome.empty() || iterator->position == 0 ) { throw std::runtime_error( "Cannot iterate multiple input sources in parallel, as (at least) " "one of them has an invalid chromosome (empty name) or position (0). " "Offending input source: " + iterator.data().source_name + " at " + iterator->chromosome + ":" + std::to_string( iterator->position ) ); } } // ------------------------------------------------------------------------- // update_variants_() // ------------------------------------------------------------------------- void VariantParallelInputIterator::Iterator::update_variants_() { assert( iterators_.size() == variants_.size() ); for( size_t i = 0; i < iterators_.size(); ++i ) { auto& iterator = iterators_[i]; // If the iterator is already finished, we store an empty optional variant. if( ! iterator ) { variants_[i] = utils::nullopt; continue; } // If the iterator is at the current locus, we store its data here, // so that users can access it. If not, we store an empty optional variant. if( locus_equal( iterator->chromosome, iterator->position, current_locus_ )) { // We ideally want to move all data here, for efficiency. // The user does not have access to the iterators, so this is okay. // We however cannot move all the data, as we will later need access to the // chromosome and position of the iterators; so instead, we only move the expensive // BaseCounts samples. In order to avoid that when we add more elements to Variant later // and then accidentally forget to also set them here, we do a three-step process where // we move the BaseCounts over to a temp location first, and then copy the rest. // This ensures that whatever other fields Variant gets in the future, we always // copy them as well. So future proof! // Move the samples and leave them in a well-defined empty state in the iterator. auto tmp_samples = std::move( iterator->samples ); iterator->samples.clear(); // Now we can copy the rest, which will not copy any samples (as we just cleared them), // and then finally move over the samples again. variants_[i] = *iterator; variants_[i]->samples = std::move( tmp_samples ); // Check for consistency. This is also already checked in all our input // file sources that we have implemented so far, but better safe than sorry. // Also, we need to do this in case someone uses a different source that does not check. if( variants_[i]->samples.size() != variant_sizes_[i] ) { throw std::runtime_error( "Cannot iterate multiple input sources in parallel, as (at least) " "one of them has an inconsistent number of samples. " "Offending input source: " + iterator.data().source_name + " at " + iterator->chromosome + ":" + std::to_string( iterator->position ) + ". " + "Expecting " + std::to_string( variant_sizes_[i] ) + " samples (based on the first used line of input of that source), " + "but found " + std::to_string( variants_[i]->samples.size() ) + " at the indicated locus." ); } // Naive version that just makes a full copy. // variants_[i] = *iterator; } else { // The iterator is not at our current locus. We already checked that it is // however still valid, so it must be beyond the current one. Assert this. assert( locus_greater( iterator->chromosome, iterator->position, current_locus_ )); variants_[i] = utils::nullopt; } } } } // namespace population } // namespace genesis
gpl-3.0
bottiger/SoundWaves
app/src/main/java/org/bottiger/podcast/utils/StorageUtils.java
10048
package org.bottiger.podcast.utils; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Environment; import android.os.Looper; import android.preference.PreferenceManager; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.annotation.WorkerThread; import android.text.TextUtils; import android.util.Log; import android.webkit.MimeTypeMap; import org.bottiger.podcast.BuildConfig; import org.bottiger.podcast.R; import org.bottiger.podcast.SoundWaves; import org.bottiger.podcast.flavors.CrashReporter.VendorCrashReporter; import org.bottiger.podcast.provider.FeedItem; import org.bottiger.podcast.provider.IEpisode; import org.bottiger.podcast.provider.ISubscription; import org.bottiger.podcast.provider.Subscription; import org.bottiger.podcast.service.Downloader.SoundWavesDownloadManager; import java.io.File; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.LinkedList; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; /** * Created by aplb on 07-04-2016. */ public class StorageUtils { private static final String TAG = StorageUtils.class.getSimpleName(); private static final String MIME_AUDIO = "audio"; private static final String MIME_VIDEO = "video"; private static final String MIME_OTHER = "other"; @Retention(RetentionPolicy.SOURCE) @IntDef({AUDIO, VIDEO, OTHER}) public @interface MimeType {} public static final int AUDIO = 1; public static final int VIDEO = 2; public static final int OTHER = 3; /** * Removes all the expired downloads async */ public static void removeExpiredDownloadedPodcasts(Context context) { removeExpiredDownloadedPodcastsTask(context); } @RequiresPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) public static boolean removeTmpFolderCruft(@NonNull Context argContext) throws SecurityException { String tmpFolder; try { tmpFolder = SDCardManager.getTmpDir(argContext); } catch (IOException e) { Log.w(TAG, "Could not access tmp storage. removeTmpFolderCruft() returns without success"); // NoI18N return false; } Log.d(TAG, "Cleaning tmp folder: " + tmpFolder); // NoI18N File dir = new File(tmpFolder); if(dir.exists() && dir.isDirectory()) { return FileUtils.cleanDirectory(dir, false); } return true; } /** * Iterates through all the downloaded episodes and deletes the ones who * exceed the download limit Runs with minimum priority */ @WorkerThread private static void removeExpiredDownloadedPodcastsTask(Context context) throws SecurityException { if (BuildConfig.DEBUG && Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalStateException("Should not be executed on main thread!"); } if (!SDCardManager.getSDCardStatus()) { return; } SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); long bytesToKeep = SoundWavesDownloadManager.bytesToKeep(sharedPreferences, context.getResources()); ArrayList<IEpisode> episodes = SoundWaves.getAppContext(context).getLibraryInstance().getEpisodes(); LinkedList<String> filesToKeep = new LinkedList<>(); IEpisode episode; FeedItem item; File file; boolean isFeedItem; long lastModifiedKey; // Build list of downloaded files SortedMap<Long, FeedItem> sortedMap = new TreeMap<>(); for (int i = 0; i < episodes.size(); i++) { // Extract data. episode = episodes.get(i); isFeedItem = episode instanceof FeedItem; if (!isFeedItem) { continue; } item = (FeedItem) episode; if (item.isDownloaded(context)) { try { file = new File(item.getAbsolutePath(context)); lastModifiedKey = file.lastModified(); sortedMap.put(-lastModifiedKey, item); } catch (IOException e) { ErrorUtils.handleException(e); } } } SortedSet<Long> keys = new TreeSet<>(sortedMap.keySet()); for (Long key : keys) { boolean deleteFile = true; item = sortedMap.get(key); try { file = new File(item.getAbsolutePath(context)); } catch (IOException e) { ErrorUtils.handleException(e); continue; } if (file.exists()) { bytesToKeep = bytesToKeep - item.getFilesize(); // if we have exceeded our limit start deleting old // items if (bytesToKeep < 0) { deleteExpireFile(context, item); } else { deleteFile = false; filesToKeep.add(item.getFilename()); } } if (deleteFile) { item.setDownloaded(false); } } // Delete the remaining files which are not indexed in the // database // Duplicated code from DownloadManagerReceiver File directory; try { directory = SDCardManager.getDownloadDir(context); } catch (IOException e) { ErrorUtils.handleException(e); return; } File[] files = directory.listFiles(); for (File keepFile : files) { if (!filesToKeep.contains(keepFile.getName())) { // Delete each file keepFile.delete(); } } } public static boolean canPerform(@SoundWavesDownloadManager.Action int argAction, @NonNull Context argContext, @NonNull ISubscription argSubscription) { Log.v(TAG, "canPerform: " + argAction); boolean isLargeFile = argAction == SoundWavesDownloadManager.ACTION_DOWNLOAD_AUTOMATICALLY; @SoundWavesDownloadManager.NetworkState int networkState = NetworkUtils.getNetworkStatus(argContext, isLargeFile); if (networkState == SoundWavesDownloadManager.NETWORK_DISCONNECTED) return false; boolean wifiOnly = PreferenceHelper.getBooleanPreferenceValue(argContext, R.string.pref_download_only_wifi_key, R.bool.pref_download_only_wifi_default); boolean automaticDownload = PreferenceHelper.getBooleanPreferenceValue(argContext, R.string.pref_download_on_update_key, R.bool.pref_download_on_update_default); if (argSubscription instanceof Subscription) { Subscription subscription = (Subscription) argSubscription; automaticDownload = subscription.doDownloadNew(automaticDownload); } switch (argAction) { case SoundWavesDownloadManager.ACTION_DOWNLOAD_AUTOMATICALLY: { if (!automaticDownload) return false; if (wifiOnly) return networkState == SoundWavesDownloadManager.NETWORK_OK; else return networkState == SoundWavesDownloadManager.NETWORK_OK || networkState == SoundWavesDownloadManager.NETWORK_RESTRICTED; } case SoundWavesDownloadManager.ACTION_DOWNLOAD_MANUALLY: case SoundWavesDownloadManager.ACTION_REFRESH_SUBSCRIPTION: case SoundWavesDownloadManager.ACTION_STREAM_EPISODE: { return networkState == SoundWavesDownloadManager.NETWORK_OK || networkState == SoundWavesDownloadManager.NETWORK_RESTRICTED; } } VendorCrashReporter.report(TAG, "canPerform defaults to false. Action: " + argAction); return false; // FIXME this should never happen. Ensure we never get here } /** * Deletes the downloaded file and updates the database record * * @param context */ private static void deleteExpireFile(@NonNull Context context, FeedItem item) throws SecurityException { if (item == null) return; item.delFile(context); } public static @MimeType int getFileType(@Nullable String argMimeType) { if (TextUtils.isEmpty(argMimeType)) return OTHER; String lowerCase = argMimeType.toLowerCase(); if (lowerCase.contains(MIME_AUDIO)) return AUDIO; if (lowerCase.contains(MIME_VIDEO)) return VIDEO; return OTHER; } public static String getMimeType(String fileUrl) { String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl); return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } public static int getStorageCapacityGB(@NonNull Context argContext) { String collectionSize = PreferenceHelper.getStringPreferenceValue(argContext, R.string.pref_podcast_collection_size_key, R.string.pref_download_collection_size_default); return (int) (Long.valueOf(collectionSize) / 1000); } public static void openFolderIntent(@NonNull Context argContext, @NonNull String argLocation) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); Uri uri = Uri.parse(argLocation); //intent.setDataAndType(uri, "text/csv"); intent.setDataAndType(uri, "text/csv"); argContext.startActivity(Intent.createChooser(intent, "Open folder")); } }
gpl-3.0
tybor/monodes
legacy/reactions.cpp
3425
/* Copyright (c) 2010 Paolo Redaelli This file is part of Monodes. Monodes 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. Monodes 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 Lesser GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <iostream> #include "reactions.h" #include "node.h" #include "nodedialog.h" #include "truss.h" Reactions::Reactions(Node &parent) : node(parent) { setParentItem(&parent); } void Reactions::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { // /// TODO: Currently drawing only the horizontal reaction // // Drawing a little below the node // painter->translate(0.0, node.boundingRect().bottom()*1.2); // // Drawing a vertical arrow // painter->setPen(heavy); // Truss *truss = reinterpret_cast<Truss*>(node.parentItem()); /// This won't be necessary in Eiffel since parent_object would be redefined as TRUSS. // assert (truss!=NULL); // qreal l =node.vertical*truss->action_scale, w = l/8; // //std::cout<<"freccia "<<l<<"x"<<w<<" scala "<<truss->action_scale<<std::endl; // painter->drawLine(0.0, 0.0, 0.0, l); // //painter->setPen(QPen(QColor(Qt::red))); // painter->drawLine(QPointF(), QPointF(-w, w)); // painter->drawLine(QPointF(), QPointF( w, w)); // // Please note that those lines should be drawed providing QPointF objects; if you pass their actual coordinates they get casted into integers and you won't get what you intend. // // Draw reaction // painter->rotate(90); // painter->translate(bigger/2,bigger); // painter->setPen(Qt::green); // //QRectF label_rect(QPointF(0.0, 0.0), QPointF(bigger, 3*bigger)); // //painter->drawRect(label_rect);; /// debug // QString label = QString("N %1 kg").arg(node.vertical); // ///* Pick the size that fits the load rectangle better */ // // QFont font = QFont("sans"); // // text_rect = painter->boundingRect(QrectF(),label); // The size we would occupy // // qreal new_size = font.pointSizeF() * fmin( // // label_rect.width() / text_rect.width(), // // label_rect.height() / text_rect.height()); // // std::cout<<"Reaction label size:"<<new_size<<std::endl; // // assert(new_size>0.0); // // font.setPointSizeF(new_size); // // painter->setFont(font); // painter->drawText(text_rect, label); // painter->setPen(Qt::red); // painter->drawRect(text_rect); } QRectF Reactions::boundingRect() const { qreal displacement = node.boundingRect().bottom()*1.2; return node.boundingRect().adjusted (-bigger/2, displacement, bigger/2, displacement+4*bigger); } void Reactions::mousePressEvent(QGraphicsSceneMouseEvent *) { NodeDialog dialog(node); // A dialog for current node //dialog.show(); /* unused int res = */ dialog.exec(); update(); //QGraphicsItem::mousePressEvent(event); }
gpl-3.0
derrybryson/kisside
source/api/auth.php
2240
<?php function authAdd($user) { global $db; $hash = hash_init("sha256"); hash_update($hash, $user["username"]); hash_update($hash, $user["password"]); hash_update($hash, time()); $authToken = hash_final($hash); $expdate = time() + AUTH_EXPIRE_SECONDS; $retval = null; try { $db->beginTransaction(); $query = "insert into auths (auth_token, userid, expdate) values (" . $db->quote($authToken) . ", " . $db->quote($user["userid"]) . ", " . $db->quote($expdate) . ")"; $result = $db->query($query); if(!$result) $retval = $authToken; $db->commit(); $retval = $authToken; } catch(Exception $e) { error_log($e->getMessage() . ": " . $e->getTraceAsString()); $db->rollBack(); } return $retval; } function authRem($authToken) { global $db; $retval = false; try { $db->beginTransaction(); $query = "delete from auths where auth_token=" . $db->quote($authToken); $result = $db->query($query); if(!$result) $retval = true; $db->commit(); } catch(Exception $e) { error_log($e->getMessage() . ": " . $e->getTraceAsString()); $db->rollBack(); } return $retval; } function authVerify($authToken) { global $db; $auth = null; try { $db->beginTransaction(); $query = "select * from auths where auth_token=" . $db->quote($authToken); $result = $db->query($query); if($result) { $auth = $result->fetch(); error_log("auth = " . print_r($auth, true) . ", time = " . time()); if($auth && $auth["expdate"] <= time()) { error_log("clearing auth"); $auth = null; $query = "delete from auths where auth_token=" . $db->quote($authToken); $result = $db->query($query); } else { $expdate = time() + AUTH_EXPIRE_SECONDS; $query = "update auths set expdate=" . $db->quote($expdate) . " where auth_token=" . $db->quote($authToken); error_log("query = $query"); $result = $db->query($query); error_log("error updating auths record"); } } $db->commit(); } catch(Exception $e) { error_log($e->getMessage() . ": " . $e->getTraceAsString()); $db->rollBack(); } return $auth; } ?>
gpl-3.0
paulscode/mupen64plus-ae
jni/mupen64plus-video-glide64mk2/src/Glitch64/OGLglitchmain.cpp
72894
/* * Glide64 - Glide video plugin for Nintendo 64 emulators. * Copyright (c) 2002 Dave2001 * Copyright (c) 2003-2009 Sergey 'Gonetz' Lipski * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define SAVE_CBUFFER #ifdef _WIN32 #include <windows.h> #include <commctrl.h> #else #include <stdint.h> #include <stdarg.h> #include <string.h> #include <SDL.h> #endif // _WIN32 #include <stdlib.h> #include <stdio.h> #include <iostream> #include <fstream> #include <math.h> #include "glide.h" #include "g3ext.h" #include "main.h" #include "m64p.h" #ifdef VPDEBUG #include <IL/il.h> #endif extern void (*renderCallback)(int); wrapper_config config = {0, 0, 0, 0}; int screen_width, screen_height; static inline void opt_glCopyTexImage2D( GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border ) { int w, h, fmt; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &fmt); //printf("copyteximage %dx%d fmt %x oldfmt %x\n", width, height, internalFormat, fmt); if (w == (int) width && h == (int) height && fmt == (int) internalFormat) { if (x+width >= screen_width) { width = screen_width - x; //printf("resizing w --> %d\n", width); } if (y+height >= screen_height+viewport_offset) { height = screen_height+viewport_offset - y; //printf("resizing h --> %d\n", height); } glCopyTexSubImage2D(target, level, 0, 0, x, y, width, height); } else { //printf("copyteximage %dx%d fmt %x old %dx%d oldfmt %x\n", width, height, internalFormat, w, h, fmt); // glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, GL_UNSIGNED_BYTE, 0); // glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &fmt); // printf("--> %dx%d newfmt %x\n", width, height, fmt); glCopyTexImage2D(target, level, internalFormat, x, y, width, height, border); } } #define glCopyTexImage2D opt_glCopyTexImage2D #ifdef _WIN32 PFNGLACTIVETEXTUREARBPROC glActiveTextureARB; PFNGLBLENDFUNCSEPARATEEXTPROC glBlendFuncSeparateEXT; PFNGLMULTITEXCOORD2FARBPROC glMultiTexCoord2fARB; PFNGLFOGCOORDFPROC glFogCoordfEXT; PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB; PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT; PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT; PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT; PFNGLBINDRENDERBUFFEREXTPROC glBindRenderbufferEXT = NULL; PFNGLDELETERENDERBUFFERSEXTPROC glDeleteRenderbuffersEXT = NULL; PFNGLGENRENDERBUFFERSEXTPROC glGenRenderbuffersEXT = NULL; PFNGLRENDERBUFFERSTORAGEEXTPROC glRenderbufferStorageEXT = NULL; PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glFramebufferRenderbufferEXT = NULL; PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT; PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT; PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB; PFNGLSHADERSOURCEARBPROC glShaderSourceARB; PFNGLCOMPILESHADERARBPROC glCompileShaderARB; PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB; PFNGLATTACHOBJECTARBPROC glAttachObjectARB; PFNGLLINKPROGRAMARBPROC glLinkProgramARB; PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB; PFNGLGETHANDLEARBPROC glGetHandleARB; PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB; PFNGLUNIFORM1IARBPROC glUniform1iARB; PFNGLUNIFORM4IARBPROC glUniform4iARB; PFNGLUNIFORM4FARBPROC glUniform4fARB; PFNGLUNIFORM1FARBPROC glUniform1fARB; PFNGLDELETEOBJECTARBPROC glDeleteObjectARB; PFNGLGETINFOLOGARBPROC glGetInfoLogARB; PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB; PFNGLSECONDARYCOLOR3FPROC glSecondaryColor3f; // FXT1,DXT1,DXT5 support - Hiroshi Morii <koolsmoky(at)users.sourceforge.net> // NOTE: Glide64 + GlideHQ use the following formats // GL_COMPRESSED_RGB_S3TC_DXT1_EXT // GL_COMPRESSED_RGBA_S3TC_DXT5_EXT // GL_COMPRESSED_RGB_FXT1_3DFX // GL_COMPRESSED_RGBA_FXT1_3DFX PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2DARB; #endif // _WIN32 typedef struct { unsigned int address; int width; int height; unsigned int fbid; unsigned int zbid; unsigned int texid; int buff_clear; } fb; int nbTextureUnits; int nbAuxBuffers, current_buffer; int width, widtho, heighto, height; int saved_width, saved_height; int blend_func_separate_support; int npot_support; int fog_coord_support; int render_to_texture = 0; int texture_unit; int use_fbo; int buffer_cleared; // ZIGGY // to allocate a new static texture name, take the value (free_texture++) int free_texture; int default_texture; // the infamous "32*1024*1024" is now configurable int current_texture; int depth_texture, color_texture; int glsl_support = 1; int viewport_width, viewport_height, viewport_offset = 0, nvidia_viewport_hack = 0; int save_w, save_h; int lfb_color_fmt; float invtex[2]; //Gonetz int UMAmode = 0; //support for VSA-100 UMA mode; #ifdef _WIN32 static HDC hDC = NULL; static HGLRC hGLRC = NULL; static HWND hToolBar = NULL; static HWND hwnd_win = NULL; static unsigned long windowedExStyle, windowedStyle; #endif // _WIN32 static unsigned long fullscreen; #ifdef _WIN32 static RECT windowedRect; static HMENU windowedMenu; #endif // _WIN32 static int savedWidtho, savedHeighto; static int savedWidth, savedHeight; unsigned int pBufferAddress; static int pBufferFmt; static int pBufferWidth, pBufferHeight; static fb fbs[100]; static int nb_fb = 0; static unsigned int curBufferAddr = 0; struct TMU_USAGE { int min, max; } tmu_usage[2] = { {0xfffffff, 0}, {0xfffffff, 0} }; struct texbuf_t { FxU32 start, end; int fmt; }; #define NB_TEXBUFS 128 // MUST be a power of two static texbuf_t texbufs[NB_TEXBUFS]; static int texbuf_i; unsigned short frameBuffer[2048*2048]; unsigned short depthBuffer[2048*2048]; //#define VOODOO1 void display_warning(const char *text, ...) { static int first_message = 100; if (first_message) { char buf[1000]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); va_end(ap); first_message--; } } #ifdef _WIN32 void display_error() { LPVOID lpMsgBuf; if (!FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL )) { // Handle the error. return; } // Process any inserts in lpMsgBuf. // ... // Display the string. MessageBox( NULL, (LPCTSTR)lpMsgBuf, "Error", MB_OK | MB_ICONINFORMATION ); // Free the buffer. LocalFree( lpMsgBuf ); } #endif // _WIN32 #ifdef LOGGING char out_buf[256]; bool log_open = false; std::ofstream log_file; void OPEN_LOG() { if (!log_open) { log_file.open ("wrapper_log.txt", std::ios_base::out|std::ios_base::app); log_open = true; } } void CLOSE_LOG() { if (log_open) { log_file.close(); log_open = false; } } void LOG(const char *text, ...) { #ifdef VPDEBUG if (!dumping) return; #endif if (!log_open) return; va_list ap; va_start(ap, text); vsprintf(out_buf, text, ap); log_file << out_buf; log_file.flush(); va_end(ap); } class LogManager { public: LogManager() { OPEN_LOG(); } ~LogManager() { CLOSE_LOG(); } }; LogManager logManager; #else // LOGGING #define OPEN_LOG() #define CLOSE_LOG() //#define LOG #endif // LOGGING FX_ENTRY void FX_CALL grSstOrigin(GrOriginLocation_t origin) { LOG("grSstOrigin(%d)\r\n", origin); if (origin != GR_ORIGIN_UPPER_LEFT) display_warning("grSstOrigin : %x", origin); } FX_ENTRY void FX_CALL grClipWindow( FxU32 minx, FxU32 miny, FxU32 maxx, FxU32 maxy ) { LOG("grClipWindow(%d,%d,%d,%d)\r\n", minx, miny, maxx, maxy); if (use_fbo && render_to_texture) { if (int(minx) < 0) minx = 0; if (int(miny) < 0) miny = 0; if (maxx < minx) maxx = minx; if (maxy < miny) maxy = miny; glScissor(minx, miny, maxx - minx, maxy - miny); glEnable(GL_SCISSOR_TEST); return; } if (!use_fbo) { int th = height; if (th > screen_height) th = screen_height; maxy = th - maxy; miny = th - miny; FxU32 tmp = maxy; maxy = miny; miny = tmp; if (maxx > (FxU32) width) maxx = width; if (maxy > (FxU32) height) maxy = height; if (int(minx) < 0) minx = 0; if (int(miny) < 0) miny = 0; if (maxx < minx) maxx = minx; if (maxy < miny) maxy = miny; glScissor(minx, miny+viewport_offset, maxx - minx, maxy - miny); //printf("gl scissor %d %d %d %d\n", minx, miny, maxx, maxy); } else { glScissor(minx, (viewport_offset)+height-maxy, maxx - minx, maxy - miny); } glEnable(GL_SCISSOR_TEST); } FX_ENTRY void FX_CALL grColorMask( FxBool rgb, FxBool a ) { LOG("grColorMask(%d, %d)\r\n", rgb, a); glColorMask(rgb, rgb, rgb, a); } FX_ENTRY void FX_CALL grGlideInit( void ) { LOG("grGlideInit()\r\n"); } FX_ENTRY void FX_CALL grSstSelect( int which_sst ) { LOG("grSstSelect(%d)\r\n", which_sst); } int isExtensionSupported(const char *extension) { const GLubyte *extensions = NULL; const GLubyte *start; GLubyte *where, *terminator; where = (GLubyte *)strchr(extension, ' '); if (where || *extension == '\0') return 0; extensions = glGetString(GL_EXTENSIONS); start = extensions; for (;;) { where = (GLubyte *) strstr((const char *) start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return 1; start = terminator; } return 0; } #ifdef _WIN32 int isWglExtensionSupported(const char *extension) { const GLubyte *extensions = NULL; const GLubyte *start; GLubyte *where, *terminator; where = (GLubyte *)strchr(extension, ' '); if (where || *extension == '\0') return 0; extensions = (GLubyte*)wglGetExtensionsStringARB(wglGetCurrentDC()); start = extensions; for (;;) { where = (GLubyte *) strstr((const char *) start, extension); if (!where) break; terminator = where + strlen(extension); if (where == start || *(where - 1) == ' ') if (*terminator == ' ' || *terminator == '\0') return 1; start = terminator; } return 0; } #endif // _WIN32 #define GrPixelFormat_t int FX_ENTRY GrContext_t FX_CALL grSstWinOpenExt( HWND hWnd, GrScreenResolution_t screen_resolution, GrScreenRefresh_t refresh_rate, GrColorFormat_t color_format, GrOriginLocation_t origin_location, GrPixelFormat_t pixelformat, int nColBuffers, int nAuxBuffers) { LOG("grSstWinOpenExt(%d, %d, %d, %d, %d, %d %d)\r\n", hWnd, screen_resolution, refresh_rate, color_format, origin_location, nColBuffers, nAuxBuffers); return grSstWinOpen(hWnd, screen_resolution, refresh_rate, color_format, origin_location, nColBuffers, nAuxBuffers); } #ifdef _WIN32 # include <fcntl.h> # ifndef ATTACH_PARENT_PROCESS # define ATTACH_PARENT_PROCESS ((FxU32)-1) # endif #endif FX_ENTRY GrContext_t FX_CALL grSstWinOpen( HWND hWnd, GrScreenResolution_t screen_resolution, GrScreenRefresh_t refresh_rate, GrColorFormat_t color_format, GrOriginLocation_t origin_location, int nColBuffers, int nAuxBuffers) { static int show_warning = 1; // ZIGGY // allocate static texture names // the initial value should be big enough to support the maximal resolution free_texture = 32*2048*2048; default_texture = free_texture++; color_texture = free_texture++; depth_texture = free_texture++; LOG("grSstWinOpen(%08lx, %d, %d, %d, %d, %d %d)\r\n", hWnd, screen_resolution&~0x80000000, refresh_rate, color_format, origin_location, nColBuffers, nAuxBuffers); #ifdef _WIN32 if ((HWND)hWnd == NULL) hWnd = GetActiveWindow(); hwnd_win = (HWND)hWnd; #endif // _WIN32 width = height = 0; m64p_handle video_general_section; printf("&ConfigOpenSection is %p\n", &ConfigOpenSection); if (ConfigOpenSection("Video-General", &video_general_section) != M64ERR_SUCCESS) { printf("Could not open video settings"); return false; } // Load Glide64mk2 settings to get AA option [Willrandship] m64p_handle video_glide64mk2_section; ConfigOpenSection("Video-Glide64mk2", &video_glide64mk2_section); int aalevel = ConfigGetParamInt(video_glide64mk2_section, "wrpAntiAliasing"); width = ConfigGetParamInt(video_general_section, "ScreenWidth"); height = ConfigGetParamInt(video_general_section, "ScreenHeight"); fullscreen = ConfigGetParamBool(video_general_section, "Fullscreen"); int vsync = ConfigGetParamBool(video_general_section, "VerticalSync"); //viewport_offset = ((screen_resolution>>2) > 20) ? screen_resolution >> 2 : 20; // ZIGGY viewport_offset is WIN32 specific, with SDL just set it to zero viewport_offset = 0; //-10 //-20; CoreVideo_Init(); CoreVideo_GL_SetAttribute(M64P_GL_DOUBLEBUFFER, 1); CoreVideo_GL_SetAttribute(M64P_GL_SWAP_CONTROL, vsync); CoreVideo_GL_SetAttribute(M64P_GL_BUFFER_SIZE, 16); // SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); // SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); // SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); CoreVideo_GL_SetAttribute(M64P_GL_DEPTH_SIZE, 16); if(aalevel > 0){ CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLEBUFFERS, 1); CoreVideo_GL_SetAttribute(M64P_GL_MULTISAMPLESAMPLES, aalevel); } printf("(II) Setting video mode %dx%d...\n", width, height); if(CoreVideo_SetVideoMode(width, height, 0, fullscreen ? M64VIDEO_FULLSCREEN : M64VIDEO_WINDOWED, (m64p_video_flags) 0) != M64ERR_SUCCESS) { printf("(EE) Error setting videomode %dx%d\n", width, height); return false; } char caption[500]; # ifdef _DEBUG sprintf(caption, "Glide64mk2 debug"); # else // _DEBUG sprintf(caption, "Glide64mk2"); # endif // _DEBUG CoreVideo_SetCaption(caption); glViewport(0, viewport_offset, width, height); lfb_color_fmt = color_format; if (origin_location != GR_ORIGIN_UPPER_LEFT) display_warning("origin must be in upper left corner"); if (nColBuffers != 2) display_warning("number of color buffer is not 2"); if (nAuxBuffers != 1) display_warning("number of auxiliary buffer is not 1"); if (isExtensionSupported("GL_ARB_texture_env_combine") == 0 && isExtensionSupported("GL_EXT_texture_env_combine") == 0 && show_warning) display_warning("Your video card doesn't support GL_ARB_texture_env_combine extension"); if (isExtensionSupported("GL_ARB_multitexture") == 0 && show_warning) display_warning("Your video card doesn't support GL_ARB_multitexture extension"); if (isExtensionSupported("GL_ARB_texture_mirrored_repeat") == 0 && show_warning) display_warning("Your video card doesn't support GL_ARB_texture_mirrored_repeat extension"); show_warning = 0; #ifdef _WIN32 glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)wglGetProcAddress("glActiveTextureARB"); glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC)wglGetProcAddress("glMultiTexCoord2fARB"); #endif // _WIN32 nbTextureUnits = 0; glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &nbTextureUnits); if (nbTextureUnits == 1) display_warning("You need a video card that has at least 2 texture units"); nbAuxBuffers = 0; glGetIntegerv(GL_AUX_BUFFERS, &nbAuxBuffers); if (nbAuxBuffers > 0) printf("Congratulations, you have %d auxilliary buffers, we'll use them wisely !\n", nbAuxBuffers); #ifdef VOODOO1 nbTextureUnits = 2; #endif if (isExtensionSupported("GL_EXT_blend_func_separate") == 0) blend_func_separate_support = 0; else blend_func_separate_support = 1; if (isExtensionSupported("GL_EXT_packed_pixels") == 0) packed_pixels_support = 0; else { printf("packed pixels extension used\n"); packed_pixels_support = 1; } if (isExtensionSupported("GL_ARB_texture_non_power_of_two") == 0) npot_support = 0; else { printf("NPOT extension used\n"); npot_support = 1; } #ifdef _WIN32 glBlendFuncSeparateEXT = (PFNGLBLENDFUNCSEPARATEEXTPROC)wglGetProcAddress("glBlendFuncSeparateEXT"); #endif // _WIN32 if (isExtensionSupported("GL_EXT_fog_coord") == 0) fog_coord_support = 0; else fog_coord_support = 1; #ifdef _WIN32 glFogCoordfEXT = (PFNGLFOGCOORDFPROC)wglGetProcAddress("glFogCoordfEXT"); #endif // _WIN32 #ifdef _WIN32 wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); #endif // _WIN32 #ifdef _WIN32 glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)wglGetProcAddress("glBindFramebufferEXT"); glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)wglGetProcAddress("glFramebufferTexture2DEXT"); glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)wglGetProcAddress("glGenFramebuffersEXT"); glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)wglGetProcAddress("glCheckFramebufferStatusEXT"); glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)wglGetProcAddress("glDeleteFramebuffersEXT"); glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)wglGetProcAddress("glBindRenderbufferEXT"); glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)wglGetProcAddress("glDeleteRenderbuffersEXT"); glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)wglGetProcAddress("glGenRenderbuffersEXT"); glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)wglGetProcAddress("glRenderbufferStorageEXT"); glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)wglGetProcAddress("glFramebufferRenderbufferEXT"); use_fbo = config.fbo && (glFramebufferRenderbufferEXT != NULL); #else use_fbo = config.fbo; #endif // _WIN32 printf("use_fbo %d\n", use_fbo); if (isExtensionSupported("GL_ARB_shading_language_100") && isExtensionSupported("GL_ARB_shader_objects") && isExtensionSupported("GL_ARB_fragment_shader") && isExtensionSupported("GL_ARB_vertex_shader")) { #ifdef _WIN32 glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)wglGetProcAddress("glCreateShaderObjectARB"); glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)wglGetProcAddress("glShaderSourceARB"); glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)wglGetProcAddress("glCompileShaderARB"); glCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)wglGetProcAddress("glCreateProgramObjectARB"); glAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)wglGetProcAddress("glAttachObjectARB"); glLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)wglGetProcAddress("glLinkProgramARB"); glUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)wglGetProcAddress("glUseProgramObjectARB"); glGetHandleARB = (PFNGLGETHANDLEARBPROC)wglGetProcAddress("glGetHandleARB"); glGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)wglGetProcAddress("glGetUniformLocationARB"); glUniform1iARB = (PFNGLUNIFORM1IARBPROC)wglGetProcAddress("glUniform1iARB"); glUniform4iARB = (PFNGLUNIFORM4IARBPROC)wglGetProcAddress("glUniform4iARB"); glUniform4fARB = (PFNGLUNIFORM4FARBPROC)wglGetProcAddress("glUniform4fARB"); glUniform1fARB = (PFNGLUNIFORM1FARBPROC)wglGetProcAddress("glUniform1fARB"); glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)wglGetProcAddress("glDeleteObjectARB"); glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)wglGetProcAddress("glGetInfoLogARB"); glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)wglGetProcAddress("glGetObjectParameterivARB"); glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)wglGetProcAddress("glSecondaryColor3f"); #endif // _WIN32 } if (isExtensionSupported("GL_EXT_texture_compression_s3tc") == 0 && show_warning) display_warning("Your video card doesn't support GL_EXT_texture_compression_s3tc extension"); if (isExtensionSupported("GL_3DFX_texture_compression_FXT1") == 0 && show_warning) display_warning("Your video card doesn't support GL_3DFX_texture_compression_FXT1 extension"); #ifdef _WIN32 glCompressedTexImage2DARB = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)wglGetProcAddress("glCompressedTexImage2DARB"); #endif #ifdef _WIN32 glViewport(0, viewport_offset, width, height); viewport_width = width; viewport_height = height; nvidia_viewport_hack = 1; #else glViewport(0, viewport_offset, width, height); viewport_width = width; viewport_height = height; #endif // _WIN32 // void do_benchmarks(); // do_benchmarks(); // VP try to resolve z precision issues glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, 1-zscale); glScalef(1, 1, zscale); widtho = width/2; heighto = height/2; pBufferWidth = pBufferHeight = -1; current_buffer = GL_BACK; texture_unit = GL_TEXTURE0_ARB; { int i; for (i=0; i<NB_TEXBUFS; i++) texbufs[i].start = texbufs[i].end = 0xffffffff; } if (!use_fbo && nbAuxBuffers == 0) { // create the framebuffer saving texture int w = width, h = height; glBindTexture(GL_TEXTURE_2D, color_texture); if (!npot_support) { w = h = 1; while (w<width) w*=2; while (h<height) h*=2; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); save_w = save_h = 0; } void FindBestDepthBias(); FindBestDepthBias(); init_geometry(); init_textures(); init_combiner(); // Aniso filter check if (config.anisofilter > 0 ) glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy); // ATI hack - certain texture formats are slow on ATI? // Hmm, perhaps the internal format need to be specified explicitly... { GLint ifmt; glTexImage2D(GL_PROXY_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, NULL); glGetTexLevelParameteriv(GL_PROXY_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &ifmt); if (ifmt != GL_RGB5_A1) { display_warning("ATI SUCKS %x\n", ifmt); ati_sucks = 1; } else ati_sucks = 0; } return 1; } FX_ENTRY void FX_CALL grGlideShutdown( void ) { LOG("grGlideShutdown\r\n"); } FX_ENTRY FxBool FX_CALL grSstWinClose( GrContext_t context ) { int i, clear_texbuff = use_fbo; LOG("grSstWinClose(%d)\r\n", context); for (i=0; i<2; i++) { tmu_usage[i].min = 0xfffffff; tmu_usage[i].max = 0; invtex[i] = 0; } free_combiners(); #ifndef _WIN32 try // I don't know why, but opengl can be killed before this function call when emulator is closed (Gonetz). // ZIGGY : I found the problem : it is a function pointer, when the extension isn't supported , it is then zero, so just need to check the pointer prior to do the call. { if (use_fbo) glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); } catch (...) { clear_texbuff = 0; } if (clear_texbuff) { for (i=0; i<nb_fb; i++) { glDeleteTextures( 1, &(fbs[i].texid) ); glDeleteFramebuffersEXT( 1, &(fbs[i].fbid) ); glDeleteRenderbuffersEXT( 1, &(fbs[i].zbid) ); } } #endif nb_fb = 0; free_textures(); #ifndef _WIN32 // ZIGGY for some reasons, Pj64 doesn't like remove_tex on exit remove_tex(0, 0xfffffff); #endif //*/ #ifdef _WIN32 if (hGLRC) { wglMakeCurrent(hDC,NULL); wglDeleteContext(hGLRC); hGLRC = NULL; } if (fullscreen) { ChangeDisplaySettings(NULL, 0); SetWindowPos(hwnd_win, NULL, windowedRect.left, windowedRect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE); SetWindowLong(hwnd_win, GWL_STYLE, windowedStyle); SetWindowLong(hwnd_win, GWL_EXSTYLE, windowedExStyle); if (windowedMenu) SetMenu(hwnd_win, windowedMenu); fullscreen = 0; } #else //SDL_QuitSubSystem(SDL_INIT_VIDEO); //sleep(2); #endif CoreVideo_Quit(); return FXTRUE; } FX_ENTRY void FX_CALL grTextureBufferExt( GrChipID_t tmu, FxU32 startAddress, GrLOD_t lodmin, GrLOD_t lodmax, GrAspectRatio_t aspect, GrTextureFormat_t fmt, FxU32 evenOdd) { int i; static int fbs_init = 0; //printf("grTextureBufferExt(%d, %d, %d, %d, %d, %d, %d)\r\n", tmu, startAddress, lodmin, lodmax, aspect, fmt, evenOdd); LOG("grTextureBufferExt(%d, %d, %d, %d %d, %d, %d)\r\n", tmu, startAddress, lodmin, lodmax, aspect, fmt, evenOdd); if (lodmin != lodmax) display_warning("grTextureBufferExt : loading more than one LOD"); if (!use_fbo) { if (!render_to_texture) { //initialization return; } render_to_texture = 2; if (aspect < 0) { pBufferHeight = 1 << lodmin; pBufferWidth = pBufferHeight >> -aspect; } else { pBufferWidth = 1 << lodmin; pBufferHeight = pBufferWidth >> aspect; } if (curBufferAddr && startAddress+1 != curBufferAddr) updateTexture(); #ifdef SAVE_CBUFFER //printf("saving %dx%d\n", pBufferWidth, pBufferHeight); // save color buffer if (nbAuxBuffers > 0) { glDrawBuffer(GL_AUX0); current_buffer = GL_AUX0; } else { int tw, th; if (pBufferWidth < screen_width) tw = pBufferWidth; else tw = screen_width; if (pBufferHeight < screen_height) th = pBufferHeight; else th = screen_height; glReadBuffer(GL_BACK); glActiveTextureARB(texture_unit); glBindTexture(GL_TEXTURE_2D, color_texture); // save incrementally the framebuffer if (save_w) { if (tw > save_w && th > save_h) { glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, save_h, 0, viewport_offset+save_h, tw, th-save_h); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, save_w, 0, save_w, viewport_offset, tw-save_w, save_h); save_w = tw; save_h = th; } else if (tw > save_w) { glCopyTexSubImage2D(GL_TEXTURE_2D, 0, save_w, 0, save_w, viewport_offset, tw-save_w, save_h); save_w = tw; } else if (th > save_h) { glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, save_h, 0, viewport_offset+save_h, save_w, th-save_h); save_h = th; } } else { glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, viewport_offset, tw, th); save_w = tw; save_h = th; } glBindTexture(GL_TEXTURE_2D, default_texture); } #endif if (startAddress+1 != curBufferAddr || (curBufferAddr == 0L && nbAuxBuffers == 0)) buffer_cleared = 0; curBufferAddr = pBufferAddress = startAddress+1; pBufferFmt = fmt; int rtmu = startAddress < grTexMinAddress(GR_TMU1)? 0 : 1; int size = pBufferWidth*pBufferHeight*2; //grTexFormatSize(fmt); if ((unsigned int) tmu_usage[rtmu].min > pBufferAddress) tmu_usage[rtmu].min = pBufferAddress; if ((unsigned int) tmu_usage[rtmu].max < pBufferAddress+size) tmu_usage[rtmu].max = pBufferAddress+size; // printf("tmu %d usage now %gMb - %gMb\n", // rtmu, tmu_usage[rtmu].min/1024.0f, tmu_usage[rtmu].max/1024.0f); width = pBufferWidth; height = pBufferHeight; widtho = width/2; heighto = height/2; // this could be improved, but might be enough as long as the set of // texture buffer addresses stay small for (i=(texbuf_i-1)&(NB_TEXBUFS-1) ; i!=texbuf_i; i=(i-1)&(NB_TEXBUFS-1)) if (texbufs[i].start == pBufferAddress) break; texbufs[i].start = pBufferAddress; texbufs[i].end = pBufferAddress + size; texbufs[i].fmt = fmt; if (i == texbuf_i) texbuf_i = (texbuf_i+1)&(NB_TEXBUFS-1); //printf("texbuf %x fmt %x\n", pBufferAddress, fmt); // ZIGGY it speeds things up to not delete the buffers // a better thing would be to delete them *sometimes* // remove_tex(pBufferAddress+1, pBufferAddress + size); add_tex(pBufferAddress); //printf("viewport %dx%d\n", width, height); if (height > screen_height) { glViewport( 0, viewport_offset + screen_height - height, width, height); } else glViewport( 0, viewport_offset, width, height); glScissor(0, viewport_offset, width, height); } else { if (!render_to_texture) //initialization { if(!fbs_init) { for(i=0; i<100; i++) fbs[i].address = 0; fbs_init = 1; nb_fb = 0; } return; //no need to allocate FBO if render buffer is not texture buffer } render_to_texture = 2; if (aspect < 0) { pBufferHeight = 1 << lodmin; pBufferWidth = pBufferHeight >> -aspect; } else { pBufferWidth = 1 << lodmin; pBufferHeight = pBufferWidth >> aspect; } pBufferAddress = startAddress+1; width = pBufferWidth; height = pBufferHeight; widtho = width/2; heighto = height/2; for (i=0; i<nb_fb; i++) { if (fbs[i].address == pBufferAddress) { if (fbs[i].width == width && fbs[i].height == height) //select already allocated FBO { glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 ); glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fbs[i].fbid ); glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbs[i].texid, 0 ); glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, fbs[i].zbid ); glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbs[i].zbid ); glViewport( 0, 0, width, height); glScissor( 0, 0, width, height); if (fbs[i].buff_clear) { glDepthMask(1); glClear( GL_DEPTH_BUFFER_BIT ); //clear z-buffer only. we may need content, stored in the frame buffer fbs[i].buff_clear = 0; } CHECK_FRAMEBUFFER_STATUS(); curBufferAddr = pBufferAddress; return; } else //create new FBO at the same address, delete old one { glDeleteFramebuffersEXT( 1, &(fbs[i].fbid) ); glDeleteRenderbuffersEXT( 1, &(fbs[i].zbid) ); if (nb_fb > 1) memmove(&(fbs[i]), &(fbs[i+1]), sizeof(fb)*(nb_fb-i)); nb_fb--; break; } } } remove_tex(pBufferAddress, pBufferAddress + width*height*2/*grTexFormatSize(fmt)*/); //create new FBO glGenFramebuffersEXT( 1, &(fbs[nb_fb].fbid) ); glGenRenderbuffersEXT( 1, &(fbs[nb_fb].zbid) ); glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, fbs[nb_fb].zbid ); glRenderbufferStorageEXT( GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, width, height); fbs[nb_fb].address = pBufferAddress; fbs[nb_fb].width = width; fbs[nb_fb].height = height; fbs[nb_fb].texid = pBufferAddress; fbs[nb_fb].buff_clear = 0; add_tex(fbs[nb_fb].texid); glBindTexture(GL_TEXTURE_2D, fbs[nb_fb].texid); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, fbs[nb_fb].fbid); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, fbs[nb_fb].texid, 0); glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fbs[nb_fb].zbid ); glViewport(0,0,width,height); glScissor(0,0,width,height); glClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); glDepthMask(1); glClear( GL_DEPTH_BUFFER_BIT ); CHECK_FRAMEBUFFER_STATUS(); curBufferAddr = pBufferAddress; nb_fb++; } } int CheckTextureBufferFormat(GrChipID_t tmu, FxU32 startAddress, GrTexInfo *info ) { int found, i; if (!use_fbo) { for (found=i=0; i<2; i++) if ((FxU32) tmu_usage[i].min <= startAddress && (FxU32) tmu_usage[i].max > startAddress) { //printf("tmu %d == framebuffer %x\n", tmu, startAddress); found = 1; break; } } else { found = i = 0; while (i < nb_fb) { unsigned int end = fbs[i].address + fbs[i].width*fbs[i].height*2; if (startAddress >= fbs[i].address && startAddress < end) { found = 1; break; } i++; } } if (!use_fbo && found) { int tw, th, rh, cw, ch; if (info->aspectRatioLog2 < 0) { th = 1 << info->largeLodLog2; tw = th >> -info->aspectRatioLog2; } else { tw = 1 << info->largeLodLog2; th = tw >> info->aspectRatioLog2; } if (info->aspectRatioLog2 < 0) { ch = 256; cw = ch >> -info->aspectRatioLog2; } else { cw = 256; ch = cw >> info->aspectRatioLog2; } if (use_fbo || th < screen_height) rh = th; else rh = screen_height; //printf("th %d rh %d ch %d\n", th, rh, ch); invtex[tmu] = 1.0f - (th - rh) / (float)th; } else invtex[tmu] = 0; if (info->format == GR_TEXFMT_ALPHA_INTENSITY_88 ) { if (!found) { return 0; } if(tmu == 0) { if(blackandwhite1 != found) { blackandwhite1 = found; need_to_compile = 1; } } else { if(blackandwhite0 != found) { blackandwhite0 = found; need_to_compile = 1; } } return 1; } return 0; } FX_ENTRY void FX_CALL grTextureAuxBufferExt( GrChipID_t tmu, FxU32 startAddress, GrLOD_t thisLOD, GrLOD_t largeLOD, GrAspectRatio_t aspectRatio, GrTextureFormat_t format, FxU32 odd_even_mask ) { LOG("grTextureAuxBufferExt(%d, %d, %d, %d %d, %d, %d)\r\n", tmu, startAddress, thisLOD, largeLOD, aspectRatio, format, odd_even_mask); //display_warning("grTextureAuxBufferExt"); } FX_ENTRY void FX_CALL grAuxBufferExt( GrBuffer_t buffer ); FX_ENTRY GrProc FX_CALL grGetProcAddress( char *procName ) { LOG("grGetProcAddress(%s)\r\n", procName); if(!strcmp(procName, "grSstWinOpenExt")) return (GrProc)grSstWinOpenExt; if(!strcmp(procName, "grTextureBufferExt")) return (GrProc)grTextureBufferExt; if(!strcmp(procName, "grChromaRangeExt")) return (GrProc)grChromaRangeExt; if(!strcmp(procName, "grChromaRangeModeExt")) return (GrProc)grChromaRangeModeExt; if(!strcmp(procName, "grTexChromaRangeExt")) return (GrProc)grTexChromaRangeExt; if(!strcmp(procName, "grTexChromaModeExt")) return (GrProc)grTexChromaModeExt; // ZIGGY framebuffer copy extension if(!strcmp(procName, "grFramebufferCopyExt")) return (GrProc)grFramebufferCopyExt; if(!strcmp(procName, "grColorCombineExt")) return (GrProc)grColorCombineExt; if(!strcmp(procName, "grAlphaCombineExt")) return (GrProc)grAlphaCombineExt; if(!strcmp(procName, "grTexColorCombineExt")) return (GrProc)grTexColorCombineExt; if(!strcmp(procName, "grTexAlphaCombineExt")) return (GrProc)grTexAlphaCombineExt; if(!strcmp(procName, "grConstantColorValueExt")) return (GrProc)grConstantColorValueExt; if(!strcmp(procName, "grTextureAuxBufferExt")) return (GrProc)grTextureAuxBufferExt; if(!strcmp(procName, "grAuxBufferExt")) return (GrProc)grAuxBufferExt; if(!strcmp(procName, "grWrapperFullScreenResolutionExt")) return (GrProc)grWrapperFullScreenResolutionExt; if(!strcmp(procName, "grConfigWrapperExt")) return (GrProc)grConfigWrapperExt; if(!strcmp(procName, "grKeyPressedExt")) return (GrProc)grKeyPressedExt; if(!strcmp(procName, "grQueryResolutionsExt")) return (GrProc)grQueryResolutionsExt; if(!strcmp(procName, "grGetGammaTableExt")) return (GrProc)grGetGammaTableExt; display_warning("grGetProcAddress : %s", procName); return 0; } FX_ENTRY FxU32 FX_CALL grGet( FxU32 pname, FxU32 plength, FxI32 *params ) { LOG("grGet(%d,%d)\r\n", pname, plength); switch(pname) { case GR_MAX_TEXTURE_SIZE: if (plength < 4 || params == NULL) return 0; params[0] = 2048; return 4; break; case GR_NUM_TMU: if (plength < 4 || params == NULL) return 0; if (!nbTextureUnits) { grSstWinOpen((unsigned long)NULL, GR_RESOLUTION_640x480 | 0x80000000, 0, GR_COLORFORMAT_ARGB, GR_ORIGIN_UPPER_LEFT, 2, 1); grSstWinClose(0); } #ifdef VOODOO1 params[0] = 1; #else if (nbTextureUnits > 2) params[0] = 2; else params[0] = 1; #endif return 4; break; case GR_NUM_BOARDS: case GR_NUM_FB: case GR_REVISION_FB: case GR_REVISION_TMU: if (plength < 4 || params == NULL) return 0; params[0] = 1; return 4; break; case GR_MEMORY_FB: if (plength < 4 || params == NULL) return 0; params[0] = 16*1024*1024; return 4; break; case GR_MEMORY_TMU: if (plength < 4 || params == NULL) return 0; params[0] = 16*1024*1024; return 4; break; case GR_MEMORY_UMA: if (plength < 4 || params == NULL) return 0; params[0] = 16*1024*1024*nbTextureUnits; return 4; break; case GR_BITS_RGBA: if (plength < 16 || params == NULL) return 0; params[0] = 8; params[1] = 8; params[2] = 8; params[3] = 8; return 16; break; case GR_BITS_DEPTH: if (plength < 4 || params == NULL) return 0; params[0] = 16; return 4; break; case GR_BITS_GAMMA: if (plength < 4 || params == NULL) return 0; params[0] = 8; return 4; break; case GR_GAMMA_TABLE_ENTRIES: if (plength < 4 || params == NULL) return 0; params[0] = 256; return 4; break; case GR_FOG_TABLE_ENTRIES: if (plength < 4 || params == NULL) return 0; params[0] = 64; return 4; break; case GR_WDEPTH_MIN_MAX: if (plength < 8 || params == NULL) return 0; params[0] = 0; params[1] = 65528; return 8; break; case GR_ZDEPTH_MIN_MAX: if (plength < 8 || params == NULL) return 0; params[0] = 0; params[1] = 65535; return 8; break; case GR_LFB_PIXEL_PIPE: if (plength < 4 || params == NULL) return 0; params[0] = FXFALSE; return 4; break; case GR_MAX_TEXTURE_ASPECT_RATIO: if (plength < 4 || params == NULL) return 0; params[0] = 3; return 4; break; case GR_NON_POWER_OF_TWO_TEXTURES: if (plength < 4 || params == NULL) return 0; params[0] = FXFALSE; return 4; break; case GR_TEXTURE_ALIGN: if (plength < 4 || params == NULL) return 0; params[0] = 0; return 4; break; default: display_warning("unknown pname in grGet : %x", pname); } return 0; } FX_ENTRY const char * FX_CALL grGetString( FxU32 pname ) { LOG("grGetString(%d)\r\n", pname); switch(pname) { case GR_EXTENSION: { static char extension[] = "CHROMARANGE TEXCHROMA TEXMIRROR PALETTE6666 FOGCOORD EVOODOO TEXTUREBUFFER TEXUMA TEXFMT COMBINE GETGAMMA"; return extension; } break; case GR_HARDWARE: { static char hardware[] = "Voodoo5 (tm)"; return hardware; } break; case GR_VENDOR: { static char vendor[] = "3Dfx Interactive"; return vendor; } break; case GR_RENDERER: { static char renderer[] = "Glide"; return renderer; } break; case GR_VERSION: { static char version[] = "3.0"; return version; } break; default: display_warning("unknown grGetString selector : %x", pname); } return NULL; } static void render_rectangle(int texture_number, int dst_x, int dst_y, int src_width, int src_height, int tex_width, int tex_height, int invert) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBegin(GL_QUADS); glMultiTexCoord2fARB(texture_number, 0.0f, 0.0f); glVertex2f(((int)dst_x - widtho) / (float)(width/2), invert*-((int)dst_y - heighto) / (float)(height/2)); glMultiTexCoord2fARB(texture_number, 0.0f, (float)src_height / (float)tex_height); glVertex2f(((int)dst_x - widtho) / (float)(width/2), invert*-((int)dst_y + (int)src_height - heighto) / (float)(height/2)); glMultiTexCoord2fARB(texture_number, (float)src_width / (float)tex_width, (float)src_height / (float)tex_height); glVertex2f(((int)dst_x + (int)src_width - widtho) / (float)(width/2), invert*-((int)dst_y + (int)src_height - heighto) / (float)(height/2)); glMultiTexCoord2fARB(texture_number, (float)src_width / (float)tex_width, 0.0f); glVertex2f(((int)dst_x + (int)src_width - widtho) / (float)(width/2), invert*-((int)dst_y - heighto) / (float)(height/2)); glMultiTexCoord2fARB(texture_number, 0.0f, 0.0f); glVertex2f(((int)dst_x - widtho) / (float)(width/2), invert*-((int)dst_y - heighto) / (float)(height/2)); glEnd(); compile_shader(); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); } void reloadTexture() { if (use_fbo || !render_to_texture || buffer_cleared) return; LOG("reload texture %dx%d\n", width, height); //printf("reload texture %dx%d\n", width, height); buffer_cleared = 1; glPushAttrib(GL_ALL_ATTRIB_BITS); glActiveTextureARB(texture_unit); glBindTexture(GL_TEXTURE_2D, pBufferAddress); glDisable(GL_ALPHA_TEST); glDrawBuffer(current_buffer); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); set_copy_shader(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); int w = 0, h = 0; if (height > screen_height) h = screen_height - height; render_rectangle(texture_unit, -w, -h, width, height, width, height, -1); glBindTexture(GL_TEXTURE_2D, default_texture); glPopAttrib(); } void updateTexture() { if (!use_fbo && render_to_texture == 2) { LOG("update texture %x\n", pBufferAddress); //printf("update texture %x\n", pBufferAddress); // nothing changed, don't update the texture if (!buffer_cleared) { LOG("update cancelled\n", pBufferAddress); return; } glPushAttrib(GL_ALL_ATTRIB_BITS); // save result of render to texture into actual texture glReadBuffer(current_buffer); glActiveTextureARB(texture_unit); // ZIGGY // deleting the texture before resampling it increases speed on certain old // nvidia cards (geforce 2 for example), unfortunatly it slows down a lot // on newer cards. //glDeleteTextures( 1, &pBufferAddress ); glBindTexture(GL_TEXTURE_2D, pBufferAddress); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, viewport_offset, width, height, 0); glBindTexture(GL_TEXTURE_2D, default_texture); glPopAttrib(); } } FX_ENTRY void FX_CALL grFramebufferCopyExt(int x, int y, int w, int h, int from, int to, int mode) { if (mode == GR_FBCOPY_MODE_DEPTH) { int tw = 1, th = 1; if (npot_support) { tw = width; th = height; } else { while (tw < width) tw <<= 1; while (th < height) th <<= 1; } if (from == GR_FBCOPY_BUFFER_BACK && to == GR_FBCOPY_BUFFER_FRONT) { //printf("save depth buffer %d\n", render_to_texture); // save the depth image in a texture glReadBuffer(current_buffer); glBindTexture(GL_TEXTURE_2D, depth_texture); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 0, viewport_offset, tw, th, 0); glBindTexture(GL_TEXTURE_2D, default_texture); return; } if (from == GR_FBCOPY_BUFFER_FRONT && to == GR_FBCOPY_BUFFER_BACK) { //printf("writing to depth buffer %d\n", render_to_texture); glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_ALPHA_TEST); glDrawBuffer(current_buffer); glActiveTextureARB(texture_unit); glBindTexture(GL_TEXTURE_2D, depth_texture); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); set_depth_shader(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDisable(GL_CULL_FACE); render_rectangle(texture_unit, 0, 0, width, height, tw, th, -1); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glBindTexture(GL_TEXTURE_2D, default_texture); glPopAttrib(); return; } } } FX_ENTRY void FX_CALL grRenderBuffer( GrBuffer_t buffer ) { #ifdef _WIN32 static HANDLE region = NULL; int realWidth = pBufferWidth, realHeight = pBufferHeight; #endif // _WIN32 LOG("grRenderBuffer(%d)\r\n", buffer); //printf("grRenderBuffer(%d)\n", buffer); switch(buffer) { case GR_BUFFER_BACKBUFFER: if(render_to_texture) { updateTexture(); // VP z fix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, 1-zscale); glScalef(1, 1, zscale); inverted_culling = 0; grCullMode(culling_mode); width = savedWidth; height = savedHeight; widtho = savedWidtho; heighto = savedHeighto; if (use_fbo) { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 ); } curBufferAddr = 0; glViewport(0, viewport_offset, width, viewport_height); glScissor(0, viewport_offset, width, height); #ifdef SAVE_CBUFFER if (!use_fbo && render_to_texture == 2) { // restore color buffer if (nbAuxBuffers > 0) { glDrawBuffer(GL_BACK); current_buffer = GL_BACK; } else if (save_w) { int tw = 1, th = 1; //printf("restore %dx%d\n", save_w, save_h); if (npot_support) { tw = screen_width; th = screen_height; } else { while (tw < screen_width) tw <<= 1; while (th < screen_height) th <<= 1; } glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_ALPHA_TEST); glDrawBuffer(GL_BACK); glActiveTextureARB(texture_unit); glBindTexture(GL_TEXTURE_2D, color_texture); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); set_copy_shader(); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); render_rectangle(texture_unit, 0, 0, save_w, save_h, tw, th, -1); glBindTexture(GL_TEXTURE_2D, default_texture); glPopAttrib(); save_w = save_h = 0; } } #endif render_to_texture = 0; } glDrawBuffer(GL_BACK); break; case 6: // RENDER TO TEXTURE if(!render_to_texture) { savedWidth = width; savedHeight = height; savedWidtho = widtho; savedHeighto = heighto; } { if (!use_fbo) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, 1-zscale); glScalef(1, 1, zscale); inverted_culling = 0; } else { float m[4*4] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f,-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; glMatrixMode(GL_MODELVIEW); glLoadMatrixf(m); // VP z fix glTranslatef(0, 0, 1-zscale); glScalef(1, 1*1, zscale); inverted_culling = 1; grCullMode(culling_mode); } } render_to_texture = 1; break; default: display_warning("grRenderBuffer : unknown buffer : %x", buffer); } } FX_ENTRY void FX_CALL grAuxBufferExt( GrBuffer_t buffer ) { LOG("grAuxBufferExt(%d)\r\n", buffer); //display_warning("grAuxBufferExt"); if (buffer == GR_BUFFER_AUXBUFFER) { invtex[0] = 0; invtex[1] = 0; need_to_compile = 0; set_depth_shader(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDisable(GL_CULL_FACE); glDisable(GL_ALPHA_TEST); glDepthMask(GL_TRUE); grTexFilterMode(GR_TMU1, GR_TEXTUREFILTER_POINT_SAMPLED, GR_TEXTUREFILTER_POINT_SAMPLED); } else { glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); need_to_compile = 1; } } FX_ENTRY void FX_CALL grBufferClear( GrColor_t color, GrAlpha_t alpha, FxU32 depth ) { LOG("grBufferClear(%d,%d,%d)\r\n", color, alpha, depth); switch(lfb_color_fmt) { case GR_COLORFORMAT_ARGB: glClearColor(((color >> 16) & 0xFF) / 255.0f, ((color >> 8) & 0xFF) / 255.0f, ( color & 0xFF) / 255.0f, alpha / 255.0f); break; case GR_COLORFORMAT_RGBA: glClearColor(((color >> 24) & 0xFF) / 255.0f, ((color >> 16) & 0xFF) / 255.0f, (color & 0xFF) / 255.0f, alpha / 255.0f); break; default: display_warning("grBufferClear: unknown color format : %x", lfb_color_fmt); } if (w_buffer_mode) glClearDepth(1.0f - ((1.0f + (depth >> 4) / 4096.0f) * (1 << (depth & 0xF))) / 65528.0); else glClearDepth(depth / 65535.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // ZIGGY TODO check that color mask is on buffer_cleared = 1; } // #include <unistd.h> FX_ENTRY void FX_CALL grBufferSwap( FxU32 swap_interval ) { GLhandleARB program; glFinish(); // printf("rendercallback is %p\n", renderCallback); if(renderCallback) { program = glGetHandleARB(GL_PROGRAM_OBJECT_ARB); glUseProgramObjectARB(0); (*renderCallback)(1); if (program) glUseProgramObjectARB(program); } int i; LOG("grBufferSwap(%d)\r\n", swap_interval); //printf("swap\n"); if (render_to_texture) { display_warning("swap while render_to_texture\n"); return; } CoreVideo_GL_SwapBuffers(); for (i = 0; i < nb_fb; i++) fbs[i].buff_clear = 1; // VP debugging #ifdef VPDEBUG dump_stop(); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: switch (event.key.keysym.sym) { case 'd': printf("Dumping !\n"); dump_start(); break; case 'w': { static int wireframe; wireframe = !wireframe; glPolygonMode(GL_FRONT_AND_BACK, wireframe? GL_LINE : GL_FILL); break; } } break; } } #endif } // frame buffer FX_ENTRY FxBool FX_CALL grLfbLock( GrLock_t type, GrBuffer_t buffer, GrLfbWriteMode_t writeMode, GrOriginLocation_t origin, FxBool pixelPipeline, GrLfbInfo_t *info ) { LOG("grLfbLock(%d,%d,%d,%d,%d)\r\n", type, buffer, writeMode, origin, pixelPipeline); if (type == GR_LFB_WRITE_ONLY) { display_warning("grLfbLock : write only"); } else { unsigned char *buf; int i,j; switch(buffer) { case GR_BUFFER_FRONTBUFFER: glReadBuffer(GL_FRONT); break; case GR_BUFFER_BACKBUFFER: glReadBuffer(GL_BACK); break; default: display_warning("grLfbLock : unknown buffer : %x", buffer); } if(buffer != GR_BUFFER_AUXBUFFER) { if (writeMode == GR_LFBWRITEMODE_888) { //printf("LfbLock GR_LFBWRITEMODE_888\n"); info->lfbPtr = frameBuffer; info->strideInBytes = width*4; info->writeMode = GR_LFBWRITEMODE_888; info->origin = origin; glReadPixels(0, viewport_offset, width, height, GL_BGRA, GL_UNSIGNED_BYTE, frameBuffer); } else { buf = (unsigned char*)malloc(width*height*4); info->lfbPtr = frameBuffer; info->strideInBytes = width*2; info->writeMode = GR_LFBWRITEMODE_565; info->origin = origin; glReadPixels(0, viewport_offset, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buf); for (j=0; j<height; j++) { for (i=0; i<width; i++) { frameBuffer[(height-j-1)*width+i] = ((buf[j*width*4+i*4+0] >> 3) << 11) | ((buf[j*width*4+i*4+1] >> 2) << 5) | (buf[j*width*4+i*4+2] >> 3); } } free(buf); } } else { info->lfbPtr = depthBuffer; info->strideInBytes = width*2; info->writeMode = GR_LFBWRITEMODE_ZA16; info->origin = origin; glReadPixels(0, viewport_offset, width, height, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, depthBuffer); } } return FXTRUE; } FX_ENTRY FxBool FX_CALL grLfbUnlock( GrLock_t type, GrBuffer_t buffer ) { LOG("grLfbUnlock(%d,%d)\r\n", type, buffer); if (type == GR_LFB_WRITE_ONLY) { display_warning("grLfbUnlock : write only"); } return FXTRUE; } FX_ENTRY FxBool FX_CALL grLfbReadRegion( GrBuffer_t src_buffer, FxU32 src_x, FxU32 src_y, FxU32 src_width, FxU32 src_height, FxU32 dst_stride, void *dst_data ) { unsigned char *buf; unsigned int i,j; unsigned short *frameBuffer = (unsigned short*)dst_data; unsigned short *depthBuffer = (unsigned short*)dst_data; LOG("grLfbReadRegion(%d,%d,%d,%d,%d,%d)\r\n", src_buffer, src_x, src_y, src_width, src_height, dst_stride); switch(src_buffer) { case GR_BUFFER_FRONTBUFFER: glReadBuffer(GL_FRONT); break; case GR_BUFFER_BACKBUFFER: glReadBuffer(GL_BACK); break; /*case GR_BUFFER_AUXBUFFER: glReadBuffer(current_buffer); break;*/ default: display_warning("grReadRegion : unknown buffer : %x", src_buffer); } if(src_buffer != GR_BUFFER_AUXBUFFER) { buf = (unsigned char*)malloc(src_width*src_height*4); glReadPixels(src_x, (viewport_offset)+height-src_y-src_height, src_width, src_height, GL_RGBA, GL_UNSIGNED_BYTE, buf); for (j=0; j<src_height; j++) { for (i=0; i<src_width; i++) { frameBuffer[j*(dst_stride/2)+i] = ((buf[(src_height-j-1)*src_width*4+i*4+0] >> 3) << 11) | ((buf[(src_height-j-1)*src_width*4+i*4+1] >> 2) << 5) | (buf[(src_height-j-1)*src_width*4+i*4+2] >> 3); } } free(buf); } else { buf = (unsigned char*)malloc(src_width*src_height*2); glReadPixels(src_x, (viewport_offset)+height-src_y-src_height, src_width, src_height, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, depthBuffer); for (j=0;j<src_height; j++) { for (i=0; i<src_width; i++) { depthBuffer[j*(dst_stride/2)+i] = ((unsigned short*)buf)[(src_height-j-1)*src_width*4+i*4]; } } free(buf); } return FXTRUE; } FX_ENTRY FxBool FX_CALL grLfbWriteRegion( GrBuffer_t dst_buffer, FxU32 dst_x, FxU32 dst_y, GrLfbSrcFmt_t src_format, FxU32 src_width, FxU32 src_height, FxBool pixelPipeline, FxI32 src_stride, void *src_data ) { unsigned char *buf; unsigned int i,j; unsigned short *frameBuffer = (unsigned short*)src_data; int texture_number; unsigned int tex_width = 1, tex_height = 1; LOG("grLfbWriteRegion(%d,%d,%d,%d,%d,%d,%d,%d)\r\n",dst_buffer, dst_x, dst_y, src_format, src_width, src_height, pixelPipeline, src_stride); glPushAttrib(GL_ALL_ATTRIB_BITS); while (tex_width < src_width) tex_width <<= 1; while (tex_height < src_height) tex_height <<= 1; switch(dst_buffer) { case GR_BUFFER_BACKBUFFER: glDrawBuffer(GL_BACK); break; case GR_BUFFER_AUXBUFFER: glDrawBuffer(current_buffer); break; default: display_warning("grLfbWriteRegion : unknown buffer : %x", dst_buffer); } if(dst_buffer != GR_BUFFER_AUXBUFFER) { buf = (unsigned char*)malloc(tex_width*tex_height*4); texture_number = GL_TEXTURE0_ARB; glActiveTextureARB(texture_number); const unsigned int half_stride = src_stride / 2; switch(src_format) { case GR_LFB_SRC_FMT_1555: for (j=0; j<src_height; j++) { for (i=0; i<src_width; i++) { const unsigned int col = frameBuffer[j*half_stride+i]; buf[j*tex_width*4+i*4+0]=((col>>10)&0x1F)<<3; buf[j*tex_width*4+i*4+1]=((col>>5)&0x1F)<<3; buf[j*tex_width*4+i*4+2]=((col>>0)&0x1F)<<3; buf[j*tex_width*4+i*4+3]= (col>>15) ? 0xFF : 0; } } break; case GR_LFBWRITEMODE_555: for (j=0; j<src_height; j++) { for (i=0; i<src_width; i++) { const unsigned int col = frameBuffer[j*half_stride+i]; buf[j*tex_width*4+i*4+0]=((col>>10)&0x1F)<<3; buf[j*tex_width*4+i*4+1]=((col>>5)&0x1F)<<3; buf[j*tex_width*4+i*4+2]=((col>>0)&0x1F)<<3; buf[j*tex_width*4+i*4+3]=0xFF; } } break; case GR_LFBWRITEMODE_565: for (j=0; j<src_height; j++) { for (i=0; i<src_width; i++) { const unsigned int col = frameBuffer[j*half_stride+i]; buf[j*tex_width*4+i*4+0]=((col>>11)&0x1F)<<3; buf[j*tex_width*4+i*4+1]=((col>>5)&0x3F)<<2; buf[j*tex_width*4+i*4+2]=((col>>0)&0x1F)<<3; buf[j*tex_width*4+i*4+3]=0xFF; } } break; default: display_warning("grLfbWriteRegion : unknown format : %d", src_format); } #ifdef VPDEBUG if (dumping) { ilTexImage(tex_width, tex_height, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, buf); char name[128]; static int id; sprintf(name, "dump/writecolor%d.png", id++); ilSaveImage(name); //printf("dumped gdLfbWriteRegion %s\n", name); } #endif glBindTexture(GL_TEXTURE_2D, default_texture); glTexImage2D(GL_TEXTURE_2D, 0, 4, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buf); free(buf); set_copy_shader(); glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); render_rectangle(texture_number, dst_x, dst_y, src_width, src_height, tex_width, tex_height, +1); } else { float *buf = (float*)malloc(src_width*(src_height+(viewport_offset))*sizeof(float)); if (src_format != GR_LFBWRITEMODE_ZA16) display_warning("unknown depth buffer write format:%x", src_format); if(dst_x || dst_y) display_warning("dst_x:%d, dst_y:%d\n",dst_x, dst_y); for (j=0; j<src_height; j++) { for (i=0; i<src_width; i++) { buf[(j+(viewport_offset))*src_width+i] = (frameBuffer[(src_height-j-1)*(src_stride/2)+i]/(65536.0f*(2.0f/zscale)))+1-zscale/2.0f; } } #ifdef VPDEBUG if (dumping) { unsigned char * buf2 = (unsigned char *)malloc(src_width*(src_height+(viewport_offset))); for (i=0; i<src_width*src_height ; i++) buf2[i] = buf[i]*255.0f; ilTexImage(src_width, src_height, 1, 1, IL_LUMINANCE, IL_UNSIGNED_BYTE, buf2); char name[128]; static int id; sprintf(name, "dump/writedepth%d.png", id++); ilSaveImage(name); //printf("dumped gdLfbWriteRegion %s\n", name); free(buf2); } #endif glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glDrawBuffer(GL_BACK); glClear( GL_DEPTH_BUFFER_BIT ); glDepthMask(1); glDrawPixels(src_width, src_height+(viewport_offset), GL_DEPTH_COMPONENT, GL_FLOAT, buf); free(buf); } glDrawBuffer(current_buffer); glPopAttrib(); return FXTRUE; } /* wrapper-specific glide extensions */ FX_ENTRY char ** FX_CALL grQueryResolutionsExt(FxI32 * Size) { return 0; /* LOG("grQueryResolutionsExt\r\n"); return g_FullScreenResolutions.getResolutionsList(Size); */ } FX_ENTRY GrScreenResolution_t FX_CALL grWrapperFullScreenResolutionExt(FxU32* width, FxU32* height) { return 0; /* LOG("grWrapperFullScreenResolutionExt\r\n"); g_FullScreenResolutions.getResolution(config.res, width, height); return config.res; */ } FX_ENTRY FxBool FX_CALL grKeyPressedExt(FxU32 key) { return 0; /* #ifdef _WIN32 return (GetAsyncKeyState(key) & 0x8000); #else if (key == 1) //LBUTTON { Uint8 mstate = SDL_GetMouseState(NULL, NULL); return (mstate & SDL_BUTTON_LMASK); } else { Uint8 *keystates = SDL_GetKeyState( NULL ); if( keystates[ key ] ) { return 1; } else { return 0; } } #endif */ } FX_ENTRY void FX_CALL grConfigWrapperExt(FxI32 resolution, FxI32 vram, FxBool fbo, FxBool aniso) { LOG("grConfigWrapperExt\r\n"); config.res = resolution; config.vram_size = vram; config.fbo = fbo; config.anisofilter = aniso; } // unused by glide64 FX_ENTRY FxI32 FX_CALL grQueryResolutions( const GrResolution *resTemplate, GrResolution *output ) { int res_inf = 0; int res_sup = 0xf; int i; int n=0; LOG("grQueryResolutions\r\n"); display_warning("grQueryResolutions"); if ((unsigned int)resTemplate->resolution != GR_QUERY_ANY) { res_inf = res_sup = resTemplate->resolution; } if ((unsigned int)resTemplate->refresh == GR_QUERY_ANY) display_warning("querying any refresh rate"); if ((unsigned int)resTemplate->numAuxBuffers == GR_QUERY_ANY) display_warning("querying any numAuxBuffers"); if ((unsigned int)resTemplate->numColorBuffers == GR_QUERY_ANY) display_warning("querying any numColorBuffers"); if (output == NULL) return res_sup - res_inf + 1; for (i=res_inf; i<=res_sup; i++) { output[n].resolution = i; output[n].refresh = resTemplate->refresh; output[n].numAuxBuffers = resTemplate->numAuxBuffers; output[n].numColorBuffers = resTemplate->numColorBuffers; n++; } return res_sup - res_inf + 1; } FX_ENTRY FxBool FX_CALL grReset( FxU32 what ) { display_warning("grReset"); return 1; } FX_ENTRY void FX_CALL grEnable( GrEnableMode_t mode ) { LOG("grEnable(%d)\r\n", mode); if (mode == GR_TEXTURE_UMA_EXT) UMAmode = 1; } FX_ENTRY void FX_CALL grDisable( GrEnableMode_t mode ) { LOG("grDisable(%d)\r\n", mode); if (mode == GR_TEXTURE_UMA_EXT) UMAmode = 0; } FX_ENTRY void FX_CALL grDisableAllEffects( void ) { display_warning("grDisableAllEffects"); } FX_ENTRY void FX_CALL grErrorSetCallback( GrErrorCallbackFnc_t fnc ) { display_warning("grErrorSetCallback"); } FX_ENTRY void FX_CALL grFinish(void) { display_warning("grFinish"); } FX_ENTRY void FX_CALL grFlush(void) { display_warning("grFlush"); } FX_ENTRY void FX_CALL grTexMultibase( GrChipID_t tmu, FxBool enable ) { display_warning("grTexMultibase"); } FX_ENTRY void FX_CALL grTexMipMapMode( GrChipID_t tmu, GrMipMapMode_t mode, FxBool lodBlend ) { display_warning("grTexMipMapMode"); } FX_ENTRY void FX_CALL grTexDownloadTablePartial( GrTexTable_t type, void *data, int start, int end ) { display_warning("grTexDownloadTablePartial"); } FX_ENTRY void FX_CALL grTexDownloadTable( GrTexTable_t type, void *data ) { display_warning("grTexDownloadTable"); } FX_ENTRY FxBool FX_CALL grTexDownloadMipMapLevelPartial( GrChipID_t tmu, FxU32 startAddress, GrLOD_t thisLod, GrLOD_t largeLod, GrAspectRatio_t aspectRatio, GrTextureFormat_t format, FxU32 evenOdd, void *data, int start, int end ) { display_warning("grTexDownloadMipMapLevelPartial"); return 1; } FX_ENTRY void FX_CALL grTexDownloadMipMapLevel( GrChipID_t tmu, FxU32 startAddress, GrLOD_t thisLod, GrLOD_t largeLod, GrAspectRatio_t aspectRatio, GrTextureFormat_t format, FxU32 evenOdd, void *data ) { display_warning("grTexDownloadMipMapLevel"); } FX_ENTRY void FX_CALL grTexNCCTable( GrNCCTable_t table ) { display_warning("grTexNCCTable"); } FX_ENTRY void FX_CALL grViewport( FxI32 x, FxI32 y, FxI32 width, FxI32 height ) { display_warning("grViewport"); } FX_ENTRY void FX_CALL grDepthRange( FxFloat n, FxFloat f ) { display_warning("grDepthRange"); } FX_ENTRY void FX_CALL grSplash(float x, float y, float width, float height, FxU32 frame) { display_warning("grSplash"); } FX_ENTRY FxBool FX_CALL grSelectContext( GrContext_t context ) { display_warning("grSelectContext"); return 1; } FX_ENTRY void FX_CALL grAADrawTriangle( const void *a, const void *b, const void *c, FxBool ab_antialias, FxBool bc_antialias, FxBool ca_antialias ) { display_warning("grAADrawTriangle"); } FX_ENTRY void FX_CALL grAlphaControlsITRGBLighting( FxBool enable ) { display_warning("grAlphaControlsITRGBLighting"); } FX_ENTRY void FX_CALL grGlideSetVertexLayout( const void *layout ) { display_warning("grGlideSetVertexLayout"); } FX_ENTRY void FX_CALL grGlideGetVertexLayout( void *layout ) { display_warning("grGlideGetVertexLayout"); } FX_ENTRY void FX_CALL grGlideSetState( const void *state ) { display_warning("grGlideSetState"); } FX_ENTRY void FX_CALL grGlideGetState( void *state ) { display_warning("grGlideGetState"); } FX_ENTRY void FX_CALL grLfbWriteColorFormat(GrColorFormat_t colorFormat) { display_warning("grLfbWriteColorFormat"); } FX_ENTRY void FX_CALL grLfbWriteColorSwizzle(FxBool swizzleBytes, FxBool swapWords) { display_warning("grLfbWriteColorSwizzle"); } FX_ENTRY void FX_CALL grLfbConstantDepth( FxU32 depth ) { display_warning("grLfbConstantDepth"); } FX_ENTRY void FX_CALL grLfbConstantAlpha( GrAlpha_t alpha ) { display_warning("grLfbConstantAlpha"); } FX_ENTRY void FX_CALL grTexMultibaseAddress( GrChipID_t tmu, GrTexBaseRange_t range, FxU32 startAddress, FxU32 evenOdd, GrTexInfo *info ) { display_warning("grTexMultibaseAddress"); } /* inline void MySleep(FxU32 ms) { #ifdef _WIN32 Sleep(ms); #else SDL_Delay(ms); #endif } */ #ifdef _WIN32 static void CorrectGamma(LPVOID apGammaRamp) { HDC hdc = GetDC(NULL); if (hdc != NULL) { SetDeviceGammaRamp(hdc, apGammaRamp); ReleaseDC(NULL, hdc); } } #else static void CorrectGamma(const FxU16 aGammaRamp[3][256]) { //TODO? //int res = SDL_SetGammaRamp(aGammaRamp[0], aGammaRamp[1], aGammaRamp[2]); //LOG("SDL_SetGammaRamp returned %d\r\n", res); } #endif FX_ENTRY void FX_CALL grLoadGammaTable( FxU32 nentries, FxU32 *red, FxU32 *green, FxU32 *blue) { LOG("grLoadGammaTable\r\n"); if (!fullscreen) return; FxU16 aGammaRamp[3][256]; for (int i = 0; i < 256; i++) { aGammaRamp[0][i] = (FxU16)((red[i] << 8) & 0xFFFF); aGammaRamp[1][i] = (FxU16)((green[i] << 8) & 0xFFFF); aGammaRamp[2][i] = (FxU16)((blue[i] << 8) & 0xFFFF); } CorrectGamma(aGammaRamp); //MySleep(1000); //workaround for Mupen64 } FX_ENTRY void FX_CALL grGetGammaTableExt(FxU32 nentries, FxU32 *red, FxU32 *green, FxU32 *blue) { return; //TODO? /* LOG("grGetGammaTableExt()\r\n"); FxU16 aGammaRamp[3][256]; #ifdef _WIN32 HDC hdc = GetDC(NULL); if (hdc == NULL) return; if (GetDeviceGammaRamp(hdc, aGammaRamp) == TRUE) { ReleaseDC(NULL, hdc); #else if (SDL_GetGammaRamp(aGammaRamp[0], aGammaRamp[1], aGammaRamp[2]) != -1) { #endif for (int i = 0; i < 256; i++) { red[i] = aGammaRamp[0][i] >> 8; green[i] = aGammaRamp[1][i] >> 8; blue[i] = aGammaRamp[2][i] >> 8; } } */ } FX_ENTRY void FX_CALL guGammaCorrectionRGB( FxFloat gammaR, FxFloat gammaG, FxFloat gammaB ) { LOG("guGammaCorrectionRGB()\r\n"); if (!fullscreen) return; FxU16 aGammaRamp[3][256]; for (int i = 0; i < 256; i++) { aGammaRamp[0][i] = (((FxU16)((pow(i/255.0F, 1.0F/gammaR)) * 255.0F + 0.5F)) << 8) & 0xFFFF; aGammaRamp[1][i] = (((FxU16)((pow(i/255.0F, 1.0F/gammaG)) * 255.0F + 0.5F)) << 8) & 0xFFFF; aGammaRamp[2][i] = (((FxU16)((pow(i/255.0F, 1.0F/gammaB)) * 255.0F + 0.5F)) << 8) & 0xFFFF; } CorrectGamma(aGammaRamp); } FX_ENTRY void FX_CALL grDitherMode( GrDitherMode_t mode ) { display_warning("grDitherMode"); } void grChromaRangeExt(GrColor_t color0, GrColor_t color1, FxU32 mode) { display_warning("grChromaRangeExt"); } void grChromaRangeModeExt(GrChromakeyMode_t mode) { display_warning("grChromaRangeModeExt"); } void grTexChromaRangeExt(GrChipID_t tmu, GrColor_t color0, GrColor_t color1, GrTexChromakeyMode_t mode) { display_warning("grTexChromaRangeExt"); } void grTexChromaModeExt(GrChipID_t tmu, GrChromakeyMode_t mode) { display_warning("grTexChromaRangeModeExt"); } // VP debug #ifdef VPDEBUG int dumping = 0; static int tl_i; static int tl[10240]; void dump_start() { static int init; if (!init) { init = 1; ilInit(); ilEnable(IL_FILE_OVERWRITE); } dumping = 1; tl_i = 0; } void dump_stop() { if (!dumping) return; int i, j; for (i=0; i<nb_fb; i++) { dump_tex(fbs[i].texid); } dump_tex(default_texture); dump_tex(depth_texture); dumping = 0; glReadBuffer(GL_FRONT); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, frameBuffer); ilTexImage(width, height, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, frameBuffer); ilSaveImage("dump/framecolor.png"); glReadPixels(0, 0, width, height, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, depthBuffer); // FILE * fp = fopen("glide_depth1.bin", "rb"); // fread(depthBuffer, 2, width*height, fp); // fclose(fp); for (j=0; j<height; j++) { for (i=0; i<width; i++) { //uint16_t d = ( (uint16_t *)depthBuffer )[i+(height-1-j)*width]/2 + 0x8000; uint16_t d = ( (uint16_t *)depthBuffer )[i+j*width]; uint32_t c = ( (uint32_t *)frameBuffer )[i+j*width]; ( (unsigned char *)frameBuffer )[(i+j*width)*3] = d&0xff; ( (unsigned char *)frameBuffer )[(i+j*width)*3+1] = d>>8; ( (unsigned char *)frameBuffer )[(i+j*width)*3+2] = c&0xff; } } ilTexImage(width, height, 1, 3, IL_RGB, IL_UNSIGNED_BYTE, frameBuffer); ilSaveImage("dump/framedepth.png"); for (i=0; i<tl_i; i++) { glBindTexture(GL_TEXTURE_2D, tl[i]); GLint w, h, fmt; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &w); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &h); glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &fmt); fprintf(stderr, "Texture %d %dx%d fmt %x\n", tl[i], (int)w, (int)h, (int) fmt); uint32_t * pixels = (uint32_t *) malloc(w*h*4); // 0x1902 is another constant meaning GL_DEPTH_COMPONENT // (but isn't defined in gl's headers !!) if (fmt != GL_DEPTH_COMPONENT && fmt != 0x1902) { glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); ilTexImage(w, h, 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, pixels); } else { glGetTexImage(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, pixels); int i; for (i=0; i<w*h; i++) ((unsigned char *)frameBuffer)[i] = ((unsigned short *)pixels)[i]/256; ilTexImage(w, h, 1, 1, IL_LUMINANCE, IL_UNSIGNED_BYTE, frameBuffer); } char name[128]; // sprintf(name, "mkdir -p dump ; rm -f dump/tex%04d.png", i); // system(name); sprintf(name, "dump/tex%04d.png", i); fprintf(stderr, "Writing '%s'\n", name); ilSaveImage(name); // SDL_FreeSurface(surf); free(pixels); } glBindTexture(GL_TEXTURE_2D, default_texture); } void dump_tex(int id) { if (!dumping) return; int n; // yes, it's inefficient for (n=0; n<tl_i; n++) if (tl[n] == id) return; tl[tl_i++] = id; int i = tl_i-1; } #endif
gpl-3.0
ernestbuffington/PHP-Nuke-Titanium
themes/CarbinFiber-Red-Flames/theme.php
6651
<?php #---------------------------------------------------------------------------------------# # THEME SYSTEM FILE # #---------------------------------------------------------------------------------------# # THEME INFO # # CarbinFiber Theme v1.0 (Fixed & Full Width) # # # # Final Build Date 08/17/2019 Saturday 7:40pm # # # # A Very Nice Black Carbin Fiber Styled Design. # # Copyright © 2019 By: TheGhost AKA Ernest Allen Bffington # # e-Mail : ernest.buffington@gmail.com # #---------------------------------------------------------------------------------------# # CREATION INFO # # Created On: 1st August, 2019 (v1.0) # # # # Updated On: 1st August, 2019 (v3.0) # # HTML5 Theme Code Updated By: Lonestar (Lonestar-Modules.com) # # # # Read CHANGELOG File for Updates & Upgrades Info # # # # Designed By: TheGhost # # Web Site: https://theghost.86it.us # # Purpose: PHP-Nuke Titanium | Xtreme Evo # #---------------------------------------------------------------------------------------# # CMS INFO # # PHP-Nuke Copyright (c) 2006 by Francisco Burzi phpnuke.org # # PHP-Nuke Titanium (c) 2019 : Enhanced PHP-Nuke Web Portal System # #---------------------------------------------------------------------------------------# if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) { exit('Access Denied'); } $theme_name = basename(dirname(__FILE__)); #--------------------------# # Theme Management Section # #--------------------------# include(NUKE_THEMES_DIR.$theme_name.'/theme_info.php'); #-------------------------# # Theme Colors Definition # #-------------------------# global $digits_color, $fieldset_border_width, $fieldset_color, $define_theme_xtreme_209e, $avatar_overide_size, $ThemeInfo, $use_xtreme_voting, $make_xtreme_avatar_small; # This is to tell the main portal menu to luook for the images # in the theme dir "theme_name/images/menu" global $use_theme_image_dir_for_portal_menu; $use_theme_image_dir_for_portal_menu = false; $digits_color ='#ffb825'; $fieldset_border_width = '1px'; $fieldset_color = '#4e4e4e'; $define_theme_xtreme_209e = false; $avatar_overide_size = '150'; $make_xtreme_avatar_small = true; $use_xtreme_voting = false; $bgcolor1 = $ThemeInfo['bgcolor1']; $bgcolor2 = $ThemeInfo['bgcolor2']; $bgcolor3 = $ThemeInfo['bgcolor3']; $bgcolor4 = $ThemeInfo['bgcolor4']; $textcolor1 = $ThemeInfo['textcolor1']; $textcolor2 = $ThemeInfo['textcolor2']; define('carbinfiber_red_flames_theme_dir', 'themes/'.$theme_name.'/'); define('carbinfiber_red_flames_images_dir', carbinfiber_red_flames_theme_dir.'images/'); define('carbinfiber_red_flames_style_dir', carbinfiber_red_flames_theme_dir.'style/'); define('carbinfiber_red_flames_js_dir', carbinfiber_red_flames_style_dir.'js/'); define('carbinfiber_red_flames_hdr_images', carbinfiber_red_flames_images_dir.'hdr/'); define('carbinfiber_red_flames_ftr_images', carbinfiber_red_flames_images_dir.'ftr/'); define('carbinfiber_red_flames_width', ((substr($ThemeInfo['themewidth'], -1) == '%') ? str_replace('%','',($ThemeInfo['themewidth'])).'%' : str_replace('px','',($ThemeInfo['themewidth'])).'px')); define('carbinfiber_red_flames_copyright', 'CarbinFiber Red Flames Designed By: TheGhost<br />Copyright &copy '.date('Y').' The 86it Developer Network<br />All Rights Reserved'); define('carbinfiber_red_flames_copyright_click', 'Click the Link to Display Copyrights'); addCSSToHead(carbinfiber_red_flames_style_dir.'style.css','file'); addCSSToHead(carbinfiber_red_flames_style_dir.'menu.css','file'); #-------------------# # OpenTable Section # #-------------------# include_once(carbinfiber_red_flames_theme_dir.'function_OpenTable.php'); include_once(carbinfiber_red_flames_theme_dir.'function_CloseTable.php'); include_once(carbinfiber_red_flames_theme_dir.'function_OpenTable2.php'); include_once(carbinfiber_red_flames_theme_dir.'function_CloseTable2.php'); include_once(carbinfiber_red_flames_theme_dir.'function_OpenTable3.php'); include_once(carbinfiber_red_flames_theme_dir.'function_CloseTable3.php'); include_once(carbinfiber_red_flames_theme_dir.'function_OpenTable4.php'); include_once(carbinfiber_red_flames_theme_dir.'function_CloseTable4.php'); #---------------------# # FormatStory Section # #---------------------# include_once(carbinfiber_red_flames_theme_dir.'function_FormatStory.php'); #----------------# # Header Section # #----------------# function themeheader(){ include_once(carbinfiber_red_flames_theme_dir.'HDRcarbinfiber.php'); } #----------------# # Footer Section # #----------------# function themefooter(){ include_once(carbinfiber_red_flames_theme_dir.'FTRcarbinfiber.php'); } #--------------------# # News Index Section # #--------------------# include_once(carbinfiber_red_flames_theme_dir.'function_themeindex.php'); #----------------------# # News Article Section # #----------------------# include_once(carbinfiber_red_flames_theme_dir.'function_themearticle.php'); #-------------------# # Centerbox Section # #-------------------# include_once(carbinfiber_red_flames_theme_dir.'function_themecenterbox.php'); #-----------------# # Preview Section # #-----------------# include_once(carbinfiber_red_flames_theme_dir.'function_themepreview.php'); #-----------------# # Sidebox Section # #-----------------# include_once(carbinfiber_red_flames_theme_dir.'function_themesidebox.php'); ?>
gpl-3.0
sathukorale/libDatabaseHelper
libDatabaseHelperUnitTests/forms/frmInvalidSampleTable3_NoPrimaryKey.cs
1288
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using libDatabaseHelper.forms; using libDatabaseHelper.classes.generic; namespace libDatabaseHelperUnitTests.forms { public partial class frmInvalidSampleTable3_NoPrimaryKey : DatabaseEntityForm { public frmInvalidSampleTable3_NoPrimaryKey() { InitializeComponent(); SetOkButton(btnOK); SetResetButton(btnReset); SetCancelButton(btnCancel); txtColumn2.Tag = new TableColumnField(true, typeof(InvalidSampleTable3_NoPrimaryKey), "Column2"); cmbColumn3.Tag = new TableColumnField(true, typeof(InvalidSampleTable3_NoPrimaryKey), "Column3"); _type=typeof(InvalidSampleTable3_NoPrimaryKey); LoadColumns(); } #region "Autogenerated Data Loaders" private void LoadColumns() { try { var items = GenericDatabaseManager.GetDatabaseManager(DatabaseType.SqlCE).Select<SampleTable1>(null); cmbColumn3.Items.Clear(); cmbColumn3.Items.AddRange(items); } catch { } } #endregion } }
gpl-3.0
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-security-mvc-socket/src/main/webapp/resources/scripts/controllers/socketController.js
1495
'use strict'; angularApp .controller('socketController', function ($scope, SocketService) { /** * URL mapping endpoints. */ var SECURED_CHAT = '/secured/chat'; var SECURED_CHAT_HISTORY = '/secured/history'; var SECURED_CHAT_ROOM = '/secured/room'; var SECURED_CHAT_SPECIFIC_USER = '/secured/user/queue/specific-user'; var opts = { from: 'from', to: 'to', text: 'text', disconnect: 'disconnect', conversationDiv: 'conversationDiv', response: 'response' }; $scope.sendEndpoint = ''; $scope.stompClient = null; /** * Broadcast to All Users. */ $scope.connectAll = function (context) { $scope.sendEndpoint = context + SECURED_CHAT; $scope.stompClient = SocketService.connect($scope.sendEndpoint , opts, true); }; $scope.subscribeAll = function () { SocketService.subscribeToAll($scope.stompClient, SECURED_CHAT_HISTORY, opts); }; /** * Broadcast to Specific User. */ $scope.connectSpecific = function (context) { $scope.sendEndpoint = context + SECURED_CHAT_ROOM; $scope.stompClient = SocketService.connect(context + SECURED_CHAT_ROOM, opts, false); }; $scope.subscribeSpecific = function () { SocketService.subscribeToSpecific($scope.stompClient, SECURED_CHAT_SPECIFIC_USER, opts); }; $scope.disconnect = function () { SocketService.disconnect(opts, $scope.stompClient); }; $scope.sendMessage = function () { SocketService.sendMessage(opts, $scope.stompClient, $scope.sendEndpoint); }; });
gpl-3.0
selleron/pointageWebCEGID
user/pointage_prevision_user2_cegid.php
3298
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="fr" xml:lang="fr"> <head> <title> Pointage </title> <?PHP include_once("../header.php"); include_once("../sql/previsionnel_user_cegid.php"); include_once("../sql/member_db.php");// lien croisé avec tool_db.php include_once("../js/date_calendar.js"); // affichage calebdrier pour saisie date include_once("../js/form_db.js"); // affichage calebdrier pour saisie date ?> </head> <body> <div id="header"> <h1>Serveur Web Pointage : Gestion Pointage Previsionnel Utilisateurs</h1> </div> <div id="contenu"> <?PHP showBandeauHeaderPage("Gestion Pointage Previsionnel Par Collaborateur"); ?> <div class="article"> <div class="section"> <?php echo "<p>Gestion Pointage Previsionnel Par Collaborateur CEGID.<br/></p>"; showTracePOST(); beginTable();beginTableRow(); beginTableCell(); $multiselection = blockCondition("multiselection_pointage", "<h4>multi-selection [<value>]</h4>", false); endTableCell(); beginTableCell(); $inclureAbsence = blockCondition("include_abscence", "<h4>Inclure les absences [<value>]</h4>", false); endTableCell(); endTableRow();endTable(); echo "</tr></table>"; applyNextPreviousSelectUser(); echo"<p>"; //global $URL_ROOT_POINTAGE; global $urlPointage; global $urlPrevision; global $urlPrevisionProjet; global $urlPrevisionCollaborateur; ; showProjectSelection(""/*url*/,""/*form*/,"yes"/*year*/, "pointage;formaction='$urlPointage',previsionel;formaction='$urlPrevision',prev. collaborateurs;formaction='$urlPrevisionCollaborateur', prev. projet;formaction='$urlPrevisionProjet' ", "yes"/*user*/, "yes"/*previous*/, "yes"/*next*/, $multiselection); echo"<br/>Next Previous sur le user <br/></p>"; //actions $res = -1; //showAction("applyGestionOneProject"); $res = applyGestionOneProject(); if ($res<=0){ //showAction("applyGestionCoutOneProjectForm"); $res = applyGestionCoutOneProjectForm(); } if ($res <=0){ //showAction("applyGestionPrevisionnelUserCegid"); //$res = applyGestionPrevisionnelProjetCegid(); $res = applyGestionPrevisionnelUserCegid(); } if ($res <=0){ //showAction("applySynchronizePrevisionnel"); $res = applySynchronizePrevisionnel(); } // beginTable(); // beginTableRow( getVAlign("top") ); // beginTableCell(); // showGestionOneProject(); // endTableCell(); // beginTableCell(); // showTableCoutOneProjectPrevisionel(); // endTableCell(); // endTableRow(); // endTable(); //permet d'ajout un pointage pour un utilisateur showInsertTablePointageCegid(); //pour la resynchronisation showSynchronizePrevisionnel(); echo"<br>"; //show prevision showTablePrevisionnelByUserPointageCegid("no"); ?> <br/><br/><br/> </div> <!-- section --> </div> <!-- article --> </div> <!-- contenu --> <?PHP include("../menu.php"); ?> <?PHP include("../sql/deconnection_db.php"); ?> <?PHP include("../footer.php"); ?> </body> </html>
gpl-3.0
hy1314200/HyDM
Skyline.Commands/View/CommandViewPrint.cs
683
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Skyline.Core; namespace Skyline.Commands { public class CommandViewPrint:Skyline.Define.SkylineBaseCommand { public CommandViewPrint() { this.m_Category = "三维浏览"; this.m_Caption = "视图快照"; this.m_Message = "视图快照"; this.m_Tooltip = "点击将当前视图保存为图片"; } public override void OnClick() { MenuIDCommand.RunMenuCommand(m_SkylineHook.SGWorld, CommandParam.ISaveCamera, CommandParam.PSaveCamera); } } }
gpl-3.0
Robert09/TeleportMod
src/main/java/me/bubbles/teleportmod/reference/Names.java
279
package me.bubbles.teleportmod.reference; public final class Names { public static final class Keys { public static final String CATEGORY = "keys.teleportmod.category"; public static final String GET_COORDINATES = "keys.teleportmod.get_coordinates"; } }
gpl-3.0
jensnockert/ceres-api
lib/ceres/api/fw.rb
7295
# # fw.rb # This file is part of Ceres-API. # # Ceres 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. # # Ceres 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 Ceres-API. If not, see <http://www.gnu.org/licenses/>. # # Created by Jens Nockert on 11/4/09. # module Ceres class API def faction_warfare_statistics xml = self.download(Ceres.faction_warfare_urls[:statistics]) result = { :totals / :kills / :yesterday => xml.read_node("/eveapi/result/totals/killsYesterday").to_i, :totals / :kills / :last_week => xml.read_node("/eveapi/result/totals/killsLastWeek").to_i, :totals / :kills / :total => xml.read_node("/eveapi/result/totals/killsTotal").to_i, :totals / :victory_points / :yesterday => xml.read_node("/eveapi/result/totals/victoryPointsYesterday").to_i, :totals / :victory_points / :last_week => xml.read_node("/eveapi/result/totals/victoryPointsLastWeek").to_i, :totals / :victory_points / :total => xml.read_node("/eveapi/result/totals/victoryPointsTotal").to_i, :wars => xml.read_nodes("/eveapi/result/rowset[@name='factionWars']/row").map do |war| { :id => war.read_attribute("factionID").to_i, :name => war.read_attribute("factionName").to_s, :against / :id => war.read_attribute("againstID").to_i, :against / :name => war.read_attribute("againstName").to_s } end } [ [500001, :factions / :caldari], [500002, :factions / :minmatar], [500003, :factions / :amarr], [500004, :factions / :gallente] ].each do |faction_id, faction_symbol| faction = xml.read_node("/eveapi/result/rowset[@name='factions']/row[@factionID='#{faction_id}']") hash[faction_symbol / :id] = faction.read_attribute("factionID").to_i hash[faction_symbol / :name] = faction.read_attribute("factionName").to_s hash[faction_symbol / :pilots] = faction.read_attribute("pilots").to_i hash[faction_symbol / :systems_controlled] = faction.read_attribute("systemsControlled").to_i hash[faction_symbol / :kills / :yesterday] = faction.read_attribute("killsYesterday").to_i hash[faction_symbol / :kills / :last_week] = faction.read_attribute("killsLastWeek").to_i hash[faction_symbol / :kills / :total] = faction.read_attribute("killsTotal").to_i hash[faction_symbol / :victory_points / :yesterday] = faction.read_attribute("victoryPointsYesterday").to_i hash[faction_symbol / :victory_points / :last_week] = faction.read_attribute("victoryPointsLastWeek").to_i hash[faction_symbol / :victory_points / :total] = faction.read_attribute("victoryPointsTotal").to_i end return result, xml.cached_until end def faction_warfare_top_100 xml = self.download(Ceres.faction_warfare_urls[:top_100]) def parse_stats(xml, path, type) xml.findNodes(path).map do |character| hash = { :id => character.read_attribute("characterID").to_i, :name => character.read_attribute("characterName").to_s } case type when :kills hash[:kills] = character.read_attribute("kills").to_i when :victory_points hash[:victory_points] = character.read_attribute("victoryPoints") end end end result = { :characters / :kills / :yesterday => parse_stats(xml, "/eveapi/result/characters/rowset[@name='KillsYesterday']/row", :kills), :characters / :kills / :last_week => parse_stats(xml, "/eveapi/result/characters/rowset[@name='KillsLastWeek']/row", :kills), :characters / :kills / :total => parse_stats(xml, "/eveapi/result/characters/rowset[@name='KillsTotal']/row", :kills), :characters / :victory_points / :yesterday => parse_stats(xml, "/eveapi/result/characters/rowset[@name='VictoryPointsYesterday']/row", :victory_points), :characters / :victory_points / :last_week => parse_stats(xml, "/eveapi/result/characters/rowset[@name='VictoryPointsLastWeek']/row", :victory_points), :characters / :victory_points / :total => parse_stats(xml, "/eveapi/result/characters/rowset[@name='VictoryPointsTotal']/row", :victory_points), :corporations / :kills / :yesterday => parse_stats(xml, "/eveapi/result/corporations/rowset[@name='KillsYesterday']/row", :kills), :corporations / :kills / :last_week => parse_stats(xml, "/eveapi/result/corporations/rowset[@name='KillsLastWeek']/row", :kills), :corporations / :kills / :total => parse_stats(xml, "/eveapi/result/corporations/rowset[@name='KillsTotal']/row", :kills), :corporations / :victory_points / :yesterday => parse_stats(xml, "/eveapi/result/corporations/rowset[@name='VictoryPointsYesterday']/row", :victory_points), :corporations / :victory_points / :last_week => parse_stats(xml, "/eveapi/result/corporations/rowset[@name='VictoryPointsLastWeek']/row", :victory_points), :corporations / :victory_points / :total => parse_stats(xml, "/eveapi/result/corporations/rowset[@name='VictoryPointsTotal']/row", :victory_points), :factions / :kills / :yesterday => parse_stats(xml, "/eveapi/result/factions/rowset[@name='KillsYesterday']/row", :kills), :factions / :kills / :last_week => parse_stats(xml, "/eveapi/result/factions/rowset[@name='KillsLastWeek']/row", :kills), :factions / :kills / :total => parse_stats(xml, "/eveapi/result/factions/rowset[@name='KillsTotal']/row", :kills), :factions / :victory_points / :yesterday => parse_stats(xml, "/eveapi/result/factions/rowset[@name='VictoryPointsYesterday']/row", :victory_points), :factions / :victory_points / :last_week => parse_stats(xml, "/eveapi/result/factions/rowset[@name='VictoryPointsLastWeek']/row", :victory_points), :factions / :victory_points / :total => parse_stats(xml, "/eveapi/result/factions/rowset[@name='VictoryPointsTotal']/row", :victory_points) } return result, xml.cached_until end def occupancy xml = self.download(Ceres.faction_warfare_urls[:occupancy]) systems = xml.read_nodes("/eveapi/result/rowset/row").map do |system| { :id => system.read_attribute("solarSystemID").to_i, :name => system.read_attribute("solarSystemName").to_s, :contested => (system.read_attribute("contested").to_s == "True"), :faction / :id => system.read_attribute("occupyingFactionID").to_i, :faction / :name => system.read_attribute("occupyingFactionName").to_s } end return systems, xml.cached_until end end end
gpl-3.0
Libco/bestiary5thedition
app/src/main/java/sk/libco/bestiaryfive/ui/adapter/viewholder/MonsterViewHolder.java
770
package sk.libco.bestiaryfive.ui.adapter.viewholder; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import sk.libco.bestiaryfive.databinding.FragmentMonsterlistBinding; import sk.libco.bestiaryfive.ui.adapter.MonsterListAdapter; import sk.libco.bestiaryfive.ui.models.MonsterViewModel; public class MonsterViewHolder extends RecyclerView.ViewHolder { private final FragmentMonsterlistBinding mBinding; public MonsterViewHolder(FragmentMonsterlistBinding binding, MonsterListAdapter.Listener listener) { super(binding.getRoot()); binding.setListener(listener); mBinding = binding; } public void performBind(@NonNull MonsterViewModel item) { mBinding.setModel(item); } }
gpl-3.0
shengqh/RcpaBioJava
src/cn/ac/rcpa/database/utils/ApplicationContextFactory.java
1835
/* * Created on 2005-12-14 * * Rcpa development code * * Author Sheng QuanHu(qhsheng@sibs.ac.cn / shengqh@gmail.com) * This code is developed by RCPA Bioinformatic Platform * http://www.proteomics.ac.cn/ * */ package cn.ac.rcpa.database.utils; import java.util.HashMap; import java.util.Map; import org.hibernate.SessionFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.ac.rcpa.bio.database.RcpaDatabaseType; public class ApplicationContextFactory { private static Map<RcpaDatabaseType, String[]> databaseMap = new HashMap<RcpaDatabaseType, String[]>(); static { databaseMap.put(RcpaDatabaseType.ANNOTATION, new String[]{"annotation-applicationContext.xml","annotationSessionFactory"}); } private static Map<RcpaDatabaseType, ApplicationContext> applicationMap = new HashMap<RcpaDatabaseType, ApplicationContext>(); public static SessionFactory getSessionFactory(RcpaDatabaseType dbType) { String sessionFactoryName = databaseMap.get(dbType)[1]; return (SessionFactory)getContext(dbType).getBean(sessionFactoryName); } public static ApplicationContext getContext(RcpaDatabaseType dbType) { if (applicationMap.containsKey(dbType)) { return applicationMap.get(dbType); } if (!databaseMap.containsKey(dbType)) { throw new IllegalStateException( "There is no applicationContext defined to " + dbType + ", call programmer to correct it!"); } String applicationContextFile = databaseMap.get(dbType)[0]; ApplicationContext result = new ClassPathXmlApplicationContext( applicationContextFile); applicationMap.put(dbType, result); return result; } }
gpl-3.0
lyy289065406/expcodes
java/01-framework/dubbo-admin/incubator-dubbo-ops/dubbo-admin-backend/src/main/java/org/apache/dubbo/admin/web/mvc/governance/ServicesController.java
10329
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.admin.web.mvc.governance; import org.apache.dubbo.admin.registry.common.domain.Override; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.utils.StringUtils; import org.apache.dubbo.admin.governance.service.ConsumerService; import org.apache.dubbo.admin.governance.service.OverrideService; import org.apache.dubbo.admin.governance.service.ProviderService; import org.apache.dubbo.admin.registry.common.route.OverrideUtils; import org.apache.dubbo.admin.web.mvc.BaseController; import org.apache.dubbo.admin.web.pulltool.Tool; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.support.BindingAwareModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; /** * ProvidersController. URI: /services/$service/providers /addresses/$address/services /application/$application/services * */ @Controller @RequestMapping("/governance/services") public class ServicesController extends BaseController { @Autowired private ProviderService providerService; @Autowired private ConsumerService consumerService; @Autowired private OverrideService overrideService; @RequestMapping("") public String index(HttpServletRequest request, HttpServletResponse response, Model model) { prepare(request, response, model, "index", "services"); BindingAwareModelMap newModel = (BindingAwareModelMap)model; String service = (String)newModel.get("service"); String application = (String)newModel.get("app"); String address = (String)newModel.get("address"); String keyword = request.getParameter("keyword"); if (service == null && application == null && address == null) { model.addAttribute("service", "*"); } List<String> providerServices = null; List<String> consumerServices = null; List<Override> overrides = null; if (application != null && application.length() > 0) { model.addAttribute("app", application); providerServices = providerService.findServicesByApplication(application); consumerServices = consumerService.findServicesByApplication(application); overrides = overrideService.findByApplication(application); } else if (address != null && address.length() > 0) { providerServices = providerService.findServicesByAddress(address); consumerServices = consumerService.findServicesByAddress(address); overrides = overrideService.findByAddress(Tool.getIP(address)); } else { providerServices = providerService.findServices(); consumerServices = consumerService.findServices(); overrides = overrideService.findAll(); } Set<String> services = new TreeSet<String>(); if (providerServices != null) { services.addAll(providerServices); } if (consumerServices != null) { services.addAll(consumerServices); } Map<String, List<Override>> service2Overrides = new HashMap<String, List<Override>>(); if (overrides != null && overrides.size() > 0 && services != null && services.size() > 0) { for (String s : services) { if (overrides != null && overrides.size() > 0) { for (Override override : overrides) { List<Override> serOverrides = new ArrayList<Override>(); if (override.isMatch(s, address, application)) { serOverrides.add(override); } Collections.sort(serOverrides, OverrideUtils.OVERRIDE_COMPARATOR); service2Overrides.put(s, serOverrides); } } } } model.addAttribute("providerServices", providerServices); model.addAttribute("consumerServices", consumerServices); model.addAttribute("services", services); model.addAttribute("overrides", service2Overrides); if (keyword != null && !"*".equals(keyword)) { keyword = keyword.toLowerCase(); Set<String> newList = new HashSet<String>(); Set<String> newProviders = new HashSet<String>(); Set<String> newConsumers = new HashSet<String>(); for (String o : services) { if (o.toLowerCase().toLowerCase().indexOf(keyword) != -1) { newList.add(o); } if (o.toLowerCase().toLowerCase().equals(keyword.toLowerCase())) { service = o; } } for (String o : providerServices) { if (o.toLowerCase().indexOf(keyword) != -1) { newProviders.add(o); } } for (String o : consumerServices) { if (o.toLowerCase().indexOf(keyword) != -1) { newConsumers.add(o); } } model.addAttribute("services", newList); model.addAttribute("keyword", keyword); model.addAttribute("providerServices", newProviders); model.addAttribute("consumerServices", newConsumers); } return "governance/screen/services/index"; } @RequestMapping("/{ids}/shield") public String shield(@PathVariable("ids") Long[] ids, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { return mock(ids, "force:return null", "shield", request, response, model); } @RequestMapping("/{ids}/tolerant") public String tolerant(@PathVariable("ids") Long[] ids, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { return mock(ids, "fail:return null", "tolerant", request, response, model); } @RequestMapping("/{ids}/recover") public String recover(@PathVariable("ids") Long[] ids, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { return mock(ids, "", "recover", request, response, model); } private String mock(Long[] ids, String mock, String methodName, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { prepare(request, response, model, methodName, "services"); BindingAwareModelMap newModel = (BindingAwareModelMap)model; String services = (String) newModel.get("service"); String application = (String) newModel.get("app"); if (services == null || services.length() == 0 || application == null || application.length() == 0) { model.addAttribute("message", getMessage("NoSuchOperationData")); model.addAttribute("success", false); model.addAttribute("redirect", "../../services"); return "governance/screen/redirect"; } for (String service : SPACE_SPLIT_PATTERN.split(services)) { if (!super.currentUser.hasServicePrivilege(service)) { model.addAttribute("message", getMessage("HaveNoServicePrivilege", service)); model.addAttribute("success", false); model.addAttribute("redirect", "../../services"); return "governance/screen/redirect"; } } for (String service : SPACE_SPLIT_PATTERN.split(services)) { List<Override> overrides = overrideService.findByServiceAndApplication(service, application); if (overrides != null && overrides.size() > 0) { for (Override override : overrides) { Map<String, String> map = StringUtils.parseQueryString(override.getParams()); if (mock == null || mock.length() == 0) { map.remove("mock"); } else { map.put("mock", URL.encode(mock)); } if (map.size() > 0) { override.setParams(StringUtils.toQueryString(map)); override.setEnabled(true); override.setOperator(operator); override.setOperatorAddress(operatorAddress); overrideService.updateOverride(override); } else { overrideService.deleteOverride(override.getId()); } } } else if (mock != null && mock.length() > 0) { Override override = new Override(); override.setService(service); override.setApplication(application); override.setParams("mock=" + URL.encode(mock)); override.setEnabled(true); override.setOperator(operator); override.setOperatorAddress(operatorAddress); overrideService.saveOverride(override); } } model.addAttribute("success", true); model.addAttribute("redirect", "../../services"); return "governance/screen/redirect"; } }
gpl-3.0
CroissanceCommune/autonomie
autonomie/alembic/versions/2_2_activity_status__15d4152bd5d6.py
2581
"""2.2 : activity status and participants Revision ID: 15d4152bd5d6 Revises: b04de7c28 Create Date: 2014-06-23 17:55:00.671922 """ # revision identifiers, used by Alembic. revision = '15d4152bd5d6' down_revision = 'b04de7c28' from alembic import op import sqlalchemy as sa def upgrade(): from autonomie.models.activity import Attendance, Activity from autonomie_base.models.base import DBSESSION from alembic.context import get_bind session = DBSESSION() # Migrating attendance relationship query = "select event.id, event.status, rel.account_id, rel.activity_id from activity_participant rel inner join activity on rel.activity_id=activity.id LEFT JOIN event on event.id=activity.id" conn = get_bind() result = conn.execute(query) handled = [] for event_id, status, user_id, activity_id in result: if status == 'planned': user_status = 'registered' elif status == 'excused': user_status = 'excused' status = 'cancelled' elif status == 'closed': user_status = 'attended' elif status == 'absent': user_status = 'absent' status = 'cancelled' # create attendance for each participant if (user_id, activity_id) not in handled: a = Attendance() a.status = user_status a.account_id = user_id a.event_id = activity_id session.add(a) session.flush() # Update the event's status regarding the new norm query = "update event set status='{0}' where id='{1}';".format( status, event_id,) op.execute(query) handled.append((user_id, activity_id,)) # Migrating activity to add duration and use datetimes op.add_column('activity', sa.Column('duration', sa.Integer, default=0)) op.alter_column( 'event', 'date', new_column_name='datetime', type_=sa.DateTime() ) query = "select id, conseiller_id from activity;" result = conn.execute(query) values = [] for activity_id, conseiller_id in result: values.append("(%s, %s)" % (activity_id, conseiller_id)) if values != []: query = "insert into activity_conseiller (`activity_id`, `account_id`) \ VALUES {0}".format(','.join(values)) op.execute(query) op.execute("alter table activity drop foreign key `activity_ibfk_2`;") op.drop_column('activity', 'conseiller_id') op.drop_table('activity_participant') def downgrade(): pass
gpl-3.0
kms77/Fayabank
src/test/java/fr/trouillet/faya/fayabank/service/MailServiceIntTest.java
10502
/* * Copyright (c) 2017 dtrouillet * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package fr.trouillet.faya.fayabank.service; import fr.trouillet.faya.fayabank.FayabankApp; import fr.trouillet.faya.fayabank.domain.User; import io.github.jhipster.config.JHipsterProperties; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.MessageSource; import org.springframework.mail.MailSendException; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.test.context.junit4.SpringRunner; import org.thymeleaf.spring4.SpringTemplateEngine; import javax.mail.Multipart; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.ByteArrayOutputStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = FayabankApp.class) public class MailServiceIntTest { @Autowired private JHipsterProperties jHipsterProperties; @Autowired private MessageSource messageSource; @Autowired private SpringTemplateEngine templateEngine; @Spy private JavaMailSenderImpl javaMailSender; @Captor private ArgumentCaptor messageCaptor; private MailService mailService; @Before public void setup() { MockitoAnnotations.initMocks(this); doNothing().when(javaMailSender).send(any(MimeMessage.class)); mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine); } @Test public void testSendEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject","testContent", false, false); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); } @Test public void testSendHtmlEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject","testContent", false, true); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendMultipartEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject","testContent", true, false); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); MimeMultipart mp = (MimeMultipart) message.getContent(); MimeBodyPart part = (MimeBodyPart)((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); ByteArrayOutputStream aos = new ByteArrayOutputStream(); part.writeTo(aos); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); } @Test public void testSendMultipartHtmlEmail() throws Exception { mailService.sendEmail("john.doe@example.com", "testSubject","testContent", true, true); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); MimeMultipart mp = (MimeMultipart) message.getContent(); MimeBodyPart part = (MimeBodyPart)((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0); ByteArrayOutputStream aos = new ByteArrayOutputStream(); part.writeTo(aos); assertThat(message.getSubject()).isEqualTo("testSubject"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com"); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendEmailFromTemplate() throws Exception { User user = new User(); user.setLogin("john"); user.setEmail("john.doe@example.com"); user.setLangKey("en"); mailService.sendEmailFromTemplate(user, "testEmail", "email.test.title"); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); assertThat(message.getSubject()).isEqualTo("test title"); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).contains("<html>test title, http://127.0.0.1:8080, john</html>\n"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendActivationEmail() throws Exception { User user = new User(); user.setLangKey("fr"); user.setLogin("john"); user.setEmail("john.doe@example.com"); mailService.sendActivationEmail(user); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testCreationEmail() throws Exception { User user = new User(); user.setLangKey("fr"); user.setLogin("john"); user.setEmail("john.doe@example.com"); mailService.sendCreationEmail(user); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendPasswordResetMail() throws Exception { User user = new User(); user.setLangKey("fr"); user.setLogin("john"); user.setEmail("john.doe@example.com"); mailService.sendPasswordResetMail(user); verify(javaMailSender).send((MimeMessage) messageCaptor.capture()); MimeMessage message = (MimeMessage) messageCaptor.getValue(); assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail()); assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost"); assertThat(message.getContent().toString()).isNotEmpty(); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); } @Test public void testSendEmailWithException() throws Exception { doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class)); mailService.sendEmail("john.doe@example.com", "testSubject","testContent", false, false); } }
gpl-3.0
ondrik/libsfta
include/sfta/dual_hash_table_leaf_allocator.hh
9980
/***************************************************************************** * Symbolic Finite Tree Automata Library * * Copyright (c) 2010 Ondra Lengal <ondra@lengal.net> * * Description: * File with DualHashTableLeafAllocator policy for CUDDSharedMTBDD * *****************************************************************************/ #ifndef _SFTA_DUAL_HASH_TABLE_LEAF_ALLOCATOR_HH_ #define _SFTA_DUAL_HASH_TABLE_LEAF_ALLOCATOR_HH_ // Standard library header files #include <tr1/unordered_map> // Boost library headers #include <boost/functional/hash.hpp> // insert the class into proper namespace namespace SFTA { namespace Private { template < typename Leaf, typename Handle, class AbstractMonadicApplyFunctor > struct DualHashTableLeafAllocator; } } /** * @brief Leaf allocator that uses dual hash tables * @author Ondra Lengal <ondra@lengal.net> * @date 2010 * * This is a @c LeafAllocator policy for SFTA::CUDDSharedMTBDD that uses two * hash tables to provide mapping between virtual and real leaves of an MTBDD * and an inverse mapping. * * @see SFTA::CUDDSharedMTBDD * * @tparam Leaf The type of leaf. * @tparam Handle The type of handle. * @tparam AbstractMonadicApplyFunctor The type of the monadic Apply functor * of the underlying MTBDD package * facade. */ template < typename Leaf, typename Handle, class AbstractMonadicApplyFunctor > struct SFTA::Private::DualHashTableLeafAllocator { public: // Public data types /** * @brief Type of leaf * * The data type of leaf. */ typedef Leaf LeafType; /** * @brief Type of leaf handle * * The data type of leaf handle. */ typedef Handle HandleType; private: // Private data types /** * @brief Structure for handle <-> leaf pair * * This structure contains the pair of handle and leaf */ struct LeafDescriptor { public: // public data members /** * Leaf handle. */ HandleType handle; /** * Leaf. */ LeafType leaf; public: // public methods /** * @brief Constructor * * The constructor of the structure. */ LeafDescriptor(HandleType hndl, const LeafType& lf) : handle(hndl), leaf(lf) { } }; /** * Container that maps leaf handles to leaf desciptors */ typedef std::tr1::unordered_map<HandleType, LeafDescriptor*> HandleToDescriptorMap; /** * Container that maps leaves to leaf descriptors. */ typedef std::tr1::unordered_map<LeafType, LeafDescriptor*> LeafToDescriptorMap; /** * @brief The type of the Convert class * * The type of the Convert class. */ typedef SFTA::Private::Convert Convert; private: // Private data types /** * @brief Leaf releaser * * Monadic Apply functor that properly releases leaves. */ class ReleaserMonadicApplyFunctor : public AbstractMonadicApplyFunctor { private: DualHashTableLeafAllocator* allocator_; ReleaserMonadicApplyFunctor(const ReleaserMonadicApplyFunctor& func); ReleaserMonadicApplyFunctor& operator=( const ReleaserMonadicApplyFunctor& func); public: ReleaserMonadicApplyFunctor(DualHashTableLeafAllocator* allocator) : allocator_(allocator) { // Assertions assert(allocator_ != static_cast<DualHashTableLeafAllocator*>(0)); } virtual HandleType operator()(const HandleType& val) { return val; } }; private: // Private data members /** * Mapping of handles to leaf descriptors. */ HandleToDescriptorMap handles_; /** * Mapping of leaves to leaf descriptors. */ LeafToDescriptorMap leaves_; /** * @brief Counter of indices * * Counter of indices, if a new leaf is to be inserted, this counter * increments and the old value is returned. */ HandleType nextIndex_; /** * @brief Leaf releaser * * Monadic Apply functor that is used when a leaf is released. */ AbstractMonadicApplyFunctor* releaser_; protected:// Protected data memebers /** * @brief The bottom of the MTBDD * * The value used for the bottom of the MTBDD. */ static const HandleType BOTTOM; private: // Private methods DualHashTableLeafAllocator(const DualHashTableLeafAllocator&); DualHashTableLeafAllocator& operator=(const DualHashTableLeafAllocator&); /** * @brief Inserts leaf descriptor * * This method inserts a leaf descriptor into both maps. * * @param[in] leafPtr Pointer to leaf descriptor (pointer cannot point * to stack and by being passed to this method the * structure takes responsibility for its target) */ void insertLeafDescriptor(LeafDescriptor* leafPtr) { // insert the leaf -> descriptor pair to the map bool insertedNewLeaf = leaves_.insert(std::make_pair(leafPtr->leaf, leafPtr)).second; // check that new value really was inserted assert(insertedNewLeaf); // insert the handle -> descriptor pair to the map bool insertedNewHandle = handles_.insert(std::make_pair(leafPtr->handle, leafPtr)).second; // check that new value really was inserted assert(insertedNewHandle); } protected:// Protected methods /** * @brief Constructor * * The default constructor */ DualHashTableLeafAllocator() : handles_(), leaves_(), nextIndex_(BOTTOM + 1), releaser_(new ReleaserMonadicApplyFunctor(this)) { } /** * @brief Sets the value of bottom * * Sets the value of bottom of the MTBDD. This method needs to be called * before any other, otherwise the internal structure of mapping may be * inconsistent. * * @see BOTTOM * * @param[in] leaf The value of the bottom */ void setBottom(const LeafType& leaf) { LeafDescriptor* leafDesc = new LeafDescriptor(BOTTOM, leaf); insertLeafDescriptor(leafDesc); } /** * @brief Creates a leaf * * Attempts to first find the leaf in the container and in case it is not * there creates a new one and returns reference to it. * * @param[in] leaf The value of the leaf * * @returns Handle to the leaf */ HandleType createLeaf(const LeafType& leaf) { // first attempt to find the leaf if it already exists typename LeafToDescriptorMap::iterator itLeaf; if ((itLeaf = leaves_.find(leaf)) == leaves_.end()) { // in case the leaf is not in the structure yet // create new descriptor HandleType handle = nextIndex_; ++nextIndex_; LeafDescriptor* leafDesc = new LeafDescriptor(handle, leaf); insertLeafDescriptor(leafDesc); return handle; } else { // in case the leaf is already present return itLeaf->second->handle; } } /** * @brief Returns a leaf associated with given handle * * Returns the leaf that is at given container associated with given handle. * * @param[in] handle The handle the leaf for which is to be found * * @returns The leaf associated with given handle */ LeafType& getLeafOfHandle(const HandleType& handle) { // try to find given leafb typename HandleToDescriptorMap::iterator itHandles; if ((itHandles = handles_.find(handle)) == handles_.end()) { // in case it couldn't be found throw std::runtime_error("Trying to access leaf \"" + SFTA::Private::Convert::ToString(handle) + "\" that is not managed."); } return itHandles->second->leaf; } /** * @brief @copybrief getLeafOfHandle() * * @copydetails getLeafOfHandle() */ const LeafType& getLeafOfHandle(const HandleType& handle) const { // try to find given leaf typename HandleToDescriptorMap::const_iterator itHandles; if ((itHandles = handles_.find(handle)) == handles_.end()) { // in case it couldn't be found throw std::runtime_error("Trying to access leaf \"" + SFTA::Private::Convert::ToString(handle) + "\" that is not managed."); } return itHandles->second->leaf; } /** * @brief Returns all handles * * Returns a std::vector of all handles that have a leaf associated in the * container * * @returns A std::vector vector of all handles */ std::vector<HandleType> getAllHandles() const { std::vector<HandleType> result; for (typename HandleToDescriptorMap::const_iterator itHandles = handles_.begin(); itHandles != handles_.end(); ++itHandles) { // push back all handles that have associated a leaf in the container result.push_back(itHandles->first); } return result; } /** * @brief Gets the release functor * * Returns the release monadic Apply functor. This functor takes care of * properly releasing given leaf. * * @returns Proper release monadic Apply functor */ inline AbstractMonadicApplyFunctor* getLeafReleaser() { return releaser_; } /** * @brief Serialization method * * This method serializes the object into std::string */ std::string serialize() const { std::string result; result += "<mapleafallocator>\n"; std::vector<HandleType> handles = getAllHandles(); for (typename std::vector<HandleType>::const_iterator itHandle = handles.begin(); itHandle != handles.end(); ++itHandle) { result += "<pairing>"; result += "<left>"; result += Convert::ToString(*itHandle); result += "</left>"; result += "<right>"; result += Convert::ToString(getLeafOfHandle(*itHandle)); result += "</right>"; result += "</pairing>"; result += "\n"; } result += "</mapleafallocator>"; return result; }; /** * @brief Destructor * * The destructor. */ ~DualHashTableLeafAllocator() { delete releaser_; for (typename HandleToDescriptorMap::iterator itHandles = handles_.begin(); itHandles != handles_.end(); ++itHandles) { // for each handle delete itHandles->second; } } }; // The bottom of the MTBDD template < typename L, typename H, class AMAF > const typename SFTA::Private::DualHashTableLeafAllocator<L, H, AMAF>::HandleType SFTA::Private::DualHashTableLeafAllocator<L, H, AMAF>::BOTTOM = 0; #endif
gpl-3.0
justmesr/web-ui
src/app/core/store/collections/collections.state.ts
2231
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Answer Institute, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import {createEntityAdapter, EntityState} from '@ngrx/entity'; import {createSelector} from '@ngrx/store'; import {AppState} from '../app.state'; import {CollectionModel} from './collection.model'; import {selectQuery} from '../navigation/navigation.state'; export interface CollectionsState extends EntityState<CollectionModel> { loaded: boolean; } export const collectionsAdapter = createEntityAdapter<CollectionModel>({selectId: collection => collection.code}); export const initialCollectionsState: CollectionsState = collectionsAdapter.getInitialState({loaded: false}); export const selectCollectionsState = (state: AppState) => state.collections; export const selectAllCollections = createSelector(selectCollectionsState, collectionsAdapter.getSelectors().selectAll); export const selectCollectionsDictionary = createSelector(selectCollectionsState, collectionsAdapter.getSelectors().selectEntities); export const selectCollectionsLoaded = createSelector(selectCollectionsState, (state: CollectionsState) => state.loaded); export const selectCollectionsByQuery = createSelector(selectCollectionsDictionary, selectQuery, (collections, query) => { return query.collectionCodes.length === 0 ? Object.values(collections) : query.collectionCodes.map(code => collections[code]); }); export function selectCollectionByCode(code: string) { return createSelector(selectCollectionsDictionary, collections => collections[code]); }
gpl-3.0
janjouketjalsma/Panoply
config/cli-config.php
340
<?php use Doctrine\ORM\Tools\Console\ConsoleRunner; require 'vendor/autoload.php'; $settings = require __DIR__ .'/../app/settings.php'; $doctrineService = new Panoply\Service\Doctrine($settings['settings']['doctrine']); $entityManager = $doctrineService->entityManager(); return ConsoleRunner::createHelperSet($entityManager);
gpl-3.0
CrazyRundong/UWP-Playground
HamburgerNavigation/App.xaml.cs
3892
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace HamburgerNavigation { /// <summary> /// 提供特定于应用程序的行为,以补充默认的应用程序类。 /// </summary> sealed partial class App : Application { /// <summary> /// 初始化单一实例应用程序对象。这是执行的创作代码的第一行, /// 已执行,逻辑上等同于 main() 或 WinMain()。 /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// 在应用程序由最终用户正常启动时进行调用。 /// 将在启动应用程序以打开特定文件等情况下使用。 /// </summary> /// <param name="e">有关启动请求和过程的详细信息。</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // 不要在窗口已包含内容时重复应用程序初始化, // 只需确保窗口处于活动状态 if (rootFrame == null) { // 创建要充当导航上下文的框架,并导航到第一页 rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: 从之前挂起的应用程序加载状态 } // 将框架放在当前窗口中 Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // 当导航堆栈尚未还原时,导航到第一页, // 并通过将所需信息作为导航参数传入来配置 // 参数 rootFrame.Navigate(typeof(MainPage), e.Arguments); } // 确保当前窗口处于活动状态 Window.Current.Activate(); } } /// <summary> /// 导航到特定页失败时调用 /// </summary> ///<param name="sender">导航失败的框架</param> ///<param name="e">有关导航失败的详细信息</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// 在将要挂起应用程序执行时调用。 在不知道应用程序 /// 无需知道应用程序会被终止还是会恢复, /// 并让内存内容保持不变。 /// </summary> /// <param name="sender">挂起的请求的源。</param> /// <param name="e">有关挂起请求的详细信息。</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: 保存应用程序状态并停止任何后台活动 deferral.Complete(); } } }
gpl-3.0
ftisunpar/BlueTape
vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
19534
<?php namespace GuzzleHttp\Handler; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Promise\PromiseInterface; use GuzzleHttp\Psr7; use GuzzleHttp\TransferStats; use GuzzleHttp\Utils; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Psr\Http\Message\UriInterface; /** * HTTP handler that uses PHP's HTTP stream wrapper. * * @final */ class StreamHandler { /** * @var array */ private $lastHeaders = []; /** * Sends an HTTP request. * * @param RequestInterface $request Request to send. * @param array $options Request transfer options. */ public function __invoke(RequestInterface $request, array $options): PromiseInterface { // Sleep if there is a delay specified. if (isset($options['delay'])) { \usleep($options['delay'] * 1000); } $startTime = isset($options['on_stats']) ? Utils::currentTime() : null; try { // Does not support the expect header. $request = $request->withoutHeader('Expect'); // Append a content-length header if body size is zero to match // cURL's behavior. if (0 === $request->getBody()->getSize()) { $request = $request->withHeader('Content-Length', '0'); } return $this->createResponse( $request, $options, $this->createStream($request, $options), $startTime ); } catch (\InvalidArgumentException $e) { throw $e; } catch (\Exception $e) { // Determine if the error was a networking error. $message = $e->getMessage(); // This list can probably get more comprehensive. if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed || false !== \strpos($message, 'Connection refused') || false !== \strpos($message, "couldn't connect to host") // error on HHVM || false !== \strpos($message, "connection attempt failed") ) { $e = new ConnectException($e->getMessage(), $request, $e); } else { $e = RequestException::wrapException($request, $e); } $this->invokeStats($options, $request, $startTime, null, $e); return \GuzzleHttp\Promise\rejection_for($e); } } private function invokeStats( array $options, RequestInterface $request, ?float $startTime, ResponseInterface $response = null, \Throwable $error = null ): void { if (isset($options['on_stats'])) { $stats = new TransferStats( $request, $response, Utils::currentTime() - $startTime, $error, [] ); ($options['on_stats'])($stats); } } /** * @param resource $stream */ private function createResponse( RequestInterface $request, array $options, $stream, ?float $startTime ): PromiseInterface { $hdrs = $this->lastHeaders; $this->lastHeaders = []; $parts = \explode(' ', \array_shift($hdrs), 3); $ver = \explode('/', $parts[0])[1]; $status = (int) $parts[1]; $reason = $parts[2] ?? null; $headers = Utils::headersFromLines($hdrs); [$stream, $headers] = $this->checkDecode($options, $headers, $stream); $stream = Psr7\stream_for($stream); $sink = $stream; if (\strcasecmp('HEAD', $request->getMethod())) { $sink = $this->createSink($stream, $options); } $response = new Psr7\Response($status, $headers, $sink, $ver, $reason); if (isset($options['on_headers'])) { try { $options['on_headers']($response); } catch (\Exception $e) { $msg = 'An error was encountered during the on_headers event'; $ex = new RequestException($msg, $request, $response, $e); return \GuzzleHttp\Promise\rejection_for($ex); } } // Do not drain when the request is a HEAD request because they have // no body. if ($sink !== $stream) { $this->drain( $stream, $sink, $response->getHeaderLine('Content-Length') ); } $this->invokeStats($options, $request, $startTime, $response, null); return new FulfilledPromise($response); } private function createSink(StreamInterface $stream, array $options): StreamInterface { if (!empty($options['stream'])) { return $stream; } $sink = $options['sink'] ?? \fopen('php://temp', 'r+'); return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\stream_for($sink); } /** * @param resource $stream */ private function checkDecode(array $options, array $headers, $stream): array { // Automatically decode responses when instructed. if (!empty($options['decode_content'])) { $normalizedKeys = Utils::normalizeHeaderKeys($headers); if (isset($normalizedKeys['content-encoding'])) { $encoding = $headers[$normalizedKeys['content-encoding']]; if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') { $stream = new Psr7\InflateStream( Psr7\stream_for($stream) ); $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']]; // Remove content-encoding header unset($headers[$normalizedKeys['content-encoding']]); // Fix content-length header if (isset($normalizedKeys['content-length'])) { $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']]; $length = (int) $stream->getSize(); if ($length === 0) { unset($headers[$normalizedKeys['content-length']]); } else { $headers[$normalizedKeys['content-length']] = [$length]; } } } } } return [$stream, $headers]; } /** * Drains the source stream into the "sink" client option. * * @param string $contentLength Header specifying the amount of * data to read. * * @throws \RuntimeException when the sink option is invalid. */ private function drain( StreamInterface $source, StreamInterface $sink, string $contentLength ): StreamInterface { // If a content-length header is provided, then stop reading once // that number of bytes has been read. This can prevent infinitely // reading from a stream when dealing with servers that do not honor // Connection: Close headers. Psr7\copy_to_stream( $source, $sink, (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1 ); $sink->seek(0); $source->close(); return $sink; } /** * Create a resource and check to ensure it was created successfully * * @param callable $callback Callable that returns stream resource * * @return resource * * @throws \RuntimeException on error */ private function createResource(callable $callback) { $errors = []; \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool { $errors[] = [ 'message' => $msg, 'file' => $file, 'line' => $line ]; return true; }); $resource = $callback(); \restore_error_handler(); if (!$resource) { $message = 'Error creating resource: '; foreach ($errors as $err) { foreach ($err as $key => $value) { $message .= "[$key] $value" . \PHP_EOL; } } throw new \RuntimeException(\trim($message)); } return $resource; } /** * @return resource */ private function createStream(RequestInterface $request, array $options) { static $methods; if (!$methods) { $methods = \array_flip(\get_class_methods(__CLASS__)); } // HTTP/1.1 streams using the PHP stream wrapper require a // Connection: close header if ($request->getProtocolVersion() == '1.1' && !$request->hasHeader('Connection') ) { $request = $request->withHeader('Connection', 'close'); } // Ensure SSL is verified by default if (!isset($options['verify'])) { $options['verify'] = true; } $params = []; $context = $this->getDefaultContext($request); if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) { throw new \InvalidArgumentException('on_headers must be callable'); } if (!empty($options)) { foreach ($options as $key => $value) { $method = "add_{$key}"; if (isset($methods[$method])) { $this->{$method}($request, $context, $value, $params); } } } if (isset($options['stream_context'])) { if (!\is_array($options['stream_context'])) { throw new \InvalidArgumentException('stream_context must be an array'); } $context = \array_replace_recursive( $context, $options['stream_context'] ); } // Microsoft NTLM authentication only supported with curl handler if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) { throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler'); } $uri = $this->resolveHost($request, $options); $contextResource = $this->createResource( static function () use ($context, $params) { return \stream_context_create($context, $params); } ); return $this->createResource( function () use ($uri, &$http_response_header, $contextResource, $context, $options, $request) { $resource = \fopen((string) $uri, 'r', false, $contextResource); $this->lastHeaders = $http_response_header; if (false === $resource) { throw new ConnectException( sprintf('Connection refused for URI %s', $uri), $request, null, $context ); } if (isset($options['read_timeout'])) { $readTimeout = $options['read_timeout']; $sec = (int) $readTimeout; $usec = ($readTimeout - $sec) * 100000; \stream_set_timeout($resource, $sec, $usec); } return $resource; } ); } private function resolveHost(RequestInterface $request, array $options): UriInterface { $uri = $request->getUri(); if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) { if ('v4' === $options['force_ip_resolve']) { $records = \dns_get_record($uri->getHost(), \DNS_A); if (false === $records || !isset($records[0]['ip'])) { throw new ConnectException( \sprintf( "Could not resolve IPv4 address for host '%s'", $uri->getHost() ), $request ); } return $uri->withHost($records[0]['ip']); } if ('v6' === $options['force_ip_resolve']) { $records = \dns_get_record($uri->getHost(), \DNS_AAAA); if (false === $records || !isset($records[0]['ipv6'])) { throw new ConnectException( \sprintf( "Could not resolve IPv6 address for host '%s'", $uri->getHost() ), $request ); } return $uri->withHost('[' . $records[0]['ipv6'] . ']'); } } return $uri; } private function getDefaultContext(RequestInterface $request): array { $headers = ''; foreach ($request->getHeaders() as $name => $value) { foreach ($value as $val) { $headers .= "$name: $val\r\n"; } } $context = [ 'http' => [ 'method' => $request->getMethod(), 'header' => $headers, 'protocol_version' => $request->getProtocolVersion(), 'ignore_errors' => true, 'follow_location' => 0, ], ]; $body = (string) $request->getBody(); if (!empty($body)) { $context['http']['content'] = $body; // Prevent the HTTP handler from adding a Content-Type header. if (!$request->hasHeader('Content-Type')) { $context['http']['header'] .= "Content-Type:\r\n"; } } $context['http']['header'] = \rtrim($context['http']['header']); return $context; } /** * @param mixed $value as passed via Request transfer options. */ private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void { if (!\is_array($value)) { $options['http']['proxy'] = $value; } else { $scheme = $request->getUri()->getScheme(); if (isset($value[$scheme])) { if (!isset($value['no']) || !Utils::isHostInNoProxy( $request->getUri()->getHost(), $value['no'] ) ) { $options['http']['proxy'] = $value[$scheme]; } } } } /** * @param mixed $value as passed via Request transfer options. */ private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void { if ($value > 0) { $options['http']['timeout'] = $value; } } /** * @param mixed $value as passed via Request transfer options. */ private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void { if ($value === false) { $options['ssl']['verify_peer'] = false; $options['ssl']['verify_peer_name'] = false; return; } if (\is_string($value)) { $options['ssl']['cafile'] = $value; if (!\file_exists($value)) { throw new \RuntimeException("SSL CA bundle not found: $value"); } } elseif ($value !== true) { throw new \InvalidArgumentException('Invalid verify request option'); } $options['ssl']['verify_peer'] = true; $options['ssl']['verify_peer_name'] = true; $options['ssl']['allow_self_signed'] = false; } /** * @param mixed $value as passed via Request transfer options. */ private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void { if (\is_array($value)) { $options['ssl']['passphrase'] = $value[1]; $value = $value[0]; } if (!\file_exists($value)) { throw new \RuntimeException("SSL certificate not found: {$value}"); } $options['ssl']['local_cert'] = $value; } /** * @param mixed $value as passed via Request transfer options. */ private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void { $this->addNotification( $params, static function ($code, $a, $b, $c, $transferred, $total) use ($value) { if ($code == \STREAM_NOTIFY_PROGRESS) { $value($total, $transferred, null, null); } } ); } /** * @param mixed $value as passed via Request transfer options. */ private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void { if ($value === false) { return; } static $map = [ \STREAM_NOTIFY_CONNECT => 'CONNECT', \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED', \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT', \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS', \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS', \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED', \STREAM_NOTIFY_PROGRESS => 'PROGRESS', \STREAM_NOTIFY_FAILURE => 'FAILURE', \STREAM_NOTIFY_COMPLETED => 'COMPLETED', \STREAM_NOTIFY_RESOLVE => 'RESOLVE', ]; static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max']; $value = Utils::debugResource($value); $ident = $request->getMethod() . ' ' . $request->getUri()->withFragment(''); $this->addNotification( $params, static function () use ($ident, $value, $map, $args): void { $passed = \func_get_args(); $code = \array_shift($passed); \fprintf($value, '<%s> [%s] ', $ident, $map[$code]); foreach (\array_filter($passed) as $i => $v) { \fwrite($value, $args[$i] . ': "' . $v . '" '); } \fwrite($value, "\n"); } ); } private function addNotification(array &$params, callable $notify): void { // Wrap the existing function if needed. if (!isset($params['notification'])) { $params['notification'] = $notify; } else { $params['notification'] = $this->callArray([ $params['notification'], $notify ]); } } private function callArray(array $functions): callable { return static function () use ($functions) { $args = \func_get_args(); foreach ($functions as $fn) { \call_user_func_array($fn, $args); } }; } }
gpl-3.0
waikato-datamining/adams-base
adams-spreadsheet/src/main/java/adams/flow/core/MissingLookUpKey.java
1164
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * MissingLookUpKey.java * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand */ package adams.flow.core; /** * Describes the behaviors if a lookup key is not found. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public enum MissingLookUpKey { /** don't output anything. */ NO_OUTPUT, /** output the missing value. */ OUTPUT_MISSING_VALUE, /** output the key. */ OUTPUT_KEY, /** report an error. */ CAUSE_ERROR }
gpl-3.0
nicolacimmino/ExpensesTracker
AndroidApplication/android/ExpensesReporter/tracker/src/main/java/com/nicolacimmino/expensestracker/tracker/expenses_api/ExpensesApiGetExpensesRequest.java
1652
/* ExpensesApiGetExpensesRequest is part of ExpensesTracker and represents a specialized request * to the Expenses API. * * Copyright (C) 2014 Nicola Cimmino * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * */ package com.nicolacimmino.expensestracker.tracker.expenses_api; import com.nicolacimmino.expensestracker.tracker.data_sync.ExpensesAccountResolver; import org.json.JSONArray; /* * Specialization of ExpensesApiRequest to request all expenses for the user. */ public class ExpensesApiGetExpensesRequest extends ExpensesApiRequest { public ExpensesApiGetExpensesRequest() { // API call to get all expenses is: // GET /expenses/:username setRequestMethod("GET"); setUrl(ExpensesApiContract.URL + "/expenses/" + ExpensesAccountResolver.getInstance().getUsername() + "?auth_token=" + ExpensesAccountResolver.getInstance().getAuthorizationToken()); } // Gets the expenses returned by the API. public JSONArray getExpenses() { return jsonResponseArray; } }
gpl-3.0
PaleoCrafter/paleocraft
pc_common/de/paleocrafter/pcraft/tileentity/TileFossil.java
474
package de.paleocrafter.pcraft.tileentity; import java.util.Random; import cpw.mods.fml.common.network.PacketDispatcher; /** * PaleoCraft * * TileFossil * * @author PaleoCrafter * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) */ public class TileFossil extends TilePC { public void init() { this.setOrientation(new Random().nextInt(5)); PacketDispatcher.sendPacketToAllPlayers(getDescriptionPacket()); } }
gpl-3.0
bhatfield/jsduck
lib/jsduck/source/file_parser.rb
1993
require 'jsduck/js_parser' require 'jsduck/css_parser' require 'jsduck/doc_parser' require 'jsduck/merger' require 'jsduck/ast' require 'jsduck/doc_type' require 'jsduck/doc_ast' require 'jsduck/class_doc_expander' module JsDuck module Source # Performs the actual parsing of CSS or JS source. # # This is the class that brings together all the different steps of # parsing the source. class FileParser def initialize @doc_type = DocType.new @doc_parser = DocParser.new @class_doc_expander = ClassDocExpander.new @doc_ast = DocAst.new @merger = Merger.new end # Parses file into final docset that can be fed into Aggregator def parse(contents, filename="", options={}) @doc_ast.filename = filename parse_js_or_css(contents, filename, options).map do |docset| expand(docset) end.flatten.map do |docset| merge(docset) end end private # Parses the file depending on filename as JS or CSS def parse_js_or_css(contents, filename, options) if filename =~ /\.s?css$/ docs = CssParser.new(contents, options).parse else docs = JsParser.new(contents, options).parse docs = Ast.new(docs, options).detect_all! end end # Parses the docs, detects tagname and expands class docset def expand(docset) docset[:comment] = @doc_parser.parse(docset[:comment], @doc_ast.filename, docset[:linenr]) docset[:tagname] = @doc_type.detect(docset[:comment], docset[:code]) if docset[:tagname] == :class @class_doc_expander.expand(docset) else docset end end # Merges comment and code parts of docset def merge(docset) @doc_ast.linenr = docset[:linenr] docset[:comment] = @doc_ast.detect(docset[:tagname], docset[:comment]) @merger.merge(docset) end end end end
gpl-3.0
lsuits/Moodle-2.0-Plugin-for-Panopto
db/access.php
2383
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package block_panopto * @copyright Panopto 2009 - 2015 with contributions from Spenser Jones (sjones@ambrose.edu) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $capabilities = array( 'block/panopto:provision_course' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW, ) ), 'block/panopto:provision_multiple' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'block/panopto:provision_asteacher' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array() ), 'block/panopto:provision_aspublisher' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array() ), 'block/panopto:addinstance' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:manageblocks' ), 'block/panopto:myaddinstance' => array('captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW, ), 'clonepermissionsfrom' => 'moodle/my:manageblocks' ) ); /* End of file access.php */
gpl-3.0
kanafghan/jpizzeria
site/controllers/opinion.php
1431
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla controllerform library jimport('joomla.application.component.controller'); /** * Opinion Controller */ class PizzaControllerOpinion extends JController { /** * Proxy for getModel. * @since 1.6 */ public function getModel($name = 'Opinions', $prefix = 'PizzaModel') { $model = parent::getModel($name, $prefix, array('ignore_request' => true)); return $model; } public function add() { // get form data $input = JFactory::getApplication()->input; $data = $input->getArray(array( 'review' => 'STRING', 'customer_id' => 'INT', 'item_id' => 'INT' )); $data['creation_date'] = date(JFactory::getDbo()->getDateFormat()); if (empty($data['review'])) { $url = 'index.php?option=com_pizza&view=opinions&layout=modal&'; $url .= 'tmpl=component&itemId='. $data['item_id']; $this->setRedirect( $url, JText::_('COM_PIZZA_ERROR_NO_REVIEW'), 'error' ); return false; } $url = ''; $model = $this->getModel('review'); if (!$model->save($data)) { $this->setMessage(JText::_('COM_PIZZA_ERROR_SAVING_REVIEW'), 'error'); $url = 'index.php?option=com_pizza&view=opinions&layout=modal&'; $url .= 'tmpl=component&itemId='. $data['item_id']; } else { $url = 'index.php?option=com_pizza&view=close&tmpl=component'; } $this->setRedirect($url); } }
gpl-3.0
ZeroOne71/ql
02_ECCentral/03_Service/BizEntity/Customer/CustomerInfo/CustomerPrepayLog.cs
1143
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ECCentral.BizEntity.Common; namespace ECCentral.BizEntity.Customer { /// <summary> /// 客户余额日志 /// </summary> public class CustomerPrepayLog : IIdentity { /// <summary> /// 余额日志的系统编号 /// </summary> public int? SysNo { get; set; } /// <summary> /// 用户系统编号 /// </summary> public int? CustomerSysNo { get; set; } /// <summary> /// 调整类型 /// </summary> public PrepayType? PrepayType { get; set; } /// <summary> /// 订单系统编号 /// </summary> public int? SOSysNo { get; set; } /// <summary> /// 调整金额,如果是消费的话值为负数,如果是获得(包括消费返还)值为正数 /// </summary> public decimal? AdjustAmount { get; set; } // public string Memo { get; set; } /// <summary> /// 调整备注 /// </summary> public string Note { get; set; } } }
gpl-3.0
Jameswiseman/techjobs
webpack/src/store/modules/positions.js
3839
import * as types from '../mutation-types' import Vue from 'vue' // Initial state const state = { all: [], currentPage: 1, loadCompleted: false } const actions = { getAllPositions ({ commit }) { Vue.http.get('http://localhost:3000/positions?_sort=updatedAt&_order=DESC').then((response) => { const positions = response.body commit(types.RECEIVE_POSITIONS, { positions }) }) }, getInitialPositions ({ commit }) { Vue.http.get('http://localhost:3000/positions?_sort=updatedAt&_order=DESC&_limit=5&_page=1').then((response) => { const positions = response.body commit(types.RECEIVE_POSITIONS, { positions }) }) }, getNextPositions ({ commit }) { const nextPage = state.currentPage + 1 Vue.http.get(`http://localhost:3000/positions?_sort=updatedAt&_order=DESC&_limit=10&_page=${nextPage}`).then((response) => { const positions = response.body console.log(positions) if (positions.length === 0) { state.loadCompleted = true return } commit(types.NEXT_POSITION, { positions }) state.currentPage = nextPage }) }, getPosition ({ commit }) { }, createPosition ({ commit }, newPosition) { Vue.http.post('http://localhost:3000/positions', { 'title': newPosition.title, 'salary': newPosition.salary, 'description': newPosition.description, 'type': newPosition.type, 'category': newPosition.category, 'company': { 'name': newPosition.company.name, 'location': newPosition.company.location, 'email': newPosition.company.email, 'website': newPosition.company.website }, 'updatedAt': newPosition.createdAt || new Date(), 'createdAt': newPosition.createdAt || new Date() }).then((response) => { console.log('success') console.log(response) const position = response.body console.log(position) commit(types.CREATE_POSITION, {position}) }) }, deletePosition ({ commit }, position) { console.log('Call Remove Position to API') Vue.http.delete(`http://localhost:3000/positions/${position.id}`) .then((response) => { commit(types.DELETE_POSITION, { position }) }) }, updatePosition ({ commit }, position) { console.log('[Update Position] Call to API') Vue.http.put(`http://localhost:3000/positions/${position.id}`, { 'title': position.title, 'salary': position.salary, 'description': position.description, 'type': position.type, 'category': position.category, 'company': { 'name': position.company.name, 'location': position.company.location, 'email': position.company.email, 'website': position.company.website }, 'updatedAt': new Date() }).then((response) => { console.log('success') console.log(response) const position = response.body console.log(position) commit(types.UPDATE_POSITION, {position}) }) } } const mutations = { [types.RECEIVE_POSITIONS] (state, { positions }) { state.all = positions }, [types.CREATE_POSITION] (state, { position }) { console.log('Mutation with CREATE') console.log(position) state.all.push(position) }, [types.DELETE_POSITION] (state, { position }) { console.log('Mutation with DELETE') const index = state.all.indexOf(position) state.all.splice(index, 1) }, [types.UPDATE_POSITION] (state, { positions }) { console.log('Mutation with UPDATE') }, [types.NEXT_POSITION] (state, { positions }) { for (let i = 0; i < positions.length; i++) { state.all.push(positions[i]) } } } const getters = { allPositions: state => state.all, loadCompleted: state => state.loadCompleted } export default { state, mutations, getters, actions }
gpl-3.0
hamstercat/perfect-media
PerfectMedia.UI/Images/ImageLoader.cs
10275
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImageLoader.cs" company="Bryan A. Woodruff"> // Copyright (c) 2011 Bryan A. Woodruff. // </copyright> // <summary> // The ImageLoader class is a derived class of System.Windows.Controls.Image. // It uses BitmapImage as a source to load the associated ImageUri and displays // an initial image in place until the image load has completed. // </summary> // <license> // Microsoft Public License (Ms-PL) // // This license governs use of the accompanying software. If you use the software, you accept this license. // If you do not accept the license, do not use the software. // // * Definitions // The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here // as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the // software. A "contributor" is any person that distributes its contribution under this license. // "Licensed patents" are a contributor's patent claims that read directly on its contribution. // // * Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the license conditions and // limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright // license to reproduce its contribution, prepare derivative works of its contribution, and distribute its // contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in // section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its // licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its // contribution in the software or derivative works of the contribution in the software. // // * Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or // trademarks. // (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the // software, your patent license from such contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and // attribution notices that are present in the software. // (D) If you distribute any portion of the software in source code form, you may do so only under this license // by including a complete copy of this license with your distribution. If you distribute any portion of the // software in compiled or object code form, you may only do so under a license that complies with this // license. // (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, // guarantees, or conditions. You may have additional consumer rights under your local laws which this license // cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties // of merchantability, fitness for a particular purpose and non-infringement. // </license> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO; using System.Net.Cache; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace PerfectMedia.UI.Images { /// <summary> /// Defines the ImageLoader class, derived from System.Windows.Controls.Image. /// </summary> public class ImageLoader : System.Windows.Controls.Image { /// <summary> /// The ImageUri dependency property. /// </summary> public static readonly DependencyProperty ImageUriProperty = DependencyProperty.Register("ImageUri", typeof(string), typeof(ImageLoader), new PropertyMetadata(null, OnImageUriChanged)); private static void OnImageUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var imageLoader = (ImageLoader)d; if (e.NewValue != e.OldValue) { imageLoader._retryCount = 0; imageLoader.Refresh(); } } /// <summary> /// Gets or sets the ImageUri property. /// </summary> public string ImageUri { get { return (string)GetValue(ImageUriProperty); } set { SetValue(ImageUriProperty, value); } } /// <summary> /// The WidthRatio dependency property. /// </summary> public static readonly DependencyProperty WidthRatioProperty = DependencyProperty.Register("WidthRatio", typeof(double), typeof(ImageLoader), new PropertyMetadata(0d, OnRatioChanged)); private static void OnRatioChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var imageLoader = (ImageLoader)d; imageLoader.LoadInitialImage(); } /// <summary> /// Gets or sets the width ratio. /// </summary> public double WidthRatio { get { return (double)GetValue(WidthRatioProperty); } set { SetValue(WidthRatioProperty, value); } } /// <summary> /// The HeightRatio dependency property. /// </summary> public static readonly DependencyProperty HeightRatioProperty = DependencyProperty.Register("HeightRatio", typeof(double), typeof(ImageLoader), new PropertyMetadata(0d, OnRatioChanged)); /// <summary> /// Gets or sets the height ratio. /// </summary> public double HeightRatio { get { return (double)GetValue(HeightRatioProperty); } set { SetValue(HeightRatioProperty, value); } } /// <summary> /// Gets or sets the source property which forwards to the base Image class. /// This is made an internal property in ImageLoader to prevent confusion with the base class. /// This property is managed as a result of the bitmap load operations. /// </summary> private new ImageSource Source { get { return base.Source; } set { base.Source = value; } } /// <summary> /// Storage for the loaded image. /// </summary> private BitmapImage _loadedImage; /// <summary> /// Number of times an image has failed to load in a refresh. /// </summary> private int _retryCount; /// <summary> /// True if the image from ImageUri has been loaded. /// </summary> private bool _imageLoaded; /// <summary> /// Handles the download failure event. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="e">The event arguments.</param> private void OnDownloadFailed(object sender, ExceptionEventArgs e) { if (_retryCount < 2) { Refresh(); } } /// <summary> /// Handles the DownloadCompleted event. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="e">The event arguments.</param> private void OnDownloadCompleted(object sender, EventArgs e) { _imageLoaded = true; Source = _loadedImage; } private void Refresh() { _imageLoaded = false; if (!string.IsNullOrEmpty(ImageUri) && PathIsValid(ImageUri)) { _retryCount++; LoadImage(); // The image may be cached, in which case we will not use the initial image if (!_loadedImage.IsDownloading) { _imageLoaded = true; Source = _loadedImage; } else { LoadInitialImage(); } } else { LoadInitialImage(); } } private bool PathIsValid(string imagePath) { return IsPathAnUrl(imagePath) || FileExists(imagePath); } private bool IsPathAnUrl(string path) { return path.StartsWith("http://") || path.StartsWith("https://"); } private static bool FileExists(string imagePath) { var file = new FileInfo(imagePath); return file.Exists && file.Length > 0; } private void LoadImage() { _loadedImage = new BitmapImage(); _loadedImage.BeginInit(); _loadedImage.CacheOption = BitmapCacheOption.OnLoad; _loadedImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache | BitmapCreateOptions.IgnoreColorProfile; _loadedImage.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); _loadedImage.DownloadCompleted += OnDownloadCompleted; _loadedImage.DownloadFailed += OnDownloadFailed; _loadedImage.UriSource = new Uri(ImageUri); _loadedImage.EndInit(); } private void LoadInitialImage() { if (!_imageLoaded) { // Set the initial image as the image source Source = CreateInitialImage(); } } private DrawingImage CreateInitialImage() { var geometryGroup = new GeometryGroup(); geometryGroup.Children.Add( new RectangleGeometry(new Rect(0, 0, WidthRatio, HeightRatio)) ); var geometryDrawing = new GeometryDrawing { Geometry = geometryGroup, Brush = new SolidColorBrush(Colors.LightGray) }; var image = new DrawingImage(geometryDrawing); image.Freeze(); return image; } } }
gpl-3.0
pomahtuk/vadim_folio
works/migrations/0001_initial.py
2302
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-10 14:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import embed_video.fields import sorl.thumbnail.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Work', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='\u0417\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a')), ], options={ 'verbose_name': '\u041f\u0440\u043e\u0435\u043a\u0442', 'verbose_name_plural': '\u041f\u0440\u043e\u0435\u043a\u0442\u044b', }, ), migrations.CreateModel( name='WorkPart', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200, verbose_name='\u0417\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a')), ('content', models.TextField(verbose_name='\u041e\u043f\u0438\u0441\u0430\u043d\u0438\u0435')), ('use_video', models.BooleanField(default=False, verbose_name='\u0412\u0438\u0434\u0435\u043e\u0431\u044d\u043a\u0433\u0440\u0430\u0443\u043d\u0434?')), ('image', sorl.thumbnail.fields.ImageField(null=True, upload_to='news/', verbose_name='\u0418\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435')), ('video', embed_video.fields.EmbedVideoField(null=True, verbose_name='\u0421\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 youtube')), ('work', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='detail', to='works.Work', verbose_name='\u041f\u0440\u043e\u0435\u043a\u0442')), ], options={ 'verbose_name': '\u041f\u043e\u0434\u0440\u043e\u0431\u043d\u043e\u0441\u0442\u044c', 'verbose_name_plural': '\u041f\u043e\u0434\u0440\u043e\u0431\u043d\u043e\u0441\u0442\u0438', }, ), ]
gpl-3.0
cereda/macro-expander
src/main/java/br/usp/poli/lta/cereda/macro/model/Macro.java
5084
/** * ------------------------------------------------------ * Laboratório de Linguagens e Técnicas Adaptativas * Escola Politécnica, Universidade São Paulo * ------------------------------------------------------ * * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software * Foundation, either version 3 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will * be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License * for more details. * **/ package br.usp.poli.lta.cereda.macro.model; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; /** * Representa uma macro. * @author Paulo Roberto Massa Cereda * @version 1.0 * @since 1.0 */ public class Macro { // nome da macro private String name; // mapa contendo os parâmetros e seus respectivos índices posicionais private Map<Integer, String> parameters; // corpo da macro private String body; /** * Obtém o nome da macro. * @return Nome da macro. */ public String getName() { return name; } /** * Define o nome da macro. * @param name Nome da macro. */ public void setName(String name) { this.name = name; } /** * Obtém o mapa de parâmetros. * @return Mapa de parâmetros. */ public Map<Integer, String> getParameters() { return parameters; } /** * Define o mapa de parâmetros. * @param parameters Mapa de parâmetros. */ public void setParameters(Map<Integer, String> parameters) { this.parameters = parameters; } /** * Obtém o corpo da macro. * @return Corpo da macro. */ public String getBody() { return body; } /** * Define o corpo da macro. * @param body Corpo da macro. */ public void setBody(String body) { this.body = body; } /** * Construtor vazio. */ public Macro() { } /** * Construtor de uma macro simples. * @param name Nome da macro. * @param body Corpo da macro. */ public Macro(String name, String body) { this.name = name; this.parameters = new HashMap<>(); this.body = body; } /** * Construtor de uma macro paramétrica. * @param name Nome da macro. * @param parameters Mapa de parâmetros. * @param body Corpo da macro. */ public Macro(String name, Map<Integer, String> parameters, String body) { this.name = name; this.parameters = parameters; this.body = body; } /** * Obtém a identificação de hash do objeto corrente. * @return Um valor inteiro representando a identificação de hash do objeto * corrente. É importante observar que este é calculado de acordo com o nome * da macro e o número de seus parâmetros; a representação mnemônica de * cada parâmetro não importa. */ @Override public int hashCode() { return new HashCodeBuilder(). append(name). append(parameters.size()). build(); } /** * Verifica se um objeto é igual ao objeto corrente. * @param object Objeto a ser comparado. * @return Um valor lógico indicando se o objeto fornecido é igual ao objeto * corrente. A mesma observação feita para o método hashCode() vale nessa * situação: uma macro é dita igual a outra se estas possuem o mesmo nome e * o mesmo número de parâmetros (o corpo da macro e o mnmenômico de cada * parâmetro são irrelevantes no contexto). Este método é utilizado pela * estrutura de dados Set para verificar se um objeto já está inserido no * conjunto (um conjunto não admite elementos duplicados). */ @Override public boolean equals(Object object) { if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } final Macro reference = (Macro) object; return new EqualsBuilder(). append(name, reference.name). append(parameters.size(), reference.parameters.size()). isEquals(); } /** * Fornece uma representação textual da macro. * @return Representação textual da macro. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Macro: {"); sb.append("nome = ").append(name).append(","); sb.append("parâmetros = ").append(parameters).append(","); sb.append("corpo = ").append(body).append(" }"); return sb.toString(); } }
gpl-3.0
thedj21/bukkit--src
src/main/java/org/bukkit/material/Button.java
2648
package org.bukkit.material; import org.bukkit.block.BlockFace; import org.bukkit.Material; /** * Represents a button */ public class Button extends SimpleAttachableMaterialData implements Redstone { public Button() { super(Material.STONE_BUTTON); } /** * @param type the type * @deprecated Magic value */ @Deprecated public Button(final int type) { super(type); } public Button(final Material type) { super(type); } /** * @param type the raw type id * @param data the raw data value * @deprecated Magic value */ @Deprecated public Button(final int type, final byte data) { super(type, data); } /** * @param type the type * @param data the raw data value * @deprecated Magic value */ @Deprecated public Button(final Material type, final byte data) { super(type, data); } /** * Gets the current state of this Material, indicating if it's powered or * unpowered * * @return true if powered, otherwise false */ public boolean isPowered() { return (getData() & 0x8) == 0x8; } /** * Sets the current state of this button * * @param bool * whether or not the button is powered */ public void setPowered(boolean bool) { setData((byte) (bool ? (getData() | 0x8) : (getData() & ~0x8))); } /** * Gets the face that this block is attached on * * @return BlockFace attached to */ public BlockFace getAttachedFace() { byte data = (byte) (getData() & 0x7); switch (data) { case 0x1: return BlockFace.WEST; case 0x2: return BlockFace.EAST; case 0x3: return BlockFace.NORTH; case 0x4: return BlockFace.SOUTH; } return null; } /** * Sets the direction this button is pointing toward */ public void setFacingDirection(BlockFace face) { byte data = (byte) (getData() & 0x8); switch (face) { case EAST: data |= 0x1; break; case WEST: data |= 0x2; break; case SOUTH: data |= 0x3; break; case NORTH: data |= 0x4; break; } setData(data); } @Override public String toString() { return super.toString() + " " + (isPowered() ? "" : "NOT ") + "POWERED"; } @Override public Button clone() { return (Button) super.clone(); } }
gpl-3.0
DirtyCajunRice/PlexShowSilencer
plexshowsilencer/silencer/migrations/0002_table_plural_to_single.py
490
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-11 23:03 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('silencer', '0001_initial'), ] operations = [ migrations.RenameModel( old_name='Movies', new_name='Movie', ), migrations.RenameModel( old_name='TVShows', new_name='TVShow', ), ]
gpl-3.0
mnemotron/Roots
roots/src/main/java/roots/core/SystemResourceIcons.java
1846
package roots.core; public final class SystemResourceIcons { // configuration public static final String ICON_CONFIG_TREE_LEAF_LOOKANDFEEL = "/roots/icons/config.png"; public static final String ICON_CONFIG_TREE_SELECTED_LOOKANDFEEL = "/roots/icons/config.png"; // repository public static final String ICON_REPO_DB_STATUS_RED = "/roots/icons/dbred.png"; public static final String ICON_REPO_DB_STATUS_GREEN = "/roots/icons/dbgreen.png"; public static final String ICON_REPO_DB_STATUS_YELLOW = "/roots/icons/dbyellow.png"; public static final String ICON_REPO_DB_STATUS_NATIVE = "/roots/icons/dbnative.png"; // menu public static final String ICON_MENU_ROOTS = ""; public static final String ICON_MENU_ROOTS_EXIT = "/roots/icons/exit.png"; public static final String ICON_MENU_PROGRAMS = "/roots/icons/programs.png"; public static final String ICON_MENU_REPOSITORY = "/roots/icons/repository.png"; public static final String ICON_MENU_REPOSITORY_INFO = "/roots/icons/repinfo.png"; public static final String ICON_MENU_REPOSITORY_CHANGE = "/roots/icons/repchange.png"; public static final String ICON_MENU_REPOSITORY_IMPORT = "/roots/icons/repimport.png"; public static final String ICON_MENU_REPOSITORY_EXPORT = "/roots/icons/repexport.png"; public static final String ICON_MENU_LANGUAGE_DE = "/roots/icons/de.png"; public static final String ICON_MENU_LANGUAGE_EN = "/roots/icons/en.png"; public static final String ICON_MENU_INFO = "/roots/icons/info.png"; public static final String ICON_MENU_INFO_HELP = "/roots/icons/help.png"; public static final String ICON_MENU_INFO_LOG = "/roots/icons/log.png"; // gui public static final String ICON_REPOSITORY_CREATE = "/roots/icons/repcreate.png"; }
gpl-3.0
savirhkhan/Practice-Python
tick_tak_toe.py
2559
def draw_line(width, edge, filling): print(filling.join([edge] * (width + 1))) def display_winner(player): if player == 0: print("Tie") else: print("Player " + str(player) + " wins!") def check_row_winner(row): """ Return the player number that wins for that row. If there is no winner, return 0. """ if row[0] == row[1] and row[1] == row[2]: return row[0] return 0 def get_col(game, col_number): return [game[x][col_number] for x in range(3)] def get_row(game, row_number): return game[row_number] def check_winner(game): game_slices = [] for index in range(3): game_slices.append(get_row(game, index)) game_slices.append(get_col(game, index)) # check diagonals down_diagonal = [game[x][x] for x in range(3)] up_diagonal = [game[0][2], game[1][1], game[2][0]] game_slices.append(down_diagonal) game_slices.append(up_diagonal) for game_slice in game_slices: winner = check_row_winner(game_slice) if winner != 0: return winner return winner def start_game(): return [[0, 0, 0] for x in range(3)] def display_game(game): d = {2: "O", 1: "X", 0: "_"} draw_line(3, " ", "_") for row_num in range(3): new_row = [] for col_num in range(3): new_row.append(d[game[row_num][col_num]]) print("|" + "|".join(new_row) + "|") def add_piece(game, player, row, column): """ game: game state player: player number row: 0-index row column: 0-index column """ game[row][column] = player return game def check_space_empty(game, row, column): return game[row][column] == 0 def convert_input_to_coordinate(user_input): return user_input - 1 def switch_player(player): if player == 1: return 2 else: return 1 def moves_exist(game): for row_num in range(3): for col_num in range(3): if game[row_num][col_num] == 0: return True return False if __name__ == '__main__': game = start_game() display_game(game) player = 1 winner = 0 # the winner is not yet defined # go on forever while winner == 0 and moves_exist(game): print("Currently player: " + str(player)) available = False while not available: row = convert_input_to_coordinate(int(input("Which row? (start with 1) "))) column = convert_input_to_coordinate(int(input("Which column? (start with 1) "))) available = check_space_empty(game, row, column) game = add_piece(game, player, row, column) display_game(game) player = switch_player(player) winner = check_winner(game) display_winner(winner)
gpl-3.0
Hambrook/Nest
tests/arraySetTest.php
1199
<?php require_once(implode(DIRECTORY_SEPARATOR, [__DIR__, "..", "src", "Nest.php"])); use \Hambrook\Nest\Nest as Nest; /** * Tests for PHPUnit * * @author Rick Hambrook <rick@rickhambrook.com> * @copyright 2015 Rick Hambrook * @license https://www.gnu.org/licenses/gpl.txt GNU General Public License v3 */ class arraySetTest extends PHPUnit_Framework_TestCase { public function testSet() { $Nest = new Nest([]); // Setting empty array $this->assertEquals([], $Nest->set("foo")->get("foo")); // Setting value $this->assertEquals("baz", $Nest->set("bar", "baz")->get("bar")); } public function testSetNested() { $Nest = new Nest([]); // Setting empty array $key = ["one", "two"]; $this->assertEquals([], $Nest->set($key)->get($key)); // Valid $this->assertEquals("three", $Nest->set($key, "three")->get($key)); } public function testSetMagic() { $Nest = new Nest([]); // Valid, 1 level) $Nest->foo = "bar"; $this->assertEquals("bar", $Nest->foo); } public function testSetNestedMagic() { $Nest = new Nest([]); // Invalid, 1 level $Nest->one__two = "four"; $this->assertEquals("four", $Nest->one__two); } }
gpl-3.0
scraymer/lyle-wedding
sites/blocks/gallery-couple.php
4679
<div id="block-gallery-thumbnails"> <div class="header"></div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Christmas.JPG" rel="shadowbox[Couple]" title="Christmas 2007"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Christmas_220x220.JPG" alt="Christmas 2007" title="Christmas 2007" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Cottage.JPG" rel="shadowbox[Couple]" title="Cottage 2007"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Cottage_220x220.JPG" alt="Cottage 2007" title="Cottage 2007" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_May.JPG" rel="shadowbox[Couple]" title="May 2007"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_May_220x220.JPG" alt="May 2007" title="May 2007" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Prom.JPG" rel="shadowbox[Couple]" title="Prom 2007"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Prom_220x220.JPG" alt="Prom 2007" title="Prom 2007" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Winter.JPG" rel="shadowbox[Couple]" title="Winter 2007"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2007_Winter_220x220.JPG" alt="Winter 2007" title="Winter 2007" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2010_Christmas.JPG" rel="shadowbox[Couple]" title="Christmas 2010"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2010_Christmas_220x220.JPG" alt="Christmas 2010" title="Christmas 2010" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Easter.JPG" rel="shadowbox[Couple]" title="Easter 2011"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Easter_220x220.JPG" alt="Easter 2011" title="Easter 2011" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_KirJeffWedding.JPG" rel="shadowbox[Couple]" title="Kir & Jeff's Wedding"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_KirJeffWedding_220x220.JPG" alt="Kir & Jeff's Wedding" title="Kir & Jeff's Wedding" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Naples_1.JPG" rel="shadowbox[Couple]" title="Naples 2011"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Naples_1_220x220.JPG" alt="Naples 2011" title="Naples 2011" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Naples_2.JPG" rel="shadowbox[Couple]" title="Naples 2011"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Naples_2_220x220.JPG" alt="Naples 2011" title="Naples 2011" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_SteveRetirementParty.JPG" rel="shadowbox[Couple]" title="Steve's Retirement Party"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_SteveRetirementParty_220x220.JPG" alt="Steve's Retirement Party" title="Steve's Retirement Party" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_SueCottage.JPG" rel="shadowbox[Couple]" title="Sue's Cottage 2011"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_SueCottage_220x220.JPG" alt="Sue's Cottage 2011" title="Sue's Cottage 2011" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Summer.JPG" rel="shadowbox[Couple]" title="Summer 2011"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Summer_220x220.JPG" alt="Summer 2011" title="Summer 2011" /> </a> </div> <div class="thumbnail"> <a href="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Winter.JPG" rel="shadowbox[Couple]" title="Winter 2011"> <img src="https://dl.dropbox.com/u/36151686/sites/images/gallery/couple/2011_Winter_220x220.JPG" alt="Winter 2011" title="Winter 2011" /> </a> </div> <div class="footer"></div> </div>
gpl-3.0
CatLabInteractive/dolumar
public/cache.php
1097
<?php /** * Dolumar, browser based strategy game * Copyright (C) 2009 Thijs Van der Schaeghe * CatLab Interactive bvba, Gent, Belgium * http://www.catlab.eu/ * http://www.dolumar.com/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ include ('../bootstrap/bootstrap.php'); $dir = isset ($_GET['d']) ? $_GET['d'] : null; if (file_exists (CACHE_DIR.$dir)) { echo file_get_contents (CACHE_DIR.$dir); }
gpl-3.0
arneboe/PixelController
pixelcontroller-gui/src/test/java/com/neophob/sematrix/gui/callback/GuiStateTest.java
2029
/** * Copyright (C) 2011-2014 Michael Vogt <michu@neophob.com> * * This file is part of PixelController. * * PixelController 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. * * PixelController 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 PixelController. If not, see <http://www.gnu.org/licenses/>. */ package com.neophob.sematrix.gui.callback; import static org.junit.Assert.*; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.Test; public class GuiStateTest { @Test public void testGuiState() { GuiState gs = new GuiState(); List<String> o = new LinkedList<String>(); o.add("CHANGE_GENERATOR_A 1"); o.add("CHANGE_GENERATOR_B 0"); o.add("BLINKEN bnf_auge.bml"); gs.updateState(o); Map<String,String> result = gs.getState(); assertEquals(3, result.size()); assertEquals("1", result.get("CHANGE_GENERATOR_A")); assertEquals("0", result.get("CHANGE_GENERATOR_B")); assertEquals("bnf_auge.bml", result.get("BLINKEN")); o.clear(); o.add("CHANGE_GENERATOR_B 3"); o.add("CHANGE_EFFECT_B 1"); gs.updateState(o); result = gs.getState(); assertEquals(4, result.size()); assertEquals("1", result.get("CHANGE_GENERATOR_A")); assertEquals("3", result.get("CHANGE_GENERATOR_B")); assertEquals("1", result.get("CHANGE_EFFECT_B")); assertEquals("bnf_auge.bml", result.get("BLINKEN")); Map<String,String> diff = gs.getDiff(); assertEquals(2, diff.size()); assertEquals("3", result.get("CHANGE_GENERATOR_B")); assertEquals("1", result.get("CHANGE_EFFECT_B")); } }
gpl-3.0
Throne-of-Heptagram/Door_of_Soul.Communication
Door_of_Soul.Communication.Protocol.External/Device/EventParameter/SystemEventParameterCode.cs
182
namespace Door_of_Soul.Communication.Protocol.External.Device.EventParameter { public enum SystemEventParameterCode : byte { EventCode, Parameters } }
gpl-3.0
annoviko/pyclustering
pyclustering/cluster/tests/unit/ut_encoder.py
10675
"""! @brief Unit-tests for clustering result representation. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ import unittest import math import matplotlib matplotlib.use('Agg') from pyclustering.cluster.encoder import cluster_encoder from pyclustering.cluster.encoder import type_encoding class Test(unittest.TestCase): def getIndexRepresentor(self): clusters = [ [0, 1, 2, 3], [4, 5, 6, 7] ] data = [10, 11, 13, 12, 64, 65, 65, 68] return cluster_encoder(type_encoding.CLUSTER_INDEX_LIST_SEPARATION, clusters, data) def testIndexToLabel(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def testIndexToObject(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) assert 2 == len(representor.get_clusters()); assert [ [10, 11, 13, 12 ], [64, 65, 65, 68] ] == representor.get_clusters() def testObjectToIndex(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [0, 1, 2, 3], [4, 5, 6, 7] ] == representor.get_clusters() def testObjectToLabel(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def testLabelToIndex(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [0, 1, 2, 3], [4, 5, 6, 7] ] == representor.get_clusters() def testLabelToObject(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [10, 11, 13, 12 ], [64, 65, 65, 68] ] == representor.get_clusters() def testLabelToLabel(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def testObjectToObject(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [10, 11, 13, 12 ], [64, 65, 65, 68] ] == representor.get_clusters() def testIndexToIndex(self): representor = self.getIndexRepresentor() representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [0, 1, 2, 3], [4, 5, 6, 7] ] == representor.get_clusters() def getIndexRepresentorDoubleData(self): clusters = [ [0, 1, 2, 3], [4, 5, 6, 7] ] data = [5.4562, 5.1235, 4.9235, 4.8712, 8.3451, 8.4215, 8.6535, 8.7345] return cluster_encoder(type_encoding.CLUSTER_INDEX_LIST_SEPARATION, clusters, data) def testDoubleObjectToIndex(self): representor = self.getIndexRepresentorDoubleData() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) assert 2 == len(representor.get_clusters()); assert [ [0, 1, 2, 3], [4, 5, 6, 7] ] == representor.get_clusters() def testDoubleObjectToLabel(self): representor = self.getIndexRepresentorDoubleData() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def testOverAllTypes(self): representor = self.getIndexRepresentorDoubleData() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def getIndexRepresentorTwoDimensionData(self): clusters = [ [0, 1, 2, 3], [4, 5, 6, 7] ] data = [ [5.1, 5.2], [5.2, 5.1], [5.4, 5.2], [5.1, 5.0], [8.1, 8.0], [8.4, 8.2], [8.3, 8.4], [8.5, 8.5]] return cluster_encoder(type_encoding.CLUSTER_INDEX_LIST_SEPARATION, clusters, data) def testIndexToLabelTwoDimension(self): representor = self.getIndexRepresentorTwoDimensionData() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def testIndexToObjectTwoDimension(self): representor = self.getIndexRepresentorTwoDimensionData() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [[5.1, 5.2], [5.2, 5.1], [5.4, 5.2], [5.1, 5.0]], [[8.1, 8.0], [8.4, 8.2], [8.3, 8.4], [8.5, 8.5]] ] == representor.get_clusters() def testObjectToIndexTwoDimension(self): representor = self.getIndexRepresentorTwoDimensionData() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [0, 1, 2, 3], [4, 5, 6, 7] ] == representor.get_clusters() def testObjectToLabelTwoDimension(self): representor = self.getIndexRepresentorTwoDimensionData() representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) assert 8 == len(representor.get_clusters()) assert [0, 0, 0, 0, 1, 1, 1, 1] == representor.get_clusters() def testLabelToIndexTwoDimension(self): representor = self.getIndexRepresentorTwoDimensionData() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) representor.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [[0, 1, 2, 3], [4, 5, 6, 7]] == representor.get_clusters() def testLabelToObjectTwoDimension(self): representor = self.getIndexRepresentorTwoDimensionData() representor.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) representor.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) assert 2 == len(representor.get_clusters()) assert [ [[5.1, 5.2], [5.2, 5.1], [5.4, 5.2], [5.1, 5.0]], [[8.1, 8.0], [8.4, 8.2], [8.3, 8.4], [8.5, 8.5]] ] == representor.get_clusters() def testIndexListToLabelsMissedPoint(self): clusters = [[0, 1, 2, 3], [4, 5, 6]] # the last point is missed data = [[5.1, 5.2], [5.2, 5.1], [5.4, 5.2], [5.1, 5.0], [8.1, 8.0], [8.4, 8.2], [8.3, 8.4], [8.5, 8.5]] encoder = cluster_encoder(type_encoding.CLUSTER_INDEX_LIST_SEPARATION, clusters, data) encoder.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) expected = [0, 0, 0, 0, 1, 1, 1, float('NaN')] actual = encoder.get_clusters() self.assertEqual(len(expected), len(actual)) for i in range(len(expected)): if math.isnan(expected[i]) is True: self.assertTrue(math.isnan(actual[i])) else: self.assertEqual(expected[i], actual[i]) def testObjectListToLabelsMissedPoint(self): clusters = [[[5.1, 5.2], [5.2, 5.1]], [[8.1, 8.0], [8.4, 8.2]]] data = [[5.1, 5.2], [5.2, 5.1], [14.1, 76.0], [8.1, 8.0], [8.4, 8.2]] encoder = cluster_encoder(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION, clusters, data) encoder.set_encoding(type_encoding.CLUSTER_INDEX_LABELING) expected = [0, 0, float('NaN'), 1, 1] actual = encoder.get_clusters() self.assertEqual(len(expected), len(actual)) for i in range(len(expected)): if math.isnan(expected[i]) is True: self.assertTrue(math.isnan(actual[i])) else: self.assertEqual(expected[i], actual[i]) def testLabelsToIndexListAndObjectListMissedPoint(self): clusters = [0, 0, float('NaN'), 1, 1] data = [[5.1, 5.2], [5.2, 5.1], [14.1, 76.0], [8.1, 8.0], [8.4, 8.2]] encoder = cluster_encoder(type_encoding.CLUSTER_INDEX_LABELING, clusters, data) encoder.set_encoding(type_encoding.CLUSTER_INDEX_LIST_SEPARATION) expected = [[0, 1], [3, 4]] actual = encoder.get_clusters() self.assertEqual(len(expected), len(actual)) self.assertEqual(expected, actual) encoder = cluster_encoder(type_encoding.CLUSTER_INDEX_LABELING, clusters, data) encoder.set_encoding(type_encoding.CLUSTER_OBJECT_LIST_SEPARATION) expected = [[[5.1, 5.2], [5.2, 5.1]], [[8.1, 8.0], [8.4, 8.2]]] actual = encoder.get_clusters() self.assertEqual(len(expected), len(actual)) self.assertEqual(expected, actual)
gpl-3.0
pcimcioch/scraper
src/main/java/scraper/module/chan/collector/thread/ThreadDsRepository.java
283
package scraper.module.chan.collector.thread; import org.springframework.data.repository.CrudRepository; /** * Neo4j repository for {@link ThreadDs}. */ public interface ThreadDsRepository extends CrudRepository<ThreadDs, Long> { ThreadDs findByThreadId(String threadId); }
gpl-3.0
victorzhao/miniblink49
cef/libcef_dll/ctocpp/browser_process_handler_ctocpp.cc
3444
// Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // --------------------------------------------------------------------------- // // This file was generated by the CEF translator tool. If making changes by // hand only do so within the body of existing method and function // implementations. See the translator.README.txt file in the tools directory // for more information. // #if (defined ENABLE_CEF) && (ENABLE_CEF == 1) #include "libcef_dll/cpptoc/command_line_cpptoc.h" #include "libcef_dll/cpptoc/list_value_cpptoc.h" #include "libcef_dll/ctocpp/browser_process_handler_ctocpp.h" #include "libcef_dll/ctocpp/print_handler_ctocpp.h" // VIRTUAL METHODS - Body may be edited by hand. void CefBrowserProcessHandlerCToCpp::OnContextInitialized() { cef_browser_process_handler_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, on_context_initialized)) return; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute _struct->on_context_initialized(_struct); } void CefBrowserProcessHandlerCToCpp::OnBeforeChildProcessLaunch( CefRefPtr<CefCommandLine> command_line) { cef_browser_process_handler_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, on_before_child_process_launch)) return; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: command_line; type: refptr_diff DCHECK(command_line.get()); if (!command_line.get()) return; // Execute _struct->on_before_child_process_launch(_struct, CefCommandLineCppToC::Wrap(command_line)); } void CefBrowserProcessHandlerCToCpp::OnRenderProcessThreadCreated( CefRefPtr<CefListValue> extra_info) { cef_browser_process_handler_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, on_render_process_thread_created)) return; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Verify param: extra_info; type: refptr_diff DCHECK(extra_info.get()); if (!extra_info.get()) return; // Execute _struct->on_render_process_thread_created(_struct, CefListValueCppToC::Wrap(extra_info)); } CefRefPtr<CefPrintHandler> CefBrowserProcessHandlerCToCpp::GetPrintHandler() { cef_browser_process_handler_t* _struct = GetStruct(); if (CEF_MEMBER_MISSING(_struct, get_print_handler)) return NULL; // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING // Execute cef_print_handler_t* _retval = _struct->get_print_handler(_struct); // Return type: refptr_same return CefPrintHandlerCToCpp::Wrap(_retval); } // CONSTRUCTOR - Do not edit by hand. CefBrowserProcessHandlerCToCpp::CefBrowserProcessHandlerCToCpp() { } template<> cef_browser_process_handler_t* CefCToCpp<CefBrowserProcessHandlerCToCpp, CefBrowserProcessHandler, cef_browser_process_handler_t>::UnwrapDerived( CefWrapperType type, CefBrowserProcessHandler* c) { NOTREACHED() << "Unexpected class type: " << type; return NULL; } #ifndef NDEBUG template<> base::AtomicRefCount CefCToCpp<CefBrowserProcessHandlerCToCpp, CefBrowserProcessHandler, cef_browser_process_handler_t>::DebugObjCt = 0; #endif template<> CefWrapperType CefCToCpp<CefBrowserProcessHandlerCToCpp, CefBrowserProcessHandler, cef_browser_process_handler_t>::kWrapperType = WT_BROWSER_PROCESS_HANDLER; #endif
gpl-3.0
tmshlvck/ulg
ulgbird.py
23756
#!/usr/bin/env python # # ULG - Universal Looking Glass # (C) 2012 CZ.NIC, z.s.p.o. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Imports import os import socket import re import pexpect import hashlib import defaults import ulgmodel import ulggraph IPV46_SUBNET_REGEXP = '^[0-9a-fA-F:\.]+(/[0-9]{1,2}){0,1}$' RTNAME_REGEXP = '^[a-zA-Z0-9]+$' STRING_SYMBOL_ROUTING_TABLE = 'routing table' STRING_EXPECT_SSH_NEWKEY='Are you sure you want to continue connecting' STRING_EXPECT_PASSWORD='(P|p)assword:' STRING_EXPECT_SHELL_PROMPT_REGEXP = '\n[a-zA-Z0-9\._-]+>' STRING_EXPECT_REPLY_START = 'BIRD\s+[^\s]+\s+ready\.' STRING_LOGOUT_COMMAND = 'exit' BIRD_SOCK_HEADER_REGEXP='^([0-9]+)[-\s](.+)$' BIRD_SOCK_REPLY_END_REGEXP='^([0-9]+)\s*(\s.*)?$' BIRD_CONSOLE_PROMPT_REGEXP='[^>]+>\s*' BIRD_SHOW_PROTO_LINE_REGEXP='^\s*([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)(\s+([^\s].+)){0,1}\s*$' BIRD_SHOW_PROTO_HEADER_REGEXP='^\s*(name)\s+(proto)\s+(table)\s+(state)\s+(since)\s+(info)\s*$' BIRD_RT_LINE_REGEXP = '^([^\s]+)\s+via\s+([^\s]+)\s+on\s+([^\s]+)\s+(\[[^\]]+\])\s+(\*?)\s*([^\s]+)\s+([^\s]+)' BIRD_ASFIELD_REGEXP = '^\s*\[AS([0-9]+)(i|\?)\]\s*$' BIRD_SHOW_SYMBOLS_LINE_REGEXP = '^([^\s]+)\s+(.+)\s*' BIRD_GRAPH_SH_ROUTE_ALL = "Graph show route table <RT> for <IP subnet>" bird_sock_header_regexp = re.compile(BIRD_SOCK_HEADER_REGEXP) bird_sock_reply_end_regexp = re.compile(BIRD_SOCK_REPLY_END_REGEXP) bird_rt_line_regexp = re.compile(BIRD_RT_LINE_REGEXP) bird_asfield_regexp = re.compile(BIRD_ASFIELD_REGEXP) bird_show_symbols_line_regexp = re.compile(BIRD_SHOW_SYMBOLS_LINE_REGEXP) bird_show_proto_line_regexp = re.compile(BIRD_SHOW_PROTO_LINE_REGEXP) BIRD_SH_ROUTE_ALL_ASES_REGEXP = "^(\s*BGP\.as_path:\s+)([0-9\s]+)\s*$" bird_sh_route_all_ases_regexp = re.compile(BIRD_SH_ROUTE_ALL_ASES_REGEXP) BIRD_SH_ROUTE_ALL_NEXTHOP_REGEXP = ".*\s+via\s+([0-9a-fA-F:\.]+)\s+on\s+[^\s]+\s+\[([^\s]+)\s+.*" bird_sh_route_all_nexthop_regexp = re.compile(BIRD_SH_ROUTE_ALL_NEXTHOP_REGEXP) BIRD_SH_ROUTE_ALL_USED_REGEXP = ".*\]\s+\*\s+\(.*" bird_sh_route_all_used_regexp = re.compile(BIRD_SH_ROUTE_ALL_USED_REGEXP) def bird_parse_sh_route_all(text,prependas): def split_ases(ases): return str.split(ases) DEFAULT_PARAMS = {'recuse':False, 'reconly':False, 'aggr':None} res = [] params = dict(DEFAULT_PARAMS) for l in str.splitlines(text): m = bird_sh_route_all_nexthop_regexp.match(l) if(m): params['peer'] = m.group(2) if(bird_sh_route_all_used_regexp.match(l)): params['recuse'] = True m = bird_sh_route_all_ases_regexp.match(l) if(m): ases = [ulgmodel.annotateAS("AS"+str(asn)) for asn in [prependas] + split_ases(m.group(2))] res.append((ases,params)) params = dict(DEFAULT_PARAMS) continue return res def bird_reduce_paths(paths): def assign_value(path): if(path[1]['recuse']): return 1 elif(path[1]['reconly']): return 100 else: return 10 return sorted(paths,key=assign_value) def parseBirdShowProtocols(text): def parseShowProtocolsLine(line): m = bird_show_proto_line_regexp.match(line) if(m): res = list(m.groups()[0:5]) if(m.group(6)): res.append(m.group(6)) return res else: # skip silently the bgp log # ulgmodel.log("WARN: bird.parseShowProtocolsLine failed to match line: "+line) return None header = [] table = [] for l in str.splitlines(text): if(re.match('^\s*$',l)): continue hm = re.match(BIRD_SHOW_PROTO_HEADER_REGEXP,l) if(hm): header = hm.groups() else: pl = parseShowProtocolsLine(l) if(pl): table.append(pl) # else: # ulgmodel.log("ulgbird.parseBirdShowProtocols skipping unparsable line: "+l) return (header,table,len(table)) # classes class BirdShowProtocolsCommand(ulgmodel.TextCommand): COMMAND_TEXT = 'show protocols' def __init__(self,name=None,show_proto_all_command=None,proto_filter=None): ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[],name=name) self.show_proto_all_command = show_proto_all_command self.fltr = proto_filter def _getPeerURL(self,decorator_helper,router,peer_id): if decorator_helper and self.show_proto_all_command: return decorator_helper.getRuncommandURL({'routerid':str(decorator_helper.getRouterID(router)), 'commandid':str(decorator_helper.getCommandID(router,self.show_proto_all_command)), 'param0':peer_id}) else: return None def _getPeerTableCell(self,decorator_helper,router,peer_id): url = self._getPeerURL(decorator_helper,router,peer_id) if(url): return decorator_helper.ahref(url,peer_id) else: return peer_id def _decorateTableLine(self,table_line,router,decorator_helper): def _getTableLineColor(state): if(state == 'up'): return ulgmodel.TableDecorator.GREEN elif(state == 'start'): return ulgmodel.TableDecorator.YELLOW else: return ulgmodel.TableDecorator.RED color = _getTableLineColor(table_line[3]) tl = [(self._getPeerTableCell(decorator_helper,router,table_line[0]),color), (table_line[1],color), (table_line[2],color), (table_line[3],color), (table_line[4],color), ] if(len(table_line)>5): tl.append((table_line[5],color)) return tl def decorateResult(self,session,decorator_helper=None): if(not session): raise Exception("Can not decorate result without valid session.") if(session.getResult() == None): return (decorator_helper.pre(defaults.STRING_EMPTY), 1) if((not session.getRouter()) or (not decorator_helper)): return "<pre>\n%s\n</pre>" % session.getResult() else: pr = parseBirdShowProtocols(session.getResult()) table_header = pr[0] table = [] for tl in pr[1][session.getRange():session.getRange()+defaults.range_step]: # skip when there is a filter and it does not match the protocol type if(self.fltr) and (not re.match(self.fltr,tl[1])): continue table.append(self._decorateTableLine(tl,session.getRouter(),decorator_helper)) return (ulgmodel.TableDecorator(table,table_header).decorate(),pr[2]) class AbstractBGPPeerSelectCommand(ulgmodel.TextCommand): """ Abstract class for all BIRD BGP peer-specific commands """ def __init__(self,router,name=None): ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[router.getBGPPeerSelect()],name=name) class BirdShowProtocolsAllCommand(AbstractBGPPeerSelectCommand): COMMAND_TEXT = 'show protocols all %s' class AbstractRouteTableCommand(ulgmodel.TextCommand): def _decorateOriginAS(self,asfield,decorator_helper): # expected input is "[AS28171i]" m = bird_asfield_regexp.match(asfield) if(m): return '['+decorator_helper.decorateASN(m.group(1))+m.group(2)+']' else: return asfield def _genTable(self,table_lines,decorator_helper,router): def matchBIRDBGPRTLine(line): m = bird_rt_line_regexp.match(line) if(m): return m.groups() else: ulgmodel.debug("BirdShowRouteProtocolCommand: Can not parse line: "+line) return None result = [] for tl in table_lines: ml=matchBIRDBGPRTLine(tl) if(ml): # generate table content result.append([ (decorator_helper.decoratePrefix(ml[0]),), (ml[1],), (ml[2],), (ml[3],), (ml[4],), (ml[5],), (self._decorateOriginAS(ml[6],decorator_helper),), ]) return result def decorateResult(self,session,decorator_helper=None): if(not session): raise Exception("Can not decorate result without valid session.") if(session.getResult() == None): return (decorator_helper.pre(defaults.STRING_EMPTY), 1) if((not session.getRouter()) or (not decorator_helper)): return "<pre>\n%s\n</pre>" % session.getResult() table=[] table_header=['Prefix', 'Next-hop', 'Interface', 'Since', 'Status', 'Metric', 'Info',] lines = str.splitlines(session.getResult()) result_len = len(lines) lines = lines[session.getRange():session.getRange()+defaults.range_step] table = self._genTable(lines,decorator_helper,session.getRouter()) return (ulgmodel.TableDecorator(table,table_header).decorate(),result_len) class BirdShowRouteExportCommand(AbstractBGPPeerSelectCommand,AbstractRouteTableCommand): COMMAND_TEXT = 'show route export %s' class BirdShowRouteCommand(AbstractRouteTableCommand): COMMAND_TEXT = 'show route table %s for %s' def __init__(self,router,name=None): ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[ router.getRoutingTableSelect(), ulgmodel.TextParameter(pattern=IPV46_SUBNET_REGEXP,name=defaults.STRING_IPSUBNET), ],name=name) class BirdShowRouteProtocolCommand(BirdShowRouteCommand): COMMAND_TEXT = 'show route table %s protocol %s' def __init__(self,router,name=None): ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[router.getRoutingTableSelect(),router.getBGPPeerSelect()],name=name) class BirdShowRouteAllCommand(ulgmodel.TextCommand): COMMAND_TEXT = 'show route table %s all for %s' def __init__(self,router,name=None): ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[ router.getRoutingTableSelect(), ulgmodel.TextParameter(pattern=IPV46_SUBNET_REGEXP,name=defaults.STRING_IPSUBNET), ], name=name) def decorateResult(self,session,decorator_helper=None): def decorateLine(l): m = bird_sh_route_all_ases_regexp.match(l) if(m): r = m.group(1) ases = str.split(m.group(2)) for asn in ases: r = r + decorator_helper.decorateASN(asn,prefix='') r = r + ' ' return decorator_helper.annotateIPs(r) else: return decorator_helper.annotateIPs(l) if(session.getResult() == None): return (decorator_helper.pre(defaults.STRING_EMPTY), 1) s = str.splitlines(session.getResult()) r='' for sl in s: r += decorateLine(sl) + "\n" return ("<pre>\n%s\n</pre>" % r, len(s)) class BirdGraphShowRouteAll(ulgmodel.TextCommand): COMMAND_TEXT = 'show route table %s all for %s' def __init__(self,router,name=BIRD_GRAPH_SH_ROUTE_ALL): ulgmodel.TextCommand.__init__(self,self.COMMAND_TEXT,param_specs=[ router.getRoutingTableSelect(), ulgmodel.TextParameter(pattern=IPV46_SUBNET_REGEXP,name=defaults.STRING_IPSUBNET), ], name=name) def finishHook(self,session): session.setData(bird_parse_sh_route_all(session.getResult(),str(session.getRouter().getASN()))) def decorateResult(self,session,decorator_helper=None): if(session.isFinished()): if(session.getData() != None) and (session.getData() != []): return (decorator_helper.img(decorator_helper.getSpecialContentURL(session.getSessionId()),defaults.STRING_BGP_GRAPH),1) else: return (decorator_helper.pre(defaults.STRING_BGP_GRAPH_ERROR), 1) else: return ('',0) def getSpecialContent(self,session,**params): paths = session.getData() print "Content-type: image/png\n" ulggraph.bgp_graph_gen(bird_reduce_paths(paths),start=session.getRouter().getName(), end=session.getParameters()[1]) def showRange(self): return False class BirdRouter(ulgmodel.Router): """ Abstract class representing common base for BIRD router objects. """ RESCAN_PEERS_COMMAND = 'show protocols' RESCAN_TABLES_COMMAND = 'show symbols' DEFAULT_PROTOCOL_FLTR = '^BGP.*$' def __init__(self): self.bgp_peers = None self.routing_tables = None self.bgp_peer_select = None self.rt_select = None def _getDefaultCommands(self): sh_proto_all = BirdShowProtocolsAllCommand(self) sh_proto_route = BirdShowRouteProtocolCommand(self) sh_proto_export = BirdShowRouteExportCommand(self) return [BirdShowProtocolsCommand(show_proto_all_command=sh_proto_all, proto_filter = self.proto_fltr), BirdShowRouteCommand(self), sh_proto_all, sh_proto_route, sh_proto_export, BirdShowRouteAllCommand(self), BirdGraphShowRouteAll(self), # ulgmodel.TextCommand('show status'), # ulgmodel.TextCommand('show memory') ] def rescanPeers(self): res = self.runRawSyncCommand(self.RESCAN_PEERS_COMMAND) psp = parseBirdShowProtocols(res) peers = [] for pspl in psp[1]: if(re.match(self.proto_fltr,pspl[1])): peers.append(pspl[0]) self.bgp_peers = sorted(peers) def rescanRoutingTables(self): res = self.runRawSyncCommand(self.RESCAN_TABLES_COMMAND) tables = [] for l in str.splitlines(res): m = bird_show_symbols_line_regexp.match(l) if(m and m.group(2).lstrip().rstrip() == STRING_SYMBOL_ROUTING_TABLE): tables.append(m.group(1)) self.routing_tables = sorted(tables) def getBGPPeers(self): if(not self.bgp_peers): self.rescanPeers() return self.bgp_peers def getRoutingTables(self): if(not self.routing_tables): self.rescanRoutingTables() return self.routing_tables def initBGPPeerSelect(self,peers): rid = hashlib.md5(self.getName()).hexdigest() self.bgp_peer_select = ulgmodel.CommonSelectionParameter(rid+"bgp",[tuple((p,p,)) for p in peers], name=defaults.STRING_PEERID) def initRoutingTableSelect(self,rt): rid = hashlib.md5(self.getName()).hexdigest() self.rt_select = ulgmodel.CommonSelectionParameter(rid+"rt",[tuple((p,p,)) for p in rt], name=defaults.STRING_RTABLE) def getBGPPeerSelect(self): if(not self.bgp_peer_select): self.initBGPPeerSelect(self.getBGPPeers()) return self.bgp_peer_select def getRoutingTableSelect(self): if(not self.rt_select): self.initRoutingTableSelect(self.getRoutingTables()) return self.rt_select class BirdRouterLocal(ulgmodel.LocalRouter,BirdRouter): def __init__(self,sock=defaults.default_bird_sock,commands=None,proto_fltr=None,asn='My ASN',name='localhost',acl=None): ulgmodel.LocalRouter.__init__(self,acl=acl) BirdRouter.__init__(self) self.sock = sock self.setName(name) self.setASN(asn) if(proto_fltr): self.proto_fltr = proto_fltr else: self.proto_fltr = self.DEFAULT_PROTOCOL_FLTR self.rescanPeers() self.rescanRoutingTables() # command autoconfiguration might run only after other parameters are set if(commands): self.setCommands(commands) else: self.setCommands(self._getDefaultCommands()) def runRawCommand(self,command,outfile): def parseBirdSockLine(line): hm = bird_sock_header_regexp.match(line) if(hm): # first line of the reply return (int(hm.group(1)),hm.group(2)) em = bird_sock_reply_end_regexp.match(line) if(em): # most likely the last line of the reply return (int(em.group(1)),None) if(line[0] == '+'): # ignore async reply return (None,None) if(line[0] == ' '): # return reply line as it is (remove padding) return (None,line[1:]) raise Exception("Can not parse BIRD output line: "+line) def isBirdSockReplyEnd(code): if(code==None): return False if(code == 0): # end of reply return True elif(code == 13): # show status last line return True elif(code == 8001): # network not in table end return True elif(code >= 9000): # probably error return True else: return False # try: # open socket to BIRD s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.settimeout(defaults.default_bird_sock_timeout) s.connect(self.sock) # cretate FD for the socket sf=s.makefile() # wait for initial header l = sf.readline() # send the command string sf.write(command+"\n") sf.flush() # read and capture lines until the output delimiter string is hit while(True): l = sf.readline() ulgmodel.debug("Raw line read: " + l) # process line according to rules take out from the C code lp = parseBirdSockLine(l) if(isBirdSockReplyEnd(lp[0])): # End of reply (0000 or similar code) ulgmodel.debug("End of reply. Code="+str(lp[0])) if(lp[1]): ulgmodel.debug("Last read line after normalize: " + lp[1]) outfile.write(lp[1].rstrip()+"\n") break else: if(lp[1]): ulgmodel.debug("Read line after normalize: " + lp[1]) outfile.write(lp[1].rstrip()+"\n") else: ulgmodel.debug("Read line was empty after normalize.") # close the socket and return captured result s.close() # except socket.timeout as e: # # catch only timeout exception, while letting other exceptions pass # outfile.result(defaults.STRING_SOCKET_TIMEOUT) def getForkNeeded(self): return False class BirdRouterRemote(ulgmodel.RemoteRouter,BirdRouter): PS_KEY_BGP = '-bgppeers' PS_KEY_RT = '-routetab' def __init__(self,host,user,password='',port=22,commands=None,proto_fltr=None,asn='My ASN',name=None,bin_birdc=None,bin_ssh=None,acl=None): ulgmodel.RemoteRouter.__init__(self,acl=acl) BirdRouter.__init__(self) self.setHost(host) self.setUser(user) self.setPassword(password) self.setPort(port) if(name): self.setName(name) else: self.setName(host) self.setASN(asn) if(proto_fltr): self.proto_fltr = proto_fltr else: self.proto_fltr = self.DEFAULT_PROTOCOL_FLTR if(bin_birdc): self.bin_birdc = bin_birdc else: self.bin_birdc = defaults.default_bin_birdc if(bin_ssh): self.bin_ssh = bin_ssh else: self.bin_ssh = defaults.bin_ssh if(defaults.rescan_on_display): self.rescanHook() else: self.loadPersistentInfo() # command autoconfiguration might run only after other parameters are set if(commands): self.setCommands(commands) else: self.setCommands(self._getDefaultCommands()) def getForkNeeded(self): return True def runRawCommand(self,command,outfile): c = '/bin/bash -c \'echo "'+command+'" | '+self.bin_ssh+' -p'+str(self.getPort())+' '+str(self.getUser())+'@'+self.getHost()+' '+self.bin_birdc+'\'' skiplines = 2 s=pexpect.spawn(c,timeout=defaults.timeout) # s.logfile = open('/tmp/ulgbird.log', 'w') # handle ssh y=0 p=0 l=0 capture=False while True: i=s.expect([STRING_EXPECT_SSH_NEWKEY,STRING_EXPECT_PASSWORD,STRING_EXPECT_REPLY_START,'\n',pexpect.EOF,pexpect.TIMEOUT]) if(i==0): if(y>1): raise Exception("pexpect session failed: Can not save SSH key.") s.sendline('yes') y+=1 elif(i==1): if(p>1): raise Exception("pexpect session failed: Password not accepted.") s.sendline(self.password) p+=1 elif(i==2): capture=True elif(i==3): if(capture): if(l>=skiplines): outfile.write(re.sub(BIRD_CONSOLE_PROMPT_REGEXP,'',s.before)) l+=1 elif(i==4): # EOF -> process output break elif(i==5): raise Exception("pexpect session timed out. last output: "+s.before) else: raise Exception("pexpect session failed: Unknown error. last output: "+s.before) def savePersistentInfo(self): key_bgp = self.getHost() + self.getName() + self.PS_KEY_BGP key_rt = self.getHost() + self.getName() + self.PS_KEY_RT ps = ulgmodel.loadPersistentStorage() ps.set(key_bgp,self.getBGPPeers()) ps.set(key_rt,self.getRoutingTables()) ps.save() def loadPersistentInfo(self): key_bgp = self.getHost() + self.getName() + self.PS_KEY_BGP key_rt = self.getHost() + self.getName() + self.PS_KEY_RT ps = ulgmodel.loadPersistentStorage() self.bgp_peers = ps.get(key_bgp) self.routing_tables = ps.get(key_rt) if(not self.getBGPPeers()) or (not self.getRoutingTables()): self.rescanHook() def rescanHook(self): self.rescanPeers() self.rescanRoutingTables() self.savePersistentInfo()
gpl-3.0
dineth454/MOE
Extended_principle_user/viewProfile.php
23761
<!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"> <meta name="description" content=""> <meta name="author" content=""> <title>GTMS | Profile</title> <!-- Bootstrap Core CSS --> <link href="../assets/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="../assets/css/sb-admin.css" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="../assets/css/plugins/morris.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="../assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="../assets/css/smallbox.css" rel="stylesheet"> <link href="../assets/css/footer.css" rel="stylesheet"> <link href="../assets/css/navbar_styles.css" rel="stylesheet"> </head> <body> <div id="wrapper" > <nav class="navbar navbar-inverse navbar-fixed-top" style="background-color:#020816;" role="navigation"> <!-- include Navigation BAr --> <?php include '../interfaces/navigation_bar.php' ?> <!-- Finished NAvigation bar --> <!-- Sidebar --> <?php include 'Extended_principle_sidebar_activation.php'; include 'Extended_principle_sidebar.php';?> <!-- /#sidebar-wrapper --> <!-- Page Content --> </nav> <div id="page-content-wrapper" style="min-height: 540px;"> <div class="container-fluid";> <div class="col-lg-9 col-lg-offset-1" style="padding-top: 50px;"> <?php //get session attribute Values require '../classes/employee.php'; $employee = new Employee(); $designationTypeID = $_SESSION["designationTypeID"]; // echo $designationTypeID; $nicNumber = $_SESSION["nic"]; $roleType = $_SESSION["roleTypeID"]; $fullName = $_SESSION["fullName"]; $nameWithInitials = $_SESSION["nameWithInitials"]; // echo $nameWithInitials; $employmentID = $_SESSION["employementID"]; $emailAddress = $_SESSION["email"]; $address = $_SESSION["currentAdderss"]; $gender = $_SESSION["gender"]; $marrigeState = $_SESSION["marrageState"]; $mobileNumber = $_SESSION["mobile"]; // Initialize Variables $searchUserSubjectId = 0; $searchUserSchoolId = 0; $searchUserZonalId = 0; $searchUserProvinceId = 0; // Get The result $result1 = $employee->findProvinceOfficerDetails($nicNumber); $result2 = $employee->getZonalOfficerDetails($nicNumber); $result3 = $employee->getPrincipalTeacherBasicDetails($nicNumber); $result4 = $employee->getTeacherSubjectDetails($nicNumber); //$searchUserProvinceId = $result3['provinceOfficeID']; //Sys admin or ministry Officer if($designationTypeID == 1){ $designationTypeID = $_SESSION["designationTypeID"]; // echo $designationTypeID; $nicNumber = $_SESSION["nic"]; $roleType = $_SESSION["roleTypeID"]; $fullName = $_SESSION["fullName"]; $nameWithInitials = $_SESSION["nameWithInitials"]; // echo $nameWithInitials; $employmentID = $_SESSION["employementID"]; $emailAddress = $_SESSION["email"]; $address = $_SESSION["currentAdderss"]; $gender = $_SESSION["gender"]; $marrigeState = $_SESSION["marrageState"]; $mobileNumber = $_SESSION["mobile"]; //Province Officer }else if($designationTypeID == 2){ $searchUserProvinceId = $result1['provinceID']; //zonal Officer }else if($designationTypeID == 3){ $searchUserProvinceId = $result2['provinceOfficeID']; $searchUserZonalId= $result2['zonalID']; //Principal }else if($designationTypeID == 4){ $searchUserProvinceId = $result3['provinceOfficeID']; $searchUserZonalId = $result3['zonalOfficeID']; $searchUserSchoolId = $result3['schoolID']; //teacher }else{ $searchUserProvinceId = $result3['provinceOfficeID']; $searchUserZonalId = $result3['zonalOfficeID']; $searchUserSchoolId = $result3['schoolID']; $searchUserSubjectId = $result4['appoinmentSubject']; } if (isset($_POST['submit'])) { echo '</br>'; $role_subitted = $_POST['select_role']; $nameInitialsSubmitted = $_POST['name']; $nameFullUpdated = $_POST['fname']; $eIDSubmitted = $_POST['eId']; $emailUpdated = $_POST['email']; $addressUpdated = $_POST['address']; $genderUpdated = $_POST['gender']; $merrageUpdated = $_POST['marrrige']; $mobileUpdated = $_POST['mobileNm']; $resultUpdated = $employee->updateEmployeeBasic($nicNumber, $role_subitted, $nameInitialsSubmitted, $nameFullUpdated, $eIDSubmitted, $emailUpdated, $addressUpdated, $genderUpdated, $merrageUpdated, $mobileUpdated); if ($resultUpdated == 1) { echo '<script language="javascript">'; echo 'alert("Updated SuccessFully.Thankyou")'; echo '</script>'; // header("Location: updateEmployeeFront.php"); } else { echo '<script language="javascript">'; echo 'alert("Error Occured While Updating.Thankyou")'; echo '</script>'; } } ?> <div class="row"> <div class="col-lg-7"> <h1 style="padding-bottom:40px; padding-left: 28px;"><strong>My Profile</strong></h1> <!-- Check System admin or not --> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST"> <div class="row"> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <div class="form-group col-lg-12"> <!-- NIC number--> <div class="col-lg-6"><label> NIC Number </label></div> <div class="col-lg-6"><label><?php echo $nicNumber; ?></label></div> </div> <div class="form-group col-lg-12"> <!-- Designation--> <div class="col-lg-6"><label>Designation</label></div> <div class="col-lg-6"> <?php if($designationTypeID == 1) { ?> <?php if($nicNumber == '921003072V') {?> <label>System Admin</label> <?php } else {?> <label>Ministry Officer</label> <?php }?> <?php }else if($designationTypeID == 2) {?> <label>Province Officer</label> <?php } else if($designationTypeID == 3) {?> <label>Zonal Officer</label> <?php } else if( $designationTypeID == 4) {?> <label>Principal</label> <?php } else {?> <label>Teacher</label> <?php } ?> </div> </div> <?php if($searchUserProvinceId > 0) {?> <div id="provinceIDDiv" class="form-group col-lg-12"> <div id="provinceHiddenForm" class="col-lg-6"> <label>Province Office</label></div> <div class="col-lg-6"> <?php if ($searchUserProvinceId == 1) { ?> <!--<option selected="true" value="1">centralProvince</option>--> <label>Central Province</label> <?php } else if ($searchUserProvinceId == 2) { ?> <label>Western Province</label> <?php } else if ($searchUserProvinceId == 3) { ?> <label>Southern Province</label> <?php } else if ($searchUserProvinceId == 4) { ?> <label>Northern Province</label> <?php } else if ($searchUserProvinceId == 5) { ?> <label>Eastern Province</label> <?php } else { } ?> </div> </div> <?php } ?> <?php if($searchUserZonalId > 0) { ?> <div id="zonalOfficeDiv" class="form-group col-lg-12"> <div id="zonalOfficeHidden" class="col-lg-6"> <label>Zonal Office</label></div> <div class="col-lg-6"> <?php $result = $employee->loadZonalOffices(); foreach ($result as $array) { if ($array['zonalID'] == $searchUserZonalId) { echo '<label selected = "true" value="' . $array['zonalID'] . '" >' . $array['zonalName'] . '</label>'; } } ?> </div> </div> <?php } ?> <?php if($searchUserSchoolId > 0) {?> <div id="schoolIdDiv" class="form-group col-lg-12"> <div id="schoolHidden" class="col-lg-6"> <label>School</label></div> <div class="col-lg-6"> <?php $result = $employee->loadSchools(); foreach ($result as $array) { if ($array['schoolID'] == $searchUserSchoolId) { echo '<label selected = "true" value="' . $array['schoolID'] . '" >' . $array['schoolName'] . '</label>'; } } ?> </div> </div> <?php } ?> <?php if($searchUserSubjectId > 0) {?> <div id="subjectHiddenDiv" class="form-group col-lg-12"> <div id="subjectHidden" class="col-lg-6"> <label>Appoinment Subject</label></div> <div class="col-lg-6"> <?php $result = $employee->loadSubjects(); foreach ($result as $array) { if ($array['subjectID'] == $searchUserSubjectId) { echo '<label selected = "true" value="' . $array['subjectID'] . '" >' . $array['subject'] . '</label>'; } } ?> </div> </div> <?php } ?> <div class="form-group col-lg-12"> <!-- Name with initials--> <div class="col-lg-6"><label>Name with Initials</label></div> <div class="col-lg-6"> <label><?php echo $nameWithInitials; ?></label> </div> </div> <div class="form-group col-lg-12"> <!-- Full Name--> <div class="col-lg-6"><label>Full Name</label></div> <div class="col-lg-6"> <label ><?php echo $fullName; ?></label> </div> </div> <div class="form-group col-lg-12"> <!--Email--> <div class="col-lg-6"><label>Email</label></div> <div class="col-lg-6"> <label ><?php echo $emailAddress; ?></label> </div> </div> <div class="form-group col-lg-12"> <!-- Employment ID--> <div class="col-lg-6"><label>Employment ID</label></div> <div class="col-lg-6"> <label ><?php echo $employmentID; ?></label> </div> </div> <div class="form-group col-lg-12"> <!--Email--> <div class="col-lg-6"><label>Current Address</label></div> <div class="col-lg-6"> <label> <?php echo $address; ?></label> </div> </div> <div class="form-group col-lg-12 col-md-12 col-sm-12"> <!-- Gender--> <div class="col-lg-6"><label>Gender</label></div> <div class="col-lg-6"> <?php if ($gender == 2) { ?> <label>Male</label> <?php } else { ?> <label>Female</label> <?php } ?> </div> </div> <div class="form-group col-lg-12"> <!--Marrige--> <div class="col-lg-6"><label>Marriage Status</label></div> <div class="col-lg-6"> <?php if ($marrigeState == 2) { ?> <label>Yes</label> <?php } else { ?> <label>No</label> <?php } ?> </div> </div> <div class="form-group col-lg-12"> <!--mobile_numb--> <div class="col-lg-6"><label>Mobile Number</label></div> <div class="col-lg-6"> <!-- <input type="text" class="form-control" id="mobileNm" value="<?php echo $mobileNumber; ?>" name="mobileNm" placeholder="Enter mobile Number"/>-- <!--<label id="errorFirstName" style="font-size:10px"> </label>--> <label> <?php echo $mobileNumber; ?></label> </div> </div> <div class="col-lg-5" style="position: fixed; top: 150px; left: 850px;"> <img src="../images/personDetails.png" width="400" height="400"> </div> </div> </div> </form> </div> </div> </div> </div> </div> </div> <!-- /#page-content-wrapper --> <?php #session_unset(); ?> <?php #session_destroy(); ?> </br></br> <?php include '../interfaces/footer.php' ?> <script src = "../assets/js/jquery-2.1.4.min.js"></script> <script src="../assets/js/jquery.js"></script> <script src="../assets/js/bootstrap.min.js"></script> </div> </body> </html>
gpl-3.0