repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
panbasten/imeta | imeta2.x/imeta-src/imeta-ui/src/main/java/com/panet/imeta/trans/steps/filesfromresult/FilesFromResultDialog.java | 2011 | package com.panet.imeta.trans.steps.filesfromresult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.panet.iform.core.BaseFormMeta;
import com.panet.iform.core.ValidateForm;
import com.panet.iform.core.base.ButtonMeta;
import com.panet.iform.forms.columnForm.ColumnFormDataMeta;
import com.panet.iform.forms.columnForm.ColumnFormMeta;
import com.panet.iform.forms.labelInput.LabelInputMeta;
import com.panet.imeta.trans.TransMeta;
import com.panet.imeta.trans.step.BaseStepDialog;
import com.panet.imeta.trans.step.StepDialogInterface;
import com.panet.imeta.trans.step.StepMeta;
import com.panet.imeta.ui.exception.ImetaException;
public class FilesFromResultDialog extends BaseStepDialog implements
StepDialogInterface {
/**
* 列式表单
*/
private ColumnFormMeta columnFormMeta;
private ColumnFormDataMeta columnFormDataMeta;
/**
* 步骤名
*/
private LabelInputMeta name;
public FilesFromResultDialog(StepMeta stepMeta, TransMeta transMeta) {
super(stepMeta, transMeta);
}
@Override
public JSONObject open() throws ImetaException {
try {
JSONObject rtn = new JSONObject();
JSONArray cArr = new JSONArray();
String id = this.getId();
// 得到form
this.columnFormDataMeta = new ColumnFormDataMeta(id, null);
this.columnFormMeta = new ColumnFormMeta(columnFormDataMeta);
// 步骤名
this.name = new LabelInputMeta(id + ".name", "步骤名", null, null,
"步骤名必须填写", super.getStepMeta().getName(), null, ValidateForm
.getInstance().setRequired(true));
this.name.setSingle(true);
// 装载到form
columnFormMeta.putFieldsetsContent(new BaseFormMeta[] { this.name});
columnFormMeta.putFieldsetsFootButtons(new ButtonMeta[] {super.getOkBtn(),super.getCancelBtn() });
cArr.add(columnFormMeta.getFormJo());
rtn.put("items", cArr);
rtn.put("title", super.getStepMeta().getName());
return rtn;
} catch (Exception ex) {
throw new ImetaException(ex.getMessage(), ex);
}
}
}
| gpl-2.0 |
teamfx/openjfx-10-dev-rt | modules/javafx.controls/src/main/java/javafx/scene/control/cell/TreeItemPropertyValueFactory.java | 8643 | /*
* Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.scene.control.cell;
import javafx.beans.NamedArg;
import javafx.beans.property.Property;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableColumn.CellDataFeatures;
import javafx.scene.control.TreeTableView;
import javafx.util.Callback;
import com.sun.javafx.property.PropertyReference;
import com.sun.javafx.scene.control.Logging;
import sun.util.logging.PlatformLogger;
import sun.util.logging.PlatformLogger.Level;
/**
* A convenience implementation of the Callback interface, designed specifically
* for use within the {@link TreeTableColumn}
* {@link TreeTableColumn#cellValueFactoryProperty() cell value factory}. An example
* of how to use this class is:
*
* <pre><code>
* TreeTableColumn<Person,String> firstNameCol = new TreeTableColumn<Person,String>("First Name");
* firstNameCol.setCellValueFactory(new TreeItemPropertyValueFactory<Person,String>("firstName"));
* </code></pre>
*
* <p>
* In this example, {@code Person} is the class type of the {@link TreeItem}
* instances used in the {@link TreeTableView}.
* The class {@code Person} must be declared public.
* {@code TreeItemPropertyValueFactory} uses the constructor argument,
* {@code "firstName"}, to assume that {@code Person} has a public method
* {@code firstNameProperty} with no formal parameters and a return type of
* {@code ObservableValue<String>}.
* </p>
* <p>
* If such a method exists, then it is invoked, and additionally assumed
* to return an instance of {@code Property<String>}. The return value is used
* to populate the {@link TreeTableCell}. In addition, the {@code TreeTableView}
* adds an observer to the return value, such that any changes fired will be
* observed by the {@code TreeTableView}, resulting in the cell immediately
* updating.
* </p>
* <p>
* If no such method exists, then {@code TreeItemPropertyValueFactory}
* assumes that {@code Person} has a public method {@code getFirstName} or
* {@code isFirstName} with no formal parameters and a return type of
* {@code String}. If such a method exists, then it is invoked, and its return
* value is wrapped in a {@link ReadOnlyObjectWrapper}
* and returned to the {@code TreeTableCell}. In this situation,
* the {@code TreeTableCell} will not be able to observe changes to the property,
* unlike in the first approach above.
* </p>
*
* <p>For reference (and as noted in the TreeTableColumn
* {@link TreeTableColumn#cellValueFactoryProperty() cell value factory} documentation), the
* long form of the code above would be the following:
* </p>
*
* <pre><code>
* TreeTableColumn<Person,String> firstNameCol = new TreeTableColumn<Person,String>("First Name");
* {@literal
* firstNameCol.setCellValueFactory(new Callback<CellDataFeatures<Person, String>, ObservableValue<String>>() {
* public ObservableValue<String> call(CellDataFeatures<Person, String> p) {
* // p.getValue() returns the TreeItem<Person> instance for a particular
* // TreeTableView row, and the second getValue() call returns the
* // Person instance contained within the TreeItem.
* return p.getValue().getValue().firstNameProperty();
* }
* });
* }
* }
* </code></pre>
*
* <p><b>Deploying an Application as a Module</b></p>
* <p>
* If the referenced class is in a named module, then it must be reflectively
* accessible to the {@code javafx.base} module.
* A class is reflectively accessible if the module
* {@link Module#isOpen(String,Module) opens} the containing package to at
* least the {@code javafx.base} module.
* Otherwise the {@link #call call(TreeTableColumn.CellDataFeatures)} method
* will log a warning and return {@code null}.
* </p>
* <p>
* For example, if the {@code Person} class is in the {@code com.foo} package
* in the {@code foo.app} module, the {@code module-info.java} might
* look like this:
* </p>
*
<pre>{@code module foo.app {
opens com.foo to javafx.base;
}}</pre>
*
* <p>
* Alternatively, a class is reflectively accessible if the module
* {@link Module#isExported(String) exports} the containing package
* unconditionally.
* </p>
*
* @see TreeTableColumn
* @see TreeTableView
* @see TreeTableCell
* @see PropertyValueFactory
* @see MapValueFactory
* @since JavaFX 8.0
*/
public class TreeItemPropertyValueFactory<S,T> implements Callback<TreeTableColumn.CellDataFeatures<S,T>, ObservableValue<T>> {
private final String property;
private Class<?> columnClass;
private String previousProperty;
private PropertyReference<T> propertyRef;
/**
* Creates a default PropertyValueFactory to extract the value from a given
* TableView row item reflectively, using the given property name.
*
* @param property The name of the property with which to attempt to
* reflectively extract a corresponding value for in a given object.
*/
public TreeItemPropertyValueFactory(@NamedArg("property") String property) {
this.property = property;
}
/** {@inheritDoc} */
@Override public ObservableValue<T> call(CellDataFeatures<S, T> param) {
TreeItem<S> treeItem = param.getValue();
return getCellDataReflectively(treeItem.getValue());
}
/**
* Returns the property name provided in the constructor.
* @return the property name provided in the constructor
*/
public final String getProperty() { return property; }
private ObservableValue<T> getCellDataReflectively(S rowData) {
if (getProperty() == null || getProperty().isEmpty() || rowData == null) return null;
try {
// we attempt to cache the property reference here, as otherwise
// performance suffers when working in large data models. For
// a bit of reference, refer to RT-13937.
if (columnClass == null || previousProperty == null ||
! columnClass.equals(rowData.getClass()) ||
! previousProperty.equals(getProperty())) {
// create a new PropertyReference
this.columnClass = rowData.getClass();
this.previousProperty = getProperty();
this.propertyRef = new PropertyReference<T>(rowData.getClass(), getProperty());
}
if (propertyRef != null) {
return propertyRef.getProperty(rowData);
}
} catch (RuntimeException e) {
try {
// attempt to just get the value
T value = propertyRef.get(rowData);
return new ReadOnlyObjectWrapper<T>(value);
} catch (RuntimeException e2) {
// fall through to logged exception below
}
// log the warning and move on
final PlatformLogger logger = Logging.getControlsLogger();
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Can not retrieve property '" + getProperty() +
"' in TreeItemPropertyValueFactory: " + this +
" with provided class type: " + rowData.getClass(), e);
}
propertyRef = null;
}
return null;
}
}
| gpl-2.0 |
SRMSE/cron-wikidata | vendor/ask/ask/src/Language/Option/SortExpression.php | 1076 | <?php
namespace Ask\Language\Option;
use InvalidArgumentException;
/**
* A sort expression.
*
* @since 1.0
*
* @licence GNU GPL v2+
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
abstract class SortExpression implements \Ask\Immutable, \Ask\Typeable {
const PROPERTY_VALUE = 'propertyValue';
const DIRECTION_ASCENDING = 'asc';
const DIRECTION_DESCENDING = 'desc';
/**
* The sort direction.
* This is one of the SortExpression::DIRECTION_ constants.
*
* @var string|null
*/
protected $direction = null;
/**
* Returns the sort direction.
* This is one of the SortExpression::DIRECTION_ constants.
*
* @since 1.0
*
* @return string
*/
public function getDirection() {
assert( $this->direction !== null );
return $this->direction;
}
protected function assertIsDirection( $direction ) {
if ( !is_string( $direction ) || !in_array( $direction, array( self::DIRECTION_ASCENDING, self::DIRECTION_DESCENDING ) ) ) {
throw new InvalidArgumentException( '$direction needs to be one of the direction constants' );
}
}
} | gpl-2.0 |
Meritei/FINAL-MTRH | Mtrh/app/views/admission/destroy.blade.php | 2255 | @extends('defaults.masterpage')
@section('header')
{{ HTML::style('css/main.css') }}
<title>Delete Admission</title>
@stop
@section('content')
<center>
<div id="covera">
{{Form::open(['route'=>'admission.destroy'])}}
<table id="tabler">
<tr>
<th colspan = "7">FILL THESE FORM TO DELETE ADMISSION</th>
</tr>
<tr>
<td colspan = "7"><p><i>Please ensure you have filled the file number section</br>The rest section is not compulsory </i></p></td>
</tr>
<tr>
<td> {{Form::label('file_number','File Number:')}}</td>
<td>{{Form::input('text','file_number')}} {{ $errors->first('name', '<span class=error>:message></span>') }}</td>
<td> {{Form::label('diagnosis','Diagnosis:')}}</td>
<td> {{Form::input('text','diagnosis')}} </td>
<td>{{Form::label('prescription','Prescription:')}}</td>
<td>{{Form::input('text','prescription')}}</td>
<td>{{Form::label('word_allocated','Word Allocated:')}}</td>
<td>{{Form::input('text','word_allocated')}} </td>
</tr>
<tr>
<td>{{Form::label('word_number','Word Number:')}}</td>
<td>{{Form::input('text','word_number')}}</td>
<td>{{Form::label('word_room','Word Room:')}}</td>
<td>{{Form::input('text','word_room')}} </td>
<td>{{Form::label('current_condition','Current Condition:')}}</td>
<td>{{Form::input('text','current_condition')}} </td>
<td>{{Form::label('comments','Doctor's Comments:')}}</td>
<td>{{Form::input('text','comments')}} </td>
</tr>
<tr>
<td></td>
<td>{{Form::label('farther_test','Farther Test:')}}</td>
<td>{{Form::input('text','farther_test')}}</td>
<td>{{Form::label('farther_resuilt','Farther Resuilts:')}}</td>
<td>{{Form::input('text','farther_resuilt')}}</td>
<td>{{Form::label('relised_date','Relise Date:')}}</td>
<td>{{Form::input('text','relised_date')}} </td>
<td></td>
<tr>
<tr>
<td colspan = "7">{{Form::submit('DELETE')}}</td>
</tr>
</table>
{{Form::close()}}
</div>
</center>
@stop
@section('footer')
<center><p>A luke Dennis production . dennisluke44@gmail.com</p></center>
@stop | gpl-2.0 |
Automattic/wp-calypso | client/layout/guided-tours/tours/marketing-connections-tour/meta.js | 77 | export default {
name: 'marketingConnectionsTour',
version: '20200410',
};
| gpl-2.0 |
felladrin/last-wish | Scripts/Items/Special/Broken Furniture Collection/BrokenBookcase.cs | 1987 | namespace Server.Items
{
[Flipable( 0xC14, 0xC15 )]
public class BrokenBookcaseComponent : AddonComponent
{
public override int LabelNumber { get { return 1076258; } } // Broken Bookcase
public BrokenBookcaseComponent() : base( 0xC14 )
{
}
public BrokenBookcaseComponent( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
public class BrokenBookcaseAddon : BaseAddon
{
public override BaseAddonDeed Deed { get { return new BrokenBookcaseDeed(); } }
[Constructable]
public BrokenBookcaseAddon() : base()
{
AddComponent( new BrokenBookcaseComponent(), 0, 0, 0 );
}
public BrokenBookcaseAddon( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
public class BrokenBookcaseDeed : BaseAddonDeed
{
public override BaseAddon Addon { get { return new BrokenBookcaseAddon(); } }
public override int LabelNumber { get { return 1076258; } } // Broken Bookcase
[Constructable]
public BrokenBookcaseDeed() : base()
{
LootType = LootType.Blessed;
}
public BrokenBookcaseDeed( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
}
}
| gpl-2.0 |
GaloisInc/KOA | infrastructure/source/MobileVotingSystem/Voting Server J2SE/src/Server.java | 1693 | import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This server class will listen indefinitely for connection requests from a client
* and spawn a new thread to handle each new session on the appropriate port.
*/
public class Server {
// The port on which to listen
final static int PORT = 8000;
public static void main(String[] args) throws IOException {
// Create a new server socket
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Listening on port " + PORT + "...");
// To number a client
int clientNo = 1;
while (true) {
// Listen for a new connection request
Socket connectToClient = serverSocket.accept();
// Print the new connection number to the console
System.out.println("Start thread for client " + clientNo);
// Find the clients host name and ip address
InetAddress clientInetAddress = connectToClient.getInetAddress();
System.out.println("Client " + clientNo + "'s host name is "
+ clientInetAddress.getHostName());
System.out.println("Client " + clientNo + "'s IP Address is "
+ clientInetAddress.getHostAddress());
// Create a new thread for the connection
HandleAClient thread = new HandleAClient(connectToClient);
// Start the new thread
thread.start();
// Increment clientNo
clientNo++;
}
}
}
| gpl-2.0 |
ThimPressWP/FundPress | inc/admin/views/metaboxes/donate.php | 7865 | <?php
/**
* Admin view: Donate detail meta box.
*
* @version 2.0
* @package View
* @author Thimpress, leehld
*/
/**
* Prevent loading this file directly
*/
defined( 'ABSPATH' ) || exit();
?>
<?php
global $post;
$donation = DN_Donate::instance( $post->ID );
$currency = $donation->currency ? $donation->currency : donate_get_currency();
$donor_id = $donation->donor_id;
$type = $this->get_field_value( 'type', 'system' );
?>
<div class="cmb2-wrap">
<div class="cmb-field-list">
<!-- donate type -->
<div class="cmb-row">
<div class="cmb-th">
<label for="<?php echo esc_attr( $this->get_field_name( 'type' ) ) ?>"><?php _e( 'Donate Type', 'fundpress' ); ?></label>
</div>
<div class="cmb-td">
<select name="<?php echo esc_attr( $this->get_field_name( 'type' ) ) ?>"
id="<?php echo esc_attr( $this->get_field_name( 'type' ) ) ?>">
<option value="system"<?php selected( $donation->type, 'system' ); ?>><?php _e( 'System', 'fundpress' ); ?></option>
<option value="campaign"<?php selected( $donation->type, 'campaign' ); ?>><?php _e( 'Campaign', 'fundpress' ); ?></option>
</select>
<p class="cmb2-metabox-description"><?php _e( 'Select donate type, donate for <i>Campaign</i> or <i>System</i>', 'fundpress' ); ?></p>
</div>
</div>
<!-- end donate type -->
<!-- donor -->
<div class="cmb-row">
<div class="cmb-th">
<label for="<?php echo esc_attr( $this->get_field_name( 'donor_id' ) ) ?>"><?php _e( 'Donor', 'fundpress' ); ?></label>
</div>
<div class="cmb-td">
<select name="<?php echo esc_attr( $this->get_field_name( 'donor_id' ) ) ?>"
id="<?php echo esc_attr( $this->get_field_name( 'donor_id' ) ) ?>">
<?php foreach ( donate_get_donors() as $id ) : ?>
<?php $donor = DN_Donor::instance( $id ); ?>
<option value="<?php echo esc_attr( $id ); ?>"<?php selected( $donor_id, $id ); ?>>
<?php printf( '%s(%s)', $donor->get_fullname(), $donor->email ) ?>
</option>
<?php endforeach; ?>
</select>
<p class="cmb2-metabox-description"><?php _e( 'Select donor', 'fundpress' ); ?></p>
</div>
</div>
<!-- end donor -->
<!-- donate for campaign -->
<div class="donate_section_type<?php echo $type !== 'campaign' ? ' hide-if-js' : '' ?>" id="section_campaign">
<!-- hide-if-js -->
<table class="donate_items" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th class="campaign"><?php _e( 'Campaign', 'fundpress' ); ?></th>
<th class="amount"><?php _e( 'Amount', 'fundpress' ); ?></th>
<th class="action"><?php _e( 'Action', 'fundpress' ); ?></th>
</tr>
</thead>
<tbody>
<?php if ( $items = $donation->get_items() ) : ?>
<?php foreach ( $items as $k => $item ) : ?>
<tr class="item" data-id="<?php echo esc_attr( $item->id ); ?>">
<td class="campaign">
<?php if ( $campaigns = donate_get_campaigns() ) : ?>
<select name="donate_item[<?php echo esc_attr( $k ); ?>][campaign_id]">
<optgroup label="<?php _e( 'Select Campaign', 'fundpress' ); ?>">
<?php foreach ( $campaigns as $campaign_id ) : ?>
<option value="<?php echo esc_attr( $campaign_id ); ?>"<?php selected( $item->campaign_id, $campaign_id ); ?>><?php printf( '%s', get_the_title( $campaign_id ) ) ?></option>
<?php endforeach; ?>
</optgroup>
</select>
<?php endif; ?>
</td>
<td class="amount">
<input type="number" step="any"
name="donate_item[<?php echo esc_attr( $k ); ?>][amount]"
value="<?php echo esc_attr( $item->total ); ?>" class="donate_item_total"/>
</td>
<td class="action">
<input type="hidden" name="donate_item[<?php echo esc_attr( $k ); ?>][item_id]"
value="<?php echo esc_attr( $item->id ); ?>"/>
<a href="#" data-item-id="<?php echo esc_attr( $item->id ); ?>" class="remove"><i
class="icon-cross"></i></a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
<tfoot data-currency="<?php echo esc_attr( donate_get_currency_symbol( $donation->currency ) ); ?>">
<tr class="item">
<td class="campaign" colspan="3" style="text-align: center;">
<a href="#" class="button donate_add_campaign"><?php _e( 'Add Campaign', 'fundpress' ); ?></a>
</td>
</tr>
<tr>
<td class="total"><?php printf( __( 'Total(%s)', 'fundpress' ), donate_get_currency_symbol( $donation->currency ) ); ?></td>
<td class="amount">
<ins><?php printf( '%s', $donation->total ) ?></ins>
</td>
</tr>
</tfoot>
</table>
</div>
<!-- end donate for campaign -->
<!-- donate for system -->
<div class="donate_section_type<?php echo $type !== 'system' ? ' hide-if-js' : '' ?>" id="section_system">
<div class="cmb-row">
<div class="cmb-th">
<label for="<?php echo esc_attr( $this->get_field_name( 'total' ) ) ?>"><?php _e( 'Total', 'fundpress' ); ?></label>
</div>
<div class="cmb-td">
<input type="number" name="<?php echo esc_attr( $this->get_field_name( 'total' ) ) ?>" step="any"
min="0" value="<?php echo esc_attr( $donation->total ); ?>"/>
<p class="cmb2-metabox-description"><?php printf( __( 'Donate Total(%s)', 'fundpress' ), donate_get_currency_symbol( $donation->currency ) ); ?></p>
</div>
</div>
</div>
<!-- end donate for system -->
</div>
</div>
<script type="text/html" id="tmpl-donate-template-campaign-item">
<tr class="item">
<td class="campaign">
<?php if ( $campaigns = donate_get_campaigns() ) : ?>
<select name="donate_item[{{ data.unique_id }}][campaign_id]">
<optgroup label="<?php _e( 'Select Campaign', 'fundpress' ); ?>">
<?php foreach ( $campaigns as $campaign_id ) : ?>
<option value="<?php echo esc_attr( $campaign_id ); ?>"><?php printf( '%s', get_the_title( $campaign_id ) ) ?></option>
<?php endforeach; ?>
</optgroup>
</select>
<?php endif; ?>
</td>
<td class="amount">
<input type="number" step="any" name="donate_item[{{ data.unique_id }}][amount]" value=""
class="donate_item_total"/>
</td>
<td class="action">
<input type="hidden" name="donate_item[{{ data.unique_id }}][item_id]" value=""/>
<a href="#" data-item-id="" class="remove"><i class="icon-cross"></i></a>
</td>
</tr>
</script>
| gpl-2.0 |
NBassan/rivendell | rdcatch/rdcatch_es.ts | 36493 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>AddRecording</name>
<message>
<source>Schedule a:</source>
<translation>Programar:</translation>
</message>
<message>
<source>&Recording</source>
<translation>&Grabación</translation>
</message>
<message>
<source>&Playout</source>
<translation>&Reproducción</translation>
</message>
<message>
<source>&Macro Cart</source>
<translation>Cartucho &Macro</translation>
</message>
<message>
<source>&Switch Event</source>
<translation>&Evento con la Suichera</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>&Download</source>
<translation>&Descarga</translation>
</message>
<message>
<source>&Upload</source>
<translation>&Subida</translation>
</message>
</context>
<context>
<name>CatchListView</name>
<message>
<source>Edit Cue Markers</source>
<translation>Editar marcadores Cue</translation>
</message>
</context>
<context>
<name>DeckMon</name>
<message>
<source>MON</source>
<translation>MON</translation>
</message>
<message>
<source>ABORT</source>
<translation>ABORTAR</translation>
</message>
<message>
<source>OFFLINE</source>
<translation>OFFLINE</translation>
</message>
<message>
<source>L</source>
<translation>Iz</translation>
</message>
<message>
<source>R</source>
<translation>De</translation>
</message>
<message>
<source>IDLE</source>
<translation>IDLE</translation>
</message>
<message>
<source>READY</source>
<translation>LISTO</translation>
</message>
<message>
<source>WAITING</source>
<translation>ESPERA</translation>
</message>
<message>
<source>RECORDING</source>
<translation>GRABANDO</translation>
</message>
<message>
<source>PLAYING</source>
<translation>REPROD</translation>
</message>
<message>
<source>[no description]</source>
<translation>[sin descripción]</translation>
</message>
<message>
<source>[multiple events]</source>
<translation>[múltiples eventos]</translation>
</message>
<message>
<source>[unknown cut]</source>
<translation>[audio desconocido]</translation>
</message>
</context>
<context>
<name>EditCartEvent</name>
<message>
<source>Edit Cart Event</source>
<translation>Editar evento de cartucho</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento activo</translation>
</message>
<message>
<source>Location:</source>
<translation>Ubicación:</translation>
</message>
<message>
<source>Start Time:</source>
<translation>Hora inicio:</translation>
</message>
<message>
<source>Description:</source>
<translation>Descripción:</translation>
</message>
<message>
<source>Cart Number:</source>
<translation>Nro. cartucho:</translation>
</message>
<message>
<source>&Select</source>
<translation>&Seleccionar</translation>
</message>
<message>
<source>Active Days</source>
<translation>Días activos</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>Sunday</source>
<translation>Domingo</translation>
</message>
<message>
<source>Make OneShot</source>
<translation>Una sola vez</translation>
</message>
<message>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>Invalid Cart</source>
<translation>Cartucho inválido</translation>
</message>
<message>
<source>That cart doesn't exist!</source>
<translation>¡El cartucho no existe!</translation>
</message>
<message>
<source>Duplicate Event</source>
<translation>Evento duplicado</translation>
</message>
<message>
<source>An event with these parameters already exists!</source>
<translation>¡Un evento con esos parámetros ya existe!</translation>
</message>
<message>
<source>&Save As
New</source>
<translation>&Guardar
como nuevo</translation>
</message>
</context>
<context>
<name>EditDownload</name>
<message>
<source>Edit Download</source>
<translation>Edtar Descarga</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento Activo</translation>
</message>
<message>
<source>Location:</source>
<translation>Ubicación:</translation>
</message>
<message>
<source>Start Time:</source>
<translation>Hora Inicio:</translation>
</message>
<message>
<source>Description:</source>
<translation>Descripción:</translation>
</message>
<message>
<source>Url:</source>
<translation>Url:</translation>
</message>
<message>
<source>Username:</source>
<translation>Usuario:</translation>
</message>
<message>
<source>Password:</source>
<translation>Contraseña:</translation>
</message>
<message>
<source>Destination:</source>
<translation>Destino:</translation>
</message>
<message>
<source>&Select</source>
<translation>&Seleccionar</translation>
</message>
<message>
<source>Active Days</source>
<translation>Días activo</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>Sunday</source>
<translation></translation>
</message>
<message>
<source>Make OneShot</source>
<translation>Una sola vez</translation>
</message>
<message>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>Cut</source>
<translation>Audio</translation>
</message>
<message>
<source>Invalid URL</source>
<translation>URL inválido</translation>
</message>
<message>
<source>The URL is invalid!</source>
<translation>¡El URL es inválido!</translation>
</message>
<message>
<source>Unsupported URL protocol!</source>
<translation>¡Protocolo de URL no soportado!</translation>
</message>
<message>
<source>Duplicate Event</source>
<translation>Evento duplicado</translation>
</message>
<message>
<source>An event with these parameters already exists!</source>
<translation>¡Un evento con esos parámetros ya existe!</translation>
</message>
<message>
<source>&Save As
New</source>
<translation>&Guardar
como Nuevo</translation>
</message>
<message>
<source>Autotrim</source>
<translation>Autorecortar</translation>
</message>
<message>
<source>Level:</source>
<translation>Nivel:</translation>
</message>
<message>
<source>dBFS</source>
<translation>dBFS</translation>
</message>
<message>
<source>Normalize</source>
<translation>Normalizar</translation>
</message>
<message>
<source>Channels:</source>
<translation>Canales:</translation>
</message>
<message>
<source>Event Offset:</source>
<translation>Desplaz.Evento:</translation>
</message>
<message>
<source>days</source>
<translation>días</translation>
</message>
<message>
<source>Missing Username</source>
<translation>Falta el usuario</translation>
</message>
<message>
<source>You must specify a username!</source>
<translation>¡Debe especificar un nombre de usuario!</translation>
</message>
<message>
<source>Update Library Metadata</source>
<translation>Actualizar metadatos en biblioteca</translation>
</message>
</context>
<context>
<name>EditPlayout</name>
<message>
<source>Edit Playout</source>
<translation>Editar Reproducción</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento activo</translation>
</message>
<message>
<source>Location:</source>
<translation>Ubicación:</translation>
</message>
<message>
<source>Start Time:</source>
<translation>Hora Inicio:</translation>
</message>
<message>
<source>Description:</source>
<translation>Descripción:</translation>
</message>
<message>
<source>Destination:</source>
<translation>Destino:</translation>
</message>
<message>
<source>&Select</source>
<translation>&Seleccionar</translation>
</message>
<message>
<source>Active Days</source>
<translation>Días Activo</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>Sunday</source>
<translation>Domingo</translation>
</message>
<message>
<source>Make OneShot</source>
<translation>Una sola vez</translation>
</message>
<message>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>Duplicate Event</source>
<translation>Evento duplicado</translation>
</message>
<message>
<source>An event with these parameters already exists!</source>
<translation>¡Un evento con esos parámetros ya existe!</translation>
</message>
<message>
<source>&Save As
New</source>
<translation>&Guardar
como Nuevo</translation>
</message>
</context>
<context>
<name>EditRecording</name>
<message>
<source>Edit Recording</source>
<translation>Edtar Grabación</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento activo</translation>
</message>
<message>
<source>Location:</source>
<translation>Ubicación:</translation>
</message>
<message>
<source>Start Parameters</source>
<translation>Parámetros de Inicio</translation>
</message>
<message>
<source>Use Hard Time</source>
<translation>Hora estricta</translation>
</message>
<message>
<source>Record Start Time:</source>
<translation>Inicio de grabación:</translation>
</message>
<message>
<source>Use GPI</source>
<translation>Usar GPI</translation>
</message>
<message>
<source>Window Start Time:</source>
<translation>Margen de inicio:</translation>
</message>
<message>
<source>GPI Matrix:</source>
<translation>Matriz GPI:</translation>
</message>
<message>
<source>GPI Line:</source>
<translation>Línea GPI:</translation>
</message>
<message>
<source>Start Delay:</source>
<translation>Demora en Inicio:</translation>
</message>
<message>
<source>End Parameters</source>
<translation>Parámetros de Fin</translation>
</message>
<message>
<source>Use Length</source>
<translation>Usar duración</translation>
</message>
<message>
<source>Record Length:</source>
<translation>Duración de Grabación:</translation>
</message>
<message>
<source>Record End Time:</source>
<translation>Hora fin de grabación:</translation>
</message>
<message>
<source>Window End Time:</source>
<translation>Margen de fin:</translation>
</message>
<message>
<source>Description:</source>
<translation>Descripción:</translation>
</message>
<message>
<source>Source:</source>
<translation>Fuente:</translation>
</message>
<message>
<source>Destination:</source>
<translation>Destino:</translation>
</message>
<message>
<source>&Select</source>
<translation>&Seleccionar</translation>
</message>
<message>
<source>Active Days</source>
<translation>Días activo</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>Sunday</source>
<translation>Domingo</translation>
</message>
<message>
<source>Start Date Offset:</source>
<translation>Desplaz. Fecha Inicio:</translation>
</message>
<message>
<source>None</source>
<translation>Nada</translation>
</message>
<message>
<source>End Date Offset:</source>
<translation>Desplaz. Fecha Fin:</translation>
</message>
<message>
<source>Channels:</source>
<translation>Canales:</translation>
</message>
<message>
<source>Make OneShot</source>
<translation>Una sola vez</translation>
</message>
<message>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>Cut</source>
<translation>Audio</translation>
</message>
<message>
<source>Missing Cut</source>
<translation>Audio no encontrado</translation>
</message>
<message>
<source>You must assign a record cut!</source>
<translation>¡Debe asignar un audio para la grabación!</translation>
</message>
<message>
<source>Record Parameter Error</source>
<translation>Error de parámetros de la grabación</translation>
</message>
<message>
<source>The start GPI window cannot end before it begins!</source>
<translation>¡La ventana GPI inicial no puede terminar antes de que empiece!</translation>
</message>
<message>
<source>The recording cannot end before it begins!</source>
<translation>¡La grabación no puede terminar antes de que empiece!</translation>
</message>
<message>
<source>The end GPI window cannot end before it begins!</source>
<translation>¡La ventana GPI final no puede terminar antes de que empiece!</translation>
</message>
<message>
<source>The start GPI matrix doesn't exist!</source>
<translation>¡La matriz GPI de inicio no existe!</translation>
</message>
<message>
<source>The start GPI line doesn't exist!</source>
<translation>¡La línea GPI de inicio no existe!</translation>
</message>
<message>
<source>The end GPI matrix doesn't exist!</source>
<translation>¡La matriz GPI final no existe!</translation>
</message>
<message>
<source>The end GPI line doesn't exist!</source>
<translation>¡La línea GPi final no existe!</translation>
</message>
<message>
<source>&Save As
New</source>
<translation>&Guardar
como Nuevo</translation>
</message>
<message>
<source>Duplicate Event</source>
<translation>Evento duplicado</translation>
</message>
<message>
<source>An event with these parameters already exists!</source>
<translation>¡Un evento con esos parámetros ya existe!</translation>
</message>
<message>
<source>Max Record Length:</source>
<translation>Máx Duración de la Grabación:</translation>
</message>
<message>
<source>Allow Multiple Recordings within this Window</source>
<translation>Permitir múltiples grabaciones en esta ventana</translation>
</message>
<message>
<source>Autotrim</source>
<translation>Autorecortar</translation>
</message>
<message>
<source>Level:</source>
<translation>Nivel:</translation>
</message>
<message>
<source>dBFS</source>
<translation>dBFS</translation>
</message>
<message>
<source>Normalize</source>
<translation>Normalizar</translation>
</message>
</context>
<context>
<name>EditSwitchEvent</name>
<message>
<source>Edit Switcher Event</source>
<translation>Editar Eventos de Suichera</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento Activo</translation>
</message>
<message>
<source>Location:</source>
<translation>Ubicación:</translation>
</message>
<message>
<source>Start Time:</source>
<translation>Tiempo Inicio:</translation>
</message>
<message>
<source>Description:</source>
<translation>Descripción:</translation>
</message>
<message>
<source>Switch Matrix:</source>
<translation>Matriz de Suich.:</translation>
</message>
<message>
<source>Switch Input:</source>
<translation>Entrada de Suich.:</translation>
</message>
<message>
<source>Switch Output:</source>
<translation>Salida de Suich.:</translation>
</message>
<message>
<source>Active Days</source>
<translation>Días Activo</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>Sunday</source>
<translation>Domingo</translation>
</message>
<message>
<source>Make OneShot</source>
<translation>Una sola vez</translation>
</message>
<message>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>Duplicate Event</source>
<translation>Evento duplicado</translation>
</message>
<message>
<source>An event with these parameters already exists!</source>
<translation>¡Un evento con esos parámetros ya existe!</translation>
</message>
<message>
<source>&Save As
New</source>
<translation>&Guardar
como Nuevo</translation>
</message>
<message>
<source>--OFF--</source>
<translation>--APAGADO--</translation>
</message>
</context>
<context>
<name>EditUpload</name>
<message>
<source>Edit Upload</source>
<translation>Editar Subida</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento Activo</translation>
</message>
<message>
<source>Location:</source>
<translation>Ubicación:</translation>
</message>
<message>
<source>Start Time:</source>
<translation>Tiempo de Inicio:</translation>
</message>
<message>
<source>Source:</source>
<translation>Fuente:</translation>
</message>
<message>
<source>&Select</source>
<translation>&Seleccionar</translation>
</message>
<message>
<source>Description:</source>
<translation>Descripción:</translation>
</message>
<message>
<source>Url:</source>
<translation>Url:</translation>
</message>
<message>
<source>Username:</source>
<translation>Usuario:</translation>
</message>
<message>
<source>Password:</source>
<translation>Contraseña:</translation>
</message>
<message>
<source>S&et</source>
<translation>Po&ner</translation>
</message>
<message>
<source>Active Days</source>
<translation>Días activos</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>Sunday</source>
<translation></translation>
</message>
<message>
<source>Make OneShot</source>
<translation>Una sola vez</translation>
</message>
<message>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<source>Cut</source>
<translation>Audio</translation>
</message>
<message>
<source>Invalid URL</source>
<translation>URL inválido</translation>
</message>
<message>
<source>The URL is invalid!</source>
<translation>¡El URL es inválido!</translation>
</message>
<message>
<source>Unsupported URL protocol!</source>
<translation>¡Protocolo de URL no soportado!</translation>
</message>
<message>
<source>Export Format:</source>
<translation>Formato Exportac.:</translation>
</message>
<message>
<source>Unsupported Format</source>
<translation>Formato no soportado</translation>
</message>
<message>
<source>The currently selected export format is unsupported on this host!</source>
<translation>¡El formato seleccionado no está soportado por este equipo!</translation>
</message>
<message>
<source>The currently selected export format is unsupported on host </source>
<translation>El formato de exportación seleccionado no está soportado en el equipo </translation>
</message>
<message>
<source>Normalize</source>
<translation>Normalizar</translation>
</message>
<message>
<source>Level:</source>
<translation>Nivel:</translation>
</message>
<message>
<source>dBFS</source>
<translation>dBFS</translation>
</message>
<message>
<source>&Save As
New</source>
<translation>&Guardar
como Nuevo</translation>
</message>
<message>
<source>Duplicate Event</source>
<translation>Evento duplicado</translation>
</message>
<message>
<source>An event with these parameters already exists!</source>
<translation>¡Un evento con esos parámetros ya existe!</translation>
</message>
<message>
<source>RSS Feed:</source>
<translation>Flujo RSS:</translation>
</message>
<message>
<source>[none]</source>
<translation>[ninguno]</translation>
</message>
<message>
<source>Event Offset:</source>
<translation>Desplaz. Evento:</translation>
</message>
<message>
<source>days</source>
<translation>días</translation>
</message>
<message>
<source>Missing Username</source>
<translation>Falta el usuario</translation>
</message>
<message>
<source>You must specify a username!</source>
<translation>¡Debe especificar un nombre de usuario!</translation>
</message>
<message>
<source>Export Library Metadata</source>
<translation>Exportar Bibliot. Metadatos</translation>
</message>
</context>
<context>
<name>ListReports</name>
<message>
<source>RDLibrary Reports</source>
<translation>Reportes RDLibrary</translation>
</message>
<message>
<source>Type:</source>
<translation>Tipo:</translation>
</message>
<message>
<source>&Generate</source>
<translation>&Generar</translation>
</message>
<message>
<source>&Close</source>
<translation>&Cerrar</translation>
</message>
<message>
<source>Event Report</source>
<translation>Reporte de Evento</translation>
</message>
<message>
<source>Upload/Download Report</source>
<translation>Reporte Subidas/Descargas</translation>
</message>
</context>
<context>
<name>MainWidget</name>
<message>
<source>RDCatch - Host:</source>
<translation type="obsolete">RDCatch - Computador:</translation>
</message>
<message>
<source>Can't Connect</source>
<translation>No puedo conectarme</translation>
</message>
<message>
<source>Show Only Active Events</source>
<translation>Ver sólo eventos activos</translation>
</message>
<message>
<source>Show Only Today's Events</source>
<translation>Ver sólo eventos de hoy</translation>
</message>
<message>
<source>Show DayOfWeek:</source>
<translation>Mostrar Día de Semana:</translation>
</message>
<message>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<source>Weekdays</source>
<translation>Días de semana</translation>
</message>
<message>
<source>Sunday</source>
<translation>Domingo</translation>
</message>
<message>
<source>Monday</source>
<translation>Lunes</translation>
</message>
<message>
<source>Tuesday</source>
<translation>Martes</translation>
</message>
<message>
<source>Wednesday</source>
<translation>Miércoles</translation>
</message>
<message>
<source>Thursday</source>
<translation>Jueves</translation>
</message>
<message>
<source>Friday</source>
<translation>Viernes</translation>
</message>
<message>
<source>Saturday</source>
<translation>Sábado</translation>
</message>
<message>
<source>DESCRIPTION</source>
<translation>DESCRIPCIÓN</translation>
</message>
<message>
<source>LOCATION</source>
<translation>UBICACIÓN</translation>
</message>
<message>
<source>START</source>
<translation>INICIO</translation>
</message>
<message>
<source>END</source>
<translation>FIN</translation>
</message>
<message>
<source>SOURCE</source>
<translation>FUENTE</translation>
</message>
<message>
<source>DESTINATION</source>
<translation>DESTINO</translation>
</message>
<message>
<source>ONE SHOT</source>
<translation>UNA VEZ</translation>
</message>
<message>
<source>TRIM THRESHOLD</source>
<translation>RECORTAR NIVEL</translation>
</message>
<message>
<source>STARTDATE OFFSET</source>
<translation>DESPLAZ. FECHA INICIO</translation>
</message>
<message>
<source>ENDDATE OFFSET</source>
<translation>DESPLAZ. FECHA FIN</translation>
</message>
<message>
<source>FORMAT</source>
<translation>FORMATO</translation>
</message>
<message>
<source>CHANNELS</source>
<translation>CANALES</translation>
</message>
<message>
<source>SAMPLE RATE</source>
<translation>TASA DE SAMPLEO</translation>
</message>
<message>
<source>BIT RATE</source>
<translation>TASA DE BITS</translation>
</message>
<message>
<source>STATION</source>
<translation>ESTACIÓN</translation>
</message>
<message>
<source>DECK</source>
<translation>DECK</translation>
</message>
<message>
<source>CUT</source>
<translation>AUDIO</translation>
</message>
<message>
<source>CART</source>
<translation>CARTUCHO</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>TYPE</source>
<translation>TIPO</translation>
</message>
<message>
<source>&Add</source>
<translation>&Añadir</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Borrar</translation>
</message>
<message>
<source>Scroll</source>
<translation>Deslizar</translation>
</message>
<message>
<source>&Close</source>
<translation>&Cerrar</translation>
</message>
<message>
<source>Are you sure you want to delete event</source>
<translation>Desea borrar el evento</translation>
</message>
<message>
<source>Delete Event</source>
<translation>Borrar evento</translation>
</message>
<message>
<source>Control connection timed out to host</source>
<translation>La conexión de control no pudo realizarse</translation>
</message>
<message>
<source>Su</source>
<translation>Do</translation>
</message>
<message>
<source>Mo</source>
<translation>Lu</translation>
</message>
<message>
<source>Tu</source>
<translation>Ma</translation>
</message>
<message>
<source>We</source>
<translation>Mi</translation>
</message>
<message>
<source>Th</source>
<translation>Ju</translation>
</message>
<message>
<source>Fr</source>
<translation>Vi</translation>
</message>
<message>
<source>Sa</source>
<translation>Sa</translation>
</message>
<message>
<source>dB</source>
<translation>dB</translation>
</message>
<message>
<source>Hard</source>
<translation>Estricto</translation>
</message>
<message>
<source>Gpi</source>
<translation>Gpi</translation>
</message>
<message>
<source>Len</source>
<translation>Lon</translation>
</message>
<message>
<source>Cut</source>
<translation>Audio</translation>
</message>
<message>
<source>Cart</source>
<translation>Cartucho</translation>
</message>
<message>
<source>ORIGIN</source>
<translation>ORIGEN</translation>
</message>
<message>
<source>STATUS</source>
<translation>ESTADO</translation>
</message>
<message>
<source>PCM16</source>
<translation></translation>
</message>
<message>
<source>MPEG Layer 1</source>
<translation></translation>
</message>
<message>
<source>MPEG Layer 2</source>
<translation></translation>
</message>
<message>
<source>MPEG Layer 3</source>
<translation></translation>
</message>
<message>
<source>FLAC</source>
<translation></translation>
</message>
<message>
<source>OggVorbis</source>
<translation></translation>
</message>
<message>
<source>STATE</source>
<translation>ESTADO</translation>
</message>
<message>
<source>Event Active</source>
<translation>Evento activo</translation>
</message>
<message>
<source>You cannot edit an active event!</source>
<translation>¡No puede editar un evento activo!</translation>
</message>
<message>
<source>EXIT CODE</source>
<translation>COD DE SALIDA</translation>
</message>
<message>
<source>Unable to connect to Core AudioEngine</source>
<translation>No pude conectar al Core AudioEngine</translation>
</message>
<message>
<source>Reports</source>
<translation>Reportes</translation>
</message>
<message>
<source>[none]</source>
<translation>[ninguno]</translation>
</message>
<message>
<source>rdcatch : </source>
<translation>rdcatch : </translation>
</message>
<message>
<source>Unknown</source>
<translation>Desconocido</translation>
</message>
<message>
<source>Host</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>User</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>PCM24</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| gpl-2.0 |
tyll/bodhi | bodhi/server/push.py | 7244 | # -*- coding: utf-8 -*-
# Copyright © 2007-2017 Red Hat, Inc.
#
# This file is part of Bodhi.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""The CLI tool for triggering update pushes."""
from collections import defaultdict
from datetime import datetime
import glob
import json
from sqlalchemy.sql import or_
import click
from bodhi.server import initialize_db
from bodhi.server.config import config
from bodhi.server.models import Release, ReleaseState, Build, Update, UpdateRequest
from bodhi.server.util import transactional_session_maker
import bodhi.server.notifications
@click.command()
@click.option('--builds', help='Push updates for a comma-separated list of builds')
@click.option('--cert-prefix', default="shell",
help="The prefix of a fedmsg cert used to sign the message")
@click.option('--releases', help=('Push updates for a comma-separated list of releases (default: '
'current and pending releases)'))
@click.option('--request', default='testing,stable',
help='Push updates with a specific request (default: testing,stable)')
@click.option('--resume', help='Resume one or more previously failed pushes',
is_flag=True, default=False)
@click.option('--staging', help='Use the staging bodhi instance',
is_flag=True, default=False)
@click.option('--username', envvar='USERNAME', prompt=True)
@click.version_option(message='%(version)s')
def push(username, cert_prefix, **kwargs):
"""Push builds out to the repositories."""
staging = kwargs.pop('staging')
resume = kwargs.pop('resume')
lockfiles = defaultdict(list)
locked_updates = []
if staging:
locks = '/var/cache/bodhi/mashing/MASHING-*'
else:
locks = '/mnt/koji/mash/updates/MASHING-*'
for lockfile in glob.glob(locks):
with file(lockfile) as lock:
state = json.load(lock)
for update in state['updates']:
lockfiles[lockfile].append(update)
locked_updates.append(update)
update_titles = None
initialize_db(config)
db_factory = transactional_session_maker()
with db_factory() as session:
updates = []
# If we're resuming a push
if resume:
for lockfile in lockfiles:
if not click.confirm('Resume {}?'.format(lockfile)):
continue
for update in lockfiles[lockfile]:
update = session.query(Update).filter(Update.title == update).first()
updates.append(update)
else:
# Accept both comma and space separated request list
requests = kwargs['request'].replace(',', ' ').split(' ')
requests = [UpdateRequest.from_string(val) for val in requests]
query = session.query(Update).filter(Update.request.in_(requests))
if kwargs.get('builds'):
query = query.join(Update.builds)
query = query.filter(
or_(*[Build.nvr == build for build in kwargs['builds'].split(',')]))
query = _filter_releases(session, query, kwargs.get('releases'))
for update in query.all():
# Skip locked updates that are in a current push
if update.locked:
if update.title in locked_updates:
continue
# Warn about locked updates that aren't a part of a push and
# push them again.
else:
click.echo('Warning: %s is locked but not in a push' %
update.title)
# Skip unsigned updates (this checks that all builds in the update are signed)
if not update.signed:
click.echo('Warning: %s has unsigned builds and has been skipped' %
update.title)
continue
updates.append(update)
for update in updates:
click.echo(update.title)
if updates:
click.confirm('Push these {:d} updates?'.format(len(updates)), abort=True)
click.echo('\nLocking updates...')
for update in updates:
update.locked = True
update.date_locked = datetime.utcnow()
else:
click.echo('\nThere are no updates to push.')
update_titles = list([update.title for update in updates])
if update_titles:
click.echo('\nSending masher.start fedmsg')
# Because we're a script, we want to send to the fedmsg-relay,
# that's why we say active=True
bodhi.server.notifications.init(active=True, cert_prefix=cert_prefix)
bodhi.server.notifications.publish(
topic='masher.start',
msg=dict(
updates=update_titles,
resume=resume,
agent=username,
),
force=True,
)
def _filter_releases(session, query, releases=None):
"""
Filter the given query by releases.
Apply a filter() transformation to the given query on Updates to filter updates that match the
given releases argument. If releases evaluates "Falsey", this function will filter for Updates
that are part of a current Release.
:param session: The database session
:param query: An Update query that we want to modify by filtering based on Releases
:param releases: A comma-separated string of release names
:returns: A filtered version of query with an additional filter based on releases.
"""
# We will store models.Release object here that we want to filter by
_releases = []
if releases:
for r in releases.split(','):
release = session.query(Release).filter(
or_(Release.name == r,
Release.name == r.upper(),
Release.version == r)).first()
if not release:
raise click.BadParameter('Unknown release: %s' % r)
else:
_releases.append(release)
else:
# Since the user didn't ask for specific Releases, let's just filter for releases that are
# current or pending.
_releases = session.query(Release).filter(or_(Release.state == ReleaseState.current,
Release.state == ReleaseState.pending))
return query.filter(or_(*[Update.release == r for r in _releases]))
if __name__ == '__main__':
push()
| gpl-2.0 |
lestcape/Global-AppMenu | globalAppMenu@lestcape/applet.js | 26839 | // Copyright (C) 2014-2015 Lester Carballo Pérez <lestcape@gmail.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 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
const Clutter = imports.gi.Clutter;
const St = imports.gi.St;
const Gio = imports.gi.Gio;
const GLib = imports.gi.GLib;
const Lang = imports.lang;
const Gettext = imports.gettext;
const Applet = imports.ui.applet;
const Main = imports.ui.main;
const Settings = imports.ui.settings;
const AppletManager = imports.ui.appletManager;
const Util = imports.misc.util;
const AppletPath = AppletManager.applets["globalAppMenu@lestcape"];
const IndicatorAppMenuWatcher = AppletPath.indicatorAppMenuWatcher;
const ConfigurableMenus = AppletPath.configurableMenus;
function _(str) {
let resultConf = Gettext.dgettext("globalAppMenu@lestcape", str);
if(resultConf != str) {
return resultConf;
}
return Gettext.gettext(str);
};
function MyMenuFactory() {
this._init.apply(this, arguments);
}
MyMenuFactory.prototype = {
__proto__: ConfigurableMenus.MenuFactory.prototype,
_init: function() {
ConfigurableMenus.MenuFactory.prototype._init.call(this);
this._showBoxPointer = true;
this._openSubMenu = false;
this._closeSubMenu = false;
this._floatingMenu = false;
this._floatingSubMenu = true;
this._alignSubMenu = false;
this._showItemIcon = true;
this._desaturateItemIcon = false;
this._openOnHover = false;
this._arrowSide = St.Side.BOTTOM;
this._effectType = "none";
this._effectTime = 0.4;
},
setMainMenuArrowSide: function(arrowSide) {
if(this._arrowSide != arrowSide) {
this._arrowSide = arrowSide;
for(let pos in this._menuLikend) {
let shellMenu = this._menuLikend[pos].getShellItem();
if(shellMenu)
shellMenu.setArrowSide(this._arrowSide);
}
}
},
setOpenOnHover: function(openOnHover) {
if(this._openOnHover != openOnHover) {
this._openOnHover = openOnHover;
for(let pos in this._menuLikend) {
let shellMenu = this._menuLikend[pos].getShellItem();
if(shellMenu)
shellMenu.setOpenOnHover(this._openOnHover);
}
}
},
setEffect: function(effect) {
if(this._effectType != effect) {
this._effectType = effect;
for(let pos in this._menuManager) {
this._menuManager[pos].setEffect(this._effectType);
}
}
},
setEffectTime: function(effectTime) {
if(this._effectTime != effectTime) {
this._effectTime = effectTime;
for(let pos in this._menuManager) {
this._menuManager[pos].setEffectTime(this._effectTime);
}
}
},
setFloatingState: function(floating) {
if(this._floatingMenu != floating) {
this._floatingMenu = floating;
for(let pos in this._menuLikend) {
let shellMenu = this._menuLikend[pos].getShellItem();
if(shellMenu) {
shellMenu.setFloatingState(this._floatingMenu);
}
}
}
},
showBoxPointer: function(show) {
if(this._showBoxPointer != show) {
this._showBoxPointer = show;
for(let pos in this._menuManager) {
this._menuManager[pos].showBoxPointer(this._showBoxPointer);
}
}
},
setAlignSubMenu: function(align) {
if(this._alignSubMenu != align) {
this._alignSubMenu= align;
for(let pos in this._menuManager) {
this._menuManager[pos].setAlignSubMenu(this._alignSubMenu);
}
}
},
setOpenSubMenu: function(openSubMenu) {
if(this._openSubMenu != openSubMenu) {
this._openSubMenu = openSubMenu;
for(let pos in this._menuManager) {
this._menuManager[pos].setOpenSubMenu(this._openSubMenu);
}
}
},
setCloseSubMenu: function(closeSubMenu) {
if(this._closeSubMenu != closeSubMenu) {
this._closeSubMenu = closeSubMenu;
for(let pos in this._menuManager) {
this._menuManager[pos].setCloseSubMenu(this._closeSubMenu);
}
}
},
setFloatingSubMenu: function(floating) {
if(this._floatingSubMenu != floating) {
this._floatingSubMenu = floating;
for(let pos in this._menuManager) {
this._menuManager[pos].setFloatingSubMenu(this._floatingSubMenu);
}
}
},
setShowItemIcon: function(show) {
if(this._showItemIcon != show) {
this._showItemIcon = show;
for(let pos in this._menuManager) {
this._menuManager[pos].setShowItemIcon(this._showItemIcon);
}
}
},
desaturateItemIcon: function(desaturate) {
if(this._desaturateItemIcon != desaturate) {
this._desaturateItemIcon = desaturate;
for(let pos in this._menuManager) {
this._menuManager[pos].desaturateItemIcon(this._desaturateItemIcon);
}
}
},
_createShellItem: function(factoryItem, launcher, orientation, menuManager) {
// Decide whether it's a submenu or not
this._arrowSide = orientation;
if(menuManager) {
menuManager.showBoxPointer(this._showBoxPointer);
menuManager.setOpenSubMenu(this._openSubMenu);
menuManager.setCloseSubMenu(this._closeSubMenu);
menuManager.setAlignSubMenu(this._alignSubMenu);
menuManager.setShowItemIcon(this._showItemIcon);
menuManager.desaturateItemIcon(this._desaturateItemIcon);
menuManager.setEffect(this._effectType);
menuManager.setEffectTime(this._effectTime);
}
let shellItem = null;
let itemType = factoryItem.getFactoryType();
if(itemType == ConfigurableMenus.FactoryClassTypes.RootMenuClass)
shellItem = new ConfigurableMenus.ConfigurableMenuApplet(launcher, orientation, menuManager);
if(itemType == ConfigurableMenus.FactoryClassTypes.SubMenuMenuItemClass)
shellItem = new ConfigurableMenus.ConfigurablePopupSubMenuMenuItem("FIXME");
else if(itemType == ConfigurableMenus.FactoryClassTypes.MenuSectionMenuItemClass)
shellItem = new ConfigurableMenus.ConfigurablePopupMenuSection();
else if(itemType == ConfigurableMenus.FactoryClassTypes.SeparatorMenuItemClass)
shellItem = new ConfigurableMenus.ConfigurableSeparatorMenuItem();
else if(itemType == ConfigurableMenus.FactoryClassTypes.MenuItemClass)
shellItem = new ConfigurableMenus.ConfigurableApplicationMenuItem("FIXME");
//else
// throw new TypeError('Trying to instantiate a shell item with an invalid factory type');
if(itemType == ConfigurableMenus.FactoryClassTypes.RootMenuClass) {
shellItem.setFloatingState(this._floatingMenu);
shellItem.setOpenOnHover(this._openOnHover);
} else if(itemType == ConfigurableMenus.FactoryClassTypes.SubMenuMenuItemClass) {
shellItem.menu.setFloatingState(this._floatingSubMenu);
}
return shellItem;
},
};
function MyApplet() {
this._init.apply(this, arguments);
}
MyApplet.prototype = {
__proto__: Applet.Applet.prototype,
_init: function(metadata, orientation, panelHeight, instanceId) {
Applet.Applet.prototype._init.call(this, orientation, panelHeight, instanceId);
try {
this.uuid = metadata["uuid"];
this.orientation = orientation;
this.execInstallLanguage();
this.set_applet_tooltip(_("Global Application Menu"));
this.currentWindow = null;
this.sendWindow = null;
this.showAppIcon = true;
this.showAppName = true;
this.desaturateAppIcon = false;
this.maxAppNameSize = 10;
this.automaticActiveMainMenu = true;
this.openActiveSubmenu = false;
this.closeActiveSubmenu = false;
this.showBoxPointer = true;
this.alignMenuLauncher = false;
this.showItemIcon = true;
this.desaturateItemIcon = false;
this.openOnHover = false;
this._keybindingTimeOut = 0;
this.effectType = "none";
this.effectTime = 0.4;
this.actorIcon = new St.Bin();
this.gradient = new ConfigurableMenus.GradientLabelMenuItem("", 10);
this.actor.add(this.actorIcon, { y_align: St.Align.MIDDLE, y_fill: false });
this.actor.add(this.gradient.actor, { y_align: St.Align.MIDDLE, y_fill: false });
this.actor.connect("enter-event", Lang.bind(this, this._onAppletEnterEvent));
this.menuFactory = new MyMenuFactory();
this._system = new IndicatorAppMenuWatcher.SystemProperties();
// Swap applet_context_menu to Configurable Menu Api.
this._menuManager.removeMenu(this._applet_context_menu);
this._applet_context_menu.destroy();
this._applet_context_menu = new ConfigurableMenus.ConfigurableMenu(this, 0.0, orientation, true);
this._menuManager = new ConfigurableMenus.ConfigurableMenuManager(this);
this._menuManager.addMenu(this._applet_context_menu);
this._createSettings();
this.indicatorDbus = new IndicatorAppMenuWatcher.IndicatorAppMenuWatcher(
IndicatorAppMenuWatcher.AppmenuMode.MODE_STANDARD, this._getIconSize());
this._isReady = this._initEnvironment();
if(this._isReady) {
this.indicatorDbus.watch();
this.indicatorDbus.connect('appmenu-changed', Lang.bind(this, this._onAppmenuChanged));
} else {
Main.notify(_("You need restart your computer, to active the unity-gtk-module"));
}
}
catch(e) {
Main.notify("Init error %s".format(e.message));
global.logError("Init error %s".format(e.message));
}
},
_createSettings: function() {
this.settings = new Settings.AppletSettings(this, this.uuid, this.instance_id);
this.settings.bindProperty(Settings.BindingDirection.IN, "enable-environment", "enableEnvironment", this._onEnableEnvironmentChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "enable-jayantana", "enableJayantana", this._onEnableJayantanaChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "show-app-icon", "showAppIcon", this._onShowAppIconChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "desaturate-app-icon", "desaturateAppIcon", this._onDesaturateAppIconChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "show-app-name", "showAppName", this._onShowAppNameChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "text-gradient", "textGradient", this._onTextGradientChange, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "max-app-name-size", "maxAppNameSize", this._onMaxAppNameSizeChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "automatic-active-mainmenu", "automaticActiveMainMenu", this._automaticActiveMainMenuChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "open-active-submenu", "openActiveSubmenu", this._onOpenActiveSubmenuChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "close-active-submenu", "closeActiveSubmenu", this._onCloseActiveSubmenuChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "show-boxpointer", "showBoxPointer", this._onShowBoxPointerChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "align-menu-launcher", "alignMenuLauncher", this._onAlignMenuLauncherChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "global-overlay-key", "overlayKey", this._updateKeybinding, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "display-in-panel", "displayInPanel", this._onDisplayInPanelChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "show-item-icon", "showItemIcon", this._onShowItemIconChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "desaturate-item-icon", "desaturateItemIcon", this._onDesaturateItemIconChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "activate-on-hover", "openOnHover", this._onOpenOnHoverChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "effect", "effectType", this._onEffectTypeChanged, null);
this.settings.bindProperty(Settings.BindingDirection.IN, "effect-time", "effectTime", this._onEffectTimeChanged, null);
this._onEnableEnvironmentChanged();
this._onEnableJayantanaChanged();
this._onDisplayInPanelChanged();
this._onShowAppIconChanged();
this._onDesaturateAppIconChanged();
this._onShowAppNameChanged();
this._onTextGradientChange();
this._onMaxAppNameSizeChanged();
this._updateKeybinding();
this._onOpenActiveSubmenuChanged();
this._onCloseActiveSubmenuChanged();
this._onShowBoxPointerChanged();
this._onAlignMenuLauncherChanged();
this._onShowItemIconChanged();
this._onDesaturateItemIconChanged();
this._onOpenOnHoverChanged();
this._onEffectTypeChanged();
this._onEffectTimeChanged();
},
_initEnvironment: function() {
let isReady = this._system.activeUnityGtkModule(true);
if(isReady) {
this._system.activeJAyantanaModule(this.enableJayantana);
this._system.shellShowAppmenu(true);
this._system.shellShowMenubar(true);
this._system.activeUnityMenuProxy(true);
return true;
}
return false;
},
openAbout: function() {
if(Applet.Applet.prototype.openAbout)
Applet.Applet.prototype.openAbout.call(this);
else
Main.notify("Missing reference to the About Dialog");
},
configureApplet: function() {
if(Applet.Applet.prototype.configureApplet)
Applet.Applet.prototype.configureApplet.call(this);
else
Util.spawnCommandLine("xlet-settings applet " + this._uuid + " " + this.instance_id);
},
finalizeContextMenu: function () {
// Add default context menus if we're in panel edit mode, ensure their removal if we're not
let items = this._applet_context_menu._getMenuItems();
if (this.context_menu_item_remove == null) {
this.context_menu_item_remove = new ConfigurableMenus.ConfigurableBasicPopupMenuItem(_("Remove '%s'").format(_(this._meta.name)));
this.context_menu_item_remove.setIconName("edit-delete");
this.context_menu_item_remove.setShowItemIcon(true);
this.context_menu_item_remove.setIconType(St.IconType.SYMBOLIC);
this.context_menu_item_remove.connect('activate', Lang.bind(this, function() {
AppletManager._removeAppletFromPanel(this._uuid, this.instance_id);
}));
}
if (this.context_menu_item_about == null) {
this.context_menu_item_about = new ConfigurableMenus.ConfigurableBasicPopupMenuItem(_("About..."));
this.context_menu_item_about.setIconName("dialog-question");
this.context_menu_item_about.setShowItemIcon(true);
this.context_menu_item_about.setIconType(St.IconType.SYMBOLIC);
this.context_menu_item_about.connect('activate', Lang.bind(this, this.openAbout));
}
if (this.context_menu_separator == null) {
this.context_menu_separator = new ConfigurableMenus.ConfigurableSeparatorMenuItem();
}
if (items.indexOf(this.context_menu_item_about) == -1) {
this._applet_context_menu.addMenuItem(this.context_menu_item_about);
}
if (!this._meta["hide-configuration"] && GLib.file_test(this._meta["path"] + "/settings-schema.json", GLib.FileTest.EXISTS)) {
if (this.context_menu_item_configure == null) {
this.context_menu_item_configure = new ConfigurableMenus.ConfigurableBasicPopupMenuItem(_("Configure..."));
this.context_menu_item_configure.setIconName("system-run");
this.context_menu_item_configure.setShowItemIcon(true);
this.context_menu_item_configure.setIconType(St.IconType.SYMBOLIC);
this.context_menu_item_configure.connect('activate', Lang.bind(this, this.configureApplet));
}
if (items.indexOf(this.context_menu_item_configure) == -1) {
this._applet_context_menu.addMenuItem(this.context_menu_item_configure);
}
}
if (items.indexOf(this.context_menu_item_remove) == -1) {
this._applet_context_menu.addMenuItem(this.context_menu_item_remove);
}
},
_finalizeEnvironment: function() {
this._system.shellShowAppmenu(false);
this._system.shellShowMenubar(false);
this._system.activeUnityMenuProxy(false);
this._system.activeJAyantanaModule(false);
// FIXME When we can call system.activeUnityGtkModule(false)?
// Is possible that we need to add an option to the settings
// to be more easy to the user uninstall the applet in a
// propertly way.
},
_onEnableEnvironmentChanged: function() {
if(this.enableEnvironment != this._system.isEnvironmentSet()) {
this._system.setEnvironmentVar(this.enableEnvironment, Lang.bind(this, this._envVarChanged));
}
},
_envVarChanged: function(result, error) {
this.enableEnvironment = result;
if(error)
Main.notify(_("The environment variable cannot be changed"));
else
Main.notify(_("The environment variable was set, a logout will be required to apply the changes"));
},
_onEnableJayantanaChanged: function() {
this._system.activeJAyantanaModule(this.enableJayantana);
},
_updateKeybinding: function() {
Main.keybindingManager.addHotKey("global-overlay-key", this.overlayKey, Lang.bind(this, function() {
if(this.menu && !Main.overview.visible && !Main.expo.visible) {
this.menu.toogleSubmenu(true);
}
}));
},
_onEffectTypeChanged: function() {
this.menuFactory.setEffect(this.effectType);
},
_onEffectTimeChanged: function() {
this.menuFactory.setEffectTime(this.effectTime);
},
_onOpenOnHoverChanged: function() {
this.menuFactory.setOpenOnHover(this.openOnHover);
},
_onDisplayInPanelChanged: function() {
this.menuFactory.setFloatingState(!this.displayInPanel);
},
_onShowAppIconChanged: function() {
this.actorIcon.visible = this.showAppIcon;
},
_onDesaturateAppIconChanged: function() {
if(this.desaturateAppIcon)
this.actorIcon.add_effect_with_name("desaturate", new Clutter.DesaturateEffect());
else
this.actorIcon.remove_effect_by_name("desaturate");
},
_onShowAppNameChanged: function() {
this.gradient.actor.visible = this.showAppName;
},
_onTextGradientChange: function() {
this.gradient.setTextDegradation(this.textGradient);
},
_onMaxAppNameSizeChanged: function() {
this.gradient.setSize(this.maxAppNameSize);
},
_automaticActiveMainMenuChanged: function() {
if(this.automaticActiveMainMenu)
this._closeMenu();
},
_onOpenActiveSubmenuChanged: function() {
this.menuFactory.setOpenSubMenu(this.openActiveSubmenu);
},
_onCloseActiveSubmenuChanged: function() {
this.menuFactory.setCloseSubMenu(this.closeActiveSubmenu);
},
_onShowBoxPointerChanged: function() {
this.menuFactory.showBoxPointer(this.showBoxPointer);
if(this._applet_context_menu.showBoxPointer)
this._applet_context_menu.showBoxPointer(this.showBoxPointer);
},
_onAlignMenuLauncherChanged: function() {
this.menuFactory.setAlignSubMenu(this.alignMenuLauncher);
},
_onShowItemIconChanged: function() {
this.menuFactory.setShowItemIcon(this.showItemIcon);
},
_onDesaturateItemIconChanged: function() {
this.menuFactory.desaturateItemIcon(this.desaturateItemIcon);
},
_onAppmenuChanged: function(indicator, window) {
let newLabel = null;
let newIcon = null;
let newMenu = null;
this.currentWindow = window;
if(window) {
let app = this.indicatorDbus.getAppForWindow(window);
if(app) {
newIcon = this.indicatorDbus.getIconForWindow(window);
newLabel = app.get_name();
let dbusMenu = this.indicatorDbus.getMenuForWindow(window);
if(dbusMenu) {
newMenu = this.menuFactory.getShellMenu(dbusMenu);
if(!newMenu) {
let menuManager = new ConfigurableMenus.ConfigurableMenuManager(this);
newMenu = this.menuFactory.buildShellMenu(dbusMenu, this, this.orientation, menuManager);
}
}
}
}
this._tryToShow(newLabel, newIcon, newMenu);
},
_tryToShow: function(newLabel, newIcon, newMenu) {
if((newLabel != null)&&(newIcon != null)) {
this._changeAppmenu(newLabel, newIcon, newMenu);
} else {
this._cleanAppmenu();
}
},
_changeAppmenu: function(newLabel, newIcon, newMenu) {
if(this._isNewMenu(newMenu)) {
this._closeMenu();
this.menu = newMenu;
if(this.menu && this.automaticActiveMainMenu && !this.menu.isInFloatingState())
this.menu.open();
}
if(this._isNewApp(newLabel, newIcon)) {
this.gradient.setText(newLabel);
this.actorIcon.set_child(newIcon);
}
},
_closeMenu: function() {
if((this.menu)&&(this.menu.isOpen)) {
this.menu.close(false, true);
this.sendWindow = null;
}
},
_cleanAppmenu: function() {
this._closeMenu();
this.menu = null;
this.actorIcon.set_child(null);
this.gradient.setText("");
},
_isNewApp: function(newLabel, newIcon) {
return ((newIcon != this.actorIcon.get_child())||
(newLabel != this.gradient.text));
},
_isNewMenu: function(newMenu) {
return (newMenu != this.menu);
},
_getIconSize: function() {
let iconSize;
let ui_scale = global.ui_scale;
if(!ui_scale) ui_scale = 1;
if(this._scaleMode)
iconSize = this._panelHeight * Applet.COLOR_ICON_HEIGHT_FACTOR / ui_scale;
else
iconSize = Applet.FALLBACK_ICON_HEIGHT;
return iconSize;
},
_onAppletEnterEvent: function() {
if(this.currentWindow) {
if(this.currentWindow != this.sendWindow) {
this.indicatorDbus.updateMenuForWindow(this.currentWindow);
this.sendWindow = this.currentWindow;
}
}
if((this.menu)&&(this.openOnHover))
this.menu.open(true);
},
on_orientation_changed: function(orientation) {
this.orientation = orientation;
this.menuFactory.setMainMenuArrowSide(orientation);
this._applet_context_menu.setArrowSide(orientation);
},
on_panel_height_changed: function() {
let iconSize = this._getIconSize();
this.indicatorDbus.setIconSize(iconSize);
},
on_applet_removed_from_panel: function() {
this.indicatorDbus.destroy();
this._finalizeEnvironment();
},
on_applet_clicked: function(event) {
if((this.menu) && (event.get_button() == 1)) {
this.menu.forcedToggle();
return true;
}
return false;
},
execInstallLanguage: function() {
let localeFolder = Gio.file_new_for_path(GLib.get_home_dir() + "/.local/share/locale");
Gettext.bindtextdomain(this.uuid, localeFolder.get_path());
try {
let moFolder = Gio.file_new_for_path(localeFolder.get_parent().get_path() + "/cinnamon/applets/" + this.uuid + "/po/mo/");
let children = moFolder.enumerate_children('standard::name,standard::type,time::modified',
Gio.FileQueryInfoFlags.NONE, null);
let info, child, moFile, moLocale, moPath, src, dest, modified, destModified;
while((info = children.next_file(null)) != null) {
modified = info.get_modification_time().tv_sec;
if(info.get_file_type() == Gio.FileType.REGULAR) {
moFile = info.get_name();
if(moFile.substring(moFile.lastIndexOf(".")) == ".mo") {
moLocale = moFile.substring(0, moFile.lastIndexOf("."));
moPath = localeFolder.get_path() + "/" + moLocale + "/LC_MESSAGES/";
src = Gio.file_new_for_path(String(moFolder.get_path() + "/" + moFile));
dest = Gio.file_new_for_path(String(moPath + this.uuid + ".mo"));
try {
if(dest.query_exists(null)) {
destModified = dest.query_info('time::modified', Gio.FileQueryInfoFlags.NONE, null).get_modification_time().tv_sec;
if((modified > destModified)) {
src.copy(dest, Gio.FileCopyFlags.OVERWRITE, null, null);
}
} else {
this._makeDirectoy(dest.get_parent());
src.copy(dest, Gio.FileCopyFlags.OVERWRITE, null, null);
}
} catch(e) {
global.logWarning("Error %s".format(e.message));
}
}
}
}
} catch(e) {
global.logWarning("Error %s".format(e.message));
}
},
_isDirectory: function(fDir) {
try {
let info = fDir.query_filesystem_info("standard::type", null);
if((info)&&(info.get_file_type() != Gio.FileType.DIRECTORY))
return true;
} catch(e) {
}
return false;
},
_makeDirectoy: function(fDir) {
if(!this._isDirectory(fDir))
this._makeDirectoy(fDir.get_parent());
if(!this._isDirectory(fDir))
fDir.make_directory(null);
},
};
function main(metadata, orientation, panel_height, instance_id) {
let myApplet = new MyApplet(metadata, orientation, panel_height, instance_id);
return myApplet;
}
| gpl-2.0 |
angelonuffer/blobby-volley-2 | src/ScriptedInputSource.cpp | 16829 | /*=============================================================================
Blobby Volley 2
Copyright (C) 2006 Jonathan Sieber (jonathan_sieber@yahoo.de)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
=============================================================================*/
#include "ScriptedInputSource.h"
#include "DuelMatch.h"
#include "GameConstants.h"
#include "BotAPICalculations.h"
extern "C"
{
#include "lua/lua.h"
#include "lua/lauxlib.h"
#include "lua/lualib.h"
}
#include <iostream>
#include <SDL/SDL.h>
#include <physfs.h>
#include <cmath>
#include <algorithm>
DuelMatch* ScriptedInputSource::mMatch = 0;
ScriptedInputSource* ScriptedInputSource::mCurrentSource = 0;
struct pos_x;
struct pos_y;
struct vel_x;
struct vel_y;
template<class T>
float convert(float f);
template<class T>
struct ScriptedInputSource::coordinate {
coordinate(float f) : value(convert(f)) {
}
coordinate(double f) : value(convert(f)) {
}
operator float() const {
return value;
}
float value;
private:
// other constructors ar prohibited !
template<class U>
coordinate(U u);
static float convert(float f);
};
// functions for coodinate transformation
template<>
float ScriptedInputSource::coordinate<pos_x>::convert (float val) {
return mCurrentSource->mSide == LEFT_PLAYER ? val : RIGHT_PLANE - val;
}
template<>
float ScriptedInputSource::coordinate<pos_y>::convert (float val) {
return 600.f - val;
}
template<>
float ScriptedInputSource::coordinate<vel_x>::convert (float val) {
return mCurrentSource->mSide == LEFT_PLAYER ? val : -val;
}
template<>
float ScriptedInputSource::coordinate<vel_y>::convert (float val) {
return -val;
}
struct ReaderInfo
{
PHYSFS_file* handle;
char readBuffer[2048];
};
static const char* chunkReader(lua_State* state, void* data, size_t *size)
{
ReaderInfo* info = (ReaderInfo*) data;
int bytesRead = PHYSFS_read(info->handle, info->readBuffer, 1, 2048);
*size = bytesRead;
if (bytesRead == 0)
{
return 0;
}
else
{
return info->readBuffer;
}
}
ScriptedInputSource::ScriptedInputSource(const std::string& filename,
PlayerSide playerside, unsigned int difficulty): mLastBallSpeed(0),
mMaxDelay(difficulty), mCurDelay(difficulty), mSide(playerside)
{
mStartTime = SDL_GetTicks();
mState = lua_open();
// set game constants
lua_pushnumber(mState, RIGHT_PLANE);
lua_setglobal(mState, "CONST_FIELD_WIDTH");
lua_pushnumber(mState, 600 - GROUND_PLANE_HEIGHT_MAX);
lua_setglobal(mState, "CONST_GROUND_HEIGHT");
lua_pushnumber(mState, -BALL_GRAVITATION);
lua_setglobal(mState, "CONST_BALL_GRAVITY");
lua_pushnumber(mState, BALL_RADIUS);
lua_setglobal(mState, "CONST_BALL_RADIUS");
lua_pushnumber(mState, BLOBBY_JUMP_ACCELERATION);
lua_setglobal(mState, "CONST_BLOBBY_JUMP");
lua_pushnumber(mState, BLOBBY_LOWER_RADIUS);
lua_setglobal(mState, "CONST_BLOBBY_BODY_RADIUS");
lua_pushnumber(mState, BLOBBY_UPPER_RADIUS);
lua_setglobal(mState, "CONST_BLOBBY_HEAD_RADIUS");
lua_pushnumber(mState, BLOBBY_HEIGHT);
lua_setglobal(mState, "CONST_BLOBBY_HEIGHT");
lua_pushnumber(mState, -GRAVITATION);
lua_setglobal(mState, "CONST_BLOBBY_GRAVITY");
lua_pushnumber(mState, 600 - NET_SPHERE_POSITION);
lua_setglobal(mState, "CONST_NET_HEIGHT");
lua_pushnumber(mState, NET_RADIUS);
lua_setglobal(mState, "CONST_NET_RADIUS");
luaopen_math(mState);
lua_register(mState, "touches", touches);
lua_register(mState, "launched", launched);
lua_register(mState, "debug", debug);
lua_register(mState, "jump", jump);
lua_register(mState, "moveto", moveto);
lua_register(mState, "left", left);
lua_register(mState, "right", right);
lua_register(mState, "ballx", ballx);
lua_register(mState, "bally", bally);
lua_register(mState, "bspeedx", bspeedx);
lua_register(mState, "bspeedy", bspeedy);
lua_register(mState, "posx", posx);
lua_register(mState, "posy", posy);
lua_register(mState, "oppx", oppx);
lua_register(mState, "oppy", oppy);
lua_register(mState, "estimate", estimate);
lua_register(mState, "estimx", estimx);
lua_register(mState, "estimy", estimy);
lua_register(mState, "timetox", timetox);
lua_register(mState, "timetoy", timetoy);
lua_register(mState, "predictx", predictx);
lua_register(mState, "predicty", predicty);
lua_register(mState, "xaty", xaty);
lua_register(mState, "yatx", yatx);
lua_register(mState, "nextevent", nextevent);
lua_register(mState, "predictImpact", predictImpact);
lua_register(mState, "getScore", getScore);
lua_register(mState, "getOppScore", getOppScore);
lua_register(mState, "getScoreToWin", getScoreToWin);
lua_register(mState, "getGameTime", getGameTime);
//lua_register(mState, "parabel", parabel);
ReaderInfo info;
info.handle = PHYSFS_openRead(filename.c_str());
if (!info.handle)
{
throw FileLoadException(filename);
}
int error;
error = lua_load(mState, chunkReader, &info, filename.c_str());
PHYSFS_close(info.handle);
if (error == 0)
error = lua_pcall(mState, 0, 6, 0);
if (error)
{
std::cerr << "Lua Error: " << lua_tostring(mState, -1);
std::cerr << std::endl;
ScriptException except;
except.luaerror = lua_tostring(mState, -1);
lua_pop(mState, 1);
lua_close(mState);
throw except;
}
// check whether all required lua functions are available
bool onserve, ongame, onoppserve;
lua_getglobal(mState, "OnServe");
onserve = lua_isfunction(mState, -1);
lua_getglobal(mState, "OnGame");
ongame = lua_isfunction(mState, -1);
lua_getglobal(mState, "OnOpponentServe");
onoppserve = lua_isfunction(mState, -1);
if (!onserve || !ongame ||!onoppserve)
{
std::string error_message = "Missing bot function ";
error_message += onserve ? "" : "OnServe() ";
error_message += ongame ? "" : "OnGame() ";
error_message += onoppserve ? "" : "OnOpponentServe() ";
std::cerr << "Lua Error: " << error_message << std::endl;
ScriptException except;
except.luaerror = error_message;
lua_pop(mState, 1);
lua_close(mState);
throw except;
}
// record which of the optional functions are available
lua_getglobal(mState, "OnBounce");
mOnBounce = lua_isfunction(mState, -1);
if(!mOnBounce) std::cerr << "Lua Warning: Missing function OnBounce" << std::endl;
lua_pop(mState, lua_gettop(mState));
// init delay
mBallPositions.set_capacity(mMaxDelay + 1);
mBallVelocities.set_capacity(mMaxDelay + 1);
for(unsigned int i = 0; i < mMaxDelay + 1; ++i) {
mBallPositions.push_back(Vector2(0,0));
mBallVelocities.push_back(Vector2(0,0));
}
}
ScriptedInputSource::~ScriptedInputSource()
{
lua_close(mState);
}
PlayerInput ScriptedInputSource::getInput()
{
bool serving = false;
// reset input
mLeft = false;
mRight = false;
mJump = false;
mCurrentSource = this;
mMatch = DuelMatch::getMainGame();
if (mMatch == 0)
{
return PlayerInput();
}
// ball position and velocity update
mBallPositions.push_back(mMatch->getBallPosition());
mBallVelocities.push_back(mMatch->getBallVelocity());
// adapt current delay
char action = rand() % 8;
switch(action) {
case 0:
case 1:
mCurDelay--;
break;
case 2:
case 3:
mCurDelay++;
}
if ( mLastBallSpeed != DuelMatch::getMainGame()->getBallVelocity().x ) {
mLastBallSpeed = DuelMatch::getMainGame()->getBallVelocity().x;
// reaction time after bounce
mCurDelay += rand() % (mMaxDelay+1);
}
if(mCurDelay == -1)
mCurDelay = 0;
if(mCurDelay > mMaxDelay)
mCurDelay = mMaxDelay;
int error = 0;
if (!mMatch->getBallActive() && mSide ==
// if no player is serving player, assume the left one is
(mMatch->getServingPlayer() == NO_PLAYER ? LEFT_PLAYER : mMatch->getServingPlayer() ))
{
serving = true;
lua_getglobal(mState, "OnServe");
lua_pushboolean(mState, !mMatch->getBallDown());
error = lua_pcall(mState, 1, 0, 0);
}
else if (!mMatch->getBallActive() && mCurrentSource->mSide !=
(mMatch->getServingPlayer() == NO_PLAYER ? LEFT_PLAYER : mMatch->getServingPlayer() ))
{
lua_getglobal(mState, "OnOpponentServe");
error = lua_pcall(mState, 0, 0, 0);
}
else
{
if ( mOnBounce && mLastBallSpeedVirtual != getBallVelocity().x ) {
mLastBallSpeedVirtual = getBallVelocity().x;
lua_getglobal(mState, "OnBounce");
error = lua_pcall(mState, 0, 0, 0);
if (error)
{
std::cerr << "Lua Error: " << lua_tostring(mState, -1);
std::cerr << std::endl;
lua_pop(mState, 1);
}
}
lua_getglobal(mState, "OnGame");
error = lua_pcall(mState, 0, 0, 0);
}
if (error)
{
std::cerr << "Lua Error: " << lua_tostring(mState, -1);
std::cerr << std::endl;
lua_pop(mState, 1);
}
// swap left/right if side is swapped
if ( mSide == RIGHT_PLAYER )
std::swap(mLeft, mRight);
PlayerInput currentInput = PlayerInput(mLeft, mRight, mJump);
int stacksize = lua_gettop(mState);
if (stacksize > 0)
{
std::cerr << "Warning: Stack messed up!" << std::endl;
std::cerr << "Element on stack is a ";
std::cerr << lua_typename(mState, -1) << std::endl;
lua_pop(mState, stacksize);
}
if (mStartTime + WAITING_TIME > SDL_GetTicks() && serving)
return PlayerInput();
else
return currentInput;
}
void ScriptedInputSource::setflags(lua_State* state) {
lua_pushnumber(state, FLAG_BOUNCE);
lua_setglobal(state, "FLAG_BOUNCE");
}
int ScriptedInputSource::touches(lua_State* state)
{
lua_pushnumber(state, mMatch->getHitcount(mCurrentSource->mSide));
return 1;
}
int ScriptedInputSource::launched(lua_State* state)
{
lua_pushnumber(state, mMatch->getBlobJump(mCurrentSource->mSide));
return 1;
}
int ScriptedInputSource::debug(lua_State* state)
{
float number = lua_tonumber(state, -1);
lua_pop(state, 1);
std::cerr << "Lua Debug: " << number << std::endl;
return 0;
}
int ScriptedInputSource::jump(lua_State* state)
{
mCurrentSource->mJump = true;
return 0;
}
int ScriptedInputSource::left(lua_State* state)
{
mCurrentSource->mLeft = true;
return 0;
}
int ScriptedInputSource::right(lua_State* state)
{
mCurrentSource->mRight = true;
return 0;
}
int ScriptedInputSource::moveto(lua_State* state)
{
float target = lua_tonumber(state, -1);
lua_pop(state, 1);
coordinate<pos_x> position = mMatch->getBlobPosition(mCurrentSource->mSide).x;
if (position > target + 2)
mCurrentSource->mLeft = true;
if (position < target - 2)
mCurrentSource->mRight = true;
return 0;
}
const Vector2& ScriptedInputSource::getBallPosition() {
return mCurrentSource->mBallPositions[mCurrentSource->mMaxDelay - mCurrentSource->mCurDelay];
}
const Vector2& ScriptedInputSource::getBallVelocity() {
return mCurrentSource->mBallVelocities[mCurrentSource->mMaxDelay - mCurrentSource->mCurDelay];
}
int ScriptedInputSource::ballx(lua_State* state)
{
coordinate<pos_x> pos = getBallPosition().x;
lua_pushnumber(state, pos);
return 1;
}
int ScriptedInputSource::bally(lua_State* state)
{
coordinate<pos_y> pos = getBallPosition().y;
lua_pushnumber(state, pos);
return 1;
}
int ScriptedInputSource::bspeedx(lua_State* state)
{
coordinate<vel_x> vel = getBallVelocity().x;
lua_pushnumber(state, vel);
return 1;
}
int ScriptedInputSource::bspeedy(lua_State* state)
{
coordinate<vel_y> vel = getBallVelocity().y;
lua_pushnumber(state, vel);
return 1;
}
int ScriptedInputSource::posx(lua_State* state)
{
coordinate<pos_x> pos = mMatch->getBlobPosition(mCurrentSource->mSide).x;
lua_pushnumber(state, pos);
return 1;
}
int ScriptedInputSource::posy(lua_State* state)
{
coordinate<pos_y> pos = mMatch->getBlobPosition(mCurrentSource->mSide).y;
lua_pushnumber(state, pos);
return 1;
}
int ScriptedInputSource::oppx(lua_State* state)
{
PlayerSide invPlayer =
mCurrentSource->mSide == LEFT_PLAYER ? RIGHT_PLAYER : LEFT_PLAYER;
coordinate<pos_x> pos = mMatch->getBlobPosition(invPlayer).x;
lua_pushnumber(state, pos);
return 1;
}
int ScriptedInputSource::oppy(lua_State* state)
{
PlayerSide invPlayer =
mCurrentSource->mSide == LEFT_PLAYER ? RIGHT_PLAYER : LEFT_PLAYER;
coordinate<pos_y> pos = mMatch->getBlobPosition(invPlayer).y;
lua_pushnumber(state, pos);
return 1;
}
int ScriptedInputSource::estimate(lua_State* state)
{
static bool warning_issued = false;
if( !warning_issued )
{
warning_issued = true;
std::cerr << "Lua Warning: function estimate() is deprecated!" << std::endl;
}
Vector2 pos = getBallPosition();
const Vector2& vel = getBallVelocity();
float time = (vel.y - std::sqrt((vel.y * vel.y)- (-2 * BALL_GRAVITATION * (-pos.y + GROUND_PLANE_HEIGHT_MAX - BALL_RADIUS)))) / (-BALL_GRAVITATION);
coordinate<pos_x> estim = pos.x + vel.x * time;
lua_pushnumber(state, estim);
return 1;
}
int ScriptedInputSource::estimx(lua_State* state)
{
static bool warning_issued = false;
if( !warning_issued )
{
warning_issued = true;
std::cerr << "Lua Warning: function estimx() is deprecated!" << std::endl;
}
int num = lround(lua_tonumber(state, -1));
lua_pop(state, 1);
coordinate<pos_x> estim = getBallPosition().x + num * getBallVelocity().x;
lua_pushnumber(state, estim);
return 1;
}
int ScriptedInputSource::estimy(lua_State* state)
{
static bool warning_issued = false;
if( !warning_issued )
{
warning_issued = true;
std::cerr << "Lua Warning: function estimy() is deprecated!" << std::endl;
}
int num = lround(lua_tonumber(state, -1));
lua_pop(state, 1);
coordinate<pos_y> estim = getBallPosition().y + num * (getBallVelocity().y + 0.5*BALL_GRAVITATION*num);
lua_pushnumber(state, estim);
return 1;
}
int ScriptedInputSource::predictx(lua_State* state) {
reset_flags();
float time = lua_tonumber(state, -1);
lua_pop(state, 1);
coordinate<pos_x> estim = predict_x(getBallPosition(), getBallVelocity(), time);
lua_pushnumber(state, estim);
setflags(state);
return 1;
}
int ScriptedInputSource::predicty(lua_State* state) {
reset_flags();
float time = lua_tonumber(state, -1);
lua_pop(state, 1);
coordinate<pos_y> estim = predict_y(getBallPosition(), getBallVelocity(), time);
lua_pushnumber(state, estim);
setflags(state);
return 1;
}
int ScriptedInputSource::timetox(lua_State* state) {
reset_flags();
coordinate<pos_x> destination = lua_tonumber(state, -1);
lua_pop(state, 1);
float time = time_to_x(getBallPosition(), getBallVelocity(), destination);
lua_pushnumber(state, time);
setflags(state);
return 1;
}
int ScriptedInputSource::timetoy(lua_State* state) {
reset_flags();
coordinate<pos_y> destination = lua_tonumber(state, -1);
lua_pop(state, 1);
float time = time_to_y(getBallPosition(), getBallVelocity(), destination);
lua_pushnumber(state, time);
setflags(state);
return 1;
}
int ScriptedInputSource::xaty(lua_State* state) {
reset_flags();
coordinate<pos_y> destination = lua_tonumber(state, -1);
lua_pop(state, 1);
coordinate<pos_x> x = x_at_y(getBallPosition(), getBallVelocity(), destination);
lua_pushnumber(state, x);
setflags(state);
return 1;
}
int ScriptedInputSource::yatx(lua_State* state) {
reset_flags();
coordinate<pos_x> destination = lua_tonumber(state, -1);
lua_pop(state, 1);
coordinate<pos_y> y = y_at_x(getBallPosition(), getBallVelocity(), destination);
lua_pushnumber(state, y);
setflags(state);
return 1;
}
int ScriptedInputSource::predictImpact(lua_State* state) {
reset_flags();
coordinate<pos_x> x = x_at_y(getBallPosition(), getBallVelocity(), GROUND_PLANE_HEIGHT_MAX - BLOBBY_HEIGHT - BALL_RADIUS);
lua_pushnumber(state, x);
setflags(state);
return 1;
}
int ScriptedInputSource::nextevent(lua_State* state) {
reset_flags();
float time = next_event(getBallPosition(), getBallVelocity());
lua_pushnumber(state, time);
setflags(state);
return 1;
}
int ScriptedInputSource::getScore(lua_State* state)
{
float score = mMatch->getScore( mCurrentSource->mSide );
lua_pushnumber(state, score);
return 1;
}
int ScriptedInputSource::getOppScore(lua_State* state)
{
float score = mMatch->getScore( mCurrentSource->mSide == LEFT_PLAYER ? RIGHT_PLAYER: LEFT_PLAYER );
lua_pushnumber(state, score);
return 1;
}
int ScriptedInputSource::getScoreToWin(lua_State* state)
{
float score = mMatch->getScoreToWin();
lua_pushnumber(state, score);
return 1;
}
int ScriptedInputSource::getGameTime(lua_State* state)
{
float time = mMatch->getClock().getTime();
lua_pushnumber(state, time);
return 1;
}
| gpl-2.0 |
thinkcollege/tc-code | plugins/editors-xtd/doclink/popups/lang/turkish.php | 2727 | <?php
/**
* DOCLink 1.5.x
* @version $Id: english.php 251 2007-09-01 14:28:37Z mjaz $
* @package DOCLink_1.5
* @copyright (C) 2003-2007 The DOCman Development Team
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.joomlatools.org/ Official website
**/
/**
*
* Default Turkish language file
*
* Creator: The DOCman Development Team
* Website: http://cumla.blogspot.com/
* E-mail: tolgas@gmail.com
* Revision: 1.0
* Date: Eyl�l 2007
**/
$MY_MESSAGES = array();
$MY_MESSAGES['extmissing'] = 'L�tfen bir bile�enle dosya y�kleyin, e.g. "imagefile.jpg".';
$MY_MESSAGES['nopermtodeletefile'] = 'Dosyay� silmek i�in izniniz yok.';
$MY_MESSAGES['filenotfound'] = 'Dosya bulunamad�.';
$MY_MESSAGES['unlinkfailed'] = 'Unlink hatas�.';
$MY_MESSAGES['rmdirfailed'] = 'Rmdir hatas�.';
$MY_MESSAGES['nopermtodeletefolder'] = 'Klas�r� silmek i�in izniniz yok.';
$MY_MESSAGES['foldernotfound'] = 'Klas�r bulunamad�.';
$MY_MESSAGES['foldernotempty'] = 'Klas�r bo� de�il. L�tfen ilk �nce t�m dosyalar� silin.';
$MY_MESSAGES['nopermtocreatefolder'] = 'Klas�r olu�turmak i�in izniniz yok.';
$MY_MESSAGES['pathnotfound'] = 'Dosya yolu bulunamad�.';
$MY_MESSAGES['foldernamemissing'] = 'Klas�r ismi kay�p.';
$MY_MESSAGES['folderalreadyexists'] = 'Klas�r zaten var.';
$MY_MESSAGES['mkdirfailed'] = 'Mkdir hatas�.';
$MY_MESSAGES['nopermtoupload'] = 'Y�klemek i�in izniniz yok.';
$MY_MESSAGES['extnotallowed'] = 'Dosyalar bu bile�en i�in uygun de�il.';
$MY_MESSAGES['filesizeexceedlimit'] = 'Dosyalar boyut s�n�r�n� a�t�.';
$MY_MESSAGES['filenotuploaded'] = 'Dosya y�klenemedi.';
$MY_MESSAGES['nofiles'] = 'Dosya Yok...';
$MY_MESSAGES['configproblem'] = 'Yap�land�rma problemi ';
$MY_MESSAGES['deletefile'] = 'Dosyay� sil';
$MY_MESSAGES['deletefolder'] = 'Klas�r� sil';
$MY_MESSAGES['refresh'] = 'Yenile';
$MY_MESSAGES['folder'] = 'Klas�r';
$MY_MESSAGES['type'] = '';
$MY_MESSAGES['name'] = 'Ad';
$MY_MESSAGES['size'] = 'Boyut';
$MY_MESSAGES['datemodified'] = 'D�zenleme Tarihi';
$MY_MESSAGES['url'] = 'URL';
$MY_MESSAGES['comment'] = 'Yorum';
$MY_MESSAGES['caption'] = 'Ba�l�k';
$MY_MESSAGES['upload'] = 'Y�kle';
$MY_MESSAGES['title'] = "Docman Ba�lant�s� Ekle";
$MY_MESSAGES['manager'] = "Dok�man Taray�c�";
$MY_MESSAGES['settings'] = "Ba�lant� Ayarlar�";
$MY_MESSAGES['category'] = "Kategori";
$MY_MESSAGES['inserticon'] = 'Dosya t�r� simgesi ekle';
$MY_MESSAGES['insertsize'] = 'Dosya boyutu ekle';
$MY_MESSAGES['insertdate'] = 'Dosya d�zenleme tarihini ekle';
$MY_MESSAGES['loading'] = 'Y�kleniyor ...';
| gpl-2.0 |
monokal/docker-orangehrm | www/symfony/plugins/orangehrmPimPlugin/modules/pim/templates/viewReportingMethodsSuccess.php | 5525 | <?php
/**
* OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures
* all the essential functionalities required for any enterprise.
* Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com
*
* OrangeHRM is free software; you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* OrangeHRM 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
*
*/
?>
<?php use_javascript(plugin_web_path('orangehrmPimPlugin', 'js/viewReportingMethodsSuccess')); ?>
<?php echo isset($templateMessage) ? templateMessage($templateMessage) : ''; ?>
<div id="saveFormDiv" class="box">
<div class="head">
<h1 id="saveFormHeading">Add Reporting Method</h1>
</div>
<div class="inner">
<form name="frmSave" id="frmSave" method="post" action="<?php echo url_for('pim/viewReportingMethods'); ?>">
<?php echo $form['_csrf_token']; ?>
<?php echo $form['id']->render(); ?>
<fieldset>
<ol>
<li>
<?php echo $form['name']->renderLabel(__('Name'). ' <em>*</em>'); ?>
<?php echo $form['name']->render(array("maxlength" => 100)); ?>
</li>
<li class="required">
<em>*</em> <?php echo __(CommonMessages::REQUIRED_FIELD); ?>
</li>
</ol>
<p>
<input type="button" class="" name="btnSave" id="btnSave" value="<?php echo __('Save'); ?>"/>
<input type="button" id="btnCancel" class="reset" value="<?php echo __('Cancel'); ?>"/>
</p>
</fieldset>
</form>
</div>
</div> <!-- saveFormDiv -->
<!-- Listi view -->
<div id="recordsListDiv" class="box miniList">
<div class="head">
<h1><?php echo __('Reporting Methods'); ?></h1>
</div>
<div class="inner">
<?php include_partial('global/flash_messages'); ?>
<form name="frmList" id="frmList" method="post" action="<?php echo url_for('pim/deleteReportingMethods'); ?>">
<?php echo $listForm?>
<fieldset>
<p id="listActions">
<input type="button" class="addbutton" id="btnAdd" value="<?php echo __('Add'); ?>" />
<input type="button" class="delete" id="btnDel" value="<?php echo __('Delete'); ?>"/>
</p>
</fieldset>
<table class="table hover" id="recordsListTable">
<thead>
<tr>
<th class="check" style="width:2%"><input type="checkbox" id="checkAll" class="checkbox" /></th>
<th style="width:98%"><?php echo __('Name'); ?></th>
</tr>
</thead>
<tbody>
<?php
$i=0;
foreach($records as $record):
?>
<tr class="<?php echo ($i & 1) ? 'even' : 'odd' ?>">
<td class="check">
<input type="checkbox" class="checkbox" name="chkListRecord[]" value="<?php echo $record->getId(); ?>" />
</td>
<td class="tdName tdValue">
<a href="#"><?php echo __($record->getName()); ?></a>
</td>
</tr>
<?php
$i++;
endforeach;
?>
<?php if (count($records) == 0) : ?>
<tr>
<td>
<?php echo __(TopLevelMessages::NO_RECORDS_FOUND); ?>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</form>
</div>
</div> <!-- recordsListDiv -->
<script type="text/javascript">
//<![CDATA[
var recordsCount = <?php echo count($records);?>;
var recordKeyId = "reportingMethod_id";
var saveFormFieldIds = new Array();
saveFormFieldIds[0] = "reportingMethod_name";
var urlForExistingNameCheck = '<?php echo url_for('pim/checkReportingMethodNameExistence'); ?>';
var lang_addFormHeading = "<?php echo __('Add Reporting Method'); ?>";
var lang_editFormHeading = "<?php echo __('Edit Reporting Method'); ?>";
var lang_nameIsRequired = '<?php echo __(ValidationMessages::REQUIRED); ?>';
var lang_nameExists = "<?php echo __('Name exists'); ?>";
//]]>
</script> | gpl-2.0 |
KEYSOURCE/OpenKeyos | lib/const.fr.php | 2206 | <?php
/**
* Constants settings - French
* Various constants to be used across the projects
*
* @package
* @subpackage Constants
*/
//require_once(dirname(__FILE__).'/local.php');
//require_once(dirname(__FILE__).'/local.php');
//require_once(dirname(__FILE__).'/const_notification.fr.php');
//require_once(dirname(__FILE__).'/const_krifs.fr.php');
//require_once(dirname(__FILE__).'/local.php');
//require_once(dirname(__FILE__).'/local.php');
$GLOBALS['USER_TYPES'] = array(
USER_TYPE_KEYSOURCE => 'Utilisateur Keysource',
USER_TYPE_CUSTOMER => 'Utilisateur Client',
USER_TYPE_CUSTOMER_SHOP => 'Utilisateur Boutique',
USER_TYPE_KEYSOURCE_GROUP => 'Groupe Keysource',
USER_TYPE_GROUP => 'Groupe'
);
/** Users statuses **/
$GLOBALS['USER_STATUSES'] = array (
USER_STATUS_INACTIVE => 'Pas actif',
USER_STATUS_ACTIVE => 'Actif',
USER_STATUS_AWAY_BUSINESS => 'Absent pour affaires',
USER_STATUS_AWAY_HOLIDAY => 'Parti en vacances'
);
/** ACL role types */
$GLOBALS['ACL_ROLE_TYPES'] = array (
ACL_ROLE_TYPE_KEYSOURCE => 'R�le Keysource ACL',
ACL_ROLE_TYPE_CUSTOMER => 'R�le Client ACL'
);
/** Phone types */
$GLOBALS['PHONE_TYPES'] = array(
PHONE_TYPE_MOBILE => 'Mobile',
PHONE_TYPE_OFFICE => 'Bureau',
PHONE_TYPE_HOME => 'Maison/Priv�'
);
$GLOBALS ['DAY_NAMES'] = array (
DAY_MON => 'Lundi',
DAY_TUE => 'Mardi',
DAY_WED => 'Mercredi',
DAY_THU => 'Jeudi',
DAY_FRI => 'Vendredi',
DAY_SAT => 'Samedi',
DAY_SUN => 'Dimanche'
);
$GLOBALS['PHOTO_OBJECT_CLASSES'] = array (
PHOTO_OBJECT_CLASS_COMPUTER => 'Ordinateur',
PHOTO_OBJECT_CLASS_PERIPHERAL => 'P�riph�rique',
PHOTO_OBJECT_CLASS_LOCATION => 'Emplacement',
);
$GLOBALS['LOCATION_FIXED_TYPES'] = array (
LOCATION_FIXED_TYPE_COUNTRY => 'Pays',
LOCATION_FIXED_TYPE_PROVINCE => 'Province',
LOCATION_FIXED_TYPE_TOWN => 'Ville'
);
$GLOBALS['LOCATION_TYPES'] = array (
LOCATION_TYPE_COMPLEX => 'Complexe',
LOCATION_TYPE_BUILDING => 'Immeuble',
LOCATION_TYPE_FLOOR => 'Etage',
LOCATION_TYPE_ROOM => 'Chambre'
);
/** Array with location types which can be assigned to top-level locations */
$GLOBALS['LOCATION_TYPES_TOP'] = array (
LOCATION_TYPE_COMPLEX => 'Complexe',
LOCATION_TYPE_BUILDING => 'Immeuble',
);
?> | gpl-2.0 |
donatellosantoro/freESBee | freesbeeSLA/src/it/unibas/freesbeesla/tracciatura/ws/server/stub/ServiceTermStateType.java | 1428 | package it.unibas.freesbeesla.tracciatura.ws.server.stub;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
/**
* <p>Java class for ServiceTermStateType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ServiceTermStateType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="Not_Ready"/>
* <enumeration value="Ready_Idle"/>
* <enumeration value="Ready_Processing"/>
* <enumeration value="Completed"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlEnum
public enum ServiceTermStateType {
@XmlEnumValue("Completed")
COMPLETED("Completed"),
@XmlEnumValue("Not_Ready")
NOT_READY("Not_Ready"),
@XmlEnumValue("Ready_Idle")
READY_IDLE("Ready_Idle"),
@XmlEnumValue("Ready_Processing")
READY_PROCESSING("Ready_Processing");
private final String value;
ServiceTermStateType(String v) {
value = v;
}
public String value() {
return value;
}
public static ServiceTermStateType fromValue(String v) {
for (ServiceTermStateType c : ServiceTermStateType.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v.toString());
}
}
| gpl-2.0 |
ocean0yohsuke/HookLoader | root/HookLoader/plugin/HookLoader/adm/intro.php | 283 | <?php
class phpBB3_HookLoaderPluginAdm_HookLoader_intro
{
public $API;
function main()
{
$Panel = $this->API->Template()->Custom();
$Panel->set_template('intro.html');
$Panel->create_head($this->API->Plugin->lang['HOOKLOADER_INTRO_TITLE']);
$Panel->create_body();
}
}
| gpl-2.0 |
dgachok/MikhrinCo | wp-content/themes/mikhrin-site/page-photos.php | 786 | <?php
/**
* Template Name: Page_Photos
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Mikhrin_and_Co_Site
*/
get_header(); ?>
<div id="primary" class="content__area">
<main id="main" class="site__main" role="main">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'photos' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer(); | gpl-2.0 |
novirael/django-projects-manager | projects_manager/admin.py | 123 | from django.contrib import admin
from .models import Project, Task
admin.site.register(Project)
admin.site.register(Task)
| gpl-2.0 |
michel-slm/bodhi | bodhi/tests/test_masher.py | 38939 | # This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import mock
import time
import json
import shutil
import unittest
import tempfile
from sqlalchemy import create_engine
from pyramid.paster import bootstrap
from bodhi import buildsys, log
from bodhi.config import config
from bodhi.masher import Masher, MasherThread
from bodhi.models import (DBSession, Base, Update, User, Release,
Build, UpdateRequest, UpdateType,
ReleaseState, BuildrootOverride,
UpdateStatus)
from bodhi.tests import populate
from bodhi.util import mkmetadatadir, transactional_session_maker
mock_exc = mock.Mock()
mock_exc.side_effect = Exception
mock_taskotron_results = {
'target': 'bodhi.util.taskotron_results',
'return_value': [{
"outcome": "PASSED",
"result_data": {},
"testcase": { "name": "rpmlint", }
}],
}
mock_failed_taskotron_results = {
'target': 'bodhi.util.taskotron_results',
'return_value': [{
"outcome": "FAILED",
"result_data": {},
"testcase": { "name": "rpmlint", }
}],
}
mock_absent_taskotron_results = {
'target': 'bodhi.util.taskotron_results',
'return_value': [],
}
class FakeHub(object):
def __init__(self):
self.config = {
'topic_prefix': 'org.fedoraproject',
'environment': 'dev',
'releng_fedmsg_certname': None,
'masher_topic': 'bodhi.start',
'masher': True,
}
def subscribe(self, *args, **kw):
pass
def makemsg(body=None):
if not body:
body = {'updates': 'bodhi-2.0-1.fc17'}
return {
'topic': u'org.fedoraproject.dev.bodhi.masher.start',
'body': {
u'i': 1,
u'msg': body,
u'msg_id': u'2014-9568c910-91de-4870-90f5-709cc577d56d',
u'timestamp': 1401728063,
u'topic': u'org.fedoraproject.dev.bodhi.masher.start',
u'username': u'lmacken',
},
}
class TestMasher(unittest.TestCase):
def setUp(self):
fd, self.db_filename = tempfile.mkstemp(prefix='bodhi-testing-', suffix='.db')
db_path = 'sqlite:///%s' % self.db_filename
# The BUILD_ID environment variable is set by Jenkins and allows us to
# detect if
# we are running the tests in jenkins or not
# https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-below
if os.environ.get('BUILD_ID'):
faitout = 'http://209.132.184.152/faitout/'
try:
import requests
req = requests.get('%s/new' % faitout)
if req.status_code == 200:
db_path = req.text
print 'Using faitout at: %s' % db_path
except:
pass
engine = create_engine(db_path)
DBSession.configure(bind=engine)
Base.metadata.create_all(engine)
self.db_factory = transactional_session_maker
with self.db_factory() as session:
populate(session)
assert session.query(Update).count() == 1
self.koji = buildsys.get_session()
self.koji.clear() # clear out our dev introspection
self.msg = makemsg()
self.tempdir = tempfile.mkdtemp('bodhi')
self.masher = Masher(FakeHub(), db_factory=self.db_factory, mash_dir=self.tempdir)
def tearDown(self):
shutil.rmtree(self.tempdir)
try:
DBSession.remove()
finally:
try:
os.remove(self.db_filename)
except:
pass
def set_stable_request(self, title):
with self.db_factory() as session:
query = session.query(Update).filter_by(title=title)
update = query.one()
update.request = UpdateRequest.stable
session.flush()
@mock.patch('bodhi.notifications.publish')
def test_invalid_signature(self, publish):
"""Make sure the masher ignores messages that aren't signed with the
appropriate releng cert
"""
fakehub = FakeHub()
fakehub.config['releng_fedmsg_certname'] = 'foo'
self.masher = Masher(fakehub, db_factory=self.db_factory)
self.masher.consume(self.msg)
# Make sure the update did not get locked
with self.db_factory() as session:
# Ensure that the update was locked
up = session.query(Update).one()
self.assertFalse(up.locked)
# Ensure mashtask.start never got sent
self.assertEquals(len(publish.call_args_list), 0)
@mock.patch('bodhi.notifications.publish')
def test_push_invalid_update(self, publish):
msg = makemsg()
msg['body']['msg']['updates'] = 'invalidbuild-1.0-1.fc17'
self.masher.consume(msg)
self.assertEquals(len(publish.call_args_list), 1)
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch.object(MasherThread, 'verify_updates', mock_exc)
@mock.patch('bodhi.notifications.publish')
def test_update_locking(self, publish, *args):
with self.db_factory() as session:
up = session.query(Update).one()
self.assertFalse(up.locked)
self.masher.consume(self.msg)
# Ensure that fedmsg was called 4 times
self.assertEquals(len(publish.call_args_list), 3)
# Also, ensure we reported success
publish.assert_called_with(
topic="mashtask.complete",
msg=dict(success=False, repo='f17-updates-testing'))
with self.db_factory() as session:
# Ensure that the update was locked
up = session.query(Update).one()
self.assertTrue(up.locked)
# Ensure we can't set a request
from bodhi.exceptions import LockedUpdateException
try:
env = bootstrap('development.ini')
request = env['request']
up.set_request(UpdateRequest.stable, u'bodhi')
assert False, 'Set the request on a locked update'
except LockedUpdateException:
pass
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
def test_tags(self, publish, *args):
# Make the build a buildroot override as well
title = self.msg['body']['msg']['updates']
with self.db_factory() as session:
release = session.query(Update).one().release
build = session.query(Build).one()
nvr = build.nvr
pending_testing_tag = release.pending_testing_tag
override_tag = release.override_tag
self.koji.__tagged__[title] = [release.override_tag,
pending_testing_tag]
# Start the push
self.masher.consume(self.msg)
# Ensure that fedmsg was called 3 times
self.assertEquals(len(publish.call_args_list), 4)
# Also, ensure we reported success
publish.assert_called_with(
topic="mashtask.complete",
msg=dict(success=True, repo='f17-updates-testing'))
# Ensure our single update was moved
self.assertEquals(len(self.koji.__moved__), 1)
self.assertEquals(len(self.koji.__added__), 0)
self.assertEquals(self.koji.__moved__[0], (u'f17-updates-candidate',
u'f17-updates-testing', u'bodhi-2.0-1.fc17'))
# The override tag won't get removed until it goes to stable
self.assertEquals(self.koji.__untag__[0], (pending_testing_tag, nvr))
self.assertEquals(len(self.koji.__untag__), 1)
with self.db_factory() as session:
# Set the update request to stable and the release to pending
up = session.query(Update).one()
up.release.state = ReleaseState.pending
up.request = UpdateRequest.stable
self.koji.clear()
self.masher.consume(self.msg)
# Ensure that stable updates to pending releases get their
# tags added, not removed
self.assertEquals(len(self.koji.__moved__), 0)
self.assertEquals(len(self.koji.__added__), 1)
self.assertEquals(self.koji.__added__[0], (u'f17', u'bodhi-2.0-1.fc17'))
self.assertEquals(self.koji.__untag__[0], (override_tag, u'bodhi-2.0-1.fc17'))
# Check that the override got expired
with self.db_factory() as session:
ovrd = session.query(BuildrootOverride).one()
self.assertIsNotNone(ovrd.expired_date)
# Check that the request_complete method got run
up = session.query(Update).one()
self.assertIsNone(up.request)
def test_statefile(self):
t = MasherThread(u'F17', u'testing', [u'bodhi-2.0-1.fc17'], log, self.db_factory, self.tempdir)
t.id = 'f17-updates-testing'
t.init_state()
t.save_state()
self.assertTrue(os.path.exists(t.mash_lock))
with file(t.mash_lock) as f:
state = json.load(f)
try:
self.assertEquals(state, {u'tagged': False, u'updates':
[u'bodhi-2.0-1.fc17'], u'completed_repos': []})
finally:
t.remove_state()
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.mail._send_mail')
def test_testing_digest(self, mail, *args):
t = MasherThread(u'F17', u'testing', [u'bodhi-2.0-1.fc17'],
log, self.db_factory, self.tempdir)
with self.db_factory() as session:
t.db = session
t.work()
t.db = None
self.assertEquals(t.testing_digest[u'Fedora 17'][u'bodhi-2.0-1.fc17'], """\
================================================================================
libseccomp-2.1.0-1.fc20 (FEDORA-%s-0001)
Enhanced seccomp library
--------------------------------------------------------------------------------
Update Information:
Useful details!
--------------------------------------------------------------------------------
References:
[ 1 ] Bug #12345 - None
https://bugzilla.redhat.com/show_bug.cgi?id=12345
[ 2 ] CVE-1985-0110
http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-1985-0110
--------------------------------------------------------------------------------
""" % time.strftime('%Y'))
mail.assert_called_with(config.get('bodhi_email'), config.get('fedora_test_announce_list'), mock.ANY)
assert len(mail.mock_calls) == 2, len(mail.mock_calls)
body = mail.mock_calls[1][1][2]
assert body.startswith('From: updates@fedoraproject.org\r\nTo: %s\r\nSubject: Fedora 17 updates-testing report\r\n\r\nThe following builds have been pushed to Fedora 17 updates-testing\n\n bodhi-2.0-1.fc17\n\nDetails about builds:\n\n\n================================================================================\n libseccomp-2.1.0-1.fc20 (FEDORA-%s-0001)\n Enhanced seccomp library\n--------------------------------------------------------------------------------\nUpdate Information:\n\nUseful details!\n--------------------------------------------------------------------------------\nReferences:\n\n [ 1 ] Bug #12345 - None\n https://bugzilla.redhat.com/show_bug.cgi?id=12345\n [ 2 ] CVE-1985-0110\n http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-1985-0110\n--------------------------------------------------------------------------------\n\n' % (config.get('fedora_test_announce_list'), time.strftime('%Y'))), repr(body)
def test_sanity_check(self):
t = MasherThread(u'F17', u'testing', [u'bodhi-2.0-1.fc17'],
log, self.db_factory, self.tempdir)
t.id = 'f17-updates-testing'
t.init_path()
# test without any arches
try:
t.sanity_check_repo()
assert False, "Sanity check didn't fail with empty dir"
except:
pass
# test with valid repodata
for arch in ('i386', 'x86_64', 'armhfp'):
repo = os.path.join(t.path, t.id, arch)
os.makedirs(repo)
mkmetadatadir(repo)
t.sanity_check_repo()
# test with truncated/busted repodata
xml = os.path.join(t.path, t.id, 'i386', 'repodata', 'repomd.xml')
repomd = open(xml).read()
with open(xml, 'w') as f:
f.write(repomd[:-10])
from bodhi.exceptions import RepodataException
try:
t.sanity_check_repo()
assert False, 'Busted metadata passed'
except RepodataException:
pass
def test_stage(self):
t = MasherThread(u'F17', u'testing', [u'bodhi-2.0-1.fc17'],
log, self.db_factory, self.tempdir)
t.id = 'f17-updates-testing'
t.init_path()
t.stage_repo()
stage_dir = config.get('mash_stage_dir')
link = os.path.join(stage_dir, t.id)
self.assertTrue(os.path.islink(link))
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
def test_security_update_priority(self, publish, *args):
with self.db_factory() as db:
up = db.query(Update).one()
user = db.query(User).first()
# Create a security update for a different release
release = Release(
name=u'F18', long_name=u'Fedora 18',
id_prefix=u'FEDORA', version='18',
dist_tag=u'f18', stable_tag=u'f18-updates',
testing_tag=u'f18-updates-testing',
candidate_tag=u'f18-updates-candidate',
pending_testing_tag=u'f18-updates-testing-pending',
pending_stable_tag=u'f18-updates-pending',
override_tag=u'f18-override')
db.add(release)
build = Build(nvr=u'bodhi-2.0-1.fc18', release=release,
package=up.builds[0].package)
db.add(build)
update = Update(
title=u'bodhi-2.0-1.fc18',
builds=[build], user=user,
status=UpdateStatus.testing,
request=UpdateRequest.stable,
notes=u'Useful details!', release=release)
update.type = UpdateType.security
db.add(update)
# Wipe out the tag cache so it picks up our new release
Release._tag_cache = None
self.msg['body']['msg']['updates'] += ' bodhi-2.0-1.fc18'
self.masher.consume(self.msg)
# Ensure that F18 runs before F17
calls = publish.mock_calls
# Order of fedmsgs at the the moment:
# masher.start
# mashing f18
# complete.stable (for each update)
# errata.publish
# mashtask.complete
# mashing f17
# complete.testing
# mashtask.complete
self.assertEquals(calls[1], mock.call(
msg={'repo': u'f18-updates', 'updates': [u'bodhi-2.0-1.fc18']},
topic='mashtask.mashing'))
self.assertEquals(calls[4], mock.call(
msg={'success': True, 'repo': 'f18-updates'},
topic='mashtask.complete'))
self.assertEquals(calls[5], mock.call(
msg={'repo': u'f17-updates-testing',
'updates': [u'bodhi-2.0-1.fc17']},
topic='mashtask.mashing'))
self.assertEquals(calls[-1], mock.call(
msg={'success': True, 'repo': 'f17-updates-testing'},
topic='mashtask.complete'))
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
def test_security_update_priority_testing(self, publish, *args):
with self.db_factory() as db:
up = db.query(Update).one()
up.type = UpdateType.security
up.request = UpdateRequest.testing
user = db.query(User).first()
# Create a security update for a different release
release = Release(
name=u'F18', long_name=u'Fedora 18',
id_prefix=u'FEDORA', version='18',
dist_tag=u'f18', stable_tag=u'f18-updates',
testing_tag=u'f18-updates-testing',
candidate_tag=u'f18-updates-candidate',
pending_testing_tag=u'f18-updates-testing-pending',
pending_stable_tag=u'f18-updates-pending',
override_tag=u'f18-override')
db.add(release)
build = Build(nvr=u'bodhi-2.0-1.fc18', release=release,
package=up.builds[0].package)
db.add(build)
update = Update(
title=u'bodhi-2.0-1.fc18',
builds=[build], user=user,
status=UpdateStatus.testing,
request=UpdateRequest.stable,
notes=u'Useful details!', release=release)
update.type = UpdateType.enhancement
db.add(update)
# Wipe out the tag cache so it picks up our new release
Release._tag_cache = None
self.msg['body']['msg']['updates'] += ' bodhi-2.0-1.fc18'
self.masher.consume(self.msg)
# Ensure that F17 updates-testing runs before F18
calls = publish.mock_calls
self.assertEquals(calls[1], mock.call(
msg={'repo': u'f17-updates-testing',
'updates': [u'bodhi-2.0-1.fc17']},
topic='mashtask.mashing'))
self.assertEquals(calls[3], mock.call(
msg={'success': True, 'repo': 'f17-updates-testing'},
topic='mashtask.complete'))
self.assertEquals(calls[4], mock.call(
msg={'repo': u'f18-updates',
'updates': [u'bodhi-2.0-1.fc18']},
topic='mashtask.mashing'))
self.assertEquals(calls[-1], mock.call(
msg={'success': True, 'repo': 'f18-updates'},
topic='mashtask.complete'))
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
def test_security_updates_parallel(self, publish, *args):
with self.db_factory() as db:
up = db.query(Update).one()
up.type = UpdateType.security
up.status = UpdateStatus.testing
up.request = UpdateRequest.stable
user = db.query(User).first()
# Create a security update for a different release
release = Release(
name=u'F18', long_name=u'Fedora 18',
id_prefix=u'FEDORA', version='18',
dist_tag=u'f18', stable_tag=u'f18-updates',
testing_tag=u'f18-updates-testing',
candidate_tag=u'f18-updates-candidate',
pending_testing_tag=u'f18-updates-testing-pending',
pending_stable_tag=u'f18-updates-pending',
override_tag=u'f18-override')
db.add(release)
build = Build(nvr=u'bodhi-2.0-1.fc18', release=release,
package=up.builds[0].package)
db.add(build)
update = Update(
title=u'bodhi-2.0-1.fc18',
builds=[build], user=user,
status=UpdateStatus.testing,
request=UpdateRequest.stable,
notes=u'Useful details!', release=release)
update.type = UpdateType.security
db.add(update)
# Wipe out the tag cache so it picks up our new release
Release._tag_cache = None
self.msg['body']['msg']['updates'] += ' bodhi-2.0-1.fc18'
self.masher.consume(self.msg)
# Ensure that F18 and F17 run in parallel
calls = publish.mock_calls
if calls[1] == mock.call(msg={'repo': u'f18-updates',
'updates': [u'bodhi-2.0-1.fc18']}, topic='mashtask.mashing'):
self.assertEquals(calls[2], mock.call(msg={'repo': u'f17-updates',
'updates': [u'bodhi-2.0-1.fc17']}, topic='mashtask.mashing'))
elif calls[1] == self.assertEquals(calls[1], mock.call(msg={'repo': u'f17-updates',
'updates': [u'bodhi-2.0-1.fc17']}, topic='mashtask.mashing')):
self.assertEquals(calls[2], mock.call(msg={'repo': u'f18-updates',
'updates': [u'bodhi-2.0-1.fc18']}, topic='mashtask.mashing'))
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.util.cmd')
def test_update_comps(self, cmd, *args):
cmd.return_value = '', '', 0
self.masher.consume(self.msg)
self.assertIn(mock.call(['git', 'pull'], mock.ANY), cmd.mock_calls)
self.assertIn(mock.call(['make'], mock.ANY), cmd.mock_calls)
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_mash(self, cmd, publish, *args):
cmd.return_value = '', '', 0
# Set the request to stable right out the gate so we can test gating
self.set_stable_request('bodhi-2.0-1.fc17')
t = MasherThread(u'F17', u'stable', [u'bodhi-2.0-1.fc17'], log,
self.db_factory, self.tempdir)
with self.db_factory() as session:
t.db = session
t.work()
t.db = None
# Also, ensure we reported success
publish.assert_called_with(topic="mashtask.complete",
msg=dict(success=True, repo='f17-updates'))
publish.assert_any_call(topic='update.complete.stable',
msg=mock.ANY)
self.assertIn(mock.call(['mash'] + [mock.ANY] * 7), cmd.mock_calls)
self.assertEquals(len(t.state['completed_repos']), 1)
@mock.patch(**mock_failed_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_failed_gating(self, cmd, publish, *args):
cmd.return_value = '', '', 0
# Set the request to stable right out the gate so we can test gating
self.set_stable_request('bodhi-2.0-1.fc17')
t = MasherThread(u'F17', u'stable', [u'bodhi-2.0-1.fc17'], log,
self.db_factory, self.tempdir)
with self.db_factory() as session:
t.db = session
t.work()
t.db = None
# Also, ensure we reported success
publish.assert_called_with(topic="mashtask.complete",
msg=dict(success=True, repo='f17-updates'))
publish.assert_any_call(topic='update.eject', msg=mock.ANY)
self.assertIn(mock.call(['mash'] + [mock.ANY] * 7), cmd.mock_calls)
self.assertEquals(len(t.state['completed_repos']), 1)
@mock.patch(**mock_absent_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_absent_gating(self, cmd, publish, *args):
cmd.return_value = '', '', 0
# Set the request to stable right out the gate so we can test gating
self.set_stable_request('bodhi-2.0-1.fc17')
t = MasherThread(u'F17', u'stable', [u'bodhi-2.0-1.fc17'], log,
self.db_factory, self.tempdir)
with self.db_factory() as session:
t.db = session
t.work()
t.db = None
# Also, ensure we reported success
publish.assert_called_with(topic="mashtask.complete",
msg=dict(success=True, repo='f17-updates'))
publish.assert_any_call(topic='update.eject', msg=mock.ANY)
self.assertIn(mock.call(['mash'] + [mock.ANY] * 7), cmd.mock_calls)
self.assertEquals(len(t.state['completed_repos']), 1)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
@mock.patch('bodhi.bugs.bugtracker.modified')
@mock.patch('bodhi.bugs.bugtracker.on_qa')
def test_modify_testing_bugs(self, on_qa, modified, *args):
self.masher.consume(self.msg)
on_qa.assert_called_once_with(12345, u"bodhi-2.0-1.fc17 has been pushed to the Fedora 17 testing repository. If problems still persist, please make note of it in this bug report.\\nIf you want to test the update, you can install it with \\n su -c 'yum --enablerepo=updates-testing update bodhi'. You can provide feedback for this update here: http://localhost:6543/F17/FEDORA-%s-0001" % time.localtime().tm_year)
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
@mock.patch('bodhi.bugs.bugtracker.comment')
@mock.patch('bodhi.bugs.bugtracker.close')
def test_modify_stable_bugs(self, close, comment, *args):
self.set_stable_request('bodhi-2.0-1.fc17')
t = MasherThread(u'F17', u'stable', [u'bodhi-2.0-1.fc17'], log,
self.db_factory, self.tempdir)
with self.db_factory() as session:
t.db = session
t.work()
t.db = None
close.assert_called_with(12345, fixedin=u'2.0-1.fc17')
comment.assert_called_with(12345, u'bodhi-2.0-1.fc17 has been pushed to the Fedora 17 stable repository. If problems still persist, please make note of it in this bug report.')
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_status_comment_testing(self, *args):
title = self.msg['body']['msg']['updates']
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
self.assertEquals(len(up.comments), 2)
self.masher.consume(self.msg)
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
self.assertEquals(len(up.comments), 3)
self.assertEquals(up.comments[-1]['text'], u'This update has been pushed to testing')
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_status_comment_stable(self, *args):
title = self.msg['body']['msg']['updates']
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
up.request = UpdateRequest.stable
self.assertEquals(len(up.comments), 2)
self.masher.consume(self.msg)
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
self.assertEquals(len(up.comments), 3)
self.assertEquals(up.comments[-1]['text'], u'This update has been pushed to stable')
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
def test_get_security_updates(self, *args):
build = u'bodhi-2.0-1.fc17'
t = MasherThread(u'F17', u'testing', [build],
log, self.db_factory, self.tempdir)
with self.db_factory() as session:
t.db = session
u = session.query(Update).one()
u.type = UpdateType.security
u.status = UpdateStatus.testing
u.request = None
release = session.query(Release).one()
updates = t.get_security_updates(release.long_name)
self.assertEquals(len(updates), 1)
self.assertEquals(updates[0].title, build)
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_unlock_updates(self, *args):
title = self.msg['body']['msg']['updates']
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
up.request = UpdateRequest.stable
self.assertEquals(len(up.comments), 2)
self.masher.consume(self.msg)
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
self.assertEquals(up.locked, False)
self.assertEquals(up.status, UpdateStatus.stable)
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_resume_push(self, *args):
title = self.msg['body']['msg']['updates']
with mock.patch.object(MasherThread, 'verify_updates', mock_exc):
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
up.request = UpdateRequest.testing
up.status = UpdateStatus.pending
# Simulate a failed push
self.masher.consume(self.msg)
# Ensure that the update hasn't changed state
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
self.assertEquals(up.request, UpdateRequest.testing)
self.assertEquals(up.status, UpdateStatus.pending)
# Resume the push
self.msg['body']['msg']['resume'] = True
self.masher.consume(self.msg)
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
self.assertEquals(up.status, UpdateStatus.testing)
self.assertEquals(up.request, None)
@mock.patch(**mock_taskotron_results)
@mock.patch('bodhi.masher.MasherThread.update_comps')
@mock.patch('bodhi.masher.MashThread.run')
@mock.patch('bodhi.masher.MasherThread.wait_for_mash')
@mock.patch('bodhi.masher.MasherThread.sanity_check_repo')
@mock.patch('bodhi.masher.MasherThread.stage_repo')
@mock.patch('bodhi.masher.MasherThread.generate_updateinfo')
@mock.patch('bodhi.masher.MasherThread.wait_for_sync')
@mock.patch('bodhi.notifications.publish')
@mock.patch('bodhi.util.cmd')
def test_stable_requirements_met_during_push(self, *args):
"""
Test reaching the stablekarma threshold while the update is being
pushed to testing
"""
title = self.msg['body']['msg']['updates']
# Simulate a failed push
with mock.patch.object(MasherThread, 'verify_updates', mock_exc):
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
up.request = UpdateRequest.testing
up.status = UpdateStatus.pending
self.assertEquals(up.stable_karma, 3)
self.masher.consume(self.msg)
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
# Ensure the update is still locked and in testing
self.assertEquals(up.locked, True)
self.assertEquals(up.status, UpdateStatus.pending)
self.assertEquals(up.request, UpdateRequest.testing)
# Have the update reach the stable karma threshold
self.assertEquals(up.karma, 1)
up.comment(u"foo", 1, u'foo')
self.assertEquals(up.karma, 2)
self.assertEquals(up.request, UpdateRequest.testing)
up.comment(u"foo", 1, u'bar')
self.assertEquals(up.karma, 3)
self.assertEquals(up.request, UpdateRequest.testing)
up.comment(u"foo", 1, u'biz')
self.assertEquals(up.request, UpdateRequest.testing)
self.assertEquals(up.karma, 4)
# finish push and unlock updates
self.msg['body']['msg']['resume'] = True
self.masher.consume(self.msg)
with self.db_factory() as session:
up = session.query(Update).filter_by(title=title).one()
up.comment(u"foo", 1, u'baz')
self.assertEquals(up.karma, 5)
# Ensure the masher set the autokarma once the push is done
self.assertEquals(up.locked, False)
self.assertEquals(up.request, UpdateRequest.stable)
| gpl-2.0 |
mdowton/rbs | wp-content/themes/construction/single.php | 1582 | <?php
/**
* Single post template
*
* @package wpv
* @subpackage construction
*/
get_header();
?>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<div class="row page-wrapper">
<?php WpvTemplates::left_sidebar() ?>
<article <?php post_class( 'single-post-wrapper '.WpvTemplates::get_layout() )?>>
<?php
global $wpv_has_header_sidebars;
if ( $wpv_has_header_sidebars ) {
WpvTemplates::header_sidebars();
}
?>
<div class="page-content loop-wrapper clearfix full">
<?php get_template_part( 'templates/post' ); ?>
<div class="clearboth">
<?php comments_template(); ?>
</div>
</div>
</article>
<?php WpvTemplates::right_sidebar() ?>
<?php if ( wpv_get_optionb( 'show-related-posts' ) && is_singular( 'post' ) ) : ?>
<?php
$terms = array();
$cats = get_the_category();
foreach ( $cats as $cat ) {
$terms[] = $cat->term_id;
}
?>
<div class="related-posts">
<div class="clearfix">
<div class="grid-1-1">
<?php echo apply_filters( 'wpv_related_posts_title', '<h2 class="related-content-title">'.wpv_get_option( 'related-posts-title' ).'</h3>' ) // xss ok ?>
<?php
echo WPV_Blog::shortcode( array(
'count' => 8,
'column' => 4,
'cat' => $terms,
'layout' => 'scroll-x',
'show_content' => true,
'post__not_in' => get_the_ID(),
) ); // xss ok
?>
</div>
</div>
</div>
<?php endif ?>
</div>
<?php endwhile;
endif;
get_footer();
| gpl-2.0 |
Xilaew/risiko | Risiko/src/risiko/actions/impl/MoveTroopsImpl.java | 6654 | /**
*/
package risiko.actions.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import risiko.actions.MoveTroops;
import risiko.actions.actionPackage;
import risiko.board.Country;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Move Troops</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link risiko.actions.impl.MoveTroopsImpl#getFrom <em>From</em>}</li>
* <li>{@link risiko.actions.impl.MoveTroopsImpl#getTo <em>To</em>}</li>
* <li>{@link risiko.actions.impl.MoveTroopsImpl#getTroops <em>Troops</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MoveTroopsImpl extends InGameActionImpl implements MoveTroops {
/**
* The cached value of the '{@link #getFrom() <em>From</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFrom()
* @generated
* @ordered
*/
protected Country from;
/**
* The cached value of the '{@link #getTo() <em>To</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTo()
* @generated
* @ordered
*/
protected Country to;
/**
* The default value of the '{@link #getTroops() <em>Troops</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTroops()
* @generated
* @ordered
*/
protected static final int TROOPS_EDEFAULT = 0;
/**
* The cached value of the '{@link #getTroops() <em>Troops</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTroops()
* @generated
* @ordered
*/
protected int troops = TROOPS_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MoveTroopsImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return actionPackage.Literals.MOVE_TROOPS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Country getFrom() {
if (from != null && from.eIsProxy()) {
InternalEObject oldFrom = (InternalEObject)from;
from = (Country)eResolveProxy(oldFrom);
if (from != oldFrom) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, actionPackage.MOVE_TROOPS__FROM, oldFrom, from));
}
}
return from;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Country basicGetFrom() {
return from;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setFrom(Country newFrom) {
Country oldFrom = from;
from = newFrom;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, actionPackage.MOVE_TROOPS__FROM, oldFrom, from));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Country getTo() {
if (to != null && to.eIsProxy()) {
InternalEObject oldTo = (InternalEObject)to;
to = (Country)eResolveProxy(oldTo);
if (to != oldTo) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, actionPackage.MOVE_TROOPS__TO, oldTo, to));
}
}
return to;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Country basicGetTo() {
return to;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTo(Country newTo) {
Country oldTo = to;
to = newTo;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, actionPackage.MOVE_TROOPS__TO, oldTo, to));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getTroops() {
return troops;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTroops(int newTroops) {
int oldTroops = troops;
troops = newTroops;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, actionPackage.MOVE_TROOPS__TROOPS, oldTroops, troops));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case actionPackage.MOVE_TROOPS__FROM:
if (resolve) return getFrom();
return basicGetFrom();
case actionPackage.MOVE_TROOPS__TO:
if (resolve) return getTo();
return basicGetTo();
case actionPackage.MOVE_TROOPS__TROOPS:
return getTroops();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case actionPackage.MOVE_TROOPS__FROM:
setFrom((Country)newValue);
return;
case actionPackage.MOVE_TROOPS__TO:
setTo((Country)newValue);
return;
case actionPackage.MOVE_TROOPS__TROOPS:
setTroops((Integer)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case actionPackage.MOVE_TROOPS__FROM:
setFrom((Country)null);
return;
case actionPackage.MOVE_TROOPS__TO:
setTo((Country)null);
return;
case actionPackage.MOVE_TROOPS__TROOPS:
setTroops(TROOPS_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case actionPackage.MOVE_TROOPS__FROM:
return from != null;
case actionPackage.MOVE_TROOPS__TO:
return to != null;
case actionPackage.MOVE_TROOPS__TROOPS:
return troops != TROOPS_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (troops: ");
result.append(troops);
result.append(')');
return result.toString();
}
} //MoveTroopsImpl
| gpl-2.0 |
dherrerav/Azteca-Sonora | administrator/components/com_media/views/videolist/tmpl/default_folder.php | 813 | <?php
/**
* @version $Id: default_folder.php 21020 2011-03-27 06:52:01Z infograf768 $
* @package Joomla.Administrator
* @subpackage com_media
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
?>
<div class="item">
<a href="index.php?option=com_media&view=videolist&tmpl=component&folder=<?php echo $this->_tmp_folder->path_relative; ?>&asset=<?php echo JRequest::getCmd('asset');?>&author=<?php echo JRequest::getCmd('author');?>">
<?php echo JHtml::_('image','media/folder.gif', $this->_tmp_folder->name, array('height' => 80, 'width' => 80), true); ?>
<span><?php echo $this->_tmp_folder->name; ?></span></a>
</div>
| gpl-2.0 |
tormit/SuperStructureBundle | Controller/ObjectController.php | 427 | <?php
/**
* @author Tormi Talv <tormit@gmail.com> 2013
* @since 8/16/13 9:44 PM
* @version 1.0
*/
namespace Tormit\SuperStructureBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Tormit\SuperStructureBundle\Entity\Route;
abstract class ObjectController extends Controller
{
abstract public function objectAction($objectClass, $bundleName, $objectSlug, Route $route);
} | gpl-2.0 |
kenbabu/emproj | components/com_virtuemart/views/manufacturer/tmpl/default.php | 3042 | <?php
/**
*
* Description
*
* @package VirtueMart
* @subpackage Manufacturer
* @author Kohl Patrick, Eugen Stranz
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: default.php 2701 2011-02-11 15:16:49Z impleri $
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
// Category and Columns Counter
$iColumn = 1;
$iManufacturer = 1;
// Calculating Categories Per Row
$manufacturerPerRow = 3;
if ($manufacturerPerRow != 1) {
$manufacturerCellWidth = ' width'.floor ( 100 / $manufacturerPerRow );
} else {
$manufacturerCellWidth = '';
}
// Separator
$verticalSeparator = " vertical-separator";
$horizontalSeparator = '<div class="horizontal-separator"></div>';
// Lets output the categories, if there are some
if (!empty($this->manufacturers)) { ?>
<div class="manufacturer-view-default">
<?php // Start the Output
foreach ( $this->manufacturers as $manufacturer ) {
// Show the horizontal seperator
if ($iColumn == 1 && $iManufacturer > $manufacturerPerRow) {
echo $horizontalSeparator;
}
// this is an indicator wether a row needs to be opened or not
if ($iColumn == 1) { ?>
<div class="row">
<?php }
// Show the vertical seperator
if ($iManufacturer == $manufacturerPerRow or $iManufacturer % $manufacturerPerRow == 0) {
$showVerticalSeparator = ' ';
} else {
$showVerticalSeparator = $verticalSeparator;
}
// Manufacturer Elements
$manufacturerURL = JROUTE::_('index.php?option=com_virtuemart&view=manufacturer&virtuemart_manufacturer_id=' . $manufacturer->virtuemart_manufacturer_id);
$manufacturerIncludedProductsURL = JROUTE::_('index.php?option=com_virtuemart&view=category&virtuemart_manufacturer_id=' . $manufacturer->virtuemart_manufacturer_id);
$manufacturerImage = $manufacturer->images[0]->displayMediaThumb("",false);
// Show Category ?>
<div class="manufacturer floatleft<?php echo $manufacturerCellWidth . $showVerticalSeparator ?>">
<div class="spacer">
<h2>
<a title="<?php echo $manufacturer->mf_name; ?>" href="<?php echo $manufacturerURL; ?>"><?php echo $manufacturer->mf_name; ?></a>
</h2>
<a title="<?php echo $manufacturer->mf_name; ?>" href="<?php echo $manufacturerURL; ?>"><?php echo $manufacturerImage;?></a>
</div>
</div>
<?php
$iManufacturer ++;
// Do we need to close the current row now?
if ($iColumn == $manufacturerPerRow) {
echo '<div class="clear"></div></div>';
$iColumn = 1;
} else {
$iColumn ++;
}
}
// Do we need a final closing row tag?
if ($iColumn != 1) { ?>
<div class="clear"></div>
</div>
<?php } ?>
</div>
<?php
}
?> | gpl-2.0 |
carvalhomb/tsmells | sample/argouml/argouml/org/argouml/uml/diagram/ui/FigEmptyRect.java | 2197 | // $Id: FigEmptyRect.java 7490 2005-01-09 14:59:18Z linus $
// Copyright (c) 1996-2005 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.diagram.ui;
import org.tigris.gef.presentation.FigRect;
/**
* A FigRect that is always transparent
* @author Bob Tarling
*/
public class FigEmptyRect extends FigRect {
/**
* @param x x
* @param y y
* @param w width
* @param h height
*/
public FigEmptyRect(int x, int y, int w, int h) {
super(x, y, w, h);
super.setFilled(false);
}
/**
* @see org.tigris.gef.presentation.Fig#setFilled(boolean)
*/
public void setFilled(boolean filled) {
// Do nothing, this rect will always be transparent
}
}
| gpl-2.0 |
Conedy/Conedy | testing/global/expected/sum_setFail.py | 68 | 00000 0 output/setFail.py.err
07168 1 output/setFail.py.out
| gpl-2.0 |
Fluorohydride/ygopro-scripts | c24062258.lua | 1770 | --暗躍のドルイド・ドリュース
function c24062258.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(24062258,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,24062258)
e1:SetTarget(c24062258.sptg)
e1:SetOperation(c24062258.spop)
c:RegisterEffect(e1)
end
function c24062258.filter(c,e,tp)
return not c:IsCode(24062258) and c:IsLevel(4) and c:IsAttribute(ATTRIBUTE_DARK) and (c:IsAttack(0) or c:IsDefense(0))
and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c24062258.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c24062258.filter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c24062258.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c24062258.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c24062258.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e2)
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
cotocisternas/vagrant-foreman | master_conf/modules/foreman/lib/puppet/provider/foreman_smartproxy/rest_v2.rb | 1328 | Puppet::Type.type(:foreman_smartproxy).provide(:rest_v2) do
confine :feature => :apipie_bindings
# when both rest and rest_v2 providers are installed, use this one
def self.specificity
super + 1
end
def api
@api ||= ApipieBindings::API.new({
:uri => resource[:base_url],
:api_version => 2,
:oauth => {
:consumer_key => resource[:consumer_key],
:consumer_secret => resource[:consumer_secret]
},
:timeout => resource[:timeout],
:headers => {
:foreman_user => resource[:effective_user],
},
:apidoc_cache_base_dir => File.join(Puppet[:server_datadir], 'apipie_bindings')
}).resource(:smart_proxies)
end
# proxy hash or nil
def proxy
if @proxy
@proxy
else
@proxy = api.call(:index, :search => "name=#{resource[:name]}")['results'][0]
end
end
def id
proxy ? proxy['id'] : nil
end
def exists?
! id.nil?
end
def create
api.call(:create, {
'name' => resource[:name],
'url' => resource[:url]
})
end
def destroy
api.call(:destroy, :id => id)
@proxy = nil
end
def url
proxy ? proxy['url'] : nil
end
def url=(value)
api.call(:update, :id => id, :url => value)
end
def refresh_features!
api.call(:refresh, :id => id)
end
end
| gpl-2.0 |
england9911/matteng.land | core/modules/block/src/Form/BlockDeleteForm.php | 1068 | <?php
/**
* @file
* Contains \Drupal\block\Form\BlockDeleteForm.
*/
namespace Drupal\block\Form;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Provides a deletion confirmation form for the block instance deletion form.
*/
class BlockDeleteForm extends EntityConfirmFormBase {
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete the block %name?', array('%name' => $this->entity->label()));
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('block.admin_display');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function submit(array $form, FormStateInterface $form_state) {
$this->entity->delete();
drupal_set_message($this->t('The block %name has been removed.', array('%name' => $this->entity->label())));
$form_state['redirect_route'] = $this->getCancelUrl();
}
}
| gpl-2.0 |
Adjokip/OGP-Website | lang/Hungarian/modules/subusers.php | 4020 | <?php
/*
*
* OGP - Open Game Panel
* Copyright (C) 2008 - 2017 The OGP Development Team
*
* http://www.opengamepanel.org/
*
* 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('OGP_LANG_login_name', "Felhasználónév");
define('OGP_LANG_first_name', "Keresztnév");
define('OGP_LANG_last_name', "Vezetéknév");
define('OGP_LANG_phone_number', "Telefonszám");
define('OGP_LANG_email_address', "E-mail");
define('OGP_LANG_register_a_new_user', "Új felhasználó regisztrálása");
define('OGP_LANG_password_mismatch', "A jelszavak nem egyeznek.");
define('OGP_LANG_confirm_password', "Jelszó megerősítése");
define('OGP_LANG_subuser_password', "Alfelhasználó jelszó");
define('OGP_LANG_subuser_man', "Al-felhasználó kezelés");
define('OGP_LANG_successfull', "Sikeres");
define('OGP_LANG_click_here', "Kattints ide");
define('OGP_LANG_to_login', "a belépéshez.");
define('OGP_LANG_registered_on', "Regisztrálás a :: %s");
define('OGP_LANG_register_message', "Hello,<br><br>Az Open Game Panel fiókod elkészült és most már bejelentkezhetsz az alábbi fiók adatokkal:<br><br>Felhasználónév: %s<br>Jelszó: %s<br><br>Ne felejtsd el néha megváltoztatni a jelszavadat és az első belépést követően.<br><br>Kérlek, ne válaszolj erre az e-mailre!<br><br>______________________________<br>OGP Postázó");
define('OGP_LANG_err_password', "A jelszó nem lehet üres");
define('OGP_LANG_err_confirm_password', "A jelszó ismét mező nem lehet üres");
define('OGP_LANG_err_password_mismatch', "A jelszavak nem egyeznek");
define('OGP_LANG_err_captcha', "Captcha nem egyezik.");
define('OGP_LANG_err_login_name', "A felhasználónév üres vagy már foglalt.");
define('OGP_LANG_err_first_name', "Add meg a neved.");
define('OGP_LANG_err_last_name', "Vezetéknév nincs megadva.");
define('OGP_LANG_err_phone_number', "A telefonszám üres.");
define('OGP_LANG_err_email_address', "Üres vagy érvénytelen e-mail cím.");
define('OGP_LANG_err_users_parent', "Az al-felhasználói fiókok nem hozhatnak létre más felhasználókat.");
define('OGP_LANG_err_parent_user', "The parent user ID must reference a valid pre-existing user.");
define('OGP_LANG_err_email_address_already_in_use_by', "Az e-mail cím már használatban van <b>%s</b> által.");
define('OGP_LANG_user_registration', "Felhasználó regisztrálás");
define('OGP_LANG_your_account_details_has_been_sent_by_email_to', "A fiók adataid e-mailben elküldve a(z) <b>%s</b> címre.");
define('OGP_LANG_subject', "Helló %s, üdvözöllek a(z) %s!");
define('OGP_LANG_sub_user', "Alfelhasználók");
define('OGP_LANG_create_sub_user', "Alfelhasználó hozzáadása");
define('OGP_LANG_listdel_sub_user', "Lista, al-felhasználói fiók információk módosítása vagy al-felhasználó törlése");
define('OGP_LANG_delete_sub_user', "Alfelhasználó szerkesztése / törlése");
define('OGP_LANG_del_subuser_conf', "Biztos vagy benne, hogy törölni akarod ezt a fiókot:");
define('OGP_LANG_no_subusers', "Nincsenek al-felhasználók létrehozva még a fiókod alatt.");
define('OGP_LANG_subuser_deleted', "A(z) %s al-felhasználó sikeresen törölve az adatbázisból!");
define('OGP_LANG_subuser_added', "A(z) %s al-felhasználó sikeresen létrehozva és hozzáadva az adatbázishoz.");
define('OGP_LANG_your_subusers', "Birtokolt alfelhasználói fiókok");
?> | gpl-2.0 |
siemens/fossology | src/copyright/ui/agent-copyright.php | 1570 | <?php
/***********************************************************
Copyright (C) 2010-2013 Hewlett-Packard Development Company, L.P.
Copyright (C) 2014-2015, Siemens AG
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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.
***********************************************************/
use Fossology\Lib\Plugin\AgentPlugin;
/**
* @class CopyrightAgentPlugin
* @brief Create UI plugin for copyright agent
*/
class CopyrightAgentPlugin extends AgentPlugin
{
public function __construct() {
$this->Name = "agent_copyright";
$this->Title = _("Copyright/Email/URL/Author Analysis");
$this->AgentName = "copyright";
parent::__construct();
}
/**
* @copydoc Fossology::Lib::Plugin::AgentPlugin::AgentHasResults()
* @see Fossology::Lib::Plugin::AgentPlugin::AgentHasResults()
*/
function AgentHasResults($uploadId=0)
{
return CheckARS($uploadId, $this->AgentName, "copyright scanner", "copyright_ars");
}
}
register_plugin(new CopyrightAgentPlugin());
| gpl-2.0 |
nefilim/SNSMonitor | src/main/scala/org/nefilim/snsmonitor/service/SNSMonitorAPIWorker.scala | 2250 | package org.nefilim.snsmonitor.service
import akka.actor.{Props, Actor}
import spray.http.{StatusCodes, HttpResponse, HttpRequest, Timedout}
import org.nefilim.chefclient.ChefClient
import com.typesafe.config.ConfigFactory
import org.nefilim.snsmonitor.hipchat.HipChatListener
import org.nefilim.snsmonitor.domain.Internal.MonitorEvent
import org.nefilim.snsmonitor.api.{SNSMonitorAPI, HealthAPI}
/**
* Created by peter on 3/16/14.
*/
object SNSMonitorAPIWorker {
def props() = Props(classOf[SNSMonitorAPIWorker])
}
class SNSMonitorAPIWorker
extends Actor
with SNSMonitorAPI
with HealthAPI
with ServiceActors
with AkkaExecutionContextProvider
{
def actorRefFactory = context
implicit val executionContext = context.dispatcher // TODO we want a custom dispatcher here? don't want to block request handling
val config = ConfigFactory.load() // application.conf
val chefClientId = config.getString("snsMonitor.chef.clientId")
val chefOrganization = if (!config.hasPath("snsMonitor.chef.organization")) None else Some(config.getString("snsMonitor.chef.organization"))
val chefClientKeyPath = config.getString("snsMonitor.chef.clientKeyPath")
val hipChatToken = if (!config.hasPath("snsMonitor.hipChat.token")) None else Some(config.getString("snsMonitor.hipChat.token"))
val hipChatRoom = if (!config.hasPath("snsMonitor.hipChat.room")) None else Some(config.getString("snsMonitor.hipChat.room"))
val hipChatEnabled = hipChatToken.isDefined && hipChatRoom.isDefined
if (hipChatEnabled) {
val listener = context.actorOf(HipChatListener.props(hipChatToken.get, hipChatRoom.get))
context.system.eventStream.subscribe(listener, classOf[MonitorEvent])
}
val chefClient = ChefClient(chefClientKeyPath, chefClientId, "api.opscode.com", chefOrganization.map("/organizations/" + _))
val monitorService = context.actorOf(MonitorService.props(chefClient), "monitorServiceActor")
def receive = handleTimeouts orElse router
val route = eventRoute ~ healthRoute
def router = runRoute(route)
def handleTimeouts: Receive = {
case Timedout(x: HttpRequest) =>
logger.warn(s"request ${x} timed out")
sender ! HttpResponse(StatusCodes.RequestTimeout, s"the request ${x} timed out")
}
}
| gpl-2.0 |
sathish4fri/opensource-socialnetwork | libraries/ossn.lib.system.php | 11774 | <?php
/**
* OpenSource-SocialNetwork
*
* @package (Informatikon.com).ossn
* @author OSSN Core Team <info@opensource-socialnetwork.com>
* @copyright 2014 iNFORMATIKON TECHNOLOGIES
* @license General Public Licence http://opensource-socialnetwork.com/licence
* @link http://www.opensource-socialnetwork.com/licence
*/
/*
* OSSN ACCESS VALUES
*/
define('OSSN_FRIENDS', 3);
define('OSSN_PUBLIC', 2);
define('OSSN_PRIVATE', 1);
/**
* Get site url
*
* @params $extend => Extned site url like http://site.com/my/extended/path
*
* @return string
*/
function ossn_site_url($extend = ''){
global $Ossn;
return "{$Ossn->url}{$extend}";
}
/**
* Get data directory contaning user and system files
*
* @params $extend => Extned data directory path like /home/htdocs/userdata/my/extend/path
*
* @return string
*/
function ossn_get_userdata($extend = ''){
global $Ossn;
return "{$Ossn->userdata}{$extend}";
}
/**
* Get database settings
*
* @return object
*/
function ossn_database_settings(){
global $Ossn;
$defaults = array(
'host' => $Ossn->host,
'user' => $Ossn->user,
'password' => $Ossn->password,
'database' => $Ossn->database
);
return arrayObject($defaults);
}
/**
* Get version package file
*
* @return object
*/
function ossn_package_information(){
return simplexml_load_file(ossn_route()->www.'opensource-socialnetwork.xml');
}
/**
* Add a hook to system, hooks are usefull for callback returns
*
*@param string $hook The name of the hook
* @param string $type The type of the hook
* @param callable $callback The name of a valid function or an array with object and method
* @param int $priority The priority - 500 is default, lower numbers called first
*
* @return bool
*/
function ossn_add_hook($hook, $type, $callback, $priority = 200){
global $Ossn;
if (empty($hook) || empty($type)) {
return false;
}
if (!isset($Ossn->hooks)) {
$Ossn->hooks = array();
}
if (!isset($Ossn->hooks[$hook])) {
$Ossn->hooks[$hook] = array();
}
if (!isset($Ossn->hooks[$hook][$type])) {
$Ossn->hooks[$hook][$type] = array();
}
if (!is_callable($callback, true)) {
return false;
}
$priority = max((int) $priority, 0);
while (isset($Ossn->hooks[$hook][$type][$priority])) {
$priority++;
}
$Ossn->hooks[$hook][$type][$priority] = $callback;
ksort($Ossn->hooks[$hook][$type]);
return true;
}
/**
* Check if the hook exists or not
*
* @param string $hook The name of the hook
* @param string $type The type of the hook
*
* @return bool
*/
function ossn_is_hook($hook, $type){
global $Ossn;
$hooks = array();
if (isset($Ossn->hooks[$hook][$type])) {
return true;
}
return false;
}
/**
* Call a hook
*
* @param string $hook The name of the hook
* @param string $type The type of the hook
* @param mixed $params Additional parameters to pass to the handlers
* @param mixed $returnvalue An initial return value
*
* @return mix data
*/
function ossn_call_hook($hook, $type, $params = null, $returnvalue = null) {
global $Ossn;
$hooks = array();
if (isset($Ossn->hooks[$hook][$type])) {
$hooks[] = $Ossn->hooks[$hook][$type];
}
foreach ($hooks as $callback_list) {
if (is_array($callback_list)) {
foreach ($callback_list as $hookcallback) {
if (is_callable($hookcallback)) {
$args = array($hook, $type, $returnvalue, $params);
$temp_return_value = call_user_func_array($hookcallback, $args);
if (!is_null($temp_return_value)) {
$returnvalue = $temp_return_value;
}
}
}
}
}
return $returnvalue;
}
/**
* Trigger a callback
*
* @param string $event Callback event name
* @param string $type The type of the callback
* @param mixed $params Additional parameters to pass to the handlers
*
* @return bool
*/
function ossn_trigger_callback($event, $type, $params = null) {
global $OpenSocialWebsite;
$events = array();
if (isset($OpenSocialWebsite->events[$event][$type])) {
$events[] = $OpenSocialWebsite->events[$event][$type];
}
foreach ($events as $callback_list) {
if (is_array($callback_list)) {
foreach ($callback_list as $eventcallback) {
$args = array($event, $type, $params);
if (is_callable($eventcallback) && (call_user_func_array($eventcallback, $args) === false)) {
return false;
}
}
}
}
return true;
}
/**
* Register a callback
*
* @param string $event Callback event name
* @param string $type The type of the callback
* @param mixed $params Additional parameters to pass to the handlers
* @params $priority callback priority
*
* @return bool
*/
function ossn_register_callback($event, $type, $callback, $priority = 200){
global $OpenSocialWebsite;
if (empty($event) || empty($type)) {
return false;
}
if (!isset($OpenSocialWebsite->events)) {
$OpenSocialWebsite->events = array();
}
if (!isset($OpenSocialWebsite->events[$event])) {
$OpenSocialWebsite->events[$event] = array();
}
if (!isset($OpenSocialWebsite->events[$event][$type])) {
$OpenSocialWebsite->events[$event][$type] = array();
}
if (!is_callable($callback, true)) {
return false;
}
$priority = max((int) $priority, 0);
while (isset($OpenSocialWebsite->events[$event][$type][$priority])) {
$priority++;
}
$OpenSocialWebsite->events[$event][$type][$priority] = $callback;
ksort($OpenSocialWebsite->events[$event][$type]);
return true;
}
/**
* Get a site settings
*
* @param string $settings Settings Name like ( site_name, language)
*
* @return string or null
*/
function ossn_site_settings($setting){
$settings = new OssnSite;
return $settings->getSettings($setting);
}
/**
* Redirect a user to specific url
*
* @param $new url
* if it is REF then user redirected to the url that user just came from
*
* @return return
*/
function redirect($new = ''){
$url = ossn_site_url($new);
if($new === REF){
$url = $_SERVER['HTTP_REFERER'];
}
header("Location: {$url}");
exit;
}
/**
* Get default access types
*
* @return array
*/
function ossn_access_types(){
return array(OSSN_FRIENDS, OSSN_PUBLIC, OSSN_PRIVATE);
}
/**
* Validate Access
*
* @return bool
*/
function ossn_access_validate($access, $owner){
if($access == OSSN_FRIENDS){
if(ossn_user_is_friend(ossn_loggedin_user()->guid, $owner) || ossn_loggedin_user()->guid == $owner){
return true;
}
}
if($access == OSSN_PUBLIC){
return true;
}
return false;
}
/**
* Check if the request is ajax or not
*
* @return bool
*/
function ossn_is_xhr(){
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
return true;
}
return false;
}
/**
* Serialize Array
* This starts array from key 1
* Don't use this for multidemension arrays
*
* @return array
*/
function arraySerialize($array = NULL){
if(isset($array) && !empty($array)){
array_unshift($array,"");
unset($array[0]);
return $array;
}
}
/**
* Limit a words in a string
* @params $str = string;
* @params $limit = words limit;
*
* @last edit: $arsalanshah
* @return bool
*/
function sttl($str, $limit = NULL, $dots = true){
if(isset($str)
&& isset($limit)){
if(strlen($str) > $limit){
if($dots == true){
return substr($str, 0, $limit).'...';
} elseif($dots == false){
return substr($str, 0, $limit);
}
}
elseif(strlen($str) < $limit){
return $str;
}
}
return false;
}
/**
* Update site settings
*
* @params $name => settings name
* $value => new value
* $id => $settings name
*
* @todo remove $id and update without having $id as settings names must be unique
* @return bool
*/
function ossn_site_setting_update($name, $value, $id){
$settings = new OssnSite;
if($settings->UpdateSettings(
array('value'),
array($value),
array("setting_id='{$id}'"))){
return true;
}
return false;
}
/**
* Add a system messages for users
*
* @params $messages => Message for user
* $type = message type
* $for => for site/frontend or admin/backend
* $count => count the message
*
* @return bool
*/
function ossn_system_message_add($message = null, $register = "ossn-message-success", $for = 'site', $count = false) {
if (!isset($_SESSION['ossn_messages'])) {
$_SESSION['ossn_messages'][$for] = array();
}
if (!isset($_SESSION['ossn_messages'][$for][$register]) && !empty($register)) {
$_SESSION['ossn_messages'][$for][$register][time()] = array();
}
if (!$count) {
if (!empty($message) && is_array($message)) {
$_SESSION['ossn_messages'][$for][$register][time()] = array_merge($_SESSION['ossn_messages'][$register], $message);
return true;
} else if (!empty($message) && is_string($message)) {
$_SESSION['ossn_messages'][$for][$register][time()][] = $message;
return true;
} else if (is_null($message)) {
if ($register != "") {
$returnarray = array();
$returnarray[$register] = $_SESSION['ossn_messages'][$register][time()];
$_SESSION['ossn_messages'][$for][$register][time()] = array();
} else {
$returnarray = $_SESSION['ossn_messages'];
$_SESSION['ossn_messages'][$for] = array();
}
return $returnarray;
}
} else {
if (!empty($register)) {
return sizeof($_SESSION['ossn_messages'][$for][$register][time()]);
} else {
$count = 0;
foreach ($_SESSION['ossn_messages'][$for] as $submessages) {
$count += sizeof($submessages);
}
return $count;
}
}
return false;
}
/**
* Add a system messages for users
*
* @params $messages => Message for user
* $type = message type
* $for => for site/frontend or admin/backend
*
* @return void
*/
function ossn_trigger_message($message, $type = 'success', $for = 'site'){
if($type == 'error'){
ossn_system_message_add($message, 'ossn-message-error', $for);
}
if($type == 'success'){
ossn_system_message_add($message, 'ossn-message-success', $for);
}
}
/**
* Display a system messages
*
* @params $for => for site/frontend or admin/backend
*
* @return mix data
*/
function ossn_display_system_messages($for = 'site'){
if(isset($_SESSION['ossn_messages'][$for])){
$dermessage = $_SESSION['ossn_messages'][$for];
if(!empty($dermessage)){
if (isset($dermessage) && is_array($dermessage) && sizeof($dermessage) > 0) {
foreach ($dermessage as $type => $list ) {
foreach ($list as $messages) {
foreach ($messages as $message) {
$m = "<div class='$type'>";
$m .= $message;
$m .= '</div>';
$ms[] = $m;
unset($_SESSION['ossn_messages'][$for][$type]);
}
}
}
}
}
}
if(isset($ms) && is_array($ms)){
return implode('',$ms);
}
}
/**
* Count total themes
*
* @return (int)
*/
function ossn_site_total_themes(){
$themes = new OssnThemes;
return count($themes->total());
}
/**
* Output Ossn Error page
*
* @return mix data
*/
function ossn_error_page(){
$title = ossn_print('page:error');
$contents['content'] = ossn_view('pages/contents/error');
$contents['background'] = false;
$content = ossn_set_page_layout('contents', $contents);
$data = ossn_view_page($title, $content);
echo $data;
exit;
} | gpl-2.0 |
AshamaneProject/AshamaneCore | src/server/scripts/BrokenIsles/VioletHold/boss_mind_flayer_kaarhj.cpp | 15763 | /*
* Copyright (C) 2017-2019 AshamaneProject <https://github.com/AshamaneProject>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "AreaTrigger.h"
#include "AreaTriggerTemplate.h"
#include "AreaTriggerAI.h"
#include "violet_hold_assault.h"
enum Spells
{
SPELL_DOOM = 201148,
SPELL_ETERNAL_DARKNESS = 201153,
SPELL_HYSTERIA = 201146,
SPELL_SHADOW_CRASH = 201920,
SPELL_SHADOW_CRASH_VISUAL = 197783,
SPELL_SHADOW_CRASH_TRIGGER = 201120,
SPELL_SHADOW_CRASH_AURA = 201121,
SPELL_SUMMON_TENTACLE = 201300,
SPELL_COLLAPSING_SHADOWS = 201256,
SPELL_COLLAPSING_SHADOWS_DMG = 201255,
// Faceless Tendril
SPELL_ETERNAL_DARKNESS_FACELESS = 201172,
SPELL_ETERNAL_DARKNESS_BUFF = 227178,
};
enum Events
{
EVENT_DOOM = 1,
EVENT_HYSTERIA = 2,
EVENT_SHADOW_CRASH = 3,
};
enum Says
{
SAY_INTRO = 0,
SAY_AGGRO = 1,
SAY_HYSTERIA = 2,
SAY_HYSTERIA_2 = 3,
SAY_HYSTERIA_3 = 4,
SAY_ETERNAL_DARKNESS = 5,
SAY_ETERNAL_DARKNESS_2 = 6,
SAY_ETERNAL_DARKNESS_3 = 7,
SAY_KILL = 8,
SAY_WIPE = 9,
SAY_DEATH = 10,
SAY_DEATH_2 = 11,
SAY_AGGRO_WHISPER = 12,
SAY_KILL_WHISPER = 13,
SAY_HYSTERIA_WHISP_1 = 14,
SAY_HYSTERIA_WHISP_2 = 15,
SAY_HYSTERIA_WHISP_3 = 16,
SAY_ETERNAL_DARKNESS_WHISP_1 = 17,
SAY_ETERNAL_DARKNESS_WHISP_2 = 18,
SAY_ETERNAL_DARKNESS_WHISP_3 = 19,
SAY_DEATH_WHISP = 20,
SAY_DEATH_WHISP_2 = 21,
};
class boss_mind_flayer_kaarhj : public CreatureScript
{
public:
boss_mind_flayer_kaarhj() : CreatureScript("boss_mind_flayer_kaarhj")
{
// Empty
}
struct boss_mind_flayer_kaarhj_AI : public BossAI
{
boss_mind_flayer_kaarhj_AI(Creature* creature) : BossAI(creature, DATA_MINDFLAYER_KAARHJ)
{
}
void Reset() override
{
_firstDarkness = false;
_secondDarkness = false;
_Reset();
}
void EnterCombat(Unit* /**/) override
{
Talk(SAY_AGGRO);
WhisperAll(SAY_AGGRO_WHISPER);
_EnterCombat();
events.ScheduleEvent(EVENT_SHADOW_CRASH, urand(3, 5) * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_DOOM, 8 * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_HYSTERIA, 12 * IN_MILLISECONDS);
}
void DamageTaken(Unit* /**/, uint32& /*damage*/) override
{
if (me->HealthBelowPct(80) && !_firstDarkness)
{
uint32 talk_id = urand(SAY_ETERNAL_DARKNESS, SAY_ETERNAL_DARKNESS_3);
Talk(talk_id);
WhisperTalk(talk_id);
_firstDarkness = true;
DoCast(SPELL_ETERNAL_DARKNESS);
}
else if (me->HealthBelowPct(40) && !_secondDarkness)
{
uint32 talk_id = urand(SAY_ETERNAL_DARKNESS, SAY_ETERNAL_DARKNESS_3);
Talk(talk_id);
WhisperTalk(talk_id);
_secondDarkness = true;
DoCast(SPELL_ETERNAL_DARKNESS);
}
}
void EnterEvadeMode(EvadeReason /**/) override
{
Talk(SAY_WIPE);
CreatureAI::EnterEvadeMode();
}
void KilledUnit(Unit* unit) override
{
if (unit && unit->GetTypeId() == TYPEID_PLAYER)
{
Talk(SAY_KILL);
WhisperAll(SAY_KILL_WHISPER);
}
}
void WhisperAll(uint32 id)
{
auto & players = me->GetMap()->GetPlayers();
if (players.isEmpty())
return;
for (auto itr = players.begin(); itr != players.end(); ++itr)
{
if (Player* player = itr->GetSource())
Talk(id, player);
}
}
void WhisperTalk(uint32 talk_id)
{
switch (talk_id)
{
case SAY_HYSTERIA:
WhisperAll(SAY_HYSTERIA_WHISP_1);
break;
case SAY_HYSTERIA_2:
WhisperAll(SAY_HYSTERIA_WHISP_2);
break;
case SAY_HYSTERIA_3:
WhisperAll(SAY_HYSTERIA_WHISP_3);
break;
case SAY_ETERNAL_DARKNESS:
WhisperAll(SAY_ETERNAL_DARKNESS_WHISP_1);
break;
case SAY_ETERNAL_DARKNESS_2:
WhisperAll(SAY_ETERNAL_DARKNESS_WHISP_2);
break;
case SAY_ETERNAL_DARKNESS_3:
WhisperAll(SAY_ETERNAL_DARKNESS_WHISP_3);
break;
case SAY_DEATH:
WhisperAll(SAY_DEATH_WHISP);
break;
case SAY_DEATH_2:
WhisperAll(SAY_DEATH_WHISP_2);
break;
default : break;
}
}
void JustDied(Unit* /*killer*/) override
{
uint32 talk_id = urand(SAY_DEATH, SAY_DEATH_2);
Talk(talk_id);
WhisperTalk(talk_id);
_JustDied();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SHADOW_CRASH:
DoCast(me, SPELL_SHADOW_CRASH);
events.ScheduleEvent(EVENT_SHADOW_CRASH, urand(22,24) * IN_MILLISECONDS);
break;
case EVENT_DOOM:
if (Unit* victim = me->GetVictim())
DoCast(victim, SPELL_DOOM);
events.ScheduleEvent(EVENT_DOOM, urand(18, 20) * IN_MILLISECONDS);
break;
case EVENT_HYSTERIA:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0, true))
{
uint32 talk_id = urand(SAY_HYSTERIA, SAY_HYSTERIA_3);
Talk(talk_id);
WhisperTalk(talk_id);
DoCast(target, SPELL_HYSTERIA);
}
events.ScheduleEvent(EVENT_HYSTERIA, 15 * IN_MILLISECONDS);
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
bool _firstDarkness, _secondDarkness;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new boss_mind_flayer_kaarhj_AI(creature);
}
};
class npc_faceless_tendril : public CreatureScript
{
public:
npc_faceless_tendril() : CreatureScript("npc_faceless_tendril")
{}
struct npc_faceless_tendril_AI : public ScriptedAI
{
npc_faceless_tendril_AI(Creature* creature) : ScriptedAI(creature)
{
}
void Reset() override
{
me->setActive(true);
me->SetReactState(REACT_AGGRESSIVE);
}
void UpdateAI(uint32 /*diff*/) override
{
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
if (Creature* kaarhj = me->FindNearestCreature(101950, 250.0f, true))
{
if (Unit* target = kaarhj->GetAI()->SelectTarget(SELECT_TARGET_RANDOM, 0, 0, true))
DoCast(target, SPELL_ETERNAL_DARKNESS_FACELESS);
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_faceless_tendril_AI(creature);
}
};
class spell_shadow_crash : public SpellScriptLoader
{
public:
spell_shadow_crash() : SpellScriptLoader("spell_shadow_crash")
{
}
class spell_shadow_crash_SpellScript : public SpellScript
{
public:
PrepareSpellScript(spell_shadow_crash_SpellScript);
void HandleDummy()
{
if (!GetCaster())
return;
for (auto & it : targetsList)
GetCaster()->CastSpell(it, SPELL_SHADOW_CRASH_VISUAL, true);
}
void FilterTargets(std::list<WorldObject*>& targets)
{
if (targets.empty())
return;
targets.remove_if([] (WorldObject* target)
{
if (target && target->ToPlayer())
return false;
return true;
});
for (auto & it : targets)
if (it && it->ToUnit())
targetsList.push_back(it->ToUnit());
}
void Register()
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_shadow_crash_SpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
OnCast += SpellCastFn(spell_shadow_crash_SpellScript::HandleDummy);
}
private:
std::list<Unit*> targetsList;
};
SpellScript* GetSpellScript() const
{
return new spell_shadow_crash_SpellScript();
}
};
class spell_eternal_darkness : public SpellScriptLoader
{
public:
spell_eternal_darkness() : SpellScriptLoader("spell_eternal_darkness")
{}
class spell_eternal_darkness_AuraScript : public AuraScript
{
public:
PrepareAuraScript(spell_eternal_darkness_AuraScript);
void HandleSummons(AuraEffect const* /*aurEff*/)
{
if (!GetCaster())
return;
GetCaster()->CastSpell(GetCaster(), SPELL_SUMMON_TENTACLE, true);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_eternal_darkness_AuraScript::HandleSummons, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY);
}
};
AuraScript* GetAuraScript() const
{
return new spell_eternal_darkness_AuraScript();
}
};
class spell_eternal_darkness_dmg : public SpellScriptLoader
{
public:
spell_eternal_darkness_dmg() : SpellScriptLoader("spell_eternal_darkness_dmg")
{}
class spell_eternal_darkness_dmg_AuraScript : public AuraScript
{
public:
PrepareAuraScript(spell_eternal_darkness_dmg_AuraScript);
void HandleStacks(AuraEffect const* /**/)
{
if (!GetCaster())
return;
GetCaster()->CastSpell(GetCaster(), SPELL_ETERNAL_DARKNESS_BUFF, true);
}
void Register() override
{
OnEffectPeriodic += AuraEffectPeriodicFn(spell_eternal_darkness_dmg_AuraScript::HandleStacks, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE);
}
};
AuraScript* GetAuraScript() const
{
return new spell_eternal_darkness_dmg_AuraScript();
}
};
class at_shadow_crash : public AreaTriggerEntityScript
{
public:
at_shadow_crash() : AreaTriggerEntityScript("at_shadow_crash")
{}
struct at_shadow_crash_AI : public AreaTriggerAI
{
at_shadow_crash_AI(AreaTrigger* area) : AreaTriggerAI(area)
{
}
void OnUnitEnter(Unit* unit) override
{
if (unit && unit->GetTypeId() == TYPEID_PLAYER)
unit->CastSpell(unit, SPELL_SHADOW_CRASH_AURA, true);
}
void OnUnitExit(Unit* unit) override
{
if (unit)
unit->RemoveAurasDueToSpell(SPELL_SHADOW_CRASH_AURA);
}
void OnRemove() override
{
if (Unit* kaahrj = at->FindNearestCreature(101950, 250.0f, true))
{
if (kaahrj->GetMap()->IsHeroic())
kaahrj->CastSpell(at->GetPositionX(), at->GetPositionY(), at->GetPositionZ(), SPELL_COLLAPSING_SHADOWS, true);
}
}
};
AreaTriggerAI* GetAI(AreaTrigger* areatrigger) const override
{
return new at_shadow_crash_AI(areatrigger);
}
};
class at_collapsing_shadow : public AreaTriggerEntityScript
{
public:
at_collapsing_shadow() : AreaTriggerEntityScript("at_collapsing_shadow")
{
}
struct at_collapsing_shadow_AI : public AreaTriggerAI
{
at_collapsing_shadow_AI(AreaTrigger* at) : AreaTriggerAI(at)
{
}
void OnUnitEnter(Unit* unit) override
{
if (unit && unit->GetTypeId() == TYPEID_PLAYER)
unit->CastSpell(unit, SPELL_COLLAPSING_SHADOWS_DMG, true);
}
void OnUnitExit(Unit* unit) override
{
if (unit)
unit->RemoveAurasDueToSpell(SPELL_COLLAPSING_SHADOWS_DMG);
}
};
AreaTriggerAI* GetAI(AreaTrigger* areatrigger) const override
{
return new at_collapsing_shadow_AI(areatrigger);
}
};
void AddSC_boss_mind_flayer_kaarhj()
{
new npc_faceless_tendril();
new boss_mind_flayer_kaarhj();
new spell_shadow_crash();
new spell_eternal_darkness();
new spell_eternal_darkness_dmg();
new at_shadow_crash();
new at_collapsing_shadow();
}
| gpl-2.0 |
kennknowles/scmnote | src/main.cpp | 4142 | /*
This file is part of scmnote - A scheme music system
Copyright (C) 2002 Free Software Foundation, Inc
scmnote is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
scmnote 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 scmnote; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <string>
#include <iostream>
#include <fstream>
#include <libguile.h>
#include "ScmNote.hpp"
#include "MidiFile.hpp"
#include "cmdline.h"
#include "debug.hpp"
using namespace scmnote;
void main_func( void* closure, int argc, char* argv[] )
{
cerr.setf( ios::unitbuf );
cout.setf( ios::unitbuf );
ostream* outstream;
string outFilename;
string inFilename;
gengetopt_args_info args_info;
if ( cmdline_parser( argc, argv, &args_info ) != 0 )
exit(1);
if ( args_info.inputs_num != 1 )
{
cerr << "Must supply exactly 1 filename\n";
cmdline_parser_print_help();
exit(1);
}
inFilename = args_info.inputs[0];
if ( args_info.stdout_given )
{
if ( args_info.out_file_given )
{
cerr << "Cannot specify both -s and -o\n";
}
else
{
outstream = &cout;
}
}
else
{
if ( args_info.out_file_given )
{
outFilename = args_info.out_file_arg;
}
else
{
DEBUG_MSG( "infile is " << inFilename << endl );
int lastSlash = inFilename.rfind("/");
if ( lastSlash < 0 )
{
lastSlash = -1;
DEBUG_MSG( "No slash found" );
}
else
{
DEBUG_MSG( "Slash found at position " << lastSlash << endl );
}
string inFileprefix = inFilename.substr( lastSlash+1,
inFilename.rfind(".")
- lastSlash - 1);
outFilename = inFileprefix + ".mid";
DEBUG_MSG( "outfile is " << outFilename<< "\n" );
}
outstream = new ofstream( outFilename.c_str(), ios::out );
}
DEBUG_MSG( "...?\n" );
MidiFile* midiFile = ScmNote::ReadScmSong( inFilename );
DEBUG_MSG( "...!\n" );
midiFile->Emit( *outstream );
}
int main( int argc, char* argv[] )
{
scm_boot_guile( argc, argv, main_func, 0 );
}
/*
#include <iostream>
#include <fstream>
void write16( ostream& outfile, long val )
{
outfile.put( (val & 0xFF00) >> 8 );
outfile.put( val & 0x00FF );
}
void write32( ostream& outfile, long val )
{
write16( outfile, (val & 0xFFFF0000) >> 16 );
write16( outfile, val & 0x0000FFFF );
}
void headerChunk( ostream& outfile )
{
// output type "MThd"
// we don't want trailing 0's in these files!!
outfile << "MThd";
// The length of the header chunk, a 32 bit number, value always 6
write32( outfile, 6 );
// Format of file, 16 bits
// For this program, always 0 (one track)
write16( outfile, 0 );
//Number of tracks, always one for format zero
write16( outfile, 1 );
//Default division... MSB 0 -> tick per quarter note in the other 15 bits
// This should be 1 second per quarter note
write16( outfile, 120 );
}
void trackChunk( ostream& outfile )
{
// type "MTrk"
outfile << "MTrk";
// length in bytes... will calculate later :)
//
write32( outfile, 8 );
// 4 bytes for each event = 8
// delta time of 0;
outfile.put( 0 );
// note on event
// 9 is required, 0 is the track number
outfile.put( 0x90 );
// key which was pressed, 3c = middle c
outfile.put( 0x3c );
// velocity, 40 = mezzo forte according to the docs
outfile.put( 0x40 );
// delta time of 100;
outfile.put( 120 );
// note off event
// id number 8, track 0
outfile.put( 0x80 );
// key
outfile.put( 0x3c );
// release velocity, 40 = default for insensitive stuff
outfile.put( 0x40 );
}
int main( int argc, char* argv[] )
{
ostream* outfile = &cout;
headerChunk( *outfile );
trackChunk( *outfile );
}
*/
| gpl-2.0 |
xhunterx89/shop_Joomla | components/com_jshopping/templates/default/search/form.php | 2561 | <script type="text/javascript">var liveurl = '<?php print JURI::root()?>';</script>
<div class="jshop">
<h1><?php print _JSHOP_SEARCH ?></h1>
<form action = "<?php print $this->action?>" name = "form_ad_search" method = "post" onsubmit = "return validateFormAdvancedSearch('form_ad_search')">
<input type="hidden" name="setsearchdata" value="1">
<table class = "jshop" cellpadding = "6" cellspacing="0">
<tr>
<td width="120">
<?php print _JSHOP_SEARCH_TEXT?>
</td>
<td>
<input type = "text" name = "search" class = "inputbox" style = "width:300px" />
</td>
</tr>
<tr>
<td>
<?php print _JSHOP_SEARCH_CATEGORIES ?>
</td>
<td>
<?php print $this->list_categories ?><br />
<input type = "checkbox" name = "include_subcat" id = "include_subcat" value = "1" />
<label for = "include_subcat"><?php print _JSHOP_SEARCH_INCLUDE_SUBCAT ?></label>
</td>
</tr>
<tr>
<td>
<?php print _JSHOP_SEARCH_MANUFACTURERS ?>
</td>
<td>
<?php print $this->list_manufacturers ?>
</td>
</tr>
<tr>
<td>
<?php print _JSHOP_SEARCH_PRICE_FROM ?>
</td>
<td>
<input type = "text" class = "inputbox" name = "price_from" id = "price_from" /> <?php print $this->config->currency_code?>
</td>
</tr>
<tr>
<td>
<?php print _JSHOP_SEARCH_PRICE_TO ?>
</td>
<td>
<input type = "text" class = "inputbox" name = "price_to" id = "price_to" /> <?php print $this->config->currency_code?>
</td>
</tr>
<tr>
<td>
<?php print _JSHOP_SEARCH_DATE_FROM ?>
</td>
<td>
<?php echo JHTML::_('calendar','', 'date_from', 'date_from', '%Y-%m-%d', array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?>
</td>
</tr>
<tr>
<td>
<?php print _JSHOP_SEARCH_DATE_TO ?>
</td>
<td>
<?php echo JHTML::_('calendar','', 'date_to', 'date_to', '%Y-%m-%d', array('class'=>'inputbox', 'size'=>'25', 'maxlength'=>'19')); ?>
</td>
</tr>
<tr>
<td colspan="2" id="list_characteristics"><?php print $this->characteristics?></td>
</tr>
</table>
<div style="padding:6px;">
<input type = "submit" class="button" value = "<?php print _JSHOP_SEARCH ?>" />
</div>
</form>
</div> | gpl-2.0 |
imran031387/Drupal-8-Content-Store | sites/default/files/php/twig/79904dbd_field--node--uid.html.twig_b7b6f46499a0c3197a619cb5d66ad236d34b5473f08e97962c2cc3d7fe576cd2/f1399d1ef14c19dffce274d47887f3603ddff48852a73781c9712383c14a410f.php | 3509 | <?php
/* core/themes/classy/templates/field/field--node--uid.html.twig */
class __TwigTemplate_74e6367c9fc91b5220f56bcd0bd813119718ff75a39fea1893e45b8f82258884 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 23
$context["classes"] = array(0 => "field", 1 => ("field--name-" . \Drupal\Component\Utility\Html::getClass( // line 25
(isset($context["field_name"]) ? $context["field_name"] : null))), 2 => ("field--type-" . \Drupal\Component\Utility\Html::getClass( // line 26
(isset($context["field_type"]) ? $context["field_type"] : null))), 3 => ("field--label-" . // line 27
(isset($context["label_display"]) ? $context["label_display"] : null)));
// line 30
echo "<span";
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true);
echo ">";
// line 31
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["items"]) ? $context["items"] : null));
foreach ($context['_seq'] as $context["_key"] => $context["item"]) {
// line 32
echo $this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute($context["item"], "content", array()), "html", null, true);
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 34
echo "</span>
";
}
public function getTemplateName()
{
return "core/themes/classy/templates/field/field--node--uid.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 38 => 34, 32 => 32, 28 => 31, 24 => 30, 22 => 27, 21 => 26, 20 => 25, 19 => 23,);
}
}
/* {#*/
/* /***/
/* * @file*/
/* * Theme override for the node user field.*/
/* **/
/* * This is an override of field.html.twig for the node user field. See that*/
/* * template for documentation about its details and overrides.*/
/* **/
/* * Available variables:*/
/* * - attributes: HTML attributes for the containing span element.*/
/* * - items: List of all the field items. Each item contains:*/
/* * - attributes: List of HTML attributes for each item.*/
/* * - content: The field item content.*/
/* * - entity_type: The entity type to which the field belongs.*/
/* * - field_name: The name of the field.*/
/* * - field_type: The type of the field.*/
/* * - label_display: The display settings for the label.*/
/* **/
/* * @see field.html.twig*/
/* *//* */
/* #}*/
/* {%*/
/* set classes = [*/
/* 'field',*/
/* 'field--name-' ~ field_name|clean_class,*/
/* 'field--type-' ~ field_type|clean_class,*/
/* 'field--label-' ~ label_display,*/
/* ]*/
/* %}*/
/* <span{{ attributes.addClass(classes) }}>*/
/* {%- for item in items -%}*/
/* {{ item.content }}*/
/* {%- endfor -%}*/
/* </span>*/
/* */
| gpl-2.0 |
Adiss/wowserver | src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp | 16763 | /*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Comment: The event with the Living Mojos is not implemented, just is done that when one of the mojos around the boss take damage will make the boss enter in combat!
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "gundrak.h"
#include "SpellInfo.h"
enum Spells
{
SPELL_EMERGE = 54850,
SPELL_ELEMENTAL_SPAWN_EFFECT = 54888,
SPELL_MOJO_VOLLEY = 54849,
SPELL_SURGE_VISUAL = 54827,
SPELL_MERGE = 54878,
SPELL_MIGHTY_BLOW = 54719,
SPELL_SURGE = 54801,
SPELL_FREEZE_ANIM = 16245,
SPELL_MOJO_PUDDLE = 55627,
SPELL_MOJO_WAVE = 55626,
};
enum ColossusEvents
{
EVENT_MIGHTY_BLOW = 1,
};
enum ColossusActions
{
ACTION_SUMMON_ELEMENTAL = 1,
ACTION_FREEZE_COLOSSUS = 2,
ACTION_UNFREEZE_COLOSSUS = 3,
};
enum ColossusPhases
{
COLOSSUS_PHASE_NORMAL = 1,
COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON = 2,
COLOSSUS_PHASE_SECOND_ELEMENTAL_SUMMON = 3
};
enum ColossusData
{
DATA_COLOSSUS_PHASE = 1,
DATA_INTRO_DONE = 2
};
enum ElementalActions
{
ACTION_RETURN_TO_COLOSSUS = 1
};
enum ElementalEvents
{
EVENT_SURGE = 1
};
class boss_drakkari_colossus : public CreatureScript
{
public:
boss_drakkari_colossus() : CreatureScript("boss_drakkari_colossus") { }
struct boss_drakkari_colossusAI : public BossAI
{
boss_drakkari_colossusAI(Creature* creature) : BossAI(creature, DATA_DRAKKARI_COLOSSUS_EVENT)
{
me->SetReactState(REACT_PASSIVE);
introDone = false;
}
void InitializeAI() OVERRIDE
{
if (!me->isDead())
Reset();
}
void Reset() OVERRIDE
{
_Reset();
if (GetData(DATA_INTRO_DONE))
{
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
me->RemoveAura(SPELL_FREEZE_ANIM);
}
//events.Reset(); -> done in _Reset();
events.ScheduleEvent(EVENT_MIGHTY_BLOW, urand(10000, 30000));
phase = COLOSSUS_PHASE_NORMAL;
// Note: This should not be called, but before use SetBossState function we should use BossAI
// in all the bosses of the instance
instance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, NOT_STARTED);
}
void EnterCombat(Unit* /*who*/) OVERRIDE
{
_EnterCombat();
me->RemoveAura(SPELL_FREEZE_ANIM);
// Note: This should not be called, but before use SetBossState function we should use BossAI
// in all the bosses of the instance
instance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, IN_PROGRESS);
}
void JustDied(Unit* /*killer*/) OVERRIDE
{
_JustDied();
// Note: This should not be called, but before use SetBossState function we should use BossAI
// in all the bosses of the instance
instance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, DONE);
}
void JustReachedHome() OVERRIDE
{
// Note: This should not be called, but before use SetBossState function we should use BossAI
// in all the bosses of the instance
instance->SetData(DATA_DRAKKARI_COLOSSUS_EVENT, FAIL);
}
void DoAction(int32 action) OVERRIDE
{
switch (action)
{
case ACTION_SUMMON_ELEMENTAL:
DoCast(SPELL_EMERGE);
break;
case ACTION_FREEZE_COLOSSUS:
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveIdle();
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
DoCast(me, SPELL_FREEZE_ANIM);
break;
case ACTION_UNFREEZE_COLOSSUS:
if (me->GetReactState() == REACT_AGGRESSIVE)
return;
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
me->RemoveAura(SPELL_FREEZE_ANIM);
me->SetInCombatWithZone();
if (me->GetVictim())
me->GetMotionMaster()->MoveChase(me->GetVictim(), 0, 0);
break;
}
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) OVERRIDE
{
if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC))
damage = 0;
if (phase == COLOSSUS_PHASE_NORMAL ||
phase == COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON)
{
if (HealthBelowPct( phase == COLOSSUS_PHASE_NORMAL ? 50 : 5))
{
damage = 0;
phase = (phase == COLOSSUS_PHASE_NORMAL ? COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON : COLOSSUS_PHASE_SECOND_ELEMENTAL_SUMMON);
DoAction(ACTION_FREEZE_COLOSSUS);
DoAction(ACTION_SUMMON_ELEMENTAL);
}
}
}
uint32 GetData(uint32 data) const OVERRIDE
{
if (data == DATA_COLOSSUS_PHASE)
return phase;
else if (data == DATA_INTRO_DONE)
return introDone;
return 0;
}
void SetData(uint32 type, uint32 data) OVERRIDE
{
if (type == DATA_INTRO_DONE)
introDone = data;
}
void UpdateAI(uint32 diff) OVERRIDE
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_MIGHTY_BLOW:
DoCastVictim(SPELL_MIGHTY_BLOW);
events.ScheduleEvent(EVENT_MIGHTY_BLOW, urand(5000, 15000));
break;
}
}
if (me->GetReactState() == REACT_AGGRESSIVE)
DoMeleeAttackIfReady();
}
void JustSummoned(Creature* summon) OVERRIDE
{
summon->SetInCombatWithZone();
if (phase == COLOSSUS_PHASE_SECOND_ELEMENTAL_SUMMON)
summon->SetHealth(summon->GetMaxHealth() / 2);
}
private:
uint8 phase;
bool introDone;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetInstanceAI<boss_drakkari_colossusAI>(creature);
}
};
class boss_drakkari_elemental : public CreatureScript
{
public:
boss_drakkari_elemental() : CreatureScript("boss_drakkari_elemental") { }
struct boss_drakkari_elementalAI : public ScriptedAI
{
boss_drakkari_elementalAI(Creature* creature) : ScriptedAI(creature)
{
DoCast(me, SPELL_ELEMENTAL_SPAWN_EFFECT);
instance = creature->GetInstanceScript();
}
void Reset() OVERRIDE
{
events.Reset();
events.ScheduleEvent(EVENT_SURGE, urand(5000, 15000));
me->AddAura(SPELL_MOJO_VOLLEY, me);
}
void JustDied(Unit* killer) OVERRIDE
{
if (killer == me)
return;
if (Creature* colossus = Unit::GetCreature(*me, instance->GetData64(DATA_DRAKKARI_COLOSSUS)))
killer->Kill(colossus);
}
void UpdateAI(uint32 diff) OVERRIDE
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SURGE:
DoCast(SPELL_SURGE_VISUAL);
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true))
DoCast(target, SPELL_SURGE);
events.ScheduleEvent(EVENT_SURGE, urand(5000, 15000));
break;
}
}
DoMeleeAttackIfReady();
}
void DoAction(int32 action) OVERRIDE
{
switch (action)
{
case ACTION_RETURN_TO_COLOSSUS:
DoCast(SPELL_SURGE_VISUAL);
if (Creature* colossus = Unit::GetCreature(*me, instance->GetData64(DATA_DRAKKARI_COLOSSUS)))
// what if the elemental is more than 80 yards from drakkari colossus ?
DoCast(colossus, SPELL_MERGE, true);
break;
}
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) OVERRIDE
{
if (HealthBelowPct(50) && instance)
{
if (Creature* colossus = Unit::GetCreature(*me, instance->GetData64(DATA_DRAKKARI_COLOSSUS)))
{
if (colossus->AI()->GetData(DATA_COLOSSUS_PHASE) == COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON)
{
damage = 0;
// to prevent spell spaming
if (me->HasUnitState(UNIT_STATE_CHARGING))
return;
// not sure about this, the idea of this code is to prevent bug the elemental
// if it is not in a acceptable distance to cast the charge spell.
/*if (me->GetDistance(colossus) > 80.0f)
{
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
return;
me->GetMotionMaster()->MovePoint(0, colossus->GetPositionX(), colossus->GetPositionY(), colossus->GetPositionZ());
return;
}*/
DoAction(ACTION_RETURN_TO_COLOSSUS);
}
}
}
}
void EnterEvadeMode() OVERRIDE
{
me->DespawnOrUnsummon();
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) OVERRIDE
{
if (spell->Id == SPELL_MERGE)
{
if (Creature* colossus = target->ToCreature())
{
colossus->AI()->DoAction(ACTION_UNFREEZE_COLOSSUS);
me->DespawnOrUnsummon();
}
}
}
private:
EventMap events;
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetInstanceAI<boss_drakkari_elementalAI>(creature);
}
};
class npc_living_mojo : public CreatureScript
{
public:
npc_living_mojo() : CreatureScript("npc_living_mojo") { }
CreatureAI* GetAI(Creature* creature) const OVERRIDE
{
return GetInstanceAI<npc_living_mojoAI>(creature);
}
struct npc_living_mojoAI : public ScriptedAI
{
npc_living_mojoAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
void Reset() OVERRIDE
{
mojoWaveTimer = 2*IN_MILLISECONDS;
mojoPuddleTimer = 7*IN_MILLISECONDS;
}
void MoveMojos(Creature* boss)
{
std::list<Creature*> mojosList;
boss->GetCreatureListWithEntryInGrid(mojosList, me->GetEntry(), 12.0f);
if (!mojosList.empty())
{
for (std::list<Creature*>::const_iterator itr = mojosList.begin(); itr != mojosList.end(); ++itr)
{
if (Creature* mojo = *itr)
mojo->GetMotionMaster()->MovePoint(1, boss->GetHomePosition().GetPositionX(), boss->GetHomePosition().GetPositionY(), boss->GetHomePosition().GetPositionZ());
}
}
}
void MovementInform(uint32 type, uint32 id) OVERRIDE
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
if (Creature* colossus = Unit::GetCreature(*me, instance->GetData64(DATA_DRAKKARI_COLOSSUS)))
{
colossus->AI()->DoAction(ACTION_UNFREEZE_COLOSSUS);
if (!colossus->AI()->GetData(DATA_INTRO_DONE))
colossus->AI()->SetData(DATA_INTRO_DONE, true);
colossus->SetInCombatWithZone();
me->DespawnOrUnsummon();
}
}
}
void AttackStart(Unit* attacker) OVERRIDE
{
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
return;
// we do this checks to see if the creature is one of the creatures that sorround the boss
if (Creature* colossus = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_DRAKKARI_COLOSSUS)))
{
Position homePosition = me->GetHomePosition();
Position colossusHomePosition = colossus->GetHomePosition();
float distance = homePosition.GetExactDist(colossusHomePosition.GetPositionX(), colossusHomePosition.GetPositionY(), colossusHomePosition.GetPositionZ());
if (distance < 12.0f)
{
MoveMojos(colossus);
me->SetReactState(REACT_PASSIVE);
}
else
ScriptedAI::AttackStart(attacker);
}
}
void UpdateAI(uint32 diff) OVERRIDE
{
//Return since we have no target
if (!UpdateVictim())
return;
if (mojoWaveTimer <= diff)
{
DoCastVictim(SPELL_MOJO_WAVE);
mojoWaveTimer = 15*IN_MILLISECONDS;
} else mojoWaveTimer -= diff;
if (mojoPuddleTimer <= diff)
{
DoCastVictim(SPELL_MOJO_PUDDLE);
mojoPuddleTimer = 18*IN_MILLISECONDS;
} else mojoPuddleTimer -= diff;
DoMeleeAttackIfReady();
}
private:
InstanceScript* instance;
uint32 mojoWaveTimer;
uint32 mojoPuddleTimer;
};
};
void AddSC_boss_drakkari_colossus()
{
new boss_drakkari_colossus();
new boss_drakkari_elemental();
new npc_living_mojo();
}
| gpl-2.0 |
skyne/NeoCore | src/bindings/scripts/scripts/zone/alterac_valley/boss_drekthar.cpp | 4556 | /* Copyright (C) 2006 - 2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_DrekThar
SD%Complete: 50%
SDComment: Some spells listed on wowwiki but doesn't exist on wowhead
EndScriptData */
#include "precompiled.h"
#define YELL_AGGRO -2100000
#define YELL_EVADE -2100001
#define YELL_RESPAWN -2100002
#define YELL_RANDOM1 -2100003
#define YELL_RANDOM2 -2100004
#define YELL_RANDOM3 -2100005
#define YELL_RANDOM4 -2100006
#define YELL_RANDOM5 -2100007
#define SPELL_WHIRLWIND 15589
#define SPELL_WHIRLWIND2 13736
#define SPELL_KNOCKDOWN 19128
#define SPELL_FRENZY 8269
#define SPELL_SWEEPING_STRIKES 18765 // not sure
#define SPELL_CLEAVE 20677 // not sure
#define SPELL_WINDFURY 35886 // not sure
#define SPELL_STORMPIKE 51876 // not sure
struct NEO_DLL_DECL boss_drektharAI : public ScriptedAI
{
boss_drektharAI(Creature *c) : ScriptedAI(c) {}
uint32 WhirlwindTimer;
uint32 Whirlwind2Timer;
uint32 KnockdownTimer;
uint32 FrenzyTimer;
uint32 YellTimer;
uint32 ResetTimer;
void Reset()
{
WhirlwindTimer = (rand()%20)*1000;
Whirlwind2Timer = (rand()%25)*1000;
KnockdownTimer = 12000;
FrenzyTimer = 6000;
ResetTimer = 5000;
YellTimer = (20+rand()%10)*1000; //20 to 30 seconds
}
void Aggro(Unit *who)
{
DoScriptText(YELL_AGGRO, m_creature);
}
void JustRespawned()
{
Reset();
DoScriptText(YELL_RESPAWN, m_creature);
}
void KilledUnit(Unit* victim){}
void JustDied(Unit* Killer){}
void UpdateAI(const uint32 diff)
{
if(!UpdateVictim())
return;
if (WhirlwindTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_WHIRLWIND);
WhirlwindTimer = (8+rand()%10)*1000;
}else WhirlwindTimer -= diff;
if (Whirlwind2Timer < diff)
{
DoCast(m_creature->getVictim(), SPELL_WHIRLWIND2);
Whirlwind2Timer = (7+rand()%18)*1000;
}else Whirlwind2Timer -= diff;
if (KnockdownTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_KNOCKDOWN);
KnockdownTimer = (10+rand()%5)*1000;
}else KnockdownTimer -= diff;
if (FrenzyTimer < diff)
{
DoCast(m_creature->getVictim(), SPELL_FRENZY);
FrenzyTimer = (20+rand()%5)*1000;
}else FrenzyTimer -= diff;
if (YellTimer < diff) {
switch(rand()%4)
{
case 0: DoScriptText(YELL_RANDOM1, m_creature); break;
case 1: DoScriptText(YELL_RANDOM2, m_creature); break;
case 2: DoScriptText(YELL_RANDOM3, m_creature); break;
case 3: DoScriptText(YELL_RANDOM4, m_creature); break;
case 4: DoScriptText(YELL_RANDOM5, m_creature); break;
}
YellTimer = (20+rand()%10)*1000; //20 to 30 seconds
} else YellTimer -= diff;
// check if creature is not outside of building
if(ResetTimer < diff)
{
float x, y, z;
m_creature->GetPosition(x, y, z);
if(y < -260)
{
DoScriptText(YELL_EVADE, m_creature);
EnterEvadeMode();
}
ResetTimer = 5000;
}else ResetTimer -= diff;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_drekthar(Creature *_Creature)
{
return new boss_drektharAI (_Creature);
}
void AddSC_boss_drekthar()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_drekthar";
newscript->GetAI = &GetAI_boss_drekthar;
newscript->RegisterSelf();
}
| gpl-2.0 |
cguebert/Panda | core/panda/graphview/LinkTag.cpp | 4531 | #include <panda/graphview/LinkTag.h>
#include <panda/graphview/GraphView.h>
#include <panda/graphview/Viewport.h>
#include <panda/graphview/ObjectRenderersList.h>
#include <panda/graphview/object/ObjectRenderer.h>
#include <panda/data/BaseData.h>
namespace panda
{
using types::Point;
using types::Rect;
namespace graphview
{
LinkTag::LinkTag(GraphView& view, BaseData* input, BaseData* output, int index)
: m_index(index)
, m_parentView(view)
, m_inputData(input)
{
m_outputDatas.emplace(output, std::make_pair(Rect(),Rect()));
}
void LinkTag::addOutput(BaseData* output)
{
if(!m_outputDatas.count(output))
m_outputDatas.emplace(output, std::make_pair(Rect(),Rect()));
}
void LinkTag::removeOutput(BaseData* output)
{
m_outputDatas.erase(output);
}
void LinkTag::update()
{
Rect dataRect;
auto objRnd = m_parentView.objectRenderers().get(m_inputData->getOwner());
if (!objRnd)
return;
objRnd->getDataRect(m_inputData, dataRect);
m_inputDataRects.first = Rect::fromSize(dataRect.right() + tagMargin,
dataRect.center().y - tagH / 2.f,
static_cast<float>(tagW), static_cast<float>(tagH));
m_inputDataRects.second = dataRect;
float ix = dataRect.center().x;
for (auto it = m_outputDatas.begin(); it != m_outputDatas.end();)
{
objRnd = m_parentView.objectRenderers().get(it->first->getOwner());
if (!objRnd)
continue;
objRnd->getDataRect(it->first, dataRect);
float ox = dataRect.center().x;
if (!needLinkTag(ix, ox, m_parentView))
it = m_outputDatas.erase(it);
else
{
Rect tagRect = Rect::fromSize(dataRect.left() - tagW - tagMargin,
dataRect.center().y - tagH / 2.f,
static_cast<float>(tagW), static_cast<float>(tagH));
it->second.first = tagRect;
it->second.second = dataRect;
++it;
}
}
}
bool LinkTag::isEmpty()
{
return m_outputDatas.empty();
}
std::pair<BaseData*, types::Rect> LinkTag::getDataAtPoint(const Point& point)
{
if (m_inputDataRects.first.contains(point))
return { m_inputData, m_inputDataRects.first };
for(auto rect : m_outputDatas)
if(rect.second.first.contains(point))
return std::make_pair(rect.first, rect.second.first);
return { nullptr, Rect() };
}
void LinkTag::moveView(const Point& delta)
{
m_inputDataRects.first.translate(delta);
m_inputDataRects.second.translate(delta);
for (auto& rect : m_outputDatas)
{
rect.second.first.translate(delta);
rect.second.second.translate(delta);
}
}
void LinkTag::draw(graphics::DrawList& list, graphics::DrawColors& colors)
{
if(m_hovering)
{
// Draw as links
auto inputCenter = m_inputDataRects.second.center();
for(const auto& tagRect : m_outputDatas)
{
auto outputCenter = tagRect.second.second.center();
auto w = Point((outputCenter.x - inputCenter.x) / 2, 0);
list.addBezierCurve(inputCenter, inputCenter + w, outputCenter - w, outputCenter, colors.highlightColor, 3.0f);
}
// Draw the data rectangles
const auto& rect = m_inputDataRects.second;
list.addRectFilled(rect, colors.highlightColor);
list.addRect(rect, colors.penColor);
for (const auto& tagRect : m_outputDatas)
{
const auto& tr = tagRect.second.second;
list.addRectFilled(tr, colors.highlightColor);
list.addRect(tr, colors.penColor);
}
}
auto indexText = std::to_string(m_index + 1);
const float fontScale = 0.85f;
// input
auto inputRect = m_inputDataRects.first;
float x = inputRect.left();
float cy = inputRect.center().y;
list.addLine(Point(x - tagMargin, cy), Point(x, cy), colors.penColor);
list.addRectFilled(inputRect, colors.lightColor);
list.addRect(inputRect, colors.penColor);
list.addText(inputRect, indexText, colors.penColor, graphics::DrawList::Align_Center, fontScale);
// outputs
for(const auto& tagRectPair : m_outputDatas)
{
const auto& tagRect = tagRectPair.second.first;
x = tagRect.right();
cy = tagRect.center().y;
list.addLine(Point(x, cy), Point(x + tagMargin, cy), colors.penColor);
list.addRectFilled(tagRect, colors.lightColor);
list.addRect(tagRect, colors.penColor);
list.addText(tagRect, indexText, colors.penColor, graphics::DrawList::Align_Center, fontScale);
}
}
bool LinkTag::needLinkTag(float inputX, float outputX, GraphView& view)
{
return outputX <= inputX || outputX > inputX + view.viewport().viewSize().x * 2 / 3;
}
std::vector<BaseData*> LinkTag::getOutputDatas() const
{
std::vector<BaseData*> res;
for (const auto dataRect : m_outputDatas)
res.push_back(dataRect.first);
return res;
}
} // namespace graphview
} // namespace panda
| gpl-2.0 |
javascriptpotato/lotogenerator | lotogen.js | 476 | function loto(count, min, max) {
var arr = [];
for (var i = 0; i < count; i++) {
do {
var newNum = getInRange(min, max);
}
while (arr.indexOf(newNum) !== -1)
arr.push(newNum)
}
return arr;
}
function getInRange(min, max) {
return Math.floor(Math.random() * (max-min))+min;
}
document.write('<br/>');
document.write("Your lucky numbers are: ");
document.write(loto(6, 1, 49));
document.write('<br/>');
| gpl-2.0 |
nbrouse-deep/chefmatefrontburner_com | wp-content/themes/chefmate/fb-business-tips.php | 4354 | <!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<title><?php echo (is_home() || is_front_page()) ? bloginfo('name') : wp_title('| ', true, 'right'); ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php wp_head(); ?>
<script src="//use.typekit.net/kvr7che.js"></script>
<script>try{Typekit.load();}catch(e){}</script>
</head>
<body data-spy="scroll" data-target=".nav-collapse" data-offset="<?php echo get_option('scroll_link', '270'); ?>" <?php body_class(); ?>>
<div class="body-wrapper fb-tips">
<div id="header" class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn responsive-menu pull-right" data-toggle="collapse" data-target=".nav-collapse"><i class='icon-menu-1'></i></a>
<a class="brand" href="<?php echo home_url(); ?>">
<?php if( get_theme_mod('custom_logo') ) : ?>
<img src="<?php echo get_theme_mod('custom_logo'); ?>" alt="<?php echo get_theme_mod('custom_logo_alt_text'); ?>" />
<?php
else :
echo bloginfo('title');
endif;
?>
</a>
<div class="nav-collapse pull-right collapse">
<?php
if ( has_nav_menu( 'primary' ) ) {
$args = array(
'theme_location' => 'primary',
'container' => false,
'menu_id' => 'main_menu',
'menu_class' => 'nav',
'walker' => new Bootstrap_Walker_Nav_Menu()
);
wp_nav_menu($args);
}
?>
</div>
</div>
</div>
</div>
<?php
the_post();
$format = get_post_format();
if( false === $format || $format == 'standard' ) $format = 'image';
?>
<div <?php post_class('post'); ?>>
<div class="dark-wrapper">
<div class="tips-bg"></div>
<div class="container tips">
<div class="theinnercontainer">
<h1 class="center sub-header">True to you business tips</h1>
</div>
</div>
<div class="theinnercontainer">
<div clas="row-fluid">
<?php
get_template_part('loop/post', 'meta');
?>
<?php the_title('<h4 class="post-title center room">', '</h4>'); ?>
</div>
<div class="row-fluid">
<div class="span10 offset1">
<div class="business-tips-content">
<?php the_content();
wp_link_pages();
?>
</div>
</div>
</div>
</div>
</div>
</div>
<footer class="footer">
<div class="brown">
<div class="theinnercontainer">
<div class="row-fluid">
<div class="span9">
<h3>ORDERING <span style="font-style:italic;">CHEF-MATE</span> PRODUCTS IS EASY. START TODAY.</h3>
</div>
<div class="span3 hidden-phone">
<?php echo do_shortcode('[ninja-popup id=687]<div class="footer-contact-btn">Contact Us ›</div>[/ninja-popup]'); ?>
</div>
<div class="span3 visible-phone">
<a href="/contact-us/"><div class="footer-contact-btn">
Contact Us ›</div></a>
</div>
</div>
</div>
</div>
<div class="theinnercontainer">
<div class="row-fluid footerlogos">
<div class="span3">
<a href="https://www.nestleprofessional.com" target="_blank" ><img src="/wp-content/uploads/2014/10/nestle-logo.png" /></a>
</div>
<div class="span6">
<p class="terms"><a href="https://www.nestleprofessional.com/united-states/en/SiteArticles/Pages/PrivacyPolicy.aspx" target="_blank">Privacy Policy </a>| <a href="https://www.nestleprofessional.com/united-states/en/SiteArticles/Pages/TermsAndConditions.aspx?UrlReferrer=https%3a%2f%2fbasecamp.com%2f2175826%2fprojects%2f5040546%2fdocuments%2f7176368&UrlReferrer=https%3a%2f%2fbasecamp.com%2f2175826%2fpeople%2f8120761%2foutstanding_todos" target="_blank">Terms & Conditions </a> | <img src="/wp-content/uploads/2014/10/truste.png" /></p>
</div>
<div class="span3 cheflogofoot">
<a href="/"><img src="/wp-content/uploads/2014/10/chefmate-logo.png" /></a>
</div>
</div>
<div class="row-fluid trademark">
<p>All trademarks and other intellectual properties on this site are owned by Société des Produits Nestlé S.A., Vevey, Switzerland.</p>
</div>
</div>
</footer> | gpl-2.0 |
phire/Jedi-Outcast | code/icarus/TaskManager.cpp | 46875 | // Task Manager
//
// -- jweier
// this include must remain at the top of every Icarus CPP file
#include "icarus.h"
#include <assert.h>
#define ICARUS_VALIDATE(a) if ( a == false ) return TASK_FAILED;
/*
=================================================
CTask
=================================================
*/
CTask::CTask( void )
{
}
CTask::~CTask( void )
{
}
CTask *CTask::Create( int GUID, CBlock *block )
{
CTask *task = new CTask;
//TODO: Emit warning
assert( task );
if ( task == NULL )
return NULL;
task->SetTimeStamp( 0 );
task->SetBlock( block );
task->SetGUID( GUID );
return task;
}
/*
-------------------------
Free
-------------------------
*/
void CTask::Free( void )
{
//NOTENOTE: The block is not consumed by the task, it is the sequencer's job to clean blocks up
delete this;
}
/*
=================================================
CTaskGroup
=================================================
*/
CTaskGroup::CTaskGroup( void )
{
Init();
m_GUID = 0;
m_parent = NULL;
}
CTaskGroup::~CTaskGroup( void )
{
m_completedTasks.clear();
}
/*
-------------------------
SetGUID
-------------------------
*/
void CTaskGroup::SetGUID( int GUID )
{
m_GUID = GUID;
}
/*
-------------------------
Init
-------------------------
*/
void CTaskGroup::Init( void )
{
m_completedTasks.clear();
m_numCompleted = 0;
m_parent = NULL;
}
/*
-------------------------
Add
-------------------------
*/
int CTaskGroup::Add( CTask *task )
{
m_completedTasks[ task->GetGUID() ] = false;
return TASK_OK;
}
/*
-------------------------
MarkTaskComplete
-------------------------
*/
bool CTaskGroup::MarkTaskComplete( int id )
{
if ( (m_completedTasks.find( id )) != m_completedTasks.end() )
{
m_completedTasks[ id ] = true;
m_numCompleted++;
return true;
}
return false;
}
/*
=================================================
CTaskManager
=================================================
*/
CTaskManager::CTaskManager( void )
{
}
CTaskManager::~CTaskManager( void )
{
}
/*
-------------------------
Create
-------------------------
*/
CTaskManager *CTaskManager::Create( void )
{
return new CTaskManager;
}
/*
-------------------------
Init
-------------------------
*/
int CTaskManager::Init( CSequencer *owner )
{
//TODO: Emit warning
if ( owner == NULL )
return TASK_FAILED;
m_tasks.clear();
m_owner = owner;
m_ownerID = owner->GetOwnerID();
m_curGroup = NULL;
m_GUID = 0;
m_resident = false;
return TASK_OK;
}
/*
-------------------------
Free
-------------------------
*/
int CTaskManager::Free( void )
{
taskGroup_v::iterator gi;
tasks_l::iterator ti;
//Clear out all pending tasks
for ( ti = m_tasks.begin(); ti != m_tasks.end(); ti++ )
{
(*ti)->Free();
}
m_tasks.clear();
//Clear out all taskGroups
for ( gi = m_taskGroups.begin(); gi != m_taskGroups.end(); gi++ )
{
delete (*gi);
}
m_taskGroups.clear();
m_taskGroupNameMap.clear();
m_taskGroupIDMap.clear();
return TASK_OK;
}
/*
-------------------------
Flush
-------------------------
*/
int CTaskManager::Flush( void )
{
//FIXME: Rewrite
return true;
}
/*
-------------------------
AddTaskGroup
-------------------------
*/
CTaskGroup *CTaskManager::AddTaskGroup( const char *name )
{
CTaskGroup *group;
//Collect any garbage
taskGroupName_m::iterator tgni;
tgni = m_taskGroupNameMap.find( name );
if ( tgni != m_taskGroupNameMap.end() )
{
group = (*tgni).second;
//Clear it and just move on
group->Init();
return group;
}
//Allocate a new one
group = new CTaskGroup;;
//TODO: Emit warning
assert( group );
if ( group == NULL )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to allocate task group \"%s\"\n", name );
return NULL;
}
//Setup the internal information
group->SetGUID( m_GUID++ );
//Add it to the list and associate it for retrieval later
m_taskGroups.insert( m_taskGroups.end(), group );
m_taskGroupNameMap[ name ] = group;
m_taskGroupIDMap[ group->GetGUID() ] = group;
return group;
}
/*
-------------------------
GetTaskGroup
-------------------------
*/
CTaskGroup *CTaskManager::GetTaskGroup( const char *name )
{
taskGroupName_m::iterator tgi;
tgi = m_taskGroupNameMap.find( name );
if ( tgi == m_taskGroupNameMap.end() )
{
(m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Could not find task group \"%s\"\n", name );
return NULL;
}
return (*tgi).second;
}
CTaskGroup *CTaskManager::GetTaskGroup( int id )
{
taskGroupID_m::iterator tgi;
tgi = m_taskGroupIDMap.find( id );
if ( tgi == m_taskGroupIDMap.end() )
{
(m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Could not find task group \"%d\"\n", id );
return NULL;
}
return (*tgi).second;
}
/*
-------------------------
Update
-------------------------
*/
int CTaskManager::Update( void )
{
if ( (g_entities[m_ownerID].svFlags&SVF_ICARUS_FREEZE) )
{
return TASK_FAILED;
}
m_count = 0; //Needed for runaway init
m_resident = true;
int returnVal = Go();
m_resident = false;
return returnVal;
}
/*
-------------------------
IsRunning
-------------------------
*/
qboolean CTaskManager::IsRunning( void )
{
return ( m_tasks.empty() == false );
}
/*
-------------------------
Check
-------------------------
*/
inline bool CTaskManager::Check( int targetID, CBlock *block, int memberNum )
{
if ( (block->GetMember( memberNum ))->GetID() == targetID )
return true;
return false;
}
/*
-------------------------
GetFloat
-------------------------
*/
int CTaskManager::GetFloat( int entID, CBlock *block, int &memberNum, float &value )
{
char *name;
int type;
//See if this is a get() command replacement
if ( Check( ID_GET, block, memberNum ) )
{
//Update the member past the header id
memberNum++;
//get( TYPE, NAME )
type = (int) (*(float *) block->GetMemberData( memberNum++ ));
name = (char *) block->GetMemberData( memberNum++ );
//TODO: Emit warning
if ( type != TK_FLOAT )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return a non-FLOAT parameter!\n" );
return false;
}
return (m_owner->GetInterface())->I_GetFloat( entID, type, name, &value );
}
//Look for a random() inline call
if ( Check( ID_RANDOM, block, memberNum ) )
{
float min, max;
memberNum++;
min = *(float *) block->GetMemberData( memberNum++ );
max = *(float *) block->GetMemberData( memberNum++ );
value = (m_owner->GetInterface())->I_Random( min, max );
return true;
}
//Look for a tag() inline call
if ( Check( ID_TAG, block, memberNum ) )
{
(m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Invalid use of \"tag\" inline. Not a valid replacement for type FLOAT\n" );
return false;
}
CBlockMember *bm = block->GetMember( memberNum );
if ( bm->GetID() == TK_INT )
{
value = (float) (*(int *) block->GetMemberData( memberNum++ ));
}
else if ( bm->GetID() == TK_FLOAT )
{
value = *(float *) block->GetMemberData( memberNum++ );
}
else
{
assert(0);
(m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type FLOAT\n" );
return false;
}
return true;
}
/*
-------------------------
GetVector
-------------------------
*/
int CTaskManager::GetVector( int entID, CBlock *block, int &memberNum, vector_t &value )
{
char *name;
int type, i;
//See if this is a get() command replacement
if ( Check( ID_GET, block, memberNum ) )
{
//Update the member past the header id
memberNum++;
//get( TYPE, NAME )
type = (int) (*(float *) block->GetMemberData( memberNum++ ));
name = (char *) block->GetMemberData( memberNum++ );
//TODO: Emit warning
if ( type != TK_VECTOR )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return a non-VECTOR parameter!\n" );
}
return (m_owner->GetInterface())->I_GetVector( entID, type, name, value );
}
//Look for a random() inline call
if ( Check( ID_RANDOM, block, memberNum ) )
{
float min, max;
memberNum++;
min = *(float *) block->GetMemberData( memberNum++ );
max = *(float *) block->GetMemberData( memberNum++ );
for ( i = 0; i < 3; i++ )
{
value[i] = (float) (m_owner->GetInterface())->I_Random( min, max ); //FIXME: Just truncating it for now.. should be fine though
}
return true;
}
//Look for a tag() inline call
if ( Check( ID_TAG, block, memberNum ) )
{
char *tagName;
float tagLookup;
memberNum++;
ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName ) );
ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup ) );
if ( (m_owner->GetInterface())->I_GetTag( entID, tagName, (int) tagLookup, value ) == false)
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName );
assert(0);
return TASK_FAILED;
}
return true;
}
//Check for a real vector here
type = (int) (*(float *) block->GetMemberData( memberNum ));
if ( type != TK_VECTOR )
{
// (m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type VECTOR\n" );
return false;
}
memberNum++;
for ( i = 0; i < 3; i++ )
{
if ( GetFloat( entID, block, memberNum, value[i] ) == false )
return false;
}
return true;
}
/*
-------------------------
Get
-------------------------
*/
int CTaskManager::Get( int entID, CBlock *block, int &memberNum, char **value )
{
static char tempBuffer[128]; //FIXME: EEEK!
vector_t vector;
char *name, *tagName;
float tagLookup;
int type;
//Look for a get() inline call
if ( Check( ID_GET, block, memberNum ) )
{
//Update the member past the header id
memberNum++;
//get( TYPE, NAME )
type = (int) (*(float *) block->GetMemberData( memberNum++ ));
name = (char *) block->GetMemberData( memberNum++ );
//Format the return properly
//FIXME: This is probably doing double formatting in certain cases...
//FIXME: STRING MANAGEMENT NEEDS TO BE IMPLEMENTED, MY CURRENT SOLUTION IS NOT ACCEPTABLE!!
switch ( type )
{
case TK_STRING:
if ( ( m_owner->GetInterface())->I_GetString( entID, type, name, value ) == false )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name );
return false;
}
return true;
break;
case TK_FLOAT:
{
float temp;
if ( (m_owner->GetInterface())->I_GetFloat( entID, type, name, &temp ) == false )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name );
return false;
}
sprintf( (char *) tempBuffer, "%f", temp );
*value = (char *) tempBuffer;
}
return true;
break;
case TK_VECTOR:
{
vector_t vval;
if ( (m_owner->GetInterface())->I_GetVector( entID, type, name, vval ) == false )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() parameter \"%s\" could not be found!\n", name );
return false;
}
sprintf( (char *) tempBuffer, "%f %f %f", vval[0], vval[1], vval[2] );
*value = (char *) tempBuffer;
}
return true;
break;
default:
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Get() call tried to return an unknown type!\n" );
return false;
break;
}
}
//Look for a random() inline call
if ( Check( ID_RANDOM, block, memberNum ) )
{
float min, max, ret;
memberNum++;
min = *(float *) block->GetMemberData( memberNum++ );
max = *(float *) block->GetMemberData( memberNum++ );
ret = ( m_owner->GetInterface())->I_Random( min, max );
sprintf( (char *) tempBuffer, "%f", ret );
*value = (char *) tempBuffer;
return true;
}
//Look for a tag() inline call
if ( Check( ID_TAG, block, memberNum ) )
{
memberNum++;
ICARUS_VALIDATE ( Get( entID, block, memberNum, &tagName ) );
ICARUS_VALIDATE ( GetFloat( entID, block, memberNum, tagLookup ) );
if ( ( m_owner->GetInterface())->I_GetTag( entID, tagName, (int) tagLookup, vector ) == false)
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName );
assert(0 && "Unable to find tag");
return false;
}
sprintf( (char *) tempBuffer, "%f %f %f", vector[0], vector[1], vector[2] );
*value = (char *) tempBuffer;
return true;
}
//Get an actual piece of data
CBlockMember *bm = block->GetMember( memberNum );
if ( bm->GetID() == TK_INT )
{
float fval = (float) (*(int *) block->GetMemberData( memberNum++ ));
sprintf( (char *) tempBuffer, "%f", fval );
*value = (char *) tempBuffer;
return true;
}
else if ( bm->GetID() == TK_FLOAT )
{
float fval = *(float *) block->GetMemberData( memberNum++ );
sprintf( (char *) tempBuffer, "%f", fval );
*value = (char *) tempBuffer;
return true;
}
else if ( bm->GetID() == TK_VECTOR )
{
vector_t vval;
memberNum++;
for ( int i = 0; i < 3; i++ )
{
if ( GetFloat( entID, block, memberNum, vval[i] ) == false )
return false;
sprintf( (char *) tempBuffer, "%f %f %f", vval[0], vval[1], vval[2] );
*value = (char *) tempBuffer;
}
return true;
}
else if ( ( bm->GetID() == TK_STRING ) || ( bm->GetID() == TK_IDENTIFIER ) )
{
*value = (char *) block->GetMemberData( memberNum++ );
return true;
}
//TODO: Emit warning
assert( 0 );
(m_owner->GetInterface())->I_DPrintf( WL_WARNING, "Unexpected value; expected type STRING\n" );
return false;
}
/*
-------------------------
Go
-------------------------
*/
int CTaskManager::Go( void )
{
CTask *task = NULL;
bool completed = false;
//Check for run away scripts
if ( m_count++ > RUNAWAY_LIMIT )
{
assert(0);
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Runaway loop detected!\n" );
return TASK_FAILED;
}
//If there are tasks to complete, do so
if ( m_tasks.empty() == false )
{
//Get the next task
task = PopTask( POP_BACK );
assert( task );
if ( task == NULL )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Invalid task found in Go()!\n" );
return TASK_FAILED;
}
//If this hasn't been stamped, do so
if ( task->GetTimeStamp() == 0 )
task->SetTimeStamp( ( m_owner->GetInterface())->I_GetTime() );
//Switch and call the proper function
switch( task->GetID() )
{
case ID_WAIT:
Wait( task, completed );
//Push it to consider it again on the next frame if not complete
if ( completed == false )
{
PushTask( task, PUSH_BACK );
return TASK_OK;
}
Completed( task->GetGUID() );
break;
case ID_WAITSIGNAL:
WaitSignal( task, completed );
//Push it to consider it again on the next frame if not complete
if ( completed == false )
{
PushTask( task, PUSH_BACK );
return TASK_OK;
}
Completed( task->GetGUID() );
break;
case ID_PRINT: //print( STRING )
Print( task );
break;
case ID_SOUND: //sound( name )
Sound( task );
break;
case ID_MOVE: //move ( ORIGIN, ANGLES, DURATION )
Move( task );
break;
case ID_ROTATE: //rotate( ANGLES, DURATION )
Rotate( task );
break;
case ID_KILL: //kill( NAME )
Kill( task );
break;
case ID_REMOVE: //remove( NAME )
Remove( task );
break;
case ID_CAMERA: //camera( ? )
Camera( task );
break;
case ID_SET: //set( NAME, ? )
Set( task );
break;
case ID_USE: //use( NAME )
Use( task );
break;
case ID_DECLARE://declare( TYPE, NAME )
DeclareVariable( task );
break;
case ID_FREE: //free( NAME )
FreeVariable( task );
break;
case ID_SIGNAL: //signal( NAME )
Signal( task );
break;
case ID_PLAY: //play ( NAME )
Play( task );
break;
default:
assert(0);
task->Free();
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Found unknown task type!\n" );
return TASK_FAILED;
break;
}
//Pump the sequencer for another task
CallbackCommand( task, TASK_RETURN_COMPLETE );
task->Free();
}
//FIXME: A command surge limiter could be implemented at this point to be sure a script doesn't
// execute too many commands in one cycle. This may, however, cause timing errors to surface.
return TASK_OK;
}
/*
-------------------------
SetCommand
-------------------------
*/
int CTaskManager::SetCommand( CBlock *command, int type )
{
CTask *task = CTask::Create( m_GUID++, command );
//If this is part of a task group, add it in
if ( m_curGroup )
{
m_curGroup->Add( task );
}
//TODO: Emit warning
assert( task );
if ( task == NULL )
{
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to allocate new task!\n" );
return TASK_FAILED;
}
PushTask( task, type );
return TASK_OK;
}
/*
-------------------------
MarkTask
-------------------------
*/
int CTaskManager::MarkTask( int id, int operation )
{
CTaskGroup *group = GetTaskGroup( id );
assert( group );
if ( group == NULL )
return TASK_FAILED;
if ( operation == TASK_START )
{
//Reset all the completion information
group->Init();
group->SetParent( m_curGroup );
m_curGroup = group;
}
else if ( operation == TASK_END )
{
assert( m_curGroup );
if ( m_curGroup == NULL )
return TASK_FAILED;
m_curGroup = m_curGroup->GetParent();
}
#ifdef _DEBUG
else
{
assert(0);
}
#endif
return TASK_OK;
}
/*
-------------------------
Completed
-------------------------
*/
int CTaskManager::Completed( int id )
{
taskGroup_v::iterator tgi;
//Mark the task as completed
for ( tgi = m_taskGroups.begin(); tgi != m_taskGroups.end(); tgi++ )
{
//If this returns true, then the task was marked properly
if ( (*tgi)->MarkTaskComplete( id ) )
break;
}
return TASK_OK;
}
/*
-------------------------
CallbackCommand
-------------------------
*/
int CTaskManager::CallbackCommand( CTask *task, int returnCode )
{
if ( m_owner->Callback( this, task->GetBlock(), returnCode ) == SEQ_OK )
return Go( );
assert(0);
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Command callback failure!\n" );
return TASK_FAILED;
}
/*
-------------------------
RecallTask
-------------------------
*/
CBlock *CTaskManager::RecallTask( void )
{
CTask *task;
task = PopTask( POP_BACK );
if ( task )
{
// fixed 2/12/2 to free the task that has been popped (called from sequencer Recall)
CBlock* retBlock = task->GetBlock();
task->Free();
return retBlock;
// return task->GetBlock();
}
return NULL;
}
/*
-------------------------
PushTask
-------------------------
*/
int CTaskManager::PushTask( CTask *task, int flag )
{
assert( (flag == PUSH_FRONT) || (flag == PUSH_BACK) );
switch ( flag )
{
case PUSH_FRONT:
m_tasks.insert(m_tasks.begin(), task);
return TASK_OK;
break;
case PUSH_BACK:
m_tasks.insert(m_tasks.end(), task);
return TASK_OK;
break;
}
//Invalid flag
return SEQ_FAILED;
}
/*
-------------------------
PopTask
-------------------------
*/
CTask *CTaskManager::PopTask( int flag )
{
CTask *task;
assert( (flag == POP_FRONT) || (flag == POP_BACK) );
if ( m_tasks.empty() )
return NULL;
switch ( flag )
{
case POP_FRONT:
task = m_tasks.front();
m_tasks.pop_front();
return task;
break;
case POP_BACK:
task = m_tasks.back();
m_tasks.pop_back();
return task;
break;
}
//Invalid flag
return NULL;
}
/*
-------------------------
GetCurrentTask
-------------------------
*/
CBlock *CTaskManager::GetCurrentTask( void )
{
CTask *task = PopTask( POP_BACK );
if ( task == NULL )
return NULL;
// fixed 2/12/2 to free the task that has been popped (called from sequencer Interrupt)
CBlock* retBlock = task->GetBlock();
task->Free();
return retBlock;
// return task->GetBlock();
}
/*
=================================================
Task Functions
=================================================
*/
int CTaskManager::Wait( CTask *task, bool &completed )
{
CBlockMember *bm;
CBlock *block = task->GetBlock();
char *sVal;
float dwtime;
int memberNum = 0;
completed = false;
bm = block->GetMember( 0 );
//Check if this is a task completion wait
if ( bm->GetID() == TK_STRING )
{
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() )
{
//Print out the debug info
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d wait(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
}
CTaskGroup *group = GetTaskGroup( sVal );
if ( group == NULL )
{
//TODO: Emit warning
completed = false;
return TASK_FAILED;
}
completed = group->Complete();
}
else //Otherwise it's a time completion wait
{
if ( Check( ID_RANDOM, block, memberNum ) )
{//get it random only the first time
float min, max;
dwtime = *(float *) block->GetMemberData( memberNum++ );
if ( dwtime == Q3_INFINITE )
{//we have not evaluated this random yet
min = *(float *) block->GetMemberData( memberNum++ );
max = *(float *) block->GetMemberData( memberNum++ );
dwtime = (m_owner->GetInterface())->I_Random( min, max );
//store the result in the first member
bm->SetData( &dwtime, sizeof( dwtime ) );
}
}
else
{
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, dwtime ) );
}
if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() )
{
//Print out the debug info
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d wait( %d ); [%d]", m_ownerID, (int) dwtime, task->GetTimeStamp() );
}
if ( (task->GetTimeStamp() + dwtime) < ((m_owner->GetInterface())->I_GetTime()) )
{
completed = true;
memberNum = 0;
if ( Check( ID_RANDOM, block, memberNum ) )
{//set the data back to 0 so it will be re-randomized next time
dwtime = Q3_INFINITE;
bm->SetData( &dwtime, sizeof( dwtime ) );
}
}
}
return TASK_OK;
}
/*
-------------------------
WaitSignal
-------------------------
*/
int CTaskManager::WaitSignal( CTask *task, bool &completed )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
completed = false;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
if ( task->GetTimeStamp() == (m_owner->GetInterface())->I_GetTime() )
{
//Print out the debug info
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d waitsignal(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
}
if ( (m_owner->GetOwner())->CheckSignal( sVal ) )
{
completed = true;
(m_owner->GetOwner())->ClearSignal( sVal );
}
return TASK_OK;
}
/*
-------------------------
Print
-------------------------
*/
int CTaskManager::Print( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d print(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
(m_owner->GetInterface())->I_CenterPrint( sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Sound
-------------------------
*/
int CTaskManager::Sound( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal, *sVal2;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d sound(\"%s\", \"%s\"); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() );
//Only instantly complete if the user has requested it
if( (m_owner->GetInterface())->I_PlaySound( task->GetGUID(), m_ownerID, sVal2, sVal ) )
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Rotate
-------------------------
*/
int CTaskManager::Rotate( CTask *task )
{
vector_t vector;
CBlock *block = task->GetBlock();
char *tagName;
float tagLookup, duration;
int memberNum = 0;
//Check for a tag reference
if ( Check( ID_TAG, block, memberNum ) )
{
memberNum++;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &tagName ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, tagLookup ) );
if ( (m_owner->GetInterface())->I_GetTag( m_ownerID, tagName, (int) tagLookup, vector ) == false )
{
//TODO: Emit warning
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Unable to find tag \"%s\"!\n", tagName );
assert(0);
return TASK_FAILED;
}
}
else
{
//Get a normal vector
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) );
}
//Find the duration
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d rotate( <%f,%f,%f>, %d); [%d]", m_ownerID, vector[0], vector[1], vector[2], (int) duration, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Lerp2Angles( task->GetGUID(), m_ownerID, vector, duration );
return TASK_OK;
}
/*
-------------------------
Remove
-------------------------
*/
int CTaskManager::Remove( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d remove(\"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Remove( m_ownerID, sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Camera
-------------------------
*/
int CTaskManager::Camera( CTask *task )
{
interface_export_t *ie = ( m_owner->GetInterface() );
CBlock *block = task->GetBlock();
vector_t vector, vector2;
float type, fVal, fVal2, fVal3;
char *sVal;
int memberNum = 0;
//Get the camera function type
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, type ) );
switch ( (int) type )
{
case TYPE_PAN:
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) );
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2 ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( PAN, <%f %f %f>, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], fVal, task->GetTimeStamp() );
ie->I_CameraPan( vector, vector2, fVal );
break;
case TYPE_ZOOM:
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ZOOM, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() );
ie->I_CameraZoom( fVal, fVal2 );
break;
case TYPE_MOVE:
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( MOVE, <%f %f %f>, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, task->GetTimeStamp() );
ie->I_CameraMove( vector, fVal );
break;
case TYPE_ROLL:
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ROLL, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() );
ie->I_CameraRoll( fVal, fVal2 );
break;
case TYPE_FOLLOW:
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( FOLLOW, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() );
ie->I_CameraFollow( (const char *) sVal, fVal, fVal2 );
break;
case TYPE_TRACK:
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( TRACK, \"%s\", %f, %f); [%d]", m_ownerID, sVal, fVal, fVal2, task->GetTimeStamp() );
ie->I_CameraTrack( (const char *) sVal, fVal, fVal2 );
break;
case TYPE_DISTANCE:
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( DISTANCE, %f, %f); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() );
ie->I_CameraDistance( fVal, fVal2 );
break;
case TYPE_FADE:
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector2 ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal3 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( FADE, <%f %f %f>, %f, <%f %f %f>, %f, %f); [%d]", m_ownerID, vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3, task->GetTimeStamp() );
ie->I_CameraFade( vector[0], vector[1], vector[2], fVal, vector2[0], vector2[1], vector2[2], fVal2, fVal3 );
break;
case TYPE_PATH:
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( PATH, \"%s\"); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
ie->I_CameraPath( sVal );
break;
case TYPE_ENABLE:
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( ENABLE ); [%d]", m_ownerID, task->GetTimeStamp() );
ie->I_CameraEnable();
break;
case TYPE_DISABLE:
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( DISABLE ); [%d]", m_ownerID, task->GetTimeStamp() );
ie->I_CameraDisable();
break;
case TYPE_SHAKE:
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d camera( SHAKE, %f, %f ); [%d]", m_ownerID, fVal, fVal2, task->GetTimeStamp() );
ie->I_CameraShake( fVal, (int) fVal2 );
break;
}
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Move
-------------------------
*/
int CTaskManager::Move( CTask *task )
{
vector_t vector, vector2;
CBlock *block = task->GetBlock();
float duration;
int memberNum = 0;
//Get the goal position
ICARUS_VALIDATE( GetVector( m_ownerID, block, memberNum, vector ) );
//Check for possible angles field
if ( GetVector( m_ownerID, block, memberNum, vector2 ) == false )
{
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d move( <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], duration, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Lerp2Pos( task->GetGUID(), m_ownerID, vector, NULL, duration );
return TASK_OK;
}
//Get the duration and make the call
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, duration ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d move( <%f %f %f>, <%f %f %f>, %f ); [%d]", m_ownerID, vector[0], vector[1], vector[2], vector2[0], vector2[1], vector2[2], duration, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Lerp2Pos( task->GetGUID(), m_ownerID, vector, vector2, duration );
return TASK_OK;
}
/*
-------------------------
Kill
-------------------------
*/
int CTaskManager::Kill( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d kill( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Kill( m_ownerID, sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Set
-------------------------
*/
int CTaskManager::Set( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal, *sVal2;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d set( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Set( task->GetGUID(), m_ownerID, sVal, sVal2 );
return TASK_OK;
}
/*
-------------------------
Use
-------------------------
*/
int CTaskManager::Use( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d use( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Use( m_ownerID, sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
DeclareVariable
-------------------------
*/
int CTaskManager::DeclareVariable( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
float fVal;
ICARUS_VALIDATE( GetFloat( m_ownerID, block, memberNum, fVal ) );
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d declare( %d, \"%s\" ); [%d]", m_ownerID, (int) fVal, sVal, task->GetTimeStamp() );
(m_owner->GetInterface())->I_DeclareVariable( (int) fVal, sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
FreeVariable
-------------------------
*/
int CTaskManager::FreeVariable( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d free( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
(m_owner->GetInterface())->I_FreeVariable( sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Signal
-------------------------
*/
int CTaskManager::Signal( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d signal( \"%s\" ); [%d]", m_ownerID, sVal, task->GetTimeStamp() );
m_owner->GetOwner()->Signal( (const char *) sVal );
Completed( task->GetGUID() );
return TASK_OK;
}
/*
-------------------------
Play
-------------------------
*/
int CTaskManager::Play( CTask *task )
{
CBlock *block = task->GetBlock();
char *sVal, *sVal2;
int memberNum = 0;
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal ) );
ICARUS_VALIDATE( Get( m_ownerID, block, memberNum, &sVal2 ) );
(m_owner->GetInterface())->I_DPrintf( WL_DEBUG, "%4d play( \"%s\", \"%s\" ); [%d]", m_ownerID, sVal, sVal2, task->GetTimeStamp() );
(m_owner->GetInterface())->I_Play( task->GetGUID(), m_ownerID, (const char *) sVal, (const char *) sVal2 );
return TASK_OK;
}
/*
-------------------------
SaveCommand
-------------------------
*/
//FIXME: ARGH! This is duplicated from CSequence because I can't directly link it any other way...
int CTaskManager::SaveCommand( CBlock *block )
{
unsigned char flags;
int numMembers, bID, size;
CBlockMember *bm;
//Save out the block ID
bID = block->GetBlockID();
(m_owner->GetInterface())->I_WriteSaveData( 'BLID', &bID, sizeof ( bID ) );
//Save out the block's flags
flags = block->GetFlags();
(m_owner->GetInterface())->I_WriteSaveData( 'BFLG', &flags, sizeof ( flags ) );
//Save out the number of members to read
numMembers = block->GetNumMembers();
(m_owner->GetInterface())->I_WriteSaveData( 'BNUM', &numMembers, sizeof ( numMembers ) );
for ( int i = 0; i < numMembers; i++ )
{
bm = block->GetMember( i );
//Save the block id
bID = bm->GetID();
(m_owner->GetInterface())->I_WriteSaveData( 'BMID', &bID, sizeof ( bID ) );
//Save out the data size
size = bm->GetSize();
(m_owner->GetInterface())->I_WriteSaveData( 'BSIZ', &size, sizeof( size ) );
//Save out the raw data
(m_owner->GetInterface())->I_WriteSaveData( 'BMEM', bm->GetData(), size );
}
return true;
}
/*
-------------------------
Save
-------------------------
*/
void CTaskManager::Save( void )
{
CTaskGroup *taskGroup;
const char *name;
CBlock *block;
DWORD timeStamp;
bool completed;
int id, numCommands;
int numWritten;
//Save the taskmanager's GUID
(m_owner->GetInterface())->I_WriteSaveData( 'TMID', &m_GUID, sizeof( m_GUID ) ); //FIXME: This can be reconstructed
//Save out the number of tasks that will follow
int iNumTasks = m_tasks.size();
(m_owner->GetInterface())->I_WriteSaveData( 'TSK#', &iNumTasks, sizeof(iNumTasks) );
//Save out all the tasks
tasks_l::iterator ti;
STL_ITERATE( ti, m_tasks )
{
//Save the GUID
id = (*ti)->GetGUID();
(m_owner->GetInterface())->I_WriteSaveData( 'TKID', &id, sizeof ( id ) );
//Save the timeStamp (FIXME: Although, this is going to be worthless if time is not consistent...)
timeStamp = (*ti)->GetTimeStamp();
(m_owner->GetInterface())->I_WriteSaveData( 'TKTS', &timeStamp, sizeof ( timeStamp ) );
//Save out the block
block = (*ti)->GetBlock();
SaveCommand( block );
}
//Save out the number of task groups
int numTaskGroups = m_taskGroups.size();
(m_owner->GetInterface())->I_WriteSaveData( 'TG#G', &numTaskGroups, sizeof( numTaskGroups ) );
//Save out the IDs of all the task groups
numWritten = 0;
taskGroup_v::iterator tgi;
STL_ITERATE( tgi, m_taskGroups )
{
id = (*tgi)->GetGUID();
(m_owner->GetInterface())->I_WriteSaveData( 'TKG#', &id, sizeof( id ) );
numWritten++;
}
assert (numWritten == numTaskGroups);
//Save out the task groups
numWritten = 0;
STL_ITERATE( tgi, m_taskGroups )
{
//Save out the parent
id = ( (*tgi)->GetParent() == NULL ) ? -1 : ((*tgi)->GetParent())->GetGUID();
(m_owner->GetInterface())->I_WriteSaveData( 'TKGP', &id, sizeof( id ) );
//Save out the number of commands
numCommands = (*tgi)->m_completedTasks.size();
(m_owner->GetInterface())->I_WriteSaveData( 'TGNC', &numCommands, sizeof( numCommands ) );
//Save out the command map
CTaskGroup::taskCallback_m::iterator tci;
STL_ITERATE( tci, (*tgi)->m_completedTasks )
{
//Write out the ID
id = (*tci).first;
(m_owner->GetInterface())->I_WriteSaveData( 'GMID', &id, sizeof( id ) );
//Write out the state of completion
completed = (*tci).second;
(m_owner->GetInterface())->I_WriteSaveData( 'GMDN', &completed, sizeof( completed ) );
}
//Save out the number of completed commands
id = (*tgi)->m_numCompleted;
(m_owner->GetInterface())->I_WriteSaveData( 'TGDN', &id, sizeof( id ) ); //FIXME: This can be reconstructed
numWritten++;
}
assert (numWritten == numTaskGroups);
//Only bother if we've got tasks present
if ( m_taskGroups.size() )
{
//Save out the currently active group
int curGroupID = ( m_curGroup == NULL ) ? -1 : m_curGroup->GetGUID();
(m_owner->GetInterface())->I_WriteSaveData( 'TGCG', &curGroupID, sizeof( curGroupID ) );
}
//Save out the task group name maps
taskGroupName_m::iterator tmi;
numWritten = 0;
STL_ITERATE( tmi, m_taskGroupNameMap )
{
name = ((*tmi).first).c_str();
//Make sure this is a valid string
assert( ( name != NULL ) && ( name[0] != NULL ) );
int length = strlen( name ) + 1;
//Save out the string size
(m_owner->GetInterface())->I_WriteSaveData( 'TGNL', &length, sizeof ( length ) );
//Write out the string
(m_owner->GetInterface())->I_WriteSaveData( 'TGNS', (void *) name, length );
taskGroup = (*tmi).second;
id = taskGroup->GetGUID();
//Write out the ID
(m_owner->GetInterface())->I_WriteSaveData( 'TGNI', &id, sizeof( id ) );
numWritten++;
}
assert (numWritten == numTaskGroups);
}
/*
-------------------------
Load
-------------------------
*/
void CTaskManager::Load( void )
{
unsigned char flags;
CTaskGroup *taskGroup;
CBlock *block;
CTask *task;
DWORD timeStamp;
bool completed;
void *bData;
int id, numTasks, numMembers;
int bID, bSize;
//Get the GUID
(m_owner->GetInterface())->I_ReadSaveData( 'TMID', &m_GUID, sizeof( m_GUID ), NULL );
//Get the number of tasks to follow
(m_owner->GetInterface())->I_ReadSaveData( 'TSK#', &numTasks, sizeof( numTasks ), NULL );
//Reload all the tasks
for ( int i = 0; i < numTasks; i++ )
{
task = new CTask;
assert( task );
//Get the GUID
(m_owner->GetInterface())->I_ReadSaveData( 'TKID', &id, sizeof( id ), NULL );
task->SetGUID( id );
//Get the time stamp
(m_owner->GetInterface())->I_ReadSaveData( 'TKTS', &timeStamp, sizeof( timeStamp ), NULL );
task->SetTimeStamp( timeStamp );
//
// BLOCK LOADING
//
//Get the block ID and create a new container
(m_owner->GetInterface())->I_ReadSaveData( 'BLID', &id, sizeof( id ), NULL );
block = new CBlock;
block->Create( id );
//Read the block's flags
(m_owner->GetInterface())->I_ReadSaveData( 'BFLG', &flags, sizeof( flags ), NULL );
block->SetFlags( flags );
//Get the number of block members
(m_owner->GetInterface())->I_ReadSaveData( 'BNUM', &numMembers, sizeof( numMembers ), NULL );
for ( int j = 0; j < numMembers; j++ )
{
//Get the member ID
(m_owner->GetInterface())->I_ReadSaveData( 'BMID', &bID, sizeof( bID ), NULL );
//Get the member size
(m_owner->GetInterface())->I_ReadSaveData( 'BSIZ', &bSize, sizeof( bSize ), NULL );
//Get the member's data
if ( ( bData = ICARUS_Malloc( bSize ) ) == NULL )
{
assert( 0 );
return;
}
//Get the actual raw data
(m_owner->GetInterface())->I_ReadSaveData( 'BMEM', bData, bSize, NULL );
//Write out the correct type
switch ( bID )
{
case TK_FLOAT:
block->Write( TK_FLOAT, *(float *) bData );
break;
case TK_IDENTIFIER:
block->Write( TK_IDENTIFIER, (char *) bData );
break;
case TK_STRING:
block->Write( TK_STRING, (char *) bData );
break;
case TK_VECTOR:
block->Write( TK_VECTOR, *(vec3_t *) bData );
break;
case ID_RANDOM:
block->Write( ID_RANDOM, *(float *) bData );//ID_RANDOM );
break;
case ID_TAG:
block->Write( ID_TAG, (float) ID_TAG );
break;
case ID_GET:
block->Write( ID_GET, (float) ID_GET );
break;
default:
(m_owner->GetInterface())->I_DPrintf( WL_ERROR, "Invalid Block id %d\n", bID);
assert( 0 );
break;
}
//Get rid of the temp memory
ICARUS_Free( bData );
}
task->SetBlock( block );
STL_INSERT( m_tasks, task );
}
//Load the task groups
int numTaskGroups;
(m_owner->GetInterface())->I_ReadSaveData( 'TG#G', &numTaskGroups, sizeof( numTaskGroups ), NULL );
if ( numTaskGroups == 0 )
return;
int *taskIDs = new int[ numTaskGroups ];
//Get the task group IDs
for (int i = 0; i < numTaskGroups; i++ )
{
//Creat a new task group
taskGroup = new CTaskGroup;
assert( taskGroup );
//Get this task group's ID
(m_owner->GetInterface())->I_ReadSaveData( 'TKG#', &taskIDs[i], sizeof( taskIDs[i] ), NULL );
taskGroup->m_GUID = taskIDs[i];
m_taskGroupIDMap[ taskIDs[i] ] = taskGroup;
STL_INSERT( m_taskGroups, taskGroup );
}
//Recreate and load the task groups
for (int i = 0; i < numTaskGroups; i++ )
{
taskGroup = GetTaskGroup( taskIDs[i] );
assert( taskGroup );
//Load the parent ID
(m_owner->GetInterface())->I_ReadSaveData( 'TKGP', &id, sizeof( id ), NULL );
if ( id != -1 )
taskGroup->m_parent = ( GetTaskGroup( id ) != NULL ) ? GetTaskGroup( id ) : NULL;
//Get the number of commands in this group
(m_owner->GetInterface())->I_ReadSaveData( 'TGNC', &numMembers, sizeof( numMembers ), NULL );
//Get each command and its completion state
for ( int j = 0; j < numMembers; j++ )
{
//Get the ID
(m_owner->GetInterface())->I_ReadSaveData( 'GMID', &id, sizeof( id ), NULL );
//Write out the state of completion
(m_owner->GetInterface())->I_ReadSaveData( 'GMDN', &completed, sizeof( completed ), NULL );
//Save it out
taskGroup->m_completedTasks[ id ] = completed;
}
//Get the number of completed tasks
(m_owner->GetInterface())->I_ReadSaveData( 'TGDN', &taskGroup->m_numCompleted, sizeof( taskGroup->m_numCompleted ), NULL );
}
//Reload the currently active group
int curGroupID;
(m_owner->GetInterface())->I_ReadSaveData( 'TGCG', &curGroupID, sizeof( curGroupID ), NULL );
//Reload the map entries
for (int i = 0; i < numTaskGroups; i++ )
{
char name[1024];
int length;
//Get the size of the string
(m_owner->GetInterface())->I_ReadSaveData( 'TGNL', &length, sizeof( length ), NULL );
//Get the string
(m_owner->GetInterface())->I_ReadSaveData( 'TGNS', &name, length, NULL );
//Get the id
(m_owner->GetInterface())->I_ReadSaveData( 'TGNI', &id, sizeof( id ), NULL );
taskGroup = GetTaskGroup( id );
assert( taskGroup );
m_taskGroupNameMap[ name ] = taskGroup;
m_taskGroupIDMap[ taskGroup->GetGUID() ] = taskGroup;
}
m_curGroup = ( curGroupID == -1 ) ? NULL : m_taskGroupIDMap[curGroupID];
delete[] taskIDs;
}
| gpl-2.0 |
kost/dockscan | lib/dockscan/modules/discover/get-containers.rb | 276 | class GetContainers < Dockscan::Modules::DiscoverModule
def info
return 'Container discovery module'
end
def run
sp=Dockscan::Scan::Plugin.new
sp.obj = Docker::Container.all(:all => true)
sp.output = sp.obj.map{|k,v| "#{k}=#{v}"}.join("\n")
return sp
end
end
| gpl-2.0 |
eefsparreboom/socialmet | wp-content/plugins/optimizePressPlugin/lib/js/jquery/jquery.loadScript.js | 878 | (function ($) {
$.loadScript = function (url, arg1, arg2) {
var cache = false, callback = null;
//arg1 and arg2 can be interchangable
if ($.isFunction(arg1)){
callback = arg1;
cache = arg2 || cache;
} else {
cache = arg1 || cache;
callback = arg2 || callback;
}
var load = true;
//check all existing script tags in the page for the url
$('script[type="text/javascript"]')
.each(function () {
return load = (url != $(this).attr('src'));
});
if (load){
//didn't find it in the page, so load it
$.ajax({
type: 'GET',
url: url,
success: callback,
dataType: 'script',
cache: cache
});
} else {
//already loaded so just call the callback
if ($.isFunction(callback)) {
callback.call(this);
};
};
};
}(opjq)); | gpl-2.0 |
martolini/Vana | scripts/portals/s4hitman.lua | 1314 | --[[
Copyright (C) 2008-2015 Vana Development Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.
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.
--]]
-- Assassinate quest
dofile("scripts/utils/tableHelper.lua");
if isQuestActive(6201) then
if getItemAmount(4031452) == 0 then
if not isInstance("assassinate4th") then
createInstance("assassinate4th", 20 * 60, true);
addInstancePlayer(getId());
playPortalSe();
maps = {910200000, 910200001, 910200002};
setMap(selectElement(maps));
else
showMessage("Other characters are on request. You can't enter.", msg_red);
end
else
showMessage("Shawn's request is completed. You don't need to go in again.", msg_red);
end
else
showMessage("You can't go. You didn't get Shawn's request.", msg_red);
end | gpl-2.0 |
subtext/joomla-cms | components/com_config/view/modules/tmpl/default.php | 5944 | <?php
/**
* @package Joomla.Site
* @subpackage com_config
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidator');
JHtml::_('behavior.keepalive');
JHtml::_('behavior.framework', true);
JHtml::_('behavior.combobox');
JHtml::_('formbehavior.chosen', 'select');
$hasContent = empty($this->item['module']) || $this->item['module'] == 'custom' || $this->item['module'] == 'mod_custom';
// If multi-language site, make language read-only
if (JLanguageMultilang::isEnabled())
{
$this->form->setFieldAttribute('language', 'readonly', 'true');
}
JFactory::getDocument()->addScriptDeclaration("
Joomla.submitbutton = function(task)
{
if (task == 'config.cancel.modules' || document.formvalidator.isValid(document.getElementById('modules-form')))
{
Joomla.submitform(task, document.getElementById('modules-form'));
}
}
");
?>
<form
action="<?php echo JRoute::_('index.php?option=com_config'); ?>"
method="post" name="adminForm" id="modules-form"
class="form-validate">
<div class="row-fluid">
<!-- Begin Content -->
<div class="span12">
<div class="btn-toolbar">
<div class="btn-group">
<button type="button" class="btn btn-default btn-primary"
onclick="Joomla.submitbutton('config.save.modules.apply')">
<i class="icon-apply"></i>
<?php echo JText::_('JAPPLY') ?>
</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default"
onclick="Joomla.submitbutton('config.save.modules.save')">
<i class="icon-save"></i>
<?php echo JText::_('JSAVE') ?>
</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default"
onclick="Joomla.submitbutton('config.cancel.modules')">
<i class="icon-cancel"></i>
<?php echo JText::_('JCANCEL') ?>
</button>
</div>
</div>
<hr class="hr-condensed" />
<legend><?php echo JText::_('COM_CONFIG_MODULES_SETTINGS_TITLE'); ?></legend>
<div>
<?php echo JText::_('COM_CONFIG_MODULES_MODULE_NAME') ?>
<span class="label label-default"><?php echo $this->item['title'] ?></span>
<?php echo JText::_('COM_CONFIG_MODULES_MODULE_TYPE') ?>
<span class="label label-default"><?php echo $this->item['module'] ?></span>
</div>
<hr />
<div class="row-fluid">
<div class="span12">
<fieldset class="form-horizontal">
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('title'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('title'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('showtitle'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('showtitle'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('position'); ?>
</div>
<div class="controls">
<?php echo $this->loadTemplate('positions'); ?>
</div>
</div>
<hr />
<?php
if (JFactory::getUser()->authorise('core.edit.state', 'com_modules.module.' . $this->item['id'])): ?>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('published'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('published'); ?>
</div>
</div>
<?php endif ?>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('publish_up'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('publish_up'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('publish_down'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('publish_down'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('access'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('access'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('ordering'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('ordering'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('language'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('language'); ?>
</div>
</div>
<div class="control-group">
<div class="control-label">
<?php echo $this->form->getLabel('note'); ?>
</div>
<div class="controls">
<?php echo $this->form->getInput('note'); ?>
</div>
</div>
<hr />
<div id="options">
<?php echo $this->loadTemplate('options'); ?>
</div>
<?php if ($hasContent): ?>
<div class="tab-pane" id="custom">
<?php echo $this->form->getInput('content'); ?>
</div>
<?php endif; ?>
</fieldset>
</div>
<input type="hidden" name="id" value="<?php echo $this->item['id'];?>" />
<input type="hidden" name="return" value="<?php echo JFactory::getApplication()->input->get('return', null, 'base64');?>" />
<input type="hidden" name="task" value="" />
<?php echo JHtml::_('form.token'); ?>
</div>
</div>
<!-- End Content -->
</div>
</form>
| gpl-2.0 |
ewout/moodle-atpusp | mod/tracker/lang/es_es_utf8/tracker.php | 14402 | <?php // $Id: tracker.php,v 1.1.2.1 2010/08/01 22:48:00 diml Exp $
// tracker.php - created with Moodle 1.2 development (2003111400)
$string['AND'] = 'Y';
$string['IN'] = 'EN';
$string['abandonned'] = 'Abandonado';
$string['action'] = 'Acción';
$string['addacomment'] = 'Añadir un cometario';
$string['addanoption'] = 'Añadir una opción';
$string['addaquerytomemo'] = 'Añadir esta consulta a \"mis consultas\"';
$string['addawatcher'] = 'Añadir un seguimiento';
$string['addtothetracker'] = 'Añadirme a este tracker';
$string['administration'] = 'Administración';
$string['administrators'] = 'Administradores';
$string['any'] = 'Todos';
$string['askraise'] = 'Pedir a los responsables elevar la prioridad';
$string['assignedto'] = 'Asignar a';
$string['assignee'] = 'Asignado';
$string['attributes'] = 'Atributos';
$string['browse'] = 'Visualizar';
$string['browser'] = 'Visualizador';
$string['build'] = 'Version';
$string['by'] = '<i>asignado por</i>';
$string['cascade'] = 'Enviar a un nivel superior';
$string['cascadedticket'] = 'Transferido desde: ';
$string['cced'] = 'Cced';
$string['ccs'] = 'Ccs';
$string['checkbox'] = 'Casilla de verificación'; // @DYNA
$string['checkboxhoriz'] = 'Casilla de verificación horizontal'; // @DYNA
$string['chooselocal'] = 'Escoger un tracker local como padre';
$string['chooseremote'] = 'Escoger un host remoto';
$string['chooseremoteparent'] = 'Escoger una instancia remota';
$string['clearsearch'] = 'Limpiar los criterios de búsqueda';
$string['comment'] = 'Comentario';
$string['comments'] = 'Comentarios';
$string['component'] = 'Componente';
$string['createnewelement'] = 'Crear un nuevo elemento';
$string['currentbinding'] = 'Cascada actual';
$string['database'] = 'Base de datos';
$string['datereported'] = 'Fecha del informe';
$string['deleteattachedfile'] = 'Borrar adjuntos';
$string['dependancies'] = 'Dependencias';
$string['dependson'] = 'Depende de ';
$string['descriptionisempty'] = 'La descripción está vacia';
$string['doaddelementcheckbox'] = 'Añadir un elemento del tipo casilla de verificación'; // @DYNA
$string['doaddelementcheckboxhoriz'] = 'Añadir un elemento del tipo casilla de verificación horizontal'; // @DYNA
$string['doaddelementdropdown'] = 'Añadir un elemento desplegable'; // @DYNA
$string['doaddelementfile'] = 'Añadir un elemento para fichero adjunto'; // @DYNA
$string['doaddelementradio'] = 'Añadir un elemento de radio'; // @DYNA
$string['doaddelementradiohoriz'] = 'Añadir un elemento de radio en horizontal'; // @DYNA
$string['doaddelementtext'] = 'Añadir un campo simple de texto'; // @DYNA
$string['doaddelementtextarea'] = 'Añadir un campo de área texto'; // @DYNA
$string['doupdateelementcheckbox'] = 'Actualizar un elemento de tipo casilla de verificación'; // @DYNA
$string['doupdateelementcheckboxhoriz'] = 'Actualizar un elemento de tipo casilla de verificación horizontal'; // @DYNA
$string['doupdateelementdropdown'] = 'Actualizar un elemento desplegable';// @DYNA
$string['doupdateelementfile'] = 'Actualizar un elemento para fichero adjunto'; // @DYNA
$string['doupdateelementradio'] = 'Actualizar un elemento de radio'; // @DYNA
$string['doupdateelementradiohoriz'] = 'Actualizar un elemento de radio horizontal'; // @DYNA
$string['doupdateelementtext'] = 'Actualizar un campo simple de texto'; // @DYNA
$string['doupdateelementtextarea'] = 'Actualizar un campo de área de texto'; // @DYNA
$string['dropdown'] = 'Desplegable';
$string['editoptions'] = 'Actualizar opciones';
$string['editproperties'] = 'Actualizar propiedades';
$string['editquery'] = 'Cambiar una consulta archivada';
$string['editwatch'] = 'Cambiar un cc registrado';
$string['elements'] = 'Elementos disponibles';
$string['elementsused'] = 'Elementos utilizados';
$string['emailoptions'] = 'Opciones de Correo';
$string['emergency'] = 'Consulta urgente';
$string['emptydefinition'] = 'El objetivo del tracker no ha sido definido.';
$string['enablecomments'] = 'Permitir comentarios';
$string['errorcoursemisconfigured'] = 'El curso esta desconfigurado';
$string['errorcoursemodid'] = 'El ID del módulo del curso es incorrecto';
$string['errorfindingaction'] = 'Error: Acción no encontrada: ';
$string['errormoduleincorrect'] = 'El módulo del curso es incorrecto';
$string['errornoaccessallissues'] = 'No tiene permiso paa ver todos los asuntos.';
$string['errornoaccessissue'] = 'No tiene permiso para ver este asunto.';
$string['errornoeditissue'] = 'No tiene permiso para editar este asunto.';
$string['file'] = 'Archivo adjunto';
$string['follow'] = 'Seguir';
$string['hassolution'] = 'Para este asunto ya ha sido publicada una solución';
$string['hideccs'] = 'Ocultar seguidores';
$string['hidecomments'] = 'Ocultar comentarios';
$string['hidedependancies'] = 'Ocultar dependencias';
$string['hidehistory'] = 'Ocultar historial';
$string['history'] = 'Historial';
$string['iamadeveloper'] = 'Soy un desarrollador';
$string['iamnotadeveloper'] = 'No soy un desarrollador';
$string['icanmanage'] = 'Puedo gestionar asuntos';
$string['icannotmanage'] = 'No puedo gestionar';
$string['icannotreport'] = 'No puedo emitir informes';
$string['icannotresolve'] = 'No puedo resolver';
$string['icanreport'] = 'Puedo emitir informes';
$string['icanresolve'] = 'Se me pueden asignar algunos tickets';
$string['id'] = 'Identificador';
$string['issueid'] = 'Ticket';
$string['issuename'] = 'Etiqueta del Ticket ';
$string['issuenumber'] = 'Nº Ticket';
$string['issues'] = 'tickets registrados';
$string['knownelements'] = 'Elementos conocidos del formulario del tracker';
$string['listissues'] = 'Ver lista';
$string['local'] = 'Local';
$string['lowerpriority'] = 'Prioridad baja';
$string['lowertobottom'] = 'Bajar al nivel básico';
$string['manageelements'] = 'Gestionar elementos';
$string['managenetwork'] = 'Cascada y configuración de red';
$string['manager'] = 'Gestor';
$string['me'] = 'Mi perfil';
$string['mode_bugtracker'] = 'Equipo para tracker de errores';
$string['mode_ticketting'] = 'Servicio de soporte al usuario';
$string['modulename'] = 'Tracker: Servicio de soporte al usuario';
$string['modulenameplural'] = 'Trackers: Servicios de soporte a usuarios';
$string['myassignees'] = 'Responsable al que asigné';
$string['myissues'] = 'Tickets que atiendo';
$string['mypreferences'] = 'Mis preferencias';
$string['myprofile'] = 'Mi perfil';
$string['myqueries'] = 'Mis consultas';
$string['mytickets'] = 'Mis tickets';
$string['mywatches'] = 'Mis seguimientos';
$string['name'] = 'Nombre';
$string['namecannotbeblank'] = 'El Nombre no puede quedar en blanco';
$string['newissue'] = 'Nuevo ticket';
$string['noassignees'] = 'Sin asignar';
$string['nocomments'] = 'Sin comentarios';
$string['noelements'] = 'Sin elementos';
$string['noelementscreated'] = 'Sin elementos creados';
$string['nofile'] = 'Sin ficheros adjuntos (subidos)';
$string['noissuesreported'] = 'No hay tickets aquí';
$string['noissuesresolved'] = 'No hay tickets resueltos';
$string['nolocalcandidate'] = 'No hay candidatos locales para cascada';
$string['nooptions'] = 'No hay opciones';
$string['noqueryssaved'] = 'No hay consultas archivadas';
$string['noremotehosts'] = 'No hay network host disponible';
$string['noremotetrackers'] = 'No hay trackers remotos disponibles';
$string['noreporters'] = 'No hay remitentes, probablemente no hay asuntos aquí.';
$string['noresolvers'] = 'No hay responsables';
$string['noresolvingissue'] = 'No hay tickets asignados';
$string['notickets'] = 'No hay tickets emitidos.';
$string['notifications'] = 'Notificaciones';
$string['notrackeradmins'] = 'No hay administradores';
$string['nowatches'] = 'No hay seguidores';
$string['numberofissues'] = 'Recuento de Tickets';
$string['observers'] = 'Observadores';
$string['open'] = 'Abierto';
$string['option'] = 'Opción ';
$string['optionisused'] = 'El ID de esta opción ya se está usando para este elemento.';
$string['order'] = 'Orden';
$string['pages'] = 'Páginas';
$string['posted'] = 'Publicado';
$string['potentialresolvers'] = 'Responsables potenciales';
$string['preferences'] = 'Preferencias';
$string['prefsnote'] = 'Preferencias configura las notificaciones que por defecto se reciben cuando se publica un nuevo asunto (ticket) y cuando uno se registra para realizar el seguimiento de un asunto existente';
$string['priority'] = 'Prioridad atribuída';
$string['profile'] = 'Ajustes del usuario';
$string['queries'] = 'Consultas';
$string['query'] = 'Consulta';
$string['queryname'] = 'Etiqueta de la consulta';
$string['radio'] = 'Botones de radio'; // @DYNA
$string['radiohoriz'] = 'Botones de radio en horizontal'; // @DYNA
$string['raisepriority'] = 'Elevar la prioridad';
$string['raiserequestcaption'] = 'Solicitar la elevación de prioridad de un ticket';
$string['raiserequesttitle'] = 'Solicitar una elevación de prioridad';
$string['raisetotop'] = 'elevar al nivel superior';
$string['reason'] = 'Razón';
$string['register'] = 'Seguir este ticket';
$string['reportanissue'] = 'Publicar un ticket';
$string['reportedby'] = 'Publicado por';
$string['reporter'] = 'Remitente';
$string['resolution'] = 'Solución';
$string['resolved'] = 'Resuelto';
$string['resolvedplural'] = 'Resueltos';
$string['resolver'] = 'Mis asuntos';
$string['resolvers'] = 'Responsables';
$string['resolving'] = 'En proceso de resolución';
$string['saveasquery'] = 'Guardar una consulta';
$string['savequery'] = 'Guardar la consulta';
$string['search'] = 'Buscar';
$string['searchresults'] = 'Resultados de la búsqueda';
$string['searchwiththat'] = 'Ejecutar esta consulta otra vez';
$string['selectparent'] = 'Seleccionar Padre';
$string['sendrequest'] = 'Enviar petición';
$string['setwhenopens'] = 'No avisarme cuando se abra';
$string['setwhenresolves'] = 'No avisarem cuando se resuelva';
$string['unsetwhentesting'] = 'No avisarme cuando se experimente una solución';
$string['setwhenthrown'] = 'No avisarme cuando se abandone';
$string['setwhenwaits'] = 'No avisarem cuando se mantenga en espera';
$string['setwhenworks'] = 'No avisarme cuando se trabaje sobre ello';
$string['setoncomment'] = 'Enviarme los comentarios';
$string['sharethiselement'] = 'Comparyir este elemento en todo el sitio';
$string['sharing'] = 'Compartido';
$string['showccs'] = 'Ver seguidores';
$string['showcomments'] = 'Ver comentarios';
$string['showdependancies'] = 'Ver dependencias';
$string['showhistory'] = 'Ver historial';
$string['site'] = 'Sitio WEB';
$string['solution'] = 'Solución';
$string['sortorder'] = 'Ordenar';
$string['standalone'] = 'Tracker independiente (soporte al más alto nivel).';
$string['status'] = 'Status';
$string['submission'] = 'Se ha publicado de un nuevo ticket en el tracker [$a]';
$string['submitbug'] = 'Enviar el ticket';
$string['sum_opened'] = 'Abierto';
$string['sum_posted'] = 'Esperando';
$string['sum_reported'] = 'Informado';
$string['sum_resolved'] = 'Resuelto';
$string['summary'] = 'Resumen';
$string['supportmode'] = 'Tipo $string['doaddelementfile'] = 'Add an attachment file'; // @DYNAde soporte';
$string['testing'] = 'En proceso de experimentación';
$string['text'] = 'Campo de texto simple'; // @DYNA
$string['textarea'] = 'Campo de área de texto'; // @DYNA
$string['thanks'] = 'Gracias por su contribución a la mejora constante de este servicio.';
$string['ticketprefix'] = 'Prefijo del Ticket';
$string['tracker-levelaccess'] = 'Mis capacidades en este tracker';
$string['tracker:canbecced'] = 'Puedo ser elegido para cc';
$string['tracker:comment'] = 'Comentar asuntos';
$string['tracker:configure'] = 'Configurar opciones del tracker';
$string['tracker:develop'] = 'Puedo ser elegido para resolver tickets (responsable)';
$string['tracker:manage'] = 'Gestionar asuntos';
$string['tracker:managepriority'] = 'Gestionar prioridades';
$string['tracker:managewatches'] = 'Gestionar seguimientos de un ticket';
$string['tracker:report'] = 'Informar sobre tickets';
$string['tracker:resolve'] = 'Resolver tickets';
$string['tracker:seeissues'] = 'Ver contenidos de los asuntos';
$string['tracker:viewallissues'] = 'Ver todos los tickets';
$string['tracker:viewpriority'] = 'Ver prioridad de mis propios tickets';
$string['tracker_cascade_description'] = '<p>Al publicar en este servicio, conoce y acepta que los trackers de $a reenvien (cascada) los tickets de soporte a un tracker local.</p>
<ul><li><i>Dependiendo de</i>: You have to suscribe $a to this service.</li></ul>
<p>Suscribing to this service allows local trackers to send support tickets to some tracker in $a.</p>
<ul><li><i>Dependiendo de</i>: You have to publish this service on $a.</li></ul>';
$string['tracker_cascade_name'] = 'Transporte de tickets de soporte (Tracker Modulo)';
$string['trackerelements'] = 'Definición del Tracker';
$string['trackereventchanged'] = 'Cambio de estado del asunto en el tracker [$a]';
$string['trackerhost'] = 'Host Padre para el tracker';
$string['trackername'] = 'Nombre del Tracker';
$string['transfer'] = 'Transferencia';
$string['transfered'] = 'Transferido';
$string['transferservice'] = 'Cascada del soporte de tickets';
$string['turneditingoff'] = 'Desactivar edición';
$string['turneditingon'] = 'Activar edición';
$string['type'] = 'Tipo';
$string['unassigned'] = 'Sin asignar' ;
$string['unbind'] = 'Desplegar en cascada';
$string['unmatchingelements'] = 'La definición de ambos trackers no se corresponden. Esto puede ocasionar un resultado inesperado en el funcionamiento de la cascada del soporte de tickets.';
$string['unregisterall'] = 'Desvincularse de todos' ;
$string['unsetwhenopens'] = 'Avisarme cuando se abra';
$string['unsetwhenresolves'] = 'Avisarme cuando se resuelva';
$string['unsetwhentesting'] = 'Avisarme cuando se experimente una solución';
$string['unsetwhenthrown'] = 'Avisarme cuando se tira a la papelera';
$string['unsetwhenwaits'] = 'Avisarme cuando se está en espera';
$string['unsetwhenworks'] = 'Avisarme cuando se esté trabajando sobre ello';
$string['unsetoncomment'] = 'Avisarme cuando se envíen comentarios';
$string['urgentraiserequestcaption'] = 'Un usario ha solicitado una petición de Prioridad Urgente';
$string['urgentsignal'] = 'CONSULTA URGENTE';
$string['view'] = 'Vistas';
$string['vieworiginal'] = 'Ver original';
$string['voter'] = 'Votar';
$string['waiting'] = 'En Espera';
$string['watches'] = 'Seguimientos';
$string['youneedanaccount'] = 'Para abrir un ticket aquí, se necesita una cuenta autorizada.';
?>
| gpl-2.0 |
stuenofotso/remoteComputer | tour de hanoi/src/com/polytech/tour_de_hanoi/aide_main.java | 288 | package com.polytech.tour_de_hanoi;
import android.app.Activity;
import android.os.Bundle;
public class aide_main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help_layout);
}
}
| gpl-2.0 |
sdl/Sdl-Community | DeepL LC Addon/Sdl.LC.AddonBlueprint/Enums/DataTypeEnum.cs | 576 | namespace Sdl.Community.DeeplAddon.Enums
{
/// <summary>
/// The data types.
/// </summary>
public enum DataTypeEnum
{
/// <summary>
/// The string data type.
/// </summary>
@string,
/// <summary>
/// The number data type.
/// </summary>
@number,
/// <summary>
/// The integer data type.
/// </summary>
@integer,
/// <summary>
/// The boolean data type.
/// </summary>
@boolean,
/// <summary>
/// The date time data type.
/// </summary>
@dateTime,
/// <summary>
/// The secret data type.
/// </summary>
@secret
}
} | gpl-2.0 |
trevoristall/mynameistrevor | inc/custom-header.php | 3669 | <?php
/**
* Sample implementation of the Custom Header feature
* http://codex.wordpress.org/Custom_Headers
*
* You can add an optional custom header image to header.php like so ...
<?php if ( get_header_image() ) : ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt="">
</a>
<?php endif; // End header image check. ?>
*
* @package mynameistrevor
*/
/**
* Set up the WordPress core custom header feature.
*
* @uses mynameistrevor_header_style()
* @uses mynameistrevor_admin_header_style()
* @uses mynameistrevor_admin_header_image()
*/
function mynameistrevor_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'mynameistrevor_custom_header_args', array(
'default-image' => '',
'default-text-color' => '000000',
'width' => 1000,
'height' => 250,
'flex-height' => true,
'wp-head-callback' => 'mynameistrevor_header_style',
'admin-head-callback' => 'mynameistrevor_admin_header_style',
'admin-preview-callback' => 'mynameistrevor_admin_header_image',
) ) );
}
add_action( 'after_setup_theme', 'mynameistrevor_custom_header_setup' );
if ( ! function_exists( 'mynameistrevor_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog
*
* @see mynameistrevor_custom_header_setup().
*/
function mynameistrevor_header_style() {
$header_text_color = get_header_textcolor();
// If no custom options for text are set, let's bail
// get_header_textcolor() options: HEADER_TEXTCOLOR is default, hide text (returns 'blank') or any hex value
if ( HEADER_TEXTCOLOR == $header_text_color ) {
return;
}
// If we get this far, we have custom styles. Let's do this.
?>
<style type="text/css">
<?php
// Has the text been hidden?
if ( 'blank' == $header_text_color ) :
?>
.site-title,
.site-description {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
}
<?php
// If the user has set a custom color for the text use that
else :
?>
.site-title a,
.site-description {
color: #<?php echo esc_attr( $header_text_color ); ?>;
}
<?php endif; ?>
</style>
<?php
}
endif; // mynameistrevor_header_style
if ( ! function_exists( 'mynameistrevor_admin_header_style' ) ) :
/**
* Styles the header image displayed on the Appearance > Header admin panel.
*
* @see mynameistrevor_custom_header_setup().
*/
function mynameistrevor_admin_header_style() {
?>
<style type="text/css">
.appearance_page_custom-header #headimg {
border: none;
}
#headimg h1,
#desc {
}
#headimg h1 {
}
#headimg h1 a {
}
#desc {
}
#headimg img {
}
</style>
<?php
}
endif; // mynameistrevor_admin_header_style
if ( ! function_exists( 'mynameistrevor_admin_header_image' ) ) :
/**
* Custom header image markup displayed on the Appearance > Header admin panel.
*
* @see mynameistrevor_custom_header_setup().
*/
function mynameistrevor_admin_header_image() {
$style = sprintf( ' style="color:#%s;"', get_header_textcolor() );
?>
<div id="headimg">
<h1 class="displaying-header-text"><a id="name"<?php echo $style; ?> onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1>
<div class="displaying-header-text" id="desc"<?php echo $style; ?>><?php bloginfo( 'description' ); ?></div>
<?php if ( get_header_image() ) : ?>
<img src="<?php header_image(); ?>" alt="">
<?php endif; ?>
</div>
<?php
}
endif; // mynameistrevor_admin_header_image | gpl-2.0 |
eveseat/eveapi | src/Jobs/Corporation/Info.php | 2073 | <?php
/*
* This file is part of SeAT
*
* Copyright (C) 2015 to 2022 Leon Jacobs
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
namespace Seat\Eveapi\Jobs\Corporation;
use Seat\Eveapi\Jobs\AbstractCorporationJob;
use Seat\Eveapi\Mapping\Corporations\InfoMapping;
use Seat\Eveapi\Models\Corporation\CorporationInfo;
/**
* Class Info.
*
* @package Seat\Eveapi\Jobs\Corporation
*/
class Info extends AbstractCorporationJob
{
/**
* @var string
*/
protected $method = 'get';
/**
* @var string
*/
protected $endpoint = '/corporations/{corporation_id}/';
/**
* @var string
*/
protected $version = 'v5';
/**
* @var array
*/
protected $tags = ['corporation'];
/**
* Execute the job.
*
* @return void
*
* @throws \Throwable
*/
public function handle()
{
$corporation = $this->retrieve([
'corporation_id' => $this->getCorporationId(),
]);
if ($corporation->isCachedLoad() && CorporationInfo::find($this->getCorporationId())) return;
$model = CorporationInfo::firstOrNew([
'corporation_id' => $this->getCorporationId(),
]);
InfoMapping::make($model, $corporation, [
'corporation_id' => function () {
return $this->getCorporationId();
},
])->save();
}
}
| gpl-2.0 |
biluna/biluna | acc/src/gui/acc_salesorderwidget.cpp | 35648 | /*****************************************************************
* $Id: acc_salesorderwidget.cpp 2217 2015-02-13 18:18:14Z rutger $
* Created: Jan 20, 2010 4:14:42 PM - rutger
*
* Copyright (C) 2010 Red-Bag. All rights reserved.
* This file is part of the Biluna ACC project.
*
* See http://www.red-bag.com for further details.
*****************************************************************/
#include "acc_salesorderwidget.h"
#include "acc.h"
#include "acc_dialogfactory.h"
#include "acc_salesinvoicehtml.h"
#include "acc_modelfactory.h"
#include "acc_objectfactory.h"
#include "acc_orderpreviewwidget.h"
#include "acc_processtransdoc.h"
#include "acc_salesquotationhtml.h"
#include "acc_selectstockitemwidget.h"
#include "acc_sotransdoc.h"
#include "acc_sqlcommonfunctions.h"
#include "acc_taxconfirmationwidget.h"
#include "rb_datawidgetmapper.h"
#include "rb_mdiwindow.h"
#include "rb_sqlrelationaldelegate.h"
/**
* Constructor
*/
ACC_SalesOrderWidget::ACC_SalesOrderWidget(QWidget *parent)
: RB_Widget(parent) {
setupUi(this);
mModel = NULL;
mChildModel = NULL;
mParentModel = NULL;
mMapper = NULL;
mChildMapper = NULL;
mDebtorTransList = NULL;
mTransDoc = NULL;
mCurrencyId = "";
mExchangeRate = 1.0;
}
/**
* Destructor
*/
ACC_SalesOrderWidget::~ACC_SalesOrderWidget() {
// unique models are always deleted by the widgets,
// can be MDI window or dialog, but also a dockWindow with table or tree
delete mDebtorTransList;
delete mTransDoc;
// mappers are deleted by the models
delete mChildModel;
delete mModel;
RB_DEBUG->print("ACC_SalesOrderWidget::~ACC_SalesOrderWidget() OK");
}
/**
* Initialize widget and models
*/
void ACC_SalesOrderWidget::init() {
tbbOrder->initEdit(false, true, true, false, true);
tvOrders->setToolButtonBar(tbbOrder);
connect(tbbOrder, SIGNAL(addClicked()),
this, SLOT(slotAddOrderClicked()));
connect(tbbOrder, SIGNAL(copyClicked()),
this, SLOT(slotCopyOrderClicked()));
//
// Set parent model, customer, for name only
//
mParentModel = ACC_MODELFACTORY->getModel(ACC_ModelFactory::ModelCustomer);
connect(mParentModel, SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
this, SLOT(slotParentSelectionChanged(QModelIndex,QModelIndex)));
//
// 1. Set model (not ID, is set by parent model) and/or query
//
mModel = ACC_MODELFACTORY->getModel(ACC_ModelFactory::ModelSalesOrder);
//
// 2. Set relations and mapper for line edits etc.
//
mMapper = mModel->getMapper();
// tab Delivery
mMapper->addMapping(leOrderNo, mModel->fieldIndex("orderno"));
mMapper->addMapping(leDeliverTo, mModel->fieldIndex("deliverto"));
addComboBoxMapping(mModel,"fromstkloc_id", "ACC_Location", "id",
"locationname", cbWarehouse, mMapper);
mMapper->addMapping(deOrderDate, mModel->fieldIndex("orddate"));
mMapper->addMapping(deDispatchDate, mModel->fieldIndex("deliverydate"));
mMapper->addMapping(ileContact, mModel->fieldIndex("contact_idx"));
mMapper->addMapping(leContactPhoneNumber, mModel->fieldIndex("contactphone"));
mMapper->addMapping(leContactEmail, mModel->fieldIndex("contactemail"));
mMapper->addMapping(leCustomerReference, mModel->fieldIndex("customerref"));
RB_StringList items;
items << tr("Show company details") << tr("Hide company details");
cbPacklistType->setModel(new QStringListModel(items, this));
mMapper->addMapping(cbPacklistType, mModel->fieldIndex("deliverblind"),
"currentIndex");
mMapper->addMapping(leChargeFreightcost, mModel->fieldIndex("freightcost"));
addComboBoxMapping(mModel,"shipvia_id", "ACC_Shipper", "id",
"shippername", cbFreightMethod, mMapper);
items.clear();
items << tr("No") << tr("Yes");
cbQuotationOnly->setModel(new QStringListModel(items, this));
mMapper->addMapping(cbQuotationOnly, mModel->fieldIndex("quotation"),
"currentIndex");
// tab Description
mMapper->addMapping(teComment, mModel->fieldIndex("comments"));
mMapper->addMapping(leOrderDescription, mModel->fieldIndex("ordertitle"));
// tab Address
mMapper->addMapping(leDeliveryAddress1, mModel->fieldIndex("deladd1"));
mMapper->addMapping(leDeliveryAddress2, mModel->fieldIndex("deladd2"));
mMapper->addMapping(leDeliveryAddress3, mModel->fieldIndex("deladd3"));
mMapper->addMapping(leDeliveryAddress4, mModel->fieldIndex("deladd4"));
mMapper->addMapping(leDeliveryAddress5, mModel->fieldIndex("deladd5"));
mMapper->addMapping(leDeliveryAddress6, mModel->fieldIndex("deladd6"));
// tab Invoice
mMapper->addMapping(leInvoiceComment, mModel->fieldIndex("invoicecomment"));
mMapper->addMapping(leConsignment, mModel->fieldIndex("consignment"));
//
// 3. Select after relations have been set, only for database models
//
// mModel->select(); not here done by parent model
// mModel->setHeaderData(RB2::HIDDENCOLUMNS, Qt::Horizontal, tr("Rutger"));
//
// 4. Connect model to main view
//
formatTableView(tvOrders, mModel);
//
// 0.
//
tbbDetail->initEdit(false, false);
tvDetails->setToolButtonBar(tbbDetail);
connect(tbbDetail, SIGNAL(addClicked()),
this, SLOT(slotAddDetailClicked()));
//
// 1. Set child model
// 2. Mapping and relations
// (3. Root will be set by selecting row in parent model)
// 4. connect to child (table) view
//
mChildModel = ACC_MODELFACTORY->getModel(ACC_ModelFactory::ModelSalesOrderDetail);
mChildMapper = mChildModel->getMapper();
mChildMapper->addMapping(ileStockCode, mChildModel->fieldIndex("stk_idx"));
mChildMapper->addMapping(leItemDescription, mChildModel->fieldIndex("stkdescription"));
mChildMapper->addMapping(leUnitOfMeasurement, mChildModel->fieldIndex("stkuom"));
mChildMapper->addMapping(leSerialNumber, mChildModel->fieldIndex("serialno"));
mChildMapper->addMapping(leUnitPrice, mChildModel->fieldIndex("unitprice"));
mChildMapper->addMapping(leQuantity, mChildModel->fieldIndex("quantity"));
mChildMapper->addMapping(leDiscountPercent, mChildModel->fieldIndex("discountpercent"));
mChildMapper->addMapping(pteNarrative, mChildModel->fieldIndex("narrative"));
// tab Dispatch
// not mChildMapper->addMapping(leOrderedQuantity, mChildModel->fieldIndex("quantity"));
mChildMapper->addMapping(leAlreadyDispatched, mChildModel->fieldIndex("qtyinvoiced"));
mChildMapper->addMapping(leCurrentDispatch, mChildModel->fieldIndex("qtydispatched"));
mChildMapper->addMapping(deItemDue, mChildModel->fieldIndex("itemdue"));
formatTableView(tvDetails, mChildModel);
connect(tvDetails->selectionModel(),
SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)),
this, SLOT(slotItemSelectionChanged(const QModelIndex&,const QModelIndex&)));
// Calculate total item price
connect(leUnitPrice, SIGNAL(editingFinished()),
this, SLOT(slotCalculateItemTotal()));
connect(leQuantity, SIGNAL(editingFinished()),
this, SLOT(slotCalculateItemTotal()));
connect(this->leDiscountPercent, SIGNAL(editingFinished()),
this, SLOT(slotCalculateItemTotal()));
readSettings();
for (int i = 0; i < mModel->columnCount(QModelIndex()); ++i) {
if (i != RB2::HIDDENCOLUMNS && i != RB2::HIDDENCOLUMNS + 1
&& i!= mModel->fieldIndex("ordertitle")) {
tvOrders->hideColumn(i);
} else {
tvOrders->showColumn(i);
if (tvOrders->columnWidth(i) < 5) {
tvOrders->setColumnWidth(i, 100);
}
}
}
for (int i = 0; i < mChildModel->columnCount(QModelIndex()); ++i) {
if (i != mChildModel->fieldIndex("stk_idx")
&& i!= mChildModel->fieldIndex("stkdescription")
&& i!= mChildModel->fieldIndex("stkuom")
&& i!= mChildModel->fieldIndex("unitprice")
&& i!= mChildModel->fieldIndex("quantity")
&& i!= mChildModel->fieldIndex("qtyinvoiced")
&& i!= mChildModel->fieldIndex("qtydispatched")
&& i!= mChildModel->fieldIndex("itemdue")){
tvDetails->hideColumn(i);
} else {
tvDetails->showColumn(i);
if (tvDetails->columnWidth(i) < 5) {
tvDetails->setColumnWidth(i, 100);
}
}
}
// Navigation widget has been set to the correct tab
// Request modelindex in case of already selected index
RB_Widget* wgt = ACC_DIALOGFACTORY->getWidget(ACC_DialogFactory::WidgetNavigation, NULL);
QModelIndex idx = wgt->getCurrentModelIndex(ACC_ModelFactory::ModelCustomer);
mModel->slotParentCurrentRowChanged(idx, QModelIndex());
slotParentSelectionChanged(idx, QModelIndex());
// TODO: if MaterialManagement tables exist and stock management true
// this->leCurrentDispatch->setEnabled(false);
// testing only, old
// RB_SignalSpyDialog* ssd = new RB_SignalSpyDialog(this, tvOrders /*mModel*/);
// ssd->show();
// testing only, new
// ACC_DIALOGFACTORY->setSignalSpyTarget(tvOrders);
}
bool ACC_SalesOrderWidget::fileSave(bool withSelect) {
beforeFileSave();
if (withSelect) {
mChildModel->submitAllRB();
mModel->submitAllAndSelect();
} else {
mChildModel->submitAllRB();
mModel->submitAllRB();
}
setWindowModified(false);
return true;
}
void ACC_SalesOrderWidget::fileRevert() {
mChildModel->revertAllRB();
mModel->revertAllRB();
setWindowModified(false);
}
void ACC_SalesOrderWidget::slotAddOrderClicked() {
if (!mModel->getCurrentIndex().isValid()) {
return;
}
// Get next sequence number
ACC_SqlCommonFunctions f;
int orderNo = f.getNextTransNo(ACC2::TransSalesOrder, "none", "Sales Order");
if (orderNo < 0) {
RB_DEBUG->print(RB_Debug::D_ERROR,
"ACC_SalesOrderWidget::on_pbAddOrder_clicked() orderNo ERROR");
}
// always insert at the beginning
int row = 0; // mModel->rowCount();
// NOTE: do not forget to set the default column values, specially for the
// relational table otherwise new row will not show!
QModelIndex orderIdx = mModel->index(row, mModel->fieldIndex("shipvia_id"));
mModel->setData(orderIdx, "0", Qt::EditRole);
orderIdx = mModel->index(row, mModel->fieldIndex("fromstkloc_id"));
mModel->setData(orderIdx, "0", Qt::EditRole);
orderIdx = mModel->index(row, mModel->fieldIndex("deliverblind"));
mModel->setData(orderIdx, 0, Qt::EditRole);
orderIdx = mModel->index(row, mModel->fieldIndex("quotation"));
mModel->setData(orderIdx, 0, Qt::EditRole);
// setExchangeRate();
// orderIdx = mModel->index(row, mModel->fieldIndex("rate"));
// mModel->setData(orderIdx, mExchangeRate, Qt::EditRole);
// end NOTE
tvOrders->setCurrentIndex(mModel->index(row, mModel->fieldIndex("orderno"), QModelIndex()));
QModelIndex parIdx = mParentModel->getCurrentIndex();
QModelIndex custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("mname"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deliverto"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("phoneno"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("contactphone"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("email"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("contactemail"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("brstreetaddress1"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deladd1"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("brstreetaddress2"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deladd2"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("brstreetaddress3"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deladd3"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("brstreetaddress4"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deladd4"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("brstreetaddress5"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deladd5"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("brstreetaddress6"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("deladd6"));
mModel->setData(orderIdx, custIdx.data(Qt::DisplayRole), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("defaultlocation_id"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("fromstkloc_id"));
mModel->setData(orderIdx, custIdx.data(RB2::RoleOrigData), Qt::EditRole);
custIdx = mParentModel->index(parIdx.row(), mParentModel->fieldIndex("defaultshipvia_id"), parIdx.parent());
orderIdx = mModel->index(row, mModel->fieldIndex("shipvia_id"));
mModel->setData(orderIdx, custIdx.data(RB2::RoleOrigData), Qt::EditRole);
QDate dt = QDate::currentDate();
orderIdx = mModel->index(row, mModel->fieldIndex("orddate"));
mModel->setData(orderIdx, dt.toString(Qt::ISODate), Qt::EditRole);
orderIdx = mModel->index(row, mModel->fieldIndex("deliverydate"));
mModel->setData(orderIdx, dt.toString(Qt::ISODate), Qt::EditRole);
orderIdx = mModel->index(row, mModel->fieldIndex("orderno"));
mModel->setData(orderIdx, orderNo, Qt::EditRole);
// tvOrders->setCurrentIndex(mModel->index(row, RB2::HIDDENCOLUMNS));
// tvOrders->scrollTo(tvOrders->currentIndex());
twOrderDetails->setCurrentIndex(0);
twItemDetails->setCurrentIndex(0);
leDeliverTo->setFocus();
leDeliverTo->selectAll();
}
void ACC_SalesOrderWidget::slotCopyOrderClicked() {
if (!mModel->getCurrentIndex().isValid()) {
return;
}
int row = mModel->getCurrentIndex().row();
// Get next sequence number
ACC_SqlCommonFunctions f;
int orderNo = f.getNextTransNo(ACC2::TransSalesOrder, "none", "Sales Order");
QModelIndex idx;
idx = mModel->index(row, mModel->fieldIndex("orderno"));
mModel->setData(idx, orderNo, Qt::EditRole);
idx = mModel->index(row, mModel->fieldIndex("customerref"));
mModel->setData(idx, "", Qt::EditRole);
QDate dt = QDate::currentDate();
idx = mModel->index(row, mModel->fieldIndex("orddate"));
mModel->setData(idx, dt.toString(Qt::ISODate), Qt::EditRole);
idx = mModel->index(row, mModel->fieldIndex("deliverydate"));
mModel->setData(idx, dt.toString(Qt::ISODate), Qt::EditRole);
int rowCount = mChildModel->rowCount();
for (int row = 0; row < rowCount; row++) {
idx = mChildModel->index(row, mChildModel->fieldIndex("qtyinvoiced"));
mChildModel->setData(idx, 0, Qt::EditRole);
idx = mChildModel->index(row, mChildModel->fieldIndex("qtydispatched"));
mChildModel->setData(idx, 0, Qt::EditRole);
idx = mChildModel->index(row, mChildModel->fieldIndex("itemdue"));
mChildModel->setData(idx, QDate::currentDate().toString(Qt::ISODate));
// refresh budget/cost center
idx = mChildModel->index(row, mChildModel->fieldIndex("stk_idx"));
QString stockId = mChildModel->data(idx, RB2::RoleOrigData).toString();
QString costCenterIdx =
f.selectFromWhereId("costcenter_idx", "acc_stockmaster",
stockId).toString();
idx = mChildModel->index(row, mChildModel->fieldIndex("costcenter_idx"));
mChildModel->setData(idx, costCenterIdx);
}
leDeliverTo->setFocus();
leDeliverTo->selectAll();
}
/**
* Button select item clicked
*/
void ACC_SalesOrderWidget::on_ileContact_clicked() {
if (!tvOrders->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestWarningDialog(tr("No sales order selected.\n"
"Please select an order first."));
return;
}
RB_DialogWindow* dlg = ACC_DIALOGFACTORY->getDialogWindow(ACC_DialogFactory::WidgetSelectContact);
int res = dlg->exec();
RB_ObjectBase* obj = dlg->getCurrentObject(); // was index
if (res == QDialog::Accepted && obj) {
RB_MmProxy* m = mModel;
int row = tvOrders->currentIndex().row();
QModelIndex idx = m->index(row, m->fieldIndex("contact_idx"));
m->setData(idx, obj->getId() + obj->getValue("firstname").toString()
+ " " + obj->getValue("lastname").toString(), Qt::EditRole);
idx = mModel->index(row, mModel->fieldIndex("contactphone"));
mModel->setData(idx, obj->getValue("phonework"), Qt::EditRole);
idx = mModel->index(row, mModel->fieldIndex("contactemail"));
mModel->setData(idx, obj->getValue("email1"), Qt::EditRole);
}
dlg->deleteLater();
}
void ACC_SalesOrderWidget::on_ileContact_clear() {
if (!tvOrders->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestWarningDialog(tr("No sales order selected.\n"
"Please select an order first."));
return;
}
RB_MmProxy* m = mModel;
int row = tvOrders->currentIndex().row();
QModelIndex idx = m->index(row, m->fieldIndex("contact_idx"));
m->setData(idx, "0", Qt::EditRole);
idx = mModel->index(row, mModel->fieldIndex("contactphone"));
mModel->setData(idx, "", Qt::EditRole);
idx = mModel->index(row, mModel->fieldIndex("contactemail"));
mModel->setData(idx, "", Qt::EditRole);
}
/**
* Button add order detail clicked
*/
void ACC_SalesOrderWidget::slotAddDetailClicked() {
if (!mChildModel->getCurrentIndex().isValid()) {
return;
}
int row = mChildModel->getCurrentIndex().row();
QModelIndex idx = mChildModel->index(row, mChildModel->fieldIndex("itemdue"));
mChildModel->setData(idx, QDate::currentDate().toString(Qt::ISODate),
Qt::EditRole);
tvDetails->setCurrentIndex(mChildModel->index(row,
mChildModel->fieldIndex("stk_idx"), QModelIndex()));
tvDetails->scrollTo(tvDetails->currentIndex());
twItemDetails->setCurrentIndex(0);
ileStockCode->setFocus();
}
/**
* Button select item clicked
*/
void ACC_SalesOrderWidget::on_ileStockCode_clicked() {
if (!tvDetails->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestWarningDialog(tr("No sales order item selected.\n"
"Please select an order item first."));
return;
}
RB_DialogWindow* dlg = ACC_DIALOGFACTORY->getDialogWindow(
ACC_DialogFactory::WidgetSelectStockMaster);
if (dlg->exec() != QDialog::Accepted) {
return;
}
// TODO: refactor to getCurrentObject to prevent casting
ACC_SelectStockItemWidget* wgt =
dynamic_cast<ACC_SelectStockItemWidget*>(dlg->getCentralWidget());
QModelIndex index = wgt->getCurrentChild1ModelIndex();
if (index.isValid()) {
RB_MmProxy* m = mChildModel;
// int row = m->getProxyIndex().row();
int row = tvDetails->currentIndex().row();
QModelIndex idx = m->index(row, m->fieldIndex("stk_idx"));
m->setData(idx, wgt->getStockId() + wgt->getCode(), Qt::EditRole);
idx = m->index(row, m->fieldIndex("stkdescription"));
m->setData(idx, wgt->getDescription(), Qt::EditRole);
idx = m->index(row, m->fieldIndex("stkuom"));
m->setData(idx, wgt->getUnitOfMeasurement(), Qt::EditRole);
idx = m->index(row, m->fieldIndex("serialno"));
m->setData(idx, wgt->getSerialNumber(), Qt::EditRole);
idx = m->index(row, m->fieldIndex("unitprice"));
m->setData(idx, wgt->getPrice(), Qt::EditRole);
idx = m->index(row, m->fieldIndex("quantity"));
m->setData(idx, 0.0, Qt::EditRole);
idx = m->index(row, m->fieldIndex("narrative"));
m->setData(idx, RB_String(""), Qt::EditRole);
leDiscountPercent->setText("0");
leTotalItemPrice->setText("0.00");
idx = m->index(row, m->fieldIndex("taxcat_id"));
m->setData(idx, wgt->getTaxCatId(), Qt::EditRole);
idx = m->index(row, m->fieldIndex("costcenter_idx"));
m->setData(idx, wgt->getCostCenterIdx(), Qt::EditRole);
}
dlg->deleteLater();
}
void ACC_SalesOrderWidget::on_ileStockCode_clear() {
if (!tvDetails->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestWarningDialog(tr("No sales order item selected.\n"
"Please select an order item first."));
return;
}
RB_MmProxy* m = mChildModel;
int row = tvDetails->currentIndex().row();
// QModelIndex idx = m->index(row, m->fieldIndex("stk_idx")); already by ileStockCode
// m->setData(idx, dlg->getStockId()+ dlg->getCode(), Qt::EditRole);
QModelIndex idx = m->index(row, m->fieldIndex("stkdescription"));
m->setData(idx, RB_String(""), Qt::EditRole);
idx = m->index(row, m->fieldIndex("stkuom"));
m->setData(idx, RB_String(""), Qt::EditRole);
idx = m->index(row, m->fieldIndex("serialno"));
m->setData(idx, RB_String(""), Qt::EditRole);
idx = m->index(row, m->fieldIndex("unitprice"));
m->setData(idx, 0.0, Qt::EditRole);
idx = m->index(row, m->fieldIndex("quantity"));
m->setData(idx, 0.0, Qt::EditRole);
idx = m->index(row, m->fieldIndex("narrative"));
m->setData(idx, RB_String(""), Qt::EditRole);
leDiscountPercent->setText("0");
leTotalItemPrice->setText("0.00");
idx = m->index(row, m->fieldIndex("taxcat_id"));
m->setData(idx, "0", Qt::EditRole);
idx = m->index(row, m->fieldIndex("costcenter_idx"));
m->setData(idx, "0", Qt::EditRole);
}
void ACC_SalesOrderWidget::on_pbPreviewPrintQuotation_clicked() {
if (!tvOrders->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("No order selected."));
return;
}
if (isWindowModified()) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("Save your data first."));
return;
}
if (cbQuotationOnly->currentIndex() != 1) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("Note: not a quotation,\n"
"this is a sales order."));
}
bool isOrder;
if (mModel->getCurrentValue("quotation", Qt::EditRole) != 1) {
isOrder = true;
} else {
isOrder = false;
}
ACC_SalesQuotationHtml oper;
oper.setIsOrder(isOrder);
if (!oper.execute(mModel->getObject(tvOrders->currentIndex(), RB2::ResolveAll))) {
// Mistake, for example: the GL account of supplier is not set
ACC_DIALOGFACTORY->requestWarningDialog(tr("Could not process the order. \n"
"For example: order is completed, \n"
"order has no items or \n"
"value of items is not set."));
return;
}
RB_String fileName;
if (isOrder) {
fileName = "so_" + leOrderNo->text();
} else {
fileName = "sq_" + leOrderNo->text();
}
// Show preview invoice dialog
RB_DialogWindow* dlg =
ACC_DIALOGFACTORY->getDialogWindow(ACC_DialogFactory::WidgetOrderPreview);
ACC_OrderPreviewWidget* wgt
= dynamic_cast<ACC_OrderPreviewWidget*>(dlg->getCentralWidget());
dlg->setWindowTitle("ACC - Quotation");
wgt->setCurrentFileName(fileName);
wgt->setHtml(oper.getHtml());
dlg->exec();
dlg->deleteLater();
}
/**
* Button preview invoice clicked
*/
void ACC_SalesOrderWidget::on_pbPreviewInvoice_clicked() {
if (!tvOrders->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("No order selected."));
return;
}
if (isWindowModified()) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("Save your data first."));
return;
}
if (cbQuotationOnly->currentIndex() != 0) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("Quotation only."));
return;
}
// Translate sales order in transaction document and debtor details
if (translateSalesOrder(false) == QDialog::Rejected) {
// Canceled or nothing to invoice
return;
}
ACC_SalesInvoiceHtml oper;
if (!oper.execute(mTransDoc, mDebtorTransList)) {
QApplication::restoreOverrideCursor();
// Mistake, for example: the GL account of customer is not set
ACC_DIALOGFACTORY->requestWarningDialog(tr("Could not preview the invoice. \n"
"For example:\n"
"- sales GL posting of product category,\n"
"- sales area, \n"
"- sales type, \n"
"- company tax province, \n"
"- customer tax group or \n"
"- delivery location is not set."));
return;
}
// Show preview invoice dialog
RB_DialogWindow* dlg =
ACC_DIALOGFACTORY->getDialogWindow(ACC_DialogFactory::WidgetOrderPreview);
ACC_OrderPreviewWidget* wgt
= dynamic_cast<ACC_OrderPreviewWidget*>(dlg->getCentralWidget());
dlg->setWindowTitle("ACC - Preview Invoice");
wgt->setCurrentFileName("so_invoice_" + mTransDoc->getValue("transno").toString());
wgt->setHtml(oper.getHtml());
dlg->exec();
dlg->deleteLater();
}
/**
* Button confirm dispatch and process invoice clicked
*/
void ACC_SalesOrderWidget::on_pbProcessInvoice_clicked() {
if (!tvOrders->currentIndex().isValid()) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("No order selected."));
return;
}
if (isWindowModified()) {
ACC_DIALOGFACTORY->requestInformationDialog(tr("Save your data first."));
return;
}
if (cbQuotationOnly->currentIndex() != 0) { // not No is Yes
ACC_DIALOGFACTORY->requestInformationDialog(tr("Quotation only."));
return;
}
// Translate sales order in transaction document and debtor details
if (translateSalesOrder(true) == QDialog::Rejected) {
// Canceled or nothing to invoice
return;
}
setExchangeRate();
// Rate could have been changed in the mean time
// QModelIndex orderIdx = tvOrders->currentIndex();
// if (orderIdx.isValid()) {
// orderIdx = mModel->index(orderIdx.row(), mModel->fieldIndex("rate"));
// mModel->setData(orderIdx, mExchangeRate, Qt::EditRole);
// }
// Process invoice and post debtor and general ledger transactions
// and handle exchange rate of customer currency
ACC_ProcessTransDoc operTransDoc;
if (!operTransDoc.execute(mTransDoc, mDebtorTransList, mExchangeRate)) {
// Mistake, for example: the GL account of customer is not set
ACC_DIALOGFACTORY->requestWarningDialog(tr("Could not process the invoice. \n"
"For example:\n"
"- sales GL posting of product category,\n"
"- sales area, \n"
"- sales type, \n"
"- company tax province, \n"
"- customer tax group or \n"
"- delivery location is not set."));
return;
}
// Process stock moves the TODO to be part of material management
/* From ACC_ProcessInvoice based on stockmoves from webERP, not used anymore
*
* Execute debtor, stock and General Ledger transactions
*
* -> Salesorder, DONE
* 1-Update sales order comment
*
* -> TODO: Stockmoves and sales
* 21-Update salesorderdetail quantities
* 22-Insert orderdeliverydifferenceslog
* 23-Update salesorderdetail for quantity invoiced and actual dispatch dates
* 24-Update location stock records if not a dummy stock item M, B (MBflag Make, Buy)
* else A (Assembly)
* 25-Insert stockmoves, different for M, B flag and A flag
* 26-Insert stockmovestaxes
* 27-Insert stockserialmovements
* 28-Insert and update salesanalysis records
*
* -> General Ledger, DONE
* 31-Cost of sales
* 32-Stock
* 33-Net sales
* 34-Discount
* 35-Gross sales
* 36-Freight
* 37-Tax
*
* @returns true on success
*/
ACC_SalesInvoiceHtml oper;
oper.execute(mTransDoc, mDebtorTransList);
// Show final invoice dialog
RB_DialogWindow* dlg =
ACC_DIALOGFACTORY->getDialogWindow(ACC_DialogFactory::WidgetOrderPreview);
ACC_OrderPreviewWidget* wgt
= dynamic_cast<ACC_OrderPreviewWidget*>(dlg->getCentralWidget());
dlg->setWindowTitle("ACC - Invoice");
wgt->setCurrentFileName("so_invoice_" + mTransDoc->getValue("transno").toString());
wgt->setHtml(oper.getHtml());
dlg->exec();
dlg->deleteLater();
}
/**
* Translate sales order in transaction document,
* create price salestaxes per line item for confirmation
* @param isPost false if this is only to preview the invoice
*/
int ACC_SalesOrderWidget::translateSalesOrder(bool isPost) {
QApplication::setOverrideCursor(Qt::WaitCursor);
// Reset debtor transactions
if (mDebtorTransList) {
delete mDebtorTransList;
}
mDebtorTransList = new RB_ObjectContainer(RB_Uuid::createUuid().toString(), NULL,
"ACC_DebtorTransList", ACC_OBJECTFACTORY);
// Reset document
if (mTransDoc) {
delete mTransDoc;
}
mTransDoc = ACC_OBJECTFACTORY->newSingleObject("ACC_TransDoc");
// Set transaction document data and relevant taxes of this order
ACC_SoTransDoc oper;
if (!oper.preparePreview(mTransDoc, mDebtorTransList)) {
QApplication::restoreOverrideCursor();
ACC_DIALOGFACTORY->requestWarningDialog(tr("Could not preview the invoice. \n"
"For example:\n"
"- sales GL posting of product category,\n"
"- sales area, \n"
"- sales type, \n"
"- company tax province, \n"
"- customer tax group or \n"
"- delivery location\n"
"is not set."));
return QDialog::Rejected;
}
// Check whether there are amounts to be invoiced
double invoiceAmount = 0.0;
RB_ObjectIterator* iterDt = mDebtorTransList->getIterator();
for (iterDt->first(); !iterDt->isDone(); iterDt->next()) {
RB_ObjectBase* debtorTrans = iterDt->currentObject();
invoiceAmount += debtorTrans->getValue("amount").toDouble();
}
if (invoiceAmount <= 0.0) {
QApplication::restoreOverrideCursor();
ACC_DIALOGFACTORY->requestWarningDialog(tr("There are no quantities to invoice\n"
"or the salesorder is completed."));
return QDialog::Rejected;
}
QApplication::restoreOverrideCursor();
// Show tax confirmation dialog if not for posting invoice
bool isSalesOrder = true;
RB_DialogWindow* dlg = ACC_DIALOGFACTORY->getDialogWindow(
ACC_DialogFactory::WidgetTaxConfirmation);
ACC_TaxConfirmationWidget* wgt =
dynamic_cast<ACC_TaxConfirmationWidget*>(dlg->getCentralWidget());
wgt->setTransModel(mTransDoc, mDebtorTransList, isSalesOrder);
int result = dlg->exec();
if (isPost && result == QDialog::Accepted) {
// Get invoice number and update quantities in order detail items
oper.preparePost(mTransDoc);
}
dlg->deleteLater();
return result;
}
/**
* Set exchange rate based on the currency of the customer
*/
void ACC_SalesOrderWidget::setExchangeRate() {
if (mCurrencyId.size() < 38) {
mExchangeRate = 1.0;
} else {
ACC_SqlCommonFunctions f;
mExchangeRate = f.selectFromWhereId("rate", "ACC_Currency", mCurrencyId).toDouble();
}
}
/**
* Slot to set name of supplier
*/
void ACC_SalesOrderWidget::slotParentSelectionChanged(const QModelIndex& current,
const QModelIndex& /*previous*/) {
if (current.isValid()) {
leCustomer->setText(mParentModel->getCurrentValue("mname").toString());
mCurrencyId = mParentModel->getCurrentValue("currency_id", RB2::RoleOrigData).toString();
} else {
leCustomer->setText("");
mCurrencyId = "";
}
}
/**
* Slot calculate item total based on selected item changed
*/
void ACC_SalesOrderWidget::slotItemSelectionChanged(const QModelIndex& /*current*/,
const QModelIndex& /* previous */) {
slotCalculateItemTotal();
}
/**
* Slot calculate item total price based on quantity, unit price and discount
*/
void ACC_SalesOrderWidget::slotCalculateItemTotal() {
double price = leUnitPrice->text().toDouble();
double qty = leQuantity->text().toDouble();
double discount = leDiscountPercent->text().toDouble() / 100.0;
if (0.0 <= discount && discount <= 1.0 && qty >= 0.0 && price >= 0.0) {
double totalPrice = price * qty * (1.0 - discount);
leTotalItemPrice->setText(RB_String::number(totalPrice));
} else if (discount == 0.0 && qty >= 0.0 && price < 0.0) {
leTotalItemPrice->setText("discount");
} else {
leTotalItemPrice->setText("error");
}
// Repeat value
leOrderedQuantity->setText(leQuantity->text());
}
/**
* @returns the help subject, in this case the widget objectname
*/
RB_String ACC_SalesOrderWidget::getHelpSubject() const {
return objectName();
}
/**
* Change event, for example translation
*/
void ACC_SalesOrderWidget::changeEvent(QEvent *e) {
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
retranslateUi(this);
break;
default:
break;
}
}
| gpl-2.0 |
thebrightspark/BitsAndBobs | src/main/java/com/brightspark/bitsandbobs/block/BlockChatter.java | 1462 | package com.brightspark.bitsandbobs.block;
import com.brightspark.bitsandbobs.tileentity.TileChatter;
import com.brightspark.bitsandbobs.util.CommonUtils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class BlockChatter extends BABBlockContainer
{
public BlockChatter()
{
super("chatter");
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileChatter();
}
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos)
{
//TODO: Only send the message when a redstone pulse is received
if(!worldIn.isRemote)
{
TileEntity te = worldIn.getTileEntity(pos);
if(te instanceof TileChatter)
((TileChatter) te).sendMessage();
}
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
if(world.isRemote && !player.isSneaking())
CommonUtils.openGui(player, world, pos);
return true;
}
}
| gpl-2.0 |
arobbins/wp-shopify | gulp/tasks/css-public.js | 548 | /////////
// CSS //
/////////
import gulp from 'gulp';
import config from '../config';
import sass from 'gulp-sass';
import rename from "gulp-rename";
import postcss from 'gulp-postcss';
import gulpStylelint from 'gulp-stylelint';
gulp.task('css-public', () => {
return gulp.src(config.files.cssEntryPublic)
.pipe(sass())
.pipe(gulpStylelint( config.stylelintConfig() ))
.pipe(postcss( config.postCSSPlugins() ))
.pipe(rename(config.names.cssPublic))
.pipe(gulp.dest(config.folders.dist))
.pipe(config.bs.stream());
});
| gpl-2.0 |
DeGuitard/moviesearch | moviesearch/src/main/java/fr/univtls2/web/moviesearch/services/indexation/normalization/rules/TransformationRule.java | 548 | package fr.univtls2.web.moviesearch.services.indexation.normalization.rules;
import fr.univtls2.web.moviesearch.model.Term;
/**
* <p>Interface that describe a transformation rule.</p>
* <p>Typically used to transform words, for instance: 'documentation' => 'documen'.</p>
*
* @author Vianney Dupoy de Guitard
*/
public interface TransformationRule {
/**
* Transforms a term with a normalization rule.
* @param termToTransform : the term to transform.
* @return the new transformed term.
*/
Term transform(Term termToTransform);
}
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/QulightUI/Addons/Infotext/Bags.lua | 1442 | --------------------------------------------------------------------
-- BAGS
--------------------------------------------------------------------
if Qulight["datatext"].Bags and Qulight["datatext"].Bags > 0 then
local Stat = CreateFrame("Frame")
Stat:EnableMouse(true)
Stat:SetFrameStrata("BACKGROUND")
Stat:SetFrameLevel(3)
local Text = DataLeftPanel:CreateFontString(nil, "OVERLAY")
Text:SetFont(Qulight["media"].font, 10, "OVERLAY")
PP(Qulight["datatext"].Bags, Text)
local function OnEvent(self, event, ...)
local free, total, used = 0, 0, 0
for i = 0, NUM_BAG_SLOTS do
free, total = free + GetContainerNumFreeSlots(i), total + GetContainerNumSlots(i)
end
used = total - free
Text:SetText("背包: "..qColor..free)
Stat:SetAllPoints(Text)
Stat:SetScript("OnEnter", function()
GameTooltip:SetOwner(self, "ANCHOR_TOP", 0, 6);
GameTooltip:ClearAllPoints()
GameTooltip:SetPoint("BOTTOM", self, "TOP", 0, 1)
GameTooltip:ClearLines()
GameTooltip:AddDoubleLine("背包")
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine("总数:",total,0, 0.6, 1, 1, 1, 1)
GameTooltip:AddDoubleLine("已使用:",used,0, 0.6, 1, 1, 0.5, 0)
GameTooltip:Show()
end)
Stat:SetScript("OnLeave", function() GameTooltip:Hide() end)
end
Stat:RegisterEvent("PLAYER_LOGIN")
Stat:RegisterEvent("BAG_UPDATE")
Stat:SetScript("OnEvent", OnEvent)
Stat:SetScript("OnMouseDown", function() OpenAllBags() end)
end | gpl-2.0 |
openjdk/jdk8u | jdk/src/linux/classes/jdk/internal/platform/cgroupv1/SubSystem.java | 9771 | /*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.platform.cgroupv1;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigInteger;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;
public class SubSystem {
String root;
String mountPoint;
String path;
public SubSystem(String root, String mountPoint) {
this.root = root;
this.mountPoint = mountPoint;
}
public void setPath(String cgroupPath) {
if (root != null && cgroupPath != null) {
if (root.equals("/")) {
if (!cgroupPath.equals("/")) {
path = mountPoint + cgroupPath;
}
else {
path = mountPoint;
}
}
else {
if (root.equals(cgroupPath)) {
path = mountPoint;
}
else {
if (cgroupPath.startsWith(root)) {
if (cgroupPath.length() > root.length()) {
String cgroupSubstr = cgroupPath.substring(root.length());
path = mountPoint + cgroupSubstr;
}
}
}
}
}
}
public String path() {
return path;
}
/**
* getSubSystemStringValue
*
* Return the first line of the file "parm" argument from the subsystem.
*
* TODO: Consider using weak references for caching BufferedReader object.
*
* @param subsystem
* @param parm
* @return Returns the contents of the file specified by param.
*/
public static String getStringValue(SubSystem subsystem, String parm) {
if (subsystem == null) return null;
try {
return subsystem.readStringValue(parm);
} catch (IOException e) {
return null;
}
}
private String readStringValue(String param) throws IOException {
PrivilegedExceptionAction<BufferedReader> pea = () ->
Files.newBufferedReader(Paths.get(path(), param));
try (BufferedReader bufferedReader =
AccessController.doPrivileged(pea)) {
String line = bufferedReader.readLine();
return line;
} catch (PrivilegedActionException e) {
Metrics.unwrapIOExceptionAndRethrow(e);
throw new InternalError(e.getCause());
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
public static long getLongValueMatchingLine(SubSystem subsystem,
String param,
String match,
Function<String, Long> conversion) {
long retval = Metrics.unlimited_minimum + 1; // default unlimited
try {
List<String> lines = subsystem.readMatchingLines(param);
for (String line: lines) {
if (line.contains(match)) {
retval = conversion.apply(line);
break;
}
}
} catch (IOException e) {
// Ignore. Default is unlimited.
}
return retval;
}
private List<String> readMatchingLines(String param) throws IOException {
try {
PrivilegedExceptionAction<List<String>> pea = () ->
Files.readAllLines(Paths.get(path(), param));
return AccessController.doPrivileged(pea);
} catch (PrivilegedActionException e) {
Metrics.unwrapIOExceptionAndRethrow(e);
throw new InternalError(e.getCause());
} catch (UncheckedIOException e) {
throw e.getCause();
}
}
public static long getLongValue(SubSystem subsystem, String parm) {
String strval = getStringValue(subsystem, parm);
return convertStringToLong(strval);
}
public static long convertStringToLong(String strval) {
if (strval == null) return 0L;
long retval = 0;
try {
retval = Long.parseLong(strval);
} catch (NumberFormatException e) {
// For some properties (e.g. memory.limit_in_bytes) we may overflow the range of signed long.
// In this case, return Long.max
BigInteger b = new BigInteger(strval);
if (b.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
return Long.MAX_VALUE;
}
}
return retval;
}
public static double getDoubleValue(SubSystem subsystem, String parm) {
String strval = getStringValue(subsystem, parm);
if (strval == null) return 0L;
double retval = Double.parseDouble(strval);
return retval;
}
/**
* getSubSystemlongEntry
*
* Return the long value from the line containing the string "entryname"
* within file "parm" in the "subsystem".
*
* TODO: Consider using weak references for caching BufferedReader object.
*
* @param subsystem
* @param parm
* @param entryname
* @return long value
*/
public static long getLongEntry(SubSystem subsystem, String parm, String entryname) {
String val = null;
if (subsystem == null) return 0L;
try (Stream<String> lines = Metrics.readFilePrivileged(Paths.get(subsystem.path(), parm))) {
Optional<String> result = lines.map(line -> line.split(" "))
.filter(line -> (line.length == 2 &&
line[0].equals(entryname)))
.map(line -> line[1])
.findFirst();
return result.isPresent() ? Long.parseLong(result.get()) : 0L;
} catch (IOException e) {
return 0L;
} catch (UncheckedIOException e) {
return 0L;
}
}
public static int getIntValue(SubSystem subsystem, String parm) {
String val = getStringValue(subsystem, parm);
if (val == null) return 0;
return Integer.parseInt(val);
}
/**
* StringRangeToIntArray
*
* Convert a string in the form of 1,3-4,6 to an array of
* integers containing all the numbers in the range.
*
* @param range
* @return int[] containing a sorted list of processors or memory nodes
*/
public static int[] StringRangeToIntArray(String range) {
int[] ints = new int[0];
if (range == null) return ints;
ArrayList<Integer> results = new ArrayList<>();
String strs[] = range.split(",");
for (String str : strs) {
if (str.contains("-")) {
String lohi[] = str.split("-");
// validate format
if (lohi.length != 2) {
continue;
}
int lo = Integer.parseInt(lohi[0]);
int hi = Integer.parseInt(lohi[1]);
for (int i = lo; i <= hi; i++) {
results.add(i);
}
}
else {
results.add(Integer.parseInt(str));
}
}
// sort results
results.sort(null);
// convert ArrayList to primitive int array
ints = new int[results.size()];
int i = 0;
for (Integer n : results) {
ints[i++] = n;
}
return ints;
}
public static class MemorySubSystem extends SubSystem {
private boolean hierarchical;
private boolean swapenabled;
public MemorySubSystem(String root, String mountPoint) {
super(root, mountPoint);
}
boolean isHierarchical() {
return hierarchical;
}
void setHierarchical(boolean hierarchical) {
this.hierarchical = hierarchical;
}
boolean isSwapEnabled() {
return swapenabled;
}
void setSwapEnabled(boolean swapenabled) {
this.swapenabled = swapenabled;
}
}
}
| gpl-2.0 |
diegoferose/portalWebEsteSiEs | view/intinerarioView.php | 9425 | <!DOCTYPE html>
<!--
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.
-->
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1 maximum-scale=1, user-scalable=no"/>
<link type="text/css" rel="stylesheet" href="../web/css/stylesheet.css"/>
<link rel="stylesheet" href="../web/css/bootstrap.min.css">
<title></title>
</head>
<body>
<div class="modal fade" id="miventana" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header ">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<img src="../web/img/logo.png" height="310" width="410" class="img-responsive">
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<a>¿No tienes cuenta? Registrate</a><br><br>
<button type="submit" class="btn btn-success btn-lg">Ingresar</button>
<button type="button" class="btn btn-danger btn-lg" data-dismiss="modal" aria-hidden="true">Cancelar</button>
</form>
</div>
</div>
</div>
</div>
<div class="container container-fluid">
<div class="row">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="../web/img/logo1.png" height="30" width="50"></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="¿Que desea buscar?">
</div>
<button type="submit" class="btn btn-default">Buscar</button>
</form>
<li><a data-toggle="modal" data-target="#miventana">Iniciar Sesion</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Menu <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Categorias</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Eventos</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Sitios</a></li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
<div class="row">
<div class="contenedor">
<h1>ITINERARIO</h1>
<table class="table table-striped table-responsive">
<thead>
<th>Horario</th>
<th>Lugar</th>
<th>Descripcion</th>
<th>Direccion</th>
<th>enlace</th>
<th>acciones</th>
</thead>
<tbody>
<tr>
<td>8am - 9am</td>
<td>Basilica</td>
<td>misa en la basilica</td>
<td>avenida 4 con carrera 14</td>
<td><a>informacion del sitio</a></td>
<td><input type="checkbox">Realizado <input type="button" class="btn btn-danger" value="Eliminar"></td>
</tr>
<tr>
<td>8am - 9am</td>
<td>Basilica</td>
<td>misa en la basilica</td>
<td>avenida 4 con carrera 14</td>
<td><a>informacion del sitio</a></td>
<td><input type="checkbox">Realizado <input type="button" class="btn btn-danger" value="Eliminar"></td>
</tr>
<tr>
<td>8am - 9am</td>
<td>Basilica</td>
<td>misa en la basilica</td>
<td>avenida 4 con carrera 14</td>
<td><a>informacion del sitio</a></td>
<td><input type="checkbox">Realizado <input type="button" class="btn btn-danger" value="Eliminar"></td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- <div class="row">
<div class="categoria">
<div class="row">
<div class="col-sm-6 col-md-4">
<img src="../web/img/religioso.png" alt="..." height="150" width="150">
<div class="caption">
<h3 class="enlaces">Categoria 1</h3>
<p>...</p>
</div>
</div>
<div class="col-sm-6 col-md-4">
<img src="../web/img/turista.png" alt="..." height="150" width="150">
<div class="caption">
<h3 class="enlaces">Categoria 1</h3>
<p>...</p>
</div>
</div>
<div class="col-sm-6 col-md-4">
<img src="../web/img/bar.png" alt="..." height="150" width="150">
<div class="caption">
<h3 class="enlaces">Categoria 1</h3>
<p>...</p>
</div>
</div>
</div>
</div>
</div>-->
<div class="row">
<div class="piee">
<div class="enlaces">
Copyright reserved(C)
</div>
</div>
</div>
</div>
</div>
<script src="../web/js/jquery-2.1.4.min.js"></script>
<script src="../web/js/bootstrap.min.js"></script>
</body>
</html>
| gpl-2.0 |
aclements/mtrace | mtrace-tools/crud/sersec.cc | 9334 | #include <stdio.h>
#include <string.h>
#include <ext/hash_map>
#include <assert.h>
#include <cinttypes>
#include <list>
extern "C" {
#include <mtrace-magic.h>
#include "util.h"
}
#include "mscan.hh"
#include "hash.h"
#include "sersec.hh"
//
// LockManager
//
bool
LockManager::release(const struct mtrace_lock_entry* lock, SerialSection& ss)
{
static int misses;
LockState* ls;
auto it = state_.find(lock->lock);
if (it == state_.end()) {
misses++;
if (misses >= 20)
die("LockManager: released too many unheld locks");
return false;
}
ls = it->second;
ls->release(lock);
if (ls->depth_ == 0) {
ss = ls->ss_;
stack_.remove(ls);
state_.erase(it);
delete ls;
return true;
}
return false;
}
void
LockManager::acquire(const struct mtrace_lock_entry* lock)
{
auto it = state_.find(lock->lock);
if (it == state_.end()) {
pair<LockStateTable::iterator, bool> r;
LockState* ls = new LockState();
r = state_.insert(pair<uint64_t, LockState*>(lock->lock, ls));
if (!r.second)
die("acquire: insert failed");
stack_.push_front(ls);
it = r.first;
}
it->second->acquire(lock);
}
void
LockManager::acquired(const struct mtrace_lock_entry* lock)
{
static int misses;
auto it = state_.find(lock->lock);
if (it == state_.end()) {
misses++;
if (misses >= 10)
die("acquired: acquired too many missing locks");
return;
}
it->second->acquired(lock);
}
bool
LockManager::access(const struct mtrace_access_entry* a, SerialSection& ss)
{
if (stack_.empty()) {
ss.start = a->h.ts;
ss.end = ss.start + 1;
ss.acquire_cpu = a->h.cpu;
ss.release_cpu = a->h.cpu;
ss.call_pc = mtrace_call_pc[a->h.cpu];
ss.acquire_pc = a->pc;
if (a->traffic)
ss.per_pc_coherence_miss[a->pc] = 1;
else if (a->lock)
ss.locked_inst = 1;
return true;
}
stack_.front()->access(a);
return false;
}
//
// SerialSections
//
SerialSections::SerialSections(void)
: lock_manager_()
{
}
void
SerialSections::handle(const union mtrace_entry* entry)
{
if (!guest_enabled_mtrace())
return;
switch (entry->h.type) {
case mtrace_entry_access:
handle_access(&entry->access);
break;
case mtrace_entry_lock:
handle_lock(&entry->lock);
break;
default:
die("SerialSections::handle type %u", entry->h.type);
}
}
void
SerialSections::exit(void)
{
auto it = stat_.begin();
printf("serial sections:\n");
for (; it != stat_.end(); ++it) {
SerialSectionStat* stat = &it->second;
printf(" %s %" PRIu64" %" PRIu64"\n",
stat->name.c_str(),
stat->summary.total_cycles(),
stat->summary.acquires);
}
}
void
SerialSections::exit(JsonDict* json_file)
{
JsonList* list = JsonList::create();
auto it = stat_.begin();
for (; it != stat_.end(); ++it) {
SerialSectionStat* stat = &it->second;
JsonDict* dict = JsonDict::create();
dict->put("name", stat->name);
dict->put("section-type", stat->lock_section ? "lock" : "instruction");
populateSummaryDict(dict, &stat->summary);
JsonList* pc_list = JsonList::create();
auto mit = stat->per_pc.begin();
for (; mit != stat->per_pc.end(); ++mit) {
JsonDict* pc_dict = JsonDict::create();
SerialSectionSummary* sum = &mit->second;
pc_t pc = mit->first;
pc_dict->put("pc", new JsonHex(pc));
pc_dict->put("info", addr2line->function_description(pc));
populateSummaryDict(pc_dict, sum);
pc_list->append(pc_dict);
}
dict->put("per-acquire-pc", pc_list);
JsonList* tid_list = JsonList::create();
auto tit = stat->per_tid.begin();
for (; tit != stat->per_tid.end(); ++tit) {
JsonDict* tid_dict = JsonDict::create();
SerialSectionSummary* sum = &tit->second;
tid_t tid = tit->first;
tid_dict->put("tid", tid);
tid_dict->put("acquires", sum->acquires);
tid_list->append(tid_dict);
}
dict->put("tids", tid_list);
list->append(dict);
}
json_file->put("serial-sections", list);
}
timestamp_t
SerialSections::total_cycles(void) const
{
timestamp_t sum = 0;
auto it = stat_.begin();
for (; it != stat_.end(); ++it)
sum += it->second.summary.total_cycles();
return sum;
}
uint64_t
SerialSections::coherence_misses(void) const
{
uint64_t sum = 0;
auto it = stat_.begin();
for (; it != stat_.end(); ++it)
sum += it->second.summary.coherence_misses();
return sum;
}
void
SerialSections::populateSummaryDict(JsonDict* dict, SerialSectionSummary* sum)
{
timestamp_t tot;
float bench_frac;
JsonList* list;
int i;
tot = sum->total_cycles();
dict->put("total-instructions", tot);
bench_frac = (float)tot / (float)total_instructions();
dict->put("benchmark-fraction", bench_frac);
list = JsonList::create();
for (i = 0; i < mtrace_summary.num_cpus; i++) {
float percent;
percent = 0.0;
if (tot != 0.0)
percent = 100.0 * ((float)sum->ts_cycles[i] / (float)tot);
list->append(percent);
}
dict->put("per-cpu-percent", list);
dict->put("acquires", sum->acquires);
JsonList* coherence_list = JsonList::create();
auto it = sum->per_pc_coherence_miss.begin();
for (; it != sum->per_pc_coherence_miss.end(); ++it) {
JsonDict* coherence_dict = JsonDict::create();
pc_t pc = it->first;
coherence_dict->put("pc", new JsonHex(pc));
coherence_dict->put("info", addr2line->function_description(pc));
coherence_dict->put("count", it->second);
coherence_list->append(coherence_dict);
}
dict->put("coherence-miss", sum->coherence_misses());
dict->put("coherence-miss-list", coherence_list);
dict->put("locked-inst", sum->locked_inst);
dict->put("mismatches", sum->mismatches);
}
void
SerialSections::handle_lock(const struct mtrace_lock_entry* l)
{
switch (l->op) {
case mtrace_lockop_release: {
SerialSection ss;
if (lock_manager_.release(l, ss)) {
MtraceObject object;
SerialSectionKey key;
if (!mtrace_label_map.object(l->lock, object)) {
fprintf(stderr, "SerialSections::handle: missing %" PRIx64" (%s) %" PRIx64"\n",
l->lock, l->str, l->pc);
return;
}
key.lock_id = l->lock;
key.obj_id = object.id_;
auto it = stat_.find(key);
if (it == stat_.end()) {
stat_[key].init(&object, l);
it = stat_.find(key);
}
it->second.add(&ss);
}
break;
}
case mtrace_lockop_acquire:
lock_manager_.acquire(l);
break;
case mtrace_lockop_acquired:
lock_manager_.acquired(l);
break;
default:
die("SerialSections::handle: bad op");
}
}
void
SerialSections::handle_access(const struct mtrace_access_entry* a)
{
SerialSection ss;
if (lock_manager_.access(a, ss)) {
MtraceObject object;
SerialSectionKey key;
key.obj_id = 0;
if (mtrace_label_map.object(a->guest_addr, object))
key.obj_id = object.id_;
key.lock_id = a->guest_addr;
auto it = stat_.find(key);
if (it == stat_.end()) {
stat_[key].init(&object, a, object.name_);
it = stat_.find(key);
}
it->second.add(&ss);
}
}
//
// SerialSections::SerialSectionSummary
//
SerialSections::SerialSectionSummary::SerialSectionSummary(void)
: per_pc_coherence_miss(),
ts_cycles {0},
acquires(0),
mismatches(0),
locked_inst(0)
{
}
void
SerialSections::SerialSectionSummary::add(const SerialSection* ss)
{
if (ss->acquire_cpu != ss->release_cpu) {
mismatches++;
return;
}
if (ss->end < ss->start)
die("SerialSectionSummary::add %" PRIu64" < %" PRIu64,
ss->end, ss->start);
ts_cycles[ss->acquire_cpu] += ss->end - ss->start;
auto it = ss->per_pc_coherence_miss.begin();
for (; it != ss->per_pc_coherence_miss.end(); ++it)
per_pc_coherence_miss[it->first] += it->second;
locked_inst += ss->locked_inst;
acquires++;
}
timestamp_t
SerialSections::SerialSectionSummary::total_cycles(void) const
{
timestamp_t sum = 0;
int i;
for (i = 0; i < MAX_CPUS; i++)
sum += ts_cycles[i];
return sum;
}
uint64_t
SerialSections::SerialSectionSummary::coherence_misses(void) const
{
uint64_t sum = 0;
auto it = per_pc_coherence_miss.begin();
for (; it != per_pc_coherence_miss.end(); ++it)
sum += it->second;
return sum;
}
| gpl-2.0 |
autermann/SOS | coding/kvp/src/main/java/org/n52/sos/decode/kvp/v1/DescribeSensorKvpDecoderv100.java | 2249 | /*
* Copyright (C) 2012-2018 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.decode.kvp.v1;
import org.n52.shetland.ogc.sos.Sos1Constants;
import org.n52.shetland.ogc.sos.SosConstants;
import org.n52.sos.decode.kvp.AbstractSosKvpDecoder;
import org.n52.shetland.ogc.sos.request.DescribeSensorRequest;
/**
* @since 4.0.0
*
*/
public class DescribeSensorKvpDecoderv100 extends AbstractSosKvpDecoder<DescribeSensorRequest> {
public DescribeSensorKvpDecoderv100() {
super(DescribeSensorRequest::new,
Sos1Constants.SERVICEVERSION,
SosConstants.Operations.DescribeSensor);
}
@Override
protected void getRequestParameterDefinitions(Builder<DescribeSensorRequest> builder) {
builder.add(SosConstants.DescribeSensorParams.procedure, DescribeSensorRequest::setProcedure);
builder.add(Sos1Constants.DescribeSensorParams.outputFormat,
normalizeMediaType(DescribeSensorRequest::setProcedureDescriptionFormat));
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/jdk/test/java/awt/Modal/ModalInternalFrameTest/ModalInternalFrameTest.java | 6341 | /*
* Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
@test
@bug 6518753
@summary Tests the functionality of modal Swing internal frames
@author artem.ananiev: area=awt.modal
@run main/timeout=30 ModalInternalFrameTest
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import sun.awt.*;
public class ModalInternalFrameTest
{
private boolean passed = true;
private JDesktopPane pane1;
private JDesktopPane pane2;
private JFrame frame1;
private JFrame frame2;
private JButton bn1;
private JButton bs1;
private JButton bn2;
private JButton bs2;
private Point bn1Loc;
private Point bs1Loc;
private Point bn2Loc;
private Point bs2Loc;
private volatile boolean unblocked1 = true;
private volatile boolean unblocked2 = true;
public ModalInternalFrameTest()
{
}
public void init()
{
pane1 = new JDesktopPane();
pane2 = new JDesktopPane();
frame1 = new JFrame("F1");
frame1.setBounds(100, 100, 320, 240);
frame1.getContentPane().setLayout(new BorderLayout());
frame1.getContentPane().add(pane1);
bn1 = new JButton("Test");
bn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
unblocked1 = true;
}
});
frame1.getContentPane().add(bn1, BorderLayout.NORTH);
bs1 = new JButton("Show dialog");
bs1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showInternalMessageDialog(pane1, "Dialog1");
}
});
frame1.getContentPane().add(bs1, BorderLayout.SOUTH);
frame2 = new JFrame("F2");
frame2.setBounds(100, 400, 320, 240);
frame2.getContentPane().setLayout(new BorderLayout());
frame2.getContentPane().add(pane2);
bn2 = new JButton("Test");
bn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
unblocked2 = true;
}
});
frame2.getContentPane().add(bn2, BorderLayout.NORTH);
bs2 = new JButton("Show dialog");
bs2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showInternalMessageDialog(pane2, "Dialog2");
}
});
frame2.getContentPane().add(bs2, BorderLayout.SOUTH);
frame1.setVisible(true);
frame2.setVisible(true);
}
private void getLocations()
{
bn1Loc = bn1.getLocationOnScreen();
bn1Loc.translate(bn1.getWidth() / 2, bn1.getHeight() / 2);
bn2Loc = bn2.getLocationOnScreen();
bn2Loc.translate(bn2.getWidth() / 2, bn2.getHeight() / 2);
bs1Loc = bs1.getLocationOnScreen();
bs1Loc.translate(bs1.getWidth() / 2, bs1.getHeight() / 2);
bs2Loc = bs2.getLocationOnScreen();
bs2Loc.translate(bs2.getWidth() / 2, bs2.getHeight() / 2);
}
private void mouseClick(Robot r, Point p)
throws Exception
{
r.mouseMove(p.x, p.y);
r.mousePress(InputEvent.BUTTON1_MASK);
r.mouseRelease(InputEvent.BUTTON1_MASK);
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
}
private void start()
throws Exception
{
Robot r = new Robot();
r.setAutoDelay(200);
unblocked1 = false;
mouseClick(r, bn1Loc);
if (!unblocked1)
{
throw new RuntimeException("Test FAILED: frame1 must be unblocked, if no modal internal frames are shown");
}
unblocked2 = false;
mouseClick(r, bn2Loc);
if (!unblocked2)
{
throw new RuntimeException("Test FAILED: frame2 must be unblocked, if no modal internal frame is shown in it");
}
mouseClick(r, bs1Loc);
unblocked1 = false;
mouseClick(r, bn1Loc);
if (unblocked1)
{
throw new RuntimeException("Test FAILED: frame1 must be blocked, if a modal internal frame is shown in it");
}
unblocked2 = false;
mouseClick(r, bn2Loc);
if (!unblocked2)
{
throw new RuntimeException("Test FAILED: frame2 must be unblocked, if no modal internal frame is shown in it");
}
mouseClick(r, bs2Loc);
unblocked2 = false;
mouseClick(r, bn2Loc);
if (unblocked2)
{
throw new RuntimeException("Test FAILED: frame2 must be blocked, if a modal internal frame is shown in it");
}
}
private static ModalInternalFrameTest test;
public static void main(String[] args)
throws Exception
{
test = new ModalInternalFrameTest();
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
test.init();
}
});
((SunToolkit)Toolkit.getDefaultToolkit()).realSync();
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
test.getLocations();
}
});
test.start();
}
}
| gpl-2.0 |
recoverym/masterdisist | sites/all/libraries/pdf.js/src/worker_loader.js | 1381 | /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
function onMessageLoader(evt) {
// Reset the `onmessage` function as it was only set to call
// this function the first time a message is passed to the worker
// but shouldn't get called anytime afterwards.
this.onmessage = null;
if (evt.data.action !== 'workerSrc') {
throw 'Worker expects first message to be `workerSrc`';
}
// Content of `PDFJS.workerSrc` as defined on the main thread.
var workerSrc = evt.data.data;
// Extract the directory that contains the source files to load.
// Assuming the source files have the same relative possition as the
// `workerSrc` file.
var dir = workerSrc.substring(0, workerSrc.lastIndexOf('/') + 1);
// List of files to include;
var files = [
'core.js',
'util.js',
'canvas.js',
'obj.js',
'function.js',
'charsets.js',
'cidmaps.js',
'colorspace.js',
'crypto.js',
'evaluator.js',
'fonts.js',
'glyphlist.js',
'image.js',
'metrics.js',
'parser.js',
'pattern.js',
'stream.js',
'worker.js',
'../external/jpgjs/jpg.js'
];
// Load all the files.
for (var i = 0; i < files.length; i++) {
importScripts(dir + files[i]);
}
}
this.onmessage = onMessageLoader;
| gpl-2.0 |
rongandat/scalaprj | catalog/includes/languages/espanol/privacy.php | 429 | <?php
/*
$Id: privacy.php 1739 2007-12-20 00:52:16Z hpdl $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2002 osCommerce
Released under the GNU General Public License
*/
define('NAVBAR_TITLE', 'Confidencialidad');
define('HEADING_TITLE', 'Confidencialidad');
define('TEXT_INFORMATION', 'Ponga aqui información sobre el tratamiento de los datos.');
?>
| gpl-2.0 |
adiabuk/random_scripts | websites/www.amroxonline.com/html/includes/modules/downloads.php | 4047 | <?php
/*
$Id: downloads.php 1739 2007-12-20 00:52:16Z hpdl $
osCommerce, Open Source E-Commerce Solutions
http://www.oscommerce.com
Copyright (c) 2007 osCommerce
Released under the GNU General Public License
*/
?>
<!-- downloads //-->
<?php
if (!strstr($PHP_SELF, FILENAME_ACCOUNT_HISTORY_INFO)) {
// Get last order id for checkout_success
$orders_query = tep_db_query("select orders_id from " . TABLE_ORDERS . " where customers_id = '" . (int)$customer_id . "' order by orders_id desc limit 1");
$orders = tep_db_fetch_array($orders_query);
$last_order = $orders['orders_id'];
} else {
$last_order = $HTTP_GET_VARS['order_id'];
}
// Now get all downloadable products in that order
$downloads_query = tep_db_query("select date_format(o.date_purchased, '%Y-%m-%d') as date_purchased_day, opd.download_maxdays, op.products_name, opd.orders_products_download_id, opd.orders_products_filename, opd.download_count, opd.download_maxdays from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS_PRODUCTS_DOWNLOAD . " opd, " . TABLE_ORDERS_STATUS . " os where o.customers_id = '" . (int)$customer_id . "' and o.orders_id = '" . (int)$last_order . "' and o.orders_id = op.orders_id and op.orders_products_id = opd.orders_products_id and opd.orders_products_filename != '' and o.orders_status = os.orders_status_id and os.downloads_flag = '1' and os.language_id = '" . (int)$languages_id . "'");
if (tep_db_num_rows($downloads_query) > 0) {
?>
<tr>
<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
</tr>
<tr>
<td class="main"><b><?php echo HEADING_DOWNLOAD; ?></b></td>
</tr>
<tr>
<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
</tr>
<tr>
<td><table border="0" width="100%" cellspacing="1" cellpadding="2" class="infoBox">
<!-- list of products -->
<?php
while ($downloads = tep_db_fetch_array($downloads_query)) {
// MySQL 3.22 does not have INTERVAL
list($dt_year, $dt_month, $dt_day) = explode('-', $downloads['date_purchased_day']);
$download_timestamp = mktime(23, 59, 59, $dt_month, $dt_day + $downloads['download_maxdays'], $dt_year);
$download_expiry = date('Y-m-d H:i:s', $download_timestamp);
?>
<tr class="infoBoxContents">
<!-- left box -->
<?php
// The link will appear only if:
// - Download remaining count is > 0, AND
// - The file is present in the DOWNLOAD directory, AND EITHER
// - No expiry date is enforced (maxdays == 0), OR
// - The expiry date is not reached
if ( ($downloads['download_count'] > 0) && (file_exists(DIR_FS_DOWNLOAD . $downloads['orders_products_filename'])) && ( ($downloads['download_maxdays'] == 0) || ($download_timestamp > time())) ) {
echo ' <td class="main"><a href="' . tep_href_link(FILENAME_DOWNLOAD, 'order=' . $last_order . '&id=' . $downloads['orders_products_download_id']) . '">' . $downloads['products_name'] . '</a></td>' . "\n";
} else {
echo ' <td class="main">' . $downloads['products_name'] . '</td>' . "\n";
}
?>
<!-- right box -->
<?php
echo ' <td class="main">' . TABLE_HEADING_DOWNLOAD_DATE . tep_date_long($download_expiry) . '</td>' . "\n" .
' <td class="main" align="right">' . $downloads['download_count'] . TABLE_HEADING_DOWNLOAD_COUNT . '</td>' . "\n" .
' </tr>' . "\n";
}
?>
</tr>
</table></td>
</tr>
<?php
if (!strstr($PHP_SELF, FILENAME_ACCOUNT_HISTORY_INFO)) {
?>
<tr>
<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
</tr>
<tr>
<td class="smalltext" colspan="4"><p><?php printf(FOOTER_DOWNLOAD, '<a href="' . tep_href_link(FILENAME_ACCOUNT, '', 'SSL') . '">' . HEADER_TITLE_MY_ACCOUNT . '</a>'); ?></p></td>
</tr>
<?php
}
}
?>
<!-- downloads_eof //-->
| gpl-2.0 |
C3Style/appuihec | tmp/install_512c96e4f0432/classes/DOCMAN_model.class.php | 10393 | <?php
/**
* DOCman 1.4.x - Joomla! Document Manager
* @version $Id: DOCMAN_model.class.php 765 2009-01-05 20:55:57Z mathias $
* @package DOCman_1.4
* @copyright (C) 2003-2009 Joomlatools
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.joomlatools.eu/ Official website
**/
defined('_VALID_MOS') or die('Restricted access');
if (defined('_DOCMAN_MODEL')) {
return;
} else {
define('_DOCMAN_MODEL', 1);
}
require_once($_DOCMAN->getPath('classes', 'utils'));
require_once($_DOCMAN->getPath('classes', 'user'));
class DOCMAN_Model
{
var $objDBTable = null;
var $objFormatData = null;
var $objFormatLink = null;
var $objFormatPath = null;
function DOCMAN_Model()
{
$this->objFormatData = new stdClass();
$this->objFormatLink = new stdClass();
$this->objFormatPath = new stdClass();
}
function getLink($identifier)
{
if (isset($this->objFormatLink->$identifier))
return $this->objFormatLink->$identifier;
else
return null;
}
function getPath($identifier)
{
if (isset($this->objFormatPath->$identifier))
return $this->objFormatPath->$identifier;
else return null;
}
function getData($identifier)
{
if (isset($this->objFormatData->$identifier))
return $this->objFormatData->$identifier;
else
return null;
}
function setData($identifier, $data)
{
$this->objFormatData->$identifier = $data;
}
function &getLinkObject()
{
return $this->objFormatLink;
}
function &getPathObject()
{
return $this->objFormatPath;
}
function &getDataObject()
{
return $this->objFormatData;
}
function getDBObject()
{
return $this->objDBTable;
}
function _format($objDBTable)
{
}
function _formatLink($task, $params = array(), $sef = true, $indexfile = 'index.php', $token = false)
{
global $_DOCMAN;
require_once($_DOCMAN->getPath('classes', 'token'));
if($token)
{
$params[DOCMAN_token::get(false)] = 1;
}
$link = DOCMAN_Utils::taskLink($task, $this->objDBTable->id, $params, $sef, $indexfile );
return $link;
}
}
class DOCMAN_Category extends DOCMAN_Model
{
function DOCMAN_Category($id)
{
$this->objDBTable = & mosDMCategory::getInstance( $id );
$this->_format($this->objDBTable);
}
function getPath($identifier, $type = 1, $param = null, $png = 1)
{
$result = null;
switch ($identifier) {
case 'icon' :
$result = DOCMAN_Utils::pathIcon ('folder.png', $type, $param, $png);
break;
default :
$result = parent::getPath($identifier);
}
return $result;
}
function _format(&$objDBCat)
{
global $_DOCMAN;
$user = $_DOCMAN->getUser();
// format category data
$this->objFormatData = DOCMAN_Utils::get_object_vars($objDBCat);
$this->objFormatData->files = DOCMAN_Cats::countDocsInCatByUser($objDBCat->id, $user, true);
// format category links
$this->objFormatLink->view = $this->_formatLink('cat_view');
// format category paths
$this->objFormatPath->thumb = DOCMAN_Utils::pathThumb($objDBCat->image);
$this->objFormatPath->icon = DOCMAN_Utils::pathIcon ('folder.png', 1);
}
}
class DOCMAN_Document extends DOCMAN_Model
{
function DOCMAN_Document($id)
{
global $database;
$this->objDBTable = new mosDMDocument($database);
$this->objDBTable->load($id);
$this->_format($this->objDBTable);
}
function & getInstance($id) {
static $instances;
if(!isset($instances)) {
$instances = array();
}
if(!isset($instances[$id])) {
$instances[$id] = new DOCMAN_Document($id);
}
return $instances[$id];
}
function getPath($identifier, $type = 1, $param = null)
{
$result = null;
switch ($identifier) {
case 'icon' :
$result = DOCMAN_Utils::pathIcon ($this->objFormatData->filetype . ".png", $type, $param);
break;
default :
$result = parent::getPath($identifier);
}
return $result;
}
function _format(&$objDBDoc)
{
global $_DOCMAN;
require_once($_DOCMAN->getPath('classes', 'file'));
require_once($_DOCMAN->getPath('classes', 'params'));
require_once($_DOCMAN->getPath('classes', 'mambots'));
$file = new DOCMAN_file($objDBDoc->dmfilename, $_DOCMAN->getCfg('dmpath'));
$params = new dmParameters( $objDBDoc->attribs, '' , 'params' );
// format document data
$this->objFormatData = DOCMAN_Utils::get_object_vars($objDBDoc);
$this->objFormatData->owner = $this->_formatUserName($objDBDoc->dmowner);
$this->objFormatData->submited_by = $this->_formatUserName($objDBDoc->dmsubmitedby);
$this->objFormatData->maintainedby = $this->_formatUserName($objDBDoc->dmmantainedby);
$this->objFormatData->lastupdatedby = $this->_formatUserName($objDBDoc->dmlastupdateby);
$this->objFormatData->checkedoutby = $this->_formatUserName($objDBDoc->checked_out);
$this->objFormatData->filename = $this->_formatFilename($objDBDoc);
$this->objFormatData->filesize = $file->getSize();
$this->objFormatData->filetype = $file->ext;
$this->objFormatData->mime = $file->mime;
$this->objFormatData->hot = $this->_formatHot($objDBDoc);
$this->objFormatData->new = $this->_formatNew($objDBDoc);
$this->objFormatData->state = $this->objFormatData->new.' '.$this->objFormatData->hot; //for backwards compat with 1.3
$this->objFormatData->params = $params;
//$this->objFormatData->dmdescription = mosHTML::cleanText($objDBDoc->dmdescription);
$this->objFormatData->dmdescription = $objDBDoc->dmdescription;
// onFetchButtons event
// plugins should always return an array of Button objects
$bot = new DOCMAN_mambot('onFetchButtons');
$bot->setParm('doc' , $this);
$bot->setParm('file' , $file);
$bot->trigger();
if ($bot->getError()) {
_returnTo('cat_view', $bot->getErrorMsg());
}
$buttons = array();
foreach( $bot->getReturn() as $return) {
if(!is_array($return)) {
$return = array($return);
}
$buttons = array_merge($buttons, $return);
}
$this->objFormatLink = & $buttons;
// format document paths
$this->objFormatPath->icon = DOCMAN_Utils::pathIcon ($file->ext . ".png", 1);
$this->objFormatPath->thumb = DOCMAN_Utils::pathThumb($objDBDoc->dmthumbnail, 1);
}
// @desc Translate the numeric ID to a character string
// @param integer $ The numeric ID of the user
// @return string Contains the user name in string format
function _formatUserName($userid)
{
global $database, $_DOCMAN;
require_once($_DOCMAN->getPath('classes', 'user'));
require_once($_DOCMAN->getPath('classes', 'groups'));
switch ($userid)
{
case '-1':
return _DML_EVERYBODY;
break;
case '0':
return _DML_ALL_REGISTERED;
break;
case _DM_PERMIT_PUBLISHER:
return _DML_GROUP_PUBLISHER;
break;
case _DM_PERMIT_EDITOR:
return _DML_GROUP_EDITOR;
break;
case _DM_PERMIT_AUTHOR:
return _DML_GROUP_AUTHOR;
break;
default:
if ($userid > 0)
{
$user = DOCMAN_users::get($userid);
return $user->username;
}
if($userid < -5)
{
$calcgroups = (abs($userid) - 10);
$user = DOCMAN_groups::get($calcgroups);
return $user->groups_name;
}
break;
}
return "USER ID?";
}
function _formatNew(&$objDBDoc){
global $_DOCMAN;
$days = $_DOCMAN->getCfg('days_for_new');
$result = null;
if ($days > 0 &&
(DOCMAN_Utils::Daysdiff ($objDBDoc->dmdate_published) > ($days -2 * $days)) && (DOCMAN_Utils::Daysdiff ($objDBDoc->dmdate_published) <= 0)) {
$result = _DML_NEW;
}
return $result;
}
function _formatHot(&$objDBDoc){
global $_DOCMAN;
$hot = $_DOCMAN->getCfg('hot');
$result = null;
if ($hot > 0 && $objDBDoc->dmcounter >= $hot) {
$result = _DML_HOT;
}
return $result;
}
function _formatFilename( &$objDBDoc) {
global $_DOCMAN;
$_DMUSER = $_DOCMAN->getUser();
$filename = $objDBDoc->dmfilename;
$is_link = ( substr($filename, 0, strlen(_DM_DOCUMENT_LINK) ) == _DM_DOCUMENT_LINK );
$hide_remote = $_DOCMAN->getCfg( 'hide_remote', 1 );
$can_edit = $_DMUSER->canEdit( $objDBDoc );
if( $is_link AND $hide_remote AND !$can_edit ) {
// strip 'Link: '
$filename = ereg_replace( '^'._DM_DOCUMENT_LINK, '', $filename) ;
// strip scheme (http://, ftp:// )
$filename = ereg_replace( '^[a-zA-Z]+://', '', $filename);
if( strpos( $filename, '/' )) { // format www.mysite.com/ or www.mysite.com/path/ or www.mysite.com/path/myfile.com
// strip domain (www.mysite.com )
$filename = ereg_replace( '^(([.]?[a-zA-Z0-9_-])*)/', '/', $filename);
// strip path
$filename = substr( $filename, strrpos( $filename, '/')+1 );
} else { // format www.mysite.com (no trailing slash or path or filename)
$filename ='';
}
// if there's nothing left, we mark it 'unknown'
$filename = ( $filename ? _DML_LINKTO.$filename : _DML_UNKNOWN );
}
return $filename;
}
} | gpl-2.0 |
JamesCullum/PGP-Anywhere | js/options.js | 13407 | var masterpw = "", syncloadcount = 0, syncsetcount = 0, synccounter = 0;
var bcrypt = new bCrypt();
$(document).ready(function() {
var options = {
rules: {
activated: {
wordTwoCharacterClasses: true,
wordRepetitions: true
}
},
ui: {
showVerdictsInsideProgressBar: true,
verdicts: [ chrome.i18n.getMessage("verdict_weak"), chrome.i18n.getMessage("verdict_normal"), chrome.i18n.getMessage("verdict_medium"),
chrome.i18n.getMessage("verdict_strong"), chrome.i18n.getMessage("verdict_very_strong") ]
}
};
$('#inputMasterPassword').pwstrength(options);
if( loadval("pgpanywhere_encrypted",0)==1 )
{
master_auth(function(decpw) {
masterpw = decpw;
$("#inputMasterPassword").val(decpw);
$("#inputMasterPassword2").val(decpw);
$("#inputMasterPassword").pwstrength("forceUpdate");
loadkeyrings();
});
}
else loadkeyrings();
$("#addpgpdeckey").keyup(function() {
var keyval = $(this).val();
if(keyval.indexOf("-----BEGIN PGP PRIVATE KEY BLOCK-----")!=-1) $("#savekeypassword").removeAttr("disabled");
else $("#savekeypassword").attr("disabled","disabled");
});
$("#selectDecKey").change(function() {
var optval = $(this).val();
if(optval=="addnew")
{
$("#removebutton, #savekeypassword").attr("disabled","disabled");
$("#savekeypassword, #inputEmail, #addpgpdeckey").val("");
$("#addbutton").removeClass("btn-primary btn-info").addClass("btn-primary");
$("#inputEmail, #addpgpdeckey").keyup();
}
else
{
$("#removebutton").removeAttr("disabled");
var infosplit = optval.split("|");
if(infosplit[1] == "0")
{
var container = openkeyring("private");
for(var i=0;i<container.length;i++)
{
if( container[i].email == infosplit[0] )
{
$("#savekeypassword").val(container[i].password);
$("#inputEmail").val(container[i].email);
$("#addpgpdeckey").val(container[i].key);
}
}
$("#savekeypassword").removeAttr("disabled");
}
else
{
var container = openkeyring("public");
for(var i=0;i<container.length;i++)
{
if( container[i].email == infosplit[0] )
{
$("#inputEmail").val(container[i].email);
$("#addpgpdeckey").val(container[i].key);
}
}
$("#savekeypassword").val("").attr("disabled","disabled");
}
$("#inputEmail, #addpgpdeckey").keyup();
$("#addbutton").removeClass("disabled btn-primary btn-info").addClass("btn-info").text(chrome.i18n.getMessage("export"));
}
});
$("#inputMasterPassword").keyup(function() {
$("#inputMasterPassword2").val("").show();
});
$("#inputEmail, #addpgpdeckey").keyup(function() {
var user = $("#inputEmail").val();
var key = $("#addpgpdeckey").val();
var iskey = $("#selectDecKey").val();
var enteredkey = $("#addpgpdeckey").val();
if( iskey == "addnew" && user.length && !enteredkey.length ) $("#generatekey").removeClass("disabled");
else $("#generatekey").addClass("disabled");
if( user.length && key.length ) $("#addbutton").removeClass("disabled btn-primary btn-info").addClass("btn-primary").text(chrome.i18n.getMessage("save"));
else $("#addbutton").addClass("disabled");
});
$("#generatekey").click(function(e) {
e.preventDefault();
var user = getAlias();
if(!user) return;
$("#addpgpdeckey, #inputEmail, #generatekey, #addbutton, #submitbutton, #flushbutton").addClass("disabled").attr("disabled", "disabled");
var befText = $(this).html();
$(this).html(chrome.i18n.getMessage("generating") + ' <i class="fa fa-cog fa-spin"></i>');
var createdString = createRandomString(30);
var createOptions = {
numBits: 2048,
userIds: [{name:user}],
passphrase: createdString
};
openpgp.generateKey(createOptions).then(function(keypair) {
var privkey = keypair.privateKeyArmored;
var pubkey = keypair.publicKeyArmored;
savekey(user, pubkey, "");
savekey(user, privkey, createdString);
$("#generatekey").html(befText)
$("#addpgpdeckey, #inputEmail, #generatekey, #addbutton, #submitbutton, #flushbutton").removeClass("disabled").removeAttr("disabled");
$("#selectDecKey").val(user+"|1").change();
}).catch(function(error) {
alert(error);
});
});
$("#removebutton").click(function(e) {
e.preventDefault();
var remindex = $("#selectDecKey").val();
var infosplit = remindex.split("|");
if(infosplit[1] == "0") var container = openkeyring("private");
else var container = openkeyring("public");
for(var i=container.length-1;i>=0;i--) if( container[i].email == infosplit[0] ) container.splice(i,1);
if(infosplit[1] == "0") savekeyring("private",container);
else savekeyring("public",container);
$("option[value='"+remindex+"']","#selectDecKey").remove();
$("#savekeypassword, #inputEmail, #addpgpdeckey").val("");
$("#selectDecKey").change();
});
$("#addbutton").click(function(e) {
e.preventDefault();
if( $(this).hasClass("btn-primary") )
{
var pass = $("#savekeypassword").val();
var email = getAlias();
var key = $("#addpgpdeckey").val();
if(!email) return;
savekey(email, key, pass);
$("#inputEmail, #addpgpdeckey, #savekeypassword").val("");
}
else
{
var infosplit = $("#selectDecKey").val().split("|");
var splitlabel;
if(infosplit[1] == "0")
{
$(".modal-body .well").text($("#savekeypassword").val()).show();
$(".modal-body p").html(chrome.i18n.getMessage("export_private_desc"));
splitlabel = "private";
}
else
{
$(".modal-body .well").text("").hide();
$(".modal-body p").html(chrome.i18n.getMessage("export_public_desc"));
splitlabel = "public";
}
$("#downloadKey").attr("download", $("#inputEmail").val()+'.'+splitlabel+'.asc').attr("href", 'data:text/plain;base64,'+btoa($("#addpgpdeckey").val()));
if($("#savekeypassword").val().length) $(".modal-body .well").show();
else $(".modal-body .well").hide();
$(".modal").show();
}
});
$(".modal-header .close, .modal-footer .btn-default").click(function() {
$(".modal").hide();
$(".modal-body .well").text("");
});
$("#flushbutton").click(function(e) {
e.preventDefault();
if(confirm(chrome.i18n.getMessage("delete_confirm")))
{
chrome.storage.sync.clear();
localStorage.clear();
window.location=window.location;
}
});
$("#submitbutton").click(function(e) {
e.preventDefault();
var encpw = $("#inputMasterPassword").val();
if( encpw != $("#inputMasterPassword2").val() ) return alert(chrome.i18n.getMessage("password_no_match"));
var encrypted = encpw.length ? 1 : 0;
var temp_public = (loadval("pgpanywhere_encrypted",0)==1) ? sjcl.decrypt(masterpw,loadval("pgpanywhere_public_keyring","[]")) : loadval("pgpanywhere_public_keyring","[]");
var temp_private = (loadval("pgpanywhere_encrypted",0)==1) ? sjcl.decrypt(masterpw,loadval("pgpanywhere_private_keyring","[]")) : loadval("pgpanywhere_private_keyring","[]");
temp_public_save = encpw.length ? sjcl.encrypt(encpw, temp_public) : temp_public;
temp_private_save = encpw.length ? sjcl.encrypt(encpw, temp_private) : temp_private;
$("#submitbutton").attr("disabled","disabled");
masterpw = encpw;
localStorage.setItem("pgpanywhere_encrypted", encrypted);
localStorage.setItem("pgpanywhere_public_keyring", temp_public_save);
localStorage.setItem("pgpanywhere_private_keyring", temp_private_save);
chrome.runtime.sendMessage({ msg: "unlock", "auth": masterpw });
if(encrypted)
{
var d = new Date();
syncsetcount = 0;
// Hash-Generation
var hashtype = 2; //always bCrypt
createhash( encpw, hashtype, function(encrypted_hash) {
var settingscontainer = {"encrypted":encrypted, "hash":encrypted_hash};
localStorage.setItem("pgpanywhere_encrypted_hash", encrypted_hash );
addSyncElement(6);
chrome.storage.sync.set({"pgpanywhere_sync_container_settings": JSON.stringify(settingscontainer)}, function() { onsyncset(); });
// Public Keys
var container = openkeyring("public");
addSyncElement(container.length);
for(var i=0;i<container.length;i++)
{
var enc_item = sjcl.encrypt(encpw, JSON.stringify(container[i]));
var sync_label = "pgpanywhere_sync_public_"+i;
var sync_item = {};
sync_item[sync_label] = enc_item;
chrome.storage.sync.set(sync_item, function() { onsyncset(); });
}
chrome.storage.sync.set({"pgpanywhere_sync_public_list": container.length}, function() { onsyncset(); });
// Private Keys
var container = openkeyring("private");
addSyncElement(container.length);
for(var i=0;i<container.length;i++)
{
var enc_item = sjcl.encrypt(encpw, JSON.stringify(container[i]));
var sync_label = "pgpanywhere_sync_private_"+i;
var sync_item = {};
sync_item[sync_label] = enc_item;
chrome.storage.sync.set(sync_item, function() { onsyncset(); });
}
chrome.storage.sync.set({"pgpanywhere_sync_private_list": container.length}, function() { onsyncset(); });
// Empty container from older versions
chrome.storage.sync.remove("pgpanywhere_sync_container_publickeys", function() { onsyncset(); });
chrome.storage.sync.remove("pgpanywhere_sync_container_privatekeys", function() { onsyncset(); });
var timestamp = Math.floor(Date.now() / 1000);
chrome.storage.sync.set({"pgpanywhere_sync_set": timestamp}, function() { onsyncset(); });
});
}
else window.close();
});
});
function savekey(email, key, pass)
{
if( key.indexOf('-----BEGIN PGP PRIVATE KEY BLOCK-----') != -1 )
{
var container = openkeyring("private");
for(var i=container.length-1;i>=0;i--) if( container[i].email == email ) container.splice(i,1);
var addobj = {"email":email, "key":key, "password": pass};
container.push(addobj);
savekeyring("private",container);
}
else if( key.indexOf('-----BEGIN PGP PUBLIC KEY BLOCK-----') != -1 )
{
var container = openkeyring("public");
for(var i=container.length-1;i>=0;i--) if( container[i].email == email ) container.splice(i,1);
var addobj = {"email":email, "key":key};
container.push(addobj);
savekeyring("public",container);
}
else alert(chrome.i18n.getMessage("invalid_key"));
$("#selectDecKey").html('');
$("#selectDecKey").append('<option value="addnew">'+chrome.i18n.getMessage("add_key")+'</option>');
loadkeyrings();
$("#selectDecKey").change();
}
function getAlias()
{
var user = $("#inputEmail").val();
if(!user.length)
{
var bef = $("#inputEmail").css("border");
$("#inputEmail").css("border","1px solid red");
alert(chrome.i18n.getMessage("require_identity"));
$("#inputEmail").css("border",bef);
return false;
}
return user;
}
function loadkeyrings()
{
var container = openkeyring("private");
if(container.length)
{
$("#selectDecKey").append('<optgroup label="'+chrome.i18n.getMessage("private_key_label")+'" id="privateKeyGroup"></div>');
for(var i=0;i<container.length;i++) $("#privateKeyGroup").append('<option value="'+container[i].email+'|0">'+container[i].email+'</option>');
}
var container = openkeyring("public");
if(container.length)
{
$("#selectDecKey").append('<optgroup label="'+chrome.i18n.getMessage("public_key_label")+'" id="publicKeyGroup"></div>');
for(var i=0;i<container.length;i++) $("#publicKeyGroup").append('<option value="'+container[i].email+'|1">'+container[i].email+'</option>');
}
}
function openkeyring(type)
{
var container = loadval("pgpanywhere_"+type+"_keyring","[]");
if(loadval("pgpanywhere_encrypted",0)==1 && container.indexOf('"iv":') != -1) container = sjcl.decrypt(masterpw,container);
if(!container.length || container=="[]") container = [];
else container = jQuery.parseJSON(container);
return container;
}
function savekeyring(type,array)
{
var container = JSON.stringify(array);
if(loadval("pgpanywhere_encrypted",0)==1) container = sjcl.encrypt(masterpw,container);
localStorage.setItem("pgpanywhere_"+type+"_keyring", container);
}
function loadval(key,def)
{
var retval = localStorage.getItem(key);
if( retval == undefined ) retval = def;
return retval;
}
function addSyncElement(add)
{
synccounter+=add;
}
function onsyncset()
{
syncsetcount++;
if(syncsetcount>=synccounter) window.close();
}
function createhash(str, algo, func)
{
if(!str.length) return func("");
if(algo == 1) return func(getshahash(str)); //SHA512
if(algo == 2) //bCrypt
{
if(!bcrypt.ready()) return setTimeout(function() { createhash(str, algo, func); }, 500);
var salt;
try{
salt = bcrypt.gensalt(10);
bcrypt.hashpw( str, salt, function(result) {
return func(result);
}, function() {});
}catch(err){
return alert(err);
}
}
}
function getshahash(str)
{
var shaObj = new jsSHA(str, "TEXT");
var hash = shaObj.getHash("SHA-512", "HEX");
return hash;
}
function createRandomString(length)
{
var charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var i;
var result = "";
if(window.crypto && window.crypto.getRandomValues)
{
values = new Uint32Array(length);
window.crypto.getRandomValues(values);
for(i=0; i<length; i++)
{
result += charset[values[i] % charset.length];
}
return result;
}
else {
alert("Your browser appears to be outdated and can't generate secure random numbers. If this is a mistake, please refer to the GitHub page to report a bug.");
}
}
| gpl-2.0 |
jpoet/gst-plugins-bad | ext/qt/qtwindow.cc | 11082 | /*
* GStreamer
* Copyright (C) 2016 Freescale Semiconductor, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <gst/video/video.h>
#include "qtwindow.h"
#include "gstqsgtexture.h"
#include "gstqtglutility.h"
#include <QtCore/QDateTime>
#include <QtCore/QRunnable>
#include <QtGui/QGuiApplication>
#include <QtQuick/QQuickWindow>
#include <QOpenGLFramebufferObject>
/* compatability definitions... */
#ifndef GL_READ_FRAMEBUFFER
#define GL_READ_FRAMEBUFFER 0x8CA8
#endif
/**
* SECTION:
*
* #QtGLWindow is an #QQuickWindow that grab QtQuick view to GStreamer OpenGL video buffers.
*/
GST_DEBUG_CATEGORY_STATIC (qt_window_debug);
#define GST_CAT_DEFAULT qt_window_debug
struct _QtGLWindowPrivate
{
GMutex lock;
GCond update_cond;
GstBuffer *buffer;
GstCaps *caps;
GstVideoInfo v_info;
gboolean initted;
gboolean updated;
gboolean quit;
gboolean result;
gboolean useDefaultFbo;
GstGLDisplay *display;
GstGLContext *other_context;
GLuint fbo;
/* frames that qmlview rendered in its gl thread */
quint64 frames_rendered;
quint64 start;
quint64 stop;
};
class InitQtGLContext : public QRunnable
{
public:
InitQtGLContext(QtGLWindow *window);
void run();
private:
QtGLWindow *window_;
};
InitQtGLContext::InitQtGLContext(QtGLWindow *window) :
window_(window)
{
}
void InitQtGLContext::run()
{
window_->onSceneGraphInitialized();
}
QtGLWindow::QtGLWindow ( QWindow * parent, QQuickWindow *src ) :
QQuickWindow( parent ), source (src)
{
QGuiApplication *app = static_cast<QGuiApplication *> (QCoreApplication::instance ());
static volatile gsize _debug;
g_assert (app != NULL);
if (g_once_init_enter (&_debug)) {
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "qtglwindow", 0, "Qt GL QuickWindow");
g_once_init_leave (&_debug, 1);
}
this->priv = g_new0 (QtGLWindowPrivate, 1);
g_mutex_init (&this->priv->lock);
g_cond_init (&this->priv->update_cond);
this->priv->display = gst_qt_get_gl_display();
connect (source, SIGNAL(beforeRendering()), this, SLOT(beforeRendering()), Qt::DirectConnection);
connect (source, SIGNAL(afterRendering()), this, SLOT(afterRendering()), Qt::DirectConnection);
connect (app, SIGNAL(aboutToQuit()), this, SLOT(aboutToQuit()), Qt::DirectConnection);
if (source->isSceneGraphInitialized())
source->scheduleRenderJob(new InitQtGLContext(this), QQuickWindow::BeforeSynchronizingStage);
else
connect (source, SIGNAL(sceneGraphInitialized()), this, SLOT(onSceneGraphInitialized()), Qt::DirectConnection);
connect (source, SIGNAL(sceneGraphInvalidated()), this, SLOT(onSceneGraphInvalidated()), Qt::DirectConnection);
GST_DEBUG ("%p init Qt Window", this->priv->display);
}
QtGLWindow::~QtGLWindow()
{
GST_DEBUG ("deinit Qt Window");
g_mutex_clear (&this->priv->lock);
g_cond_clear (&this->priv->update_cond);
if (this->priv->other_context)
gst_object_unref(this->priv->other_context);
if (this->priv->display)
gst_object_unref(this->priv->display);
g_free (this->priv);
this->priv = NULL;
}
void
QtGLWindow::beforeRendering()
{
unsigned int width, height;
g_mutex_lock (&this->priv->lock);
static volatile gsize once = 0;
if (g_once_init_enter(&once)) {
this->priv->start = QDateTime::currentDateTime().toMSecsSinceEpoch();
g_once_init_leave(&once,1);
}
if (!fbo && !this->priv->useDefaultFbo) {
width = source->width();
height = source->height();
GST_DEBUG ("create new framebuffer object %dX%d", width, height);
fbo.reset(new QOpenGLFramebufferObject (width, height,
QOpenGLFramebufferObject::NoAttachment, GL_TEXTURE_2D, GL_RGBA));
source->setRenderTarget(fbo.data());
} else if (this->priv->useDefaultFbo) {
GST_DEBUG ("use default fbo for render target");
fbo.reset(NULL);
source->setRenderTarget(NULL);
}
g_mutex_unlock (&this->priv->lock);
}
void
QtGLWindow::afterRendering()
{
GstVideoFrame gl_frame;
GstVideoInfo *info;
GstGLContext *context;
gboolean ret;
guint width, height;
const GstGLFuncs *gl;
GLuint dst_tex;
g_mutex_lock (&this->priv->lock);
this->priv->frames_rendered++;
if(!this->priv->buffer || this->priv->updated == TRUE) {
GST_DEBUG ("skip this frame");
g_mutex_unlock (&this->priv->lock);
return;
}
GST_DEBUG ("copy buffer %p",this->priv->buffer);
width = GST_VIDEO_INFO_WIDTH (&this->priv->v_info);
height = GST_VIDEO_INFO_HEIGHT (&this->priv->v_info);
info = &this->priv->v_info;
context = this->priv->other_context;
gst_gl_context_activate (context, TRUE);
gl = context->gl_vtable;
ret = gst_video_frame_map (&gl_frame, info, this->priv->buffer,
(GstMapFlags) (GST_MAP_WRITE | GST_MAP_GL));
if (!ret) {
this->priv->buffer = NULL;
GST_ERROR ("Failed to map video frame");
goto errors;
}
gl->BindFramebuffer (GL_READ_FRAMEBUFFER, this->source->renderTargetId());
ret = gst_gl_context_check_framebuffer_status (context);
if (!ret) {
GST_ERROR ("FBO errors");
goto errors;
}
dst_tex = *(guint *) gl_frame.data[0];
GST_DEBUG ("qml render target id %d, render to tex %d %dX%d",
this->source->renderTargetId(), dst_tex, width,height);
gl->BindTexture (GL_TEXTURE_2D, dst_tex);
if (gl->BlitFramebuffer) {
gl->BindFramebuffer (GL_DRAW_FRAMEBUFFER, this->priv->fbo);
gl->FramebufferTexture2D (GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, dst_tex, 0);
ret = gst_gl_context_check_framebuffer_status (context);
if (!ret) {
GST_ERROR ("FBO errors");
goto errors;
}
gl->ReadBuffer (GL_COLOR_ATTACHMENT0);
gl->BlitFramebuffer (0, 0, width, height,
0, 0, width, height,
GL_COLOR_BUFFER_BIT, GL_LINEAR);
} else {
gl->CopyTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, width, height, 0);
}
GST_DEBUG ("rendering finished");
errors:
gl->BindFramebuffer (GL_FRAMEBUFFER, 0);
gst_video_frame_unmap (&gl_frame);
gst_gl_context_activate (context, FALSE);
this->priv->result = ret;
this->priv->updated = TRUE;
g_cond_signal (&this->priv->update_cond);
g_mutex_unlock (&this->priv->lock);
}
void
QtGLWindow::aboutToQuit()
{
g_mutex_lock (&this->priv->lock);
this->priv->updated = TRUE;
this->priv->quit = TRUE;
g_cond_signal (&this->priv->update_cond);
this->priv->stop = QDateTime::currentDateTime().toMSecsSinceEpoch();
qint64 duration = this->priv->stop - this->priv->start;
float fps = ((float)this->priv->frames_rendered / duration * 1000);
GST_DEBUG("about to quit, total refresh frames (%lld) in (%0.3f) seconds, fps: %0.3f",
this->priv->frames_rendered, (float)duration / 1000, fps);
g_mutex_unlock (&this->priv->lock);
}
void
QtGLWindow::onSceneGraphInitialized()
{
GST_DEBUG ("scene graph initialization with Qt GL context %p",
this->source->openglContext ());
this->priv->initted = gst_qt_get_gl_wrapcontext (this->priv->display,
&this->priv->other_context, NULL);
if (this->priv->initted && this->priv->other_context) {
const GstGLFuncs *gl;
gst_gl_context_activate (this->priv->other_context, TRUE);
gl = this->priv->other_context->gl_vtable;
gl->GenFramebuffers (1, &this->priv->fbo);
gst_gl_context_activate (this->priv->other_context, FALSE);
}
GST_DEBUG ("%p created wrapped GL context %" GST_PTR_FORMAT, this,
this->priv->other_context);
}
void
QtGLWindow::onSceneGraphInvalidated()
{
GST_DEBUG ("scene graph invalidated");
if (this->priv->fbo && this->priv->other_context) {
const GstGLFuncs *gl;
gst_gl_context_activate (this->priv->other_context, TRUE);
gl = this->priv->other_context->gl_vtable;
gl->DeleteFramebuffers (1, &this->priv->fbo);
gst_gl_context_activate (this->priv->other_context, FALSE);
}
}
bool
QtGLWindow::getGeometry(int * width, int * height)
{
if (width == NULL || height == NULL)
return FALSE;
*width = this->source->width();
*height = this->source->height();
return TRUE;
}
GstGLContext *
qt_window_get_qt_context (QtGLWindow * qt_window)
{
g_return_val_if_fail (qt_window != NULL, NULL);
if (!qt_window->priv->other_context)
return NULL;
return (GstGLContext *) gst_object_ref (qt_window->priv->other_context);
}
GstGLDisplay *
qt_window_get_display (QtGLWindow * qt_window)
{
g_return_val_if_fail (qt_window != NULL, NULL);
if (!qt_window->priv->display)
return NULL;
return (GstGLDisplay *) gst_object_ref (qt_window->priv->display);
}
gboolean
qt_window_is_scenegraph_initialized (QtGLWindow * qt_window)
{
g_return_val_if_fail (qt_window != NULL, FALSE);
return qt_window->priv->initted;
}
gboolean
qt_window_set_caps (QtGLWindow * qt_window, GstCaps * caps)
{
GstVideoInfo v_info;
g_return_val_if_fail (qt_window != NULL, FALSE);
g_return_val_if_fail (GST_IS_CAPS (caps), FALSE);
g_return_val_if_fail (gst_caps_is_fixed (caps), FALSE);
if (qt_window->priv->caps && gst_caps_is_equal_fixed (qt_window->priv->caps, caps))
return TRUE;
if (!gst_video_info_from_caps (&v_info, caps))
return FALSE;
g_mutex_lock (&qt_window->priv->lock);
gst_caps_replace (&qt_window->priv->caps, caps);
qt_window->priv->v_info = v_info;
g_mutex_unlock (&qt_window->priv->lock);
return TRUE;
}
gboolean
qt_window_set_buffer (QtGLWindow * qt_window, GstBuffer * buffer)
{
g_return_val_if_fail (qt_window != NULL, FALSE);
g_return_val_if_fail (qt_window->priv->initted, FALSE);
gboolean ret;
g_mutex_lock (&qt_window->priv->lock);
if (qt_window->priv->quit){
GST_DEBUG("about to quit, drop this buffer");
g_mutex_unlock (&qt_window->priv->lock);
return TRUE;
}
qt_window->priv->updated = FALSE;
qt_window->priv->buffer = buffer;
while (!qt_window->priv->updated)
g_cond_wait (&qt_window->priv->update_cond, &qt_window->priv->lock);
ret = qt_window->priv->result;
g_mutex_unlock (&qt_window->priv->lock);
return ret;
}
void
qt_window_use_default_fbo (QtGLWindow * qt_window, gboolean useDefaultFbo)
{
g_return_if_fail (qt_window != NULL);
g_mutex_lock (&qt_window->priv->lock);
GST_DEBUG ("set to use default fbo %d", useDefaultFbo);
qt_window->priv->useDefaultFbo = useDefaultFbo;
g_mutex_unlock (&qt_window->priv->lock);
}
| gpl-2.0 |
elitelinux/hack-space | php/front/autoupdatesystem.php | 1254 | <?php
/*
* @version $Id: autoupdatesystem.php 22657 2014-02-12 16:17:54Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
include ('../inc/includes.php');
$dropdown = new AutoUpdateSystem();
include (GLPI_ROOT . "/front/dropdown.common.php");
?>
| gpl-2.0 |
yoavain/mediaportal-fanart-handler | FanartHandler/UtilsMyFilms.cs | 3463 | // Type: FanartHandler.UtilsMyFilms
// Assembly: FanartHandler, Version=4.0.3.0, Culture=neutral, PublicKeyToken=null
// MVID: 073E8D78-B6AE-4F86-BDE9-3E09A337833B
extern alias FHNLog;
using MyFilmsPlugin;
using MyFilmsPlugin.DataBase;
using FHNLog.NLog;
using System;
using System.Collections;
using System.IO;
using System.Runtime.CompilerServices;
using MediaPortal.Video.Database;
namespace FanartHandler
{
internal static class UtilsMyFilms
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
static UtilsMyFilms()
{
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void GetMyFilmsBackdrops()
{
if (!Utils.MyFilmsEnabled)
return;
try
{
var allFilenames = Utils.DBm.GetAllFilenames(Utils.Category.MyFilms, Utils.SubCategory.MyFilmsManual);
var movielist = new ArrayList();
BaseMesFilms.GetMovies(ref movielist);
foreach (MFMovie movie in movielist)
{
MFMovie current = movie;
var backdropFullPath = current.Fanart;
var ImdbID = current.IMDBNumber.Trim();
if (!string.IsNullOrWhiteSpace(backdropFullPath) && (allFilenames == null || !allFilenames.Contains(backdropFullPath)))
{
if (File.Exists(backdropFullPath))
{
Utils.DBm.LoadFanart(Utils.GetArtist(current.Title, Utils.Category.MyFilms, Utils.SubCategory.MyFilmsManual), null, ImdbID, null, backdropFullPath, backdropFullPath, Utils.Category.MyFilms, Utils.SubCategory.MyFilmsManual, Utils.Provider.MyFilms);
}
}
}
if (allFilenames != null)
allFilenames.Clear();
}
catch (MissingMethodException ex)
{
logger.Debug("GetMyFilmsBackdrops: " + ex);
}
catch (Exception ex)
{
logger.Error("GetMyFilmsBackdrops: " + ex);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void GetMyFilmsMoviesList(ref ArrayList movies)
{
if (!Utils.MyFilmsEnabled)
return;
try
{
var movielist = new ArrayList();
BaseMesFilms.GetMovies(ref movielist);
if (movielist == null)
{
return;
}
foreach (MFMovie movie in movielist)
{
MFMovie current = movie;
var ImdbID = string.IsNullOrEmpty(current.IMDBNumber) ? string.Empty : current.IMDBNumber.Trim().ToLowerInvariant().Replace("unknown", string.Empty);
if (!string.IsNullOrEmpty(ImdbID))
{
if (!Utils.GetIsStopping())
{
IMDBMovie details = new IMDBMovie();
details.ID = current.ID;
details.IMDBNumber = ImdbID;
details.TMDBNumber = current.TMDBNumber;
details.Title = current.Title;
details.Year = current.Year;
movies.Add(details);
}
else
{
break;
}
}
}
if (movielist != null)
movielist.Clear();
}
catch (MissingMethodException ex)
{
logger.Debug("GetMyFilmsMoviesList: Missing: " + ex);
}
catch (Exception ex)
{
logger.Error("GetMyFilmsMoviesList: " + ex);
}
}
}
}
| gpl-2.0 |
akifhatipoglu/Decision-Tree | Decision tree/src/c45/c45Test.java | 3057 | package c45;
import java.util.HashMap;
import java.util.List;
import java.util.Queue;
import java.util.Map.Entry;
import java.util.concurrent.LinkedBlockingQueue;
import main.Sample;
import main.SampleCollection;
public class c45Test {
private double accuracy;
public double getAccuracy() {
return accuracy;
}
private C45DecisionTree dt;
HashMap<String,Double> etiketler = new HashMap<String, Double>();
public c45Test(C45DecisionTree dt, SampleCollection testSamples, String typeOfTest) {
this.dt = dt;
// System.out.println(SampleCollection.FEATURES.subFeatureList);
if(typeOfTest.equals("train")){
classifyAndSetAccuracy(testSamples.sampleList,SampleCollection.FEATURES.subFeatureList);
}
if(typeOfTest.equals("test")){
classifyAndSetAccuracy(testSamples.testList,SampleCollection.FEATURES.subFeatureList);
}
}
private void classifyAndSetAccuracy(List<Sample> samples,List<String> features) {
double correct = 0, wrongs = 0;
for (Sample sample : samples) {
etiketler.put(sample.getSampleSınıfEtiketi(), 0.0);
}
for (Sample sample : samples) {
String classifiedAs = classify(sample, features);
// System.out.println("classifiedAs " + classifiedAs);
if (classifiedAs.equals(sample.getSampleSınıfEtiketi()))
correct++;
else
wrongs++;
}
accuracy = (correct / (correct + wrongs)) * 100;
}
private String classify(Sample sample, List<String> features) {
C45DecisionTreeNode root = dt.rootNode;
// System.out.println("classifying " + sample);
while (true) {
if (!root.isYaprak()) {
String featureName = root.getFeatureName();
// System.out.println(featureName);
int featureindex = features.indexOf(featureName);
String featureVal = sample.subSample.get(featureindex);//getDescreteValue(featureindex);
if (root.getChildren().keySet().contains(featureVal)) {
root = root.getChildren().get(featureVal);
} else {
// System.out.println("getting prominent");
return prominentClass(root);
}
} else
return root.getNodesinifEtiketi();
}
}
private String prominentClass(C45DecisionTreeNode root) {
int pos = 0, neg = 0;
Queue<C45DecisionTreeNode> curr = new LinkedBlockingQueue<C45DecisionTreeNode>();
curr.add(root);
while (!curr.isEmpty()) {
C45DecisionTreeNode node = curr.poll();
if (node.isYaprak()) {
for(Entry<String, Double> entry : etiketler.entrySet()) {
if (entry.getKey().equals(node.getNodesinifEtiketi())){
entry.setValue(entry.getValue() + 1 );
}
}
} else {
HashMap<String, C45DecisionTreeNode> children = node.getChildren();
for (String vals : children.keySet()) {
// System.out.println("children " + children.get(vals));
curr.add(children.get(vals));
}
}
}
String sinifEtiketi = "";
Double counter = 0.0;
for(Entry<String, Double> entry : etiketler.entrySet()) {
if(entry.getValue()>=counter){
sinifEtiketi = entry.getKey();
counter = entry.getValue();
}
}
return sinifEtiketi;
}
}
| gpl-2.0 |
Ilya-d/htdocs | wp-content/themes/malivi/templates/community/edit-achievement.php | 5012 | <?php
if (isset($tribe_event_id)) {
$image_id = get_post_thumbnail_id($tribe_event_id);
$current_image_url = wp_get_attachment_image_url( $image_id, Malivi::IMAGE_SQUARE_X2 );
} else {
$current_image_url = '';
}
if ($_POST) {
$title = isset($_POST['post_title']) ? stripslashes($_POST['post_title']) : '';
$description = isset($_POST['post_content']) ? stripslashes($_POST['post_content']) : '';
$image_url = isset($_POST['post_image_url']) ? $_POST['post_image_url'] : '';
if (!empty($image_url)) {
$current_image_url = $image_url;
}
} else {
$title = isset($event->post_title) ? $event->post_title : '';
$description = isset($event->post_content) ? $event->post_content : '';
$image_url = '';
}
?>
<?php echo tribe_community_events_get_messages(); ?>
<form class="tribe-community-submit-form eventForm" method="post" enctype="multipart/form-data">
<input type="hidden" name="post_ID" id="post_ID" value="<?php echo absint( $tribe_event_id ); ?>"/>
<?php wp_nonce_field( 'ecp_event_submission' ); ?>
<div class="group-element page-section">
<div class="text-content">
<div class="tribe_sectionheader">
<h4><?php tribe_community_events_field_label( 'event_texts', __( 'Основное', 'the-events-calendar') ); ?></h4>
</div>
<?php // Title ?>
<div class="block">
<p><?php tribe_community_events_field_label( 'post_title', __( 'Title:', 'tribe-events-community' ) ); ?></p>
<p class="note"><?php echo sprintf( __( 'Простое и короткое название. Рекомендуем использовать не более 40 символов.', 'tribe-events-community' ), 40 ); ?></p>
<p><input class="full-width" type="text" id="post_title" name="post_title" value="<?php echo htmlentities( $title ); ?>"/></p>
</div>
<?php // Description ?>
<div class="block">
<p><?php tribe_community_events_field_label( 'post_content', __( 'Description:', 'tribe-events-community' ) ); ?></p>
<p class="note"><?php _e( 'Описание одной строкой', 'tribe-events-community' ); ?></p>
<p><?php Tribe__Events__Community__Main::instance()->formContentEditor('post_content', apply_filters('the_content', $description)); ?></p>
</div>
<?php // Image ?>
<div class="block">
<p><?php tribe_community_events_field_label( 'post_image', __( 'Обложка:', 'tribe-events-community' ) ); ?></p>
<p class="note"><?php _e( 'Картинка для отображения на достижении', 'tribe-events-community'); ?></p>
<p><table>
<tr><td class="min"><span class="label">Файл:</span></td><td><input id="post_image" class="full-width featured-image-input" type="file" name="post_image"></td></tr>
<tr><td class="min"><span class="label">Или ссылка:</span></td><td><input id="post_image_url" class="full-width featured-image-url-input" type="text" name="post_image_url" value="<?php echo $image_url ?>"></td></tr>
</table></p>
</div>
</div>
</div>
<h3 class="aligncenter">Как это будет выглядеть:</h3>
<? // Small preview ?>
<div class="fixed-width-content posts-list-row group-element page-section">
<div class="posts-list-post-image-thumbnail posts-list-cell" >
<?php create_background_image_from_url($current_image_url, 'automargin image tribe-community-post-back-post_image')?>
</div>
<div class="posts-list-text-cell" >
<div class="posts-list-text-cell-header tribe-community-post_title">
<?php echo $title; ?>
</div>
<div class="posts-list-text-cell-content tribe-community-post_excerpt">
<?php echo $description; ?>
</div>
</div>
</div>
<div class="group-element page-section">
<div class="text-content">
<?php Malivi_Templates::get_template( 'community/modules/organizer', array('post' => $event)); ?>
</div>
</div>
<!-- Form Submit -->
<div class="tribe-events-community-footer">
<input type="submit" id="submit" class="button submit events-community-submit" value="<?php
if ( isset( $tribe_event_id ) && $tribe_event_id ) {
_e( 'Update', 'tribe-events-community' );
} else {
if (current_user_can('publish_tribe_events')) {
_e( 'Publish', 'tribe-events-community' );
} else {
_e( 'Submit for moderation', 'tribe-events-community' );
}
}
?>" name="community-event" />
</div><!-- .tribe-events-community-footer -->
</form>
| gpl-2.0 |
Automattic/wp-calypso | client/components/gsuite/gsuite-price/test/index.js | 533 | import renderer from 'react-test-renderer';
import GSuitePrice from '../';
describe( 'GSuitePrice', () => {
const product = {
product_id: 69,
product_name: 'G Suite',
product_slug: 'gapps',
description: '',
cost: 76,
available: true,
is_domain_registration: false,
cost_display: '€76.00',
currency_code: 'EUR',
};
test( 'renders correctly', () => {
const tree = renderer
.create( <GSuitePrice product={ product } currencyCode={ 'EUR' } /> )
.toJSON();
expect( tree ).toMatchSnapshot();
} );
} );
| gpl-2.0 |
smtlaissezfaire/balie | ca/uottawa/balie/LanguageIdentification.java | 14552 | /*
* Balie - BAseLine Information Extraction
* Copyright (C) 2004-2007 David Nadeau
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Apr 12, 2004
*/
package ca.uottawa.balie;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import weka.classifiers.functions.SMO;
/**
* Methods for training, testing and using language identification.
*
* @author David Nadeau (pythonner@gmail.com)
*/
public class LanguageIdentification {
/**
* The latest LangID model (if found) is loaded upon construction.
* Language guesser will only work if a model is found.
*/
public LanguageIdentification() {
m_Model = null;
m_NGramLength = 2;
m_NGramMaxNum = 500;
m_nGramFreqThreshold = 100;
try {
m_Model = WekaPersistance.Load(Balie.LANGUAGE_ID_MODEL);
if (m_Model == null) {
throw new Error("Unable to find the language identification model :" + Balie.LANGUAGE_ID_MODEL);
}
} catch (Exception e) {
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("No LanguageIdentification model found.");
}
}
private WekaLearner m_Model;
private int m_NGramLength;
private int m_NGramMaxNum;
private int m_nGramFreqThreshold;
private WekaLearner TrainModel(ArrayList<String> pi_Languages) {
// Extract N-Gram from every training text
Iterator<String> iCur = pi_Languages.iterator();
Hashtable<String,ArrayList<CharacterNGram>> Lan2NGrams = new Hashtable<String,ArrayList<CharacterNGram>>();
Hashtable<String,Integer> hashAllNGrams = new Hashtable<String,Integer>();
Hashtable<String,Integer> hashAllUNIGrams = new Hashtable<String,Integer>();
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("Reading files.");
while (iCur.hasNext()) {
String strCurLan = (String)iCur.next();
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(strCurLan);
ArrayList<CharacterNGram> alCurNGrams = null;
try {
alCurNGrams = Files2NGram(Balie.LANGUAGE_ID_TRAINING_CORPUS, strCurLan, hashAllNGrams, hashAllUNIGrams);
} catch (Exception e) {
throw new Error("Training corpus was not found here: " + Balie.LANGUAGE_ID_TRAINING_CORPUS);
}
Lan2NGrams.put(strCurLan, alCurNGrams);
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("Done");
}
// Get a reasonable list of attributes (remove low freq)
ArrayList<String> alSelectedNgramAttributes = GetGlobalNGramList(hashAllNGrams);
ArrayList<String> alSelectedUnigramAttributes = GetGlobalNGramList(hashAllUNIGrams);
// Proceed to Attribute Selection only on the BiGRAMS
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("Attribute Selection...");
WekaAttribute[] wekaAttr = new WekaAttribute[alSelectedNgramAttributes.size()];
for (int i = 0; i != alSelectedNgramAttributes.size(); ++i) {
wekaAttr[i] = new WekaAttribute((String)alSelectedNgramAttributes.get(i));
}
//String[] strAttr = (String[])alSelectedNgramAttributes.toArray(new String [alSelectedNgramAttributes.size()]);
String[] strClass = (String[])pi_Languages.toArray(new String [pi_Languages.size()]);
WekaAttributeSelection was = new WekaAttributeSelection(WekaAttributeSelection.WEKA_CHI_SQUARE, wekaAttr, strClass);
iCur = pi_Languages.iterator();
while (iCur.hasNext()) {
String strCurLan = (String)iCur.next();
ArrayList<CharacterNGram> alCurNGrams = Lan2NGrams.get(strCurLan);
Iterator<CharacterNGram> iNCur = alCurNGrams.iterator();
while (iNCur.hasNext()) {
CharacterNGram cng = iNCur.next();
Double[] nGram = cng.Instance((String[])alSelectedNgramAttributes.toArray(new String[0]));
was.AddInstance(nGram, strCurLan);
}
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(String.valueOf(alCurNGrams.size()) + " instances created for " + strCurLan);
}
was.NumAttributes(m_NGramMaxNum);
was.Select(true);
String[] strReducedAttr = was.ReduceDimentionality();
// Now, concat chosen nGram and unigram in the final list of attributes
String[] strAllAttributes = new String[m_NGramMaxNum + alSelectedUnigramAttributes.size()];
WekaAttribute[] wekaFinalAttr = new WekaAttribute[strAllAttributes.length];
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("Creating the classifier...");
for (int i = 0; i !=strReducedAttr.length; ++i) {
wekaFinalAttr[i] = new WekaAttribute(strReducedAttr[i]);
strAllAttributes[i] = strReducedAttr[i];
}
// At the list of the Reduced Attributes(NGrams) add the list of UNIGrams
int nPos = strReducedAttr.length;
for (int i = 0; i != alSelectedUnigramAttributes.size(); ++i) {
wekaFinalAttr[nPos] = new WekaAttribute((String)alSelectedUnigramAttributes.get(i));
strAllAttributes[nPos] = (String)alSelectedUnigramAttributes.get(i);
++nPos;
}
WekaLearner wl = new WekaLearner(wekaFinalAttr, strClass);
iCur = pi_Languages.iterator();
while (iCur.hasNext()) {
String strCurLan = (String)iCur.next();
ArrayList<CharacterNGram> alCurNGrams = Lan2NGrams.get(strCurLan);
Iterator<CharacterNGram> iNCur = alCurNGrams.iterator();
while (iNCur.hasNext()) {
CharacterNGram cng = iNCur.next();
Double[] nGram = cng.Instance(strAllAttributes);
wl.AddTrainInstance(nGram, strCurLan);
}
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(String.valueOf(alCurNGrams.size()) + " TRAIN instances created for " + strCurLan);
}
SMO smo = new SMO();
wl.CreateModel(smo);
/*
// Create a classifier
if (MODE.equals(Balie.LANGUAGE_ID_MODEL_HUGE)) {
SMO smo = new SMO();
wl.CreateModel(smo);
} else {
NaiveBayes nb = new NaiveBayes();
//nb.setUseKernelEstimator(true);
wl.CreateModel(nb);
}
*/
return wl;
}
private void TestModel(WekaLearner pi_Model, ArrayList<String> pi_Languages) {
// Extract N-Gram from every testing text
Iterator<String> iCur = pi_Languages.iterator();
Hashtable<String,ArrayList<CharacterNGram>> Lan2NGrams = new Hashtable<String,ArrayList<CharacterNGram>>();
Hashtable<String, Integer> hashAllNGrams = new Hashtable<String, Integer>();
Hashtable<String, Integer> hashAllUNIGrams = new Hashtable<String, Integer>();
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("Reading files.");
while (iCur.hasNext()) {
String strCurLan = (String)iCur.next();
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(strCurLan);
ArrayList<CharacterNGram> alCurNGrams = null;
try {
alCurNGrams = Files2NGram(Balie.LANGUAGE_ID_TESTING_CORPUS, strCurLan, hashAllNGrams, hashAllUNIGrams);
} catch (Exception e) {
throw new Error("Testing corpus was not found here: " + Balie.LANGUAGE_ID_TESTING_CORPUS);
}
Lan2NGrams.put(strCurLan, alCurNGrams);
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out("Done");
}
// Get the list of attributes
String[] strSelectedAttributes = pi_Model.GetAttributeList();
iCur = pi_Languages.iterator();
while (iCur.hasNext()) {
String strCurLan = (String)iCur.next();
ArrayList<CharacterNGram> alCurNGrams = Lan2NGrams.get(strCurLan);
Iterator<CharacterNGram> iNCur = alCurNGrams.iterator();
while (iNCur.hasNext()) {
CharacterNGram cng = iNCur.next();
Double[] nGram = cng.Instance(strSelectedAttributes);
pi_Model.AddTestInstance(nGram, strCurLan);
}
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(String.valueOf(alCurNGrams.size()) + " TEST instances created for " + strCurLan);
}
System.out.println(pi_Model.TestModel());
}
private ArrayList<String> GetGlobalNGramList(Hashtable<String, Integer> pi_hashAllNGrams) {
ArrayList<String> alSelectedAttributes = new ArrayList<String>();
// Attribute Selection
Enumeration<String> keyEnum = pi_hashAllNGrams.keys();
while (keyEnum.hasMoreElements()) {
String strNGram = keyEnum.nextElement();
if (((Integer)pi_hashAllNGrams.get(strNGram)).intValue() > m_nGramFreqThreshold) {
alSelectedAttributes.add(strNGram);
}
}
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(String.valueOf(alSelectedAttributes.size()) + " attributes found");
return alSelectedAttributes;
}
private ArrayList<CharacterNGram> Files2NGram(String pi_Corpus, String pi_Language, Hashtable<String,Integer> pi_hashAllNGrams, Hashtable<String,Integer> pi_hashAllUNIGrams) {
ArrayList<CharacterNGram> alCurNGrams = new ArrayList<CharacterNGram>();
String strTextPath = pi_Corpus + "/" + pi_Language;
File fBasePath = new File(strTextPath);
String[] strTrainingFiles = fBasePath.list();
for (int i = 0; i != strTrainingFiles.length; ++i) {
if (!strTrainingFiles[i].equals("CVS")) {
try {
// Language Identification corpus
String strContent = FileHandler.GetTextFileContent(fBasePath.getAbsolutePath() + "/" + strTrainingFiles[i], Balie.ENCODING_LITTLE_INDIAN);
CharacterNGram cng = new CharacterNGram(m_NGramLength);
cng.Feed(strContent);
Hashtable<String,Integer> NGR_freq = cng.NGramFrequency();
Hashtable<String,Integer> UNIGR_freq = cng.UNIGramFrequency();
Enumeration<String> N_keyEnum = NGR_freq.keys();
while (N_keyEnum.hasMoreElements()) {
String strNGram = N_keyEnum.nextElement();
if (pi_hashAllNGrams.containsKey(strNGram)){
int old = ((Integer)pi_hashAllNGrams.get(strNGram)).intValue();
int cur = ((Integer)NGR_freq.get(strNGram)).intValue();
pi_hashAllNGrams.put(strNGram, new Integer(old+cur));
} else {
pi_hashAllNGrams.put(strNGram, NGR_freq.get(strNGram));
}
}
//We create a separate Hashtable for the UNI_Grams
Enumeration<String> UNI_keyEnum = UNIGR_freq.keys();
while (UNI_keyEnum.hasMoreElements()) {
String strUNIGram = (String)UNI_keyEnum.nextElement();
if (pi_hashAllUNIGrams.containsKey(strUNIGram)){
int old = ((Integer)pi_hashAllUNIGrams.get(strUNIGram)).intValue();
int cur = ((Integer)UNIGR_freq.get(strUNIGram)).intValue();
pi_hashAllUNIGrams.put(strUNIGram, new Integer(old+cur));
} else {
pi_hashAllUNIGrams.put(strUNIGram, UNIGR_freq.get(strUNIGram));
}
}
alCurNGrams.add(cng);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) System.out.print(".");
}
return alCurNGrams;
}
/**
* Gives the likelihood of every language given a text.
*
* @param pi_Text A text for which we want to guess the language
* @return Array of LanguageIdentificationGuess (one per supported language)
*/
public LanguageIdentificationGuess[] GetLanguageLikelihood(String pi_Text) {
if (m_Model == null) {
throw new Error("Model must be loaded at construction time.");
}
CharacterNGram cng = new CharacterNGram(m_NGramLength);
cng.Feed(pi_Text);
Double[] instance = cng.Instance(m_Model.GetAttributeList());
String strLangs[] = (String[])m_Model.GetClassList();
double fProb[] = m_Model.GetDistribution(instance);
if (strLangs.length != fProb.length) {
throw new Error("Incompatible language list and probability distribution.");
}
LanguageIdentificationGuess guesses[] = new LanguageIdentificationGuess[strLangs.length];
for (int i = 0; i != strLangs.length; ++i) {
guesses[i] = new LanguageIdentificationGuess(strLangs[i], new Double(fProb[i]));
if(Balie.DEBUG_LANGUAGE_IDENTIFICATION) DebugInfo.Out(strLangs[i] + "(" + fProb[i] + ")");
}
return guesses;
}
/**
* Gives the language with the highest likelihood.
*
* @param pi_Text A text for which we want to guess the language
* @return String that represent the most probable language (see {@link Balie} for enumeration)
* @see Balie
*/
public String DetectLanguage(String pi_Text) {
String strLanguage = Balie.LANGUAGE_UNKNOWN;
LanguageIdentificationGuess[] guesses = GetLanguageLikelihood(pi_Text);
// sort language by probability
Arrays.sort(guesses);
//TODO: implements better heuristic in case many language are probable..
strLanguage = guesses[0].Language();
return strLanguage;
}
/**
* Trains and Tests the language identification model.
*/
public static void TrainLanguageIdentification() {
ArrayList<String> alLang = new ArrayList<String>();
alLang.add(Balie.LANGUAGE_ENGLISH);
alLang.add(Balie.LANGUAGE_FRENCH);
alLang.add(Balie.LANGUAGE_SPANISH);
alLang.add(Balie.LANGUAGE_GERMAN);
alLang.add(Balie.LANGUAGE_ROMANIAN);
LanguageIdentification li = new LanguageIdentification();
WekaLearner wl = li.TrainModel(alLang);
li.TestModel(wl, alLang);
// output arff file for visualization and debugging
WekaPersistance.PrintToArffFile(wl, Balie.OUT_LI_TRAIN_MODEL, WekaPersistance.PRINT_TRAINING_SET);
WekaPersistance.PrintToArffFile(wl, Balie.OUT_LI_TEST_MODEL, WekaPersistance.PRINT_TESTING_SET);
// reduce model size
wl.Shrink();
// save model
WekaPersistance.Save(wl, Balie.LANGUAGE_ID_MODEL);
}
/**
* Execute TrainLanguageIdentification()
*
* @param args
*/
public static void main(String[] args) {
TrainLanguageIdentification();
}
}
| gpl-2.0 |
wolflee/coreboot | util/spdtool/spdtool.py | 8139 | #!/usr/bin/env python
# spdtool - Tool for partial deblobbing of UEFI firmware images
# Copyright (C) 2019 9elements Agency GmbH <patrick.rudolph@9elements.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.
#
#
# Parse a blob and search for SPD files.
# First it is searched for a possible SPD header.
#
# For each candidate the function verify_match is invoked to check
# additional fields (known bits, reserved bits, CRC, ...)
#
# Dumps the found SPDs into the current folder.
#
# Implemented:
# DDR4 SPDs
#
import argparse
import crc16
import struct
class Parser(object):
def __init__(self, blob, verbose=False, ignorecrc=False):
self.blob = blob
self.ignorecrc = ignorecrc
self.verbose = verbose
@staticmethod
def get_matches():
"""Return the first byte to look for"""
raise Exception("Function not implemented")
def verify_match(self, header, offset):
"""Return true if it looks like a SPD"""
raise Exception("Function not implemented")
def get_len(self, header, offset):
"""Return the length of the SPD"""
raise Exception("Function not implemented")
def get_part_number(self, offset):
"""Return the part number in SPD"""
return ""
def get_manufacturer_id(self, offset):
"""Return the manufacturer ID in SPD"""
return 0xffff
def get_mtransfers(self, offset):
"""Return the number of MT/s"""
return 0
def get_manufacturer(self, offset):
"""Return manufacturer as string"""
id = self.get_manufacturer_id(offset)
if id == 0xffff:
return "Unknown"
ids = {
0x2c80: "Crucial/Micron",
0x4304: "Ramaxel",
0x4f01: "Transcend",
0x9801: "Kingston",
0x987f: "Hynix",
0x9e02: "Corsair",
0xb004: "OCZ",
0xad80: "Hynix/Hyundai",
0xb502: "SuperTalent",
0xcd04: "GSkill",
0xce80: "Samsung",
0xfe02: "Elpida",
0xff2c: "Micron",
}
if id in ids:
return ids[id]
return "Unknown"
def blob_as_ord(self, offset):
"""Helper for python2/python3 compatibility"""
return self.blob[offset] if type(self.blob[offset]) is int \
else ord(self.blob[offset])
def search(self, start):
"""Search for SPD at start. Returns -1 on error or offset
if found.
"""
for i in self.get_matches():
for offset in range(start, len(self.blob)):
if self.blob_as_ord(offset) == i and \
self.verify_match(i, offset):
return offset, self.get_len(i, offset)
return -1, 0
class SPD4Parser(Parser):
@staticmethod
def get_matches():
"""Return DDR4 possible header candidates"""
ret = []
for i in [1, 2, 3, 4]:
for j in [1, 2]:
ret.append(i + j * 16)
return ret
def verify_match(self, header, offset):
"""Verify DDR4 specific bit fields."""
# offset 0 is a candidate, no need to validate
if self.blob_as_ord(offset + 1) == 0xff:
return False
if self.blob_as_ord(offset + 2) != 0x0c:
return False
if self.blob_as_ord(offset + 5) & 0xc0 > 0:
return False
if self.blob_as_ord(offset + 6) & 0xc > 0:
return False
if self.blob_as_ord(offset + 7) & 0xc0 > 0:
return False
if self.blob_as_ord(offset + 8) != 0:
return False
if self.blob_as_ord(offset + 9) & 0xf > 0:
return False
if self.verbose:
print("%x: Looks like DDR4 SPD" % offset)
crc = crc16.crc16xmodem(self.blob[offset:offset + 0x7d + 1])
# Vendors ignore the endianness...
crc_spd1 = self.blob_as_ord(offset + 0x7f)
crc_spd1 |= (self.blob_as_ord(offset + 0x7e) << 8)
crc_spd2 = self.blob_as_ord(offset + 0x7e)
crc_spd2 |= (self.blob_as_ord(offset + 0x7f) << 8)
if crc != crc_spd1 and crc != crc_spd2:
if self.verbose:
print("%x: CRC16 doesn't match" % offset)
if not self.ignorecrc:
return False
return True
def get_len(self, header, offset):
"""Return the length of the SPD found."""
if (header >> 4) & 7 == 1:
return 256
if (header >> 4) & 7 == 2:
return 512
return 0
def get_part_number(self, offset):
"""Return part number as string"""
if offset + 0x15c >= len(self.blob):
return ""
tmp = self.blob[offset + 0x149:offset + 0x15c + 1]
return tmp.decode('utf-8').rstrip()
def get_manufacturer_id(self, offset):
"""Return manufacturer ID"""
if offset + 0x141 >= len(self.blob):
return 0xffff
tmp = self.blob[offset + 0x140:offset + 0x141 + 1]
return struct.unpack('H', tmp)[0]
def get_mtransfers(self, offset):
"""Return MT/s as specified by MTB and FTB"""
if offset + 0x7d >= len(self.blob):
return 0
if self.blob_as_ord(offset + 0x11) != 0:
return 0
mtb = 8.0
ftb = 1000.0
tmp = self.blob[offset + 0x12:offset + 0x12 + 1]
tckm = struct.unpack('B', tmp)[0]
tmp = self.blob[offset + 0x7d:offset + 0x7d + 1]
tckf = struct.unpack('b', tmp)[0]
return int(2000 / (tckm / mtb + tckf / ftb))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='SPD rom dumper')
parser.add_argument('--blob', required=True,
help='The ROM to search SPDs in.')
parser.add_argument('--spd4', action='store_true', default=False,
help='Search for DDR4 SPDs.')
parser.add_argument('--hex', action='store_true', default=False,
help='Store SPD in hex format otherwise binary.')
parser.add_argument('-v', '--verbose', help='increase output verbosity',
action='store_true')
parser.add_argument('--ignorecrc', help='Ignore CRC mismatch',
action='store_true', default=False)
args = parser.parse_args()
blob = open(args.blob, "rb").read()
if args.spd4:
p = SPD4Parser(blob, args.verbose, args.ignorecrc)
else:
raise Exception("Must specify one of the following arguments:\n--spd4")
offset = 0
cnt = 0
while True:
offset, length = p.search(offset)
if length == 0:
break
print("Found SPD at 0x%x" % offset)
print(" '%s', size %d, manufacturer %s (0x%04x) %d MT/s\n" %
(p.get_part_number(offset), length, p.get_manufacturer(offset),
p.get_manufacturer_id(offset), p.get_mtransfers(offset)))
filename = "spd-%d-%s-%s.bin" % (cnt, p.get_part_number(offset),
p.get_manufacturer(offset))
filename = filename.replace("/", "_")
filename = "".join([c for c in filename if c.isalpha() or c.isdigit()
or c == '-' or c == '.' or c == '_']).rstrip()
if not args.hex:
open(filename, "wb").write(blob[offset:offset + length])
else:
filename += ".hex"
with open(filename, "w") as fn:
j = 0
for i in blob[offset:offset + length]:
fn.write("%02X" % struct.unpack('B', i)[0])
fn.write(" " if j < 15 else "\n")
j = (j + 1) % 16
offset += 1
cnt += 1
| gpl-2.0 |
Elv13/Umbrello-ng2 | umbrello/widgets/linkwidget.cpp | 2290 | /***************************************************************************
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* copyright (C) 2004-2012 *
* Umbrello UML Modeller Authors <uml-devel@uml.sf.net> *
***************************************************************************/
// own header
#include "linkwidget.h"
// app includes
#include "classifier.h"
#include "operation.h"
#include "uml.h"
#include "umlobject.h"
#include "umlview.h"
LinkWidget::LinkWidget()
{
}
LinkWidget::~LinkWidget()
{
}
/**
* Motivated by FloatingTextWidget::slotMenuSelection(mt_Operation)
*/
UMLClassifier *LinkWidget::operationOwner()
{
UMLOperation *op = operation();
if (op == NULL)
return NULL;
return static_cast<UMLClassifier*>(op->parent());
}
/**
* Return the operation text.
* When no scene parameter is given, the scene of the current view
* is taken instead.
* @param scene the given scene
* @return the operation text
*/
QString LinkWidget::operationText(UMLScene *scene)
{
UMLOperation *op = operation();
if (op == NULL)
return customOpText();
if (scene == NULL)
scene = UMLApp::app()->currentView()->umlScene();
Uml::SignatureType sigType;
if (scene && scene->showOpSig())
sigType = Uml::SignatureType::SigNoVis;
else
sigType = Uml::SignatureType::NoSigNoVis;
QString opText = op->toString(sigType);
return opText;
}
/**
* Motivated by FloatingTextWidget::slotMenuSelection(mt_Reset_Label_Positions)
* Only applies to AssociationWidget.
*/
void LinkWidget::resetTextPositions()
{
}
/**
* Motivated by FloatingTextWidget::mouseDoubleClickEvent()
* Only applies to AssociationWidget.
*/
void LinkWidget::showPropertiesDialog()
{
}
/**
* Motivated by FloatingTextWidget::setLink().
* Only applies to AssociationWidget.
*/
void LinkWidget::calculateNameTextSegment()
{
}
| gpl-2.0 |
kldavis4/copcast-server | lib/utils/email_manager.js | 5127 | /**
* Created by brunosiqueira on 29/02/16.
*/
var emailTemplates = require('email-templates'),
nodemailer = require('nodemailer'),
smtpTransport = require("nodemailer-smtp-transport"),
config = require('../config'),
path = require('path'),
templatesDir = path.resolve(__dirname, '..', 'templates'),
_ = require('lodash'),
smtpTransport = nodemailer.createTransport(smtpTransport({
service: config.email.service,
auth: {
user: config.email.user,
pass: config.email.pass
}
}));
var emailManager = {};
emailManager.sendEmailExportSuccess = function(email, downloadUrl, username, callback) {
emailTemplates(templatesDir, function (err, template) {
if (err) {
console.log(err);
callback(false, err);
} else {
var locals = {
email: email,
username: username,
downloadUrl: downloadUrl
};
template("export", locals, function (err, html, text) {
if (err) {
console.log(err);
callback(false, err);
} else {
if (smtpTransport) {
smtpTransport.sendMail({
from: config.email.from,
to: locals.email,
subject: "Video export is ready",
html: html
}, function (err, responseStatus) {
if (err) {
console.log(err);
callback(false, err);
} else {
console.log(responseStatus.message);
callback(true);
}
});
} else {
callback(false, 'problems with smtpTransport. returning HTTP 500');
}
}
});
}
});
};
emailManager.sendEmailErrorExport = function(email, username, callback) {
emailTemplates(templatesDir, function (err, template) {
if (err) {
console.log(err);
callback(false, err);
} else {
var locals = {
email: email,
username: username
};
template("errorExport", locals, function (err, html, text) {
if (err) {
console.log(err);
callback(false, err);
} else {
if (smtpTransport) {
smtpTransport.sendMail({
from: config.email.from,
to: locals.email,
subject: "There was an error exporting your videos",
html: html
}, function (err, responseStatus) {
if (err) {
console.log(err);
callback(false, err);
} else {
console.log(responseStatus.message);
callback(true);
}
});
} else {
callback(false, 'problems with smtpTransport. returning HTTP 500');
}
}
});
}
});
};
emailManager.sendEmailForgotPassword = function(email, accessUrl, username, callback) {
emailTemplates(templatesDir, function (err, template) {
if (err) {
console.log(err);
callback(false, err);
} else {
var locals = {
email: email,
username: username,
accessUrl: accessUrl
};
template("forgotPass", locals, function (err, html, text) {
if (err) {
console.log(err);
callback(false, err);
} else {
if (smtpTransport) {
smtpTransport.sendMail({
from: config.email.from,
to: locals.email,
subject: "New Password",
html: html
}, function (err, responseStatus) {
if (err) {
console.log(err);
callback(false, err);
} else {
console.log(responseStatus.message);
callback(true);
}
});
} else {
callback(false, 'problems with smtpTransport. returning HTTP 500');
}
}
});
}
});
}
emailManager.sendEmailAdmError = function(error, username, callback) {
emailTemplates(templatesDir, function (err, template) {
if (err) {
console.log(err);
callback(false, err);
} else {
var locals = {
email: config.email.administrator,
username: username,
error: JSON.stringify(error)
};
template("errorAdm", locals, function (err, html, text) {
if (err) {
console.log(err);
callback(false, err);
} else {
if (smtpTransport) {
smtpTransport.sendMail({
from: config.email.from,
to: locals.email,
subject: "There was an error in the app",
html: html
}, function (err, responseStatus) {
if (err) {
console.log(err);
callback(false, err);
} else {
console.log(responseStatus.message);
callback(true);
}
});
} else {
callback(false, 'problems with smtpTransport. returning HTTP 500');
}
}
});
}
});
};
module.exports = emailManager;
| gpl-2.0 |
nbdarling/typechoi7-master | usr/themes/Baroque-Duoshuo-3.0.1/post.php | 817 | <?php if (!defined('__TYPECHO_ROOT_DIR__')) exit; ?>
<?php $this->need('header.php'); ?>
<div class="wrapper main" role="main">
<article class="post" itemscope itemtype="http://schema.org/BlogPosting">
<h1 class="post-title" itemprop="name headline"><?php $this->title() ?></h1>
<div class="post-meta">
<span class="post-category"><?php $this->category(','); ?></span><span datetime="<?php $this->date('c'); ?>" itemprop="datePublished"><?php $this->date('n月j日'); ?></span><span class="ds-thread-count" data-thread-key="<?php $this->cid(); ?>"></span>
</div>
<div class="post-content" itemprop="articleBody">
<?php $this->content(); ?>
</div>
</article>
<?php $this->need('comments.php'); ?>
</div>
<?php $this->need('footer.php'); ?>
| gpl-2.0 |
thinkdrop/dogblog | tests/vendor/autoload.php | 183 | <?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit35257630e8d0100c721af79839202da1::getLoader();
| gpl-2.0 |
scottlerch/HappiestProgrammer | WebApp/Controllers/CommentsController.cs | 2138 | using HappiestProgrammer.Core.Entities;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebAPI.OutputCache;
using WebApp.Models;
using HappiestProgrammer.Core.Utilities;
namespace WebApp.Controllers
{
public class CommentsController : ApiController
{
private const int NumberOfComments = 7;
// GET api/values
[CacheOutput(ClientTimeSpan = 86400, ServerTimeSpan = 86400)]
public IEnumerable<Comment> Get(DateTime date, string language, bool positive, int days)
{
var table = this.GetSentimentsTable();
var query = new TableQuery<CommentEntity>().Where(
TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.LessThanOrEqual, date.ToString("yyyyMMdd")),
TableOperators.And,
TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, date.AddDays(-days).ToString("yyyyMMdd"))));
foreach (var entity in table.ExecuteQuery(query)
.Where(c =>
string.Compare(c.Language, language, ignoreCase: true) == 0 &&
((positive && c.Score > 0) || (!positive && c.Score < 0)))
.OrderBy(c => c.Score, descending: positive)
.Take(NumberOfComments))
{
yield return new Comment
{
Score = entity.Score,
Text = entity.Comment,
Date = entity.Date,
Language = language,
};
}
}
private CloudTable GetSentimentsTable()
{
var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
var tableClient = storageAccount.CreateCloudTableClient();
return tableClient.GetTableReference("commentscores");
}
}
} | gpl-2.0 |
UnboundID/ldapsdk | tests/unit/src/com/unboundid/util/args/ProhibitDNInSubtreeArgumentValueValidatorTestCase.java | 7474 | /*
* Copyright 2015-2020 Ping Identity Corporation
* All Rights Reserved.
*/
/*
* Copyright 2015-2020 Ping Identity Corporation
*
* 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.
*/
/*
* Copyright (C) 2015-2020 Ping Identity Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (GPLv2 only)
* or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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.unboundid.util.args;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.unboundid.ldap.sdk.DN;
import com.unboundid.ldap.sdk.LDAPSDKTestCase;
/**
* This class provides a set of test cases for the prohibit DN in subtree
* argument value validator.
*/
public final class ProhibitDNInSubtreeArgumentValueValidatorTestCase
extends LDAPSDKTestCase
{
// A number of validator instances to use in testing.
private ProhibitDNInSubtreeArgumentValueValidator prohibitSingle;
private ProhibitDNInSubtreeArgumentValueValidator prohibitMultiple;
// Arguments to use for testing.
private DNArgument dnArg;
private StringArgument stringArg;
/**
* Sets up the necessary elements for testing.
*
* @throws Exception If an unexpected problem occurs.
*/
@BeforeClass()
public void setUp()
throws Exception
{
prohibitSingle = new ProhibitDNInSubtreeArgumentValueValidator(
new DN("ou=Excluded1,dc=example,dc=com"));
assertNotNull(prohibitSingle.getBaseDNs());
assertEquals(prohibitSingle.getBaseDNs().size(), 1);
assertNotNull(prohibitSingle.toString());
prohibitMultiple = new ProhibitDNInSubtreeArgumentValueValidator(
new DN("ou=Excluded1,dc=example,dc=com"),
new DN("ou=Excluded2,dc=example,dc=com"));
assertNotNull(prohibitMultiple.getBaseDNs());
assertEquals(prohibitMultiple.getBaseDNs().size(), 2);
assertNotNull(prohibitMultiple.toString());
dnArg = new DNArgument(null, "testDN", false, 1, "{dn}", "Description");
stringArg = new StringArgument(null, "testString", false, 1, "{value}",
"Description");
}
/**
* Tests the validator with the provided information.
*
* @param value The value to be tested.
* @param matchesExcluded1 Indicates whether the provided value is within
* the first excluded branch.
* @param matchesExcluded2 Indicates whether the provided value is within
* the second excluded branch.
*
* @throws Exception If an unexpected problem occurs.
*/
@Test(dataProvider = "testData")
public void testValidator(final String value, final boolean matchesExcluded1,
final boolean matchesExcluded2)
throws Exception
{
// See if the provided value is a valid DN. If not, then it'll always be
// rejected.
if (! DN.isValidDN(value))
{
assertInvalid(prohibitSingle, value);
assertInvalid(prohibitMultiple, value);
return;
}
// See if the value matches the first prohibited DN.
if (matchesExcluded1)
{
assertInvalid(prohibitSingle, value);
assertInvalid(prohibitMultiple, value);
}
else
{
assertValid(prohibitSingle, value);
}
// See if the value matches the second prohibited DN.
if (matchesExcluded2)
{
assertValid(prohibitSingle, value);
assertInvalid(prohibitMultiple, value);
}
else if (! matchesExcluded1)
{
assertValid(prohibitSingle, value);
assertValid(prohibitMultiple, value);
}
}
/**
* Retrieves data that can be used for testing.
*
* @return Data that can be used for testing.
*
* @throws Exception If an unexpected problem occurs.
*/
@DataProvider(name="testData")
public Object[][] getTestData()
throws Exception
{
return new Object[][]
{
new Object[]
{
"",
false,
false
},
new Object[]
{
"invalid",
false,
false
},
new Object[]
{
"dc=example,dc=com",
false,
false
},
new Object[]
{
"ou=Excluded1,dc=example,dc=com",
true,
false
},
new Object[]
{
"ou=Sub1,ou=Excluded1,dc=example,dc=com",
true,
false
},
new Object[]
{
"ou=Sub2,ou=Excluded1,dc=example,dc=com",
true,
false
},
new Object[]
{
"ou=Excluded2,dc=example,dc=com",
false,
true
},
new Object[]
{
"ou=Sub1,ou=Excluded2,dc=example,dc=com",
false,
true
},
new Object[]
{
"ou=Sub2,ou=Excluded2,dc=example,dc=com",
false,
true
},
};
}
/**
* Ensures that the provided value is valid for the provided validator.
*
* @param validator The validator to use.
* @param value The value to validate.
*/
private void assertValid(
final ProhibitDNInSubtreeArgumentValueValidator validator,
final String value)
{
try
{
validator.validateArgumentValue(dnArg, value);
}
catch (final ArgumentException ae)
{
fail("Expected value '" + value + "' to be accepted by validator " +
validator);
}
try
{
validator.validateArgumentValue(stringArg, value);
}
catch (final ArgumentException ae)
{
fail("Expected value '" + value + "' to be accepted by validator " +
validator);
}
}
/**
* Ensures that the provided value is not valid for the provided validator.
*
* @param validator The validator to use.
* @param value The value to validate.
*/
private void assertInvalid(
final ProhibitDNInSubtreeArgumentValueValidator validator,
final String value)
{
try
{
validator.validateArgumentValue(dnArg, value);
fail("Expected value '" + value + "' to be rejected by validator " +
validator);
}
catch (final ArgumentException ae)
{
// This was expected.
}
try
{
validator.validateArgumentValue(stringArg, value);
fail("Expected value '" + value + "' to be rejected by validator " +
validator);
}
catch (final ArgumentException ae)
{
// This was expected.
}
}
}
| gpl-2.0 |
estrategasdigitales/lactibox | wp-content/plugins/detheme_builder/lib/helpers.php | 14391 | <?php
/**
* @package WordPress
* @subpackage DT Page Builder
* @version 1.3.2
* @since 1.0.0
*/
defined('DTPB_BASENAME') or die();
/* helper */
include_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
include_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php');
if (!function_exists('aq_resize')) {
function aq_resize( $url, $width, $height = null, $crop = null, $single = true ) {
if(!$url OR !($width || $height)) return false;
//define upload path & dir
$upload_info = wp_upload_dir();
$upload_dir = $upload_info['basedir'];
$upload_url = $upload_info['baseurl'];
//check if $img_url is local
/* Gray this out because WPML doesn't like it.
if(strpos( $url, home_url() ) === false) return false;
*/
//define path of image
$rel_path = str_replace( str_replace( array( 'http://', 'https://' ),"",$upload_url), '', str_replace( array( 'http://', 'https://' ),"",$url));
$img_path = $upload_dir . $rel_path;
//check if img path exists, and is an image indeed
if( !file_exists($img_path) OR !getimagesize($img_path) ) return false;
//get image info
$info = pathinfo($img_path);
$ext = $info['extension'];
list($orig_w,$orig_h) = getimagesize($img_path);
$dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
if(!$dims){
return $single?$url:array('0'=>$url,'1'=>$orig_w,'2'=>$orig_h);
}
$dst_w = $dims[4];
$dst_h = $dims[5];
//use this to check if cropped image already exists, so we can return that instead
$suffix = "{$dst_w}x{$dst_h}";
$dst_rel_path = str_replace( '.'.$ext, '', $rel_path);
$destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";
//if orig size is smaller
if($width >= $orig_w) {
if(!$dst_h) :
//can't resize, so return original url
$img_url = $url;
$dst_w = $orig_w;
$dst_h = $orig_h;
else :
//else check if cache exists
if(file_exists($destfilename) && getimagesize($destfilename)) {
$img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
}
else {
$imageEditor=wp_get_image_editor( $img_path );
if(!is_wp_error($imageEditor)){
$imageEditor->resize($width, $height, $crop );
$imageEditor->save($destfilename);
$resized_rel_path = str_replace( $upload_dir, '', $destfilename);
$img_url = $upload_url . $resized_rel_path;
}
else{
$img_url = $url;
$dst_w = $orig_w;
$dst_h = $orig_h;
}
}
endif;
}
//else check if cache exists
elseif(file_exists($destfilename) && getimagesize($destfilename)) {
$img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
}
else {
$imageEditor=wp_get_image_editor( $img_path );
if(!is_wp_error($imageEditor)){
$imageEditor->resize($width, $height, $crop );
$imageEditor->save($destfilename);
$resized_rel_path = str_replace( $upload_dir, '', $destfilename);
$img_url = $upload_url . $resized_rel_path;
}
else{
$img_url = $url;
$dst_w = $orig_w;
$dst_h = $orig_h;
}
}
if(!$single) {
$image = array (
'0' => $img_url,
'1' => $dst_w,
'2' => $dst_h
);
} else {
$image = $img_url;
}
return $image;
}
}
function get_image_size( $image_id,$img_size="thumbnail"){
global $_wp_additional_image_sizes;
if(''==$img_size)
$img_size="thumbnail";
if(''==$image_id)
return false;
if(in_array($img_size, array('thumbnail','thumb','small', 'medium', 'large','full'))){
if ( $img_size == 'thumb' || $img_size == 'small' || $img_size == 'thumbnail' ) {
$image=wp_get_attachment_image_src($image_id,'thumbnail');
}
elseif ( $img_size == 'medium' ) {
$image=wp_get_attachment_image_src($image_id,'medium');
}
elseif ( $img_size == 'large' ) {
$image=wp_get_attachment_image_src($image_id,'large');
}else{
$image=wp_get_attachment_image_src($image_id,'full');
}
}
elseif(!empty($_wp_additional_image_sizes[$img_size]) && is_array($_wp_additional_image_sizes[$img_size])){
$width=$_wp_additional_image_sizes[$img_size]['width'];
$height=$_wp_additional_image_sizes[$img_size]['height'];
$img_url = wp_get_attachment_image_src($image_id,'full',false);
$image=aq_resize( $img_url[0],$width, $height, true,false ) ;
}
else{
preg_match_all('/\d+/', $img_size, $thumb_matches);
if(isset($thumb_matches[0])) {
$thumb_size = array();
if(count($thumb_matches[0]) > 1) {
$thumb_size[] = $thumb_matches[0][0]; // width
$thumb_size[] = $thumb_matches[0][1]; // height
} elseif(count($thumb_matches[0]) > 0 && count($thumb_matches[0]) < 2) {
$thumb_size[] = $thumb_matches[0][0]; // width
$thumb_size[] = $thumb_matches[0][0]; // height
} else {
$thumb_size = false;
}
}
if($thumb_size){
$img_url = wp_get_attachment_image_src($image_id,'full',false);
$image=aq_resize( $img_url[0],$thumb_size[0], $thumb_size[1], true,false ) ;
}
else{
return false;
}
}
return $image;
}
function get_dt_elements(){
global $DElements;
if(!is_object($DElements)){
$DElements=DElements::getInstance();
}
return $DElements->getElements();
}
function get_dt_element($shortcode=""){
if(''==$shortcode) return false;
global $DElements;
if(!is_object($DElements)){
$DElements=DElements::getInstance();
}
$elements=$DElements->getElements();
return isset($elements[$shortcode])?$elements[$shortcode]:false;
}
function add_dt_element($shortcode_id,$params){
global $DElements;
if(!is_object($DElements)){
$DElements=DElements::getInstance();
}
$DElements->addElement($shortcode_id,$params);
}
function remove_dt_element($shortcode_id){
global $DElements;
if(!is_object($DElements)){
$DElements=DElements::getInstance();
}
$DElements->removeElement($shortcode_id);
}
function add_dt_element_render($shortcode_id,$funtionName){
/**
* @deprecated 1.4.0 use 2 args
*
*/
add_filter('render_'.$shortcode_id.'_shortcode',$funtionName,1,3);
}
function add_dt_element_preview($shortcode_id,$funtionName){
add_filter('preview_'.$shortcode_id.'_shortcode',$funtionName,1,3);
}
function add_dt_element_option($shortcode_id,$options=array(),$replace=true){
if($shortcode_id=='')
return false;
if(!$element=get_dt_element($shortcode_id))
return false;
$element->addOption($options,$replace);
}
function add_dt_element_options($shortcode_id,$options=array(),$replace=true){
if($shortcode_id=='')
return false;
if(!$element=get_dt_element($shortcode_id))
return false;
$element->addOptions($options,$replace);
}
function remove_dt_element_options($shortcode_id,$optionName){
if($shortcode_id=='')
return false;
$element=get_dt_element($shortcode_id);
if(!$element) return false;
$element->removeOption($optionName);
}
/**
*
* @since 1.3.2
*/
function remove_dt_element_option($shortcode_id,$optionName){
if($shortcode_id=='')
return false;
$element=get_dt_element($shortcode_id);
if(!$element) return false;
$element->removeOption($optionName);
}
function add_dt_field_type($type,$function_name){
$classField='DElement_Field_'.$type;
if(class_exists($classField) || !function_exists($function_name)) return false;
add_action( $classField,$function_name,1,2);
}
function create_dependency_param($option=array()){
if(!isset($option['dependency']) || ! is_array($option['dependency']))
return "";
$param=wp_parse_args($option['dependency'],array('element'=>"",'value'=>'','not_empty'=>false));
$dependent=$param['element'];
$dependent_value=$param['value'];
$not_empty=$param['not_empty'];
if($dependent=='' || ($dependent_value=='' && !$not_empty))
return "";
return " data-dependent=\"".$dependent."\" data-dependvalue=\"".($not_empty?"not_empty":(is_array($dependent_value)?@implode(",",$dependent_value):$dependent_value))."\"";
}
function getCssID($prefix=""){
global $dt_el_id;
if(!isset($dt_el_id)) {
$dt_el_id=0;
}
$dt_el_id++;
return $prefix.$dt_el_id;
}
function getCssMargin($atts,$is_array=false){
$defaults=array(
'm_top'=>'',
'm_bottom'=>'',
'm_left'=>'',
'm_right'=>'',
'p_top'=>'',
'p_bottom'=>'',
'p_left'=>'',
'p_right'=>'',
);
$args=wp_parse_args($atts,$defaults);
extract($args);
$css_style=array();
if(''!=$m_top){$m_top=(int)$m_top;$css_style['margin-top']="margin-top:".$m_top."px";}
if(''!=$m_bottom){$m_bottom=(int)$m_bottom;$css_style['margin-bottom']="margin-bottom:".$m_bottom."px";}
if(''!=$m_left){$m_left=(int)$m_left;$css_style['margin-left']="margin-left:".$m_left."px";}
if(''!=$m_right){$m_right=(int)$m_right;$css_style['margin-right']="margin-right:".$m_right."px";}
if(''!=$p_top){$p_top=(int)$p_top;$css_style['padding-top']="padding-top:".$p_top."px";}
if(''!=$p_bottom){$p_bottom=(int)$p_bottom;$css_style['padding-bottom']="padding-bottom:".$p_bottom."px";}
if(''!=$p_left){$p_left=(int)$p_left;$css_style['padding-left']="padding-left:".$p_left."px";}
if(''!=$p_right){$p_right=(int)$p_right;$css_style['padding-right']="padding-right:".$p_right."px";}
return $is_array?$css_style:@implode(";",$css_style);
}
if(!function_exists('darken')){
function darken($colourstr, $procent=0) {
$colourstr = str_replace('#','',$colourstr);
$rhex = substr($colourstr,0,2);
$ghex = substr($colourstr,2,2);
$bhex = substr($colourstr,4,2);
$r = hexdec($rhex);
$g = hexdec($ghex);
$b = hexdec($bhex);
$r = max(0,min(255,$r - ($r*$procent/100)));
$g = max(0,min(255,$g - ($g*$procent/100)));
$b = max(0,min(255,$b - ($b*$procent/100)));
return '#'.str_repeat("0", 2-strlen(dechex($r))).dechex($r).str_repeat("0", 2-strlen(dechex($g))).dechex($g).str_repeat("0", 2-strlen(dechex($b))).dechex($b);
}
}
if(!function_exists('lighten')){
function lighten($colourstr, $procent=0){
$colourstr = str_replace('#','',$colourstr);
$rhex = substr($colourstr,0,2);
$ghex = substr($colourstr,2,2);
$bhex = substr($colourstr,4,2);
$r = hexdec($rhex);
$g = hexdec($ghex);
$b = hexdec($bhex);
$r = max(0,min(255,$r + ($r*$procent/100)));
$g = max(0,min(255,$g + ($g*$procent/100)));
$b = max(0,min(255,$b + ($b*$procent/100)));
return '#'.str_repeat("0", 2-strlen(dechex($r))).dechex($r).str_repeat("0", 2-strlen(dechex($g))).dechex($g).str_repeat("0", 2-strlen(dechex($b))).dechex($b);
}
}
function get_carousel_preview($option=array(),$value=''){
$dependency=create_dependency_param($option);
$output='<div class="carousel-preview" '.$dependency.'>
<div class="owl-pagination">
<div class="owl-page active"><span></span></div>
<div class="owl-page"><span></span></div>
<div class="owl-page"><span></span></div>
</div>
</div>';
print $output;
}
add_dt_field_type('carousel_preview','get_carousel_preview');
function dt_remove_autop($content) {
return preg_replace('/<\/?p\>/', "", $content);
}
function dt_remove_wpautop($content) {
return wpautop(preg_replace('/<\/?p\>/', "", $content)."");
}
if(!function_exists('dt_exctract_icon')){
function dt_exctract_icon($file="",$pref=""){
$wp_filesystem=new WP_Filesystem_Direct(array());
if(!$wp_filesystem->is_file($file) || !$wp_filesystem->exists($file))
return false;
if ($buffers=$wp_filesystem->get_contents_array($file)) {
$icons=array();
foreach ($buffers as $line => $buffer) {
if(preg_match("/^(\.".$pref.")([^:\]\"].*?):before/i",$buffer,$out)){
if($out[2]!==""){
$icons[$pref.$out[2]]=$pref.$out[2];
}
}
}
return $icons;
}else{
return false;
}
}
}
function get_font_lists($path){
$wp_filesystem=new WP_Filesystem_Direct(array());
$icons=array();
if($dirlist=$wp_filesystem->dirlist($path)){
foreach ($dirlist as $dirname => $dirattr) {
if($dirattr['type']=='d'){
if($dirfont=$wp_filesystem->dirlist($path.$dirname)){
foreach ($dirfont as $filename => $fileattr) {
if(preg_match("/(\.css)$/", $filename)){
if($icon=dt_exctract_icon($path.$dirname."/".$filename)){
$icons=@array_merge($icon,$icons);
}
break;
}
}
}
}
elseif($dirattr['type']=='f' && preg_match("/(\.css)$/", $dirname)){
if($icon=dt_exctract_icon($path.$dirname)){
$icons=@array_merge($icon,$icons);
}
}
}
}
return $icons;
}
function get_dt_plugin_dir_url(){
return plugins_url( '/detheme_builder/');
}
function detheme_font_list(){
$path=DTPB_DIR."webicons/";
$icons=array();
if($newicons=get_font_lists($path)){
$icons=array_merge($icons,$newicons);
}
return apply_filters('detheme_font_list',$icons);
}
if(! function_exists('is_assoc_array')){
function is_assoc_array(array $array){
$keys = array_keys($array);
return array_keys($keys) !== $keys;
}
}
?>
| gpl-2.0 |
dicolit/d7 | sites/nscem/themes/nscem/scripts/main.js | 12413 | /* jshint devel:true */
'use strict';
var App = window.App || {};
// GLOBAL
jQuery(document).ready(function($) {
$('.logged-user--toggle-profile').on('click', function() {
$(this).toggleClass('active');
$('.logged-user--detail').slideToggle();
});
$('.top-links--user-info a').on('click', function(e) {
var menuId = $(this).attr('href').replace('#', '');
if ($(this).attr('id') == 'user-info--search') {
$('.top-links--user-info a').removeClass('active');
$('.drop-down-menu-inner').hide();
$('.mobile-menu').hide();
return;
}
$('.mobile-menu, .mobile-menu-inner').hide();
if ($(this).hasClass('active')) {
$('.top-links--user-info a').removeClass('active');
$('.drop-down-menu-inner').hide();
$('.mobile-menu').hide();
} else {
$('.top-links--user-info a').removeClass('active');
$(this).addClass('active');
// desktop dropdown
$('.drop-down-menu-inner').hide();
$('#' + menuId).show();
$('#mobile-' + menuId).show();
$('.mobile-menu').show();
}
return false; // avoid #link
});
$('#btn-backtop').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: 0
}, 500);
});
stickMenu();
/*Stick Menu*/
function stickMenu() {
//Keep track of last scroll
var lastScroll = 0;
$(window).scroll(function() {
//Sets the current scroll position
var st = $(this).scrollTop();
//Determines up-or-down scrolling
if (st > lastScroll) {
//Replace this with your function call for downward-scrolling
if (st > 600 ) {
$('#btn-backtop').addClass('on');
}
}
else {
//Replace this with your function call for upward-scrolling
if (st < 600) {
$('#btn-backtop').removeClass('on');
}
}
//Updates scroll position
lastScroll = st;
});
}
});
// OVERLAYS
(function($) {
var Overlay = {
overlayHandle: function(_trigger, _overlay){
var triggerBttn = _trigger,
overlay = _overlay,
closeBttn = _overlay.find('.overlay-close'),
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
support = { transitions : Modernizr.csstransitions };
function toggleOverlay() {
if( overlay.hasClass('open') ) {
overlay.removeClass( 'open' );
$('body').removeClass('noscroll');
overlay.addClass( 'close' );
var onEndTransitionFn = function( ev ) {
if( support.transitions ) {
if( ev.propertyName !== 'visibility' ) return;
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
overlay.removeClass( 'close' );
};
if( support.transitions ) {
overlay[0].addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
}
else if( !overlay.hasClass( 'close' ) ) {
overlay.addClass( 'open' );
$('body').addClass('noscroll');
}
}
triggerBttn.on( 'click', toggleOverlay );
closeBttn.on( 'click', toggleOverlay );
}
}
/*Video overlay*/
if ($('.overlay.video-overlay').length) {
Overlay.overlayHandle($('#detail-actions--snackbox'), $('.overlay.video-overlay'));
}
if ($('.overlay.rate-overlay').length) {
Overlay.overlayHandle($('#detail-actions--rate'), $('.overlay.rate-overlay'));
}
if ($('.overlay.point-overlay').length) {
Overlay.overlayHandle($('.detail-info--view-point-breakdown a'), $('.overlay.point-overlay'));
}
if ($('.overlay.email-overlay').length) {
Overlay.overlayHandle($('#detail-actions--print'), $('.overlay.email-overlay'));
$('#addRecipient').on('click', function(evt){
if($('#recipient').val() != "")
{
var tag = '<div class="recipient-tag">\
<span class="mail">'+ $('#recipient').val() +'</span>\
<span class="tag-delete">x</span>\
</div>';
$('#recipient-list').val( $('#recipient-list').val() + $('#recipient').val() + ',' );
$('#recipient').val("");
$(evt.currentTarget).parent().append(tag);
}
});
$(document).on('click','.tag-delete', function(evt){
$(evt.currentTarget).parents('.recipient-tag').remove();
var t = $('#recipient-list').val();
t = t.replace($(evt.currentTarget).parents('.recipient-tag').find('.mail').text() + ',',"")
$('#recipient-list').val(t);
})
}
if ($('.overlay.share-overlay').length) {
Overlay.overlayHandle($('#detail-actions--share'), $('.overlay.share-overlay'));
}
})(jQuery);
// SELECT BOX
(function($){
//Select Wrapper
$('.select-wrapper').each(function() {
if ($(this).find('span').length <= 0) {
$(this).prepend('<span>' + $(this).find('select option:selected').text() + '</span>');
}
});
$(document).on('change', '.select-wrapper select', function() {
$(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>');
});
})(jQuery);
//EDIT PHOTO POPUP
(function($){
if(!$('#editPhotoModal').length)
return;
var oldVal = 0;
var cropW;
var setCropW = {
setW: function() {
setTimeout(function(){
if($(window).innerWidth() < 768) {
cropW = $('#editPhotoModal .img-wrapper').width();
}
else {
cropW = 348;
}
$('#editPhotoModal #cropimage').each(function () {
$(this).cropbox({width: cropW, height: cropW*0.66})
});
oldVal = 0;
$( "#editPhotoModal #slider" ).slider( "value", oldVal );
},100);
}
}
$(window).on('resize', function(){
setCropW.setW();
})
setCropW.setW();
$('#editPhotoModal #cropimage').cropbox({
width: cropW,
height: cropW*0.66,
zoom: 10,
maxZoom: 1,
showControls: "never"
})
.on('cropbox', function (e, result) {
//console.log(result);
});
$( "#editPhotoModal #slider").slider({
min: 0,
max: 9,
step: 1,
slide: function(event,ui) {
var crop = $('#editPhotoModal #cropimage').data('cropbox');
if(ui.value > oldVal)
crop.zoomIn();
else
crop.zoomOut();
oldVal = ui.value;
}
});
$('#editPhotoModal .slider-wrapper .zoom-out').on('click', function(evt){
var crop = $('#editPhotoModal #cropimage').data('cropbox');
crop.zoomOut();
if(oldVal>0) {
oldVal--;
$( "#editPhotoModal #slider" ).slider( "value", oldVal );
}
})
$('#editPhotoModal .slider-wrapper .zoom-in').on('click', function(evt){
var crop = $('#editPhotoModal #cropimage').data('cropbox');
crop.zoomIn();
if(oldVal<9) {
oldVal++;
$( "#editPhotoModal #slider" ).slider( "value", oldVal );
}
})
})(jQuery);
//QTIP
(function($){
if(!$('.icon-tip').length)
return;
var tipHelper = {
checkTarget: function(obj) {
if($(window).innerWidth() < 640) {
return $(obj.attr('dock-mobile'));
}
else{
return obj;
}
},
updateArrow: function(obj) {
var $this = obj;
setTimeout(function(){
if($(window).innerWidth() < 640) {
var dockW = tipHelper.checkTarget($this).innerWidth();
var targetPadding = (tipHelper.checkTarget($this).width() - dockW)/2;
var offsetW = Math.abs($this.offset().left + 12.5 - (tipHelper.checkTarget($this).offset().left + targetPadding));
var percen = offsetW / dockW * 100;
$('.qtip-tip').css({
'left': percen + "%",
});
}
else{
$('.qtip-tip').css({
'left': "50%",
});
}
},100);
}
}
$('.icon-tip').each(function(){
var $this = $(this);
var content = $($this.attr('qtip-content'));
var dock = tipHelper.checkTarget($this);
$this.qtip({ // Grab some elements to apply the tooltip to
content: {
text: $(content)
},
position: {
my: 'top center', // Position my top left...
at: 'bottom center', // at the bottom right of...
adjust: {
y: 5
},
target: dock // my target
},
show: "click",
hide: "click",
style: {
classes: 'qtip-light',
width: "95%",
tip: {
width: 12,
height: 10
}
},
events: {
show: function(event, api) {
if($(window).innerWidth() < 640) {
$('.qtip').addClass('onMobile');
}
else
{
$('.qtip').removeClass('onMobile');
}
tipHelper.updateArrow($this);
}
}
});
});
$(window).on('resize scroll', function(){
$('.icon-tip').each(function(){
var $this = $(this);
if($(window).innerWidth() < 640) {
$('.qtip').addClass('onMobile');
$('.icon-tip').qtip('option', 'position.target', tipHelper.checkTarget($this));
}
else
{
$('.qtip').removeClass('onMobile');
$('.icon-tip').qtip('option', 'position.target', tipHelper.checkTarget($this));
}
tipHelper.updateArrow($this);
});
});
})(jQuery);
//WEBTOUR
(function($){
if($('#home-page').length) {
//var tour = new webtour();
//tour.initHomeStep();
//tour.initTour();
}
else
return;
})(jQuery);
//RATING
(function($){
if($('.stars').length && $('.stars').find('label').length)
{
var value;
$('.stars').on('click', function(){
value = $('.stars').find('input:checked').val();
$('.stars').find('span').css({
width: value * 20 + "%"
});
});
}
})(jQuery);
//ISOTOPE
(function($){
if(!$('.listing .listing--list').length)
return;
// init Isotope
var $grid = $('.listing .listing--list').isotope({
layoutMode: 'masonry'
});
// layout Isotope after each image loads
$grid.imagesLoaded().progress( function() {
$grid.isotope('layout');
});
})(jQuery);
//MODAL HANDLE
(function($){
$('.modal-dialog .close-btn, .modal-dialog .cancel-btn, .modal-dialog .no').on('click', function(){
if($('.modal').is(':visible')) {
$('.modal').modal('hide');
}
})
})(jQuery);
| gpl-2.0 |
Pengfei-Gao/source-Insight-3-for-centos7 | SourceInsight3/NetFramework/SimpleHashtable.cs | 406 | public class SimpleHashtable
{
// Constructors
public SimpleHashtable(uint threshold) {}
// Methods
public System.Collections.IDictionaryEnumerator GetEnumerator() {}
public void Remove(object key) {}
public Type GetType() {}
public virtual string ToString() {}
public virtual bool Equals(object obj) {}
public virtual int GetHashCode() {}
// Properties
public object Item { get{} set{} }
}
| gpl-2.0 |
healthcommcore/lung_cancer_site | components/com_jomcomment/languages/latvian.php | 6017 | <?php
DEFINE("_JC_","Guest");
DEFINE("_JC_GUEST_NAME", "viesis");
// Templates
DEFINE("_JC_TPL_ADDCOMMENT", "Komentēt");
DEFINE("_JC_TPL_AUTHOR", "Lietotāja vārds");
DEFINE("_JC_TPL_EMAIL", "e-pasts");
DEFINE("_JC_TPL_WEBSITE", "Web lapa");
DEFINE("_JC_TPL_COMMENT", "Komentārs");
DEFINE("_JC_TPL_TITLE", "Virsraksts");
DEFINE("_JC_TPL_WRITTEN_BY", "autors");
// Warning
DEFINE("_JC_CAPTCHA_MISMATCH", "Kļūdaina parole");
DEFINE("_JC_INVALID_EMAIL", "Kļūdaina e-pasta adrese");
DEFINE("_JC_USERNAME_TAKEN", "Šāds vārds jau ir reģistrēts. Izvēlies citu vārdu.");
DEFINE("_JC_NO_GUEST", "Piekļuves kļūda. Vispirms reģistrējies");
DEFINE("_JC_IP_BLOCKED", "Tava IP adrese ir bloķēta");
DEFINE("_JC_DOMAIN_BLOCKED", "Tavs domēns ir bloķēts");
DEFINE("_JC_MESSAGE_NEED_MOD", "Komentārs pievienots. To vispirms pārbaudīs administrators.");
DEFINE("_JC_MESSAGE_ADDED", "Komentārs pievienots!");
// New in 1.3
DEFINE("_JC_TPL_READMORE", "Lasīt vairāk");
DEFINE("_JC_TPL_COMMENTS", "Komentāri"); // plural
DEFINE("_JC_TPL_SEC_CODE", "Rakstīt attēlotās zīmes"); // plural
DEFINE("_JC_TPL_SUBMIT_COMMENTS", "Pievienot komentāru"); // plural
// New in 1.4
DEFINE("_JC_EMPTY_USERNAME", "Ieraksti savu lietotāja vārdu");
DEFINE("_JC_USERNAME_BLOCKED", "Tavs lietotāja vārds ir bloķēts");
DEFINE("_JC_TPL_WRITE_COMMENT", "Rakstīt komentāru");
DEFINE("_JC_TPL_GUEST_MUST_LOGIN", "Lai pievienotu komentāru, jābūt reģistrētam lietotājam. Ja Tev nav lietotāja konta, lūdzu, reģistrējies.");
DEFINE("_JC_TPL_REPORT_POSTING", "Ziņojums administratoram");
DEFINE("_JC_TPL_NO_COMMENT", "Šim rakstam vēl nav komentāru...");
// New in 1.5
DEFINE("_JC_TPL_HIDESHOW_FORM", "Rādīt/slēpt komentāra formu");
DEFINE("_JC_TPL_HIDESHOW_AREA", "Rādīt/slēpt komentārus");
DEFINE("_JC_TPL_REMEMBER_INFO", "Atcerēties info?");
// New in 1.6
DEFINE("_JC_TPL_TOO_SHORT", "Tavs komentārs ir pārāk īss");
DEFINE("_JC_TPL_TOO_LONG", "Tavs komentārs ir pārāk garš");
DEFINE("_JC_TPL_SUBSCRIBE", "Saņemt e-pasta ziņu par jaunu komentāru");
DEFINE("_JC_TPL_PAGINATE_NEXT", "nākošie komentāri");
DEFINE("_JC_TPL_PAGINATE_PREV", "iepriekšējie komentāri");
// New 1.6.8
DEFINE("_JC_TPL_DUPLICATE", "Atrasts dubults ieraksts");
DEFINE("_JC_TPL_NOSCRIPT", "Lai komentētu, jābūt ieslēgtam JavaScript atbalstam");
// New 1.7
DEFINE("_JC_TPL_INPUT_LOCKED", "Komentāri ir slēgti. Tu vairs nevari pievienot komentārus.");
DEFINE("_JC_TPL_TRACKBACK_URI", "Ieraksta sekošanas URI");
DEFINE("_JC_TPL_COMMENT_RSS_URI", "Parakstīties uz šo komentāru RSS barotni");
// New 1.9
// Do not modify {INTERVAL} as it is from configuration
DEFINE("_JC_TPL_REPOST_WARNING", "Vai Tu mēģini spamot? Lūdzu, ievēro '{INTERVAL}' sekunžu intervālu starp komentāriem.");
DEFINE("_JC_TPL_BIGGER", "lielāks");
DEFINE("_JC_TPL_SMALLER", "mazāks");
DEFINE("_JC_VOTE_VOTED", "Tav balss ir pieņemta");
DEFINE("_JC_NOTIFY_ADMIN", "Ziņojums par komentāru ir aizsūtīta administratoram");
DEFINE("_JC_LOW_VOTE","Zemu vērtētie komentāri");
DEFINE("_JC_SHOW_LOW_VOTE","Rādīt");
DEFINE("_JC_VOTE_UP","Balsot pozitīvi");
DEFINE("_JC_VOTE_DOWN","Balsot negatīvi");
DEFINE("_JC_REPORT","Ziņojums");
DEFINE("_JC_TPL_USERSUBSCRIBE","Parakstīties, izmantojot e-pastu (Tikai reģistrētiem lietotājiem)");
DEFINE("_JC_TPL_BOOKMARK","Grāmatzīme");
DEFINE("_JC_TPL_MARKING_FAVORITE","Iezīmē rakstu kā favorītu..");
DEFINE("_JC_TPL_MAILTHIS","Sūtīt pa e-pastu");
DEFINE("_JC_TPL_FAVORITE","Pievienot favorītiem");
DEFINE("_JC_TPL_ADDED_FAVORITE","Šis raksts ir pievienots favorītu sarakstam.");
DEFINE("_JC_TPL_HITS","Skatīts");
DEFINE("_JC_TPL_WARNING_FAVORITE","Šis raksts jau ir Tavu favorītu sarakstā.");
DEFINE("_JC_TPL_LINK_FAVORITE","Skatīt favorītu ierakstus šeit.");
DEFINE("_JC_TPL_DISPLAY_VOTES","Balsis:");
DEFINE("_JC_TPL_MEMBERS_FAV","Atvaino, tikai reģistrētiem lietotājiem.");
DEFINE("_JC_TPL_AGREE_TERMS","Esmu lasījis un piekrītu");
DEFINE("_JC_TPL_LINK_TERMS","Lietošanas noteikumi.");
DEFINE("_JC_TPL_TERMS_WARNING","Lūdzu, apstiprini, ka piekrīti lietošanas noteikumiem.");
DEFINE("_JC_TPL_REPORTS_DUP","Nav atļauts ziņot par komentāru vairāk par vienu reizi");
DEFINE("_JC_TPL_VOTINGS_DUP","Nav atļauts komentāru vērtēt vairāk par vienu reizi");
DEFINE("_JC_TPL_TB_TITLE","Sekošana");
DEFINE("_JC_TPL_DOWN_VOTE","balsot negatīvi");
DEFINE("_JC_TPL_UP_VOTE","balsot pozitīvi");
DEFINE("_JC_TPL_ABUSE_REPORT","ziņot par ļaunprātību");
DEFINE("_JC_TPL_GOLAST_PAGE","Tu vari pievienot komentāru");
DEFINE("_JC_TPL_GOLINK_LAST","šeit");
// New 2.2
DEFINE("_JC_TPL_UNPUBLISH_ADM", "Unpublish");
DEFINE("_JC_TPL_EDIT_ADM", "Edit");
// New
DEFINE("_JC_TPL_RESTRICTED_AREA", "The comment section is restricted to members only.");
DEFINE("_JC_TPL_PREVIEW_COMMENTS", "Preview");
DEFINE("_JC_TPL_ERROR_PREVIEW", "Please enter a comment.");
DEFINE("_JC_TPL_HEAD_PREVIEW", "Comment Preview");
// New 3.0 (Email this popup)
DEFINE("_JC_TITLE_SHARE", "Share this article with a friend");
DEFINE("_JC_FRIEND_EMAIL", "Friends Email");
DEFINE("_JC_YOUR_NAME", "Your Name");
DEFINE("_JC_YOUR_EMAIL", "Your Email");
DEFINE("_JC_EMAIL_SUBJECT", "Message Subject");
DEFINE("_JC_SEND_BUTTON", "Send");
DEFINE("_JC_RESET_BUTTON", "Reset");
// New 3.0 (Bookmark this popup)
DEFINE("_JC_TITLE_BOOKMARKS", "Share this");
// New 3.0 (Favorites popup)
DEFINE("_JC_TITLE_FAVORITES", "Set As Favorite");
DEFINE("_JC_RECAPTCHA_MISMATCH","Invalid recaptcha password");
DEFINE("_JC_TPL_CLOSEWIN","Close");
DEFINE("_JC_TPL_CBMAILTITLE","A user commented on user");
DEFINE("_JC_TPL_SENT_MAIL","An email has been sent to");
DEFINE("_JC_TPL_TERMS_TITLE","Terms & Conditions");
?> | gpl-2.0 |
arjunthandi76/sandbox | sites/all/themes/evucan/templates/ds/field--ds--field_dir_main_business_category.tpl.php | 5818 | <?php
/**
* This is a copy of cores field.tpl.php modified to support HTML5. The main
* difference to Drupal core is that field labels are treated like headings. In
* the context of HTML5 we need to account for sectioning, so this template, like
* is counterpart adaptivetheme_field() conditionally supplies the top level
* element as either <section> (field label is showing) or <div> (field label
* is hidden). "Hidden labels" is a misnomer and implies they are output and
* hidden via CSS - not so, if a label is hidden it does not print.
*
* Additionally field labels are wrapped in h2 elements to improve the outline.
*
* Useage:
* This file is not used by default by Adaptivetheme which is why this is a text
* file - it is here to serve as an example if you want to override field
* templates using suggestions.
*
* Adaptivetheme overrides theme_field() to achieve the same markup you see
* here because functions are 5 times faster than templates. theme_field() is
* called often in Drupal 7 sites so we want to keep things as fast as possible.
*
* Taxonomy Fields:
* Adaptivetheme outputs taxonomy term fields as unordered lists - it
* does this in adaptivetheme_field__taxonomy_term_reference().
*
* Image Fields:
* Image fields are overridden in adaptivetheme_field__image(), instead of
* the regular div container for images we use <figure> from HTML5.
* The template can print captions also, using the <figcaption> element, again
* from HTML5. You need to enable the "Image" theme settings in "Site Tweaks"
* to enable and configure the captioning features. Captions use the #title
* field for the caption text, so you must have titles enabled on image fields
* for this to work.
*
* Adaptivetheme variables:
* - $field_view_mode: The view mode so we can test for it inside a template.
* - $image_caption_teaser: Boolean value to test for a theme setting.
* - $image_caption_full: Boolean value to test for a theme setting.
* - $is_mobile: Bool, requires the Browscap module to return TRUE for mobile
* devices. Use to test for a mobile context.
*
* Available variables:
* - $items: An array of field values. Use render() to output them.
* - $label: The item label.
* - $label_hidden: Whether the label display is set to 'hidden'.
* - $classes: String of classes that can be used to style contextually through
* CSS. It can be manipulated through the variable $classes_array from
* preprocess functions. The default values can be one or more of the
* following:
* - field: The current template type, i.e., "theming hook".
* - field-name-[field_name]: The current field name. For example, if the
* field name is "field_description" it would result in
* "field-name-field-description".
* - field-type-[field_type]: The current field type. For example, if the
* field type is "text" it would result in "field-type-text".
* - field-label-[label_display]: The current label position. For example, if
* the label position is "above" it would result in "field-label-above".
*
* Other variables:
* - $element['#object']: The entity to which the field is attached.
* - $element['#view_mode']: View mode, e.g. 'full', 'teaser'...
* - $element['#field_name']: The field name.
* - $element['#field_type']: The field type.
* - $element['#field_language']: The field language.
* - $element['#field_translatable']: Whether the field is translatable or not.
* - $element['#label_display']: Position of label display, inline, above, or
* hidden.
* - $field_name_css: The css-compatible field name.
* - $field_type_css: The css-compatible field type.
* - $classes_array: Array of html class attribute values. It is flattened
* into a string within the variable $classes.
*
* @see template_preprocess_field()
* @see theme_field()
* @see adaptivetheme_preprocess_field()
* @see adaptivetheme_field()
* @see adaptivetheme_field__taxonomy_term_reference()
* @see adaptivetheme_field__image()
*/
/* DIRECTORY SPECIFIC CATEGORY FIELD */
?>
<?php foreach ($items as $delta => $item) : ?>
<div class="field-item">
<?php
if (isset ($item['#items'][0]['data'])) {
//dpm($item);
$contentexists= true;
$title = $item['#items'][0]['data'];
$catlink = str_replace(" ", "-", strtolower($title));
$output_str .= l($title, 'directory/posts/'.$catlink) . " | ";
$way1 = true;
}elseif (isset ($item['#lineage'][0])) {
$contentexists = true;
$way1 = false;
// $example = mb_convert_encoding($item['#lineage'][0]['#title'], "utf-8", "HTML-ENTITIES" );
// $title = htmlspecialchars_decode(utf8_encode($example));
$title = $item['#lineage'][0]['#title'];
$title = str_replace("&", "&", $title);
$item['#lineage'][0]['#title']= $title;
if (isset ($item['#lineage'][1])) {
$title = $item['#lineage'][1]['#title'];
$title = str_replace("&", "&", $title);
$item['#lineage'][1]['#title']= $title;
}
if (isset ($item['#lineage'][2])) {
$title = $item['#lineage'][2]['#title'];
$title = str_replace("&", "&", $title);
$item['#lineage'][2]['#title']= $title;
}
}
?>
</div>
<?php endforeach; ?>
<?php
if ($way1 == true) {
if (!$label_hidden && $contentexists) {
$output_str = rtrim($output_str, " | ");
print '<div class="label-above">'. $label . '</div>';
print $output_str;
}
} else {
print render($item);
}
?>
| gpl-2.0 |
Dasfaust/WebMarket | src/main/java/com/survivorserver/Dasfaust/WebMarket/netty/WebSocketServer.java | 2858 | package com.survivorserver.Dasfaust.WebMarket.netty;
import java.util.logging.Logger;
import com.survivorserver.Dasfaust.WebMarket.WebMarket;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
public class WebSocketServer extends Thread {
private Logger log;
private final int port;
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private Channel ch;
private WebMarket web;
public WebSocketServer(int port, Logger log, WebMarket web) {
this.port = port;
this.log = log;
this.web = web;
}
public void run() {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("codec-http", new HttpServerCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
final WebSocketServerHandler handler = new WebSocketServerHandler(web, log);
pipeline.addLast("handler", handler);
ChannelFuture closeFuture = ch.closeFuture();
closeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
WebSocketSession ses = handler.findSession(future.channel());
if (ses != null) {
ses.onDisconnect();
}
}
});
}
});
ChannelFuture future = b.bind(port).sync();
if (!future.isSuccess()) {
log.severe("Couldn't start the server! Is something already running on port " + port + "? Change it and use /webmarket reload");
bossGroup.shutdownGracefully().await();
workerGroup.shutdownGracefully().await();
return;
}
ch = future.channel();
log.info("Server started on port " + port);
ch.closeFuture().sync();
} catch (InterruptedException ignored) {
shutDown();
}
}
public synchronized void shutDown() {
log.info("Stopping server...");
ch.close().syncUninterruptibly();
ch.pipeline().close().syncUninterruptibly();
bossGroup.shutdownGracefully().awaitUninterruptibly();
workerGroup.shutdownGracefully().awaitUninterruptibly();
log.info("Server stopped");
}
}
| gpl-2.0 |
kmoffett/ifupdown-ng | ifupdown_ng/config/tokenizer.py | 3241 | """
ifupdown_ng.config.tokenizer - interfaces(5) config file tokenization
Copyright (C) 2012-2013 Kyle Moffett <kyle@moffetthome.net>
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; otherwise you can obtain it here:
http://www.gnu.org/licenses/gpl-2.0.txt
"""
## Futureproofing boilerplate
from __future__ import absolute_import
from ifupdown_ng import parser
from ifupdown_ng import utils
class InterfacesFile(parser.FileParser):
"""Parse an interfaces(5)-format file into single statements
An iterator which yields individual statements from a file in the
interfaces(5) format given a sequence of lines.
This ignores blank lines and comments and removes backslash-newline
line continuations, then splits the result into first-word and
rest-of-line tokens.
Attributes:
continued_line: Partially accumulated line continuation
"""
def __init__(self, *args, **kwargs):
super(InterfacesFile, self).__init__(*args, **kwargs)
self.continued_line = None
def validate_interface_name(self, ifname):
"""Report an error if an interface name is not valid"""
if utils.valid_interface_name(ifname):
return True
self.error('Invalid interface name: %s' % ifname)
return False
def __iter__(self):
"""Iterate over this object (it is already an iterator)"""
return self
def next(self):
"""Return the next statement as (first_word, rest_of_line)"""
result = None
while result is None:
result = self._handle_one_line()
return result
def _handle_one_line(self):
"""Parse a single line and maybe return a completed statement
Raises:
StopIteration: If the input is exhausted and no more
statements are available for read.
Returns:
A completed statement as (first_word, rest_of_line)
if one is available, otherwise returns None if more
work remains to be done.
"""
if self.lines is None:
raise StopIteration()
try:
try:
line = self._next_line().lstrip().rstrip('\n')
except EnvironmentError as ex:
self.error('Read error: %s' % ex.strerror)
raise StopIteration()
except StopIteration:
if self.autoclose:
self.lines.close()
self.lines = None
if self.continued_line is None:
raise
else:
self.warning("Trailing backslash at EOF")
line = ''
if self.continued_line is not None:
line = self.continued_line + ' ' + line
elif line.startswith('#'):
return None
if line.endswith('\\') and not line.endswith('\\\\'):
self.continued_line = line[0:-1].rstrip()
return None
self.continued_line = None
if '#' in line:
self.warning("Possible inline comment found")
self.warning("Comments must be on separate lines")
## Split on whitespace and return the statement
fields = line.split(None, 1)
if fields:
return (fields[0], fields[1])
| gpl-2.0 |
paeschli/test-kiara | src/KIARA/Core/GCObject.cpp | 1906 | /* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages
*
* Copyright (C) 2012, 2013 German Research Center for Artificial Intelligence (DFKI)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* GCObject.cpp
*
* Created on: 13.08.2012
* Author: Dmitri Rubinstein
*/
#define KIARA_LIB
#include <KIARA/Common/Config.hpp>
#include <KIARA/Core/GCObject.hpp>
#include <KIARA/Core/CycleCollector.hpp>
#include <iostream>
namespace KIARA
{
// RTTI
DFC_DEFINE_ABSTRACT_TYPE(KIARA::GCObject)
GCObject::GCObject(CycleCollector &collector)
: collector_(collector)
, possibleCycleRoot_(false)
{
collector_.onNewObject(this);
}
GCObject::~GCObject()
{
}
void GCObject::destroy()
{
collector_.onDestroyObject(this);
InheritedType::destroy();
}
size_t GCObject::addRef()
{
possibleCycleRoot_ = false;
size_t result = InheritedType::addRef();
collector_.onObjectAddRef(result);
return result;
}
size_t GCObject::release()
{
possibleCycleRoot_ = true;
CycleCollector &collector = collector_;
size_t result = InheritedType::release();
collector.onObjectRelease(result);
return result;
}
} // namespace KIARA
| gpl-2.0 |
ms08-067/niemtinmoi | components/com_aicontactsafe/views/message/view.html.php | 55468 | <?php
/**
* @version $Id$ 2.0.15
* @package Joomla
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
*
* added/fixed in version 2.0.1
* - added new field types Checkbox - List, Radio - List, Date, Emails, Contacts
* - added mark_required_fields character
* - added id attribute on div tags for each rows for a better control with css
* - added the test for captcha activation to profile
* added/fixed in version 2.0.7
* - replaced domready with load
* added/fixed in version 2.0.8
* - added field parameters to the radio buttons labels and date field combo boxes
* - fixed the problem with current_url variable when the form is generated from a plugin
* added/fixed in version 2.0.10.b
* - replaced sufix with prefix as it is the correct order
* - added the posibility to use either fixed or procentual width for the contact form and the contact information ( you can specify it in the profile )
* added/fixed in version 2.0.10.c
* - fixed the problem with the duplication of the div "aiContactSafe_mainbody" when AJAX is used
* added/fixed in version 2.0.12
* - check for the load.gif in the template and use the one delivered with the extension if it is not found
* added/fixed in version 2.0.13
* - added SqueezeBox for aiContactSafe feed-back
* - added highlighting for fields with errors
* - placed the CAPTCHA generated by Multiple CAPTCHA Engine plugin in a div with the same ID as the aiContactSafe native CAPTCHA
* - added the possibility to keep the session alive while the form is displayed
* added/fixed in version 2.0.14
* - filter variables read with JRequest::getVar
* - follow the errors based on the profile
* added/fixed in version 2.0.15
* - fixed the problem with generating error messages when the error highlighting is disabled
* - fixed the problem with errors displayed when aiContactSafeLink was used
* - fixed the problem with errors displayed when aiContactSafeForm was used
* - fixed the problem with loading SqueezeBox for module and plugins
*
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
// define the control_panel view class of aiContactSafe
class AiContactSafeViewMessage extends AiContactSafeViewDefault {
// fields to display into the contact form
var $fields = null;
// the contact form
var $contact_form = null;
// the contact informations
var $contactinformations = array();
// the profile informations
var $profile = null;
// the url to return the form on success
var $return_to = null;
// the current url ( sent from the plugin if the form is used like that )
var $current_url = null;
// activate or deactivate the back button
var $back_button = null;
// display only the contact form ( for AJAX ) without buttons and captcha
var $returnAjaxForm = false;
// id of the requested variables registered in the session
var $r_id = null;
// check if there are any requested fields to display
var $requested_fields = 0;
// lang variable to use
var $lang = null;
// function to define the toolbar depending on the section
function setToolbar() {
// no toolbar here
}
// function to initialize the variables used in the template
function setVariables() {
if (!$this->returnAjaxForm) {
// load the mootools javascript library
JHTML::_('behavior.mootools');
}
$doc = JFactory::getDocument();
$new_JFilterInput = new JFilterInput();
$jfcookie = JRequest::getVar('jfcookie', null ,"COOKIE");
$lang = '';
if (isset($jfcookie["lang"]) && $jfcookie["lang"] != "") {
$lang = $new_JFilterInput->clean($jfcookie["lang"], 'cmd');
}
if (strlen($lang) == 0) {
$lang = $this->_app->getUserState('application.lang', 'en');
$lang = substr($lang,0,2);
}
$this->lang = JRequest::getCmd('lang', $lang);
$pf = 0;
$this->return_to = '';
$this->r_id = JRequest::getInt( 'r_id', mt_rand() );
$model = $this->getModel();
$uri = JURI::getInstance();
$test_return_to = $uri->toString( array('scheme', 'host', 'port', 'path', 'query', 'fragment'));
$this->current_url = $uri->toString( array('scheme', 'host', 'port', 'path', 'query', 'fragment'));
// get the Itemid variable
$menuItemid = JRequest::getInt( 'Itemid' );
// get the menu variable
$new_JSite = new JSite();
$menu = $new_JSite->getMenu();
// read the parameters of the menu
$menuparams = $menu->getParams( $menuItemid );
// read the joomla version
$version = new JVersion;
$this->joomla = $version->getShortVersion();
if(version_compare(JVERSION, '1.6.0', 'ge')) {
$this->page_title = $menuparams->get( 'page_heading' );
if(strlen($this->page_title) == 0) {
$this->page_title = $menuparams->get( 'page_title' );
}
if(strlen($this->page_title) == 0) {
$this->page_title = $doc->getTitle();
}
$this->show_page_title = $menuparams->get( 'show_page_heading' );
$this->pageclass_sfx = $menuparams->get( 'pageclass_sfx' );
$sitename_pagetitles = $this->_app->getCfg('sitename_pagetitles');
switch($sitename_pagetitles) {
case 2:
$doc->setTitle($this->page_title.' - '.$this->_app->getCfg('sitename'));
break;
case 1:
$doc->setTitle($this->_app->getCfg('sitename').' - '.$this->page_title);
break;
}
} else {
$this->page_title = $menuparams->get( 'page_title' );
$this->show_page_title = $menuparams->get( 'show_page_title' );
$this->pageclass_sfx = $menuparams->get( 'pageclass_sfx' );
}
//read the post data
$postData = $model->readPostDataFromSession();
if(is_array($postData) && array_key_exists('from_module',$postData)) {
$from_module = (int)$postData['from_module'];
} else {
$from_module = 0;
}
if($from_module == 1) {
$this->page_title = '';
$this->show_page_title = 0;
$this->pageclass_sfx = '';
}
// initialize the variable that will allow the use of the profile redirect on success
$use_profile_redirect_on_success = false;
// if the last send process ended up with an error
if ($this->_app->_session->get( 'isOK:' . $this->_sTask ) === false) {
if (is_array($postData)) {
$pf = (int)$postData['pf'];
$this->return_to = str_replace('&','&',$postData['return_to']);
$this->current_url = str_replace('&','&',(array_key_exists('current_url',$postData)?$postData['current_url']:$this->current_url));
$this->back_button = array_key_exists('back_button',$postData)?$postData['back_button']:0;
$this->lang = array_key_exists('lang',$postData)?$postData['lang']:$this->lang;
}
}
if ($pf == 0) {
// if there is a menulink get the parameters from it
if ($menuItemid) {
$pf = $menuparams->get( 'pf' );
$this->return_to = $menuparams->get( 'redirect_on_success' );
$test_return_to = $menuparams->get( 'redirect_on_success' );
}
// if no profile is specified check for one specified in request
if ($pf == 0) {
$pf = JRequest::getVar('pf', 0, 'request', 'int');
}
// if no return link is defined check for one in the request variables
if ( $this->return_to == '' ) {
$this->return_to = $new_JFilterInput->clean(str_replace('&','&',JRequest::getVar('return_to', '', 'request', 'string')), 'path');
}
// if no return link is found generate one and record if the one in the profile can be used
if ( $this->return_to == '' ) {
$this->return_to = $test_return_to;
$use_profile_redirect_on_success = true;
}
// check if the back button will be used
if ($this->return_to != '' && $this->return_to != $test_return_to) {
$this->back_button = 1;
} else {
$this->back_button = 0;
}
}
$this->profile = $model->getProfile($pf);
if ($use_profile_redirect_on_success && strlen(trim($this->profile->redirect_on_success)) > 0) {
$this->return_to = $this->profile->redirect_on_success;
}
$this->fields = $model->readFields( $this->profile );
$this->fields = $this->generateHtmlFields( $this->fields );
$this->contactinformations['contact_info'] = '';
$this->contactinformations = $model->readContactInformations( $pf, $this->r_id );
$this->contactinformations['required_field_notification'] = str_replace('%mark%', $this->profile->required_field_mark,$this->contactinformations['required_field_notification']);
// check if the contact information width and contact form width specified in the profile have "px" or "%" at the end and add "px" if it is not specified
if (substr($this->profile->contact_form_width,-2) != 'px' && substr($this->profile->contact_form_width,-1) != '%') {
$this->profile->contact_form_width .= 'px';
}
if (substr($this->profile->contact_info_width,-2) != 'px' && substr($this->profile->contact_info_width,-1) != '%') {
$this->profile->contact_info_width .= 'px';
}
// if the form is not called after a submit with ajax run all the content plugin on contact information
if ( !$this->returnAjaxForm && $this->profile->plg_contact_info ) {
$this->contactinformations['contact_info'] = JHTML::_('content.prepare',$this->contactinformations['contact_info']);
}
if ( array_key_exists('meta_description',$this->contactinformations) && strlen($this->contactinformations['meta_description']) > 0 ) {
$doc->setMetaData( 'description', $this->contactinformations['meta_description'] );
}
if ( array_key_exists('meta_keywords',$this->contactinformations) && strlen($this->contactinformations['meta_keywords']) > 0 ) {
$doc->setMetaData( 'keywords', $this->contactinformations['meta_keywords'] );
}
if ( array_key_exists('meta_robots',$this->contactinformations) && strlen($this->contactinformations['meta_robots']) > 0 ) {
$doc->setMetaData( 'robots', $this->contactinformations['meta_robots'] );
}
if (!$this->returnAjaxForm) {
$db = JFactory::getDBO();
$query = 'SELECT config_value FROM `#__aicontactsafe_config` WHERE `config_key` = \'use_SqueezeBox\'';
$db->setQuery( $query );
$use_SqueezeBox = (int)$db->loadResult();
// load the javascript juctions
require_once( JPATH_ROOT.DS.'components'.DS.'com_aicontactsafe'.DS.'includes'.DS.'js'.DS.'aicontactsafe.js.php' );
$use_ajax = JRequest::getVar( 'use_ajax', $this->profile->use_ajax, 'request', 'int');
$script = "
//<![CDATA[
<!--
window.addEvent('load', function() {
changeCaptcha(".$this->profile->id.",0);\n".($use_ajax?"resetSubmit(".$this->profile->id.");\n":"")."
if(".$use_SqueezeBox." == 1 && typeof SqueezeBox != 'undefined' && $('system-message')) {
SqueezeBox.initialize();
SqueezeBox.open($('system-message'), {
handler: 'adopt',
size: {x: $('system-message').offsetWidth+30, y: $('system-message').offsetHeight+30}
});
}
});
//-->
//]]>
";
$document = JFactory::getDocument();
$document->addScriptDeclaration($script);
if ( $this->_config_values['keep_session_alive'] ) {
echo JHTML::_('behavior.keepalive');
}
}
}
// function to display the default template
function viewDefault( $returnAjaxForm = false ) {
// initialize $returnAjaxForm
$this->returnAjaxForm = $returnAjaxForm;
$use_ajax = JRequest::getVar( 'use_ajax', 0, 'request', 'int');
if($use_ajax) {
$this->returnAjaxForm = true;
}
// add javascript
$document = JFactory::getDocument();
if(version_compare(JVERSION, '1.6.0', 'ge')) {
$document->addScript( JURI::root(true).'/media/system/js/core.js');
} else {
$document->addScript(JURI::root(true).'/includes/js/joomla.javascript.js');
}
// initialize the template variables
$this->setVariables();
// generate the css file name based on the profile
$css_file = 'profile_css_'.$this->profile->id.'.css';
// call the css file
$this->callCssFile($css_file);
// determine to what section to return to
$this->setTaskReturn();
if ($returnAjaxForm) {
parent::display();
} else {
echo '<div class="aiContactSafe" id="aiContactSafe_mainbody_'.$this->profile->id.'">';
parent::display();
echo '</div>';
}
// reset the form fields after the form was displayed
$model = $this->getModel( $this->_sTask, '', $this->_parameters );
$model->resetFormFields();
if($use_ajax) {
jexit();
}
}
// function to generate the header of the template to display
function getTmplHeader() {
$header = '<form action="'.JURI::root().'index.php?option=com_aicontactsafe" method="post" id="adminForm_'.$this->profile->id.'" name="adminForm_'.$this->profile->id.'" enctype="multipart/form-data">';
return $header;
}
// function to generate the footer of the template to display
function getTmplFooter() {
$footer = '';
$footer .= '<input type="hidden" id="option" name="option" value="com_aicontactsafe" />';
$footer .= '<input type="hidden" id="sTask" name="sTask" value="' . $this->escape($this->_sTask) . '" />';
$footer .= '<input type="hidden" id="task" name="task" value="' . $this->escape($this->_task) . '" />';
$footer .= '<input type="hidden" id="send_mail" name="send_mail" value="1" />';
$footer .= '<input type="hidden" id="pf" name="pf" value="'.(int)$this->profile->id.'" />';
$return_to = $this->return_to;
if ( strpos($return_to, '&') === false && strpos($return_to, '&') !== false ) {
$return_to = str_replace('&','&',$return_to);
}
$footer .= '<input type="hidden" id="return_to" name="return_to" value="'.$this->escape($return_to).'" />';
$uri = JURI::getInstance();
$current_url = $this->current_url;
if ( strpos($current_url, '&') === false && strpos($current_url, '&') !== false ) {
$current_url = str_replace('&','&',$current_url);
}
$current_url = str_replace('"','"',$current_url);
$footer .= '<input type="hidden" id="current_url" name="current_url" value="'.$this->escape($current_url).'" />';
$Itemid = JRequest::getInt( 'Itemid' );
if($Itemid > 0) {
$footer .= '<input type="hidden" id="Itemid" name="Itemid" value="'.(int)$Itemid.'" />';
}
$footer .= '<input type="hidden" id="lang" name="lang" value="'.$this->escape($this->lang).'" />';
$footer .= '<input type="hidden" id="back_button" name="back_button" value="'.$this->escape($this->back_button).'" />';
$footer .= '<input type="hidden" id="boxchecked" name="boxchecked" value="0" />';
$use_ajax = JRequest::getVar( 'use_ajax', $this->profile->use_ajax, 'request', 'int');
if($use_ajax == 0) {
$use_ajax = JRequest::getVar( 'next_use_ajax', $this->profile->use_ajax, 'request', 'int');
}
$footer .= '<input type="hidden" id="use_ajax" name="use_ajax" value="'.(int)$use_ajax.'" />';
$footer .= '<input type="hidden" id="r_id" name="r_id" value="'.(int)$this->r_id.'" />';
$footer .= JHTML::_( 'form.token' );
$footer .= '</form>';
// display the version of aiContactSafe
$veraicontactsafe = JRequest::getVar('veraicontactsafe', 0, 'request', 'int');
if ($veraicontactsafe) {
$footer .= '<br clear="all" /><div id="veraicontactsafe">aiContactSafe version : '.$this->_version.'</div><br clear="all" />';
}
return $footer;
}
// function to generate the html tags for each field type
function generateHtmlFields( $fields = null ) {
// initialize the model
$model = $this->getModel();
// check if the fields were read from the database
if(!$fields) {
$fields = $this->fields;
}
if(!$fields) {
$this->fields = $model->readFields( $this->profile );
$fields = $this->fields;
}
// if the values are sent from aiContactSafeLink deactivate highlight_errors
$dt = JRequest::getVar('dt', 0, 'post', 'int');
// initialize the fields with error array
$fieldsWithErrors = array();
// get the information entered into the contact form if an error has occured, or generate the default values to use on the form
$postData = null;
if ($this->_app->_session->get( 'isOK:' . $this->_sTask ) === false) {
$postData = $model->readPostDataFromSession();
if ($dt== 0 && $this->_config_values['highlight_errors']) {
$r_id = JRequest::getInt( 'r_id' );
$fieldsWithErrors = $this->_app->_session->get( 'fieldsWithErrors:' . $this->_sTask . '_' . $this->profile->id . '_' . $r_id );
}
} else {
// check if any parameters were recorded into the session
$postData = $model->readParametersDataFromSession( $this->r_id );
if (!is_array($postData)) {
$postData = null;
}
}
// initialize the db for contacts only once
$contacts_db_not_initialized = true;
// get user informations
if ($this->_user_id > 0) {
$user = JFactory::getUser();
$joomla_user_name = $user->get('name');
$joomla_user_email = $user->get('email');
}
// import joomla clases to manage file system
jimport('joomla.filesystem.file');
// generate the path to the load.gif image
$template_name = $this->_app->getTemplate();
$tPath = JPATH_ROOT.DS.'templates'.DS.$template_name.DS.'html'.DS.'com_aicontactsafe'.DS.'message'.DS.'load.gif';
if (JFile::exists($tPath)) {
$loadImage = JURI::root().'templates/'.$template_name.'/html/com_aicontactsafe/message/load.gif';
} else {
$loadImage = JURI::root().'components/com_aicontactsafe/includes/images/load.gif';
}
// reset the variable to check if there is any required field
$this->requested_fields = 0;
// initialize the form
foreach($fields as $field_key=>$field) {
$field->html_tag = '';
$field->field_label = $this->revert_specialchars($field->field_label);
$field->label_parameters = $this->revert_specialchars($field->label_parameters);
$field->field_parameters = $this->revert_specialchars($field->field_parameters);
// check if the field is required and modify the varible $this->requested_fields
if ($field->field_required) {
$this->requested_fields = 1;
}
$postData_field_value = null;
if ( $field->field_type == 'UQ' && $model->useUqField() ) {
// $postData_field_value = trim(uniqid(trim($field->default_value), true));
$postData_field_value = $this->random_string(6);
}
if ($this->_user_id > 0 && strlen(trim($field->auto_fill)) > 0) {
switch($field->auto_fill) {
case 'UN' :
$postData_field_value = $joomla_user_name;
break;
case 'UE' :
$postData_field_value = $joomla_user_email;
break;
}
}
if ( $field->field_type == 'HD' && strlen(trim($field->field_values)) > 0 ) {
$postData_field_value = trim($field->field_values);
}
if (is_null($postData_field_value)) {
$postData_field_value = $field->default_value;
}
if (is_array($postData) && array_key_exists($field->name, $postData)) {
$postData_field_value = $postData[$field->name];
if (is_array($postData_field_value)) {
$postData_field_value = implode(';',$postData_field_value);
}
}
$postData_field_value = $model->replace_specialchars($postData_field_value);
switch($field->field_type) {
case 'TX' :
// Textbox
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$maxlength = '';
if (substr_count(strtolower($field->field_parameters), 'maxlength') == 0 && $field->field_limit > 0) {
$maxlength = 'maxlength="'.$field->field_limit.'"';
}
$field->html_tag = '<input type="text" name="' . $field->name . '" id="' . $field->name . '" ' . $maxlength . ' ' . $field->field_parameters . ' value="' . $postData_field_value . '" />';
break;
case 'CK' :
// Checkbox
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$field->html_tag = '<input type="checkbox" name="' . $field->name . '" id="' . $field->name . '" ' . $field->field_parameters . ' ' . ($postData_field_value?'checked="checked"':'') . ' />';
break;
case 'CB' :
// Combobox
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$field_values = explode(';',$model->revert_specialchars($field->field_values));
// generate the array with the combovalues
$select_combo = array();
if (!is_numeric($field->default_value) && strlen(trim($field->default_value)) > 0) {
$txtSelect = new stdClass;
$txtSelect->name = trim($field->default_value);
$txtSelect->id = -1;
$select_combo[] = $txtSelect;
}
foreach($field_values as $id => $combo_value) {
$txtSelect = new stdClass;
$txtSelect->name = $combo_value;
$txtSelect->id = $id;
$select_combo[] = $txtSelect;
}
// generate the html tag
$field->html_tag = JHTML::_('select.genericlist', $select_combo, $field->name, $field->field_parameters, 'id', 'name', $postData_field_value, false, false);
break;
case 'ED' :
// Editbox
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$cols = '';
if (substr_count(strtolower($field->field_parameters), 'cols') == 0 && $this->_config_values['editbox_cols'] > 0) {
$cols = 'cols="'.$this->_config_values['editbox_cols'].'"';
}
$rows = '';
if (substr_count(strtolower($field->field_parameters), 'rows') == 0 && $this->_config_values['editbox_rows'] > 0) {
$rows = 'rows="'.$this->_config_values['editbox_rows'].'"';
}
if ($field->field_limit > 0) {
$field->html_tag = '<textarea name="' . $field->name . '" id="' . $field->name . '" ' . $cols . ' ' . $rows . ' ' . $field->field_parameters . ' onkeydown="checkEditboxLimit('.$this->profile->id.',\''.$field->name.'\', '.$field->field_limit.')" onkeyup="checkEditboxLimit('.$this->profile->id.',\''.$field->name.'\','.$field->field_limit.')" onchange="checkEditboxLimit('.$this->profile->id.',\''.$field->name.'\','.$field->field_limit.')">' . $model->revert_specialchars($postData_field_value) . '</textarea>';
$field->html_tag .= '<br />';
$field->html_tag .= '<div class="countdown_div">' . JText::_('COM_AICONTACTSAFE_YOU_HAVE') . '<input type="text" readonly="readonly" class="countdown_editbox" name="countdown_'.$field->name.'" id="countdown_'.$field->name.'" size="'.strlen($field->field_limit).'" value="'.$field->field_limit.'" />' . JText::_('COM_AICONTACTSAFE_CHARACTERS_LEFT') . '.</div>';
} else {
$field->html_tag = '<textarea name="' . $field->name . '" id="' . $field->name . '" ' . $cols . ' ' . $rows . ' ' . $field->field_parameters . '>' . $model->revert_specialchars($postData_field_value) . '</textarea>';
}
break;
case 'CL' :
// Checkbox - List
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</span>';
$field_values = explode(';',$model->revert_specialchars($field->field_values));
$count_values = count($field_values);
if ((int)strpos($postData_field_value, ';') > 0) {
$postData_field_value = explode(';',$model->revert_specialchars($postData_field_value));
}
for($i=0;$i<$count_values;$i++) {
if (is_array($postData_field_value)) {
$postDataValue = $this->escape($postData_field_value[$i]);
} else {
$postDataValue = 0;
}
$field->html_tag .= '<div id="div_' . $field->name . $i . '" class="' . $field->name . '" ' . $field->field_parameters . '>';
$field->html_tag .= '<input type="checkbox" id="' . $field->name . '_chk_' . $i . '" class="' . $field->name . '" onchange="clickCheckBox('.$this->profile->id.',\'' . $field->name . $i . '\',this.checked)" ' . $field->field_parameters . ' ' . ($postDataValue?'checked="checked"':'') . ' />';
$field->html_tag .= '<input type="hidden" value="' . $postDataValue . '" id="' . $field->name . $i . '" name="' . $field->name . '[]" /> <label for="' . $field->name . '_chk_' . $i . '">' . $field_values[$i] . '</label></div>';
}
break;
case 'RL' :
// Radio - List
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</span>';
$field_values = explode(';',$model->revert_specialchars($field->field_values));
$count_values = count($field_values);
for($i=0;$i<$count_values;$i++) {
$field->html_tag .= '<div id="div_' . $field->name . $i . '" class="' . $field->name . '" ' . $field->field_parameters . '><input type="radio" id="' . $field->name . $i . '" class="' . $field->name . '" name="' . $field->name . '" value="' . $field_values[$i] . '" '.($postData_field_value == $field_values[$i]?'checked="checked"':'').' ' . $field->field_parameters . ' /><label for="' . $field->name . $i . '" ' . $field->field_parameters . ' > ' . $field_values[$i] . '</label></div>';
}
break;
case 'DT' :
// Date
// modify the field name to use the profile id so the same date field can be used more then once o a web page
$date_field_name = $field->name . '_' . $this->profile->id;
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $date_field_name . '" ' . $field->label_parameters . '><label for="' . $date_field_name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
if ($postData_field_value) {
$postDataValue = $postData_field_value;
} else {
$postDataValue = date('Y-m-d');
}
$year = substr($postDataValue,0,4);
$month = substr($postDataValue,5,2);
$day = substr($postDataValue,8,2);
// generate the day combo
$select_day = '<select name="day_' . $date_field_name . '" id="day_' . $date_field_name . '" onchange="checkDate('.$this->profile->id.',\'' . $date_field_name . '\')" >';
for($i = 1; $i<=31; $i++) {
$select_day .= '<option value="' . str_pad($i, 2, "0", STR_PAD_LEFT) . '" ' . (( str_pad($i, 2, "0", STR_PAD_LEFT) == $day )?'selected="selected"':'') . ' ' . $field->field_parameters . ' >' . str_pad($i, 2, "0", STR_PAD_LEFT) . '</option>';
}
$select_day .= '</select>';
// generate the month combo
$select_month = '<select name="month_' . $date_field_name . '" id="month_' . $date_field_name . '" onchange="checkDate('.$this->profile->id.',\'' . $date_field_name . '\')" >';
for($i = 1; $i<=12; $i++) {
$select_month .= '<option value="' . str_pad($i, 2, "0", STR_PAD_LEFT) . '" ' . (( str_pad($i, 2, "0", STR_PAD_LEFT) == $month )?'selected="selected"':'') . ' ' . $field->field_parameters . ' >' . $model->getMonth($i) . '</option>';
}
$select_month .= '</select>';
// generate the year combo
$select_year = '<select name="year_' . $date_field_name . '" id="year_' . $date_field_name . '" onchange="checkDate('.$this->profile->id.',\'' . $date_field_name . '\')" >';
$year_min = (int)$year - $this->profile->custom_date_years_back;
$year_max = (int)$year + $this->profile->custom_date_years_forward;
for($i = $year_min; $i<=$year_max; $i++) {
$select_year .= '<option value="' . str_pad($i, 4, "0", STR_PAD_LEFT) . '" ' . (( str_pad($i, 4, "0", STR_PAD_LEFT) == $year )?'selected="selected"':'') . ' ' . $field->field_parameters . ' >' . str_pad($i, 4, "0", STR_PAD_LEFT) . '</option>';
}
$select_year .= '</select>';
$field->html_tag .= '<div id="div_' . $date_field_name . '" class="' . $date_field_name . '" ' . $field->field_parameters . '><table id="table_' . $date_field_name . '" class="aiContactSafe_date" border="0" cellpadding="0" cellspacing="0"><tr>';
switch( $this->profile->custom_date_format ) {
case 'mdy':
$field->html_tag .= '<td>'. $select_month .'</td><td>'. $select_day .'</td><td>'. $select_year .'</td>';
break;
case 'ymd':
$field->html_tag .= '<td>'. $select_year .'</td><td>'. $select_month .'</td><td>'. $select_day .'</td>';
break;
case 'dmy':
default :
$field->html_tag .= '<td>'. $select_day .'</td><td>'. $select_month .'</td><td>'. $select_year .'</td>';
break;
}
$field->html_tag .= '<td>'. JHTML::_('calendar', $postDataValue, $date_field_name, $date_field_name, '%Y-%m-%d', array('class'=>'aiContactSafe_dateinputbox', 'size'=>'1', 'onchange'=>'setDate('.$this->profile->id.',this.value,\'' . $date_field_name . '\')', 'style'=>'display:none;')) .'</td>';
$field->html_tag .= '</tr></table></div>';
break;
//
case 'EM' :
// Email
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$maxlength = '';
if (substr_count(strtolower($field->field_parameters), 'maxlength') == 0 && $field->field_limit > 0) {
$maxlength = 'maxlength="'.$field->field_limit.'"';
}
$field->html_tag = '<input type="text" name="' . $field->name . '" id="' . $field->name . '" ' . $maxlength . ' ' . $field->field_parameters . ' value="' . $postData_field_value . '" />';
break;
case 'EL' :
// Email - List
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$field_values = explode(';',$model->revert_specialchars($field->field_values));
// generate the array with the combovalues
$select_combo = array();
foreach($field_values as $id => $combo_value) {
if (strlen($combo_value) > 0) {
$combo_value = substr($combo_value, 0, strpos($combo_value,':'));
$txtSelect = new stdClass;
$txtSelect->name = $combo_value;
$txtSelect->id = $id;
$select_combo[] = $txtSelect;
}
}
// generate the html tag
if (count($select_combo) == 0) {
$field->html_tag = '<font color="red">' . JText::_('COM_AICONTACTSAFE_NO_DATA_AVAILABLE') . '</font>';
} else {
if (!is_numeric($field->default_value) && strlen(trim($field->default_value)) > 0) {
$txtSelect = new stdClass;
$txtSelect->name = trim($field->default_value);
$txtSelect->id = -1;
array_unshift($select_combo, $txtSelect);
}
$field->html_tag = JHTML::_('select.genericlist', $select_combo, $field->name, $field->field_parameters, 'id', 'name', $postData_field_value, false, false);
}
break;
case 'JC' :
// Joomla Contacts
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
if ($contacts_db_not_initialized) {
// initialize different variables
$db = JFactory::getDBO();
$contacts_db_not_initialized = false;
}
$user = JFactory::getUser();
if(version_compare(JVERSION, '1.6.0', 'ge')) {
$groups = implode(',', $user->getAuthorisedViewLevels());
$query = 'SELECT name, id FROM #__contact_details WHERE published = 1 AND access IN ('.$groups.') ORDER BY ordering';
} else {
$aid = $user->get('aid', 0);
$query = 'SELECT name, id FROM #__contact_details WHERE published = 1 AND access <= ' . (int) $aid . ' ORDER BY ordering';
}
$db->setQuery($query);
$select_contacts = $db->loadObjectList();
// generate the html tag
if (count($select_contacts) == 0) {
$field->html_tag = '<font color="red">' . JText::_('COM_AICONTACTSAFE_NO_DATA_AVAILABLE') . '</font>';
} else {
if (!is_numeric($field->default_value) && strlen(trim($field->default_value)) > 0) {
$txtSelect = new stdClass;
$txtSelect->name = trim($field->default_value);
$txtSelect->id = 0;
array_unshift($select_contacts, $txtSelect);
}
$field->html_tag = JHTML::_('select.genericlist', $select_contacts, $field->name, $field->field_parameters, 'id', 'name', $postData_field_value, false, false);
}
break;
case 'JU' :
// Joomla Users
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
if ($contacts_db_not_initialized) {
// initialize different variables
$db = JFactory::getDBO();
$contacts_db_not_initialized = false;
}
$query = 'SELECT name, id FROM #__users WHERE block = 0 ORDER BY name';
$db->setQuery($query);
$select_users = $db->loadObjectList();
// generate the html tag
if (count($select_users) == 0) {
$field->html_tag = '<font color="red">' . JText::_('COM_AICONTACTSAFE_NO_DATA_AVAILABLE') . '</font>';
} else {
if (!is_numeric($field->default_value) && strlen(trim($field->default_value)) > 0) {
$txtSelect = new stdClass;
$txtSelect->name = trim($field->default_value);
$txtSelect->id = 0;
array_unshift($select_users, $txtSelect);
}
$field->html_tag = JHTML::_('select.genericlist', $select_users, $field->name, $field->field_parameters, 'id', 'name', $postData_field_value, false, false);
}
break;
case 'SB' :
// SOBI2 Entries
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
if ($contacts_db_not_initialized) {
// initialize different variables
$db = JFactory::getDBO();
$contacts_db_not_initialized = false;
}
$query = 'SELECT title, itemid FROM #__sobi2_item WHERE published = 1 AND approved = 1 ORDER BY title';
$db->setQuery($query);
$select_sobi = $db->loadObjectList();
// generate the html tag
if (count($select_sobi) == 0) {
$field->html_tag = '<font color="red">' . JText::_('COM_AICONTACTSAFE_NO_DATA_AVAILABLE') . '</font>';
} else {
if (!is_numeric($field->default_value) && strlen(trim($field->default_value)) > 0) {
$txtSelect = new stdClass;
$txtSelect->title = trim($field->default_value);
$txtSelect->itemid = 0;
array_unshift($select_sobi, $txtSelect);
}
$field->html_tag = JHTML::_('select.genericlist', $select_sobi, $field->name, $field->field_parameters, 'itemid', 'title', $postData_field_value, false, false);
}
break;
case 'HD' :
// Hidden
if ( strlen(trim($field->field_label)) > 0 ) {
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</span>';
} else {
$field->html_label = null;
}
$field->html_tag = '<input type="hidden" name="' . $field->name . '" id="' . $field->name . '" ' . $field->field_parameters . ' value="' . $postData_field_value . '" />';
break;
case 'SP' :
// Separator
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</span>';
$field->html_tag = '<div id="sp_' . $field->name . '" ' . $field->field_parameters . '>' . (is_null($postData_field_value)?'':$postData_field_value) . '<input type="hidden" name="' . $field->name . '" id="' . $field->name . '" value="' . $postData_field_value . '" /></div>';
break;
case 'FL' :
// File
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$field->html_tag = '';
if ( is_array($postData) ) {
if ( array_key_exists($field->name.'_attachment_id', $postData) && strlen($postData[$field->name.'_attachment_id']) > 0 ) {
$field->html_tag .= '<div id="upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:none"><input type="file" name="' . $field->name . '" id="' . $field->name . '" ' . ' onchange="startUploadFile(\''.$field->name.'\','.$this->profile->id.')" /></div>';
$field->html_tag .= '<div id="cancel_upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:inline">';
$field->html_tag .= '<input type="text" name="' . $field->name . '_attachment_name" id="' . $field->name . '_attachment_name" ' . $field->field_parameters . ' value="' . (array_key_exists($field->name.'_attachment_name',$postData)?$postData[$field->name.'_attachment_name']:'') . '" readonly="readonly" />';
$field->html_tag .= '<input type="button" name="' . $field->name . '_attachment_cancel" id="' . $field->name . '_attachment_cancel" value="' . JText::_('COM_AICONTACTSAFE_CANCEL') . '" onclick="cancelUploadFile(\''.$field->name.'\', '.$this->profile->id.');" />';
$field->html_tag .= '</div>';
} else {
$field->html_tag .= '<div id="upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:inline"><input type="file" name="' . $field->name . '" id="' . $field->name . '" ' . ' onchange="startUploadFile(\''.$field->name.'\','.$this->profile->id.')" /></div>';
$field->html_tag .= '<div id="cancel_upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:none">';
$field->html_tag .= '<input type="text" name="' . $field->name . '_attachment_name" id="' . $field->name . '_attachment_name" ' . $field->field_parameters . ' value="' . (array_key_exists($field->name.'_attachment_name',$postData)?$postData[$field->name.'_attachment_name']:'') . '" readonly="readonly" />';
$field->html_tag .= '<input type="button" name="' . $field->name . '_attachment_cancel" id="' . $field->name . '_attachment_cancel" value="' . JText::_('COM_AICONTACTSAFE_CANCEL') . '" onclick="cancelUploadFile(\''.$field->name.'\', '.$this->profile->id.');" />';
$field->html_tag .= '</div>';
}
} else {
$field->html_tag .= '<div id="upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:inline"><input type="file" name="' . $field->name . '" id="' . $field->name . '" ' . ' onchange="startUploadFile(\''.$field->name.'\','.$this->profile->id.')" /></div>';
$field->html_tag .= '<div id="cancel_upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:none">';
$field->html_tag .= '<input type="text" name="' . $field->name . '_attachment_name" id="' . $field->name . '_attachment_name" ' . $field->field_parameters . ' value="" readonly="readonly" />';
$field->html_tag .= '<input type="button" name="' . $field->name . '_attachment_cancel" id="' . $field->name . '_attachment_cancel" value="' . JText::_('COM_AICONTACTSAFE_CANCEL') . '" onclick="cancelUploadFile(\''.$field->name.'\', '.$this->profile->id.');" />';
$field->html_tag .= '</div>';
}
$field->html_tag .= '<input type="hidden" name="' . $field->name . '_attachment_id" id="' . $field->name . '_attachment_id" value="' . ((is_array($postData) && array_key_exists($field->name.'_attachment_id',$postData))?$postData[$field->name.'_attachment_id']:'') . '" />';
$field->html_tag .= '<div id="wait_upload_'.$this->profile->id.'_file_'.$field->name.'" style="display:none" ><img id="imgLoading_' . $field->name . '" border="0" src="'.$loadImage.'" /> '.JText::_('COM_AICONTACTSAFE_PLEASE_WAIT').'</div>';
$field->html_tag .= '<iframe id="iframe_upload_file_' . $this->profile->id.'_file_'.$field->name.'" name="iframe_upload_file_' . $this->profile->id.'_file_'.$field->name.'" src="'.JURI::root().'components/com_aicontactsafe/index.html" style="width:0;height:0;border:0px solid #FFF;display:none;"></iframe>';
break;
case 'NO' :
// Number
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$maxlength = '';
if (substr_count(strtolower($field->field_parameters), 'maxlength') == 0 && $field->field_limit > 0) {
$maxlength = 'maxlength="'.$field->field_limit.'"';
}
$field->html_tag = '<input type="text" name="' . $field->name . '" id="' . $field->name . '" ' . $maxlength . ' ' . $field->field_parameters . ' value="' . $postData_field_value . '" />';
break;
case 'HE' :
// Hidden Email
// it will generate a field only if it has a post value in it
if ( strlen(trim($postData_field_value)) > 0 ) {
$field->html_label = '';
$he_value = $model->ascunde_sir($postData_field_value);
$field->html_tag = '<input type="hidden" name="' . $field->name . '" id="' . $field->name . '" value="' . $he_value . '" />';
} else {
$field->html_label = null;
$field->html_tag = null;
}
break;
case 'UQ' :
// Unique text
if($model->useUqField()) {
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$maxlength = '';
if (substr_count(strtolower($field->field_parameters), 'maxlength') == 0 && $field->field_limit > 0) {
$maxlength = 'maxlength="'.$field->field_limit.'"';
}
$field->html_tag = '<input type="text" name="' . $field->name . '" id="' . $field->name . '" ' . $maxlength . ' ' . $field->field_parameters . ' value="' . $postData_field_value . '" />';
} else {
$field->html_label = '';
$field->html_tag = '';
}
break;
case 'CC' :
// Credit card
if($model->useCcField()) {
$field->html_label = '<span class="aiContactSafe_label" id="aiContactSafe_label_' . $field->name . '" ' . $field->label_parameters . '><label for="' . $field->name . '" ' . $field->label_parameters . '>' . $field->field_label . '</label></span>';
$maxlength = '';
if (substr_count(strtolower($field->field_parameters), 'maxlength') == 0 && $field->field_limit > 0) {
$maxlength = 'maxlength="'.$field->field_limit.'"';
}
$postData_field_value_creditcardtype = '';
if (is_array($postData) && array_key_exists($field->name.'_creditcardtype', $postData)) {
$postData_field_value_creditcardtype = $postData[$field->name.'_creditcardtype'];
}
$postData_field_value_creditcardnumber = '';
if (is_array($postData) && array_key_exists($field->name.'_creditcardnumber', $postData)) {
$postData_field_value_creditcardnumber = $postData[$field->name.'_creditcardnumber'];
}
$postData_field_value_creditcardverification = '';
if (is_array($postData) && array_key_exists($field->name.'_creditcardverification', $postData)) {
$postData_field_value_creditcardverification = $postData[$field->name.'_creditcardverification'];
}
$postData_field_value_creditcardexpirationmonth = '';
if (is_array($postData) && array_key_exists($field->name.'_creditcardexpirationmonth', $postData)) {
$postData_field_value_creditcardexpirationmonth = $postData[$field->name.'_creditcardexpirationmonth'];
}
$postData_field_value_creditcardexpirationyear = '';
if (is_array($postData) && array_key_exists($field->name.'_creditcardexpirationyear', $postData)) {
$postData_field_value_creditcardexpirationyear = $postData[$field->name.'_creditcardexpirationyear'];
}
$field->html_tag = '<div class="cc_field_container">';
$field->html_tag .= '<div class="cc_label cc_label_type">'.JText::_('COM_AICONTACTSAFE_CREDIT_CARD_TYPE').'</div>';
$field->html_tag .= '<div class="cc_field cc_field_type">';
$field->html_tag .= '<select size="1" name="' . $field->name . '_creditcardtype" id="' . $field->name . '_creditcardtype" class="inputbox">';
$field->html_tag .= '<option value="Visa"'.($postData_field_value_creditcardtype=='Visa'?' selected="selected"':'').'>Visa</option>';
$field->html_tag .= '<option value="Mastercard"'.($postData_field_value_creditcardtype=='Mastercard'?' selected="selected"':'').'>Mastercard</option>';
$field->html_tag .= '<option value="American Express"'.($postData_field_value_creditcardtype=='American Express'?' selected="selected"':'').'>American Express</option>';
$field->html_tag .= '<option value="Discover"'.($postData_field_value_creditcardtype=='Discover'?' selected="selected"':'').'>Discover</option>';
$field->html_tag .= '</select>';
$field->html_tag .= '</div>';
$field->html_tag .= '<div class="cc_label cc_label_number">'.JText::_('COM_AICONTACTSAFE_CREDIT_CARD_NUMBER').'</div>';
$field->html_tag .= '<div class="cc_field cc_field_number">';
$field->html_tag .= '<input type="text" name="' . $field->name . '_creditcardnumber" id="' . $field->name . '_creditcardnumber" class="inputbox" value="'.$postData_field_value_creditcardnumber.'" />';
$field->html_tag .= '</div>';
$field->html_tag .= '<div class="cc_label cc_label_verification">'.JText::_('COM_AICONTACTSAFE_CREDIT_CARD_VERIFICATION').' <span class="cc_label_verification_info">'.JText::_('COM_AICONTACTSAFE_CREDIT_CARD_VERIFICATION_INFO').'</span></div>';
$field->html_tag .= '<div class="cc_field cc_field_verification">';
$field->html_tag .= '<input type="text" name="' . $field->name . '_creditcardverification" id="' . $field->name . '_creditcardverification" class="inputbox" value="'.$postData_field_value_creditcardverification.'" />';
$field->html_tag .= '</div>';
$field->html_tag .= '<div class="cc_label cc_label_expiration_month">'.JText::_('COM_AICONTACTSAFE_CREDIT_CARD_EXPIRATION_MONTH').'</div>';
$field->html_tag .= '<div class="cc_field cc_field_expiration_month">';
$field->html_tag .= '<select size="1" name="' . $field->name . '_creditcardexpirationmonth" id="' . $field->name . '_creditcardexpirationmonth" class="inputbox">';
$field->html_tag .= '<option value="01"'.($postData_field_value_creditcardexpirationmonth=='01'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_JANUARY').'</option>';
$field->html_tag .= '<option value="02"'.($postData_field_value_creditcardexpirationmonth=='02'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_FEBRUARY').'</option>';
$field->html_tag .= '<option value="03"'.($postData_field_value_creditcardexpirationmonth=='03'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_MARCH').'</option>';
$field->html_tag .= '<option value="04"'.($postData_field_value_creditcardexpirationmonth=='04'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_APRIL').'</option>';
$field->html_tag .= '<option value="05"'.($postData_field_value_creditcardexpirationmonth=='05'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_MAY').'</option>';
$field->html_tag .= '<option value="06"'.($postData_field_value_creditcardexpirationmonth=='06'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_JUNE').'</option>';
$field->html_tag .= '<option value="07"'.($postData_field_value_creditcardexpirationmonth=='07'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_JULY').'</option>';
$field->html_tag .= '<option value="08"'.($postData_field_value_creditcardexpirationmonth=='08'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_AUGUST').'</option>';
$field->html_tag .= '<option value="09"'.($postData_field_value_creditcardexpirationmonth=='09'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_SEPTEMBER').'</option>';
$field->html_tag .= '<option value="10"'.($postData_field_value_creditcardexpirationmonth=='10'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_OCTOBER').'</option>';
$field->html_tag .= '<option value="11"'.($postData_field_value_creditcardexpirationmonth=='11'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_NOVEMBER').'</option>';
$field->html_tag .= '<option value="12"'.($postData_field_value_creditcardexpirationmonth=='12'?' selected="selected"':'').'>'.JText::_('COM_AICONTACTSAFE_DECEMBER').'</option>';
$field->html_tag .= '</select>';
$field->html_tag .= '</div>';
$field->html_tag .= '<div class="cc_label cc_label_expiration_year">'.JText::_('COM_AICONTACTSAFE_CREDIT_CARD_EXPIRATION_MONTH').'</div>';
$field->html_tag .= '<div class="cc_field cc_field_expiration_year">';
$field->html_tag .= '<select size="1" name="' . $field->name . '_creditcardexpirationyear" id="' . $field->name . '_creditcardexpirationyear" class="inputbox">';
$year = date('Y');
for($i=0;$i<20;$i++) {
$field->html_tag .= '<option value="'.$year.'"'.($postData_field_value_creditcardexpirationyear==$year?' selected="selected"':'').'>'.$year.'</option>';
$year++;
}
$field->html_tag .= '</select>';
$field->html_tag .= '</div>';
$field->html_tag .= '</div>';
} else {
$field->html_label = '';
$field->html_tag = '';
}
break;
}
if (strlen(trim($field->html_tag)) > 0) {
if (strlen(trim($field->field_prefix)) > 0) {
$field->html_tag = '<span class="aiContactSafe_prefix" id="' . $field->name . '_prefix">'.trim($field->field_prefix).'</span>'.$field->html_tag;
}
if (strlen(trim($field->field_sufix)) > 0) {
$field->html_tag = $field->html_tag.'<span class="aiContactSafe_sufix" id="' . $field->name . '_sufix">'.trim($field->field_sufix).'</span>';
}
}
if ($dt == 0 && $this->_config_values['highlight_errors']) {
if(is_array($fieldsWithErrors) && array_key_exists($field->id,$fieldsWithErrors)) {
$field->has_errors = true;
$field->error_msg = $fieldsWithErrors[$field->id];
} else {
$field->has_errors = false;
$field->error_msg = array();
}
} else {
$field->has_errors = false;
$field->error_msg = array();
}
$fields[$field_key] = $field;
}
return $fields;
}
// function to call the css file used with this view
function callCssFile($cssFile = '') {
// check if css is activated/deactivated in the current profile
$use_css = $this->profile->use_message_css;
// if no cssFile is named call the default one of the class
if (strlen($cssFile) == 0) {
$cssFile = $this->_cssFile;
}
// if css is activated and there is a css file to call, continue the function
if ($use_css) {
$document = JFactory::getDocument();
$nameCssGeneral = JURI::root().'components/com_aicontactsafe/includes/css/aicontactsafe_general.css';
$document->addStyleSheet($nameCssGeneral);
if (strlen($cssFile) > 0) {
// import joomla clases to manage file system
jimport('joomla.filesystem.file');
// determine if to use the css from the template or from the component
$template_name = $this->_app->getTemplate();
$tPath = JPATH_ROOT.DS.'templates'.DS.$template_name.DS.'html'.DS.'com_aicontactsafe'.DS.'message'.DS.$cssFile;
if (JFile::exists($tPath)) {
$nameCssFile = JURI::root().'templates/'.$template_name.'/html/com_aicontactsafe/message/'.$cssFile;
} else {
$nameCssFile = JURI::root().'media/aicontactsafe/cssprofiles/'.$cssFile;
}
$document->addStyleSheet($nameCssFile);
}
}
}
// function to generate captcha code
function writeCaptcha() {
// if captcha is activated, generate the image
if ($this->profile->use_captcha == 1 || ($this->profile->use_captcha == 2 && $this->_user_id == 0)) {
switch($this->profile->captcha_type) {
case 0:
// native plugin
$captcha_info = JText::_('COM_AICONTACTSAFE_PLEASE_ENTER_THE_FOLLOWING_SECURITY_CODE') . ':';
$change_image = JText::_('COM_AICONTACTSAFE_NOT_READABLE_CHANGE_TEXT');
?>
<div id="div_captcha">
<div id="div_captcha_info"><?php echo $captcha_info; ?></div>
<div id="div_captcha_img"><div id="div_captcha_img_<?php echo $this->profile->id; ?>" style="width:<?php echo $this->profile->captcha_width; ?>px;height:<?php echo $this->profile->captcha_height; ?>px;">...</div></div>
<div id="div_captcha_new">
<a href="javascript:void(0);" onclick="changeCaptcha(<?php echo $this->profile->id; ?>,1);"
id="change-image"><?php echo $change_image; ?></a>
</div>
<div style="margin-top:5px;" id="div_captcha_code"><input type="text" name="captcha-code" id="captcha-code" /></div>
</div>
<?php
break;
case 1:
// Multiple CAPTCHA Engine
$captchaPlugin = JPluginHelper::getPlugin('content', 'captcha');
$captchaPluginParameters = new JParameter($captchaPlugin->params);
if ( $captchaPluginParameters->get( 'captcha_systems' ) == 'recaptcha' ) {
?>
<input type="hidden" id="reCaptchaReset" name="reCaptchaReset" value="1" />
<input type="hidden" id="reCaptchaPublicKey" name="reCaptchaPublicKey" value="<?php echo $captchaPluginParameters->get( 'captcha_systems-recaptcha-PubKey' ); ?>" />
<input type="hidden" id="reCaptchaTheme" name="reCaptchaTheme" value="<?php echo $captchaPluginParameters->get( 'captcha_systems-recaptcha-Theme' ); ?>" />
<?php
}
JPluginHelper::importPlugin('content', 'captcha');
$dispatcher = JDispatcher::getInstance();
echo '<div id="div_captcha">';
$dispatcher->trigger('onAfterDisplayForm');
echo '</div>';
break;
}
}
}
// function to generate a random string
function random_string($max = 20){
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghijklmnopqrstuvwxwz0123456789';
for($i = 0; $i < $max; $i++){
$rand_key = mt_rand(0, strlen($chars));
$string .= substr($chars, $rand_key, 1);
}
return str_shuffle($string);
}
}
| gpl-2.0 |
kosmosby/medicine-prof | components/com_flexicontent/models/fields/fieldtypes.php | 98 | <?php
require_once("administrator/components/com_flexicontent/models/fields/fieldtypes.php");
?> | gpl-2.0 |
psoetens/orocos-rtt | rtt/scripting/CommonParser.cpp | 6984 | /***************************************************************************
tag: Peter Soetens Thu Jul 15 11:21:07 CEST 2004 CommonParser.cxx
CommonParser.cxx - description
-------------------
begin : Thu July 15 2004
copyright : (C) 2004 Peter Soetens
email : peter.soetens at mech.kuleuven.ac.be
***************************************************************************
* This library 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; *
* version 2 of the License. *
* *
* As a special exception, you may use this file as part of a free *
* software library without restriction. Specifically, if other files *
* instantiate templates or use macros or inline functions from this *
* file, or you compile this file and link it with other files to *
* produce an executable, this file does not by itself cause the *
* resulting executable to be covered by the GNU General Public *
* License. This exception does not however invalidate any other *
* reasons why the executable file might be covered by the GNU General *
* Public License. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307 USA *
* *
***************************************************************************/
#include <boost/bind.hpp>
#include "parse_exception.hpp"
#include "parser-debug.hpp"
#include "CommonParser.hpp"
namespace RTT {
using boost::bind;
using namespace detail;
namespace {
boost::spirit::classic::assertion<std::string> expect_eos("End of statement expected. Use a newline or ';' to separate statements.");
}
CommonParser::~CommonParser() {}
CommonParser::CommonParser()
: identchar( "a-zA-Z_0-9" ), skipeol(true),
skipper( eol_skip_functor(skipeol) )
{
// we reserve a few words
keywordstable =
"do",
"until",
"done",
"or",
"and",
"not",
"include",
"if",
"define",
"then",
"else",
"for",
"foreach",
"while",
"true",
"false",
"async",
"time",
"const",
"nothing", // do not exclude 'do nothing' !
"yield",
"var",
"set",
"alias",
"sync",
"send",
"call",
"collect",
"collectIfDone",
"return",
"call",
"try",
"catch";
BOOST_SPIRIT_DEBUG_RULE( idr );
BOOST_SPIRIT_DEBUG_RULE( idlr );
BOOST_SPIRIT_DEBUG_RULE( eos );
BOOST_SPIRIT_DEBUG_RULE( notassertingeos );
BOOST_SPIRIT_DEBUG_RULE( leos );
BOOST_SPIRIT_DEBUG_RULE( endofkeyword );
BOOST_SPIRIT_DEBUG_RULE( keywords );
BOOST_SPIRIT_DEBUG_RULE( keyword );
BOOST_SPIRIT_DEBUG_RULE( identifier );
BOOST_SPIRIT_DEBUG_RULE( templ );
BOOST_SPIRIT_DEBUG_RULE( tidentifier );
BOOST_SPIRIT_DEBUG_RULE( identchar );
BOOST_SPIRIT_DEBUG_RULE( notassertingidentifier );
BOOST_SPIRIT_DEBUG_RULE( lexeme_identifier );
BOOST_SPIRIT_DEBUG_RULE( lexeme_notassertingidentifier );
BOOST_SPIRIT_DEBUG_RULE( type_name );
BOOST_SPIRIT_DEBUG_RULE( skipper );
// an identifier is a word which can be used to identify a
// label, or be the name of an object or method. it is required
// to start with a letter, followed by any number of letters,
// numbers, dashes, underscores or letters. The keywords we
// reserved above are excluded..
keywords = keywordstable;
endofkeyword = (~identchar) | eol_p | end_p;
keyword = lexeme_d[keywords >> eps_p(endofkeyword)];
// if a rule is going to be used inside a lexeme_d, then it
// needs to be of a different type.. Since identifier is used
// both inside and outside of lexeme_d, we need two versions of
// it. Those are provided here: lexeme_identifier and
// identifier..
idr = lexeme_d[ alpha_p >> *identchar ][assign( lastparsedident )] - keyword;
idlr = lexeme_d[ alpha_p >> *identchar ][assign( lastparsedident )] - keyword;
// #warning " Rule on stack ?? "
//RULE( identifier_base, lexeme_d[ alpha_p >> *identchar ][assign( lastparsedident )] - as_lower_d[keywords] );
//BOOST_SPIRIT_DEBUG_RULE( identifier_base );
lexeme_identifier = idlr | keyword[bind( &CommonParser::seenillegalidentifier, this )];
lexeme_notassertingidentifier = idlr;
notassertingidentifier = idr >> !str_p("[]");
identifier = (idr >> !str_p("[]")) | keyword[bind( &CommonParser::seenillegalidentifier, this )];
// this is a recursive rule. 't' stands for 'template' and 'terminal' (followed by a '(')
templ = ch_p('<') >> identifier >> *templ >> '>';
tidentifier = identifier >> *templ; // >> eps_p( ch_p('(') ); // This is a hack: we expect always the form A<B<C>>(...)
// end of statement is on a newline or a ';'
//eos = lexeme_d[ *(space_p - eol_p) >> (eol_p | ch_p(';')) ];
eos = expect_eos( notassertingeos ); // detect } as eos, but do not consume.
notassertingeos = eol_p | ch_p(';') | eps_p(ch_p('}')); // detect } as eos, but do not consume.
leos = *(space_p - eol_p) >> (eol_p | ch_p(';') | eps_p(ch_p('}')));
chset<> t_identchar( "a-zA-Z-_0-9/<>." );
type_name = lexeme_d[ alpha_p >> *t_identchar ] - keyword;
}
void CommonParser::seenillegalidentifier()
{
throw parse_exception_illegal_identifier( lastparsedident );
}
}
| gpl-2.0 |
bfosberry/GameSocial | db/migrate/20141003195026_add_uid_to_events.rb | 149 | class AddUidToEvents < ActiveRecord::Migration
def change
add_column :events, :uid, :string
add_column :game_events, :uid, :string
end
end
| gpl-2.0 |
twistor/character-encoder | src/Adapter/MbString.php | 529 | <?php
/**
* @file
* Contains \CharacterEncoder\Adapter\MbString.
*/
namespace CharacterEncoder\Adapter;
/**
* Encoding adapter using the mbstring extension.
*/
class MbString implements Adapter
{
/**
* {@inheritdoc}
*/
public function check($string, $encoding)
{
return (bool) @mb_check_encoding($string, $encoding);
}
/**
* {@inheritdoc}
*/
public function convert($string, $from, $to)
{
return (string) @mb_convert_encoding($string, $to, $from);
}
}
| gpl-2.0 |
RyanChan0220/LotteryAnalysis | mysql_db.py | 1787 | __author__ = 'Ryan'
import MySQLdb
class MySQLDB(object):
__db_name = ""
__con = None
def __init__(self):
pass
def connect(self, db_name):
self.__db_name = db_name
try:
self.__con = MySQLdb.connect(host='localhost', user='root', passwd='7758258', db=db_name, port=3306)
except MySQLdb.Error, e:
print "Mysql connect error %d: %s" % (e.args[0], e.args[1])
def close_connect(self):
self.__con.close()
def insert_many(self, table, columns, values):
with self.__con:
cur = self.__con.cursor()
col_length = len(columns.split(','))
column_values = "%s" + ", %s"*(col_length - 1)
statement = """INSERT INTO %s(%s) VALUES(%s)""" % (table, columns, column_values)
#print statement
cur.executemany(statement, values)
self.__con.commit()
cur.close()
def insert(self, table, column, value):
with self.__con:
cur = self.__con.cursor()
statement = """INSERT INTO %s(%s) VALUES(%s)""" % (table, column, value)
cur.execute(statement)
cur.close()
def query(self, table, column, value):
with self.__con:
cur = self.__con.cursor()
statement = """SELECT * FROM %s where %s = %s""" % (table, column, value)
cur.execute(statement)
data = cur.fetchall()
cur.close()
return data
def query(self, table, column):
with self.__con:
cur = self.__con.cursor()
statement = """SELECT %s FROM %s""" % (column, table)
cur.execute(statement)
data = cur.fetchall()
cur.close()
return data
| gpl-2.0 |
TheWatcher/InteractiveTimeline | InteractiveTimeline.alias.php | 220 | <?php
/**
* Aliases for the InteractiveTimeline extension.
*
* @file
* @ingroup Extensions
*/
$aliases = array();
/** English */
$aliases['en'] = array(
'InteractiveTimeline' => array( 'InteractiveTimeline' )
);
| gpl-2.0 |
vext01/c2tzx4u | src/C2TZX.cpp | 3849 | // C2TZX.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
unsigned int initCodeHeader(unsigned char* header, unsigned int codeSize, unsigned int codeLocation)
{
unsigned char checksum = 0;
header[0] = 16; // 0x10 ID
header[1] = 232; // 1 second pause
header[2] = 3; // 1 second pause
header[3] = 19; // ??
header[4] = 0; // ??
header[5] = 0; // ??
header[6] = 3; // ??
header[7] = 's';
header[8] = 'd';
header[9] = 'c';
header[10] = 'c';
header[11] = ' ';
header[12] = 'g';
header[13] = 'a';
header[14] = 'y';
header[15] = ' ';
header[16] = ' ';
header[17] = codeSize & 255; // Code size
header[18] = codeSize >> 8; // Code size
header[19] = codeLocation & 255; // Data location
header[20] = codeLocation >> 8; // Data location
header[21] = 0;
header[22] = 128;
for(int i = 6; i<=22; i++)
{
checksum ^= header[i];
}
header[23] = checksum; // Checksum
return 24;
}
unsigned int initCodeDataSection(unsigned char* codeDataHeader, unsigned char* codeSection, unsigned int codeSize)
{
unsigned char checksum = 0;
codeDataHeader[0] = 16; // 0x10 ID
codeDataHeader[1] = 232; // 1 second pause
codeDataHeader[2] = 3; // 1 second pause
unsigned int codeSizePlus2 = codeSize + 2; // +2 for 0xFF and checksum
codeDataHeader[3] = codeSizePlus2 & 255; // Code size
codeDataHeader[4] = codeSizePlus2 >> 8; // Code size
codeDataHeader[5] = 255; // ??
unsigned int i;
for(i=0; i<codeSize; i++)
{
codeDataHeader[6+i] = codeSection[i]; // Code
}
for(i=5; i<6+codeSize; i++)
{
checksum ^= codeDataHeader[i];
}
codeDataHeader[6+codeSize] = checksum; // Checksum
return 7 + codeSize;
}
int main(int argc, char* argv[])
{
if(argc < 4)
{
printf("********************************************\r\n");
printf("* *\r\n");
printf("* Usage: *\r\n");
printf("* c2tzx header bin output *\r\n");
printf("* *\r\n");
printf("* Example: *\r\n");
printf("* c2tzx header.bin my_code.bin my_prog.tzx *\r\n");
printf("* *\r\n");
printf("********************************************\r\n");
return 0;
}
FILE* header = fopen (argv[1], "rb" );
FILE* code = fopen (argv[2], "rb" );
FILE* tzx = fopen (argv[3], "w+b" );
unsigned int codeLocation = 32768;
unsigned int i;
if(!header || !code || !tzx)
return 0;
unsigned char headerData[4000];
unsigned int headerSize = (unsigned int)fread(headerData, 1, 4000, header);
unsigned char codeData[10000];
unsigned int codeSize = (unsigned int)fread(codeData, 1, 4000, code);
unsigned char codeHeader[24];
unsigned char codeDataHeader[10000];
unsigned int codeHeaderLength = initCodeHeader(codeHeader, codeSize, codeLocation);
unsigned int codeDataHeaderLength = initCodeDataSection(codeDataHeader, codeData, codeSize);
unsigned char tzxData[20000];
unsigned int off = 0;
for(i=0; i<headerSize; i++)
{
tzxData[i] = headerData[i];
}
off += headerSize;
for(i=0; i < codeHeaderLength; i++)
{
tzxData[off+i] = codeHeader[i];
}
off += codeHeaderLength;
for(i=0; i < codeDataHeaderLength; i++)
{
tzxData[off+i] = codeDataHeader[i];
}
off += codeDataHeaderLength;
fwrite(tzxData, 1, off, tzx);
fclose(header);
fclose(code);
fclose(tzx);
//delete codeDataHeader;
return 0;
}
| gpl-2.0 |
sugao516/gltron-code | art/biohazard/artpack.lua | 26 | settings.show_gl_logo = 0
| gpl-2.0 |
estrategasdigitales/digmota | sistema/app/views/sitio/libretas/fotorevise/navbar.php | 962 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<nav class="menu">
<h1>CREA TU LIBRETA</h1>
<ul>
<li>
<button value="" type="button" class="principal_menu btn btn-warning btn-block ttip listo" title="este es el tooltip."><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>ELIGE TU DISEÑO Y TAMAÑO</button>
</li>
<li>
<button value="" type="button" class="personaliza_menu btn btn-warning btn-block ttip listo" title="este es el tooltip."><span class="glyphicon glyphicon-ok" aria-hidden="true"></span>PERSONALIZA</button>
</li>
<li class="activo">
<button disabled value="" type="button" class="compra_menu btn btn-warning btn-block ttip" title="este es el tooltip.">REVISA Y COMPRA</button>
</li>
</ul>
</nav> | gpl-2.0 |