code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package org.bimserver.plugins;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.io.Closeable;
import java.io.IOException;
import org.bimserver.interfaces.objects.SPluginBundle;
import org.bimserver.interfaces.objects.SPluginBundleVersion;
public interface PluginBundle extends Iterable<PluginContext> {
String getVersion();
void add(PluginContext pluginContext);
void close() throws IOException;
SPluginBundleVersion getPluginBundleVersion();
SPluginBundle getPluginBundle();
void addCloseable(Closeable closeable);
PluginContext getPluginContext(String identifier);
}
| opensourceBIM/BIMserver | PluginBase/src/org/bimserver/plugins/PluginBundle.java | Java | agpl-3.0 | 1,454 |
/*
* Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
*
* This file is part of fiware-iotagent-lib
*
* fiware-iotagent-lib is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* fiware-iotagent-lib is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with fiware-iotagent-lib.
* If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by the GNU Affero General Public License
* please contact with::daniel.moranjimenez@telefonica.com
*/
const logger = require('logops');
const dbService = require('../../model/dbConn');
const config = require('../../commonConfig');
const fillService = require('./../common/domain').fillService;
const alarmsInt = require('../common/alarmManagement').intercept;
const errors = require('../../errors');
const constants = require('../../constants');
const Device = require('../../model/Device');
const async = require('async');
let context = {
op: 'IoTAgentNGSI.MongoDBDeviceRegister'
};
const attributeList = [
'id',
'type',
'name',
'service',
'subservice',
'lazy',
'commands',
'staticAttributes',
'active',
'registrationId',
'internalId',
'internalAttributes',
'resource',
'apikey',
'protocol',
'endpoint',
'transport',
'polling',
'timestamp',
'explicitAttrs',
'expressionLanguage',
'ngsiVersion'
];
/**
* Generates a handler for the save device operations. The handler will take the customary error and the saved device
* as the parameters (and pass the serialized DAO as the callback value).
*
* @return {Function} The generated handler.
*/
function saveDeviceHandler(callback) {
return function saveHandler(error, deviceDAO) {
if (error) {
logger.debug(fillService(context, deviceDAO), 'Error storing device information: %s', error);
callback(new errors.InternalDbError(error));
} else {
callback(null, deviceDAO.toObject());
}
};
}
/**
* Create a new register for a device. The device object should contain the id, type and registrationId
*
* @param {Object} newDevice Device object to be stored
*/
function storeDevice(newDevice, callback) {
/* eslint-disable-next-line new-cap */
const deviceObj = new Device.model();
attributeList.forEach((key) => {
deviceObj[key] = newDevice[key];
});
// Ensure protocol is in newDevice
if (!newDevice.protocol && config.getConfig().iotManager && config.getConfig().iotManager.protocol) {
deviceObj.protocol = config.getConfig().iotManager.protocol;
}
logger.debug(context, 'Storing device with id [%s] and type [%s]', newDevice.id, newDevice.type);
deviceObj.save(function saveHandler(error, deviceDAO) {
if (error) {
if (error.code === 11000) {
logger.debug(context, 'Tried to insert a device with duplicate ID in the database: %s', error);
callback(new errors.DuplicateDeviceId(newDevice.id));
} else {
logger.debug(context, 'Error storing device information: %s', error);
callback(new errors.InternalDbError(error));
}
} else {
callback(null, deviceDAO.toObject());
}
});
}
/**
* Remove the device identified by its id and service.
*
* @param {String} id Device ID of the device to remove.
* @param {String} service Service of the device to remove.
* @param {String} subservice Subservice inside the service for the removed device.
*/
function removeDevice(id, service, subservice, callback) {
const condition = {
id,
service,
subservice
};
logger.debug(context, 'Removing device with id [%s]', id);
Device.model.deleteOne(condition, function (error) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else {
logger.debug(context, 'Device [%s] successfully removed.', id);
callback(null);
}
});
}
/**
* Return the list of currently registered devices (via callback).
*
* @param {String} tyoe Type for which the devices are requested.
* @param {String} service Service for which the devices are requested.
* @param {String} subservice Subservice inside the service for which the devices are requested.
* @param {Number} limit Maximum number of entries to return.
* @param {Number} offset Number of entries to skip for pagination.
*/
function listDevices(type, service, subservice, limit, offset, callback) {
const condition = {};
if (type) {
condition.type = type;
}
if (service) {
condition.service = service;
}
if (subservice) {
condition.subservice = subservice;
}
const query = Device.model.find(condition).sort();
if (limit) {
query.limit(parseInt(limit, 10));
}
if (offset) {
query.skip(parseInt(offset, 10));
}
async.series([query.exec.bind(query), Device.model.countDocuments.bind(Device.model, condition)], function (
error,
results
) {
callback(error, {
count: results[1],
devices: results[0]
});
});
}
function findOneInMongoDB(queryParams, id, callback) {
const query = Device.model.findOne(queryParams);
query.select({ __v: 0 });
query.lean().exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else if (data) {
context = fillService(context, data);
logger.debug(context, 'Device data found: %j', data);
callback(null, data);
} else {
logger.debug(context, 'Device [%s] not found.', id);
callback(new errors.DeviceNotFound(id));
}
});
}
/**
* Internal function used to find a device in the DB.
*
* @param {String} id ID of the Device to find.
* @param {String} service Service the device belongs to (optional).
* @param {String} subservice Division inside the service (optional).
*/
function getDeviceById(id, service, subservice, callback) {
const queryParams = {
id,
service,
subservice
};
context = fillService(context, queryParams);
logger.debug(context, 'Looking for device with id [%s].', id);
findOneInMongoDB(queryParams, id, callback);
}
/**
* Retrieves a device using it ID, converting it to a plain Object before calling the callback.
*
* @param {String} id ID of the Device to find.
* @param {String} service Service the device belongs to.
* @param {String} subservice Division inside the service.
*/
function getDevice(id, service, subservice, callback) {
getDeviceById(id, service, subservice, function (error, data) {
if (error) {
callback(error);
} else {
callback(null, data);
}
});
}
function getByName(name, service, servicepath, callback) {
context = fillService(context, { service, subservice: servicepath });
logger.debug(context, 'Looking for device with name [%s].', name);
const query = Device.model.findOne({
name,
service,
subservice: servicepath
});
query.select({ __v: 0 });
query.lean().exec(function handleGet(error, data) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else if (data) {
callback(null, data);
} else {
logger.debug(context, 'Device [%s] not found.', name);
callback(new errors.DeviceNotFound(name));
}
});
}
/**
* Updates the given device into the database.
* updated.
*
* @param {Object} device Device object with the new values to write.
*/
function update(device, callback) {
logger.debug(context, 'Storing updated values for device [%s]:\n%s', device.id, JSON.stringify(device, null, 4));
getDeviceById(device.id, device.service, device.subservice, function (error, data) {
if (error) {
callback(error);
} else {
data.lazy = device.lazy;
data.active = device.active;
data.internalId = device.internalId;
data.staticAttributes = device.staticAttributes;
data.internalAttributes = device.internalAttributes;
data.commands = device.commands;
data.endpoint = device.endpoint;
data.polling = device.polling;
data.name = device.name;
data.type = device.type;
data.apikey = device.apikey;
data.registrationId = device.registrationId;
data.explicitAttrs = device.explicitAttrs;
data.ngsiVersion = device.ngsiVersion;
/* eslint-disable-next-line new-cap */
const deviceObj = new Device.model(data);
deviceObj.isNew = false;
deviceObj.save(saveDeviceHandler(callback));
}
});
}
/**
* Cleans all the information in the database, leaving it in a clean state.
*/
function clear(callback) {
dbService.db.db.dropDatabase(callback);
}
function itemToObject(i) {
if (i.toObject) {
return i.toObject();
} else {
return i;
}
}
function getDevicesByAttribute(name, value, service, subservice, callback) {
const filter = {};
if (service) {
filter.service = service;
}
if (subservice) {
filter.subservice = subservice;
}
filter[name] = value;
context = fillService(context, filter);
logger.debug(context, 'Looking for device with filter [%j].', filter);
const query = Device.model.find(filter);
query.select({ __v: 0 });
query.exec(function handleGet(error, devices) {
if (error) {
logger.debug(context, 'Internal MongoDB Error getting device: %s', error);
callback(new errors.InternalDbError(error));
} else if (devices) {
callback(null, devices.map(itemToObject));
} else {
logger.debug(context, 'Device [%s] not found.', name);
callback(new errors.DeviceNotFound(name));
}
});
}
exports.getDevicesByAttribute = alarmsInt(constants.MONGO_ALARM, getDevicesByAttribute);
exports.store = alarmsInt(constants.MONGO_ALARM, storeDevice);
exports.update = alarmsInt(constants.MONGO_ALARM, update);
exports.remove = alarmsInt(constants.MONGO_ALARM, removeDevice);
exports.list = alarmsInt(constants.MONGO_ALARM, listDevices);
exports.get = alarmsInt(constants.MONGO_ALARM, getDevice);
exports.getSilently = getDevice;
exports.getByName = alarmsInt(constants.MONGO_ALARM, getByName);
exports.clear = alarmsInt(constants.MONGO_ALARM, clear);
| telefonicaid/iotagent-node-lib | lib/services/devices/deviceRegistryMongoDB.js | JavaScript | agpl-3.0 | 11,503 |
/*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jbilling is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with jbilling. If not, see <http://www.gnu.org/licenses/>.
This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015.
You may download the latest source from webdataconsulting.github.io.
*/
package com.sapienter.jbilling.server.payment.tasks;
import java.util.HashMap;
import java.util.Map;
import com.sapienter.jbilling.common.FormatLogger;
import com.sapienter.jbilling.server.invoice.db.InvoiceDTO;
import com.sapienter.jbilling.server.payment.PaymentDTOEx;
import com.sapienter.jbilling.server.pluggableTask.PaymentTask;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskException;
/**
* Routes payments to other processor plug-ins based on currency.
* To configure the routing, set the parameter name to the currency
* code and the parameter value to the processor plug-in id.
*/
public class PaymentRouterCurrencyTask extends AbstractPaymentRouterTask {
private static final FormatLogger LOG = new FormatLogger(
PaymentRouterCurrencyTask.class);
@Override
protected PaymentTask selectDelegate(PaymentDTOEx paymentInfo)
throws PluggableTaskException {
String currencyCode = paymentInfo.getCurrency().getCode();
Integer selectedTaskId = null;
try {
// try to get the task id for this currency
selectedTaskId = intValueOf(parameters.get(currencyCode));
} catch (NumberFormatException e) {
throw new PluggableTaskException("Invalid task id for currency " +
"code: " + currencyCode);
}
if (selectedTaskId == null) {
LOG.warn("Could not find processor for %s", parameters.get(currencyCode));
return null;
}
LOG.debug("Delegating to task id %s", selectedTaskId);
PaymentTask selectedTask = instantiateTask(selectedTaskId);
return selectedTask;
}
@Override
public Map<String, String> getAsyncParameters(InvoiceDTO invoice)
throws PluggableTaskException {
String currencyCode = invoice.getCurrency().getCode();
Map<String, String> parameters = new HashMap<String, String>(1);
parameters.put("currency", currencyCode);
return parameters;
}
}
| WebDataConsulting/billing | src/java/com/sapienter/jbilling/server/payment/tasks/PaymentRouterCurrencyTask.java | Java | agpl-3.0 | 3,019 |
# -*- coding: utf-8 -*-
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl).
from odoo import models, api
class SendPEC(models.TransientModel):
_name = 'wizard.fatturapa.send.pec'
_description = "Wizard to send multiple e-invoice PEC"
@api.multi
def send_pec(self):
if self.env.context.get('active_ids'):
attachments = self.env['fatturapa.attachment.out'].browse(
self.env.context['active_ids'])
attachments.send_via_pec()
| linkitspa/l10n-italy | l10n_it_fatturapa_pec/wizard/send_pec.py | Python | agpl-3.0 | 503 |
{{--
Copyright 2015 ppy Pty. Ltd.
This file is part of osu!web. osu!web is distributed with the hope of
attracting more community contributions to the core ecosystem of osu!.
osu!web is free software: you can redistribute it and/or modify
it under the terms of the Affero GNU General Public License version 3
as published by the Free Software Foundation.
osu!web is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with osu!web. If not, see <http://www.gnu.org/licenses/>.
--}}
@extends("master")
@section("content")
@include("store.header")
{!! Form::open([
"url" => "store/add-to-cart",
"data-remote" => true,
"id" => "product-form",
"class" => "osu-layout__row osu-layout__row--page-compact osu-layout__row--sm1"
]) !!}
<div class="osu-layout__sub-row osu-layout__sub-row--lg1" id="product-header" style="background-image: url({{ $product->header_image }})">
<div>{!! Markdown::convertToHtml($product->header_description) !!}</div>
</div>
<div class="osu-layout__sub-row">
<div class="row">
<div class="col-md-12">
<h1>{{ $product->name }}</h1>
</div>
</div>
@if($product->custom_class && View::exists("store.products.{$product->custom_class}"))
<div class="row">
<div class="col-md-12">
{!! Markdown::convertToHtml($product->description) !!}
</div>
</div>
@include("store.products.{$product->custom_class}")
@else
<div class="row">
<div class="col-md-6">
@if($product->images())
<ul id="product-slides" class="rslides">
@foreach($product->images() as $i => $image)
<li>
<?php $imageSize = fast_imagesize($image[1]); ?>
<a
class="js-gallery"
data-width="{{ $imageSize[0] }}"
data-height="{{ $imageSize[1] }}"
data-gallery-id="product-{{ $product->product_id }}"
data-index="{{ $i }}"
href="{{ $image[1] }}"
style="background-image: url('{{ $image[1] }}');">
</a>
</li>
@endforeach
</ul>
<ul id="product-slides-nav" class="rslides-nav">
@foreach($product->images() as $image)
<li>
<a href="#"><div style="background-image: url('{{ $image[0] }}');"></div></a>
</li>
@endforeach
</ul>
@else
<div class="preview" data-image="{{ $product->image }}" style="background-image: url('{{ $product->image }}');"></div>
@endif
</div>
<div class="col-md-6">
<div class="row">
<div class="col-md-12">
{!! Markdown::convertToHtml($product->description) !!}
</div>
</div>
<div class="row price-box">
<div class="col-md-12">
<p class="price">{{ currency($product->cost) }}</p>
<p class="notes">excluding shipping fees</p>
</div>
</div>
@if($product->types())
@foreach($product->types() as $type => $values)
<div class="form-group">
<label for="select-product-{{ $type }}">{{ $type }}</label>
<select id="select-product-{{ $type }}" class="form-control js-url-selector" data-keep-scroll="1">
@foreach($values as $value => $product_id)
<option {{ $product_id === $product->product_id ? "selected" : "" }} value="{{ action("StoreController@getProduct", $product_id) }}">
{{ $value }}
</option>
@endforeach
</select>
</div>
@endforeach
@endif
@if($product->inStock())
<div class="row">
<div class="col-md-12">
<div class='form-group'>
<input type="hidden" name="item[product_id]" value="{{ $product->product_id }}" />
{!! Form::label('item[quantity]', 'Quantity') !!}
{!! Form::select("item[quantity]", product_quantity_options($product), 1, ['class' => 'js-store-item-quantity form-control']) !!}
</div>
</div>
</div>
@else
<div class="row">
<div class="col-md-12">
Currently out of stock :(. Check back soon.
</div>
</div>
@endif
</div>
</div>
@endif
</div>
@if($product->inStock())
<div class="osu-layout__sub-row osu-layout__sub-row--with-separator" id="add-to-cart">
<div class="big-button">
<button type="submit" class="js-store-add-to-cart btn-osu btn-osu-default">Add to Cart</button>
</div>
</div>
@endif
{!! Form::close() !!}
@endsection
| dvcrn/osu-web | resources/views/store/product.blade.php | PHP | agpl-3.0 | 6,180 |
require 'spec_helper'
feature "Using embedded shopfront functionality", js: true do
include OpenFoodNetwork::EmbeddedPagesHelper
include AuthenticationWorkflow
include WebHelper
include ShopWorkflow
include CheckoutWorkflow
include UIComponentHelper
describe "using iframes" do
let(:distributor) { create(:distributor_enterprise, name: 'My Embedded Hub', permalink: 'test_enterprise', with_payment_and_shipping: true) }
let(:supplier) { create(:supplier_enterprise) }
let(:oc1) { create(:simple_order_cycle, distributors: [distributor], coordinator: create(:distributor_enterprise), orders_close_at: 2.days.from_now) }
let(:product) { create(:simple_product, name: 'Framed Apples', supplier: supplier) }
let(:variant) { create(:variant, product: product, price: 19.99) }
let(:exchange) { Exchange.find(oc1.exchanges.to_enterprises(distributor).outgoing.first.id) }
let(:user) { create(:user) }
before do
add_variant_to_order_cycle(exchange, variant)
Spree::Config[:enable_embedded_shopfronts] = true
Spree::Config[:embedded_shopfronts_whitelist] = 'test.com'
allow_any_instance_of(ActionDispatch::Request).to receive(:referer).and_return('https://www.test.com')
visit "/embedded-shop-preview.html?#{distributor.permalink}"
end
after do
Spree::Config[:enable_embedded_shopfronts] = false
end
it "displays modified shopfront layout" do
on_embedded_page do
within 'nav.top-bar' do
expect(page).to have_selector 'ul.left', visible: false
expect(page).to have_selector 'ul.center', visible: false
end
expect(page).to have_content "My Embedded Hub"
expect(page).to have_content "Framed Apples"
end
end
it "allows shopping and checkout" do
on_embedded_page do
fill_in "variants[#{variant.id}]", with: 1
wait_until_enabled 'input.add_to_cart'
first("input.add_to_cart:not([disabled='disabled'])").click
expect(page).to have_text 'Your shopping cart'
find('a#checkout-link').click
expect(page).to have_text 'Checkout now'
click_button 'Login'
login_with_modal
expect(page).to have_text 'Payment'
within "#details" do
fill_in "First Name", with: "Some"
fill_in "Last Name", with: "One"
fill_in "Email", with: "test@example.com"
fill_in "Phone", with: "0456789012"
end
within "#billing" do
fill_in "Address", with: "123 Street"
select "Australia", from: "Country"
select "Victoria", from: "State"
fill_in "City", with: "Melbourne"
fill_in "Postcode", with: "3066"
end
within "#shipping" do
find('input[type="radio"]').click
end
within "#payment" do
find('input[type="radio"]').click
end
place_order
expect(page).to have_content "Your order has been processed successfully"
end
end
it "redirects to embedded hub on logout when embedded" do
on_embedded_page do
wait_for_shop_loaded
find('ul.right li#login-link a').click
login_with_modal
wait_for_shop_loaded
wait_until { page.find('ul.right li.user-menu.has-dropdown').value.present? }
logout_via_navigation
expect(page).to have_text 'My Embedded Hub'
end
end
end
private
# When you have pending changes and try to navigate away from a page, it asks you "Are you sure?".
# When we click the "Update" button to save changes, we need to wait
# until it is actually saved and "loading" disappears before doing anything else.
def wait_for_shop_loaded
page.has_no_content? "Loading"
page.has_no_css? "input[value='Updating cart...']"
end
def login_with_modal
page.has_selector? 'div.login-modal', visible: true
within 'div.login-modal' do
fill_in "Email", with: user.email
fill_in "Password", with: user.password
find('input[type="submit"]').click
end
page.has_no_selector? 'div.login-modal', visible: true
end
def logout_via_navigation
first('ul.right li.user-menu a').click
find('ul.right ul.dropdown li a[title="Logout"]').click
end
end
| lin-d-hop/openfoodnetwork | spec/features/consumer/shopping/embedded_shopfronts_spec.rb | Ruby | agpl-3.0 | 4,300 |
# To ensure that the core entry types are registered
| melissiproject/server | melisi/mlscommon/__init__.py | Python | agpl-3.0 | 54 |
import AbstractServiceReceiver from "../../Base/AbstractServiceReceiver";
import Sender from "../../Base/Container/Sender";
import HomeInstanceController from "./HomeInstanceController";
import ClientBootSender from "../../Contents/Sender/ClientBootSender";
import GetRoomSender from "../../Contents/Sender/GetRoomSender";
import ConnInfoSender from "../../Contents/Sender/ConnInfoSender";
import UseActorSender from "../../Contents/Sender/UseActorSender";
import ChatMessageSender from "../../Contents/Sender/ChatMessageSender";
import GetTimelineSender from "../../Contents/Sender/GetTimelineSender";
import TimelineSender from "../../Contents/Sender/TimelineSender";
import UpdateTimelineSender from "../../Contents/Sender/UpdateTimelineSender";
import ServentSender from "../../Contents/Sender/ServentSender";
import ServentCloseSender from "../../Contents/Sender/ServentCloseSender";
import VoiceChatMemberSender from "../../Contents/Sender/VoiceChatMemberSender";
import ChatInfoSender from "../../Contents/Sender/ChatInfoSender";
import AudioBlobSender from "../../Contents/Sender/AudioBlobSender";
import GetAudioBlobSender from "../../Contents/Sender/GetAudioBlobSender";
export default class HomeInstanceReceiver extends AbstractServiceReceiver<HomeInstanceController> {
/**
*
*/
public Receive(conn: PeerJs.DataConnection, sender: Sender) {
// クライアントの起動通知
if (sender.type === ClientBootSender.ID) {
let ci = new ConnInfoSender();
let mbc = this.IsMultiBoot(sender.uid, conn);
ci.isBootCheck = !mbc;
ci.isMultiBoot = mbc;
this.Controller.SwPeer.SendTo(conn, ci);
return;
}
// ルームの要求
if (sender.type === GetRoomSender.ID) {
this.Controller.SendRoom(conn, sender as GetRoomSender);
}
// 使用アクター通知
if (sender.type === UseActorSender.ID) {
let useActor = sender as UseActorSender;
this.Controller.Manager.Room.SetActor(conn, useActor);
}
// チャットメッセージ通知
if (sender.type === ChatMessageSender.ID) {
let chatMessage = sender as ChatMessageSender;
this.Controller.Manager.Chat.SetMessage(chatMessage);
}
// チャット入力中通知
if (sender.type === ChatInfoSender.ID) {
let cis = sender as ChatInfoSender;
this.Controller.Manager.Chat.SetInfo(cis);
}
// タイムラインの要求
if (sender.type === GetTimelineSender.ID) {
let gtl = sender as GetTimelineSender;
let result = new TimelineSender();
result.msgs = this.Controller.Manager.Chat.GetBeforeMessages(gtl.hid, gtl.count);
this.Controller.SwPeer.SendTo(conn, result);
}
// タイムラインの更新
if (sender.type === UpdateTimelineSender.ID) {
let utl = sender as UpdateTimelineSender;
this.Controller.Manager.Chat.UpdateTimeline(utl.message);
}
// サーバントの起動/更新通知
if (sender.type === ServentSender.ID) {
this.Controller.Manager.Servent.SetServent(sender as ServentSender);
}
// サーバントの終了通知
if (sender.type === ServentCloseSender.ID) {
this.Controller.Manager.Servent.CloseServent(sender as ServentCloseSender);
}
// ボイスチャットルームのメンバー通知
if (sender.type === VoiceChatMemberSender.ID) {
this.Controller.Manager.VoiceChat.SetMember(sender as VoiceChatMemberSender);
}
// 音声の登録
if (sender.type === AudioBlobSender.ID) {
let abs = sender as AudioBlobSender;
this.Controller.Model.SaveVoice(abs, () => { });
}
// 音声の要求
if (sender.type === GetAudioBlobSender.ID) {
let key = sender as GetAudioBlobSender;
this.Controller.Model.LoadVoice(key, (resultAbs) => {
// 要求があったクライアントに音声情報を返す
this.Controller.SwPeer.SendTo(conn, resultAbs);
});
}
}
/**
* ユーザーID毎の接続MAP
*/
private _userConnMap = new Map<string, PeerJs.DataConnection>();
/**
*
* @param uid
* @param peerid
*/
private IsMultiBoot(uid: string, conn: PeerJs.DataConnection): boolean {
if (this._userConnMap.has(uid)) {
let preConn = this._userConnMap.get(uid);
if (preConn.open) {
if (preConn.remoteId === conn.remoteId) {
return false;
}
else {
return true;
}
}
else {
// 接続が切れていた場合は上書き
this._userConnMap.set(uid, conn);
return false;
}
}
else {
// 未登録だった場合
this._userConnMap.set(uid, conn);
return false;
}
}
}
| iwatendo/skybeje | src/Page/HomeInstance/HomeInstanceReceiver.ts | TypeScript | agpl-3.0 | 5,246 |
class PandaseqModule extends Module {
constructor (params) {
super ("pandaseq", "https://github.com/yoann-dufresne/amplicon_pipeline/wiki/Pandaseq-module");
this.params = params;
}
onLoad () {
super.onLoad();
var that = this;
// --- Inputs ---
var inputs = this.dom.getElementsByClassName('input_file');
this.fwd = inputs[0]; this.rev = inputs[1];
this.fwd.onchange = this.rev.onchange = () => {that.input_change()};
}
input_change () {
// If the names are standards
if (this.fwd.value.includes('_fwd.fastq') && this.rev.value.includes('_rev.fastq')) {
// Get the main name
var i1 = this.fwd.value.indexOf('_fwd.fastq');
var sub1 = this.fwd.value.substring(0, i1);
var i2 = this.rev.value.indexOf('_rev.fastq');
var sub2 = this.rev.value.substring(0, i2);
if (sub2 == sub1) {
let output_file = this.dom.getElementsByClassName('output_zone')[0];
output_file = output_file.getElementsByTagName('input')[0];
output_file.value = sub1 + '_panda.fasta';
output_file.onchange();
}
}
}
};
module_manager.moduleCreators.pandaseq = (params) => {
return new PandaseqModule(params);
};
| yoann-dufresne/amplicon_pipeline | www/modules/pandaseq.js | JavaScript | agpl-3.0 | 1,149 |
# frozen_string_literal: true
module Decidim
module Meetings
# This class serializes a Meeting so can be exported to CSV, JSON or other
# formats.
class MeetingSerializer < Decidim::Exporters::Serializer
include Decidim::ApplicationHelper
include Decidim::ResourceHelper
# Public: Initializes the serializer with a meeting.
def initialize(meeting)
@meeting = meeting
end
# Public: Exports a hash with the serialized data for this meeting.
def serialize
{
id: meeting.id,
category: {
id: meeting.category.try(:id),
name: meeting.category.try(:name)
},
scope: {
id: meeting.scope.try(:id),
name: meeting.scope.try(:name)
},
participatory_space: {
id: meeting.participatory_space.id,
url: Decidim::ResourceLocatorPresenter.new(meeting.participatory_space).url
},
component: { id: component.id },
title: meeting.title,
description: meeting.description,
start_time: meeting.start_time.to_s(:db),
end_time: meeting.end_time.to_s(:db),
attendees: meeting.attendees_count.to_i,
contributions: meeting.contributions_count.to_i,
organizations: meeting.attending_organizations,
address: meeting.address,
location: meeting.location,
reference: meeting.reference,
comments: meeting.comments.count,
attachments: meeting.attachments.count,
followers: meeting.followers.count,
url: url,
related_proposals: related_proposals,
related_results: related_results
}
end
private
attr_reader :meeting
def component
meeting.component
end
def related_proposals
meeting.linked_resources(:proposals, "proposals_from_meeting").map do |proposal|
Decidim::ResourceLocatorPresenter.new(proposal).url
end
end
def related_results
meeting.linked_resources(:results, "meetings_through_proposals").map do |result|
Decidim::ResourceLocatorPresenter.new(result).url
end
end
def url
Decidim::ResourceLocatorPresenter.new(meeting).url
end
end
end
end
| codegram/decidim | decidim-meetings/lib/decidim/meetings/meeting_serializer.rb | Ruby | agpl-3.0 | 2,351 |
# -*- coding: utf-8 -*-
# © 2016 Elico Corp (https://www.elico-corp.com).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Business Requirement Deliverable - Project',
'category': 'Business Requirements Management',
'summary': 'Create projects and tasks directly from'
' the Business Requirement and Resources lines',
'version': '8.0.4.0.6',
'website': 'https://www.elico-corp.com/',
"author": "Elico Corp, Odoo Community Association (OCA)",
'depends': [
'business_requirement_deliverable',
'project',
],
'data': [
'views/business_view.xml',
'views/project.xml',
'wizard/generate_projects_view.xml',
],
'image': [
'static/description/icon.png',
'static/img/bus_req_project.png'
],
'license': 'AGPL-3',
'installable': False,
}
| sudhir-serpentcs/business-requirement | business_requirement_deliverable_project/__manifest__.py | Python | agpl-3.0 | 882 |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SSCMS.Configuration;
using SSCMS.Core.StlParser.Models;
using SSCMS.Core.StlParser.StlElement;
using SSCMS.Utils;
namespace SSCMS.Web.Controllers.Stl
{
public partial class ActionsIfController
{
[HttpPost, Route(Constants.RouteStlRouteActionsIf)]
public async Task<GetResult> Get([FromBody] GetRequest request)
{
var user = await _authManager.GetUserAsync();
var dynamicInfo = StlDynamic.GetDynamicInfo(_settingsManager, request.Value, request.Page, user, Request.Path + Request.QueryString);
var ifInfo = TranslateUtils.JsonDeserialize<DynamicIfInfo>(dynamicInfo.Settings);
var isSuccess = false;
var html = string.Empty;
if (ifInfo != null)
{
if (StringUtils.EqualsIgnoreCase(ifInfo.Type, StlIf.TypeIsUserLoggin))
{
isSuccess = _authManager.IsUser;
}
var template = isSuccess ? dynamicInfo.YesTemplate : dynamicInfo.NoTemplate;
html = await StlDynamic.ParseDynamicAsync(_parseManager, dynamicInfo, template);
}
return new GetResult
{
Value = isSuccess,
Html = html
};
}
}
}
| siteserver/cms | src/SSCMS.Web/Controllers/Stl/ActionsIfController.Get.cs | C# | agpl-3.0 | 1,361 |
#!/usr/bin/env python3
# -*- coding : utf-8 -*-
def newone():
print("newone test!")
newone() | kmahyyg/learn_py3 | modules/mymodule1/__init__.py | Python | agpl-3.0 | 98 |
/*
* Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of Essentia
*
* Essentia is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
#include "ifftwcomplex.h"
#include "fftw.h"
using namespace std;
using namespace essentia;
using namespace standard;
const char* IFFTWComplex::name = "IFFTC";
const char* IFFTWComplex::category = "Standard";
const char* IFFTWComplex::description = DOC("This algorithm calculates the inverse short-term Fourier transform (STFT) of an array of complex values using the FFT algorithm. The resulting frame has a size equal to the input fft frame size. The inverse Fourier transform is not defined for frames which size is less than 2 samples. Otherwise an exception is thrown.\n"
"\n"
"An exception is thrown if the input's size is not larger than 1.\n"
"\n"
"References:\n"
" [1] Fast Fourier transform - Wikipedia, the free encyclopedia,\n"
" http://en.wikipedia.org/wiki/Fft\n\n"
" [2] Fast Fourier Transform -- from Wolfram MathWorld,\n"
" http://mathworld.wolfram.com/FastFourierTransform.html");
IFFTWComplex::~IFFTWComplex() {
ForcedMutexLocker lock(FFTW::globalFFTWMutex);
fftwf_destroy_plan(_fftPlan);
fftwf_free(_input);
fftwf_free(_output);
}
void IFFTWComplex::compute() {
const std::vector<std::complex<Real> >& fft = _fft.get();
std::vector<std::complex<Real> >& signal = _signal.get();
// check if input is OK
int size = (int)fft.size();
if (size <= 0) {
throw EssentiaException("IFFTComplex: Input size cannot be 0 or 1");
}
if ((_fftPlan == 0) ||
((_fftPlan != 0) && _fftPlanSize != size)) {
createFFTObject(size);
}
// copy input into plan
memcpy(_input, &fft[0], size*sizeof(complex<Real>));
// calculate the fft
fftwf_execute(_fftPlan);
// copy result from plan to output vector
signal.resize(size);
memcpy(&signal[0], _output, size*sizeof(complex<Real>));
}
void IFFTWComplex::configure() {
createFFTObject(parameter("size").toInt());
}
void IFFTWComplex::createFFTObject(int size) {
ForcedMutexLocker lock(FFTW::globalFFTWMutex);
// create the temporary storage array
fftwf_free(_input);
fftwf_free(_output);
_input = (complex<Real>*)fftwf_malloc(sizeof(complex<Real>)*size);
_output = (complex<Real>*)fftwf_malloc(sizeof(complex<Real>)*size);
if (_fftPlan != 0) {
fftwf_destroy_plan(_fftPlan);
}
//_fftPlan = fftwf_plan_dft_c2r_1d(size, (fftwf_complex*)_input, _output, FFTW_MEASURE);
_fftPlan = fftwf_plan_dft_1d(size, (fftwf_complex*)_input, (fftwf_complex*)_output, FFTW_FORWARD, FFTW_ESTIMATE);
_fftPlanSize = size;
}
| carthach/essentia | src/algorithms/standard/ifftwcomplex.cpp | C++ | agpl-3.0 | 3,238 |
/*
* Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
* General Public License as published by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package scrum.server.impediments;
import ilarkesto.pdf.ACell;
import ilarkesto.pdf.APdfContainerElement;
import ilarkesto.pdf.ARow;
import ilarkesto.pdf.ATable;
import ilarkesto.pdf.FontStyle;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import scrum.server.common.APdfCreator;
import scrum.server.project.Project;
import scrum.server.sprint.Task;
public class ImpedimentListPdfCreator extends APdfCreator {
public ImpedimentListPdfCreator(Project project) {
super(project);
}
@Override
protected void build(APdfContainerElement pdf) {
pdf.paragraph().text("Impediments", headerFonts[0]);
List<Impediment> impediments = new ArrayList<Impediment>(project.getImpediments());
Collections.sort(impediments);
for (Impediment imp : impediments) {
if (imp.isClosed()) continue;
impediment(pdf, imp);
}
}
private void impediment(APdfContainerElement pdf, Impediment imp) {
pdf.nl();
ATable table = pdf.table(2, 20, 3);
ARow rowHeader = table.row().setDefaultBackgroundColor(Color.LIGHT_GRAY);
rowHeader.cell().setFontStyle(referenceFont).text(imp.getReference());
rowHeader.cell().setFontStyle(new FontStyle(defaultFont).setBold(true)).text(imp.getLabel());
rowHeader.cell().setFontStyle(smallerFont).text(imp.getDate());
richtextRow(table, "Description", imp.getDescription());
if (imp.isSolutionSet()) richtextRow(table, "Solution", imp.getSolution());
Set<Task> tasks = imp.getTasks();
if (!tasks.isEmpty()) {
ACell cell = richtextRow(table, "Blocked tasks", null);
for (Task task : tasks) {
cell.paragraph().text(task.getReference(), referenceFont).text(" ").text(task.getLabel()).text(" (")
.text(task.getRequirement().getReference(), referenceFont).text(")");
}
}
table.createCellBorders(Color.GRAY, 0.2f);
}
@Override
protected String getFilename() {
return "impediments";
}
}
| MiguelSMendoza/Kunagi | WEB-INF/classes/scrum/server/impediments/ImpedimentListPdfCreator.java | Java | agpl-3.0 | 2,682 |
using UnityEngine;
using System.Collections;
public class ExitButton : MonoBehaviour {
public Texture buttonTextureExit;
void OnGUI() {
GUIStyle myButtonStyle = new GUIStyle(GUI.skin.button);
myButtonStyle.fontSize = 20;
if (GUI.Button (new Rect ((Screen.width*2/4) -40, Screen.height*4/5, 80, 80), buttonTextureExit)) {
//exit game
Application.Quit();
}
if (GUI.Button (new Rect ((Screen.width*1/10) - 55, Screen.height*9/10-30, 110, 60), "MainMenu",myButtonStyle)) {
//go to MainMenu
Application.LoadLevel("MainMenu");
}
}
}
| softwarejimenez/funnyBall | project/Assets/Scripts/ExitButton.cs | C# | agpl-3.0 | 558 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Breeze.Sharp;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Northwind.Models;
namespace Test_NetClient
{
[TestClass]
public class InsideEntityTests
{
private String _serviceName;
[TestInitialize]
public void TestInitializeMethod()
{
Configuration.Instance.ProbeAssemblies(typeof(Customer).Assembly);
_serviceName = "http://localhost:56337/breeze/Northwind/";
}
/// <summary>
/// Once you’ve changed an entity, it stays in a changed state
/// … even if you manually restore the original values.
/// </summary>
[TestMethod]
public async Task EntityStaysModified()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customer = manager.GetEntities<Customer>().First();
var oldCompanyName = customer.CompanyName; // assume existing "Unchanged" entity
Assert.AreEqual(EntityState.Unchanged, customer.EntityAspect.EntityState);
customer.CompanyName = "Something new"; // EntityState becomes "Modified"
Assert.AreEqual(EntityState.Modified, customer.EntityAspect.EntityState);
customer.CompanyName = oldCompanyName; // EntityState is still "Modified
Assert.AreEqual(EntityState.Modified, customer.EntityAspect.EntityState);
}
/// <summary>
/// Call RejectChanges to cancel pending changes,
/// revert properties to their prior values,
/// and set the entityState to "Unchanged".
/// </summary>
/// <returns></returns>
[TestMethod]
public async Task CancelWithRejectChanges()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customer = manager.GetEntities<Customer>().First();
var oldCompanyName = customer.CompanyName; // assume existing "Unchanged" entity
Assert.AreEqual(EntityState.Unchanged, customer.EntityAspect.EntityState);
customer.CompanyName = "Something new"; // EntityState becomes "Modified"
Assert.AreEqual(EntityState.Modified, customer.EntityAspect.EntityState);
customer.EntityAspect.RejectChanges(); // EntityState restored to "Unchanged”
// customer.CompanyName = oldCompanyName
Assert.AreEqual(EntityState.Unchanged, customer.EntityAspect.EntityState);
Assert.AreEqual(oldCompanyName, customer.CompanyName);
}
/// <summary>
/// You can also call rejectChanges on the EntityManager
/// to cancel and revert pending changes for every entity in cache.
/// </summary>
[TestMethod]
public async Task RevertAllPendingChangesInCache()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customer1 = manager.GetEntities<Customer>().First();
var customer2 = manager.GetEntities<Customer>().Last();
var oldCompanyName1 = customer1.CompanyName; // assume existing "Unchanged" entity
var oldCompanyName2 = customer2.CompanyName;
Assert.AreEqual(EntityState.Unchanged, customer1.EntityAspect.EntityState);
Assert.AreEqual(EntityState.Unchanged, customer2.EntityAspect.EntityState);
customer1.CompanyName = "Something new"; // EntityState becomes "Modified"
customer2.CompanyName = "Something different";
Assert.AreEqual(EntityState.Modified, customer1.EntityAspect.EntityState);
Assert.AreEqual(EntityState.Modified, customer2.EntityAspect.EntityState);
manager.RejectChanges(); // revert all pending changes in cache
Assert.AreEqual(EntityState.Unchanged, customer1.EntityAspect.EntityState);
Assert.AreEqual(oldCompanyName1, customer1.CompanyName);
Assert.AreEqual(EntityState.Unchanged, customer2.EntityAspect.EntityState);
Assert.AreEqual(oldCompanyName2, customer2.CompanyName);
}
[TestMethod]
public async Task OriginalValuesMapUpdatesWithPropertyChanges()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customer = manager.GetEntities<Customer>().First();
var oldCompanyName = customer.CompanyName; // assume existing "Unchanged" entity
// The OriginalValuesMap is an empty object while the entity is in the "Unchanged" state.
Assert.AreEqual(0, customer.EntityAspect.OriginalValuesMap.Count);
// When you change an entity property for the first time...
customer.CompanyName = "Something new";
// ...Breeze adds the pre-change value to the OriginalValuesMap...
Assert.AreEqual(1, customer.EntityAspect.OriginalValuesMap.Count, "The OriginalValuesMap should have added an entry for the CompanyName change.");
Assert.AreEqual(oldCompanyName, customer.EntityAspect.OriginalValuesMap.First().Value, "The old company name should have been added to the OriginalValuesMap.");
// ...using the property name as the key.
var names = GetOriginalValuesPropertyNames(customer);
Assert.AreEqual("CompanyName", names.First(), "'CompanyName' should be the key in the OriginalValuesMap.");
// Breeze replaces EntityAspect.OriginalValuesMap with a new empty hash
// when any operation restores the entity to the "Unchanged" state.
customer.EntityAspect.RejectChanges();
Assert.AreEqual(0, customer.EntityAspect.OriginalValuesMap.Count, "The OriginalValuesMap should be empty after RejectChanges.");
Assert.AreEqual(EntityState.Unchanged, customer.EntityAspect.EntityState);
}
public IEnumerable<string> GetOriginalValuesPropertyNames(IEntity entity)
{
var names = new List<string>();
foreach (var name in entity.EntityAspect.OriginalValuesMap)
{
names.Add(name.Key);
}
return names;
}
[TestMethod]
public async Task ChangingPropertyRaisesPropertyChanged()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customer = manager.GetEntities<Customer>().First();
// get ready for propertyChanged event after property change
var aspectPropertyChangedEventCount = 0;
customer.EntityAspect.PropertyChanged += (sender, args) => ++aspectPropertyChangedEventCount;
// make a change
customer.CompanyName = "Something new";
Assert.IsTrue(aspectPropertyChangedEventCount > 0, "The PropertyChanged event should have fired after changing the CompanyName and updated the event counter.");
}
[TestMethod]
public async Task CanGetEntityMetadataFromEntityType()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customerType = manager.MetadataStore.GetEntityType(typeof(Customer));
var customer = customerType.CreateEntity();
// customer.EntityAspect.EntityType == customerType
Assert.AreEqual(customer.EntityAspect.EntityType, customerType, "an entity's entityType should be the same type that created it");
customer.EntityAspect.GetValue("CompanyName");
}
[TestMethod]
public async Task GetSetValue()
{
var manager = new EntityManager(_serviceName);
await PrimeCache(manager);
var customer = manager.GetEntities<Customer>().First();
var setName = "Ima Something Corp";
customer.EntityAspect.SetValue("CompanyName", setName);
var getName = customer.EntityAspect.GetValue("CompanyName");
// getName == setName
Assert.AreEqual(setName, getName);
}
private async Task PrimeCache(EntityManager manager)
{
var q = new EntityQuery<Customer>().Take(5);
await q.Execute(manager);
}
}
}
| Breeze/breeze.sharp.samples | DocCode/Client/DocCode.Client/InsideEntityTests.cs | C# | agpl-3.0 | 8,515 |
# encoding: utf-8
# This file is part of the K5 bot project.
# See files README.md and COPYING for copyright and licensing information.
require 'stringio'
require 'IRC/complex_regexp/visitors/node_visitor'
module ComplexRegexp
module Visitors
class NodeStringVisitor
include NodeVisitor
attr_reader :buffer
def initialize(full_traverse = false, buffer = StringIO.new)
@buffer = buffer
@full_traverse = full_traverse
end
def enter_node(n)
raise "Unknown Node: #{n}"
end
def enter_match_any(n)
# empty string
end
def enter_simple_run(n)
@buffer << n.text
end
def enter_complex_run(n)
# will be filled by children
end
def enter_multi_match(n)
# will be filled by children
end
def enter_multi_match_rest(n, child)
@buffer << '&'
# will be filled by children
end
def enter_guard(n)
@buffer << "{#{n.guard_name}}" if @full_traverse && n.guard_name
# will be filled by children
end
def enter_guard_applicator(n)
# will be filled by children
end
def enter_guard_applicator_rest(n, child)
# will be filled by children
@buffer << '&&'
end
def enter_capture_group(n)
@buffer << '('
@buffer << "?#{n.group_name}" if n.group_name
# will be filled by children
end
def leave_capture_group(n)
@buffer << ')'
end
def enter_question_group(n)
@buffer << '(?'
# will be filled by children
end
def leave_question_group(n)
@buffer << ')'
end
end
end
end | k5bot/k5bot | IRC/complex_regexp/visitors/node_string_visitor.rb | Ruby | agpl-3.0 | 1,709 |
/*
Copyright (c) 2000-2013 "independIT Integrative Technologies GmbH",
Authors: Ronald Jeninga, Dieter Stubler
schedulix Enterprise Job Scheduling System
independIT Integrative Technologies GmbH [http://www.independit.de]
mailto:contact@independit.de
This file is part of schedulix
schedulix is free software:
you can redistribute it and/or modify it under the terms of the
GNU Affero General Public License as published by the
Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.independit.scheduler.server.repository;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.sql.*;
import de.independit.scheduler.server.*;
import de.independit.scheduler.server.util.*;
import de.independit.scheduler.server.exception.*;
public class SDMSnpSrvrSRFootprint extends SDMSnpSrvrSRFootprintProxyGeneric
{
protected SDMSnpSrvrSRFootprint(SDMSObject p_object)
{
super(p_object);
}
public void delete(SystemEnvironment sysEnv)
throws SDMSException
{
super.delete(sysEnv);
}
}
| schedulix/schedulix | src/server/repository/SDMSnpSrvrSRFootprint.java | Java | agpl-3.0 | 1,454 |
/*********************************************************************************
* Ephesoft is a Intelligent Document Capture and Mailroom Automation program
* developed by Ephesoft, Inc. Copyright (C) 2010-2012 Ephesoft Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Ephesoft, Inc. headquarters at 111 Academy Way,
* Irvine, CA 92617, USA. or at email address info@ephesoft.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Ephesoft" logo.
* If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by Ephesoft".
********************************************************************************/
package com.ephesoft.dcma.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ephesoft.dcma.constant.UtilConstants;
/**
* This class is a utility file consisting of various APIs related to different functions that can be performed with a file.
*
* @author Ephesoft
* @version 1.0
* @see java.io.FileInputStream
*/
public class FileUtils implements IUtilCommonConstants {
/**
* Logger for logging the messages.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/**
* This method deletes a given directory with its content.
*
* @param srcPath {@link File}
* @return true if successful false other wise.
*/
public static boolean deleteDirectoryAndContents(File srcPath) {
String files[] = srcPath.list();
boolean folderDelete = true;
if (files != null) {
for (int index = 0; index < files.length; index++) {
String sFilePath = srcPath.getPath() + File.separator + files[index];
File fFilePath = new File(sFilePath);
folderDelete = folderDelete & fFilePath.delete();
}
}
folderDelete = folderDelete & srcPath.delete();
return folderDelete;
}
/**
* This method zips the contents of Directory specified into a zip file whose name is provided.
*
* @param dir {@link String}
* @param zipfile {@link String}
* @param excludeBatchXml boolean
* @throws IOException
* @throws IllegalArgumentException in case of error
*/
public static void zipDirectory(final String dir, final String zipfile, final boolean excludeBatchXml) throws IOException,
IllegalArgumentException {
// Check that the directory is a directory, and get its contents
File directory = new File(dir);
if (!directory.isDirectory()) {
throw new IllegalArgumentException("Not a directory: " + dir);
}
String[] entries = directory.list();
byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
int bytesRead;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int index = 0; index < entries.length; index++) {
if (excludeBatchXml && entries[index].contains(IUtilCommonConstants.BATCH_XML)) {
continue;
}
File file = new File(directory, entries[index]);
if (file.isDirectory()) {
continue;// Ignore directory
}
FileInputStream input = new FileInputStream(file); // Stream to read file
ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
out.putNextEntry(entry); // Store entry
bytesRead = input.read(buffer);
while (bytesRead != -1) {
out.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
if (input != null) {
input.close();
}
}
if (out != null) {
out.close();
}
}
/**
* API to zip list of files to a desired file. Operation aborted if any file is invalid or a directory.
*
* @param filePaths {@link List}< {@link String}>
* @param outputFilePath {@link String}
* @throws IOException in case of error
*/
public static void zipMultipleFiles(List<String> filePaths, String outputFilePath) throws IOException {
LOGGER.info("Zipping files to " + outputFilePath + ".zip file");
File outputFile = new File(outputFilePath);
if (outputFile.exists()) {
LOGGER.info(outputFilePath + " file already exists. Deleting existing and creating a new file.");
outputFile.delete();
}
byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
int bytesRead;
ZipOutputStream out = null;
FileInputStream input = null;
try {
out = new ZipOutputStream(new FileOutputStream(outputFilePath));
for (String filePath : filePaths) {
LOGGER.info("Writing file " + filePath + " into zip file.");
File file = new File(filePath);
if (!file.exists() || file.isDirectory()) {
throw new Exception("Invalid file: " + file.getAbsolutePath()
+ ". Either file does not exists or it is a directory.");
}
input = new FileInputStream(file); // Stream to read file
ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
out.putNextEntry(entry); // Store entry
bytesRead = input.read(buffer);
while (bytesRead != -1) {
out.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
}
} catch (Exception e) {
LOGGER.error("Exception occured while zipping file." + e.getMessage(), e);
} finally {
if (input != null) {
input.close();
}
if (out != null) {
out.close();
}
}
}
/**
* This method deletes a given directory with its content.
*
* @param srcPath {@link String}
* @return true if successful false other wise.
*/
public static boolean deleteDirectoryAndContents(String sSrcPath) {
return deleteContents(sSrcPath, true);
}
/**
* This method deletes a given directory with its content.
*
* @param srcPath {@link String}
* @param folderDelete boolean
* @return true if successful false other wise.
*/
public static boolean deleteContents(final String sSrcPath, final boolean folderDelete) {
File srcPath = new File(sSrcPath);
boolean returnVal = folderDelete;
if (null == srcPath || !srcPath.exists()) {
returnVal = false;
} else {
String files[] = srcPath.list();
if (files != null) {
for (int index = 0; index < files.length; index++) {
String sFilePath = srcPath.getPath() + File.separator + files[index];
File fFilePath = new File(sFilePath);
returnVal = returnVal & fFilePath.delete();
}
returnVal = returnVal & srcPath.delete();
}
}
return returnVal;
}
/**
* This method deletes contents only.
*
* @param srcPath {@link String}
* @return true if successful false other wise.
*/
public static boolean deleteContentsOnly(String srcPath) {
boolean folderDelete = true;
File srcPathFile = new File(srcPath);
if (null == srcPathFile || !srcPathFile.exists()) {
folderDelete = false;
} else {
String files[] = srcPathFile.list();
if (files != null) {
for (int index = 0; index < files.length; index++) {
String sFilePath = srcPathFile.getPath() + File.separator + files[index];
File fFilePath = new File(sFilePath);
folderDelete = folderDelete & fFilePath.delete();
}
}
}
return folderDelete;
}
/**
* This method copies the src file to dest file.
*
* @param srcFile {@link File}
* @param destFile {@link File}
* @throws IOException in case of error
*/
public static void copyFile(File srcFile, File destFile) throws IOException {
InputStream input = null;
OutputStream out = null;
input = new FileInputStream(srcFile);
out = new FileOutputStream(destFile);
byte[] buf = new byte[UtilConstants.BUF_CONST];
int len = input.read(buf);
while (len > 0) {
out.write(buf, 0, len);
len = input.read(buf);
}
if (input != null) {
input.close();
}
if (out != null) {
out.close();
}
}
/**
* This methods copies a directory with all its files.
*
* @param srcPath {@link File}
* @param dstPath {@link File}
* @throws IOException in case of error
*/
public static void copyDirectoryWithContents(final File srcPath, final File dstPath) throws IOException {
if (srcPath.isDirectory()) {
if (!dstPath.exists()) {
dstPath.mkdir();
}
String[] files = srcPath.list();
if (files.length > 0) {
Arrays.sort(files);
for (int index = 0; index < files.length; index++) {
copyDirectoryWithContents(new File(srcPath, files[index]), new File(dstPath, files[index]));
}
}
} else {
if (srcPath.exists()) {
InputStream input = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
// Transfer bytes from in to out
byte[] buf = new byte[UtilConstants.BUF_CONST];
int len = input.read(buf);
while (len > 0) {
out.write(buf, 0, len);
len = input.read(buf);
}
if (input != null) {
input.close();
}
if (out != null) {
out.close();
}
}
}
}
/**
* This methods copies a directory with all its files.
*
* @param sSrcPath {@link String}
* @param sDstPath {@link String}
* @throws IOException in case of error
*/
public static void copyDirectoryWithContents(final String sSrcPath, final String sDstPath) throws IOException {
File srcPath = new File(sSrcPath);
File dstPath = new File(sDstPath);
if (srcPath.isDirectory()) {
if (!dstPath.exists()) {
dstPath.mkdir();
}
String[] files = srcPath.list();
if (files.length > 0) {
Arrays.sort(files);
for (int index = 0; index < files.length; index++) {
copyDirectoryWithContents(new File(srcPath, files[index]), new File(dstPath, files[index]));
}
}
} else {
if (srcPath.exists()) {
InputStream input = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
// Transfer bytes from in to out
byte[] buf = new byte[UtilConstants.BUF_CONST];
int len = input.read(buf);
while (len > 0) {
out.write(buf, 0, len);
len = input.read(buf);
}
if (input != null) {
input.close();
}
if (out != null) {
out.close();
}
}
}
}
/**
* To delete all XML files.
* @param folderName {@link String}
*/
public static void deleteAllXMLs(String folderName) {
File file = new File(folderName);
if (file.isDirectory()) {
File[] allFiles = file.listFiles();
for (int index = 0; index < allFiles.length; index++) {
if (allFiles[index].getName().endsWith(EXTENSION_XML)) {
allFiles[index].delete();
}
}
}
}
/**
* To delete all HOCR files.
* @param folderName {@link String}
*/
public static void deleteAllHocrFiles(String folderName) {
File file = new File(folderName);
if (file.isDirectory()) {
File[] allFiles = file.listFiles();
for (int index = 0; index < allFiles.length; index++) {
if (allFiles[index].getName().endsWith(EXTENSION_HTML)) {
allFiles[index].delete();
}
}
}
}
/**
* To copy all XML files.
* @param fromLoc {@link String}
* @param toLoc {@link String}
*/
public static void copyAllXMLFiles(String fromLoc, String toLoc) {
File inputFolder = new File(fromLoc);
File outputFolder = new File(toLoc);
File[] inputFiles = inputFolder.listFiles();
for (int index = 0; index < inputFiles.length; index++) {
if (inputFiles[index].getName().endsWith(EXTENSION_XML)) {
FileReader input;
FileWriter out;
int character;
try {
input = new FileReader(inputFiles[index]);
out = new FileWriter(outputFolder + File.separator + inputFiles[index].getName());
character = input.read();
while (character != -1) {
out.write(character);
character = input.read();
}
if (input != null) {
input.close();
}
if (out != null) {
out.close();
}
} catch (FileNotFoundException e) {
LOGGER.error("Exception while reading files:" + e);
} catch (IOException e) {
LOGGER.error("Exception while copying files:" + e);
}
}
}
}
/**
* To check the existence of Hocr files.
* @param folderLocation {@link String}
* @return boolean
*/
public static boolean checkHocrFileExist(String folderLocation) {
boolean returnValue = false;
File folderLoc = new File(folderLocation);
File[] allFiles = folderLoc.listFiles();
for (int index = 0; index < allFiles.length; index++) {
if (allFiles[index].getName().endsWith(EXTENSION_HTML)) {
returnValue = true;
}
}
return returnValue;
}
/**
* An utility method to update the properties file.
*
* @param propertyFile File
* @param propertyMap Map<String, String>
* @param comments String
* @throws IOException If any of the parameter is null or input property file is not found.
*/
public static void updateProperty(final File propertyFile, final Map<String, String> propertyMap, final String comments)
throws IOException {
if (null == propertyFile || null == propertyMap || propertyMap.isEmpty()) {
throw new IOException("propertyFile/propertyMap is null or empty.");
}
String commentsToAdd = HASH_STRING + comments;
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
List<String> propertiesToWrite = null;
try {
fileInputStream = new FileInputStream(propertyFile);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
propertiesToWrite = new ArrayList<String>();
propertiesToWrite.add(commentsToAdd);
processPropertyFile(propertyMap, bufferedReader, propertiesToWrite);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException exception) {
LOGGER.error("Exception occured while closing bufferedReader :" + exception);
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException exception) {
LOGGER.error("Exception while closing input stream :" + exception);
}
}
}
writeToPropertyFile(propertyFile, propertiesToWrite);
}
/**
* API to write a list of Strings to a property file.
*
* @param propertyFile {@link File}
* @param propertiesToWrite {@link List}
* @throws IOException
*/
private static void writeToPropertyFile(final File propertyFile, final List<String> propertiesToWrite) throws IOException {
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try {
fileWriter = new FileWriter(propertyFile, false);
bufferedWriter = new BufferedWriter(fileWriter);
for (String lineToWrite : propertiesToWrite) {
bufferedWriter.write(lineToWrite);
bufferedWriter.newLine();
}
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException exception) {
LOGGER.error("Exception occured while closing bufferedWriter : " + exception);
}
}
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException exception) {
LOGGER.error("Exception occured while closing fileWriter : " + exception);
}
}
}
}
/**
* API to process A property file and add all properties along with comment to list.
*
* @param propertyMap {@link Map}
* @param bufferedReader {@link BufferedReader}
* @param propertiesToWrite {@link List}
* @throws IOException
*/
private static void processPropertyFile(final Map<String, String> propertyMap, final BufferedReader bufferedReader,
final List<String> propertiesToWrite) throws IOException {
String strLine = null;
String key = null;
String value = null;
while ((strLine = bufferedReader.readLine()) != null) {
strLine = strLine.trim();
if (strLine.startsWith(HASH_STRING)) {
propertiesToWrite.add(strLine);
} else {
int indexOfDelimeter = strLine.indexOf(EQUAL_TO);
if (indexOfDelimeter > 0) {
key = strLine.substring(0, indexOfDelimeter).trim();
StringBuilder lineToWrite = new StringBuilder(key);
lineToWrite.append(EQUAL_TO);
value = propertyMap.get(key);
if (value != null) {
lineToWrite.append(value);
} else {
lineToWrite.append(strLine
.substring(indexOfDelimeter + 1));
}
propertiesToWrite.add(lineToWrite.toString());
}
}
}
}
/**
* To get Absolute File Path.
* @param pathname {@link String}
* @return {@link String}
*/
public static String getAbsoluteFilePath(String pathname) {
assert pathname != null : "Path name is Null, pathname : " + pathname;
File file = new File(pathname);
return file.getAbsolutePath();
}
/**
* To change File Extension.
*
* @param fileName {@link String}
* @param extension {@link String}
* @return {@link String}
*/
public static String changeFileExtension(String fileName, String extension) {
String name = fileName;
int indexOf = name.lastIndexOf(DOT);
int endIndex = name.length();
String substring = name.substring(indexOf + 1, endIndex);
name = name.replace(substring, extension);
return name;
}
/**
* This method zips the contents of Directory specified into a zip file whose name is provided.
*
* @param dir2zip {@link String}
* @param zout {@link String}
* @param dir2zipName {@link String}
* @throws IOException in case of error
*/
public static void zipDirectory(String dir2zip, ZipOutputStream zout, String dir2zipName) throws IOException {
File srcDir = new File(dir2zip);
List<String> fileList = listDirectory(srcDir);
for (String fileName : fileList) {
File file = new File(srcDir.getParent(), fileName);
String zipName = fileName;
if (File.separatorChar != FORWARD_SLASH) {
zipName = fileName.replace(File.separatorChar, FORWARD_SLASH);
}
zipName = zipName.substring(zipName.indexOf(dir2zipName + BACKWARD_SLASH) + 1 + (dir2zipName + BACKWARD_SLASH).length());
ZipEntry zipEntry;
if (file.isFile()) {
zipEntry = new ZipEntry(zipName);
zipEntry.setTime(file.lastModified());
zout.putNextEntry(zipEntry);
FileInputStream fin = new FileInputStream(file);
byte[] buffer = new byte[UtilConstants.BUFFER_CONST];
for (int n; (n = fin.read(buffer)) > 0;) {
zout.write(buffer, 0, n);
}
if (fin != null) {
fin.close();
}
} else {
zipEntry = new ZipEntry(zipName + FORWARD_SLASH);
zipEntry.setTime(file.lastModified());
zout.putNextEntry(zipEntry);
}
}
if (zout != null) {
zout.close();
}
}
/**
* List the contents of directory.
* @param directory {@link File}
* @return List<String>
* @throws IOException in case of error
*/
public static List<String> listDirectory(File directory) throws IOException {
return listDirectory(directory, true);
}
/**
* List the contents of directory.
* @param directory {@link File}
* @param includingDirectory boolean
* @return List<String>
* @throws IOException in case of error
*/
public static List<String> listDirectory(File directory, boolean includingDirectory) throws IOException {
Stack<String> stack = new Stack<String>();
List<String> list = new ArrayList<String>();
// If it's a file, just return itself
if (directory.isFile()) {
if (directory.canRead()) {
list.add(directory.getName());
}
} else {
// Traverse the directory in width-first manner, no-recursively
String root = directory.getParent();
stack.push(directory.getName());
while (!stack.empty()) {
String current = (String) stack.pop();
File curDir = new File(root, current);
String[] fileList = curDir.list();
if (fileList != null) {
for (String entry : fileList) {
File file = new File(curDir, entry);
if (file.isFile()) {
if (file.canRead()) {
list.add(current + File.separator + entry);
} else {
throw new IOException("Can't read file: " + file.getPath());
}
} else if (file.isDirectory()) {
if (includingDirectory) {
list.add(current + File.separator + entry);
}
stack.push(current + File.separator + file.getName());
} else {
throw new IOException("Unknown entry: " + file.getPath());
}
}
}
}
}
return list;
}
/**
* This method deletes a given directory with its content.
*
* @param srcPath {@link File}
* @param deleteSrcDir boolean
*/
public static void deleteDirectoryAndContentsRecursive(File srcPath, boolean deleteSrcDir) {
if (srcPath.exists()) {
File[] files = srcPath.listFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
if (files[index].isDirectory()) {
deleteDirectoryAndContentsRecursive(files[index], true);
}
files[index].delete();
}
}
}
if (deleteSrcDir) {
srcPath.delete();
}
}
/**
* This method deletes a given directory with its content.
*
* @param srcPath {@link File}
*/
public static void deleteDirectoryAndContentsRecursive(File srcPath) {
deleteDirectoryAndContentsRecursive(srcPath, true);
}
/**
* This method unzips a given directory with its content.
*
* @param zipFilepath {@link File}
* @param destinationDir {@link String}
*/
public static void unzip(File zipFile, String destinationDir) {
File destinationFile = new File(destinationDir);
if (destinationFile.exists()) {
destinationFile.delete();
}
/**
* Expander class.
*/
final class Expander extends Expand {
private static final String UNZIP = "unzip";
public Expander() {
super();
setProject(new Project());
getProject().init();
setTaskType(UNZIP);
setTaskName(UNZIP);
}
}
Expander expander = new Expander();
expander.setSrc(zipFile);
expander.setDest(destinationFile);
expander.execute();
}
/**
* To get File Name of required Type from Folder.
*
* @param dirLocation {@link String}
* @param fileExtOrFolderName {@link String}
* @return {@link String}
*/
public static String getFileNameOfTypeFromFolder(String dirLocation, String fileExtOrFolderName) {
String fileOrFolderName = EMPTY_STRING;
File[] listFiles = new File(dirLocation).listFiles();
if (listFiles != null) {
for (int index = 0; index < listFiles.length; index++) {
if (listFiles[index].getName().toLowerCase(Locale.getDefault()).indexOf(
fileExtOrFolderName.toLowerCase(Locale.getDefault())) > -1) {
fileOrFolderName = listFiles[index].getPath();
break;
}
}
}
return fileOrFolderName;
}
/**
* To create Thread Pool Lock File.
*
* @param batchInstanceIdentifier {@link String}
* @param lockFolderPath {@link String}
* @param pluginFolderName {@link String}
* @throws IOException in case of error
*/
public static void createThreadPoolLockFile(String batchInstanceIdentifier, String lockFolderPath, String pluginFolderName)
throws IOException {
File lockFolder = new File(lockFolderPath);
if (!lockFolder.exists()) {
lockFolder.mkdir();
}
File _lockFile = new File(lockFolderPath + File.separator + pluginFolderName);
boolean isCreateSuccess = _lockFile.createNewFile();
if (!isCreateSuccess) {
LOGGER.error("Unable to create lock file for threadpool for pluginName:" + pluginFolderName);
}
}
/**
* To delete Thread Pool Lock File.
*
* @param batchInstanceIdentifier {@link String}
* @param lockFolderPath {@link String}
* @param pluginFolderName {@link String}
* @throws IOException in case of error
*/
public static void deleteThreadPoolLockFile(String batchInstanceIdentifier, String lockFolderPath, String pluginFolderName)
throws IOException {
File _lockFile = new File(lockFolderPath + File.separator + pluginFolderName);
boolean isDeleteSuccess = _lockFile.delete();
if (!isDeleteSuccess) {
LOGGER.error("Unable to delete lock file for threadpool for pluginName:" + pluginFolderName);
}
}
/**
* To move Directory and Contents.
* @param sourceDirPath {@link String}
* @param destDirPath {@link String}
* @return boolean
*/
public static boolean moveDirectoryAndContents(String sourceDirPath, String destDirPath) {
boolean success = true;
File sourceDir = new File(sourceDirPath);
File destDir = new File(destDirPath);
if (sourceDir.exists() && destDir.exists()) {
// delete the directory if it already exists
deleteDirectoryAndContentsRecursive(destDir);
success = sourceDir.renameTo(destDir);
}
return success;
}
/**
* To delete Selected Files from Directory.
* @param directoryPath {@link String}
* @param filesList List<String>
*/
public static void deleteSelectedFilesFromDirectory(String directoryPath, List<String> filesList) {
File directory = new File(directoryPath);
if (directory != null && directory.exists()) {
for (File file : directory.listFiles()) {
if (filesList == null || filesList.isEmpty() || !filesList.contains(file.getName())) {
file.delete();
}
}
}
}
/**
* This API is creating file if not exists.
*
* @param filePath {@link String}
* @return isFileCreated
*/
public static boolean createFile(String filePath) {
boolean isFileCreated = false;
File file = new File(filePath);
if (file.exists()) {
isFileCreated = true;
} else {
try {
isFileCreated = file.createNewFile();
} catch (IOException e) {
LOGGER.error("Unable to create file" + e.getMessage(), e);
}
}
return isFileCreated;
}
/**
* This method append the src file to dest file.
*
* @param srcFile {@link File}
* @param destFile {@link File}
* @throws IOException in case of error
*/
public static void appendFile(File srcFile, File destFile) throws IOException {
InputStream inputSream = null;
FileOutputStream out = null;
try {
inputSream = new FileInputStream(srcFile);
out = new FileOutputStream(destFile, true);
byte[] buf = new byte[UtilConstants.BUF_CONST];
int len = inputSream.read(buf);
while (len > 0) {
out.write(buf, 0, len);
len = inputSream.read(buf);
}
} finally {
IOUtils.closeQuietly(inputSream);
}
}
/**
* This API merging the input files into single output file.
*
* @param srcFiles {@link String}
* @param destFile {@link String}
* @return boolean
* @throws IOException in case of error
*/
public static boolean mergeFilesIntoSingleFile(List<String> srcFiles, String destFile) throws IOException {
boolean isFileMerged = false;
File outputFile = new File(destFile);
for (String string : srcFiles) {
File inputFile = new File(string);
appendFile(inputFile, outputFile);
}
return isFileMerged;
}
/**
* To get output Stream from Zip.
*
* @param zipName {@link String}
* @param fileName {@link String}
* @return {@link InputStream}
* @throws FileNotFoundException in case of error
* @throws IOException in case of error
*/
public static OutputStream getOutputStreamFromZip(final String zipName, final String fileName) throws FileNotFoundException,
IOException {
ZipOutputStream stream = null;
stream = new ZipOutputStream(new FileOutputStream(new File(zipName + ZIP_FILE_EXT)));
ZipEntry zipEntry = new ZipEntry(fileName);
stream.putNextEntry(zipEntry);
return stream;
}
/**
* To get Input Stream from Zip.
*
* @param zipName {@link String}
* @param fileName {@link String}
* @return {@link InputStream}
* @throws FileNotFoundException in case of error
* @throws IOException in case of error
*/
public static InputStream getInputStreamFromZip(final String zipName, final String fileName) throws FileNotFoundException,
IOException {
ZipFile zipFile = new ZipFile(zipName + ZIP_FILE_EXT);
// InputStream inputStream = zipFile.getInputStream(zipFile.getEntry(fileName));
return zipFile.getInputStream(zipFile.getEntry(fileName));
}
/**
* This method checks for the existence of zip files.
*
* @param zipFilePath {@link String}
* @return boolean
*/
public static boolean isZipFileExists(String zipFilePath) {
File file = new File(zipFilePath + ZIP_FILE_EXT);
return file.exists();
}
/**
* This method returns the updated file name if file with same already exists in the parent folder.
*
* @param fileName {@link String}
* @param parentFolder {@link File}
* @return {@link String}
*/
public static String getUpdatedFileNameForDuplicateFile(String fileName, File parentFolder) {
return getUpdatedFileNameForDuplicateFile(fileName, parentFolder, -1);
}
/**
* This method returns the updated file name if file with same already exists in the parent folder.
*
* @param fileName {@link String}
* @param parentFolder {@link File}
* @param fileCount {@link Integer} Specifies the count to be appended in the file name if file with same name already exists.
* (Initially -1 is passed when method is called first time for a file)
* @return {@link String}
*/
public static String getUpdatedFileNameForDuplicateFile(String fileName, File parentFolder, int fileCount) {
String updatedFileName = null;
if (fileCount < 0) {
updatedFileName = fileName;
} else {
updatedFileName = fileName + UtilConstants.UNDERSCORE + fileCount;
}
if (isFileExists(updatedFileName, parentFolder)) {
updatedFileName = getUpdatedFileNameForDuplicateFile(fileName, parentFolder, fileCount + 1);
}
return updatedFileName;
}
/**
* This method checks if the file with specific filer name already exists in the the parent folder.
*
* @param fileName {@link String}
* @param parentFolder {@link File}
* @return boolean
*/
public static boolean isFileExists(String fileName, File parentFolder) {
LOGGER.info("checking if file with name " + fileName + " exists in folder " + parentFolder.getAbsolutePath());
File[] fileArray = parentFolder.listFiles();
String existingFileName = "";
int extensionIndex = 0;
boolean fileExists = false;
if (fileArray != null) {
for (File file : fileArray) {
existingFileName = file.getName();
extensionIndex = existingFileName.indexOf(UtilConstants.DOT);
extensionIndex = extensionIndex == -1 ? existingFileName.length() : extensionIndex;
if (existingFileName.substring(0, extensionIndex).equals(fileName)) {
LOGGER.info("file exists with name " + fileName + " in folder " + parentFolder.getAbsolutePath());
fileExists = true;
break;
}
}
}
return fileExists;
}
/**
* To clean up Directory.
* @param srcPath {@link File}
* @return boolean
*/
public static boolean cleanUpDirectory(File srcPath) {
boolean isDeleted = true;
if (srcPath.exists()) {
File[] files = srcPath.listFiles();
if (files != null) {
for (int index = 0; index < files.length; index++) {
if (files[index].isDirectory()) {
isDeleted &= cleanUpDirectory(files[index]);
}
isDeleted &= files[index].delete();
// files[index].
}
}
}
isDeleted &= srcPath.delete();
return isDeleted;
}
/**
* To create OS Independent Path.
* @param path {@link String}
* @return {@link String}
*/
public static String createOSIndependentPath(String path) {
StringTokenizer tokenizer = new StringTokenizer(path, "/\\");
StringBuffer OSIndependentfilePath = new StringBuffer();
boolean isFirst = true;
while (tokenizer.hasMoreTokens()) {
if (!isFirst) {
OSIndependentfilePath.append(File.separator);
}
OSIndependentfilePath.append(tokenizer.nextToken());
isFirst = false;
}
return OSIndependentfilePath.toString();
}
/**
* This API moves file from source path to destination path by creating destination path if it does not exists.
*
* @param sourcePath source path of file to be moved
* @param destinationPath destination path where file has to be moved
* @return operation success
* @throws IOException if error occurs
* @throws Exception error occurred while copying file from source to destination path
*/
public static boolean moveFile(String sourcePath, String destinationPath) throws IOException {
boolean success = false;
if (null != sourcePath && null != destinationPath) {
File sourceFile = new File(sourcePath);
File destinationFile = new File(destinationPath);
// Delete the file if already exists
if (destinationFile.exists()) {
deleteDirectoryAndContentsRecursive(destinationFile, true);
}
// Create directories for destination path
if (destinationFile.getParentFile() != null) {
destinationFile.getParentFile().mkdirs();
}
// Moving file from source path to destination path
if (sourceFile.exists() && sourceFile.canWrite()) {
success = sourceFile.renameTo(destinationFile);
}
// Copy file from source to destination path when the source file cannot be deleted
if (!success && sourceFile.exists() && !sourceFile.canWrite()) {
success = true;
if (sourceFile.isDirectory()) {
copyDirectoryWithContents(sourceFile, destinationFile);
} else {
copyFile(sourceFile, destinationFile);
}
}
}
return success;
}
/**
* This method checks whether the given file is a directory or file.
*
* @param folderDetail - file to be checked
* @return boolean
*/
public static boolean checkForFile(String filePath) {
boolean isFile = false;
if (null != filePath) {
File file = new File(filePath);
isFile = file.isFile();
}
return isFile;
}
/**
* Method to replace invalid characters from file name {fileName} by the replace character specified by admin.
*
* @param fileName name of the file from which invalid characters are to be replaced.
* @param invalidChars array of invalid characters which are to be replaced.
* @return {@link String}
*/
public static String replaceInvalidFileChars(final String fileName) {
String finalReplaceChar = IUtilCommonConstants.UNDER_SCORE;
String[] invalidChars = IUtilCommonConstants.INVALID_FILE_EXTENSIONS.split(IUtilCommonConstants.INVALID_CHAR_SEPARATOR);
LOGGER.info("Entering removeInvalidFileChars method");
String updatedFileName = fileName;
if (fileName != null && !fileName.isEmpty() && invalidChars != null && invalidChars.length > UtilConstants.ZERO) {
if (finalReplaceChar == null || finalReplaceChar.isEmpty()) {
LOGGER.info("Replace character not specified. Using default character '-' as a replace character.");
finalReplaceChar = DEFAULT_REPLACE_CHAR;
}
for (String invalidChar : invalidChars) {
if (finalReplaceChar.equals(invalidChar)) {
LOGGER
.info("Replace character not specified or an invalid character. Using default character '-' as a replace character.");
finalReplaceChar = DEFAULT_REPLACE_CHAR;
}
updatedFileName = updatedFileName.replace(invalidChar, finalReplaceChar);
}
}
LOGGER.info("Exiting removeInvalidFileChars method");
return updatedFileName;
}
/**
* API to take read write lock on the folder represented by the given folder path.
*
* @param folderPath {@link String}
* @return true if lock is successfully acquired, else false
*/
public static boolean lockFolder(String folderPath) {
String lockFileName = folderPath + File.separator + "_lock";
boolean isLockAcquired = true;
try {
File lockFile = new File(lockFileName);
FileChannel fileChannel = new RandomAccessFile(lockFile, "rw").getChannel();
FileLock lock = fileChannel.lock();
try {
if (lock == null) {
lock = fileChannel.tryLock();
}
} catch (OverlappingFileLockException e) {
LOGGER.trace("File is already locked in this thread or virtual machine");
}
if (lock == null) {
LOGGER.trace("File is already locked in this thread or virtual machine");
}
} catch (Exception e) {
LOGGER.error("Unable to aquire lock on file : " + lockFileName, e);
isLockAcquired = false;
}
return isLockAcquired;
}
/**
* API to get the size of a file in mega bytes.
*
* @param file {@link File} file whose size is to be calculated
* @return
*/
public static double getSizeInMB(File file) {
double sizeInMb = 0.0;
if (file != null && file.exists()) {
sizeInMb = file.length() * 1.0 / BYTES_IN_ONE_MB;
}
return sizeInMb;
}
}
| kuzavas/ephesoft | dcma-util/src/main/java/com/ephesoft/dcma/util/FileUtils.java | Java | agpl-3.0 | 38,031 |
<?php
/**
* @author Joas Schilling <coding@schilljs.com>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
*
* @copyright Copyright (c) 2016, ownCloud GmbH.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCP\Mail;
use OC\Mail\Message;
/**
* Class IMailer provides some basic functions to create a mail message that can be used in combination with
* \OC\Mail\Message.
*
* Example usage:
*
* $mailer = \OC::$server->getMailer();
* $message = $mailer->createMessage();
* $message->setSubject('Your Subject');
* $message->setFrom(['cloud@domain.org' => 'ownCloud Notifier']);
* $message->setTo(['recipient@domain.org' => 'Recipient']);
* $message->setPlainBody('The message text');
* $message->setHtmlBody('The <strong>message</strong> text');
* $mailer->send($message);
*
* This message can then be passed to send() of \OC\Mail\Mailer
*
* @package OCP\Mail
* @since 8.1.0
*/
interface IMailer {
/**
* Creates a new message object that can be passed to send()
*
* @return Message
* @since 8.1.0
*/
public function createMessage();
/**
* Send the specified message. Also sets the from address to the value defined in config.php
* if no-one has been passed.
*
* @param Message $message Message to send
* @return string[] Array with failed recipients. Be aware that this depends on the used mail backend and
* therefore should be considered
* @throws \Exception In case it was not possible to send the message. (for example if an invalid mail address
* has been supplied.)
* @since 8.1.0
*/
public function send(Message $message);
/**
* Checks if an e-mail address is valid
*
* @param string $email Email address to be validated
* @return bool True if the mail address is valid, false otherwise
* @since 8.1.0
*/
public function validateMailAddress($email);
}
| IljaN/core | lib/public/Mail/IMailer.php | PHP | agpl-3.0 | 2,482 |
<?php
/**
* Copyright (C) 2016 Piotr Janczyk
*
* This file is part of lo1olkusz unofficial app - website.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace pjanczyk\lo1olkusz\Cron;
use pjanczyk\lo1olkusz\Database;
use pjanczyk\lo1olkusz\Config;
use pjanczyk\lo1olkusz\DAO\LuckyNumberRepository;
use pjanczyk\lo1olkusz\DAO\ReplacementsRepository;
use pjanczyk\lo1olkusz\SimpleHtmlDom\SimpleHtmlDom;
class CronTask
{
const LUCKY_NUMBER_URL = 'http://lo1.olkusz.pl';
const REPLACEMENT_URL = 'https://lo1olkusz.edu.pl/netstudent/replacements.php';
public function run()
{
Database::init(Config::getInstance()->getDatabaseConfig());
$this->updateLuckyNumbers();
$this->updateReplacements();
echo "done\n";
}
private function updateLuckyNumbers()
{
$url = self::LUCKY_NUMBER_URL;
$dom = SimpleHtmlDom::fromUrl($url);
if ($dom === false) {
echo "cannot get {$url}\n";
return;
}
$model = new LuckyNumberRepository;
$parser = new LuckyNumberParser;
$remote = $parser->getLuckyNumber($dom);
$this->logErrors('LuckyNumberParser', $parser->getErrors());
if ($remote !== null) {
$local = $model->getByDate($remote->date);
if ($local === null || $remote->value !== $local->value) {
$model->setValue($remote->date, $remote->value);
echo "updated ln/{$remote->date}\n";
}
}
}
private function updateReplacements()
{
$url = self::REPLACEMENT_URL;
$dom = SimpleHtmlDom::fromUrl($url);
if ($dom === false) {
echo "cannot get {$url}\n";
return;
}
$model = new ReplacementsRepository;
$parser = new ReplacementsParser;
$remoteList = $parser->getReplacements($dom);
$this->logErrors('ReplacementsParser', $parser->getErrors());
if ($remoteList !== null) {
foreach ($remoteList as $remote) {
$local = $model->getByClassAndDate($remote->class, $remote->date);
if ($local === null || $remote->value !== $local->value) {
$model->setValue($remote->class, $remote->date, $remote->value);
echo "updated replacements/{$remote->date}/{$remote->class}\n";
}
}
}
}
private function logErrors($tag, $errors)
{
if (count($errors) > 0) {
echo $tag . ":\n";
foreach ($errors as $error) {
echo ' ' . $error . "\n";
}
}
}
} | pjanczyk/lo1olkusz-website | app/code/src/Cron/CronTask.php | PHP | agpl-3.0 | 3,232 |
import click
from lc8_download.lc8 import Downloader
@click.command('lc8_download')
@click.argument('scene', type=str, metavar='<scene>')
@click.option('-b', type=str, help="""Bands to be downloaded. Use commas as
delimiter. Example: '-b 2,3,4,BQA'""")
@click.option('--all', is_flag=True, help="Download all bands and metadata")
@click.option('path', '--path', default=None,
type=click.Path(file_okay=False, writable=True),
help="Directory where the files will be saved. Default: ~/landsat/")
@click.option('--metadata', is_flag=True, help="Download scene metadata file.")
def cli(scene, b, path, metadata, all):
lc8 = Downloader(scene)
if all:
bands = list(range(1, 12)) + ['BQA']
metadata = True
else:
bands = []
for band in b.split(','):
if band != 'BQA':
band = int(band)
bands.append(band)
lc8.download(bands, path, metadata)
| ibamacsr/lc8_download | lc8_download/scripts/cli.py | Python | agpl-3.0 | 937 |
const patron = require('patron.js');
class Remove extends patron.Command {
constructor() {
super({
names: ['remove', 'r'],
groupName: 'fun',
description: 'Deletes the command',
guildOnly: false,
args: [
new patron.Argument({
name: 'text',
key: 'text',
type: 'string',
example: 'No way hoe zay',
remainder: true
})
]
});
}
async run(msg, args) {
//Left blank, the message is deleted by the Command service
}
}
module.exports = new Remove();
| VapidSlay/selfbot | src/commands/Fun/remove.js | JavaScript | agpl-3.0 | 565 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
global $current_user;
$focus = new Email();
// Get Group User IDs
$groupUserQuery = 'SELECT name, group_id FROM inbound_email ie INNER JOIN users u ON (ie.group_id = u.id AND u.is_group = 1)';
$groupUserQuery = 'SELECT group_id FROM inbound_email ie';
$groupUserQuery .= ' INNER JOIN team_memberships tm ON ie.team_id = tm.team_id';
$groupUserQuery .= ' INNER JOIN teams ON ie.team_id = teams.id AND teams.private = 0';
$groupUserQuery .= ' WHERE tm.user_id = \''.$current_user->id.'\'';
_pp($groupUserQuery);
$r = $focus->db->query($groupUserQuery);
$groupIds = '';
while($a = $focus->db->fetchByAssoc($r)) {
$groupIds .= "'".$a['group_id']."', ";
}
$groupIds = substr($groupIds, 0, (strlen($groupIds) - 2));
$query = 'SELECT emails.id AS id FROM emails';
$query .= ' LEFT JOIN team_memberships ON emails.team_id = team_memberships.team_id';
$query .= ' LEFT JOIN teams ON emails.team_id = teams.id ';
$query .= " WHERE emails.deleted = 0 AND emails.status = 'unread' AND emails.assigned_user_id IN ({$groupIds})";
if(!$current_user->is_admin) {
$query .= " AND team_memberships.user_id = '{$current_user->id}'";
}
//$query .= ' LIMIT 1';
//_ppd($query);
$r2 = $focus->db->query($query);
$count = 0;
$a2 = $focus->db->fetchByAssoc($r2);
$focus->retrieve($a2['id']);
$focus->assigned_user_id = $current_user->id;
$focus->save();
if(!empty($a2['id'])) {
header('Location: index.php?module=Emails&action=ListView&type=inbound&assigned_user_id='.$current_user->id);
} else {
header('Location: index.php?module=Emails&action=ListView&show_error=true&type=inbound&assigned_user_id='.$current_user->id);
}
?>
| harish-patel/ecrm | modules/Emails/Grab.php | PHP | agpl-3.0 | 3,432 |
import {
event as currentEvent,
selectAll as d3SelectAll,
select as d3Select,
mouse as currentMouse,
} from 'd3-selection'
import { NODE_RADIUS } from '../constants'
const nodeRe = /node(\d*)_(.*)/
const getNodeIdFromElementId = (elementId) => (
[
elementId.replace(nodeRe, "$1"),
elementId.replace(nodeRe, "$2")
]
)
export const createOuterDrag = (simulation) => (actions) => {
return {
dragstart: function() {
const mouseXy = currentMouse(this.container.node())
this.graph.dragLine
.classed("hidden", false)
.attr("d", `M ${d.x} ${d.y} L ${mouseXy[0]} ${mouseXy[1]}`);
},
drag: function() {
const mouseXy = currentMouse(this.container.node())
this.graph.dragLine
.attr("d", `M ${d.x} ${d.y} L ${mouseXy[0]} ${mouseXy[1]}`);
const nodeSelection = d3SelectAll('.node')
const prevHoveredNodes = d3SelectAll('.node-hovered')
// back to their default color again
prevHoveredNodes.select('circle')
prevHoveredNodes.classed('node-hovered', false)
nodeSelection.each(node => {
if (node === d) return
const distanceToNode = Math.sqrt((node.x - mouseXy[0])**2 + (node.y - mouseXy[1])**2)
if (distanceToNode < node.radius) {
// change background color
d3Select(`#node-${node.id}`)
.classed('node-hovered', true)
.select('circle')
}
})
},
dragend: function() {
const mouseXy = currentMouse(this.container.node())
const nodeSelection = d3SelectAll('.node')
const { nodes } = this.props
this.graph.dragLine.classed("hidden", true)
const prevHoveredNodes = d3SelectAll('.node-hovered')
// back to their default color again
prevHoveredNodes.select('circle')
prevHoveredNodes.classed('node-hovered', false)
nodeSelection.each(node => {
if (node.id === d.id) return
const distanceToNode = Math.sqrt((node.x - mouseXy[0])**2 + (node.y - mouseXy[1])**2)
if (distanceToNode < node.radius) {
// create an edge from this node to otherNode
return actions.connect(d.id, node.id)
}
})
}
}
}
export const createInnerDrag = (self) => (actions) => {
let startX = null
let startY = null;
let dragStarted = false;
let nodes = null;
return {
dragstart: function() {
/*
* Freeze the graph
*/
const [ index, id ] = getNodeIdFromElementId(d3Select(this).attr('id'))
if (id === self.props.focusNodeId) {
return;
}
dragStarted = true;
startX = currentEvent.x
startY = currentEvent.y
// nodes = self.tree.nodes(d)
},
drag: function(d) {
if (!dragStarted) {
return;
}
const nodeElement = d3Select(this)
const [ index, id ] = getNodeIdFromElementId(nodeElement.attr('id'))
const node = self.nodesById[id]
// nodeElement.attr('transform', `translate(${currentEvent.x}, ${currentEvent.y})`)
self.props.dragElement(
id,
index,
currentEvent.y,
currentEvent.x,
currentEvent.y - startY, // dy from dragStart
currentEvent.x - startX, // dx from dragStart
)
// // TODO: panning (move with screen when dragging to edges - 2018-02-02
// const nodeSelection = d3SelectAll('.node')
// const prevHoveredNodes = d3SelectAll('.node-hovered')
// // back to their default color again
// prevHoveredNodes.select('circle')
// prevHoveredNodes.classed('node-hovered', false)
// nodeSelection.each(node => {
// if (node === d) return
// const distanceToNode = Math.sqrt((node.x - d.x)**2 + (node.y - d.y)**2)
// if (distanceToNode < node.radius) {
// // change background color
// d3Select(`#node-${node.id}`)
// .classed('node-hovered', true)
// .select('circle')
// }
// })
},
dragend: function() {
/*
* Create an edge to all nodes which are being hovered over
*/
if (!dragStarted) {
return;
}
dragStarted = false
const nodeElement = d3Select(this)
const [ index, id ] = getNodeIdFromElementId(nodeElement.attr('id'))
const node = self.nodesById[id]
const nodeSelection = d3SelectAll('.node-below')
self.props.dragElement()
console.log(index, id)
nodeSelection.each(function() {
// undo fixed state as set in dragstart
const currentNodeElement = d3Select(this)
const [ currentIndex, currentId ] = getNodeIdFromElementId(currentNodeElement.attr('id'))
const currentNode = self.nodesById[currentId]
if (id === currentId) {
return;
}
// TODO: x and y are switched here for currentNode - 2018-02-02
const distanceToNode = Math.sqrt((currentNode.y - currentEvent.x)**2 + (currentNode.x - currentEvent.y)**2)
if (distanceToNode < NODE_RADIUS) {
if (node.parent && node.parent.data.id === currentNode.data.id) {
// dragged over the already existing parent
return;
}
// move this node to the abstraction that is hovered over
// TODO: need a method for getting the currently visible abstraction chain
return actions.moveToAbstraction(
node.parent && node.parent.data.id,
node.data.id,
currentNode.data.id, //TODO: here it is data and before not, do something about this...
)
}
})
}
}
}
| bryanph/Geist | client/app/components/graphs/ExploreGraph/drag.js | JavaScript | agpl-3.0 | 6,601 |
#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Addison Arches.
#
# Addison Arches is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Addison Arches is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Addison Arches. If not, see <http://www.gnu.org/licenses/>.
from collections import namedtuple
Action = namedtuple(
"Action", ["name", "rel", "typ", "ref", "method", "parameters", "prompt"])
Parameter = namedtuple("Parameter", ["name", "required", "regex", "values", "tip"])
class View:
def __init__(self, obj, actions={}, *args, **kwargs):
super().__init__(*args, **kwargs)
self.obj = obj
self.type = obj.__class__.__name__
self.fields = obj._fields
self.actions = actions
def rejects(self, action:str):
try:
data = vars(self.obj)
except TypeError:
data = self.obj._asdict()
action = self.actions[action]
missing = [i for i in action.parameters
if i.required and i.name not in data]
missing = missing or [
i for i in action.parameters if i.name in data
and i.values and data[i.name] not in i.values]
missing = missing or [
i for i in action.parameters
if i.name in data and not i.regex.match(str(data[i.name]))]
return missing
| tundish/addisonarches | addisonarches/web/hateoas.py | Python | agpl-3.0 | 1,827 |
<?php
//Pau: Google Analytics asynchronous tracking code
//If we are not running on a local machine
if (!preg_match('/localhost/', $_SERVER['HTTP_HOST'])):
//And we are not in a UPF computer
$excludedIPs = array (
'^193\.145\.56\.241$',
'^193\.145\.56\.242$',
'^193\.145\.56\.243$',
'^193\.145\.56\.244$',
'^193\.145\.39', // Last part can be anything, WiFi connections from the UPF
'^127\.0\.0', //Localhost
);
$regexp = implode('|', $excludedIPs);
//if (!preg_match("/($regexp)/", $_SERVER['REMOTE_ADDR'])):
?>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36286106-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<?php
//endif;
endif;
?>
| GTI-Learning/LdShake | views/default/page_elements/analytics.php | PHP | agpl-3.0 | 1,065 |
# -*- coding: utf-8 -*-
""" Tests for student account views. """
import re
from unittest import skipUnless
from urllib import urlencode
import json
import mock
import ddt
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core import mail
from django.test.utils import override_settings
from util.testing import UrlResetMixin
from third_party_auth.tests.testutil import simulate_running_pipeline
from openedx.core.djangoapps.user_api.api import account as account_api
from openedx.core.djangoapps.user_api.api import profile as profile_api
from xmodule.modulestore.tests.django_utils import (
ModuleStoreTestCase, mixed_store_config
)
from xmodule.modulestore.tests.factories import CourseFactory
from student.tests.factories import CourseModeFactory
MODULESTORE_CONFIG = mixed_store_config(settings.COMMON_TEST_DATA_ROOT, {}, include_xml=False)
@ddt.ddt
class StudentAccountUpdateTest(UrlResetMixin, TestCase):
""" Tests for the student account views that update the user's account information. """
USERNAME = u"heisenberg"
ALTERNATE_USERNAME = u"walt"
OLD_PASSWORD = u"ḅḷüëṡḳÿ"
NEW_PASSWORD = u"🄱🄸🄶🄱🄻🅄🄴"
OLD_EMAIL = u"walter@graymattertech.com"
NEW_EMAIL = u"walt@savewalterwhite.com"
INVALID_ATTEMPTS = 100
INVALID_EMAILS = [
None,
u"",
u"a",
"no_domain",
"no+domain",
"@",
"@domain.com",
"test@no_extension",
# Long email -- subtract the length of the @domain
# except for one character (so we exceed the max length limit)
u"{user}@example.com".format(
user=(u'e' * (account_api.EMAIL_MAX_LENGTH - 11))
)
]
INVALID_KEY = u"123abc"
@mock.patch.dict(settings.FEATURES, {'ENABLE_NEW_DASHBOARD': True})
def setUp(self):
super(StudentAccountUpdateTest, self).setUp("student_account.urls")
# Create/activate a new account
activation_key = account_api.create_account(self.USERNAME, self.OLD_PASSWORD, self.OLD_EMAIL)
account_api.activate_account(activation_key)
# Login
result = self.client.login(username=self.USERNAME, password=self.OLD_PASSWORD)
self.assertTrue(result)
def test_index(self):
response = self.client.get(reverse('account_index'))
self.assertContains(response, "Student Account")
def test_change_email(self):
response = self._change_email(self.NEW_EMAIL, self.OLD_PASSWORD)
self.assertEquals(response.status_code, 200)
# Verify that the email associated with the account remains unchanged
profile_info = profile_api.profile_info(self.USERNAME)
self.assertEquals(profile_info['email'], self.OLD_EMAIL)
# Check that an email was sent with the activation key
self.assertEqual(len(mail.outbox), 1)
self._assert_email(
mail.outbox[0],
[self.NEW_EMAIL],
u"Email Change Request",
u"There was recently a request to change the email address"
)
# Retrieve the activation key from the email
email_body = mail.outbox[0].body
result = re.search('/email/confirmation/([^ \n]+)', email_body)
self.assertIsNot(result, None)
activation_key = result.group(1)
# Attempt to activate the email
response = self.client.get(reverse('email_change_confirm', kwargs={'key': activation_key}))
self.assertEqual(response.status_code, 200)
# Verify that the email was changed
profile_info = profile_api.profile_info(self.USERNAME)
self.assertEquals(profile_info['email'], self.NEW_EMAIL)
# Verify that notification emails were sent
self.assertEqual(len(mail.outbox), 2)
self._assert_email(
mail.outbox[1],
[self.OLD_EMAIL, self.NEW_EMAIL],
u"Email Change Successful",
u"You successfully changed the email address"
)
def test_email_change_wrong_password(self):
response = self._change_email(self.NEW_EMAIL, "wrong password")
self.assertEqual(response.status_code, 401)
def test_email_change_request_no_user(self):
# Patch account API to raise an internal error when an email change is requested
with mock.patch('student_account.views.account_api.request_email_change') as mock_call:
mock_call.side_effect = account_api.AccountUserNotFound
response = self._change_email(self.NEW_EMAIL, self.OLD_PASSWORD)
self.assertEquals(response.status_code, 400)
def test_email_change_request_email_taken_by_active_account(self):
# Create/activate a second user with the new email
activation_key = account_api.create_account(self.ALTERNATE_USERNAME, self.OLD_PASSWORD, self.NEW_EMAIL)
account_api.activate_account(activation_key)
# Request to change the original user's email to the email now used by the second user
response = self._change_email(self.NEW_EMAIL, self.OLD_PASSWORD)
self.assertEquals(response.status_code, 409)
def test_email_change_request_email_taken_by_inactive_account(self):
# Create a second user with the new email, but don't active them
account_api.create_account(self.ALTERNATE_USERNAME, self.OLD_PASSWORD, self.NEW_EMAIL)
# Request to change the original user's email to the email used by the inactive user
response = self._change_email(self.NEW_EMAIL, self.OLD_PASSWORD)
self.assertEquals(response.status_code, 200)
@ddt.data(*INVALID_EMAILS)
def test_email_change_request_email_invalid(self, invalid_email):
# Request to change the user's email to an invalid address
response = self._change_email(invalid_email, self.OLD_PASSWORD)
self.assertEquals(response.status_code, 400)
def test_email_change_confirmation(self):
# Get an email change activation key
activation_key = account_api.request_email_change(self.USERNAME, self.NEW_EMAIL, self.OLD_PASSWORD)
# Follow the link sent in the confirmation email
response = self.client.get(reverse('email_change_confirm', kwargs={'key': activation_key}))
self.assertContains(response, "Email change successful")
# Verify that the email associated with the account has changed
profile_info = profile_api.profile_info(self.USERNAME)
self.assertEquals(profile_info['email'], self.NEW_EMAIL)
def test_email_change_confirmation_invalid_key(self):
# Visit the confirmation page with an invalid key
response = self.client.get(reverse('email_change_confirm', kwargs={'key': self.INVALID_KEY}))
self.assertContains(response, "Something went wrong")
# Verify that the email associated with the account has not changed
profile_info = profile_api.profile_info(self.USERNAME)
self.assertEquals(profile_info['email'], self.OLD_EMAIL)
def test_email_change_confirmation_email_already_exists(self):
# Get an email change activation key
email_activation_key = account_api.request_email_change(self.USERNAME, self.NEW_EMAIL, self.OLD_PASSWORD)
# Create/activate a second user with the new email
account_activation_key = account_api.create_account(self.ALTERNATE_USERNAME, self.OLD_PASSWORD, self.NEW_EMAIL)
account_api.activate_account(account_activation_key)
# Follow the link sent to the original user
response = self.client.get(reverse('email_change_confirm', kwargs={'key': email_activation_key}))
self.assertContains(response, "address you wanted to use is already used")
# Verify that the email associated with the original account has not changed
profile_info = profile_api.profile_info(self.USERNAME)
self.assertEquals(profile_info['email'], self.OLD_EMAIL)
def test_email_change_confirmation_internal_error(self):
# Get an email change activation key
activation_key = account_api.request_email_change(self.USERNAME, self.NEW_EMAIL, self.OLD_PASSWORD)
# Patch account API to return an internal error
with mock.patch('student_account.views.account_api.confirm_email_change') as mock_call:
mock_call.side_effect = account_api.AccountInternalError
response = self.client.get(reverse('email_change_confirm', kwargs={'key': activation_key}))
self.assertContains(response, "Something went wrong")
def test_email_change_request_missing_email_param(self):
response = self._change_email(None, self.OLD_PASSWORD)
self.assertEqual(response.status_code, 400)
def test_email_change_request_missing_password_param(self):
response = self._change_email(self.OLD_EMAIL, None)
self.assertEqual(response.status_code, 400)
@skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in LMS')
def test_password_change(self):
# Request a password change while logged in, simulating
# use of the password reset link from the account page
response = self._change_password()
self.assertEqual(response.status_code, 200)
# Check that an email was sent
self.assertEqual(len(mail.outbox), 1)
# Retrieve the activation link from the email body
email_body = mail.outbox[0].body
result = re.search('(?P<url>https?://[^\s]+)', email_body)
self.assertIsNot(result, None)
activation_link = result.group('url')
# Visit the activation link
response = self.client.get(activation_link)
self.assertEqual(response.status_code, 200)
# Submit a new password and follow the redirect to the success page
response = self.client.post(
activation_link,
# These keys are from the form on the current password reset confirmation page.
{'new_password1': self.NEW_PASSWORD, 'new_password2': self.NEW_PASSWORD},
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Your password has been set.")
# Log the user out to clear session data
self.client.logout()
# Verify that the new password can be used to log in
result = self.client.login(username=self.USERNAME, password=self.NEW_PASSWORD)
self.assertTrue(result)
# Try reusing the activation link to change the password again
response = self.client.post(
activation_link,
{'new_password1': self.OLD_PASSWORD, 'new_password2': self.OLD_PASSWORD},
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "The password reset link was invalid, possibly because the link has already been used.")
self.client.logout()
# Verify that the old password cannot be used to log in
result = self.client.login(username=self.USERNAME, password=self.OLD_PASSWORD)
self.assertFalse(result)
# Verify that the new password continues to be valid
result = self.client.login(username=self.USERNAME, password=self.NEW_PASSWORD)
self.assertTrue(result)
@ddt.data(True, False)
def test_password_change_logged_out(self, send_email):
# Log the user out
self.client.logout()
# Request a password change while logged out, simulating
# use of the password reset link from the login page
if send_email:
response = self._change_password(email=self.OLD_EMAIL)
self.assertEqual(response.status_code, 200)
else:
# Don't send an email in the POST data, simulating
# its (potentially accidental) omission in the POST
# data sent from the login page
response = self._change_password()
self.assertEqual(response.status_code, 400)
def test_password_change_inactive_user(self):
# Log out the user created during test setup
self.client.logout()
# Create a second user, but do not activate it
account_api.create_account(self.ALTERNATE_USERNAME, self.OLD_PASSWORD, self.NEW_EMAIL)
# Send the view the email address tied to the inactive user
response = self._change_password(email=self.NEW_EMAIL)
self.assertEqual(response.status_code, 400)
def test_password_change_no_user(self):
# Log out the user created during test setup
self.client.logout()
# Send the view an email address not tied to any user
response = self._change_password(email=self.NEW_EMAIL)
self.assertEqual(response.status_code, 400)
def test_password_change_rate_limited(self):
# Log out the user created during test setup, to prevent the view from
# selecting the logged-in user's email address over the email provided
# in the POST data
self.client.logout()
# Make many consecutive bad requests in an attempt to trigger the rate limiter
for attempt in xrange(self.INVALID_ATTEMPTS):
self._change_password(email=self.NEW_EMAIL)
response = self._change_password(email=self.NEW_EMAIL)
self.assertEqual(response.status_code, 403)
@ddt.data(
('get', 'account_index', []),
('post', 'email_change_request', []),
('get', 'email_change_confirm', [123])
)
@ddt.unpack
def test_require_login(self, method, url_name, args):
# Access the page while logged out
self.client.logout()
url = reverse(url_name, args=args)
response = getattr(self.client, method)(url, follow=True)
# Should have been redirected to the login page
self.assertEqual(len(response.redirect_chain), 1)
self.assertIn('accounts/login?next=', response.redirect_chain[0][0])
@ddt.data(
('get', 'account_index', []),
('post', 'email_change_request', []),
('get', 'email_change_confirm', [123]),
('post', 'password_change_request', []),
)
@ddt.unpack
def test_require_http_method(self, correct_method, url_name, args):
wrong_methods = {'get', 'put', 'post', 'head', 'options', 'delete'} - {correct_method}
url = reverse(url_name, args=args)
for method in wrong_methods:
response = getattr(self.client, method)(url)
self.assertEqual(response.status_code, 405)
def _assert_email(self, email, expected_to, expected_subject, expected_body):
"""Check whether an email has the correct properties. """
self.assertEqual(email.to, expected_to)
self.assertIn(expected_subject, email.subject)
self.assertIn(expected_body, email.body)
def _change_email(self, new_email, password):
"""Request to change the user's email. """
data = {}
if new_email is not None:
data['email'] = new_email
if password is not None:
# We can't pass a Unicode object to urlencode, so we encode the Unicode object
data['password'] = password.encode('utf-8')
return self.client.post(path=reverse('email_change_request'), data=data)
def _change_password(self, email=None):
"""Request to change the user's password. """
data = {}
if email:
data['email'] = email
return self.client.post(path=reverse('password_change_request'), data=data)
@ddt.ddt
@override_settings(MODULESTORE=MODULESTORE_CONFIG)
class StudentAccountLoginAndRegistrationTest(ModuleStoreTestCase):
""" Tests for the student account views that update the user's account information. """
USERNAME = "bob"
EMAIL = "bob@example.com"
PASSWORD = "password"
@ddt.data(
("account_login", "login"),
("account_register", "register"),
)
@ddt.unpack
def test_login_and_registration_form(self, url_name, initial_mode):
response = self.client.get(reverse(url_name))
expected_data = u"data-initial-mode=\"{mode}\"".format(mode=initial_mode)
self.assertContains(response, expected_data)
@ddt.data("account_login", "account_register")
def test_login_and_registration_form_already_authenticated(self, url_name):
# Create/activate a new account and log in
activation_key = account_api.create_account(self.USERNAME, self.PASSWORD, self.EMAIL)
account_api.activate_account(activation_key)
result = self.client.login(username=self.USERNAME, password=self.PASSWORD)
self.assertTrue(result)
# Verify that we're redirected to the dashboard
response = self.client.get(reverse(url_name))
self.assertRedirects(response, reverse("dashboard"))
@mock.patch.dict(settings.FEATURES, {"ENABLE_THIRD_PARTY_AUTH": False})
@ddt.data("account_login", "account_register")
def test_third_party_auth_disabled(self, url_name):
response = self.client.get(reverse(url_name))
self._assert_third_party_auth_data(response, None, [])
@ddt.data(
("account_login", None, None),
("account_register", None, None),
("account_login", "google-oauth2", "Google"),
("account_register", "google-oauth2", "Google"),
("account_login", "facebook", "Facebook"),
("account_register", "facebook", "Facebook"),
)
@ddt.unpack
def test_third_party_auth(self, url_name, current_backend, current_provider):
# Simulate a running pipeline
if current_backend is not None:
pipeline_target = "student_account.views.third_party_auth.pipeline"
with simulate_running_pipeline(pipeline_target, current_backend):
response = self.client.get(reverse(url_name))
# Do NOT simulate a running pipeline
else:
response = self.client.get(reverse(url_name))
# This relies on the THIRD_PARTY_AUTH configuration in the test settings
expected_providers = [
{
"name": "Facebook",
"iconClass": "fa-facebook",
"loginUrl": self._third_party_login_url("facebook", "account_login"),
"registerUrl": self._third_party_login_url("facebook", "account_register")
},
{
"name": "Google",
"iconClass": "fa-google-plus",
"loginUrl": self._third_party_login_url("google-oauth2", "account_login"),
"registerUrl": self._third_party_login_url("google-oauth2", "account_register")
}
]
self._assert_third_party_auth_data(response, current_provider, expected_providers)
@ddt.data([], ["honor"], ["honor", "verified", "audit"], ["professional"])
def test_third_party_auth_course_id_verified(self, modes):
# Create a course with the specified course modes
course = CourseFactory.create()
for slug in modes:
CourseModeFactory.create(
course_id=course.id,
mode_slug=slug,
mode_display_name=slug
)
# Verify that the entry URL for third party auth
# contains the course ID and redirects to the track selection page.
course_modes_choose_url = reverse(
"course_modes_choose",
kwargs={"course_id": unicode(course.id)}
)
expected_providers = [
{
"name": "Facebook",
"iconClass": "fa-facebook",
"loginUrl": self._third_party_login_url(
"facebook", "account_login",
course_id=unicode(course.id),
redirect_url=course_modes_choose_url
),
"registerUrl": self._third_party_login_url(
"facebook", "account_register",
course_id=unicode(course.id),
redirect_url=course_modes_choose_url
)
},
{
"name": "Google",
"iconClass": "fa-google-plus",
"loginUrl": self._third_party_login_url(
"google-oauth2", "account_login",
course_id=unicode(course.id),
redirect_url=course_modes_choose_url
),
"registerUrl": self._third_party_login_url(
"google-oauth2", "account_register",
course_id=unicode(course.id),
redirect_url=course_modes_choose_url
)
}
]
# Verify that the login page contains the correct provider URLs
response = self.client.get(reverse("account_login"), {"course_id": unicode(course.id)})
self._assert_third_party_auth_data(response, None, expected_providers)
def test_third_party_auth_course_id_shopping_cart(self):
# Create a course with a white-label course mode
course = CourseFactory.create()
CourseModeFactory.create(
course_id=course.id,
mode_slug="honor",
mode_display_name="Honor",
min_price=100
)
# Verify that the entry URL for third party auth
# contains the course ID and redirects to the shopping cart
shoppingcart_url = reverse("shoppingcart.views.show_cart")
expected_providers = [
{
"name": "Facebook",
"iconClass": "fa-facebook",
"loginUrl": self._third_party_login_url(
"facebook", "account_login",
course_id=unicode(course.id),
redirect_url=shoppingcart_url
),
"registerUrl": self._third_party_login_url(
"facebook", "account_register",
course_id=unicode(course.id),
redirect_url=shoppingcart_url
)
},
{
"name": "Google",
"iconClass": "fa-google-plus",
"loginUrl": self._third_party_login_url(
"google-oauth2", "account_login",
course_id=unicode(course.id),
redirect_url=shoppingcart_url
),
"registerUrl": self._third_party_login_url(
"google-oauth2", "account_register",
course_id=unicode(course.id),
redirect_url=shoppingcart_url
)
}
]
# Verify that the login page contains the correct provider URLs
response = self.client.get(reverse("account_login"), {"course_id": unicode(course.id)})
self._assert_third_party_auth_data(response, None, expected_providers)
def _assert_third_party_auth_data(self, response, current_provider, providers):
"""Verify that third party auth info is rendered correctly in a DOM data attribute. """
expected_data = u"data-third-party-auth='{auth_info}'".format(
auth_info=json.dumps({
"currentProvider": current_provider,
"providers": providers
})
)
self.assertContains(response, expected_data)
def _third_party_login_url(self, backend_name, auth_entry, course_id=None, redirect_url=None):
"""Construct the login URL to start third party authentication. """
params = [("auth_entry", auth_entry)]
if redirect_url:
params.append(("next", redirect_url))
if course_id:
params.append(("enroll_course_id", course_id))
return u"{url}?{params}".format(
url=reverse("social:begin", kwargs={"backend": backend_name}),
params=urlencode(params)
)
| UQ-UQx/edx-platform_lti | lms/djangoapps/student_account/test/test_views.py | Python | agpl-3.0 | 23,896 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import uuid
from itertools import groupby
from datetime import datetime, timedelta
from werkzeug.urls import url_encode
from odoo import api, fields, models, _
from odoo.exceptions import UserError, AccessError
from odoo.osv import expression
from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.misc import formatLang
from odoo.addons import decimal_precision as dp
class SaleOrder(models.Model):
_name = "sale.order"
_inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin']
_description = "Quotation"
_order = 'date_order desc, id desc'
@api.depends('order_line.price_total')
def _amount_all(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
amount_untaxed = amount_tax = 0.0
for line in order.order_line:
amount_untaxed += line.price_subtotal
amount_tax += line.price_tax
order.update({
'amount_untaxed': order.pricelist_id.currency_id.round(amount_untaxed),
'amount_tax': order.pricelist_id.currency_id.round(amount_tax),
'amount_total': amount_untaxed + amount_tax,
})
@api.depends('state', 'order_line.invoice_status')
def _get_invoiced(self):
"""
Compute the invoice status of a SO. Possible statuses:
- no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to
invoice. This is also hte default value if the conditions of no other status is met.
- to invoice: if any SO line is 'to invoice', the whole SO is 'to invoice'
- invoiced: if all SO lines are invoiced, the SO is invoiced.
- upselling: if all SO lines are invoiced or upselling, the status is upselling.
The invoice_ids are obtained thanks to the invoice lines of the SO lines, and we also search
for possible refunds created directly from existing invoices. This is necessary since such a
refund is not directly linked to the SO.
"""
for order in self:
invoice_ids = order.order_line.mapped('invoice_lines').mapped('invoice_id').filtered(lambda r: r.type in ['out_invoice', 'out_refund'])
# Search for invoices which have been 'cancelled' (filter_refund = 'modify' in
# 'account.invoice.refund')
# use like as origin may contains multiple references (e.g. 'SO01, SO02')
refunds = invoice_ids.search([('origin', 'like', order.name), ('company_id', '=', order.company_id.id)]).filtered(lambda r: r.type in ['out_invoice', 'out_refund'])
invoice_ids |= refunds.filtered(lambda r: order.name in [origin.strip() for origin in r.origin.split(',')])
# Search for refunds as well
refund_ids = self.env['account.invoice'].browse()
if invoice_ids:
for inv in invoice_ids:
refund_ids += refund_ids.search([('type', '=', 'out_refund'), ('origin', '=', inv.number), ('origin', '!=', False), ('journal_id', '=', inv.journal_id.id)])
# Ignore the status of the deposit product
deposit_product_id = self.env['sale.advance.payment.inv']._default_product_id()
line_invoice_status = [line.invoice_status for line in order.order_line if line.product_id != deposit_product_id]
if order.state not in ('sale', 'done'):
invoice_status = 'no'
elif any(invoice_status == 'to invoice' for invoice_status in line_invoice_status):
invoice_status = 'to invoice'
elif all(invoice_status == 'invoiced' for invoice_status in line_invoice_status):
invoice_status = 'invoiced'
elif all(invoice_status in ['invoiced', 'upselling'] for invoice_status in line_invoice_status):
invoice_status = 'upselling'
else:
invoice_status = 'no'
order.update({
'invoice_count': len(set(invoice_ids.ids + refund_ids.ids)),
'invoice_ids': invoice_ids.ids + refund_ids.ids,
'invoice_status': invoice_status
})
@api.model
def get_empty_list_help(self, help):
self = self.with_context(
empty_list_help_document_name=_("sale order"),
)
return super(SaleOrder, self).get_empty_list_help(help)
def _get_default_access_token(self):
return str(uuid.uuid4())
@api.model
def _default_note(self):
return self.env['ir.config_parameter'].sudo().get_param('sale.use_sale_note') and self.env.user.company_id.sale_note or ''
@api.model
def _get_default_team(self):
return self.env['crm.team']._get_default_team_id()
@api.onchange('fiscal_position_id')
def _compute_tax_id(self):
"""
Trigger the recompute of the taxes if the fiscal position is changed on the SO.
"""
for order in self:
order.order_line._compute_tax_id()
name = fields.Char(string='Order Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)]}, index=True, default=lambda self: _('New'))
origin = fields.Char(string='Source Document', help="Reference of the document that generated this sales order request.")
client_order_ref = fields.Char(string='Customer Reference', copy=False)
access_token = fields.Char(
'Security Token', copy=False,
default=_get_default_access_token)
state = fields.Selection([
('draft', 'Quotation'),
('sent', 'Quotation Sent'),
('sale', 'Sales Order'),
('done', 'Locked'),
('cancel', 'Cancelled'),
], string='Status', readonly=True, copy=False, index=True, track_visibility='onchange', default='draft')
date_order = fields.Datetime(string='Order Date', required=True, readonly=True, index=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=False, default=fields.Datetime.now)
validity_date = fields.Date(string='Quote Validity', readonly=True, copy=False, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
help="Validity date of the quotation, after this date, the customer won't be able to validate the quotation online.")
is_expired = fields.Boolean(compute='_compute_is_expired', string="Is expired")
create_date = fields.Datetime(string='Creation Date', readonly=True, index=True, help="Date on which sales order is created.")
confirmation_date = fields.Datetime(string='Confirmation Date', readonly=True, index=True, help="Date on which the sales order is confirmed.", oldname="date_confirm", copy=False)
user_id = fields.Many2one('res.users', string='Salesperson', index=True, track_visibility='onchange', default=lambda self: self.env.user)
partner_id = fields.Many2one('res.partner', string='Customer', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, required=True, change_default=True, index=True, track_visibility='always')
partner_invoice_id = fields.Many2one('res.partner', string='Invoice Address', readonly=True, required=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'sale': [('readonly', False)]}, help="Invoice address for current sales order.")
partner_shipping_id = fields.Many2one('res.partner', string='Delivery Address', readonly=True, required=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)], 'sale': [('readonly', False)]}, help="Delivery address for current sales order.")
pricelist_id = fields.Many2one('product.pricelist', string='Pricelist', required=True, readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="Pricelist for current sales order.")
currency_id = fields.Many2one("res.currency", related='pricelist_id.currency_id', string="Currency", readonly=True, required=True)
analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, help="The analytic account related to a sales order.", copy=False, oldname='project_id')
order_line = fields.One2many('sale.order.line', 'order_id', string='Order Lines', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True, auto_join=True)
invoice_count = fields.Integer(string='Invoice Count', compute='_get_invoiced', readonly=True)
invoice_ids = fields.Many2many("account.invoice", string='Invoices', compute="_get_invoiced", readonly=True, copy=False)
invoice_status = fields.Selection([
('upselling', 'Upselling Opportunity'),
('invoiced', 'Fully Invoiced'),
('to invoice', 'To Invoice'),
('no', 'Nothing to Invoice')
], string='Invoice Status', compute='_get_invoiced', store=True, readonly=True)
note = fields.Text('Terms and conditions', default=_default_note)
amount_untaxed = fields.Monetary(string='Untaxed Amount', store=True, readonly=True, compute='_amount_all', track_visibility='onchange')
amount_tax = fields.Monetary(string='Taxes', store=True, readonly=True, compute='_amount_all')
amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_amount_all', track_visibility='always')
payment_term_id = fields.Many2one('account.payment.term', string='Payment Terms', oldname='payment_term')
fiscal_position_id = fields.Many2one('account.fiscal.position', oldname='fiscal_position', string='Fiscal Position')
company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env['res.company']._company_default_get('sale.order'))
team_id = fields.Many2one('crm.team', 'Sales Channel', change_default=True, default=_get_default_team, oldname='section_id')
product_id = fields.Many2one('product.product', related='order_line.product_id', string='Product')
def _compute_portal_url(self):
super(SaleOrder, self)._compute_portal_url()
for order in self:
order.portal_url = '/my/orders/%s' % (order.id)
def _compute_is_expired(self):
now = datetime.now()
for order in self:
if order.validity_date and fields.Datetime.from_string(order.validity_date) < now:
order.is_expired = True
else:
order.is_expired = False
@api.model
def _get_customer_lead(self, product_tmpl_id):
return False
@api.multi
def unlink(self):
for order in self:
if order.state not in ('draft', 'cancel'):
raise UserError(_('You can not delete a sent quotation or a sales order! Try to cancel it before.'))
return super(SaleOrder, self).unlink()
@api.multi
def _track_subtype(self, init_values):
self.ensure_one()
if 'state' in init_values and self.state == 'sale':
return 'sale.mt_order_confirmed'
elif 'state' in init_values and self.state == 'sent':
return 'sale.mt_order_sent'
return super(SaleOrder, self)._track_subtype(init_values)
@api.multi
@api.onchange('partner_shipping_id', 'partner_id')
def onchange_partner_shipping_id(self):
"""
Trigger the change of fiscal position when the shipping address is modified.
"""
self.fiscal_position_id = self.env['account.fiscal.position'].get_fiscal_position(self.partner_id.id, self.partner_shipping_id.id)
return {}
@api.multi
@api.onchange('partner_id')
def onchange_partner_id(self):
"""
Update the following fields when the partner is changed:
- Pricelist
- Payment terms
- Invoice address
- Delivery address
"""
if not self.partner_id:
self.update({
'partner_invoice_id': False,
'partner_shipping_id': False,
'payment_term_id': False,
'fiscal_position_id': False,
})
return
addr = self.partner_id.address_get(['delivery', 'invoice'])
values = {
'pricelist_id': self.partner_id.property_product_pricelist and self.partner_id.property_product_pricelist.id or False,
'payment_term_id': self.partner_id.property_payment_term_id and self.partner_id.property_payment_term_id.id or False,
'partner_invoice_id': addr['invoice'],
'partner_shipping_id': addr['delivery'],
'user_id': self.partner_id.user_id.id or self.env.uid
}
if self.env['ir.config_parameter'].sudo().get_param('sale.use_sale_note') and self.env.user.company_id.sale_note:
values['note'] = self.with_context(lang=self.partner_id.lang).env.user.company_id.sale_note
if self.partner_id.team_id:
values['team_id'] = self.partner_id.team_id.id
self.update(values)
@api.onchange('partner_id')
def onchange_partner_id_warning(self):
if not self.partner_id:
return
warning = {}
title = False
message = False
partner = self.partner_id
# If partner has no warning, check its company
if partner.sale_warn == 'no-message' and partner.parent_id:
partner = partner.parent_id
if partner.sale_warn and partner.sale_warn != 'no-message':
# Block if partner only has warning but parent company is blocked
if partner.sale_warn != 'block' and partner.parent_id and partner.parent_id.sale_warn == 'block':
partner = partner.parent_id
title = ("Warning for %s") % partner.name
message = partner.sale_warn_msg
warning = {
'title': title,
'message': message,
}
if partner.sale_warn == 'block':
self.update({'partner_id': False, 'partner_invoice_id': False, 'partner_shipping_id': False, 'pricelist_id': False})
return {'warning': warning}
if warning:
return {'warning': warning}
@api.model
def create(self, vals):
if vals.get('name', _('New')) == _('New'):
if 'company_id' in vals:
vals['name'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code('sale.order') or _('New')
else:
vals['name'] = self.env['ir.sequence'].next_by_code('sale.order') or _('New')
# Makes sure partner_invoice_id', 'partner_shipping_id' and 'pricelist_id' are defined
if any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id']):
partner = self.env['res.partner'].browse(vals.get('partner_id'))
addr = partner.address_get(['delivery', 'invoice'])
vals['partner_invoice_id'] = vals.setdefault('partner_invoice_id', addr['invoice'])
vals['partner_shipping_id'] = vals.setdefault('partner_shipping_id', addr['delivery'])
vals['pricelist_id'] = vals.setdefault('pricelist_id', partner.property_product_pricelist and partner.property_product_pricelist.id)
result = super(SaleOrder, self).create(vals)
return result
@api.multi
def _write(self, values):
""" Override of private write method in order to generate activities
based in the invoice status. As the invoice status is a computed field
triggered notably when its lines and linked invoice status changes the
flow does not necessarily goes through write if the action was not done
on the SO itself. We hence override the _write to catch the computation
of invoice_status field. """
if self.env.context.get('mail_activity_automation_skip'):
return super(SaleOrder, self)._write(values)
res = super(SaleOrder, self)._write(values)
if 'invoice_status' in values:
self.activity_unlink(['sale.mail_act_sale_upsell'])
if values['invoice_status'] == 'upselling':
for order in self:
order.activity_schedule(
'sale.mail_act_sale_upsell', fields.Date.today(),
user_id=order.user_id.id,
note=_("Upsell <a href='#' data-oe-model='%s' data-oe-id='%d'>%s</a> for customer <a href='#' data-oe-model='%s' data-oe-id='%s'>%s</a>") % (
order._name, order.id, order.name,
order.partner_id._name, order.partner_id.id, order.partner_id.display_name))
return res
@api.multi
def copy_data(self, default=None):
if default is None:
default = {}
if 'order_line' not in default:
default['order_line'] = [(0, 0, line.copy_data()[0]) for line in self.order_line.filtered(lambda l: not l.is_downpayment)]
return super(SaleOrder, self).copy_data(default)
@api.multi
def name_get(self):
if self._context.get('sale_show_partner_name'):
res = []
for order in self:
name = order.name
if order.partner_id.name:
name = '%s - %s' % (name, order.partner_id.name)
res.append((order.id, name))
return res
return super(SaleOrder, self).name_get()
@api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
if self._context.get('sale_show_partner_name'):
if operator in ('ilike', 'like', '=', '=like', '=ilike'):
domain = expression.AND([
args or [],
['|', ('name', operator, name), ('partner_id.name', operator, name)]
])
return self.search(domain, limit=limit).name_get()
return super(SaleOrder, self).name_search(name, args, operator, limit)
@api.model_cr_context
def _init_column(self, column_name):
""" Initialize the value of the given column for existing rows.
Overridden here because we need to generate different access tokens
and by default _init_column calls the default method once and applies
it for every record.
"""
if column_name != 'access_token':
super(SaleOrder, self)._init_column(column_name)
else:
query = """UPDATE %(table_name)s
SET %(column_name)s = md5(md5(random()::varchar || id::varchar) || clock_timestamp()::varchar)::uuid::varchar
WHERE %(column_name)s IS NULL
""" % {'table_name': self._table, 'column_name': column_name}
self.env.cr.execute(query)
def _generate_access_token(self):
for order in self:
order.access_token = self._get_default_access_token()
@api.multi
def _prepare_invoice(self):
"""
Prepare the dict of values to create the new invoice for a sales order. This method may be
overridden to implement custom invoice generation (making sure to call super() to establish
a clean extension chain).
"""
self.ensure_one()
journal_id = self.env['account.invoice'].default_get(['journal_id'])['journal_id']
if not journal_id:
raise UserError(_('Please define an accounting sales journal for this company.'))
invoice_vals = {
'name': self.client_order_ref or '',
'origin': self.name,
'type': 'out_invoice',
'account_id': self.partner_invoice_id.property_account_receivable_id.id,
'partner_id': self.partner_invoice_id.id,
'partner_shipping_id': self.partner_shipping_id.id,
'journal_id': journal_id,
'currency_id': self.pricelist_id.currency_id.id,
'comment': self.note,
'payment_term_id': self.payment_term_id.id,
'fiscal_position_id': self.fiscal_position_id.id or self.partner_invoice_id.property_account_position_id.id,
'company_id': self.company_id.id,
'user_id': self.user_id and self.user_id.id,
'team_id': self.team_id.id
}
return invoice_vals
@api.multi
def print_quotation(self):
self.filtered(lambda s: s.state == 'draft').write({'state': 'sent'})
return self.env.ref('sale.action_report_saleorder').report_action(self)
@api.multi
def action_view_invoice(self):
invoices = self.mapped('invoice_ids')
action = self.env.ref('account.action_invoice_tree1').read()[0]
if len(invoices) > 1:
action['domain'] = [('id', 'in', invoices.ids)]
elif len(invoices) == 1:
action['views'] = [(self.env.ref('account.invoice_form').id, 'form')]
action['res_id'] = invoices.ids[0]
else:
action = {'type': 'ir.actions.act_window_close'}
return action
@api.multi
def action_invoice_create(self, grouped=False, final=False):
"""
Create the invoice associated to the SO.
:param grouped: if True, invoices are grouped by SO id. If False, invoices are grouped by
(partner_invoice_id, currency)
:param final: if True, refunds will be generated if necessary
:returns: list of created invoices
"""
inv_obj = self.env['account.invoice']
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
invoices = {}
references = {}
for order in self:
group_key = order.id if grouped else (order.partner_invoice_id.id, order.currency_id.id)
for line in order.order_line.sorted(key=lambda l: l.qty_to_invoice < 0):
if float_is_zero(line.qty_to_invoice, precision_digits=precision):
continue
if group_key not in invoices:
inv_data = order._prepare_invoice()
invoice = inv_obj.create(inv_data)
references[invoice] = order
invoices[group_key] = invoice
elif group_key in invoices:
vals = {}
if order.name not in invoices[group_key].origin.split(', '):
vals['origin'] = invoices[group_key].origin + ', ' + order.name
if order.client_order_ref and order.client_order_ref not in invoices[group_key].name.split(', ') and order.client_order_ref != invoices[group_key].name:
vals['name'] = invoices[group_key].name + ', ' + order.client_order_ref
invoices[group_key].write(vals)
if line.qty_to_invoice > 0:
line.invoice_line_create(invoices[group_key].id, line.qty_to_invoice)
elif line.qty_to_invoice < 0 and final:
line.invoice_line_create(invoices[group_key].id, line.qty_to_invoice)
if references.get(invoices.get(group_key)):
if order not in references[invoices[group_key]]:
references[invoices[group_key]] |= order
if not invoices:
raise UserError(_('There is no invoiceable line.'))
for invoice in invoices.values():
if not invoice.invoice_line_ids:
raise UserError(_('There is no invoiceable line.'))
# If invoice is negative, do a refund invoice instead
if invoice.amount_untaxed < 0:
invoice.type = 'out_refund'
for line in invoice.invoice_line_ids:
line.quantity = -line.quantity
# Use additional field helper function (for account extensions)
for line in invoice.invoice_line_ids:
line._set_additional_fields(invoice)
# Necessary to force computation of taxes. In account_invoice, they are triggered
# by onchanges, which are not triggered when doing a create.
invoice.compute_taxes()
invoice.message_post_with_view('mail.message_origin_link',
values={'self': invoice, 'origin': references[invoice]},
subtype_id=self.env.ref('mail.mt_note').id)
return [inv.id for inv in invoices.values()]
@api.multi
def action_draft(self):
orders = self.filtered(lambda s: s.state in ['cancel', 'sent'])
return orders.write({
'state': 'draft',
})
@api.multi
def action_cancel(self):
return self.write({'state': 'cancel'})
@api.multi
def action_quotation_send(self):
'''
This function opens a window to compose an email, with the edi sale template message loaded by default
'''
self.ensure_one()
ir_model_data = self.env['ir.model.data']
try:
template_id = ir_model_data.get_object_reference('sale', 'email_template_edi_sale')[1]
except ValueError:
template_id = False
try:
compose_form_id = ir_model_data.get_object_reference('mail', 'email_compose_message_wizard_form')[1]
except ValueError:
compose_form_id = False
ctx = {
'default_model': 'sale.order',
'default_res_id': self.ids[0],
'default_use_template': bool(template_id),
'default_template_id': template_id,
'default_composition_mode': 'comment',
'mark_so_as_sent': True,
'custom_layout': "mail.mail_notification_borders",
'proforma': self.env.context.get('proforma', False),
'force_email': True
}
return {
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'mail.compose.message',
'views': [(compose_form_id, 'form')],
'view_id': compose_form_id,
'target': 'new',
'context': ctx,
}
@api.multi
@api.returns('self', lambda value: value.id)
def message_post(self, **kwargs):
if self.env.context.get('mark_so_as_sent'):
self.filtered(lambda o: o.state == 'draft').with_context(tracking_disable=True).write({'state': 'sent'})
return super(SaleOrder, self.with_context(mail_post_autofollow=True)).message_post(**kwargs)
@api.multi
def force_quotation_send(self):
for order in self:
email_act = order.action_quotation_send()
if email_act and email_act.get('context'):
email_ctx = email_act['context']
email_ctx.update(default_email_from=order.company_id.email)
order.with_context(email_ctx).message_post_with_template(email_ctx.get('default_template_id'))
return True
@api.multi
def action_done(self):
return self.write({'state': 'done'})
@api.multi
def action_unlock(self):
self.write({'state': 'sale'})
@api.multi
def _action_confirm(self):
for order in self.filtered(lambda order: order.partner_id not in order.message_partner_ids):
order.message_subscribe([order.partner_id.id])
self.write({
'state': 'sale',
'confirmation_date': fields.Datetime.now()
})
if self.env.context.get('send_email'):
self.force_quotation_send()
# create an analytic account if at least an expense product
if any([expense_policy != 'no' for expense_policy in self.order_line.mapped('product_id.expense_policy')]):
if not self.analytic_account_id:
self._create_analytic_account()
return True
@api.multi
def action_confirm(self):
self._action_confirm()
if self.env['ir.config_parameter'].sudo().get_param('sale.auto_done_setting'):
self.action_done()
return True
@api.multi
def _create_analytic_account(self, prefix=None):
for order in self:
name = order.name
if prefix:
name = prefix + ": " + order.name
analytic = self.env['account.analytic.account'].create({
'name': name,
'code': order.client_order_ref,
'company_id': order.company_id.id,
'partner_id': order.partner_id.id
})
order.analytic_account_id = analytic
@api.multi
def order_lines_layouted(self):
"""
Returns this order lines classified by sale_layout_category and separated in
pages according to the category pagebreaks. Used to render the report.
"""
self.ensure_one()
report_pages = [[]]
for category, lines in groupby(self.order_line, lambda l: l.layout_category_id):
# If last added category induced a pagebreak, this one will be on a new page
if report_pages[-1] and report_pages[-1][-1]['pagebreak']:
report_pages.append([])
# Append category to current report page
report_pages[-1].append({
'name': category and category.name or _('Uncategorized'),
'subtotal': category and category.subtotal,
'pagebreak': category and category.pagebreak,
'lines': list(lines)
})
return report_pages
@api.multi
def _get_tax_amount_by_group(self):
self.ensure_one()
res = {}
for line in self.order_line:
price_reduce = line.price_unit * (1.0 - line.discount / 100.0)
taxes = line.tax_id.compute_all(price_reduce, quantity=line.product_uom_qty, product=line.product_id, partner=self.partner_shipping_id)['taxes']
for tax in line.tax_id:
group = tax.tax_group_id
res.setdefault(group, {'amount': 0.0, 'base': 0.0})
for t in taxes:
if t['id'] == tax.id or t['id'] in tax.children_tax_ids.ids:
res[group]['amount'] += t['amount']
res[group]['base'] += t['base']
res = sorted(res.items(), key=lambda l: l[0].sequence)
res = [(l[0].name, l[1]['amount'], l[1]['base'], len(res)) for l in res]
return res
@api.multi
def get_access_action(self, access_uid=None):
""" Instead of the classic form view, redirect to the online order for
portal users or if force_website=True in the context. """
# TDE note: read access on sales order to portal users granted to followed sales orders
self.ensure_one()
if self.state != 'cancel' and (self.state != 'draft' or self.env.context.get('mark_so_as_sent')):
user, record = self.env.user, self
if access_uid:
user = self.env['res.users'].sudo().browse(access_uid)
record = self.sudo(user)
if user.share or self.env.context.get('force_website'):
try:
record.check_access_rule('read')
except AccessError:
if self.env.context.get('force_website'):
return {
'type': 'ir.actions.act_url',
'url': '/my/orders/%s' % self.id,
'target': 'self',
'res_id': self.id,
}
else:
pass
else:
return {
'type': 'ir.actions.act_url',
'url': '/my/orders/%s?access_token=%s' % (self.id, self.access_token),
'target': 'self',
'res_id': self.id,
}
return super(SaleOrder, self).get_access_action(access_uid)
def get_mail_url(self):
return self.get_share_url()
def get_portal_confirmation_action(self):
return self.env['ir.config_parameter'].sudo().get_param('sale.sale_portal_confirmation_options', default='none')
@api.multi
def _notify_get_groups(self, message, groups):
""" Give access button to users and portal customer as portal is integrated
in sale. Customer and portal group have probably no right to see
the document so they don't have the access button. """
groups = super(SaleOrder, self)._notify_get_groups(message, groups)
self.ensure_one()
if self.state not in ('draft', 'cancel'):
for group_name, group_method, group_data in groups:
if group_name in ('customer', 'portal'):
continue
group_data['has_button_access'] = True
return groups
class SaleOrderLine(models.Model):
_name = 'sale.order.line'
_description = 'Sales Order Line'
_order = 'order_id, layout_category_id, sequence, id'
@api.depends('state', 'product_uom_qty', 'qty_delivered', 'qty_to_invoice', 'qty_invoiced')
def _compute_invoice_status(self):
"""
Compute the invoice status of a SO line. Possible statuses:
- no: if the SO is not in status 'sale' or 'done', we consider that there is nothing to
invoice. This is also hte default value if the conditions of no other status is met.
- to invoice: we refer to the quantity to invoice of the line. Refer to method
`_get_to_invoice_qty()` for more information on how this quantity is calculated.
- upselling: this is possible only for a product invoiced on ordered quantities for which
we delivered more than expected. The could arise if, for example, a project took more
time than expected but we decided not to invoice the extra cost to the client. This
occurs onyl in state 'sale', so that when a SO is set to done, the upselling opportunity
is removed from the list.
- invoiced: the quantity invoiced is larger or equal to the quantity ordered.
"""
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for line in self:
if line.state not in ('sale', 'done'):
line.invoice_status = 'no'
elif not float_is_zero(line.qty_to_invoice, precision_digits=precision):
line.invoice_status = 'to invoice'
elif line.state == 'sale' and line.product_id.invoice_policy == 'order' and\
float_compare(line.qty_delivered, line.product_uom_qty, precision_digits=precision) == 1:
line.invoice_status = 'upselling'
elif float_compare(line.qty_invoiced, line.product_uom_qty, precision_digits=precision) >= 0:
line.invoice_status = 'invoiced'
else:
line.invoice_status = 'no'
@api.depends('product_uom_qty', 'discount', 'price_unit', 'tax_id')
def _compute_amount(self):
"""
Compute the amounts of the SO line.
"""
for line in self:
price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_id, partner=line.order_id.partner_shipping_id)
line.update({
'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])),
'price_total': taxes['total_included'],
'price_subtotal': taxes['total_excluded'],
})
@api.depends('product_id', 'order_id.state', 'qty_invoiced', 'qty_delivered')
def _compute_product_updatable(self):
for line in self:
if line.state in ['done', 'cancel'] or (line.state == 'sale' and (line.qty_invoiced > 0 or line.qty_delivered > 0)):
line.product_updatable = False
else:
line.product_updatable = True
@api.depends('qty_invoiced', 'qty_delivered', 'product_uom_qty', 'order_id.state')
def _get_to_invoice_qty(self):
"""
Compute the quantity to invoice. If the invoice policy is order, the quantity to invoice is
calculated from the ordered quantity. Otherwise, the quantity delivered is used.
"""
for line in self:
if line.order_id.state in ['sale', 'done']:
if line.product_id.invoice_policy == 'order':
line.qty_to_invoice = line.product_uom_qty - line.qty_invoiced
else:
line.qty_to_invoice = line.qty_delivered - line.qty_invoiced
else:
line.qty_to_invoice = 0
@api.depends('invoice_lines.invoice_id.state', 'invoice_lines.quantity')
def _get_invoice_qty(self):
"""
Compute the quantity invoiced. If case of a refund, the quantity invoiced is decreased. Note
that this is the case only if the refund is generated from the SO and that is intentional: if
a refund made would automatically decrease the invoiced quantity, then there is a risk of reinvoicing
it automatically, which may not be wanted at all. That's why the refund has to be created from the SO
"""
for line in self:
qty_invoiced = 0.0
for invoice_line in line.invoice_lines:
if invoice_line.invoice_id.state != 'cancel':
if invoice_line.invoice_id.type == 'out_invoice':
qty_invoiced += invoice_line.uom_id._compute_quantity(invoice_line.quantity, line.product_uom)
elif invoice_line.invoice_id.type == 'out_refund':
qty_invoiced -= invoice_line.uom_id._compute_quantity(invoice_line.quantity, line.product_uom)
line.qty_invoiced = qty_invoiced
@api.depends('price_unit', 'discount')
def _get_price_reduce(self):
for line in self:
line.price_reduce = line.price_unit * (1.0 - line.discount / 100.0)
@api.depends('price_total', 'product_uom_qty')
def _get_price_reduce_tax(self):
for line in self:
line.price_reduce_taxinc = line.price_total / line.product_uom_qty if line.product_uom_qty else 0.0
@api.depends('price_subtotal', 'product_uom_qty')
def _get_price_reduce_notax(self):
for line in self:
line.price_reduce_taxexcl = line.price_subtotal / line.product_uom_qty if line.product_uom_qty else 0.0
@api.multi
def _compute_tax_id(self):
for line in self:
fpos = line.order_id.fiscal_position_id or line.order_id.partner_id.property_account_position_id
# If company_id is set, always filter taxes by the company
taxes = line.product_id.taxes_id.filtered(lambda r: not line.company_id or r.company_id == line.company_id)
line.tax_id = fpos.map_tax(taxes, line.product_id, line.order_id.partner_shipping_id) if fpos else taxes
@api.model
def _get_purchase_price(self, pricelist, product, product_uom, date):
return {}
@api.model
def _prepare_add_missing_fields(self, values):
""" Deduce missing required fields from the onchange """
res = {}
onchange_fields = ['name', 'price_unit', 'product_uom', 'tax_id']
if values.get('order_id') and values.get('product_id') and any(f not in values for f in onchange_fields):
line = self.new(values)
line.product_id_change()
for field in onchange_fields:
if field not in values:
res[field] = line._fields[field].convert_to_write(line[field], line)
return res
@api.model
def create(self, values):
values.update(self._prepare_add_missing_fields(values))
line = super(SaleOrderLine, self).create(values)
if line.order_id.state == 'sale':
msg = _("Extra line with %s ") % (line.product_id.display_name,)
line.order_id.message_post(body=msg)
# create an analytic account if at least an expense product
if line.product_id.expense_policy != 'no' and not self.order_id.analytic_account_id:
self.order_id._create_analytic_account()
return line
def _update_line_quantity(self, values):
orders = self.mapped('order_id')
for order in orders:
order_lines = self.filtered(lambda x: x.order_id == order)
msg = "<b>The ordered quantity has been updated.</b><ul>"
for line in order_lines:
msg += "<li> %s:" % (line.product_id.display_name,)
msg += "<br/>" + _("Ordered Quantity") + ": %s -> %s <br/>" % (
line.product_uom_qty, float(values['product_uom_qty']),)
if line.product_id.type in ('consu', 'product'):
msg += _("Delivered Quantity") + ": %s <br/>" % (line.qty_delivered,)
msg += _("Invoiced Quantity") + ": %s <br/>" % (line.qty_invoiced,)
msg += "</ul>"
order.message_post(body=msg)
@api.multi
def write(self, values):
if 'product_uom_qty' in values:
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
self.filtered(
lambda r: r.state == 'sale' and float_compare(r.product_uom_qty, values['product_uom_qty'], precision_digits=precision) != 0)._update_line_quantity(values)
# Prevent writing on a locked SO.
protected_fields = self._get_protected_fields()
if 'done' in self.mapped('order_id.state') and any(f in values.keys() for f in protected_fields):
protected_fields_modified = list(set(protected_fields) & set(values.keys()))
fields = self.env['ir.model.fields'].search([
('name', 'in', protected_fields_modified), ('model', '=', self._name)
])
raise UserError(
_('It is forbidden to modify the following fields in a locked order:\n%s')
% '\n'.join(fields.mapped('field_description'))
)
result = super(SaleOrderLine, self).write(values)
return result
order_id = fields.Many2one('sale.order', string='Order Reference', required=True, ondelete='cascade', index=True, copy=False)
name = fields.Text(string='Description', required=True)
sequence = fields.Integer(string='Sequence', default=10)
invoice_lines = fields.Many2many('account.invoice.line', 'sale_order_line_invoice_rel', 'order_line_id', 'invoice_line_id', string='Invoice Lines', copy=False)
invoice_status = fields.Selection([
('upselling', 'Upselling Opportunity'),
('invoiced', 'Fully Invoiced'),
('to invoice', 'To Invoice'),
('no', 'Nothing to Invoice')
], string='Invoice Status', compute='_compute_invoice_status', store=True, readonly=True, default='no')
price_unit = fields.Float('Unit Price', required=True, digits=dp.get_precision('Product Price'), default=0.0)
price_subtotal = fields.Monetary(compute='_compute_amount', string='Subtotal', readonly=True, store=True)
price_tax = fields.Float(compute='_compute_amount', string='Total Tax', readonly=True, store=True)
price_total = fields.Monetary(compute='_compute_amount', string='Total', readonly=True, store=True)
price_reduce = fields.Float(compute='_get_price_reduce', string='Price Reduce', digits=dp.get_precision('Product Price'), readonly=True, store=True)
tax_id = fields.Many2many('account.tax', string='Taxes', domain=['|', ('active', '=', False), ('active', '=', True)])
price_reduce_taxinc = fields.Monetary(compute='_get_price_reduce_tax', string='Price Reduce Tax inc', readonly=True, store=True)
price_reduce_taxexcl = fields.Monetary(compute='_get_price_reduce_notax', string='Price Reduce Tax excl', readonly=True, store=True)
discount = fields.Float(string='Discount (%)', digits=dp.get_precision('Discount'), default=0.0)
product_id = fields.Many2one('product.product', string='Product', domain=[('sale_ok', '=', True)], change_default=True, ondelete='restrict', required=True)
product_updatable = fields.Boolean(compute='_compute_product_updatable', string='Can Edit Product', readonly=True, default=True)
product_uom_qty = fields.Float(string='Ordered Quantity', digits=dp.get_precision('Product Unit of Measure'), required=True, default=1.0)
product_uom = fields.Many2one('uom.uom', string='Unit of Measure', required=True)
# Non-stored related field to allow portal user to see the image of the product he has ordered
product_image = fields.Binary('Product Image', related="product_id.image", store=False)
qty_delivered_method = fields.Selection([
('manual', 'Manual'),
('analytic', 'Analytic From Expenses')
], string="Method to update delivered qty", compute='_compute_qty_delivered_method', compute_sudo=True, store=True, readonly=True,
help="According to product configuration, the delivered quantity can be automatically computed by mechanism :\n"
" - Manual: the quantity is set manually on the line\n"
" - Analytic From expenses: the quantity is the quantity sum from posted expenses\n"
" - Timesheet: the quantity is the sum of hours recorded on tasks linked to this sale line\n"
" - Stock Moves: the quantity comes from confirmed pickings\n")
qty_delivered = fields.Float('Delivered', copy=False, compute='_compute_qty_delivered', inverse='_inverse_qty_delivered', compute_sudo=True, store=True, digits=dp.get_precision('Product Unit of Measure'), default=0.0)
qty_delivered_manual = fields.Float('Delivered Manually', copy=False, digits=dp.get_precision('Product Unit of Measure'), default=0.0)
qty_to_invoice = fields.Float(
compute='_get_to_invoice_qty', string='To Invoice', store=True, readonly=True,
digits=dp.get_precision('Product Unit of Measure'))
qty_invoiced = fields.Float(
compute='_get_invoice_qty', string='Invoiced', store=True, readonly=True,
digits=dp.get_precision('Product Unit of Measure'))
salesman_id = fields.Many2one(related='order_id.user_id', store=True, string='Salesperson', readonly=True)
currency_id = fields.Many2one(related='order_id.currency_id', depends=['order_id'], store=True, string='Currency', readonly=True)
company_id = fields.Many2one(related='order_id.company_id', string='Company', store=True, readonly=True)
order_partner_id = fields.Many2one(related='order_id.partner_id', store=True, string='Customer')
analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags')
analytic_line_ids = fields.One2many('account.analytic.line', 'so_line', string="Analytic lines")
is_expense = fields.Boolean('Is expense', help="Is true if the sales order line comes from an expense or a vendor bills")
is_downpayment = fields.Boolean(
string="Is a down payment", help="Down payments are made when creating invoices from a sales order."
" They are not copied when duplicating a sales order.")
state = fields.Selection([
('draft', 'Quotation'),
('sent', 'Quotation Sent'),
('sale', 'Sales Order'),
('done', 'Done'),
('cancel', 'Cancelled'),
], related='order_id.state', string='Order Status', readonly=True, copy=False, store=True, default='draft')
customer_lead = fields.Float(
'Delivery Lead Time', required=True, default=0.0,
help="Number of days between the order confirmation and the shipping of the products to the customer", oldname="delay")
layout_category_id = fields.Many2one('sale.layout_category', string='Section')
layout_category_sequence = fields.Integer(string='Layout Sequence')
# TODO: remove layout_category_sequence in master or make it work properly
@api.multi
@api.depends('state', 'is_expense')
def _compute_qty_delivered_method(self):
""" Sale module compute delivered qty for product [('type', 'in', ['consu']), ('service_type', '=', 'manual')]
- consu + expense_policy : analytic (sum of analytic unit_amount)
- consu + no expense_policy : manual (set manually on SOL)
- service (+ service_type='manual', the only available option) : manual
This is true when only sale is installed: sale_stock redifine the behavior for 'consu' type,
and sale_timesheet implements the behavior of 'service' + service_type=timesheet.
"""
for line in self:
if line.is_expense:
line.qty_delivered_method = 'analytic'
else: # service and consu
line.qty_delivered_method = 'manual'
@api.multi
@api.depends('qty_delivered_method', 'qty_delivered_manual', 'analytic_line_ids.so_line', 'analytic_line_ids.unit_amount', 'analytic_line_ids.product_uom_id')
def _compute_qty_delivered(self):
""" This method compute the delivered quantity of the SO lines: it covers the case provide by sale module, aka
expense/vendor bills (sum of unit_amount of AAL), and manual case.
This method should be overriden to provide other way to automatically compute delivered qty. Overrides should
take their concerned so lines, compute and set the `qty_delivered` field, and call super with the remaining
records.
"""
# compute for analytic lines
lines_by_analytic = self.filtered(lambda sol: sol.qty_delivered_method == 'analytic')
mapping = lines_by_analytic._get_delivered_quantity_by_analytic([('amount', '<=', 0.0)])
for so_line in lines_by_analytic:
so_line.qty_delivered = mapping.get(so_line.id, 0.0)
# compute for manual lines
for line in self:
if line.qty_delivered_method == 'manual':
line.qty_delivered = line.qty_delivered_manual or 0.0
@api.multi
def _get_delivered_quantity_by_analytic(self, additional_domain):
""" Compute and write the delivered quantity of current SO lines, based on their related
analytic lines.
:param additional_domain: domain to restrict AAL to include in computation (required since timesheet is an AAL with a project ...)
"""
result = {}
# avoid recomputation if no SO lines concerned
if not self:
return result
# group anaytic lines by product uom and so line
domain = expression.AND([[('so_line', 'in', self.ids)], additional_domain])
data = self.env['account.analytic.line'].read_group(
domain,
['so_line', 'unit_amount', 'product_uom_id'], ['product_uom_id', 'so_line'], lazy=False
)
# convert uom and sum all unit_amount of analytic lines to get the delivered qty of SO lines
# browse so lines and product uoms here to make them share the same prefetch
lines_map = {line.id: line for line in self}
product_uom_ids = [item['product_uom_id'][0] for item in data if item['product_uom_id']]
product_uom_map = {uom.id: uom for uom in self.env['uom.uom'].browse(product_uom_ids)}
for item in data:
if not item['product_uom_id']:
continue
so_line_id = item['so_line'][0]
so_line = lines_map[so_line_id]
result.setdefault(so_line_id, 0.0)
uom = product_uom_map.get(item['product_uom_id'][0])
if so_line.product_uom.category_id == uom.category_id:
qty = uom._compute_quantity(item['unit_amount'], so_line.product_uom)
else:
qty = item['unit_amount']
result[so_line_id] += qty
return result
@api.multi
@api.onchange('qty_delivered')
def _inverse_qty_delivered(self):
""" When writing on qty_delivered, if the value should be modify manually (`qty_delivered_method` = 'manual' only),
then we put the value in `qty_delivered_manual`. Otherwise, `qty_delivered_manual` should be False since the
delivered qty is automatically compute by other mecanisms.
"""
for line in self:
if line.qty_delivered_method == 'manual':
line.qty_delivered_manual = line.qty_delivered
else:
line.qty_delivered_manual = 0.0
@api.multi
def _prepare_invoice_line(self, qty):
"""
Prepare the dict of values to create the new invoice line for a sales order line.
:param qty: float quantity to invoice
"""
self.ensure_one()
res = {}
account = self.product_id.property_account_income_id or self.product_id.categ_id.property_account_income_categ_id
if not account:
raise UserError(_('Please define income account for this product: "%s" (id:%d) - or for its category: "%s".') %
(self.product_id.name, self.product_id.id, self.product_id.categ_id.name))
fpos = self.order_id.fiscal_position_id or self.order_id.partner_id.property_account_position_id
if fpos:
account = fpos.map_account(account)
res = {
'name': self.name,
'sequence': self.sequence,
'origin': self.order_id.name,
'account_id': account.id,
'price_unit': self.price_unit,
'quantity': qty,
'discount': self.discount,
'uom_id': self.product_uom.id,
'product_id': self.product_id.id or False,
'layout_category_id': self.layout_category_id and self.layout_category_id.id or False,
'invoice_line_tax_ids': [(6, 0, self.tax_id.ids)],
'account_analytic_id': self.order_id.analytic_account_id.id,
'analytic_tag_ids': [(6, 0, self.analytic_tag_ids.ids)],
}
return res
@api.multi
def invoice_line_create(self, invoice_id, qty):
""" Create an invoice line. The quantity to invoice can be positive (invoice) or negative (refund).
:param invoice_id: integer
:param qty: float quantity to invoice
:returns recordset of account.invoice.line created
"""
invoice_lines = self.env['account.invoice.line']
precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
for line in self:
if not float_is_zero(qty, precision_digits=precision):
vals = line._prepare_invoice_line(qty=qty)
vals.update({'invoice_id': invoice_id, 'sale_line_ids': [(6, 0, [line.id])]})
invoice_lines |= self.env['account.invoice.line'].create(vals)
return invoice_lines
@api.multi
def _prepare_procurement_values(self, group_id=False):
""" Prepare specific key for moves or other components that will be created from a procurement rule
comming from a sale order line. This method could be override in order to add other custom key that could
be used in move/po creation.
"""
return {}
@api.multi
def _get_display_price(self, product):
# TO DO: move me in master/saas-16 on sale.order
if self.order_id.pricelist_id.discount_policy == 'with_discount':
return product.with_context(pricelist=self.order_id.pricelist_id.id).price
final_price, rule_id = self.order_id.pricelist_id.get_product_price_rule(self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
context_partner = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order)
base_price, currency_id = self.with_context(context_partner)._get_real_price_currency(self.product_id, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
if currency_id != self.order_id.pricelist_id.currency_id.id:
currency = self.env['res.currency'].browse(currency_id)
base_price = currency._convert(
base_price, self.order_id.pricelist_id.currency_id,
self.order_id.company_id, self.order_id.date_order or fields.Date.today())
# negative discounts (= surcharge) are included in the display price
return max(base_price, final_price)
@api.multi
@api.onchange('product_id')
def product_id_change(self):
if not self.product_id:
return {'domain': {'product_uom': []}}
vals = {}
domain = {'product_uom': [('category_id', '=', self.product_id.uom_id.category_id.id)]}
if not self.product_uom or (self.product_id.uom_id.id != self.product_uom.id):
vals['product_uom'] = self.product_id.uom_id
vals['product_uom_qty'] = 1.0
product = self.product_id.with_context(
lang=self.order_id.partner_id.lang,
partner=self.order_id.partner_id.id,
quantity=vals.get('product_uom_qty') or self.product_uom_qty,
date=self.order_id.date_order,
pricelist=self.order_id.pricelist_id.id,
uom=self.product_uom.id
)
result = {'domain': domain}
title = False
message = False
warning = {}
if product.sale_line_warn != 'no-message':
title = _("Warning for %s") % product.name
message = product.sale_line_warn_msg
warning['title'] = title
warning['message'] = message
result = {'warning': warning}
if product.sale_line_warn == 'block':
self.product_id = False
return result
name = product.name_get()[0][1]
if product.description_sale:
name += '\n' + product.description_sale
vals['name'] = name
self._compute_tax_id()
if self.order_id.pricelist_id and self.order_id.partner_id:
vals['price_unit'] = self.env['account.tax']._fix_tax_included_price_company(self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id)
self.update(vals)
return result
@api.onchange('product_uom', 'product_uom_qty')
def product_uom_change(self):
if not self.product_uom or not self.product_id:
self.price_unit = 0.0
return
if self.order_id.pricelist_id and self.order_id.partner_id:
product = self.product_id.with_context(
lang=self.order_id.partner_id.lang,
partner=self.order_id.partner_id.id,
quantity=self.product_uom_qty,
date=self.order_id.date_order,
pricelist=self.order_id.pricelist_id.id,
uom=self.product_uom.id,
fiscal_position=self.env.context.get('fiscal_position')
)
self.price_unit = self.env['account.tax']._fix_tax_included_price_company(self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id)
@api.multi
def name_get(self):
result = []
for so_line in self:
name = '%s - %s' % (so_line.order_id.name, so_line.name.split('\n')[0] or so_line.product_id.name)
if so_line.order_partner_id.ref:
name = '%s (%s)' % (name, so_line.order_partner_id.ref)
result.append((so_line.id, name))
return result
@api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
if operator in ('ilike', 'like', '=', '=like', '=ilike'):
args = expression.AND([
args or [],
['|', ('order_id.name', operator, name), ('name', operator, name)]
])
return super(SaleOrderLine, self).name_search(name, args, operator, limit)
@api.multi
def unlink(self):
if self.filtered(lambda x: x.state in ('sale', 'done')):
raise UserError(_('You can not remove an order line once the sales order is confirmed.\nYou should rather set the quantity to 0.'))
return super(SaleOrderLine, self).unlink()
def _get_real_price_currency(self, product, rule_id, qty, uom, pricelist_id):
"""Retrieve the price before applying the pricelist
:param obj product: object of current product record
:parem float qty: total quentity of product
:param tuple price_and_rule: tuple(price, suitable_rule) coming from pricelist computation
:param obj uom: unit of measure of current order line
:param integer pricelist_id: pricelist id of sales order"""
PricelistItem = self.env['product.pricelist.item']
field_name = 'lst_price'
currency_id = None
product_currency = None
if rule_id:
pricelist_item = PricelistItem.browse(rule_id)
if pricelist_item.pricelist_id.discount_policy == 'without_discount':
while pricelist_item.base == 'pricelist' and pricelist_item.base_pricelist_id and pricelist_item.base_pricelist_id.discount_policy == 'without_discount':
price, rule_id = pricelist_item.base_pricelist_id.with_context(uom=uom.id).get_product_price_rule(product, qty, self.order_id.partner_id)
pricelist_item = PricelistItem.browse(rule_id)
if pricelist_item.base == 'standard_price':
field_name = 'standard_price'
if pricelist_item.base == 'pricelist' and pricelist_item.base_pricelist_id:
field_name = 'price'
product = product.with_context(pricelist=pricelist_item.base_pricelist_id.id)
product_currency = pricelist_item.base_pricelist_id.currency_id
currency_id = pricelist_item.pricelist_id.currency_id
product_currency = product_currency or(product.company_id and product.company_id.currency_id) or self.env.user.company_id.currency_id
if not currency_id:
currency_id = product_currency
cur_factor = 1.0
else:
if currency_id.id == product_currency.id:
cur_factor = 1.0
else:
cur_factor = currency_id._get_conversion_rate(product_currency, currency_id, self.company_id, self.order_id.date_order)
product_uom = self.env.context.get('uom') or product.uom_id.id
if uom and uom.id != product_uom:
# the unit price is in a different uom
uom_factor = uom._compute_price(1.0, product.uom_id)
else:
uom_factor = 1.0
return product[field_name] * uom_factor * cur_factor, currency_id
def _get_protected_fields(self):
return [
'product_id', 'name', 'price_unit', 'product_uom', 'product_uom_qty',
'tax_id', 'analytic_tag_ids'
]
@api.onchange('product_id', 'price_unit', 'product_uom', 'product_uom_qty', 'tax_id')
def _onchange_discount(self):
self.discount = 0.0
if not (self.product_id and self.product_uom and
self.order_id.partner_id and self.order_id.pricelist_id and
self.order_id.pricelist_id.discount_policy == 'without_discount' and
self.env.user.has_group('sale.group_discount_per_so_line')):
return
context_partner = dict(self.env.context, partner_id=self.order_id.partner_id.id, date=self.order_id.date_order)
pricelist_context = dict(context_partner, uom=self.product_uom.id)
price, rule_id = self.order_id.pricelist_id.with_context(pricelist_context).get_product_price_rule(self.product_id, self.product_uom_qty or 1.0, self.order_id.partner_id)
new_list_price, currency_id = self.with_context(context_partner)._get_real_price_currency(self.product_id, rule_id, self.product_uom_qty, self.product_uom, self.order_id.pricelist_id.id)
if new_list_price != 0:
if self.order_id.pricelist_id.currency_id.id != currency_id:
# we need new_list_price in the same currency as price, which is in the SO's pricelist's currency
currency = self.env['res.currency'].browse(currency_id)
new_list_price = currency._convert(
new_list_price, self.order_id.pricelist_id.currency_id,
self.order_id.company_id, self.order_id.date_order or fields.Date.today())
discount = (new_list_price - price) / new_list_price * 100
if discount > 0:
self.discount = discount
| maxive/erp | addons/sale/models/sale.py | Python | agpl-3.0 | 64,688 |
package com.x.processplatform.assemble.designer.jaxrs.file;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.exception.ExceptionAccessDenied;
import com.x.base.core.project.exception.ExceptionEntityNotExist;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.processplatform.assemble.designer.Business;
import com.x.processplatform.core.entity.element.Application;
import com.x.processplatform.core.entity.element.File;
import com.x.processplatform.core.entity.element.File_;
class ActionCopy extends BaseAction {
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, String applicationFlag) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
File file = emc.flag(flag, File.class);
if (null == file) {
throw new ExceptionEntityNotExist(flag, File.class);
}
Application application = emc.find(file.getApplication(), Application.class);
if (null == application) {
throw new ExceptionEntityNotExist(file.getApplication(), Application.class);
}
if (!business.editable(effectivePerson, application)) {
throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName());
}
Application toApplication = emc.flag(applicationFlag, Application.class);
if (null == toApplication) {
throw new ExceptionEntityNotExist(applicationFlag, Application.class);
}
if (!business.editable(effectivePerson, toApplication)) {
throw new ExceptionAccessDenied(effectivePerson.getDistinguishedName());
}
File toFile = new File();
toFile.setName(this.getName(business, file.getName(), toFile.getId(), toApplication.getId()));
toFile.setApplication(toApplication.getId());
toFile.setDescription(file.getDescription());
toFile.setData(file.getData());
toFile.setFileName(file.getFileName());
toFile.setLastUpdatePerson(file.getLastUpdatePerson());
toFile.setLastUpdateTime(new Date());
toFile.setLength(file.getLength());
emc.beginTransaction(File.class);
emc.persist(toFile, CheckPersistType.all);
emc.commit();
CacheManager.notify(File.class);
Wo wo = new Wo();
wo.setId(toFile.getId());
result.setData(wo);
return result;
}
}
private String getName(Business business, String name, String id, String applicationId) throws Exception {
for (int i = 0; i < 10000; i++) {
if (!this.exist(business, name + i, id, applicationId)) {
return name;
}
}
throw new ExceptionErrorName(name);
}
private boolean exist(Business business, String name, String id, String applicationId) throws Exception {
EntityManager em = business.entityManagerContainer().get(File.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<File> root = cq.from(File.class);
Predicate p = cb.or(cb.equal(root.get(File_.name), name), cb.equal(root.get(File_.alias), name),
cb.equal(root.get(File_.id), name));
p = cb.and(p, cb.equal(root.get(File_.application), applicationId), cb.notEqual(root.get(File_.id), id));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult() > 0;
}
public static class Wo extends WoId {
}
} | o2oa/o2oa | o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/jaxrs/file/ActionCopy.java | Java | agpl-3.0 | 3,848 |
// Copyright 2014-2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package operation
import (
"time"
corecharm "github.com/juju/charm/v9"
"github.com/juju/errors"
"github.com/juju/names/v4"
utilexec "github.com/juju/utils/v2/exec"
"github.com/juju/juju/core/model"
"github.com/juju/juju/worker/uniter/charm"
"github.com/juju/juju/worker/uniter/hook"
"github.com/juju/juju/worker/uniter/remotestate"
"github.com/juju/juju/worker/uniter/runner"
"github.com/juju/juju/worker/uniter/runner/context"
)
//go:generate go run github.com/golang/mock/mockgen -package mocks -destination mocks/interface_mock.go github.com/juju/juju/worker/uniter/operation Operation,Factory,Callbacks
// Logger is here to stop the desire of creating a package level Logger.
// Don't do this, pass one in to the needed functions.
type logger interface{}
var _ logger = struct{}{}
// Logger determines the logging methods used by the operations package.
type Logger interface {
Errorf(string, ...interface{})
Warningf(string, ...interface{})
Infof(string, ...interface{})
Debugf(string, ...interface{})
Tracef(string, ...interface{})
}
// Operation encapsulates the stages of the various things the uniter can do,
// and the state changes that need to be recorded as they happen. Operations
// are designed to be Run (or Skipped) by an Executor, which supplies starting
// state and records the changes returned.
type Operation interface {
// String returns a short representation of the operation.
String() string
// NeedsGlobalMachineLock returns a bool expressing whether we need to lock the machine.
NeedsGlobalMachineLock() bool
// ExecutionGroup returns a string used to construct the name of the machine lock.
ExecutionGroup() string
// Prepare ensures that the operation is valid and ready to be executed.
// If it returns a non-nil state, that state will be validated and recorded.
// If it returns ErrSkipExecute, it indicates that the operation can be
// committed directly.
Prepare(state State) (*State, error)
// Execute carries out the operation. It must not be called without having
// called Prepare first. If it returns a non-nil state, that state will be
// validated and recorded.
Execute(state State) (*State, error)
// Commit ensures that the operation's completion is recorded. If it returns
// a non-nil state, that state will be validated and recorded.
Commit(state State) (*State, error)
// RemoteStateChanged is called when the remote state changed during execution
// of the operation.
RemoteStateChanged(snapshot remotestate.Snapshot)
}
// WrappedOperation extends Operation to provide access to the wrapped operation.
type WrappedOperation interface {
Operation
WrappedOperation() Operation
}
// Unwrap peels back one layer of a wrapped operation.
func Unwrap(op Operation) Operation {
if op == nil {
return nil
}
if wrapped, ok := op.(WrappedOperation); ok {
return wrapped.WrappedOperation()
}
return op
}
// Executor records and exposes uniter state, and applies suitable changes as
// operations are run or skipped.
type Executor interface {
// State returns a copy of the executor's current operation state.
State() State
// Run will Prepare, Execute, and Commit the supplied operation, writing
// indicated state changes between steps. If any step returns an unknown
// error, the run will be aborted and an error will be returned.
// On remote state change, the executor will fire the operation's
// RemoteStateChanged method.
Run(Operation, <-chan remotestate.Snapshot) error
// Skip will Commit the supplied operation, and write any state change
// indicated. If Commit returns an error, so will Skip.
Skip(Operation) error
}
// Factory creates operations.
type Factory interface {
// NewInstall creates an install operation for the supplied charm.
NewInstall(charmURL *corecharm.URL) (Operation, error)
// NewUpgrade creates an upgrade operation for the supplied charm.
NewUpgrade(charmURL *corecharm.URL) (Operation, error)
// NewRemoteInit inits the remote charm on CAAS pod.
NewRemoteInit(runningStatus remotestate.ContainerRunningStatus) (Operation, error)
// NewSkipRemoteInit skips a remote-init operation.
NewSkipRemoteInit(retry bool) (Operation, error)
// NewNoOpFinishUpgradeSeries creates a noop which simply resets the
// status of a units upgrade series.
NewNoOpFinishUpgradeSeries() (Operation, error)
// NewRevertUpgrade creates an operation to clear the unit's resolved flag,
// and execute an upgrade to the supplied charm that is careful to excise
// remnants of a previously failed upgrade to a different charm.
NewRevertUpgrade(charmURL *corecharm.URL) (Operation, error)
// NewResolvedUpgrade creates an operation to clear the unit's resolved flag,
// and execute an upgrade to the supplied charm that is careful to preserve
// non-overlapping remnants of a previously failed upgrade to the same charm.
NewResolvedUpgrade(charmURL *corecharm.URL) (Operation, error)
// NewRunHook creates an operation to execute the supplied hook.
NewRunHook(hookInfo hook.Info) (Operation, error)
// NewSkipHook creates an operation to mark the supplied hook as
// completed successfully, without executing the hook.
NewSkipHook(hookInfo hook.Info) (Operation, error)
// NewAction creates an operation to execute the supplied action.
NewAction(actionId string) (Operation, error)
// NewFailAction creates an operation that marks an action as failed.
NewFailAction(actionId string) (Operation, error)
// NewCommands creates an operation to execute the supplied script in the
// indicated relation context, and pass the results back over the supplied
// func.
NewCommands(args CommandArgs, sendResponse CommandResponseFunc) (Operation, error)
// NewAcceptLeadership creates an operation to ensure the uniter acts as
// application leader.
NewAcceptLeadership() (Operation, error)
// NewResignLeadership creates an operation to ensure the uniter does not
// act as application leader.
NewResignLeadership() (Operation, error)
}
// CommandArgs stores the arguments for a Command operation.
type CommandArgs struct {
// Commands is the arbitrary commands to execute on the unit
Commands string
// RelationId is the relation context to execute the commands in.
RelationId int
// RemoteUnitName is the remote unit for the relation context.
RemoteUnitName string
// TODO(jam): 2019-10-24 Include RemoteAppName
// ForceRemoteUnit skips unit inference and existence validation.
ForceRemoteUnit bool
// RunLocation describes where the command must run.
RunLocation runner.RunLocation
}
// Validate the command arguments.
func (args CommandArgs) Validate() error {
if args.Commands == "" {
return errors.New("commands required")
}
if args.RemoteUnitName != "" {
if args.RelationId == -1 {
return errors.New("remote unit not valid without relation")
} else if !names.IsValidUnit(args.RemoteUnitName) {
return errors.Errorf("invalid remote unit name %q", args.RemoteUnitName)
}
}
return nil
}
// CommandResponseFunc is for marshalling command responses back to the source
// of the original request.
type CommandResponseFunc func(*utilexec.ExecResponse, error) bool
// Callbacks exposes all the uniter code that's required by the various operations.
// It's far from cohesive, and fundamentally represents inappropriate coupling, so
// it's a prime candidate for future refactoring.
type Callbacks interface {
// PrepareHook and CommitHook exist so that we can defer worrying about how
// to untangle Uniter.relationers from everything else. They're only used by
// RunHook operations.
PrepareHook(info hook.Info) (name string, err error)
CommitHook(info hook.Info) error
// SetExecutingStatus sets the agent state to "Executing" with a message.
SetExecutingStatus(string) error
// NotifyHook* exist so that we can defer worrying about how to untangle the
// callbacks inserted for uniter_test. They're only used by RunHook operations.
NotifyHookCompleted(string, context.Context)
NotifyHookFailed(string, context.Context)
// The following methods exist primarily to allow us to test operation code
// without using a live api connection.
// FailAction marks the supplied action failed. It's only used by
// RunActions operations.
FailAction(actionId, message string) error
// ActionStatus returns the status of the action required by the action operation for
// cancelation.
ActionStatus(actionId string) (string, error)
// GetArchiveInfo is used to find out how to download a charm archive. It's
// only used by Deploy operations.
GetArchiveInfo(charmURL *corecharm.URL) (charm.BundleInfo, error)
// SetCurrentCharm records intent to deploy a given charm. It must be called
// *before* recording local state referencing that charm, to ensure there's
// no path by which the controller can legitimately garbage collect that
// charm or the application's settings for it. It's only used by Deploy operations.
SetCurrentCharm(charmURL *corecharm.URL) error
// SetUpgradeSeriesStatus is intended to give the uniter a chance to
// upgrade the status of a running series upgrade before or after
// upgrade series hook code completes and, for display purposes, to
// supply a reason as to why it is making the change.
SetUpgradeSeriesStatus(status model.UpgradeSeriesStatus, reason string) error
// SetSecretRotated updates the time when the secret was rotated.
SetSecretRotated(url string, when time.Time) error
// PostStartHook indiciates that the charms start hook has successfully run
PostStartHook()
// RemoteInit copies the charm to the remote instance. CAAS only.
RemoteInit(runningStatus remotestate.ContainerRunningStatus, abort <-chan struct{}) error
}
// StorageUpdater is an interface used for updating local knowledge of storage
// attachments.
type StorageUpdater interface {
// UpdateStorage updates local knowledge of the storage attachments
// with the specified tags.
UpdateStorage([]names.StorageTag) error
}
| jameinel/juju | worker/uniter/operation/interface.go | GO | agpl-3.0 | 10,078 |
(function(C2C, $) {
// area selector size
C2C.changeSelectSize = function(id, up_down) {
var select = $('#' + id);
var height = select.height();
if (up_down) {
height += 150;
} else {
height = Math.max(100, height - 150);
}
select.height(height);
};
// for some search inputs like date selection, we hide some parts
// depending on the first field value
// e.g. only display one input for selecting summits higher than 4000m,
// two inputs for selecting summits between 2000m and 3000m
C2C.update_on_select_change = function(field, optionIndex) {
var index = $('#' + field + '_sel').val();
if (index == '0' || index === ' ' || index == '-' || index >= 4) {
$('#' + field + '_span1').hide();
$('#' + field + '_span2').hide();
if (optionIndex >= 4) {
if (index == 4) {
$('#' + field + '_span3').show();
} else {
$('#' + field + '_span3').hide();
}
}
} else {
$('#' + field + '_span1').show();
if (index == '~' || index == 3) {
$('#' + field + '_span2').show();
} else {
$('#' + field + '_span2').hide();
}
if (optionIndex >= 4) {
$('#' + field + '_span3').hide();
}
}
};
// hide some fields depending onf the activity selected
function hide_unrelated_filter_fields() {
var activities = [];
$.each($("input[name='act[]']:checked"), function() {
activities.push($(this).val());
});
// show/hide data-act-filter tags depending on selected activities
$('[data-act-filter]').hide();
$('[data-act-filter="none"]').toggle(!!activities);
if (!!activities) $.each(activities, function (i, activity) {
$('[data-act-filter~='+ activity +']').show();
});
// some configuration should only be available if
// activity 2 (snow, ice, mixed) is selected
// not that not all browser allow to hide option tags, so we also
// disable them
var select = $('#conf'), select_size;
var options = select.find('option:eq(4), option:eq(5)');
if (activities && $.inArray("2", activities) !== -1) {
select_size = 6;
options.prop('disabled', false).show();
} else {
select_size = 4;
options.prop('disabled', true).hide();
}
select.attr('size', select_size);
}
$('#actform').on('click', "input[name='act[]']", function() {
hide_unrelated_filter_fields();
});
// run it once
hide_unrelated_filter_fields();
})(window.C2C = window.C2C || {}, jQuery);
| c2corg/camptocamp.org | web/static/js/filter.js | JavaScript | agpl-3.0 | 2,561 |
/*
* Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of vcash.
*
* vcash is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COIN_STACK_HPP
#define COIN_STACK_HPP
#include <cstdint>
#include <ctime>
#include <map>
#include <string>
namespace coin {
class stack_impl;
/**
* The stack.
*/
class stack
{
public:
/**
* Constructor
*/
stack();
/**
* Starts the stack.
* @param args The arguments.
*/
void start(
const std::map<std::string, std::string> & args =
std::map<std::string, std::string> ()
);
/**
* Stops the stack.
*/
void stop();
/**
* Sends coins.
* @param amount The amount.
* @param destination The destination.
* @param wallet_values The wallet ke/values.
*/
void send_coins(
const std::int64_t & amount, const std::string & destination,
const std::map<std::string, std::string> & wallet_values
);
/**
* Starts mining.
* @param mining_values An std::map<std::string, std::string>.
*/
void start_mining(
const std::map<std::string, std::string> & mining_values
);
/**
* Stops mining.
* @param mining_values An std::map<std::string, std::string>.
*/
void stop_mining(
const std::map<std::string, std::string> & mining_values
);
/**
* Broadcasts an alert.
* @param pairs An std::map<std::string, std::string>.
*/
void broadcast_alert(
const std::map<std::string, std::string> & pairs
);
/**
* Encrypts the wallet.
* @param passphrase The passphrase.
*/
void wallet_encrypt(const std::string & passphrase);
/**
* Locks the wallet.
*/
void wallet_lock();
/**
* Unlocks the wallet.
* @param passphrase The passphrase.
*/
void wallet_unlock(const std::string & passphrase);
/**
* Changes the wallet passphrase.
* @param passphrase_old The old passphrase.
* @param password_new The new passphrase.
*/
void wallet_change_passphrase(
const std::string & passphrase_old,
const std::string & password_new
);
/**
* If true the wallet is crypted.
* @param wallet_id The wallet id.
*/
bool wallet_is_crypted(const std::uint32_t & wallet_id = 0);
/**
* If true the wallet is locked.
* @param wallet_id The wallet id.
*/
bool wallet_is_locked(const std::uint32_t & wallet_id = 0);
/**
* Performs a ZeroTime lock on the transaction.
* @param tx_id The transaction id.
*/
void wallet_zerotime_lock(const std::string & tx_id);
/**
* Starts chainblender.
*/
void chainblender_start();
/**
* Stops chainblender.
*/
void chainblender_stop();
/**
* Sends an RPC command line.
* @param command_line The command line.
*/
void rpc_send(const std::string & command_line);
/**
* Rescans the chain.
*/
void rescan_chain();
/**
* Sets the wallet.transaction.history.maximum
* @param val The value.
*/
void set_configuration_wallet_transaction_history_maximum(
const std::time_t & val
);
/**
* The wallet.transaction.history.maximum.
*/
const std::time_t
configuration_wallet_transaction_history_maximum() const
;
/**
* Sets chainblender to use common output denominations.
* @param val The value.
*/
void set_configuration_chainblender_use_common_output_denominations(
const bool & val
);
/**
* The chainblender.use_common_output_denominations.
*/
const bool
configuration_chainblender_use_common_output_denominations()
const;
/**
* Called when an error occurs.
* @param pairs The key/value pairs.
*/
virtual void on_error(
const std::map<std::string, std::string> & pairs
);
/**
* Called when a status update occurs.
* @param pairs The key/value pairs.
*/
virtual void on_status(
const std::map<std::string, std::string> & pairs
);
/**
* Called when an alert is received.
* @param pairs The key/value pairs.
*/
virtual void on_alert(
const std::map<std::string, std::string> & pairs
);
private:
// ...
protected:
/**
* The stack implementation.
*/
stack_impl * stack_impl_;
};
} // namespace coin
#endif // COIN_STACK_HPP
| xCoreDev/vanillacoin | include/coin/stack.hpp | C++ | agpl-3.0 | 6,768 |
# frozen_string_literal: true
module Decidim
module Blogs
# The data store for a Blog in the Decidim::Blogs component. It stores a
# title, description and any other useful information to render a blog.
class Post < Blogs::ApplicationRecord
include Decidim::Resourceable
include Decidim::HasAttachments
include Decidim::HasAttachmentCollections
include Decidim::HasComponent
include Decidim::Authorable
include Decidim::Comments::CommentableWithComponent
include Decidim::Searchable
include Decidim::Endorsable
include Decidim::Followable
include Decidim::TranslatableResource
include Traceable
include Loggable
component_manifest_name "blogs"
translatable_fields :title, :body
validates :title, presence: true
scope :created_at_desc, -> { order(arel_table[:created_at].desc) }
searchable_fields({
participatory_space: { component: :participatory_space },
A: :title,
D: :body,
datetime: :created_at
},
index_on_create: true,
index_on_update: ->(post) { post.visible? })
def visible?
participatory_space.try(:visible?) && component.try(:published?)
end
# Public: Overrides the `comments_have_alignment?` Commentable concern method.
def comments_have_alignment?
true
end
# Public: Overrides the `comments_have_votes?` Commentable concern method.
def comments_have_votes?
true
end
# Public: Overrides the `allow_resource_permissions?` Resourceable concern method.
def allow_resource_permissions?
true
end
def official?
author.nil?
end
def users_to_notify_on_comment_created
followers
end
def attachment_context
:admin
end
end
end
end
| decidim/decidim | decidim-blogs/app/models/decidim/blogs/post.rb | Ruby | agpl-3.0 | 2,000 |
/**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.ifc2x3tc1;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
public interface IfcBoundingBox extends IfcGeometricRepresentationItem {
/**
* Returns the value of the '<em><b>Corner</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Corner</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Corner</em>' reference.
* @see #setCorner(IfcCartesianPoint)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_Corner()
* @model
* @generated
*/
IfcCartesianPoint getCorner();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getCorner <em>Corner</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Corner</em>' reference.
* @see #getCorner()
* @generated
*/
void setCorner(IfcCartesianPoint value);
/**
* Returns the value of the '<em><b>XDim</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>XDim</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>XDim</em>' attribute.
* @see #setXDim(double)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_XDim()
* @model
* @generated
*/
double getXDim();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getXDim <em>XDim</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>XDim</em>' attribute.
* @see #getXDim()
* @generated
*/
void setXDim(double value);
/**
* Returns the value of the '<em><b>XDim As String</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>XDim As String</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>XDim As String</em>' attribute.
* @see #setXDimAsString(String)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_XDimAsString()
* @model
* @generated
*/
String getXDimAsString();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getXDimAsString <em>XDim As String</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>XDim As String</em>' attribute.
* @see #getXDimAsString()
* @generated
*/
void setXDimAsString(String value);
/**
* Returns the value of the '<em><b>YDim</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>YDim</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>YDim</em>' attribute.
* @see #setYDim(double)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_YDim()
* @model
* @generated
*/
double getYDim();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getYDim <em>YDim</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>YDim</em>' attribute.
* @see #getYDim()
* @generated
*/
void setYDim(double value);
/**
* Returns the value of the '<em><b>YDim As String</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>YDim As String</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>YDim As String</em>' attribute.
* @see #setYDimAsString(String)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_YDimAsString()
* @model
* @generated
*/
String getYDimAsString();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getYDimAsString <em>YDim As String</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>YDim As String</em>' attribute.
* @see #getYDimAsString()
* @generated
*/
void setYDimAsString(String value);
/**
* Returns the value of the '<em><b>ZDim</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>ZDim</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>ZDim</em>' attribute.
* @see #setZDim(double)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_ZDim()
* @model
* @generated
*/
double getZDim();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getZDim <em>ZDim</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>ZDim</em>' attribute.
* @see #getZDim()
* @generated
*/
void setZDim(double value);
/**
* Returns the value of the '<em><b>ZDim As String</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>ZDim As String</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>ZDim As String</em>' attribute.
* @see #setZDimAsString(String)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_ZDimAsString()
* @model
* @generated
*/
String getZDimAsString();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getZDimAsString <em>ZDim As String</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>ZDim As String</em>' attribute.
* @see #getZDimAsString()
* @generated
*/
void setZDimAsString(String value);
/**
* Returns the value of the '<em><b>Dim</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Dim</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Dim</em>' attribute.
* @see #isSetDim()
* @see #unsetDim()
* @see #setDim(long)
* @see org.bimserver.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcBoundingBox_Dim()
* @model unsettable="true" derived="true"
* @generated
*/
long getDim();
/**
* Sets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getDim <em>Dim</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Dim</em>' attribute.
* @see #isSetDim()
* @see #unsetDim()
* @see #getDim()
* @generated
*/
void setDim(long value);
/**
* Unsets the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getDim <em>Dim</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetDim()
* @see #getDim()
* @see #setDim(long)
* @generated
*/
void unsetDim();
/**
* Returns whether the value of the '{@link org.bimserver.models.ifc2x3tc1.IfcBoundingBox#getDim <em>Dim</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Dim</em>' attribute is set.
* @see #unsetDim()
* @see #getDim()
* @see #setDim(long)
* @generated
*/
boolean isSetDim();
} // IfcBoundingBox
| opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc2x3tc1/IfcBoundingBox.java | Java | agpl-3.0 | 9,365 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2016 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb_testprocs.regressionsuites.querytimeout;
import org.voltdb.ProcInfo;
import org.voltdb.SQLStmt;
import org.voltdb.VoltProcedure;
import org.voltdb.VoltTable;
@ProcInfo
(
singlePartition = true,
partitionInfo = "P1.PHONE_NUMBER: 0"
)
public class SPPartitionReadOnlyProc extends VoltProcedure {
public final SQLStmt longRunningCrossJoinAgg = new SQLStmt
("SELECT t1.contestant_number, t2.state, COUNT(*) "
+ "FROM P1 t1, R1 t2 "
+ "GROUP BY t1.contestant_number, t2.state;");
public VoltTable[] run(int partitionKey) {
voltQueueSQL(longRunningCrossJoinAgg);
return voltExecuteSQL(true);
}
}
| paulmartel/voltdb | tests/testprocs/org/voltdb_testprocs/regressionsuites/querytimeout/SPPartitionReadOnlyProc.java | Java | agpl-3.0 | 1,818 |
package videoworker;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import io.dropwizard.client.JerseyClientConfiguration;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
/**
* Created by Martin on 24.10.2015.
*/
public class VWConfiguration extends Configuration {
@Valid
@NotNull
private String videoDirName;
@Valid
@NotNull
private String gsServiceURL;
@Valid
@NotNull
@JsonProperty("jerseyClient")
private JerseyClientConfiguration jerseyClientConfiguration=new JerseyClientConfiguration();
@Valid
@NotNull
private int serverID;
private String jwtkey=null;
@NotNull
private String ffmpeg; //Path to the ffmpeg executable
@NotNull
private String ffprobe; //Path to the ffprobe executable
public void setVideoDirName(String videoDirName) {
this.videoDirName = videoDirName;
}
public String getVideoDirName() {
return videoDirName;
}
public String getGsServiceURL() {
return gsServiceURL;
}
public void setGsServiceURL(String gsServiceURL) {
this.gsServiceURL = gsServiceURL;
}
public JerseyClientConfiguration getJerseyClientConfiguration() {
return jerseyClientConfiguration;
}
public void setJerseyClientConfiguration(JerseyClientConfiguration jerseyClientConfiguration) {
this.jerseyClientConfiguration = jerseyClientConfiguration;
}
public int getServerID() {
return serverID;
}
public void setServerID(int serverID) {
this.serverID = serverID;
}
public String getJwtkey() {
return jwtkey;
}
public void setJwtkey(String jwtkey) {
this.jwtkey = jwtkey;
}
public String getFfmpeg() {
return ffmpeg;
}
public void setFfmpeg(String ffmpeg) {
this.ffmpeg = ffmpeg;
}
public String getFfprobe() {
return ffprobe;
}
public void setFfprobe(String ffprobe) {
this.ffprobe = ffprobe;
}
}
| gamesurvey/GSurveyCode | gsvideo/src/main/java/videoworker/VWConfiguration.java | Java | agpl-3.0 | 2,078 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2013 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2013. All rights reserved".
********************************************************************************/
abstract class ZurmoBaseController extends Controller
{
const RIGHTS_FILTER_PATH = 'application.modules.zurmo.controllers.filters.RightsControllerFilter';
const REQUIRED_ATTRIBUTES_FILTER_PATH = 'application.modules.zurmo.controllers.filters.RequiredAttributesControllerFilter';
const ADMIN_VIEW_MOBILE_CHECK_FILTER_PATH = 'application.modules.zurmo.controllers.filters.AdminViewMobileCheckControllerFilter';
public function filters()
{
$moduleClassName = $this->resolveModuleClassNameForFilters();
$filters = array();
if (is_subclass_of($moduleClassName, 'SecurableModule'))
{
$filters[] = array(
self::getRightsFilterPath(),
'moduleClassName' => $moduleClassName,
'rightName' => $moduleClassName::getAccessRight(),
);
$filters[] = array(
self::getRightsFilterPath() . ' + create, createFromRelation, inlineCreateSave, copy',
'moduleClassName' => $moduleClassName,
'rightName' => $moduleClassName::getCreateRight(),
);
$filters[] = array(
self::getRightsFilterPath() . ' + delete',
'moduleClassName' => $moduleClassName,
'rightName' => $moduleClassName::getDeleteRight(),
);
}
$filters[] = array(
self::getRightsFilterPath() . ' + massEdit, massEditProgressSave',
'moduleClassName' => 'ZurmoModule',
'rightName' => ZurmoModule::RIGHT_BULK_WRITE,
);
$filters['RIGHT_BULK_DELETE'] = array(
self::getRightsFilterPath() . ' + massDelete, massDeleteProgress',
'moduleClassName' => 'ZurmoModule',
'rightName' => ZurmoModule::RIGHT_BULK_DELETE,
);
return $filters;
}
public function resolveModuleClassNameForFilters()
{
return get_class($this->getModule());
}
public function __construct($id, $module = null)
{
parent::__construct($id, $module);
}
/**
* Override if the module is a nested module such as groups or roles.
*/
public function resolveAndGetModuleId()
{
return $this->getModule()->getId();
}
public static function getRightsFilterPath()
{
return static::RIGHTS_FILTER_PATH;
}
protected function makeActionBarSearchAndListView($searchModel, $dataProvider,
$actionBarViewClassName = 'SecuredActionBarForSearchAndListView',
$viewPrefixName = null, $activeActionElementType = null)
{
assert('is_string($actionBarViewClassName)');
assert('is_string($viewPrefixName) || $viewPrefixName == null');
assert('is_string($activeActionElementType) || $activeActionElementType == null');
if ($viewPrefixName == null)
{
$viewPrefixName = $this->getModule()->getPluralCamelCasedName();
}
$listModel = $searchModel->getModel();
return new ActionBarSearchAndListView(
$this->getId(),
$this->getModule()->getId(),
$searchModel,
$listModel,
$viewPrefixName,
$dataProvider,
GetUtil::resolveSelectedIdsFromGet(),
$actionBarViewClassName,
$activeActionElementType
);
}
protected function makeListView(SearchForm $searchForm, $dataProvider, $listViewClassName = null)
{
assert('is_string($listViewClassName) || $listViewClassName == null');
$listModel = $searchForm->getModel();
if ($listViewClassName == null)
{
$listViewClassName = $this->getModule()->getPluralCamelCasedName() . 'ListView';
}
$listView = new $listViewClassName(
$this->getId(),
$this->getModule()->getId(),
get_class($listModel),
$dataProvider,
GetUtil::resolveSelectedIdsFromGet(),
null,
array(),
$searchForm->getListAttributesSelector(),
$searchForm->getKanbanBoard());
return $listView;
}
protected function resolveSearchDataProvider(
$searchModel,
$pageSize,
$stateMetadataAdapterClassName = null,
$stickySearchKey = null,
$setSticky = true)
{
assert('$searchModel instanceof RedBeanModel || $searchModel instanceof ModelForm');
assert('$stickySearchKey == null || is_string($stickySearchKey)');
assert('is_bool($setSticky)');
$listModelClassName = get_class($searchModel->getModel());
static::resolveToTriggerOnSearchEvents($listModelClassName);
$this->resolveKanbanBoardIsActiveByGet($searchModel);
$dataCollection = $this->makeDataCollectionAndResolveSavedSearch($searchModel, $stickySearchKey, $setSticky);
$pageSize = $this->resolvePageSizeForKanbanBoard($searchModel, $pageSize);
$dataProvider = $this->makeRedBeanDataProviderByDataCollection($searchModel, $pageSize,
$stateMetadataAdapterClassName, $dataCollection);
return $dataProvider;
}
/**
* @param $searchModel
*/
private function resolveKanbanBoardIsActiveByGet($searchModel)
{
if (!$searchModel instanceof SearchForm || $searchModel->getKanbanBoard() == null)
{
return;
}
if (isset($_GET['kanbanBoard']) && $_GET['kanbanBoard'] && !Yii::app()->userInterface->isMobile())
{
$searchModel->getKanbanBoard()->setIsActive();
}
elseif (isset($_GET['kanbanBoard']) && !$_GET['kanbanBoard'])
{
$searchModel->getKanbanBoard()->setIsNotActive();
$searchModel->getKanbanBoard()->setClearSticky();
}
elseif (Yii::app()->userInterface->isMobile())
{
$searchModel->getKanbanBoard()->setIsNotActive();
}
}
/**
* @param $searchModel
* @param $pageSize
* @return int
*/
private function resolvePageSizeForKanbanBoard($searchModel, $pageSize)
{
if (!$searchModel instanceof SearchForm)
{
return $pageSize;
}
if ($searchModel->getKanbanBoard() !== null && $searchModel->getKanbanBoard()->getIsActive())
{
$pageSize = KanbanBoardExtendedGridView::resolvePageSizeForMaxCount();
}
return $pageSize;
}
private function makeDataCollectionAndResolveSavedSearch($searchModel, $stickySearchKey = null, $setSticky = true)
{
$dataCollection = new SearchAttributesDataCollection($searchModel);
if ($searchModel instanceof SavedDynamicSearchForm)
{
$getData = GetUtil::getData();
if ($stickySearchKey != null && isset($getData['clearingSearch']) && $getData['clearingSearch'])
{
StickySearchUtil::clearDataByKey($stickySearchKey);
}
if ($stickySearchKey != null && null != $stickySearchData = StickySearchUtil::getDataByKey($stickySearchKey))
{
SavedSearchUtil::resolveSearchFormByStickyDataAndModel($stickySearchData, $searchModel);
SavedSearchUtil::resolveSearchFormByStickySortData($getData, $searchModel, $stickySearchData);
$dataCollection = new SavedSearchAttributesDataCollection($searchModel);
}
else
{
SavedSearchUtil::resolveSearchFormByGetData($getData, $searchModel);
if ($searchModel->savedSearchId != null)
{
$dataCollection = new SavedSearchAttributesDataCollection($searchModel);
}
}
if ($stickySearchKey != null && ($setSticky ||
($searchModel->getKanbanBoard() != null && $searchModel->getKanbanBoard()->getClearSticky())))
{
if ($stickySearchData == null)
{
$stickySearchData = array();
}
SavedSearchUtil::setDataByKeyAndDataCollection($stickySearchKey, $dataCollection, $stickySearchData);
}
$searchModel->loadSavedSearchUrl = Yii::app()->createUrl($this->getModule()->getId() . '/' . $this->getId() . '/list/');
}
return $dataCollection;
}
protected function resolveToTriggerOnSearchEvents($listModelClassName)
{
$pageVariableName = $listModelClassName . '_page';
if (isset($_GET[$pageVariableName]) && $_GET[$pageVariableName] == null)
{
Yii::app()->gameHelper->triggerSearchModelsEvent($listModelClassName);
}
}
protected function getDataProviderByResolvingSelectAllFromGet(
$searchModel,
$pageSize,
$userId,
$stateMetadataAdapterClassName = null,
$stickySearchKey = null
)
{
assert('$searchModel instanceof RedBeanModel || $searchModel instanceof ModelForm');
assert('is_string($stickySearchKey) || $stickySearchKey == null');
if ($_GET['selectAll'])
{
if (!isset($_GET[get_class($searchModel)]) && $stickySearchKey != null)
{
$resolvedStickySearchKey = $stickySearchKey;
}
else
{
$resolvedStickySearchKey = null;
}
return $this->resolveSearchDataProvider(
$searchModel,
$pageSize,
$stateMetadataAdapterClassName,
$resolvedStickySearchKey);
}
else
{
return null;
}
}
/**
* This method is called after a mass edit form is first submitted.
* It is called from the actionMassEdit.
* @see actionMassEdit in the module default controllers.
*/
protected function processMassEdit(
$pageSize,
$activeAttributes,
$selectedRecordCount,
$pageViewClassName,
$listModel,
$title,
$dataProvider = null
)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
assert('$dataProvider == null || $dataProvider instanceof CDataProvider');
$modelClassName = get_class($listModel);
$selectedRecordCount = static::getSelectedRecordCountByResolvingSelectAllFromGet($dataProvider);
if (isset($_POST[$modelClassName]))
{
PostUtil::sanitizePostForSavingMassEdit($modelClassName);
//Generically test that the changes are valid before attempting to save on each model.
$sanitizedPostData = PostUtil::sanitizePostByDesignerTypeForSavingModel(new $modelClassName(false), $_POST[$modelClassName]);
$sanitizedOwnerPostData = PostUtil::sanitizePostDataToJustHavingElementForSavingModel($sanitizedPostData, 'owner');
$sanitizedPostDataWithoutOwner = PostUtil::removeElementFromPostDataForSavingModel($sanitizedPostData, 'owner');
$massEditPostDataWithoutOwner = PostUtil::removeElementFromPostDataForSavingModel($_POST['MassEdit'], 'owner');
$listModel->setAttributes($sanitizedPostDataWithoutOwner);
if ($listModel->validate(array_keys($massEditPostDataWithoutOwner)))
{
$passedOwnerValidation = true;
if ($sanitizedOwnerPostData != null)
{
$listModel->setAttributes($sanitizedOwnerPostData);
$passedOwnerValidation = $listModel->validate(array('owner'));
}
if ($passedOwnerValidation)
{
MassEditInsufficientPermissionSkipSavingUtil::clear($modelClassName);
Yii::app()->gameHelper->triggerMassEditEvent(get_class($listModel));
$this->saveMassEdit(
get_class($listModel),
$modelClassName,
$selectedRecordCount,
$dataProvider,
$_GET[$modelClassName . '_page'],
$pageSize
);
//cancel diminish of save scoring
if ($selectedRecordCount > $pageSize)
{
$view = new $pageViewClassName(ZurmoDefaultViewUtil::
makeStandardViewForCurrentUser($this,
$this->makeMassEditProgressView(
$listModel,
1,
$selectedRecordCount,
1,
$pageSize,
$title,
null)
));
echo $view->render();
Yii::app()->end(0, false);
}
else
{
$skipCount = MassEditInsufficientPermissionSkipSavingUtil::getCount($modelClassName);
$successfulCount = MassEditInsufficientPermissionSkipSavingUtil::resolveSuccessfulCountAgainstSkipCount(
$selectedRecordCount, $skipCount);
MassEditInsufficientPermissionSkipSavingUtil::clear($modelClassName);
$notificationContent = Zurmo::t('ZurmoModule', 'Successfully updated') . ' ' .
$successfulCount . ' ' .
LabelUtil::getUncapitalizedRecordLabelByCount($successfulCount) .
'.';
if ($skipCount > 0)
{
$notificationContent .= ' ' .
MassEditInsufficientPermissionSkipSavingUtil::getSkipCountMessageContentByModelClassName(
$skipCount, $modelClassName);
}
Yii::app()->user->setFlash('notification', $notificationContent);
$this->redirect(array('default/'));
Yii::app()->end(0, false);
}
}
}
}
return $listModel;
}
/**
* Called only during a mulitple phase save from mass edit. This occurs if the quantity of models to save
* is greater than the pageSize. This signals a save that must be conducted in phases where each phase
* updates a quantity of models no greater than the page size.
*/
protected function processMassEditProgressSave(
$modelClassName,
$pageSize,
$title,
$dataProvider = null)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
assert('$dataProvider == null || $dataProvider instanceof CDataProvider');
$listModel = new $modelClassName(false);
$selectedRecordCount = static::getSelectedRecordCountByResolvingSelectAllFromGet($dataProvider);
PostUtil::sanitizePostForSavingMassEdit($modelClassName);
$this->saveMassEdit(
get_class($listModel),
$modelClassName,
$selectedRecordCount,
$dataProvider,
$_GET[$modelClassName . '_page'],
$pageSize
);
$view = $this->makeMassEditProgressView(
$listModel,
$_GET[$modelClassName . '_page'],
$selectedRecordCount,
$this->getMassEditProgressStartFromGet(
$modelClassName,
$pageSize
),
$pageSize,
$title,
MassEditInsufficientPermissionSkipSavingUtil::getCount($modelClassName)
);
echo $view->renderRefreshJSONScript();
}
protected function makeMassEditProgressView(
$model,
$page,
$selectedRecordCount,
$start,
$pageSize,
$title,
$skipCount)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
assert('$skipCount == null || is_int($skipCount)');
return new MassEditProgressView(
$this->getId(),
$this->getModule()->getId(),
$model,
$selectedRecordCount,
$start,
$pageSize,
$page,
'massEditProgressSave',
$title,
$skipCount
);
}
/**
* Called either from a mass edit save, or a mass edit progress save.
*/
protected function saveMassEdit($modelClassName, $postVariableName, $selectedRecordCount, $dataProvider, $page, $pageSize)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
Yii::app()->gameHelper->muteScoringModelsOnSave();
$modelsToSave = $this->getModelsToSave($modelClassName, $dataProvider, $selectedRecordCount, $page, $pageSize);
foreach ($modelsToSave as $modelToSave)
{
if (ControllerSecurityUtil::doesCurrentUserHavePermissionOnSecurableItem($modelToSave, Permission::WRITE))
{
$sanitizedPostData = PostUtil::sanitizePostByDesignerTypeForSavingModel($modelToSave, $_POST[$modelClassName]);
$sanitizedOwnerPostData = PostUtil::sanitizePostDataToJustHavingElementForSavingModel($sanitizedPostData, 'owner');
$sanitizedPostDataWithoutOwner = PostUtil::removeElementFromPostDataForSavingModel($sanitizedPostData, 'owner');
$modelToSave->setAttributes($sanitizedPostDataWithoutOwner);
if ($sanitizedOwnerPostData != null)
{
$modelToSave->setAttributes($sanitizedOwnerPostData);
}
$modelToSave->save(false);
}
else
{
MassEditInsufficientPermissionSkipSavingUtil::setByModelIdAndName(
$modelClassName, $modelToSave->id, $modelToSave->name);
}
}
Yii::app()->gameHelper->unmuteScoringModelsOnSave();
}
/**
* This method is called after a mass delete form is first submitted.
* It is called from the actionMassDelete.
* @see actionMassDelete in the module default controllers.
*/
protected function processMassDelete(
$pageSize,
$activeAttributes,
$selectedRecordCount,
$pageViewClassName,
$listModel,
$title,
$dataProvider = null,
$redirectUrl = null
)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
assert('$dataProvider == null || $dataProvider instanceof CDataProvider');
$modelClassName = get_class($listModel);
$selectedRecordCount = static::getSelectedRecordCountByResolvingSelectAllFromGet($dataProvider);
if (isset($_POST['selectedRecordCount']))
{
$this->doMassDelete(
get_class($listModel),
$modelClassName,
$selectedRecordCount,
$dataProvider,
$_GET[$modelClassName . '_page'],
$pageSize
);
// Cancel diminish of save scoring
if ($selectedRecordCount > $pageSize)
{
$view = new $pageViewClassName( ZurmoDefaultViewUtil::
makeStandardViewForCurrentUser($this,
$this->makeMassDeleteProgressView(
$listModel,
1,
$selectedRecordCount,
1,
$pageSize,
$title,
null)
));
echo $view->render();
Yii::app()->end(0, false);
}
else
{
$skipCount = MassDeleteInsufficientPermissionSkipSavingUtil::getCount($modelClassName);
$successfulCount = MassDeleteInsufficientPermissionSkipSavingUtil::resolveSuccessfulCountAgainstSkipCount(
$selectedRecordCount, $skipCount);
MassDeleteInsufficientPermissionSkipSavingUtil::clear($modelClassName);
$notificationContent = $successfulCount . ' ' .
LabelUtil::getUncapitalizedRecordLabelByCount($successfulCount) .
' ' . Zurmo::t('ZurmoModule', 'successfully deleted') . '.';
if ($skipCount > 0)
{
$notificationContent .= ' ' .
MassDeleteInsufficientPermissionSkipSavingUtil::getSkipCountMessageContentByModelClassName(
$skipCount, $modelClassName);
}
Yii::app()->user->setFlash('notification', $notificationContent);
if ($redirectUrl === null)
{
$this->redirect(array('default/'));
}
else
{
$this->redirect($redirectUrl);
}
Yii::app()->end(0, false);
}
}
return $listModel;
}
protected function processMassDeleteProgress(
$modelClassName,
$pageSize,
$title,
$dataProvider = null)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
assert('$dataProvider == null || $dataProvider instanceof CDataProvider');
$listModel = new $modelClassName(false);
$postData = PostUtil::getData();
$selectedRecordCount = ArrayUtil::getArrayValue($postData, 'selectedRecordCount');
$this->doMassDelete(
get_class($listModel),
$modelClassName,
$selectedRecordCount,
$dataProvider,
$_GET[$modelClassName . '_page'],
$pageSize
);
$view = $this->makeMassDeleteProgressView(
$listModel,
$_GET[$modelClassName . '_page'],
$selectedRecordCount,
$this->getMassDeleteProgressStartFromGet(
$modelClassName,
$pageSize
),
$pageSize,
$title,
MassDeleteInsufficientPermissionSkipSavingUtil::getCount($modelClassName)
);
echo $view->renderRefreshJSONScript();
}
protected function makeMassDeleteProgressView(
$model,
$page,
$selectedRecordCount,
$start,
$pageSize,
$title,
$skipCount)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
assert('$skipCount == null || is_int($skipCount)');
return new MassDeleteProgressView(
$this->getId(),
$this->getModule()->getId(),
$model,
$selectedRecordCount,
$start,
$pageSize,
$page,
'massDeleteProgress',
$title,
$skipCount
);
}
protected function doMassDelete($modelClassName, $postVariableName, $selectedRecordCount, $dataProvider, $page, $pageSize)
{
// TODO: @Shoaibi/@Jason: Low: Deprecated
// trigger_error('Deprecated');
Yii::app()->gameHelper->muteScoringModelsOnDelete();
$modelsToDelete = $this->getModelsToDelete($modelClassName, $dataProvider, $selectedRecordCount, $page, $pageSize);
foreach ($modelsToDelete as $modelToDelete)
{
if (ControllerSecurityUtil::doesCurrentUserHavePermissionOnSecurableItem($modelToDelete, Permission::DELETE))
{
$modelToDelete->delete(false);
}
else
{
MassDeleteInsufficientPermissionSkipSavingUtil::setByModelIdAndName(
$modelClassName, $modelToDelete->id, $modelToDelete->name);
}
}
Yii::app()->gameHelper->unmuteScoringModelsOnDelete();
}
protected static function resolvePageValueForMassAction($modelClassName)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
return intval(Yii::app()->request->getQuery($modelClassName . '_page'));
}
protected function resolveReturnUrlForMassAction()
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
return $this->createUrl('/' . $this->getModule()->getId() . '/' . $this->getId() . '/');
}
protected static function resolveViewIdByMassActionId($actionId, $returnProgressViewName, $moduleName = null)
{
if (strpos($actionId, 'massEdit') === 0 || strpos($actionId, 'massDelete') === 0)
{
$viewNameSuffix = (!$returnProgressViewName)? 'View': 'ProgressView';
$viewNamePrefix = static::resolveMassActionId($actionId, true);
if (strpos($actionId, 'massEdit') === 0)
{
$viewNamePrefix = $moduleName . $viewNamePrefix;
}
return $viewNamePrefix . $viewNameSuffix;
}
else
{
throw new NotSupportedException();
}
}
protected static function resolveTitleByMassActionId($actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
if (strpos($actionId, 'massDelete') === 0)
{
return Zurmo::t('Core', 'Mass Delete');
}
elseif (strpos($actionId, 'massEdit') === 0)
{
return Zurmo::t('Core', 'Mass Update');
}
else
{
throw new NotSupportedException();
}
}
/**
* Check if form is posted. If form is posted attempt to save. If save is complete, confirm the current
* user can still read the model. If not, then redirect the user to the index action for the module.
*/
protected function attemptToSaveModelFromPost($model, $redirectUrlParams = null, $redirect = true)
{
assert('$redirectUrlParams == null || is_array($redirectUrlParams) || is_string($redirectUrlParams)');
$savedSuccessfully = false;
$modelToStringValue = null;
$postVariableName = get_class($model);
if (isset($_POST[$postVariableName]))
{
$postData = $_POST[$postVariableName];
$controllerUtil = static::getZurmoControllerUtil();
$model = $controllerUtil->saveModelFromPost($postData, $model, $savedSuccessfully,
$modelToStringValue);
}
if ($savedSuccessfully && $redirect)
{
$this->actionAfterSuccessfulModelSave($model, $modelToStringValue, $redirectUrlParams);
}
return $model;
}
protected static function getZurmoControllerUtil()
{
return new ZurmoControllerUtil();
}
protected function actionAfterSuccessfulModelSave($model, $modelToStringValue, $redirectUrlParams = null)
{
assert('is_string($modelToStringValue)');
assert('$redirectUrlParams == null || is_array($redirectUrlParams) || is_string($redirectUrlParams)');
if (ControllerSecurityUtil::doesCurrentUserHavePermissionOnSecurableItem($model, Permission::READ))
{
$this->redirectAfterSaveModel($model->id, $redirectUrlParams);
}
else
{
$notificationContent = Zurmo::t('ZurmoModule', 'You no longer have permissions to access {modelName}.',
array('{modelName}' => $modelToStringValue)
);
Yii::app()->user->setFlash('notification', $notificationContent);
$this->redirect(array($this->getId() . '/index'));
}
}
protected function redirectAfterSaveModel($modelId, $urlParams = null)
{
if ($urlParams == null)
{
$urlParams = array($this->getId() . '/details', 'id' => $modelId);
}
$this->redirect($urlParams);
}
protected static function getModelAndCatchNotFoundAndDisplayError($modelClassName, $id)
{
assert('is_string($modelClassName)');
assert('is_int($id)');
try
{
return $modelClassName::getById($id);
}
catch (NotFoundException $e)
{
$messageContent = Zurmo::t('ZurmoModule', 'The record you are trying to access does not exist.');
$messageView = new ModelNotFoundView($messageContent);
$view = new ModelNotFoundPageView($messageView);
echo $view->render();
Yii::app()->end(0, false);
}
}
protected function triggerMassAction($modelClassName, $searchForm, $pageView, $title, $searchView = null,
$stateMetadataAdapterClassName = null, $useModuleClassNameForItemLabel = true)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$actionId = $this->getAction()->getId();
$pageSize = static::resolvePageSizeByMassActionId($actionId);
$model = new $modelClassName(false);
$dataProvider = $this->getDataProviderByResolvingSelectAllFromGet(
new $searchForm($model),
$pageSize,
Yii::app()->user->userModel->id,
$stateMetadataAdapterClassName,
$searchView
);
if (strpos($actionId, 'Progress') !== false)
{
$this->massActionProgress($model, $pageSize, $title, $actionId, $dataProvider);
}
else
{
$this->massAction($model, $pageSize, $title, $pageView, $actionId, $dataProvider, $useModuleClassNameForItemLabel);
}
}
protected function massActionProgress($model, $pageSize, $title, $actionId, $dataProvider)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$this->processMassActionProgress(
$model,
$pageSize,
$title,
$actionId,
$dataProvider
);
}
protected function massAction($model, $pageSize, $title, $pageView, $actionId, $dataProvider, $useModuleClassNameForItemLabel = true)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$activeAttributes = static::resolveActiveAttributesFromPostForMassAction($actionId);
$selectedRecordCount = static::resolveSelectedRecordCountByMassActionId($actionId, $dataProvider, array());
$model = $this->processMassAction(
$pageSize,
$selectedRecordCount,
$pageView,
$model,
$title,
$actionId,
$dataProvider
);
$massActionView = $this->makeMassActionView(
$model,
$activeAttributes,
$selectedRecordCount,
$title,
$actionId,
$useModuleClassNameForItemLabel
);
$view = new $pageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser(
$this, $massActionView));
echo $view->render();
}
protected function processMassAction($pageSize, $selectedRecordCount, $pageViewClassName, $listModel, $title,
$actionId, $dataProvider = null)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
assert('$dataProvider == null || $dataProvider instanceof CDataProvider');
$postSelectedRecordCount = Yii::app()->request->getPost('selectedRecordCount');
$modelClassName = get_class($listModel);
$postModelClassName = Yii::app()->request->getPost($modelClassName);
if (isset($postSelectedRecordCount) || isset($postModelClassName))
{
$page = static::resolvePageValueForMassAction($modelClassName);
$insufficientPermissionSkipSavingUtil = static::resolveInsufficientPermissionSkipSavingUtilByMassActionId($actionId);
$start = ($selectedRecordCount > $pageSize)? 1: $selectedRecordCount;
$skipCount = ($selectedRecordCount > $pageSize)? null: 0;
$massActionSuccessful = static::processModelsForMassAction($listModel,
$modelClassName,
$selectedRecordCount,
$dataProvider,
$page,
$pageSize,
$insufficientPermissionSkipSavingUtil,
$postModelClassName,
$actionId);
if ($massActionSuccessful)
{
$progressView = $this->makeMassActionProgressView(
$listModel,
1,
$selectedRecordCount,
$start,
$pageSize,
$title,
$skipCount,
$actionId);
if ($selectedRecordCount > $pageSize)
{
$view = new $pageViewClassName(
ZurmoDefaultViewUtil::makeStandardViewForCurrentUser(
$this, $progressView));
echo $view->render();
}
else
{
$refreshScript = $progressView->renderRefreshScript();
Yii::app()->user->setFlash('notification', $refreshScript['message']);
$this->redirect($this->resolveReturnUrlForMassAction());
}
Yii::app()->end(0, false);
}
}
return $listModel;
}
protected static function processModelsForMassAction($model, $modelClassName, $selectedRecordCount, $dataProvider,
$page, $pageSize, $insufficientPermissionSkipSavingUtil,
$postModelClassName, $actionId)
{
$doMassActionFunctionName = 'processModelsForMassActionWithoutScoring';
$doMassActionFunctionArguments = array(
$modelClassName,
$selectedRecordCount,
$dataProvider,
$page,
$pageSize,
$insufficientPermissionSkipSavingUtil,
$actionId
);
if (strpos($actionId, 'massEdit') === 0 && strpos($actionId, 'Progress') === false)
{
$doMassActionFunctionName = 'processModelsForMassEditAction';
array_unshift($doMassActionFunctionArguments, $postModelClassName, $model);
}
$doMassActionFunctionName = 'static::' . $doMassActionFunctionName;
return call_user_func_array($doMassActionFunctionName, $doMassActionFunctionArguments);
}
protected static function processModelsForMassActionWithoutScoring($modelClassName, $selectedRecordCount, $dataProvider,
$page, $pageSize, $insufficientPermissionSkipSavingUtil, $actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$returnValue = false;
static::toggleMuteScoringModelValueByMassActionId($actionId, true);
$modelsToProcess = static::getModelsToUpdate($modelClassName, $dataProvider, $selectedRecordCount, $page, $pageSize);
$modelPermission = static::resolvePermissionOnSecurableItemByMassActionId($actionId);
foreach ($modelsToProcess as $modelToProcess)
{
if (ControllerSecurityUtil::doesCurrentUserHavePermissionOnSecurableItem($modelToProcess, $modelPermission))
{
$function = 'processModelFor' . static::resolveMassActionId($actionId, true);
$returnValue = static::$function($modelToProcess);
}
else
{
$insufficientPermissionSkipSavingUtil::setByModelIdAndName($modelClassName,
$modelToProcess->id,
$modelToProcess->name);
}
}
static::toggleMuteScoringModelValueByMassActionId($actionId, false);
return $returnValue;
}
protected static function processModelsForMassEditAction($postModelClassName, $model, $modelClassName, $selectedRecordCount, $dataProvider,
$page, $pageSize, $insufficientPermissionSkipSavingUtil, $actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
PostUtil::sanitizePostForSavingMassEdit($modelClassName);
//Generically test that the changes are valid before attempting to save on each model.
$sanitizedPostData = PostUtil::sanitizePostByDesignerTypeForSavingModel(new $modelClassName(false), $postModelClassName);
$sanitizedOwnerPostData = PostUtil::sanitizePostDataToJustHavingElementForSavingModel($sanitizedPostData, 'owner');
$sanitizedPostDataWithoutOwner = PostUtil::removeElementFromPostDataForSavingModel($sanitizedPostData, 'owner');
$postMassEdit = Yii::app()->request->getPost('MassEdit');
$massEditPostDataWithoutOwner = PostUtil::removeElementFromPostDataForSavingModel($postMassEdit, 'owner');
$model->setAttributes($sanitizedPostDataWithoutOwner);
if ($model->validate(array_keys($massEditPostDataWithoutOwner)))
{
$passedOwnerValidation = true;
if ($sanitizedOwnerPostData != null)
{
$model->setAttributes($sanitizedOwnerPostData);
$passedOwnerValidation = $model->validate(array('owner'));
}
if ($passedOwnerValidation)
{
MassEditInsufficientPermissionSkipSavingUtil::clear($modelClassName);
Yii::app()->gameHelper->triggerMassEditEvent($modelClassName);
return static::processModelsForMassActionWithoutScoring($modelClassName, $selectedRecordCount, $dataProvider,
$page, $pageSize, $insufficientPermissionSkipSavingUtil, $actionId);
}
}
return false;
}
protected function makeMassActionView(
$model,
$activeAttributes,
$selectedRecordCount,
$title,
$actionId,
$useModuleClassNameForItemLabel = true)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$moduleName = $this->getModule()->getPluralCamelCasedName();
$moduleClassName = $moduleName . 'Module';
$alertMessage = static::resolveMassActionAlertMessage(get_class($model), $actionId);
$title = static::resolveTitleByMassActionId($actionId) . ': ' . $title;
$massActionViewClassName = static::resolveViewIdByMassActionId($actionId, false, $moduleName);
$view = new $massActionViewClassName(
$this->getId(),
$this->getModule()->getId(),
$model,
$activeAttributes,
$selectedRecordCount,
$title,
$alertMessage,
$moduleClassName,
$useModuleClassNameForItemLabel);
return $view;
}
protected function processMassActionProgress(
$listModel,
$pageSize,
$title,
$actionId,
$dataProvider = null)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
assert('$dataProvider == null || $dataProvider instanceof CDataProvider');
$modelClassName = get_class($listModel);
$startPage = static::resolvePageValueForMassAction($modelClassName);
$postData = static::resolvePostDataByMassActionId($actionId, $modelClassName);
$postModelClassName = Yii::app()->request->getPost($modelClassName);
$pageVariableName = $modelClassName . '_page';
$selectedRecordCount = static::resolveSelectedRecordCountByMassActionId($actionId, $dataProvider, $postData);
$insufficientPermissionSkipSavingUtil = static::resolveInsufficientPermissionSkipSavingUtilByMassActionId($actionId);
static::processModelsForMassAction($listModel,
$modelClassName,
$selectedRecordCount,
$dataProvider,
$startPage,
$pageSize,
$insufficientPermissionSkipSavingUtil,
$postModelClassName,
$actionId);
$view = $this->makeMassActionProgressView(
$listModel,
$startPage,
$selectedRecordCount,
static::getMassActionProgressStartFromGet($pageVariableName, $pageSize),
$pageSize,
$title,
$insufficientPermissionSkipSavingUtil::getCount($modelClassName),
$actionId);
echo $view->renderRefreshJSONScript();
}
protected function makeMassActionProgressView(
$model,
$page,
$selectedRecordCount,
$start,
$pageSize,
$title,
$skipCount,
$actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
assert('$skipCount == null || is_int($skipCount)');
$massActionProgressActionName = static::resolveProgressActionId($actionId);
$progressViewClassName = static::resolveViewIdByMassActionId($actionId, true);
$params = $this->resolveParamsForMassProgressView();
return new $progressViewClassName(
$this->getId(),
$this->getModule()->getId(),
$model,
$selectedRecordCount,
$start,
$pageSize,
$page,
$massActionProgressActionName,
$title,
$skipCount,
$params
);
}
protected static function resolvePostDataByMassActionId($actionId, $modelClassName = null)
{
if (strpos($actionId, 'massEdit') === 0)
{
PostUtil::sanitizePostForSavingMassEdit($modelClassName);
}
return PostUtil::getData();
}
protected static function resolveSelectedRecordCountByMassActionId($actionId, $dataProvider = null, $postData = array())
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$selectedRecordCount = static::getSelectedRecordCountByResolvingSelectAllFromGet($dataProvider);
if (strpos($actionId, 'Progress') !== false && strpos($actionId, 'massEdit') === false)
{
$selectedRecordCount = ArrayUtil::getArrayValue($postData, 'selectedRecordCount');
}
return $selectedRecordCount;
}
protected static function resolveMassActionAlertMessage($postVariableName, $actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$actionId = static::resolveMassActionId($actionId, true);
$alertMessageHandler = 'resolve' . $actionId . 'AlertMessage';
return (method_exists(get_called_class(), $alertMessageHandler))?
static::$alertMessageHandler($postVariableName) : null;
}
protected static function resolvePageSizeByMassActionId($actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$type = 'massEditProgressPageSize';
if (strpos($actionId, 'massDelete') === 0)
{
$type = 'massDeleteProgressPageSize';
}
return Yii::app()->pagination->resolveActiveForCurrentUserByType($type);
}
protected static function toggleMuteScoringModelValueByMassActionId($actionId, $mute = true)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$toggle = ($mute)? 'mute' : 'unmute';
$function = (strpos($actionId, 'massDelete') === 0)? 'Delete' : 'Save';
$function = $toggle . 'ScoringModelsOn' . $function;
Yii::app()->gameHelper->$function();
}
protected static function resolvePermissionOnSecurableItemByMassActionId($actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
return (strpos($actionId, 'massDelete') === 0) ? Permission::DELETE : Permission::WRITE;
}
protected static function processModelForMassDelete(& $model)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
if (!$model->delete(false))
{
throw new FailedToDeleteModelException();
}
else
{
return true;
}
}
protected static function processModelForMassEdit(& $model)
{
$postModelClassName = Yii::app()->request->getPost(get_class($model));
$sanitizedPostData = PostUtil::sanitizePostByDesignerTypeForSavingModel($model, $postModelClassName);
$sanitizedOwnerPostData = PostUtil::sanitizePostDataToJustHavingElementForSavingModel($sanitizedPostData, 'owner');
$sanitizedPostDataWithoutOwner = PostUtil::removeElementFromPostDataForSavingModel($sanitizedPostData, 'owner');
$model->setAttributes($sanitizedPostDataWithoutOwner);
if ($sanitizedOwnerPostData != null)
{
$model->setAttributes($sanitizedOwnerPostData);
}
if (!$model->save(false))
{
throw new FailedToSaveModelException();
}
else
{
return true;
}
}
protected static function resolveInsufficientPermissionSkipSavingUtilByMassActionId($actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$insufficientPermissionSkipSavingUtil = 'MassEditInsufficientPermissionSkipSavingUtil';
if (strpos($actionId, 'massDelete') === 0)
{
$insufficientPermissionSkipSavingUtil = 'MassDeleteInsufficientPermissionSkipSavingUtil';
}
return $insufficientPermissionSkipSavingUtil;
}
protected static function resolveProgressActionId($actionId)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$actionId = static::resolveMassActionId($actionId, false);
$actionId .= 'Progress';
$actionId = (strpos($actionId, 'massEdit') === 0)? $actionId . 'Save' : $actionId;
return $actionId;
}
protected function resolveParamsForMassProgressView()
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
return array(
'insufficientPermissionSkipSavingUtil' => null,
'returnUrl' => $this->resolveReturnUrlForMassAction(),
'returnMessage' => null,
);
}
protected static function resolveMassActionId($actionId, $capitalizeFirst = true)
{
// TODO: @Shoaibi/@Jason: Low: Candidate for MassActionController
$actionId = str_replace(array('Progress', 'Save'), '', $actionId);
return ($capitalizeFirst)? ucfirst($actionId) : $actionId;
}
protected function resolveActiveElementTypeForKanbanBoard(SearchForm $searchForm)
{
if ($searchForm->getKanbanBoard()->getIsActive())
{
return ListViewTypesToggleLinkActionElement::TYPE_KANBAN_BOARD;
}
else
{
return ListViewTypesToggleLinkActionElement::TYPE_GRID;
}
}
}
?>
| sandeep1027/zurmo_ | app/protected/modules/zurmo/components/ZurmoBaseController.php | PHP | agpl-3.0 | 61,140 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
********************************************************************************/
$mod_strings = array (
'LBL_LIST_ORDER' => 'Kolejność:',
'LBL_LIST_LIST_ORDER' => 'Kolejność',
'LBL_ID' => 'ID',
'LBL_DATE_ENTERED' => 'Data wprowadzenia',
'LBL_DATE_MODIFIED' => 'Data modyfikacji',
'LBL_MODIFIED_USER_ID' => 'ID użytkownika zmodyfikowanego',
'LBL_CREATED_BY' => 'Utworzone przez',
'LBL_DELETED' => 'Usunięte',
'LBL_DOCUMENTS' => 'Dokumenty',
'LBL_TYPE_NAME' => 'Wpisz nazwę',
'LBL_MODULE_NAME' => 'Typ kontraktu',
'LBL_MODULE_TITLE' => 'Typy kontraktów',
'LBL_LIST_FORM_TITLE' => 'Typy kontraktów',
'LBL_CONTRACT_TYPE' => 'Typ kontraktu',
'LNK_CONTRACTTYPE_LIST' => 'Pokaż typy kontraktów',
'LNK_NEW_CONTRACTTYPE' => 'Utwórz typ kontraktu',
'LBL_LIST_NAME' => 'Nazwa',
'LBL_NAME' => 'Nazwa:',
'NTC_DELETE_CONFIRMATION' => 'Usunąć typ kontraktu?',
'LBL_DOCUMENTS_SUBPANEL_TITLE' => 'Dokumenty',
'LBL_SEARCH_FORM_TITLE' => 'Wyszukiwanie typów kontraktów',
);
| harish-patel/ecrm | modules/ContractTypes/language/pl_PL.lang.php | PHP | agpl-3.0 | 2,751 |
'use strict';
var Tokenizer = require('../tokenization/tokenizer'),
HTML = require('./html');
//Aliases
var $ = HTML.TAG_NAMES,
NS = HTML.NAMESPACES,
ATTRS = HTML.ATTRS;
//MIME types
var MIME_TYPES = {
TEXT_HTML: 'text/html',
APPLICATION_XML: 'application/xhtml+xml'
};
//Attributes
var DEFINITION_URL_ATTR = 'definitionurl',
ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL',
SVG_ATTRS_ADJUSTMENT_MAP = {
'attributename': 'attributeName',
'attributetype': 'attributeType',
'basefrequency': 'baseFrequency',
'baseprofile': 'baseProfile',
'calcmode': 'calcMode',
'clippathunits': 'clipPathUnits',
'contentscripttype': 'contentScriptType',
'contentstyletype': 'contentStyleType',
'diffuseconstant': 'diffuseConstant',
'edgemode': 'edgeMode',
'externalresourcesrequired': 'externalResourcesRequired',
'filterres': 'filterRes',
'filterunits': 'filterUnits',
'glyphref': 'glyphRef',
'gradienttransform': 'gradientTransform',
'gradientunits': 'gradientUnits',
'kernelmatrix': 'kernelMatrix',
'kernelunitlength': 'kernelUnitLength',
'keypoints': 'keyPoints',
'keysplines': 'keySplines',
'keytimes': 'keyTimes',
'lengthadjust': 'lengthAdjust',
'limitingconeangle': 'limitingConeAngle',
'markerheight': 'markerHeight',
'markerunits': 'markerUnits',
'markerwidth': 'markerWidth',
'maskcontentunits': 'maskContentUnits',
'maskunits': 'maskUnits',
'numoctaves': 'numOctaves',
'pathlength': 'pathLength',
'patterncontentunits': 'patternContentUnits',
'patterntransform': 'patternTransform',
'patternunits': 'patternUnits',
'pointsatx': 'pointsAtX',
'pointsaty': 'pointsAtY',
'pointsatz': 'pointsAtZ',
'preservealpha': 'preserveAlpha',
'preserveaspectratio': 'preserveAspectRatio',
'primitiveunits': 'primitiveUnits',
'refx': 'refX',
'refy': 'refY',
'repeatcount': 'repeatCount',
'repeatdur': 'repeatDur',
'requiredextensions': 'requiredExtensions',
'requiredfeatures': 'requiredFeatures',
'specularconstant': 'specularConstant',
'specularexponent': 'specularExponent',
'spreadmethod': 'spreadMethod',
'startoffset': 'startOffset',
'stddeviation': 'stdDeviation',
'stitchtiles': 'stitchTiles',
'surfacescale': 'surfaceScale',
'systemlanguage': 'systemLanguage',
'tablevalues': 'tableValues',
'targetx': 'targetX',
'targety': 'targetY',
'textlength': 'textLength',
'viewbox': 'viewBox',
'viewtarget': 'viewTarget',
'xchannelselector': 'xChannelSelector',
'ychannelselector': 'yChannelSelector',
'zoomandpan': 'zoomAndPan'
},
XML_ATTRS_ADJUSTMENT_MAP = {
'xlink:actuate': {prefix: 'xlink', name: 'actuate', namespace: NS.XLINK},
'xlink:arcrole': {prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK},
'xlink:href': {prefix: 'xlink', name: 'href', namespace: NS.XLINK},
'xlink:role': {prefix: 'xlink', name: 'role', namespace: NS.XLINK},
'xlink:show': {prefix: 'xlink', name: 'show', namespace: NS.XLINK},
'xlink:title': {prefix: 'xlink', name: 'title', namespace: NS.XLINK},
'xlink:type': {prefix: 'xlink', name: 'type', namespace: NS.XLINK},
'xml:base': {prefix: 'xml', name: 'base', namespace: NS.XML},
'xml:lang': {prefix: 'xml', name: 'lang', namespace: NS.XML},
'xml:space': {prefix: 'xml', name: 'space', namespace: NS.XML},
'xmlns': {prefix: '', name: 'xmlns', namespace: NS.XMLNS},
'xmlns:xlink': {prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS}
};
//SVG tag names adjustment map
var SVG_TAG_NAMES_ADJUSTMENT_MAP = {
'altglyph': 'altGlyph',
'altglyphdef': 'altGlyphDef',
'altglyphitem': 'altGlyphItem',
'animatecolor': 'animateColor',
'animatemotion': 'animateMotion',
'animatetransform': 'animateTransform',
'clippath': 'clipPath',
'feblend': 'feBlend',
'fecolormatrix': 'feColorMatrix',
'fecomponenttransfer': 'feComponentTransfer',
'fecomposite': 'feComposite',
'feconvolvematrix': 'feConvolveMatrix',
'fediffuselighting': 'feDiffuseLighting',
'fedisplacementmap': 'feDisplacementMap',
'fedistantlight': 'feDistantLight',
'feflood': 'feFlood',
'fefunca': 'feFuncA',
'fefuncb': 'feFuncB',
'fefuncg': 'feFuncG',
'fefuncr': 'feFuncR',
'fegaussianblur': 'feGaussianBlur',
'feimage': 'feImage',
'femerge': 'feMerge',
'femergenode': 'feMergeNode',
'femorphology': 'feMorphology',
'feoffset': 'feOffset',
'fepointlight': 'fePointLight',
'fespecularlighting': 'feSpecularLighting',
'fespotlight': 'feSpotLight',
'fetile': 'feTile',
'feturbulence': 'feTurbulence',
'foreignobject': 'foreignObject',
'glyphref': 'glyphRef',
'lineargradient': 'linearGradient',
'radialgradient': 'radialGradient',
'textpath': 'textPath'
};
//Tags that causes exit from foreign content
var EXITS_FOREIGN_CONTENT = {};
EXITS_FOREIGN_CONTENT[$.B] = true;
EXITS_FOREIGN_CONTENT[$.BIG] = true;
EXITS_FOREIGN_CONTENT[$.BLOCKQUOTE] = true;
EXITS_FOREIGN_CONTENT[$.BODY] = true;
EXITS_FOREIGN_CONTENT[$.BR] = true;
EXITS_FOREIGN_CONTENT[$.CENTER] = true;
EXITS_FOREIGN_CONTENT[$.CODE] = true;
EXITS_FOREIGN_CONTENT[$.DD] = true;
EXITS_FOREIGN_CONTENT[$.DIV] = true;
EXITS_FOREIGN_CONTENT[$.DL] = true;
EXITS_FOREIGN_CONTENT[$.DT] = true;
EXITS_FOREIGN_CONTENT[$.EM] = true;
EXITS_FOREIGN_CONTENT[$.EMBED] = true;
EXITS_FOREIGN_CONTENT[$.H1] = true;
EXITS_FOREIGN_CONTENT[$.H2] = true;
EXITS_FOREIGN_CONTENT[$.H3] = true;
EXITS_FOREIGN_CONTENT[$.H4] = true;
EXITS_FOREIGN_CONTENT[$.H5] = true;
EXITS_FOREIGN_CONTENT[$.H6] = true;
EXITS_FOREIGN_CONTENT[$.HEAD] = true;
EXITS_FOREIGN_CONTENT[$.HR] = true;
EXITS_FOREIGN_CONTENT[$.I] = true;
EXITS_FOREIGN_CONTENT[$.IMG] = true;
EXITS_FOREIGN_CONTENT[$.LI] = true;
EXITS_FOREIGN_CONTENT[$.LISTING] = true;
EXITS_FOREIGN_CONTENT[$.MENU] = true;
EXITS_FOREIGN_CONTENT[$.META] = true;
EXITS_FOREIGN_CONTENT[$.NOBR] = true;
EXITS_FOREIGN_CONTENT[$.OL] = true;
EXITS_FOREIGN_CONTENT[$.P] = true;
EXITS_FOREIGN_CONTENT[$.PRE] = true;
EXITS_FOREIGN_CONTENT[$.RUBY] = true;
EXITS_FOREIGN_CONTENT[$.s] = true;
EXITS_FOREIGN_CONTENT[$.SMALL] = true;
EXITS_FOREIGN_CONTENT[$.SPAN] = true;
EXITS_FOREIGN_CONTENT[$.STRONG] = true;
EXITS_FOREIGN_CONTENT[$.STRIKE] = true;
EXITS_FOREIGN_CONTENT[$.SUB] = true;
EXITS_FOREIGN_CONTENT[$.SUP] = true;
EXITS_FOREIGN_CONTENT[$.TABLE] = true;
EXITS_FOREIGN_CONTENT[$.TT] = true;
EXITS_FOREIGN_CONTENT[$.U] = true;
EXITS_FOREIGN_CONTENT[$.UL] = true;
EXITS_FOREIGN_CONTENT[$.VAR] = true;
//Check exit from foreign content
exports.causesExit = function (startTagToken) {
var tn = startTagToken.tagName;
if (tn === $.FONT && (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null ||
Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null ||
Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null)) {
return true;
}
return EXITS_FOREIGN_CONTENT[tn];
};
//Token adjustments
exports.adjustTokenMathMLAttrs = function (token) {
for (var i = 0; i < token.attrs.length; i++) {
if (token.attrs[i].name === DEFINITION_URL_ATTR) {
token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;
break;
}
}
};
exports.adjustTokenSVGAttrs = function (token) {
for (var i = 0; i < token.attrs.length; i++) {
var adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];
if (adjustedAttrName)
token.attrs[i].name = adjustedAttrName;
}
};
exports.adjustTokenXMLAttrs = function (token) {
for (var i = 0; i < token.attrs.length; i++) {
var adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];
if (adjustedAttrEntry) {
token.attrs[i].prefix = adjustedAttrEntry.prefix;
token.attrs[i].name = adjustedAttrEntry.name;
token.attrs[i].namespace = adjustedAttrEntry.namespace;
}
}
};
exports.adjustTokenSVGTagName = function (token) {
var adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName];
if (adjustedTagName)
token.tagName = adjustedTagName;
};
//Integration points
exports.isMathMLTextIntegrationPoint = function (tn, ns) {
return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT);
};
exports.isHtmlIntegrationPoint = function (tn, ns, attrs) {
if (ns === NS.MATHML && tn === $.ANNOTATION_XML) {
for (var i = 0; i < attrs.length; i++) {
if (attrs[i].name === ATTRS.ENCODING) {
var value = attrs[i].value.toLowerCase();
return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;
}
}
}
return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE);
};
| Adimpression/NewsMute | service/lambda/counsellor/node_modules/cheerio/node_modules/jsdom/node_modules/parse5/lib/common/foreign_content.js | JavaScript | agpl-3.0 | 9,186 |
/* Copyright © 2016 Lukas Rosenthaler, André Kilchenmann, Andreas Aeschlimann,
* Sofia Georgakopoulou, Ivan Subotic, Benjamin Geer, Tobias Schweizer.
* This file is part of SALSAH.
* SALSAH is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* SALSAH 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.
* You should have received a copy of the GNU Affero General Public
* License along with SALSAH. If not, see <http://www.gnu.org/licenses/>.
* */
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { ApiServiceError, Project, ProjectsService } from '@knora/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'salsah-project',
templateUrl: './project.component.html',
styleUrls: ['./project.component.scss']
})
export class ProjectComponent implements OnInit {
isLoading: boolean = true;
errorMessage: any = undefined;
project: Project = new Project();
projectRoute: string;
projectAdmin: boolean = false;
firstTab: boolean;
public menu: any = [
{
name: 'Team',
route: 'team'
},
{
name: 'Ontologies',
route: 'ontologies'
},
{
name: 'Lists',
route: 'lists'
}
];
public currentProject: string = undefined;
constructor(private _title: Title,
private _router: Router,
private _route: ActivatedRoute,
private _projectsService: ProjectsService) {
}
ngOnInit() {
sessionStorage.removeItem('currentProject');
this._route.params.subscribe((params: Params) => {
// get the project shortname from the route
this.currentProject = params['pid'];
// set the root of the project route; it's needed for the first tab
this.projectRoute = '/project/' + this.currentProject;
this.firstTab = (this._router.url === this.projectRoute);
// set the metadata page title
this._title.setTitle('Salsah | Project (' + this.currentProject + ')');
// get the project information
this._projectsService.getProjectByShortname(this.currentProject)
.subscribe(
(result: Project) => {
this.project = result;
sessionStorage.setItem('currentProject', JSON.stringify(this.project));
this.isLoading = false;
},
(error: ApiServiceError) => {
console.log(error);
this.errorMessage = <any>error;
sessionStorage.removeItem('currentProject');
this.isLoading = false;
}
);
});
if (this.currentProject === 'new') {
alert('Create a new project!?');
}
}
toggleFirstTab(first: boolean) {
this.firstTab = first === true;
}
}
| dhlab-basel/Salsah | src/app/view/dashboard/project/project.component.ts | TypeScript | agpl-3.0 | 3,384 |
/********
* This file is part of Ext.NET.
*
* Ext.NET is free software: you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Ext.NET is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with Ext.NET. If not, see <http://www.gnu.org/licenses/>.
*
*
* @version : 2.0.0.beta - Community Edition (AGPLv3 License)
* @author : Ext.NET, Inc. http://www.ext.net/
* @date : 2012-03-07
* @copyright : Copyright (c) 2007-2012, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
* @license : GNU AFFERO GENERAL PUBLIC LICENSE (AGPL) 3.0.
* See license.txt and http://www.ext.net/license/.
* See AGPL License at http://www.gnu.org/licenses/agpl-3.0.txt
********/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Ext.Net
{
/// <summary>
///
/// </summary>
public partial class XTemplate
{
/* Ctor
-----------------------------------------------------------------------------------------------*/
/// <summary>
///
/// </summary>
public XTemplate(Config config)
{
this.Apply(config);
}
/* Implicit XTemplate.Config Conversion to XTemplate
-----------------------------------------------------------------------------------------------*/
/// <summary>
///
/// </summary>
public static implicit operator XTemplate(XTemplate.Config config)
{
return new XTemplate(config);
}
/// <summary>
///
/// </summary>
new public partial class Config : LazyObservable.Config
{
/* Implicit XTemplate.Config Conversion to XTemplate.Builder
-----------------------------------------------------------------------------------------------*/
/// <summary>
///
/// </summary>
public static implicit operator XTemplate.Builder(XTemplate.Config config)
{
return new XTemplate.Builder(config);
}
/* ConfigOptions
-----------------------------------------------------------------------------------------------*/
private List<JFunction> functions = null;
/// <summary>
/// Inline functions
/// </summary>
public List<JFunction> Functions
{
get
{
if (this.functions == null)
{
this.functions = new List<JFunction>();
}
return this.functions;
}
}
private string html = "";
/// <summary>
/// Template text
/// </summary>
[DefaultValue("")]
public virtual string Html
{
get
{
return this.html;
}
set
{
this.html = value;
}
}
}
}
} | codeyu/Ext.NET.Community | Ext.Net/Factory/Config/XTemplateConfig.cs | C# | agpl-3.0 | 3,369 |
<?php
/**
* Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
*
* AFI-OPAC 2.0 is free software; you can redistribute it and/or modify
* it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
* the Free Software Foundation.
*
* There are special exceptions to the terms and conditions of the AGPL as it
* is applied to this software (see README file).
*
* AFI-OPAC 2.0 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
* along with AFI-OPAC 2.0; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class Class_Webservice_SIGB_BiblixNet_Service extends Class_WebService_SIGB_AbstractRESTService {
/**
* @return Class_Webservice_SIGB_BiblixNet_Service
*/
public static function newInstance() {
return new self();
}
/**
* @param string $server_root
* @return Class_Webservice_SIGB_BiblixNet_Service
*/
public static function getService($server_root) {
return self::newInstance()->setServerRoot($server_root);
}
/**
* @param Class_Users $user
* @return Class_WebService_SIGB_Emprunteur
*/
public function getEmprunteur($user) {
return $this->ilsdiGetPatronInfo(array('patronId' => $user->getIdSigb(),
'showLoans' => '1',
'showHolds' => '1'),
Class_WebService_SIGB_BiblixNet_PatronInfoReader::newInstance());
}
/**
* @param Class_Users $user
* @param int $notice_id
* @param string $code_annexe
* @return array
*/
public function reserverExemplaire($user, $exemplaire, $code_annexe) {
return $this->ilsdiHoldTitle(
array('patronId' => $user->getIdSigb(),
'bibId' => $exemplaire->getIdOrigine(),
'pickupLocation' => $code_annexe),
'code');
}
/**
* @param Class_Users $user
* @param int $reservation_id
* @return array
*/
public function supprimerReservation($user, $reservation_id) {
return $this->ilsdiCancelHold(array(
'patronId' => $user->getIdSigb(),
'itemId' => sprintf('%011d', $reservation_id)),
'code');
}
/**
* @param Class_Users $user
* @param int $pret_id
* @return array
*/
public function prolongerPret($user, $pret_id) {
return $this->ilsdiRenewLoan(array(
'patronId' => $user->getIdSigb(),
'itemId' => $pret_id),
'code');
}
/**
* @param string $id
* @return Class_WebService_SIGB_Notice
*/
public function getNotice($id) {
return $this->ilsdiGetRecords($id,
Class_WebService_SIGB_BiblixNet_GetRecordsResponseReader::newInstance());
}
}
?> | lolgzs/opacce | library/Class/WebService/SIGB/BiblixNet/Service.php | PHP | agpl-3.0 | 3,002 |
/**
* Copyright (C) 2001-2019 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.ports.impl;
import com.rapidminer.operator.ports.IncompatibleMDClassException;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.Port;
import com.rapidminer.operator.ports.PortException;
import com.rapidminer.operator.ports.Ports;
import com.rapidminer.operator.ports.metadata.MetaData;
/**
* An abstract output port implementation. Only the
* {@link #deliver(com.rapidminer.operator.IOObject)} method is missing.
*
* @author Nils Woehler
*
*/
public abstract class AbstractOutputPort extends AbstractPort implements OutputPort {
private InputPort connectedTo;
private MetaData metaData;
private MetaData realMetaData;
protected AbstractOutputPort(Ports<? extends Port> owner, String name, boolean simulatesStack) {
super(owner, name, simulatesStack);
}
@Override
public void deliverMD(MetaData md) {
this.metaData = md;
if (connectedTo != null) {
this.connectedTo.receiveMD(md);
}
}
@Override
public MetaData getMetaData() {
if (realMetaData != null) {
return realMetaData;
} else {
return metaData;
}
}
@Override
public InputPort getDestination() {
return connectedTo;
}
@Override
public String getDescription() {
return "";
}
@Override
public boolean isConnected() {
return connectedTo != null;
}
@Override
public boolean shouldAutoConnect() {
return getPorts().getOwner().getOperator().shouldAutoConnect(this);
}
@SuppressWarnings("unchecked")
@Override
public <T extends MetaData> T getMetaData(Class<T> desiredClass) throws IncompatibleMDClassException {
if (realMetaData != null) {
checkDesiredClass(realMetaData, desiredClass);
return (T) realMetaData;
} else {
if (metaData != null) {
checkDesiredClass(metaData, desiredClass);
}
return (T) metaData;
}
}
@Override
public void clear(int clearFlags) {
super.clear(clearFlags);
if ((clearFlags & CLEAR_REAL_METADATA) > 0) {
realMetaData = null;
}
if ((clearFlags & CLEAR_METADATA) > 0) {
metaData = null;
}
}
protected void assertConnected() throws PortException {
if (this.connectedTo == null) {
throw new PortException(this, "Not connected.");
}
}
/*
* private void assertDisconnected() throws PortException { if (this.connectedTo != null) {
* throw new PortException(this, "Already connected."); } }
*/
@Override
public void connectTo(InputPort inputPort) throws PortException {
if (this.connectedTo == inputPort) {
return;
}
if (inputPort.getPorts().getOwner().getConnectionContext() != this.getPorts().getOwner().getConnectionContext()) {
throw new PortException("Cannot connect " + getSpec() + " to " + inputPort.getSpec()
+ ": ports must be in the same subprocess, but are in "
+ this.getPorts().getOwner().getConnectionContext().getName() + " and "
+ inputPort.getPorts().getOwner().getConnectionContext().getName() + ".");
}
boolean destConnected = inputPort.isConnected();
boolean sourceConnected = this.isConnected();
boolean bothConnected = destConnected && sourceConnected;
boolean connected = destConnected || sourceConnected;
if (connected) {
if (bothConnected) {
throw new CannotConnectPortException(this, inputPort, this.getDestination(), inputPort.getSource());
} else if (sourceConnected) {
throw new CannotConnectPortException(this, inputPort, this.getDestination());
} else {
throw new CannotConnectPortException(this, inputPort, inputPort.getSource());
}
}
this.connectedTo = inputPort;
((AbstractInputPort) inputPort).connect(this);
fireUpdate(this);
}
@Override
public void disconnect() throws PortException {
assertConnected();
((AbstractInputPort) this.connectedTo).connect(null);
this.connectedTo.receive(null);
this.connectedTo.receiveMD(null);
this.connectedTo = null;
fireUpdate(this);
}
/**
* @return the realMetaData
*/
protected MetaData getRealMetaData() {
return this.realMetaData;
}
/**
* @param realMetaData
* the realMetaData to set
*/
protected void setRealMetaData(MetaData realMetaData) {
this.realMetaData = realMetaData;
}
}
| aborg0/rapidminer-studio | src/main/java/com/rapidminer/operator/ports/impl/AbstractOutputPort.java | Java | agpl-3.0 | 5,206 |
var map;
var maps = [];
var thisLayer;
var proj_4326 = new OpenLayers.Projection('EPSG:4326');
var proj_900913 = new OpenLayers.Projection('EPSG:900913');
var vlayer;
var vlayers = [];
var highlightCtrl;
var selectCtrl;
var selectedFeatures = [];
function initEditMap(settings){
var defaultSettings = {
mapContainer:"mapContainer",
editContainer:"editContainer",
fieldName:"location"
};
settings = jQuery.extend(defaultSettings, settings);
var options = {
units: "dd",
numZoomLevels: 18,
controls:[],
theme: false,
projection: proj_900913,
'displayProjection': proj_4326,
/* eventListeners: {
"zoomend": incidentZoom
},*/
maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
maxResolution: 156543.0339
};
// Now initialise the map
map = new OpenLayers.Map(settings.mapContainer, options);
maps[settings.fieldName] = map;
var google_satellite = new OpenLayers.Layer.Google("Google Maps Satellite", {
type: google.maps.MapTypeId.SATELLITE,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_hybrid = new OpenLayers.Layer.Google("Google Maps Hybrid", {
type: google.maps.MapTypeId.HYBRID,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_normal = new OpenLayers.Layer.Google("Google Maps Normal", {
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_physical = new OpenLayers.Layer.Google("Google Maps Physical", {
type: google.maps.MapTypeId.TERRAIN,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
maps[settings.fieldName].addLayers([google_normal,google_satellite,google_hybrid,google_physical]);
maps[settings.fieldName].addControl(new OpenLayers.Control.Navigation());
maps[settings.fieldName].addControl(new OpenLayers.Control.Zoom());
maps[settings.fieldName].addControl(new OpenLayers.Control.MousePosition());
maps[settings.fieldName].addControl(new OpenLayers.Control.ScaleLine());
maps[settings.fieldName].addControl(new OpenLayers.Control.Scale('mapScale'));
maps[settings.fieldName].addControl(new OpenLayers.Control.LayerSwitcher());
// Vector/Drawing Layer Styles
style1 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#ffcc66",
fillOpacity: "0.7",
strokeColor: "#CC0000",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style2 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker-green.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style3 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1
});
var vlayerStyles = new OpenLayers.StyleMap({
"default": style1,
"select": style2,
"temporary": style3
});
vlayer = new OpenLayers.Layer.Vector( "Editable", {
styleMap: vlayerStyles,
rendererOptions: {
zIndexing: true
}
});
vlayers[settings.fieldName] = vlayer;
maps[settings.fieldName].addLayer(vlayers[settings.fieldName]);
var endDragfname = settings.fieldName+"_endDrag"
var code = ""
//code += "function "+endDragfname+"(feature, pixel) {";
code +="for (f in selectedFeatures) {";
code +=" f.state = OpenLayers.State.UPDATE;";
code +="}";
code +="refreshFeatures(\""+settings.fieldName+"\");";
code +="var latitude = parseFloat(jQuery('input[name=\""+settings.fieldName+"_latitude\"]').val());"
code +="var longitude = parseFloat(jQuery('input[name=\""+settings.fieldName+"_longitude\"]').val());"
code +="reverseGeocode(latitude, longitude,\""+settings.fieldName+"\");"
//code +="}";
var endDragf = new Function(code);
// Drag Control
var drag = new OpenLayers.Control.DragFeature(vlayers[settings.fieldName], {
onStart: startDrag,
onDrag: doDrag,
onComplete: endDragf
});
maps[settings.fieldName].addControl(drag);
// Vector Layer Events
vlayers[settings.fieldName].events.on({
beforefeaturesadded: function(event) {
//for(i=0; i < vlayer.features.length; i++) {
// if (vlayer.features[i].geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// vlayer.removeFeatures(vlayer.features);
// }
//}
// Disable this to add multiple points
// vlayer.removeFeatures(vlayer.features);
},
featuresadded: function(event) {
refreshFeatures(event,settings.fieldName);
},
featuremodified: function(event) {
refreshFeatures(event,settings.fieldName);
},
featuresremoved: function(event) {
refreshFeatures(event,settings.fieldName);
}
});
// Vector Layer Highlight Features
highlightCtrl = new OpenLayers.Control.SelectFeature(vlayers[settings.fieldName], {
hover: true,
highlightOnly: true,
renderIntent: "temporary"
});
selectCtrl = new OpenLayers.Control.SelectFeature(vlayers[settings.fieldName], {
clickout: true,
toggle: false,
multiple: false,
hover: false,
renderIntent: "select",
onSelect: addSelected,
onUnselect: clearSelected
});
maps[settings.fieldName].addControl(highlightCtrl);
maps[settings.fieldName].addControl(selectCtrl);
// Insert Saved Geometries
wkt = new OpenLayers.Format.WKT();
if(settings.geometries){
for(i in settings.geometries){
wktFeature = wkt.read(settings.geometries[i]);
wktFeature.geometry.transform(proj_4326,proj_900913);
vlayers[settings.fieldName].addFeatures(wktFeature);
}
}else{
// Default Point
point = new OpenLayers.Geometry.Point(settings.longitude, settings.latitude);
OpenLayers.Projection.transform(point, proj_4326, maps[settings.fieldName].getProjectionObject());
var origFeature = new OpenLayers.Feature.Vector(point);
vlayers[settings.fieldName].addFeatures(origFeature);
}
// Create a lat/lon object
var startPoint = new OpenLayers.LonLat(settings.longitude, settings.latitude);
startPoint.transform(proj_4326, maps[settings.fieldName].getProjectionObject());
// Display the map centered on a latitude and longitude (Google zoom levels)
maps[settings.fieldName].setCenter(startPoint, 8);
// Create the Editing Toolbar
var container = document.getElementById(settings.editContainer);
var panel = new OpenLayers.Control.EditingToolbar(
vlayers[settings.fieldName], {
div: container
}
);
maps[settings.fieldName].addControl(panel);
panel.activateControl(panel.controls[0]);
drag.activate();
highlightCtrl.activate();
selectCtrl.activate();
jQuery('.'+settings.fieldName+'_locationButtonsLast').on('click', function () {
if (vlayers[settings.fieldName].features.length > 0) {
x = vlayers[settings.fieldName].features.length - 1;
vlayers[settings.fieldName].removeFeatures(vlayers[settings.fieldName].features[x]);
}
/*jQuery('#geometry_color').ColorPickerHide();
jQuery('#geometryLabelerHolder').hide(400);*/
selectCtrl.activate();
return false;
});
// Delete Selected Features
jQuery('.'+settings.fieldName+'_locationButtonsDelete').on('click', function () {
for(var y=0; y < selectedFeatures.length; y++) {
vlayers[settings.fieldName].removeFeatures(selectedFeatures);
}
/*jQuery('#geometry_color').ColorPickerHide();
jQuery('#geometryLabelerHolder').hide(400);*/
selectCtrl.activate();
return false;
});
// Clear Map
jQuery('.'+settings.fieldName+'_locationButtonsClear').on('click', function () {
vlayers[settings.fieldName].removeFeatures(vlayers[settings.fieldName].features);
jQuery('input[name="'+settings.fieldName+'_geometry[]"]').remove();
jQuery('input[name="'+settings.fieldName+'_latitude"]').val("");
jQuery('input[name="'+settings.fieldName+'_longitude"]').val("");
/*jQuery('#geometry_label').val("");
jQuery('#geometry_comment').val("");
jQuery('#geometry_color').val("");
jQuery('#geometry_lat').val("");
jQuery('#geometry_lon').val("");
jQuery('#geometry_color').ColorPickerHide();
jQuery('#geometryLabelerHolder').hide(400);*/
selectCtrl.activate();
return false;
});
// GeoCode
jQuery('.'+settings.fieldName+'_buttonFind').on('click', function () {
geoCode(settings.fieldName);
});
jQuery('#'+settings.fieldName+'_locationFind').bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
geoCode(settings.fieldName);
return false;
}
});
// Event on Latitude/Longitude Typing Change
jQuery('#'+settings.fieldName+'_latitude, #'+settings.fieldName+'_longitude').bind("focusout keyup", function() {
var newlat = jQuery('input[name="'+settings.fieldName+'_latitude"]').val();
var newlon = jQuery('input[name="'+settings.fieldName+'_longitude"]').val();
if (!isNaN(newlat) && !isNaN(newlon))
{
// Clear the map first
vlayers[settings.fieldName].removeFeatures(vlayers[settings.fieldName].features);
jQuery('input[name="'+settings.fieldName+'_geometry[]"]').remove();
point = new OpenLayers.Geometry.Point(newlon, newlat);
OpenLayers.Projection.transform(point, proj_4326,proj_900913);
f = new OpenLayers.Feature.Vector(point);
vlayers[settings.fieldName].addFeatures(f);
// create a new lat/lon object
myPoint = new OpenLayers.LonLat(newlon, newlat);
myPoint.transform(proj_4326, maps[settings.fieldName].getProjectionObject());
// display the map centered on a latitude and longitude
maps[settings.fieldName].panTo(myPoint);
}
else
{
// Commenting this out as its horribly annoying
//alert('Invalid value!');
}
});
}
function initViewMap(settings){
var defaultSettings = {
mapContainer:"mapContainer",
editContainer:"editContainer",
fieldName:"location"
};
settings = jQuery.extend(defaultSettings, settings);
var options = {
units: "dd",
numZoomLevels: 18,
controls:[],
theme: false,
projection: proj_900913,
'displayProjection': proj_4326,
/* eventListeners: {
"zoomend": incidentZoom
},*/
maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34),
maxResolution: 156543.0339
};
// Now initialise the map
map = new OpenLayers.Map(settings.mapContainer, options);
maps[settings.fieldName] = map
var google_satellite = new OpenLayers.Layer.Google("Google Maps Satellite", {
type: google.maps.MapTypeId.SATELLITE,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_hybrid = new OpenLayers.Layer.Google("Google Maps Hybrid", {
type: google.maps.MapTypeId.HYBRID,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_normal = new OpenLayers.Layer.Google("Google Maps Normal", {
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
var google_physical = new OpenLayers.Layer.Google("Google Maps Physical", {
type: google.maps.MapTypeId.TERRAIN,
animationEnabled: true,
sphericalMercator: true,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34)
});
maps[settings.fieldName].addLayers([google_normal,google_satellite,google_hybrid,google_physical]);
maps[settings.fieldName].addControl(new OpenLayers.Control.Navigation());
maps[settings.fieldName].addControl(new OpenLayers.Control.Zoom());
maps[settings.fieldName].addControl(new OpenLayers.Control.MousePosition());
maps[settings.fieldName].addControl(new OpenLayers.Control.ScaleLine());
maps[settings.fieldName].addControl(new OpenLayers.Control.Scale('mapScale'));
maps[settings.fieldName].addControl(new OpenLayers.Control.LayerSwitcher());
// Vector/Drawing Layer Styles
style1 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#ffcc66",
fillOpacity: "0.7",
strokeColor: "#CC0000",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style2 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1,
externalGraphic: "res/openlayers/img/marker-green.png",
graphicOpacity: 1,
graphicWidth: 21,
graphicHeight: 25,
graphicXOffset: -14,
graphicYOffset: -27
});
style3 = new OpenLayers.Style({
pointRadius: "8",
fillColor: "#30E900",
fillOpacity: "0.7",
strokeColor: "#197700",
strokeWidth: 2.5,
graphicZIndex: 1
});
var vlayerStyles = new OpenLayers.StyleMap({
"default": style1,
"select": style2,
"temporary": style3
});
vlayer = new OpenLayers.Layer.Vector( "Editable", {
styleMap: vlayerStyles,
rendererOptions: {
zIndexing: true
}
});
vlayers[settings.fieldName] = vlayer
maps[settings.fieldName].addLayer(vlayers[settings.fieldName]);
// Insert Saved Geometries
wkt = new OpenLayers.Format.WKT();
if(settings.geometries){
for(i in settings.geometries){
wktFeature = wkt.read(settings.geometries[i]);
wktFeature.geometry.transform(proj_4326,proj_900913);
vlayers[settings.fieldName].addFeatures(wktFeature);
}
}else{
// Default Point
point = new OpenLayers.Geometry.Point(settings.longitude, settings.latitude);
OpenLayers.Projection.transform(point, proj_4326, maps[settings.fieldName].getProjectionObject());
var origFeature = new OpenLayers.Feature.Vector(point);
vlayers[settings.fieldName].addFeatures(origFeature);
}
// Create a lat/lon object
var startPoint = new OpenLayers.LonLat(settings.longitude, settings.latitude);
startPoint.transform(proj_4326, maps[settings.fieldName].getProjectionObject());
// Display the map centered on a latitude and longitude (Google zoom levels)
maps[settings.fieldName].setCenter(startPoint, 8);
// Create the Editing Toolbar
//var container = document.getElementById(settings.editContainer);
//refreshFeatures(settings.fieldName);
}
function geoCode(fieldName)
{
jQuery('#'+fieldName+'_findLoading').html('<img src="res/openlayers/img/loading_g.gif">');
address = jQuery("#"+fieldName+"_locationFind").val();
jQuery.post("index.php?mod=events&act=geocode", {
address: address
},
function(data){
if (data.status == 'success'){
// Clear the map first
vlayers[fieldName].removeFeatures(vlayers[fieldName].features);
jQuery('input[name="'+fieldName+'_geometry[]"]').remove();
point = new OpenLayers.Geometry.Point(data.longitude, data.latitude);
OpenLayers.Projection.transform(point, proj_4326,proj_900913);
f = new OpenLayers.Feature.Vector(point);
vlayers[fieldName].addFeatures(f);
// create a new lat/lon object
myPoint = new OpenLayers.LonLat(data.longitude, data.latitude);
myPoint.transform(proj_4326, maps[fieldName].getProjectionObject());
// display the map centered on a latitude and longitude
maps[fieldName].panTo(myPoint);
// Update form values
jQuery("#"+fieldName+"_country_name").val(data.country);
jQuery('input[name="'+fieldName+'_latitude"]').val(data.latitude);
jQuery('input[name="'+fieldName+'_longitude"]').val(data.longitude);
jQuery("#"+fieldName+"_location_name").val(data.location_name);
} else {
// Alert message to be displayed
var alertMessage = address + " not found!\n\n***************************\n" +
"Enter more details like city, town, country\nor find a city or town " +
"close by and zoom in\nto find your precise location";
alert(alertMessage)
}
jQuery('div#'+fieldName+'_findLoading').html('');
}, "json");
return false;
}
/* Keep track of the selected features */
function addSelected(feature) {
selectedFeatures.push(feature);
selectCtrl.activate();
if (vlayer.features.length == 1 && feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// This is a single point, no need for geometry metadata
} else {
//jQuery('#geometryLabelerHolder').show(400);
if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
/*jQuery('#geometryLat').show();
jQuery('#geometryLon').show();
jQuery('#geometryColor').hide();
jQuery('#geometryStrokewidth').hide();*/
thisPoint = feature.clone();
thisPoint.geometry.transform(proj_900913,proj_4326);
/*jQuery('#geometry_lat').val(thisPoint.geometry.y);
jQuery('#geometry_lon').val(thisPoint.geometry.x);*/
} else {
/*jQuery('#geometryLat').hide();
jQuery('#geometryLon').hide();
jQuery('#geometryColor').show();
jQuery('#geometryStrokewidth').show();*/
}
/*if ( typeof(feature.label) != 'undefined') {
jQuery('#geometry_label').val(feature.label);
}
if ( typeof(feature.comment) != 'undefined') {
jQuery('#geometry_comment').val(feature.comment);
}
if ( typeof(feature.lon) != 'undefined') {
jQuery('#geometry_lon').val(feature.lon);
}
if ( typeof(feature.lat) != 'undefined') {
jQuery('#geometry_lat').val(feature.lat);
}
if ( typeof(feature.color) != 'undefined') {
jQuery('#geometry_color').val(feature.color);
}
if ( typeof(feature.strokewidth) != 'undefined' && feature.strokewidth != '') {
jQuery('#geometry_strokewidth').val(feature.strokewidth);
} else {
jQuery('#geometry_strokewidth').val("2.5");
}*/
}
}
/* Clear the list of selected features */
function clearSelected(feature) {
selectedFeatures = [];
/*jQuery('#geometryLabelerHolder').hide(400);
jQuery('#geometry_label').val("");
jQuery('#geometry_comment').val("");
jQuery('#geometry_color').val("");
jQuery('#geometry_lat').val("");
jQuery('#geometry_lon').val("");*/
selectCtrl.deactivate();
selectCtrl.activate();
//jQuery('#geometry_color').ColorPickerHide();
}
/* Feature starting to move */
function startDrag(feature, pixel) {
lastPixel = pixel;
}
/* Feature moving */
function doDrag(feature, pixel) {
for (f in selectedFeatures) {
if (feature != selectedFeatures[f]) {
var res = maps[settings.fieldName].getResolution();
selectedFeatures[f].geometry.move(res * (pixel.x - lastPixel.x), res * (lastPixel.y - pixel.y));
vlayer.drawFeature(selectedFeatures[f]);
}
}
lastPixel = pixel;
}
/* Featrue stopped moving */
/*function endDrag(feature, pixel) {
for (f in selectedFeatures) {
f.state = OpenLayers.State.UPDATE;
}
refreshFeatures(fieldName);
// Fetching Lat Lon Values
var latitude = parseFloat(jQuery('input[name="latitude"]').val());
var longitude = parseFloat(jQuery('input[name="longitude"]').val());
// Looking up country name using reverse geocoding
reverseGeocode(latitude, longitude);
}*/
function refreshFeatures(event,fieldName) {
var geoCollection = new OpenLayers.Geometry.Collection;
jQuery('input[name="'+fieldName+'_geometry[]"]').remove();
for(i=0; i < vlayers[fieldName].features.length; i++) {
newFeature = vlayers[fieldName].features[i].clone();
newFeature.geometry.transform(proj_900913,proj_4326);
geoCollection.addComponents(newFeature.geometry);
if (vlayers[fieldName].features.length == 1 && vlayers[fieldName].features[i].geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
// If feature is a Single Point - save as lat/lon
} else {
// Otherwise, save geometry values
// Convert to Well Known Text
var format = new OpenLayers.Format.WKT();
var geometry = format.write(newFeature);
var label = '';
var comment = '';
var lon = '';
var lat = '';
var color = '';
var strokewidth = '';
if ( typeof(vlayers[fieldName].features[i].label) != 'undefined') {
label = vlayers[fieldName].features[i].label;
}
if ( typeof(vlayers[fieldName].features[i].comment) != 'undefined') {
comment = vlayers[fieldName].features[i].comment;
}
if ( typeof(vlayers[fieldName].features[i].lon) != 'undefined') {
lon = vlayers[fieldName].features[i].lon;
}
if ( typeof(vlayers[fieldName].features[i].lat) != 'undefined') {
lat = vlayers[fieldName].features[i].lat;
}
if ( typeof(vlayers[fieldName].features[i].color) != 'undefined') {
color = vlayers[fieldName].features[i].color;
}
if ( typeof(vlayers[fieldName].features[i].strokewidth) != 'undefined') {
strokewidth = vlayers[fieldName].features[i].strokewidth;
}
geometryAttributes = JSON.stringify({
geometry: geometry,
label: label,
comment: comment,
lat: lat,
lon: lon,
color: color,
strokewidth: strokewidth
});
jQuery('form').append(jQuery('<input></input>').attr('name',fieldName+'_geometry[]').attr('type','hidden').attr('value',geometryAttributes));
}
}
// Centroid of location will constitute the Location
// if its not a point
centroid = geoCollection.getCentroid(true);
jQuery('input[name="'+fieldName+'_latitude"]').val(centroid.y);
jQuery('input[name="'+fieldName+'_longitude"]').val(centroid.x);
}
function incidentZoom(event) {
jQuery("#incident_zoom").val(maps[settings.fieldName].getZoom());
}
function updateFeature(feature, color, strokeWidth){
// Create a symbolizer from exiting stylemap
var symbolizer = feature.layer.styleMap.createSymbolizer(feature);
// Color available?
if (color) {
symbolizer['fillColor'] = "#"+color;
symbolizer['strokeColor'] = "#"+color;
symbolizer['fillOpacity'] = "0.7";
} else {
if ( typeof(feature.color) != 'undefined' && feature.color != '' ) {
symbolizer['fillColor'] = "#"+feature.color;
symbolizer['strokeColor'] = "#"+feature.color;
symbolizer['fillOpacity'] = "0.7";
}
}
// Stroke available?
if (parseFloat(strokeWidth)) {
symbolizer['strokeWidth'] = parseFloat(strokeWidth);
} else if ( typeof(feature.strokewidth) != 'undefined' && feature.strokewidth !='' ) {
symbolizer['strokeWidth'] = feature.strokewidth;
} else {
symbolizer['strokeWidth'] = "2.5";
}
// Set the unique style to the feature
feature.style = symbolizer;
// Redraw the feature with its new style
feature.layer.drawFeature(feature);
}
// Reverse GeoCoder
function reverseGeocode(latitude, longitude,fieldName) {
var latlng = new google.maps.LatLng(latitude, longitude);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': latlng
}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var country = results[results.length - 1].formatted_address;
jQuery("#"+fieldName+"_country_name").val(country);
} else {
console.log("Geocoder failed due to: " + status);
}
});
} | txau/OpenEvSys | www/res/openlayers/map.js | JavaScript | agpl-3.0 | 26,354 |
# coding: utf-8
# @ 2015 Valentin CHEMIERE @ Akretion
# © @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import logging
import os
import threading
import odoo
from odoo import models, api
# from odoo.addons.auth_signup.controllers.main import AuthSignupHome
from odoo.addons.tko_document_ocr.models.ir_attachment import \
_PDF_OCR_DOCUMENTS_THREADS
_logger = logging.getLogger(__name__)
class Task(models.Model):
_inherit = 'external.file.task'
def _import_file_threaded(self, attach_obj, conn, file_name):
md5_datas = ''
with api.Environment.manage():
with odoo.registry(
self.env.cr.dbname).cursor() as new_cr:
new_env = api.Environment(new_cr, self.env.uid,
self.env.context)
try:
full_path = os.path.join(self.filepath, file_name)
file_data = conn.open(full_path, 'rb')
datas = file_data.read()
if self.md5_check:
md5_file = conn.open(full_path + '.md5', 'rb')
md5_datas = md5_file.read().rstrip('\r\n')
attach_vals = self._prepare_attachment_vals(
datas, file_name, md5_datas)
attachment = attach_obj.with_env(new_env).create(
attach_vals)
new_full_path = False
if self.after_import == 'rename':
new_name = self._template_render(
self.new_name, attachment)
new_full_path = os.path.join(
self.filepath, new_name)
elif self.after_import == 'move':
new_full_path = os.path.join(
self.move_path, file_name)
elif self.after_import == 'move_rename':
new_name = self._template_render(
self.new_name, attachment)
new_full_path = os.path.join(
self.move_path, new_name)
if new_full_path:
conn.rename(full_path, new_full_path)
if self.md5_check:
conn.rename(
full_path + '.md5',
new_full_path + '/md5')
if self.after_import == 'delete':
conn.remove(full_path)
if self.md5_check:
conn.remove(full_path + '.md5')
except Exception, e:
new_env.cr.rollback()
_logger.error('Error importing file %s '
'from %s: %s',
file_name,
self.filepath,
e)
# move on to process other files
else:
new_env.cr.commit()
@api.multi
def run_import(self):
self.ensure_one()
protocols = self.env['external.file.location']._get_classes()
cls = protocols.get(self.location_id.protocol)[1]
attach_obj = self.env['ir.attachment.metadata']
try:
connection = cls.connect(self.location_id)
with connection as conn:
try:
files = conn.listdir(path=self.filepath,
wildcard=self.filename or '',
files_only=True)
for file_name in files:
t = threading.Thread(target=self._import_file_threaded,
name=u'import_file' + file_name,
args=(attach_obj,
conn,
file_name))
t.start()
for t in _PDF_OCR_DOCUMENTS_THREADS:
t.join()
except:
_logger.error('Directory %s does not exist', self.filepath)
return
except:
_logger.error('Root directory %s does not exist', self.filepath)
return | thinkopensolutions/tkobr-addons | tko_document_ocr_external_file_location_threaded/models/task.py | Python | agpl-3.0 | 4,504 |
<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| http://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: user_name_last_include.php
| Author: Chubatyj Vitalij (Rizado)
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
if (!defined("IN_FUSION")) { die("Access Denied"); }
if ($profile_method == "input") {
$options += array('inline'=>1, 'max_length'=>20, 'max_width'=>'200px');
$user_fields = form_text('user_name_last',$locale['uf_name_last'], $field_value, $options);
} elseif ($profile_method == "display") {
if ($field_value) {
$user_fields = array('title'=>$locale['uf_name_last'], 'value'=>$field_value);
}
}
| Talocha/PHP-Fusion | includes/user_fields/user_name_last_include.php | PHP | agpl-3.0 | 1,190 |
// installed by cozy-scripts
require('babel-polyfill')
// polyfill for requestAnimationFrame
/* istanbul ignore next */
global.requestAnimationFrame = cb => {
setTimeout(cb, 0)
}
| gregorylegarec/cozy-collect | test/jestLib/setup.js | JavaScript | agpl-3.0 | 182 |
// This file is part of Mystery Dungeon eXtended.
// Copyright (C) 2015 Pikablu, MDX Contributors, PMU Staff
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Text;
namespace Server.DataConverter.Moves.V1
{
public class Move
{
public string Name { get; set; }
public int ClassReq { get; set; }
public int ClassReq2 { get; set; }
public int ClassReq3 { get; set; }
public int LevelReq { get; set; }
public int MPCost { get; set; }
public int Sound { get; set; }
public Enums.MoveType Type { get; set; }
public int Data1 { get; set; }
public int Data2 { get; set; }
public int Data3 { get; set; }
public int Range { get; set; }
public int SpellAnim { get; set; }
public int SpellTime { get; set; }
public int SpellDone { get; set; }
public bool AE { get; set; }
public bool Big { get; set; }
public int Element { get; set; }
public bool IsKey { get; set; }
public int KeyItem { get; set; }
}
}
| pmdcp/Server | Server/DataConverter/Moves/V1/Move.cs | C# | agpl-3.0 | 1,744 |
package scrum.client.common;
import ilarkesto.core.base.Str;
import ilarkesto.gwt.client.AAction;
import ilarkesto.gwt.client.AWidget;
import ilarkesto.gwt.client.ButtonWidget;
import ilarkesto.gwt.client.DropdownMenuButtonWidget;
import ilarkesto.gwt.client.Gwt;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
public class BlockHeaderWidget extends AWidget {
private HorizontalPanel table;
private FocusPanel dragHandleWrapper;
private FocusPanel centerFocusPanel;
private FlowPanel centerWrapper;
private Label centerText;
private DropdownMenuButtonWidget menu;
private int prefixCellCount = 0;
private int suffixCellCount = 0;
private Label dragHandle;
@Override
protected Widget onInitialization() {
dragHandleWrapper = new FocusPanel();
dragHandleWrapper.setStyleName("BlockHeaderWidget-dragHandle");
// dragHandleWrapper.setHeight("100%");
centerText = Gwt.createInline(null);
centerText.setStyleName("BlockHeaderWidget-center-text");
centerWrapper = new FlowPanel();
centerWrapper.setStyleName("BlockHeaderWidget-center");
centerWrapper.setWidth("100%");
centerWrapper.add(centerText);
centerFocusPanel = new FocusPanel(centerWrapper);
centerFocusPanel.setHeight("100%");
table = new HorizontalPanel();
table.setStyleName("BlockHeaderWidget");
table.setWidth("100%");
table.add(dragHandleWrapper);
table.setCellWidth(dragHandleWrapper, "50px");
table.add(centerFocusPanel);
return table;
}
@Override
protected void onUpdate() {
super.onUpdate();
centerFocusPanel.setFocus(false);
}
public Label appendCenterSuffix(String text) {
Label label = Gwt.createInline(text);
label.setStyleName("BlockHeaderWidget-centerSuffix");
centerWrapper.add(label);
return label;
}
public Label insertPrefixLabel(String width, boolean secondary) {
Label label = new Label();
insertPrefixCell(label, width, true, "BlockHeaderWidget-prefixLabel", secondary);
return label;
}
public SimplePanel insertPrefixIcon() {
SimplePanel cell = insertPrefixCell(null, "16px", false, "BlockHeaderWidget-prefixIcon", false);
cell.setHeight("16px");
cell.getElement().getStyle().setMarginTop(2, Unit.PX);
return cell;
}
public SimplePanel insertSuffixCell(Widget widget, String width, boolean nowrap, String additionalStyleName,
boolean secondary) {
SimplePanel cell = createCell(widget, nowrap, additionalStyleName);
if (secondary) cell.addStyleName("BlockHeaderWidget-cell-secondary");
suffixCellCount++;
table.insert(cell, prefixCellCount + 1 + suffixCellCount);
if (width != null) table.setCellWidth(cell, width);
return cell;
}
public SimplePanel insertPrefixCell(Widget widget, String width, boolean nowrap, String additionalStyleName,
boolean secondary) {
SimplePanel cell = createCell(widget, nowrap, additionalStyleName);
if (secondary) cell.addStyleName("BlockHeaderWidget-cell-secondary");
prefixCellCount++;
table.insert(cell, prefixCellCount);
if (width != null) {
table.setCellWidth(cell, width);
cell.setWidth(width);
}
return cell;
}
public void appendCell(Widget widget, String width, boolean nowrap, boolean alignRight, String additionalStyleName) {
SimplePanel cell = createCell(widget, nowrap, additionalStyleName);
table.add(cell);
if (alignRight) table.setCellHorizontalAlignment(cell, HorizontalPanel.ALIGN_RIGHT);
if (width != null) table.setCellWidth(cell, width);
}
private SimplePanel createCell(Widget widget, boolean nowrap, String additionalStyleName) {
SimplePanel wrapper = new SimplePanel();
wrapper.setStyleName("BlockHeaderWidget-cell");
wrapper.setHeight("100%");
if (nowrap) wrapper.getElement().getStyle().setProperty("whiteSpace", "nowrap");
if (additionalStyleName != null) wrapper.addStyleName(additionalStyleName);
wrapper.setWidget(widget);
return wrapper;
}
public void addMenuAction(AScrumAction action) {
if (menu == null) {
menu = new DropdownMenuButtonWidget();
appendCell(menu, "30px", true, false, null);
}
menu.addAction(action);
}
public void addToolbarAction(AAction action) {
appendCell(new ButtonWidget(action), "5px", true, false, null);
}
public void setDragHandle(String text) {
if (dragHandle == null) {
dragHandle = new Label();
setDragHandle(dragHandle);
}
dragHandle.setText(text);
}
public void setDragHandle(Widget widget) {
dragHandleWrapper.setWidget(widget);
}
public void setCenter(String text) {
if (Str.isBlank(text)) text = "<new>";
centerText.setText(text);
}
public void addClickHandler(ClickHandler handler) {
centerFocusPanel.addClickHandler(handler);
}
public FocusPanel getDragHandle() {
return dragHandleWrapper;
}
}
| hogi/kunagi | src/main/java/scrum/client/common/BlockHeaderWidget.java | Java | agpl-3.0 | 5,038 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using common;
using wServer.logic.behaviors;
using wServer.realm.entities;
using wServer.realm;
using wServer.realm.worlds;
using wServer.realm.worlds.logic;
namespace wServer.logic
{
public class DamageCounter
{
Enemy enemy;
public Enemy Host { get { return enemy; } }
public Projectile LastProjectile { get; private set; }
public Player LastHitter { get; private set; }
public DamageCounter Corpse { get; set; }
public DamageCounter Parent { get; set; }
WeakDictionary<Player, int> hitters = new WeakDictionary<Player, int>();
public DamageCounter(Enemy enemy)
{
this.enemy = enemy;
}
public void HitBy(Player player, RealmTime time, Projectile projectile, int dmg)
{
int totalDmg;
if (!hitters.TryGetValue(player, out totalDmg))
totalDmg = 0;
totalDmg += dmg;
hitters[player] = totalDmg;
LastProjectile = projectile;
LastHitter = player;
player.FameCounter.Hit(projectile, enemy);
}
public Tuple<Player, int>[] GetPlayerData()
{
if (Parent != null)
return Parent.GetPlayerData();
List<Tuple<Player, int>> dat = new List<Tuple<Player, int>>();
foreach (var i in hitters)
{
if (i.Key.Owner == null) continue;
dat.Add(new Tuple<Player, int>(i.Key, i.Value));
}
return dat.ToArray();
}
public void Death(RealmTime time)
{
if (Corpse != null)
{
Corpse.Parent = this;
return;
}
var enemy = (Parent ?? this).enemy;
if (enemy.Owner is Realm)
(enemy.Owner as Realm).EnemyKilled(enemy, (Parent ?? this).LastHitter);
if (enemy.Spawned || enemy.Owner is Arena || enemy.Owner is ArenaSolo)
return;
int lvlUps = 0;
foreach (var player in enemy.Owner.Players.Values
.Where(p => enemy.Dist(p) < 25))
{
if (player.HasConditionEffect(common.resources.ConditionEffects.Paused))
continue;
float xp = enemy.GivesNoXp ? 0 : 1;
xp *= enemy.ObjectDesc.MaxHP / 10f *
(enemy.ObjectDesc.ExpMultiplier ?? 1);
float upperLimit = player.ExperienceGoal * 0.1f;
if (player.Quest == enemy)
upperLimit = player.ExperienceGoal * 0.5f;
float playerXp;
if (upperLimit < xp)
playerXp = upperLimit;
else
playerXp = xp;
if (player.Owner is DeathArena || player.Owner.GetDisplayName().Contains("Theatre"))
playerXp *= .33f;
if (player.XPBoostTime != 0 && player.Level < 20)
playerXp *= 2;
var killer = (Parent ?? this).LastHitter == player;
if (player.EnemyKilled(
enemy,
(int)playerXp,
killer) && !killer)
lvlUps++;
}
if ((Parent ?? this).LastHitter != null)
(Parent ?? this).LastHitter.FameCounter.LevelUpAssist(lvlUps);
}
/*public void Death(RealmTime time)
{
if (Corpse != null)
{
Corpse.Parent = this;
return;
}
List<Tuple<Player, int>> eligiblePlayers = new List<Tuple<Player, int>>();
int totalDamage = 0;
int totalPlayer = 0;
var enemy = (Parent ?? this).enemy;
foreach (var i in (Parent ?? this).hitters)
{
if (i.Key.Owner == null) continue;
totalDamage += i.Value;
totalPlayer++;
eligiblePlayers.Add(new Tuple<Player, int>(i.Key, i.Value));
}
if (totalPlayer != 0)
{
float totalExp = totalPlayer * (enemy.ObjectDesc.MaxHP / 10f) * (enemy.ObjectDesc.ExpMultiplier ?? 1);
float lowerLimit = totalExp / totalPlayer * 0.1f;
int lvUps = 0;
foreach (var i in eligiblePlayers)
{
float playerXp = totalExp * i.Item2 / totalDamage;
float upperLimit = i.Item1.ExperienceGoal * 0.1f;
if (i.Item1.Quest == enemy)
upperLimit = i.Item1.ExperienceGoal * 0.5f;
if (playerXp < lowerLimit) playerXp = lowerLimit;
if (playerXp > upperLimit) playerXp = upperLimit;
var killer = (Parent ?? this).LastHitter == i.Item1;
if (i.Item1.EnemyKilled(
enemy,
(int)playerXp,
killer) && !killer)
lvUps++;
}
(Parent ?? this).LastHitter.FameCounter.LevelUpAssist(lvUps);
}
if (enemy.Owner is Realm)
(enemy.Owner as Realm).EnemyKilled(enemy, (Parent ?? this).LastHitter);
}*/
public void TransferData(DamageCounter dc)
{
dc.LastProjectile = LastProjectile;
dc.LastHitter = LastHitter;
foreach (var plr in hitters.Keys)
{
int totalDmg;
int totalExistingDmg;
if (!hitters.TryGetValue(plr, out totalDmg))
totalDmg = 0;
if (!dc.hitters.TryGetValue(plr, out totalExistingDmg))
totalExistingDmg = 0;
dc.hitters[plr] = totalDmg + totalExistingDmg;
}
}
}
}
| cp-nilly/NR-CORE | wServer/logic/DamageCounter.cs | C# | agpl-3.0 | 6,032 |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.common.task;
import java.io.Serializable;
import org.ow2.proactive.scheduler.task.launcher.TaskLauncher.OneShotDecrypter;
/**
* ExecutableInitializer is used to initialized the executable.
* It is sent to the init method of each executable.
*
* @author The ProActive Team
* @since ProActive Scheduling 1.0
*/
public interface ExecutableInitializer extends Serializable {
/**
* Set the decrypter value to the given decrypter value
*
* @param decrypter the decrypter to set
*/
public void setDecrypter(OneShotDecrypter decrypter);
/**
* Get the decrypter from this initializer
*
* @return the decrypter from this initializer
*/
public OneShotDecrypter getDecrypter();
}
| acontes/scheduling | src/scheduler/src/org/ow2/proactive/scheduler/common/task/ExecutableInitializer.java | Java | agpl-3.0 | 2,209 |
package de.fhg.fokus.mdc.serviceNutzerProfil.services;
// imports
import java.io.IOException;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import de.fhg.fokus.mdc.serviceNutzerProfil.datastore.UserProfileDataStoreClient;
/**
* The class implements the service for getting the details of a user profile.
*
* @author Nikolay Tcholtchev, nikolay.tcholtchev@fokus.fraunhofer.de
* @author izi
*/
@Path("/get_user_details")
public class GetUserDetailsService {
/** The logger of the class. */
private static Logger log = Logger.getLogger(GetUserDetailsService.class
.getName());
/**
* The method obtains the details for a particular user.
*
* @param username
* the name of the user to check for.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public String query(@QueryParam("username") String username,
@Context HttpHeaders headers) throws IOException {
// check the parameter
if (username == null || username.matches("^\\s*$")) {
return "FAILED: NO USERNAME SPECIFIED";
}
UserProfileDataStoreClient userClient = UserProfileDataStoreClient
.getInstance();
userClient.setAuthHeaders(headers);
String userDetails = userClient.getUserDetails(username);
if (userDetails == null || userDetails.matches("^\\s*$")) {
return "NO USER DETAILS FOUND";
}
return userDetails;
}
}
| fraunhoferfokus/gemo | src/mobility-services/userprofile/src/main/java/de/fhg/fokus/mdc/serviceNutzerProfil/services/GetUserDetailsService.java | Java | agpl-3.0 | 1,541 |
//******************************************************************************
///
/// @file core/shape/truetype.cpp
///
/// This module implements rendering of TrueType fonts.
/// This file was written by Alexander Enzmann. He wrote the code for
/// rendering glyphs and generously provided us these enhancements.
///
/// @copyright
/// @parblock
///
/// Persistence of Vision Ray Tracer ('POV-Ray') version 3.7.
/// Copyright 1991-2015 Persistence of Vision Raytracer Pty. Ltd.
///
/// POV-Ray is free software: you can redistribute it and/or modify
/// it under the terms of the GNU Affero General Public License as
/// published by the Free Software Foundation, either version 3 of the
/// License, or (at your option) any later version.
///
/// POV-Ray is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU Affero General Public License for more details.
///
/// You should have received a copy of the GNU Affero General Public License
/// along with this program. If not, see <http://www.gnu.org/licenses/>.
///
/// ----------------------------------------------------------------------------
///
/// POV-Ray is based on the popular DKB raytracer version 2.12.
/// DKBTrace was originally written by David K. Buck.
/// DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
///
/// @endparblock
///
//******************************************************************************
// configcore.h must always be the first POV file included in core *.cpp files (pulls in platform config)
#include "core/configcore.h"
#include "core/shape/truetype.h"
#include "base/fileinputoutput.h"
#include "core/bounding/boundingbox.h"
#include "core/math/matrix.h"
#include "core/render/ray.h"
#include "core/scene/tracethreaddata.h"
#include "core/shape/csg.h"
// this must be the last file included
#include "base/povdebug.h"
namespace pov
{
/*****************************************************************************
* Local preprocessor defines
******************************************************************************/
/* uncomment this to debug ttf. DEBUG1 gives less output than DEBUG2
#define TTF_DEBUG2 1
#define TTF_DEBUG 1
#define TTF_DEBUG3 1
*/
const DBL TTF_Tolerance = 1.0e-6; /* -4 worked, -8 failed */
const int MAX_ITERATIONS = 50;
const DBL COEFF_LIMIT = 1.0e-20;
/* For decoding glyph coordinate bit flags */
const int ONCURVE = 0x01;
const int XSHORT = 0x02;
const int YSHORT = 0x04;
const int REPEAT_FLAGS = 0x08; /* repeat flag n times */
const int SHORT_X_IS_POS = 0x10; /* the short vector is positive */
const int NEXT_X_IS_ZERO = 0x10; /* the relative x coordinate is zero */
const int SHORT_Y_IS_POS = 0x20; /* the short vector is positive */
const int NEXT_Y_IS_ZERO = 0x20; /* the relative y coordinate is zero */
/* For decoding multi-component glyph bit flags */
const int ARG_1_AND_2_ARE_WORDS = 0x0001;
const int ARGS_ARE_XY_VALUES = 0x0002;
const int ROUND_XY_TO_GRID = 0x0004;
const int WE_HAVE_A_SCALE = 0x0008;
/* RESERVED = 0x0010 */
const int MORE_COMPONENTS = 0x0020;
const int WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
const int WE_HAVE_A_TWO_BY_TWO = 0x0080;
const int WE_HAVE_INSTRUCTIONS = 0x0100;
const int USE_MY_METRICS = 0x0200;
/* For decoding kern coverage bit flags */
const int KERN_HORIZONTAL = 0x01;
const int KERN_MINIMUM = 0x02;
const int KERN_CROSS_STREAM = 0x04;
const int KERN_OVERRIDE = 0x08;
/* Some marcos to make error detection easier, as well as clarify code */
#define READSHORT(fp) readSHORT(fp, __LINE__, __FILE__)
#define READLONG(fp) readLONG(fp, __LINE__, __FILE__)
#define READUSHORT(fp) readUSHORT(fp, __LINE__, __FILE__)
#define READULONG(fp) readULONG(fp, __LINE__, __FILE__)
#define READFIXED(fp) readLONG(fp, __LINE__, __FILE__)
#define READFWORD(fp) readSHORT(fp, __LINE__, __FILE__)
#define READUFWORD(fp) readUSHORT(fp, __LINE__, __FILE__)
/*****************************************************************************
* Local typedefs
******************************************************************************/
/* Type definitions to match the TTF spec, makes code clearer */
typedef char CHAR;
typedef unsigned char BYTE;
typedef short SHORT;
typedef unsigned short USHORT;
typedef int LONG;
typedef unsigned int ULONG;
typedef short FWord;
typedef unsigned short uFWord;
#if !defined(TARGET_OS_MAC)
typedef int Fixed;
#endif
typedef struct
{
Fixed version; /* 0x10000 (1.0) */
USHORT numTables; /* number of tables */
USHORT searchRange; /* (max2 <= numTables)*16 */
USHORT entrySelector; /* log2 (max2 <= numTables) */
USHORT rangeShift; /* numTables*16-searchRange */
} sfnt_OffsetTable;
typedef struct
{
BYTE tag[4];
ULONG checkSum;
ULONG offset;
ULONG length;
} sfnt_TableDirectory;
typedef sfnt_TableDirectory *sfnt_TableDirectoryPtr;
typedef struct
{
ULONG bc;
ULONG ad;
} longDateTime;
typedef struct
{
Fixed version; /* for this table, set to 1.0 */
Fixed fontRevision; /* For Font Manufacturer */
ULONG checkSumAdjustment;
ULONG magicNumber; /* signature, must be 0x5F0F3CF5 == MAGIC */
USHORT flags;
USHORT unitsPerEm; /* How many in Font Units per EM */
longDateTime created;
longDateTime modified;
FWord xMin; /* Font wide bounding box in ideal space */
FWord yMin; /* Baselines and metrics are NOT worked */
FWord xMax; /* into these numbers) */
FWord yMax;
USHORT macStyle; /* macintosh style word */
USHORT lowestRecPPEM; /* lowest recommended pixels per Em */
SHORT fontDirectionHint;
SHORT indexToLocFormat; /* 0 - short offsets, 1 - long offsets */
SHORT glyphDataFormat;
} sfnt_FontHeader;
typedef struct
{
USHORT platformID;
USHORT specificID;
ULONG offset;
} sfnt_platformEntry;
typedef sfnt_platformEntry *sfnt_platformEntryPtr;
typedef struct
{
USHORT format;
USHORT length;
USHORT version;
} sfnt_mappingTable;
typedef struct
{
Fixed version;
FWord Ascender;
FWord Descender;
FWord LineGap;
uFWord advanceWidthMax;
FWord minLeftSideBearing;
FWord minRightSideBearing;
FWord xMaxExtent;
SHORT caretSlopeRise;
SHORT caretSlopeRun;
SHORT reserved1;
SHORT reserved2;
SHORT reserved3;
SHORT reserved4;
SHORT reserved5;
SHORT metricDataFormat;
USHORT numberOfHMetrics; /* number of hMetrics in the hmtx table */
} sfnt_HorizHeader;
struct GlyphHeader
{
SHORT numContours;
SHORT xMin;
SHORT yMin;
SHORT xMax;
SHORT yMax;
GlyphHeader() : numContours(0), xMin(0), yMin(0), xMax(0), yMax(0) {}
};
struct GlyphOutline
{
GlyphHeader header;
USHORT numPoints;
USHORT *endPoints;
BYTE *flags;
DBL *x, *y;
USHORT myMetrics;
GlyphOutline() :
header(),
numPoints(0),
endPoints(NULL),
flags(NULL),
x(NULL), y(NULL),
myMetrics(0)
{}
~GlyphOutline()
{
if (endPoints != NULL) POV_FREE(endPoints);
if (flags != NULL) POV_FREE(flags);
if (x != NULL) POV_FREE(x);
if (y != NULL) POV_FREE(y);
}
};
typedef struct
{
BYTE inside_flag; /* 1 if this an inside contour, 0 if outside */
USHORT count; /* Number of points in the contour */
BYTE *flags; /* On/off curve flags */
DBL *x, *y; /* Coordinates of control vertices */
} Contour;
/* Contour information for a single glyph */
struct GlyphStruct
{
GlyphHeader header; /* Count and sizing information about this
* glyph */
USHORT glyph_index; /* Internal glyph index for this character */
Contour *contours; /* Array of outline contours */
USHORT unitsPerEm; /* Max units character */
USHORT myMetrics; /* Which glyph index this is for metrics */
};
typedef struct KernData_struct
{
USHORT left, right; /* Glyph index of left/right to kern */
FWord value; /* Delta in FUnits to apply in between */
} KernData;
/*
* [esp] There's already a "KernTable" on the Mac... renamed to TTKernTable for
* now in memorium to its author.
*/
typedef struct KernStruct
{
USHORT coverage; /* Coverage bit field of this subtable */
USHORT nPairs; /* # of kerning pairs in this table */
KernData *kern_pairs; /* Array of kerning values */
} TTKernTable;
typedef struct KernTableStruct
{
USHORT nTables; /* # of subtables in the kerning table */
TTKernTable *tables;
} KernTables;
typedef struct longHorMertric
{
uFWord advanceWidth; /* Total width of a glyph in FUnits */
FWord lsb; /* FUnits to the left of the glyph */
} longHorMetric;
typedef std::map<USHORT, GlyphPtr> GlyphPtrMap;
struct TrueTypeInfo
{
TrueTypeInfo();
~TrueTypeInfo();
USHORT platformID[4]; /* Character encoding search order */
USHORT specificID[4];
ULONG cmap_table_offset; /* File locations for these tables */
ULONG glyf_table_offset;
USHORT numGlyphs; /* How many symbols in this file */
USHORT unitsPerEm; /* The "resoultion" of this font */
SHORT indexToLocFormat; /* 0 - short format, 1 - long format */
ULONG *loca_table; /* Mapping from characters to glyphs */
GlyphPtrMap glyphsByChar; /* Cached info for this font */
GlyphPtrMap glyphsByIndex; /* Cached info for this font */
KernTables kerning_tables; /* Kerning info for this font */
USHORT numberOfHMetrics; /* The number of explicit spacings */
longHorMetric *hmtx_table; /* Horizontal spacing info */
ULONG glyphIDoffset; /* Offset for Type 4 encoding tables */
USHORT segCount, searchRange, /* Counts for Type 4 encoding tables */
entrySelector, rangeShift;
USHORT *startCount, *endCount, /* Type 4 (MS) encoding tables */
*idDelta, *idRangeOffset;
};
/*****************************************************************************
* Local variables
******************************************************************************/
const BYTE tag_CharToIndexMap[] = "cmap"; /* 0x636d6170; */
const BYTE tag_FontHeader[] = "head"; /* 0x68656164; */
const BYTE tag_GlyphData[] = "glyf"; /* 0x676c7966; */
const BYTE tag_IndexToLoc[] = "loca"; /* 0x6c6f6361; */
const BYTE tag_Kerning[] = "kern"; /* 0x6b65726e; */
const BYTE tag_MaxProfile[] = "maxp"; /* 0x6d617870; */
const BYTE tag_HorizHeader[] = "hhea"; /* 0x68686561; */
const BYTE tag_HorizMetric[] = "hmtx"; /* 0x686d7478; */
const BYTE tag_TTCFontFile[] = "ttcf"; /* */
/*****************************************************************************
* Static functions
******************************************************************************/
/* Byte order independent I/O routines (probably already in other routines) */
SHORT readSHORT(IStream *infile, int line, const char *file);
USHORT readUSHORT(IStream *infile, int line, const char *file);
LONG readLONG(IStream *infile, int line, const char *file);
ULONG readULONG(IStream *infile, int line, const char *file);
int compare_tag4(BYTE *ttf_tag, BYTE *known_tag);
/* Internal TTF input routines */
void ProcessFontFile(TrueTypeFont* ffile);
void ProcessHeadTable(TrueTypeFont *ffile, int head_table_offset);
void ProcessLocaTable(TrueTypeFont *ffile, int loca_table_offset);
void ProcessMaxpTable(TrueTypeFont *ffile, int maxp_table_offset);
void ProcessKernTable(TrueTypeFont *ffile, int kern_table_offset);
void ProcessHheaTable(TrueTypeFont *ffile, int hhea_table_offset);
void ProcessHmtxTable(TrueTypeFont *ffile, int hmtx_table_offset);
GlyphPtr ProcessCharacter(TrueTypeFont *ffile, unsigned int search_char, unsigned int *glyph_index);
USHORT ProcessCharMap(TrueTypeFont *ffile, unsigned int search_char);
USHORT ProcessFormat0Glyph(TrueTypeFont *ffile, unsigned int search_char);
USHORT ProcessFormat4Glyph(TrueTypeFont *ffile, unsigned int search_char);
USHORT ProcessFormat6Glyph(TrueTypeFont *ffile, unsigned int search_char);
GlyphPtr ExtractGlyphInfo(TrueTypeFont *ffile, unsigned int glyph_index, unsigned int c);
GlyphOutline *ExtractGlyphOutline(TrueTypeFont *ffile, unsigned int glyph_index, unsigned int c);
GlyphPtr ConvertOutlineToGlyph(TrueTypeFont *ffile, const GlyphOutline *ttglyph);
/*
* The following work as macros if sizeof(short) == 16 bits and
* sizeof(long) == 32 bits, but tend to break otherwise. Making these
* into error functions also allows file error checking. Do not attempt to
* "optimize" these functions - some architectures require them the way
* that they are written.
*/
SHORT readSHORT(IStream *infile, int line, const char *file)
{
int i0, i1 = 0; /* To quiet warnings */
if ((i0 = infile->Read_Byte ()) == EOF || (i1 = infile->Read_Byte ()) == EOF)
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
if (i0 & 0x80) /* Subtract 1 after value is negated to avoid overflow [AED] */
return -(((255 - i0) << 8) | (255 - i1)) - 1;
else
return (i0 << 8) | i1;
}
USHORT readUSHORT(IStream *infile, int line, const char *file)
{
int i0, i1 = 0; /* To quiet warnings */
if ((i0 = infile->Read_Byte ()) == EOF || (i1 = infile->Read_Byte ()) == EOF)
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
return (USHORT)((((USHORT)i0) << 8) | ((USHORT)i1));
}
LONG readLONG(IStream *infile, int line, const char *file)
{
LONG i0, i1 = 0, i2 = 0, i3 = 0; /* To quiet warnings */
if ((i0 = infile->Read_Byte ()) == EOF || (i1 = infile->Read_Byte ()) == EOF ||
(i2 = infile->Read_Byte ()) == EOF || (i3 = infile->Read_Byte ()) == EOF)
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
if (i0 & 0x80) /* Subtract 1 after value is negated to avoid overflow [AED] */
return -(((255 - i0) << 24) | ((255 - i1) << 16) |
((255 - i2) << 8) | (255 - i3)) - 1;
else
return (i0 << 24) | (i1 << 16) | (i2 << 8) | i3;
}
ULONG readULONG(IStream *infile, int line, const char *file)
{
int i0, i1 = 0, i2 = 0, i3 = 0; /* To quiet warnings */
if ((i0 = infile->Read_Byte ()) == EOF || (i1 = infile->Read_Byte ()) == EOF ||
(i2 = infile->Read_Byte ()) == EOF || (i3 = infile->Read_Byte ()) == EOF)
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
return (ULONG) ((((ULONG) i0) << 24) | (((ULONG) i1) << 16) |
(((ULONG) i2) << 8) | ((ULONG) i3));
}
static int compare_tag4(const BYTE *ttf_tag, const BYTE *known_tag)
{
return (ttf_tag[0] == known_tag[0] && ttf_tag[1] == known_tag[1] &&
ttf_tag[2] == known_tag[2] && ttf_tag[3] == known_tag[3]);
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessNewTTF
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Ennzmann
*
* DESCRIPTION
*
* Takes an input string and a font filename, and creates a POV-Ray CSG
* object for each letter in the string.
*
* CHANGES
*
* Allow usage of built-in fonts via an additional parameter
* (triggered when filename is null) - Oct 2012 [JG]
*
******************************************************************************/
void TrueType::ProcessNewTTF(CSG *Object, TrueTypeFont *ffile, const UCS2 *text_string, DBL depth, const Vector3d& offset, Parser *parser, shared_ptr<SceneData>& sceneData)
{
Vector3d local_offset, total_offset;
TrueType *ttf;
DBL funit_size;
TTKernTable *table;
USHORT coverage;
unsigned int search_char;
unsigned int glyph_index, last_index = 0;
FWord kern_value_x, kern_value_min_x;
FWord kern_value_y, kern_value_min_y;
int i, j, k;
TRANSFORM Trans;
/* Get info about each character in the string */
total_offset = Vector3d(0.0, 0.0, 0.0);
for (i = 0; text_string[i] != 0; i++)
{
/*
* We need to make sure (for now) that this is only the lower 8 bits,
* so we don't have all the high bits set if converted from a signed
* char to an unsigned short.
*/
search_char = (unsigned int)(text_string[i]);
#ifdef TTF_DEBUG
Debug_Info("\nChar: '%c' (0x%X), Offset[%d]: <%g,%g,%g>\n", (char)search_char,
search_char, i, total_offset[X], total_offset[Y], total_offset[Z]);
#endif
/* Make a new child for each character */
ttf = new TrueType();
/* Set the depth information for the character */
ttf->depth = depth;
/*
* Get pointers to the contour information for each character
* in the text string.
*/
ttf->glyph = ProcessCharacter(ffile, search_char, &glyph_index);
funit_size = 1.0 / (DBL)(ffile->info->unitsPerEm);
/*
* Spacing based on the horizontal metric table, the kerning table,
* and (possibly) the previous glyph.
*/
if (i == 0) /* Ignore spacing on the left for the first character only */
{
/* Shift the glyph to start at the origin */
total_offset[X] = -ttf->glyph->header.xMin * funit_size;
Compute_Translation_Transform(&Trans, total_offset);
ttf->Translate(total_offset, &Trans);
/* Shift next glyph by the width of this one excluding the left offset*/
total_offset[X] = (ffile->info->hmtx_table[ttf->glyph->myMetrics].advanceWidth -
ffile->info->hmtx_table[ttf->glyph->myMetrics].lsb) * funit_size;
#ifdef TTF_DEBUG
Debug_Info("aw(%d): %g\n", i,
(ffile->info->hmtx_table[ttf->glyph->myMetrics].advanceWidth -
ffile->info->hmtx_table[ttf->glyph->myMetrics].lsb)*funit_size);
#endif
}
else /* Kern all of the other characters */
{
kern_value_x = kern_value_y = 0;
kern_value_min_x = kern_value_min_y = -ffile->info->unitsPerEm;
local_offset = Vector3d(0.0, 0.0, 0.0);
for (j = 0; j < ffile->info->kerning_tables.nTables; j++)
{
table = ffile->info->kerning_tables.tables;
coverage = table->coverage;
/*
* Don't use vertical kerning until such a time when we support
* characters moving in the vertical direction...
*/
if (!(coverage & KERN_HORIZONTAL))
continue;
/*
* If we were keen, we could do a binary search for this
* character combination, since the pairs are sorted in
* order as if the left and right index values were a 32 bit
* unsigned int (mostly - at least they are sorted on the
* left glyph). Something to do when everything else works...
*/
for (k = 0; k < table[j].nPairs; k++)
{
if (table[j].kern_pairs[k].left == last_index &&
table[j].kern_pairs[k].right == ttf->glyph->myMetrics)
{
#ifdef TTF_DEBUG2
Debug_Info("Found a kerning for <%d, %d> = %d\n",
last_index, glyph_index, table[j].kern_pairs[k].value);
#endif
/*
* By default, Windows & OS/2 assume at most a single table with
* !KERN_MINIMUM, !KERN_CROSS_STREAM, KERN_OVERRIDE.
*/
if (coverage & KERN_MINIMUM)
{
#ifdef TTF_DEBUG2
Debug_Info(" KERN_MINIMUM\n");
#endif
if (coverage & KERN_CROSS_STREAM)
kern_value_min_y = table[j].kern_pairs[k].value;
else
kern_value_min_x = table[j].kern_pairs[k].value;
}
else
{
if (coverage & KERN_CROSS_STREAM)
{
#ifdef TTF_DEBUG2
Debug_Info(" KERN_CROSS_STREAM\n");
#endif
if (table[j].kern_pairs[k].value == (FWord)0x8000)
{
kern_value_y = 0;
}
else
{
if (coverage & KERN_OVERRIDE)
kern_value_y = table[j].kern_pairs[k].value;
else
kern_value_y += table[j].kern_pairs[k].value;
}
}
else
{
#ifdef TTF_DEBUG2
Debug_Info(" KERN_VALUE\n");
#endif
if (coverage & KERN_OVERRIDE)
kern_value_x = table[j].kern_pairs[k].value;
else
kern_value_x += table[j].kern_pairs[k].value;
}
}
break;
}
/* Abort now if we have passed all potential matches */
else if (table[j].kern_pairs[k].left > last_index)
{
break;
}
}
}
kern_value_x = (kern_value_x > kern_value_min_x ?
kern_value_x : kern_value_min_x);
kern_value_y = (kern_value_y > kern_value_min_y ?
kern_value_y : kern_value_min_y);
/*
* Offset this character so that the left edge of the glyph is at
* the previous offset + the lsb + any kerning amount.
*/
local_offset[X] = total_offset[X] +
(DBL)(ffile->info->hmtx_table[ttf->glyph->myMetrics].lsb -
ttf->glyph->header.xMin + kern_value_x) * funit_size;
local_offset[Y] = total_offset[Y] + (DBL)kern_value_y * funit_size;
/* Translate this glyph to its final position in the string */
Compute_Translation_Transform(&Trans, local_offset);
ttf->Translate(local_offset, &Trans);
/* Shift next glyph by the width of this one + any kerning amount */
total_offset[X] += (ffile->info->hmtx_table[ttf->glyph->myMetrics].advanceWidth +kern_value_x) * funit_size;
#ifdef TTF_DEBUG
Debug_Info("kern(%d): <%d, %d> (%g,%g)\n", i, last_index, glyph_index,
(DBL)kern_value_x*funit_size, (DBL)kern_value_y * funit_size);
Debug_Info("lsb(%d): %g\n", i,
(DBL)ffile->info->hmtx_table[glyph->myMetrics].lsb * funit_size);
Debug_Info("aw(%d): %g\n", i,
(DBL)ffile->info->hmtx_table[glyph->myMetrics].advanceWidth *
funit_size);
#endif
}
/*
* Add to the offset of the next character the minimum spacing specified.
*/
total_offset += offset;
/* Link this glyph with the others in the union */
Object->Type |= (ttf->Type & CHILDREN_FLAGS);
ttf->Type |= IS_CHILD_OBJECT;
Object->children.push_back(ttf);
last_index = glyph_index;
}
#ifdef TTF_DEBUG
// TODO - text_string is an UCS2 strings, while Debug_Info will expect char strings.
#error broken code
if (filename)
{
Debug_Info("TTF parsing of \"%s\" from %s complete\n", text_string, filename);
}
else
{
Debug_Info("TTF parsing of \"%s\" from builtin %d complete\n", text_string, font_id);
}
#endif
/* Close the font file descriptor */
if(ffile->fp!=NULL)
{
delete ffile->fp;
ffile->fp = NULL;
}
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessFontFile
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* Alexander Ennzmann
*
* DESCRIPTION
*
* Read the header information about the specific font. Parse the tables
* as we come across them.
*
* CHANGES
*
* Added tests for reading manditory tables/validity checks - Jan 1996 [AED]
* Reordered table parsing to avoid lots of file seeking - Jan 1996 [AED]
*
* Added builtin fonts when fontfilename is nullptr - Oct 2012 [JG]
*
******************************************************************************/
void ProcessFontFile(TrueTypeFont* ffile)
{
unsigned i;
int head_table_offset = 0;
int loca_table_offset = 0;
int maxp_table_offset = 0;
int kern_table_offset = 0;
int hhea_table_offset = 0;
int hmtx_table_offset = 0;
BYTE temp_tag[4];
sfnt_OffsetTable OffsetTable;
sfnt_TableDirectory Table;
/* We have already read all the header info, no need to do it again */
if (ffile->info != NULL)
return;
ffile->info = new TrueTypeInfo;
/*
* For Microsoft encodings 3, 1 is for Unicode
* 3, 0 is for Non-Unicode (ie symbols)
* For Macintosh encodings 1, 0 is for Roman character set
* For Unicode encodings 0, 3 is for Unicode
*/
switch(ffile->textEncoding)
{
case kStringEncoding_ASCII:
// first choice
ffile->info->platformID[0] = 1;
ffile->info->specificID[0] = 0;
// second choice
ffile->info->platformID[1] = 3;
ffile->info->specificID[1] = 1;
// third choice
ffile->info->platformID[2] = 0;
ffile->info->specificID[2] = 3;
// fourth choice
ffile->info->platformID[3] = 3;
ffile->info->specificID[3] = 0;
break;
case kStringEncoding_UTF8:
case kStringEncoding_System:
// first choice
ffile->info->platformID[0] = 0;
ffile->info->specificID[0] = 3;
// second choice
ffile->info->platformID[1] = 3;
ffile->info->specificID[1] = 1;
// third choice
ffile->info->platformID[2] = 1;
ffile->info->specificID[2] = 0;
// fourth choice
ffile->info->platformID[3] = 3;
ffile->info->specificID[3] = 0;
break;
}
/*
* Read the initial directory header on the TTF. The numTables variable
* tells us how many tables are present in this file.
*/
if (!ffile->fp->read(reinterpret_cast<char *>(&temp_tag), sizeof(BYTE) * 4))
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file table tag");
}
if (compare_tag4(temp_tag, tag_TTCFontFile))
{
READFIXED(ffile->fp); // header version - ignored [trf]
READULONG(ffile->fp); // directory count - ignored [trf]
// go to first font data block listed in the directory table entry [trf]
ffile->fp->seekg(READULONG(ffile->fp), SEEK_SET);
}
else
{
// if it is no TTC style file, it is a regular TTF style file
ffile->fp->seekg(0, SEEK_SET);
}
OffsetTable.version = READFIXED(ffile->fp);
OffsetTable.numTables = READUSHORT(ffile->fp);
OffsetTable.searchRange = READUSHORT(ffile->fp);
OffsetTable.entrySelector = READUSHORT(ffile->fp);
OffsetTable.rangeShift = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("OffsetTable:\n");
Debug_Info("version=%d\n", OffsetTable.version);
Debug_Info("numTables=%u\n", OffsetTable.numTables);
Debug_Info("searchRange=%u\n", OffsetTable.searchRange);
Debug_Info("entrySelector=%u\n", OffsetTable.entrySelector);
Debug_Info("rangeShift=%u\n", OffsetTable.rangeShift);
#endif
/*
* I don't know why we limit this to 40 tables, since the spec says there
* can be any number, but that's how it was when I got it. Added a warning
* just in case it ever happens in real life. [AED]
*/
if (OffsetTable.numTables > 40)
{
// TODO MESSAGE Warning("More than 40 (%d) TTF Tables in %s - some info may be lost!",
// OffsetTable.numTables, ffile->filename);
}
/* Process general font information and save it. */
for (i = 0; i < OffsetTable.numTables && i < 40; i++)
{
if (!ffile->fp->read(reinterpret_cast<char *>(&Table.tag), sizeof(BYTE) * 4))
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file table tag");
}
Table.checkSum = READULONG(ffile->fp);
Table.offset = READULONG(ffile->fp);
Table.length = READULONG(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("\nTable %d:\n",i);
Debug_Info("tag=%c%c%c%c\n", Table.tag[0], Table.tag[1],
Table.tag[2], Table.tag[3]);
Debug_Info("checkSum=%u\n", Table.checkSum);
Debug_Info("offset=%u\n", Table.offset);
Debug_Info("length=%u\n", Table.length);
#endif
if (compare_tag4(Table.tag, tag_CharToIndexMap))
ffile->info->cmap_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_GlyphData))
ffile->info->glyf_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_FontHeader))
head_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_IndexToLoc))
loca_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_MaxProfile))
maxp_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_Kerning))
kern_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_HorizHeader))
hhea_table_offset = Table.offset;
else if (compare_tag4(Table.tag, tag_HorizMetric))
hmtx_table_offset = Table.offset;
}
if (ffile->info->cmap_table_offset == 0 || ffile->info->glyf_table_offset == 0 ||
head_table_offset == 0 || loca_table_offset == 0 ||
hhea_table_offset == 0 || hmtx_table_offset == 0 ||
maxp_table_offset == 0)
{
// TODO MESSAGE throw POV_EXCEPTION(kFileDataErr, "Invalid TrueType font headers in %s", ffile->filename);
}
ProcessHeadTable(ffile, head_table_offset); /* Need indexToLocFormat */
if ((ffile->info->indexToLocFormat != 0 && ffile->info->indexToLocFormat != 1) ||
(ffile->info->unitsPerEm < 16 || ffile->info->unitsPerEm > 16384))
;// TODO MESSAGE Error("Invalid TrueType font data in %s", ffile->filename);
ProcessMaxpTable(ffile, maxp_table_offset); /* Need numGlyphs */
if (ffile->info->numGlyphs <= 0)
;// TODO MESSAGE Error("Invalid TrueType font data in %s", ffile->filename);
ProcessLocaTable(ffile, loca_table_offset); /* Now we can do loca_table */
ProcessHheaTable(ffile, hhea_table_offset); /* Need numberOfHMetrics */
if (ffile->info->numberOfHMetrics <= 0)
;// TODO MESSAGE Error("Invalid TrueType font data in %s", ffile->filename);
ProcessHmtxTable(ffile, hmtx_table_offset); /* Now we can read HMetrics */
if (kern_table_offset != 0)
ProcessKernTable(ffile, kern_table_offset);
}
/* Process the font header table */
void ProcessHeadTable(TrueTypeFont *ffile, int head_table_offset)
{
sfnt_FontHeader fontHeader;
/* Read head table */
ffile->fp->seekg(head_table_offset);
fontHeader.version = READFIXED(ffile->fp);
fontHeader.fontRevision = READFIXED(ffile->fp);
fontHeader.checkSumAdjustment = READULONG(ffile->fp);
fontHeader.magicNumber = READULONG(ffile->fp); /* should be 0x5F0F3CF5 */
fontHeader.flags = READUSHORT(ffile->fp);
fontHeader.unitsPerEm = READUSHORT(ffile->fp);
fontHeader.created.bc = READULONG(ffile->fp);
fontHeader.created.ad = READULONG(ffile->fp);
fontHeader.modified.bc = READULONG(ffile->fp);
fontHeader.modified.ad = READULONG(ffile->fp);
fontHeader.xMin = READFWORD(ffile->fp);
fontHeader.yMin = READFWORD(ffile->fp);
fontHeader.xMax = READFWORD(ffile->fp);
fontHeader.yMax = READFWORD(ffile->fp);
fontHeader.macStyle = READUSHORT(ffile->fp);
fontHeader.lowestRecPPEM = READUSHORT(ffile->fp);
fontHeader.fontDirectionHint = READSHORT(ffile->fp);
fontHeader.indexToLocFormat = READSHORT(ffile->fp);
fontHeader.glyphDataFormat = READSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("\nfontHeader:\n");
Debug_Info("version: %d\n",fontHeader.version);
Debug_Info("fontRevision: %d\n",fontHeader.fontRevision);
Debug_Info("checkSumAdjustment: %u\n",fontHeader.checkSumAdjustment);
Debug_Info("magicNumber: 0x%8X\n",fontHeader.magicNumber);
Debug_Info("flags: %u\n",fontHeader.flags);
Debug_Info("unitsPerEm: %u\n",fontHeader.unitsPerEm);
Debug_Info("created.bc: %u\n",fontHeader.created.bc);
Debug_Info("created.ad: %u\n",fontHeader.created.ad);
Debug_Info("modified.bc: %u\n",fontHeader.modified.bc);
Debug_Info("modified.ad: %u\n",fontHeader.modified.ad);
Debug_Info("xMin: %d\n",fontHeader.xMin);
Debug_Info("yMin: %d\n",fontHeader.yMin);
Debug_Info("xMax: %d\n",fontHeader.xMax);
Debug_Info("yMax: %d\n",fontHeader.yMax);
Debug_Info("macStyle: %u\n",fontHeader.macStyle);
Debug_Info("lowestRecPPEM: %u\n",fontHeader.lowestRecPPEM);
Debug_Info("fontDirectionHint: %d\n",fontHeader.fontDirectionHint);
Debug_Info("indexToLocFormat: %d\n",fontHeader.indexToLocFormat);
Debug_Info("glyphDataFormat: %d\n",fontHeader.glyphDataFormat);
#endif
if (fontHeader.magicNumber != 0x5F0F3CF5)
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font.");
}
ffile->info->indexToLocFormat = fontHeader.indexToLocFormat;
ffile->info->unitsPerEm = fontHeader.unitsPerEm;
}
/* Determine the relative offsets of glyphs */
void ProcessLocaTable(TrueTypeFont *ffile, int loca_table_offset)
{
int i;
/* Move to location of table in file */
ffile->fp->seekg(loca_table_offset);
ffile->info->loca_table = new ULONG[ffile->info->numGlyphs+1];
#ifdef TTF_DEBUG
Debug_Info("\nlocation table:\n");
Debug_Info("version: %s\n",(ffile->info->indexToLocFormat?"long":"short"));
#endif
/* Now read and save the location table */
if (ffile->info->indexToLocFormat == 0) /* short version */
{
for (i = 0; i < ffile->info->numGlyphs; i++)
{
ffile->info->loca_table[i] = ((ULONG)READUSHORT(ffile->fp)) << 1;
#ifdef TTF_DEBUG2
Debug_Info("loca_table[%d] @ %u\n", i, ffile->info->loca_table[i]);
#endif
}
}
else /* long version */
{
for (i = 0; i < ffile->info->numGlyphs; i++)
{
ffile->info->loca_table[i] = READULONG(ffile->fp);
#ifdef TTF_DEBUG2
Debug_Info("loca_table[%d] @ %u\n", i, ffile->info->loca_table[i]);
#endif
}
}
}
/*
* This routine determines the total number of glyphs in a TrueType file.
* Necessary so that we can allocate the proper amount of storage for the glyph
* location table.
*/
void ProcessMaxpTable(TrueTypeFont *ffile, int maxp_table_offset)
{
/* seekg to the maxp table, skipping the 4 byte version number */
ffile->fp->seekg(maxp_table_offset + 4);
ffile->info->numGlyphs = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("\nmaximum profile table:\n");
Debug_Info("numGlyphs: %u\n", ffile->info->numGlyphs);
#endif
}
/* Read the kerning information for a glyph */
void ProcessKernTable(TrueTypeFont *ffile, int kern_table_offset)
{
int i, j;
USHORT temp16;
USHORT length;
KernTables *kern_table;
kern_table = &ffile->info->kerning_tables;
/* Move to the beginning of the kerning table, skipping the 2 byte version */
ffile->fp->seekg(kern_table_offset + 2);
/* Read in the number of kerning tables */
kern_table->nTables = READUSHORT(ffile->fp);
kern_table->tables = NULL; /*<==[esp] added (in case nTables is zero)*/
#ifdef TTF_DEBUG
Debug_Info("\nKerning table:\n", kern_table_offset);
Debug_Info("Offset: %d\n", kern_table_offset);
Debug_Info("Number of tables: %u\n",kern_table->nTables);
#endif
/* Don't do any more work if there isn't kerning info */
if (kern_table->nTables == 0)
return;
kern_table->tables = new TTKernTable[kern_table->nTables];
for (i = 0; i < kern_table->nTables; i++)
{
/* Read in a subtable */
temp16 = READUSHORT(ffile->fp); /* Subtable version */
length = READUSHORT(ffile->fp); /* Subtable length */
kern_table->tables[i].coverage = READUSHORT(ffile->fp); /* Coverage bits */
#ifdef TTF_DEBUG
Debug_Info("Coverage table[%d] (0x%X):", i, kern_table->tables[i].coverage);
Debug_Info(" type %u", (kern_table->tables[i].coverage >> 8));
Debug_Info(" %s", (kern_table->tables[i].coverage & KERN_HORIZONTAL ?
"Horizontal" : "Vertical" ));
Debug_Info(" %s values", (kern_table->tables[i].coverage & KERN_MINIMUM ?
"Minimum" : "Kerning" ));
Debug_Info("%s", (kern_table->tables[i].coverage & KERN_CROSS_STREAM ?
" Cross-stream" : "" ));
Debug_Info("%s\n", (kern_table->tables[i].coverage & KERN_OVERRIDE ?
" Override" : "" ));
#endif
kern_table->tables[i].kern_pairs = NULL; /*<==[esp] added*/
kern_table->tables[i].nPairs = 0; /*<==[esp] added*/
if ((kern_table->tables[i].coverage >> 8) == 0)
{
/* Can only handle format 0 kerning subtables */
kern_table->tables[i].nPairs = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("entries in table[%d]: %d\n", i, kern_table->tables[i].nPairs);
#endif
temp16 = READUSHORT(ffile->fp); /* searchRange */
temp16 = READUSHORT(ffile->fp); /* entrySelector */
temp16 = READUSHORT(ffile->fp); /* rangeShift */
kern_table->tables[i].kern_pairs = new KernData[kern_table->tables[i].nPairs];
for (j = 0; j < kern_table->tables[i].nPairs; j++)
{
/* Read in a kerning pair */
kern_table->tables[i].kern_pairs[j].left = READUSHORT(ffile->fp);
kern_table->tables[i].kern_pairs[j].right = READUSHORT(ffile->fp);
kern_table->tables[i].kern_pairs[j].value = READFWORD(ffile->fp);
#ifdef TTF_DEBUG2
Debug_Info("Kern pair: <%d,%d> = %d\n",
(int)kern_table->tables[i].kern_pairs[j].left,
(int)kern_table->tables[i].kern_pairs[j].right,
(int)kern_table->tables[i].kern_pairs[j].value);
#endif
}
}
else
{
#ifdef TTF_DEBUG2
Warning("Cannot handle format %u kerning data",
(kern_table->tables[i].coverage >> 8));
#endif
/*
* seekg to the end of this table, excluding the length of the version,
* length, and coverage USHORTs, which we have already read.
*/
ffile->fp->seekg((int)(length - 6), POV_SEEK_CUR);
kern_table->tables[i].nPairs = 0;
}
}
}
/*
* This routine determines the total number of horizontal metrics.
*/
void ProcessHheaTable(TrueTypeFont *ffile, int hhea_table_offset)
{
#ifdef TTF_DEBUG
sfnt_HorizHeader horizHeader;
/* seekg to the hhea table */
ffile->fp->seekg(hhea_table_offset);
horizHeader.version = READFIXED(ffile->fp);
horizHeader.Ascender = READFWORD(ffile->fp);
horizHeader.Descender = READFWORD(ffile->fp);
horizHeader.LineGap = READFWORD(ffile->fp);
horizHeader.advanceWidthMax = READUFWORD(ffile->fp);
horizHeader.minLeftSideBearing = READFWORD(ffile->fp);
horizHeader.minRightSideBearing = READFWORD(ffile->fp);
horizHeader.xMaxExtent = READFWORD(ffile->fp);
horizHeader.caretSlopeRise = READSHORT(ffile->fp);
horizHeader.caretSlopeRun = READSHORT(ffile->fp);
horizHeader.reserved1 = READSHORT(ffile->fp);
horizHeader.reserved2 = READSHORT(ffile->fp);
horizHeader.reserved3 = READSHORT(ffile->fp);
horizHeader.reserved4 = READSHORT(ffile->fp);
horizHeader.reserved5 = READSHORT(ffile->fp);
horizHeader.metricDataFormat = READSHORT(ffile->fp);
#else
/* seekg to the hhea table, skipping all that stuff we don't need */
ffile->fp->seekg (hhea_table_offset + 34);
#endif
ffile->info->numberOfHMetrics = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("\nhorizontal header table:\n");
Debug_Info("Ascender: %d\n",horizHeader.Ascender);
Debug_Info("Descender: %d\n",horizHeader.Descender);
Debug_Info("LineGap: %d\n",horizHeader.LineGap);
Debug_Info("advanceWidthMax: %d\n",horizHeader.advanceWidthMax);
Debug_Info("minLeftSideBearing: %d\n",horizHeader.minLeftSideBearing);
Debug_Info("minRightSideBearing: %d\n",horizHeader.minRightSideBearing);
Debug_Info("xMaxExtent: %d\n",horizHeader.xMaxExtent);
Debug_Info("caretSlopeRise: %d\n",horizHeader.caretSlopeRise);
Debug_Info("caretSlopeRun: %d\n",horizHeader.caretSlopeRun);
Debug_Info("metricDataFormat: %d\n",horizHeader.metricDataFormat);
Debug_Info("numberOfHMetrics: %d\n",ffile->numberOfHMetrics);
#endif
}
void ProcessHmtxTable (TrueTypeFont *ffile, int hmtx_table_offset)
{
int i;
longHorMetric *metric;
uFWord lastAW = 0; /* Just to quiet warnings. */
ffile->fp->seekg (hmtx_table_offset);
ffile->info->hmtx_table = new longHorMetric[ffile->info->numGlyphs];
/*
* Read in the total glyph width, and the left side offset. There is
* guaranteed to be at least one longHorMetric entry in this table to
* set the advanceWidth for the subsequent lsb entries.
*/
for (i=0, metric=ffile->info->hmtx_table; i < ffile->info->numberOfHMetrics; i++,metric++)
{
lastAW = metric->advanceWidth = READUFWORD(ffile->fp);
metric->lsb = READFWORD(ffile->fp);
}
/* Read in the remaining left offsets */
for (; i < ffile->info->numGlyphs; i++, metric++)
{
metric->advanceWidth = lastAW;
metric->lsb = READFWORD(ffile->fp);
}
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessCharacter
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* Finds the glyph description for the current character.
*
* CHANGES
*
* -
*
******************************************************************************/
GlyphPtr ProcessCharacter(TrueTypeFont *ffile, unsigned int search_char, unsigned int *glyph_index)
{
GlyphPtrMap::iterator iGlyph;
/* See if we have already processed this glyph */
iGlyph = ffile->info->glyphsByChar.find(search_char);
if (iGlyph != ffile->info->glyphsByChar.end())
{
/* Found it, no need to do any more work */
#ifdef TTF_DEBUG
Debug_Info("Cached glyph: %c/%u\n",(char)search_char,(*iGlyph).second->glyph_index);
#endif
*glyph_index = (*iGlyph).second->glyph_index;
return (*iGlyph).second;
}
*glyph_index = ProcessCharMap(ffile, search_char);
if (*glyph_index == 0)
;// TODO MESSAGE Warning("Character %d (0x%X) not found in %s", (BYTE)search_char,
// search_char, ffile->filename);
/* See if we have already processed this glyph (using the glyph index) */
iGlyph = ffile->info->glyphsByIndex.find(*glyph_index);
if (iGlyph != ffile->info->glyphsByIndex.end())
{
/* Found it, no need to do any more work (except remember the char-to-glyph mapping for next time) */
ffile->info->glyphsByChar[search_char] = (*iGlyph).second;
#ifdef TTF_DEBUG
Debug_Info("Cached glyph: %c/%u\n",(char)search_char,(*iGlyph).second->glyph_index);
#endif
*glyph_index = (*iGlyph).second->glyph_index;
return (*iGlyph).second;
}
GlyphPtr glyph = ExtractGlyphInfo(ffile, *glyph_index, search_char);
/* Add this glyph to the ones we already know about */
ffile->info->glyphsByChar[search_char] = glyph;
ffile->info->glyphsByIndex[*glyph_index] = glyph;
/* Glyph is all built */
return glyph;
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessCharMap
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* Find the character mapping for 'search_char'. We should really know
* which character set we are using (ie ISO 8859-1, Mac, Unicode, etc).
* Search char should really be a USHORT to handle double byte systems.
*
* CHANGES
*
* 961120 esp Added check to allow Macintosh encodings to pass
*
******************************************************************************/
USHORT ProcessCharMap(TrueTypeFont *ffile, unsigned int search_char)
{
int initial_table_offset;
int old_table_offset;
int entry_offset;
sfnt_platformEntry cmapEntry;
sfnt_mappingTable encodingTable;
int i, j, table_count;
/* Move to the start of the character map, skipping the 2 byte version */
ffile->fp->seekg (ffile->info->cmap_table_offset + 2);
table_count = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("table_count=%d\n", table_count);
#endif
/*
* Search the tables until we find the glyph index for the search character.
* Just return the first one we find...
*/
initial_table_offset = ffile->fp->tellg (); /* Save the initial position */
for(j = 0; j <= 3; j++)
{
ffile->fp->seekg(initial_table_offset); /* Always start new search at the initial position */
for (i = 0; i < table_count; i++)
{
cmapEntry.platformID = READUSHORT(ffile->fp);
cmapEntry.specificID = READUSHORT(ffile->fp);
cmapEntry.offset = READULONG(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("cmapEntry: platformID=%d\n", cmapEntry.platformID);
Debug_Info("cmapEntry: specificID=%d\n", cmapEntry.specificID);
Debug_Info("cmapEntry: offset=%d\n", cmapEntry.offset);
#endif
/*
* Check if this is the encoding table we want to use.
* The search is done according to user preference.
*/
if ( ffile->info->platformID[j] != cmapEntry.platformID ) /* [JAC 01/99] */
{
continue;
}
entry_offset = cmapEntry.offset;
old_table_offset = ffile->fp->tellg (); /* Save the current position */
ffile->fp->seekg (ffile->info->cmap_table_offset + entry_offset);
encodingTable.format = READUSHORT(ffile->fp);
encodingTable.length = READUSHORT(ffile->fp);
encodingTable.version = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("Encoding table, format: %u, length: %u, version: %u\n",
encodingTable.format, encodingTable.length, encodingTable.version);
#endif
if (encodingTable.format == 0)
{
/*
* Translation is simple - add 'entry_char' to the start of the
* table and grab what's there.
*/
#ifdef TTF_DEBUG
Debug_Info("Apple standard index mapping\n");
#endif
return(ProcessFormat0Glyph(ffile, search_char));
}
#if 0 /* Want to get the rest of these working first */
else if (encodingTable.format == 2)
{
/* Used for multi-byte character encoding (Chinese, Japanese, etc) */
#ifdef TTF_DEBUG
Debug_Info("High-byte index mapping\n");
#endif
return(ProcessFormat2Glyph(ffile, search_char));
}
#endif
else if (encodingTable.format == 4)
{
/* Microsoft UGL encoding */
#ifdef TTF_DEBUG
Debug_Info("Microsoft standard index mapping\n");
#endif
return(ProcessFormat4Glyph(ffile, search_char));
}
else if (encodingTable.format == 6)
{
#ifdef TTF_DEBUG
Debug_Info("Trimmed table mapping\n");
#endif
return(ProcessFormat6Glyph(ffile, search_char));
}
#ifdef TTF_DEBUG
else
Debug_Info("Unsupported TrueType font index mapping format: %u\n",
encodingTable.format);
#endif
/* Go to the next table entry if we didn't find a match */
ffile->fp->seekg (old_table_offset);
}
}
/*
* No character mapping was found - very odd, we should really have had the
* character in at least one table. Perhaps getting here means we didn't
* have any character mapping tables. '0' means no mapping.
*/
return 0;
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessFormat0Glyph
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* This handles the Apple standard index mapping for glyphs.
* The file pointer must be pointing immediately after the version entry in the
* encoding table for the next two functions to work.
*
* CHANGES
*
* -
*
******************************************************************************/
USHORT ProcessFormat0Glyph(TrueTypeFont *ffile, unsigned int search_char)
{
BYTE temp_index;
ffile->fp->seekg ((int)search_char, POV_SEEK_CUR);
if (!ffile->fp->read (reinterpret_cast<char *>(&temp_index), 1)) /* Each index is 1 byte */
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
return (USHORT)(temp_index);
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessFormat4Glyph
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* This handles the Microsoft standard index mapping for glyph tables
*
* CHANGES
*
* Mar 26, 1996: Cache segment info rather than read each time. [AED]
*
******************************************************************************/
USHORT ProcessFormat4Glyph(TrueTypeFont *ffile, unsigned int search_char)
{
int i;
unsigned int glyph_index = 0; /* Set the glyph index to "not present" */
/*
* If this is the first time we are here, read all of the segment headers,
* and save them for later calls to this function, rather than seeking and
* mallocing for each character
*/
if (ffile->info->segCount == 0)
{
USHORT temp16;
ffile->info->segCount = READUSHORT(ffile->fp) >> 1;
ffile->info->searchRange = READUSHORT(ffile->fp);
ffile->info->entrySelector = READUSHORT(ffile->fp);
ffile->info->rangeShift = READUSHORT(ffile->fp);
/* Now allocate and read in the segment arrays */
ffile->info->endCount = new USHORT[ffile->info->segCount];
ffile->info->startCount = new USHORT[ffile->info->segCount];
ffile->info->idDelta = new USHORT[ffile->info->segCount];
ffile->info->idRangeOffset = new USHORT[ffile->info->segCount];
for (i = 0; i < ffile->info->segCount; i++)
{
ffile->info->endCount[i] = READUSHORT(ffile->fp);
}
temp16 = READUSHORT(ffile->fp); /* Skip over 'reservedPad' */
for (i = 0; i < ffile->info->segCount; i++)
{
ffile->info->startCount[i] = READUSHORT(ffile->fp);
}
for (i = 0; i < ffile->info->segCount; i++)
{
ffile->info->idDelta[i] = READUSHORT(ffile->fp);
}
/* location of start of idRangeOffset */
ffile->info->glyphIDoffset = ffile->fp->tellg ();
for (i = 0; i < ffile->info->segCount; i++)
{
ffile->info->idRangeOffset[i] = READUSHORT(ffile->fp);
}
}
/* Search the segments for our character */
glyph_search:
for (i = 0; i < ffile->info->segCount; i++)
{
if (search_char <= ffile->info->endCount[i])
{
if (search_char >= ffile->info->startCount[i])
{
/* Found correct range for this character */
if (ffile->info->idRangeOffset[i] == 0)
{
glyph_index = search_char + ffile->info->idDelta[i];
}
else
{
/*
* Alternate encoding of glyph indices, relies on a quite unusual way
* of storing the offsets. We need the *2s because we are talking
* about addresses of shorts and not bytes.
*
* (glyphIDoffset + i*2 + idRangeOffset[i]) == &idRangeOffset[i]
*/
ffile->fp->seekg (ffile->info->glyphIDoffset + 2*i + ffile->info->idRangeOffset[i]+
2*(search_char - ffile->info->startCount[i]));
glyph_index = READUSHORT(ffile->fp);
if (glyph_index != 0)
glyph_index = glyph_index + ffile->info->idDelta[i];
}
}
break;
}
}
/*
* If we haven't found the character yet, and this is the first time to
* search the tables, try looking in the Unicode user space, since this
* is the location Microsoft recommends for symbol characters like those
* in wingdings and dingbats.
*/
if (glyph_index == 0 && search_char < 0x100)
{
search_char += 0xF000;
#ifdef TTF_DEBUG
Debug_Info("Looking for glyph in Unicode user space (0x%X)\n", search_char);
#endif
goto glyph_search;
}
/* Deallocate the memory we used for the segment arrays */
return glyph_index;
}
/*****************************************************************************
*
* FUNCTION
*
* ProcessFormat6Glyph
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* This handles the trimmed table mapping for glyphs.
*
* CHANGES
*
* -
*
******************************************************************************/
USHORT ProcessFormat6Glyph(TrueTypeFont *ffile, unsigned int search_char)
{
USHORT firstCode, entryCount;
USHORT glyph_index;
firstCode = READUSHORT(ffile->fp);
entryCount = READUSHORT(ffile->fp);
if (search_char >= firstCode && search_char < firstCode + entryCount)
{
ffile->fp->seekg (((int)(search_char - firstCode))*2, POV_SEEK_CUR);
glyph_index = READUSHORT(ffile->fp);
}
else
glyph_index = 0;
return glyph_index;
}
/*****************************************************************************
*
* FUNCTION
*
* ExtractGlyphInfo
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* Change TTF outline information for the glyph(s) into a useful format
*
* CHANGES
*
* -
*
******************************************************************************/
GlyphPtr ExtractGlyphInfo(TrueTypeFont *ffile, unsigned int glyph_index, unsigned int c)
{
GlyphOutline *ttglyph;
GlyphPtr glyph;
ttglyph = ExtractGlyphOutline(ffile, glyph_index, c);
/*
* Convert the glyph outline information from TrueType layout into a more
* easily processed format
*/
glyph = ConvertOutlineToGlyph(ffile, ttglyph);
glyph->glyph_index = glyph_index;
glyph->myMetrics = ttglyph->myMetrics;
/* Free up outline information */
if (ttglyph)
delete ttglyph;
#ifdef TTF_DEBUG3
int i, j;
Debug_Info("// Character '%c'\n", (char)c);
for(i = 0; i < (int)glyph->header.numContours; i++)
{
Debug_Info("BYTE gGlypthFlags_%c_%d[] = \n", (char)c, i);
Debug_Info("{");
for(j = 0; j <= (int)glyph->contours[i].count; j++)
{
if((j % 10) == 0)
Debug_Info("\n\t");
Debug_Info("0x%x, ", (unsigned int)glyph->contours[i].flags[j]);
}
Debug_Info("\n};\n\n");
Debug_Info("DBL gGlypthX_%c_%d[] = \n", (char)c, i);
Debug_Info("{");
for(j = 0; j <= (int)glyph->contours[i].count; j++)
{
if((j % 10) == 0)
Debug_Info("\n\t");
Debug_Info("%f, ", (DBL)glyph->contours[i].x[j]);
}
Debug_Info("\n};\n\n");
Debug_Info("DBL gGlypthY_%c_%d[] = \n", (char)c, i);
Debug_Info("{");
for(j = 0; j <= (int)glyph->contours[i].count; j++)
{
if((j % 10) == 0)
Debug_Info("\n\t");
Debug_Info("%f, ", (DBL)glyph->contours[i].y[j]);
}
Debug_Info("\n};\n\n");
}
Debug_Info("Contour gGlypthContour_%c[] = \n", (char)c);
Debug_Info("{\n");
for(i = 0; i < glyph->header.numContours; i++)
{
Debug_Info("\t{\n");
Debug_Info("\t\t%u, // inside_flag \n", (unsigned int)glyph->contours[i].inside_flag);
Debug_Info("\t\t%u, // count \n", (unsigned int)glyph->contours[i].count);
Debug_Info("\t\tgGlypthFlags_%c_%d, // flags[]\n", (char)c, i);
Debug_Info("\t\tgGlypthX_%c_%d, // x[]\n", (char)c, i);
Debug_Info("\t\tgGlypthY_%c_%d // y[]\n", (char)c, i);
Debug_Info("\t},\n");
}
Debug_Info("\n};\n\n");
Debug_Info("Glyph gGlypth_%c = \n", (char)c);
Debug_Info("{\n");
Debug_Info("\t{ // header\n");
Debug_Info("\t\t%u, // header.numContours \n", (unsigned int)glyph->header.numContours);
Debug_Info("\t\t%f, // header.xMin\n", (DBL)glyph->header.xMin);
Debug_Info("\t\t%f, // header.yMin\n", (DBL)glyph->header.yMin);
Debug_Info("\t\t%f, // header.xMax\n", (DBL)glyph->header.xMax);
Debug_Info("\t\t%f // header.yMax\n", (DBL)glyph->header.yMax);
Debug_Info("\t},\n");
Debug_Info("\t%u, // glyph_index\n", (unsigned int)glyph->glyph_index);
Debug_Info("\tgGlypthContour_%c, // contours[]\n", (char)c);
Debug_Info("\t%u, // unitsPerEm\n", (unsigned int)glyph->unitsPerEm);
Debug_Info("\tNULL, // next\n");
Debug_Info("\t%u, // c\n", (unsigned int)glyph->c);
Debug_Info("\t%u // myMetrics\n", (unsigned int)glyph->myMetrics);
Debug_Info("};\n\n");
#endif
return glyph;
}
/*****************************************************************************
*
* FUNCTION
*
* ExtractGlyphOutline
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* Read the contour information for a specific glyph. This has to be a
* separate routine from ExtractGlyphInfo because we call it recurisvely
* for multiple component glyphs.
*
* CHANGES
*
* -
*
******************************************************************************/
GlyphOutline *ExtractGlyphOutline(TrueTypeFont *ffile, unsigned int glyph_index, unsigned int c)
{
int i;
USHORT n;
SHORT nc;
GlyphOutline *ttglyph;
ttglyph = new GlyphOutline;
ttglyph->myMetrics = glyph_index;
/* Have to treat space characters differently */
if (c != ' ')
{
ffile->fp->seekg (ffile->info->glyf_table_offset+ffile->info->loca_table[glyph_index]);
ttglyph->header.numContours = READSHORT(ffile->fp);
ttglyph->header.xMin = READFWORD(ffile->fp); /* These may be */
ttglyph->header.yMin = READFWORD(ffile->fp); /* unreliable in */
ttglyph->header.xMax = READFWORD(ffile->fp); /* some fonts. */
ttglyph->header.yMax = READFWORD(ffile->fp);
}
#ifdef TTF_DEBUG
Debug_Info("ttglyph->header:\n");
Debug_Info("glyph_index=%d\n", glyph_index);
Debug_Info("loca_table[%d]=%d\n",glyph_index,ffile->info->loca_table[glyph_index]);
Debug_Info("numContours=%d\n", (int)ttglyph->header.numContours);
#endif
nc = ttglyph->header.numContours;
/*
* A positive number of contours means a regular glyph, with possibly
* several separate line segments making up the outline.
*/
if (nc > 0)
{
FWord coord;
BYTE flag, repeat_count;
USHORT temp16;
/* Grab the contour endpoints */
ttglyph->endPoints = reinterpret_cast<USHORT *>(POV_MALLOC(nc * sizeof(USHORT), "ttf"));
for (i = 0; i < nc; i++)
{
ttglyph->endPoints[i] = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("endPoints[%d]=%d\n", i, ttglyph->endPoints[i]);
#endif
}
/* Skip over the instructions */
temp16 = READUSHORT(ffile->fp);
ffile->fp->seekg (temp16, POV_SEEK_CUR);
#ifdef TTF_DEBUG
Debug_Info("skipping instruction bytes: %d\n", temp16);
#endif
/* Determine the number of points making up this glyph */
n = ttglyph->numPoints = ttglyph->endPoints[nc - 1] + 1;
#ifdef TTF_DEBUG
Debug_Info("numPoints=%d\n", ttglyph->numPoints);
#endif
/* Read the flags */
ttglyph->flags = reinterpret_cast<BYTE *>(POV_MALLOC(n * sizeof(BYTE), "ttf"));
for (i = 0; i < ttglyph->numPoints; i++)
{
if (!ffile->fp->read(reinterpret_cast<char *>(&ttglyph->flags[i]), sizeof(BYTE)))
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
if (ttglyph->flags[i] & REPEAT_FLAGS)
{
if (!ffile->fp->read(reinterpret_cast<char *>(&repeat_count), sizeof(BYTE)))
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
for (; repeat_count > 0; repeat_count--, i++)
{
#ifdef TTF_DEBUG
if (i>=n)
{
Debug_Info("readflags ERROR: i >= n (%d > %d)\n", i, n);
}
#endif
if (i<n) /* hack around a bug that is trying to write too many flags */
ttglyph->flags[i + 1] = ttglyph->flags[i];
}
}
}
#ifdef TTF_DEBUG
Debug_Info("flags:");
for (i=0; i<n; i++)
Debug_Info(" %02x", ttglyph->flags[i]);
Debug_Info("\n");
#endif
/* Read the coordinate vectors */
ttglyph->x = reinterpret_cast<DBL *>(POV_MALLOC(n * sizeof(DBL), "ttf"));
ttglyph->y = reinterpret_cast<DBL *>(POV_MALLOC(n * sizeof(DBL), "ttf"));
coord = 0;
for (i = 0; i < ttglyph->numPoints; i++)
{
/* Read each x coordinate */
flag = ttglyph->flags[i];
if (flag & XSHORT)
{
BYTE temp8;
if (!ffile->fp->read(reinterpret_cast<char *>(&temp8), 1))
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
if (flag & SHORT_X_IS_POS)
coord += temp8;
else
coord -= temp8;
}
else if (!(flag & NEXT_X_IS_ZERO))
{
coord += READSHORT(ffile->fp);
}
/* Find our own maximum and minimum x coordinates */
if (coord > ttglyph->header.xMax)
ttglyph->header.xMax = coord;
if (coord < ttglyph->header.xMin)
ttglyph->header.xMin = coord;
ttglyph->x[i] = (DBL)coord / (DBL)ffile->info->unitsPerEm;
}
coord = 0;
for (i = 0; i < ttglyph->numPoints; i++)
{
/* Read each y coordinate */
flag = ttglyph->flags[i];
if (flag & YSHORT)
{
BYTE temp8;
if (!ffile->fp->read(reinterpret_cast<char *>(&temp8), 1))
{
throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
}
if (flag & SHORT_Y_IS_POS)
coord += temp8;
else
coord -= temp8;
}
else if (!(flag & NEXT_Y_IS_ZERO))
{
coord += READSHORT(ffile->fp);
}
/* Find out our own maximum and minimum y coordinates */
if (coord > ttglyph->header.yMax)
ttglyph->header.yMax = coord;
if (coord < ttglyph->header.yMin)
ttglyph->header.yMin = coord;
ttglyph->y[i] = (DBL)coord / (DBL)ffile->info->unitsPerEm;
}
}
/*
* A negative number for numContours means that this glyph is
* made up of several separate glyphs.
*/
else if (nc < 0)
{
USHORT flags;
ttglyph->header.numContours = 0;
ttglyph->numPoints = 0;
do
{
GlyphOutline *sub_ttglyph;
unsigned int sub_glyph_index;
int current_pos;
SHORT arg1, arg2;
DBL xoff = 0, yoff = 0;
DBL xscale = 1, yscale = 1;
DBL scale01 = 0, scale10 = 0;
USHORT n2;
SHORT nc2;
flags = READUSHORT(ffile->fp);
sub_glyph_index = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
Debug_Info("sub_glyph %d: ", sub_glyph_index);
#endif
if (flags & ARG_1_AND_2_ARE_WORDS)
{
#ifdef TTF_DEBUG
Debug_Info("ARG_1_AND_2_ARE_WORDS ");
#endif
arg1 = READSHORT(ffile->fp);
arg2 = READSHORT(ffile->fp);
}
else
{
arg1 = READUSHORT(ffile->fp);
arg2 = arg1 & 0xFF;
arg1 = (arg1 >> 8) & 0xFF;
}
#ifdef TTF_DEBUG
if (flags & ROUND_XY_TO_GRID)
{
Debug_Info("ROUND_XY_TO_GRID ");
}
if (flags & MORE_COMPONENTS)
{
Debug_Info("MORE_COMPONENTS ");
}
#endif
if (flags & WE_HAVE_A_SCALE)
{
xscale = yscale = (DBL)READSHORT(ffile->fp)/0x4000;
#ifdef TTF_DEBUG
Debug_Info("WE_HAVE_A_SCALE ");
Debug_Info("xscale = %lf\t", xscale);
Debug_Info("scale01 = %lf\n", scale01);
Debug_Info("scale10 = %lf\t", scale10);
Debug_Info("yscale = %lf\n", yscale);
#endif
}
else if (flags & WE_HAVE_AN_X_AND_Y_SCALE)
{
xscale = (DBL)READSHORT(ffile->fp)/0x4000;
yscale = (DBL)READSHORT(ffile->fp)/0x4000;
#ifdef TTF_DEBUG
Debug_Info("WE_HAVE_AN_X_AND_Y_SCALE ");
Debug_Info("xscale = %lf\t", xscale);
Debug_Info("scale01 = %lf\n", scale01);
Debug_Info("scale10 = %lf\t", scale10);
Debug_Info("yscale = %lf\n", yscale);
#endif
}
else if (flags & WE_HAVE_A_TWO_BY_TWO)
{
xscale = (DBL)READSHORT(ffile->fp)/0x4000;
scale01 = (DBL)READSHORT(ffile->fp)/0x4000;
scale10 = (DBL)READSHORT(ffile->fp)/0x4000;
yscale = (DBL)READSHORT(ffile->fp)/0x4000;
#ifdef TTF_DEBUG
Debug_Info("WE_HAVE_A_TWO_BY_TWO ");
Debug_Info("xscale = %lf\t", xscale);
Debug_Info("scale01 = %lf\n", scale01);
Debug_Info("scale10 = %lf\t", scale10);
Debug_Info("yscale = %lf\n", yscale);
#endif
}
if (flags & ARGS_ARE_XY_VALUES)
{
xoff = (DBL)arg1 / ffile->info->unitsPerEm;
yoff = (DBL)arg2 / ffile->info->unitsPerEm;
#ifdef TTF_DEBUG
Debug_Info("ARGS_ARE_XY_VALUES ");
Debug_Info("\narg1 = %d xoff = %lf\t", arg1, xoff);
Debug_Info("arg2 = %d yoff = %lf\n", arg2, yoff);
#endif
}
else /* until I understand how this method works... */
{
// TODO MESSAGE Warning("Cannot handle part of glyph %d (0x%X).", c, c);
continue;
}
if (flags & USE_MY_METRICS)
{
#ifdef TTF_DEBUG
Debug_Info("USE_MY_METRICS ");
#endif
ttglyph->myMetrics = sub_glyph_index;
}
current_pos = ffile->fp->tellg ();
sub_ttglyph = ExtractGlyphOutline(ffile, sub_glyph_index, c);
ffile->fp->seekg (current_pos);
if ((nc2 = sub_ttglyph->header.numContours) == 0)
continue;
nc = ttglyph->header.numContours;
n = ttglyph->numPoints;
n2 = sub_ttglyph->numPoints;
ttglyph->endPoints = reinterpret_cast<USHORT *>(POV_REALLOC(ttglyph->endPoints,
(nc + nc2) * sizeof(USHORT), "ttf"));
ttglyph->flags = reinterpret_cast<BYTE *>(POV_REALLOC(ttglyph->flags, (n+n2)*sizeof(BYTE), "ttf"));
ttglyph->x = reinterpret_cast<DBL *>(POV_REALLOC(ttglyph->x, (n + n2) * sizeof(DBL), "ttf"));
ttglyph->y = reinterpret_cast<DBL *>(POV_REALLOC(ttglyph->y, (n + n2) * sizeof(DBL), "ttf"));
/* Add the sub glyph info to the end of the current glyph */
ttglyph->header.numContours += nc2;
ttglyph->numPoints += n2;
for (i = 0; i < nc2; i++)
{
ttglyph->endPoints[i + nc] = sub_ttglyph->endPoints[i] + n;
#ifdef TTF_DEBUG
Debug_Info("endPoints[%d]=%d\n", i + nc, ttglyph->endPoints[i + nc]);
#endif
}
for (i = 0; i < n2; i++)
{
#ifdef TTF_DEBUG
Debug_Info("x[%d]=%lf\t", i, sub_ttglyph->x[i]);
Debug_Info("y[%d]=%lf\n", i, sub_ttglyph->y[i]);
#endif
ttglyph->flags[i + n] = sub_ttglyph->flags[i];
ttglyph->x[i + n] = xscale * sub_ttglyph->x[i] +
scale01 * sub_ttglyph->y[i] + xoff;
ttglyph->y[i + n] = scale10 * sub_ttglyph->x[i] +
yscale * sub_ttglyph->y[i] + yoff;
#ifdef TTF_DEBUG
Debug_Info("x[%d]=%lf\t", i+n, ttglyph->x[i+n]);
Debug_Info("y[%d]=%lf\n", i+n, ttglyph->y[i+n]);
#endif
if (ttglyph->x[i + n] < ttglyph->header.xMin)
ttglyph->header.xMin = ttglyph->x[i + n];
if (ttglyph->x[i + n] > ttglyph->header.xMax)
ttglyph->header.xMax = ttglyph->x[i + n];
if (ttglyph->y[i + n] < ttglyph->header.yMin)
ttglyph->header.yMin = ttglyph->y[i + n];
if (ttglyph->y[i + n] > ttglyph->header.yMax)
ttglyph->header.yMax = ttglyph->y[i + n];
}
/* Free up the sub glyph outline information */
delete sub_ttglyph;
} while (flags & MORE_COMPONENTS);
}
#ifdef TTF_DEBUG
Debug_Info("xMin=%d\n",ttglyph->header.xMin);
Debug_Info("yMin=%d\n",ttglyph->header.yMin);
Debug_Info("xMax=%d\n",ttglyph->header.xMax);
Debug_Info("yMax=%d\n",ttglyph->header.yMax);
#endif
return ttglyph;
}
/*****************************************************************************
*
* FUNCTION
*
* ConvertOutlineToGlyph
*
* INPUT
*
* OUTPUT
*
* RETURNS
*
* AUTHOR
*
* POV-Ray Team
*
* DESCRIPTION
*
* Transform a glyph from TrueType storage format to something a little easier
* to manage.
*
* CHANGES
*
* -
*
******************************************************************************/
GlyphPtr ConvertOutlineToGlyph(TrueTypeFont *ffile, const GlyphOutline *ttglyph)
{
GlyphPtr glyph;
DBL *temp_x, *temp_y;
BYTE *temp_f;
USHORT i, j, last_j;
/* Create storage for this glyph */
glyph = new GlyphStruct;
if (ttglyph->header.numContours > 0)
{
glyph->contours = new Contour[ttglyph->header.numContours];
}
else
{
glyph->contours = NULL;
}
/* Copy sizing information about this glyph */
POV_MEMCPY(&glyph->header, &ttglyph->header, sizeof(GlyphHeader));
/* Keep track of the size for this glyph */
glyph->unitsPerEm = ffile->info->unitsPerEm;
/* Now copy the vertex information into the contours */
for (i = 0, last_j = 0; i < (USHORT) ttglyph->header.numContours; i++)
{
/* Figure out number of points in contour */
j = ttglyph->endPoints[i] - last_j + 1;
/* Copy the coordinate information into the glyph */
temp_x = reinterpret_cast<DBL *>(POV_MALLOC((j + 1) * sizeof(DBL), "ttf"));
temp_y = reinterpret_cast<DBL *>(POV_MALLOC((j + 1) * sizeof(DBL), "ttf"));
temp_f = reinterpret_cast<BYTE *>(POV_MALLOC((j + 1) * sizeof(BYTE), "ttf"));
POV_MEMCPY(temp_x, &ttglyph->x[last_j], j * sizeof(DBL));
POV_MEMCPY(temp_y, &ttglyph->y[last_j], j * sizeof(DBL));
POV_MEMCPY(temp_f, &ttglyph->flags[last_j], j * sizeof(BYTE));
temp_x[j] = ttglyph->x[last_j];
temp_y[j] = ttglyph->y[last_j];
temp_f[j] = ttglyph->flags[last_j];
/* Figure out if this is an inside or outside contour */
glyph->contours[i].inside_flag = 0;
/* Plug in the reset of the contour components into the glyph */
glyph->contours[i].count = j;
glyph->contours[i].x = temp_x;
glyph->contours[i].y = temp_y;
glyph->contours[i].flags = temp_f;
/*
* Set last_j to point to the beginning of the next contour's coordinate
* information
*/
last_j = ttglyph->endPoints[i] + 1;
}
/* Show statistics about this glyph */
#ifdef TTF_DEBUG
Debug_Info("Number of contours: %u\n", glyph->header.numContours);
Debug_Info("X extent: [%f, %f]\n",
(DBL)glyph->header.xMin / (DBL)ffile->info->unitsPerEm,
(DBL)glyph->header.xMax / (DBL)ffile->info->unitsPerEm);
Debug_Info("Y extent: [%f, %f]\n",
(DBL)glyph->header.yMin / (DBL)ffile->info->unitsPerEm,
(DBL)glyph->header.yMax / (DBL)ffile->info->unitsPerEm);
Debug_Info("Converted coord list(%d):\n", (int)glyph->header.numContours);
for (i=0;i<(USHORT)glyph->header.numContours;i++)
{
for (j=0;j<=glyph->contours[i].count;j++)
Debug_Info(" %c[%f, %f]\n",
(glyph->contours[i].flags[j] & ONCURVE ? '*' : ' '),
glyph->contours[i].x[j], glyph->contours[i].y[j]);
Debug_Info("\n");
}
#endif
return glyph;
}
/* Test to see if "point" is inside the splined polygon "points". */
bool TrueType::Inside_Glyph(double x, double y, const GlyphStruct* glyph) const
{
int i, j, k, n, n1, crossings;
int qi, ri, qj, rj;
Contour *contour;
double xt[3], yt[3], roots[2];
DBL *xv, *yv;
double x0, x1, x2, t;
double y0, y1, y2;
double m, b, xc;
BYTE *fv;
crossings = 0;
n = glyph->header.numContours;
contour = glyph->contours;
for (i = 0; i < n; i++)
{
xv = contour[i].x;
yv = contour[i].y;
fv = contour[i].flags;
x0 = xv[0];
y0 = yv[0];
n1 = contour[i].count;
for (j = 1; j <= n1; j++)
{
x1 = xv[j];
y1 = yv[j];
if (fv[j] & ONCURVE)
{
/* Straight line - first set up for the next */
/* Now do the crossing test */
qi = ri = qj = rj = 0;
if (y0 == y1)
goto end_line_test;
/* if (fabs((y - y0) / (y1 - y0)) < EPSILON) goto end_line_test; */
if (y0 < y)
qi = 1;
if (y1 < y)
qj = 1;
if (qi == qj)
goto end_line_test;
if (x0 > x)
ri = 1;
if (x1 > x)
rj = 1;
if (ri & rj)
{
crossings++;
goto end_line_test;
}
if ((ri | rj) == 0)
goto end_line_test;
m = (y1 - y0) / (x1 - x0);
b = (y1 - y) - m * (x1 - x);
if ((b / m) < EPSILON)
{
crossings++;
}
end_line_test:
x0 = x1;
y0 = y1;
}
else
{
if (j == n1)
{
x2 = xv[0];
y2 = yv[0];
}
else
{
x2 = xv[j + 1];
y2 = yv[j + 1];
if (!(fv[j + 1] & ONCURVE))
{
/*
* Parabola with far end floating - readjust the far end so that it
* is on the curve.
*/
x2 = 0.5 * (x1 + x2);
y2 = 0.5 * (y1 + y2);
}
}
/* only test crossing when y is in the range */
/* this should also help saving some computations */
if (((y0 < y) && (y1 < y) && (y2 < y)) ||
((y0 > y) && (y1 > y) && (y2 > y)))
goto end_curve_test;
yt[0] = y0 - 2.0 * y1 + y2;
yt[1] = 2.0 * (y1 - y0);
yt[2] = y0 - y;
k = solve_quad(yt, roots, 0.0, 1.0);
for (ri = 0; ri < k;) {
if (roots[ri] <= EPSILON) {
/* if y actually is not in range, discard the root */
if (((y <= y0) && (y < y1)) || ((y >= y0) && (y > y1))) {
k--;
if (k > ri)
roots[ri] = roots[ri+1];
continue;
}
}
else if (roots[ri] >= (1.0 - EPSILON)) {
/* if y actually is not in range, discard the root */
if (((y < y2) && (y < y1)) || ((y > y2) && (y > y1))) {
k--;
if (k > ri)
roots[ri] = roots[ri+1];
continue;
}
}
ri++;
}
if (k > 0)
{
xt[0] = x0 - 2.0 * x1 + x2;
xt[1] = 2.0 * (x1 - x0);
xt[2] = x0;
t = roots[0];
xc = (xt[0] * t + xt[1]) * t + xt[2];
if (xc > x)
crossings++;
if (k > 1)
{
t = roots[1];
xc = (xt[0] * t + xt[1]) * t + xt[2];
if (xc > x)
crossings++;
}
}
end_curve_test:
x0 = x2;
y0 = y2;
}
}
}
return ((crossings & 1) != 0);
}
int TrueType::solve_quad(double *x, double *y, double mindist, DBL maxdist) const
{
double d, t, a, b, c, q;
a = x[0];
b = -x[1];
c = x[2];
if (fabs(a) < COEFF_LIMIT)
{
if (fabs(b) < COEFF_LIMIT)
return 0;
q = c / b;
if (q >= mindist && q <= maxdist)
{
y[0] = q;
return 1;
}
else
return 0;
}
d = b * b - 4.0 * a * c;
if (d < EPSILON)
return 0;
d = sqrt(d);
t = 2.0 * a;
q = (b + d) / t;
if (q >= mindist && q <= maxdist)
{
y[0] = q;
q = (b - d) / t;
if (q >= mindist && q <= maxdist)
{
y[1] = q;
return 2;
}
return 1;
}
q = (b - d) / t;
if (q >= mindist && q <= maxdist)
{
y[0] = q;
return 1;
}
return 0;
}
/*
* Returns the distance to z = 0 in t0, and the distance to z = 1 in t1.
* These distances are to the the bottom and top surfaces of the glyph.
* The distances are set to -1 if there is no hit.
*/
void TrueType::GetZeroOneHits(const GlyphStruct* glyph, const Vector3d& P, const Vector3d& D, DBL glyph_depth, double *t0, double *t1) const
{
double x0, y0, t;
*t0 = -1.0;
*t1 = -1.0;
/* Are we parallel to the x-y plane? */
if (fabs(D[Z]) < EPSILON)
return;
/* Solve: P[Y] + t * D[Y] = 0 */
t = -P[Z] / D[Z];
x0 = P[X] + t * D[X];
y0 = P[Y] + t * D[Y];
if (Inside_Glyph(x0, y0, glyph))
*t0 = t;
/* Solve: P[Y] + t * D[Y] = glyph_depth */
t += (glyph_depth / D[Z]);
x0 = P[X] + t * D[X];
y0 = P[Y] + t * D[Y];
if (Inside_Glyph(x0, y0, glyph))
*t1 = t;
}
/*
* Solving for a linear sweep of a non-linear curve can be performed by
* projecting the ray onto the x-y plane, giving a parametric equation for the
* ray as:
*
* x = x0 + x1 t, y = y0 + y1 t
*
* Eliminating t from the above gives the implicit equation:
*
* y1 x - x1 y - (x0 y1 - y0 x1) = 0.
*
* Substituting a parametric equation for x and y gives:
*
* y1 x(s) - x1 y(s) - (x0 y1 - y0 x1) = 0.
*
* which can be written as
*
* a x(s) + b y(s) + c = 0,
*
* where a = y1, b = -x1, c = (y0 x1 - x0 y1).
*
* For piecewise quadratics, the parametric equations will have the forms:
*
* x(s) = (1-s)^2 P0(x) + 2 s (1 - s) P1(x) + s^2 P2(x) y(s) = (1-s)^2 P0(y) + 2 s
* (1 - s) P1(y) + s^2 P2(y)
*
* where P0 is the first defining vertex of the spline, P1 is the second, P2 is
* the third. Using the substitutions:
*
* xt2 = x0 - 2 x1 + x2, xt1 = 2 * (x1 - x0), xt0 = x0; yt2 = y0 - 2 y1 + y2, yt1
* = 2 * (y1 - y0), yt0 = y0;
*
* the equations can be written as:
*
* x(s) = xt2 s^2 + xt1 s + xt0, y(s) = yt2 s^2 + yt1 s + yt0.
*
* Substituting and multiplying out gives the following equation in s:
*
* s^2 * (a*xt2 + b*yt2) + s * (a*xt1 + b*yt1) + c + a*xt0 + b*yt0
*
* This is then solved using the quadratic formula. Any solutions of s that are
* between 0 and 1 (inclusive) are valid solutions.
*/
bool TrueType::GlyphIntersect(const Vector3d& P, const Vector3d& D, const GlyphStruct* glyph, DBL glyph_depth, const BasicRay& ray, IStack& Depth_Stack, TraceThreadData *Thread)
{
Contour *contour;
int i, j, k, l, n, m;
bool Flag = false;
Vector3d N, IPoint;
DBL Depth;
double x0, x1, y0, y1, x2, y2, t, t0, t1, z;
double xt0, xt1, xt2, yt0, yt1, yt2;
double a, b, c, d0, d1, C[3], S[2];
DBL *xv, *yv;
BYTE *fv;
int dirflag = 0;
/*
* First thing to do is to get any hits at z = 0 and z = 1 (which are the
* bottom and top surfaces of the glyph.
*/
GetZeroOneHits(glyph, P, D, glyph_depth, &t0, &t1);
if (t0 > 0.0)
{
Depth = t0 /* / len */;
IPoint = ray.Evaluate(Depth);
if (Depth > TTF_Tolerance && (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread)))
{
N = Vector3d(0.0, 0.0, -1.0);
MTransNormal(N, N, Trans);
N.normalize();
Depth_Stack->push(Intersection(Depth, IPoint, N, this));
Flag = true;
}
}
if (t1 > 0.0)
{
Depth = t1 /* / len */;
IPoint = ray.Evaluate(Depth);
if (Depth > TTF_Tolerance && (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread)))
{
N = Vector3d(0.0, 0.0, 1.0);
MTransNormal(N, N, Trans);
N.normalize();
Depth_Stack->push(Intersection(Depth, IPoint, N, this));
Flag = true;
}
}
/* Simple test to see if we can just toss this ray */
if (fabs(D[X]) < EPSILON)
{
if (fabs(D[Y]) < EPSILON)
{
/*
* This means the ray is moving parallel to the walls of the sweep
* surface
*/
return Flag;
}
else
{
dirflag = 0;
}
}
else
{
dirflag = 1;
}
/*
* Now walk through the glyph, looking for places where the ray hits the
* walls
*/
a = D[Y];
b = -D[X];
c = (P[Y] * D[X] - P[X] * D[Y]);
n = glyph->header.numContours;
for (i = 0, contour = glyph->contours; i < n; i++, contour++)
{
xv = contour->x;
yv = contour->y;
fv = contour->flags;
x0 = xv[0];
y0 = yv[0];
m = contour->count;
for (j = 1; j <= m; j++)
{
x1 = xv[j];
y1 = yv[j];
if (fv[j] & ONCURVE)
{
/* Straight line */
d0 = (x1 - x0);
d1 = (y1 - y0);
t0 = d1 * D[X] - d0 * D[Y];
if (fabs(t0) < EPSILON)
/* No possible intersection */
goto end_line_test;
t = (D[X] * (P[Y] - y0) - D[Y] * (P[X] - x0)) / t0;
if (t < 0.0 || t > 1.0)
goto end_line_test;
if (dirflag)
t = ((x0 + t * d0) - P[X]) / D[X];
else
t = ((y0 + t * d1) - P[Y]) / D[Y];
z = P[Z] + t * D[Z];
Depth = t /* / len */;
if (z >= 0 && z <= glyph_depth && Depth > TTF_Tolerance)
{
IPoint = ray.Evaluate(Depth);
if (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread))
{
N = Vector3d(d1, -d0, 0.0);
MTransNormal(N, N, Trans);
N.normalize();
Depth_Stack->push(Intersection(Depth, IPoint, N, this));
Flag = true;
}
}
end_line_test:
x0 = x1;
y0 = y1;
}
else
{
if (j == m)
{
x2 = xv[0];
y2 = yv[0];
}
else
{
x2 = xv[j + 1];
y2 = yv[j + 1];
if (!(fv[j + 1] & ONCURVE))
{
/*
* Parabola with far end DBLing - readjust the far end so that it
* is on the curve. (In the correct place too.)
*/
x2 = 0.5 * (x1 + x2);
y2 = 0.5 * (y1 + y2);
}
}
/* Make the interpolating quadrics */
xt2 = x0 - 2.0 * x1 + x2;
xt1 = 2.0 * (x1 - x0);
xt0 = x0;
yt2 = y0 - 2.0 * y1 + y2;
yt1 = 2.0 * (y1 - y0);
yt0 = y0;
C[0] = a * xt2 + b * yt2;
C[1] = a * xt1 + b * yt1;
C[2] = a * xt0 + b * yt0 + c;
k = solve_quad(C, S, 0.0, 1.0);
for (l = 0; l < k; l++)
{
if (dirflag)
t = ((S[l] * S[l] * xt2 + S[l] * xt1 + xt0) - P[X]) / D[X];
else
t = ((S[l] * S[l] * yt2 + S[l] * yt1 + yt0) - P[Y]) / D[Y];
/*
* If the intersection with this wall is between 0 and glyph_depth
* along the z-axis, then it is a valid hit.
*/
z = P[Z] + t * D[Z];
Depth = t /* / len */;
if (z >= 0 && z <= glyph_depth && Depth > TTF_Tolerance)
{
IPoint = ray.Evaluate(Depth);
if (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread))
{
N = Vector3d(2.0 * yt2 * S[l] + yt1, -2.0 * xt2 * S[l] - xt1, 0.0);
MTransNormal(N, N, Trans);
N.normalize();
Depth_Stack->push(Intersection(Depth, IPoint, N, this));
Flag = true;
}
}
}
x0 = x2;
y0 = y2;
}
}
}
return Flag;
}
bool TrueType::All_Intersections(const Ray& ray, IStack& Depth_Stack, TraceThreadData *Thread)
{
Vector3d P, D;
Thread->Stats()[Ray_TTF_Tests]++;
/* Transform the point into the glyph's space */
MInvTransPoint(P, ray.Origin, Trans);
MInvTransDirection(D, ray.Direction, Trans);
/* Tweak the ray to try to avoid pathalogical intersections */
/* DBL len;
D[0] *= 1.0000013147;
D[1] *= 1.0000022741;
D[2] *= 1.0000017011;
D.normalize();
*/
if (GlyphIntersect(P, D, glyph, depth, ray, Depth_Stack, Thread)) /* tw */
{
Thread->Stats()[Ray_TTF_Tests_Succeeded]++;
return true;
}
return false;
}
bool TrueType::Inside(const Vector3d& IPoint, TraceThreadData *Thread) const
{
Vector3d New_Point;
/* Transform the point into font space */
MInvTransPoint(New_Point, IPoint, Trans);
if (New_Point[Z] >= 0.0 && New_Point[Z] <= depth &&
Inside_Glyph(New_Point[X], New_Point[Y], glyph))
return (!Test_Flag(this, INVERTED_FLAG));
else
return (Test_Flag(this, INVERTED_FLAG));
}
void TrueType::Normal(Vector3d& Result, Intersection *Inter, TraceThreadData *Thread) const
{
/* Use precomputed normal. [ARE 11/94] */
Result = Inter->INormal;
}
ObjectPtr TrueType::Copy()
{
TrueType *New = new TrueType();
Destroy_Transform(New->Trans);
*New = *this;
New->Trans = Copy_Transform(Trans);
New->glyph = glyph; // TODO - How can this work correctly? [trf]
return (New);
}
void TrueType::Translate(const Vector3d& /*Vector*/, const TRANSFORM *tr)
{
Transform(tr);
}
void TrueType::Rotate(const Vector3d& /*Vector*/, const TRANSFORM *tr)
{
Transform(tr);
}
void TrueType::Scale(const Vector3d& /*Vector*/, const TRANSFORM *tr)
{
Transform(tr);
}
void TrueType::Transform(const TRANSFORM *tr)
{
Compose_Transforms(Trans, tr);
/* Calculate the bounds */
Compute_BBox();
}
TrueType::TrueType() : ObjectBase(TTF_OBJECT)
{
/* Initialize TTF specific information */
Trans = Create_Transform();
glyph = NULL;
depth = 1.0;
/* Default bounds */
Make_BBox(BBox, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0);
}
TrueType::~TrueType()
{
Destroy_Transform(Trans);
}
/*****************************************************************************
*
* FUNCTION
*
* Compute_TTF_BBox
*
* INPUT
*
* ttf - ttf
*
* OUTPUT
*
* ttf
*
* RETURNS
*
* AUTHOR
*
* Dieter Bayer, August 1994
*
* DESCRIPTION
*
* Calculate the bounding box of a true type font.
*
* CHANGES
*
* -
*
******************************************************************************/
void TrueType::Compute_BBox()
{
DBL funit_size, xMin, yMin, zMin, xMax, yMax, zMax;
funit_size = 1.0 / (DBL)(glyph->unitsPerEm);
xMin = (DBL)glyph->header.xMin * funit_size;
yMin = (DBL)glyph->header.yMin * funit_size;
zMin = -TTF_Tolerance;
xMax = (DBL)glyph->header.xMax * funit_size;
yMax = (DBL)glyph->header.yMax * funit_size;
zMax = depth + TTF_Tolerance;
Make_BBox(BBox, xMin, yMin, zMin, xMax - xMin, yMax - yMin, zMax - zMin);
#ifdef TTF_DEBUG
Debug_Info("Bounds: <%g,%g,%g> -> <%g,%g,%g>\n",
ttf->BBox.lowerLeft[0],
ttf->BBox.lowerLeft[1],
ttf->BBox.lowerLeft[2],
ttf->BBox.size[0],
ttf->BBox.size[1],
ttf->BBox.size[2]);
#endif
/* Apply the transformation to the bounding box */
Recompute_BBox(&BBox, Trans);
}
TrueTypeFont::TrueTypeFont(UCS2* fn, IStream* fp, StringEncoding te) :
filename(fn),
fp(fp),
textEncoding(te),
info(NULL)
{
ProcessFontFile(this);
}
TrueTypeFont::~TrueTypeFont()
{
if (fp != NULL)
delete fp;
if (filename != NULL)
POV_FREE(filename);
if (info != NULL)
delete info;
}
TrueTypeInfo::TrueTypeInfo() :
cmap_table_offset(0),
glyf_table_offset(0),
numGlyphs(0),
unitsPerEm(0),
indexToLocFormat(0),
loca_table(NULL),
numberOfHMetrics(0),
hmtx_table(NULL),
glyphIDoffset(0),
segCount(0),
searchRange(0),
entrySelector(0),
rangeShift(0),
startCount(NULL),
endCount(NULL),
idDelta(NULL),
idRangeOffset(NULL)
{
for (int i = 0; i < 4; i ++)
{
platformID[i] = 0;
specificID[i] = 0;
}
kerning_tables.nTables = 0;
kerning_tables.tables = NULL;
}
TrueTypeInfo::~TrueTypeInfo()
{
if (loca_table != NULL)
delete[] loca_table;
for (GlyphPtrMap::iterator iGlyph = glyphsByIndex.begin(); iGlyph != glyphsByIndex.end(); ++iGlyph)
{
if ((*iGlyph).second->contours != NULL)
{
for (int i = 0; i < (*iGlyph).second->header.numContours; i++)
{
POV_FREE((*iGlyph).second->contours[i].flags);
POV_FREE((*iGlyph).second->contours[i].x);
POV_FREE((*iGlyph).second->contours[i].y);
}
delete[] (*iGlyph).second->contours;
}
delete (*iGlyph).second;
}
if (kerning_tables.tables != NULL)
{
for (int i = 0; i < kerning_tables.nTables; i++)
{
if (kerning_tables.tables[i].kern_pairs)
delete[] kerning_tables.tables[i].kern_pairs;
}
delete[] kerning_tables.tables;
}
if (hmtx_table != NULL)
delete[] hmtx_table;
if (endCount != NULL)
delete[] endCount;
if (startCount != NULL)
delete[] startCount;
if (idDelta != NULL)
delete[] idDelta;
if (idRangeOffset != NULL)
delete[] idRangeOffset;
}
}
| FLOWERCLOUD/povray | source/core/shape/truetype.cpp | C++ | agpl-3.0 | 95,703 |
# Based on https://bitbucket.org/jokull/django-email-login/
import re
from uuid import uuid4
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib.sites.models import RequestSite, Site
from registration import signals
from registration.models import RegistrationProfile
from invitation.backends import InvitationBackend
from forms import RegistrationForm
class RegistrationBackend(InvitationBackend):
"""
Does not require the user to pick a username. Sets the username to a random
string behind the scenes.
"""
def register(self, request, **kwargs):
email, password = kwargs['email'], kwargs['password1']
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
new_user = RegistrationProfile.objects.create_inactive_user(
uuid4().get_hex()[:10], email, password, site)
signals.user_registered.send(
sender=self.__class__, user=new_user, request=request)
return new_user
def get_form_class(self, request):
"""
Return the default form class used for user registration.
"""
return RegistrationForm
email_re = re.compile(
# dot-atom
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"
# quoted-string
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|'
r'\\[\001-\011\013\014\016-\177])*"'
# domain
r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE)
class AuthBackend(ModelBackend):
"""Authenticate using email only"""
def authenticate(self, username=None, password=None, email=None):
if email is None:
email = username
if email_re.search(email):
user = User.objects.filter(email__iexact=email)
if user.count() > 0:
user = user[0]
if user.check_password(password):
return user
return None
| datagutten/comics | comics/accounts/backends.py | Python | agpl-3.0 | 2,013 |
package cs.lang.scobol.dfa;
import cs.lang.scobol.Language;
import cs.lang.DFAState;
import cs.lang.scobol.Alphabet;
import cs.lang.DFATools;
public class END extends DFAState<Language.DFAState, Language.LexicalUnit, Character>{
public END(){
super(Language.LexicalUnit.END_KEYWORD);
transition.put('-', Language.DFAState.END_);
DFATools.fill(transition, Alphabet.IDENTIFIER, Language.DFAState.IDENTIFIER_3);
}
}
| aureooms-ulb-2010-2015/2013-2014-infof403-project | 1/more/src/cs/lang/scobol/dfa/END.java | Java | agpl-3.0 | 424 |
import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events, { ApplyBuffEvent } from 'parser/core/Events';
import { ThresholdStyle } from 'parser/core/ParseResults';
import Combatants from 'parser/shared/modules/Combatants';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import * as SPELLS from '../../SPELLS';
class WaterShield extends Analyzer {
static dependencies = {
combatants: Combatants,
};
protected combatants!: Combatants;
healing = 0;
buffHealing = 0;
category = STATISTIC_CATEGORY.TALENTS;
prepullApplication = false;
constructor(options: Options) {
super(options);
this.active = true;
console.log('Spec: ' + this.selectedCombatant.specId);
this.category = STATISTIC_CATEGORY.GENERAL;
this.addEventListener(
Events.applybuff.by(SELECTED_PLAYER).spell({ id: SPELLS.WATER_SHIELD }),
this.waterShieldPrepullCheck,
);
}
waterShieldPrepullCheck(event: ApplyBuffEvent) {
if (event.prepull) {
this.prepullApplication = true;
}
}
get uptime() {
return Object.values(this.combatants.players).reduce(
(uptime, player) => uptime + player.getBuffUptime(SPELLS.WATER_SHIELD, this.owner.playerId),
0,
);
}
get uptimePercent() {
return this.uptime / this.owner.fightDuration;
}
get suggestionThresholds() {
return {
actual: this.uptimePercent,
isLessThan: {
minor: 0.95,
average: 0.9,
major: 0.8,
},
style: ThresholdStyle.PERCENTAGE,
};
}
get suggestionThresholdsPrepull() {
return {
actual: this.prepullApplication,
isEqual: false,
style: ThresholdStyle.BOOLEAN,
};
}
}
export default WaterShield;
| Juko8/WoWAnalyzer | analysis/tbcshaman/src/modules/spells/WaterShield.tsx | TypeScript | agpl-3.0 | 1,755 |
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Björn Schießle <bjoern@schiessle.org>
* @author Joas Schilling <coding@schilljs.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Share20;
use OC\Files\Cache\Cache;
use OC\Files\Cache\CacheEntry;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Share\IShareProvider;
use OC\Share20\Exception\InvalidShare;
use OC\Share20\Exception\ProviderException;
use OCP\Share\Exceptions\ShareNotFound;
use OC\Share20\Exception\BackendError;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IUserManager;
use OCP\Files\IRootFolder;
use OCP\IDBConnection;
use OCP\Files\Node;
/**
* Class DefaultShareProvider
*
* @package OC\Share20
*/
class DefaultShareProvider implements IShareProvider {
// Special share type for user modified group shares
const SHARE_TYPE_USERGROUP = 2;
/** @var IDBConnection */
private $dbConn;
/** @var IUserManager */
private $userManager;
/** @var IGroupManager */
private $groupManager;
/** @var IRootFolder */
private $rootFolder;
/**
* DefaultShareProvider constructor.
*
* @param IDBConnection $connection
* @param IUserManager $userManager
* @param IGroupManager $groupManager
* @param IRootFolder $rootFolder
*/
public function __construct(
IDBConnection $connection,
IUserManager $userManager,
IGroupManager $groupManager,
IRootFolder $rootFolder) {
$this->dbConn = $connection;
$this->userManager = $userManager;
$this->groupManager = $groupManager;
$this->rootFolder = $rootFolder;
}
/**
* Return the identifier of this provider.
*
* @return string Containing only [a-zA-Z0-9]
*/
public function identifier() {
return 'ocinternal';
}
/**
* Share a path
*
* @param \OCP\Share\IShare $share
* @return \OCP\Share\IShare The share object
* @throws ShareNotFound
* @throws \Exception
*/
public function create(\OCP\Share\IShare $share) {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share');
$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
//Set the UID of the user we share with
$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
//Set the GID of the group we share with
$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
//Set the token of the share
$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
//If a password is set store it
if ($share->getPassword() !== null) {
$qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
}
//If an expiration date is set store it
if ($share->getExpirationDate() !== null) {
$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
}
if (method_exists($share, 'getParent')) {
$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
}
} else {
throw new \Exception('invalid share type!');
}
// Set what is shares
$qb->setValue('item_type', $qb->createParameter('itemType'));
if ($share->getNode() instanceof \OCP\Files\File) {
$qb->setParameter('itemType', 'file');
} else {
$qb->setParameter('itemType', 'folder');
}
// Set the file id
$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
// set the permissions
$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
// Set who created this share
$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
// Set who is the owner of this file/folder (and this the owner of the share)
$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
// Set the file target
$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
// Set the time this share was created
$qb->setValue('stime', $qb->createNamedParameter(time()));
// insert the data and fetch the id of the share
$this->dbConn->beginTransaction();
$qb->execute();
$id = $this->dbConn->lastInsertId('*PREFIX*share');
$this->dbConn->commit();
// Now fetch the inserted share and create a complete share object
$qb = $this->dbConn->getQueryBuilder();
$qb->select('*')
->from('share')
->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
$cursor = $qb->execute();
$data = $cursor->fetch();
$cursor->closeCursor();
if ($data === false) {
throw new ShareNotFound();
}
$share = $this->createShare($data);
return $share;
}
/**
* Update a share
*
* @param \OCP\Share\IShare $share
* @return \OCP\Share\IShare The share object
*/
public function update(\OCP\Share\IShare $share) {
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
/*
* We allow updating the recipient on user shares.
*/
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
->set('permissions', $qb->createNamedParameter($share->getPermissions()))
->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
->execute();
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
->set('permissions', $qb->createNamedParameter($share->getPermissions()))
->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
->execute();
/*
* Update all user defined group shares
*/
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
->execute();
/*
* Now update the permissions for all children that have not set it to 0
*/
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
->set('permissions', $qb->createNamedParameter($share->getPermissions()))
->execute();
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
->set('share_with', $qb->createNamedParameter($share->getPassword()))
->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
->set('permissions', $qb->createNamedParameter($share->getPermissions()))
->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
->set('token', $qb->createNamedParameter($share->getToken()))
->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
->execute();
}
return $share;
}
/**
* Get all children of this share
* FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
*
* @param \OCP\Share\IShare $parent
* @return \OCP\Share\IShare[]
*/
public function getChildren(\OCP\Share\IShare $parent) {
$children = [];
$qb = $this->dbConn->getQueryBuilder();
$qb->select('*')
->from('share')
->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
->andWhere(
$qb->expr()->in(
'share_type',
$qb->createNamedParameter([
\OCP\Share::SHARE_TYPE_USER,
\OCP\Share::SHARE_TYPE_GROUP,
\OCP\Share::SHARE_TYPE_LINK,
], IQueryBuilder::PARAM_INT_ARRAY)
)
)
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
))
->orderBy('id');
$cursor = $qb->execute();
while($data = $cursor->fetch()) {
$children[] = $this->createShare($data);
}
$cursor->closeCursor();
return $children;
}
/**
* Delete a share
*
* @param \OCP\Share\IShare $share
*/
public function delete(\OCP\Share\IShare $share) {
$qb = $this->dbConn->getQueryBuilder();
$qb->delete('share')
->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
/*
* If the share is a group share delete all possible
* user defined groups shares.
*/
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
}
$qb->execute();
}
/**
* Unshare a share from the recipient. If this is a group share
* this means we need a special entry in the share db.
*
* @param \OCP\Share\IShare $share
* @param string $recipient UserId of recipient
* @throws BackendError
* @throws ProviderException
*/
public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
$group = $this->groupManager->get($share->getSharedWith());
$user = $this->userManager->get($recipient);
if (!$group->inGroup($user)) {
throw new ProviderException('Recipient not in receiving group');
}
// Try to fetch user specific share
$qb = $this->dbConn->getQueryBuilder();
$stmt = $qb->select('*')
->from('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
))
->execute();
$data = $stmt->fetch();
/*
* Check if there already is a user specific group share.
* If there is update it (if required).
*/
if ($data === false) {
$qb = $this->dbConn->getQueryBuilder();
$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
//Insert new share
$qb->insert('share')
->values([
'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
'share_with' => $qb->createNamedParameter($recipient),
'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
'parent' => $qb->createNamedParameter($share->getId()),
'item_type' => $qb->createNamedParameter($type),
'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
'file_target' => $qb->createNamedParameter($share->getTarget()),
'permissions' => $qb->createNamedParameter(0),
'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
])->execute();
} else if ($data['permissions'] !== 0) {
// Update existing usergroup share
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->set('permissions', $qb->createNamedParameter(0))
->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
->execute();
}
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
if ($share->getSharedWith() !== $recipient) {
throw new ProviderException('Recipient does not match');
}
// We can just delete user and link shares
$this->delete($share);
} else {
throw new ProviderException('Invalid shareType');
}
}
/**
* @inheritdoc
*/
public function move(\OCP\Share\IShare $share, $recipient) {
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
// Just update the target
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->set('file_target', $qb->createNamedParameter($share->getTarget()))
->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
->execute();
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
// Check if there is a usergroup share
$qb = $this->dbConn->getQueryBuilder();
$stmt = $qb->select('id')
->from('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
))
->setMaxResults(1)
->execute();
$data = $stmt->fetch();
$stmt->closeCursor();
if ($data === false) {
// No usergroup share yet. Create one.
$qb = $this->dbConn->getQueryBuilder();
$qb->insert('share')
->values([
'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
'share_with' => $qb->createNamedParameter($recipient),
'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
'parent' => $qb->createNamedParameter($share->getId()),
'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
'file_target' => $qb->createNamedParameter($share->getTarget()),
'permissions' => $qb->createNamedParameter($share->getPermissions()),
'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
])->execute();
} else {
// Already a usergroup share. Update it.
$qb = $this->dbConn->getQueryBuilder();
$qb->update('share')
->set('file_target', $qb->createNamedParameter($share->getTarget()))
->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
->execute();
}
}
return $share;
}
public function getSharesInFolder($userId, Folder $node, $reshares) {
$qb = $this->dbConn->getQueryBuilder();
$qb->select('*')
->from('share', 's')
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
));
$qb->andWhere($qb->expr()->orX(
$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
));
/**
* Reshares for this user are shares where they are the owner.
*/
if ($reshares === false) {
$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
} else {
$qb->andWhere(
$qb->expr()->orX(
$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
)
);
}
$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
$qb->orderBy('id');
$cursor = $qb->execute();
$shares = [];
while ($data = $cursor->fetch()) {
$shares[$data['fileid']][] = $this->createShare($data);
}
$cursor->closeCursor();
return $shares;
}
/**
* @inheritdoc
*/
public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
$qb = $this->dbConn->getQueryBuilder();
$qb->select('*')
->from('share')
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
));
$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
/**
* Reshares for this user are shares where they are the owner.
*/
if ($reshares === false) {
$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
} else {
$qb->andWhere(
$qb->expr()->orX(
$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
)
);
}
if ($node !== null) {
$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
}
if ($limit !== -1) {
$qb->setMaxResults($limit);
}
$qb->setFirstResult($offset);
$qb->orderBy('id');
$cursor = $qb->execute();
$shares = [];
while($data = $cursor->fetch()) {
$shares[] = $this->createShare($data);
}
$cursor->closeCursor();
return $shares;
}
/**
* @inheritdoc
*/
public function getShareById($id, $recipientId = null) {
$qb = $this->dbConn->getQueryBuilder();
$qb->select('*')
->from('share')
->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
->andWhere(
$qb->expr()->in(
'share_type',
$qb->createNamedParameter([
\OCP\Share::SHARE_TYPE_USER,
\OCP\Share::SHARE_TYPE_GROUP,
\OCP\Share::SHARE_TYPE_LINK,
], IQueryBuilder::PARAM_INT_ARRAY)
)
)
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
));
$cursor = $qb->execute();
$data = $cursor->fetch();
$cursor->closeCursor();
if ($data === false) {
throw new ShareNotFound();
}
try {
$share = $this->createShare($data);
} catch (InvalidShare $e) {
throw new ShareNotFound();
}
// If the recipient is set for a group share resolve to that user
if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
$share = $this->resolveGroupShares([$share], $recipientId)[0];
}
return $share;
}
/**
* Get shares for a given path
*
* @param \OCP\Files\Node $path
* @return \OCP\Share\IShare[]
*/
public function getSharesByPath(Node $path) {
$qb = $this->dbConn->getQueryBuilder();
$cursor = $qb->select('*')
->from('share')
->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
->andWhere(
$qb->expr()->orX(
$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
)
)
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
))
->execute();
$shares = [];
while($data = $cursor->fetch()) {
$shares[] = $this->createShare($data);
}
$cursor->closeCursor();
return $shares;
}
/**
* Returns whether the given database result can be interpreted as
* a share with accessible file (not trashed, not deleted)
*/
private function isAccessibleResult($data) {
// exclude shares leading to deleted file entries
if ($data['fileid'] === null) {
return false;
}
// exclude shares leading to trashbin on home storages
$pathSections = explode('/', $data['path'], 2);
// FIXME: would not detect rare md5'd home storage case properly
if ($pathSections[0] !== 'files' && explode(':', $data['storage_string_id'], 2)[0] === 'home') {
return false;
}
return true;
}
/**
* @inheritdoc
*/
public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
/** @var Share[] $shares */
$shares = [];
if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
//Get shares directly with this user
$qb = $this->dbConn->getQueryBuilder();
$qb->select('s.*',
'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
)
->selectAlias('st.id', 'storage_string_id')
->from('share', 's')
->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
// Order by id
$qb->orderBy('s.id');
// Set limit and offset
if ($limit !== -1) {
$qb->setMaxResults($limit);
}
$qb->setFirstResult($offset);
$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
));
// Filter by node if provided
if ($node !== null) {
$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
}
$cursor = $qb->execute();
while($data = $cursor->fetch()) {
if ($this->isAccessibleResult($data)) {
$shares[] = $this->createShare($data);
}
}
$cursor->closeCursor();
} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
$user = $this->userManager->get($userId);
$allGroups = $this->groupManager->getUserGroups($user);
/** @var Share[] $shares2 */
$shares2 = [];
$start = 0;
while(true) {
$groups = array_slice($allGroups, $start, 100);
$start += 100;
if ($groups === []) {
break;
}
$qb = $this->dbConn->getQueryBuilder();
$qb->select('s.*',
'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
)
->selectAlias('st.id', 'storage_string_id')
->from('share', 's')
->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
->orderBy('s.id')
->setFirstResult(0);
if ($limit !== -1) {
$qb->setMaxResults($limit - count($shares));
}
// Filter by node if provided
if ($node !== null) {
$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
}
$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
$groups,
IQueryBuilder::PARAM_STR_ARRAY
)))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
));
$cursor = $qb->execute();
while($data = $cursor->fetch()) {
if ($offset > 0) {
$offset--;
continue;
}
if ($this->isAccessibleResult($data)) {
$shares2[] = $this->createShare($data);
}
}
$cursor->closeCursor();
}
/*
* Resolve all group shares to user specific shares
*/
$shares = $this->resolveGroupShares($shares2, $userId);
} else {
throw new BackendError('Invalid backend');
}
return $shares;
}
/**
* Get a share by token
*
* @param string $token
* @return \OCP\Share\IShare
* @throws ShareNotFound
*/
public function getShareByToken($token) {
$qb = $this->dbConn->getQueryBuilder();
$cursor = $qb->select('*')
->from('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
))
->execute();
$data = $cursor->fetch();
if ($data === false) {
throw new ShareNotFound();
}
try {
$share = $this->createShare($data);
} catch (InvalidShare $e) {
throw new ShareNotFound();
}
return $share;
}
/**
* Create a share object from an database row
*
* @param mixed[] $data
* @return \OCP\Share\IShare
* @throws InvalidShare
*/
private function createShare($data) {
$share = new Share($this->rootFolder, $this->userManager);
$share->setId((int)$data['id'])
->setShareType((int)$data['share_type'])
->setPermissions((int)$data['permissions'])
->setTarget($data['file_target'])
->setMailSend((bool)$data['mail_send']);
$shareTime = new \DateTime();
$shareTime->setTimestamp((int)$data['stime']);
$share->setShareTime($shareTime);
if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
$share->setSharedWith($data['share_with']);
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
$share->setSharedWith($data['share_with']);
} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
$share->setPassword($data['share_with']);
$share->setToken($data['token']);
}
$share->setSharedBy($data['uid_initiator']);
$share->setShareOwner($data['uid_owner']);
$share->setNodeId((int)$data['file_source']);
$share->setNodeType($data['item_type']);
if ($data['expiration'] !== null) {
$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
$share->setExpirationDate($expiration);
}
if (isset($data['f_permissions'])) {
$entryData = $data;
$entryData['permissions'] = $entryData['f_permissions'];
$entryData['parent'] = $entryData['f_parent'];;
$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
\OC::$server->getMimeTypeLoader()));
}
$share->setProviderId($this->identifier());
return $share;
}
/**
* @param Share[] $shares
* @param $userId
* @return Share[] The updates shares if no update is found for a share return the original
*/
private function resolveGroupShares($shares, $userId) {
$result = [];
$start = 0;
while(true) {
/** @var Share[] $shareSlice */
$shareSlice = array_slice($shares, $start, 100);
$start += 100;
if ($shareSlice === []) {
break;
}
/** @var int[] $ids */
$ids = [];
/** @var Share[] $shareMap */
$shareMap = [];
foreach ($shareSlice as $share) {
$ids[] = (int)$share->getId();
$shareMap[$share->getId()] = $share;
}
$qb = $this->dbConn->getQueryBuilder();
$query = $qb->select('*')
->from('share')
->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
->andWhere($qb->expr()->orX(
$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
));
$stmt = $query->execute();
while($data = $stmt->fetch()) {
$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
$shareMap[$data['parent']]->setTarget($data['file_target']);
}
$stmt->closeCursor();
foreach ($shareMap as $share) {
$result[] = $share;
}
}
return $result;
}
/**
* A user is deleted from the system
* So clean up the relevant shares.
*
* @param string $uid
* @param int $shareType
*/
public function userDeleted($uid, $shareType) {
$qb = $this->dbConn->getQueryBuilder();
$qb->delete('share');
if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
/*
* Delete all user shares that are owned by this user
* or that are received by this user
*/
$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
$qb->andWhere(
$qb->expr()->orX(
$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
)
);
} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
/*
* Delete all group shares that are owned by this user
* Or special user group shares that are received by this user
*/
$qb->where(
$qb->expr()->andX(
$qb->expr()->orX(
$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
),
$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
)
);
$qb->orWhere(
$qb->expr()->andX(
$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
)
);
} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
/*
* Delete all link shares owned by this user.
* And all link shares initiated by this user (until #22327 is in)
*/
$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
$qb->andWhere(
$qb->expr()->orX(
$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
)
);
}
$qb->execute();
}
/**
* Delete all shares received by this group. As well as any custom group
* shares for group members.
*
* @param string $gid
*/
public function groupDeleted($gid) {
/*
* First delete all custom group shares for group members
*/
$qb = $this->dbConn->getQueryBuilder();
$qb->select('id')
->from('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
$cursor = $qb->execute();
$ids = [];
while($row = $cursor->fetch()) {
$ids[] = (int)$row['id'];
}
$cursor->closeCursor();
if (!empty($ids)) {
$chunks = array_chunk($ids, 100);
foreach ($chunks as $chunk) {
$qb->delete('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
$qb->execute();
}
}
/*
* Now delete all the group shares
*/
$qb = $this->dbConn->getQueryBuilder();
$qb->delete('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
$qb->execute();
}
/**
* Delete custom group shares to this group for this user
*
* @param string $uid
* @param string $gid
*/
public function userDeletedFromGroup($uid, $gid) {
/*
* Get all group shares
*/
$qb = $this->dbConn->getQueryBuilder();
$qb->select('id')
->from('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
$cursor = $qb->execute();
$ids = [];
while($row = $cursor->fetch()) {
$ids[] = (int)$row['id'];
}
$cursor->closeCursor();
if (!empty($ids)) {
$chunks = array_chunk($ids, 100);
foreach ($chunks as $chunk) {
/*
* Delete all special shares wit this users for the found group shares
*/
$qb->delete('share')
->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
$qb->execute();
}
}
}
}
| endsguy/server | lib/private/Share20/DefaultShareProvider.php | PHP | agpl-3.0 | 33,698 |
'use strict';
angular.module('malariaplantdbApp')
.config(function ($stateProvider) {
$stateProvider
.state('admin', {
abstract: true,
parent: 'site'
});
});
| acheype/malaria-plant-db | src/main/webapp/scripts/app/admin/admin.js | JavaScript | agpl-3.0 | 231 |
/**
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.silverpeas.comment.model;
import java.util.Date;
import com.silverpeas.SilverpeasContent;
import com.silverpeas.accesscontrol.AccessController;
import com.silverpeas.accesscontrol.AccessControllerProvider;
import com.stratelia.webactiv.beans.admin.UserDetail;
import com.stratelia.webactiv.util.WAPrimaryKey;
/**
* This object contains the description of document
* @author Georgy Shakirin
* @version 1.0
*/
public class Comment implements SilverpeasContent {
private static final long serialVersionUID = 3738544756345055840L;
public static final String TYPE = "Comment";
private CommentPK pk;
private String resourceType;
private WAPrimaryKey foreign_key;
private int owner_id;
private String message;
private Date creation_date;
private Date modification_date;
private UserDetail ownerDetail;
private void init(CommentPK pk, String resourceType, WAPrimaryKey foreign_key, int owner_id,
String message, Date creation_date, Date modification_date) {
this.pk = pk;
this.resourceType = resourceType;
this.foreign_key = foreign_key;
this.owner_id = owner_id;
this.message = message;
this.creation_date = new Date(creation_date.getTime());
if (modification_date != null) {
this.modification_date = new Date(modification_date.getTime());
}
}
public Comment(CommentPK pk, String resourceType, WAPrimaryKey foreign_key, int owner_id,
String owner, String message, Date creation_date,
Date modification_date) {
init(pk, resourceType, foreign_key, owner_id, message, creation_date,
modification_date);
}
public Comment(CommentPK pk, String resourceType, WAPrimaryKey contentPk, String authorId,
String message, Date creationDate, Date modificationDate) {
init(pk, resourceType, contentPk, Integer.valueOf(authorId), message, creationDate,
modificationDate);
}
public void setCommentPK(CommentPK pk) {
this.pk = pk;
}
public CommentPK getCommentPK() {
return this.pk;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public String getResourceType() {
return resourceType;
}
public void setForeignKey(WAPrimaryKey foreign_key) {
this.foreign_key = foreign_key;
}
public WAPrimaryKey getForeignKey() {
return this.foreign_key;
}
public int getOwnerId() {
return this.owner_id;
}
public String getOwner() {
if (getOwnerDetail() != null) {
return getOwnerDetail().getDisplayedName();
}
return "";
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
public void setCreationDate(Date creation_date) {
this.creation_date = new Date(creation_date.getTime());
}
@Override
public Date getCreationDate() {
return new Date(this.creation_date.getTime());
}
public void setModificationDate(Date modification_date) {
this.modification_date = new Date(modification_date.getTime());
}
public Date getModificationDate() {
Date date = null;
if (this.modification_date != null) {
date = new Date(this.modification_date.getTime());
}
return date;
}
public UserDetail getOwnerDetail() {
return getCreator();
}
public void setOwnerDetail(UserDetail ownerDetail) {
this.ownerDetail = ownerDetail;
}
@Override
public String toString() {
StringBuilder str = new StringBuilder();
str.append("getCommentPK() = ").append(getCommentPK().toString()).append(
", \n");
str.append("getResourceType() = ").append(getResourceType()).append(
", \n");
str.append("getForeignKey() = ").append(getForeignKey().toString()).append(
", \n");
str.append("getOwnerId() = ").append(getOwnerId()).append(", \n");
str.append("getMessage() = ").append(getMessage())
.append(", \n");
str.append("getCreationDate() = ").append(getCreationDate())
.append(", \n");
str.append("getModificationDate() = ").append(
getModificationDate());
return str.toString();
}
@Override
public UserDetail getCreator() {
if (ownerDetail == null || !ownerDetail.isFullyDefined()) {
ownerDetail = UserDetail.getById(String.valueOf(owner_id));
}
return ownerDetail;
}
@Override
public String getTitle() {
return "";
}
@Override
public String getDescription() {
return "";
}
@Override
public String getId() {
return pk.getId();
}
@Override
public String getComponentInstanceId() {
return pk.getInstanceId();
}
@Override
public String getContributionType() {
return TYPE;
}
/**
* Is the specified user can access this comment?
* <p/>
* A user can access a comment if it has enough rights to access the application instance in
* which is managed this comment.
* <p/>
* Be caution, the access control on the commented resource is usually more reliable than using
* this method.
* @param user a user in Silverpeas.
* @return true if the user can access this comment, false otherwise.
*/
@Override
public boolean canBeAccessedBy(final UserDetail user) {
AccessController<String> accessController =
AccessControllerProvider.getAccessController("componentAccessController");
return accessController.isUserAuthorized(user.getId(), getComponentInstanceId());
}
@Override
public String getSilverpeasContentId() {
return "";
}
} | CecileBONIN/Silverpeas-Core | lib-core/src/main/java/com/silverpeas/comment/model/Comment.java | Java | agpl-3.0 | 6,643 |
import { change, date } from 'common/changelog';
import SPELLS from 'common/SPELLS';
import { Adoraci, Khadaj, Ogofo, Oratio, Reglitch, VMakaev, Zeboot, jasper } from 'CONTRIBUTORS';
import { SpellLink } from 'interface';
import React from 'react';
export default [
change(date(2021, 4, 11), <>Updated <SpellLink id={SPELLS.GUARDIAN_FAERIE.id} /> damage reduction to 20% and corrected DR calculation.</>, Adoraci),
change(date(2021, 4, 9), <>Support for <SpellLink id={SPELLS.CLARITY_OF_MIND.id} /></>, Reglitch),
change(date(2021, 4, 8), <>Support for <SpellLink id={SPELLS.SHATTERED_PERCEPTIONS.id} /></>, Reglitch),
change(date(2021, 4, 6), <>9.0.5 support! <SpellLink id={SPELLS.SPIRIT_SHELL_TALENT.id} /> support for everyone!</>, Reglitch),
change(date(2021, 1, 31), <>Added <SpellLink id={SPELLS.POWER_INFUSION.id} /> to the checklist.</>, jasper),
change(date(2021, 1, 23), <>Added <SpellLink id={SPELLS.TWINS_OF_THE_SUN_PRIESTESS.id} /> legendary.</>, Adoraci),
change(date(2020, 12, 28), <>Fixing <SpellLink id={SPELLS.BOON_OF_THE_ASCENDED.id} /></>, Khadaj),
change(date(2020, 12, 28), <>Adding support for <SpellLink id={SPELLS.FAE_GUARDIANS.id} /></>, Khadaj),
change(date(2020, 12, 28), <>Adding support for <SpellLink id={SPELLS.UNHOLY_NOVA.id} /></>, Khadaj),
change(date(2020, 12, 2), <>Fixed damage bonus of <SpellLink id={SPELLS.SCHISM_TALENT.id} /> to 25% to match Shadowlands nerf.</>, VMakaev),
change(date(2020, 11, 13), <>Implementation of <SpellLink id={SPELLS.SHINING_RADIANCE.id} />.</>, Oratio),
change(date(2020, 10, 18), 'Converted legacy listeners to new event filters', Zeboot),
change(date(2020, 10, 10), <>Implementation of <SpellLink id={SPELLS.BOON_OF_THE_ASCENDED.id} />.</>, Ogofo),
change(date(2020, 10, 3), <>Update <SpellLink id={SPELLS.POWER_WORD_SOLACE_TALENT.id} /> cooldown.</>, Reglitch),
change(date(2020, 10, 2), <>Converting all disc modules to Typescript.</>, Khadaj),
change(date(2020, 10, 2), <>Implementation of <SpellLink id={SPELLS.MINDGAMES.id} /></>, Oratio),
change(date(2020, 9, 30), <>Shadowlands Clean up.</>, Oratio),
];
| anom0ly/WoWAnalyzer | analysis/priestdiscipline/src/CHANGELOG.tsx | TypeScript | agpl-3.0 | 2,119 |
OC.L10N.register(
"external",
{
"Please enter valid urls - they have to start with either http://, https:// or /" : "Ju lutemi, jepni URL të vlefshme - duhet të fillojnë http://, https:// ose /",
"External sites saved." : "Sajtet e jashtëm u ruajtën.",
"External Sites" : "Sajte të Jashtëm",
"Please note that some browsers will block displaying of sites via http if you are running https." : "Ju lutemi, kini parasysh që disa shfletues do të bllokojnë shfaqjen e sajteve përmes http-je, nëse xhironi https.",
"Furthermore please note that many sites these days disallow iframing due to security reasons." : "Për më tepër, ju lutemi, kini parasysh që mjaft sajte në këto kohë s’lejojnë iframing, për arsye sigurie.",
"We highly recommend to test the configured sites below properly." : "Këshillojmë me forcë të testoni si duhet më poshtë sajtet e formësuar.",
"Name" : "Emër",
"URL" : "URL",
"Select an icon" : "Përzgjidhni një ikonë",
"Remove site" : "Hiqe sajtin",
"Add" : "Shtoje"
},
"nplurals=2; plural=(n != 1);");
| jacklicn/owncloud | apps/external/l10n/sq.js | JavaScript | agpl-3.0 | 1,106 |
# solution to Tokens 5, 6
think(0)
while object_here():
take()
move()
while carries_object():
put()
while not at_goal():
move()
| code4futuredotorg/reeborg_tw | test/src/tokens56_en.py | Python | agpl-3.0 | 144 |
/* Copyright 2012 Canonical Ltd. This software is licensed under the
* GNU Affero General Public License version 3 (see the file LICENSE). */
YUI.add('lp.registry.team.mailinglists.test', function (Y) {
// Local aliases.
var Assert = Y.Assert,
ArrayAssert = Y.ArrayAssert;
var team_mailinglists = Y.lp.registry.team.mailinglists;
var tests = Y.namespace('lp.registry.team.mailinglists.test');
tests.suite = new Y.Test.Suite('lp.registry.team.mailinglists Tests');
tests.suite.add(new Y.Test.Case({
name: 'Team Mailinglists',
setUp: function() {
window.LP = {
links: {},
cache: {}
};
},
tearDown: function() {
},
test_render_message: function () {
var config = {
messages: [
{
'message_id': 3,
'headers': {
'Subject': 'Please stop breaking things',
'To': 'the_list@example.hu',
'From': 'someone@else.com',
'Date': '2011-10-13'
},
'nested_messages': [],
'attachments': []
}
],
container: Y.one('#messagelist'),
forwards_navigation: Y.all('.last,.next'),
backwards_navigation: Y.all('.first,.previous')
};
var message_list = new Y.lp.registry.team.mailinglists.MessageList(
config);
message_list.display_messages();
var message = Y.one("#message-3");
Assert.areEqual(message.get('text'), 'Please stop breaking things');
},
test_nav: function () {
var config = {
messages: [],
container: Y.one('#messagelist'),
forwards_navigation: Y.all('.last,.next'),
backwards_navigation: Y.all('.first,.previous')
};
var message_list = new Y.lp.registry.team.mailinglists.MessageList(
config);
var fired = false;
Y.on('messageList:backwards', function () {
fired = true;
});
var nav_link = Y.one('.first');
nav_link.simulate('click');
Assert.isTrue(fired);
}
}));
}, '0.1', {
requires: ['test', 'lp.testing.helpers', 'test-console',
'lp.registry.team.mailinglists', 'lp.mustache',
'node-event-simulate', 'widget-stack', 'event']
});
| abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/registry/javascript/tests/test_team_mailinglists.js | JavaScript | agpl-3.0 | 2,657 |
package com.nexusplay.elements;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nexusplay.db.MediaDatabase;
/**
* Servlet implementation class Search
*/
@WebServlet("/Search")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Search() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
MediaDisplayer searchResult = new MediaDisplayer(MediaDatabase.searchMedia(request.getParameter("q"),10));
if(searchResult.getCategsMap().size()!=0){
request.setAttribute("categories", searchResult.getCategories());
request.getRequestDispatcher("/templates/elements/MediaDisplayer.jsp").include(request, response);
}
} catch (SQLException e) {
request.getRequestDispatcher("/templates/elements/MinimalHeader.jsp").include(request, response);
request.getRequestDispatcher("/templates/information_screens/InternalError.jsp").include(request, response);
request.getRequestDispatcher("/templates/elements/MinimalFooter.jsp").include(request, response);
e.printStackTrace();
return;
}
out.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| AlexCristian/NexusPlay | src/com/nexusplay/elements/Search.java | Java | agpl-3.0 | 1,994 |
/*
* The Exomiser - A tool to annotate and prioritize genomic variants
*
* Copyright (c) 2016-2018 Queen Mary University of London.
* Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.monarchinitiative.exomiser.core.prioritisers.util;
import org.jblas.FloatMatrix;
import java.util.Collections;
import java.util.Map;
/**
* Specialised stub implementation of the {@code DataMatrix}. This is deliberately package private as it should only be
* returned from the interface {@code empty()} method.
*
* @author Jules Jacobsen <j.jacobsen@qmul.ac.uk>
* @since 10.0.0
*/
class StubDataMatrix implements DataMatrix {
private static final StubDataMatrix EMPTY = new StubDataMatrix();
private StubDataMatrix() {
}
static DataMatrix empty() {
return EMPTY;
}
@Override
public Map<Integer, Integer> getEntrezIdToRowIndex() {
return Collections.emptyMap();
}
@Override
public FloatMatrix getMatrix() {
return FloatMatrix.EMPTY;
}
@Override
public int numRows() {
return 0;
}
@Override
public int numColumns() {
return 0;
}
@Override
public boolean containsGene(Integer entrezGeneId) {
return false;
}
@Override
public Integer getRowIndexForGene(int entrezGeneId) {
return null;
}
@Override
public FloatMatrix getColumnMatrixForGene(int entrezGeneId) {
return null;
}
}
| exomiser/Exomiser | exomiser-core/src/main/java/org/monarchinitiative/exomiser/core/prioritisers/util/StubDataMatrix.java | Java | agpl-3.0 | 2,170 |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
namespace BloodOfEvil.Player.Services.Language.UI
{
using Helpers;
using Utilities.UI;
using Extensions;
public class LanguageCategoryButton : AButton
{
#region Fields
public ELanguageCategory LanguageCategory { get; private set; }
private string text;
#endregion
#region Public Behaviour
public void Initialize(ELanguageCategory languageCategory)
{
this.LanguageCategory = languageCategory;
this.text = EnumerationHelper.EnumerationToString(this.LanguageCategory).ReplaceUppercaseBySpaceAndUppercase();
this.UpdateTextLanguage();
PlayerServicesAndModulesContainer.Instance.LanguageService.NewLanguageHaveBeenLoaded += this.UpdateTextLanguage;
}
#endregion
#region Abstract Behaviour
public override void ButtonActionOnClick()
{
transform.parent.GetComponent<LanguageNodeUIManager>().LanguageCategorySelected = this.LanguageCategory;
}
#endregion
#region Private Behaviour
private void UpdateTextLanguage()
{
transform.Find("Text").
GetComponent<Text>().
text = PlayerServicesAndModulesContainer.Instance.LanguageService.GetText(ELanguageCategory.LanguageCategory, this.text);
}
#endregion
}
} | HaddadBenjamin/Blood-Of-Evil-Remake-2 | Blood Of Evil/Assets/Project/Scripts/Player/Services/Language Service/UI/Language Editor/LanguageCategoryButton.cs | C# | agpl-3.0 | 1,464 |
/*
* This file is part of huborcid.
*
* huborcid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* huborcid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u044f\u043a\u0448\u0430\u043d\u0431\u0430",
"\u0434\u0443\u0448\u0430\u043d\u0431\u0430",
"\u0441\u0435\u0448\u0430\u043d\u0431\u0430",
"\u0447\u043e\u0440\u0448\u0430\u043d\u0431\u0430",
"\u043f\u0430\u0439\u0448\u0430\u043d\u0431\u0430",
"\u0436\u0443\u043c\u0430",
"\u0448\u0430\u043d\u0431\u0430"
],
"ERANAMES": [
"\u041c.\u0410.",
"\u042d"
],
"ERAS": [
"\u041c.\u0410.",
"\u042d"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u042f\u043d\u0432\u0430\u0440",
"\u0424\u0435\u0432\u0440\u0430\u043b",
"\u041c\u0430\u0440\u0442",
"\u0410\u043f\u0440\u0435\u043b",
"\u041c\u0430\u0439",
"\u0418\u044e\u043d",
"\u0418\u044e\u043b",
"\u0410\u0432\u0433\u0443\u0441\u0442",
"\u0421\u0435\u043d\u0442\u044f\u0431\u0440",
"\u041e\u043a\u0442\u044f\u0431\u0440",
"\u041d\u043e\u044f\u0431\u0440",
"\u0414\u0435\u043a\u0430\u0431\u0440"
],
"SHORTDAY": [
"\u042f\u043a\u0448",
"\u0414\u0443\u0448",
"\u0421\u0435\u0448",
"\u0427\u043e\u0440",
"\u041f\u0430\u0439",
"\u0416\u0443\u043c",
"\u0428\u0430\u043d"
],
"SHORTMONTH": [
"\u042f\u043d\u0432",
"\u0424\u0435\u0432",
"\u041c\u0430\u0440",
"\u0410\u043f\u0440",
"\u041c\u0430\u0439",
"\u0418\u044e\u043d",
"\u0418\u044e\u043b",
"\u0410\u0432\u0433",
"\u0421\u0435\u043d",
"\u041e\u043a\u0442",
"\u041d\u043e\u044f",
"\u0414\u0435\u043a"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, y MMMM dd",
"longDate": "y MMMM d",
"medium": "y MMM d HH:mm:ss",
"mediumDate": "y MMM d",
"mediumTime": "HH:mm:ss",
"short": "yy/MM/dd HH:mm",
"shortDate": "yy/MM/dd",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "uz-cyrl",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| Cineca/OrcidHub | src/main/webapp/bower_components/angular-i18n/angular-locale_uz-cyrl.js | JavaScript | agpl-3.0 | 3,592 |
/*
* This file is part of BaseballScore.
*
* BaseballScore is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BaseballScore is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BaseballScore. If not, see <http://www.gnu.org/licenses/>.
*/
package org.meerkatlabs.baseballscore.models.enums;
import org.meerkatlabs.baseballscore.models.IPosition;
/**
* Positions for a standard base ball game.
*
* @author Robert Robinson rerobins@meerkatlabs.org
*/
public enum NineBallBaseballPosition implements IPosition {
/**
* Pitcher.
*/
PITCHER("Pitcher", "P"),
/**
* Catcher.
*/
CATCHER("Catcher", "C"),
/**
* First Base.
*/
FIRST_BASE("First Base", "1B"),
/**
* Second Base.
*/
SECOND_BASE("Second Base", "2B"),
/**
* Third Base.
*/
THIRD_BASE("Third Base", "3B"),
/**
* Short Stop.
*/
SHORT_STOP("Short Stop", "SS"),
/**
* Left Field.
*/
LEFT_FIELD("Left Field", "LF"),
/**
* Center Field.
*/
CENTER_FIELD("Center Field", "CF"),
/**
* Right Field.
*/
RIGHT_FIELD("Right Field", "RF");
/**
* Human readable version of the enumeration.
*/
String humanReadable;
/**
* Abbreviation of the position.
*/
String abbreviation;
/**
* Constructor.
*
* @param humanReadable string.
* @param abbreviation string.
*/
NineBallBaseballPosition(final String humanReadable, final String abbreviation) {
this.humanReadable = humanReadable;
this.abbreviation = abbreviation;
}
@Override
public String getAbbreviation() {
return abbreviation;
}
@Override
public String toString() {
return humanReadable;
}
@Override
public int getNumericalValue() {
return ordinal() + 1;
}
@Override
public boolean isPitcher() {
return this == PITCHER;
}
}
| rerobins/baseballscore | src/main/java/org/meerkatlabs/baseballscore/models/enums/NineBallBaseballPosition.java | Java | agpl-3.0 | 2,451 |
/*
* Copyright (C) 2000 - 2013 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have recieved a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.silverpeas.notification.message;
/**
* User: Yohann Chastagnier
* Date: 07/11/13
*/
public enum MessageType {
info,
success,
warning,
error,
severe
}
| CecileBONIN/Silverpeas-Core | lib-core/src/main/java/org/silverpeas/notification/message/MessageType.java | Java | agpl-3.0 | 1,318 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG AMessage
#include "AMessage.h"
#include <ctype.h>
#include "AAtomizer.h"
#include "ABuffer.h"
#include "ADebug.h"
//#include "ALooperRoster.h"
#include "AString.h"
//#include <binder/Parcel.h>
#include "hexdump.h"
namespace android {
//extern ALooperRoster gLooperRoster;
AMessage::AMessage(uint32_t what/*, ALooper::handler_id target*/)
: mWhat(what),
//mTarget(target),
mNumItems(0) {
}
AMessage::~AMessage() {
clear();
}
void AMessage::setWhat(uint32_t what) {
mWhat = what;
}
uint32_t AMessage::what() const {
return mWhat;
}
/*void AMessage::setTarget(ALooper::handler_id handlerID) {
mTarget = handlerID;
}
ALooper::handler_id AMessage::target() const {
return mTarget;
}*/
void AMessage::clear() {
for (size_t i = 0; i < mNumItems; ++i) {
Item *item = &mItems[i];
freeItem(item);
}
mNumItems = 0;
}
void AMessage::freeItem(Item *item) {
switch (item->mType) {
case kTypeString:
{
delete item->u.stringValue;
break;
}
case kTypeObject:
case kTypeMessage:
case kTypeBuffer:
{
if (item->u.refValue != NULL) {
item->u.refValue->decStrong(this);
}
break;
}
default:
break;
}
}
AMessage::Item *AMessage::allocateItem(const char *name) {
name = AAtomizer::Atomize(name);
size_t i = 0;
while (i < mNumItems && mItems[i].mName != name) {
++i;
}
Item *item;
if (i < mNumItems) {
item = &mItems[i];
freeItem(item);
} else {
//CHECK(mNumItems < kMaxNumItems);
i = mNumItems++;
item = &mItems[i];
item->mName = name;
}
return item;
}
const AMessage::Item *AMessage::findItem(
const char *name, Type type) const {
name = AAtomizer::Atomize(name);
for (size_t i = 0; i < mNumItems; ++i) {
const Item *item = &mItems[i];
if (item->mName == name) {
return item->mType == type ? item : NULL;
}
}
return NULL;
}
#define BASIC_TYPE(NAME,FIELDNAME,TYPENAME) \
void AMessage::set##NAME(const char *name, TYPENAME value) { \
Item *item = allocateItem(name); \
\
item->mType = kType##NAME; \
item->u.FIELDNAME = value; \
} \
\
bool AMessage::find##NAME(const char *name, TYPENAME *value) const { \
const Item *item = findItem(name, kType##NAME); \
if (item) { \
*value = item->u.FIELDNAME; \
return true; \
} \
return false; \
}
BASIC_TYPE(Int32,int32Value,int32_t)
BASIC_TYPE(Int64,int64Value,int64_t)
BASIC_TYPE(Size,sizeValue,size_t)
BASIC_TYPE(Float,floatValue,float)
BASIC_TYPE(Double,doubleValue,double)
BASIC_TYPE(Pointer,ptrValue,void *)
#undef BASIC_TYPE
void AMessage::setString(
const char *name, const char *s, ssize_t len) {
Item *item = allocateItem(name);
item->mType = kTypeString;
item->u.stringValue = new AString(s, len < 0 ? strlen(s) : len);
}
void AMessage::setObjectInternal(
const char *name, const sp<RefBase> &obj, Type type) {
Item *item = allocateItem(name);
item->mType = type;
if (obj != NULL) { obj->incStrong(this); }
item->u.refValue = obj.get();
}
void AMessage::setObject(const char *name, const sp<RefBase> &obj) {
setObjectInternal(name, obj, kTypeObject);
}
void AMessage::setBuffer(const char *name, const sp<ABuffer> &buffer) {
setObjectInternal(name, sp<RefBase>(buffer), kTypeBuffer);
}
void AMessage::setMessage(const char *name, const sp<AMessage> &obj) {
Item *item = allocateItem(name);
item->mType = kTypeMessage;
if (obj != NULL) { obj->incStrong(this); }
item->u.refValue = obj.get();
}
void AMessage::setRect(
const char *name,
int32_t left, int32_t top, int32_t right, int32_t bottom) {
Item *item = allocateItem(name);
item->mType = kTypeRect;
item->u.rectValue.mLeft = left;
item->u.rectValue.mTop = top;
item->u.rectValue.mRight = right;
item->u.rectValue.mBottom = bottom;
}
bool AMessage::findString(const char *name, AString *value) const {
const Item *item = findItem(name, kTypeString);
if (item) {
*value = *item->u.stringValue;
return true;
}
return false;
}
bool AMessage::findObject(const char *name, sp<RefBase> *obj) const {
const Item *item = findItem(name, kTypeObject);
if (item) {
*obj = item->u.refValue;
return true;
}
return false;
}
bool AMessage::findBuffer(const char *name, sp<ABuffer> *buf) const {
const Item *item = findItem(name, kTypeBuffer);
if (item) {
*buf = (ABuffer *)(item->u.refValue);
return true;
}
return false;
}
bool AMessage::findMessage(const char *name, sp<AMessage> *obj) const {
const Item *item = findItem(name, kTypeMessage);
if (item) {
*obj = static_cast<AMessage *>(item->u.refValue);
return true;
}
return false;
}
bool AMessage::findRect(
const char *name,
int32_t *left, int32_t *top, int32_t *right, int32_t *bottom) const {
const Item *item = findItem(name, kTypeRect);
if (item == NULL) {
return false;
}
*left = item->u.rectValue.mLeft;
*top = item->u.rectValue.mTop;
*right = item->u.rectValue.mRight;
*bottom = item->u.rectValue.mBottom;
return true;
}
void AMessage::post(int64_t delayUs) {
//gLooperRoster.postMessage(this, delayUs);
}
status_t AMessage::postAndAwaitResponse(sp<AMessage> *response) {
return 0; // gLooperRoster.postAndAwaitResponse(this, response);
}
void AMessage::postReply(uint32_t replyID) {
// gLooperRoster.postReply(replyID, this);
}
bool AMessage::senderAwaitsResponse(uint32_t *replyID) const {
int32_t tmp;
bool found = findInt32("replyID", &tmp);
if (!found) {
return false;
}
*replyID = static_cast<uint32_t>(tmp);
return true;
}
sp<AMessage> AMessage::dup() const {
sp<AMessage> msg = new AMessage(mWhat/*, mTarget*/);
msg->mNumItems = mNumItems;
for (size_t i = 0; i < mNumItems; ++i) {
const Item *from = &mItems[i];
Item *to = &msg->mItems[i];
to->mName = from->mName;
to->mType = from->mType;
switch (from->mType) {
case kTypeString:
{
to->u.stringValue =
new AString(*from->u.stringValue);
break;
}
case kTypeObject:
case kTypeBuffer:
{
to->u.refValue = from->u.refValue;
to->u.refValue->incStrong(msg.get());
break;
}
case kTypeMessage:
{
sp<AMessage> copy =
static_cast<AMessage *>(from->u.refValue)->dup();
to->u.refValue = copy.get();
to->u.refValue->incStrong(msg.get());
break;
}
default:
{
to->u = from->u;
break;
}
}
}
return msg;
}
static void appendIndent(AString *s, int32_t indent) {
static const char kWhitespace[] =
" "
" ";
//CHECK_LT((size_t)indent, sizeof(kWhitespace));
s->append(kWhitespace, indent);
}
static bool isFourcc(uint32_t what) {
return isprint(what & 0xff)
&& isprint((what >> 8) & 0xff)
&& isprint((what >> 16) & 0xff)
&& isprint((what >> 24) & 0xff);
}
AString AMessage::debugString(int32_t indent) const {
AString s = "AMessage(what = ";
AString tmp;
if (isFourcc(mWhat)) {
tmp = StringPrintf(
"'%c%c%c%c'",
(char)(mWhat >> 24),
(char)((mWhat >> 16) & 0xff),
(char)((mWhat >> 8) & 0xff),
(char)(mWhat & 0xff));
} else {
tmp = StringPrintf("0x%08x", mWhat);
}
s.append(tmp);
/* if (mTarget != 0) {
tmp = StringPrintf(", target = %d", mTarget);
s.append(tmp);
} */
s.append(") = {\n");
for (size_t i = 0; i < mNumItems; ++i) {
const Item &item = mItems[i];
switch (item.mType) {
case kTypeInt32:
tmp = StringPrintf(
"int32_t %s = %d", item.mName, item.u.int32Value);
break;
case kTypeInt64:
tmp = StringPrintf(
"int64_t %s = %lld", item.mName, item.u.int64Value);
break;
case kTypeSize:
tmp = StringPrintf(
"size_t %s = %d", item.mName, item.u.sizeValue);
break;
case kTypeFloat:
tmp = StringPrintf(
"float %s = %f", item.mName, item.u.floatValue);
break;
case kTypeDouble:
tmp = StringPrintf(
"double %s = %f", item.mName, item.u.doubleValue);
break;
case kTypePointer:
tmp = StringPrintf(
"void *%s = %p", item.mName, item.u.ptrValue);
break;
case kTypeString:
tmp = StringPrintf(
"string %s = \"%s\"",
item.mName,
item.u.stringValue->c_str());
break;
case kTypeObject:
tmp = StringPrintf(
"RefBase *%s = %p", item.mName, item.u.refValue);
break;
case kTypeBuffer:
{
sp<ABuffer> buffer = static_cast<ABuffer *>(item.u.refValue);
if (buffer != NULL && buffer->size() <= 64) {
tmp = StringPrintf("Buffer %s = {\n", item.mName);
hexdump(buffer->data(), buffer->size(), indent + 4, &tmp);
appendIndent(&tmp, indent + 2);
tmp.append("}");
} else {
tmp = StringPrintf(
"Buffer *%s = %p", item.mName, buffer.get());
}
break;
}
case kTypeMessage:
tmp = StringPrintf(
"AMessage %s = %s",
item.mName,
static_cast<AMessage *>(
item.u.refValue)->debugString(
indent + strlen(item.mName) + 14).c_str());
break;
case kTypeRect:
tmp = StringPrintf(
"Rect %s(%d, %d, %d, %d)",
item.mName,
item.u.rectValue.mLeft,
item.u.rectValue.mTop,
item.u.rectValue.mRight,
item.u.rectValue.mBottom);
break;
default:
//TRESPASS();
break;
}
appendIndent(&s, indent);
s.append(" ");
s.append(tmp);
s.append("\n");
}
appendIndent(&s, indent);
s.append("}");
return s;
}
// static
/*sp<AMessage> AMessage::FromParcel(const Parcel &parcel) {
int32_t what = parcel.readInt32();
sp<AMessage> msg = new AMessage(what);
msg->mNumItems = static_cast<size_t>(parcel.readInt32());
for (size_t i = 0; i < msg->mNumItems; ++i) {
Item *item = &msg->mItems[i];
item->mName = AAtomizer::Atomize(parcel.readCString());
item->mType = static_cast<Type>(parcel.readInt32());
switch (item->mType) {
case kTypeInt32:
{
item->u.int32Value = parcel.readInt32();
break;
}
case kTypeInt64:
{
item->u.int64Value = parcel.readInt64();
break;
}
case kTypeSize:
{
item->u.sizeValue = static_cast<size_t>(parcel.readInt32());
break;
}
case kTypeFloat:
{
item->u.floatValue = parcel.readFloat();
break;
}
case kTypeDouble:
{
item->u.doubleValue = parcel.readDouble();
break;
}
case kTypeString:
{
item->u.stringValue = new AString(parcel.readCString());
break;
}
case kTypeMessage:
{
sp<AMessage> subMsg = AMessage::FromParcel(parcel);
subMsg->incStrong(msg.get());
item->u.refValue = subMsg.get();
break;
}
default:
{
ALOGE("This type of object cannot cross process boundaries.");
TRESPASS();
}
}
}
return msg;
}
void AMessage::writeToParcel(Parcel *parcel) const {
parcel->writeInt32(static_cast<int32_t>(mWhat));
parcel->writeInt32(static_cast<int32_t>(mNumItems));
for (size_t i = 0; i < mNumItems; ++i) {
const Item &item = mItems[i];
parcel->writeCString(item.mName);
parcel->writeInt32(static_cast<int32_t>(item.mType));
switch (item.mType) {
case kTypeInt32:
{
parcel->writeInt32(item.u.int32Value);
break;
}
case kTypeInt64:
{
parcel->writeInt64(item.u.int64Value);
break;
}
case kTypeSize:
{
parcel->writeInt32(static_cast<int32_t>(item.u.sizeValue));
break;
}
case kTypeFloat:
{
parcel->writeFloat(item.u.floatValue);
break;
}
case kTypeDouble:
{
parcel->writeDouble(item.u.doubleValue);
break;
}
case kTypeString:
{
parcel->writeCString(item.u.stringValue->c_str());
break;
}
case kTypeMessage:
{
static_cast<AMessage *>(item.u.refValue)->writeToParcel(parcel);
break;
}
default:
{
ALOGE("This type of object cannot cross process boundaries.");
TRESPASS();
}
}
}
}
*/
size_t AMessage::countEntries() const {
return mNumItems;
}
const char *AMessage::getEntryNameAt(size_t index, Type *type) const {
if (index >= mNumItems) {
*type = kTypeInt32;
return NULL;
}
*type = mItems[index].mType;
return mItems[index].mName;
}
} // namespace android
| noamtamim/khls | HLSPlayerSDK/jni/mpeg2ts_parser/AMessage.cpp | C++ | agpl-3.0 | 16,234 |
MWF.xApplication.Selector = MWF.xApplication.Selector || {};
MWF.xDesktop.requireApp("Selector", "Identity", null, false);
MWF.xApplication.Selector.IdentityWidthDuty = new Class({
Extends: MWF.xApplication.Selector.Identity,
options: {
"style": "default",
"count": 0,
"title": "",
"dutys": [],
"units": [],
"values": [],
"zIndex": 1000,
"expand": false,
"noUnit" : false,
"include" : [], //增加的可选项
"resultType" : "", //可以设置成个人,那么结果返回个人
"expandSubEnable": true,
"selectAllEnable" : true, //分类是否允许全选下一层
"exclude" : [],
"selectType" : "identity"
},
setInitTitle: function(){
this.setOptions({"title": MWF.xApplication.Selector.LP.selectIdentity});
},
_init : function(){
this.selectType = "identity";
this.className = "IdentityWidthDuty"
},
loadSelectItems: function(addToNext){
this.loadingCountDuty = "wait";
this.allUnitObjectWithDuty = {};
var afterLoadSelectItemFun = this.afterLoadSelectItem.bind(this);
if( this.options.disabled ){
this.afterLoadSelectItem();
return;
}
if( this.options.resultType === "person" ){
if( this.titleTextNode ){
this.titleTextNode.set("text", MWF.xApplication.Selector.LP.selectPerson );
}else{
this.options.title = MWF.xApplication.Selector.LP.selectPerson;
}
}
if (this.options.dutys.length){
var dutyLoaded = 0;
var loadDutySuccess = function () {
dutyLoaded++;
if( dutyLoaded === this.options.dutys.length ){
this.dutyLoaded = true;
if( this.includeLoaded ){
afterLoadSelectItemFun();
}
}
}.bind(this);
this.loadInclude( function () {
this.includeLoaded = true;
if( this.dutyLoaded ){
afterLoadSelectItemFun();
}
}.bind(this));
var loadDuty = function () {
if( this.isCheckStatusOrCount() ){
this.loadingCountDuty = "ready";
this.checkLoadingCount();
}
this.options.dutys.each(function(duty){
var data = {"name": duty, "id":duty};
var category = this._newItemCategory("ItemCategory",data, this, this.itemAreaNode);
this.subCategorys.push(category);
this.allUnitObjectWithDuty[data.name] = category;
loadDutySuccess();
}.bind(this));
}.bind(this);
if( this.options.units.length === 0 ){
loadDuty();
}else{
var unitList = [];
this.options.units.each(function(u) {
var unitName = typeOf(u) === "string" ? u : (u.distinguishedName || u.unique || u.levelName || u.id);
if (unitName)unitList.push( unitName )
});
debugger;
if( !this.options.expandSubEnable ){
this.allUnitNames = unitList;
loadDuty();
}else{
var unitObjectList = [];
var loadNestedUnit = function(){
MWF.Actions.get("x_organization_assemble_express").listUnitSubNested({"unitList": unitList }, function(json1){
var unitNames = [];
//排序
if( this.options.units.length === 1 ){
// unitNames = unitList.concat( json1.data );
unitNames = Array.clone(unitList);
for( var i=0; i<json1.data.length; i++ ){
if( !unitNames.contains(json1.data[i].distinguishedName) ){
unitNames.push( json1.data[i].distinguishedName );
}
}
}else{
unitObjectList.each( function ( u ) {
unitNames.push( u.distinguishedName || u.unique || u.levelName || u.id );
for( var i=0; i<json1.data.length; i++ ){
if( json1.data[i].levelName.indexOf(u.levelName) > -1 ){
unitNames.push( json1.data[i].distinguishedName );
}
}
})
}
this.allUnitNames = unitNames;
loadDuty();
}.bind(this), null);
}.bind(this);
var flag = false; //需要获取层次名用于排序
if( this.options.units.length === 1 ){
loadNestedUnit();
}else{
this.options.units.each(function(u) {
if (typeOf(u) === "string" ) {
u.indexOf("/") === -1 ? (flag = true) : unitObjectList.push( { levelName : u } );
} else {
u.levelName ? unitObjectList.push( u ) : (flag = true);
}
});
if( flag ){ //需要获取层次名来排序
o2.Actions.load("x_organization_assemble_express").UnitActions.listObject( function (json) {
unitObjectList = json.data || [];
loadNestedUnit();
}.bind(this) )
}else{
loadNestedUnit();
}
}
}
}
}
if( this.isCheckStatusOrCount() ) {
this.loadingCountInclude = "wait";
this.loadIncludeCount();
}
},
search: function(){
var key = this.searchInput.get("value");
if (key){
this.initSearchArea(true);
var createdId = this.searchInItems(key) || [];
if( this.options.include && this.options.include.length ){
this.includeObject.listByFilter( "key", key, function( array ){
array.each( function(d){
if( !createdId.contains( d.distinguishedName ) ){
if( !this.isExcluded( d ) ) {
this._newItem( d, this, this.itemSearchAreaNode);
}
}
}.bind(this))
}.bind(this))
}
}else{
this.initSearchArea(false);
}
},
listPersonByPinyin: function(node){
this.searchInput.focus();
var pinyin = this.searchInput.get("value");
pinyin = pinyin+node.get("text");
this.searchInput.set("value", pinyin);
this.search();
},
checkLoadSelectItems: function(){
if (!this.options.units.length){
this.loadSelectItems();
}else{
this.loadSelectItems();
}
},
_scrollEvent: function(y){
return true;
},
_getChildrenItemIds: function(){
return null;
},
_newItemCategory: function(type, data, selector, item, level, category, delay){
return new MWF.xApplication.Selector.IdentityWidthDuty[type](data, selector, item, level, category, delay)
},
_listItemByKey: function(callback, failure, key){
if (this.options.units.length) key = {"key": key, "unitList": this.options.units};
this.orgAction.listIdentityByKey(function(json){
if (callback) callback.apply(this, [json]);
}.bind(this), failure, key);
},
_getItem: function(callback, failure, id, async){
this.orgAction.getIdentity(function(json){
if (callback) callback.apply(this, [json]);
}.bind(this), failure, ((typeOf(id)==="string") ? id : id.distinguishedName), async);
},
_newItemSelected: function(data, selector, item, selectedNode){
return new MWF.xApplication.Selector.IdentityWidthDuty.ItemSelected(data, selector, item, selectedNode)
},
_listItemByPinyin: function(callback, failure, key){
if (this.options.units.length) key = {"key": key, "unitList": this.options.units};
this.orgAction.listIdentityByPinyin(function(json){
if (callback) callback.apply(this, [json]);
}.bind(this), failure, key);
},
_newItem: function(data, selector, container, level, category, delay){
return new MWF.xApplication.Selector.IdentityWidthDuty.Item(data, selector, container, level, category, delay);
},
_newItemSearch: function(data, selector, container, level){
return new MWF.xApplication.Selector.IdentityWidthDuty.SearchItem(data, selector, container, level);
},
uniqueIdentityList: function(list){
var items = [], map = {};
(list||[]).each(function(d) {
if (d.distinguishedName || d.unique) {
if ((!d.distinguishedName || !map[d.distinguishedName]) && (!d.unique || !map[d.unique])) {
items.push(d);
map[d.distinguishedName] = true;
map[d.unique] = true;
}
} else {
items.push(d);
}
})
return items;
},
loadIncludeCount: function(){
var unitList = [];
var groupList = [];
if (this.options.include.length > 0) {
this.options.include.each(function (d) {
var dn = typeOf(d) === "string" ? d : d.distinguishedName;
var flag = dn.split("@").getLast().toLowerCase();
if (flag === "u") {
unitList.push(dn);
} else if (flag === "g") {
groupList.push(dn)
}
})
}
if(unitList.length || groupList.length){
this._loadUnitAndGroupCount(unitList, groupList, function () {
this.loadingCountInclude = "ready";
this.checkLoadingCount();
}.bind(this));
}else{
this.loadingCountInclude = "ignore";
this.checkLoadingCount();
}
},
checkLoadingCount: function(){
if(this.loadingCountDuty === "ready" && this.loadingCountInclude === "ready"){
this.checkCountAndStatus();
this.loadingCount = "done";
}else if(this.loadingCountDuty === "ready" && this.loadingCountInclude === "ignore"){
this.loadingCount = "done";
}
},
addSelectedCount: function( itemOrItemSelected, count, items ){
if( this.loadingCountInclude === "ignore" ){
this._addSelectedCountWithDuty(itemOrItemSelected, count, items);
}else{
this._addSelectedCountWithDuty(itemOrItemSelected, count, items);
this._addSelectedCount(itemOrItemSelected, count);
}
},
_addSelectedCountWithDuty: function( itemOrItemSelected, count, items ){
var itemData = itemOrItemSelected.data;
debugger;
items.each(function(item){
if(item.category && item.category._addSelectedCount && item.category.className === "ItemCategory"){
item.category._addSelectedCount( count );
}
}.bind(this));
},
//_listItemNext: function(last, count, callback){
// this.action.listRoleNext(last, count, function(json){
// if (callback) callback.apply(this, [json]);
// }.bind(this));
//}
});
MWF.xApplication.Selector.IdentityWidthDuty.Item = new Class({
Extends: MWF.xApplication.Selector.Identity.Item,
_getShowName: function(){
return this.data.name;
},
_getTtiteText: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
},
_setIcon: function(){
var style = this.selector.options.style;
this.iconNode.setStyle("background-image", "url("+"../x_component_Selector/$Selector/"+style+"/icon/personicon.png)");
}
});
MWF.xApplication.Selector.IdentityWidthDuty.SearchItem = new Class({
Extends: MWF.xApplication.Selector.Identity.Item,
_getShowName: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemSelected = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemSelected,
_getShowName: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
},
_getTtiteText: function(){
return this.data.name+((this.data.unitLevelName) ? "("+this.data.unitLevelName+")" : "");
},
_setIcon: function(){
var style = this.selector.options.style;
this.iconNode.setStyle("background-image", "url("+"../x_component_Selector/$Selector/"+style+"/icon/personicon.png)");
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemCategory = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemCategory,
createNode: function(){
this.className = "ItemCategory";
this.node = new Element("div", {
"styles": this.selector.css.selectorItemCategory_department,
"title" : this._getTtiteText()
}).inject(this.container);
},
_getShowName: function(){
return this.data.name;
},
_setIcon: function(){
var style = this.selector.options.style;
this.iconNode.setStyle("background-image", "url("+"../x_component_Selector/$Selector/"+style+"/icon/companyicon.png)");
},
_addSelectAllSelectedCount: function(){
var count = this._getSelectedCount();
this._checkCountAndStatus(count);
},
_addSelectedCount : function(){
if( this.selector.loadingCount === "done" ){
var count = this._getSelectedCount();
this._checkCountAndStatus(count);
}
},
_getTotalCount : function(){
return this.subItems.length;
},
_getSelectedCount : function(){
var list = this.subItems.filter( function (item) { return item.isSelected; });
return list.length;
},
loadSub : function(callback){
this._loadSub( function( firstLoad ) {
if(firstLoad){
if( this.selector.isCheckStatusOrCount() ){
// var count = this._getSelectedCount();
// this.checkCountAndStatus(count);
if( this.selector.loadingCount === "done" ){
this.checkCountAndStatus();
}
}
}
if(callback)callback();
}.bind(this))
},
_loadSub: function(callback){
if (!this.loaded && !this.loadingsub){
this.loadingsub = true;
if (this.selector.options.units.length){
var data = {
"name":this.data.name,
"unit":"",
"unitList" : this.selector.allUnitNames
};
MWF.Actions.get("x_organization_assemble_express").getDuty(data, function(json){
var list = this.selector.uniqueIdentityList(json.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
if (!this.loaded) {
this.loaded = true;
this.loadingsub = false;
this.itemLoaded = true;
if (callback) callback( true );
}
}.bind(this), null, false);
// if (this.selector.options.units.length){
// var action = MWF.Actions.get("x_organization_assemble_express");
// var data = {"name":this.data.name, "unit":""};
// var count = this.selector.options.units.length;
// var i = 0;
//
// if (this.selector.options.expandSubEnable) {
// this.selector.options.units.each(function(u){
// var unitName = "";
// if (typeOf(u)==="string"){
// unitName = u;
// }else{
// unitName = u.distinguishedName || u.unique || u.id || u.levelName
// }
// if (unitName){
// var unitNames;
// action.listUnitNameSubNested({"unitList": [unitName]}, function(json){
// unitNames = json.data.unitList;
// }.bind(this), null, false);
//
// unitNames.push(unitName);
// if (unitNames && unitNames.length){
// data.unitList = unitNames;
// action.getDuty(data, function(json){
// json.data.each(function(idSubData){
// if( !this.selector.isExcluded( idSubData ) ) {
// var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
// this.selector.items.push(item);
// if(this.subItems)this.subItems.push( item );
// }
// }.bind(this));
// }.bind(this), null, false);
// }
// }
//
// i++;
// if (i>=count){
// if (!this.loaded) {
// this.loaded = true;
// this.loadingsub = false;
// this.itemLoaded = true;
// if (callback) callback();
// }
// }
// }.bind(this));
// }else{
// this.selector.options.units.each(function(u){
// if (typeOf(u)==="string"){
// data.unit = u;
// }else{
// data.unit = u.distinguishedName || u.unique || u.id || u.levelName
// }
// action.getDuty(data, function(json){
// json.data.each(function(idSubData){
// if( !this.selector.isExcluded( idSubData ) ) {
// var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
// this.selector.items.push(item);
// if(this.subItems)this.subItems.push( item );
// }
// }.bind(this));
// i++;
// if (i>=count){
// if (!this.loaded) {
// this.loaded = true;
// this.loadingsub = false;
// this.itemLoaded = true;
// if (callback) callback();
// }
// }
// }.bind(this));
// }.bind(this));
// }
}else{
this.selector.orgAction.listIdentityWithDuty(function(json){
var list = this.selector.uniqueIdentityList(json.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
this.loaded = true;
this.loadingsub = false;
if (callback) callback( true );
}.bind(this), null, this.data.name);
}
}else{
if (callback) callback( );
}
},
loadCategoryChildren: function(callback){
this.loadSub(callback);
this.categoryLoaded = true;
//if (callback) callback();
},
loadItemChildren: function(callback){
this.loadSub(callback);
},
_hasChild: function(){
return true;
},
_hasChildCategory: function(){
return true;
},
_hasChildItem: function(){
return true;
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemUnitCategory = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemUnitCategory,
loadSub: function(callback){
if (!this.loaded){
this.selector.orgAction.listIdentityWithUnit(function(idJson){
if( !this.itemLoaded ){
var list = this.selector.uniqueIdentityList(idJson.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
this.itemLoaded = true;
}
if( !this.selector.options.expandSubEnable ){
this.loaded = true;
if (callback) callback();
}
if( this.selector.options.expandSubEnable ){
this.selector.orgAction.listSubUnitDirect(function(json){
json.data.each(function(subData){
if( !this.selector.isExcluded( subData ) ) {
if( subData && this.data.parentLevelName)subData.parentLevelName = this.data.parentLevelName +"/" + subData.name;
var category = this.selector._newItemCategory("ItemUnitCategory", subData, this.selector, this.children, this.level + 1, this);
this.subCategorys.push( category );
this.subCategoryMap[subData.parentLevelName || subData.levelName] = category;
}
}.bind(this));
this.loaded = true;
if (callback) callback();
}.bind(this), null, this.data.distinguishedName);
}
}.bind(this), null, this.data.distinguishedName);
}else{
if (callback) callback( );
}
},
loadCategoryChildren: function(callback){
if (!this.categoryLoaded){
this.loadSub(callback);
this.categoryLoaded = true;
this.itemLoaded = true;
//if( this.selector.options.expandSubEnable ){
// this.selector.orgAction.listSubUnitDirect(function(json){
// json.data.each(function(subData){
// if( !this.selector.isExcluded( subData ) ) {
// var category = this.selector._newItemCategory("ItemUnitCategory", subData, this.selector, this.children, this.level + 1, this);
// this.subCategorys.push( category );
// }
// }.bind(this));
// this.categoryLoaded = true;
// if (callback) callback();
// }.bind(this), null, this.data.distinguishedName);
//}else{
// if (callback) callback();
//}
}else{
if (callback) callback( );
}
},
loadItemChildren: function(callback){
if (!this.itemLoaded){
this.selector.orgAction.listIdentityWithUnit(function(idJson){
var list = this.selector.uniqueIdentityList(idJson.data);
list.each(function(idSubData){
if( !this.selector.isExcluded( idSubData ) ) {
var item = this.selector._newItem(idSubData, this.selector, this.children, this.level + 1, this);
this.selector.items.push(item);
if(this.subItems)this.subItems.push( item );
}
}.bind(this));
if (callback) callback();
}.bind(this), null, this.data.distinguishedName);
this.itemLoaded = true;
}else{
if (callback) callback( );
}
}
});
MWF.xApplication.Selector.IdentityWidthDuty.ItemGroupCategory = new Class({
Extends: MWF.xApplication.Selector.Identity.ItemGroupCategory
});
MWF.xApplication.Selector.IdentityWidthDuty.Filter = new Class({
Implements: [Options, Events],
options: {
"style": "default",
"units": [],
"dutys": []
},
initialize: function(value, options){
this.setOptions(options);
this.value = value;
this.orgAction = MWF.Actions.get("x_organization_assemble_control");
},
getList: function(callback){
if (false && this.list){
if (callback) callback();
}else{
this.list = [];
MWF.require("MWF.widget.PinYin", function(){
this.options.dutys.each(function(duty){
if (this.options.units.length){
var action = MWF.Actions.get("x_organization_assemble_express");
var data = {"name":duty, "unit":""};
this.options.units.each(function(u){
if (typeOf(u)==="string"){
data.unit = u;
}else{
data.unit = u.distinguishedName || u.unique || u.levelName || u.id
}
action.getDuty(data, function(json){
json.data.each(function(d){
d.pinyin = d.name.toPY().toLowerCase();
d.firstPY = d.name.toPYFirst().toLowerCase();
this.list.push(d);
}.bind(this));
}.bind(this), null, false);
}.bind(this));
}else{
this.orgAction.listIdentityWithDuty(function(json){
json.data.each(function(d){
d.pinyin = d.name.toPY().toLowerCase();
d.firstPY = d.name.toPYFirst().toLowerCase();
this.list.push(d);
}.bind(this));
}.bind(this), null, duty, false);
}
}.bind(this));
if (callback) callback();
}.bind(this));
}
},
filter: function(value, callback){
this.value = value;
this.getList(function(){
var data = this.list.filter(function(d){
var text = d.name+"#"+d.pinyin+"#"+d.firstPY;
return (text.indexOf(this.value)!=-1);
}.bind(this));
if (callback) callback(data);
}.bind(this));
}
});
| o2oa/o2oa | o2web/source/x_component_Selector/IdentityWidthDuty.js | JavaScript | agpl-3.0 | 29,141 |
<?php
/**
* Centurion
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@centurion-project.org so we can send you a copy immediately.
*
* @category Centurion
* @package Centurion_Db
* @subpackage Table
* @copyright Copyright (c) 2008-2011 Octave & Octave (http://www.octaveoctave.com)
* @license http://centurion-project.org/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Centurion
* @package Centurion_Db
* @subpackage Table
* @copyright Copyright (c) 2008-2011 Octave & Octave (http://www.octaveoctave.com)
* @license http://centurion-project.org/license/new-bsd New BSD License
* @author Florent Messa <florent.messa@gmail.com>
* @author Nicolas Duteil <nd@octaveoctave.com>
* @author Laurent Chenay <lc@centurion-project.org>
* @author Antoine Roesslinger <ar@octaveoctave.com>
*/
abstract class Centurion_Db_Table_Abstract extends Zend_Db_Table_Abstract implements Countable, Centurion_Traits_Traitsable
{
const CREATED_AT_COL = 'created_at';
const UPDATED_AT_COL = 'updated_at';
const RETRIEVE_ROW_ON_INSERT = 'retrieve';
const VERBOSE = 'verbose';
const MANY_DEPENDENT_TABLES = 'manyDependentTables';
const TABLE_IS_TESTABLE = 'tableTestable';
const ROW_IS_TESTABLE = 'rowTestable';
const FILTERS_ON = true;
const FILTERS_OFF = false;
/**
* Many to Many dependent tables.
*
* @var array
*/
protected $_manyDependentTables = array();
/**
* Classname for row.
*
* @var string
*/
protected $_rowClass = 'Centurion_Db_Table_Row';
/**
* Classname for rowset.
*
* @var string
*/
protected $_rowsetClass = 'Centurion_Db_Table_Rowset';
protected static $_kinds = array(
'day' => '%Y-%m-%d',
'month' => '%Y-%m-01',
'year' => '%Y-01-01',
);
protected $_cache = null;
protected $_meta = null;
protected $_selectClass = 'Centurion_Db_Table_Select';
protected $_select = null;
protected $_config = array();
/**
* Default options for cache backend defined in config ('resources.cachemanager.class')
* Setted by the main bootstrap in /application
* @var array
*/
protected static $_defaultBackendOptions = array();
/**
* Default options for cache frontent defined in config ('resources.cachemanager.class')
* Setted by the main bootstrap in /application
* @var array
*/
protected static $_defaultFrontendOptions = array();
protected $_traitQueue;
private static $_filtersOn = self::FILTERS_ON;
private static $_previousFiltersStatus = array(self::FILTERS_ON);
public static function getFiltersStatus()
{
return self::$_filtersOn;
}
public static function setFiltersStatus($status)
{
self::saveFiltersStatus();
self::$_filtersOn = (bool) $status;
}
public static function saveFiltersStatus()
{
self::$_previousFiltersStatus[] = self::$_filtersOn;
}
public static function restoreFiltersStatus()
{
if(count(self::$_previousFiltersStatus)){
self::$_filtersOn = array_pop(self::$_previousFiltersStatus);
} else{
throw new Exception('Error, there are no previous status in the stack');
}
}
public static function switchFiltersStatus()
{
self::setFiltersStatus(!self::getFiltersStatus());
}
public function getTraitQueue()
{
if (null == $this->_traitQueue)
$this->_traitQueue = new Centurion_Traits_Queue();
return $this->_traitQueue;
}
public function __construct($config = array())
{
if (null === $this->_name) {
$this->_name = Centurion_Inflector::tableize(str_replace('_Model_DbTable_', '', get_class($this)));
}
Centurion_Signal::factory('pre_init')->send($this);
parent::__construct($config);
$this->_config = $config;
if (null === $this->_meta) {
$this->_setupMeta();
}
Centurion_Traits_Common::initTraits($this);
Centurion_Signal::factory('post_init')->send($this);
}
public function isAllowedContext($context, $resource = null)
{
return in_array($context, iterator_to_array($this->_traitQueue), true);
}
/**
* Check if the current table have the given column
* @param string $columnName
* @return boolean true if current table have the column
*/
public function hasColumn($columnName)
{
return in_array($columnName, $this->info(self::COLS));
}
/**
* Check if the column is an index in the table
* @param string $columnName
* @return boolean true if current table have the column
*/
public function isIndex($columnName)
{
if ($this->getAdapter() instanceof Zend_Db_Adapter_Pdo_Mysql) {
foreach ($this->getAdapter()->query('show KEYS from ' . $this->_name)->fetchAll() as $row) {
if (0 === strcmp($row['Column_name'], $columnName)) {
return true;
}
}
return false;
} else {
throw new Centurion_Db_Table_Exception('Adapter is not MYSQL, so I can not check index.');
}
}
/**
* Find the column and table as set in foreign key of a column
* @param string $columnName The name of the column to find foreign key
* @return array|bool false if no foreign key, else array: array('table' => 'tablename', 'column' => 'column')
* @throws Centurion_Db_Table_Exception
*/
public function getMysqlForeignKey($columnName)
{
if ($this->getAdapter() instanceof Zend_Db_Adapter_Pdo_Mysql) {
$createTable = $this->getAdapter()->query('show create table ' . $this->_name)->fetch();
if (!isset($createTable['Create Table'])) {
return false;
}
$sql = $createTable['Create Table'];
if (preg_match('^CONSTRAINT .* FOREIGN KEY \(`'.$columnName.'`\) REFERENCES `(.*)\` \(`(.*)`\)^', $sql, $matches)) {
return array('table' => $matches['1'], 'column' => $matches['2']);
}
return false;
} else {
throw new Centurion_Db_Table_Exception('Adapter is not MYSQL, so I can not check index.');
}
}
public function delegateGet($context, $column)
{
if (!$this->isAllowedContext($context, $column))
throw new Centurion_Db_Exception(sprintf('Unauthorized property %s', $column));
return $this->{$column};
}
public function delegateSet($context, $column, $value)
{
if (!$this->isAllowedContext($context, $column))
throw new Centurion_Db_Exception(sprintf('Unauthorized property %s', $column));
$this->$column = $value;
}
public function delegateCall($context, $method, $args = array())
{
if (!$this->isAllowedContext($context, $method))
throw new Centurion_Db_Exception(sprintf('Unauthorized method %s', $method));
return call_user_func_array(array($this, $method), $args);
}
public function __get($property)
{
$trait = Centurion_Traits_Common::checkTraitPropertyExists($this, $property);
if (null !== $trait) {
return $trait->{$property};
}
}
public function __set($column, $value)
{
return;
}
public function __isset($column)
{
if (Centurion_Traits_Common::checkTraitPropertyExists($this, $column)) {
return true;
}
return false;
}
public function __unset($column)
{
return;
}
/**
* Sleep function. We only save the config needed to make the table again.
*/
public function __sleep()
{
return array('_config');
}
/**
* Wake up after putting in cache.
*
* @todo think multiple database
* @return void
*/
public function __wakeup()
{
if ($this->_config) {
$this->setOptions($this->_config);
}
$this->_setup();
$this->init();
if (null === $this->_meta) {
$this->_setupMeta();
}
}
/**
* Fetches all rows.
*
* Honors the Zend_Db_Adapter fetch mode.
*
* @param string|array|Zend_Db_Table_Select $where OPTIONAL An SQL WHERE clause or Zend_Db_Table_Select object.
* @param string|array $order OPTIONAL An SQL ORDER clause.
* @param int $count OPTIONAL An SQL LIMIT count.
* @param int $offset OPTIONAL An SQL LIMIT offset.
* @return Zend_Db_Table_Rowset_Abstract The row results per the Zend_Db_Adapter fetch mode.
*/
public function all($where = null, $order = null, $count = null, $offset = null)
{
return $this->fetchAll($where, $order, $count, $offset);
}
/**
* Returns an instance of a Centurion_Db_Table_Select object.
*
* @param bool $withFromPart Whether or not to include the from part of the select based on the table
* @return Centurion_Db_Table_Select
*/
public function select($withFromPart = self::SELECT_WITHOUT_FROM_PART, $applyDefaultFilters = null, $stored = false)
{
if (!$stored || null === $this->_select) {
$select = new $this->_selectClass($this);
if ($withFromPart == self::SELECT_WITH_FROM_PART) {
$select->from($this->info(self::NAME), Zend_Db_Table_Select::SQL_WILDCARD, $this->info(self::SCHEMA));
} else {
if (null === $applyDefaultFilters)
$applyDefaultFilters = self::FILTERS_OFF;
}
if (null === $applyDefaultFilters)
$applyDefaultFilters = self::$_filtersOn;
Centurion_Signal::factory('on_dbTable_select')->send($this, array($select, $applyDefaultFilters));
if (!$stored) {
return $select;
}
$this->_select = $select;
}
return $this->_select;
}
public function getSelectClass()
{
return $this->_selectClass;
}
/**
* may be override to provide a way to get a filtered select
* @return Centurion_Db_Table_Select
*/
public function preFilteredSelect()
{
return $this->select(true);
}
/**
* Retrieve information about attached table.
*
* @param string $key OPTIONAL Key
*/
public function info($key = null)
{
$this->_setupPrimaryKey();
if (null !== $key) {
switch ($key) {
case self::NAME:
return $this->_name;
case self::COLS:
return $this->_getCols();
case self::MANY_DEPENDENT_TABLES:
return $this->_manyDependentTables;
case self::SCHEMA:
return $this->_schema;
case self::PRIMARY:
$this->_setupPrimaryKey();
return (array) $this->_primary;
case self::METADATA:
return $this->_metadata;
case self::ROW_CLASS:
return $this->getRowClass();
case self::ROWSET_CLASS:
return $this->getRowsetClass();
case self::REFERENCE_MAP:
return $this->_referenceMap;
case self::DEPENDENT_TABLES:
return $this->_dependentTables;
case self::SEQUENCE:
return $this->_sequence;
}
}
return parent::info($key);
}
/**
* Insert a new row.
*
* @param array $data Column-value pairs
* @return mixed The primary key of the row inserted
*/
public function insert(array $data)
{
Centurion_Signal::factory('pre_insert')->send($this, $data);
if (in_array(self::CREATED_AT_COL, $this->_getCols()) && empty($data[self::CREATED_AT_COL])) {
$data[self::CREATED_AT_COL] = Zend_Date::now()->toString(Centurion_Date::MYSQL_DATETIME);
}
if (in_array(self::UPDATED_AT_COL, $this->_getCols()) && empty($data[self::UPDATED_AT_COL])) {
$data[self::UPDATED_AT_COL] = Zend_Date::now()->toString(Centurion_Date::MYSQL_DATETIME);
}
$retrieveRowOnInsert = false;
if (array_key_exists(self::RETRIEVE_ROW_ON_INSERT, $data)
&& $data[self::RETRIEVE_ROW_ON_INSERT] === true) {
$retrieveRowOnInsert = true;
unset($data[self::RETRIEVE_ROW_ON_INSERT]);
}
if (array_key_exists(self::VERBOSE, $data) && $data[self::VERBOSE] === false) {
$data = array_intersect_key($data, array_flip($this->info('cols')));
}
$result = parent::insert($data);
if ($retrieveRowOnInsert && null !== $result) {
$primaryValues = array();
if (is_string($result)) {
$primaryValues = array($result);
} else {
foreach($this->_primary as $primary) {
$primaryValues[] = $result[$primary];
}
}
$result = call_user_func_array(array($this, 'find'), $primaryValues)->current();
}
Centurion_Signal::factory('post_insert')->send($this, $result);
return $result;
}
/**
* Updates existing rows.
*
* @param array $data Column-value pairs
* @param array|string $where An SQL WHERE clause, or an array of SQL WHERE clauses
* @return int The number of rows updated
*/
public function update(array $data, $where)
{
Centurion_Signal::factory('pre_update')->send($this, array($data, $where));
if (in_array(self::UPDATED_AT_COL, $this->_getCols()) && empty($data[self::UPDATED_AT_COL])) {
$data[self::UPDATED_AT_COL] = Zend_Date::now()->toString(Centurion_Date::MYSQL_DATETIME);
}
$count = parent::update($data, $where);
Centurion_Signal::factory('post_update')->send($this, array($data, $where, $count));
return $count;
}
/**
* Smart save.
*
* @param array $data Associative array with row data
* @return mixed Primary key value
*/
public function save($data)
{
$this->_setupPrimaryKey();
$cols = array_intersect_key($data, array_flip($this->_getCols()));
if (array_intersect((array) $this->_primary, array_keys(array_filter($cols)))) {
if (is_array($this->_primary)) {
$a = array();
foreach ($this->_primary as $pk) {
$a[] = $cols[$pk];
}
if (count($this->_primary) != count($a)) {
throw new Centurion_Db_Table_Exception('Invalid primary key.(Primary key is composed, but incomplete)');
}
$rows = call_user_func_array(array($this , 'find'), $a);
} else {
$rows = $this->find($cols[$this->_primary]);
}
if (1 == $rows->count()) {
$pk = $rows->current()->setFromArray($cols)->save();
} elseif (0 == $rows->count()) {
$pk = $this->insert($cols);
} else {
throw new Centurion_Db_Table_Exception('Error updating requested row.(More than 1 row or invalid Id?!)');
}
} else {
$pk = $this->insert($v = array_diff_key($cols, array_flip((array) $this->_primary)));
}
return $pk;
}
/**
* Adds support for magic finders, inspired by Doctrine_Table.
*
* This method add support for calling methods not defined in code, such as:
* findByColumnName, findByRelationAlias
* findOneByColumnName, findOneByNotColumnName
* findById, findByContactId, etc.
*
* @return Centurion_Db_Table_Row|Centurion_Db_Table_Rowset The result of the finder
*/
public function __call($method, array $args)
{
$lcMethod = strtolower($method);
/**
* @deprecated : to much time consuming wihtout real gain. use $this->findOneBy('id', 1) instead of $this->findOneById(1); Preserve also autocompletion.
*/
if (substr($lcMethod, 0, 6) == 'findby') {
$by = substr($method, 6, strlen($method));
$method = '_findBy';
} else if (substr($lcMethod, 0, 9) == 'findoneby') {
$by = substr($method, 9, strlen($method));
$method = '_findOneBy';
}
if (isset($by)) {
if (!isset($args[0])) {
throw new Centurion_Db_Table_Exception('You must specify the value to ' . $method);
}
return $this->{$method}($by, $args);
}
list($found, $retVal) = Centurion_Traits_Common::checkTraitOverload($this, $method, $args);
if ($found) {
return $retVal;
}
throw new Centurion_Db_Table_Exception(sprintf("method %s does not exist", $method));
}
/**
* Generates a string representation of this object, inspired by Doctrine_Table.
*
* @TODO: this method should be refactored
* @return Centurion_Db_Table_Select
*/
protected function _buildFindByWhere($by, $values)
{
$values = (array) $values;
$ands = array();
$e = explode('And', $by);
$i = 0;
foreach ($e as $k => $v) {
$and = '';
$e2 = explode('Or', $v);
$ors = array();
foreach ($e2 as $k2 => $v2) {
$v2 = Centurion_Inflector::tableize($v2);
$fieldName = $this->_isFieldNameBelongToTable($v2);
if ($fieldName) {
if (substr($values[$i], 0, 1) == '!') {
$ors[] = $this->getAdapter()->quoteInto(sprintf('%s.%s != ?', $this->_name, $this->getAdapter()->quoteIdentifier($fieldName)), substr($values[$i], 1));
} else {
$ors[] = $this->getAdapter()->quoteInto(sprintf('%s.%s = ?', $this->_name, $this->getAdapter()->quoteIdentifier($fieldName)), $values[$i]);
}
$i++;
} else {
throw new Centurion_Db_Table_Exception(str_replace('{__FIELDNAME__}', $v2, Centurion_Db_Table_Exception::FIELDNAME_NOT_BELONG));
}
}
$and .= implode(' OR ', $ors);
$and = count($ors) > 1 ? '(' . $and . ')':$and;
$ands[] = $and;
}
$where = implode(' AND ', $ands);
return $this->select()
->where($where);
}
/**
* Find a reference with a column name.
*
* @param string $columnName Column name to search
* @return array|boolean The reference map entry
*/
public function getReferenceByColumnName($columnName)
{
$references = $this->_getReferenceMapNormalized();
foreach ($references as $key => $value) {
if (!in_array($columnName, $value[self::COLUMNS])) {
continue;
}
return $value[self::REF_TABLE_CLASS];
}
return false;
}
/**
* Retrieve a referenceMap entry with its key name or all referenceMaps if not key is given.
*
* @param string $name Key name
* @return array
* @throws Centurion_Db_Exception When the referenceMap key does not exist
*/
public function getReferenceMap($name = null, $throwException = true)
{
if (null !== $name) {
if (!array_key_exists($name, $this->_referenceMap)) {
if (true === $throwException) {
throw new Centurion_Db_Exception(sprintf('referenceMap key "%s" does not exist', $name));
} else {
return false;
}
}
return $this->_referenceMap[$name];
}
return $this->_referenceMap;
}
/**
*
* @param string $cond The WHERE condition.
* @param mixed $value OPTIONAL The value to quote into the condition.
* @param constant $type OPTIONAL The type of the given value
* @return string
*/
public function rowsCount($condition = null, $value = null, $type = null)
{
if ($condition instanceof Centurion_Db_Table_Select) {
$select = $condition;
} else {
$select = $this->select()
->from($this->_name, 'COUNT(*)');
if (null !== $condition)
$select->where($condition, $value, $type);
}
return $this->getAdapter()->fetchOne($select);
}
/**
* Deletes existing rows.
*
* @param array|string $where SQL WHERE clause(s).
* @return int The number of rows deleted.
*/
public function delete($where)
{
Centurion_Signal::factory('pre_delete')->send($this, array($where));
list($found, $return) = Centurion_Traits_Common::checkTraitOverload($this, 'delete', array($where));
if (!$found) {
$return = parent::delete($where);
}
Centurion_Signal::factory('post_delete')->send($this, array($where));
return $return;
}
public function getCacheTag()
{
return sprintf('__%s', $this->info(Centurion_Db_Table_Abstract::NAME));
}
/**
* Deletes existing rows.
*
* @param array|string $where SQL WHERE clause(s).
* @return int The number of rows deleted.
*/
public function deleteRow($where)
{
$rowSet = $this->_where($this->select(true), $where)->fetchAll();
$return = true;
foreach ($rowSet as $row) {
$return &= $row->delete();
}
return $return;
}
/**
* Proxy method for rowsCount
*
* @param string $cond The WHERE condition.
* @param mixed $value OPTIONAL The value to quote into the condition.
* @param constant $type OPTIONAL The type of the given value
* @return string
*/
public function count($condition = null, $value = null, $type = null)
{
return $this->rowsCount($condition, $value, $type);
}
/**
* Returns a list of date objects with their count representing all available dates for
* the given fieldName, scoped to 'kind'.
*
* @param string $fieldName
* @param string $kind
* @param string $order
* @return void
*/
public function dates($fieldName, $kind, $order = 'ASC')
{
if (!in_array($kind, array_keys(self::$_kinds))) {
throw new Centurion_Db_Exception("'kind' must be one of 'year', 'month' or 'day'.");
}
if (!in_array($order, array('ASC', 'DESC'))) {
throw new Centurion_Db_Exception("'order' must be either 'ASC' or 'DESC'.");
}
return $this->select()
->distinct()
->from(array('p' => $this->info('name')),
array(
'date' => new Zend_Db_Expr("CAST(DATE_FORMAT(" . $fieldName . ", '" . self::$_kinds[$kind] . " 00:00:00') AS DATETIME)"),
'count' => new Zend_Db_Expr("COUNT(*)")))
->group('date')
->order(sprintf('%s %s', $fieldName, $order));
}
/**
* Looks up an object with the given kwargs, creating one if necessary.
* Returns a tuple of (object, created), where created is a boolean
* specifying whether an object was created.
*
* @param array $kwargs
* @return array
*/
public function getOrCreate(array $kwargs)
{
try {
return array($this->get($kwargs), false);
} catch (Centurion_Db_Table_Row_Exception_DoesNotExist $e) {
$row = $this->createRow($kwargs);
$row->save();
return array($row, true);
}
}
/**
* Looks up an object with the given kwargs, creating one if necessary.
* Returns a true if created, false if already exist.
*
* @param array $kwargs
* @todo use insert ignore (or alternative) when SGBD is compatible
* @return bool
*/
public function insertIfNotExist(array $kwargs)
{
list(, $created) = $this->getOrCreate($kwargs);
return $created;
}
/**
* Performs the query and returns a single object matching the given
* keyword arguments.
*
* @param array $kwargs
* @todo raise an exception when two result set is returned
* @return void
*/
public function get(array $kwargs)
{
$object = $this->filter($kwargs);
//Zend_Debug::dump($object);
$num = $object->count();
if ($num === 1) {
return $object->current();
}
if (!$num) {
throw new Centurion_Db_Table_Row_Exception_DoesNotExist(sprintf("%s matching query does not exist.", get_class($this)));
}
throw new Centurion_Db_Table_Row_Exception_MultipleObjectsReturned(sprintf("get() returned more than one %s -- it returned %s! Lookup parameters were %s",
get_class($this), $num, json_encode($kwargs)));
}
/**
* Returns a new Zend_Db_Select instance with the args ANDed to the existing
* set.
* If the first character of the column name is '!', it will set a WHERE NOT clause.
* If the value is null, it will set a WHERE IS NULL clause.
*
* @param array $kwargs
* @todo add new fonctionalities, see django.db.models.query
* @return void
*/
public function filter(array $kwargs, $select = null)
{
if (null === $select) {
$select = $this->select(true);
}
return $select->filter($kwargs)->fetchAll();
}
/**
* Called by parent table's class during delete() method.
*
* @param string $parentTableClassname
* @param array $primaryKey
* @return int Number of affected rows
*/
public function _cascadeDelete($parentTableClassname, array $primaryKey)
{
$this->_setupMetadata();
$rowsAffected = 0;
foreach ($this->_getReferenceMapNormalized() as $map) {
if ($map[self::REF_TABLE_CLASS] == $parentTableClassname && isset($map[self::ON_DELETE])) {
switch ($map[self::ON_DELETE]) {
case self::CASCADE:
$where = array();
for ($i = 0, $count = count($map[self::COLUMNS]); $i < $count; ++$i) {
$col = $this->_db->foldCase($map[self::COLUMNS][$i]);
$refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
$type = $this->_metadata[$col]['DATA_TYPE'];
$where[] = $this->_db->quoteInto(
sprintf('%s.%s = ?', $this->_db->quoteIdentifier($this->_name), $this->_db->quoteIdentifier($col, true)),
$primaryKey[$refCol], $type
);
}
/*
* Fix : Suround, in the implode, AND with withspaces because if the relation is build with several key
* the implode returned : "myKey=XANDmySecondKey=Y" instead of "myKey=X AND mySecondKey=Y"
*/
foreach ($this->fetchAll(implode(' AND ', $where)) as $row) {
$rowsAffected += $row->delete();
}
// old way but it's not trapped by the row, and if you have routines in your delete method of your row...
// $rowsAffected += $this->delete($where);
break;
case self::SET_NULL:
for ($i = 0, $count = count($map[self::COLUMNS]); $i < $count; ++$i) {
$col = $this->_db->foldCase($map[self::COLUMNS][$i]);
$refCol = $this->_db->foldCase($map[self::REF_COLUMNS][$i]);
$type = $this->_metadata[$col]['DATA_TYPE'];
$where = $this->_db->quoteInto(
sprintf('%s.%s = ?', $this->_db->quoteIdentifier($this->_name), $this->_db->quoteIdentifier($col, true)),
$primaryKey[$refCol], $type);
$rowsAffected += $this->update(array($col => null), $where);
}
break;
default:
// no action
break;
}
}
}
return $rowsAffected;
}
/**
* Set meta information.
*
* @param array $values Values
* @return Centurion_Db_Table_Abstract
*/
public function setMeta(array $values)
{
$this->_meta = $values;
return $this;
}
/**
* Get meta information.
*
* @return array
*/
public function getMeta()
{
return $this->_meta;
}
/**
* Get Many dependent tables.
*
* @return array
*/
public function getManyDependentTables()
{
return $this->_manyDependentTables;
}
/**
* Get a random row.
*
* @param Zend_Db_Table_Select|array $select The select used to process the query
* @return Centurion_Db_Table_Row_Abstract
*/
public function random($where = null)
{
if (!($where instanceof Zend_Db_Select)) {
$select = $this->select(true);
$select = $this->_where($select, $where);
} else {
$select = $where;
$where = null;
}
$select = $select->order(new Zend_Db_Expr('RAND()'));
return $select->fetchRow();
}
public function getCountsSelect ($groupby, $filter = null, $order = null, $limit = null)
{
if ($filter instanceof Centurion_Db_Table_Select) {
$select = $filter;
$filter = array();
} else {
$select = $this->select(true);
$filter = (array) $filter;
}
if (!in_array($groupby, $this->info(Centurion_Db_Table_Abstract::COLS)) && !$select->hasColumn($groupby)) {
$select->setIntegrityCheck(false);
$col = new Zend_Db_Expr($select->addRelated($groupby));
$select->columns($col);
} else {
$col = $groupby;
}
$select->group($col);
$select->columns(array('_nb' => new Zend_Db_Expr('COUNT(*)')));
if (null !== $filter)
$select->filter($filter);
if ($limit)
$select->limit($limit);
if ($order)
$select->order($order);
// $select->order(new Zend_Db_Expr('_nb DESC'));
return $select;
}
public function getCounts($groupby, $filter = null, $order = null, $limit = null)
{
$select = $this->getCountsSelect($groupby, $filter, $order, $limit);
return $select->count();
}
/**
* Get the cached table.
*
* @param string $frontendOptions
* @param string $backendOptions
* @param string $backendName
* @return Centurion_Db_Cache
*/
public function getCache($frontendOptions = null, $backendOptions = null, $backendName = null)
{
if (null === $this->_cache) {
if (null === $frontendOptions) {
$frontendOptions = self::$_defaultFrontendOptions;
}
if (null === $backendOptions) {
$backendOptions = self::$_defaultBackendOptions;
}
$this->_cache = new Centurion_Db_Cache($this, $frontendOptions, $backendOptions, $backendName);
}
return $this->_cache;
}
/**
* Retrieve the default backend options for all tables.
*
* @return array
*/
public static function getDefaultBackendOptions()
{
return self::$_defaultBackendOptions;
}
/**
* Retrieve the default frontend options for all tables.
*
* @return array
*/
public static function getDefaultFrontendOptions()
{
return self::$_defaultFrontendOptions;
}
/**
* Set the default backend options for all tables.
*
* @param array $options
* @return void
*/
public static function setDefaultBackendOptions(array $options = array())
{
self::$_defaultBackendOptions = $options;
}
/**
* Set the default frontend options for all tables.
*
* @param array $options
* @return void
*/
public static function setDefaultFrontendOptions(array $options = array())
{
self::$_defaultFrontendOptions = $options;
}
/**
* Setup meta information.
*
* @return Centurion_Db_Table_Abstract
*/
protected function _setupMeta()
{
$name = explode('_', $this->_name);
$verboseName = implode('_', array_splice($name, 1));
$this->setMeta(array(
'verboseName' => $verboseName,
'verbosePlural'=> sprintf('%s_set', $verboseName)
));
return $this;
}
/**
* @deprecated use public function findOneBy instead
*/
protected function _findOneBy($fieldName, $values)
{
return $this->findOneBy($fieldName, $values);
}
/**
* Find a row with a formatted field name.
*
* @param string $fieldName Formatted field name
* @param array $values Values
*/
public function findOneBy($fieldName, $values)
{
return $this->fetchRow($this->_buildFindByWhere($fieldName, $values));
}
/**
* Find a rowset with a formatted field name.
*
* @param string $fieldName Formatted field name
* @param array $values Values
*/
public function findBy($fieldName, $values)
{
return $this->fetchAll($this->_buildFindByWhere($fieldName, $values));
}
/**
* @deprecated use public function findBy instead
*/
protected function _findBy($fieldName, $values)
{
return $this->findBy($fieldName, $values);
}
/**
* Check if a field name belongs to the table.
*
* @param string $fieldName
* @return boolean|string False if the field doesn't belong to the table, otherwise, tableized field
*/
protected function _isFieldNameBelongToTable($fieldName)
{
$fieldName = Centurion_Inflector::tableize($fieldName);
if (in_array($fieldName, $this->_getCols()))
return $fieldName;
return false;
}
/**
* Proxy function to test _genRefRuleName
* @see Centurion_Db_Table_TableTest
* @param string $base
* @return string
*/
public function testGenRefRuleName($base)
{
return $this->_genRefRuleName($base);
}
/**
* generate a new name for a reference rule (guarantee name uniqness)
* @param string $base desired name for the rule if it is already taken a suffix will be added
*/
protected function _genRefRuleName($base)
{
if ('' == trim($base))
$base = uniqid();
$refMapRule = $base;
$i = 1;
$existingRefRules = array();
$mergeAllRefs = array_merge($this->getReferenceMap(), $this->getDependentTables(), $this->getManyDependentTables());
foreach ($mergeAllRefs as $key => $val) {
if (!is_int($key)) {
$existingRefRules[$key] = true;
}
}
while (isset($existingRefRules[$refMapRule])) {
$refMapRule = sprintf('%s_%u', $base, $i);
$i++;
}
return $refMapRule;
}
public function getTestCondition()
{
return null;
}
}
| Sparfel/iTop-s-Portal | library/Centurion/Db/Table/Abstract.php | PHP | agpl-3.0 | 36,806 |
<?php
/**
*
* bareos-webui - Bareos Web-Frontend
*
* @link https://github.com/bareos/bareos-webui for the canonical source repository
* @copyright Copyright (c) 2013-2014 Bareos GmbH & Co. KG (http://www.bareos.org/)
* @license GNU Affero General Public License (http://www.gnu.org/licenses/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class StatusGlyphicons extends AbstractHelper
{
public function __invoke($status)
{
switch($status)
{
case '0':
$output = '<div class="text-success"><span class="glyphicon glyphicon-ok"></span></div>';
break;
case '-1':
$output = '<div class="text-danger"><span class="glyphicon glyphicon-remove"></span></div>';
break;
default:
$output = $status;
break;
}
return $output;
}
}
| syllaibr64/bareos-webui | module/Application/src/Application/View/Helper/StatusGlyphicons.php | PHP | agpl-3.0 | 1,516 |
import { SortMeta } from 'primeng/api'
import { Directive, OnInit, ViewChild } from '@angular/core'
import { Notifier, RestPagination, RestTable } from '@app/core'
import { BatchDomainsModalComponent } from '@app/shared/shared-moderation/batch-domains-modal.component'
import { ServerBlock } from '@shared/models'
import { BlocklistComponentType, BlocklistService } from './blocklist.service'
@Directive()
// eslint-disable-next-line @angular-eslint/directive-class-suffix
export class GenericServerBlocklistComponent extends RestTable implements OnInit {
@ViewChild('batchDomainsModal') batchDomainsModal: BatchDomainsModalComponent
// @ts-expect-error: "Abstract methods can only appear within an abstract class"
public abstract mode: BlocklistComponentType
blockedServers: ServerBlock[] = []
totalRecords = 0
sort: SortMeta = { field: 'createdAt', order: -1 }
pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
constructor (
protected notifier: Notifier,
protected blocklistService: BlocklistService
) {
super()
}
// @ts-expect-error: "Abstract methods can only appear within an abstract class"
public abstract getIdentifier (): string
ngOnInit () {
this.initialize()
}
unblockServer (serverBlock: ServerBlock) {
const operation = (host: string) => this.mode === BlocklistComponentType.Account
? this.blocklistService.unblockServerByUser(host)
: this.blocklistService.unblockServerByInstance(host)
const host = serverBlock.blockedServer.host
operation(host).subscribe(
() => {
this.notifier.success(
this.mode === BlocklistComponentType.Account
? $localize`Instance ${host} unmuted.`
: $localize`Instance ${host} unmuted by your instance.`
)
this.reloadData()
}
)
}
addServersToBlock () {
this.batchDomainsModal.openModal()
}
onDomainsToBlock (domains: string[]) {
const operation = (domain: string) => this.mode === BlocklistComponentType.Account
? this.blocklistService.blockServerByUser(domain)
: this.blocklistService.blockServerByInstance(domain)
domains.forEach(domain => {
operation(domain).subscribe(
() => {
this.notifier.success(
this.mode === BlocklistComponentType.Account
? $localize`Instance ${domain} muted.`
: $localize`Instance ${domain} muted by your instance.`
)
this.reloadData()
}
)
})
}
protected reloadData () {
const operation = this.mode === BlocklistComponentType.Account
? this.blocklistService.getUserServerBlocklist({
pagination: this.pagination,
sort: this.sort,
search: this.search
})
: this.blocklistService.getInstanceServerBlocklist({
pagination: this.pagination,
sort: this.sort,
search: this.search
})
return operation.subscribe({
next: resultList => {
this.blockedServers = resultList.data
this.totalRecords = resultList.total
},
error: err => this.notifier.error(err.message)
})
}
}
| Chocobozzz/PeerTube | client/src/app/shared/shared-moderation/server-blocklist.component.ts | TypeScript | agpl-3.0 | 3,158 |
<!DOCTYPE html>
<html>
<head>
<title>mySQL - UTENTI</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="keywords" content="docenti, scuola secondaria, Trentino, ore, database, articoli, recupero">
<meta name="description" content="sito per la registrazione delle attività aggiuntive svolte a scuola">
<meta name="author" content="Alessandro Vallin">
<link rel="stylesheet" href="css/kube.min.css" />
<link rel="stylesheet" href="css/stile.css" />
<link rel="icon" href="img/clip.ico" />
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="js/kube.min.js"></script>
<script src="sorttable.js"></script>
</head>
<?
session_start();
session_regenerate_id(TRUE);
if (!isset($_SESSION['username'] ) )
{
header('location:index.php');
exit;
}
else
{
echo '<a href="logout.php"><right><img src="img/out.png" width="55" height="55" title="logout" align="right"></right></a><br>'."utente collegato: ".$_SESSION['username'].'<br>'."oggi è il giorno: ".date("d-m-y");
}
?>
<body>
<div class="units-row">
<div class="unit-centered unit-80">
<br><br>
<div class="tools-alert tools-alert-blue" align="left">
Torna alla <a href="db.php">pagina precedente</a>
</div>
<h3 align="center">mySQL - tabella UTENTI</h3>
<br>
Si possono <font color="#7094FF"><b>ordinare i dati</b></font> in modo diverso cliccando sulle celle dell'intestazione.
<br><br>
<?
$objConnect = mysql_connect("","","") or die("Impossibile selezionare il database");
$objDB = mysql_select_db("my_daado");
$strSQL = ("SELECT * FROM utenti WHERE username!='sudo' ORDER BY scuola,cognome,nome,username asc ");
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?>
<div class="table-container" align="center">
<table class="table-hovered sortable">
<tr>
<th class="text-centered highlight">titolo</th>
<th class="text-centered highlight">nome</th>
<th class="text-centered highlight">cognome</th>
<th class="text-centered highlight">scuola</th>
<th class="text-centered highlight">materia</th>
<th class="text-centered highlight">username</th>
<th class="text-centered highlight">password</th>
<th class="text-centered highlight">active</th>
<th class="text-centered highlight">accesso</th>
<th colspan="2" class="text-centered sorttable_nosort"></th>
</tr>
<?
while($objResult = mysql_fetch_array($objQuery))
{
?>
<tr>
<td class="text-centered"><?=$objResult["titolo"];?></td>
<td class="text-centered"><?=$objResult["nome"];?></td>
<td class="text-centered"><?=$objResult["cognome"];?></td>
<td class="text-centered"><?=$objResult["scuola"];?></td>
<td class="text-centered"><?=$objResult["materia"];?></td>
<td class="text-centered"><?=$objResult["username"];?></td>
<td class="text-centered"><?=$objResult["password"];?></td>
<td class="text-centered"><?=$objResult["active"];?></td>
<td class="text-centered"><?=$objResult["accesso"];?></td>
<td class="text-centered"><a href="mod_utente.php?id=<?=$objResult["id"];?>"><img src="img/update.gif" width="29" height="20" title="modifica" onclick="return confirm('Vuoi davvero modificare questi dati?')"></a></td>
<td class="text-centered"><a href="can_utente.php?id=<?=$objResult["id"];?>"><img src="img/bin.png" width="19" height="20" title="cancella" onclick="return confirm('Vuoi davvero cancellare questi dati?')"></a></td>
</tr>
<?
}
?>
</table>
</div>
<?
mysql_close($objConnect);
?>
</div>
</div>
</body>
</html>
| aletrento/daado | db_utenti.php | PHP | agpl-3.0 | 3,503 |
# Copyright 2020 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
{
"name": "Product Template Attribute Value Menu",
"version": "12.0.1.1.0",
"license": "AGPL-3",
"author": "AvanzOSC",
"website": "http://www.avanzosc.es",
"category": "Sales",
"depends": [
"stock",
"sale_management"
],
"data": [
"security/product_template_attribute_value_menu_rules.xml",
"views/product_template_attribute_value_view.xml",
],
"installable": True,
}
| oihane/odoo-addons | product_template_attribute_value_menu/__manifest__.py | Python | agpl-3.0 | 558 |
<?php
//============================================================+
// File name : bel.php
// Begin : 2010-10-26
// Last Update : 2010-10-26
//
// Description : Language module for TCPDF
// (contains translated texts)
// Basque
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// Manor Coach House, Church Hill
// Aldershot, Hants, GU12 4RQ
// UK
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* TCPDF language file (contains translated texts).
* @package com.tecnick.tcpdf
* @brief TCPDF language file: Basque
* @since 2010-10-26
*/
// Basque
global $l;
$l = Array();
// PAGE META DESCRIPTORS --------------------------------------
$l['a_meta_charset'] = 'UTF-8';
$l['a_meta_dir'] = 'ltr';
$l['a_meta_language'] = 'be';
// TRANSLATIONS --------------------------------------
$l['w_page'] = 'старонкі';
//============================================================+
// END OF FILE
//============================================================+
| culturagovbr/CEUs | includes/tcpdf/config/lang/bel.php | PHP | agpl-3.0 | 1,196 |
# -*- coding: utf-8 -*-
# See README file for full copyright and licensing details.
from . import sale
from . import delivery
| rgbconsulting/rgb-sale | delivery_sale_cost/models/__init__.py | Python | agpl-3.0 | 127 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2016 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import org.voltdb.AuthSystem.AuthUser;
import org.voltdb.catalog.Procedure;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltdb.common.Permission;
import org.voltdb.utils.LogKeys;
/**
* Checks if a user has permission to call a procedure.
*/
public class InvocationSysprocPermissionPolicy extends InvocationPermissionPolicy {
private static final VoltLogger authLog = new VoltLogger("AUTH");
public InvocationSysprocPermissionPolicy() {
}
/**
*
* @param user whose permission needs to be checked.
* @param invocation invocation associated with this request
* @param proc procedure associated.
* @return PolicyResult ALLOW, DENY or NOT_APPLICABLE
* @see org.voltdb.InvocationAcceptancePolicy#shouldAccept(org.voltdb.AuthSystem.AuthUser,
* org.voltdb.StoredProcedureInvocation, org.voltdb.catalog.Procedure,
* org.voltcore.network.WriteStream)
*/
@Override
public PolicyResult shouldAccept(AuthUser user, StoredProcedureInvocation invocation, Procedure proc) {
//Since AdHoc perms are diff we only check sysprocs other than AdHoc
if (proc.getSystemproc() && !invocation.procName.startsWith("@AdHoc")) {
if (!user.hasPermission(Permission.ADMIN) && !proc.getReadonly()) {
return PolicyResult.DENY;
}
return PolicyResult.ALLOW;
}
return PolicyResult.NOT_APPLICABLE;
}
@Override
public ClientResponseImpl getErrorResponse(AuthUser user, StoredProcedureInvocation invocation, Procedure procedure) {
authLog.l7dlog(Level.INFO,
LogKeys.auth_ClientInterface_LackingPermissionForSysproc.name(),
new String[] { user.m_name, invocation.procName },
null);
return new ClientResponseImpl(ClientResponseImpl.UNEXPECTED_FAILURE,
new VoltTable[0],
"User " + user.m_name + " does not have admin permission",
invocation.clientHandle);
}
}
| paulmartel/voltdb | src/frontend/org/voltdb/InvocationSysprocPermissionPolicy.java | Java | agpl-3.0 | 2,820 |
/**
*
* @param viewMode
* @constructor
*/
function ComboBoxControl( viewMode ) {
_.superClass( ListBoxControl, this, viewMode );
}
_.inherit( ComboBoxControl, ListEditorBaseControl );
_.extend( ComboBoxControl.prototype, {
/**
*
* @returns {ComboBoxModel}
*/
createControlModel: function() {
return new ComboBoxModel();
},
/**
*
* @param model
* @returns {ComboBoxView}
*/
createControlView: function( model ) {
return new ComboBoxView( { model: model } );
},
/**
*
* @param message
*/
setNoItemsMessage: function( message ) {
this.controlModel.setNoItemsMessage( message );
}
} );
InfinniUI.ComboBoxControl = ComboBoxControl;
| InfinniPlatform/InfinniUI | app/controls/comboBox/comboBoxControl.js | JavaScript | agpl-3.0 | 752 |
{{ Form::open(array('url' => URL::route('contact.post'), 'method' => 'POST', 'class' => 'form-horizontal')) }}
<div class="form-group{{ ($errors->has('first_name')) ? ' has-error' : '' }}">
<label class="col-md-2 col-sm-3 col-xs-10 control-label" for="first_name">First Name</label>
<div class="col-lg-3 col-md-4 col-sm-5 col-xs-10">
<input name="first_name" id="first_name" value="{{ Request::old('first_name') }}" type="text" class="form-control" placeholder="First Name">
{{ ($errors->has('first_name') ? $errors->first('first_name') : '') }}
</div>
</div>
<div class="form-group{{ ($errors->has('last_name')) ? ' has-error' : '' }}">
<label class="col-md-2 col-sm-3 col-xs-10 control-label" for="last_name">Last Name</label>
<div class="col-lg-3 col-md-4 col-sm-5 col-xs-10">
<input name="last_name" id="last_name" value="{{ Request::old('last_name') }}" type="text" class="form-control" placeholder="Last Name">
{{ ($errors->has('last_name') ? $errors->first('last_name') : '') }}
</div>
</div>
<div class="form-group{{ ($errors->has('email')) ? ' has-error' : '' }}">
<label class="col-md-2 col-sm-3 col-xs-10 control-label" for="email">Email</label>
<div class="col-lg-3 col-md-4 col-sm-5 col-xs-10">
<input name="email" id="email" value="{{ Request::old('email') }}" type="text" class="form-control" placeholder="Email">
{{ ($errors->has('email') ? $errors->first('email') : '') }}
</div>
</div>
<div class="form-group{{ ($errors->has('message')) ? ' has-error' : '' }}">
<label class="col-md-2 col-sm-3 col-xs-10 control-label" for="message">Message</label>
<div class="col-lg-6 col-md-8 col-sm-9 col-xs-12">
<textarea name="message" id="message" class="form-control" placeholder="Message" rows="8">{{ Request::old('message') }}</textarea>
{{ ($errors->has('message') ? $errors->first('message') : '') }}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-sm-offset-3 col-sm-10 col-xs-12">
<button class="btn btn-primary" type="submit"><i class="fa fa-rocket"></i> Submit</button>
<button class="btn btn-inverse" type="reset">Reset</button>
</div>
</div>
{{ Form::close() }}
| GrahamDeprecated/CMS-Contact | src/views/form.blade.php | PHP | agpl-3.0 | 2,362 |
class AddDzInfoToEvents < ActiveRecord::Migration
def change
add_column :events, :dz_info, :text
end
end
| skyderby/skyderby | db/migrate/20140902053906_add_dz_info_to_events.rb | Ruby | agpl-3.0 | 113 |
/**
* The tab view stacks several pages above each other and allows to switch
* between them by using a list of buttons.
*
* The buttons are positioned on one of the tab view's edges.
*
* *Example*
*
* Here is a little example of how to use the widget.
*
* <pre class='javascript'>
* var tabView = new qx.ui.tabview.TabView();
*
* var page1 = new qx.ui.tabview.Page("Layout", "icon/16/apps/utilities-terminal.png");
* page1.setLayout(new qx.ui.layout.VBox());
* page1.add(new qx.ui.basic.Label("Page Content"));
* tabView.add(page1);
*
* var page2 = new qx.ui.tabview.Page("Notes", "icon/16/apps/utilities-notes.png");
* tabView.add(page2);
*
* this.getRoot().add(tabView);
* </pre>
*
* This example builds a tab view with two pages called "Layout" and "Notes".
* Each page is a container widget, which can contain any other widget. Note
* that the pages need layout to render their children.
*
* *External Documentation*
*
* <a href='http://manual.qooxdoo.org/1.4/pages/widget/tabview.html' target='_blank'>
* Documentation of this widget in the qooxdoo manual.</a>
*/
| Seldaiendil/meyeOS | devtools/qooxdoo-1.5-sdk/framework/source/class/qx/ui/tabview/__init__.js | JavaScript | agpl-3.0 | 1,118 |
/*
* Copyright (C) 2015 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdexcept>
#include <cstdlib>
#include <boost/range/algorithm/find_if.hpp>
#include <seastar/core/align.hh>
#include <seastar/core/bitops.hh>
#include <seastar/core/byteorder.hh>
#include <seastar/core/fstream.hh>
#include "../compress.hh"
#include "compress.hh"
#include "unimplemented.hh"
#include "segmented_compress_params.hh"
#include "utils/class_registrator.hh"
namespace sstables {
extern logging::logger sstlog;
enum class mask_type : uint8_t {
set,
clear
};
// size_bits cannot be >= 64
static inline uint64_t make_mask(uint8_t size_bits, uint8_t offset, mask_type t) noexcept {
const uint64_t mask = ((1 << size_bits) - 1) << offset;
return t == mask_type::set ? mask : ~mask;
}
/*
* ----> memory addresses
* MSB LSB
* | | | | |3|2|1|0| CPU integer (big or little endian byte order)
* -------
* |
* +-----+ << shift = prefix bits
* |
* -------
* 7 6 5 4 3 2 1 0 index*
* | |3|2|1|0| | | | raw storage (unaligned, little endian byte order)
* = ------- =====
* | |
* | +-> prefix bits
* +-> suffix bits
*
* |0|1|1|1|1|0|0|0| read/write mask
*
* * On big endian systems the indices in storage are reversed and
* run left to right: 0 1 .. 6 7. To avoid differences in the
* encoding logic on machines with different native byte orders
* reads and writes to storage must be explicitly little endian.
*/
struct bit_displacement {
uint64_t shift;
uint64_t mask;
};
inline bit_displacement displacement_for(uint64_t prefix_bits, uint8_t size_bits, mask_type t) {
return {prefix_bits, make_mask(size_bits, prefix_bits, t)};
}
std::pair<bucket_info, segment_info> params_for_chunk_size(uint32_t chunk_size) {
const uint8_t chunk_size_log2 = log2ceil(chunk_size);
auto it = boost::find_if(bucket_infos, [&] (const bucket_info& bi) {
return bi.chunk_size_log2 == chunk_size_log2;
});
// This scenario should be so rare that we only fall back to a safe
// set of parameters, not optimal ones.
if (it == bucket_infos.end()) {
const uint8_t data_size = bucket_infos.front().best_data_size_log2;
return {{chunk_size_log2, data_size, (8 * bucket_size - 56) / data_size},
{chunk_size_log2, data_size, uint8_t(1)}};
}
auto b = *it;
auto s = *boost::find_if(segment_infos, [&] (const segment_info& si) {
return si.data_size_log2 == b.best_data_size_log2 && si.chunk_size_log2 == b.chunk_size_log2;
});
return {std::move(b), std::move(s)};
}
uint64_t compression::segmented_offsets::read(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits) const {
const uint64_t offset_byte = offset_bits / 8;
uint64_t value = seastar::read_le<uint64_t>(_storage[bucket_index].storage.get() + offset_byte);
const auto displacement = displacement_for(offset_bits % 8, size_bits, mask_type::set);
value &= displacement.mask;
value >>= displacement.shift;
return value;
}
void compression::segmented_offsets::write(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits, uint64_t value) {
const uint64_t offset_byte = offset_bits / 8;
uint64_t old_value = seastar::read_le<uint64_t>(_storage[bucket_index].storage.get() + offset_byte);
const auto displacement = displacement_for(offset_bits % 8, size_bits, mask_type::clear);
value <<= displacement.shift;
if ((~displacement.mask | value) != ~displacement.mask) {
throw std::invalid_argument(format("{}: to-be-written value would overflow the allocated bits", __FUNCTION__));
}
old_value &= displacement.mask;
value |= old_value;
seastar::write_le(_storage[bucket_index].storage.get() + offset_byte, value);
}
void compression::segmented_offsets::state::update_position_trackers(std::size_t index, uint16_t segment_size_bits,
uint32_t segments_per_bucket, uint8_t grouped_offsets) {
if (_current_index != index - 1) {
_current_index = index;
const uint64_t current_segment_index = _current_index / grouped_offsets;
_current_bucket_segment_index = current_segment_index % segments_per_bucket;
_current_segment_relative_index = _current_index % grouped_offsets;
_current_bucket_index = current_segment_index / segments_per_bucket;
_current_segment_offset_bits = (_current_bucket_segment_index % segments_per_bucket) * segment_size_bits;
} else {
++_current_index;
++_current_segment_relative_index;
// Crossed segment boundary.
if (_current_segment_relative_index == grouped_offsets) {
++_current_bucket_segment_index;
_current_segment_relative_index = 0;
// Crossed bucket boundary.
if (_current_bucket_segment_index == segments_per_bucket) {
++_current_bucket_index;
_current_bucket_segment_index = 0;
_current_segment_offset_bits = 0;
} else {
_current_segment_offset_bits += segment_size_bits;
}
}
}
}
void compression::segmented_offsets::init(uint32_t chunk_size) {
assert(chunk_size != 0);
_chunk_size = chunk_size;
const auto params = params_for_chunk_size(chunk_size);
sstlog.trace(
"{} {}(): chunk size {} (log2)",
fmt::ptr(this),
__FUNCTION__,
static_cast<int>(params.first.chunk_size_log2));
_grouped_offsets = params.second.grouped_offsets;
_segment_base_offset_size_bits = params.second.data_size_log2;
_segmented_offset_size_bits = static_cast<uint64_t>(log2ceil((_chunk_size + 64) * (_grouped_offsets - 1)));
_segment_size_bits = _segment_base_offset_size_bits + (_grouped_offsets - 1) * _segmented_offset_size_bits;
_segments_per_bucket = params.first.segments_per_bucket;
}
uint64_t compression::segmented_offsets::at(std::size_t i, compression::segmented_offsets::state& s) const {
if (i >= _size) {
throw std::out_of_range(format("{}: index {} is out of range", __FUNCTION__, i));
}
s.update_position_trackers(i, _segment_size_bits, _segments_per_bucket, _grouped_offsets);
const uint64_t bucket_base_offset = _storage[s._current_bucket_index].base_offset;
const uint64_t segment_base_offset = bucket_base_offset + read(s._current_bucket_index, s._current_segment_offset_bits, _segment_base_offset_size_bits);
if (s._current_segment_relative_index == 0) {
return segment_base_offset;
}
return segment_base_offset
+ read(s._current_bucket_index,
s._current_segment_offset_bits + _segment_base_offset_size_bits + (s._current_segment_relative_index - 1) * _segmented_offset_size_bits,
_segmented_offset_size_bits);
}
void compression::segmented_offsets::push_back(uint64_t offset, compression::segmented_offsets::state& s) {
s.update_position_trackers(_size, _segment_size_bits, _segments_per_bucket, _grouped_offsets);
if (s._current_bucket_index == _storage.size()) {
_storage.push_back(bucket{_last_written_offset, std::unique_ptr<char[]>(new char[bucket_size])});
}
const uint64_t bucket_base_offset = _storage[s._current_bucket_index].base_offset;
if (s._current_segment_relative_index == 0) {
write(s._current_bucket_index, s._current_segment_offset_bits, _segment_base_offset_size_bits, offset - bucket_base_offset);
} else {
const uint64_t segment_base_offset = bucket_base_offset + read(s._current_bucket_index, s._current_segment_offset_bits, _segment_base_offset_size_bits);
write(s._current_bucket_index,
s._current_segment_offset_bits + _segment_base_offset_size_bits + (s._current_segment_relative_index - 1) * _segmented_offset_size_bits,
_segmented_offset_size_bits,
offset - segment_base_offset);
}
_last_written_offset = offset;
++_size;
}
/**
* Thin wrapper type around a "compressor" object.
* This is the non-shared part of sstable compression,
* since the compressor might have both dependents and
* semi-state that cannot be shared across shards.
*
* The local state is instantiated in either
* reader/writer object for the sstable on demand,
* typically based on the shared compression
* info/table schema.
*/
class local_compression {
compressor_ptr _compressor;
public:
local_compression()= default;
local_compression(const compression&);
local_compression(compressor_ptr);
size_t uncompress(const char* input, size_t input_len, char* output,
size_t output_len) const;
size_t compress(const char* input, size_t input_len, char* output,
size_t output_len) const;
size_t compress_max_size(size_t input_len) const;
operator bool() const {
return _compressor != nullptr;
}
const compressor_ptr& compressor() const {
return _compressor;
}
};
local_compression::local_compression(compressor_ptr p)
: _compressor(std::move(p))
{}
local_compression::local_compression(const compression& c)
: _compressor([&c] {
sstring n(c.name.value.begin(), c.name.value.end());
return compressor::create(n, [&c, &n](const sstring& key) -> compressor::opt_string {
if (key == compression_parameters::CHUNK_LENGTH_KB || key == compression_parameters::CHUNK_LENGTH_KB_ERR) {
return to_sstring(c.chunk_len / 1024);
}
if (key == compression_parameters::SSTABLE_COMPRESSION) {
return n;
}
for (auto& o : c.options.elements) {
if (key == sstring(o.key.value.begin(), o.key.value.end())) {
return sstring(o.value.value.begin(), o.value.value.end());
}
}
return std::nullopt;
});
}())
{}
size_t local_compression::uncompress(const char* input,
size_t input_len, char* output, size_t output_len) const {
if (!_compressor) {
throw std::runtime_error("uncompress is not supported");
}
return _compressor->uncompress(input, input_len, output, output_len);
}
size_t local_compression::compress(const char* input, size_t input_len,
char* output, size_t output_len) const {
if (!_compressor) {
throw std::runtime_error("compress is not supported");
}
return _compressor->compress(input, input_len, output, output_len);
}
size_t local_compression::compress_max_size(size_t input_len) const {
return _compressor ? _compressor->compress_max_size(input_len) : 0;
}
void compression::set_compressor(compressor_ptr c) {
if (c) {
unqualified_name uqn(compressor::namespace_prefix, c->name());
const sstring& cn = uqn;
name.value = bytes(cn.begin(), cn.end());
for (auto& p : c->options()) {
if (p.first != compression_parameters::SSTABLE_COMPRESSION) {
auto& k = p.first;
auto& v = p.second;
options.elements.push_back({bytes(k.begin(), k.end()), bytes(v.begin(), v.end())});
}
}
}
}
void compression::update(uint64_t compressed_file_length) {
_compressed_file_length = compressed_file_length;
}
compressor_ptr get_sstable_compressor(const compression& c) {
return local_compression(c).compressor();
}
// locate() takes a byte position in the uncompressed stream, and finds the
// the location of the compressed chunk on disk which contains it, and the
// offset in this chunk.
// locate() may only be used for offsets of actual bytes, and in particular
// the end-of-file position (one past the last byte) MUST not be used. If the
// caller wants to read from the end of file, it should simply read nothing.
compression::chunk_and_offset
compression::locate(uint64_t position, const compression::segmented_offsets::accessor& accessor) {
auto ucl = uncompressed_chunk_length();
auto chunk_index = position / ucl;
decltype(ucl) chunk_offset = position % ucl;
auto chunk_start = accessor.at(chunk_index);
auto chunk_end = (chunk_index + 1 == offsets.size())
? _compressed_file_length
: accessor.at(chunk_index + 1);
return { chunk_start, chunk_end - chunk_start, chunk_offset };
}
}
template <typename ChecksumType>
requires ChecksumUtils<ChecksumType>
class compressed_file_data_source_impl : public data_source_impl {
std::optional<input_stream<char>> _input_stream;
sstables::compression* _compression_metadata;
sstables::compression::segmented_offsets::accessor _offsets;
sstables::local_compression _compression;
uint64_t _underlying_pos;
uint64_t _pos;
uint64_t _beg_pos;
uint64_t _end_pos;
public:
compressed_file_data_source_impl(file f, sstables::compression* cm,
uint64_t pos, size_t len, file_input_stream_options options)
: _compression_metadata(cm)
, _offsets(_compression_metadata->offsets.get_accessor())
, _compression(*cm)
{
_beg_pos = pos;
if (pos > _compression_metadata->uncompressed_file_length()) {
throw std::runtime_error("attempt to uncompress beyond end");
}
if (len == 0 || pos == _compression_metadata->uncompressed_file_length()) {
// Nothing to read
_end_pos = _pos = _beg_pos;
return;
}
if (len <= _compression_metadata->uncompressed_file_length() - pos) {
_end_pos = pos + len;
} else {
_end_pos = _compression_metadata->uncompressed_file_length();
}
// _beg_pos and _end_pos specify positions in the compressed stream.
// We need to translate them into a range of uncompressed chunks,
// and open a file_input_stream to read that range.
auto start = _compression_metadata->locate(_beg_pos, _offsets);
auto end = _compression_metadata->locate(_end_pos - 1, _offsets);
_input_stream = make_file_input_stream(std::move(f),
start.chunk_start,
end.chunk_start + end.chunk_len - start.chunk_start,
std::move(options));
_underlying_pos = start.chunk_start;
_pos = _beg_pos;
}
virtual future<temporary_buffer<char>> get() override {
if (_pos >= _end_pos) {
return make_ready_future<temporary_buffer<char>>();
}
auto addr = _compression_metadata->locate(_pos, _offsets);
// Uncompress the next chunk. We need to skip part of the first
// chunk, but then continue to read from beginning of chunks.
if (_pos != _beg_pos && addr.offset != 0) {
throw std::runtime_error("compressed reader out of sync");
}
return _input_stream->read_exactly(addr.chunk_len).
then([this, addr](temporary_buffer<char> buf) {
// The last 4 bytes of the chunk are the adler32/crc32 checksum
// of the rest of the (compressed) chunk.
auto compressed_len = addr.chunk_len - 4;
// FIXME: Do not always calculate checksum - Cassandra has a
// probability (defaulting to 1.0, but still...)
auto checksum = read_be<uint32_t>(buf.get() + compressed_len);
if (checksum != ChecksumType::checksum(buf.get(), compressed_len)) {
throw std::runtime_error("compressed chunk failed checksum");
}
// We know that the uncompressed data will take exactly
// chunk_length bytes (or less, if reading the last chunk).
temporary_buffer<char> out(
_compression_metadata->uncompressed_chunk_length());
// The compressed data is the whole chunk, minus the last 4
// bytes (which contain the checksum verified above).
auto len = _compression.uncompress(buf.get(), compressed_len, out.get_write(), out.size());
out.trim(len);
out.trim_front(addr.offset);
_pos += out.size();
_underlying_pos += addr.chunk_len;
return out;
});
}
virtual future<> close() override {
if (!_input_stream) {
return make_ready_future<>();
}
return _input_stream->close();
}
virtual future<temporary_buffer<char>> skip(uint64_t n) override {
_pos += n;
assert(_pos <= _end_pos);
if (_pos == _end_pos) {
return make_ready_future<temporary_buffer<char>>();
}
auto addr = _compression_metadata->locate(_pos, _offsets);
auto underlying_n = addr.chunk_start - _underlying_pos;
_underlying_pos = addr.chunk_start;
_beg_pos = _pos;
return _input_stream->skip(underlying_n).then([] {
return make_ready_future<temporary_buffer<char>>();
});
}
};
template <typename ChecksumType>
requires ChecksumUtils<ChecksumType>
class compressed_file_data_source : public data_source {
public:
compressed_file_data_source(file f, sstables::compression* cm,
uint64_t offset, size_t len, file_input_stream_options options)
: data_source(std::make_unique<compressed_file_data_source_impl<ChecksumType>>(
std::move(f), cm, offset, len, std::move(options)))
{}
};
template <typename ChecksumType>
requires ChecksumUtils<ChecksumType>
inline input_stream<char> make_compressed_file_input_stream(
file f, sstables::compression *cm, uint64_t offset, size_t len,
file_input_stream_options options)
{
return input_stream<char>(compressed_file_data_source<ChecksumType>(
std::move(f), cm, offset, len, std::move(options)));
}
// For SSTables 2.x (formats 'ka' and 'la'), the full checksum is a combination of checksums of compressed chunks.
// For SSTables 3.x (format 'mc'), however, it is supposed to contain the full checksum of the file written so
// the per-chunk checksums also count.
enum class compressed_checksum_mode {
checksum_chunks_only,
checksum_all,
};
// compressed_file_data_sink_impl works as a filter for a file output stream,
// where the buffer flushed will be compressed and its checksum computed, then
// the result passed to a regular output stream.
template <typename ChecksumType, compressed_checksum_mode mode>
requires ChecksumUtils<ChecksumType>
class compressed_file_data_sink_impl : public data_sink_impl {
output_stream<char> _out;
sstables::compression* _compression_metadata;
sstables::compression::segmented_offsets::writer _offsets;
sstables::local_compression _compression;
size_t _pos = 0;
uint32_t _full_checksum;
public:
compressed_file_data_sink_impl(output_stream<char> out, sstables::compression* cm, sstables::local_compression lc)
: _out(std::move(out))
, _compression_metadata(cm)
, _offsets(_compression_metadata->offsets.get_writer())
, _compression(lc)
, _full_checksum(ChecksumType::init_checksum())
{}
future<> put(net::packet data) { abort(); }
virtual future<> put(temporary_buffer<char> buf) override {
auto output_len = _compression.compress_max_size(buf.size());
// account space for checksum that goes after compressed data.
temporary_buffer<char> compressed(output_len + 4);
// compress flushed data.
auto len = _compression.compress(buf.get(), buf.size(), compressed.get_write(), output_len);
if (len > output_len) {
return make_exception_future(std::runtime_error("possible overflow during compression"));
}
// total length of the uncompressed data.
_compression_metadata->set_uncompressed_file_length(_compression_metadata->uncompressed_file_length() + buf.size());
_offsets.push_back(_pos);
// account compressed data + 32-bit checksum.
_pos += len + 4;
_compression_metadata->set_compressed_file_length(_pos);
// compute 32-bit checksum for compressed data.
uint32_t per_chunk_checksum = ChecksumType::checksum(compressed.get(), len);
_full_checksum = checksum_combine_or_feed<ChecksumType>(_full_checksum, per_chunk_checksum, compressed.get(), len);
// write checksum into buffer after compressed data.
write_be<uint32_t>(compressed.get_write() + len, per_chunk_checksum);
if constexpr (mode == compressed_checksum_mode::checksum_all) {
uint32_t be_per_chunk_checksum = cpu_to_be(per_chunk_checksum);
_full_checksum = ChecksumType::checksum(_full_checksum,
reinterpret_cast<const char*>(&be_per_chunk_checksum), sizeof(be_per_chunk_checksum));
}
_compression_metadata->set_full_checksum(_full_checksum);
compressed.trim(len + 4);
auto f = _out.write(compressed.get(), compressed.size());
return f.then([compressed = std::move(compressed)] {});
}
virtual future<> close() override {
return _out.close();
}
};
template <typename ChecksumType, compressed_checksum_mode mode>
requires ChecksumUtils<ChecksumType>
class compressed_file_data_sink : public data_sink {
public:
compressed_file_data_sink(output_stream<char> out, sstables::compression* cm, sstables::local_compression lc)
: data_sink(std::make_unique<compressed_file_data_sink_impl<ChecksumType, mode>>(
std::move(out), cm, std::move(lc))) {}
};
template <typename ChecksumType, compressed_checksum_mode mode>
requires ChecksumUtils<ChecksumType>
inline output_stream<char> make_compressed_file_output_stream(output_stream<char> out,
sstables::compression* cm,
const compression_parameters& cp) {
// buffer of output stream is set to chunk length, because flush must
// happen every time a chunk was filled up.
auto p = cp.get_compressor();
cm->set_compressor(p);
cm->set_uncompressed_chunk_length(cp.chunk_length());
// FIXME: crc_check_chance can be configured by the user.
// probability to verify the checksum of a compressed chunk we read.
// defaults to 1.0.
cm->options.elements.push_back({"crc_check_chance", "1.0"});
auto outer_buffer_size = cm->uncompressed_chunk_length();
return output_stream<char>(compressed_file_data_sink<ChecksumType, mode>(std::move(out), cm, p), outer_buffer_size, true);
}
input_stream<char> sstables::make_compressed_file_k_l_format_input_stream(file f,
sstables::compression* cm, uint64_t offset, size_t len,
class file_input_stream_options options)
{
return make_compressed_file_input_stream<adler32_utils>(std::move(f), cm, offset, len, std::move(options));
}
output_stream<char> sstables::make_compressed_file_k_l_format_output_stream(output_stream<char> out,
sstables::compression* cm,
const compression_parameters& cp) {
return make_compressed_file_output_stream<adler32_utils, compressed_checksum_mode::checksum_chunks_only>(
std::move(out), cm, cp);
}
input_stream<char> sstables::make_compressed_file_m_format_input_stream(file f,
sstables::compression *cm, uint64_t offset, size_t len,
class file_input_stream_options options) {
return make_compressed_file_input_stream<crc32_utils>(std::move(f), cm, offset, len, std::move(options));
}
output_stream<char> sstables::make_compressed_file_m_format_output_stream(output_stream<char> out,
sstables::compression* cm,
const compression_parameters& cp) {
return make_compressed_file_output_stream<crc32_utils, compressed_checksum_mode::checksum_all>(
std::move(out), cm, cp);
}
| avikivity/scylla | sstables/compress.cc | C++ | agpl-3.0 | 24,543 |
package org.neo4j.rdf.model;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.rdf.store.RdfStore;
/**
* A hook for a statement which provides metadata editing and reading
* capabilities. A {@link StatementMetadata} implementation is typically
* provided by an {@link RdfStore} implementation and supplied to
* each {@link CompleteStatement} in f.ex
* {@link RdfStore#getStatements(WildcardStatement, boolean)}.
*/
public interface StatementMetadata
{
/**
* Returns wether or not a certain metadata exists.
* @param key the metadata key, typically a URI.
* @return <code>true</code> if the metadata exists, otherwise
* <code>false</code>.
*/
boolean has( String key );
/**
* Returns the metadata value (as a {@link Literal}) for a certain key.
* Throws a runtime exception if the specific metadata doesn't exist.
* @param key the metadata key, typically a URI.
* @return the metadata value for the given key, or throws exception
* if if doesn't exist.
*/
Literal get( String key );
/**
* Sets a metadata value for a certain key. Accepted values are those
* that a {@link PropertyContainer} accepts.
* @param key the metadata key, typically a URI.
* @param value the {@link Literal} value which will be associated with
* the key.
*/
void set( String key, Literal value );
/**
* Removes the metadata value for a certain key. Throws a runtime exception
* if the specific metadata doesn't exist.
* @param key the metadata key, typically a URI.
*/
void remove( String key );
/**
* @return all metadata keys for this statement.
*/
Iterable<String> getKeys();
}
| neo4j-contrib/neo4j-rdf | src/main/java/org/neo4j/rdf/model/StatementMetadata.java | Java | agpl-3.0 | 1,749 |
load('nashorn:mozilla_compat.js');
/*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation. You may not use, modify
or distribute this program under any other version of the
GNU Affero General Public 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* J.J.
NLC VIP Eye Color Change.
*/
var status = 0;
var price = 1000000;
var colors = Array();
function start() {
status = -1;
action(1, 0, 0);
}
function action(mode, type, selection) {
if (mode == -1) {
cm.dispose();
} else {
if (mode == 0 && status == 0) {
cm.dispose();
return;
}
if (mode == 1)
status++;
else
status--;
if (status == 0) {
cm.sendSimple("Hey, there~! I'm J.J.! I'm in charge of the cosmetic lenses here at NLC Shop! If you have a #b#t5152036##k, I can get you the best cosmetic lenses you have ever had! Now, what would you like to do?\r\n#L1#I would like to buy a #b#t5152036##k for " + price + " mesos, please!#l\r\n\#L2#I already have a Coupon!#l");
} else if (status == 1) {
if (selection == 1) {
if(cm.getMeso() >= price) {
cm.gainMeso(-price);
cm.gainItem(5152036, 1);
cm.sendOk("Enjoy!");
} else {
cm.sendOk("You don't have enough mesos to buy a coupon!");
}
cm.dispose();
} else if (selection == 2) {
if (cm.getChar().getGender() == 0) {
var current = cm.getChar().getFace()
% 100 + 20000;
}
if (cm.getChar().getGender() == 1) {
var current = cm.getChar().getFace()
% 100 + 21000;
}
colors = Array();
colors = Array(current , current + 100, current + 200, current + 300, current +400, current + 500, current + 600, current + 700);
cm.sendStyle("With our specialized machine, you can see yourself after the treatment in advance. What kind of lens would you like to wear? Choose the style of your liking.", colors);
}
}
else if (status == 2){
cm.dispose();
if (cm.haveItem(5152036) == true){
cm.gainItem(5152036, -1);
cm.setFace(colors[selection]);
cm.sendOk("Enjoy your new and improved cosmetic lenses!");
} else {
cm.sendOk("I'm sorry, but I don't think you have our cosmetic lens coupon with you right now. Without the coupon, I'm afraid I can't do it for you..");
}
}
}
}
| NoetherEmmy/intransigentms-scripts | npc/9201062.js | JavaScript | agpl-3.0 | 2,969 |
<?php
/*********************************************************************************
* Zurmo is a customer relationship management program developed by
* Zurmo, Inc. Copyright (C) 2014 Zurmo Inc.
*
* Zurmo is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* Zurmo 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive
* Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com.
*
* The interactive user interfaces in original and modified versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the Zurmo
* logo and Zurmo copyright notice. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display the words
* "Copyright Zurmo Inc. 2014. All rights reserved".
********************************************************************************/
class ContactWebFormsUtilTest extends ZurmoBaseTest
{
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
SecurityTestHelper::createSuperAdmin();
}
public function setUp()
{
parent::setUp();
Yii::app()->user->userModel = User::getByUsername('super');
}
public function testGetAttributes()
{
$contactWebForm = new ContactWebForm();
$allAttributes = ContactWebFormsUtil::getAllAttributes();
$this->assertNotEmpty($allAttributes);
$placedAttributes = ContactWebFormsUtil::getPlacedAttributes($contactWebForm);
$nonPlacedAttributes = ContactWebFormsUtil::getNonPlacedAttributes($contactWebForm);
$this->assertTrue(count($placedAttributes) < count($nonPlacedAttributes));
}
public function testGetEmbedScript()
{
$embedScript = ContactWebFormsUtil::getEmbedScript(1);
$this->assertNotEmpty($embedScript);
$this->assertContains('zurmoExternalWebForm', $embedScript);
}
}
?> | maruthisivaprasad/zurmo | app/protected/modules/contactWebForms/tests/unit/ContactWebFormsUtilTest.php | PHP | agpl-3.0 | 3,267 |
<?php
/**
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Robin Appelman <icewind@owncloud.com>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Stefan Weil <sw@weilnetz.de>
* @author Vincent Petry <pvince81@owncloud.com>
*
* @copyright Copyright (c) 2018, ownCloud GmbH
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Files\External\Service;
use OC\Files\Filesystem;
use OCP\Files\External\IStorageConfig;
use OCP\Files\External\IStoragesBackendService;
use OCP\Files\External\Service\IGlobalStoragesService;
/**
* Service class to manage global external storages
*/
class GlobalStoragesService extends StoragesService implements IGlobalStoragesService {
/**
* Triggers $signal for all applicable users of the given
* storage
*
* @param IStorageConfig $storage storage data
* @param string $signal signal to trigger
*/
protected function triggerHooks(IStorageConfig $storage, $signal) {
// FIXME: Use as expression in empty once PHP 5.4 support is dropped
$applicableUsers = $storage->getApplicableUsers();
$applicableGroups = $storage->getApplicableGroups();
if (empty($applicableUsers) && empty($applicableGroups)) {
// raise for user "all"
$this->triggerApplicableHooks(
$signal,
$storage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_USER,
['all']
);
return;
}
$this->triggerApplicableHooks(
$signal,
$storage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_USER,
$applicableUsers
);
$this->triggerApplicableHooks(
$signal,
$storage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_GROUP,
$applicableGroups
);
}
/**
* Triggers signal_create_mount or signal_delete_mount to
* accommodate for additions/deletions in applicableUsers
* and applicableGroups fields.
*
* @param IStorageConfig $oldStorage old storage config
* @param IStorageConfig $newStorage new storage config
*/
protected function triggerChangeHooks(IStorageConfig $oldStorage, IStorageConfig $newStorage) {
// if mount point changed, it's like a deletion + creation
if ($oldStorage->getMountPoint() !== $newStorage->getMountPoint()) {
$this->triggerHooks($oldStorage, Filesystem::signal_delete_mount);
$this->triggerHooks($newStorage, Filesystem::signal_create_mount);
return;
}
$userAdditions = array_diff($newStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());
$userDeletions = array_diff($oldStorage->getApplicableUsers(), $newStorage->getApplicableUsers());
$groupAdditions = array_diff($newStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());
$groupDeletions = array_diff($oldStorage->getApplicableGroups(), $newStorage->getApplicableGroups());
// FIXME: Use as expression in empty once PHP 5.4 support is dropped
// if no applicable were set, raise a signal for "all"
$oldApplicableUsers = $oldStorage->getApplicableUsers();
$oldApplicableGroups = $oldStorage->getApplicableGroups();
if (empty($oldApplicableUsers) && empty($oldApplicableGroups)) {
$this->triggerApplicableHooks(
Filesystem::signal_delete_mount,
$oldStorage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_USER,
['all']
);
}
// trigger delete for removed users
$this->triggerApplicableHooks(
Filesystem::signal_delete_mount,
$oldStorage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_USER,
$userDeletions
);
// trigger delete for removed groups
$this->triggerApplicableHooks(
Filesystem::signal_delete_mount,
$oldStorage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_GROUP,
$groupDeletions
);
// and now add the new users
$this->triggerApplicableHooks(
Filesystem::signal_create_mount,
$newStorage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_USER,
$userAdditions
);
// and now add the new groups
$this->triggerApplicableHooks(
Filesystem::signal_create_mount,
$newStorage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_GROUP,
$groupAdditions
);
// FIXME: Use as expression in empty once PHP 5.4 support is dropped
// if no applicable, raise a signal for "all"
$newApplicableUsers = $newStorage->getApplicableUsers();
$newApplicableGroups = $newStorage->getApplicableGroups();
if (empty($newApplicableUsers) && empty($newApplicableGroups)) {
$this->triggerApplicableHooks(
Filesystem::signal_create_mount,
$newStorage->getMountPoint(),
IStorageConfig::MOUNT_TYPE_USER,
['all']
);
}
}
/**
* Get the visibility type for this controller, used in validation
*
* @return string IStoragesBackendService::VISIBILITY_* constants
*/
public function getVisibilityType() {
return IStoragesBackendService::VISIBILITY_ADMIN;
}
protected function isApplicable(IStorageConfig $config) {
return true;
}
/**
* Get all configured admin and personal mounts
*
* @return array map of storage id to storage config
*/
public function getStorageForAllUsers() {
$mounts = $this->dbConfig->getAllMounts();
$configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
$configs = array_filter($configs, function ($config) {
return $config instanceof IStorageConfig;
});
$keys = array_map(function (IStorageConfig $config) {
return $config->getId();
}, $configs);
return array_combine($keys, $configs);
}
}
| pollopolea/core | lib/private/Files/External/Service/GlobalStoragesService.php | PHP | agpl-3.0 | 5,913 |
/*
* StatusBarWidget.java
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.editors.text.status;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.*;
import org.rstudio.core.client.widget.IsWidgetWithHeight;
import org.rstudio.studio.client.common.icons.StandardIcons;
import org.rstudio.studio.client.common.icons.code.CodeIcons;
public class StatusBarWidget extends Composite
implements StatusBar, IsWidgetWithHeight
{
interface Binder extends UiBinder<HorizontalPanel, StatusBarWidget>
{
}
public StatusBarWidget()
{
Binder binder = GWT.create(Binder.class);
panel_ = binder.createAndBindUi(this);
panel_.setVerticalAlignment(HorizontalPanel.ALIGN_TOP);
panel_.setCellWidth(scope_, "100%");
panel_.setCellWidth(message_, "100%");
hideTimer_ = new Timer()
{
@Override
public void run()
{
hideMessage();
}
};
hideProgressTimer_ = new Timer()
{
@Override
public void run()
{
progress_.setVisible(false);
language_.setVisible(true);
}
};
// The message widget should initially be hidden, but be shown in lieu of
// the scope tree when requested.
show(scope_);
show(scopeIcon_);
hide(message_);
initWidget(panel_);
height_ = 16;
}
// NOTE: The 'show' + 'hide' methods here take advantage of the fact that
// status bar widgets live within table cells; to ensure proper sizing we
// need to set the display property on those cells rather than the widgets
// themselves.
private void hide(Widget widget)
{
widget.setVisible(false);
widget.getElement().getParentElement().getStyle().setDisplay(Display.NONE);
}
private void show(Widget widget)
{
widget.setVisible(true);
widget.getElement().getParentElement().getStyle().clearDisplay();
}
public int getHeight()
{
return height_;
}
public Widget asWidget()
{
return this;
}
public StatusBarElement getPosition()
{
return position_;
}
public StatusBarElement getMessage()
{
return message_;
}
public StatusBarElement getScope()
{
return scope_;
}
public StatusBarElement getLanguage()
{
return language_;
}
public void setScopeVisible(boolean visible)
{
scope_.setClicksEnabled(visible);
scope_.setContentsVisible(visible);
scopeIcon_.setVisible(visible);
}
public void setScopeType(int type)
{
scopeType_ = type;
if (type == StatusBar.SCOPE_TOP_LEVEL || message_.isVisible())
scopeIcon_.setVisible(false);
else
scopeIcon_.setVisible(true);
if (type == StatusBar.SCOPE_CLASS)
scopeIcon_.setResource(CodeIcons.INSTANCE.clazz());
else if (type == StatusBar.SCOPE_NAMESPACE)
scopeIcon_.setResource(CodeIcons.INSTANCE.namespace());
else if (type == StatusBar.SCOPE_LAMBDA)
scopeIcon_.setResource(StandardIcons.INSTANCE.lambdaLetter());
else if (type == StatusBar.SCOPE_ANON)
scopeIcon_.setResource(StandardIcons.INSTANCE.functionLetter());
else if (type == StatusBar.SCOPE_FUNCTION)
scopeIcon_.setResource(StandardIcons.INSTANCE.functionLetter());
else if (type == StatusBar.SCOPE_CHUNK)
scopeIcon_.setResource(RES.chunk());
else if (type == StatusBar.SCOPE_SECTION)
scopeIcon_.setResource(RES.section());
else if (type == StatusBar.SCOPE_SLIDE)
scopeIcon_.setResource(RES.slide());
else
scopeIcon_.setResource(CodeIcons.INSTANCE.function());
}
private void initMessage(String message)
{
hide(scope_);
hide(scopeIcon_);
message_.setValue(message);
show(message_);
}
private void endMessage()
{
show(scope_);
show(scopeIcon_);
hide(message_);
setScopeType(scopeType_);
}
@Override
public void showMessage(String message)
{
initMessage(message);
}
@Override
public void showMessage(String message, int timeMs)
{
initMessage(message);
hideTimer_.schedule(timeMs);
}
@Override
public void showMessage(String message, final HideMessageHandler handler)
{
initMessage(message);
// Protect against multiple messages shown at same time
if (handler_ != null)
{
handler_.removeHandler();
handler_ = null;
}
handler_ = Event.addNativePreviewHandler(new NativePreviewHandler()
{
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (handler.onNativePreviewEvent(event))
{
endMessage();
handler_.removeHandler();
handler_ = null;
}
}
});
}
@Override
public void hideMessage()
{
endMessage();
}
@Override
public void showNotebookProgress(String label)
{
// cancel the hide timer if it's running
hideProgressTimer_.cancel();
// ensure notebook progress widget is visible
if (!progress_.isVisible())
{
language_.setVisible(false);
progress_.setVisible(true);
}
progress_.setLabel(label);
progress_.setPercent(0);
}
@Override
public void updateNotebookProgress(int percent)
{
// just update the status bar
progress_.setPercent(percent);
}
@Override
public void hideNotebookProgress(boolean immediately)
{
if (progress_.isVisible())
{
if (immediately)
hideProgressTimer_.run();
else
hideProgressTimer_.schedule(400);
}
}
@Override
public HandlerRegistration addProgressClickHandler(ClickHandler handler)
{
return progress_.addClickHandler(handler);
}
@Override
public HandlerRegistration addProgressCancelHandler(Command onCanceled)
{
return progress_.addCancelHandler(onCanceled);
}
@UiField StatusBarElementWidget position_;
@UiField StatusBarElementWidget scope_;
@UiField StatusBarElementWidget message_;
@UiField StatusBarElementWidget language_;
@UiField Image scopeIcon_;
@UiField NotebookProgressWidget progress_;
public interface Resources extends ClientBundle
{
ImageResource chunk();
ImageResource section();
ImageResource slide();
}
public static Resources RES = GWT.create(Resources.class);
private final HorizontalPanel panel_;
private final Timer hideTimer_;
private final Timer hideProgressTimer_;
private int height_;
private HandlerRegistration handler_;
private int scopeType_;
}
| jrnold/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/status/StatusBarWidget.java | Java | agpl-3.0 | 8,093 |
import {EditorState} from 'draft-js';
import {repositionHighlights, redrawHighlights} from '.';
/**
* @typedef StateWithComment
* @property {ContentState} editorState
* @property {Comment} activeHighlight
*/
/**
* @name updateHighlights
* @description Updates highlight information after every content change. It
* recalculates offsets (start and end points) and reapplies the inline styling to
* match these.
* @param {EditorState} oldState
* @param {EditorState} newState
* @returns {StateWithComment}
*/
export function updateHighlights(oldState, newState) {
let updatedState = repositionHighlights(oldState, newState);
let {editorState, activeHighlight} = redrawHighlights(updatedState);
let contentChanged = oldState.getCurrentContent() !== newState.getCurrentContent();
if (contentChanged) {
editorState = preserveSelection(editorState, newState.getCurrentContent());
}
return {editorState, activeHighlight};
}
// Preserve before & after selection when content was changed. This helps
// with keeping the cursor more or less in the same position when undo-ing
// and redo-ing. Without this, all of the recalculating of offsets and styles
// will misplace the cursor position when the user performs an Undo operation.
function preserveSelection(es, content) {
let editorState = es;
let selectionBefore = content.getSelectionBefore();
let selectionAfter = content.getSelectionAfter();
editorState = EditorState.set(editorState, {allowUndo: false});
editorState = EditorState.push(editorState, editorState.getCurrentContent()
.set('selectionBefore', selectionBefore)
.set('selectionAfter', selectionAfter)
);
return EditorState.set(editorState, {allowUndo: true});
}
| Aca-jov/superdesk-client-core | scripts/core/editor3/reducers/highlights/highlights.js | JavaScript | agpl-3.0 | 1,765 |
// Copyright 2016 Canonical Ltd.
// Copyright 2016 Cloudbase Solutions
// Licensed under the AGPLv3, see LICENCE file for details.
// machineactions implements the the apiserver side of
// running actions on machines
package machineactions
import (
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/state"
"gopkg.in/juju/names.v2"
)
type Backend interface {
ActionByTag(tag names.ActionTag) (state.Action, error)
FindEntity(tag names.Tag) (state.Entity, error)
TagToActionReceiverFn(findEntity func(names.Tag) (state.Entity, error)) func(string) (state.ActionReceiver, error)
ConvertActions(ar state.ActionReceiver, fn common.GetActionsFn) ([]params.ActionResult, error)
}
// Facade implements the machineactions interface and is the concrete
// implementation of the api end point.
type Facade struct {
backend Backend
resources *common.Resources
accessMachine common.AuthFunc
}
// NewFacade creates a new server-side machineactions API end point.
func NewFacade(
backend Backend,
resources *common.Resources,
authorizer common.Authorizer,
) (*Facade, error) {
if !authorizer.AuthMachineAgent() {
return nil, common.ErrPerm
}
return &Facade{
backend: backend,
resources: resources,
accessMachine: authorizer.AuthOwner,
}, nil
}
// Actions returns the Actions by Tags passed and ensures that the machine asking
// for them is the machine that has the actions
func (f *Facade) Actions(args params.Entities) params.ActionResults {
actionFn := common.AuthAndActionFromTagFn(f.accessMachine, f.backend.ActionByTag)
return common.Actions(args, actionFn)
}
// BeginActions marks the actions represented by the passed in Tags as running.
func (f *Facade) BeginActions(args params.Entities) params.ErrorResults {
actionFn := common.AuthAndActionFromTagFn(f.accessMachine, f.backend.ActionByTag)
return common.BeginActions(args, actionFn)
}
// FinishActions saves the result of a completed Action
func (f *Facade) FinishActions(args params.ActionExecutionResults) params.ErrorResults {
actionFn := common.AuthAndActionFromTagFn(f.accessMachine, f.backend.ActionByTag)
return common.FinishActions(args, actionFn)
}
// WatchActionNotifications returns a StringsWatcher for observing
// incoming action calls to a machine.
func (f *Facade) WatchActionNotifications(args params.Entities) params.StringsWatchResults {
tagToActionReceiver := f.backend.TagToActionReceiverFn(f.backend.FindEntity)
watchOne := common.WatchOneActionReceiverNotifications(tagToActionReceiver, f.resources.Register)
return common.WatchActionNotifications(args, f.accessMachine, watchOne)
}
// RunningActions lists the actions running for the entities passed in.
// If we end up needing more than ListRunning at some point we could follow/abstract
// what's done in the client actions package.
func (f *Facade) RunningActions(args params.Entities) params.ActionsByReceivers {
canAccess := f.accessMachine
tagToActionReceiver := f.backend.TagToActionReceiverFn(f.backend.FindEntity)
response := params.ActionsByReceivers{
Actions: make([]params.ActionsByReceiver, len(args.Entities)),
}
for i, entity := range args.Entities {
currentResult := &response.Actions[i]
receiver, err := tagToActionReceiver(entity.Tag)
if err != nil {
currentResult.Error = common.ServerError(common.ErrBadId)
continue
}
currentResult.Receiver = receiver.Tag().String()
if !canAccess(receiver.Tag()) {
currentResult.Error = common.ServerError(common.ErrPerm)
continue
}
results, err := f.backend.ConvertActions(receiver, receiver.RunningActions)
if err != nil {
currentResult.Error = common.ServerError(err)
continue
}
currentResult.Actions = results
}
return response
}
| dooferlad/juju | apiserver/machineactions/machineactions.go | GO | agpl-3.0 | 3,780 |
<?php
/* KeosuCoreBundle:Menu:app.html.twig */
class __TwigTemplate_f0d74c7e515c1c49cf3db50b29d8315143e77a28818680bb00c19c65249e2de1 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())
{
$__internal_97de16eef10d264c6e841cd1032c62e9dbcd1d53e15ea7b6b13718c3c2d71708 = $this->env->getExtension("native_profiler");
$__internal_97de16eef10d264c6e841cd1032c62e9dbcd1d53e15ea7b6b13718c3c2d71708->enter($__internal_97de16eef10d264c6e841cd1032c62e9dbcd1d53e15ea7b6b13718c3c2d71708_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "KeosuCoreBundle:Menu:app.html.twig"));
// line 1
echo "<a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">
<span class=\"glyphicon glyphicon-eye-open\"></span>
";
// line 3
echo twig_escape_filter($this->env, (isset($context["curAppName"]) ? $context["curAppName"] : $this->getContext($context, "curAppName")), "html", null, true);
echo " <b class=\"caret\"></b></a>
<ul class=\"dropdown-menu\">
\t";
// line 5
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable((isset($context["apps"]) ? $context["apps"] : $this->getContext($context, "apps")));
foreach ($context['_seq'] as $context["_key"] => $context["app"]) {
// line 6
echo "\t<li role=\"presentation\">
\t\t<a href=\"";
// line 7
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("keosu_changeapp", array("appid" => $this->getAttribute($context["app"], "id", array()))), "html", null, true);
echo "\">";
echo twig_escape_filter($this->env, $this->getAttribute($context["app"], "name", array()), "html", null, true);
echo "</a>
\t</li>
\t";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['app'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 10
echo "</ul>
";
$__internal_97de16eef10d264c6e841cd1032c62e9dbcd1d53e15ea7b6b13718c3c2d71708->leave($__internal_97de16eef10d264c6e841cd1032c62e9dbcd1d53e15ea7b6b13718c3c2d71708_prof);
}
public function getTemplateName()
{
return "KeosuCoreBundle:Menu:app.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 49 => 10, 38 => 7, 35 => 6, 31 => 5, 26 => 3, 22 => 1,);
}
public function getSource()
{
return "<a href=\"#\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">
<span class=\"glyphicon glyphicon-eye-open\"></span>
{{ curAppName }} <b class=\"caret\"></b></a>
<ul class=\"dropdown-menu\">
\t{% for app in apps %}
\t<li role=\"presentation\">
\t\t<a href=\"{{ path('keosu_changeapp',{'appid':app.id}) }}\">{{ app.name }}</a>
\t</li>
\t{% endfor %}
</ul>
";
}
}
| alexandremarcel/keosu | var/cache/dev/twig/6f/6f5bc2ccaa594b65a6be6ec6b38cb924efe6c1e179defe9dc67329b8ef3d015d.php | PHP | agpl-3.0 | 3,227 |
define([
"breakeven/config"
], function (
config
) {
return {
input: {
verkaufspreis: 75000,
absatzmenge: 200,
variable_kosten: 2500,
fixkosten: 8000,
fixkosten_in_prozent: 22.4,
stueckkosten: 150,
deckungsbeitrag: 50,
gewinnschwelle: 1250,
umsatzerloese: 250000,
gesamtkosten: 28000,
ergebnis: 10000,
berechnungsart: 5,
veraenderliche_groese: 4,
config: config
},
expectedOutput: {
verkaufspreis: 0,
absatzmenge: 200,
variable_kosten: 2500,
fixkosten: 8000,
fixkosten_in_prozent: 76.19047619047619,
stueckkosten: 12.5,
deckungsbeitrag: -12.5,
gewinnschwelle: -640,
umsatzerloese: 0,
gesamtkosten: 10500,
ergebnis: -10500,
error: false
}
}
});
| ohaz/amos-ss15-proj1 | FlaskWebProject/static/scripts/rechner/spec/breakeven/testData2.js | JavaScript | agpl-3.0 | 829 |
Ext.define("CMDBuild.controller.management.common.CMModClassAndWFCommons", {
/*
* retrieve the form to use as target for the
* templateResolver asking it to its view
*
* returns null if something is not right
*/
getFormForTemplateResolver: function() {
var form = null;
if (this.view) {
var wm = this.view.getWidgetManager();
if (wm && typeof wm.getFormForTemplateResolver == "function") {
form = wm.getFormForTemplateResolver() || null;
}
}
return form;
}
}); | jzinedine/CMDBuild | cmdbuild/src/main/webapp/javascripts/cmdbuild/controller/management/common/CMModClassAndWFCommons.js | JavaScript | agpl-3.0 | 497 |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Marks an item as an ingredient, allowing it to be combined with other ingredients as marked in CraftingManager.Meals.
/// Note: This only applies to two-ingredient recipes.
/// This component was based off of Knife.cs.
/// </summary>
[RequireComponent(typeof(Pickupable))]
public class IngredientMarker : MonoBehaviour, ICheckedInteractable<InventoryApply>
{
//check if item is being applied to offhand with chopable object on it.
public bool WillInteract(InventoryApply interaction, NetworkSide side)
{
//can the player act at all?
if (!DefaultWillInteract.Default(interaction, side)) return false;
//make sure both items are ingredients!
if (!Validations.HasUsedItemTrait(interaction, CommonTraits.Instance.Ingredient)) return false;
if (!Validations.HasItemTrait(interaction.UsedObject, CommonTraits.Instance.Ingredient)) return false;
//make sure at least the target is in a hand slot
if (!interaction.IsToHandSlot) return false;
//TargetSlot must not be empty.
if (interaction.TargetSlot.Item == null) return false;
return true;
}
public void ServerPerformInteraction(InventoryApply interaction)
{
//is the target item another ingredient?
ItemAttributesV2 attr = interaction.TargetObject.GetComponent<ItemAttributesV2>();
ItemAttributesV2 selfattr = interaction.UsedObject.GetComponent<ItemAttributesV2>();
Ingredient ingredient = new Ingredient(attr.ArticleName);
Ingredient self = new Ingredient(selfattr.ArticleName);
GameObject cut = CraftingManager.SimpleMeal.FindRecipe(new List<Ingredient> { ingredient, self });
GameObject cut2 = CraftingManager.SimpleMeal.FindRecipe(new List<Ingredient> { self, ingredient });
if (cut)
{
Inventory.ServerDespawn(interaction.TargetObject);
Inventory.ServerDespawn(interaction.UsedObject);
SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.SimpleMeal.FindOutputMeal(cut.name),
SpawnDestination.At(), 1);
if (spwn.Successful)
{
Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot);
}
}
else if (cut2)
{
Inventory.ServerDespawn(interaction.TargetSlot);
Inventory.ServerDespawn(interaction.Performer);
SpawnResult spwn = Spawn.ServerPrefab(CraftingManager.SimpleMeal.FindOutputMeal(cut2.name),
SpawnDestination.At(), 1);
if (spwn.Successful)
{
Inventory.ServerAdd(spwn.GameObject, interaction.TargetSlot);
}
}
}
} | krille90/unitystation | UnityProject/Assets/IngredientMarker.cs | C# | agpl-3.0 | 2,483 |
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ObjectAccessor.h"
#include "Opcodes.h"
#include "Pet.h"
#include "Player.h"
#include "WorldPacket.h"
#include "WorldSession.h"
void WorldSession::HandleLearnTalentOpcode(WorldPacket& recvData)
{
uint32 talent_id, requested_rank;
recvData >> talent_id >> requested_rank;
_player->LearnTalent(talent_id, requested_rank);
_player->SendTalentsInfoData(false);
}
void WorldSession::HandleLearnPreviewTalents(WorldPacket& recvPacket)
{
LOG_DEBUG("network", "CMSG_LEARN_PREVIEW_TALENTS");
uint32 talentsCount;
recvPacket >> talentsCount;
uint32 talentId, talentRank;
// Client has max 44 talents for tree for 3 trees, rounded up : 150
uint32 const MaxTalentsCount = 150;
for (uint32 i = 0; i < talentsCount && i < MaxTalentsCount; ++i)
{
recvPacket >> talentId >> talentRank;
_player->LearnTalent(talentId, talentRank);
}
_player->SendTalentsInfoData(false);
recvPacket.rfinish();
}
void WorldSession::HandleTalentWipeConfirmOpcode(WorldPacket& recvData)
{
LOG_DEBUG("network", "MSG_TALENT_WIPE_CONFIRM");
ObjectGuid guid;
recvData >> guid;
Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER);
if (!unit)
{
LOG_DEBUG("network", "WORLD: HandleTalentWipeConfirmOpcode - Unit (%s) not found or you can't interact with him.", guid.ToString().c_str());
return;
}
if (!unit->isCanTrainingAndResetTalentsOf(_player))
return;
// remove fake death
if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);
if (!(_player->resetTalents()))
{
WorldPacket data(MSG_TALENT_WIPE_CONFIRM, 8 + 4); //you have not any talent
data << uint64(0);
data << uint32(0);
SendPacket(&data);
return;
}
_player->SendTalentsInfoData(false);
unit->CastSpell(_player, 14867, true); //spell: "Untalent Visual Effect"
}
void WorldSession::HandleUnlearnSkillOpcode(WorldPacket& recvData)
{
uint32 skillId;
recvData >> skillId;
if (!IsPrimaryProfessionSkill(skillId))
return;
GetPlayer()->SetSkill(skillId, 0, 0, 0);
}
| ShinDarth/azerothcore-wotlk | src/server/game/Handlers/SkillHandler.cpp | C++ | agpl-3.0 | 2,993 |
package com.mattiapette.prova.proxy;
public abstract class CommonProxy implements Iproxy
{
}
| MattiaPette/MC_Mod | src/main/java/com/mattiapette/prova/proxy/CommonProxy.java | Java | agpl-3.0 | 95 |
# -*- coding: utf-8 -*-
# Copyright(C) 2013 Christophe Lampin
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import urllib
from weboob.tools.browser import BaseBrowser, BrowserIncorrectPassword
from weboob.capabilities.bill import Detail
from decimal import Decimal
from .pages import LoginPage, HomePage, AccountPage, HistoryPage, BillsPage
__all__ = ['AmeliProBrowser']
class AmeliProBrowser(BaseBrowser):
PROTOCOL = 'https'
DOMAIN = 'espacepro.ameli.fr'
ENCODING = None
PAGES = {'.*_pageLabel=vp_login_page.*': LoginPage,
'.*_pageLabel=vp_accueil.*': HomePage,
'.*_pageLabel=vp_coordonnees_infos_perso_page.*': AccountPage,
'.*_pageLabel=vp_recherche_par_date_paiements_page.*': HistoryPage,
'.*_pageLabel=vp_releves_mensuels_page.*': BillsPage,
}
loginp = '/PortailPS/appmanager/portailps/professionnelsante?_nfpb=true&_pageLabel=vp_login_page'
homep = '/PortailPS/appmanager/portailps/professionnelsante?_nfpb=true&_pageLabel=vp_accueil_book'
accountp = '/PortailPS/appmanager/portailps/professionnelsante?_nfpb=true&_pageLabel=vp_coordonnees_infos_perso_page'
billsp = '/PortailPS/appmanager/portailps/professionnelsante?_nfpb=true&_pageLabel=vp_releves_mensuels_page'
searchp = '/PortailPS/appmanager/portailps/professionnelsante?_nfpb=true&_pageLabel=vp_recherche_par_date_paiements_page'
historyp = '/PortailPS/appmanager/portailps/professionnelsante?_nfpb=true&_windowLabel=vp_recherche_paiement_tiers_payant_portlet_1&vp_recherche_paiement_tiers_payant_portlet_1_actionOverride=%2Fportlets%2Fpaiements%2Frecherche&_pageLabel=vp_recherche_par_date_paiements_page'
def home(self):
self.location(self.homep)
def is_logged(self):
if self.is_on_page(LoginPage):
return False
return True
def login(self):
assert isinstance(self.username, basestring)
assert isinstance(self.password, basestring)
if not self.is_on_page(LoginPage):
self.location(self.loginp)
self.page.login(self.username, self.password)
if self.is_on_page(LoginPage):
raise BrowserIncorrectPassword()
def get_subscription_list(self):
if not self.is_on_page(AccountPage):
self.location(self.accountp)
return self.page.get_subscription_list()
def get_subscription(self, id):
assert isinstance(id, basestring)
return self.get_subscription_list()
def iter_history(self, subscription):
if not self.is_on_page(HistoryPage):
self.location(self.searchp)
date_deb = self.page.document.xpath('//input[@name="vp_recherche_paiement_tiers_payant_portlet_1dateDebutRecherche"]')[0].value
date_fin = self.page.document.xpath('//input[@name="vp_recherche_paiement_tiers_payant_portlet_1dateFinRecherche"]')[0].value
data = {'vp_recherche_paiement_tiers_payant_portlet_1dateDebutRecherche': date_deb,
'vp_recherche_paiement_tiers_payant_portlet_1dateFinRecherche': date_fin,
'vp_recherche_paiement_tiers_payant_portlet_1codeOrganisme': 'null',
'vp_recherche_paiement_tiers_payant_portlet_1actionEvt': 'rechercheParDate',
'vp_recherche_paiement_tiers_payant_portlet_1codeRegime': '01',
}
self.location(self.historyp, urllib.urlencode(data))
return self.page.iter_history()
def get_details(self, sub):
det = Detail()
det.id = sub.id
det.label = sub.label
det.infos = ''
det.price = Decimal('0.0')
return det
def iter_bills(self):
if not self.is_on_page(BillsPage):
self.location(self.billsp)
return self.page.iter_bills()
def get_bill(self, id):
assert isinstance(id, basestring)
for b in self.get_bills():
if id == b.id:
return b
return None
| blckshrk/Weboob | modules/amelipro/browser.py | Python | agpl-3.0 | 4,595 |