repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
rubelnimbuzz/bm2
|
android/src/org/bombusmod/BombusModService.java
|
8230
|
package org.bombusmod;
import android.app.Notification;
import android.support.v4.app.NotificationCompat;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bombusmod.scrobbler.Receiver;
public class BombusModService extends Service {
public static final String ACTION_FOREGROUND = "FOREGROUND";
private static final String LOG_TAG = "BombusModService";
private static final Class<?>[] mSetForegroundSignature = new Class[]{
boolean.class};
private static final Class<?>[] mStartForegroundSignature = new Class[]{
int.class, Notification.class};
private static final Class<?>[] mStopForegroundSignature = new Class[]{
boolean.class};
private NotificationManager mNM;
private Method mSetForeground;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mSetForegroundArgs = new Object[1];
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
protected Receiver musicReceiver;
protected NetworkStateReceiver networkStateReceiver;
void invokeMethod(Method method, Object[] args) {
try {
method.invoke(this, args);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w(LOG_TAG, "Unable to invoke method", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w(LOG_TAG, "Unable to invoke method", e);
}
}
@Override
public void onCreate() {
super.onCreate();
Log.i(LOG_TAG, "onStart();");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
try {
mStartForeground = getClass().getMethod("startForeground",
mStartForegroundSignature);
mStopForeground = getClass().getMethod("stopForeground",
mStopForegroundSignature);
} catch (NoSuchMethodException e) {
// Running on an older platform.
mStartForeground = mStopForeground = null;
}
try {
mSetForeground = getClass().getMethod("setForeground",
mSetForegroundSignature);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"OS doesn't have Service.startForeground OR Service.setForeground!");
}
//Foreground Service
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setSmallIcon(R.drawable.app_service);
notification.setContentTitle(getString(R.string.app_name));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, BombusModActivity.class), 0);
notification.setContentIntent(contentIntent);
startForegroundCompat(R.string.app_name, notification.build());
//audio scrobbler
IntentFilter filter = new IntentFilter();
//Google Android player
filter.addAction("com.android.music.playstatechanged");
filter.addAction("com.android.music.playbackcomplete");
filter.addAction("com.android.music.metachanged");
//HTC Music
filter.addAction("com.htc.music.playstatechanged");
filter.addAction("com.htc.music.playbackcomplete");
filter.addAction("com.htc.music.metachanged");
//MIUI Player
filter.addAction("com.miui.player.playstatechanged");
filter.addAction("com.miui.player.playbackcomplete");
filter.addAction("com.miui.player.metachanged");
//Real
filter.addAction("com.real.IMP.playstatechanged");
filter.addAction("com.real.IMP.playbackcomplete");
filter.addAction("com.real.IMP.metachanged");
//SEMC Music Player
filter.addAction("com.sonyericsson.music.playbackcontrol.ACTION_TRACK_STARTED");
filter.addAction("com.sonyericsson.music.playbackcontrol.ACTION_PAUSED");
filter.addAction("com.sonyericsson.music.TRACK_COMPLETED");
filter.addAction("com.sonyericsson.music.metachanged");
filter.addAction("com.sonyericsson.music.playbackcomplete");
filter.addAction("com.sonyericsson.music.playstatechanged");
//rdio
filter.addAction("com.rdio.android.metachanged");
filter.addAction("com.rdio.android.playstatechanged");
//Samsung Music Player
filter.addAction("com.samsung.sec.android.MusicPlayer.playstatechanged");
filter.addAction("com.samsung.sec.android.MusicPlayer.playbackcomplete");
filter.addAction("com.samsung.sec.android.MusicPlayer.metachanged");
filter.addAction("com.sec.android.app.music.playstatechanged");
filter.addAction("com.sec.android.app.music.playbackcomplete");
filter.addAction("com.sec.android.app.music.metachanged");
//Winamp
filter.addAction("com.nullsoft.winamp.playstatechanged");
//Amazon
filter.addAction("com.amazon.mp3.playstatechanged");
//Rhapsody
filter.addAction("com.rhapsody.playstatechanged");
//PowerAmp
filter.addAction("com.maxmpz.audioplayer.playstatechanged");
//will be added any....
//scrobblers detect for players (poweramp for example)
//Last.fm
filter.addAction("fm.last.android.metachanged");
filter.addAction("fm.last.android.playbackpaused");
filter.addAction("fm.last.android.playbackcomplete");
//A simple last.fm scrobbler
filter.addAction("com.adam.aslfms.notify.playstatechanged");
//Scrobble Droid
filter.addAction("net.jjc1138.android.scrobbler.action.MUSIC_STATUS");
musicReceiver = new Receiver();
registerReceiver(musicReceiver, filter);
// enable network state receiver
IntentFilter networkStateFilter = new IntentFilter();
networkStateFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkStateReceiver = new NetworkStateReceiver();
registerReceiver(networkStateReceiver, networkStateFilter);
}
@Override
public void onDestroy() {
Log.i(LOG_TAG, "onDestroy();");
stopForegroundCompat(R.string.app_name);
// disable network state receiver
unregisterReceiver(networkStateReceiver);
// unregister music receiver
unregisterReceiver(musicReceiver);
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod(mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean.TRUE;
invokeMethod(mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat(int id) {
// If we have the new stopForeground API, then use it.
if (mStopForeground != null) {
mStopForegroundArgs[0] = Boolean.TRUE;
invokeMethod(mStopForeground, mStopForegroundArgs);
return;
}
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean.FALSE;
invokeMethod(mSetForeground, mSetForegroundArgs);
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
|
gpl-2.0
|
dkoudela/advanced-ldap-for-crucible
|
src/main/java/com/davidkoudela/crucible/ldap/model/AdvancedLdapBind.java
|
622
|
package com.davidkoudela.crucible.ldap.model;
/**
* Description: {@link AdvancedLdapBind} contains all necessary LDAP bind parameters and their access methods.
* Copyright (C) 2015 David Koudela
*
* @author dkoudela
* @since 2015-05-06
*/
public class AdvancedLdapBind {
private String dn;
private boolean result;
public String getDn() {
return dn;
}
public void setDn(String dn) {
this.dn = dn;
}
public boolean getResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
}
|
gpl-2.0
|
rodhoff/cdn1
|
libraries/regularlabs/fields/akeebasubs.php
|
1106
|
<?php
/**
* @package Regular Labs Library
* @version 16.7.10746
*
* @author Peter van Westen <info@regularlabs.com>
* @link http://www.regularlabs.com
* @copyright Copyright © 2016 Regular Labs All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
require_once dirname(__DIR__) . '/helpers/groupfield.php';
class JFormFieldRL_AkeebaSubs extends RLFormGroupField
{
public $type = 'AkeebaSubs';
public $default_group = 'Levels';
protected function getInput()
{
if ($error = $this->missingFilesOrTables(array('levels')))
{
return $error;
}
return $this->getSelectList();
}
function getLevels()
{
$query = $this->db->getQuery(true)
->select('l.akeebasubs_level_id as id, l.title AS name, l.enabled as published')
->from('#__akeebasubs_levels AS l')
->where('l.enabled > -1')
->order('l.title, l.akeebasubs_level_id');
$this->db->setQuery($query);
$list = $this->db->loadObjectList();
return $this->getOptionsByList($list, array('id'));
}
}
|
gpl-2.0
|
graemechristie/NinjaSettings
|
NinjaSettings.Example.Autofac/Properties/AssemblyInfo.cs
|
1389
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NinjaSettings.Example.Autofac")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NinjaSettings.Example.Autofac")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a19b531a-4352-4973-94ac-48287e915273")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-2.0
|
ssteinerx/customer-area
|
src/php/core-addons/customer-private-files/templates/customer-private-files-content-item.template.php
|
1902
|
<?php /** Template version: 1.1.0
-= 1.1.0 =-
- Updated markup
- Normalized the extra class filter name
-= 1.0.0 =-
- Initial version
*/ ?>
<?php
global $post;
$is_author = get_the_author_meta('ID')==get_current_user_id();
$file_size = cuar_get_the_file_size( get_the_ID() );
if ( $is_author ) {
$subtitle_popup = __( 'You uploaded this file', 'cuar' );
$subtitle = sprintf( __( 'Published for %s', 'cuar' ), cuar_get_the_owner() );
} else {
$subtitle_popup = sprintf( __( 'Published for %s', 'cuar' ), cuar_get_the_owner() );
$subtitle = sprintf( __( 'Published by %s', 'cuar' ), get_the_author_meta( 'display_name' ) );
}
$title_popup = sprintf( __( 'Uploaded on %s', 'cuar' ), get_the_date() );
$extra_class = ' ' . get_post_type();
$extra_class = apply_filters( 'cuar/templates/list-item/extra-class?post-type=' . get_post_type(), $extra_class, $post );
?>
<div class="cuar-private-file cuar-item cuar-item-large<?php echo $extra_class; ?>">
<div class="panel">
<div class="title">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( $title_popup ); ?>"><?php the_title(); ?></a>
</div>
<div class="subtitle">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( $subtitle_popup ); ?>"><?php echo $subtitle; ?></a>
</div>
<?php if ( has_post_thumbnail( get_the_ID() ) ) : ?>
<div class="cover">
<a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( $title_popup ); ?>">
<?php the_post_thumbnail( 'medium', array( 'class' => "img-responsive" ) ); ?>
</a>
</div>
<?php endif; ?>
<div class="badges">
<a href="<?php cuar_the_file_link( get_the_ID(), 'download' ); ?>" title="<?php echo esc_attr( sprintf( __( 'Download (%1$s)', 'cuar' ), $file_size ) ); ?>">
<span class="download-badge dashicons dashicons-download dashicon-badge pull-right"></span>
</a>
</div>
</div>
</div>
|
gpl-2.0
|
jeffgdotorg/opennms
|
features/poller/monitors/core/src/test/java/org/opennms/netmgt/poller/monitors/SshMonitorIT.java
|
8538
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.poller.monitors;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.PatternSyntaxException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opennms.core.test.OpenNMSJUnit4ClassRunner;
import org.opennms.core.utils.InetAddressUtils;
import org.opennms.netmgt.poller.MonitoredService;
import org.opennms.netmgt.poller.PollStatus;
import org.opennms.netmgt.poller.ServiceMonitor;
import org.opennms.netmgt.poller.mock.MockMonitoredService;
import org.opennms.test.JUnitConfigurationEnvironment;
import org.springframework.test.context.ContextConfiguration;
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/META-INF/opennms/emptyContext.xml",
"classpath:/META-INF/opennms/applicationContext-mockDao.xml",
"classpath:/META-INF/opennms/applicationContext-commonConfigs.xml",
"classpath:/META-INF/opennms/applicationContext-minimal-conf.xml",
"classpath:/META-INF/opennms/applicationContext-soa.xml"})
@JUnitConfigurationEnvironment
public class SshMonitorIT {
public static final String HOST_TO_TEST = "127.0.0.1";
@Test
public void testPoll() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Up"), ps.isUp());
assertFalse(createAssertMessage(ps, "not Down"), ps.isDown());
}
@Test
public void testPollWithMatch() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("match", "SSH");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Up"), ps.isUp());
assertFalse(createAssertMessage(ps, "not Down"), ps.isDown());
}
@Test
public void testPollWithStarBanner() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "*");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Up"), ps.isUp());
assertFalse(createAssertMessage(ps, "not Down"), ps.isDown());
}
@Test
public void testPollWithRegexpBanner() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "^SSH");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Up"), ps.isUp());
assertFalse(createAssertMessage(ps, "not Down"), ps.isDown());
}
@Test
public void testPollWithBannerOpenSSH() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "OpenSSH");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Up"), ps.isUp());
assertFalse(createAssertMessage(ps, "not Down"), ps.isDown());
}
@Test
public void testPollWithBannerMissing() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "OpenNMS");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Down"), ps.isDown());
assertFalse(createAssertMessage(ps, "not Up"), ps.isUp());
}
@Test
public void testPollWithBannerOpenSSHRegexp() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "^SSH\\-2\\.0\\-OpenSSH_\\d+\\.\\d+.*$");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Up"), ps.isUp());
assertFalse(createAssertMessage(ps, "not Down"), ps.isDown());
}
@Test
public void testPollWithInvalidRegexpBanner() throws UnknownHostException, PatternSyntaxException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "^SSH\\-2\\.0\\-OpenSSH_\\d+\\.\\d+\\g$");
PollStatus ps = sm.poll(svc, parms);
assertTrue(ps.isUnavailable());
assertTrue(createAssertMessage(ps, "Unavailable"), ps.isUnavailable());
}
@Test
public void testPollWithInvalidRegexpMatch() throws UnknownHostException, PatternSyntaxException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.addr(HOST_TO_TEST), "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "^SSH\\-2\\.0\\-OpenSSH_\\d+\\.\\d+\\g$");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Unavailable"), ps.isUnavailable());
}
@Test
public void testPollWithInvalidHost() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", InetAddressUtils.UNPINGABLE_ADDRESS, "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Unavailable"), ps.isUnavailable());
}
@Test
public void testPollWithNoIpAddress() throws UnknownHostException {
ServiceMonitor sm = new SshMonitor();
MonitoredService svc = new MockMonitoredService(1, "Router", null, "SSH");
Map<String, Object> parms = new HashMap<String, Object>();
parms.put("banner", "OpenNMS");
PollStatus ps = sm.poll(svc, parms);
assertTrue(createAssertMessage(ps, "Down"), ps.isDown());
assertFalse(createAssertMessage(ps, "not Up"), ps.isUp());
}
private String createAssertMessage(PollStatus ps, String expectation) {
return "polled service is " + ps.toString() + " not " + expectation + " due to: " + ps.getReason() + " (do you have an SSH daemon running on " + HOST_TO_TEST + "?)";
}
}
|
gpl-2.0
|
manuelgentile/MAP
|
spring/spring_annotation_configurator/src/main/java/it/cnr/itd/uni2014/spring/service/impl/CalcolatoreServiceImpl.java
|
261
|
package it.cnr.itd.uni2014.spring.service.impl;
import it.cnr.itd.uni2014.spring.service.CalcolatoreService;
public class CalcolatoreServiceImpl implements CalcolatoreService {
@Override
public int calculate(int a, int b) {
return a+b;
}
}
|
gpl-2.0
|
mtu-most/most-delta
|
Repetier/libraries/U8gui.cpp
|
22
|
#include <U8glib.cpp>
|
gpl-2.0
|
favedit/MoPlatform
|
mp-platform/webroot/ajs/2-base/MDataset.js
|
28817
|
//==========================================================
// <T>操作数据集的管理类。</T>
//
// @tool
// @param o:object:Object 拥有者对象
// @history 091118 MAOCY 创建
//==========================================================
function MDataset(o){
o = RClass.inherits(this, o, MEditable);
//..........................................................
// @property String 数据集的名称
o.dsName = RClass.register(o, new TPtyStr('dsName', null, 'dataset'));
// @property String 数据集的服务地址
o.dsService = RClass.register(o, new TPtyStr('dsService', EService.WebDataset, 'service'));
// @property Integer 数据集的分页大小
o.dsPageSize = RClass.register(o, new TPtyInt('dsPageSize', 20, 'page_size'));
o.dispToolbar = RClass.register(o, new TPtyBool('dispToolbar', false));
// @property Boolean 是否允许搜索操作
o.editFetch = RClass.register(o, new TPtyBoolSet('editFetch', 'editConfig', EEditConfig.Fetch, false));
// @property Boolean 是否允许搜索操作
o.editSearch = RClass.register(o, new TPtyBoolSet('editSearch', 'editConfig', EEditConfig.Search, false));
// @property Boolean 是否允许复制操作
o.editCopy = RClass.register(o, new TPtyBoolSet('editCopy', 'editConfig', EEditConfig.Copy, false));
// @property String 新建命令
o.insertAction = RClass.register(o, new TPtyStr('insertAction', 'insert'));
// @property String 更新命令
o.updateAction = RClass.register(o, new TPtyStr('updateAction', 'update'));
// @property String 删除命令
o.deleteAction = RClass.register(o, new TPtyStr('deleteAction', 'delete'));
//..........................................................
// @attribute Integer 当前页号
o.dsPageIndex = 0;
// @attribute TDatasetViewer 数据察看器
o.dsViewer = null;
// @attribute TAttributes 固定数据内容
o.dsValues = null;
// @attribute TList<TSearchItem> 表单搜索信息用的列表
o.dsGlobalSearchs = null;
o.dsSearchs = null;
// @attribute TList<TOrderItem> 表单排序信息用的列表
o.dsGlobalOrders = null;
o.dsOrders = null;
//..........................................................
o.__initializeEvent = null;
o.__showEvent = null;
o.__loadedEvent = null;
o.__progress = false;
o.__progressProcess = null;
o.__validProcess = null;
//..........................................................
// @listener
o.lsnsUpdateBegin = null;
o.lsnsUpdateEnd = null;
//..........................................................
// @event
o.onDsFetch = MDataset_onDsFetch;
o.onDsPrepareCheck = RMethod.emptyTrue;
o.onDsPrepare = MDataset_onDsPrepare;
o.onDsUpdateCheck = RMethod.emptyTrue;
o.onDsUpdate = MDataset_onDsUpdate;
o.onDsDeleteCheck = RMethod.emptyTrue;
o.onDsDelete = MDataset_onDsDelete;
o.onDsCopy = MDataset_onDsCopy;
o.onDsDoUpdate = MDataset_onDsDoUpdate;
o.onDsProcess = MDataset_onDsProcess;
o.onLoadDatasetBegin = RMethod.empty;
o.onLoadDataset = RMethod.virtual(o, 'onLoadDataset');
o.onLoadDatasetEnd = RMethod.virtual(o, 'onLoadDatasetEnd');
//..........................................................
// @method
o.getDataCodes = RMethod.virtual(o, 'getDataCodes');
o.getCurrentRow = RMethod.virtual(o, 'getCurrentRow');
o.getSelectedRows = RMethod.virtual(o, 'getSelectedRows');
o.getChangedRows = RMethod.virtual(o, 'getChangedRows');
o.getRows = RMethod.virtual(o, 'getRows');
o.toDeepAttributes = MDataset_toDeepAttributes;
//..........................................................
// @method
o.construct = MDataset_construct;
o.loadDataset = MDataset_loadDataset;
o.loadDatasets = MDataset_loadDatasets;
o.doPrepare = RMethod.virtual(o, 'doPrepare');
o.doDelete = RMethod.virtual(o, 'doDelete');
o.dsInitialize = MDataset_dsInitialize;
o.dsShow = MDataset_dsShow;
o.dsLoaded = MDataset_dsLoaded;
o.dsFetch = MDataset_dsFetch;
o.dsSearch = MDataset_dsSearch;
o.dsCopy = MDataset_dsCopy;
o.dsPrepare = MDataset_dsPrepare;
o.dsUpdate = MDataset_dsUpdate;
o.dsDelete = MDataset_dsDelete;
o.dsMode = MDataset_dsMode;
o.dsDoUpdate = MDataset_dsDoUpdate;
o.dsProcess = MDataset_dsProcess;
o.dsProcessCustom = MDataset_dsProcessCustom;
o.dsProcessChanged = MDataset_dsProcessChanged;
o.dsProcessSelected = MDataset_dsProcessSelected;
o.dsProcessAll = MDataset_dsProcessAll;
o.psProgress = MDataset_psProgress;
o.psValid = MDataset_psValid;
o.dsCurrent = MDataset_dsCurrent;
// Attribute
o.dsStore = null;
o.dsSearchBox = null;
o.dsSearchWindow = null;
o.onStoreChanged = RMethod.empty;
o.onDsFetchBegin = RMethod.empty;
o.onDsFetchEnd = RMethod.empty;
o.onDsUpdateBegin = RMethod.empty;
o.onDsUpdateEnd = RMethod.empty;
// Method
o.hasAction = RMethod.virtual(o, 'hasAction');
o.dsIsChanged = MDataset_dsIsChanged;
o.dsCount = MDataset_dsCount;
o.dsMove = MDataset_dsMove;
o.dsMovePage = MDataset_dsMovePage;
o.dsGet = MDataset_dsGet;
o.dsSet = MDataset_dsSet;
o.dsRefresh = MDataset_dsRefresh;
o.doSearch = MDataset_doSearch;
return o;
}
//==========================================================
// <T>响应数据读取后的操作。</T>
//
// @event
// @param g:arg:TDatasetFetchArg 结果参数对象
//==========================================================
function MDataset_onDsFetch(g){
var o = this;
// 加载数据集
o.loadDatasets(g.resultDatasets);
// 设置加载完成
o.onLoadDatasetEnd();
// 设置焦点
o.focus();
}
//==========================================================
// <T>响应新建操作中,数据读取完成后的操作。</T>
//
// @event
// @param g:arg:TDatasetPrepareArg 结果参数对象
//==========================================================
function MDataset_onDsPrepare(g){
var o = this;
// 加载数据集
g.resultDatasets.set('/', null);
o.loadDatasets(g.resultDatasets);
// 加载主数据
o.doPrepare(g.resultRow);
// 设置加载完成
if(g.invokeSuccess()){
return;
}
o.onLoadDatasetEnd();
// 设置焦点
o.focus();
}
//==========================================================
// <T>响应更新操作中,数据读取完成后的操作。</T>
//
// @event
// @param g:arg:TDatasetFetchArg 结果参数对象
//==========================================================
function MDataset_onDsUpdate(g){
var o = this;
// 加载数据集
o.loadDatasets(g.resultDatasets);
// 设置加载完成
o.onLoadDatasetEnd();
// 设置焦点
o.focus();
}
//==========================================================
// <T>响应更新操作中,数据读取完成后的操作。</T>
//
// @event
// @param g:arg:TDatasetFetchArg 结果参数对象
//==========================================================
function MDataset_onDsCopy(g){
var o = this;
o.loadDatasets(g.resultDatasets);
// 设置加载完成
o.onLoadDatasetEnd();
// 设置焦点
o.focus();
}
//==========================================================
// <T>响应删除操作中,数据读取完成后的操作。</T>
//
// @event
// @param g:arg:TDatasetFetchArg 结果参数对象
//==========================================================
function MDataset_onDsDelete(g){
var o = this;
// 加载数据集
o.loadDatasets(g.resultDatasets);
// 删除主数据
o.doDelete(g.resultRow);
// 设置加载完成
o.onLoadDatasetEnd();
// 设置焦点
o.focus();
}
//==========================================================
// <T>响应数据更新后的操作。</T>
//
// @event
// @param g:arg:TDatasetUpdateArg 结果参数对象
//==========================================================
function MDataset_onDsProcess(g){
var o = this;
var cb = g.resultCallback;
if(cb){
cb.invoke(o, g);
}
}
//==========================================================
// <T>获得一个从指定位置向上所有数据集当前对象的数据内容的集合。</T>
//
// @method
// @param a:attributes:TAttributes 属性集合
// @param m:mode:EStore 存储模式
// @see FRow.isChanged
//==========================================================
function MDataset_toDeepAttributes(a, m){
var o = this;
if(!a){
a = new TAttributes();
}
// 获得所有顶层的数据集对象
var ts = new TList();
var p = o;
while(p){
if(RClass.isClass(p, MDataset)){
ts.push(p);
}
if(!p.parent){
break;
}
p = p.topControl(MDataset);
}
// 内层的数据覆盖外层数据集的数据
for(var n=ts.count; n>=0; n--){
var p = ts.get(n);
if(RClass.isClass(p, FForm)){
p.toAttributes(a, m);
}else if(RClass.isClass(m, FTable)){
var r = p.getCurrentRow();
if(r){
r.toAttributes(a, m);
}
}
}
return a;
}
//==========================================================
// <T>响应数据更新后的操作。</T>
//
// @event
// @param g:argument:TDatasetUpdateArg 参数对象
//==========================================================
function MDataset_onDsDoUpdate(g){
var o = this;
if(!g.invokeSuccess()){
o.psRefresh();
}
// 获得处理完成标志
if(!g.processFinish){
// 重获焦点
o.focus();
// 处理公共事件
o.lsnsUpdateEnd.process(g);
}
// 设置加载完成
o.onLoadDatasetEnd();
//o.psProgress(false);
}
//==========================================================
// <T>构造函数。</T>
//
// @method
//==========================================================
function MDataset_construct(){
var o = this;
// 构造对象
o.dsViewer = new TDatasetViewer();
o.dsValues = new TAttributes();
o.dsSearchs = new TSearchItems();
o.dsGlobalSearchs = new TSearchItems();
o.dsOrders = new TOrderItems();
o.dsGlobalOrders = new TOrderItems();
// 构造事件
o.__initializeEvent = new TEvent();
o.__showEvent = new TEvent();
o.__loadedEvent = new TEvent();
// 构造处理
o.__progressProcess = new TEventProcess(o, 'oeProgress', MProgress);
var vp = o.__validProcess = new TEventProcess(o, 'oeValid', MValidator);
vp.controls = new TList();
// 构造监听器
o.lsnsUpdateBegin = new TListeners();
o.lsnsUpdateEnd = new TListeners();
}
//==========================================================
// <T>加载单个数据集数据。</T>
//
// @method
// @param d:dataset:TDatset 数据集对象
//==========================================================
function MDataset_loadDataset(d){
var o = this;
o.dsStore = d;
d.saveViewer(o.dsViewer);
return o.onLoadDataset(d);
}
//==========================================================
// <T>加载多个数据集数据。</T>
//
// @method
// @param ds:datasets:TMap<String, TDataset> 数据集的集合
//==========================================================
function MDataset_loadDatasets(ds){
var o = this;
var c = ds.count;
for(var n=0; n<c; n++){
var d = ds.value(n);
if(d){
var dc = o.findByPath(d.name)
if(!dc){
dc = o.findByPath(d.name);
return RMessage.fatal(o, null, 'Load dataset failed. (control={0})', d.name);
}
dc.loadDataset(d);
}
}
}
//==========================================================
function MDataset_dsInitialize(){
this.callEvent('onFormInitialize', this, this.__initializeEvent);
}
//==========================================================
function MDataset_dsShow(){
this.callEvent('onFormShow', this, this.__showEvent);
}
//==========================================================
function MDataset_dsLoaded(){
this.callEvent('onDatasetLoaded', this, this.__loadedEvent);
}
//==========================================================
// <T>根据参数信息远程链接,查询数据内容获得结果集。</T>
//
// @method
// @param r:reset:Boolean
// <L value='true'>重置数据集</L>
// <L value='false'>不重置数据集</L>
// @param f:force:Boolean
// <L value='true'>强制获取</L>
// <L value='false'>不强制</L>
//==========================================================
function MDataset_dsFetch(r, f){
var o = this;
// 设置加载中
o.psProgress(true);
// 异步获得数据
var tc = o.topControl();
var g = new TDatasetFetchArg(tc.name, tc.formId, o.dsPageSize, o.dsPageIndex);
g.reset = r;
g.force = f;
g.mode = o._emode;
g.searchs.append(o.dsGlobalSearchs);
g.searchs.append(o.dsSearchs);
g.orders.append(o.dsGlobalOrders);
g.orders.append(o.dsOrders);
o.toDeepAttributes(g.values);
g.values.append(o.dsValues);
g.callback = new TInvoke(o, o.onDsFetch);
RConsole.find(FDatasetConsole).fetch(g);
}
//==========================================================
// <T>根据参数信息远程链接,查询数据内容获得结果集。</T>
//
// @method
// @param r:reset:Boolean
// <L value='true'>重置数据集</L>
// <L value='false'>不重置数据集</L>
// @param f:force:Boolean
// <L value='true'>强制获取</L>
// <L value='false'>不强制</L>
//==========================================================
function MDataset_dsSearch(s){
var o = this;
// 设置加载中
o.psProgress(true);
// 异步获得数据
var tc = o.topControl();
var pth = o.fullPath();
if(s){
pth = s.fullPath();
}
var g = new TDatasetFetchArg(tc.name, tc.formId, o.dsPageSize, 0, true, false, pth);
g.mode = tc._emode;
g.searchs.append(o.dsGlobalSearchs);
g.searchs.append(o.dsSearchs);
g.orders.append(o.dsGlobalOrders);
g.orders.append(o.dsOrders);
o.toDeepAttributes(g.values);
g.values.append(o.dsValues);
g.callback = new TInvoke(o, o.onDsFetch);
RConsole.find(FDatasetConsole).fetch(g);
}
//==========================================================
// <T>获得当前数据集新建一条记录的准备数据。</T>
//
// @method
//==========================================================
function MDataset_dsCopy(r){
var o = this;
// 设置加载中
o.psProgress(true);
// 设置工作模式为新建记录
o.psMode(EMode.Insert);
// 异步获得初始化数据
var g = new TDatasetFetchArg(o.name, o.formId, o.dsPageSize, 0, true);
g.form = o;
g.mode = EMode.Insert;
//g.reset = true;
o.dsSearchs.clear();
o.dsSearchs.push(new TSearchItem('OUID', r.get("OUID")));
g.searchs = o.dsSearchs;
g.callback = new TInvoke(o, o.onDsCopy);
// 更新处理
if(o.onDsUpdateCheck(g)){
RConsole.find(FDatasetConsole).fetch(g);
}
return;
}
//==========================================================
// <T>获得当前数据集新建一条记录的准备数据。</T>
//
// @method
//==========================================================
function MDataset_dsPrepare(cb){
var o = this;
// 设置加载中
o.psProgress(true);
// 设置工作模式为新建记录
o.psMode(EMode.Insert);
// 异步获得初始化数据
var g = new TDatasetPrepareArg(o.name, o.formId);
g.form = o;
g.values.append(o.dsValues);
g.callbackSuccess = cb;
if(o.onDsPrepareCheck(g)){
g.callback = new TInvoke(o, o.onDsPrepare);
RConsole.find(FDatasetConsole).prepare(g);
}
}
//==========================================================
// <T>更新一条记录。</T>
//
// @method
// @param u:ouid:String 唯一标识
// @param v:over:String 行记录的版本
//==========================================================
function MDataset_dsUpdate(u, v){
var o = this;
// 设置加载中
o.psProgress(true);
// 设置工作模式
o.psMode(EMode.Update);
// 获取初始化数据
o.dsFetch(true);
}
//==========================================================
// <T>删除一条记录。</T>
//
// @method
// @param u:ouid:String 记录标识
// @param v:over:String 记录版本
//==========================================================
function MDataset_dsDelete(u, v){
var o = this;
// 设置加载中
o.psProgress(true);
// 设置工作模式为新建记录
o.psMode(EMode.Delete);
// 异步获得初始化数据
var g = new TDatasetFetchArg(o.name, o.formId, o.dsPageSize, 0, true);
g.callback = new TInvoke(o, o.onDsDelete);
g.form = o;
g.mode = EMode.Delete;
if(u){
g.searchs.push(new TSearchItem('OUID', u));
}
if(v){
g.searchs.push(new TSearchItem('OVER', v));
}
g.values = o.dsValues;
if(o.onDsDeleteCheck(g)){
RConsole.find(FDatasetConsole).fetch(g);
}
return;
}
//==========================================================
// <T>根据模式设置操作。</T>
//
// @method
// @param m:mode:EMode 模式
//==========================================================
function MDataset_dsMode(m){
var o = this;
switch(m){
case EMode.Insert:
o.dsPrepare();
break;
case EMode.Update:
o.dsUpdate();
break;
case EMode.Delete:
o.dsDelete();
break;
}
}
//==========================================================
// <T>更新当前数据集内的所有变更过的数据。</T>
//
// @method
// @param cb 更新成功后的回调函数
//==========================================================
function MDataset_dsDoUpdate(cb, ck){
var o = this;
// 有效性检查
if(!o.psValid()){
return;
}
// 获得顶层控件
var t = o.topControl();
// 异步获得初始化数据
var g = new TDatasetUpdateArg(t.name, o.formId, o.dsName);
g.form = o;
g.path = o.fullPath();
g.mode = o._emode;
g.codes = o.getDataCodes();
g.callback = new TInvoke(o, o.onDsDoUpdate);
g.callbackSuccess = cb;
// 检查是否有提交数据
if(EMode.Insert == o._emode || EMode.Delete == o._emode){
g.dataset.rows.append(o.getCurrentRows());
}else{
g.dataset.rows.append(o.getChangedRows());
if(!ck){
if(!g.hasData()){
return RMessage.warn(o, RContext.get('MDataset:nochange'));
}
}
}
// 设置加载中
o.psProgress(true);
// 更新数据
RConsole.find(FDatasetConsole).update(g);
}
//==========================================================
// <T>处理当前获得焦点的记录,执行后台处理过程。</T>
// <P>无论数据是否修改过,都进行处理。如果没有任何数据,将产生警告信息,不进行任何数据处理。</P>
//
// @method
// @param da:dataAction:String 命令名称
// @param cb:callBack:TInvoke 回调处理
//==========================================================
function MDataset_dsProcess(da, cb){
var o = this;
// 有效性检查
if(!o.psValid()){
return;
}
// 构建处理事件对象
var g = new TDatasetServiceArg(o.topControl().name, da);
g.form = o;
g.controlName = o.name;
o.toDeepAttributes(g.attributes);
g.codes = o.getDataCodes();
g.push(o.getCurrentRow());
g.resultCallback = cb;
// 设置加载中
o.psProgress(true);
// 执行处理
g.callback = new TInvoke(o, o.onDsProcess);
RConsole.find(FFormConsole).process(g);
}
//==========================================================
//<T>处理当前获得焦点的记录,执行后台处理过程。</T>
//<P>无论数据是否修改过,都进行处理。如果没有任何数据,将产生警告信息,不进行任何数据处理。</P>
//
//@method
//@param da:dataAction:String 命令名称
//@param cb:callBack:TInvoke 回调处理
//==========================================================
function MDataset_dsProcessCustom(pm, da, cb, cc){
var o = this;
// 有效性检查
if(!cc){
if(!o.psValid()){
return;
}
}
// 构建处理事件对象
var g = new TDatasetServiceArg(o.topControl().name, da);
g.form = o;
g.controlName = o.name;
g.attributes = pm;
g.codes = o.getDataCodes();
g.push(o.getCurrentRow());
g.resultCallback = cb;
// 检查是否有提交数据
if(!cc){
if(!g.hasData()){
return RMessage.warn(o, RContext.get('MDataset:nodata'));
}
}
// 设置加载中
o.psProgress(true);
// 执行处理
g.callback = new TInvoke(o, o.onDsProcess);
RConsole.find(FFormConsole).process(g);
}
//==========================================================
//<T>处理当前获得焦点的记录,执行后台处理过程。</T>
//<P>无论数据是否修改过,都进行处理。如果没有任何数据,将产生警告信息,不进行任何数据处理。</P>
//
//@method
//@param da:dataAction:String 命令名称
//@param cb:callBack:TInvoke 回调处理
//==========================================================
function MDataset_dsProcessSelected(da, cb){
var o = this;
// 有效性检查
if(!o.psValid()){
return;
}
// 构建处理事件对象
var g = new TDatasetServiceArg(o.topControl().name, da);
g.form = o;
g.controlName = o.name;
o.toDeepAttributes(g.attributes);
g.codes = o.getDataCodes();
g.rows = o.getSelectedRows();
if(g.rows.count > 0){
g.resultCallback = cb;
// 检查是否有提交数据
//if(!g.hasData()){
// return RMessage.warn(o, RContext.get('MDataset:nodata'));
//}
// 设置加载中
o.psProgress(true);
// 执行处理
g.callback = new TInvoke(o, o.onDsProcess);
RConsole.find(FFormConsole).process(g);
o.clearSelectRows();
}else{
return RMessage.warn(o, RContext.get('MDataset:norows'));
}
}
//==========================================================
// <T>处理所有修改过的记录,执行后台处理过程。</T>
// <P>只有数据修改过,才进行处理。如果没有修改过的数据,将产生警告信息,不进行任何数据处理。</P>
//
// @method
// @param da:dataAction:String 命令名称
// @param cb:callBack:TInvoke 回调处理
//==========================================================
function MDataset_dsProcessChanged(da, cb){
var o = this;
// 有效性检查
if(!o.psValid()){
return;
}
// 构建处理事件对象
var g = new TDatasetServiceArg(o.topControl().name, da);
g.form = o;
g.controlName = o.name;
o.toDeepAttributes(g.attributes);
g.codes = o.getDataCodes();
g.rows = o.getChangedRows();
g.resultCallback = cb;
// 检查是否有提交数据
if(!g.hasData()){
return RMessage.warn(o, RContext.get('MDataset:nochange'));
}
// 设置加载中
o.psProgress(true);
// 执行处理
g.callback = new TInvoke(o, o.onDsProcess);
RConsole.find(FFormConsole).process(g);
}
//==========================================================
// <T>处理所有记录,执行后台处理过程。</T>
// <P>无论数据是否修改过,都进行处理。如果没有任何数据,将产生警告信息,不进行任何数据处理。</P>
//
// @method
// @param da:dataAction:String 命令名称
// @param cb:callBack:TInvoke 回调处理
//==========================================================
function MDataset_dsProcessAll(da, cb){
var o = this;
// 有效性检查
if(!o.psValid()){
return;
}
// 构建处理事件对象
var g = new TDatasetServiceArg(o.topControl().name, da);
g.form = o;
g.controlName = o.name;
o.toDeepAttributes(g.attributes);
g.codes = o.getDataCodes();
g.rows = o.getRows();
g.resultCallback = cb;
// 检查是否有提交数据
//if(!g.hasData()){
// return RMessage.warn(o, RContext.get('MDataset:nodata'));
//}
// 设置加载中
o.psProgress(true);
// 执行处理
g.callback = new TInvoke(o, o.onDsProcess);
RConsole.find(FFormConsole).process(g);
}
//==========================================================
// <T>显示是否正在处理进度。</T>
//
// @method
// @param v:visible 可见性
//==========================================================
function MDataset_psProgress(v){
var o = this;
// 检查状态变更
if(o.__progress == v){
return;
}
o.__progress = v;
// 纷发事件
var e = o.__progressProcess;
e.enable = v;
o.process(e);
}
//==========================================================
// <T>校验所有项目数据。</T>
//
// @method
//==========================================================
function MDataset_psValid(){
var o = this;
// 校验数据
var e = o.__validProcess;
var cs = e.controls;
cs.clear();
o.process(e);
// 校验结果
if(!cs.isEmpty()){
var cw = RConsole.find(FCheckWindowConsole).find();
cw.set(cs);
cw.show();
return false;
}
return true;
}
//==========================================================
// <T>获得操作的当前记录。</T>
//
// @tool
// @param o:object:Object 拥有者对象
// @author maocy
// @version 1.0.1
//==========================================================
function MDataset_dsCurrent(){
var o = this;
var ds = o.dsStore;
}
// ------------------------------------------------------------
function MDataset_dsIsChanged(){
var ds = this.dsStore;
return ds ? ds.isChanged() : false;
}
// ------------------------------------------------------------
function MDataset_dsCount(){
return this.dsStore ? this.dsStore.count : 0;
}
// ------------------------------------------------------------
// position, force
function MDataset_dsMove(p){
var o = this;
var ds = o.dsStore;
// Check
if(null == p && !ds){
return;
}
// Calculate
if(!RInt.isInt(p)){
if(EDataAction.First == p){
ds.moveFirst();
}else if(EDataAction.Prior == p){
ds.movePrior();
}else if(EDataAction.Next == p){
ds.moveNext();
}else if(EDataAction.Last == p){
ds.moveLast();
}else{
RMessage.fatal(o, null, 'Unknown position (postion={0})', p);
}
}else{
ds.move(p);
}
if(RClass.isClass(o, MValue)){
o.loadValue(ds.current());
}
}
// ------------------------------------------------------------
// page, force
function MDataset_dsMovePage(p){
var o = this;
var ds = o.dsStore;
if(!RInt.isInt(p)){
if(EDataAction.First == p){
p = 0;
}else if(EDataAction.Prior == p){
p = ds.pageIndex;
if(p > 0){
p--;
}
}else if(EDataAction.Next == p){
p = ds.pageIndex;
if(p < ds.pageCount - 1){
p++;
}
}else if(EDataAction.Last == p){
p = ds.pageCount - 1;
}else{
RMessage.fatal(o, null, 'Unknown page (page={0})', p);
}
}
if(p != ds.pageIndex){
// 设置加载中
o.psProgress(true);
// 异步获得数据
var t = o.topControl(MDataset);
var g = new TDatasetFetchArg(t.name, t.formId, o.dsPageSize, p, true);
g.path = o.fullPath();
g.mode = t._emode;
g.searchs.append(o.dsGlobalSearchs);
g.searchs.append(o.dsSearchs);
g.orders.append(o.dsGlobalOrders);
g.orders.append(o.dsOrders);
g.values = o.toDeepAttributes();
g.values.append(o.dsValues);
g.callback = new TInvoke(o, o.onDsFetch);
RConsole.find(FDatasetConsole).fetch(g);
}
}
// ------------------------------------------------------------
function MDataset_dsGet(n){
return this.dsStore ? this.dsStore.get(n) : '';
}
// ------------------------------------------------------------
function MDataset_dsSet(n, v){
if(this.dsStore){
this.dsStore.set(n, v);
}
}
// ------------------------------------------------------------
function MDataset_dsRefresh(){
if(this.dsService){
this.dsMove(this.dsPage, true);
}
}
// ------------------------------------------------------------
function MDataset_doSearch(){
var o = this;
var sw = o.dsSearchWindow;
if(!sw){
sw = o.dsSearchWindow = top.RControl.create(top.FSearchWindow);
sw.linkDsControl(o);
}
sw.show();
}
|
gpl-2.0
|
waqarmuneer/RN-Cor
|
tmp/install_50a62d3b00c3a/com_rednet/site/views/orders/tmpl/default_order_form.php
|
15848
|
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
JHtml::_ ( 'behavior.formvalidation' );
$app = JFactory::getApplication();
$form_data = $this->form_data;
$ad_on_orders = $form_data['ad_on_orders'];
$heading = '';
$add_on_txt = '';
if($form_data['is_addon'])
{
$add_on_txt = 'Add-on ';
}
if($form_data['action']=='add')
{
$heading = 'Create '.$add_on_txt.'Order';
}
if($form_data['action']=='update')
{
$heading = 'Update Order';
}
$order = $this->order;
if($order->departure_time != NULL)
{
$dep_time = date('h:i:s A',strtotime($order->departure_time));
//if add-on order receiving Departure Time
if( isset($form_data['dt']) )
{
$dep_time = date('h:i:s A',strtotime($form_data['dt']));
}
}else
{
$dep_time = date('h:i:s A',strtotime('07:30:00 AM'));
//if add-on order receiving Departure Time
if( isset($form_data['dt']) )
{
$dep_time = date('h:i:s A',strtotime($form_data['dt']));
}
}
$time_array = array();
$time_array = split(' ',$dep_time);
$time = split(':',$time_array[0]);
$time_option = strtolower($time_array[1]);
?>
<script type="text/javascript">
$('document').ready(function(){
$('input#type_order_other').keyup(function(){
type_order_error=false;
});
<?php if($order->type_order == 'others'){ ?>
$('p#type_other').show();
<?php } ?>
});
function CompDate(adate,bdate,msg)
{
a = adate.split('/');
b = bdate.split('/');
var sDate = new Date(a[2],a[0]-1,a[1]);
var eDate = new Date(b[2],b[0]-1,b[1]);
if (sDate <= eDate )
{
return true;
}
else
{
//alert(msg);
return false;
}
}
function validate_order(){
if($('select#hrs').val()==0)
{
alert('Please select Departure time correctly');
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
if($('select#mins').val()=='nil')
{
alert('Please select Departure time correctly');
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
if($('select#type_order').val()=='0')
{
alert('Please select Type!');
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
if(type_order_error==true)
{
alert('Please select Type other!');
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
if($('#instruction_file').val() != "")
{
var ext = $('#instruction_file').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['pdf','csv']) == -1) {
alert('Invalid instructions file type!');
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
}
var return_val = true;
var required_fields = $('.form-validate').find('.required').get();
$(required_fields).each(function(indx,obj){
if($(obj).val()=='')
{
alert("Please Enter "+$(obj).attr('name').split('_').join(' ').toUpperCase());
return_val = false;
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
return return_val;
});
var today_date = $('#today_date').val();
var order_date = $('#date_order').val();
var rslt_date = CompDate(today_date,order_date,"You are entring the 'Order Date' from previouse days.");
if(rslt_date == false)
{
var msg = confirm("'Order Date' is from previouse days.");
if(msg == false)
{
if(navigator.appName == "Microsoft Internet Explorer")
event.returnValue = false;
else
return false;
}
}
return return_val;
}
</script>
<style type="text/css">
.invalid {color:#B30000;}
</style>
<jdoc:include type="message" />
<div>
<table border="0" style="margin-left: 35px;">
<tr>
<td><img style="margin-right: 5px !important;" src="<?php echo $this->baseurl ?>/templates/<?php echo $app->getTemplate() ?>/images/order.gif" alt=" " id="lock_icon" width="40" /></td>
<td><h3><?php echo $heading;?></h3></td>
</tr>
</table>
<script type="text/javascript">
$('ready').ready(function(){
$('#adon_order_button').click(function(){
var server = "<?php echo JURI::base(); ?>";
var p_o= "<?php echo "$order->id"; ?>";
var m = $('#no_of_men').val();
var t = $('#no_of_trucks').val();
var tr = $('#dl_no2').val();
var od = $('#date_order').val();
var dt = $('#date_order').val();
var qry_string = "p_o="+p_o+"&m="+m+"&t="+t+"&tr="+tr+"&od="+od+"&dt="+dt;
var path =server+"<?php echo "index.php/component/rednet/orders?task=order_form&";?>"+qry_string;
window.location = path;
});
});
</script>
<?php if($form_data['action']=='update'){ ?>
<p>
<input class="button" type="submit" value="Ad-On Order" name="order_button" id="adon_order_button" style="font-size: 12px;margin-left: 85px;" />
</p>
<br />
<?php } ?>
</div>
<div class="form_wrapper_app_order">
<div class="mainform_left"></div>
<div class="mainform_middle">
<input type="hidden" name="today_date" id="today_date" value="<?php echo date('m/d/Y') ?>" />
<form class="form-validate" id="edit_worker_form" action="<?php echo JRoute::_("index.php/component/rednet/orders?task=order_form_save")?>" method="post" onSubmit="return validate_order();" enctype="multipart/form-data">
<input type="hidden" name="id" id="id" value="<?php echo $order->id;?>" />
<input type="hidden" name="action" id="action" value="<?php echo $form_data['action'];?>" />
<input type="hidden" name="is_addon" id="is_addon" value="<?php echo (isset($order->is_addon) && $order->is_addon!='0')?($order->is_addon):( ($form_data['is_addon']=='1')?'1':'0' ) ;?>" />
<input type="hidden" name="parent_order" id="parent_order" value="<?php echo isset($order->parent_order)?($order->parent_order):(JRequest::getVar('p_o'));?>" />
<table width="100%" border="0">
<tr>
<td><p class="field_para">
<label for="order_no">Order#</label>
<input name="order_no" type="text" class="main_forms_field required" id="order_no" tabindex="1" value="<?php echo $order->order_no;?>" /> <label for="fist_name"></label>
</p>
</td>
<td><p class="field_para">
<label for="name">Name</label>
<input name="name" type="text" class="main_forms_field required" id="name" tabindex="2" value="<?php echo $order->name;?>" /></p></td>
<td>
<p class="field_para">
<label for="date_order">Date (mm/dd/yyyy)</label>
<input name="date_order" type="text" class="main_forms_field required" id="date_order" tabindex="3" value="<?php echo (isset($order->date_order))?(date('m/d/Y',strtotime($order->date_order))):('');?><?php echo (isset($form_data['od']))?(date('m/d/Y',strtotime($form_data['od']))):('')?>">
</p>
</td>
</tr>
<!-- start ad-on -->
<?php if(count($ad_on_orders)!=0):?>
<?php foreach($ad_on_orders as $ordr): ?>
<tr>
<td><p class="field_para">
<label for="order_no">Ad-On Order# <a style="text-decoration: none;font-weight: bold;" href="<?php echo JURI::base()."index.php/component/rednet/orders?task=order_form&id=$ordr->id" ; ?>">Edit</a></label>
<input name="adorder_no" type="text" disabled="disables" class="main_forms_field" id="adorder_no" tabindex="" value="<?php echo $ordr->order_no;?>" /> <label for="adfist_name"></label>
</p>
</td>
<td><p class="field_para">
<label for="adname">Name</label>
<input name="aadname" type="text" disabled="disables" class="main_forms_field" id="adname" tabindex="" value="<?php echo $ordr->name;?>" /></p></td>
<td>
<p class="field_para">
<label for="date_order">Date (mm/dd/yyyy)</label>
<input name="ad_date_order" disabled="disables" type="text" class="main_forms_field" id="ad_date_order" tabindex="" value="<?php echo (isset($ordr->date_order))?(date('m/d/Y',strtotime($ordr->date_order))):('');?>">
</p>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
<!-- end ad-on -->
<tr>
<td><p class="field_para">
<label for="type_order">Order Type</label>
<select name="type_order" id="type_order" class="type_order" style="width: 135px;">
<option value="0"> -- Select --</option>
<option value="move" <?php echo ($order->type_order=='move')?('selected=selected'):('')?>>Move</option>
<option value="move_fmi" <?php echo ($order->type_order=='move_fmi')?('selected=selected'):('')?>>Move/FMI</option>
<option value="fmi_move" <?php echo ($order->type_order=='fmi_move')?('selected=selected'):('')?>>FMI/Move</option>
<option value="fmi" <?php echo ($order->type_order=='fmi')?('selected=selected'):('')?>>FMI</option>
<option value="wbe" <?php echo ($order->type_order=='pack')?('selected=selected'):('')?>>PACK</option>
<option value="others" <?php echo ($order->type_order=='others')?('selected=selected'):('')?>>others</option>
</select>
<label for="type_order"></label>
</p></td>
<td><p class="field_para">
<label for="no_of_trucks">No Of Men</label><input name="no_of_men" type="text" class="main_forms_field_date required" id="no_of_men" tabindex="4" value="<?php echo $order->no_of_men;?><?php echo (isset($form_data['m']))?($form_data['m']):('')?>" />
</p></td>
<td><p class="field_para">
<label for="no_of_trucks">No Of Truck(s)</label>
<input name="no_of_trucks" type="text" class="main_forms_field_date required" id="no_of_trucks" tabindex="5" value="<?php echo $order->no_of_trucks;?><?php echo (isset($form_data['t']))?($form_data['t']):('')?>" />
</p></td>
</tr>
<tr>
<td><p class="field_para" id="type_other">
<label for="type_order_other">Order Other Type</label>
<input name="type_order_other" type="text" class="main_forms_field" id="type_order_other" value="<?php echo $order->type_if_other;?>" />
<label for="type_order_other"></label>
</p></td>
<td>
<td> </td>
</tr>
<tr>
<td><p class="field_para">
<label for="dl_no2">Truck Requirments</label>
<input name="truck_requirments" type="text" class="main_forms_field required" id="dl_no2" tabindex="6" value="<?php echo $order->truck_requirments;?><?php echo (isset($form_data['tr']))?($form_data['tr']):('')?>" />
</p></td>
<td><p class="field_para">
<label for="class2">Out of town</label>
<p>
<label>
<input type="radio" name="out_of_town" value="yes" id="out_of_town_0" <?php echo ($order->out_of_town == 'yes')?('checked=checked'):('')?>>
Yes</label>
<label style="margin-left: 20px">
<input type="radio" name="out_of_town" value="no" id="out_of_town_1" <?php echo (!isset($order->out_of_town))?('checked=checked'):('')?> <?php echo ($order->out_of_town == 'no')?('checked=checked'):('')?> />
No</label>
</p>
<p class="field_para">
<td><p class="field_para">
<label for="hrs">Departure time</label>
<br />
<select name ="hrs" id="hrs" class="hrs" style="width: 10px;">
<option value="0">hrs</option>
<?php for($i=1; $i<=12; $i++):?>
<option value="<?php echo $i;?>" <?php echo ($i == "$time[0]")?('selected=selected'):('');?>><?php echo $i;?></option>
<?php endfor; ?>
</select>
<select name ="mins" id="mins" class="mins" style="width: 10px;">
<option value="nil">mins</option>
<?php for($x=0; $x<=45; $x = $x+15):?>
<option value="<?php echo ($x == '0')?('00'):($x);?>" <?php echo ($x == "$time[1]")?('selected=selected'):('');?>><?php echo ($x == '0')?('00'):($x);?></option>
<?php endfor; ?>
</select>
</p>
<p style="font-size: 12px;">
</p>
<p style="font-size: 12px;">
<label style="margin-left: 10px;">
<input type="radio" name="time_option" value="am" id="time_option_0" <?php echo ($time_option=='am')?('checked=checked'):('')?> <?php echo(!isset($order->departure_time))?('checked=checked'):('') ?> />
AM</label>
<br>
<label style="margin-left: 10px;">
<input type="radio" name="time_option" value="pm" id="time_option_1" <?php echo ($time_option=='pm')?('checked=checked'):('')?>>
PM</label>
<br>
</p></td>
</tr>
<tr>
<!--
<td><p class="field_para">
<label for="deposite">Deposit</label>
<input name="deposite" type="text" class="main_forms_field required" id="deposite" tabindex="7" value="<?php echo $order->deposite;?>" /></p>
</td>
-->
<td colspan="3">
<p class="field_para" style="margin-top: 20px">
<label for="cell">Attach crew instruction</label>
<input name="instruction_file" type="file" id="instruction_file" class="main_forms_field <?php echo (!isset($order->instruction_file))?(''):('');?>" tabindex="8" style="width: 300px" />
<input name="old_instruction_file" type="hidden" id="old_instruction_file" value="<?php echo $order->instruction_file;?>" />
<?php if(isset($order->instruction_file) && $order->instruction_file!='')
{?>
<p style="text-align: right;width: 210px"><a href="<?php echo JUri::base().'files/'.$order->instruction_file ?>">View file</a></p>
<?php } ?>
</p>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<br />
<div class="role_wrapper"> </div>
<p style="float: left"><input type="submit" value="Save" name="save" /></p>
</form>
</div>
<div class="mainform_left"></div>
</div>
|
gpl-2.0
|
unioslo/cerebrum
|
contrib/event/republisher.py
|
1618
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2015 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""This job publishes events residing in the event-backlog.
The event-backlog is filled with events, if the broker is down, or the network
is broken. This script should be run regularly (every five minutes or so), to
publish the messages.
The backlog is normally handeled by the event_publisher, but this only happens
when new events are beeing generated.
"""
from Cerebrum.Utils import Factory
logger = Factory.get_logger('cronjob')
def do_it():
db = Factory.get('Database')()
db._EventPublisher__try_send_messages()
db.commit()
if __name__ == '__main__':
try:
import argparse
except ImportError:
from Cerebrum.extlib import argparse
argp = argparse.ArgumentParser(description=u"""Republish failed events.""")
args = argp.parse_args()
do_it()
|
gpl-2.0
|
jeremyfr/co_nomad
|
Nomad/src/com/eads/co/nomad/ATALevel2.java
|
777
|
package com.eads.co.nomad;
import java.util.ArrayList;
public class ATALevel2 {
private String description;
private ArrayList<ATALevel3> listATALevel3;
public ATALevel2(String description) {
this.description = description;
listATALevel3 = new ArrayList<ATALevel3>();
}
public ATALevel2(String description, ArrayList<ATALevel3> listATALevel3) {
this.description = description;
this.listATALevel3 = listATALevel3;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<ATALevel3> getListATALevel3() {
return listATALevel3;
}
public void setListATALevel3(ArrayList<ATALevel3> listATALevel3) {
this.listATALevel3 = listATALevel3;
}
}
|
gpl-2.0
|
akiver/CSGO-Demos-Manager
|
Core/Models/Maps/Dust2.cs
|
162
|
namespace Core.Models.Maps
{
public class Dust2 : Map
{
public Dust2()
{
Name = "de_dust2";
PosX = -2400;
PosY = 3383;
Scale = 4.4;
}
}
}
|
gpl-2.0
|
BIORIMP/biorimp
|
BIO-RIMP/test_data/code/cio/src/main/java/org/apache/commons/io/filefilter/ConditionalFileFilter.java
|
2054
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.filefilter;
import java.util.List;
/**
* Defines operations for conditional file filters.
*
* @since 1.1
* @version $Id: ConditionalFileFilter.java 1303950 2012-03-22 18:16:04Z ggregory $
*/
public interface ConditionalFileFilter {
/**
* Adds the specified file filter to the list of file filters at the end of
* the list.
*
* @param ioFileFilter the filter to be added
* @since 1.1
*/
void addFileFilter(IOFileFilter ioFileFilter);
/**
* Returns this conditional file filter's list of file filters.
*
* @return the file filter list
* @since 1.1
*/
List<IOFileFilter> getFileFilters();
/**
* Removes the specified file filter.
*
* @param ioFileFilter filter to be removed
* @return <code>true</code> if the filter was found in the list,
* <code>false</code> otherwise
* @since 1.1
*/
boolean removeFileFilter(IOFileFilter ioFileFilter);
/**
* Sets the list of file filters, replacing any previously configured
* file filters on this filter.
*
* @param fileFilters the list of filters
* @since 1.1
*/
void setFileFilters(List<IOFileFilter> fileFilters);
}
|
gpl-2.0
|
manniss/WCell2
|
Services/WCell.RealmServer/Spells/Auras/Mod/ModManaRegenInterrupt.cs
|
1289
|
/*************************************************************************
*
* file : ModManaRegenInterrupt.cs
* copyright : (C) The WCell Team
* email : info@wcell.org
* last changed : $LastChangedDate: 2009-03-07 07:58:12 +0100 (lø, 07 mar 2009) $
* last author : $LastChangedBy: ralekdev $
* revision : $Rev: 784 $
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
*************************************************************************/
using WCell.Constants;
using WCell.RealmServer.Modifiers;
namespace WCell.RealmServer.Spells.Auras.Handlers
{
/// <summary>
/// Boosts interrupted Mana regen.
/// See: http://www.wowwiki.com/Formulas:Mana_Regen#Five_Second_Rule
/// </summary>
public class ModManaRegenInterruptHandler : AuraEffectHandler
{
protected override void Apply()
{
m_aura.Auras.Owner.ChangeModifier(StatModifierInt.ManaRegenInterruptPct, EffectValue);
}
protected override void Remove(bool cancelled)
{
m_aura.Auras.Owner.ChangeModifier(StatModifierInt.ManaRegenInterruptPct, -EffectValue);
}
}
};
|
gpl-2.0
|
hellkite500/HydroQGIS
|
HydroData/services/USGSPeak.py
|
5589
|
# -*- coding: utf-8 -*-
"""
/***************************************************************************
FFA worker class for downloading USGS peak flow data using a QThread
-------------------
begin : 2015-04-01
git sha : $Format:%H$
copyright : (C) 2014 by Nels Frazier
email : hellkite500@gmail.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from PyQt4.QtCore import QObject, pyqtSignal, QVariant
from qgis.core import QgsVectorLayer, QgsField, QgsFeature, QgsGeometry, QgsPoint, QgsMessageLog
import urllib
import json
import math
import os
import pandas as pd
class USGSPeakWorker(QObject):
"""Worker thread for calling NWIS web service"""
def __init__(self, stations):
QObject.__init__(self)
self.stations = stations
QgsMessageLog.logMessage('Station Len: '+str(len(stations)), 'Debug', QgsMessageLog.INFO)
self.killed = False
self.plugin_path = os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]
self.data_dir = os.path.join(self.plugin_path, 'tmp')
QgsMessageLog.logMessage(self.data_dir, 'Debug', QgsMessageLog.INFO)
"""
Get flood peak data from usgs for the stations listed in station_file
"""
def getFloodPeaks(self):
#Web root for USGS peakflow data
usgs_root = 'http://nwis.waterdata.usgs.gov/nwis/peak'
#Start building the peak flow query string
query = usgs_root + '?multiple_site_no='
#Add in all stations to the query string
for s in self.stations:
query += s+'%2C'
#QgsMessageLog.logMessage('Code '+s, 'Debug', QgsMessageLog.INFO)
#Quick hack to remove the last %2C from the query
query = query[:-3:]
#Add additional parameters to the http string
query += '&group_key=NONE'
query += '&sitefile_output_format=rdb_file'
query += '&column_name=agency_cd'
query += '&column_name=site_no'
query += '&column_name=station_nm'
query += '&column_name=lat_va'
query += '&column_name=long_va'
query += '&set_logscale_y=1'
query += '&format=rdb'
query += '&date_format=separate_columns'
query += '&rdb_compression=value'
query += '&hn2_compression=file'
query += '&list_of_search_criteria=multiple_site_no'
#Get peak flow file
#QgsMessageLog.logMessage(query, 'Debug', QgsMessageLog.INFO)
#TODO/FIXME Can throw error if run enough times....too many open files :S
urllib.urlretrieve(query, os.path.join(self.data_dir, 'peak'))
"""
Get the latitude, longitude, and drainage area for the stations listed in station_file
"""
def getLatLong(self):
#Web root for USGS peakflow data
usgs_root = 'http://nwis.waterdata.usgs.gov/nwis/peak'
#Start building the peak flow query string
query = usgs_root + '?multiple_site_no='
#Add in all stations to the query string
for s in self.stations:
query += s+'%2C'
#Quick hack to remove the last %2C from the query
query = query[:-3:]
#Now get lat_long data for the stations
#Add additional parameters to url
query += '&group_key=huc_cd'
query += '&format=sitefile_output'
query += '&sitefile_output_format=rdb'
query += '&column_name=site_no'
query += '&column_name=dec_lat_va'
query += '&column_name=dec_long_va'
query += '&column_name=coord_acy_cd'
query += '&column_name=coord_datum_cd'
query += '&column_name=drain_area_va'
query += '&set_logscale_y=1'
query += '&date_format=YYYY-MM-DD'
query += '&rdb_compression=file'
query += '&hn2_compression=file'
query += '&list_of_search_criteria=multiple_site_no'
#Make http request
urllib.urlretrieve(query, os.path.join(self.data_dir, 'dec_lat_long'))
#QgsMessageLog.logMessage(query, 'Debug', QgsMessageLog.INFO)
def run(self):
"""
Downloads peak flow data for given stations from USGS
TODO DESCRIBE MORE!!!
"""
try:
self.status.emit('attempting download')
self.getFloodPeaks()
self.getLatLong()
self.status.emit('Finished downloading data...')
self.finished.emit(True)
#should we download peak flow data, parse, and delete? Cache? Store as attributes???
except Exception, e:
import traceback
self.error.emit(e, traceback.format_exc())
self.status.emit("Error in FFA Service Thread")
#print e, traceback.format_exc()
self.finished.emit(False)
status = pyqtSignal(str)
error = pyqtSignal(Exception, basestring)
finished = pyqtSignal(bool)
|
gpl-2.0
|
davilla/mrmc
|
xbmc/linux/LinuxTimezone.cpp
|
7330
|
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <time.h>
#include "system.h"
#ifdef TARGET_ANDROID
#include "android/bionic_supplement/bionic_supplement.h"
#endif
#include "PlatformInclude.h"
#include "LinuxTimezone.h"
#include "utils/SystemInfo.h"
#if defined(TARGET_DARWIN)
#include "platform/darwin/OSXGNUReplacements.h"
#endif
#ifdef TARGET_FREEBSD
#include "freebsd/FreeBSDGNUReplacements.h"
#endif
#include "Util.h"
#include "utils/StringUtils.h"
#include "XBDateTime.h"
#include "settings/lib/Setting.h"
#include "settings/Settings.h"
#include <stdlib.h>
#include <algorithm>
using namespace std;
CLinuxTimezone::CLinuxTimezone() : m_IsDST(0)
{
char* line = NULL;
size_t linelen = 0;
int nameonfourthfield = 0;
std::string s;
std::vector<std::string> tokens;
// Load timezones
FILE* fp = fopen("/usr/share/zoneinfo/zone.tab", "r");
if (fp)
{
std::string countryCode;
std::string timezoneName;
while (getdelim(&line, &linelen, '\n', fp) > 0)
{
tokens.clear();
s = line;
StringUtils::Trim(s);
if (s.length() == 0)
continue;
if (s[0] == '#')
continue;
StringUtils::Tokenize(s, tokens, " \t");
if (tokens.size() < 3)
continue;
countryCode = tokens[0];
timezoneName = tokens[2];
if (m_timezonesByCountryCode.count(countryCode) == 0)
{
vector<std::string> timezones;
timezones.push_back(timezoneName);
m_timezonesByCountryCode[countryCode] = timezones;
}
else
{
vector<std::string>& timezones = m_timezonesByCountryCode[countryCode];
timezones.push_back(timezoneName);
}
m_countriesByTimezoneName[timezoneName] = countryCode;
}
fclose(fp);
}
if (line)
{
free(line);
line = NULL;
linelen = 0;
}
// Load countries
fp = fopen("/usr/share/zoneinfo/iso3166.tab", "r");
if (!fp)
{
fp = fopen("/usr/share/misc/iso3166", "r");
nameonfourthfield = 1;
}
if (fp)
{
std::string countryCode;
std::string countryName;
while (getdelim(&line, &linelen, '\n', fp) > 0)
{
s = line;
StringUtils::Trim(s);
/* TODO:STRING_CLEANUP */
if (s.length() == 0)
continue;
if (s[0] == '#')
continue;
// Search for the first non space from the 2nd character and on
int i = 2;
while (s[i] == ' ' || s[i] == '\t') i++;
if (nameonfourthfield)
{
// skip three letter
while (s[i] != ' ' && s[i] != '\t') i++;
while (s[i] == ' ' || s[i] == '\t') i++;
// skip number
while (s[i] != ' ' && s[i] != '\t') i++;
while (s[i] == ' ' || s[i] == '\t') i++;
}
countryCode = s.substr(0, 2);
countryName = s.substr(i);
m_counties.push_back(countryName);
m_countryByCode[countryCode] = countryName;
m_countryByName[countryName] = countryCode;
}
sort(m_counties.begin(), m_counties.end(), sortstringbyname());
fclose(fp);
}
free(line);
}
void CLinuxTimezone::OnSettingChanged(const CSetting *setting)
{
if (setting == NULL)
return;
const std::string &settingId = setting->GetId();
if (settingId == CSettings::SETTING_LOCALE_TIMEZONE)
{
SetTimezone(((CSettingString*)setting)->GetValue());
CDateTime::ResetTimezoneBias();
}
else if (settingId == CSettings::SETTING_LOCALE_TIMEZONECOUNTRY)
{
// nothing to do here. Changing locale.timezonecountry will trigger an
// update of locale.timezone and automatically adjust its value
// and execute OnSettingChanged() for it as well (see above)
}
}
void CLinuxTimezone::OnSettingsLoaded()
{
SetTimezone(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_TIMEZONE));
CDateTime::ResetTimezoneBias();
}
vector<std::string> CLinuxTimezone::GetCounties()
{
return m_counties;
}
vector<std::string> CLinuxTimezone::GetTimezonesByCountry(const std::string& country)
{
return m_timezonesByCountryCode[m_countryByName[country]];
}
std::string CLinuxTimezone::GetCountryByTimezone(const std::string& timezone)
{
#if defined(TARGET_DARWIN)
return "?";
#else
return m_countryByCode[m_countriesByTimezoneName[timezone]];
#endif
}
void CLinuxTimezone::SetTimezone(std::string timezoneName)
{
#if !defined(TARGET_DARWIN)
bool use_timezone = true;
#else
bool use_timezone = false;
#endif
if (use_timezone)
{
static char env_var[255];
sprintf(env_var, "TZ=:%s", timezoneName.c_str());
putenv(env_var);
tzset();
}
}
std::string CLinuxTimezone::GetOSConfiguredTimezone()
{
char timezoneName[255];
// try Slackware approach first
ssize_t rlrc = readlink("/etc/localtime-copied-from"
, timezoneName, sizeof(timezoneName)-1);
if (rlrc != -1)
{
timezoneName[rlrc] = '\0';
char* p = strrchr(timezoneName,'/');
if (p)
{ // we want the previous '/'
char* q = p;
*q = 0;
p = strrchr(timezoneName,'/');
*q = '/';
if (p)
p++;
}
return p;
}
// now try Debian approach
timezoneName[0] = 0;
FILE* fp = fopen("/etc/timezone", "r");
if (fp)
{
if (fgets(timezoneName, sizeof(timezoneName), fp))
timezoneName[strlen(timezoneName)-1] = '\0';
fclose(fp);
}
return timezoneName;
}
void CLinuxTimezone::SettingOptionsTimezoneCountriesFiller(const CSetting *setting, std::vector< std::pair<std::string, std::string> > &list, std::string ¤t, void *data)
{
vector<std::string> countries = g_timezone.GetCounties();
for (unsigned int i = 0; i < countries.size(); i++)
list.push_back(make_pair(countries[i], countries[i]));
}
void CLinuxTimezone::SettingOptionsTimezonesFiller(const CSetting *setting, std::vector< std::pair<std::string, std::string> > &list, std::string ¤t, void *data)
{
current = ((const CSettingString*)setting)->GetValue();
bool found = false;
vector<std::string> timezones = g_timezone.GetTimezonesByCountry(CSettings::GetInstance().GetString(CSettings::SETTING_LOCALE_TIMEZONECOUNTRY));
for (unsigned int i = 0; i < timezones.size(); i++)
{
if (!found && StringUtils::EqualsNoCase(timezones[i], current))
found = true;
list.push_back(make_pair(timezones[i], timezones[i]));
}
if (!found && timezones.size() > 0)
current = timezones[0];
}
CLinuxTimezone g_timezone;
|
gpl-2.0
|
nimaghorbani/THOR
|
plugins/block.lua
|
715
|
do
local function block_user_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local user = 'user#id'..result.id
if success == 0 then
return send_large_msg(receiver, "I cant block user.")
end
block_user(user, cb_ok, false)
end
end
local function run(msg, matches)
if msg.to.type == 'chat' then
local user = 'chat#id'..msg.to.id
local user = matches[2]
if matches[1] == "user" then
user = 'user#id'..user
block_user(user, callback, false)
end
if not is_sudo(msg) then
return "sicktir baw only sudo😡!"
end
return "User Has Been Blocked by sudo!"
end
end
return {
patterns = {
"^[/!$&]([Bb]lock) (user) (%d+)$",
},
run = run,
}
|
gpl-2.0
|
zaijung/udis
|
wp-content/themes/atticus/js/custom.js
|
3555
|
"use strict";
jQuery(document).ready(function(){
jQuery('.menu li a').click(function() {
var href = jQuery(this).attr('href');
jQuery("html, body").animate({ scrollTop: jQuery(href).offset().top - 90 }, 1000);
return false;
});
/* RESPONSIVE VIDEOS */
jQuery(".main").fitVids();
/*blog hover image*/
jQuery( ".blogpostcategory" ).each(function() {
var img = jQuery(this).find('img');
var height = img.height();
var width = img.width();
var over = jQuery(this).find('a.overdefultlink');
over.css({'width':width+'px', 'height':height+'px'});
var margin_left = parseInt(width)/2 - 18
var margin_top = parseInt(height)/2 - 18
over.css('backgroundPosition', margin_left+'px '+margin_top+'px');
});
/*resp menu*/
jQuery('.resp_menu_button').click(function() {
if(jQuery('.event-type-selector-dropdown').attr('style') == 'display: block;')
jQuery('.event-type-selector-dropdown').slideUp({ duration: 500, easing: "easeInOutCubic" });
else
jQuery('.event-type-selector-dropdown').slideDown({ duration: 500, easing: "easeInOutCubic" });
});
jQuery('.event-type-selector-dropdown').click(function() {
jQuery('.event-type-selector-dropdown').slideUp({ duration: 500, easing: "easeInOutCubic" });
});
/*add submenu class*/
jQuery('.menu > li').each(function() {
if(jQuery(this).find('ul').size() > 0 ){
jQuery(this).addClass('has-sub-menu');
}
});
/*animate menu*/
jQuery('ul.menu > li').hover(function(){
jQuery(this).find('ul').stop(true,true).fadeIn(300);
},
function () {
jQuery(this).find('ul').stop(true,true).fadeOut(300);
});
/*add lightbox*/
jQuery(".gallery a").attr("rel", "lightbox[gallery]").prettyPhoto({theme:'light_rounded',overlay_gallery: false,show_title: false,deeplinking:false});
/*form hide replay*/
jQuery(".reply").click(function(){
jQuery('#commentform h3').hide();
});
jQuery("#cancel-comment-reply-link").click(function(){
jQuery('#commentform h3').show();
});
var menu = jQuery('.mainmenu');
jQuery( window ).scroll(function() {
if(!menu.isOnScreen() && jQuery(this).scrollTop() > 350){
jQuery(".totop").fadeIn(200);
jQuery(".fixedmenu").slideDown(200);
jQuery(".pmc-sidebar-post:hidden").fadeIn(200);}
else{
jQuery(".fixedmenu").slideUp(200);
jQuery(".totop").fadeOut(200);
jQuery(".pmc-sidebar-post:visible").fadeOut(200);;
}
});
/*go tot op*/
jQuery('.gototop').click(function() {
jQuery('html, body').animate({scrollTop:0}, 'medium');
});
jQuery( ".pagenav.home .menu > li:first-child a" ).addClass('important_color');
jQuery('.bxslider').bxSlider({
auto: true,
speed: 1000,
controls: false,
pager :false,
easing : 'easeInOutQuint',
});
jQuery('.post-widget-slider').bxSlider({
controls: true,
displaySlideQty: 1,
speed: 800,
touchEnabled: false,
easing : 'easeInOutQuint',
prevText : '<i class="fa fa-chevron-left"></i>',
nextText : '<i class="fa fa-chevron-right"></i>',
pager :false
});
});
jQuery.fn.isOnScreen = function(){
var win = jQuery(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
if(this.offset()){
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
}
};
|
gpl-2.0
|
onishiweb/Book-Demo-Theme
|
single-ptd_menu.php
|
393
|
<?php
/**
* Template menu single
*/
?>
<?php get_header(); ?>
<?php if( have_posts() ): while( have_posts() ): the_post(); ?>
<article <?php post_class(); ?>>
<h1><?php the_title(); ?></h1>
<?php if( has_post_thumbnail() ): ?>
<?php the_post_thumbnail(); ?>
<?php endif; ?>
<?php the_content(); ?>
</article>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
|
gpl-2.0
|
cappsllc/first_app
|
app/models/product.rb
|
119
|
class Product < ActiveRecord::Base
attr_accessible :description, :ends_at, :price, :quantity, :starts_at, :title
end
|
gpl-2.0
|
admo/aria
|
aria/java/SWIGTYPE_p_ArMapChangeDetails.java
|
2191
|
/*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
Copyright (C) 2010, 2011 Adept Technology, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.36
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.mobilerobots.Aria;
public class SWIGTYPE_p_ArMapChangeDetails {
/* (begin code from javabody typemap for pointers, references, and arrays) */
private long swigCPtr;
/* for internal use by swig only */
public SWIGTYPE_p_ArMapChangeDetails(long cPtr, boolean bFutureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_ArMapChangeDetails() {
swigCPtr = 0;
}
/* for internal use by swig only */
public static long getCPtr(SWIGTYPE_p_ArMapChangeDetails obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
/* (end code from javabody typemap for pointers, references, and arrays) */
}
|
gpl-2.0
|
heros/LasCore
|
src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp
|
14084
|
/*
* Copyright (C) 2013 LasCore <http://lascore.makeforum.eu/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "SpellAuraEffects.h"
#include "oculus.h"
enum Says
{
SAY_AGGRO = 0,
SAY_AZURE = 1,
SAY_AZURE_EMOTE = 2,
SAY_DEATH = 3
};
enum Spells
{
SPELL_ENERGIZE_CORES_VISUAL = 62136,
SPELL_ENERGIZE_CORES = 50785, //Damage 5938 to 6562, effec2 Triggers 54069, effect3 Triggers 56251
SPELL_CALL_AZURE_RING_CAPTAIN = 51002, //Effect Send Event (12229)
/*SPELL_CALL_AZURE_RING_CAPTAIN_2 = 51006, //Effect Send Event (10665)
SPELL_CALL_AZURE_RING_CAPTAIN_3 = 51007, //Effect Send Event (18454)
SPELL_CALL_AZURE_RING_CAPTAIN_4 = 51008, //Effect Send Event (18455)*/
SPELL_CALL_AMPLIFY_MAGIC = 51054,
SPELL_ICE_BEAM = 49549,
SPELL_ARCANE_BEAM_PERIODIC = 51019,
SPELL_SUMMON_ARCANE_BEAM = 51017
};
enum Events
{
EVENT_ENERGIZE_CORES = 1,
EVENT_CALL_AZURE,
EVENT_AMPLIFY_MAGIC,
EVENT_ENERGIZE_CORES_VISUAL
};
class boss_varos : public CreatureScript
{
public:
boss_varos() : CreatureScript("boss_varos") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_varosAI (creature);
}
struct boss_varosAI : public BossAI
{
boss_varosAI(Creature* creature) : BossAI(creature, DATA_VAROS_EVENT)
{
if (instance->GetBossState(DATA_DRAKOS_EVENT) != DONE)
DoCast(me, SPELL_CENTRIFUGE_SHIELD);
}
void Reset()
{
_Reset();
events.ScheduleEvent(EVENT_AMPLIFY_MAGIC, urand(20, 25) * IN_MILLISECONDS);
events.ScheduleEvent(EVENT_ENERGIZE_CORES_VISUAL, 5000);
// not sure if this is handled by a timer or hp percentage
events.ScheduleEvent(EVENT_CALL_AZURE, urand(15, 30) * IN_MILLISECONDS);
firstCoreEnergize = false;
coreEnergizeOrientation = 0.0f;
}
void EnterCombat(Unit* /*who*/)
{
_EnterCombat();
Talk(SAY_AGGRO);
}
float GetCoreEnergizeOrientation()
{
return coreEnergizeOrientation;
}
void UpdateAI(const uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ENERGIZE_CORES:
DoCast(me, SPELL_ENERGIZE_CORES);
events.CancelEvent(EVENT_ENERGIZE_CORES);
break;
case EVENT_ENERGIZE_CORES_VISUAL:
if (!firstCoreEnergize)
{
coreEnergizeOrientation = me->GetOrientation();
firstCoreEnergize = true;
} else
coreEnergizeOrientation = Position::NormalizeOrientation(coreEnergizeOrientation - 2.0f);
DoCast(me, SPELL_ENERGIZE_CORES_VISUAL);
events.ScheduleEvent(EVENT_ENERGIZE_CORES_VISUAL, 5000);
events.ScheduleEvent(EVENT_ENERGIZE_CORES, 4000);
break;
case EVENT_CALL_AZURE:
// not sure how blizz handles this, i cant see any pattern between the differnt spells
DoCast(me, SPELL_CALL_AZURE_RING_CAPTAIN);
Talk(SAY_AZURE);
Talk(SAY_AZURE_EMOTE);
events.ScheduleEvent(EVENT_CALL_AZURE, urand(20, 25) * IN_MILLISECONDS);
break;
case EVENT_AMPLIFY_MAGIC:
DoCast(me->getVictim(), SPELL_CALL_AMPLIFY_MAGIC);
events.ScheduleEvent(EVENT_AMPLIFY_MAGIC, urand(17, 20) * IN_MILLISECONDS);
break;
}
}
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/)
{
_JustDied();
Talk(SAY_DEATH);
DoCast(me, SPELL_DEATH_SPELL, true); // we cast the spell as triggered or the summon effect does not occur
}
private:
bool firstCoreEnergize;
float coreEnergizeOrientation;
};
};
class npc_azure_ring_captain : public CreatureScript
{
public:
npc_azure_ring_captain() : CreatureScript("npc_azure_ring_captain") { }
struct npc_azure_ring_captainAI : public ScriptedAI
{
npc_azure_ring_captainAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
void Reset()
{
targetGUID = 0;
me->SetWalk(true);
//! HACK: Creature's can't have MOVEMENTFLAG_FLYING
me->AddUnitMovementFlag(MOVEMENTFLAG_FLYING);
me->SetReactState(REACT_AGGRESSIVE);
}
void SpellHitTarget(Unit* target, SpellInfo const* spell)
{
if (spell->Id == SPELL_ICE_BEAM)
{
target->CastSpell(target, SPELL_SUMMON_ARCANE_BEAM, true);
me->DespawnOrUnsummon();
}
}
void UpdateAI(const uint32 /*diff*/)
{
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
void MovementInform(uint32 type, uint32 id)
{
if (type != POINT_MOTION_TYPE ||
id != ACTION_CALL_DRAGON_EVENT)
return;
me->GetMotionMaster()->MoveIdle();
if (Unit* target = ObjectAccessor::GetUnit(*me, targetGUID))
DoCast(target, SPELL_ICE_BEAM);
}
void DoAction(const int32 action)
{
switch (action)
{
case ACTION_CALL_DRAGON_EVENT:
if (instance)
{
if (Creature* varos = ObjectAccessor::GetCreature(*me, instance->GetData64(DATA_VAROS)))
{
if (Unit* victim = varos->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0))
{
me->SetReactState(REACT_PASSIVE);
me->SetWalk(false);
me->GetMotionMaster()->MovePoint(ACTION_CALL_DRAGON_EVENT, victim->GetPositionX(), victim->GetPositionY(), victim->GetPositionZ() + 20.0f);
targetGUID = victim->GetGUID();
}
}
}
break;
}
}
private:
uint64 targetGUID;
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const
{
return new npc_azure_ring_captainAI(creature);
}
};
class spell_varos_centrifuge_shield : public SpellScriptLoader
{
public:
spell_varos_centrifuge_shield() : SpellScriptLoader("spell_varos_centrifuge_shield") { }
class spell_varos_centrifuge_shield_AuraScript : public AuraScript
{
PrepareAuraScript(spell_varos_centrifuge_shield_AuraScript);
bool Load()
{
Unit* caster = GetCaster();
return (caster && caster->ToCreature());
}
void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Unit* caster = GetCaster())
{
// flags taken from sniffs
// UNIT_FLAG_UNK_9 -> means passive but it is not yet implemented in core
if (caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15|UNIT_FLAG_IMMUNE_TO_NPC|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_UNK_6))
{
caster->ToCreature()->SetReactState(REACT_PASSIVE);
caster->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15|UNIT_FLAG_IMMUNE_TO_NPC|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_UNK_6);
}
}
}
void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/)
{
if (Unit* caster = GetCaster())
{
caster->ToCreature()->SetReactState(REACT_AGGRESSIVE);
caster->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15|UNIT_FLAG_IMMUNE_TO_NPC|UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_UNK_6);
}
}
void Register()
{
OnEffectRemove += AuraEffectRemoveFn(spell_varos_centrifuge_shield_AuraScript::OnRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
OnEffectApply += AuraEffectApplyFn(spell_varos_centrifuge_shield_AuraScript::OnApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL);
}
};
AuraScript* GetAuraScript() const
{
return new spell_varos_centrifuge_shield_AuraScript();
}
};
class spell_varos_energize_core_area_enemy : public SpellScriptLoader
{
public:
spell_varos_energize_core_area_enemy() : SpellScriptLoader("spell_varos_energize_core_area_enemy") {}
class spell_varos_energize_core_area_enemySpellScript : public SpellScript
{
PrepareSpellScript(spell_varos_energize_core_area_enemySpellScript)
void FilterTargets(std::list<WorldObject*>& targets)
{
Creature* varos = GetCaster()->ToCreature();
if (!varos)
return;
if (varos->GetEntry() != NPC_VAROS)
return;
float orientation = CAST_AI(boss_varos::boss_varosAI, varos->AI())->GetCoreEnergizeOrientation();
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end();)
{
Position pos;
(*itr)->GetPosition(&pos);
float angle = varos->GetAngle((*itr)->GetPositionX(), (*itr)->GetPositionY());
float diff = fabs(orientation - angle);
if (diff > 1.0f)
itr = targets.erase(itr);
else
++itr;
}
}
void Register()
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_varos_energize_core_area_enemySpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_varos_energize_core_area_enemySpellScript();
}
};
class spell_varos_energize_core_area_entry : public SpellScriptLoader
{
public:
spell_varos_energize_core_area_entry() : SpellScriptLoader("spell_varos_energize_core_area_entry") {}
class spell_varos_energize_core_area_entrySpellScript : public SpellScript
{
PrepareSpellScript(spell_varos_energize_core_area_entrySpellScript)
void FilterTargets(std::list<WorldObject*>& targets)
{
Creature* varos = GetCaster()->ToCreature();
if (!varos)
return;
if (varos->GetEntry() != NPC_VAROS)
return;
float orientation = CAST_AI(boss_varos::boss_varosAI, varos->AI())->GetCoreEnergizeOrientation();
for (std::list<WorldObject*>::iterator itr = targets.begin(); itr != targets.end();)
{
Position pos;
(*itr)->GetPosition(&pos);
float angle = varos->GetAngle((*itr)->GetPositionX(), (*itr)->GetPositionY());
float diff = fabs(orientation - angle);
if (diff > 1.0f)
itr = targets.erase(itr);
else
++itr;
}
}
void Register()
{
OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_varos_energize_core_area_entrySpellScript::FilterTargets, EFFECT_0, TARGET_UNIT_SRC_AREA_ENTRY);
}
};
SpellScript* GetSpellScript() const
{
return new spell_varos_energize_core_area_entrySpellScript();
}
};
void AddSC_boss_varos()
{
new boss_varos();
new npc_azure_ring_captain();
new spell_varos_centrifuge_shield();
new spell_varos_energize_core_area_enemy();
new spell_varos_energize_core_area_entry();
}
|
gpl-2.0
|
itos/workeet
|
wp-content/themes/workeet/includes/functions/comments.php
|
1765
|
<?php if ( ! function_exists( 'et_custom_comments_display' ) ) :
function et_custom_comments_display($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
<div class="comment-body">
<div id="comment-<?php comment_ID(); ?>" class="clearfix">
<div class="avatar-box">
<?php echo get_avatar($comment,$size='62'); ?>
<span class="avatar-overlay"></span>
</div> <!-- end .avatar-box -->
<div class="comment-wrap clearfix">
<div class="comment-meta commentmetadata"><?php printf('<span class="fn">%s</span>', get_comment_author_link()) ?> | <a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
<?php
/* translators: 1: date, 2: time */
printf( __( '%1$s at %2$s', 'LeanBiz' ), get_comment_date(), get_comment_time() ); ?></a><?php edit_comment_link( esc_html__( '(Edit)', 'LeanBiz' ), ' ' );
?>
</div><!-- .comment-meta .commentmetadata -->
<?php if ($comment->comment_approved == '0') : ?>
<em class="moderation"><?php esc_html_e('Your comment is awaiting moderation.','LeanBiz') ?></em>
<br />
<?php endif; ?>
<div class="comment-content"><?php comment_text() ?></div> <!-- end comment-content-->
<?php
$et_comment_reply_link = get_comment_reply_link( array_merge( $args, array('reply_text' => esc_attr__('Reply','LeanBiz'),'depth' => $depth, 'max_depth' => $args['max_depth'])) );
if ( $et_comment_reply_link ) echo '<div class="reply-container">' . $et_comment_reply_link . '</div>';
?>
</div> <!-- end comment-wrap-->
</div> <!-- end comment-body-->
</div> <!-- end comment-body-->
<?php }
endif; ?>
|
gpl-2.0
|
pacoqueen/ginn
|
ginn/formularios/consulta_global.py
|
157503
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) 2005-2014 Francisco José Rodríguez Bogado, #
# Diego Muñoz Escalante. #
# (pacoqueen@users.sourceforge.net, escalant3@users.sourceforge.net) #
# #
# This file is part of GeotexInn. #
# #
# GeotexInn is free software; you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation; either version 2 of the License, or #
# (at your option) any later version. #
# #
# GeotexInn 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 GeotexInn; if not, write to the Free Software #
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #
###############################################################################
###################################################################
## consulta_global.py - Resumen brutal de producciones y ventas.
###################################################################
## NOTAS:
## Después de varias actualizaciones, el tiempo estimado en
## realizar todas las consultas ronda los 3'41".
###################################################################
## Changelog:
## 12 de abril de 2006 -> Inicio
##
###################################################################
## NOTAS:
## Hay hasta 3 formas de contar los consumos de fibra. A saber:
## 1.- Con el criterio usado para calcular mermas en línea de
## geotextiles. Una partida de carga se consume completa o no se
## consume. La fecha en la que cuenta el consumo es la fecha del
## último de los partes de producción de todas las partidas que
## pertenecen a la partida de carga. Una partida de carga sin
## producción es un descenso en las existencias de la fibra que
## contiene pero no cuenta como consumo. Las partidas que empiezan
## a consumirse a final de mes no entran como consumo hasta el mes
## siguiente. De igual forma y como consecuencia de la fecha
## efectiva de consumo, a principio de mes aparecerán partidas de
## carga cuyo consumo comenzó el mes anterior pero no se
## contabiliza hasta el actual.
## 2.- Contando directamente las partidas de carga completa
## según la fecha de cada una. Hay varios métodos en la clase para
## corregir las fechas en caso de que la partida se haya creado
## antes de tiempo: igualándola a la fecha del primer parte que la
## consume, igualándola a la fecha del albarán interno (si lo
## tiene) o seleccionándola a mano. En cualquier caso, el consumo
## entre dos fechas se obtiene buscando directamente las partidas
## cuyas fechas entran en el rango. Independientemente de si se
## ha consumido o no. Se ajusta mejor al cálculo de existencias
## pero se aleja del consumo teórico que debería corresponderle a
## los geotextiles fabricados entre ese rango.
## 3.- Contabilizando la fibra asociada a los albaranes internos
## entre las fechas. Debería dar un resultado similar al método
## anterior, pero es posible que existan partidas de carga que no
## estén completamente relacionadas con albaranes, bien por olvido
## del usuario o bien porque los albaranes internos de fibra se
## empezaron a hacer cuando en el sistema ya iban en torno a 1000
## partidas de carga.
###################################################################
from formularios.ventana import Ventana
from formularios import utils
import pygtk
pygtk.require('2.0')
import gtk
from framework import pclases
import mx.DateTime
from formularios.ventana_progreso import VentanaProgreso
from collections import defaultdict
try:
from collections import OrderedDict
except ImportError:
from lib.ordereddict import OrderedDict
from formularios.consulta_producido import calcular_productividad_conjunta
import datetime
class ConsultaGlobal(Ventana):
"""
Ventana de consulta "global". Abarca varias consultas de producción y
ventas.
"""
def __init__(self, objeto=None, usuario=None):
if isinstance(usuario, int):
usuario = pclases.Usuario.get(usuario)
self.usuario = usuario
self.partidas_carga = {}
Ventana.__init__(self, 'consulta_global.glade', objeto,
usuario=usuario)
connections = {'b_salir/clicked': self.salir,
'b_buscar/clicked': self.buscar,
'b_imprimir/clicked': self.imprimir,
'b_exportar/clicked': self.exportar}
self.add_connections(connections)
self.append_meses()
preparar_tv(self.wids['tv_produccion_gtx'])
preparar_tv(self.wids['tv_ventas_gtx'])
preparar_tv(self.wids['tv_consumos_gtx'])
preparar_tv(self.wids['tv_produccion_fibra'], listview=False)
preparar_tv(self.wids['tv_ventas_fibra'])
preparar_tv(self.wids['tv_consumos_fibra'])
preparar_tv(self.wids['tv_produccion_bolsas'])
preparar_tv(self.wids['tv_ventas_bolsas'])
preparar_tv(self.wids['tv_consumos_bolsas'])
preparar_tv(self.wids['tv_compras_geocompuestos'])
preparar_tv(self.wids['tv_ventas_geocompuestos'])
annoactual = mx.DateTime.localtime().year
self.wids['e_anno'].set_text(str(annoactual))
self.wids['b_guardar'] = gtk.Button()
self.wids['b_guardar'].set_property("visible", False)
self.wids['b_guardar'].set_sensitive(False)
gtk.main()
def activar_widgets(self, *args, **kw):
pass
def append_meses(self):
"""
Añade un hbox con los 12 meses del año para poder marcar
y desmarcar los meses que se incluirán en la consulta.
"""
self.wids['hboxmeses'] = gtk.HBox()
self.wids['vbox3'].add(self.wids['hboxmeses'])
for n, mes in zip(range(1, 13), ("enero", "febrero", "marzo",
"abril", "mayo", "junio",
"julio", "agosto", "septiembre",
"octubre", "noviembre", "diciembre")):
self.wids['ch_%d' % n] = gtk.CheckButton(mes)
self.wids['ch_%d' % n].set_active(True)
self.wids['hboxmeses'].add(self.wids['ch_%d' % n])
self.wids['b_todos'] = gtk.Button("Marcar todos los meses")
self.wids['b_todos'].connect("clicked", self.marcar_todos, True)
self.wids['b_ninguno'] = gtk.Button("Desmarcar todos los meses")
self.wids['b_ninguno'].connect("clicked", self.marcar_todos, False)
self.wids['hbox_b_meses'] = gtk.HBox()
self.wids['hbox_b_meses'].add(self.wids['b_todos'])
self.wids['hbox_b_meses'].add(self.wids['b_ninguno'])
self.wids['vbox3'].add(self.wids['hbox_b_meses'])
self.wids['vbox3'].add(gtk.HSeparator())
self.wids['vbox3'].set_spacing(5)
self.wids['vbox3'].show_all()
def marcar_todos(self, boton, estado):
for i in range(1, 13):
self.wids['ch_%d' % i].set_active(estado)
def chequear_cambios(self):
pass
def get_anno(self):
"""
Devuelve el año del entry de la ventana.
Si no es un número, devuelve el año actual y
avisa con un mensaje de error.
"""
anno = self.wids['e_anno'].get_text()
try:
anno = int(anno)
except ValueError:
year = mx.DateTime.localtime().year
utils.dialogo_info(titulo = "ERROR FORMATO NUMÉRICO",
texto = "El texto %s no es un año correcto.\n\n"
"Se usará el año de la fecha actual: %d." % (
anno, year),
padre = self.wids['ventana'])
anno = year
return anno
def buscar(self, boton):
"""
Inicia la consulta para el año indicado en el widget y
rellena las tablas con la información obtenida.
"""
anno = self.get_anno()
vpro = VentanaProgreso(padre = self.wids['ventana'])
vpro.mostrar()
meses = []
for i in range(1, 13):
if self.wids['ch_%d' % i].get_active():
meses.append(i)
meses = tuple(meses)
# PLAN: cache = preconsultar()
vpro.set_valor(0.0, "Analizando venta de fibra ignorando tarifas...")
ventas_fibra_por_color = buscar_ventas_fibra_color(anno, vpro, 0.15,
meses)
vpro.set_valor(0.15, "Analizando producción de geotextiles...")
while gtk.events_pending():
gtk.main_iteration(False)
produccion_gtx = buscar_produccion_gtx(anno, vpro, 0.15, self.logger,
meses) #, cache)
vpro.set_valor(0.3, "Analizando ventas...")
(ventas_gtx,
ventas_fibra,
ventas_bolsas) = buscar_ventas(anno, vpro, 0.15, meses) #, cache)
vpro.set_valor(0.45, "Analizando consumos...")
(consumos_gtx,
consumos_fibra,
consumos_bolsas) = buscar_consumos(anno, vpro, 0.15, meses) #, cache)
vpro.set_valor(0.6, "Analizando producción de fibra...")
produccion_fibra = buscar_produccion_fibra(anno, vpro, 0.1,
self.logger,
meses) #, cache)
vpro.set_valor(0.7, "Analizando producción de fibra de cemento...")
produccion_bolsas = buscar_produccion_bolsas(anno, vpro, 0.1,
self.logger,
meses) #, cache)
vpro.set_valor(0.8, "Analizando compras de comercializados...")
compras_geocompuestos = buscar_compras_geocompuestos(anno, vpro, 0.1,
self.logger,
meses) #, cache)
vpro.set_valor(0.9, "Analizando ventas de comercializados...")
ventas_geocompuestos = buscar_ventas_geocompuestos(anno, vpro, 0.1,
self.logger,
meses) #, cache)
vpro.set_valor(1.0, "Volcando datos a la ventana...")
self.rellenar_tablas(produccion_gtx, ventas_gtx, consumos_gtx,
produccion_fibra, ventas_fibra, consumos_fibra,
ventas_fibra_por_color,
produccion_bolsas, ventas_bolsas, consumos_bolsas,
compras_geocompuestos, ventas_geocompuestos)
vpro.ocultar()
def rellenar_tablas(self, produccion_gtx, ventas_gtx, consumos_gtx,
produccion_fibra, ventas_fibra, consumos_fibra,
ventas_fibra_por_color,
produccion_bolsas, ventas_bolsas, consumos_bolsas,
compras_geocompuestos, ventas_geocompuestos):
"""
Introduce la información de producciones, ventas y consumos de
geotextiles y fibra en los TreeViews correspondientes.
"""
## GTX
self.rellenar_tabla_produccion_gtx(produccion_gtx)
self.rellenar_tabla_ventas_gtx(ventas_gtx)
self.rellenar_tabla_consumos(consumos_gtx,
self.wids['tv_consumos_gtx'])
## FIBRA
self.rellenar_tabla_produccion_fibra(produccion_fibra)
self.rellenar_tabla_consumos(consumos_fibra,
self.wids['tv_consumos_fibra'])
# CWT: CAMBIADA LA FORMA DE AGRUPAR VENTAS FIBRA:
#self.rellenar_tabla_ventas_fibra(ventas_fibra)
self.rellenar_tabla_ventas_fibra_por_color(ventas_fibra_por_color)
## BOLSAS
self.rellenar_tabla_produccion_bolsas(produccion_bolsas)
self.rellenar_tabla_ventas_bolsas(ventas_bolsas)
self.rellenar_tabla_consumos(consumos_bolsas,
self.wids['tv_consumos_bolsas'])
## GEOCOMPUESTOS (COMERCIALIZADOS)
self.rellenar_tabla_compras_geocompuestos(compras_geocompuestos)
self.rellenar_tabla_ventas_geocompuestos(ventas_geocompuestos)
def rellenar_tabla_produccion_bolsas(self, produccion_bolsas):
"""
Recibe un diccionario con la producción en A y B de geocem por
meses e introduce esa información en el treeview.
"""
model = self.wids['tv_produccion_bolsas'].get_model()
model.clear()
fila_kilos = ["Kilos"]
fila_bolsas = ["Bolsas"]
fila_kilos_a = ["Kilos A"]
fila_bolsas_a = ["Bolsas A"]
fila_kilos_b = ["Kilos B"]
fila_bolsas_b = ["Bolsas B"]
fila_consumo = ["Kg consumidos"]
fila_kilos_hora = ["Kilos / hora"]
fila_horas = ["Horas de trabajo"]
fila_horas_produccion = ["Horas de producción"]
fila_dias = ["Días de trabajo"]
fila_turnos = ["Turnos / día"]
fila_empleados = ["Trabajadores / día"]
fila_productividad = ["Productividad"]
bolsas_totales = 0
kilos_totales = 0.0
bolsas_a_totales = 0
kilos_a_totales = 0.0
bolsas_b_totales = 0
kilos_b_totales = 0.0
kilos_consumidos_totales = 0.0
for mes in xrange(12):
#for mes in produccion_bolsas:
bolsas_totales_mes = (produccion_bolsas[mes]['A']['bolsas']
+ produccion_bolsas[mes]['B']['bolsas'])
bolsas_totales += bolsas_totales_mes
fila_bolsas.append(utils.float2str(bolsas_totales_mes, 0))
kilos_totales_mes = (produccion_bolsas[mes]['A']['kilos']
+ produccion_bolsas[mes]['B']['kilos'])
kilos_totales += kilos_totales_mes
fila_kilos.append(utils.float2str(kilos_totales_mes))
bolsas_a_mes = produccion_bolsas[mes]['A']['bolsas']
fila_bolsas_a.append(utils.float2str(bolsas_a_mes, 0))
bolsas_a_totales += bolsas_a_mes
kilos_a_mes = produccion_bolsas[mes]['A']['kilos']
fila_kilos_a.append(utils.float2str(kilos_a_mes))
kilos_a_totales += kilos_a_mes
bolsas_b_mes = produccion_bolsas[mes]['B']['bolsas']
fila_bolsas_b.append(utils.float2str(bolsas_b_mes, 0))
bolsas_b_totales += bolsas_b_mes
kilos_b_mes = produccion_bolsas[mes]['B']['kilos']
fila_kilos_b.append(utils.float2str(kilos_b_mes))
kilos_b_totales += kilos_b_mes
consumo = produccion_bolsas[mes]['consumo']
kilos_consumidos_totales += consumo
fila_consumo.append(utils.float2str(consumo))
fila_kilos_hora.append(utils.float2str(
produccion_bolsas[mes]['kilos_hora']))
fila_horas.append(utils.float2str(
produccion_bolsas[mes]['horas'], autodec = True))
fila_horas_produccion.append(utils.float2str(
produccion_bolsas[mes]['horas_produccion'], autodec = True))
fila_dias.append("%d" % (produccion_bolsas[mes]['dias']))
fila_turnos.append(utils.float2str(
produccion_bolsas[mes]['turnos']))
fila_empleados.append(utils.float2str(
produccion_bolsas[mes]['empleados'], autodec = True))
fila_productividad.append("%s %%" % (utils.float2str(
produccion_bolsas[mes]['productividad'] * 100.0)))
# Totales:
fila_kilos.append(utils.float2str(kilos_totales))
fila_bolsas.append(utils.float2str(bolsas_totales, 0))
fila_kilos_a.append(utils.float2str(kilos_a_totales))
fila_bolsas_a.append(utils.float2str(bolsas_a_totales, 0))
fila_kilos_b.append(utils.float2str(kilos_b_totales))
fila_bolsas_b.append(utils.float2str(bolsas_b_totales, 0))
fila_consumo.append(utils.float2str(kilos_consumidos_totales))
avg = lambda l: (1.0 * sum(l)) / len(l)
fila_kilos_hora.append(utils.float2str(avg(
[produccion_bolsas[mes]['kilos_hora']
for mes in produccion_bolsas])))
fila_horas.append(utils.float2str(sum(
[produccion_bolsas[mes]['horas'] for mes in produccion_bolsas])))
fila_horas_produccion.append(utils.float2str(sum(
[produccion_bolsas[mes]['horas_produccion']
for mes in produccion_bolsas])))
fila_dias.append("%d" % (sum(
[produccion_bolsas[mes]['dias'] for mes in produccion_bolsas])))
fila_turnos.append("%s" % utils.float2str(avg(
[produccion_bolsas[mes]['turnos'] for mes in produccion_bolsas])))
fila_empleados.append("%s" % utils.float2str(avg(
[produccion_bolsas[mes]['empleados']
for mes in produccion_bolsas])))
fila_productividad.append("%s %%" % utils.float2str(avg(
[produccion_bolsas[mes]['productividad']
for mes in produccion_bolsas]) * 100.0))
# ... al model:
model.append(fila_kilos + ["Hello."])
model.append(fila_bolsas + ["Is there anybody in there?"])
model.append(fila_kilos_a + ["Just nod if you can hear me"])
model.append(fila_bolsas_a + ["Is there aneyone home?"])
model.append(fila_kilos_b + ["Come on, now."])
model.append(fila_bolsas_b + ["I hear you're feeling down"])
model.append(fila_consumo + ["Well I can ease your pain."])
model.append(fila_kilos_hora + ["Get you on your feet again."])
model.append(fila_horas + ["Relax."])
model.append(fila_horas_produccion + ["I need some information first"])
model.append(fila_dias + ["Just the basic facts."])
model.append(fila_turnos + ["Can you show me where it hurts?"])
model.append(fila_empleados + ["There is no pain, you are receding."])
model.append(fila_productividad + ["I have become comfortably numb."])
def rellenar_tabla_ventas_fibra_por_color(self, ventas_fibra_por_color):
model = self.wids['tv_ventas_fibra'].get_model()
model.clear()
for fila in ventas_fibra_por_color:
model.append(fila)
def rellenar_tabla_produccion_fibra(self, p):
model = self.wids['tv_produccion_fibra'].get_model()
model.clear()
# "Encabezado"
fila_total = ["Kg totales"]
filas_colores = {}
for i in xrange(12):
for color in p[i]["colores"]:
if color not in filas_colores:
filas_colores[color] = [color]
colores_ordenados = filas_colores.keys()
colores_ordenados.sort()
fila_cemento = ["Geocem"]
fila_merma = ["Merma"]
fila_porc_merma = ["% merma"]
fila_granza = ["Granza"]
fila_reciclada = ["Granza reciclada"]
fila_medio_b = ["Peso medio bala"]
fila_medio_bb = ["Peso medio bigbag"]
fila_b = ['Kg "B"']
fila_kilos_hora = ["Kilos/hora"]
fila_dias = ["Días de trabajo"]
fila_horas = ["Horas de trabajo"]
fila_horas_produccion = ["Horas de producción"]
fila_turnos = ["Turnos / día"]
fila_empleados = ["Trabajadores / día"]
fila_productividad = ["Productividad"]
fila_cable = ["Fibra C -reciclada- (no computa en el total producido)"]
filas_c = []
# Detalle meses
for i in xrange(12):
fila_total.append(utils.float2str(p[i]['total']))
for color in colores_ordenados:
#for color in filas_colores:
try:
filas_colores[color].append(
utils.float2str(p[i]["colores"][color]))
except KeyError:
filas_colores[color].append(utils.float2str(0.0))
fila_cemento.append(utils.float2str(p[i]["cemento"]))
fila_merma.append(utils.float2str(p[i]["merma"]))
fila_porc_merma.append(utils.float2str(p[i]["porc_merma"]))
fila_granza.append(utils.float2str(p[i]["granza"]))
fila_reciclada.append(utils.float2str(p[i]["reciclada"]))
fila_medio_b.append(utils.float2str(p[i]["media_bala"]))
fila_medio_bb.append(utils.float2str(p[i]["media_bigbag"]))
fila_b.append(utils.float2str(p[i]["kilos_b"]))
fila_kilos_hora.append(utils.float2str(p[i]['kilos_hora']))
fila_horas.append(utils.float2str(p[i]['horas'], autodec = True))
fila_horas_produccion.append(
utils.float2str(p[i]['horas_produccion'], autodec = True))
fila_dias.append("%d" % (p[i]['dias']))
fila_turnos.append(utils.float2str(p[i]['turnos']))
fila_empleados.append(utils.float2str(p[i]['empleados'],
autodec = True))
# Para poder después calcular la media y mostrar el valor sin
# tener que multiplicar, lo multiplico todo aquí:
p[i]['productividad'] *= 100.0
fila_productividad.append(
"%s" % (utils.float2str(p[i]['productividad'])))
fila_cable.append(
"%s" % (utils.float2str(p[i]['balas_cable']['total'])))
for tipo_cable in p[i]['balas_cable']:
if tipo_cable != 'total':
if tipo_cable not in [f[0] for f in filas_c]:
nueva_fila_c = ([tipo_cable]
+ ["0.0"]*i
+ [utils.float2str(
p[i]['balas_cable'][tipo_cable])]
+ ["0.0"]*(11-i))
filas_c.append(nueva_fila_c)
else:
for fila in filas_c:
if fila[0] == tipo_cable:
fila[i+1] = utils.float2str(
p[i]['balas_cable'][tipo_cable])
# Columna totales e invisible
avg = lambda l: (1.0 * sum(l)) / len(l)
for fila, func in ([(fila_total, sum)]
+ [(filas_colores[c], sum)
for c in colores_ordenados]
+ [(fila_cemento, sum),
(fila_merma, sum),
(fila_porc_merma, avg),
(fila_granza, sum),
(fila_reciclada, sum),
(fila_medio_b, avg),
(fila_medio_bb, avg),
(fila_b, sum),
(fila_kilos_hora, avg),
(fila_productividad, avg),
(fila_dias, sum),
(fila_horas, sum),
(fila_horas_produccion, sum),
(fila_turnos, avg),
(fila_empleados, avg),
(fila_cable, sum)]):
fila.append(utils.float2str(
func([utils._float(dato) for dato in fila[1:]])))
fila.append("Can you see the real me?")
# Este TreeView va con TreeStore en lugar de ListStore, necesita
# un nodo padre para las filas.
ultimo_padre = model.append(None, (fila))
# OJO: El último padre, tal y como se insertan los datos, es el de
# la fila cable. Si por lo que sea se llegara a cambiar hay que
# alterar el orden del desglose de la fibra reciclada de cable C
# que viene a continuación:
for fila, func in zip(filas_c, [sum]*len(filas_c)):
fila.append(utils.float2str(
func([utils._float(dato) for dato in fila[1:]])))
fila.append("Can you see the real me?")
# Este TreeView va con TreeStore en lugar de ListStore, necesita
# un nodo padre para las filas.
model.append(ultimo_padre, (fila))
def rellenar_tabla_consumos(self, dic, tv):
model = tv.get_model()
model.clear()
for producto in dic:
total = 0.0
fila = [producto.descripcion]
for mes in xrange(12):
try:
cant = dic[producto][mes]
except KeyError: # No hay consumos de ese producto para ese mes
cant = 0.0
total += cant
fila.append(utils.float2str(cant, 4, autodec = True))
fila.append(utils.float2str(total, 4, autodec = True))
model.append(fila + ["Sally take my hand"])
def rellenar_tabla_ventas_fibra(self, ventas_fibra):
model = self.wids['tv_ventas_fibra'].get_model()
model.clear()
fila_total_kg = ["kg"]
fila_total_e = ["euros"]
total_kg = 0.0
total_e = 0.0
for mes in xrange(12): # En diccionarios no hay orden. Corremos el
# riesgo de recorrer los meses erróneamente
#for mes in ventas_fibra['total']:
total_kg += ventas_fibra['total'][mes]['kilos']
total_e += ventas_fibra['total'][mes]['euros']
fila_total_kg.append(
utils.float2str(ventas_fibra['total'][mes]['kilos']))
fila_total_e.append(
utils.float2str(ventas_fibra['total'][mes]['euros']))
fila_total_kg.append(utils.float2str(total_kg))
fila_total_e.append(utils.float2str(total_e))
model.append(fila_total_kg + ["I used"])
model.append(fila_total_e + ["to love"])
for tarifa in [t for t in ventas_fibra.keys() if t != 'total']:
fila_kg = ["%s kg" % (tarifa != None and tarifa.nombre or "Otros")]
fila_e = ["%s euros"%(tarifa != None and tarifa.nombre or "Otros")]
total_kg = 0.0
total_e = 0.0
for mes in xrange(12):
# for mes in ventas_fibra[tarifa]:
if mes in ventas_fibra[tarifa]:
total_kg += ventas_fibra[tarifa][mes]['kilos']
total_e += ventas_fibra[tarifa][mes]['euros']
fila_kg.append(utils.float2str(
ventas_fibra[tarifa][mes]['kilos']))
fila_e.append(utils.float2str(
ventas_fibra[tarifa][mes]['euros']))
else:
fila_kg.append(utils.float2str(0.0))
fila_e.append(utils.float2str(0.0))
fila_kg.append(utils.float2str(total_kg))
fila_e.append(utils.float2str(total_e))
model.append(fila_kg + ["I used"])
model.append(fila_e + ["to love"])
def rellenar_tabla_compras_geocompuestos(self, compras_geocompuestos):
model = self.wids['tv_compras_geocompuestos'].get_model()
model.clear()
fila_total_cantidad = ["cantidad"]
fila_total_e = ["euros"]
total_cantidad = 0.0
total_e = 0.0
for mes in xrange(12):
total_cantidad += compras_geocompuestos['total'][mes]['cantidad']
total_e += compras_geocompuestos['total'][mes]['euros']
fila_total_cantidad.append(utils.float2str(
compras_geocompuestos['total'][mes]['cantidad']))
fila_total_e.append(utils.float2str(
compras_geocompuestos['total'][mes]['euros']))
fila_total_cantidad.append(utils.float2str(total_cantidad))
fila_total_e.append(utils.float2str(total_e))
model.append(fila_total_cantidad + ["Eternal sunshine of"])
model.append(fila_total_e + ["the spotless mind."])
# Los geocompuestos se venden en metros cuadrados...
# ... a no ser que se indique otra cosa:
try:
tdp = pclases.TipoDeMaterial.select(pclases.OR(
pclases.TipoDeMaterial.q.descripcion.contains("eocompuesto"),
pclases.TipoDeMaterial.q.descripcion.contains("omercializado"))
)[0]
moda = {}
for pc in tdp.productosCompra:
try:
moda[pc.unidad] += 1
except KeyError:
moda[pc.unidad] = 1
try:
maximo = max([moda[u] for u in moda])
for u in moda:
if moda[u] == maximo:
unidad = u
break
except ValueError:
raise IndexError # Para que coja unidad por defecto.
except IndexError:
unidad = "m²"
for proveedor in [t for t in compras_geocompuestos.keys()
if t != 'total']:
fila_cantidad = ["%s (%s)" % (
proveedor != None and proveedor.nombre or "Sin proveedor",
unidad)]
fila_e = ["%s (€)"%(proveedor != None and proveedor.nombre
or "Sin proveedor")]
total_cantidad = 0.0
total_e = 0.0
for mes in xrange(12):
if mes in compras_geocompuestos[proveedor]:
total_cantidad += compras_geocompuestos\
[proveedor][mes]['cantidad']
total_e += compras_geocompuestos[proveedor][mes]['euros']
fila_cantidad.append(utils.float2str(
compras_geocompuestos[proveedor][mes]['cantidad']))
fila_e.append(utils.float2str(
compras_geocompuestos[proveedor][mes]['euros']))
else:
fila_cantidad.append(utils.float2str(0.0))
fila_e.append(utils.float2str(0.0))
fila_cantidad.append(utils.float2str(total_cantidad))
fila_e.append(utils.float2str(total_e))
model.append(fila_cantidad +
["You can erase someone from your mind."])
model.append(fila_e +
["Getting them out of your heart is another story."])
def rellenar_tabla_ventas_geocompuestos(self, ventas_geocompuestos):
model = self.wids['tv_ventas_geocompuestos'].get_model()
model.clear()
fila_total_cantidad = ["cantidad"]
fila_total_e = ["euros"]
total_cantidad = 0.0
total_e = 0.0
for mes in xrange(12):
total_cantidad += ventas_geocompuestos['total'][mes]['cantidad']
total_e += ventas_geocompuestos['total'][mes]['euros']
fila_total_cantidad.append(utils.float2str(
ventas_geocompuestos['total'][mes]['cantidad']))
fila_total_e.append(utils.float2str(
ventas_geocompuestos['total'][mes]['euros']))
fila_total_cantidad.append(utils.float2str(total_cantidad))
fila_total_e.append(utils.float2str(total_e))
model.append(fila_total_cantidad + ["Eternal sunshine of"])
model.append(fila_total_e + ["the spotless mind."])
# Los geocompuestos se venden en metros cuadrados...
# ... a no ser que se indique otra cosa:
try:
tdp = pclases.TipoDeMaterial.select(pclases.OR(
pclases.TipoDeMaterial.q.descripcion.contains("eocompuesto"),
pclases.TipoDeMaterial.q.descripcion.contains("omercializado")
))[0]
moda = {}
for pc in tdp.productosCompra:
try:
moda[pc.unidad] += 1
except KeyError:
moda[pc.unidad] = 1
try:
maximo = max([moda[u] for u in moda])
for u in moda:
if moda[u] == maximo:
unidad = u
break
except ValueError:
raise IndexError # Para que coja unidad por defecto.
except IndexError:
unidad = "m²"
for tarifa in [t for t in ventas_geocompuestos.keys() if t != 'total']:
fila_cantidad = ["%s (%s)" % (
tarifa != None and tarifa.nombre or "Sin tarifa",
unidad)]
fila_e = ["%s (€)"%(tarifa != None and tarifa.nombre
or "Sin tarifa")]
total_cantidad = 0.0
total_e = 0.0
for mes in xrange(12):
if mes in ventas_geocompuestos[tarifa]:
total_cantidad += ventas_geocompuestos\
[tarifa][mes]['cantidad']
total_e += ventas_geocompuestos[tarifa][mes]['euros']
fila_cantidad.append(utils.float2str(
ventas_geocompuestos[tarifa][mes]['cantidad']))
fila_e.append(utils.float2str(
ventas_geocompuestos[tarifa][mes]['euros']))
else:
fila_cantidad.append(utils.float2str(0.0))
fila_e.append(utils.float2str(0.0))
fila_cantidad.append(utils.float2str(total_cantidad))
fila_e.append(utils.float2str(total_e))
model.append(fila_cantidad +
["You can erase someone from your mind."])
model.append(fila_e +
["Getting them out of your heart is another story."])
def rellenar_tabla_ventas_bolsas(self, ventas_bolsas):
model = self.wids['tv_ventas_bolsas'].get_model()
model.clear()
fila_total_bolsas = ["bolsas"]
fila_total_kg = ["kg"]
fila_total_e = ["euros"]
total_bolsas = 0.0
total_kg = 0.0
total_e = 0.0
for mes in xrange(12):
# for mes in ventas_bolsas['total']:
total_bolsas += ventas_bolsas['total'][mes]['bolsas']
total_kg += ventas_bolsas['total'][mes]['kilos']
total_e += ventas_bolsas['total'][mes]['euros']
fila_total_bolsas.append(utils.float2str(
ventas_bolsas['total'][mes]['bolsas']))
fila_total_kg.append(utils.float2str(
ventas_bolsas['total'][mes]['kilos']))
fila_total_e.append(utils.float2str(
ventas_bolsas['total'][mes]['euros']))
fila_total_bolsas.append(utils.float2str(total_bolsas, 0))
fila_total_kg.append(utils.float2str(total_kg))
fila_total_e.append(utils.float2str(total_e))
model.append(fila_total_bolsas + ["The girl"])
model.append(fila_total_kg + ["I used"])
model.append(fila_total_e + ["to love"])
for tarifa in [t for t in ventas_bolsas.keys() if t != 'total']:
fila_bolsas = ["%s bolsas" % (tarifa != None and tarifa.nombre
or "Otros")]
fila_kg = ["%s kg" % (tarifa != None and tarifa.nombre or "Otros")]
fila_e = ["%s euros"%(tarifa != None and tarifa.nombre or "Otros")]
total_bolsas = 0
total_kg = 0.0
total_e = 0.0
for mes in xrange(12):
# for mes in ventas_bolsas[tarifa]:
if mes in ventas_bolsas[tarifa]:
total_bolsas += ventas_bolsas[tarifa][mes]['bolsas']
total_kg += ventas_bolsas[tarifa][mes]['kilos']
total_e += ventas_bolsas[tarifa][mes]['euros']
fila_bolsas.append(utils.float2str(
ventas_bolsas[tarifa][mes]['bolsas']))
fila_kg.append(utils.float2str(
ventas_bolsas[tarifa][mes]['kilos']))
fila_e.append(utils.float2str(
ventas_bolsas[tarifa][mes]['euros']))
else:
fila_bolsas.append(utils.float2str(0.0))
fila_kg.append(utils.float2str(0.0))
fila_e.append(utils.float2str(0.0))
fila_bolsas.append(utils.float2str(total_bolsas, 0))
fila_kg.append(utils.float2str(total_kg))
fila_e.append(utils.float2str(total_e))
model.append(fila_bolsas + ["The girl"])
model.append(fila_kg + ["I used"])
model.append(fila_e + ["to love"])
def rellenar_tabla_ventas_gtx(self, ventas_gtx):
model = self.wids['tv_ventas_gtx'].get_model()
model.clear()
fila_total_m = ["m²"]
fila_total_kg = ["kg"]
fila_total_e = ["euros"]
total_m = 0.0
total_kg = 0.0
total_e = 0.0
for mes in xrange(12):
# for mes in ventas_gtx['total']:
total_m += ventas_gtx['total'][mes]['metros']
total_kg += ventas_gtx['total'][mes]['kilos']
total_e += ventas_gtx['total'][mes]['euros']
fila_total_m.append(
utils.float2str(ventas_gtx['total'][mes]['metros']))
fila_total_kg.append(
utils.float2str(ventas_gtx['total'][mes]['kilos']))
fila_total_e.append(
utils.float2str(ventas_gtx['total'][mes]['euros']))
fila_total_m.append(utils.float2str(total_m))
fila_total_kg.append(utils.float2str(total_kg))
fila_total_e.append(utils.float2str(total_e))
model.append(fila_total_m + ["The girl"])
model.append(fila_total_kg + ["I used"])
model.append(fila_total_e + ["to love"])
for tarifa in [t for t in ventas_gtx.keys() if t != 'total']:
fila_m = ["%s m²" % (tarifa != None and tarifa.nombre or "Otros")]
fila_kg = ["%s kg" % (tarifa != None and tarifa.nombre or "Otros")]
fila_e = ["%s euros"%(tarifa != None and tarifa.nombre or "Otros")]
total_m = 0.0
total_kg = 0.0
total_e = 0.0
for mes in xrange(12):
# for mes in ventas_gtx[tarifa]:
if mes in ventas_gtx[tarifa]:
total_m += ventas_gtx[tarifa][mes]['metros']
total_kg += ventas_gtx[tarifa][mes]['kilos']
total_e += ventas_gtx[tarifa][mes]['euros']
fila_m.append(
utils.float2str(ventas_gtx[tarifa][mes]['metros']))
fila_kg.append(
utils.float2str(ventas_gtx[tarifa][mes]['kilos']))
fila_e.append(
utils.float2str(ventas_gtx[tarifa][mes]['euros']))
else:
fila_m.append(utils.float2str(0.0))
fila_kg.append(utils.float2str(0.0))
fila_e.append(utils.float2str(0.0))
fila_m.append(utils.float2str(total_m))
fila_kg.append(utils.float2str(total_kg))
fila_e.append(utils.float2str(total_e))
model.append(fila_m + ["The girl"])
model.append(fila_kg + ["I used"])
model.append(fila_e + ["to love"])
def rellenar_tabla_produccion_gtx(self, produccion_gtx):
"""
Recibe un diccionario con la producción en A y B de geotextiles por
meses e introduce esa información en el treeview.
"""
model = self.wids['tv_produccion_gtx'].get_model()
model.clear()
# CWT: nzumer no quiere los m² B en la producción total, gramaje...
# Hay que dividir en A, B y C. Y rezar porque no aparezca un D.
filas = OrderedDict()
filas['metros'] = ["Total m² (A+B)"]
filas['kilos'] = ["Total kg teóricos (A+B)"]
filas['kilos_reales'] = ["Total kg reales (A+B+C)"]
filas['metros_a'] = ["Total m² (A)"]
filas['kilos_a'] = ["Total kg teóricos (A)"]
filas['kilos_reales_a'] = ["Total kg reales sin embalaje (A)"]
filas['metros_b'] = ["Total m² (B)"]
filas['kilos_b'] = ["Total kg teóricos (B)"]
filas['kilos_reales_b'] = ["Total kg reales sin embalaje (B)"]
filas['kilos_reales_c'] = ["Total kg reales (C)"]
filas['merma'] = ["Merma"]
filas['porciento_merma'] = ["% merma", ]
filas['gramaje_medio'] = ["Gramaje medio (A)"]
filas['kilos_hora'] = ["Kilos A+B (reales s.e.)/hora"]
filas['horas'] = ["Horas de trabajo"]
filas['horas_produccion'] = ["Horas de producción"]
filas['dias'] = ["Días de trabajo"]
filas['turnos'] = ["Turnos / día"]
filas['empleados'] = ["Trabajadores / día"]
filas['productividad'] = ["Productividad"]
filas['consumo_fibra'] = ["Consumo de fibra (partidas completas)"]
for mes in xrange(12):
update_filas_gtx(filas, produccion_gtx, mes)
# Totales:
update_filas_gtx(filas, produccion_gtx)
# Último campo que correspondería al PUID:
for k in filas:
filas[k].append(k)
for nombre_fila in filas:
fila = filas[nombre_fila]
_fila = []
for valor in fila:
if isinstance(valor, (int, float)):
valor = utils.float2str(valor)
_fila.append(valor)
model.append(_fila)
def construir_treeview_ficticio(self):
"""
Construye un TreeView con un ListModel como modelo con
las mismas columnas que los TreeViews de la ventana.
"""
tv = gtk.TreeView()
tv.set_name("Resumen global")
cols = (('', 'gobject.TYPE_STRING', False, True, True, None),
('Enero', 'gobject.TYPE_STRING', False, False, False, None),
('Febrero', 'gobject.TYPE_STRING', False, False, False, None),
('Marzo', 'gobject.TYPE_STRING', False, False, False, None),
('Abril', 'gobject.TYPE_STRING', False, False, False, None),
('Mayo', 'gobject.TYPE_STRING', False, False, False, None),
('Junio', 'gobject.TYPE_STRING', False, False, False, None),
('Julio', 'gobject.TYPE_STRING', False, False, False, None),
('Agosto', 'gobject.TYPE_STRING', False, False, False, None),
('Septiembre', 'gobject.TYPE_STRING',
False, False, False, None),
('Octubre', 'gobject.TYPE_STRING', False, False, False, None),
('Noviembre', 'gobject.TYPE_STRING',
False, False, False, None),
('Diciembre', 'gobject.TYPE_STRING',
False, False, False, None),
('Anual', 'gobject.TYPE_STRING', False, False, False, None),
('Clara', 'gobject.TYPE_STRING', False, False, False, None))
utils.preparar_listview(tv, cols)
for col in tv.get_columns()[1:]:
for cell in col.get_cell_renderers():
cell.set_property("xalign", 1.0)
col.set_alignment(0.5)
return tv
def unificar_tv(self):
"""
Construye un único TreeView con la información de los 6 mostrados en
pantalla listo para pasarlo a treeview2*.
"""
tv = self.construir_treeview_ficticio()
model = tv.get_model()
for nombretvorig, encabezado in (
("tv_produccion_gtx", "Producción geotextiles"),
("tv_ventas_gtx", "Ventas geotextiles"),
("tv_consumos_gtx", "Consumos geotextiles"),
("tv_produccion_fibra", "Producción fibra"),
("tv_ventas_fibra", "Ventas fibra"),
("tv_consumos_fibra", "Consumos fibra"),
("tv_produccion_bolsas", "Producción fibra embolsada"),
("tv_ventas_bolsas", "Ventas fibra embolsada"),
("tv_consumos_bolsas", "Consumos fibra embolsada"),
("tv_compras_geocompuestos", "Compras comercializados"),
("tv_ventas_geocompuestos", "Ventas comercializados")):
tvorig = self.wids[nombretvorig]
modelorig = tvorig.get_model()
model.append(["===", encabezado] + ["==="] * 13)
for filaorig in modelorig:
fila = []
for i in xrange(modelorig.get_n_columns()):
fila.append(filaorig[i])
model.append(fila)
for filahija in filaorig.iterchildren():
fila = [" > " + filahija[0]]
for i in xrange(1, modelorig.get_n_columns()):
fila.append(filahija[i])
model.append(fila)
model.append(["---"] * 15)
return tv
def imprimir(self, boton):
"""
Imprime el contenido de todos los TreeViews en un solo PDF apaisado.
"""
tv = self.unificar_tv()
from informes.treeview2pdf import treeview2pdf
from formularios.reports import abrir_pdf
strfecha = "%s - %s" % (utils.str_fecha(mx.DateTime.localtime()),
utils.str_hora(mx.DateTime.localtime()))
abrir_pdf(treeview2pdf(tv,
titulo="Resumen global por meses: Producción - Ventas - Consumos",
fecha = strfecha,
apaisado = True))
def exportar(self, boton):
"""
Vuelva el contenido de todos los TreeViews en un solo ".csv".
"""
tv = self.unificar_tv()
from informes.treeview2csv import treeview2csv
from formularios.reports import abrir_csv
nomarchivocsv = treeview2csv(tv)
abrir_csv(nomarchivocsv)
########################## P R O D U C C I Ó N G E O T E X T I L E S ########
def consultar_metros_y_kilos_gtx(fechaini, fechafin):
"""
Recibe 2 mx.DateTime con las fechas inicial y final de la
consulta de metros y kilos.
Devuelve los metros de A, kilos teóricos de A, kilos reales sin embalaje
de A, metros de B, metros teóricos de B y kilos reales de B; en este
orden.
"""
metros_a = kilos_teoricos_a = kilos_reales_a = 0.0
metros_b = kilos_teoricos_b = kilos_reales_b = 0.0
kilos_reales_c = 0.0
rollos = pclases.Rollo.select(pclases.AND(
pclases.Rollo.q.id == pclases.Articulo.q.rolloID,
pclases.Articulo.q.parteDeProduccionID==pclases.ParteDeProduccion.q.id,
pclases.ParteDeProduccion.q.fecha >= fechaini,
pclases.ParteDeProduccion.q.fecha < fechafin))
rollosDefectuosos = pclases.RolloDefectuoso.select(pclases.AND(
pclases.RolloDefectuoso.q.id == pclases.Articulo.q.rolloDefectuosoID,
pclases.Articulo.q.parteDeProduccionID
== pclases.ParteDeProduccion.q.id,
pclases.ParteDeProduccion.q.fecha >= fechaini,
pclases.ParteDeProduccion.q.fecha < fechafin))
rollosC = pclases.RolloC.select(pclases.AND(
pclases.RolloC.q.fechahora >= fechaini,
pclases.RolloC.q.fechahora < fechafin))
for r in rollos:
if not r.rollob:
metros_a += r.productoVenta.camposEspecificosRollo.metrosCuadrados
kilos_teoricos_a += r.peso_teorico
kilos_reales_a += r.peso_sin
else:
metros_b += r.productoVenta.camposEspecificosRollo.metrosCuadrados
kilos_teoricos_b += r.peso_teorico
kilos_reales_b += r.peso_sin
for rd in rollosDefectuosos:
superficie = rd.ancho * rd.metrosLineales
metros_b += superficie
kilos_teoricos_b += rd.peso_teorico
kilos_reales_b += rd.peso_sin
for rc in rollosC:
kilos_reales_c += rc.peso_sin
return (metros_a, kilos_teoricos_a, kilos_reales_a,
metros_b, kilos_teoricos_b, kilos_reales_b,
kilos_reales_c)
def consultar_bolsas_y_kilos(fechaini, fechafin):
"""
Recibe 2 mx.DateTime con las fechas inicial y final de la
consulta de bolsas y kilos.
Devuelve los bolsas de A, kilos de A, bolsas de B y kilos de B; en este
orden.
OJO: Ataca directamente a la BD con SQL. No es portable (aunque
a estas alturas cualquiera se atreve a cambiar de SGBD).
"""
con = pclases.Caja._connection
sqlbase = """
SELECT SUM(caja.numbolsas), SUM(caja.peso)
FROM caja, articulo, parte_de_produccion
WHERE caja.id = articulo.caja_id
AND articulo.parte_de_produccion_id = parte_de_produccion.id
AND parte_de_produccion.fecha >= '%s'
AND parte_de_produccion.fecha <= '%s'
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
if pclases.DEBUG:
bolsas, kilos = con.queryOne(sqlbase)
bolsas_a, kilos_a = con.queryOne(sqlbase
+ " AND NOT caja_es_clase_b(caja.id)")
bolsas_b, kilos_b = con.queryOne(sqlbase + " AND caja_es_clase_b(caja.id)")
if pclases.DEBUG:
kilos = kilos != None and kilos or 0.0
bolsas = bolsas != None and bolsas or 0
bolsas_a = bolsas_a != None and bolsas_a or 0
kilos_a = kilos_a != None and kilos_a or 0.0
bolsas_b = bolsas_b != None and bolsas_b or 0
kilos_b = kilos_b != None and kilos_b or 0.0
if pclases.DEBUG:
assert bolsas_a + bolsas_b == bolsas, \
"consulta_global.py::consultar_bolsas_y_kilos -> "\
"Suma de bolsas A + B diferente a bolsas totales: %s" % (
(bolsas_a, bolsas_b, bolsas), )
assert round(kilos_a + kilos_b, 2) == round(kilos, 2), \
"consulta_global.py::consultar_bolsas_y_kilos -> "\
"Suma de kilos A + B diferente a kilos totales: %s" % (
(kilos_a, kilos_b, kilos), )
return bolsas_a, kilos_a, bolsas_b, kilos_b
def consultar_kilos_bigbags_consumidos(fechaini, fechafin):
"""
Devuelve los kilos de fibra consumidos en forma de bigbag por los partes
de producción de fibra de cemento.
OJO: Se considera que un parte de producción consume un bigbag completo
aunque realmente no se haya gastado completo y se termine en el parte
siguiente.
"""
con = pclases.ParteDeProduccion._connection
sql = """
SELECT SUM(bigbag.pesobigbag)
FROM bigbag, parte_de_produccion
WHERE bigbag.parte_de_produccion_id = parte_de_produccion.id
AND parte_de_produccion.fecha >= '%s'
AND parte_de_produccion.fecha <= '%s'
AND parte_de_produccion.partida_cem_id IS NOT NULL
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
kilos = con.queryOne(sql)[0]
kilos = kilos != None and kilos or 0.0
return kilos
def consultar_kilos_fibra_consumidos(fechaini, fechafin):
"""
Recibe 2 mx.DateTime con las fechas inicial y final de la
consulta de metros y kilos.
Devuelve los kilos de fibra consumidos según el criterio de
que una partida de carga no se considera consumida por completo
si todas sus partidas no se han fabricado antes de fechafin.
OJO: Ataca directamente a la BD con SQL. No es portable (aunque
a estas alturas cualquiera se atreve a cambiar de SGBD).
(Ver metros_y_kilos_gtx.sql)
"""
partes = pclases.ParteDeProduccion.select(pclases.AND(
pclases.ParteDeProduccion.q.fechahorainicio >= fechaini,
pclases.ParteDeProduccion.q.fechahorainicio < fechafin))
return sum([pdp.calcular_consumo_mp() for pdp in partes
if pdp.es_de_geotextiles()])
def consultar_horas_reales_gtx(fechaini, fechafin):
"""
Devuelve la suma de las duraciones de los partes entre las dos
fechas recibidas.
"""
sql = """
SELECT SUM(fechahorafin - fechahorainicio)
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha < '%s' -- Parámetro fecha fin
AND observaciones NOT LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
try:
horas_sql = pclases.ParteDeProduccion._queryAll(sql)[0][0]
try:
horas = horas_sql.hours
except AttributeError: # Es un datetime.timedelta
horas = (horas_sql.days * 24.0) + (horas_sql.seconds / 3600.0)
except (IndexError, AttributeError):
horas = 0.0
return horas
def consultar_horas_reales_bolsas(fechaini, fechafin):
"""
Devuelve la suma de las duraciones de los partes entre las dos
fechas recibidas.
"""
sql = """
SELECT SUM(fechahorafin - fechahorainicio)
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha <= '%s' -- Parámetro fecha fin
AND partida_cem_id IS NOT NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
try:
horas_sql = pclases.ParteDeProduccion._queryAll(sql)[0][0]
try:
horas = horas_sql.hours
except AttributeError: # Es un datetime.timedelta
horas = (horas_sql.days * 24.0) + (horas_sql.seconds / 3600.0)
except (IndexError, AttributeError):
horas = 0.0
return horas
def consultar_horas_trabajo_bolsas(fechaini, fechafin, logger = None):
"""
Devuelve la suma de las duraciones de los partes entre las dos
fechas recibidas menos las horas de parada.
"""
partes = pclases.ParteDeProduccion.select("""
fecha >= '%s'
AND fecha <= '%s'
AND partida_cem_id IS NOT NULL
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d")))
try:
horas_trabajadas = sum([pdp.get_horas_trabajadas() for pdp in partes])
except AssertionError, msg:
txt = "consulta_global::consultar_horas_trabajo_bolsas -> "\
"Error calculando horas de trabajo de línea de geotextiles: %s."\
" Ignoro todos los partes implicados en el mismo rango de "\
"fechas del que provoca el error." % (msg)
print txt
if logger != None:
logger.error(txt)
horas_trabajadas = mx.DateTime.DateTimeDelta(0)
try:
horas_trabajadas = horas_trabajadas.hours
except AttributeError:
try: # Es un datetime.timedelta
horas_trabajadas = ((horas_trabajadas.days * 24.0)
+ (horas_trabajadas.seconds / 3600.0))
except AttributeError:
horas_trabajadas = 0.0
return horas_trabajadas
def consultar_horas_trabajo_gtx(fechaini, fechafin, logger = None):
"""
Devuelve la suma de las duraciones de los partes entre las dos
fechas recibidas menos las horas de parada.
"""
partes = pclases.ParteDeProduccion.select("""
fecha >= '%s'
AND fecha < '%s'
AND observaciones NOT LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL
""" % (fechaini.strftime("%Y-%m-%d"),
fechafin.strftime("%Y-%m-%d")))
try:
horas_trabajadas = sum([pdp.get_horas_trabajadas() for pdp in partes])
except AssertionError, msg:
txt = "consulta_global::consultar_horas_trabajo_gtx -> "\
"Error calculando horas de trabajo de línea de geotextiles: "\
"%s. Ignoro todos los partes implicados en el mismo rango de "\
"fechas del que provoca el error." % (msg)
print txt
if logger != None:
logger.error(txt)
horas_trabajadas = mx.DateTime.DateTimeDelta(0)
try:
horas_trabajadas = horas_trabajadas.hours
except AttributeError:
try: # Es un datetime.timedelta
horas_trabajadas = ((horas_trabajadas.days * 24.0)
+ (horas_trabajadas.seconds / 3600.0))
except AttributeError:
horas_trabajadas = 0.0
return horas_trabajadas
def consultar_dias_gtx(fechaini, fechafin):
"""
Devuelve el número de días (fechas distintas) en los que hay
al menos un parte de producción de geotextiles entre las fechas
recibidas.
"""
sql = """
SELECT COUNT(DISTINCT fecha)
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha < '%s' -- Parámetro fecha fin
AND observaciones NOT LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
try:
dias = pclases.ParteDeProduccion._queryAll(sql)[0][0]
except IndexError:
dias = 0
return dias
def consultar_productividad_bolsas(fechaini, fechafin):
"""
Devuelve la productividad de los partes de producción de
embolsado entre las fechas recibidas.
"""
sql_where=" fecha >= '%s' AND fecha <= '%s' AND partida_cem_id IS NULL "%(
fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
pdps = pclases.ParteDeProduccion.select(sql_where)
res = calcular_productividad_conjunta(tuple(pdps))
return res
def consultar_empleados_por_dia_bolsas(fechaini, fechafin):
"""
Devuelve el número de empleados por día a través de una tocho-consulta(TM)
a la base de datos.
"""
sql = """
SELECT fecha, empleadoid
FROM parte_de_produccion_empleado,
(SELECT id, fecha
FROM parte_de_produccion
WHERE fecha >= '%s'
AND fecha <= '%s'
AND partida_cem_id IS NOT NULL) AS partes
WHERE partes.id = parte_de_produccion_empleado.partedeproduccionid
GROUP BY fecha, empleadoid ORDER BY fecha; """ % (
fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
filas_fecha_idempleado=pclases.ParteDeProduccion._queryAll(sql)
# Y ahora sumo (lo sé, se podría hacer directamente en la consulta, pero
# prefiero dejarla así porque creo que me hará falta en un futuro tenerlo
# desglosado).
fechas = []
empleados = 0.0
for fecha, idempleado in filas_fecha_idempleado: # @UnusedVariable
if fecha not in fechas:
fechas.append(fecha)
empleados += 1
try:
res = empleados / len(fechas)
except ZeroDivisionError:
res = 0.0
return res
def consultar_empleados_por_dia_gtx(fechaini, fechafin):
"""
Devuelve el número de empleados por día a través de una tocho-consulta(TM)
a la base de datos.
"""
sql = """
SELECT fecha, empleadoid
FROM parte_de_produccion_empleado,
(SELECT id, fecha
FROM parte_de_produccion
WHERE fecha >= '%s'
AND fecha < '%s'
AND observaciones NOT LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL) AS partes
WHERE partes.id = parte_de_produccion_empleado.partedeproduccionid
GROUP BY fecha, empleadoid ORDER BY fecha; """ % (
fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
filas_fecha_idempleado = pclases.ParteDeProduccion._queryAll(sql)
# Y ahora sumo (lo sé, se podría hacer directamente en la consulta, pero
# prefiero dejarla así porque creo que me hará falta en un futuro tenerlo
# desglosado).
fechas = []
empleados = 0.0
for fecha, idempleado in filas_fecha_idempleado: # @UnusedVariable
if fecha not in fechas:
fechas.append(fecha)
empleados += 1
try:
res = empleados / len(fechas)
except ZeroDivisionError:
res = 0.0
return res
def buscar_produccion_gtx(anno, vpro=None, rango=None, logger=None, meses=()):
"""
"anno" es el año del que buscará las producciones.
"vpro" es la ventana de progreso de la ventana principal.
"rango" es un flotante que indica el porcentaje máximo a
recorrer por la ventana de progreso durante esta función.
Devuelve la producción en kg y m² de A, B y C en un diccionario
cuyas claves son el parámetro evaluado que contiene otro diccionario
con la información en cada mes (empezando por 0).
"""
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (inicializando)")
res = {}
res = dict([(i, 0) for i in xrange(12)])
res['pdps'] = defaultdict(lambda: []) # Para cálculo productividad conjunta
res['metros'] = defaultdict(lambda: 0.0) # ["Total m² (A+B)"]
res['kilos'] = defaultdict(lambda: 0.0) # ["Total kg teóricos (A+B)"]
res['kilos_reales'] = defaultdict(lambda: 0.0) # ["Total kg reales (A+B+C)"]
res['metros_a'] = defaultdict(lambda: 0.0) # ["Total m² (A)"]
res['kilos_a'] = defaultdict(lambda: 0.0) # ["Total kg teóricos (A)"]
res['kilos_reales_a'] = defaultdict(lambda: 0.0)
# ["Total kg reales sin embalaje (A)"]
res['metros_b'] = defaultdict(lambda: 0.0) # ["Total m² (B)"]
res['kilos_b'] = defaultdict(lambda: 0.0) # ["Total kg teóricos (B)"]
res['kilos_reales_b'] = defaultdict(lambda: 0.0)
# ["Total kg reales sin embalaje (B)"]
res['kilos_reales_c'] = defaultdict(lambda: 0.0) # ["Total kg reales (C)"]
res['merma'] = defaultdict(lambda: 0.0) # ["Merma"]
res['porciento_merma'] = defaultdict(lambda: 0.0) # ["% merma", ]
res['gramaje_medio'] = defaultdict(lambda: 0.0) # ["Gramaje medio (A)"]
res['kilos_hora'] = defaultdict(lambda: 0.0)
# ["Kilos A+B (reales s.e.)/hora"]
res['horas'] = defaultdict(lambda: 0.0) # ["Horas de trabajo"]
res['horas_produccion'] = defaultdict(lambda: 0.0) # ["Horas de producción"]
res['dias'] = defaultdict(lambda: 0.0) # ["Días de trabajo"]
res['turnos'] = defaultdict(lambda: 0.0) # ["Turnos / día"]
res['empleados'] = defaultdict(lambda: 0.0) # ["Trabajadores / día"]
res['productividad'] = defaultdict(lambda: 0.0) # ["Productividad"]
res['consumo_fibra'] = defaultdict(lambda: 0.0)
for mes in xrange(12):
if mes+1 not in meses:
continue
fini = mx.DateTime.DateTimeFrom(day=1, month=mes+1, year=anno)
try:
ffin = mx.DateTime.DateTimeFrom(day=1, month=fini.month + 1,
year=anno)
except mx.DateTime.RangeError:
ffin = mx.DateTime.DateTimeFrom(day=1, month=1, year=anno+1)
pdps = tuple(pclases.ParteDeProduccion.select(
pclases.AND(pclases.ParteDeProduccion.q.fecha >= fini,
pclases.ParteDeProduccion.q.fecha < ffin)))
pdps = [pdp for pdp in pdps if pdp.es_de_geotextiles()]
res["pdps"][mes] = pdps
(metros_a,
kilos_teoricos_a,
kilos_reales_a,
metros_b,
kilos_teoricos_b,
kilos_reales_b,
kilos_c) = consultar_metros_y_kilos_gtx(fini, ffin)
res['metros'][mes] = metros_a + metros_b
res['kilos'][mes] = kilos_teoricos_a + kilos_teoricos_b
res['kilos_reales'][mes] = kilos_reales_a + kilos_reales_b + kilos_c
res['metros_a'][mes] = metros_a
res['kilos_a'][mes] = kilos_teoricos_a
res['kilos_reales_a'][mes] = kilos_reales_a
res['metros_b'][mes] = metros_b
res['kilos_b'][mes] = kilos_teoricos_b
res['kilos_reales_b'][mes] = kilos_reales_b
res['kilos_reales_c'][mes] = kilos_c
kilos_consumidos = consultar_kilos_fibra_consumidos(fini,
ffin)
kilos_fabricados = kilos_reales_a + kilos_reales_b + kilos_c
res['merma'][mes] = kilos_fabricados - kilos_consumidos
try:
res['porciento_merma'][mes] = (1 - (kilos_fabricados
/ kilos_consumidos)) * 100.0
except ZeroDivisionError:
res['porciento_merma'][mes] = 0.0
try:
res['gramaje_medio'][mes] = ((kilos_reales_a + kilos_reales_b)
/ (metros_a + metros_b)) * 1000
except ZeroDivisionError:
res['gramaje_medio'][mes] = 0.0
horas = consultar_horas_reales_gtx(fini, ffin)
try:
res['kilos_hora'][mes] = (kilos_reales_a + kilos_reales_b) / horas
except ZeroDivisionError:
res['kilos_hora'][mes] = 0.0
res['horas'][mes] = horas
horas_trabajo = consultar_horas_trabajo_gtx(fini,
ffin,
logger)
res['horas_produccion'][mes] = horas_trabajo
dias = consultar_dias_gtx(fini, ffin)
res['dias'][mes] = dias
try:
turnos = (horas / 8.0) / dias
# (Horas / 8 horas por turno) / días para obtener
# los turnos por día.
except ZeroDivisionError:
turnos = 0.0
res['turnos'][mes] = turnos
res['empleados'][mes] = consultar_empleados_por_dia_gtx(fini, ffin)
res['productividad'][mes]=calcular_productividad_conjunta(tuple(pdps))
res['consumo_fibra'][mes] = kilos_consumidos
# OJO: Kg/hora se calcula con las horas en las que la máquina
# funciona, sin contar paradas. En la ventana se muestran las
# horas totales de los partes de la línea.
# OJO: Como los Geotextiles C no tienen ancho ni largo, no los
# meto en la producción global para no falsear los
# resultados.
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (%d/12)" % (mes + 1))
return res
def buscar_produccion_bolsas(anno, vpro=None, rango=None, logger=None,
meses=()):
"""
"anno" es el año del que buscará las producciones.
"vpro" es la ventana de progreso de la ventana principal.
"rango" es un flotante que indica el porcentaje máximo a
recorrer por la ventana de progreso durante esta función.
Devuelve la producción en kg y m² de A y B en un diccionario
cuyas claves son números enteros del 0 al 11 que se corresponden
con los meses. Dentro de cada clave hay otro diccionario con
claves 'A' y 'B', y como valores otro diccionario
con claves 'bolsas' y 'kilos'.
"""
res = dict([(i, 0) for i in xrange(12)])
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
for i in xrange(12):
if i+1 not in meses:
res[i] = {'A' : {'bolsas': 0, 'kilos': 0},
'B' : {'bolsas': 0, 'kilos': 0},
'consumo': 0, 'kilos_hora': 0,
'horas': 0, 'horas_produccion': 0,
'dias': 0, 'turnos': 0,
'empleados': 0, 'productividad': 0}
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
(bolsas_a,
kilos_a,
bolsas_b,
kilos_b) = consultar_bolsas_y_kilos(fechaini, fechafin)
kilos_consumidos = consultar_kilos_bigbags_consumidos(fechaini,
fechafin)
horas = consultar_horas_reales_bolsas(fechaini, fechafin)
horas_trabajo = consultar_horas_trabajo_bolsas(fechaini,
fechafin,
logger)
try:
kilos_hora = (kilos_a + kilos_b) / horas_trabajo
except ZeroDivisionError:
kilos_hora = 0.0
dias = consultar_dias_bolsas(fechaini, fechafin)
# print kilos_a, kilos_b, horas, horas_trabajo. # OJO: Kg/hora se
# calcula con las horas en las que la máquina funciona, sin contar
# paradas. En la ventana se muestran las horas totales de los
# partes de la línea.
try:
turnos = (horas / 8.0) / dias
# (Horas / 8 horas por turno) / días para obtener
# los turnos por día.
except ZeroDivisionError:
turnos = 0.0
res[i] = {'A' : {'bolsas': bolsas_a, 'kilos': kilos_a},
'B' : {'bolsas': bolsas_b, 'kilos': kilos_b},
'consumo': kilos_consumidos,
'kilos_hora': kilos_hora,
'horas': horas,
'horas_produccion': horas_trabajo,
'dias': dias,
'turnos': turnos,
'empleados':consultar_empleados_por_dia_bolsas(fechaini,
fechafin),
'productividad':consultar_productividad_bolsas(fechaini,
fechafin),
}
if vpro != None: vpro.set_valor(vpro.get_valor() + incr_progreso,
vpro.get_texto())
return res
##################### V E N T A S #############################################
def _buscar_compras_geocompuestos(fecha_ini, fecha_fin):
"""
Dadas fecha de inicio y de fin, busca todas las compras
(LDVs, LDAs y LDDs) facturadas entre esas dos fechas.
"""
compras_geocmp = {}
if 'total' not in compras_geocmp:
compras_geocmp['total'] = {'cantidad': 0.0, 'euros': 0.0}
idcliente = None # @UnusedVariable
resultado = [] # @UnusedVariable
facturas = pclases.FacturaCompra.select(pclases.AND(
pclases.FacturaCompra.q.fecha >= fecha_ini,
pclases.FacturaCompra.q.fecha <= fecha_fin),
orderBy='fecha')
for f in facturas:
for linea in f.lineasDeCompra:
p = linea.productoCompra
if p != None and (p.es_geocompuesto()):
proveedor = linea.proveedor
euros = linea.get_subtotal()
cantidad = linea.cantidad
if proveedor not in compras_geocmp:
compras_geocmp[proveedor] = {'cantidad':cantidad,
'euros':euros}
else:
compras_geocmp[proveedor]['cantidad'] += cantidad
compras_geocmp[proveedor]['euros'] += euros
compras_geocmp['total']['cantidad'] += cantidad
compras_geocmp['total']['euros'] += euros
# No hay abonos de productos de compra. Se usan facturas con cantidad < 0
return compras_geocmp
def _buscar_ventas_geocompuestos(fecha_ini, fecha_fin):
"""
Dadas fecha de inicio y de fin, busca todas las ventas
(LDVs, LDAs y LDDs) facturadas entre esas dos fechas.
"""
ventas_geocmp = {}
if 'total' not in ventas_geocmp:
ventas_geocmp['total'] = {'cantidad': 0.0, 'euros': 0.0}
idcliente = None # @UnusedVariable
resultado = [] # @UnusedVariable
facturas = pclases.FacturaVenta.select(pclases.AND(
pclases.FacturaVenta.q.fecha >= fecha_ini,
pclases.FacturaVenta.q.fecha <= fecha_fin),
orderBy='fecha')
for f in facturas:
for linea in f.lineasDeVenta:
p = linea.productoCompra
if p != None and (p.es_geocompuesto()):
tarifa = linea.get_tarifa()
euros = linea.get_subtotal()
cantidad = linea.cantidad
if tarifa not in ventas_geocmp:
ventas_geocmp[tarifa]={'cantidad':cantidad,'euros':euros}
else:
ventas_geocmp[tarifa]['cantidad'] += cantidad
ventas_geocmp[tarifa]['euros'] += euros
ventas_geocmp['total']['cantidad'] += cantidad
ventas_geocmp['total']['euros'] += euros
# No hay abonos de productos de compra. Se usan facturas con cantidad < 0
return ventas_geocmp
def _buscar_ventas(fecha_ini, fecha_fin):
"""
Dadas fecha de inicio y de fin, busca todas las ventas
(LDVs) facturadas entre esas dos fechas.
"""
ventas_gtx = {}
ventas_fibra = {}
ventas_bolsas = {}
if 'total' not in ventas_gtx:
ventas_gtx['total'] = {'metros': 0.0, 'kilos': 0.0, 'euros': 0.0}
if 'total' not in ventas_fibra:
ventas_fibra['total'] = {'kilos': 0.0, 'euros': 0.0}
if 'total' not in ventas_bolsas:
ventas_bolsas['total'] = {'bolsas': 0, 'kilos': 0.0, 'euros': 0.0}
idcliente = None # @UnusedVariable
resultado = [] # @UnusedVariable
resultado_abonos = {'lineasDeAbono': [], # @UnusedVariable
'lineasDeDevolucion': []}
facturas = pclases.FacturaVenta.select(pclases.AND(
pclases.FacturaVenta.q.fecha >= fecha_ini,
pclases.FacturaVenta.q.fecha <= fecha_fin),
orderBy='fecha')
facturasDeAbono = pclases.FacturaDeAbono.select(pclases.AND(
pclases.FacturaDeAbono.q.fecha <= fecha_fin,
pclases.FacturaDeAbono.q.fecha >= fecha_ini),
orderBy = 'fecha')
facturasDeAbono = [f for f in facturasDeAbono if f.abono]
for f in facturas:
for linea in f.lineasDeVenta:
procesar_ldv(linea, ventas_gtx, ventas_fibra, ventas_bolsas)
for f in facturasDeAbono:
abono = f.abono
for lda in abono.lineasDeAbono:
# Filtro las que son ajuste de precio de servicios.
if lda.lineaDeVenta != None:
procesar_lda(lda, ventas_gtx, ventas_fibra, ventas_bolsas)
for ldd in abono.lineasDeDevolucion:
procesar_ldd(ldd, ventas_gtx, ventas_fibra, ventas_bolsas)
return ventas_gtx, ventas_fibra, ventas_bolsas
def procesar_lda(linea, ventas_gtx, ventas_fibra, ventas_bolsas):
p = linea.productoVenta
if p != None:
tarifa = linea.get_tarifa()
euros = linea.diferencia * linea.cantidad
if p.es_rollo():
# metros = -linea.cantidad
metros = 0 # OJO: Es un ajuste de precio, no se ha devuelto
# material.
# kilos = -linea.cantidad*p.camposEspecificosRollo.gramos/1000.0
kilos = 0 # OJO: Es un ajuste de precio, no se ha devuelto material
if tarifa not in ventas_gtx:
ventas_gtx[tarifa] = {'metros': metros,
'kilos': kilos,
'euros': euros}
else:
ventas_gtx[tarifa]['metros'] += metros
ventas_gtx[tarifa]['kilos'] += kilos
ventas_gtx[tarifa]['euros'] += euros
ventas_gtx['total']['metros'] += metros
ventas_gtx['total']['kilos'] += kilos
ventas_gtx['total']['euros'] += euros
elif p.es_bigbag() or p.es_bala():
# kilos = -linea.cantidad
kilos = 0 # OJO: Es un ajuste de precio, no se ha devuelto material
if tarifa not in ventas_fibra:
ventas_fibra[tarifa] = {'kilos': kilos, 'euros': euros}
else:
ventas_fibra[tarifa]['kilos'] += kilos
ventas_fibra[tarifa]['euros'] += euros
ventas_fibra['total']['kilos'] += kilos
ventas_fibra['total']['euros'] += euros
elif p.es_bolsa():
kilos = 0 #OJO: Es un ajuste de precio, no se ha devuelto material.
bolsas = kilos / (p.camposEspecificosBala.gramosBolsa / 1000.0)
if tarifa not in ventas_bolsas:
ventas_bolsas[tarifa] = {'kilos': kilos, 'euros': euros,
'bolsas': bolsas}
else:
ventas_bolsas[tarifa]['kilos'] += kilos
ventas_bolsas[tarifa]['euros'] += euros
ventas_bolsas[tarifa]['bolsas'] += bolsas
ventas_bolsas['total']['kilos'] += kilos
ventas_bolsas['total']['euros'] += euros
ventas_bolsas['total']['bolsas'] += bolsas
elif p.es_especial(): # No sé qué hacer con los productos especiales,
# así que los ignoro.
print "OJO: Ignorando venta de línea LDA ID %d por no ser fibra"\
" ni geotextil (es producto especial)." % (linea.id)
elif p.es_bala_cable(): # Tampoco sé muy bien cómo habría que tratar
# una devolución de bala de cable enviada
# para reciclar.
print "OJO: Ignorando venta de línea LDA ID %d por no ser fibra"\
" ni geotextil (es bala_cable)." % (linea.id)
else: # No sé qué hacer con las ventas de productos de compra o
# servicios, así que las ignoro.
print "OJO: Ignorando venta de línea LDA ID %d por no ser fibra ni "\
"geotextil (es producto de compra o servicio)." % (linea.id)
def procesar_ldd(linea, ventas_gtx, ventas_fibra, ventas_bolsas):
p = linea.productoVenta
if p != None:
tarifa = linea.get_tarifa()
# euros = linea.cantidad * linea.precio
# FIXED: LineaDeDevolucion.precio es el importe total de la
# línea. Cantidad es un property que mira la cantidad exacta
# en m² o kg del bulto relacionado
# (1 LDD = 1 bulto = 1 pclases.Articulo).
euros = -1 * linea.precio
if p.es_rollo():
metros = linea.cantidad
kilos = linea.cantidad * p.camposEspecificosRollo.gramos / 1000.0
if tarifa not in ventas_gtx:
ventas_gtx[tarifa] = {'metros': metros,
'kilos': kilos,
'euros': euros}
else:
ventas_gtx[tarifa]['metros'] += metros
ventas_gtx[tarifa]['kilos'] += kilos
ventas_gtx[tarifa]['euros'] += euros
ventas_gtx['total']['metros'] += metros
ventas_gtx['total']['kilos'] += kilos
ventas_gtx['total']['euros'] += euros
elif p.es_bigbag() or p.es_bala():
kilos = linea.cantidad
if tarifa not in ventas_fibra:
ventas_fibra[tarifa] = {'kilos': kilos, 'euros': euros}
else:
ventas_fibra[tarifa]['kilos'] += kilos
ventas_fibra[tarifa]['euros'] += euros
ventas_fibra['total']['kilos'] += kilos
ventas_fibra['total']['euros'] += euros
elif p.es_bolsa():
kilos = linea.cantidad
bolsas = kilos / (p.camposEspecificosBala.gramosBolsa / 1000.0)
if tarifa not in ventas_bolsas:
ventas_bolsas[tarifa] = {'kilos': kilos, 'euros': euros,
'bolsas': bolsas}
else:
ventas_bolsas[tarifa]['kilos'] += kilos
ventas_bolsas[tarifa]['euros'] += euros
ventas_bolsas[tarifa]['bolsas'] += bolsas
ventas_bolsas['total']['kilos'] += kilos
ventas_bolsas['total']['euros'] += euros
ventas_bolsas['total']['bolsas'] += bolsas
elif p.es_especial():
# No sé qué hacer con los productos especiales, así que los ignoro.
print "OJO: Ignorando venta de línea LDD ID %d por no ser fibra"\
" ni geotextil (es producto especial)." % (linea.id)
else: # No sé qué hacer con las ventas de productos de compra o
# servicios, así que las ignoro.
print "OJO: Ignorando venta de línea LDD ID %d por no ser fibra ni "\
"geotextil (es producto de compra o servicio)." % (linea.id)
def procesar_ldv(linea, ventas_gtx, ventas_fibra, ventas_bolsas):
p = linea.productoVenta
# XXX: if p != None: OJO: Ahora la fibra se organiza de otra forma.
# Me salto las ventas de fibra aquí. Sólo proceso las de geotextiles.
if p != None and (p.es_rollo() or p.es_bolsa()):
tarifa = linea.get_tarifa()
euros = linea.get_subtotal()
if p.es_rollo():
metros = linea.cantidad
kilos = linea.cantidad * p.camposEspecificosRollo.gramos / 1000.0
if tarifa not in ventas_gtx:
ventas_gtx[tarifa] = {'metros': metros, 'kilos': kilos,
'euros': euros}
else:
ventas_gtx[tarifa]['metros'] += metros
ventas_gtx[tarifa]['kilos'] += kilos
ventas_gtx[tarifa]['euros'] += euros
ventas_gtx['total']['metros'] += metros
ventas_gtx['total']['kilos'] += kilos
ventas_gtx['total']['euros'] += euros
elif p.es_bigbag() or p.es_bala():
kilos = linea.cantidad
if tarifa not in ventas_fibra:
ventas_fibra[tarifa] = {'kilos': kilos, 'euros': euros}
else:
ventas_fibra[tarifa]['kilos'] += kilos
ventas_fibra[tarifa]['euros'] += euros
ventas_fibra['total']['kilos'] += kilos
ventas_fibra['total']['euros'] += euros
elif p.es_bolsa():
kilos = linea.cantidad
bolsas = kilos / (p.camposEspecificosBala.gramosBolsa / 1000.0)
if tarifa not in ventas_bolsas:
ventas_bolsas[tarifa] = {'kilos': kilos, 'euros': euros,
'bolsas': bolsas}
else:
ventas_bolsas[tarifa]['kilos'] += kilos
ventas_bolsas[tarifa]['euros'] += euros
ventas_bolsas[tarifa]['bolsas'] += bolsas
ventas_bolsas['total']['kilos'] += kilos
ventas_bolsas['total']['euros'] += euros
ventas_bolsas['total']['bolsas'] += bolsas
elif p.es_especial(): # No sé qué hacer con los productos
# especiales, así que los ignoro.
print "OJO: Ignorando venta de línea LDV ID %d por no ser "\
"fibra ni geotextil (es producto especial)." % (linea.id)
elif p.es_bala_cable(): # No sé cómo tratar las ventas de fibra para
# reciclar. Se supone que no se factura. Sólo
# salen en albarán.
print "OJO: Ignorando venta de línea LDV ID %d por no ser "\
"fibra ni geotextil (es bala_cable)." % (linea.id)
else: # No sé qué hacer con las ventas de productos de compra o
# servicios, así que las ignoro.
pass # En esta función ya solo se cuentan geotextiles. No tiene
# sentido sacar mensaje. Se ha cambiado la condición
# y entra en la rama else tanto si es producto de compra o
# servicio como si es fibra normal.
def ejecutar_consultas_ventas_fibra_por_color(fechaini, fechafin):
"""
Ejecuta las consultas de venta de fibra (balas) por color
entre las fechas fechaini y fechafin y devuelve los kilos y
euros de facturas y albaranes en un diccionario de colores
y "internacional" o "nacional".
Incluye fibra B (marcada como B en el parte de producción) pero
no la C (balas de cable -balaCable- que tiene True en el campo
reciclada del camposEspecificosBala del producto de venta).
"""
#prods = """
# SELECT pv.id AS producto_venta_id, color
# INTO TEMP fibra_balas_con_campos_especificos_temp
# FROM campos_especificos_bala ceb, producto_venta pv
# WHERE pv.campos_especificos_bala_id = ceb.id
# AND pv.descripcion NOT ILIKE '%GEOCEM%';
#"""
prods = """
SELECT pv.id AS producto_venta_id, color
INTO TEMP fibra_balas_con_campos_especificos_temp
FROM campos_especificos_bala ceb, producto_venta pv
WHERE pv.campos_especificos_bala_id = ceb.id
AND pv.descripcion NOT ILIKE %s
AND ceb.reciclada = FALSE;
""" % pclases.ProductoVenta.sqlrepr("%GEOCEM%")
sql_fechaini = fechaini.strftime("%Y-%m-%d")
sql_fechafin = fechafin.strftime("%Y-%m-%d")
kilos_euros_ldv = """
SELECT SUM(linea_de_venta.cantidad) AS kilos,
SUM(linea_de_venta.cantidad
* linea_de_venta.precio
* (1-linea_de_venta.descuento)) AS euros,
fibra_balas_con_campos_especificos_temp.color,
cliente.pais
FROM linea_de_venta,
factura_venta,
cliente,
fibra_balas_con_campos_especificos_temp
WHERE linea_de_venta.factura_venta_id = factura_venta.id
AND factura_venta.fecha >= '%s'
AND factura_venta.fecha <= '%s'
AND cliente.id = factura_venta.cliente_id
AND linea_de_venta.producto_venta_id
= fibra_balas_con_campos_especificos_temp.producto_venta_id
GROUP BY cliente.pais, fibra_balas_con_campos_especificos_temp.color;
""" % (sql_fechaini, sql_fechafin)
kilos_euros_lda = """
SELECT 0.0 AS kilos,
SUM(linea_de_abono.cantidad*linea_de_abono.diferencia) AS euros,
fibra_balas_con_campos_especificos_temp.color,
cliente.pais
FROM linea_de_abono,
factura_de_abono,
cliente,
abono,
linea_de_venta,
fibra_balas_con_campos_especificos_temp
WHERE linea_de_abono.abono_id = abono.id
AND linea_de_abono.linea_de_venta_id = linea_de_venta.id
AND linea_de_venta.producto_venta_id
= fibra_balas_con_campos_especificos_temp.producto_venta_id
AND factura_de_abono.fecha >= '%s'
AND factura_de_abono.fecha <= '%s'
AND cliente.id = abono.cliente_id
AND factura_de_abono.id = abono.factura_de_abono_id
GROUP BY cliente.pais, fibra_balas_con_campos_especificos_temp.color;
""" % (sql_fechaini, sql_fechafin)
frabonos = """
SELECT linea_de_devolucion.id,
linea_de_devolucion.articulo_id,
cliente.pais,
linea_de_devolucion.precio,
fibra_balas_con_campos_especificos_temp.color
INTO TEMP facturas_de_abono_temp
FROM linea_de_devolucion,
factura_de_abono,
cliente,
abono,
articulo,
fibra_balas_con_campos_especificos_temp
WHERE linea_de_devolucion.abono_id = abono.id
AND factura_de_abono.id = abono.factura_de_abono_id
AND factura_de_abono.fecha >= '%s'
AND factura_de_abono.fecha <= '%s'
AND cliente.id = abono.cliente_id
AND linea_de_devolucion.albaran_de_entrada_de_abono_id IS NOT NULL
AND articulo.id = linea_de_devolucion.articulo_id
AND articulo.producto_venta_id
= fibra_balas_con_campos_especificos_temp.producto_venta_id;
""" % (sql_fechaini, sql_fechafin)
kilos_euros_ldd = """
SELECT -1 * SUM(bala.pesobala) AS kilos,
-1 * SUM(precio) AS euros,
color,
pais
FROM bala, facturas_de_abono_temp, articulo
WHERE bala.id = articulo.bala_id
AND facturas_de_abono_temp.articulo_id = articulo.id
GROUP BY pais, color;
"""
caidita_de_roma = """
DROP TABLE fibra_balas_con_campos_especificos_temp;
DROP TABLE facturas_de_abono_temp;
"""
con = pclases.Bala._connection # En realidad la clase da igual.
con.query(prods)
con.query(frabonos)
ke_ldv = con.queryAll(kilos_euros_ldv)
ke_lda = con.queryAll(kilos_euros_lda)
ke_ldd = con.queryAll(kilos_euros_ldd)
try:
dde = pclases.DatosDeLaEmpresa.select()[0]
except IndexError:
print "No existen datos en la tabla datos_de_la_empresa. "\
"Usando 'ESPAÑA' como país predeterminado."
pais_empresa = unicode("españa")
else:
pais_empresa = unicode(dde.paisfacturacion.strip()).lower()
res = {}
for fila in ke_ldv + ke_lda + ke_ldd:
kilos, euros, color, pais = fila
if color not in res:
res[color] = {}
pais = unicode(pais.strip())
if pais != "" and pais.lower() != pais_empresa:
clavepais = "internacional"
else: # Si no lleva país, lo considero nacional (es normal
# dejarlo en blanco si el país es España).
clavepais = "nacional"
if clavepais not in res[color]:
res[color][clavepais] = {'kilos': 0.0, 'euros': 0.0}
try:
res[color][clavepais]['kilos'] += kilos
except TypeError:
res[color][clavepais]['kilos'] += float(kilos)
try:
res[color][clavepais]['euros'] += euros
except TypeError:
res[color][clavepais]['euros'] += float(euros)
con.query(caidita_de_roma)
return res
def ejecutar_consultas_ventas_bigbags(fechaini, fechafin):
"""
Ejecuta consultas SQL directamente contra la BD para
obtener las ventas de bigbags entre las fechas indicadas.
"""
sql_fechaini = fechaini.strftime("%Y-%m-%d")
sql_fechafin = fechafin.strftime("%Y-%m-%d")
prods = """
SELECT pv.id AS producto_venta_id
INTO TEMP fibra_bigbags
FROM producto_venta pv
WHERE pv.descripcion ILIKE '%GEOCEM%';
"""
kilos_euros_ldv = """
SELECT COALESCE(SUM(linea_de_venta.cantidad), 0.0) AS kilos,
COALESCE(SUM(linea_de_venta.cantidad
* linea_de_venta.precio
* (1-linea_de_venta.descuento)),
0.0) AS euros
FROM linea_de_venta, factura_venta, fibra_bigbags
WHERE linea_de_venta.factura_venta_id = factura_venta.id
AND factura_venta.fecha >= '%s'
AND factura_venta.fecha <= '%s'
AND linea_de_venta.producto_venta_id
= fibra_bigbags.producto_venta_id
;
""" % (sql_fechaini, sql_fechafin)
kilos_euros_lda = """
SELECT 0.0 AS kilos,
COALESCE(SUM(linea_de_abono.cantidad
* linea_de_abono.diferencia),
0.0) AS euros
FROM linea_de_abono, factura_de_abono, abono, linea_de_venta,
fibra_bigbags
WHERE linea_de_abono.abono_id = abono.id
AND linea_de_abono.linea_de_venta_id = linea_de_venta.id
AND linea_de_venta.producto_venta_id
= fibra_bigbags.producto_venta_id
AND factura_de_abono.fecha >= '%s'
AND factura_de_abono.fecha <= '%s'
AND factura_de_abono.id = abono.factura_de_abono_id
;
""" % (sql_fechaini, sql_fechafin)
frabonos = """
SELECT linea_de_devolucion.id, linea_de_devolucion.articulo_id,
linea_de_devolucion.precio
INTO TEMP facturas_de_abono_temp
FROM linea_de_devolucion, factura_de_abono, abono, articulo,
fibra_bigbags
WHERE linea_de_devolucion.abono_id = abono.id
AND factura_de_abono.id = abono.factura_de_abono_id
AND factura_de_abono.fecha >= '%s'
AND factura_de_abono.fecha <= '%s'
AND linea_de_devolucion.albaran_de_entrada_de_abono_id IS NOT NULL
AND articulo.id = linea_de_devolucion.articulo_id
AND articulo.producto_venta_id = fibra_bigbags.producto_venta_id;
""" % (sql_fechaini, sql_fechafin)
kilos_euros_ldd = """
SELECT COALESCE(-1 * SUM(bigbag.pesobigbag), 0.0) AS kilos,
COALESCE(-1 * SUM(precio), 0.0) AS euros
FROM bigbag, facturas_de_abono_temp, articulo
WHERE bigbag.id = articulo.bigbag_id
AND facturas_de_abono_temp.articulo_id = articulo.id
;
"""
caidita_de_roma = """
DROP TABLE fibra_bigbags;
DROP TABLE facturas_de_abono_temp;
"""
con = pclases.Bala._connection # En realidad la clase da igual.
con.query(prods)
con.query(frabonos)
ke_ldv = con.queryAll(kilos_euros_ldv)
ke_lda = con.queryAll(kilos_euros_lda)
ke_ldd = con.queryAll(kilos_euros_ldd)
res = {'kilos': 0.0, 'euros': 0.0}
for fila in ke_ldv + ke_lda + ke_ldd:
kilos, euros = fila
try:
res['kilos'] += kilos
except TypeError: # kilos viene como un Decimal. Paso a float.
res['kilos'] += float(kilos)
try:
res['euros'] += euros
except TypeError: # Viene como un Decimal. Paso a float.
res['euros'] += float(euros)
con.query(caidita_de_roma)
return res
def buscar_ventas_por_color(anno, vpro = None, rango = None, meses = []):
"""
Busca las ventas de fibra por color y país del cliente en
lugar de por tarifa.
Devuelve un diccionario de colores donde cada valor es
otro diccionario de meses con las claves "nacional" y "internacional"
y como valores otro diccionario con "euros" y "kilos" (incluye
fibra B y excluye bigbags).
"""
fibra = {}
for i in xrange(12):
if i+1 not in meses:
kilos_euros_balas_mes = {}
else:
fechaini = mx.DateTime.DateTimeFrom(day = 1,
month = i + 1,
year = anno)
fechafin = mx.DateTime.DateTimeFrom(day = -1,
month = i+1,
year = anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
kilos_euros_balas_mes = ejecutar_consultas_ventas_fibra_por_color(
fechaini, fechafin)
fibra[i] = kilos_euros_balas_mes
meses = range(12)
colores = []
tarifas = []
for mes in fibra:
for color in fibra[mes]:
if color not in colores:
colores.append(color)
for tarifa in fibra[mes][color]:
if tarifa not in tarifas:
tarifas.append(tarifa)
_fibra = {}
for color in colores:
if color not in _fibra:
_fibra[color] = {}
for tarifa in tarifas:
if tarifa not in _fibra[color]:
_fibra[color][tarifa] = {}
for mes in meses:
if mes not in _fibra[color][tarifa]:
_fibra[color][tarifa][mes] = {}
try:
_fibra[color][tarifa][mes] = fibra[mes][color][tarifa]
except KeyError:
_fibra[color][tarifa][mes] = {'kilos': 0.0, 'euros': 0.0}
return _fibra
def buscar_ventas_bigbags(anno, vpro = None, rango = None, meses = []):
"""
Devuelve un diccionario de meses cuyos valores son otro
diccionario con los euros y los kilos de bigbags vendidos
en el año recibido.
"""
fibra = {}
for i in xrange(12):
if i+1 not in meses:
kilos_euros_bigbags_mes = {'kilos': 0, 'euros': 0}
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i + 1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i + 1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
kilos_euros_bigbags_mes=ejecutar_consultas_ventas_bigbags(fechaini,
fechafin)
fibra[i] = kilos_euros_bigbags_mes
return fibra
def buscar_ventas_fibra_b(anno, vpro = None, rango = None, meses = []):
"""
Devuelve las ventas (en euros y kilos) de la fibra marcada
como baja calidad.
"""
ventasb = {}
for i in xrange(12):
if i+1 not in meses:
kilos = euros = 0
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión
# de mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
kilos, euros = ejecutar_consultas_fibra_b_por_fechas(fechaini,
fechafin)
ventasb[i] = {'kilos': kilos, 'euros': euros}
return ventasb
def buscar_ventas_cable(anno, vpro = None, rango = None):
"""
Devuelve las salidas de albarán en kilos de la fibra reciclada.
"""
cable = {}
for i in range(12):
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de mx
# de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
BC = pclases.BalaCable
A = pclases.Articulo
AS = pclases.AlbaranSalida
balasc = BC.select(pclases.AND(A.q.balaCableID == BC.q.id,
A.q.albaranSalidaID == AS.q.id,
AS.q.fecha >= fechaini,
AS.q.fecha <= fechafin))
if balasc.count() > 0:
kilos = balasc.sum("peso")
else:
kilos = 0.0
cable[i] = {'kilos': kilos} # No devuelvo euros como con el resto de
# la fibra porque salen a precio 0.
# Nos cobran por reciclarla. Se paga en
# albaranes entrada y facturas compra.
return cable
def buscar_ventas_internas_fibra(anno, vpro = None, rango = None, meses = []):
"""
Devuelve en kilos y euros la fibra consumida en la línea
de producción de geotextiles.
Se usa el precio por defecto para valorar los kilos.
"""
consumo_fibra = {}
for i in xrange(12):
if i+1 not in meses:
kilos_consumidos = euros_consumidos = 0
else:
fechaini = mx.DateTime.DateTimeFrom(day = 1,
month = i + 1,
year = anno)
fechafin = mx.DateTime.DateTimeFrom(day = -1,
month = i+1,
year = anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
kilos_consumidos, euros_consumidos \
= consultar_kilos_y_euros_fibra_consumidos_segun_pcs(
fechaini, fechafin)
consumo_fibra[i] = {'kilos': kilos_consumidos,
'euros': euros_consumidos}
return consumo_fibra
def consultar_kilos_y_euros_fibra_consumidos_segun_pcs(fechaini, fechafin):
"""
Devuelve las "ventas" internas (consumo de fibra en línea de geotextiles)
según las fechas de las partidas de carga. Es decir, es más fiel a las
existencias, pero cuenta partidas que no han producido geotextiles o que
ha servido para fabricar geotextiles fuera del rango de fechas. También
hay que confiar en que las fechas de las partidas de carga son correctas.
En cualquier caso es coherente (sean o no sean precisas las fechas de las
partidas de carga) con las existencias en listado_balas, caché, etc.
OJO: La valoración en euros es estimativa y, aunque determinista, varía
con el tiempo en función del precioDefecto que tenga cada producto en el
momento en que se ejecuta la consulta. Mucho ojito con eso.
"""
pvfs = [pv for pv in pclases.ProductoVenta.select() if pv.es_bala()]
kilos = 0.0
euros = 0.0
for pv in pvfs:
kilos_pv = pv.buscar_consumos_cantidad(fechaini, fechafin)
# Es la misma función que se usa en HistoralExistencias.test(),
# así que debe cuadar existencias fechainicio - 1 día + ventas
# + consumos - produccion == existencias fechafin.
# Por definición, vaya.
euros += kilos_pv * pv.precioDefecto
kilos += kilos_pv
return kilos, euros
def consultar_kilos_y_euros_fibra_consumidos(fechaini, fechafin):
"""
Recibe 2 mx.DateTime con las fechas inicial y final de la
consulta de metros y kilos.
Devuelve los kilos y euros a precio defecto de fibra consumidos
según el criterio de que una partida de carga no se considera
consumida por completo si todas sus partidas no se han fabricado
antes de fechafin.
OJO: Ataca directamente a la BD con SQL. No es portable (aunque
a estas alturas cualquiera se atreve a cambiar de SGBD).
(Ver metros_y_kilos_gtx.sql)
"""
con = pclases.Rollo._connection
# Consultas a pelo
partes_gtx = """
SELECT id
INTO TEMP partes_gtx_temp
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha < '%s' -- Parámetro fecha fin
AND observaciones NOT LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
rollos_fab = """
SELECT rollo_id, rollo_defectuoso_id
INTO TEMP articulos_rollo_fabricados_temp
FROM articulo
WHERE parte_de_produccion_id IN (SELECT id FROM partes_gtx_temp);
"""
partidas_rollos_def = """
SELECT partida_id
INTO TEMP partidas_rollos_defectuosos_temp
FROM rollo_defectuoso rd
WHERE rd.id IN (SELECT rollo_defectuoso_id
FROM articulos_rollo_fabricados_temp)
GROUP BY partida_id;
"""
partidas_rollos = """
SELECT partida_id
INTO TEMP partidas_rollos_temp
FROM rollo r
WHERE r.id IN (SELECT rollo_id FROM articulos_rollo_fabricados_temp)
GROUP BY partida_id;
"""
func_partes_de_partida = """
CREATE OR REPLACE FUNCTION partes_de_partida (INTEGER) RETURNS BIGINT
AS '
SELECT COUNT(id)
FROM parte_de_produccion
WHERE id IN (SELECT parte_de_produccion_id
FROM articulo
WHERE rollo_id IS NOT NULL
AND rollo_id IN (SELECT id
FROM rollo
WHERE partida_id = $1)
OR rollo_defectuoso_id IS NOT NULL
AND rollo_defectuoso_id IN (SELECT id
FROM rollo_defectuoso
WHERE partida_id = $1)
GROUP BY parte_de_produccion_id)
;
' LANGUAGE 'sql';
"""
func_partes_antes_de = """
CREATE OR REPLACE FUNCTION
partes_de_partida_antes_de_fecha (INTEGER, DATE) RETURNS BIGINT
AS '
SELECT COUNT(id)
FROM parte_de_produccion
WHERE fecha < $2
AND id IN (SELECT parte_de_produccion_id
FROM articulo
WHERE rollo_id IS NOT NULL
AND rollo_id IN (SELECT id
FROM rollo
WHERE partida_id = $1)
OR rollo_defectuoso_id IS NOT NULL
AND rollo_defectuoso_id IN (SELECT id
FROM rollo_defectuoso
WHERE partida_id = $1)
GROUP BY parte_de_produccion_id)
;
' LANGUAGE 'sql';
"""
func_partida_entra = """
CREATE OR REPLACE FUNCTION
partida_entra_en_fecha(INTEGER, DATE) RETURNS BOOLEAN
-- Recibe un ID de partida de geotextiles y una fecha.
-- Devuelve TRUE si ningún parte de producción de la partida
-- tiene fecha posterior a la recibida Y la partida existe y
-- tiene producción.
AS '
SELECT partes_de_partida($1) > 0
AND partes_de_partida($1)
= partes_de_partida_antes_de_fecha($1, $2);
' LANGUAGE 'sql';
"""
func_pc_entra = """
CREATE OR REPLACE FUNCTION
partida_carga_entra_en_fecha(INTEGER, DATE) RETURNS BOOLEAN
-- Recibe el ID de una partida de carga y devuelve TRUE si todas
-- las partidas de geotextiles de la misma pertenecen a partes de
-- producción de fecha anterior o igual al segundo parámetro.
AS'
SELECT COUNT(*) > 0
FROM partida
WHERE partida_carga_id = $1
AND partida_entra_en_fecha(partida.id, $2);
' LANGUAGE 'sql';
"""
partidas_carga_id = """
SELECT partida_carga_id
INTO TEMP partidas_carga_id_temp
FROM partida
WHERE (id IN (SELECT partida_id FROM partidas_rollos_defectuosos_temp)
OR id IN (SELECT partida_id FROM partidas_rollos_temp))
GROUP BY partida_carga_id;
"""
partidas_de_pc_en_fecha = """
SELECT partida_carga_id
INTO TEMP partidas_de_carga_de_partidas_en_fecha_temp
FROM partidas_carga_id_temp
WHERE partida_carga_entra_en_fecha(partida_carga_id, '%s');
-- Parámetro fecha fin
""" % (fechafin.strftime("%Y-%m-%d"))
balas_y_peso = """
SELECT bala.id AS id_bala_id,
AVG(pesobala) AS _pesobala,
articulo.producto_venta_id,
AVG(producto_venta.preciopordefecto) AS precio
INTO TEMP balas_con_peso_de_partida_de_carga
FROM bala, articulo, producto_venta
WHERE partida_carga_id IN (
SELECT partida_carga_id
FROM partidas_de_carga_de_partidas_en_fecha_temp)
AND bala.id = articulo.bala_id
AND articulo.producto_venta_id = producto_venta.id
GROUP BY bala.id, producto_venta_id;
-- OJO: Las balas llevan en torno a kilo o kilo y medio de plástico de
-- embalar que se cuenta como fibra consumida.
"""
total_balas_y_peso = """
SELECT COUNT(id_bala_id) AS balas, SUM(_pesobala) AS peso_ce,
SUM(_pesobala * precio) AS euros
FROM balas_con_peso_de_partida_de_carga;
"""
con.query(partes_gtx)
con.query(rollos_fab)
con.query(partidas_rollos_def)
con.query(partidas_rollos)
con.query(func_partes_de_partida)
con.query(func_partes_antes_de)
con.query(func_partida_entra)
con.query(func_pc_entra)
con.query(partidas_carga_id)
con.query(partidas_de_pc_en_fecha)
con.query(balas_y_peso)
balas_kilos = con.queryAll(total_balas_y_peso)
caidita_de_roma = """
DROP FUNCTION partes_de_partida(INTEGER);
DROP FUNCTION partes_de_partida_antes_de_fecha(INTEGER, DATE);
DROP FUNCTION partida_entra_en_fecha(INTEGER, DATE);
DROP FUNCTION partida_carga_entra_en_fecha(INTEGER, DATE);
DROP TABLE partidas_carga_id_temp;
DROP TABLE balas_con_peso_de_partida_de_carga;
DROP TABLE partidas_de_carga_de_partidas_en_fecha_temp;
DROP TABLE partidas_rollos_defectuosos_temp;
DROP TABLE partidas_rollos_temp;
DROP TABLE articulos_rollo_fabricados_temp;
DROP TABLE partes_gtx_temp;
"""
con.query(caidita_de_roma)
balas, kilos, euros = balas_kilos[0] # @UnusedVariable
return kilos and kilos or 0.0, euros and euros or 0.0
def ejecutar_consultas_fibra_b_por_fechas(fechaini, fechafin):
albaranes_facturados = """
SELECT albaran_salida.id AS albaran_salida_id,
linea_de_venta.precio*(1-linea_de_venta.descuento) AS precio,
linea_de_venta.producto_venta_id,
linea_de_venta.id AS linea_de_venta_id
INTO albaranes_facturados_en_fecha_temp
FROM albaran_salida, linea_de_venta
WHERE albaran_salida.id = linea_de_venta.albaran_salida_id
AND linea_de_venta.producto_venta_id IS NOT NULL
AND linea_de_venta.factura_venta_id
IN (SELECT factura_venta.id
FROM factura_venta
WHERE factura_venta.fecha >= '%s'
AND factura_venta.fecha <= '%s')
;
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
con = pclases.Bala._connection # En realidad la clase da igual.
con.query(albaranes_facturados)
balas_facturadas_y_producto = """
SELECT bala.pesobala,
articulo.producto_venta_id,
articulo.albaran_salida_id
FROM bala, articulo
WHERE bala.claseb = TRUE
AND articulo.bala_id = bala.id
AND articulo.albaran_salida_id IN (
SELECT albaran_salida_id
FROM albaranes_facturados_en_fecha_temp)
;
"""
filas_balas_facturadas_y_producto=con.queryAll(balas_facturadas_y_producto)
bigbags_facturados_y_producto = """
SELECT bigbag.pesobigbag,
articulo.producto_venta_id,
articulo.albaran_salida_id
FROM bigbag, articulo
WHERE bigbag.claseb = TRUE
AND articulo.bigbag_id = bigbag.id
AND articulo.albaran_salida_id IN (
SELECT albaran_salida_id
FROM albaranes_facturados_en_fecha_temp)
;
"""
filas_bigbags_facturados_y_producto = con.queryAll(
bigbags_facturados_y_producto)
filas_precios_facturados_por_producto_y_albaran = con.queryAll(
""" SELECT * FROM albaranes_facturados_en_fecha_temp; """)
# Organizo los precios por albarán y producto:
albaranes = {}
for fila in filas_precios_facturados_por_producto_y_albaran:
albaran_salida_id, precio, producto_venta_id, linea_de_venta_id = fila
if albaran_salida_id not in albaranes:
albaranes[albaran_salida_id] = {}
if producto_venta_id not in albaranes[albaran_salida_id]:
albaranes[albaran_salida_id][producto_venta_id] = {}
if (linea_de_venta_id
not in albaranes[albaran_salida_id][producto_venta_id]):
albaranes[albaran_salida_id][producto_venta_id][linea_de_venta_id]\
= precio
else:
print "consulta_global::ejecutar_consultas_fibra_b_por_fechas ->"\
" ¡ERROR! línea de venta (%d) duplicada en mismo albarán "\
"salida y producto de venta." % (linea_de_venta_id)
euros = 0.0
for fila in (filas_balas_facturadas_y_producto
+ filas_bigbags_facturados_y_producto):
peso, producto_venta_id, albaran_salida_id = fila
# Si en el albarán y producto solo hay una LDV, el precio no tiene
# confusión:
if len(albaranes[albaran_salida_id][producto_venta_id]) == 1:
idldv = albaranes[albaran_salida_id][producto_venta_id].keys()[0]
precio = albaranes[albaran_salida_id][producto_venta_id][idldv]
else:
# El precio es media ponderada:
ldvs = albaranes[albaran_salida_id][producto_venta_id]
cantidad_total = 0.0
precio_total = 0.0
for idldv in ldvs:
ldv = pclases.LineaDeVenta.get(idldv)
cantidad = ldv.cantidad # @UnusedVariable
cantidad_total += ldv.cantidad
precio_total += ldv.precio
precio = precio_total / cantidad_total
euros += peso * precio
### vvv Kilos vvv ### ^^^ euros ^^^ ###
kilos_balas_b_facturados = """
SELECT COALESCE(SUM(bala.pesobala), 0) AS kilos_b_b
FROM articulo, bala
WHERE articulo.albaran_salida_id IN (
SELECT albaran_salida_id
FROM albaranes_facturados_en_fecha_temp)
AND articulo.bala_id = bala.id
AND bala.claseb = TRUE;
"""
kilos = con.queryAll(kilos_balas_b_facturados)[0][0]
kilos_bigbags_b_facturados = """
SELECT COALESCE(SUM(bigbag.pesobigbag), 0) AS kilos_bb_b
FROM articulo, bigbag
WHERE articulo.albaran_salida_id IN (
SELECT albaran_salida_id
FROM albaranes_facturados_en_fecha_temp)
AND articulo.bigbag_id = bigbag.id
AND bigbag.claseb = TRUE;
"""
kilos += con.queryAll(kilos_bigbags_b_facturados)[0][0]
caidita_de_roma = """
DROP TABLE albaranes_facturados_en_fecha_temp;
"""
con.query(caidita_de_roma)
# DONE: ¡¡¡Aún faltaría descontar los abonos!!!
# No hay abonos en consumos internos, ceporro.
return kilos, euros
def buscar_ventas_fibra_color(anno, vpro = None, rango = None, meses = []):
"""
Busca las ventas de fibra por color, consumidas por la línea,
fibra B y bigbags. Devuelve una lista de listas. Cada lista
tiene en la primera posición un texto descriptivo, las siguientes
posiciones corresponden a las ventas en kilos o euros (dependiendo
del texto que la encabece) por cada mes y en orden. La última
posición se deja vacía ya que no se mostrará en el TreeView.
«meses» es una lista o una tupla con los meses del año sobre los
que consultar datos (comenzando en 1).
"""
# Ejecuto consulta:
if vpro != None:
incr_progreso = rango / 7.0
texto_vpro = vpro.get_texto()
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (internas)")
vi = buscar_ventas_internas_fibra(anno, vpro, rango, meses)
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (bigbags)")
vbb = buscar_ventas_bigbags(anno, vpro, rango, meses)
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (por color)")
vpc = buscar_ventas_por_color(anno, vpro, rango, meses)
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (fibra B)")
fb = buscar_ventas_fibra_b(anno, vpro, rango, meses)
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (agrupando)")
# Organizo datos:
filas = []
## Total
filas.append(["Total kilos"] + [0.0] * 12)
filas.append(["Total euros"] + [0.0] * 12)
## Geotexan
filas.append(["Kilos Geotexan"])
filas.append(["Euros Geotexan"])
for mes in vi:
filas[-2].append(vi[mes]['kilos'])
filas[-1].append(vi[mes]['euros'])
filas[0][mes+1] += vi[mes]['kilos']
filas[1][mes+1] += vi[mes]['euros']
## Geocem
filas.append(["Kilos Geocem"])
filas.append(["Euros Geocem"])
for mes in vbb:
filas[-2].append(vbb[mes]['kilos'])
filas[-1].append(vbb[mes]['euros'])
filas[0][mes+1] += vbb[mes]['kilos']
filas[1][mes+1] += vbb[mes]['euros']
## Colores
for color in vpc:
for extnac in vpc[color]:
filas.append(["Kilos %s %s (A+B)" % (color, extnac)])
filas.append(["Euros %s %s (A+B)" % (color, extnac)])
for mes in vpc[color][extnac]:
filas[-2].append(vpc[color][extnac][mes]['kilos'])
filas[-1].append(vpc[color][extnac][mes]['euros'])
filas[0][mes+1] += vpc[color][extnac][mes]['kilos']
filas[1][mes+1] += vpc[color][extnac][mes]['euros']
## B
filas.append(["Desglose: kilos fibra B"])
filas.append(["Desglose: euros fibra B"])
for mes in fb:
filas[-2].append(fb[mes]['kilos'])
filas[-1].append(fb[mes]['euros'])
# filas[0][mes+1] += fb[mes]['kilos'] # La fibra B no hay que
# sumarla otra vez. En el desglose por colores ya
# filas[1][mes+1] += fb[mes]['euros'] # se incluye fibra B.
## CABLE DE FIBRA
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (reciclada)")
filas.append(["Fibra reciclada (no computa en el total de ventas)"])
cable = buscar_ventas_cable(anno, vpro, rango)
for mes in cable:
filas[-1].append(cable[mes]['kilos'])
# Salen a siempre a 0 € porque son para reciclar y las pagamos al
# recibirlas de nuevo como granza.
## TOTALES
for fila in filas:
total_fila = sum(fila[1:])
fila += [total_fila, "Me estoy quedando sin fuerzas, solo espero ya "
"la muerte. Me falta sangre en las venas. "
"Mi corazón se retuerce."]
for i in xrange(1, len(fila) - 1):
fila[i] = utils.float2str(fila[i])
return filas
def buscar_ventas(anno, vpro = None, rango = None, meses = []):
"""
"anno" es el año del que buscará las ventas.
"""
gtx = dict([(i, 0) for i in xrange(12)])
fibra = dict([(i, 0) for i in xrange(12)])
bolsas = dict([(i, 0) for i in xrange(12)])
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
for i in xrange(12):
if i+1 not in meses:
ventas_gtx = {'total': {'metros': 0.0, 'kilos': 0.0, 'euros': 0.0}}
ventas_fibra = {'total': {'kilos': 0.0, 'euros': 0.0}}
ventas_bolsas={'total': {'kilos': 0.0, 'bolsas': 0, 'euros': 0.0}}
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
(ventas_gtx,
ventas_fibra,
ventas_bolsas) = _buscar_ventas(fechaini, fechafin)
gtx[i] = ventas_gtx
fibra[i] = ventas_fibra
bolsas[i] = ventas_bolsas
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (%d/12)" % (i+1))
_gtx = {} # En lugar de [mes][tarifa] voy a hacer un diccionario
# [tarifa][mes]
primeroanno = mx.DateTime.DateTimeFrom(day = 1, month = 1,
year = mx.DateTime.localtime().year)
#########################################
class FakeTarifa: #
def __init__(self, nombre): #
self.nombre = nombre #
#########################################
fake_tarifa = FakeTarifa("Tarifas anteriores a %s" % (
utils.str_fecha(primeroanno)))
for mes in gtx:
for tarifa in gtx[mes]:
# Filtro por fechaValidezFin de tarifas y agrupar todas las
# "caducadas" a principios de año en una sola línea.
if (tarifa != None and tarifa != "total"
and tarifa.periodoValidezFin != None
and tarifa.periodoValidezFin < primeroanno):
_tarifa = fake_tarifa
else:
_tarifa = tarifa
if _tarifa not in _gtx:
_gtx[_tarifa] = {mes: gtx[mes][tarifa]}
else:
if mes not in _gtx[_tarifa]:
_gtx[_tarifa][mes] = {}
for metros_kilos_euros in gtx[mes][tarifa]:
algo = gtx[mes][tarifa][metros_kilos_euros]
try:
_gtx[_tarifa][mes][metros_kilos_euros] += algo
except KeyError:
_gtx[_tarifa][mes][metros_kilos_euros] = algo
_fibra = {}
for mes in fibra:
for tarifa in fibra[mes]:
if tarifa not in _fibra:
_fibra[tarifa] = {mes: fibra[mes][tarifa]}
else:
_fibra[tarifa][mes] = fibra[mes][tarifa]
_bolsas = {}
for mes in bolsas:
for tarifa in bolsas[mes]:
if tarifa not in _bolsas:
_bolsas[tarifa] = {mes: bolsas[mes][tarifa]}
else:
_bolsas[tarifa][mes] = bolsas[mes][tarifa]
return _gtx, _fibra, _bolsas
def buscar_compras_geocompuestos(anno, vpro = None, rango = None,
logger = None, meses = []):
"""
Devuelve un diccionario por proveedor y mes de las compras de producto de
tipo geocompuestos, en euros y en metros cuadrados (o la unidad que tenga
la mayoría de productos de tipo geocompuesto).
"""
gcomp = dict([(i, 0) for i in xrange(12)])
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
for i in xrange(12):
if i+1 not in meses:
gcompmes = {'total': {'cantidad': 0.0, 'euros': 0.0}}
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
gcompmes = _buscar_compras_geocompuestos(fechaini, fechafin)
gcomp[i] = gcompmes
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (%d/12)" % (i+1))
_gcomp = {} # En lugar de [mes][proveedor] voy a hacer un diccionario
# [proveedor][mes]
for mes in gcomp:
for proveedor in gcomp[mes]:
if proveedor not in _gcomp:
_gcomp[proveedor] = {mes: gcomp[mes][proveedor]}
else:
_gcomp[proveedor][mes] = gcomp[mes][proveedor]
return _gcomp
def buscar_ventas_geocompuestos(anno, vpro = None, rango = None,
logger = None, meses = []):
"""
Devuelve un diccionario por tarifa y mes de las ventas de producto de
tipo geocompuestos, en euros y en metros cuadrados.
"""
gcomp = dict([(i, 0) for i in xrange(12)])
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
for i in xrange(12):
if i+1 not in meses:
gcompmes = {'total': {'cantidad': 0.0, 'euros': 0.0}}
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día
# al operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
gcompmes = _buscar_ventas_geocompuestos(fechaini, fechafin)
gcomp[i] = gcompmes
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (%d/12)" % (i+1))
_gcomp = {} # En lugar de [mes][tarifa] voy a hacer un diccionario
# [tarifa][mes]
for mes in gcomp:
for tarifa in gcomp[mes]:
if tarifa not in _gcomp:
_gcomp[tarifa] = {mes: gcomp[mes][tarifa]}
else:
_gcomp[tarifa][mes] = gcomp[mes][tarifa]
return _gcomp
################## C O N S U M O S ############################################
def consultar_consumos(mes, anno, consumos_gtx, consumos_fibra,
consumos_bolsas):
ini = mx.DateTime.DateTimeFrom(day=1, month=mes + 1, year=anno)
try:
fin = mx.DateTime.DateTimeFrom(day=1,
month=ini.month + 1,
year=anno)
except mx.DateTime.RangeError:
fin = mx.DateTime.DateTimeFrom(day=1, month=1, year=anno+1)
gtx = {} # @UnusedVariable
fibra = {} # @UnusedVariable
bolsas = {} # @UnusedVariable
pdps = pclases.ParteDeProduccion.select(pclases.AND(
pclases.ParteDeProduccion.q.fecha >= ini,
pclases.ParteDeProduccion.q.fecha < fin))
for pdp in pdps:
if pdp.es_de_balas():
consumos = consumos_fibra
elif pdp.es_de_geotextiles():
consumos = consumos_gtx
elif pdp.es_de_bolsas():
consumos = consumos_bolsas
else:
pass # Es un parte vacío
for consumo in pdp.consumos:
p = consumo.productoCompra
if p not in consumos:
consumos[p] = {}
if mes not in consumos[p]:
consumos[p][mes] = 0.0
consumos[p][mes] += consumo.cantidad
def buscar_consumos(anno, vpro = None, rango = None, meses = []):
"""
"anno" es el año del que buscará los consumos.
"""
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
consumos_gtx = {}
consumos_fibra = {}
consumos_bolsas = {}
for i in xrange(12):
if i+1 in meses:
consultar_consumos(i, anno, consumos_gtx, consumos_fibra,
consumos_bolsas)
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (%d/12)" % (i+1))
return consumos_gtx, consumos_fibra, consumos_bolsas
################### P R O D U C C I Ó N F I B R A ###########################
def consultar_horas_reales_fibra(fechaini, fechafin):
"""
Devuelve la suma de las duraciones de los partes entre las dos
fechas recibidas.
"""
sql = """
SELECT SUM(fechahorafin - fechahorainicio)
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha <= '%s' -- Parámetro fecha fin
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
try:
horas_sql = pclases.ParteDeProduccion._queryAll(sql)[0][0]
try:
horas = horas_sql.hours
except AttributeError: # Es un datetime.timedelta
horas = (horas_sql.days * 24.0) + (horas_sql.seconds / 3600.0)
except (IndexError, AttributeError):
horas = 0.0
return horas
def consultar_horas_trabajo_fibra(fechaini, fechafin, logger):
"""
Devuelve la suma de las duraciones de los partes entre las dos
fechas recibidas menos las horas de parada.
"""
partes = pclases.ParteDeProduccion.select("""
fecha >= '%s'
AND fecha <= '%s'
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL
AND observaciones NOT ILIKE '%%reenvas%%'
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d")))
# Ignoro los partes de reenvasado puesto que la máquina no ha estado
# produciendo ese tiempo.
try:
horas_trabajadas = sum([pdp.get_horas_trabajadas() for pdp in partes])
except AssertionError, msg:
txt = "consulta_global::consultar_horas_trabajo_fibra -> "\
"Error calculando horas de trabajo de línea de fibra: %s. "\
"Ignoro todos los partes implicados en el mismo rango de "\
"fechas del que provoca el error." % (msg)
print txt
if logger != None:
logger.error(txt)
horas_trabajadas = mx.DateTime.DateTimeDelta(0)
try:
horas_trabajadas = horas_trabajadas.hours
except AttributeError:
try: # Es un datetime.timedelta
horas_trabajadas = ((horas_trabajadas.days * 24.0)
+ (horas_trabajadas.seconds / 3600.0))
except AttributeError:
horas_trabajadas = 0.0
return horas_trabajadas
def consultar_dias_fibra(fechaini, fechafin):
"""
Devuelve el número de días (fechas distintas) en los que hay
al menos un parte de producción de geotextiles entre las fechas
recibidas.
"""
sql = """
SELECT COUNT(DISTINCT fecha)
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha <= '%s' -- Parámetro fecha fin
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
try:
dias = pclases.ParteDeProduccion._queryAll(sql)[0][0]
except IndexError:
dias = 0
return dias
def consultar_dias_bolsas(fechaini, fechafin):
"""
Devuelve el número de días (fechas distintas) en los que hay
al menos un parte de producción de geotextiles entre las fechas
recibidas.
"""
sql = """
SELECT COUNT(DISTINCT fecha)
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha <= '%s' -- Parámetro fecha fin
AND partida_cem_id IS NOT NULL);
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
try:
dias = pclases.ParteDeProduccion._queryAll(sql)[0][0]
except IndexError:
dias = 0
return dias
def consultar_fibra_producida(fechaini, fechafin):
"""
Ataca a la BD mediante consultas SQL y devuelve los kilos y
bultos de fibra fabricados, separados entre bigbags (fibra cemento)
y balas; y dentro de éstas, por color.
"""
partes = """
SELECT id
INTO TEMP partes_fib_temp
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha <= '%s' -- Parámetro fecha fin
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL
AND observaciones NOT ILIKE '%%reenvas%%');
-- GTX. Hay que escapar los porcientos
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
pvs = """
SELECT pv.id AS producto_venta_id, color
INTO TEMP producto_venta_con_campos_especificos_temp
FROM campos_especificos_bala ceb, producto_venta pv
WHERE (pv.campos_especificos_bala_id = ceb.id);
"""
ids_balas = """
SELECT bala_id AS id, color
INTO TEMP ids_balas_fabricadas_temp
FROM articulo, producto_venta_con_campos_especificos_temp AS pv
WHERE parte_de_produccion_id IN (SELECT id FROM partes_fib_temp)
AND articulo.producto_venta_id = pv.producto_venta_id;
"""
ids_bigbags = """
SELECT bigbag_id AS id
INTO TEMP ids_bigbags_fabricados_temp
FROM articulo
WHERE parte_de_produccion_id IN (SELECT id FROM partes_fib_temp);
"""
balas = """
SELECT bala.id, pesobala AS peso_ce, color
INTO TEMP balas_fabricadas_temp
FROM bala, ids_balas_fabricadas_temp
WHERE bala.id IN (SELECT id FROM ids_balas_fabricadas_temp)
AND bala.id = ids_balas_fabricadas_temp.id;
"""
bigbags = """
SELECT id, pesobigbag AS peso_ce
INTO TEMP bigbags_fabricados_temp
FROM bigbag
WHERE id IN (SELECT id FROM ids_bigbags_fabricados_temp);
"""
bultos_kilos_bbs = """
SELECT COUNT(id), SUM(peso_ce) AS kilos_bb
FROM bigbags_fabricados_temp;
"""
bultos_kilos_color_bs = """
SELECT COUNT(id), SUM(peso_ce) AS kilos_b, color
FROM balas_fabricadas_temp
GROUP BY color;
"""
caidita_de_roma = """
DROP TABLE balas_fabricadas_temp;
DROP TABLE bigbags_fabricados_temp;
DROP TABLE ids_balas_fabricadas_temp;
DROP TABLE ids_bigbags_fabricados_temp;
DROP TABLE producto_venta_con_campos_especificos_temp;
DROP TABLE partes_fib_temp;
"""
con = pclases.Bala._connection # En realidad la clase da igual.
for consulta in (partes, pvs, ids_balas, ids_bigbags, balas, bigbags):
con.query(consulta)
balas_kilos_color = con.queryAll(bultos_kilos_color_bs)
bigbags_kilos = con.queryAll(bultos_kilos_bbs)
con.query(caidita_de_roma)
balas = {}
for fila in balas_kilos_color:
bultos_balas, kilos_ce, color = fila
balas[color] = {'bultos': bultos_balas and bultos_balas or 0.0,
'kilos': kilos_ce and kilos_ce or 0.0}
bultos_bigbags, kilos_ce = bigbags_kilos[0]
bigbags = {'bultos': bultos_bigbags and bultos_bigbags or 0.0,
'kilos': kilos_ce and kilos_ce or 0.0}
# Clase B
bultos_bs_b, kilos_bs_b, bultos_bbs_b, kilos_bbs_b = consultar_fibra_b(
fechaini, fechafin)
balas['_FIBRACLASE_B_'] = {'bultos': bultos_bs_b and bultos_bs_b or 0.0,
'kilos': kilos_bs_b and kilos_bs_b or 0.0}
bigbags['_FIBRACLASE_B_'] = {'bultos': bultos_bbs_b and bultos_bbs_b
or 0.0,
'kilos': kilos_bbs_b and kilos_bbs_b or 0.0}
return balas, bigbags
def consultar_fibra_b(fechaini, fechafin):
"""
Devuelve la fibra de clase B separada en balas y bigbags,
kilos y bultos.
"""
partes = """
SELECT id
INTO TEMP partes_fib_temp
FROM parte_de_produccion
WHERE (fecha >= '%s' -- Parámetro fecha ini
AND fecha <= '%s' -- Parámetro fecha fin
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL
AND observaciones NOT ILIKE '%%reenvas%%');
-- GTX. Hay que escapar los porcientos
""" % (fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
ids_balas = """
SELECT bala_id AS id
INTO TEMP ids_balas_fabricadas_temp
FROM articulo
WHERE parte_de_produccion_id IN (SELECT id FROM partes_fib_temp);
"""
ids_bigbags = """
SELECT bigbag_id AS id
INTO TEMP ids_bigbags_fabricados_temp
FROM articulo
WHERE parte_de_produccion_id IN (SELECT id FROM partes_fib_temp);
"""
balas = """
SELECT bala.id, pesobala AS peso_ce
INTO TEMP balas_fabricadas_temp
FROM bala
WHERE id IN (SELECT id FROM ids_balas_fabricadas_temp)
AND bala.claseb;
"""
bigbags = """
SELECT id, pesobigbag AS peso_ce
INTO TEMP bigbags_fabricados_temp
FROM bigbag
WHERE id IN (SELECT id FROM ids_bigbags_fabricados_temp)
AND bigbag.claseb;
"""
bultos_kilos_bbs = """
SELECT COUNT(id), SUM(peso_ce) AS kilos_bb
FROM bigbags_fabricados_temp;
"""
bultos_kilos_color_bs = """
SELECT COUNT(id), SUM(peso_ce) AS kilos_b
FROM balas_fabricadas_temp
"""
caidita_de_roma = """
DROP TABLE balas_fabricadas_temp;
DROP TABLE bigbags_fabricados_temp;
DROP TABLE ids_balas_fabricadas_temp;
DROP TABLE ids_bigbags_fabricados_temp;
DROP TABLE partes_fib_temp;
"""
con = pclases.Bala._connection # En realidad la clase da igual.
for consulta in (partes, ids_balas, ids_bigbags, balas, bigbags):
con.query(consulta)
balas_kilos = con.queryAll(bultos_kilos_color_bs)
bigbags_kilos = con.queryAll(bultos_kilos_bbs)
con.query(caidita_de_roma)
bultos_bs_b, kilos_bs_b = balas_kilos[0]
bultos_bbs_b, kilos_bbs_b = bigbags_kilos[0]
return bultos_bs_b, kilos_bs_b, bultos_bbs_b, kilos_bbs_b
def consultar_granza_consumida(fechaini, fechafin):
"""
Devuelve la granza consumida por los partes de producción de fibra
entre las fechas fechaini y fechafin en forma de diccionario
cuyas claves son el tipo de granza.
"""
PDP = pclases.ParteDeProduccion
parte_where = (""" fecha >= '%s'
AND fecha <= '%s'
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL
""" % (fechaini.strftime("%Y-%m-%d"),
fechafin.strftime("%Y-%m-%d")))
pdps = PDP.select(parte_where)
granza = 0.0
granza_reciclada = 0.0
# OJO: NOTA: WARNING: ATCHUNG: HARCODED: Etcétera, etcétera. La separación
# de la granza del resto de materia
# prima y a su vez la separación
# entre granza{reciclada|recuperada}
# de las demás es totalmente
# arbitraria, a ojo y harcoded. Lo
# ideal es que tuvieran un campo en
# ProductoCompra o que hubiera un
# TipoDeMaterial que las
# distinguiese, pero -como siempre-
# ni era un requisito ni hay tiempo
# ahora de verificar que el cambio
# no afecta a todo el código que
# tira de TipoDeMaterial en el resto
# de ventanas.
for pdp in pdps:
for c in pdp.consumos:
desc = c.productoCompra.descripcion.upper()
if "GRANZA" in desc:
if "RECICLADA" in desc or "RECUPERADA" in desc:
granza_reciclada += c.cantidad
else:
granza += c.cantidad
return {'total': granza + granza_reciclada,
'granza': granza,
'reciclada': granza_reciclada}
def consultar_empleados_por_dia_fibra(fechaini, fechafin):
"""
Devuelve el número de empleados por día a través de una tocho-consulta(TM)
a la base de datos.
"""
sql = """
SELECT fecha, empleadoid
FROM parte_de_produccion_empleado,
(SELECT id,fecha
FROM parte_de_produccion
WHERE fecha >= '%s'
AND fecha <= '%s'
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL) AS partes
WHERE partes.id = parte_de_produccion_empleado.partedeproduccionid
GROUP BY fecha, empleadoid ORDER BY fecha; """ % (
fechaini.strftime("%Y-%m-%d"), fechafin.strftime("%Y-%m-%d"))
filas_fecha_idempleado = pclases.ParteDeProduccion._queryAll(sql)
# Y ahora sumo (lo sé, se podría hacer directamente en la consulta, pero
# prefiero dejarla así porque creo que me hará falta en un futuro tenerlo
# desglosado).
fechas = []
empleados = 0.0
for fecha, idempleado in filas_fecha_idempleado: # @UnusedVariable
if fecha not in fechas:
fechas.append(fecha)
empleados += 1
try:
res = empleados / len(fechas)
except ZeroDivisionError:
res = 0.0
return res
def consultar_productividad_fibra(fechaini, fechafin):
"""
Devuelve la productividad de los partes de producción de
geotextiles entre las fechas recibidas.
"""
sql_where = """ fecha >= '%s'
AND fecha <= '%s'
AND observaciones LIKE '%%;%%;%%;%%;%%;%%'
AND partida_cem_id IS NULL
""" % (fechaini.strftime("%Y-%m-%d"),
fechafin.strftime("%Y-%m-%d"))
pdps = pclases.ParteDeProduccion.select(sql_where)
res = calcular_productividad_conjunta(tuple(pdps))
return res
def buscar_produccion_fibra(anno,
vpro = None,
rango = None,
logger = None,
meses = []):
"""
"anno" es el año del que buscará las producciones.
Devuelve un diccionario _por meses_ con los kilos fabricados y
granza consumida.
"""
if vpro != None:
incr_progreso = rango / 12.0
texto_vpro = vpro.get_texto()
res = dict([(i, 0) for i in xrange(12)])
for i in xrange(12):
if i+1 not in meses:
res[i] = {'total': 0,
'consumo_total': 0}
res[i]["colores"] = {}
res[i]['cemento'] = 0
res[i]['merma'] = 0
res[i]['porc_merma'] = 0
res[i]['granza'] = 0
res[i]['reciclada'] = 0
res[i]['media_bala'] = 0
res[i]['media_bigbag'] = 0
res[i]['kilos_b'] = 0
res[i]['kilos_hora'] = 0
res[i]['horas'] = 0
res[i]['horas_produccion'] = 0
res[i]['dias'] = 0
res[i]['turnos'] = 0
res[i]['empleados'] = 0
res[i]['productividad'] = 0
res[i]['balas_cable'] = {'total': 0}
else:
fechaini = mx.DateTime.DateTimeFrom(day=1, month=i+1, year=anno)
fechafin = mx.DateTime.DateTimeFrom(day=-1, month=i+1, year=anno)
# XXX: No estoy seguro de por qué, pero de repente la versión de
# mx de Sid amd64 ha empezado a devolver -1 como día al
# operar con la fecha, en lugar de convertir los valores
# negativos en días desde el final de mes, como siempre.
fechafin = utils.asegurar_fecha_positiva(fechafin)
# XXX
bs, bbs = consultar_fibra_producida(fechaini, fechafin)
consumos_materia_prima_del_mes = consultar_granza_consumida(
fechaini, fechafin)
res[i] = {'total': bbs['kilos'] + sum([
bs[color]['kilos']
for color in bs
if color != "_FIBRACLASE_B_"]),
# _FIBRACLASE_B_ es un desglose de la fibra B.
# Va también incluida en los colores, así que no hay
# que sumarla dos veces al total.
'consumo_total': consumos_materia_prima_del_mes['total']}
res[i]["colores"] = {}
for color in bs:
if color != "_FIBRACLASE_B_":
# La clave "_FIBRACLASE_B_" se reserva para la
# fibra "claseb" (espero que a nadie se le
# ocurra dar de alta el color "_FIBRACLASE_B_"
res[i]["colores"][color] = bs[color]['kilos']
res[i]['cemento'] = bbs['kilos']
res[i]['merma'] = res[i]['consumo_total'] - res[i]['total']
try:
res[i]['porc_merma'] = (1.0
- (res[i]['total'] / res[i]['consumo_total'])) * 100.0
except ZeroDivisionError:
res[i]['porc_merma'] = 0.0
res[i]['granza'] = consumos_materia_prima_del_mes['granza']
res[i]['reciclada'] = consumos_materia_prima_del_mes['reciclada']
try:
res[i]['media_bala'] = (sum([bs[color]['kilos']
for color in bs])
/ sum([bs[color]['bultos']
for color in bs]))
except ZeroDivisionError:
res[i]['media_bala'] = 0.0
try:
res[i]['media_bigbag'] = bbs['kilos'] / bbs['bultos']
except ZeroDivisionError:
res[i]['media_bigbag'] = 0.0
res[i]['kilos_b'] = (bs['_FIBRACLASE_B_']['kilos']
+ bbs['_FIBRACLASE_B_']['kilos'])
horas = consultar_horas_reales_fibra(fechaini, fechafin)
horas_trabajo = consultar_horas_trabajo_fibra(fechaini, fechafin,
logger)
try:
kilos_hora = (res[i]['total']) / horas_trabajo
except ZeroDivisionError:
kilos_hora = 0.0
res[i]['kilos_hora'] = kilos_hora
res[i]['horas'] = horas
res[i]['horas_produccion'] = horas_trabajo
dias = consultar_dias_fibra(fechaini, fechafin)
res[i]['dias'] = dias
try:
turnos = (horas / 8.0) / dias
except ZeroDivisionError:
turnos = 0.0
res[i]['turnos'] = turnos
empleados_dia = consultar_empleados_por_dia_fibra(fechaini,
fechafin)
res[i]['empleados'] = empleados_dia
res[i]['productividad'] = consultar_productividad_fibra(fechaini,
fechafin)
# Actualización 04/07/2007: Una línea más para la fibra reciclada.
# Agrupo toda en una sola línea y no la cuento para
# totales de fibra producida. A fin de cuentas, no es realmente
# fibra. Son residuos que se embalan para reciclar y no
# consumen *estrictamente* granza. (Está claro que sí consumen,
# de algún lado debe salir, pero es imposible determinar
# de qué materia prima viene cada. Son restos que se van
# acumulando a lo largo de los turnos).
res[i]['balas_cable'] = {'total':
sum([bc.peso for bc in pclases.BalaCable.select(
pclases.AND(
pclases.BalaCable.q.fechahora >= fechaini,
pclases.BalaCable.q.fechahora
< fechafin + mx.DateTime.oneDay))])}
for ceb_reciclada in pclases.CamposEspecificosBala.select(
pclases.CamposEspecificosBala.q.reciclada == True):
descripcion = ceb_reciclada.productosVenta[0].descripcion
pesos = [bc.peso
for bc in pclases.BalaCable.select(pclases.AND(
pclases.BalaCable.q.fechahora >= fechaini,
pclases.BalaCable.q.fechahora <
fechafin + mx.DateTime.oneDay,
pclases.BalaCable.q.id ==
pclases.Articulo.q.balaCableID,
pclases.Articulo.q.productoVentaID ==
ceb_reciclada.productosVenta[0].id))]
res[i]['balas_cable'][descripcion] = sum(pesos)
if vpro != None:
vpro.set_valor(vpro.get_valor() + incr_progreso,
texto_vpro + " (%d/12)" % (i+1))
return res
###############################################################################
def preparar_tv(tv, listview=True):
"""
Prepara las columnas del TreeView.
Si listview es True usa un ListStore como modelo de datos. En
otro caso usa un TreeStore.
"""
cols = (('', 'gobject.TYPE_STRING', False, True, True, None),
('Enero', 'gobject.TYPE_STRING', False, False, False, None),
('Febrero', 'gobject.TYPE_STRING', False, False, False, None),
('Marzo', 'gobject.TYPE_STRING', False, False, False, None),
('Abril', 'gobject.TYPE_STRING', False, False, False, None),
('Mayo', 'gobject.TYPE_STRING', False, False, False, None),
('Junio', 'gobject.TYPE_STRING', False, False, False, None),
('Julio', 'gobject.TYPE_STRING', False, False, False, None),
('Agosto', 'gobject.TYPE_STRING', False, False, False, None),
('Septiembre', 'gobject.TYPE_STRING', False, False, False, None),
('Octubre', 'gobject.TYPE_STRING', False, False, False, None),
('Noviembre', 'gobject.TYPE_STRING', False, False, False, None),
('Diciembre', 'gobject.TYPE_STRING', False, False, False, None),
('Anual', 'gobject.TYPE_STRING', False, False, False, None),
('Clara', 'gobject.TYPE_STRING', False, False, False, None))
if listview:
utils.preparar_listview(tv, cols)
else:
utils.preparar_treeview(tv, cols)
for col in tv.get_columns()[1:]:
for cell in col.get_cell_renderers():
cell.set_property("xalign", 1.0)
col.set_alignment(0.5)
def consultar_gtxc(fechaini, fechafin):
"""
Devuelve los kg de geotextiles C producidos entre fechaini y
fechafin.
No devuelve m² porque de los geotextiles C solo se guarda el peso.
"""
fini = fechaini
ffin = fechafin + mx.DateTime.oneDay
rollosc = pclases.RolloC.select(pclases.AND(
pclases.RolloC.q.fechahora >= fini,
pclases.RolloC.q.fechahora < ffin))
if rollosc.count() > 0:
kilos = rollosc.sum("peso")
else:
kilos = 0.0
return kilos
def update_filas_gtx(filas, dic_gtx, mes=None):
"""
Si «mes» es None, calcula los totales.
«mes» empieza en 0 (enero), que correspondería a la posición 1 de la
lista que representa a la fila.
"""
try:
pos = mes + 1
except TypeError: # Calculo totales.
pos = 13 # cab.fila + 12 meses
for nombre_var in filas:
if 0 < pos <= 12:
while len(filas[nombre_var]) <= pos:
filas[nombre_var].append(None) # Da igual. Se va a machacar
filas[nombre_var][pos] = dic_gtx[nombre_var][mes]
else:
filas[nombre_var].append(None) # Da igual. Se va a machacar
sumatorio = lambda v:sum(dic_gtx[v][mes] for mes in xrange(12))
if nombre_var == "porciento_merma":
kilos_reales_totales = sumatorio("kilos_reales")
kilos_fibra_consumidos = sumatorio("consumo_fibra")
try:
total = 1 - (kilos_reales_totales / kilos_fibra_consumidos)
except ZeroDivisionError:
total = 0.0
elif nombre_var == "gramaje_medio":
kilos_a_reales_totales = sumatorio("kilos_reales_a")
metros_a_totales = sumatorio("metros_a")
try:
total = (kilos_a_reales_totales / metros_a_totales) * 1000
except ZeroDivisionError:
total = 0.0
elif nombre_var == "kilos_hora":
kilos_a_reales_totales = sumatorio("kilos_reales_a")
kilos_b_reales_totales = sumatorio("kilos_reales_b")
horas_produccion = sumatorio("horas_produccion")
try:
total = (kilos_a_reales_totales
+ kilos_b_reales_totales) / horas_produccion
except ZeroDivisionError:
total = 0.0
elif nombre_var == "turnos":
turnos = sumatorio("turnos")
dias = sumatorio("dias")
try:
total = turnos / dias
except ZeroDivisionError:
total = 0.0
elif nombre_var == "empleados":
pdps = utils.aplanar(
[dic_gtx["pdps"][mes] for mes in xrange(12)])
if pdps:
parte_ini = min(pdps, key=lambda pdp: pdp.fechahorainicio)
parte_fin = max(pdps, key=lambda pdp: pdp.fechahorafin)
fini = parte_ini.fecha
try:
ffin = parte_fin.fecha + mx.DateTime.oneDay
except TypeError: # Es un datetime.date
ffin = parte_fin.fecha + datetime.timedelta(days = 1)
# Aunque fini y ffin no sean exactamente primero de mes,
# como vamos a buscar PDPs, no existe ninguno entre el
# día 1 y el día del parte inicial porque por definición
# ya están todos en dic_gtx["pdps"].
empleados_dia = consultar_empleados_por_dia_gtx(fini,
ffin)
else:
empleados_dia = 0.0 # Si no hay partes, no hay empleados
total = empleados_dia
elif nombre_var == "productividad":
pdps = utils.aplanar(
[dic_gtx["pdps"][mes] for mes in xrange(12)])
total = calcular_productividad_conjunta(tuple(pdps))
else:
total = sumatorio(nombre_var)
filas[nombre_var][pos] = total
if __name__ == '__main__':
ConsultaGlobal()
|
gpl-2.0
|
michaelklapper/TYPO3.CMS
|
typo3/sysext/core/Classes/Integrity/DatabaseIntegrityCheck.php
|
32160
|
<?php
namespace TYPO3\CMS\Core\Integrity;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use Doctrine\DBAL\Types\Type;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\RelationHandler;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* This class holds functions used by the TYPO3 backend to check the integrity of the database (The DBint module, 'lowlevel' extension)
*
* Depends on \TYPO3\CMS\Core\Database\RelationHandler
*
* @todo Need to really extend this class when the tcemain library has been updated and the whole API is better defined. There are some known bugs in this library. Further it would be nice with a facility to not only analyze but also clean up!
* @see \TYPO3\CMS\Lowlevel\View\DatabaseIntegrityView::func_relations(), \TYPO3\CMS\Lowlevel\View\DatabaseIntegrityView::func_records()
*/
class DatabaseIntegrityCheck
{
/**
* @var bool If set, genTree() includes deleted pages. This is default.
*/
public $genTree_includeDeleted = true;
/**
* @var bool If set, genTree() includes versionized pages/records. This is default.
*/
public $genTree_includeVersions = true;
/**
* @var bool If set, genTree() includes records from pages.
*/
public $genTree_includeRecords = false;
/**
* @var array Will hold id/rec pairs from genTree()
*/
public $page_idArray = array();
/**
* @var array
*/
public $rec_idArray = array();
/**
* @var array
*/
public $checkFileRefs = array();
/**
* @var array From the select-fields
*/
public $checkSelectDBRefs = array();
/**
* @var array From the group-fields
*/
public $checkGroupDBRefs = array();
/**
* @var array Statistics
*/
public $recStats = array(
'allValid' => array(),
'published_versions' => array(),
'deleted' => array()
);
/**
* @var array
*/
public $lRecords = array();
/**
* @var string
*/
public $lostPagesList = '';
/**
* Generates a list of Page-uid's that corresponds to the tables in the tree.
* This list should ideally include all records in the pages-table.
*
* @param int $theID a pid (page-record id) from which to start making the tree
* @param string $depthData HTML-code (image-tags) used when this function calls itself recursively.
* @param bool $versions Internal variable, don't set from outside!
* @return void
*/
public function genTree($theID, $depthData = '', $versions = false)
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
$queryBuilder->getRestrictions()->removeAll();
if (!$this->genTree_includeDeleted) {
$queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
}
$queryBuilder->select('uid', 'title', 'doktype', 'deleted', 'hidden')
->from('pages')
->orderBy('sorting');
if ($versions) {
$queryBuilder->addSelect('t3ver_wsid', 't3ver_id', 't3ver_count');
$queryBuilder->where(
$queryBuilder->expr()->eq('pid', -1),
$queryBuilder->expr()->eq('t3ver_oid', (int)$theID)
);
} else {
$queryBuilder->where(
$queryBuilder->expr()->eq('pid', (int)$theID)
);
}
$result = $queryBuilder->execute();
// Traverse the records selected
while ($row = $result->fetch()) {
$newID = $row['uid'];
// Register various data for this item:
$this->page_idArray[$newID] = $row;
$this->recStats['all_valid']['pages'][$newID] = $newID;
if ($row['deleted']) {
$this->recStats['deleted']['pages'][$newID] = $newID;
}
if ($versions && $row['t3ver_count'] >= 1) {
$this->recStats['published_versions']['pages'][$newID] = $newID;
}
if ($row['deleted']) {
$this->recStats['deleted']++;
}
if ($row['hidden']) {
$this->recStats['hidden']++;
}
$this->recStats['doktype'][$row['doktype']]++;
// If all records should be shown, do so:
if ($this->genTree_includeRecords) {
foreach ($GLOBALS['TCA'] as $tableName => $cfg) {
if ($tableName != 'pages') {
$this->genTree_records($newID, '', $tableName);
}
}
}
// Add sub pages:
$this->genTree($newID);
// If versions are included in the tree, add those now:
if ($this->genTree_includeVersions) {
$this->genTree($newID, '', true);
}
}
}
/**
* @param int $theID a pid (page-record id) from which to start making the tree
* @param string $_ Unused parameter
* @param string $table Table to get the records from
* @param bool $versions Internal variable, don't set from outside!
* @return void
*/
public function genTree_records($theID, $_ = '', $table = '', $versions = false)
{
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()->removeAll();
if (!$this->genTree_includeDeleted) {
$queryBuilder->getRestrictions()->add(GeneralUtility::makeInstance(DeletedRestriction::class));
}
$queryBuilder
->select(...explode(',', BackendUtility::getCommonSelectFields($table)))
->from($table);
// Select all records from table pointing to this page
if ($versions) {
$queryBuilder->where(
$queryBuilder->expr()->eq('pid', -1),
$queryBuilder->expr()->eq('t3ver_oid', (int)$theID)
);
} else {
$queryBuilder->where(
$queryBuilder->expr()->eq('pid', (int)$theID)
);
}
$queryResult = $queryBuilder->execute();
// Traverse selected
while ($row = $queryResult->fetch()) {
$newID = $row['uid'];
// Register various data for this item:
$this->rec_idArray[$table][$newID] = $row;
$this->recStats['all_valid'][$table][$newID] = $newID;
if ($row['deleted']) {
$this->recStats['deleted'][$table][$newID] = $newID;
}
if ($versions && $row['t3ver_count'] >= 1 && $row['t3ver_wsid'] == 0) {
$this->recStats['published_versions'][$table][$newID] = $newID;
}
// Select all versions of this record:
if ($this->genTree_includeVersions && $GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
$this->genTree_records($newID, '', $table, true);
}
}
}
/**
* Fills $this->lRecords with the records from all tc-tables that are not attached to a PID in the pid-list.
*
* @param string $pid_list list of pid's (page-record uid's). This list is probably made by genTree()
* @return void
*/
public function lostRecords($pid_list)
{
$this->lostPagesList = '';
$pageIds = GeneralUtility::intExplode(',', $pid_list);
if (is_array($pageIds)) {
foreach ($GLOBALS['TCA'] as $table => $tableConf) {
$pageIdsForTable = $pageIds;
// Remove preceding "-1," for non-versioned tables
if (!BackendUtility::isTableWorkspaceEnabled($table)) {
$pageIdsForTable = array_combine($pageIdsForTable, $pageIdsForTable);
unset($pageIdsForTable[-1]);
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()->removeAll();
$queryResult = $queryBuilder->select('uid', 'pid', $GLOBALS['TCA'][$table]['ctrl']['label'])
->from($table)
->where(
$queryBuilder->expr()->notIn('pid', $pageIdsForTable)
)
->execute();
$lostIdList = [];
while ($row = $queryResult->fetch()) {
$this->lRecords[$table][$row['uid']] = [
'uid' => $row['uid'],
'pid' => $row['pid'],
'title' => strip_tags(BackendUtility::getRecordTitle($table, $row))
];
$lostIdList[] = $row['uid'];
}
if ($table == 'pages') {
$this->lostPagesList = implode(',', $lostIdList);
}
}
}
}
/**
* Fixes lost record from $table with uid $uid by setting the PID to zero.
* If there is a disabled column for the record that will be set as well.
*
* @param string $table Database tablename
* @param int $uid The uid of the record which will have the PID value set to 0 (zero)
* @return bool TRUE if done.
*/
public function fixLostRecord($table, $uid)
{
if ($table && $GLOBALS['TCA'][$table] && $uid && is_array($this->lRecords[$table][$uid]) && $GLOBALS['BE_USER']->user['admin']) {
$updateFields = [
'pid' => 0
];
// If possible a lost record restored is hidden as default
if ($GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']) {
$updateFields[$GLOBALS['TCA'][$table]['ctrl']['enablecolumns']['disabled']] = 1;
}
GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable($table)
->update($table, $updateFields, ['uid' => (int)$uid]);
return true;
} else {
return false;
}
}
/**
* Counts records from $GLOBALS['TCA']-tables that ARE attached to an existing page.
*
* @param string $pid_list list of pid's (page-record uid's). This list is probably made by genTree()
* @return array an array with the number of records from all $GLOBALS['TCA']-tables that are attached to a PID in the pid-list.
*/
public function countRecords($pid_list)
{
$list = [];
$list_n = [];
$pageIds = GeneralUtility::intExplode(',', $pid_list);
if (!empty($pageIds)) {
foreach ($GLOBALS['TCA'] as $table => $tableConf) {
$pageIdsForTable = $pageIds;
// Remove preceding "-1," for non-versioned tables
if (!BackendUtility::isTableWorkspaceEnabled($table)) {
$pageIdsForTable = array_combine($pageIdsForTable, $pageIdsForTable);
unset($pageIdsForTable[-1]);
}
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()->removeAll();
$count = $queryBuilder->count('uid')
->from($table)
->where($queryBuilder->expr()->in('pid', $pageIds))
->execute()
->fetchColumn(0);
if ($count) {
$list[$table] = $count;
}
// same query excluding all deleted records
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$count = $queryBuilder->count('uid')
->from($table)
->where($queryBuilder->expr()->in('pid', $pageIdsForTable))
->execute()
->fetchColumn(0);
if ($count) {
$list_n[$table] = $count;
}
}
}
return ['all' => $list, 'non_deleted' => $list_n];
}
/**
* Finding relations in database based on type 'group' (files or database-uid's in a list)
*
* @param string $mode $mode = file, $mode = db, $mode = '' (all...)
* @return array An array with all fields listed that somehow are references to other records (foreign-keys) or files
*/
public function getGroupFields($mode)
{
$result = array();
foreach ($GLOBALS['TCA'] as $table => $tableConf) {
$cols = $GLOBALS['TCA'][$table]['columns'];
foreach ($cols as $field => $config) {
if ($config['config']['type'] == 'group') {
if ((!$mode || $mode == 'file') && $config['config']['internal_type'] == 'file' || (!$mode || $mode == 'db') && $config['config']['internal_type'] == 'db') {
$result[$table][] = $field;
}
}
if ((!$mode || $mode == 'db') && $config['config']['type'] == 'select' && $config['config']['foreign_table']) {
$result[$table][] = $field;
}
}
if ($result[$table]) {
$result[$table] = implode(',', $result[$table]);
}
}
return $result;
}
/**
* Finds all fields that hold filenames from uploadfolder
*
* @param string $uploadfolder Path to uploadfolder
* @return array An array with all fields listed that have references to files in the $uploadfolder
*/
public function getFileFields($uploadfolder)
{
$result = array();
foreach ($GLOBALS['TCA'] as $table => $tableConf) {
$cols = $GLOBALS['TCA'][$table]['columns'];
foreach ($cols as $field => $config) {
if ($config['config']['type'] == 'group' && $config['config']['internal_type'] == 'file' && $config['config']['uploadfolder'] == $uploadfolder) {
$result[] = array($table, $field);
}
}
}
return $result;
}
/**
* Returns an array with arrays of table/field pairs which are allowed to hold references to the input table name - according to $GLOBALS['TCA']
*
* @param string $theSearchTable Table name
* @return array
*/
public function getDBFields($theSearchTable)
{
$result = array();
foreach ($GLOBALS['TCA'] as $table => $tableConf) {
$cols = $GLOBALS['TCA'][$table]['columns'];
foreach ($cols as $field => $config) {
if ($config['config']['type'] == 'group' && $config['config']['internal_type'] == 'db') {
if (trim($config['config']['allowed']) == '*' || strstr($config['config']['allowed'], $theSearchTable)) {
$result[] = array($table, $field);
}
} elseif ($config['config']['type'] == 'select' && $config['config']['foreign_table'] == $theSearchTable) {
$result[] = array($table, $field);
}
}
}
return $result;
}
/**
* This selects non-empty-records from the tables/fields in the fkey_array generated by getGroupFields()
*
* @param array $fkey_arrays Array with tables/fields generated by getGroupFields()
* @return void
* @see getGroupFields()
*/
public function selectNonEmptyRecordsWithFkeys($fkey_arrays)
{
if (is_array($fkey_arrays)) {
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
foreach ($fkey_arrays as $table => $field_list) {
if ($GLOBALS['TCA'][$table] && trim($field_list)) {
$schemaManager = $connectionPool->getConnectionForTable($table)->getSchemaManager();
$tableColumns = $schemaManager->listTableColumns($table);
$queryBuilder = $connectionPool->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()->removeAll();
$fields = GeneralUtility::trimExplode(',', $field_list, true);
$queryBuilder->select('uid')
->from($table);
$whereClause = [];
foreach ($fields as $fieldName) {
// The array index of $tableColumns is the lowercased column name!
$fieldType = $tableColumns[strtolower($fieldName)]->getType()->getName();
if (in_array(
$fieldType,
[Type::BIGINT, Type::INTEGER, Type::SMALLINT, Type::DECIMAL, Type::FLOAT],
true
)) {
$whereClause[] = $queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull($fieldName),
$queryBuilder->expr()->neq($fieldName, 0)
);
} elseif (in_array($fieldType, [Type::STRING, Type::TEXT], true)) {
$whereClause[] = $queryBuilder->expr()->andX(
$queryBuilder->expr()->isNotNull($fieldName),
$queryBuilder->expr()->neq($fieldName, $queryBuilder->quote(''))
);
}
}
$queryResult = $queryBuilder->orWhere(...$whereClause)->execute();
while ($row = $queryResult->fetch()) {
foreach ($fields as $field) {
if (trim($row[$field])) {
$fieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
if ($fieldConf['type'] == 'group') {
if ($fieldConf['internal_type'] == 'file') {
// Files...
if ($fieldConf['MM']) {
$tempArr = [];
$dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
$dbAnalysis->start('', 'files', $fieldConf['MM'], $row['uid']);
foreach ($dbAnalysis->itemArray as $somekey => $someval) {
if ($someval['id']) {
$tempArr[] = $someval['id'];
}
}
} else {
$tempArr = explode(',', trim($row[$field]));
}
foreach ($tempArr as $file) {
$file = trim($file);
if ($file) {
$this->checkFileRefs[$fieldConf['uploadfolder']][$file] += 1;
}
}
}
if ($fieldConf['internal_type'] == 'db') {
$dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
$dbAnalysis->start(
$row[$field],
$fieldConf['allowed'],
$fieldConf['MM'],
$row['uid'],
$table,
$fieldConf
);
foreach ($dbAnalysis->itemArray as $tempArr) {
$this->checkGroupDBRefs[$tempArr['table']][$tempArr['id']] += 1;
}
}
}
if ($fieldConf['type'] == 'select' && $fieldConf['foreign_table']) {
$dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
$dbAnalysis->start(
$row[$field],
$fieldConf['foreign_table'],
$fieldConf['MM'],
$row['uid'],
$table,
$fieldConf
);
foreach ($dbAnalysis->itemArray as $tempArr) {
if ($tempArr['id'] > 0) {
$this->checkGroupDBRefs[$fieldConf['foreign_table']][$tempArr['id']] += 1;
}
}
}
}
}
}
}
}
}
}
/**
* Depends on selectNonEmpty.... to be executed first!!
*
* @return array Report over files; keys are "moreReferences", "noReferences", "noFile", "error
*/
public function testFileRefs()
{
$output = array();
// Handle direct references with upload folder setting (workaround)
$newCheckFileRefs = array();
foreach ($this->checkFileRefs as $folder => $files) {
// Only direct references without a folder setting
if ($folder !== '') {
$newCheckFileRefs[$folder] = $files;
continue;
}
foreach ($files as $file => $references) {
// Direct file references have often many references (removes occurrences in the moreReferences section of the result array)
if ($references > 1) {
$references = 1;
}
// The directory must be empty (prevents checking of the root directory)
$directory = dirname($file);
if ($directory !== '') {
$newCheckFileRefs[$directory][basename($file)] = $references;
}
}
}
$this->checkFileRefs = $newCheckFileRefs;
foreach ($this->checkFileRefs as $folder => $fileArr) {
$path = PATH_site . $folder;
if (@is_dir($path) && @is_readable($path)) {
$d = dir($path);
while ($entry = $d->read()) {
if (@is_file(($path . '/' . $entry))) {
if (isset($fileArr[$entry])) {
if ($fileArr[$entry] > 1) {
$temp = $this->whereIsFileReferenced($folder, $entry);
$tempList = '';
foreach ($temp as $inf) {
$tempList .= '[' . $inf['table'] . '][' . $inf['uid'] . '][' . $inf['field'] . '] (pid:' . $inf['pid'] . ') - ';
}
$output['moreReferences'][] = array($path, $entry, $fileArr[$entry], $tempList);
}
unset($fileArr[$entry]);
} else {
// Contains workaround for direct references
if (!strstr($entry, 'index.htm') && !preg_match(('/^' . preg_quote($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/'), $folder)) {
$output['noReferences'][] = array($path, $entry);
}
}
}
}
$d->close();
$tempCounter = 0;
foreach ($fileArr as $file => $value) {
// Workaround for direct file references
if (preg_match('/^' . preg_quote($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '/') . '/', $folder)) {
$file = $folder . '/' . $file;
$folder = '';
$path = substr(PATH_site, 0, -1);
}
$temp = $this->whereIsFileReferenced($folder, $file);
$tempList = '';
foreach ($temp as $inf) {
$tempList .= '[' . $inf['table'] . '][' . $inf['uid'] . '][' . $inf['field'] . '] (pid:' . $inf['pid'] . ') - ';
}
$tempCounter++;
$output['noFile'][substr($path, -3) . '_' . substr($file, 0, 3) . '_' . $tempCounter] = array($path, $file, $tempList);
}
} else {
$output['error'][] = array($path);
}
}
return $output;
}
/**
* Depends on selectNonEmpty.... to be executed first!!
*
* @param array $theArray Table with key/value pairs being table names and arrays with uid numbers
* @return string HTML Error message
*/
public function testDBRefs($theArray)
{
$result = '';
foreach ($theArray as $table => $dbArr) {
if ($GLOBALS['TCA'][$table]) {
$ids = array_keys($dbArr);
$ids = array_map('intval', $ids);
if (!empty($ids)) {
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()
->removeAll()
->add(GeneralUtility::makeInstance(DeletedRestriction::class));
$queryResult = $queryBuilder
->select('uid')
->from($table)
->where(
$queryBuilder->expr()->in('uid', $ids)
)
->execute();
while ($row = $queryResult->fetch()) {
if (isset($dbArr[$row['uid']])) {
unset($dbArr[$row['uid']]);
} else {
$result .= 'Strange Error. ...<br />';
}
}
foreach ($dbArr as $theId => $theC) {
$result .= 'There are ' . $theC . ' records pointing to this missing or deleted record; [' . $table . '][' . $theId . ']<br />';
}
}
} else {
$result .= 'Codeerror. Table is not a table...<br />';
}
}
return $result;
}
/**
* Finding all references to record based on table/uid
*
* @param string $searchTable Table name
* @param int $id Uid of database record
* @return array Array with other arrays containing information about where references was found
*/
public function whereIsRecordReferenced($searchTable, $id)
{
// Gets tables / Fields that reference to files
$fileFields = $this->getDBFields($searchTable);
$theRecordList = [];
foreach ($fileFields as $info) {
list($table, $field) = $info;
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()->removeAll();
$queryResult = $queryBuilder
->select('uid', 'pid', $GLOBALS['TCA'][$table]['ctrl']['label'], $field)
->from($table)
->where(
$queryBuilder->expr()->like(
$field,
$queryBuilder->createNamedParameter('%' . $queryBuilder->escapeLikeWildcards($id) . '%')
)
)
->execute();
while ($row = $queryResult->fetch()) {
// Now this is the field, where the reference COULD come from.
// But we're not guaranteed, so we must carefully examine the data.
$fieldConf = $GLOBALS['TCA'][$table]['columns'][$field]['config'];
$allowedTables = $fieldConf['type'] == 'group' ? $fieldConf['allowed'] : $fieldConf['foreign_table'];
$dbAnalysis = GeneralUtility::makeInstance(RelationHandler::class);
$dbAnalysis->start($row[$field], $allowedTables, $fieldConf['MM'], $row['uid'], $table, $fieldConf);
foreach ($dbAnalysis->itemArray as $tempArr) {
if ($tempArr['table'] == $searchTable && $tempArr['id'] == $id) {
$theRecordList[] = [
'table' => $table,
'uid' => $row['uid'],
'field' => $field,
'pid' => $row['pid']
];
}
}
}
}
return $theRecordList;
}
/**
* Finding all references to file based on uploadfolder / filename
*
* @param string $uploadFolder Upload folder where file is found
* @param string $filename Filename to search for
* @return array Array with other arrays containing information about where references was found
*/
public function whereIsFileReferenced($uploadFolder, $filename)
{
// Gets tables / Fields that reference to files
$fileFields = $this->getFileFields($uploadFolder);
$theRecordList = [];
foreach ($fileFields as $info) {
list($table, $field) = $info;
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
$queryBuilder->getRestrictions()->removeAll();
$queryResult = $queryBuilder
->select('uid', 'pid', $GLOBALS['TCA'][$table]['ctrl']['label'], $field)
->from($table)
->where(
$queryBuilder->expr()->like(
$field,
$queryBuilder->createNamedParameter('%' . $queryBuilder->escapeLikeWildcards($filename) . '%')
)
)
->execute();
while ($row = $queryResult->fetch()) {
// Now this is the field, where the reference COULD come from.
// But we're not guaranteed, so we must carefully examine the data.
$tempArr = explode(',', trim($row[$field]));
foreach ($tempArr as $file) {
$file = trim($file);
if ($file == $filename) {
$theRecordList[] = [
'table' => $table,
'uid' => $row['uid'],
'field' => $field,
'pid' => $row['pid']
];
}
}
}
}
return $theRecordList;
}
}
|
gpl-2.0
|
arthurtumanyan/squid-3.0-stable1-shaga
|
src/StoreSwapLogData.cc
|
1863
|
/*
* $Id: StoreSwapLogData.cc,v 1.4 2007/08/13 17:20:51 hno Exp $
*
* DEBUG: section 47 Store Directory Routines
* AUTHOR: Duane Wessels
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from
* the Internet community; see the CONTRIBUTORS file for full
* details. Many organizations have provided support for Squid's
* development; see the SPONSORS file for full details. Squid is
* Copyrighted (C) 2001 by the Regents of the University of
* California; see the COPYRIGHT file for full details. Squid
* incorporates software developed and/or copyrighted by other
* sources; see the CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
*/
#include "StoreSwapLogData.h"
StoreSwapLogData::StoreSwapLogData(): op(0), swap_filen (0), timestamp (0), lastref (0), expires (0), lastmod(0), swap_file_sz (0), refcount (0), flags (0)
{
memset (key, '\0', sizeof(key));
}
StoreSwapLogHeader::StoreSwapLogHeader():op(SWAP_LOG_VERSION), version(1)
{
record_size = sizeof(StoreSwapLogData);
}
|
gpl-2.0
|
sgrieve/LH_Paper_Plotting
|
Plotting_Code/Figure_4_Coweeta_revision.py
|
5560
|
# -*- coding: utf-8 -*-
"""
Copyright (C) 2015 Stuart W.D Grieve 2015
Developer can be contacted by s.grieve _at_ ed.ac.uk
This program is free software;
you can redistribute it and/or modify it under the terms of the
GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY;
without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the
GNU General Public License along with this program;
if not, write to:
Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301
USA
Script to generate Figure 4 from Grieve et al. (2015)
Input data is generated using LH_Driver.cpp
Parameters to be modified are highlighted by comments
@author: SWDG
"""
def mm_to_inch(mm):
return mm*0.0393700787
import matplotlib.pyplot as plt
from matplotlib import rcParams
import MuddPyStatsTools as mpy
import numpy as np
import string
# Set up fonts for plots
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['arial']
rcParams['font.size'] = 10
rcParams['xtick.direction'] = 'out'
rcParams['ytick.direction'] = 'out'
#================ modifyable parameters start here ====================
#paths to the data and to save the figure to
path = 'C:/Users/Stuart/Dropbox/LH_Paper/nc/' #path to the folder contaning the hilltopdata files
filename = 'NC_PaperData.txt'#names of the hilltopdata file
figpath = 'C:/Users/Stuart/Desktop/FR/final_figures_revision/' #path to save the final figure
#plot style parameters
xmaxes = [450,200,400]
ymaxes = [9,13,11]
xsteps = [200,100,100]
ysteps = [2,3,2]
v_line_lims = [1.2,0,0]
#plot labels
Methods = ['Hilltop Flow Routing','Slope-Area','Drainage Density']
fig_labels = list(string.ascii_lowercase)[:3] #generate subplot labels
#number of bins in the histograms
nbins = 20
#================ modifyable parameters end here ====================
fig = plt.figure()
#load the paperdata file to get the LH data
with open(path+filename,'r') as f:
f.readline()
data = f.readlines()
lh_ = []
SA = []
SA_Plot =[]
DD = []
for d in data:
split = d.split()
lh = float(split[2])
sa_lh = float(split[9])
dd = float(split[11])
if (sa_lh > 2.0):
SA.append(sa_lh)
if (sa_lh < 350.):
SA_Plot.append(sa_lh)
if (lh > 2.0):
lh_.append(lh)
if (dd > 2.0):
DD.append(dd)
Calc_Data = [lh_,SA,DD]
Plot_Data = [lh_,SA_Plot,DD]
for subplot_count, (Method,xmax,ymax,xstep,ystep,labels,v_line_lim) in enumerate(zip(Methods,xmaxes,ymaxes,xsteps,ysteps,fig_labels,v_line_lims)):
LH = Calc_Data[subplot_count]
#get the median absolute devaition
MAD = mpy.calculate_MedianAbsoluteDeviation(LH)
#set up the 4 subplots
ax = plt.subplot(3,1,subplot_count + 1)
#Add a title with the method name
ax.text(.5,.9,Method, horizontalalignment='center', transform=ax.transAxes,fontsize=12)
#plot the histogram and get the patches so we can colour them
n,bins,patches = plt.hist(Plot_Data[subplot_count],bins=nbins,color='k',linewidth=0)
#get the median -/+ median devaition
MinMAD = np.median(LH)-MAD
MaxMAD = np.median(LH)+MAD
#color the bins that fall within +/- MAD of the median
#http://stackoverflow.com/questions/6352740/matplotlib-label-each-bin
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
if rightside < MinMAD:
patch.set_alpha(0.4)
elif leftside > MaxMAD:
patch.set_alpha(0.4)
#Insert dashed red line at median
plt.vlines(np.median(LH),0,ymax-v_line_lim,label='Median', color='r',linewidth=1,linestyle='dashed')
#set x axis limits
plt.xlim(0,xmax)
plt.ylim(0,ymax)
#format the ticks to only appear on the bottom and left axes
plt.tick_params(axis='x', which='both', top='off',length=2)
plt.tick_params(axis='y', which='both', right='off',length=2)
#configure tick spacing based on the defined spacings given
ax.xaxis.set_ticks(np.arange(0,xmax+1,xstep))
ax.yaxis.set_ticks(np.arange(0,ymax+1,ystep))
#annotate the plot with the median and MAD and the subplot label
plt.annotate('Median = '+str(int(round(np.median(LH),0)))+' m\nMAD = '+str(int(round(MAD,0)))+' m', xy=(0.6, 0.7), xycoords='axes fraction', fontsize=10, horizontalalignment='left', verticalalignment='top')
plt.annotate(labels, xy=(0.95, 0.95), xycoords='axes fraction', fontsize=10, horizontalalignment='left', verticalalignment='top')
#spacing of the plots
plt.subplots_adjust(hspace = 0.25,left=0.2)
#x and y axis labels
fig.text(0.5, 0.05, 'Hillslope length (m)', ha='center', va='center', size=12)
fig.text(0.06, 0.5, 'Count', ha='center', va='center', rotation='vertical', size=12)
# title
fig.text(0.5, 0.925, 'Coweeta', ha='center', va='center', size=14)
#set the size of the plot to be saved. These are the JGR sizes:
#quarter page = 95*115
#half page = 190*115 (horizontal) 95*230 (vertical)
#full page = 190*230
fig.set_size_inches(mm_to_inch(95), mm_to_inch(200))
plt.savefig(figpath+'Figure_4.png', dpi = 500) #change to *.tif for submission
|
gpl-2.0
|
syvaidya/openstego
|
src/main/java/com/openstego/desktop/util/dwt/Filter.java
|
3422
|
/*
* Steganography utility to hide messages into cover files
* Author: Samir Vaidya (mailto:syvaidya@gmail.com)
* Copyright (c) Samir Vaidya
*/
package com.openstego.desktop.util.dwt;
/**
* Object to store Filter data
*/
public class Filter {
/**
* Constant for filter type = NoSymm
*/
public static final int TYPE_NOSYMM = 0;
/**
* Constant for filter type = Symm
*/
public static final int TYPE_SYMM = 1;
/**
* Constant for filter type = AntiSymm
*/
public static final int TYPE_ANTISYMM = 2;
/**
* Constant for filter method = cutoff
*/
public static final int METHOD_CUTOFF = 0;
/**
* Constant for filter method = inv_cutoff
*/
public static final int METHOD_INVCUTOFF = 1;
/**
* Constant for filter method = periodical
*/
public static final int METHOD_PERIODICAL = 2;
/**
* Constant for filter method = inv_periodical
*/
public static final int METHOD_INVPERIODICAL = 3;
/**
* Constant for filter method = mirror,inv_mirror
*/
public static final int METHOD_MIRROR = 4;
/**
* Constant for filter method = inv_mirror
*/
public static final int METHOD_INVMIRROR = 5;
/**
* Type of the filter
*/
private int type = -1;
/**
* Start value of the filter
*/
private int start = 0;
/**
* End value of the filter
*/
private int end = 0;
/**
* Flag to indicate whether this is hi-pass filter or not
*/
private boolean hiPass = false;
/**
* List of associated data
*/
private double[] data = null;
/**
* Get method for type
*
* @return type
*/
public int getType() {
return this.type;
}
/**
* Set method for type
*
* @param type Value to be set
*/
public void setType(String type) {
if (type.equalsIgnoreCase("nosymm")) {
this.type = TYPE_NOSYMM;
} else if (type.equalsIgnoreCase("symm")) {
this.type = TYPE_SYMM;
} else if (type.equalsIgnoreCase("antisymm")) {
this.type = TYPE_ANTISYMM;
} else {
this.type = -1;
}
}
/**
* Get method for start
*
* @return start
*/
public int getStart() {
return this.start;
}
/**
* Set method for start
*
* @param start Value to be set
*/
public void setStart(int start) {
this.start = start;
}
/**
* Get method for end
*
* @return end
*/
public int getEnd() {
return this.end;
}
/**
* Set method for end
*
* @param end Value to be set
*/
public void setEnd(int end) {
this.end = end;
}
/**
* Get method for hiPass
*
* @return hiPass
*/
public boolean isHiPass() {
return this.hiPass;
}
/**
* Set method for hiPass
*
* @param hiPass Value to be set
*/
public void setHiPass(boolean hiPass) {
this.hiPass = hiPass;
}
/**
* Get method for data
*
* @return data
*/
public double[] getData() {
return this.data;
}
/**
* Set method for data
*
* @param data Value to be set
*/
public void setData(double[] data) {
this.data = data;
}
}
|
gpl-2.0
|
tonysparks/seventh
|
src/seventh/game/events/BombPlantedListener.java
|
308
|
/*
* The Seventh
* see license.txt
*/
package seventh.game.events;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
/**
* @author Tony
*
*/
public interface BombPlantedListener extends EventListener {
@EventMethod
public void onBombPlanted(BombPlantedEvent event);
}
|
gpl-2.0
|
zroeduardo/Framebone
|
Packages/Framebone/Package/Abstract/Package.php
|
175
|
<?php
namespace Packages\Framebone\Package\Abstract;
use \Packages\Framebone as fb;
abstract class Package implements fb\Package\Interface\Package
{
}
|
gpl-2.0
|
vishwaAbhinav/OpenNMS
|
opennms-config/src/main/java/org/opennms/netmgt/config/datacollection/descriptors/SnmpCollectionDescriptor.java
|
21465
|
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package org.opennms.netmgt.config.datacollection.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.opennms.netmgt.config.datacollection.SnmpCollection;
/**
* Class SnmpCollectionDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class SnmpCollectionDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public SnmpCollectionDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/config/datacollection";
_xmlName = "snmp-collection";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _name
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_name", "name", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getName();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.setName( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _name
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _maxVarsPerPdu
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.Integer.TYPE, "_maxVarsPerPdu", "maxVarsPerPdu", org.exolab.castor.xml.NodeType.Attribute);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
if (!target.hasMaxVarsPerPdu()) { return null; }
return new java.lang.Integer(target.getMaxVarsPerPdu());
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
// if null, use delete method for optional primitives
if (value == null) {
target.deleteMaxVarsPerPdu();
return;
}
target.setMaxVarsPerPdu( ((java.lang.Integer) value).intValue());
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("int");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _maxVarsPerPdu
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.IntValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.IntValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setMinInclusive(-2147483648);
typeValidator.setMaxInclusive(2147483647);
}
desc.setValidator(fieldValidator);
//-- _snmpStorageFlag
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_snmpStorageFlag", "snmpStorageFlag", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getSnmpStorageFlag();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.setSnmpStorageFlag( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _snmpStorageFlag
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.addPattern("(all|primary|select)");
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _rrd
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.Rrd.class, "_rrd", "rrd", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getRrd();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.setRrd( (org.opennms.netmgt.config.datacollection.Rrd) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.Rrd();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.Rrd");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _rrd
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _includeCollectionList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.IncludeCollection.class, "_includeCollectionList", "include-collection", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getIncludeCollection();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.addIncludeCollection( (org.opennms.netmgt.config.datacollection.IncludeCollection) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
SnmpCollection target = (SnmpCollection) object;
target.removeAllIncludeCollection();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.IncludeCollection();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.IncludeCollection");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _includeCollectionList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(0);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _resourceTypeList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.ResourceType.class, "_resourceTypeList", "resourceType", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getResourceType();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.addResourceType( (org.opennms.netmgt.config.datacollection.ResourceType) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
SnmpCollection target = (SnmpCollection) object;
target.removeAllResourceType();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.ResourceType();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.ResourceType");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _resourceTypeList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(0);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _groups
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.Groups.class, "_groups", "groups", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getGroups();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.setGroups( (org.opennms.netmgt.config.datacollection.Groups) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.Groups();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.Groups");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _groups
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _systems
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.Systems.class, "_systems", "systems", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
SnmpCollection target = (SnmpCollection) object;
return target.getSystems();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
SnmpCollection target = (SnmpCollection) object;
target.setSystems( (org.opennms.netmgt.config.datacollection.Systems) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.Systems();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.Systems");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _systems
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return org.opennms.netmgt.config.datacollection.SnmpCollection.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
|
gpl-2.0
|
rjbaniel/upoor
|
wp-content/themes/mystique/header.php
|
3124
|
<?php /* Mystique/digitalnature */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <?php //language_attributes('xhtml'); ?>>
<head profile="http://gmpg.org/xfn/11">
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<title><?php mystique_title(); ?></title>
<?php mystique_meta_description(); ?>
<meta name="designer" content="digitalnature.ro" />
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />
<link rel="alternate" type="application/atom+xml" title="<?php bloginfo('name'); ?> Atom Feed" href="<?php bloginfo('atom_url'); ?>" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<!-- favicon.ico location -->
<?php if(file_exists( WP_CONTENT_DIR . '/favicon.ico')) { //put your favicon.ico inside wp-content/ ?>
<link rel="icon" href="<?php echo WP_CONTENT_URL; ?>/favicon.ico" type="images/x-icon" />
<?php } elseif(file_exists( WP_CONTENT_DIR . '/favicon.png')) { //put your favicon.png inside wp-content/ ?>
<link rel="icon" href="<?php echo WP_CONTENT_URL; ?>/favicon.png" type="images/x-icon" />
<?php } elseif(file_exists( TEMPLATEPATH . '/favicon.ico')) { ?>
<link rel="icon" href="<?php echo get_template_directory_uri(); ?>/favicon.ico" type="images/x-icon" />
<?php } elseif(file_exists( TEMPLATEPATH . '/favicon.png')) { ?>
<link rel="icon" href="<?php echo get_template_directory_uri(); ?>/favicon.png" type="images/x-icon" />
<?php } ?>
<link rel="shortcut icon" href="<?php bloginfo('template_directory'); ?>/favicon.ico" />
<?php wp_head(); ?>
<?php if( get_background_image() || get_theme_mod('preset_bg') ) { ?>
<style>
#page {
background: transparent none !important;
}
</style>
<?php } ?>
</head>
<body class="<?php mystique_body_class() ?>">
<div id="page">
<div class="page-content header-wrapper">
<div id="header" class="bubbleTrigger">
<div id="site-title" class="clearfix">
<?php mystique_logo(); ?>
<?php if(get_bloginfo('description')): ?><p class="headline"><?php bloginfo('description'); ?></p><?php endif; ?>
<?php do_action('mystique_header'); ?>
</div>
<?php mystique_navigation(); ?>
</div>
</div>
<?php if('' != get_header_image() ) {
$check_width = get_mystique_option('page_width'); ?>
<div <?php if($check_width == 'fixed') { ?>
style='overflow: hidden; margin:0 auto; width: 960px; height: 150px; background: url(<?php header_image(); ?>) no-repeat center;'
<?php } else { ?>
style='overflow: hidden; margin:0 auto; max-width:1600px; min-width:780px; height: 150px; background: url(<?php header_image(); ?>) repeat-x left;'
<?php } ?> id="custom-img-header"></div>
<?php } ?>
<!-- left+right bottom shadow -->
<div class="shadow-left page-content main-wrapper">
<div class="shadow-right">
<?php do_action('mystique_before_main'); ?>
|
gpl-2.0
|
evaluon/api
|
dao/gamification.js
|
198
|
module.exports = function(app){
var Gamification = app.db.Gamification;
return {
indicators: function(user){
return Gamification.indicators(user);
}
}
}
|
gpl-2.0
|
mikhaelmurmur/GameJamKPIGame
|
GameJamKPI/Assets/Scripts/PlayerController.cs
|
628
|
using System;
using UnityEngine;
using System.Collections;
[Serializable]
public class Boundary
{
public float xMin, xMax, yMin, yMax;
}
public class PlayerController : MonoBehaviour
{
public float speed = 2f;
public float jumpHeight = 10f;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
Vector2 movement = new Vector2(moveHorizontal * speed, rb.velocity.y);
rb.AddForce(movement, ForceMode2D.Impulse);
rb.velocity = movement;
}
}
|
gpl-2.0
|
vinni-au/vega-strike
|
vegastrike/setup/src/c/setup.cpp
|
7800
|
/***************************************************************************
* setup.cpp - description
* ----------------------------
* begin : January 18, 2002
* copyright : (C) 2002 by David Ranger
* email : sabarok@start.com.au
**************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* any later version. *
* *
**************************************************************************/
#include "../include/central.h"
#include <stdlib.h>
#ifdef _WIN32
#include <direct.h>
#include <windows.h>
#else
#include <sys/dir.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
#include <vector>
#include <string>
using std::string;
using std::vector;
char origpath[65536];
static int bogus_int; //added by chuck_starchaser to squash a warning or two
static char *bogus_str; //added by chuck_starchaser to squash a warning or two
static void changeToProgramDirectory( char *argv0 )
{
int ret = -1; /* Should it use argv[0] directly? */
char *program = argv0;
#ifndef _WIN32
char buf[65536];
{
char linkname[128]; /* /proc/<pid>/exe */
linkname[0] = '\0';
pid_t pid;
/* Get our PID and build the name of the link in /proc */
pid = getpid();
sprintf( linkname, "/proc/%d/exe", pid );
ret = readlink( linkname, buf, 65535 );
if (ret <= 0) {
sprintf( linkname, "/proc/%d/file", pid );
ret = readlink( linkname, buf, 65535 );
}
if (ret <= 0)
ret = readlink( program, buf, 65535 );
if (ret > 0) {
buf[ret] = '\0';
/* Ensure proper NUL termination */
program = buf;
}
}
#endif
char *parentdir;
int pathlen = strlen( program );
parentdir = new char[pathlen+1];
char *c;
strncpy( parentdir, program, pathlen+1 );
c = (char*) parentdir;
while (*c != '\0') /* go to end */
c++;
while ( (*c != '/') && (*c != '\\') && c > parentdir ) /* back up to parent */
c--;
*c = '\0'; /* cut off last part (binary name) */
if (strlen( parentdir ) > 0)
bogus_int = chdir( parentdir ); /* chdir to the binary app's parent */
delete[] parentdir;
}
#if defined (_WINDOWS) && defined (_WIN32)
typedef char FileNameCharType[65536];
int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd )
{
char *argv0 = new char[65535];
char **argv = &argv0;
int argc = 0;
strcpy( argv0, origpath );
GetModuleFileName( NULL, argv0, 65534 );
#else
int main( int argc, char *argv[] )
{
#endif
CONFIG.data_path = NULL;
CONFIG.config_file = NULL;
CONFIG.program_name = NULL;
CONFIG.temp_file = NULL;
bogus_str = getcwd( origpath, 65535 );
origpath[65535] = 0;
changeToProgramDirectory( argv[0] );
{
vector< string >data_paths;
if (argc > 1) {
if (strcmp( argv[1], "--target" ) == 0 && argc > 2) {
data_paths.push_back( argv[2] );
} else {
fprintf( stderr, "Usage: vssetup [--target DATADIR]\n" );
return 1;
}
}
#ifdef DATA_DIR
data_paths.push_back( DATA_DIR );
#endif
data_paths.push_back( origpath );
data_paths.push_back( string( origpath )+"/.." );
data_paths.push_back( string( origpath )+"/../data4.x" );
data_paths.push_back( string( origpath )+"/../../data4.x" );
data_paths.push_back( string( origpath )+"/data4.x" );
data_paths.push_back( string( origpath )+"/data" );
data_paths.push_back( string( origpath )+"/../data" );
data_paths.push_back( string( origpath )+"/../Resources" );
bogus_str = getcwd( origpath, 65535 );
origpath[65535] = 0;
data_paths.push_back( "." );
data_paths.push_back( ".." );
data_paths.push_back( "../data4.x" );
data_paths.push_back( "../../data4.x" );
data_paths.push_back( "../data" );
data_paths.push_back( "../../data" );
data_paths.push_back( "../Resources" );
data_paths.push_back( "../Resources/data" );
data_paths.push_back( "../Resources/data4.x" );
/*
* data_paths.push_back( "/usr/share/local/vegastrike/data");
* data_paths.push_back( "/usr/local/share/vegastrike/data");
* data_paths.push_back( "/usr/local/vegastrike/data");
* data_paths.push_back( "/usr/share/vegastrike/data");
* data_paths.push_back( "/usr/local/games/vegastrike/data");
* data_paths.push_back( "/usr/games/vegastrike/data");
* data_paths.push_back( "/opt/share/vegastrike/data");
* data_paths.push_back( "/usr/share/local/vegastrike/data4.x");
* data_paths.push_back( "/usr/local/share/vegastrike/data4.x");
* data_paths.push_back( "/usr/local/vegastrike/data4.x");
* data_paths.push_back( "/usr/share/vegastrike/data4.x");
* data_paths.push_back( "/usr/local/games/vegastrike/data4.x");
* data_paths.push_back( "/usr/games/vegastrike/data4.x");
* data_paths.push_back( "/opt/share/vegastrike/data4.x");
*/
//Win32 data should be "."
for (vector< string >::iterator vsit = data_paths.begin(); vsit != data_paths.end(); vsit++) {
//Test if the dir exist and contains config_file
bogus_int = chdir( origpath );
bogus_int = chdir( (*vsit).c_str() );
FILE *setupcfg = fopen( "setup.config", "r" );
if (!setupcfg)
continue;
fclose( setupcfg );
setupcfg = fopen( "Version.txt", "r" );
if (!setupcfg)
continue;
bogus_str = getcwd( origpath, 65535 );
origpath[65535] = 0;
printf( "Found data in %s\n", origpath );
CONFIG.data_path = strdup(origpath);
break;
}
}
#ifndef _WIN32
struct passwd *pwent;
pwent = getpwuid( getuid() );
string HOMESUBDIR;
FILE *version = fopen( "Version.txt", "r" );
if (!version)
version = fopen( "../Version.txt", "r" );
if (version) {
std::string hsd = "";
int c;
while ( ( c = fgetc( version ) ) != EOF ) {
if ( isspace( c ) )
break;
hsd += (char) c;
}
fclose( version );
if ( hsd.length() )
HOMESUBDIR = hsd;
//fprintf (STD_OUT,"Using %s as the home directory\n",hsd.c_str());
}
if ( HOMESUBDIR.empty() ) {
fprintf( stderr, "Error: Failed to find Version.txt anywhere.\n" );
return 1;
}
bogus_int = chdir( pwent->pw_dir );
mkdir( HOMESUBDIR.c_str(), 0755 );
bogus_int = chdir( HOMESUBDIR.c_str() );
#endif
Start( &argc, &argv );
#if defined (_WINDOWS) && defined (_WIN32)
delete[] argv0;
#endif
return 0;
}
|
gpl-2.0
|
seecr/cqlparser
|
cqlparser/cqltoexpression.py
|
3264
|
## begin license ##
#
# "CQLParser" is a parser that builds a parsetree for the given CQL and can convert this into other formats.
#
# Copyright (C) 2015, 2020-2021 Seecr (Seek You Too B.V.) https://seecr.nl
# Copyright (C) 2015, 2021 Stichting Kennisnet https://www.kennisnet.nl
# Copyright (C) 2021 Data Archiving and Network Services https://dans.knaw.nl
# Copyright (C) 2021 SURF https://www.surf.nl
# Copyright (C) 2021 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl
#
# This file is part of "CQLParser"
#
# "CQLParser" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# "CQLParser" 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 "CQLParser"; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
## end license ##
from .cqlvisitor import CqlVisitor
from .cqlparser import parseString as parseCql
from ._queryexpression import QueryExpression
def cqlToExpression(cql):
if isinstance(cql, QueryExpression):
return cql
if not hasattr(cql, 'accept'):
cql = parseCql(cql)
return CqlToExpressionVisitor(cql).visit()
class CqlToExpressionVisitor(CqlVisitor):
def visitCQL_QUERY(self, node):
return CqlVisitor.visitCQL_QUERY(self, node)[0]
def visitSCOPED_CLAUSE(self, node):
clause = CqlVisitor.visitSCOPED_CLAUSE(self, node)
if len(clause) == 1:
return clause[0]
lhs, operator, rhs = clause
if operator == 'NOT':
operator = 'AND'
rhs.must_not = True
result = QueryExpression.nested(operator)
for hs in [lhs, rhs]:
if hs.operator == operator and not hs.must_not:
result.operands.extend(hs.operands)
else:
result.operands.append(hs)
return result
def visitSEARCH_CLAUSE(self, node):
firstChild = node.children[0].name
results = CqlVisitor.visitSEARCH_CLAUSE(self, node)
if firstChild == 'SEARCH_TERM':
return QueryExpression.searchterm(term=results[0])
elif firstChild == 'INDEX':
#INDEX(TERM('term')), RELATION(COMPARITOR('comparitor')), SEARCH_TERM(TERM('term'))
index, (relation, boost), term = results
result = QueryExpression.searchterm(
index=index,
relation=relation,
term=term,
boost=boost,
)
return result
return results[0]
def visitRELATION(self, node):
results = CqlVisitor.visitRELATION(self, node)
if len(results) == 1:
relation = results[0]
boost = None
else:
(relation, (modifier, comparitor, value)) = results
boost = float(value)
return relation, boost
|
gpl-2.0
|
cdsource/sonarmail
|
src/org/jpf/sonar/rpts/WeekRptCoverage.java
|
2663
|
/**
* @author 吴平福
* E-mail:wupf@asiainfo-linkage.com
* @version 创建时间:2013-4-12 下午6:55:39
* 类说明
*/
package org.jpf.sonar.rpts;
import java.sql.ResultSet;
public class WeekRptCoverage extends AbstractRpt
{
/**
* @param strPrjName
* @param iType
* @param strMailCC
*/
public WeekRptCoverage(String strPrjName, int iType, String strMailCC)
{
super(strPrjName, iType, strMailCC);
// TODO Auto-generated constructor stub
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
if (3 == args.length)
{
int i = Integer.parseInt(args[0]);
WeekRptCoverage cDailyPackageRpt = new WeekRptCoverage(args[1],i,args[2]);
}
}
/* (non-Javadoc)
* @see org.jpf.ci.rpts.AbstractWeekRpt#GetTemplateName()
*/
@Override
public String GetTemplateName()
{
// TODO Auto-generated method stub
return "week_coverage.html";
}
/* (non-Javadoc)
* @see org.jpf.ci.rpts.AbstractWeekRpt#GetSql()
*/
@Override
public String GetSql(int iType,String strPrjName)
{
// TODO Auto-generated method stub
String strSql="select * from hz_sonar_user where prj_name='"+strPrjName+"'";
if(1==iType)
{
strSql+=" and (IFNULL(brach_coverage1,0)<>IFNULL(brach_coverage2,0) or IFNULL(cover_branch1,0)<>IFNULL(cover_branch2,0))";
}
if (0==iType)
{
strSql+=" order by login";
}
return strSql;
}
/* (non-Javadoc)
* @see org.jpf.ci.rpts.AbstractWeekRpt#DoMailText(java.lang.StringBuffer, java.sql.ResultSet)
*/
@Override
public void DoMailText(StringBuffer sb, ResultSet rs) throws Exception
{
// TODO Auto-generated method stub
while (rs.next())
{
sb.append("<tr><td align='left'>").append(rs.getString("kee"))
.append("</td><td>").append(rs.getString("login"))
.append("</td><td>").append(FormatDouble(rs.getDouble("brach_coverage1")))
.append("%</td><td>").append(rs.getLong("cover_branch1"))
.append("</td><td>").append(rs.getLong("cover_branch1")-rs.getLong("un_cover_branch1"))
.append("</td><td>").append(FormatDouble(rs.getDouble("brach_coverage2")))
.append("%</td><td>").append(rs.getLong("cover_branch2"))
.append("</td><td>").append(rs.getLong("cover_branch2")-rs.getLong("un_cover_branch2"))
.append("</td><td>").append(rs.getLong("cover_branch1")-rs.getLong("un_cover_branch1")-rs.getLong("cover_branch2")+rs.getLong("un_cover_branch2"))
.append("</td></tr>");
}
}
/* (non-Javadoc)
* @see org.jpf.ci.rpts.AbstractRpt#GetMailTitle()
*/
@Override
public String GetMailTitle()
{
// TODO Auto-generated method stub
return " 一周代码单元测试分支覆盖率变化情况";
}
}
|
gpl-2.0
|
loadedcommerce/loaded7
|
catalog/admin/includes/functions/cfg_parameters/lc_cfg_set_currencies_pulldown_menu.php
|
1017
|
<?php
/**
@package admin::functions
@author Loaded Commerce
@copyright Copyright 2003-2014 Loaded Commerce, LLC
@copyright Portions Copyright 2003 osCommerce
@license https://github.com/loadedcommerce/loaded7/blob/master/LICENSE.txt
@version $Id: lc_cfg_set_currencies_pulldown_menu.php v1.0 2013-08-08 datazen $
*/
function lc_cfg_set_currencies_pulldown_menu($default, $key = null) {
global $lC_Database;
$css_class = 'class="input with-small-padding"';
$name = (empty($key)) ? 'configuration_value' : 'configuration[' . $key . ']';
$Qcurrencies = $lC_Database->query('select * from :table_currencies');
$Qcurrencies->bindTable(':table_currencies', TABLE_CURRENCIES);
$Qcurrencies->execute();
while ($Qcurrencies->next()) {
$currencies_array[] = array('id' => $Qcurrencies->valueInt('currencies_id'),
'text' => $Qcurrencies->value('title'));
}
return lc_draw_pull_down_menu($name, $currencies_array, $default, $css_class);
}
?>
|
gpl-2.0
|
marc1706/Board3-Portal-Gallery-Block
|
root/install/index.php
|
12674
|
<?php
/**
*
* @package B3P Addon - Gallery block
* @version $Id: index.php 67 2009-09-30 14:28:10Z Christian_N $
* @copyright (c) Christian_N ( www.phpbb-projekt.de )
* @installer based on: phpBB Gallery by nickvergessen, www.flying-bits.org
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
* borrowed from phpBB3
* @author: phpBB Group
*
*/
/**
* @ignore
*/
define('IN_PHPBB', true);
define('IN_INSTALL', true);
define('NEWEST_GB_VERSION', '1.4.2');
define('PG_VERSION', '1.0.5');
define('B3P_VERSION', '1.0.6');
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.'.$phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
include($phpbb_root_path . 'includes/acp/acp_modules.' . $phpEx);
include($phpbb_root_path . 'includes/acp/acp_bbcodes.' . $phpEx);
include($phpbb_root_path . 'includes/db/db_tools.' . $phpEx);
include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
require($phpbb_root_path . 'includes/functions_install.' . $phpEx);
// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup(array('install', 'mods/install_gallery_block'));
//need some module-names
$user->add_lang(array('acp/modules', 'acp/common', 'mods/info_acp_b3p_gallery'));
$template->set_custom_template('../adm/style', 'admin');
$template->assign_var('T_TEMPLATE_PATH', '../adm/style');
$mode = request_var('mode', 'overview');
$sub = request_var('sub', '');
// the acp template is never stored in the database
$user->theme['template_storedb'] = false;
$install = new module();
$install->create('install', "index.$phpEx", $mode, $sub);
$install->load();
// Generate the page
$install->page_header();
$install->generate_navigation();
$template->set_filenames(array(
'body' => $install->get_tpl_name())
);
$install->page_footer();
/**
* @package install
*/
class module
{
var $id = 0;
var $type = 'install';
var $module_ary = array();
var $filename;
var $module_url = '';
var $tpl_name = '';
var $mode;
var $sub;
/**
* Private methods, should not be overwritten
*/
function create($module_type, $module_url, $selected_mod = false, $selected_submod = false)
{
global $db, $config, $phpEx, $phpbb_root_path;
$module = array();
// Grab module information using Bart's "neat-o-module" system (tm)
$dir = @opendir('.');
if (!$dir)
{
$this->error('Unable to access the installation directory', __LINE__, __FILE__);
}
$setmodules = 1;
while (($file = readdir($dir)) !== false)
{
if (preg_match('#^install_(.*?)\.' . $phpEx . '$#', $file))
{
include($file);
}
}
closedir($dir);
unset($setmodules);
if (!sizeof($module))
{
$this->error('No installation modules found', __LINE__, __FILE__);
}
// Order to use and count further if modules get assigned to the same position or not having an order
$max_module_order = 1000;
foreach ($module as $row)
{
// Check any module pre-reqs
if ($row['module_reqs'] != '')
{
}
// Module order not specified or module already assigned at this position?
if (!isset($row['module_order']) || isset($this->module_ary[$row['module_order']]))
{
$row['module_order'] = $max_module_order;
$max_module_order++;
}
$this->module_ary[$row['module_order']]['name'] = $row['module_title'];
$this->module_ary[$row['module_order']]['filename'] = $row['module_filename'];
$this->module_ary[$row['module_order']]['subs'] = $row['module_subs'];
$this->module_ary[$row['module_order']]['stages'] = $row['module_stages'];
if (strtolower($selected_mod) == strtolower($row['module_title']))
{
$this->id = (int) $row['module_order'];
$this->filename = (string) $row['module_filename'];
$this->module_url = (string) $module_url;
$this->mode = (string) $selected_mod;
// Check that the sub-mode specified is valid or set a default if not
if (is_array($row['module_subs']))
{
$this->sub = strtolower((in_array(strtoupper($selected_submod), $row['module_subs'])) ? $selected_submod : $row['module_subs'][0]);
}
else if (is_array($row['module_stages']))
{
$this->sub = strtolower((in_array(strtoupper($selected_submod), $row['module_stages'])) ? $selected_submod : $row['module_stages'][0]);
}
else
{
$this->sub = '';
}
}
} // END foreach
} // END create
/**
* Load and run the relevant module if applicable
*/
function load($mode = false, $run = true)
{
global $phpbb_root_path, $phpEx;
if ($run)
{
if (!empty($mode))
{
$this->mode = $mode;
}
$module = $this->filename;
if (!class_exists($module))
{
$this->error('Module "' . htmlspecialchars($module) . '" not accessible.', __LINE__, __FILE__);
}
$this->module = new $module($this);
if (method_exists($this->module, 'main'))
{
$this->module->main($this->mode, $this->sub);
}
}
}
/**
* Output the standard page header
*/
function page_header()
{
if (defined('HEADER_INC'))
{
return;
}
define('HEADER_INC', true);
global $template, $user, $stage, $phpbb_root_path;
$template->assign_vars(array(
'L_CHANGE' => $user->lang['CHANGE'],
'L_INSTALL_PANEL' => $user->lang['INSTALL_PANEL'],
'L_SELECT_LANG' => $user->lang['SELECT_LANG'],
'L_SKIP' => $user->lang['SKIP'],
'PAGE_TITLE' => $this->get_page_title(),
'T_IMAGE_PATH' => $phpbb_root_path . 'adm/images/',
'S_CONTENT_DIRECTION' => $user->lang['DIRECTION'],
'S_CONTENT_FLOW_BEGIN' => ($user->lang['DIRECTION'] == 'ltr') ? 'left' : 'right',
'S_CONTENT_FLOW_END' => ($user->lang['DIRECTION'] == 'ltr') ? 'right' : 'left',
'S_CONTENT_ENCODING' => 'UTF-8',
'S_USER_LANG' => $user->lang['USER_LANG'],
)
);
header('Content-type: text/html; charset=UTF-8');
header('Cache-Control: private, no-cache="set-cookie"');
header('Expires: 0');
header('Pragma: no-cache');
return;
}
/**
* Output the standard page footer
*/
function page_footer()
{
global $db, $template;
$template->display('body');
// Close our DB connection.
if (!empty($db) && is_object($db))
{
$db->sql_close();
}
if (function_exists('exit_handler'))
{
exit_handler();
}
}
/**
* Returns desired template name
*/
function get_tpl_name()
{
return $this->module->tpl_name . '.html';
}
/**
* Returns the desired page title
*/
function get_page_title()
{
global $user;
if (!isset($this->module->page_title))
{
return '';
}
return (isset($user->lang[$this->module->page_title])) ? $user->lang[$this->module->page_title] : $this->module->page_title;
}
/**
* Generate the navigation tabs
*/
function generate_navigation()
{
global $user, $template, $phpEx, $language;
if (is_array($this->module_ary))
{
@ksort($this->module_ary);
foreach ($this->module_ary as $cat_ary)
{
$cat = $cat_ary['name'];
$l_cat = (!empty($user->lang['CAT_' . $cat])) ? $user->lang['CAT_' . $cat] : preg_replace('#_#', ' ', $cat);
$cat = strtolower($cat);
$url = $this->module_url . "?mode=$cat";
if ($this->mode == $cat)
{
$template->assign_block_vars('t_block1', array(
'L_TITLE' => $l_cat,
'S_SELECTED' => true,
'U_TITLE' => $url,
));
if (is_array($this->module_ary[$this->id]['subs']))
{
$subs = $this->module_ary[$this->id]['subs'];
foreach ($subs as $option)
{
$l_option = (!empty($user->lang['SUB_' . $option])) ? $user->lang['SUB_' . $option] : preg_replace('#_#', ' ', $option);
$option = strtolower($option);
$url = $this->module_url . '?mode=' . $this->mode . "&sub=$option";
$template->assign_block_vars('l_block1', array(
'L_TITLE' => $l_option,
'S_SELECTED' => ($this->sub == $option),
'U_TITLE' => $url,
));
}
}
if (is_array($this->module_ary[$this->id]['stages']))
{
$subs = $this->module_ary[$this->id]['stages'];
$matched = false;
foreach ($subs as $option)
{
$l_option = (!empty($user->lang['STAGE_' . $option])) ? $user->lang['STAGE_' . $option] : preg_replace('#_#', ' ', $option);
$option = strtolower($option);
$matched = ($this->sub == $option) ? true : $matched;
$template->assign_block_vars('l_block2', array(
'L_TITLE' => $l_option,
'S_SELECTED' => ($this->sub == $option),
'S_COMPLETE' => !$matched,
));
}
}
}
else
{
$template->assign_block_vars('t_block1', array(
'L_TITLE' => $l_cat,
'S_SELECTED' => false,
'U_TITLE' => $url,
));
}
}
}
}
/**
* Output an error message
* If skip is true, return and continue execution, else exit
*/
function error($error, $line, $file, $skip = false)
{
global $lang, $db, $template;
if ($skip)
{
$template->assign_block_vars('checks', array(
'S_LEGEND' => true,
'LEGEND' => $lang['INST_ERR'],
));
$template->assign_block_vars('checks', array(
'TITLE' => basename($file) . ' [ ' . $line . ' ]',
'RESULT' => '<b style="color:red">' . $error . '</b>',
));
return;
}
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
echo '<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">';
echo '<head>';
echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
echo '<title>' . $lang['INST_ERR_FATAL'] . '</title>';
echo '<link href="../adm/style/admin.css" rel="stylesheet" type="text/css" media="screen" />';
echo '</head>';
echo '<body id="errorpage">';
echo '<div id="wrap">';
echo ' <div id="page-header">';
echo ' </div>';
echo ' <div id="page-body">';
echo ' <div id="acp">';
echo ' <div class="panel">';
echo ' <span class="corners-top"><span></span></span>';
echo ' <div id="content">';
echo ' <h1>' . $lang['INST_ERR_FATAL'] . '</h1>';
echo ' <p>' . $lang['INST_ERR_FATAL'] . "</p>\n";
echo ' <p>' . basename($file) . ' [ ' . $line . " ]</p>\n";
echo ' <p><b>' . $error . "</b></p>\n";
echo ' </div>';
echo ' <span class="corners-bottom"><span></span></span>';
echo ' </div>';
echo ' </div>';
echo ' </div>';
echo ' <div id="page-footer">';
echo ' Powered by phpBB © 2000, 2002, 2005, 2007 <a href="http://www.phpbb.com/">phpBB Group</a>';
echo ' </div>';
echo '</div>';
echo '</body>';
echo '</html>';
if (!empty($db) && is_object($db))
{
$db->sql_close();
}
exit_handler();
}
/**
* Generate the relevant HTML for an input field and the associated label and explanatory text
*/
function input_field($name, $type, $value='', $options='')
{
global $user;
$tpl_type = explode(':', $type);
$tpl = '';
switch ($tpl_type[0])
{
case 'text':
case 'password':
$size = (int) $tpl_type[1];
$maxlength = (int) $tpl_type[2];
$tpl = '<input id="' . $name . '" type="' . $tpl_type[0] . '"' . (($size) ? ' size="' . $size . '"' : '') . ' maxlength="' . (($maxlength) ? $maxlength : 255) . '" name="' . $name . '" value="' . $value . '" />';
break;
case 'textarea':
$rows = (int) $tpl_type[1];
$cols = (int) $tpl_type[2];
$tpl = '<textarea id="' . $name . '" name="' . $name . '" rows="' . $rows . '" cols="' . $cols . '">' . $value . '</textarea>';
break;
case 'radio':
$key_yes = ($value) ? ' checked="checked" id="' . $name . '"' : '';
$key_no = (!$value) ? ' checked="checked" id="' . $name . '"' : '';
$tpl_type_cond = explode('_', $tpl_type[1]);
$type_no = ($tpl_type_cond[0] == 'disabled' || $tpl_type_cond[0] == 'enabled') ? false : true;
$tpl_no = '<label><input type="radio" name="' . $name . '" value="0"' . $key_no . ' class="radio" /> ' . (($type_no) ? $user->lang['NO'] : $user->lang['DISABLED']) . '</label>';
$tpl_yes = '<label><input type="radio" name="' . $name . '" value="1"' . $key_yes . ' class="radio" /> ' . (($type_no) ? $user->lang['YES'] : $user->lang['ENABLED']) . '</label>';
$tpl = ($tpl_type_cond[0] == 'yes' || $tpl_type_cond[0] == 'enabled') ? $tpl_yes . ' ' . $tpl_no : $tpl_no . ' ' . $tpl_yes;
break;
case 'select':
eval('$s_options = ' . str_replace('{VALUE}', $value, $options) . ';');
$tpl = '<select id="' . $name . '" name="' . $name . '">' . $s_options . '</select>';
break;
case 'custom':
eval('$tpl = ' . str_replace('{VALUE}', $value, $options) . ';');
break;
default:
break;
}
return $tpl;
}
}
?>
|
gpl-2.0
|
RedBilled/pcsc4java-framework
|
src/fr/redbilled/pcscforjava/CommandAPDU.java
|
22242
|
/*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package fr.redbilled.pcscforjava;
import java.util.Arrays;
import java.nio.ByteBuffer;
/**
* A command APDU following the structure defined in ISO/IEC 7816-4.
* It consists of a four byte header and a conditional body of variable length.
* This class does not attempt to verify that the APDU encodes a semantically
* valid command.
*
* <p>Note that when the expected length of the response APDU is specified
* in the {@linkplain #CommandAPDU(int,int,int,int,int) constructors},
* the actual length (Ne) must be specified, not its
* encoded form (Le). Similarly, {@linkplain #getNe} returns the actual
* value Ne. In other words, a value of 0 means "no data in the response APDU"
* rather than "maximum length."
*
* <p>This class supports both the short and extended forms of length
* encoding for Ne and Nc. However, note that not all terminals and Smart Cards
* are capable of accepting APDUs that use the extended form.
*
* <p>For the header bytes CLA, INS, P1, and P2 the Java type <code>int</code>
* is used to represent the 8 bit unsigned values. In the constructors, only
* the 8 lowest bits of the <code>int</code> value specified by the application
* are significant. The accessor methods always return the byte as an unsigned
* value between 0 and 255.
*
* <p>Instances of this class are immutable. Where data is passed in or out
* via byte arrays, defensive cloning is performed.
*
* @see ResponseAPDU
* @see CardChannel#transmit CardChannel.transmit
*
* @since 1.6
* @author Andreas Sterbenz
* @author JSR 268 Expert Group
*/
public final class CommandAPDU implements java.io.Serializable {
private static final long serialVersionUID = 398698301286670877L;
private static final int MAX_APDU_SIZE = 65544;
/** @serial */
private byte[] apdu;
// value of nc
private transient int nc;
// value of ne
private transient int ne;
// index of start of data within the apdu array
private transient int dataOffset;
/**
* Constructs a CommandAPDU from a byte array containing the complete
* APDU contents (header and body).
*
* <p>Note that the apdu bytes are copied to protect against
* subsequent modification.
*
* @param apdu the complete command APDU
*
* @throws NullPointerException if apdu is null
* @throws IllegalArgumentException if apdu does not contain a valid
* command APDU
*/
public CommandAPDU(byte[] apdu) {
this.apdu = apdu.clone();
parse();
}
/**
* Constructs a CommandAPDU from a byte array containing the complete
* APDU contents (header and body). The APDU starts at the index
* <code>apduOffset</code> in the byte array and is <code>apduLength</code>
* bytes long.
*
* <p>Note that the apdu bytes are copied to protect against
* subsequent modification.
*
* @param apdu the complete command APDU
* @param apduOffset the offset in the byte array at which the apdu
* data begins
* @param apduLength the length of the APDU
*
* @throws NullPointerException if apdu is null
* @throws IllegalArgumentException if apduOffset or apduLength are
* negative or if apduOffset + apduLength are greater than apdu.length,
* or if the specified bytes are not a valid APDU
*/
public CommandAPDU(byte[] apdu, int apduOffset, int apduLength) {
checkArrayBounds(apdu, apduOffset, apduLength);
this.apdu = new byte[apduLength];
System.arraycopy(apdu, apduOffset, this.apdu, 0, apduLength);
parse();
}
private void checkArrayBounds(byte[] b, int ofs, int len) {
if ((ofs < 0) || (len < 0)) {
throw new IllegalArgumentException
("Offset and length must not be negative");
}
if (b == null) {
if ((ofs != 0) && (len != 0)) {
throw new IllegalArgumentException
("offset and length must be 0 if array is null");
}
} else {
if (ofs > b.length - len) {
throw new IllegalArgumentException
("Offset plus length exceed array size");
}
}
}
/**
* Creates a CommandAPDU from the ByteBuffer containing the complete APDU
* contents (header and body).
* The buffer's <code>position</code> must be set to the start of the APDU,
* its <code>limit</code> to the end of the APDU. Upon return, the buffer's
* <code>position</code> is equal to its limit; its limit remains unchanged.
*
* <p>Note that the data in the ByteBuffer is copied to protect against
* subsequent modification.
*
* @param apdu the ByteBuffer containing the complete APDU
*
* @throws NullPointerException if apdu is null
* @throws IllegalArgumentException if apdu does not contain a valid
* command APDU
*/
public CommandAPDU(ByteBuffer apdu) {
this.apdu = new byte[apdu.remaining()];
apdu.get(this.apdu);
parse();
}
/**
* Constructs a CommandAPDU from the four header bytes. This is case 1
* in ISO 7816, no command body.
*
* @param cla the class byte CLA
* @param ins the instruction byte INS
* @param p1 the parameter byte P1
* @param p2 the parameter byte P2
*/
public CommandAPDU(int cla, int ins, int p1, int p2) {
this(cla, ins, p1, p2, null, 0, 0, 0);
}
/**
* Constructs a CommandAPDU from the four header bytes and the expected
* response data length. This is case 2 in ISO 7816, empty command data
* field with Ne specified. If Ne is 0, the APDU is encoded as ISO 7816
* case 1.
*
* @param cla the class byte CLA
* @param ins the instruction byte INS
* @param p1 the parameter byte P1
* @param p2 the parameter byte P2
* @param ne the maximum number of expected data bytes in a response APDU
*
* @throws IllegalArgumentException if ne is negative or greater than
* 65536
*/
public CommandAPDU(int cla, int ins, int p1, int p2, int ne) {
this(cla, ins, p1, p2, null, 0, 0, ne);
}
/**
* Constructs a CommandAPDU from the four header bytes and command data.
* This is case 3 in ISO 7816, command data present and Ne absent. The
* value Nc is taken as data.length. If <code>data</code> is null or
* its length is 0, the APDU is encoded as ISO 7816 case 1.
*
* <p>Note that the data bytes are copied to protect against
* subsequent modification.
*
* @param cla the class byte CLA
* @param ins the instruction byte INS
* @param p1 the parameter byte P1
* @param p2 the parameter byte P2
* @param data the byte array containing the data bytes of the command body
*
* @throws IllegalArgumentException if data.length is greater than 65535
*/
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data) {
this(cla, ins, p1, p2, data, 0, arrayLength(data), 0);
}
/**
* Constructs a CommandAPDU from the four header bytes and command data.
* This is case 3 in ISO 7816, command data present and Ne absent. The
* value Nc is taken as dataLength. If <code>dataLength</code>
* is 0, the APDU is encoded as ISO 7816 case 1.
*
* <p>Note that the data bytes are copied to protect against
* subsequent modification.
*
* @param cla the class byte CLA
* @param ins the instruction byte INS
* @param p1 the parameter byte P1
* @param p2 the parameter byte P2
* @param data the byte array containing the data bytes of the command body
* @param dataOffset the offset in the byte array at which the data
* bytes of the command body begin
* @param dataLength the number of the data bytes in the command body
*
* @throws NullPointerException if data is null and dataLength is not 0
* @throws IllegalArgumentException if dataOffset or dataLength are
* negative or if dataOffset + dataLength are greater than data.length
* or if dataLength is greater than 65535
*/
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data,
int dataOffset, int dataLength) {
this(cla, ins, p1, p2, data, dataOffset, dataLength, 0);
}
/**
* Constructs a CommandAPDU from the four header bytes, command data,
* and expected response data length. This is case 4 in ISO 7816,
* command data and Ne present. The value Nc is taken as data.length
* if <code>data</code> is non-null and as 0 otherwise. If Ne or Nc
* are zero, the APDU is encoded as case 1, 2, or 3 per ISO 7816.
*
* <p>Note that the data bytes are copied to protect against
* subsequent modification.
*
* @param cla the class byte CLA
* @param ins the instruction byte INS
* @param p1 the parameter byte P1
* @param p2 the parameter byte P2
* @param data the byte array containing the data bytes of the command body
* @param ne the maximum number of expected data bytes in a response APDU
*
* @throws IllegalArgumentException if data.length is greater than 65535
* or if ne is negative or greater than 65536
*/
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data, int ne) {
this(cla, ins, p1, p2, data, 0, arrayLength(data), ne);
}
private static int arrayLength(byte[] b) {
return (b != null) ? b.length : 0;
}
/**
* Command APDU encoding options:
*
* case 1: |CLA|INS|P1 |P2 | len = 4
* case 2s: |CLA|INS|P1 |P2 |LE | len = 5
* case 3s: |CLA|INS|P1 |P2 |LC |...BODY...| len = 6..260
* case 4s: |CLA|INS|P1 |P2 |LC |...BODY...|LE | len = 7..261
* case 2e: |CLA|INS|P1 |P2 |00 |LE1|LE2| len = 7
* case 3e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...| len = 8..65542
* case 4e: |CLA|INS|P1 |P2 |00 |LC1|LC2|...BODY...|LE1|LE2| len =10..65544
*
* LE, LE1, LE2 may be 0x00.
* LC must not be 0x00 and LC1|LC2 must not be 0x00|0x00
*/
private void parse() {
if (apdu.length < 4) {
throw new IllegalArgumentException("apdu must be at least 4 bytes long");
}
if (apdu.length == 4) {
// case 1
return;
}
int l1 = apdu[4] & 0xff;
if (apdu.length == 5) {
// case 2s
this.ne = (l1 == 0) ? 256 : l1;
return;
}
if (l1 != 0) {
if (apdu.length == 4 + 1 + l1) {
// case 3s
this.nc = l1;
this.dataOffset = 5;
return;
} else if (apdu.length == 4 + 2 + l1) {
// case 4s
this.nc = l1;
this.dataOffset = 5;
int l2 = apdu[apdu.length - 1] & 0xff;
this.ne = (l2 == 0) ? 256 : l2;
return;
} else {
throw new IllegalArgumentException
("Invalid APDU: length=" + apdu.length + ", b1=" + l1);
}
}
if (apdu.length < 7) {
throw new IllegalArgumentException
("Invalid APDU: length=" + apdu.length + ", b1=" + l1);
}
int l2 = ((apdu[5] & 0xff) << 8) | (apdu[6] & 0xff);
if (apdu.length == 7) {
// case 2e
this.ne = (l2 == 0) ? 65536 : l2;
return;
}
if (l2 == 0) {
throw new IllegalArgumentException("Invalid APDU: length="
+ apdu.length + ", b1=" + l1 + ", b2||b3=" + l2);
}
if (apdu.length == 4 + 3 + l2) {
// case 3e
this.nc = l2;
this.dataOffset = 7;
return;
} else if (apdu.length == 4 + 5 + l2) {
// case 4e
this.nc = l2;
this.dataOffset = 7;
int leOfs = apdu.length - 2;
int l3 = ((apdu[leOfs] & 0xff) << 8) | (apdu[leOfs + 1] & 0xff);
this.ne = (l3 == 0) ? 65536 : l3;
} else {
throw new IllegalArgumentException("Invalid APDU: length="
+ apdu.length + ", b1=" + l1 + ", b2||b3=" + l2);
}
}
/**
* Constructs a CommandAPDU from the four header bytes, command data,
* and expected response data length. This is case 4 in ISO 7816,
* command data and Le present. The value Nc is taken as
* <code>dataLength</code>.
* If Ne or Nc
* are zero, the APDU is encoded as case 1, 2, or 3 per ISO 7816.
*
* <p>Note that the data bytes are copied to protect against
* subsequent modification.
*
* @param cla the class byte CLA
* @param ins the instruction byte INS
* @param p1 the parameter byte P1
* @param p2 the parameter byte P2
* @param data the byte array containing the data bytes of the command body
* @param dataOffset the offset in the byte array at which the data
* bytes of the command body begin
* @param dataLength the number of the data bytes in the command body
* @param ne the maximum number of expected data bytes in a response APDU
*
* @throws NullPointerException if data is null and dataLength is not 0
* @throws IllegalArgumentException if dataOffset or dataLength are
* negative or if dataOffset + dataLength are greater than data.length,
* or if ne is negative or greater than 65536,
* or if dataLength is greater than 65535
*/
public CommandAPDU(int cla, int ins, int p1, int p2, byte[] data,
int dataOffset, int dataLength, int ne) {
checkArrayBounds(data, dataOffset, dataLength);
if (dataLength > 65535) {
throw new IllegalArgumentException("dataLength is too large");
}
if (ne < 0) {
throw new IllegalArgumentException("ne must not be negative");
}
if (ne > 65536) {
throw new IllegalArgumentException("ne is too large");
}
this.ne = ne;
this.nc = dataLength;
if (dataLength == 0) {
if (ne == 0) {
// case 1
this.apdu = new byte[4];
setHeader(cla, ins, p1, p2);
} else {
// case 2s or 2e
if (ne <= 256) {
// case 2s
// 256 is encoded as 0x00
byte len = (ne != 256) ? (byte)ne : 0;
this.apdu = new byte[5];
setHeader(cla, ins, p1, p2);
this.apdu[4] = len;
} else {
// case 2e
byte l1, l2;
// 65536 is encoded as 0x00 0x00
if (ne == 65536) {
l1 = 0;
l2 = 0;
} else {
l1 = (byte)(ne >> 8);
l2 = (byte)ne;
}
this.apdu = new byte[7];
setHeader(cla, ins, p1, p2);
this.apdu[5] = l1;
this.apdu[6] = l2;
}
}
} else {
if (ne == 0) {
// case 3s or 3e
if (dataLength <= 255) {
// case 3s
apdu = new byte[4 + 1 + dataLength];
setHeader(cla, ins, p1, p2);
apdu[4] = (byte)dataLength;
this.dataOffset = 5;
System.arraycopy(data, dataOffset, apdu, 5, dataLength);
} else {
// case 3e
apdu = new byte[4 + 3 + dataLength];
setHeader(cla, ins, p1, p2);
apdu[4] = 0;
apdu[5] = (byte)(dataLength >> 8);
apdu[6] = (byte)dataLength;
this.dataOffset = 7;
System.arraycopy(data, dataOffset, apdu, 7, dataLength);
}
} else {
// case 4s or 4e
if ((dataLength <= 255) && (ne <= 256)) {
// case 4s
apdu = new byte[4 + 2 + dataLength];
setHeader(cla, ins, p1, p2);
apdu[4] = (byte)dataLength;
this.dataOffset = 5;
System.arraycopy(data, dataOffset, apdu, 5, dataLength);
apdu[apdu.length - 1] = (ne != 256) ? (byte)ne : 0;
} else {
// case 4e
apdu = new byte[4 + 5 + dataLength];
setHeader(cla, ins, p1, p2);
apdu[4] = 0;
apdu[5] = (byte)(dataLength >> 8);
apdu[6] = (byte)dataLength;
this.dataOffset = 7;
System.arraycopy(data, dataOffset, apdu, 7, dataLength);
if (ne != 65536) {
int leOfs = apdu.length - 2;
apdu[leOfs] = (byte)(ne >> 8);
apdu[leOfs + 1] = (byte)ne;
} // else le == 65536: no need to fill in, encoded as 0
}
}
}
}
private void setHeader(int cla, int ins, int p1, int p2) {
apdu[0] = (byte)cla;
apdu[1] = (byte)ins;
apdu[2] = (byte)p1;
apdu[3] = (byte)p2;
}
/**
* Returns the value of the class byte CLA.
*
* @return the value of the class byte CLA.
*/
public int getCLA() {
return apdu[0] & 0xff;
}
/**
* Returns the value of the instruction byte INS.
*
* @return the value of the instruction byte INS.
*/
public int getINS() {
return apdu[1] & 0xff;
}
/**
* Returns the value of the parameter byte P1.
*
* @return the value of the parameter byte P1.
*/
public int getP1() {
return apdu[2] & 0xff;
}
/**
* Returns the value of the parameter byte P2.
*
* @return the value of the parameter byte P2.
*/
public int getP2() {
return apdu[3] & 0xff;
}
/**
* Returns the number of data bytes in the command body (Nc) or 0 if this
* APDU has no body. This call is equivalent to
* <code>getData().length</code>.
*
* @return the number of data bytes in the command body or 0 if this APDU
* has no body.
*/
public int getNc() {
return nc;
}
/**
* Returns a copy of the data bytes in the command body. If this APDU as
* no body, this method returns a byte array with length zero.
*
* @return a copy of the data bytes in the command body or the empty
* byte array if this APDU has no body.
*/
public byte[] getData() {
byte[] data = new byte[nc];
System.arraycopy(apdu, dataOffset, data, 0, nc);
return data;
}
/**
* Returns the maximum number of expected data bytes in a response
* APDU (Ne).
*
* @return the maximum number of expected data bytes in a response APDU.
*/
public int getNe() {
return ne;
}
/**
* Returns a copy of the bytes in this APDU.
*
* @return a copy of the bytes in this APDU.
*/
public byte[] getBytes() {
return apdu.clone();
}
/**
* Returns a string representation of this command APDU.
*
* @return a String representation of this command APDU.
*/
public String toString() {
return "CommmandAPDU: " + apdu.length + " bytes, nc=" + nc + ", ne=" + ne;
}
/**
* Compares the specified object with this command APDU for equality.
* Returns true if the given object is also a CommandAPDU and its bytes are
* identical to the bytes in this CommandAPDU.
*
* @param obj the object to be compared for equality with this command APDU
* @return true if the specified object is equal to this command APDU
*/
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof CommandAPDU == false) {
return false;
}
CommandAPDU other = (CommandAPDU)obj;
return Arrays.equals(this.apdu, other.apdu);
}
/**
* Returns the hash code value for this command APDU.
*
* @return the hash code value for this command APDU.
*/
public int hashCode() {
return Arrays.hashCode(apdu);
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
apdu = (byte[])in.readUnshared();
// initialize transient fields
parse();
}
}
|
gpl-2.0
|
AL20/SRCL
|
page-engagements.php
|
1021
|
<?php
/*
Template Name: Page Engagements
*/
$context = Timber::get_context();
include 'templates/utils/setSession.php';
//include fucntion to determine current url (data -> $context['current_url'])
include 'templates/utils/getCurrentUrl.php';
$context['title'] = get_the_title();
$context['texte_intro'] = get_field('texte_intro');
$context['titre_engagements'] = get_field('titre_engagements');
// get engagements
$args = array(
'post_type' => 'engagement',
'orderby' => 'publish_date',
'order' => 'ASC',
'posts_per_page' => '-1',
);
$context['engagements'] = Timber::get_posts($args);
// contexte for swiper lsit container
$context['swiper_contexte'] = 'swiper-page-engagement';
// texte infos after methodes list container
$context['texte_infos'] = get_field('texte_infos');
// variables for cta components
$context['active_cta'] = get_field('cta_page_engagements', 'options');
//render templates
Timber::render('pages/page-engagements.twig', $context);
|
gpl-2.0
|
jcitysinner/eggman
|
wp-content/themes/EggMan/_inc/cpt_items.php
|
2624
|
<?php
function register_cpt_items(){
$singularname = 'Item';
$pluralname = 'Items';
$slug = 'items';
$labels = array(
'name' => __($pluralname),
'singular_name' => __($singularname),
'add_new' => __('Add New '.$singularname),
'add_new_item' => __('Add New '. $singularname),
'edit_item' => __('Edit '. $singularname),
'new_item' => __('New '.$singularname),
'view_item' => __('View '.$singularname),
'search_items' => __('Search '.$pluralname)
);
$args = array(
'labels' => $labels,
'description' => 'profile',
'public' => true,
'hierarchical' => false,
'menu_icon' => 'dashicons-carrot',
'supports' => array( 'title', 'editor', 'thumbnail', 'custom-fields'),
'has_archive' => false
);
register_post_type( 'items', $args );
}
add_action( 'init', 'register_cpt_items' );
require_once ( 'items/_metaboxes.php' );
require_once ( 'items/_menu_function.php' );
/* ---------------------------------
Images in Admin
--------------------------------- */
function set_edit_items_columns( $columns ) {
unset( $columns[ 'author' ] );
unset( $columns[ 'date' ] );
return array_merge( $columns, array(
'image' => __( 'Hero Image' ),
'image2' => __( 'Secondary Image' ),
'active' => __( 'Active' )
) );
}
add_filter( 'manage_edit-items_columns', 'set_edit_items_columns' );
add_action( 'manage_posts_custom_column', 'custom_columns' );
function custom_columns( $column ) {
global $post;
switch ( $column ) {
case 'image':
$post_meta_data = get_post_custom( $post->ID );
$custom_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size = 'thumbnail', $icon = false )[0];
echo '<img src="'.$custom_image.'"/>';
break;
case 'image2':
$post_meta_data = get_post_custom( $post->ID );
$custom_image = $post_meta_data[ 'items_money' ][0];
echo '<img src="'.$custom_image.'"/>';
break;
case 'active':
$post_meta_data = get_post_custom( $post->ID );
$custom_image = $post_meta_data[ 'items_show' ];
if ($custom_image) {
if (in_array("on", $custom_image)) {
echo "✔";
}
}
break;
} //$column
}
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
echo '<style>
.image2.column-image2 img,
.image.column-image img {
max-width: 100px;
}
</style>';
}
?>
|
gpl-2.0
|
hanslovsky/bigcat
|
src/main/java/bdv/bigcat/BigCatDvidViewer.java
|
9328
|
package bdv.bigcat;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.scijava.ui.behaviour.io.InputTriggerConfig;
import org.scijava.ui.behaviour.io.InputTriggerDescription;
import org.scijava.ui.behaviour.io.yaml.YamlConfigIO;
import org.scijava.ui.behaviour.util.TriggerBehaviourBindings;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import bdv.bigcat.composite.ARGBCompositeAlphaYCbCr;
import bdv.bigcat.composite.Composite;
import bdv.bigcat.composite.CompositeCopy;
import bdv.bigcat.control.ConfirmSegmentController;
import bdv.bigcat.control.MergeController;
import bdv.bigcat.control.SelectionController;
import bdv.bigcat.control.TranslateZController;
import bdv.bigcat.label.FragmentAssignment;
import bdv.bigcat.label.FragmentSegmentAssignment;
import bdv.bigcat.label.LabelMultiSetIdPicker;
import bdv.bigcat.ui.ARGBConvertedLabelsSource;
import bdv.bigcat.ui.ModalGoldenAngleSaturatedARGBStream;
import bdv.bigcat.ui.Util;
import bdv.img.SetCache;
import bdv.img.dvid.LabelblkMultisetSetupImageLoader;
import bdv.img.dvid.Uint8blkImageLoader;
import bdv.labels.labelset.LabelMultisetType;
import bdv.util.LocalIdService;
import bdv.util.dvid.DatasetKeyValue;
import net.imglib2.interpolation.randomaccess.NearestNeighborInterpolatorFactory;
import net.imglib2.realtransform.RealViews;
import net.imglib2.type.numeric.ARGBType;
import net.imglib2.view.Views;
public class BigCatDvidViewer extends BigCatViewer< BigCatDvidViewer.Parameters >
{
static public class Parameters extends BigCatViewer.Parameters
{
@Parameter( names = { "--url" }, description = "URL" )
public String url = "";
@Parameter( names = { "--uuid" }, description = "UUID" )
public String uuid = "";
public Parameters()
{
raws = Arrays.asList( new String[] { "grayscale" } );
labels = null;
assignment = null;
}
}
/** raw pixels (image data) */
final protected ArrayList< Uint8blkImageLoader > raws = new ArrayList<>();
/** loaded segments */
final protected ArrayList< LabelblkMultisetSetupImageLoader > labels = new ArrayList<>();
public static void main( final String[] args ) throws Exception
{
final Parameters params = new Parameters();
new JCommander( params, args );
params.init();
final BigCatDvidViewer bigCat = new BigCatDvidViewer();
bigCat.init( params );
bigCat.setupBdv( params );
}
public BigCatDvidViewer() throws Exception
{
Util.initUI();
this.config = getInputTriggerConfig();
}
/**
* Load raw data and labels and initialize canvas
*
* @param params
* @throws IOException
*/
@Override
protected void initRaw( final Parameters params ) throws IOException
{
System.out.println( "Opening raw from " + params.url );
/* raw pixels */
for ( final String raw : params.raws )
{
final Uint8blkImageLoader rawLoader = new Uint8blkImageLoader(
params.url,
params.uuid,
raw);
raws.add( rawLoader );
}
}
/**
* Initialize ID service.
*
* @param params
* @throws IOException
*/
@Override
protected void initIdService( final Parameters params ) throws IOException
{
/* id */
idService = new LocalIdService();
}
/**
* Initialize assignments.
*
* @param params
*/
@Override
protected void initAssignments( final Parameters params )
{
/* fragment segment assignment */
assignment = new FragmentSegmentAssignment( idService );
/* complete fragments */
completeFragmentsAssignment = new FragmentAssignment();
/* color stream */
colorStream = new ModalGoldenAngleSaturatedARGBStream( assignment );
colorStream.setAlpha( 0x20 );
}
/**
* Load labels and create label+canvas compositions.
*
* @param params
* @throws IOException
*/
@Override
protected void initLabels( final Parameters params ) throws IOException
{
if ( params.labels != null && params.labels.size() > 0 )
{
System.out.println( "Opening labels from " + params.url );
// final Server server = new Server( params.url );
// final Repository repo = new Repository( server, params.uuid );
final double[][] resolutions = new double[][]{ { 1, 1, 1 } };
/* labels */
for ( final String label : params.labels )
{
/* labels */
// final DatasetKeyValue datasetKeyValue = new DatasetKeyValue( repo.getRootNode(), label );
final LabelblkMultisetSetupImageLoader labelLoader = new LabelblkMultisetSetupImageLoader(
setupId++,
params.url,
params.uuid,
label,
resolutions,
// new DatasetKeyValue[]{ datasetKeyValue } );
new DatasetKeyValue[ 0 ] );
/* converted labels */
final ARGBConvertedLabelsSource convertedLabelsSource =
new ARGBConvertedLabelsSource(
setupId++,
labelLoader,
colorStream );
labels.add( labelLoader );
convertedLabels.add( convertedLabelsSource );
}
}
}
/**
* Create tool.
*
* Depends on {@link #raws}, {@link #labels},
* {@link #convertedLabelCanvasPairs}, {@link #colorStream},
* {@link #idService}, {@link #assignment},
* {@link #config}, {@link #dirtyLabelsInterval},
* {@link #completeFragmentsAssignment}, {@link #canvas} being initialized.
*
* Modifies {@link #bdv}, {@link #convertedLabelCanvasPairs},
* {@link #persistenceController},
*
* @param params
* @throws Exception
*/
@Override
protected void setupBdv( final Parameters params ) throws Exception
{
/* composites */
final ArrayList< Composite< ARGBType, ARGBType > > composites = new ArrayList<>();
final ArrayList< SetCache > cacheLoaders = new ArrayList<>();
for ( final Uint8blkImageLoader loader : raws )
{
composites.add( new CompositeCopy< ARGBType >() );
cacheLoaders.add( loader );
}
for ( final LabelblkMultisetSetupImageLoader loader : labels )
{
composites.add( new ARGBCompositeAlphaYCbCr() );
cacheLoaders.add( loader );
}
final String windowTitle = "BigCAT";
bdv = Util.createViewer(
windowTitle,
raws,
convertedLabels,
cacheLoaders,
composites,
config );
bdv.getViewerFrame().setVisible( true );
final TriggerBehaviourBindings bindings = bdv.getViewerFrame().getTriggerbindings();
final SelectionController selectionController;
final LabelMultiSetIdPicker idPicker;
if ( labels.size() > 0 )
{
/* TODO fix ID picker to pick from the top most label canvas pair */
idPicker = new LabelMultiSetIdPicker(
bdv.getViewer(),
RealViews.affineReal(
Views.interpolate(
Views.extendValue(
labels.get( 0 ).getImage( 0 ),
new LabelMultisetType() ),
new NearestNeighborInterpolatorFactory< LabelMultisetType >() ),
labels.get( 0 ).getMipmapTransforms()[ 0 ] ) );
selectionController = new SelectionController(
bdv.getViewer(),
idPicker,
colorStream,
idService,
assignment,
config,
bdv.getViewerFrame().getKeybindings(),
config);
final MergeController mergeController = new MergeController(
bdv.getViewer(),
idPicker,
selectionController,
assignment,
config,
bdv.getViewerFrame().getKeybindings(),
config);
/* mark segments as finished */
final ConfirmSegmentController confirmSegment = new ConfirmSegmentController(
bdv.getViewer(),
selectionController,
assignment,
colorStream,
colorStream,
config,
bdv.getViewerFrame().getKeybindings() );
bindings.addBehaviourMap( "select", selectionController.getBehaviourMap() );
bindings.addInputTriggerMap( "select", selectionController.getInputTriggerMap() );
bindings.addBehaviourMap( "merge", mergeController.getBehaviourMap() );
bindings.addInputTriggerMap( "merge", mergeController.getInputTriggerMap() );
}
else
{
selectionController = null;
idPicker = null;
}
/* override navigator z-step size with raw[ 0 ] z resolution */
final TranslateZController translateZController = new TranslateZController(
bdv.getViewer(),
raws.get( 0 ).getMipmapResolutions()[ 0 ],
config );
bindings.addBehaviourMap( "translate_z", translateZController.getBehaviourMap() );
if ( selectionController != null )
bdv.getViewer().getDisplay().addOverlayRenderer( selectionController.getSelectionOverlay() );
}
static protected InputTriggerConfig getInputTriggerConfig() throws IllegalArgumentException
{
final String[] filenames = { "bigcatkeyconfig.yaml", System.getProperty( "user.home" ) + "/.bdv/bigcatkeyconfig.yaml" };
for ( final String filename : filenames )
{
try
{
if ( new File( filename ).isFile() )
{
System.out.println( "reading key config from file " + filename );
return new InputTriggerConfig( YamlConfigIO.read( filename ) );
}
}
catch ( final IOException e )
{
System.err.println( "Error reading " + filename );
}
}
System.out.println( "creating default input trigger config" );
// default input trigger config, disables "control button1" drag in bdv
// (collides with default of "move annotation")
final InputTriggerConfig config =
new InputTriggerConfig(
Arrays.asList(
new InputTriggerDescription[] { new InputTriggerDescription( new String[] { "not mapped" }, "drag rotate slow", "bdv" ) } ) );
return config;
}
}
|
gpl-2.0
|
pongowu/in-class
|
wp-content/themes/simplest-theme/header.php
|
1062
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="A description about your site" />
<title><?php bloginfo('name'); ?> - <?php bloginfo('description'); ?></title>
<link rel="stylesheet" href="path/to/css/reset.css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url') ?>" media="screen" />
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php wp_head(); // hook necessary for plugin css and js to work. also gives the admin bar ?>
</head>
<body class="home">
<header>
<h1><a href="<?php echo home_url(); ?>"><?php bloginfo('name'); ?></a></h1>
<h2><?php bloginfo('description'); ?></h2>
<?php get_search_form(); ?>
<ul class="utilities">
<?php wp_list_pages( array(
'title_li' => '',
'include' => '2, 146',
) ); ?>
</ul>
<nav>
<ul class="nav">
<?php wp_list_pages( array(
'title_li' => '',
'depth' => 1,
'exclude' => '2, 146',
) ); ?>
</ul>
</nav>
</header>
|
gpl-2.0
|
kunj1988/Magento2
|
dev/tests/integration/testsuite/Magento/Customer/Block/Adminhtml/Edit/Tab/View/SalesTest.php
|
3181
|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Customer\Block\Adminhtml\Edit\Tab\View;
use Magento\Customer\Controller\RegistryConstants;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Class SalesTest
*
* @magentoAppArea adminhtml
*/
class SalesTest extends \PHPUnit\Framework\TestCase
{
const MAIN_WEBSITE = 1;
/**
* Sales block under test.
*
* @var Sales
*/
private $block;
/**
* Core registry.
*
* @var \Magento\Framework\Registry
*/
private $coreRegistry;
/**
* Sales order view Html.
*
* @var string
*/
private $html;
/**
* Execute per test initialization.
*/
public function setUp()
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('adminhtml');
$this->coreRegistry = $objectManager->get(\Magento\Framework\Registry::class);
$this->coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, 1);
$this->block = $objectManager->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Customer\Block\Adminhtml\Edit\Tab\View\Sales::class,
'sales_' . mt_rand(),
['coreRegistry' => $this->coreRegistry]
)->setTemplate(
'tab/view/sales.phtml'
);
$this->html = $this->block->toHtml();
}
/**
* Execute post test cleanup.
*/
public function tearDown()
{
$this->coreRegistry->unregister(RegistryConstants::CURRENT_CUSTOMER_ID);
$this->html = '';
}
/**
* Test basic currency formatting on the Main Website.
*/
public function testFormatCurrency()
{
$this->assertEquals(
'<span class="price">$10.00</span>',
$this->block->formatCurrency(10.00, self::MAIN_WEBSITE)
);
}
/**
* Verify that the website is not in single store mode.
*/
public function testIsSingleStoreMode()
{
$this->assertFalse($this->block->isSingleStoreMode());
}
/**
* Verify sales totals. No sales so there are no totals.
*/
public function testGetTotals()
{
$this->assertEquals(
['lifetime' => 0, 'base_lifetime' => 0, 'base_avgsale' => 0, 'num_orders' => 0],
$this->block->getTotals()->getData()
);
}
/**
* Verify that there are no rows in the sales order grid.
*/
public function testGetRows()
{
$this->assertEmpty($this->block->getRows());
}
/**
* Verify that the Main Website has no websites.
*/
public function testGetWebsiteCount()
{
$this->assertEquals(0, $this->block->getWebsiteCount(self::MAIN_WEBSITE));
}
/**
* Verify basic content of the sales view Html.
*/
public function testToHtml()
{
$this->assertContains('<span class="title">Sales Statistics</span>', $this->html);
$this->assertContains('<strong>All Store Views</strong>', $this->html);
}
}
|
gpl-2.0
|
itstriz/usda_foia_log_downloader
|
csv_cleaner.py
|
1250
|
import csv, re, sys
# Check if csv file is formatted right
def check_file(csv_list, needles):
first_cell = csv_list[0][0]
if ' '.join(first_cell.split()) in needles:
return True
return False
def find_good_row(csv_list, col_num):
counter = 0
for row in csv_list:
if row[col_num] in needles:
return counter
counter = counter + 1
return False
def load_csv(file_name):
csv_list = []
with open(file_name, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
csv_list.append(row)
return csv_list
file_name = sys.argv[1]
needles = ['Request ID', 'CASE NO.', 'CASENO', 'CASE NO']
csv_list = load_csv(file_name)
if not check_file(csv_list, needles):
# First row is bad, find the starting row
for i in range(0,len(csv_list[0])):
good_row = find_good_row(csv_list, i)
if good_row:
break
if good_row:
print 'Found good row at col %s row %s, attempting re-write' % (str(i), str(good_row))
f = csv.writer(open(file_name, 'wb'))
for line in csv_list[good_row:]:
f.writerow(line[i:])
else:
print '*** Could not find good row in file.\n\n'
|
gpl-2.0
|
secern/gfreader
|
src/org/vudroid/pdfdroid/codec/PdfContext.java
|
417
|
package org.vudroid.pdfdroid.codec;
import android.content.ContentResolver;
public class PdfContext
{
static
{
System.loadLibrary("vudroid");
}
public PdfDocument openDocument(String fileName)
{
return PdfDocument.openDocument(fileName, "");
}
public void setContentResolver(ContentResolver contentResolver)
{
//TODO
}
public void recycle() {
}
}
|
gpl-2.0
|
wclifton1/biohouston
|
wp-content/themes/philanthropy-child/tribe-events/widgets/list-widget.php
|
2135
|
<?php
/**
* Events List Widget Template
* This is the template for the output of the events list widget.
* All the items are turned on and off through the widget admin.
* There is currently no default styling, which is needed.
*
* This view contains the filters required to create an effective events list widget view.
*
* You can recreate an ENTIRELY new events list widget view by doing a template override,
* and placing a list-widget.php file in a tribe-events/widgets/ directory
* within your theme directory, which will override the /views/widgets/list-widget.php.
***DONE****
*
* You can use any or all filters included in this file or create your own filters in
* your functions.php. In order to modify or extend a single filter, please see our
* readme on templates hooks and filters (TO-DO)
*
* @return string
*
* @package TribeEventsCalendar
*
*/
if ( ! defined( 'ABSPATH' ) ) {
die( '-1' );
}
//Check if any posts were found
if ( $posts ) {
?>
<ol class="hfeed vcalendar">
<?php
foreach ( $posts as $post ) :
setup_postdata( $post );
?>
<li class="tribe-events-list-widget-events <?php tribe_events_event_classes() ?>">
<?php do_action( 'tribe_events_list_widget_before_the_event_title' ); ?>
<!-- Event Title -->
<h4 class="entry-title summary">
<a href="<?php echo tribe_get_event_link(); ?>" rel="bookmark"><?php the_title(); ?></a>
</h4>
<?php do_action( 'tribe_events_list_widget_after_the_event_title' ); ?>
<!-- Event Time -->
<?php do_action( 'tribe_events_list_widget_before_the_meta' ) ?>
<div class="duration">
<?php echo tribe_events_event_schedule_details(); ?>
</div>
<?php do_action( 'tribe_events_list_widget_after_the_meta' ) ?>
</li>
<?php
endforeach;
?>
</ol><!-- .hfeed -->
<p class="tribe-events-widget-link">
<a href="<?php echo tribe_get_events_link(); ?>" rel="bookmark"><?php _e( 'View All Events', 'tribe-events-calendar' ); ?></a>
</p>
<?php
//No Events were Found
} else {
?>
<p><?php _e( 'There are no upcoming events at this time.', 'tribe-events-calendar' ); ?></p>
<?php
}
?>
|
gpl-2.0
|
amadeusproject/amadeuslms
|
notifications/templatetags/notification_filters.py
|
4909
|
"""
Copyright 2016, 2017 UFPE - Universidade Federal de Pernambuco
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença.
Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENSE", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
"""
from django import template
from datetime import datetime
from django.utils import timezone, formats
from django.utils.translation import ugettext_lazy as _
from notifications.utils import get_resource_users
from notifications.models import Notification
register = template.Library()
@register.filter(name = 'warning_class')
def warning_class(level):
if level == 1:
class_name = "alert-low"
elif level == 2:
class_name = "alert-low"
elif level == 3:
class_name = "alert-medium"
else:
class_name = "alert-danger"
return class_name
@register.filter(name = 'warning_msg')
def warning_msg(level, isnt_student):
if level == 1:
if isnt_student:
msg = _('The student still did not realize this task')
else:
msg = _('You still did not realize this task')
elif level == 2:
if isnt_student:
msg = _('The student still did not realize this task')
else:
msg = _('You still did not realize this task')
elif level == 3:
msg = _('This task is late')
else:
if isnt_student:
msg = _('The student miss this task')
else:
msg = _('You miss this task')
return msg
@register.filter(name = 'viewed_msg')
def viewed_msg(aware):
if aware:
msg = _('Yes')
else:
msg = _('No')
return msg
@register.filter(name = 'done_percent')
def done_percent(notification):
users = get_resource_users(notification.task.resource)
notified = Notification.objects.filter(user__in = users.values_list('id', flat = True), creation_date = datetime.now(), task = notification.task).count()
number_users = users.count()
not_done = (notified * 100) / number_users
return 100 - not_done
@register.filter(name = 'order_icon_class')
def order_icon_class(request, column):
getvars = request.GET.copy()
order = None
class_name = "fa-sort"
if 'order_by' in getvars:
order = getvars['order_by']
if not order:
if column == "creation_date":
class_name = "fa-sort-desc"
else:
if column in order:
if "-" in order:
class_name = "fa-sort-desc"
else:
class_name = "fa-sort-asc"
return class_name
@register.filter(name = 'order_href')
def order_href(request, column):
getvars = request.GET.copy()
order_href = "-" + column
order = None
params = ""
if 'order_by' in getvars:
order = getvars['order_by']
del getvars['order_by']
if not order:
if column == "creation_date":
order_href = "creation_date"
else:
if column in order:
if "-" in order:
order_href = column
if len(getvars) > 0:
params = '&%s' % getvars.urlencode()
return "?order_by=" + order_href + params
@register.filter(name = 'add_student')
def add_student(request, student):
getvars = request.GET.copy()
params = ""
if not student is None:
if not student == "":
if 'selected_student' in getvars:
del getvars['selected_student']
getvars['selected_student'] = student
request.GET = getvars
return request
@register.filter(name = 'order_ajax')
def order_ajax(request, column):
getvars = request.GET.copy()
order_href = "-" + column
order = None
params = ""
if 'order_by' in getvars:
order = getvars['order_by']
del getvars['order_by']
if not order:
if column == "creation_date":
order_href = "creation_date"
else:
if column in order:
if "-" in order:
order_href = column
return order_href
@register.filter(name = 'observation')
def observation(notification):
msg = ''
if notification.level == 1:
if notification.meta:
msg = _('Goal defined to task realization: %s')%(formats.date_format(notification.meta.astimezone(timezone.get_current_timezone()), "SHORT_DATETIME_FORMAT"))
elif notification.level == 2:
if notification.meta:
if notification.meta < timezone.now():
msg = _('Goal defined to task realization: %s')%(formats.date_format(notification.meta.astimezone(timezone.get_current_timezone()), "SHORT_DATETIME_FORMAT"))
else:
msg = _('New goal defined to task realization: %s')%(formats.date_format(notification.meta.astimezone(timezone.get_current_timezone()), "SHORT_DATETIME_FORMAT"))
return msg
|
gpl-2.0
|
nickhargreaves/starreports
|
app/src/org/codeforafrica/starreports/facebook/FacebookLogin.java
|
939
|
package org.codeforafrica.starreports.facebook;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class FacebookLogin extends FragmentActivity{
private MainFragment mainFragment;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
|
gpl-2.0
|
stweil/glpi
|
front/slalevel.form.php
|
3157
|
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2022 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
use Glpi\Event;
include('../inc/includes.php');
$item = new SlaLevel();
if (isset($_POST["update"])) {
$item->check($_POST["id"], UPDATE);
$item->update($_POST);
Event::log(
$_POST["id"],
"slas",
4,
"setup",
//TRANS: %s is the user login
sprintf(__('%s updates a sla level'), $_SESSION["glpiname"])
);
Html::back();
} else if (isset($_POST["add"])) {
$item->check(-1, CREATE, $_POST);
if ($item->add($_POST)) {
Event::log(
$_POST["slas_id"],
"slas",
4,
"setup",
//TRANS: %s is the user login
sprintf(__('%s adds a link with an item'), $_SESSION["glpiname"])
);
if ($_SESSION['glpibackcreated']) {
Html::redirect($item->getLinkURL());
}
}
Html::back();
} else if (isset($_POST["purge"])) {
if (isset($_POST['id'])) {
$item->check($_POST['id'], PURGE);
if ($item->delete($_POST, 1)) {
Event::log(
$_POST["id"],
"slas",
4,
"setup",
//TRANS: %s is the user login
sprintf(__('%s purges a sla level'), $_SESSION["glpiname"])
);
}
$item->redirectToList();
}
Html::back();
} else if (isset($_POST["add_action"])) {
$item->check($_POST['slalevels_id'], UPDATE);
$action = new SlaLevelAction();
$action->add($_POST);
Html::back();
} else if (isset($_POST["add_criteria"])) {
$item->check($_POST['slalevels_id'], UPDATE);
$criteria = new SlaLevelCriteria();
$criteria->add($_POST);
Html::back();
} else if (isset($_GET["id"]) && ($_GET["id"] > 0)) { //print computer information
Html::header(SlaLevel::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "config", "slm", "slalevel");
//show computer form to add
$item->display(['id' => $_GET["id"]]);
Html::footer();
}
|
gpl-2.0
|
TUD-OS/M3
|
src/libs/rustbase/src/kif/pedesc.rs
|
5973
|
/*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
use core::fmt;
int_enum! {
/// The different types of PEs
pub struct PEType : PEDescRaw {
/// Compute PE with internal memory
const COMP_IMEM = 0x0;
/// Compute PE with cache and external memory
const COMP_EMEM = 0x1;
/// Memory PE
const MEM = 0x2;
}
}
int_enum! {
/// The supported instruction set architectures (ISAs)
pub struct PEISA : PEDescRaw {
/// Dummy ISA to represent memory PEs
const NONE = 0x0;
/// x86_64 as supported by gem5
const X86 = 0x1;
/// ARMv7 as supported by gem5
const ARM = 0x2;
/// Xtensa as on Tomahawk 2/4
const XTENSA = 0x3;
/// Dummy ISA to represent the indirect-chaining fixed-function accelerator
const ACCEL_INDIR = 0x4;
/// Dummy ISA to represent the FFT fixed-function accelerator
const ACCEL_FFT = 0x5;
/// Dummy ISA to represent the toupper fixed-function accelerator
const ACCEL_TOUP = 0x6;
/// Dummy ISA to represent the ALADDIN-based stencil accelerator
const ACCEL_STE = 0x7;
/// Dummy ISA to represent the ALADDIN-based md accelerator
const ACCEL_MD = 0x8;
/// Dummy ISA to represent the ALADDIN-based spmv accelerator
const ACCEL_SPMV = 0x9;
/// Dummy ISA to represent the ALADDIN-based fft accelerator
const ACCEL_AFFT = 0xA;
/// Dummy ISA to represent the IDE controller
const IDE_DEV = 0xB;
}
}
bitflags! {
/// Special flags for PE features
pub struct PEFlags : PEDescRaw {
/// This flag is set if the MMU of the CU should be used
const MMU_VM = 0b01;
/// This flag is set if the DTU's virtual memory support should be used
const DTU_VM = 0b10;
}
}
type PEDescRaw = u32;
/// Describes a processing element (PE).
///
/// This struct is used for the [`create_vpe`] syscall to let the kernel know about the desired PE
/// type. Additionally, it is used to tell a VPE about the attributes of the PE it has been assigned
/// to.
///
/// [`create_vpe`]: ../../m3/syscalls/fn.create_vpe.html
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
pub struct PEDesc {
val: PEDescRaw,
}
impl PEDesc {
/// Creates a new PE description from the given type, ISA, and memory size.
pub fn new(ty: PEType, isa: PEISA, memsize: usize) -> PEDesc {
let val = ty.val | (isa.val << 3) | memsize as PEDescRaw;
Self::new_from(val)
}
/// Creates a new PE description from the given raw value
pub fn new_from(val: PEDescRaw) -> PEDesc {
PEDesc {
val: val
}
}
/// Returns the raw value
pub fn value(&self) -> PEDescRaw {
self.val
}
pub fn pe_type(&self) -> PEType {
PEType::from(self.val & 0x7)
}
pub fn isa(&self) -> PEISA {
PEISA::from((self.val >> 3) & 0xF)
}
pub fn flags(&self) -> PEFlags {
PEFlags::from_bits((self.val >> 7) & 0x3).unwrap()
}
/// Returns the size of the internal memory (0 if none is present)
pub fn mem_size(&self) -> usize {
(self.val & !0xFFF) as usize
}
/// Returns whether the PE executes software
pub fn is_programmable(&self) -> bool {
match self.isa() {
PEISA::X86 | PEISA::ARM | PEISA::XTENSA => true,
_ => false,
}
}
/// Returns whether the PE contains a fixed-function accelerator
pub fn is_ffaccel(&self) -> bool {
match self.isa() {
PEISA::ACCEL_INDIR | PEISA::ACCEL_FFT | PEISA::ACCEL_TOUP => true,
_ => false
}
}
/// Return if the PE supports multiple contexts
pub fn supports_ctxsw(&self) -> bool {
self.supports_ctx() && (self.isa() >= PEISA::ACCEL_INDIR || self.has_cache())
}
/// Return if the PE supports the context switching protocol
pub fn supports_ctx(&self) -> bool {
self.supports_vpes() && self.isa() != PEISA::IDE_DEV
}
/// Return if the PE supports VPEs
pub fn supports_vpes(&self) -> bool {
self.pe_type() != PEType::MEM
}
/// Returns whether the PE has an internal memory (SPM, DRAM, ...)
pub fn has_mem(&self) -> bool {
self.pe_type() == PEType::COMP_IMEM || self.pe_type() == PEType::MEM
}
/// Returns whether the PE has a cache
pub fn has_cache(&self) -> bool {
self.pe_type() == PEType::COMP_EMEM
}
/// Returns whether the PE supports virtual memory (either by DTU or MMU)
pub fn has_virtmem(&self) -> bool {
self.has_dtuvm() || self.has_mmu()
}
/// Returns whether the PE uses DTU-based virtual memory
pub fn has_dtuvm(&self) -> bool {
self.flags().contains(PEFlags::DTU_VM)
}
/// Returns whether the PE uses MMU-based virtual memory
pub fn has_mmu(&self) -> bool {
self.flags().contains(PEFlags::MMU_VM)
}
}
impl fmt::Debug for PEDesc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PEDesc[type={}, isa={}, memsz={}]", self.pe_type(), self.isa(), self.mem_size())
}
}
|
gpl-2.0
|
psahalot/runway
|
single.php
|
926
|
<?php
/**
* The Template for displaying all single posts.
*
* @package Runway
* @since Runway 1.0
*/
get_header(); ?>
<div id="maincontentcontainer">
<div id="primary" class="site-content row" role="main">
<div class="col grid_8_of_12">
<div class="main-content">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() ) {
comments_template( '', true );
}
?>
<?php runway_content_nav( 'nav-below' ); ?>
<?php endwhile; // end of the loop. ?>
</div> <!-- end .main-content -->
</div> <!-- /.col.grid_8_of_12 -->
<?php get_sidebar(); ?>
</div> <!-- /#primary.site-content.row -->
<?php get_footer(); ?>
|
gpl-2.0
|
dailin/wesnoth
|
src/editor/map/map_context.cpp
|
21108
|
/*
Copyright (C) 2008 - 2014 by Tomasz Sniatowski <kailoran@gmail.com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "wesnoth-editor"
#include "editor/action/action.hpp"
#include "map_context.hpp"
#include "display.hpp"
#include "filesystem.hpp"
#include "gettext.hpp"
#include "map_exception.hpp"
#include "map_label.hpp"
#include "resources.hpp"
#include "serialization/binary_or_text.hpp"
#include "serialization/parser.hpp"
#include "team.hpp"
#include "unit.hpp"
#include "wml_exception.hpp"
#include "formula_string_utils.hpp"
#include <boost/regex.hpp>
#include <boost/foreach.hpp>
namespace editor {
const size_t map_context::max_action_stack_size_ = 100;
map_context::map_context(const editor_map& map, const display& disp, bool pure_map, const config& schedule)
: filename_()
, map_data_key_()
, embedded_(false)
, pure_map_(pure_map)
, map_(map)
, undo_stack_()
, redo_stack_()
, actions_since_save_(0)
, starting_position_label_locs_()
, needs_reload_(false)
, needs_terrain_rebuild_(false)
, needs_labels_reset_(false)
, changed_locations_()
, everything_changed_(false)
, scenario_id_()
, scenario_name_()
, scenario_description_()
, xp_mod_(70)
, victory_defeated_(true)
, random_time_(false)
, active_area_(-1)
, labels_(disp, NULL)
, units_()
, teams_()
, tod_manager_(new tod_manager(schedule))
, mp_settings_()
, game_classification_()
, music_tracks_()
{
}
map_context::map_context(const config& game_config, const std::string& filename, const display& disp)
: filename_(filename)
, map_data_key_()
, embedded_(false)
, pure_map_(false)
, map_(game_config)
, undo_stack_()
, redo_stack_()
, actions_since_save_(0)
, starting_position_label_locs_()
, needs_reload_(false)
, needs_terrain_rebuild_(false)
, needs_labels_reset_(false)
, changed_locations_()
, everything_changed_(false)
, scenario_id_()
, scenario_name_()
, scenario_description_()
, xp_mod_(70)
, victory_defeated_(true)
, random_time_(false)
, active_area_(-1)
, labels_(disp, NULL)
, units_()
, teams_()
, tod_manager_(new tod_manager(game_config.find_child("editor_times", "id", "default")))
, mp_settings_()
, game_classification_()
, music_tracks_()
{
/*
* Overview of situations possibly found in the file:
*
* 0. Not a scenario or map file.
* 0.1 File not found
* 0.2 Map file empty
* 0.3 No valid data
* 1. It's a file containing only pure map data.
* * embedded_ = false
* * pure_map_ = true
* 2. A scenario embedding the map
* * embedded_ = true
* * pure_map_ = true
* The data/scenario-test.cfg for example.
* The map is written back to the file.
* 3. The map file is referenced by map_data={MACRO_ARGUEMENT}.
* * embedded_ = false
* * pure_map_ = true
* 4. The file contains an editor generated scenario file.
* * embedded_ = false
* * pure_map_ = false
*/
log_scope2(log_editor, "Loading file " + filename);
// 0.1 File not found
if (!filesystem::file_exists(filename) || filesystem::is_directory(filename))
throw editor_map_load_exception(filename, _("File not found"));
std::string file_string = filesystem::read_file(filename);
// 0.2 Map file empty
if (file_string.empty()) {
std::string message = _("Empty file");
throw editor_map_load_exception(filename, message);
}
// 1.0 Pure map data
boost::regex rexpression_map_data("map_data\\s*=\\s*\"(.+?)\"");
boost::smatch matched_map_data;
if (!boost::regex_search(file_string, matched_map_data, rexpression_map_data,
boost::regex_constants::match_not_dot_null)) {
map_ = editor_map::from_string(game_config, file_string); //throws on error
pure_map_ = true;
return;
}
// 2.0 Embedded map
const std::string& map_data = matched_map_data[1];
boost::regex rexpression_macro("\\{(.+?)\\}");
boost::smatch matched_macro;
if (!boost::regex_search(map_data, matched_macro, rexpression_macro)) {
// We have a map_data string but no macro ---> embedded or scenario
boost::regex rexpression_scenario("\\[scenario\\]|\\[test\\]|\\[multiplayer\\]");
if (!boost::regex_search(file_string, rexpression_scenario)) {
LOG_ED << "Loading generated scenario file" << std::endl;
// 4.0 editor generated scenario
try {
load_scenario(game_config);
} catch (config::error & e) {
throw editor_map_load_exception("load_scenario", e.message); //we already caught and rethrew this exception in load_scenario
}
return;
} else {
LOG_ED << "Loading embedded map file" << std::endl;
embedded_ = true;
pure_map_ = true;
map_ = editor_map::from_string(game_config, map_data);
return;
}
}
// 3.0 Macro referenced pure map
const std::string& macro_argument = matched_macro[1];
LOG_ED << "Map looks like a scenario, trying {" << macro_argument << "}" << std::endl;
std::string new_filename = filesystem::get_wml_location(macro_argument,
filesystem::directory_name(macro_argument));
if (new_filename.empty()) {
std::string message = _("The map file looks like a scenario, "
"but the map_data value does not point to an existing file")
+ std::string("\n") + macro_argument;
throw editor_map_load_exception(filename, message);
}
LOG_ED << "New filename is: " << new_filename << std::endl;
filename_ = new_filename;
file_string = filesystem::read_file(filename_);
map_ = editor_map::from_string(game_config, file_string);
pure_map_ = true;
}
void map_context::set_side_setup(int side, const std::string& team_name, const std::string& user_team_name,
int gold, int income, int village_gold, int village_support,
bool fog, bool share_view, bool shroud, bool share_maps,
team::CONTROLLER controller, bool hidden, bool no_leader)
{
assert(teams_.size() > static_cast<unsigned int>(side));
team& t = teams_[side];
// t.set_save_id(id);
// t.set_name(name);
t.change_team(team_name, user_team_name);
t.have_leader(!no_leader);
t.change_controller(controller);
t.set_gold(gold);
t.set_base_income(income);
t.set_hidden(hidden);
t.set_fog(fog);
t.set_share_maps(share_maps);
t.set_shroud(shroud);
t.set_share_view(share_view);
t.set_village_gold(village_gold);
t.set_village_support(village_support);
actions_since_save_++;
}
void map_context::set_scenario_setup(const std::string& id, const std::string& name, const std::string& description,
int turns, int xp_mod, bool victory_defeated, bool random_time)
{
scenario_id_ = id;
scenario_name_ = name;
scenario_description_ = description;
random_time_ = random_time;
victory_defeated_ = victory_defeated;
tod_manager_->set_number_of_turns(turns);
xp_mod_ = xp_mod;
actions_since_save_++;
}
void map_context::set_starting_time(int time)
{
tod_manager_->set_current_time(time);
if (!pure_map_)
actions_since_save_++;
}
void map_context::remove_area(int index)
{
tod_manager_->remove_time_area(index);
active_area_--;
actions_since_save_++;
}
void map_context::replace_schedule(const std::vector<time_of_day>& schedule)
{
tod_manager_->replace_schedule(schedule);
if (!pure_map_)
actions_since_save_++;
}
void map_context::replace_local_schedule(const std::vector<time_of_day>& schedule)
{
tod_manager_->replace_local_schedule(schedule, active_area_);
if (!pure_map_)
actions_since_save_++;
}
void map_context::load_scenario(const config& game_config)
{
config scenario;
try {
read(scenario, *(preprocess_file(filename_)));
} catch (config::error & e) {
LOG_ED << "Caught a config error while parsing file: '" << filename_ << "'\n" << e.message << std::endl;
throw e;
}
scenario_id_ = scenario["id"].str();
scenario_name_ = scenario["name"].str();
scenario_description_ = scenario["description"].str();
xp_mod_ = scenario["experience_modifier"].to_int();
victory_defeated_ = scenario["victory_when_enemies_defeated"].to_bool(true);
random_time_ = scenario["random_start_time"].to_bool(false);
map_ = editor_map::from_string(game_config, scenario["map_data"]); //throws on error
labels_.read(scenario);
tod_manager_.reset(new tod_manager(scenario));
BOOST_FOREACH(const config &time_area, scenario.child_range("time_area")) {
tod_manager_->add_time_area(map_,time_area);
}
BOOST_FOREACH(const config& item, scenario.child_range("item")) {
const map_location loc(item);
overlays_.insert(std::pair<map_location,
overlay>(loc, overlay(item) ));
}
BOOST_FOREACH(const config& music, scenario.child_range("music")) {
music_tracks_.insert(std::pair<std::string, sound::music_track>(music["name"], sound::music_track(music)));
}
resources::teams = &teams_;
int i = 1;
BOOST_FOREACH(config &side, scenario.child_range("side"))
{
team t;
side["side"] = i;
t.build(side, map_, NULL); //It's okay to pass a NULL gamedata ptr here, it is only used ultimately in map_location ctor and checked for null.
teams_.push_back(t);
BOOST_FOREACH(config &a_unit, side.child_range("unit")) {
map_location loc(a_unit, NULL);
a_unit["side"] = i;
units_.add(loc, unit(a_unit, true) );
}
i++;
}
}
map_context::~map_context()
{
clear_stack(undo_stack_);
clear_stack(redo_stack_);
}
bool map_context::select_area(int index)
{
return map_.set_selection(tod_manager_->get_area_by_index(index));
}
void map_context::draw_terrain(const t_translation::t_terrain & terrain,
const map_location& loc, bool one_layer_only)
{
t_translation::t_terrain full_terrain = one_layer_only ? terrain :
map_.get_terrain_info(terrain).terrain_with_default_base();
draw_terrain_actual(full_terrain, loc, one_layer_only);
}
void map_context::draw_terrain_actual(const t_translation::t_terrain & terrain,
const map_location& loc, bool one_layer_only)
{
if (!map_.on_board_with_border(loc)) {
//requests for painting off the map are ignored in set_terrain anyway,
//but ideally we should not have any
LOG_ED << "Attempted to draw terrain off the map (" << loc << ")\n";
return;
}
t_translation::t_terrain old_terrain = map_.get_terrain(loc);
if (terrain != old_terrain) {
if (terrain.base == t_translation::NO_LAYER) {
map_.set_terrain(loc, terrain, gamemap::OVERLAY);
} else if (one_layer_only) {
map_.set_terrain(loc, terrain, gamemap::BASE);
} else {
map_.set_terrain(loc, terrain);
}
add_changed_location(loc);
}
}
void map_context::draw_terrain(const t_translation::t_terrain & terrain,
const std::set<map_location>& locs, bool one_layer_only)
{
t_translation::t_terrain full_terrain = one_layer_only ? terrain :
map_.get_terrain_info(terrain).terrain_with_default_base();
BOOST_FOREACH(const map_location& loc, locs) {
draw_terrain_actual(full_terrain, loc, one_layer_only);
}
}
void map_context::clear_changed_locations()
{
everything_changed_ = false;
changed_locations_.clear();
}
void map_context::add_changed_location(const map_location& loc)
{
if (!everything_changed())
changed_locations_.insert(loc);
}
void map_context::add_changed_location(const std::set<map_location>& locs)
{
if (!everything_changed())
changed_locations_.insert(locs.begin(), locs.end());
}
void map_context::set_everything_changed()
{
everything_changed_ = true;
}
bool map_context::everything_changed() const
{
return everything_changed_;
}
void map_context::clear_starting_position_labels(display& disp)
{
disp.labels().clear_all();
starting_position_label_locs_.clear();
}
void map_context::set_starting_position_labels(display& disp)
{
std::set<map_location> new_label_locs = map_.set_starting_position_labels(disp);
starting_position_label_locs_.insert(new_label_locs.begin(), new_label_locs.end());
}
void map_context::reset_starting_position_labels(display& disp)
{
clear_starting_position_labels(disp);
set_starting_position_labels(disp);
set_needs_labels_reset(false);
}
config map_context::to_config()
{
config scenario;
scenario["id"] = scenario_id_;
scenario["name"] = t_string(scenario_name_);
scenario["description"] = scenario_description_;
scenario["experience_modifier"] = xp_mod_;
scenario["victory_when_enemies_defeated"] = victory_defeated_;
scenario["random_starting_time"] = random_time_;
scenario.append(tod_manager_->to_config());
scenario.remove_attribute("turn_at");
scenario["map_data"] = map_.write();
labels_.write(scenario);
overlay_map::const_iterator it;
for (it = overlays_.begin(); it != overlays_.end(); ++it) {
config& item = scenario.add_child("item");
it->first.write(item);
item["image"] = it->second.image;
item["id"] = it->second.id;
item["halo"] = it->second.halo;
item["visible_in_fog"] = it->second.visible_in_fog;
item["name"] = it->second.name;
item["team_name"] = it->second.team_name;
}
BOOST_FOREACH(const music_map::value_type& track, music_tracks_) {
track.second.write(scenario, true);
}
for(std::vector<team>::const_iterator t = teams_.begin(); t != teams_.end(); ++t) {
int side_num = t - teams_.begin() + 1;
config& side = scenario.add_child("side");
side["side"] = side_num;
side["hidden"] = t->hidden();
side["controller"] = team::CONTROLLER_to_string (t->controller());
side["no_leader"] = t->no_leader();
side["team_name"] = t->team_name();
side["user_team_name"] = t->user_team_name();
// TODO
// side["allow_player"] = "yes";
side["fog"] = t->uses_fog();
side["share_view"] = t->share_view();
side["shroud"] = t->uses_shroud();
side["share_maps"] = t->share_maps();
side["gold"] = t->gold();
side["income"] = t->base_income();
BOOST_FOREACH(const map_location& village, t->villages()) {
village.write(side.add_child("village"));
}
//current visible units
for(unit_map::const_iterator i = units_.begin(); i != units_.end(); ++i) {
if(i->side() == side_num) {
config& u = side.add_child("unit");
i->get_location().write(u);
u["type"] = i->type_id();
u["canrecruit"] = i->can_recruit();
u["unrenamable"] = i->unrenamable();
u["id"] = i->id();
u["name"] = i->name();
u["extra_recruit"] = utils::join(i->recruits());
u["facing"] = map_location::write_direction(i->facing());
}
}
}
return scenario;
}
bool map_context::save_scenario()
{
assert(!is_embedded());
if (scenario_id_.empty())
scenario_id_ = filesystem::base_name(filename_);
if (scenario_name_.empty())
scenario_name_ = scenario_id_;
try {
std::stringstream wml_stream;
{
config_writer out(wml_stream, false);
out.write(to_config());
}
if (!wml_stream.str().empty())
filesystem::write_file(get_filename(), wml_stream.str());
clear_modified();
} catch (filesystem::io_exception& e) {
utils::string_map symbols;
symbols["msg"] = e.what();
const std::string msg = vgettext("Could not save the scenario: $msg", symbols);
throw editor_map_save_exception(msg);
}
// TODO the return value of this method does not need to be boolean.
// We either return true or there is an exception thrown.
return true;
}
bool map_context::save_map()
{
std::string map_data = map_.write();
try {
if (!is_embedded()) {
filesystem::write_file(get_filename(), map_data);
} else {
std::string map_string = filesystem::read_file(get_filename());
boost::regex rexpression_map_data("(.*map_data\\s*=\\s*\")(.+?)(\".*)");
boost::smatch matched_map_data;
if (boost::regex_search(map_string, matched_map_data, rexpression_map_data,
boost::regex_constants::match_not_dot_null)) {
std::stringstream ss;
ss << matched_map_data[1];
ss << map_data;
ss << matched_map_data[3];
filesystem::write_file(get_filename(), ss.str());
} else {
throw editor_map_save_exception(_("Could not save into scenario"));
}
}
clear_modified();
} catch (filesystem::io_exception& e) {
utils::string_map symbols;
symbols["msg"] = e.what();
const std::string msg = vgettext("Could not save the map: $msg", symbols);
throw editor_map_save_exception(msg);
}
//TODO the return value of this method does not need to be boolean.
//We either return true or there is an exception thrown.
return true;
}
void map_context::set_map(const editor_map& map)
{
if (map_.h() != map.h() || map_.w() != map.w()) {
set_needs_reload();
} else {
set_needs_terrain_rebuild();
}
map_ = map;
}
void map_context::perform_action(const editor_action& action)
{
LOG_ED << "Performing action " << action.get_id() << ": " << action.get_name()
<< ", actions count is " << action.get_instance_count() << std::endl;
editor_action* undo = action.perform(*this);
if (actions_since_save_ < 0) {
//set to a value that will make it impossible to get to zero, as at this point
//it is no longer possible to get back the original map state using undo/redo
actions_since_save_ = 1 + undo_stack_.size();
}
actions_since_save_++;
undo_stack_.push_back(undo);
trim_stack(undo_stack_);
clear_stack(redo_stack_);
}
void map_context::perform_partial_action(const editor_action& action)
{
LOG_ED << "Performing (partial) action " << action.get_id() << ": " << action.get_name()
<< ", actions count is " << action.get_instance_count() << std::endl;
if (!can_undo()) {
throw editor_logic_exception("Empty undo stack in perform_partial_action()");
}
editor_action_chain* undo_chain = dynamic_cast<editor_action_chain*>(last_undo_action());
if (undo_chain == NULL) {
throw editor_logic_exception("Last undo action not a chain in perform_partial_action()");
}
editor_action* undo = action.perform(*this);
//actions_since_save_ += action.action_count();
undo_chain->prepend_action(undo);
clear_stack(redo_stack_);
}
bool map_context::modified() const
{
return actions_since_save_ != 0;
}
void map_context::clear_modified()
{
actions_since_save_ = 0;
}
bool map_context::can_undo() const
{
return !undo_stack_.empty();
}
bool map_context::can_redo() const
{
return !redo_stack_.empty();
}
editor_action* map_context::last_undo_action()
{
return undo_stack_.empty() ? NULL : undo_stack_.back();
}
editor_action* map_context::last_redo_action()
{
return redo_stack_.empty() ? NULL : redo_stack_.back();
}
const editor_action* map_context::last_undo_action() const
{
return undo_stack_.empty() ? NULL : undo_stack_.back();
}
const editor_action* map_context::last_redo_action() const
{
return redo_stack_.empty() ? NULL : redo_stack_.back();
}
void map_context::undo()
{
LOG_ED << "undo() beg, undo stack is " << undo_stack_.size() << ", redo stack " << redo_stack_.size() << std::endl;
if (can_undo()) {
perform_action_between_stacks(undo_stack_, redo_stack_);
actions_since_save_--;
} else {
WRN_ED << "undo() called with an empty undo stack" << std::endl;
}
LOG_ED << "undo() end, undo stack is " << undo_stack_.size() << ", redo stack " << redo_stack_.size() << std::endl;
}
void map_context::redo()
{
LOG_ED << "redo() beg, undo stack is " << undo_stack_.size() << ", redo stack " << redo_stack_.size() << std::endl;
if (can_redo()) {
perform_action_between_stacks(redo_stack_, undo_stack_);
actions_since_save_++;
} else {
WRN_ED << "redo() called with an empty redo stack" << std::endl;
}
LOG_ED << "redo() end, undo stack is " << undo_stack_.size() << ", redo stack " << redo_stack_.size() << std::endl;
}
void map_context::partial_undo()
{
//callers should check for these conditions
if (!can_undo()) {
throw editor_logic_exception("Empty undo stack in partial_undo()");
}
editor_action_chain* undo_chain = dynamic_cast<editor_action_chain*>(last_undo_action());
if (undo_chain == NULL) {
throw editor_logic_exception("Last undo action not a chain in partial undo");
}
//a partial undo performs the first action form the current action's action_chain that would be normally performed
//i.e. the *first* one.
boost::scoped_ptr<editor_action> first_action_in_chain(undo_chain->pop_first_action());
if (undo_chain->empty()) {
actions_since_save_--;
delete undo_chain;
undo_stack_.pop_back();
}
redo_stack_.push_back(first_action_in_chain.get()->perform(*this));
//actions_since_save_ -= last_redo_action()->action_count();
}
void map_context::clear_undo_redo()
{
clear_stack(undo_stack_);
clear_stack(redo_stack_);
}
void map_context::trim_stack(action_stack& stack)
{
if (stack.size() > max_action_stack_size_) {
delete stack.front();
stack.pop_front();
}
}
void map_context::clear_stack(action_stack& stack)
{
BOOST_FOREACH(editor_action* a, stack) {
delete a;
}
stack.clear();
}
void map_context::perform_action_between_stacks(action_stack& from, action_stack& to)
{
assert(!from.empty());
boost::scoped_ptr<editor_action> action(from.back());
from.pop_back();
editor_action* reverse_action = action->perform(*this);
to.push_back(reverse_action);
trim_stack(to);
}
} //end namespace editor
|
gpl-2.0
|
Eincrou/YouTubeThumbnailGrabber
|
ViewModel/ViewModel.cs
|
17676
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using YouTubeThumbnailGrabber.Model;
using YouTubeThumbnailGrabber.View;
using DialogBoxResult = System.Windows.Forms.DialogResult;
using FolderBrowserDialog = System.Windows.Forms.FolderBrowserDialog;
using YouTubeParse;
namespace YouTubeThumbnailGrabber.ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
#region Fields
private string _channelUrl;
private bool _isUpdatingThumbnail = false;
private readonly string _configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.xml");
private string SaveImageFilename
{
get
{
string imageJpgFileName;
switch (_options.ImageFileNamingMode)
{
case FileNamingMode.ChannelTitle:
string workingFileName = String.Format("{0} - {1}", _youtubePage.ChannelName,
_youtubePage.VideoTitle);
foreach (char c in Path.GetInvalidFileNameChars())
{
workingFileName = workingFileName.Replace(c, '-');
}
imageJpgFileName = workingFileName;
break;
case FileNamingMode.VideoID:
imageJpgFileName = _thumbnail.VideoUrl.VideoID;
break;
default:
throw new InvalidEnumArgumentException("An invalid FileNamingMode was found.");
}
return Path.Combine(_options.SaveImagePath, imageJpgFileName) + ".jpg";
}
}
private readonly BitmapImage _defaultThumbnail =
new BitmapImage(new Uri(@"\Resources\YouTubeThumbnailUnavailable.jpg", UriKind.Relative));
private ClipboardMonitor _clipboardMonitor;
private readonly FolderBrowserDialog _folderDialog = new FolderBrowserDialog();
private Options _options;
private YouTubeVideoThumbnail _thumbnail;
private YouTubePage _youtubePage;
public bool IsThumbnailDisplayed { get { return !(_thumbnail == null); } }
public BitmapImage ThumbnailBitmapImage
{
get
{
if (_isUpdatingThumbnail) return null;
return (_thumbnail != null) ? _thumbnail.ThumbnailImage : _defaultThumbnail;
}
}
/*
* These status bar fields will be made into a class.... later.
*/
public string StsBrUrl
{
get { return _stsBrUrl; }
set
{
_stsBrUrl = value;
OnPropertyChanged("StsBrUrl");
}
}
private string _stsBrUrl;
public string StsBrTitle
{
get { return _stsBrTitle; }
set
{
_stsBrTitle = value;
OnPropertyChanged("StsBrTitle");
}
}
private string _stsBrTitle;
public BitmapImage StsBrChanImage
{
get { return _stsBrChanImage; }
private set
{
_stsBrChanImage = value;
OnPropertyChanged("StsBrChanImage");
}
}
private BitmapImage _stsBrChanImage;
public string StsBrChanName
{
get { return _stsBrChanName; }
private set
{
_stsBrChanName = value;
OnPropertyChanged("StsBrChanName");
}
}
private string _stsBrChanName;
#endregion
public void InitializeViewModel(Window mainWindow)
{
_clipboardMonitor = new ClipboardMonitor(mainWindow);
_clipboardMonitor.ClipboardTextChanged += clipboardMonitor_ClipboardTextChanged;
mainWindow.Closed += mainWindow_Closed;
ReadSettings();
}
#region private Methods
private void ReadSettings()
{
if (File.Exists(_configPath))
{
var xml = new XmlSerializer(typeof(Options));
using (Stream input = File.OpenRead(_configPath))
{
try
{
_options = (Options)xml.Deserialize(input);
}
catch (Exception)
{
MessageBox.Show("Configuration failed to load. Using default settings.", "Load settings failed.", MessageBoxButton.OK, MessageBoxImage.Error);
LoadDefaultSettings();
}
}
}
else
LoadDefaultSettings();
if (_options.AutoLoadURLs && !_clipboardMonitor.IsMonitoringClipboard)
_clipboardMonitor.InitCBViewer();
else if (_clipboardMonitor.IsMonitoringClipboard)
_clipboardMonitor.CloseCBViewer();
_folderDialog.Description = "Select a folder to save thumbnail images.";
_folderDialog.SelectedPath = _options.SaveImagePath;
}
private void LoadDefaultSettings()
{
_options = new Options
{
ImageFileNamingMode = FileNamingMode.VideoID,
AutoSaveImages = false,
AutoLoadURLs = false,
PublishedDateTitle = false,
VideoViews = false,
SaveImagePath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
};
}
private async void UpdateStatusBar()
{
if (_youtubePage == null || !(_youtubePage.VideoUrl).Equals(_thumbnail.VideoUrl))
{
_youtubePage = new YouTubePage(_thumbnail.VideoUrl);
await Task.Run(() =>
{
_youtubePage.DownloadYouTubePage();
_youtubePage.ParseAllFields();
});
}
if (_youtubePage.ChannelIcon == null)
_youtubePage.ChanImageDownloaded += youtubePage_ChanImageDownloaded;
else
StsBrChanImage = _youtubePage.ChannelIcon;
StsBrUrl = _youtubePage.VideoUrl.ShortYTURL.AbsoluteUri;
var sb = new StringBuilder(_youtubePage.VideoTitle);
if (_options.PublishedDateTitle)
sb.Insert(0, String.Format("[{0:yy.MM.dd}] ", _youtubePage.Published));
if (_options.VideoViews)
sb.Append(String.Format(" ({0:N0})", _youtubePage.ViewCount));
StsBrTitle = sb.ToString();
StsBrChanName = _youtubePage.ChannelName;
_channelUrl = _youtubePage.ChannelUri.OriginalString;
}
private void DownloadThumbnailImage(string url)
{
_isUpdatingThumbnail = true;
OnPropertyChanged("ThumbnailBitmapImage");
_thumbnail = new YouTubeVideoThumbnail(url);
_thumbnail.GetThumbnailSuccess += Image_DownloadCompleted;
_thumbnail.GetThumbailFailure += Image_DownloadFailed;
_thumbnail.ThumbnailImage.DownloadProgress += Image_DownloadProgress;
//_youtubePage = new YouTubePage(_thumbnail.VideoUrl);
//Task.Run(() => _youtubePage.DownloadYouTubePage());
}
#endregion
#region Public Methods
/// <summary>
/// Attempts to use the input string to grab a YouTube video thumbnail image. Returns false if an invalid YouTube URL, or if the thumbnail image is already being displayed
/// </summary>
/// <param name="url">URL to a YouTube video page</param>
/// <returns>Whether the URL could be successfully parsed and is a new URL</returns>
public bool GrabThumbnail(string url)
{
url = WebUtility.HtmlDecode(url);
if (YouTubePlaylist.ValidatePlaylistUrl(url))
{
if (
MessageBox.Show("Download thumbnails for all videos in this playlist?", "YouTube Playlist Detected",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
YouTubePlaylist pl = new YouTubePlaylist(url);
foreach (var video in pl.VideoUrlsList)
{
DownloadThumbnailImage(video.LongYTURL.AbsoluteUri);
}
return true;
}
}
if (YouTubeURL.ValidateUrl(url))
{
if (_thumbnail != null && (YouTubeURL.GetVideoID(url) == _thumbnail.VideoUrl.VideoID))
{
return false;
// MessageBox.Show("This video's thumbnail is already being displayed.", "Duplicate URL");
}
DownloadThumbnailImage(url);
return true;
}
return false;
}
/// <summary>
/// Saves the currently displayed thumbnail image to a .jpg file
/// </summary>
/// <returns>Whether the save operation was successful</returns>
public bool SaveThumbnailImageToFile()
{
string fileName = SaveImageFilename;
if (File.Exists(fileName))
{
MessageBox.Show("Image file already exists in this direcotry.", "Image not saved",
MessageBoxButton.OK, MessageBoxImage.Warning);
return false;
}
else
{
if (!Directory.Exists(_options.SaveImagePath))
Directory.CreateDirectory(_options.SaveImagePath);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(_thumbnail.ThumbnailImage as BitmapImage));
try
{
using (Stream output = File.Create(fileName))
encoder.Save(output);
}
catch (System.UnauthorizedAccessException)
{
MessageBox.Show("Image could not be saved. Please run this application as an Administrator.",
"Write Permissions Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
catch (Exception)
{
MessageBox.Show("Image could not be saved.",
"Configuration Error", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
MessageBox.Show("Video Thumbnail Saved to\n" + fileName, "Image Successfully Saved",
MessageBoxButton.OK, MessageBoxImage.Asterisk);
return true;
}
}
public void OpenImageInViewer() {
string tempDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Temp\" + _thumbnail.VideoUrl.VideoID + ".jpg";
string[] checkLocations = { SaveImageFilename, tempDirectory };
bool fileExists = false;
string existingFile = String.Empty;
foreach (var check in checkLocations)
if (File.Exists(check)) {
fileExists = true;
existingFile = check;
break;
}
if (fileExists)
Process.Start(existingFile);
else {
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(_thumbnail.ThumbnailImage as BitmapImage));
try {
using (Stream output = File.Create(tempDirectory))
encoder.Save(output);
}
catch (Exception) {
MessageBox.Show("The image could not be saved.",
"Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
Process.Start(tempDirectory);
}
}
public void OpenVideoInBrowser() {
if (_thumbnail == null) return;
Process.Start(_thumbnail.VideoUrl.LongYTURL.AbsoluteUri);
}
public void SetImageToClipboard()
{
Clipboard.SetImage(_thumbnail.ThumbnailImage);
}
public void SetVideoUrlToClipboard()
{
if (_thumbnail == null) return;
Clipboard.SetText(_thumbnail.VideoUrl.ShortYTURL.AbsoluteUri);
}
public void SetChannelUrlToClipboard()
{
if (_thumbnail == null) return;
Clipboard.SetText(_channelUrl);
}
public void OpenChannelInBrowser()
{
if (_thumbnail == null) return;
Process.Start(_channelUrl);
}
public void OpenOptionsMenu()
{
var opMenu = new OptionsMenu(_options);
opMenu.Owner = Application.Current.MainWindow;
opMenu.WindowStartupLocation = WindowStartupLocation.CenterOwner;
opMenu.Closed += opMenu_Closed;
opMenu.ShowDialog();
}
#endregion
#region Event Handlers
private void clipboardMonitor_ClipboardTextChanged(object sender, ClipboardEventArgs e)
{
string clipText = e.ClipboardText;
if (YouTubeURL.ValidateUrl(clipText) || YouTubePlaylist.ValidatePlaylistUrl(clipText))
{
if (_thumbnail != null && (YouTubeURL.GetVideoID(clipText) == _thumbnail.VideoUrl.VideoID)) return;
GrabThumbnail(clipText);
}
}
private void Image_DownloadCompleted(object sender, EventArgs e)
{
//SaveImage.IsEnabled = true;
_isUpdatingThumbnail = false;
_thumbnail.GetThumbnailSuccess -= Image_DownloadCompleted;
OnPropertyChanged("ThumbnailBitmapImage");
UpdateStatusBar();
if (_options.AutoSaveImages)
SaveThumbnailImageToFile();
OnThumbnailImageCompleted(sender, e);
}
private void Image_DownloadFailed(object sender, ExceptionEventArgs e)
{
//SaveImage.IsEnabled = false;
_isUpdatingThumbnail = false;
_thumbnail.GetThumbailFailure -= Image_DownloadFailed;
OnPropertyChanged("ThumbnailBitmapImage");
OnThumbnailImageFailed(sender, e);
}
private void Image_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
OnThumbnailImageProgress(sender, e);
}
void youtubePage_ChanImageDownloaded(object sender, EventArgs e)
{
var youtubePage = sender as YouTubePage;
if (youtubePage == null) return;
StsBrChanImage = youtubePage.ChannelIcon;
youtubePage.ChanImageDownloaded -= youtubePage_ChanImageDownloaded;
}
void mainWindow_Closed(object sender, EventArgs e) {
_clipboardMonitor.CloseCBViewer();
}
void opMenu_Closed(object sender, EventArgs e) {
((OptionsMenu)sender).Closed -= opMenu_Closed;
ReadSettings();
UpdateStatusBar();
}
#endregion
#region Public Events
/// <summary>
/// Notifies upon succes of thumbnail image download
/// </summary>
public event EventHandler ThumbnailImageDownloadCompletedRouted;
private void OnThumbnailImageCompleted(object sender, EventArgs e)
{
EventHandler thumbnailImageDownloadCompleted = ThumbnailImageDownloadCompletedRouted;
if (thumbnailImageDownloadCompleted != null)
ThumbnailImageDownloadCompletedRouted(sender, e);
}
/// <summary>
/// Notifies upon failure of thumbnail image download
/// </summary>
public event EventHandler<ExceptionEventArgs> ThumbnailImageDownloadFailedRouted;
private void OnThumbnailImageFailed(object sender, ExceptionEventArgs e)
{
var thumbnailImageDownloadFailed = ThumbnailImageDownloadFailedRouted;
if (thumbnailImageDownloadFailed != null)
ThumbnailImageDownloadFailedRouted(sender, e);
}
/// <summary>
/// Notifies on the progress of thumbnail image downloads.
/// </summary>
public event EventHandler<DownloadProgressEventArgs> ThumbnailImageProgressRouted;
private void OnThumbnailImageProgress(object sender, DownloadProgressEventArgs e)
{
EventHandler<DownloadProgressEventArgs> thumbnailImageProgress = ThumbnailImageProgressRouted;
if (thumbnailImageProgress != null)
ThumbnailImageProgressRouted(sender, e);
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName = null)
{
var onPropertyChanged = PropertyChanged;
if (onPropertyChanged != null) onPropertyChanged(this, new PropertyChangedEventArgs(propName));
}
#endregion
}
}
|
gpl-2.0
|
kikocastro/2014FallWeb
|
fitness_track_app/onepageapp/content/js/diet-control.js
|
5893
|
// var or functions that angular provides comes with a $
var $mContent;
var $socialScope = null;
var friendsArray = [];
var app = angular.module('app', ["highcharts-ng", 'ui.bootstrap']).factory('DataFactory', function($http) {
var filteredData = {};
return {
getData : function(callback) {
return $http.get('?format=json').success(callback);
},
setFilteredData : function(newData) {
filteredData = newData;
},
getFilteredData : function() {
return filteredData;
}
};
}).controller('ChartCtrl', ['$scope', '$filter', 'DataFactory',
function($scope, $filter, DataFactory) {
var dataQ = DataFactory.getData(function(results) {
$scope.data = results;
$scope.filteredData = results;
});
$scope.chartConfig = {
series : [{
data : []
}],
title : {
text : ''
}
};
$scope.makeChart = function(field) {
var Title = field.charAt(0).toUpperCase() + field.slice(1);
$scope.chartConfig.title.text = Title;
dataQ.success(function(data) {
var preparedData = prepareChartData($scope.filteredData, field);
var averageData = averageChartData($scope.filteredData, field);
var data = [{
name : Title,
data : preparedData.values
}, {
name : "Average",
data : averageData
}];
$scope.chartConfig.series = data;
$scope.chartConfig.xAxis = preparedData.xAxis;
});
};
$scope.makeChart('calories');
}]).controller('IndexCtrl', ['$scope', '$filter', 'DataFactory',
function($scope, $filter, DataFactory) {
var dataQ = DataFactory.getData(function(results) {
$scope.data = results;
$scope.filteredData = results;
});
$scope.currentRow = null;
$scope.click = function(row) {
$scope.currentRow = row;
};
$scope.clearFilter = function() {
$scope.query = null;
$scope.dt = null;
};
$scope.yesterday = function() {
$scope.dt = moment().subtract(1, 'days').format('YYYY-MM-DD');
};
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear : 'yyyy',
startingDay : 1
};
$scope.format = 'yyyy-MM-dd';
dataQ.success(function(data) {
$scope.calories = function() {
return sum($scope.filteredData, 'calories');
};
$scope.fat = function() {
return sum($scope.filteredData, 'fat');
};
$scope.protein = function() {
return sum($scope.filteredData, 'protein');
};
});
$socialScope = $scope;
$scope.login = function() {
FB.login(function(response) {
checkLoginState();
}, {
scope : 'user_friends, email'
});
};
var friendsArray = function() {
angular.forEach($scope.friends, function(friend) {
console.log(friend);
});
};
$('body').on('click', ".toggle-modal", function(event) {
event.preventDefault();
var $btn = $(this);
MyFormDialog(this.href, function(data) {
$("#myAlert").show().find('div').html(JSON.stringify(data));
if ($btn.hasClass('edit')) {
$scope.data[$scope.data.indexOf($scope.currentRow)] = data;
}
if ($btn.hasClass('add')) {
$scope.data.push(data);
}
if ($btn.hasClass('delete')) {
$scope.data.splice($scope.data.indexOf($scope.currentRow), 1);
}
if ($btn.hasClass('quickadd')) {
$scope.data.push(data);
}
$scope.$apply();
});
});
}]);
function checkLoginState() {
FB.getLoginStatus(function(response) {
$socialScope.status = response;
if (response.status === 'connected') {
FB.api('/me', function(response) {
$socialScope.me = response;
$socialScope.$apply();
console.log(response);
});
FB.api('/me/taggable_friends', function(response) {
$socialScope.friends = response;
$socialScope.$apply();
console.log(response);
});
}
});
}
function prepareChartData(data, field) {
var chartData = {
values : [],
xAxis : []
};
$.each(data, function(index, element) {
chartData.values.push(parseInt(element[field]));
chartData.xAxis.push(element['dateTime'].slice(0, 10));
});
return chartData;
}
function averageChartData(data, field) {
var chartArray = [];
var total = sum(data, field);
var average = Math.round(total / (data.length));
$.each(data, function(index, element) {
chartArray.push(average);
});
return chartArray;
}
function sum(data, field) {
var total = 0;
$.each(data, function(i, el) {
total += +el[field];
});
return total;
}
/* then: callback when the form is submitted */
function MyFormDialog(url, then) {
$("#myModal").modal("show");
$.get(url + "&format=plain", function(data) {
$mContent.html(data);
$mContent.find('form').on('submit', function(e) {
e.preventDefault();
$("#myModal").modal("hide");
$.post(this.action + '&format=json', $(this).serialize(), function(data) {
then(data);
}, 'json');
});
});
}
$(function() {
$(".menu-diet-control").addClass("active");
$mContent = $("#myModal .modal-content");
var defaultContent = $mContent.html();
$('#myModal').on('hidden.bs.modal', function(e) {
$mContent.html(defaultContent);
});
$('.alert .close').on('click', function(e) {
$(this).closest('.alert').slideUp();
});
});
$('.typeahead').typeahead({
hint : true,
highlight : true
}, {
displayKey : 'name',
source : function(query, callback) {
$.getJSON('?action=search&format=json&query=' + query, function(data) {
callback(data);
});
}
}).on('typeahead:selected', quickAdd).on('typeahead:autocompleted', quickAdd);
function quickAdd($e, datum) {
MyFormDialog("?action=quickadd&id=" + datum.id);
}
|
gpl-2.0
|
f1194361820/helper
|
frameworkex/frameworkex-apache-catalina/src/main/java/com/fjn/helper/frameworkex/apache/catalina/jmxclient/Constants.java
|
998
|
/*
*
* Copyright 2018 FJN Corp.
*
* 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.
*
* Author Date Issue
* fs1194361820@163.com 2015-01-01 Initial Version
*
*/
package com.fjn.helper.frameworkex.apache.catalina.jmxclient;
public class Constants {
public static final String SERVICE_URL_PREFIX = "service:jmx:rmi:///jndi/rmi://";
public static final String SERVICE_URL_SUFFIX = "/jmxrmi";
}
|
gpl-2.0
|
slackfaith/fadingFantasy
|
rpg/src/rpg_animation.cpp
|
133
|
#include "rpg_animation.h"
rpg_animation::rpg_animation()
{
//ctor
}
rpg_animation::~rpg_animation()
{
//dtor
}
|
gpl-2.0
|
seanhoughton/kstars
|
kstars/tools/wutdialog.cpp
|
20821
|
/***************************************************************************
wutdialog.cpp - K Desktop Planetarium
-------------------
begin : Die Feb 25 2003
copyright : (C) 2003 by Thomas Kabelmann
email : tk78@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "wutdialog.h"
#include <QTimer>
#include <QCursor>
#include <QListWidgetItem>
#include <QComboBox>
#include <KLocalizedString>
#include <QPushButton>
#include "ui_wutdialog.h"
#include "kstars.h"
#include "kstarsdata.h"
#include "skymap.h"
#include "ksnumbers.h"
#include "simclock.h"
#include "dialogs/detaildialog.h"
#include "dialogs/locationdialog.h"
#include "dialogs/timedialog.h"
#include "skyobjects/kssun.h"
#include "skyobjects/ksmoon.h"
#include "skycomponents/skymapcomposite.h"
#include "tools/observinglist.h"
WUTDialogUI::WUTDialogUI( QWidget *p ) : QFrame( p ) {
setupUi( this );
}
WUTDialog::WUTDialog( QWidget *parent, bool _session, GeoLocation *_geo, KStarsDateTime _lt ) :
QDialog( parent ),
session(_session),
T0(_lt),
geo(_geo),
EveningFlag(0),
timer(NULL)
{
#ifdef Q_OS_OSX
setWindowFlags(Qt::Tool| Qt::WindowStaysOnTopHint);
#endif
WUT = new WUTDialogUI( this );
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(WUT);
setLayout(mainLayout);
setWindowTitle( i18n("What's up Tonight") );
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Close);
mainLayout->addWidget(buttonBox);
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
setModal( false );
//If the Time is earlier than 6:00 am, assume the user wants the night of the previous date
if ( T0.time().hour() < 6 )
T0 = T0.addDays( -1 );
//Now, set time T0 to midnight (of the following day)
T0.setTime( QTime( 0, 0, 0 ) );
T0 = T0.addDays( 1 );
UT0 = geo->LTtoUT( T0 );
//Set the Tomorrow date/time to Noon the following day
Tomorrow = T0.addSecs( 12*3600 );
TomorrowUT = geo->LTtoUT( Tomorrow );
//Set the Evening date/time to 6:00 pm
Evening = T0.addSecs( -6*3600 );
EveningUT = geo->LTtoUT( Evening );
QString sGeo = geo->translatedName();
if ( ! geo->translatedProvince().isEmpty() ) sGeo += ", " + geo->translatedProvince();
sGeo += ", " + geo->translatedCountry();
WUT->LocationLabel->setText( i18n( "at %1", sGeo ) );
WUT->DateLabel->setText( i18n( "The night of %1", QLocale().toString( Evening.date(), QLocale::LongFormat ) ) );
m_Mag = 10.0;
WUT->MagnitudeEdit->setValue( m_Mag );
//WUT->MagnitudeEdit->setSliderEnabled( true );
WUT->MagnitudeEdit->setSingleStep(0.100);
initCategories();
makeConnections();
QTimer::singleShot(0, this, SLOT(init()));
}
WUTDialog::~WUTDialog(){
}
void WUTDialog::makeConnections() {
connect( WUT->DateButton, SIGNAL( clicked() ), SLOT( slotChangeDate() ) );
connect( WUT->LocationButton, SIGNAL( clicked() ), SLOT( slotChangeLocation() ) );
connect( WUT->CenterButton, SIGNAL( clicked() ), SLOT( slotCenter() ) );
connect( WUT->DetailButton, SIGNAL( clicked() ), SLOT( slotDetails() ) );
connect( WUT->ObslistButton, SIGNAL( clicked() ), SLOT( slotObslist() ) );
connect( WUT->CategoryListWidget, SIGNAL( currentTextChanged(const QString &) ),
SLOT( slotLoadList(const QString &) ) );
connect( WUT->ObjectListWidget, SIGNAL( currentTextChanged(const QString &) ),
SLOT( slotDisplayObject(const QString &) ) );
connect( WUT->EveningMorningBox, SIGNAL( activated(int) ), SLOT( slotEveningMorning(int) ) );
connect( WUT->MagnitudeEdit, SIGNAL( valueChanged( double ) ), SLOT( slotChangeMagnitude() ) );
}
void WUTDialog::initCategories() {
m_Categories << i18n( "Planets" ) << i18n( "Stars" )
<< i18n( "Nebulae" ) << i18n( "Galaxies" )
<< i18n( "Star Clusters" ) << i18n( "Constellations" )
<< i18n( "Asteroids" ) << i18n( "Comets" );
foreach ( const QString &c, m_Categories )
WUT->CategoryListWidget->addItem( c );
WUT->CategoryListWidget->setCurrentRow( 0 );
}
void WUTDialog::init() {
QString sRise, sSet, sDuration;
float Dur;
int hDur,mDur;
KStarsData* data = KStarsData::Instance();
// reset all lists
foreach ( const QString &c, m_Categories ) {
if ( m_VisibleList.contains( c ) )
visibleObjects( c ).clear();
else
m_VisibleList[ c ] = QList<SkyObject*>();
m_CategoryInitialized[ c ] = false;
}
// sun almanac information
KSSun *oSun = dynamic_cast<KSSun*>( data->objectNamed("Sun") );
sunRiseTomorrow = oSun->riseSetTime( TomorrowUT, geo, true );
sunSetToday = oSun->riseSetTime( EveningUT, geo, false );
sunRiseToday = oSun->riseSetTime( EveningUT, geo, true );
//check to see if Sun is circumpolar
KSNumbers *num = new KSNumbers( UT0.djd() );
KSNumbers *oldNum = new KSNumbers( data->ut().djd() );
CachingDms LST = geo->GSTtoLST( T0.gst() );
oSun->updateCoords( num, true, geo->lat(), &LST, true );
if ( oSun->checkCircumpolar( geo->lat() ) ) {
if ( oSun->alt().Degrees() > 0.0 ) {
sRise = i18n( "circumpolar" );
sSet = i18n( "circumpolar" );
sDuration = "00:00";
Dur = hDur = mDur = 0;
} else {
sRise = i18n( "does not rise" );
sSet = i18n( "does not rise" );
sDuration = "24:00";
Dur = hDur = 24;
mDur = 0;
}
} else {
//Round times to the nearest minute by adding 30 seconds to the time
sRise = QLocale().toString( sunRiseTomorrow );
sSet = QLocale().toString( sunSetToday );
Dur = 24.0 + (float)sunRiseTomorrow.hour()
+ (float)sunRiseTomorrow.minute()/60.0
+ (float)sunRiseTomorrow.second()/3600.0
- (float)sunSetToday.hour()
- (float)sunSetToday.minute()/60.0
- (float)sunSetToday.second()/3600.0;
hDur = int(Dur);
mDur = int(60.0*(Dur - (float)hDur));
QTime tDur( hDur, mDur );
sDuration = QLocale().toString( tDur);
}
WUT->SunSetLabel->setText( i18nc( "Sunset at time %1 on date %2", "Sunset: %1 on %2" , sSet, QLocale().toString( Evening.date(), QLocale::LongFormat) ) );
WUT->SunRiseLabel->setText( i18nc( "Sunrise at time %1 on date %2", "Sunrise: %1 on %2" , sRise, QLocale().toString( Tomorrow.date(), QLocale::LongFormat) ) );
if( Dur == 0 )
WUT->NightDurationLabel->setText( i18n("Night duration: %1", sDuration ) );
else if( Dur > 1 )
WUT->NightDurationLabel->setText( i18n("Night duration: %1 hours", sDuration ) );
else if( Dur == 1 )
WUT->NightDurationLabel->setText( i18n("Night duration: %1 hour", sDuration ) );
else if( mDur > 1 )
WUT->NightDurationLabel->setText( i18n("Night duration: %1 minutes", sDuration ) );
else if( mDur == 1 )
WUT->NightDurationLabel->setText( i18n("Night duration: %1 minute", sDuration ) );
// moon almanac information
KSMoon *oMoon = dynamic_cast<KSMoon*>( data->objectNamed("Moon") );
moonRise = oMoon->riseSetTime( UT0, geo, true );
moonSet = oMoon->riseSetTime( UT0, geo, false );
//check to see if Moon is circumpolar
oMoon->updateCoords( num, true, geo->lat(), &LST, true );
if ( oMoon->checkCircumpolar( geo->lat() ) ) {
if ( oMoon->alt().Degrees() > 0.0 ) {
sRise = i18n( "circumpolar" );
sSet = i18n( "circumpolar" );
} else {
sRise = i18n( "does not rise" );
sSet = i18n( "does not rise" );
}
} else {
//Round times to the nearest minute by adding 30 seconds to the time
sRise = QLocale().toString( moonRise.addSecs(30) );
sSet = QLocale().toString( moonSet.addSecs(30) );
}
WUT->MoonRiseLabel->setText( i18n( "Moon rises at: %1 on %2", sRise, QLocale().toString( Evening.date(), QLocale::LongFormat) ) );
// If the moon rises and sets on the same day, this will be valid [ Unless
// the moon sets on the next day after staying on for over 24 hours ]
if( moonSet > moonRise )
WUT->MoonSetLabel->setText( i18n( "Moon sets at: %1 on %2", sSet, QLocale().toString( Evening.date(), QLocale::LongFormat) ) );
else
WUT->MoonSetLabel->setText( i18n( "Moon sets at: %1 on %2", sSet, QLocale().toString( Tomorrow.date(), QLocale::LongFormat) ) );
oMoon->findPhase(0);
WUT->MoonIllumLabel->setText( oMoon->phaseName() + QString( " (%1%)" ).arg(
int(100.0*oMoon->illum() ) ) );
//Restore Sun's and Moon's coordinates, and recompute Moon's original Phase
oMoon->updateCoords( oldNum, true, geo->lat(), data->lst(), true );
oSun->updateCoords( oldNum, true, geo->lat(), data->lst(), true );
oMoon->findPhase(0);
if ( WUT->CategoryListWidget->currentItem() )
slotLoadList( WUT->CategoryListWidget->currentItem()->text() );
delete num;
delete oldNum;
}
QList<SkyObject*>& WUTDialog::visibleObjects( const QString &category ) {
return m_VisibleList[ category ];
}
bool WUTDialog::isCategoryInitialized( const QString &category ) {
return m_CategoryInitialized[ category ];
}
void WUTDialog::slotLoadList( const QString &c ) {
KStarsData* data = KStarsData::Instance();
if ( ! m_VisibleList.contains( c ) )
return;
WUT->ObjectListWidget->clear();
setCursor(QCursor(Qt::WaitCursor));
if ( ! isCategoryInitialized(c) ) {
if ( c == m_Categories[0] ) { //Planets
foreach ( const QString &name, data->skyComposite()->objectNames( SkyObject::PLANET ) ) {
SkyObject *o = data->skyComposite()->findByName( name );
if ( checkVisibility( o ) && o->mag() <= m_Mag )
visibleObjects(c).append(o);
}
m_CategoryInitialized[ c ] = true;
}
else if ( c == m_Categories[1] ) { //Stars
foreach ( SkyObject *o, data->skyComposite()->stars() )
if ( o->name() != i18n("star") && checkVisibility(o) && o->mag() <= m_Mag )
visibleObjects(c).append(o);
m_CategoryInitialized[ c ] = true;
}
else if ( c == m_Categories[5] ) { //Constellations
foreach ( SkyObject *o, data->skyComposite()->constellationNames() )
if ( checkVisibility(o) )
visibleObjects(c).append(o);
m_CategoryInitialized[ c ] = true;
}
else if ( c == m_Categories[6] ) { //Asteroids
foreach ( SkyObject *o, data->skyComposite()->asteroids() )
if ( checkVisibility(o) && o->name() != i18n("Pluto") && o->mag() <= m_Mag )
visibleObjects(c).append(o);
m_CategoryInitialized[ c ] = true;
}
else if ( c == m_Categories[7] ) { //Comets
foreach ( SkyObject *o, data->skyComposite()->comets() )
if ( checkVisibility(o) && o->mag() <= m_Mag)
visibleObjects(c).append(o);
m_CategoryInitialized[ c ] = true;
}
else { //all deep-sky objects, need to split clusters, nebulae and galaxies
foreach ( DeepSkyObject *dso, data->skyComposite()->deepSkyObjects() ) {
SkyObject *o = (SkyObject*)dso;
if ( checkVisibility(o) && o->mag() <= m_Mag ) {
switch( o->type() ) {
case SkyObject::OPEN_CLUSTER: //fall through
case SkyObject::GLOBULAR_CLUSTER:
visibleObjects(m_Categories[4]).append(o); //star clusters
break;
case SkyObject::GASEOUS_NEBULA: //fall through
case SkyObject::PLANETARY_NEBULA: //fall through
case SkyObject::SUPERNOVA_REMNANT:
visibleObjects(m_Categories[2]).append(o); //nebulae
break;
case SkyObject::GALAXY:
visibleObjects(m_Categories[3]).append(o); //galaxies
break;
}
}
}
m_CategoryInitialized[ m_Categories[2] ] = true;
m_CategoryInitialized[ m_Categories[3] ] = true;
m_CategoryInitialized[ m_Categories[4] ] = true;
}
}
//Now the category has been initialized, we can populate the list widget
foreach ( SkyObject *o, visibleObjects(c) )
WUT->ObjectListWidget->addItem( o->name() );
setCursor(QCursor(Qt::ArrowCursor));
// highlight first item
if ( WUT->ObjectListWidget->count() ) {
WUT->ObjectListWidget->setCurrentRow( 0 );
WUT->ObjectListWidget->setFocus();
}
}
bool WUTDialog::checkVisibility(SkyObject *o) {
bool visible( false );
double minAlt = 6.0; //An object is considered 'visible' if it is above horizon during civil twilight.
// reject objects that never rise
if (o->checkCircumpolar(geo->lat()) == true && o->alt().Degrees() <= 0) return false;
//Initial values for T1, T2 assume all night option of EveningMorningBox
KStarsDateTime T1 = Evening;
T1.setTime( sunSetToday );
KStarsDateTime T2 = Tomorrow;
T2.setTime( sunRiseTomorrow );
//Check Evening/Morning only state:
if ( EveningFlag==0 ) { //Evening only
T2 = T0; //midnight
} else if ( EveningFlag==1 ) { //Morning only
T1 = T0; //midnight
}
for ( KStarsDateTime test = T1; test < T2; test = test.addSecs(3600) ) {
//Need LST of the test time, expressed as a dms object.
KStarsDateTime ut = geo->LTtoUT( test );
dms LST = geo->GSTtoLST( ut.gst() );
SkyPoint sp = o->recomputeCoords( ut, geo );
//check altitude of object at this time.
sp.EquatorialToHorizontal( &LST, geo->lat() );
if ( sp.alt().Degrees() > minAlt ) {
visible = true;
break;
}
}
return visible;
}
void WUTDialog::slotDisplayObject( const QString &name ) {
QTime tRise, tSet, tTransit;
QString sRise, sTransit, sSet;
sRise = "--:--";
sTransit = "--:--";
sSet = "--:--";
WUT->DetailButton->setEnabled( false );
SkyObject *o = 0;
if ( name.isEmpty() )
{ //no object selected
WUT->ObjectBox->setTitle( i18n( "No Object Selected" ) );
o = 0;
} else {
o = KStarsData::Instance()->objectNamed( name );
if ( !o ) { //should never get here
WUT->ObjectBox->setTitle( i18n( "Object Not Found" ) );
}
}
if (o) {
WUT->ObjectBox->setTitle( o->name() );
if ( o->checkCircumpolar( geo->lat() ) ) {
if ( o->alt().Degrees() > 0.0 ) {
sRise = i18n( "circumpolar" );
sSet = i18n( "circumpolar" );
} else {
sRise = i18n( "does not rise" );
sSet = i18n( "does not rise" );
}
} else {
tRise = o->riseSetTime( T0, geo, true );
tSet = o->riseSetTime( T0, geo, false );
// if ( tSet < tRise )
// tSet = o->riseSetTime( JDTomorrow, geo, false );
sRise.clear();
sRise.sprintf( "%02d:%02d", tRise.hour(), tRise.minute() );
sSet.clear();
sSet.sprintf( "%02d:%02d", tSet.hour(), tSet.minute() );
}
tTransit = o->transitTime( T0, geo );
// if ( tTransit < tRise )
// tTransit = o->transitTime( JDTomorrow, geo );
sTransit.clear();
sTransit.sprintf( "%02d:%02d", tTransit.hour(), tTransit.minute() );
WUT->DetailButton->setEnabled( true );
}
WUT->ObjectRiseLabel->setText( i18n( "Rises at: %1", sRise ) );
WUT->ObjectTransitLabel->setText( i18n( "Transits at: %1", sTransit ) );
WUT->ObjectSetLabel->setText( i18n( "Sets at: %1", sSet ) );
}
void WUTDialog::slotCenter() {
KStars* kstars = KStars::Instance();
SkyObject *o = 0;
// get selected item
if (WUT->ObjectListWidget->currentItem() != 0) {
o = kstars->data()->objectNamed( WUT->ObjectListWidget->currentItem()->text() );
}
if (o != 0) {
kstars->map()->setFocusPoint( o );
kstars->map()->setFocusObject( o );
kstars->map()->setDestination( *kstars->map()->focusPoint() );
}
}
void WUTDialog::slotDetails() {
KStars* kstars = KStars::Instance();
SkyObject *o = 0;
// get selected item
if (WUT->ObjectListWidget->currentItem() != 0) {
o = kstars->data()->objectNamed( WUT->ObjectListWidget->currentItem()->text() );
}
if (o != 0) {
QPointer<DetailDialog> detail = new DetailDialog(o, kstars->data()->ut(), geo, kstars);
detail->exec();
delete detail;
}
}
void WUTDialog::slotObslist()
{
SkyObject *o = 0;
// get selected item
if (WUT->ObjectListWidget->currentItem() != 0) {
o = KStarsData::Instance()->objectNamed( WUT->ObjectListWidget->currentItem()->text() );
}
if(o != 0) {
KStarsData::Instance()->observingList()->slotAddObject( o, session ) ;
}
}
void WUTDialog::slotChangeDate() {
// Set the time T0 to the evening of today. This will make life easier for the user, who most probably
// wants to see what's up on the night of some date, rather than the night of the previous day
T0.setTime( QTime( 18, 0, 0 ) ); // 6 PM
QPointer<TimeDialog> td = new TimeDialog( T0, KStarsData::Instance()->geo(), this );
if ( td->exec() == QDialog::Accepted ) {
T0 = td->selectedDateTime();
// If the time is set to 12 midnight, set it to 00:00:01, so that we don't have date interpretation problems
if ( T0.time() == QTime( 0, 0, 0 ) )
T0.setTime( QTime( 0, 0, 1 ) );
//If the Time is earlier than 6:00 am, assume the user wants the night of the previous date
if ( T0.time().hour() < 6 )
T0 = T0.addDays( -1 );
//Now, set time T0 to midnight (of the following day)
T0.setTime( QTime( 0, 0, 0 ) );
T0 = T0.addDays( 1 );
UT0 = geo->LTtoUT( T0 );
//Set the Tomorrow date/time to Noon the following day
Tomorrow = T0.addSecs( 12*3600 );
TomorrowUT = geo->LTtoUT( Tomorrow );
//Set the Evening date/time to 6:00 pm
Evening = T0.addSecs( -6*3600 );
EveningUT = geo->LTtoUT( Evening );
WUT->DateLabel->setText( i18n( "The night of %1", QLocale().toString( Evening.date(), QLocale::LongFormat ) ) );
init();
slotLoadList( WUT->CategoryListWidget->currentItem()->text() );
}
delete td;
}
void WUTDialog::slotChangeLocation() {
QPointer<LocationDialog> ld = new LocationDialog( this );
if ( ld->exec() == QDialog::Accepted ) {
GeoLocation *newGeo = ld->selectedCity();
if ( newGeo ) {
geo = newGeo;
UT0 = geo->LTtoUT( T0 );
TomorrowUT = geo->LTtoUT( Tomorrow );
EveningUT = geo->LTtoUT( Evening );
WUT->LocationLabel->setText( i18n( "at %1", geo->fullName() ) );
init();
slotLoadList( WUT->CategoryListWidget->currentItem()->text() );
}
}
delete ld;
}
void WUTDialog::slotEveningMorning( int index ) {
if ( EveningFlag != index ) {
EveningFlag = index;
init();
slotLoadList( WUT->CategoryListWidget->currentItem()->text() );
}
}
void WUTDialog::updateMag() {
m_Mag = WUT->MagnitudeEdit->value();
init();
slotLoadList( WUT->CategoryListWidget->currentItem()->text() );
}
void WUTDialog::slotChangeMagnitude() {
if( timer ) {
timer->stop();
} else {
timer = new QTimer( this );
timer->setSingleShot( true );
connect( timer, SIGNAL( timeout() ), this, SLOT( updateMag() ) );
}
timer->start( 500 );
}
|
gpl-2.0
|
RandallFlagg/kgbarchiver
|
KGB Archiver 1/gpl/kgb_arch_mfc/FolderDlg.cpp
|
8140
|
////////////////////////////////////////////////////////////////
// MSDN Magazine -- June 2005
// If this code works, it was written by Paul DiLascia.
// If not, I don't know who wrote it.
// Compiles with Visual Studio .NET 2003 (V7.1) on Windows XP. Tab size=3.
//
#include "stdafx.h"
#include "FolderDlg.h"
#include <shlwapi.h>
// You must link shlwapi.lib for StrRetToBuf
#pragma comment(lib, "shlwapi.lib")
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
BOOL CFolderDialog::bTRACE=0; // controls tracing
//////////////////
// For deugging: names of interfaces easier to read than GUIDs!
//
DEBUG_BEGIN_INTERFACE_NAMES()
DEBUG_INTERFACE_NAME(IFolderFilterSite)
DEBUG_INTERFACE_NAME(IFolderFilter)
DEBUG_END_INTERFACE_NAMES();
IMPLEMENT_DYNAMIC(CFolderDialog, CCmdTarget);
//////////////////
// ctor: initialize most stuff to NULL
//
CFolderDialog::CFolderDialog(CWnd* pWnd)
{
ASSERT(pWnd);
memset(&m_brinfo,0,sizeof(m_brinfo));
m_brinfo.hwndOwner=pWnd->m_hWnd; // use parent window
m_bFilter = FALSE; // default: no filtering
SHGetDesktopFolder(&m_shfRoot); // get root IShellFolder
}
//////////////////
// dtor: detach browser window before it's destroyed!
//
CFolderDialog::~CFolderDialog()
{
}
//////////////////
// Browse for folder. Args are same as for SHBrowseForFolder, but with extra
// bFilter that tells whether to do custom filtering. Note this requires
// BIF_NEWDIALOGSTYLE, which is inconsistent with some other flags--be
// careful!
//
LPCITEMIDLIST CFolderDialog::BrowseForFolder(LPCTSTR title, UINT flags,
LPCITEMIDLIST root, BOOL bFilter)
{
BFTRACE(_T("CFolderDialog::BrowseForFolder\n"));
TCHAR* buf = m_sDisplayName.GetBuffer(MAX_PATH);
m_brinfo.pidlRoot = root;
m_brinfo.pszDisplayName = buf;
m_brinfo.lpszTitle = title;
m_brinfo.ulFlags = flags;
m_brinfo.lpfn = CallbackProc;
m_brinfo.lParam = (LPARAM)this;
// filtering only supported for new-style dialogs
m_bFilter = bFilter;
ASSERT(!bFilter||(m_brinfo.ulFlags & BIF_NEWDIALOGSTYLE));
LPCITEMIDLIST pidl = SHBrowseForFolder(&m_brinfo); // do it
m_sDisplayName.ReleaseBuffer();
return pidl;
}
//////////////////
// Handy function to get the string pathname from pidl.
//
CString CFolderDialog::GetPathName(LPCITEMIDLIST pidl)
{
CString path;
TCHAR* buf = path.GetBuffer(MAX_PATH);
SHGetPathFromIDList(pidl, buf);
path.ReleaseBuffer();
return path;
}
//////////////////
// Handy function to get the display name from pidl.
//
CString CFolderDialog::GetDisplayNameOf(IShellFolder* psf, LPCITEMIDLIST pidl,
DWORD uFlags)
{
CString dn;
STRRET strret; // special struct for GetDisplayNameOf
strret.uType = STRRET_CSTR; // get as CSTR
if (SUCCEEDED(psf->GetDisplayNameOf(pidl, uFlags, &strret))) {
StrRetToBuf(&strret, pidl, dn.GetBuffer(MAX_PATH), MAX_PATH);
dn.ReleaseBuffer();
}
return dn;
}
//////////////////
// Free PIDL using shell's IMalloc
//
void CFolderDialog::FreePIDL(LPCITEMIDLIST pidl)
{
CComQIPtr<IMalloc> iMalloc; // shell's IMalloc
HRESULT hr = SHGetMalloc(&iMalloc);
ASSERT(SUCCEEDED(hr));
iMalloc->Free((void*)pidl);
}
//////////////////
// Internal callback proc used for SHBrowseForFolder passes control to
// appropriate virtual function after attaching browser window.
//
int CALLBACK CFolderDialog::CallbackProc(HWND hwnd,
UINT msg, LPARAM lp, LPARAM lpData)
{
CFolderDialog* pDlg = (CFolderDialog*)lpData;
ASSERT(pDlg);
if (pDlg->m_hWnd!=hwnd) {
if (pDlg->m_hWnd)
pDlg->UnsubclassWindow();
pDlg->SubclassWindow(hwnd);
}
return pDlg->OnMessage(msg, lp);
}
//////////////////
// Handle notification from browser window: parse args and pass to specific
// virtual handler function.
//
int CFolderDialog::OnMessage(UINT msg, LPARAM lp)
{
switch (msg) {
case BFFM_INITIALIZED:
OnInitialized();
return 0;
case BFFM_IUNKNOWN:
OnIUnknown((IUnknown*)lp);
return 0;
case BFFM_SELCHANGED:
OnSelChanged((LPCITEMIDLIST)lp);
return 0;
case BFFM_VALIDATEFAILED:
return OnValidateFailed((LPCTSTR)lp);
default:
TRACE(_T("***Warning: unknown message %d in CFolderDialog::OnMessage\n"));
}
return 0;
}
/////////////////
// Browser window initialized.
//
void CFolderDialog::OnInitialized()
{
BFTRACE(_T("CFolderDialog::OnInitialized\n"));
}
/////////////////
// Browser is notifying me with its IUnknown: use it to set filter if
// requested. Note this can be called with punk=NULL when shutting down!
//
void CFolderDialog::OnIUnknown(IUnknown* punk)
{
BFTRACE(_T("CFolderDialog::OnIUnknown: %p\n"), punk);
if (punk && m_bFilter) {
CComQIPtr<IFolderFilterSite> iffs;
VERIFY(SUCCEEDED(punk->QueryInterface(IID_IFolderFilterSite, (void**)&iffs)));
iffs->SetFilter((IFolderFilter*)&m_xFolderFilter);
// smart pointer automatically Releases iffs,
// no longer needed once you call SetFilter
}
}
//////////////////
// User selected a different folder.
//
void CFolderDialog::OnSelChanged(LPCITEMIDLIST pidl)
{
BFTRACE(_T("CFolderDialog::OnSelChanged: %s\n"),
GetDisplayNameOf(m_shfRoot, pidl, SHGDN_FORPARSING));
}
//////////////////
// User attempted to enter a name in the edit box that isn't a folder.
//
BOOL CFolderDialog::OnValidateFailed(LPCTSTR lpsz)
{
BFTRACE(_T("CFolderDialog::OnValidateFailed: %s\n"), lpsz);
return TRUE; // don't close dialog.
}
//////////////////
// Used for custom filtering. You must override to specify filter flags.
//
HRESULT CFolderDialog::OnGetEnumFlags(
IShellFolder* psf, // this folder's IShellFolder
LPCITEMIDLIST pidlFolder, // folder's PIDL
DWORD *pgrfFlags) // [out] return flags you want to allow
{
BFTRACE(_T("CFolderDialog::OnGetEnumFlags(%p): %s\n"),
psf, GetPathName(pidlFolder));
return S_OK;
}
//////////////////
// Used for custom filtering. You must override to filter items.
//
HRESULT CFolderDialog::OnShouldShow(
IShellFolder* psf, // This folder's IShellFolder
LPCITEMIDLIST pidlFolder, // PIDL for folder containing item
LPCITEMIDLIST pidlItem) // PIDL for item
{
BFTRACE(_T("CFolderDialog::OnShouldShow(%p): %s: %s\n"), psf,
GetDisplayNameOf(psf,pidlFolder,SHGDN_NORMAL),
GetDisplayNameOf(psf,pidlItem,SHGDN_NORMAL));
return S_OK;
}
//////////////// Standard MFC IUnknown -- nested classes call these ////////////////
STDMETHODIMP_(ULONG) CFolderDialog::AddRef()
{
BFTRACE(_T("CFolderDialog(%p)::AddRef\n"),this);
return ExternalAddRef();
}
STDMETHODIMP_(ULONG) CFolderDialog::Release()
{
BFTRACE(_T("CFolderDialog(%p)::Release\n"), this);
return ExternalRelease();
}
STDMETHODIMP CFolderDialog::QueryInterface(REFIID iid, LPVOID* ppvRet)
{
if (ppvRet==NULL)
return E_INVALIDARG;
BFTRACE(_T("CFolderDialog(%p)::QueryInterface(%s)\n"),this,_TR(iid));
HRESULT hr = ExternalQueryInterface(&iid, ppvRet);
BFTRACE(_T(">CFolderDialog::QueryInterface returns %s, *ppv=%p\n"),_TR(hr),*ppvRet);
return hr;
}
//////////////////////////////// IFolderFilter ////////////////////////////////
//
// Implementation passes control to parent class CFolderDialog (pThis)
//
BEGIN_INTERFACE_MAP(CFolderDialog, CCmdTarget)
INTERFACE_PART(CFolderDialog, IID_IFolderFilter, FolderFilter)
END_INTERFACE_MAP()
STDMETHODIMP_(ULONG) CFolderDialog::XFolderFilter::AddRef()
{
METHOD_PROLOGUE(CFolderDialog, FolderFilter);
return pThis->AddRef();
}
STDMETHODIMP_(ULONG) CFolderDialog::XFolderFilter::Release()
{
METHOD_PROLOGUE(CFolderDialog, FolderFilter);
return pThis->Release();
}
STDMETHODIMP CFolderDialog::XFolderFilter::QueryInterface(REFIID iid, LPVOID* ppv)
{
METHOD_PROLOGUE(CFolderDialog, FolderFilter);
return pThis->QueryInterface(iid, ppv);
}
// Note: pHwnd is always NULL here as far as I can tell.
STDMETHODIMP CFolderDialog::XFolderFilter::GetEnumFlags(IShellFolder* psf,
LPCITEMIDLIST pidlFolder, HWND *pHwnd, DWORD *pgrfFlags)
{
METHOD_PROLOGUE(CFolderDialog, FolderFilter);
return pThis->OnGetEnumFlags(psf, pidlFolder, pgrfFlags);
}
STDMETHODIMP CFolderDialog::XFolderFilter::ShouldShow(IShellFolder* psf,
LPCITEMIDLIST pidlFolder, LPCITEMIDLIST pidlItem)
{
METHOD_PROLOGUE(CFolderDialog, FolderFilter);
return pThis->OnShouldShow(psf, pidlFolder, pidlItem);
}
|
gpl-2.0
|
iammyr/Benchmark
|
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest03962.java
|
2238
|
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest03962")
public class BenchmarkTest03962 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.util.Map<String,String[]> map = request.getParameterMap();
String param = "";
if (!map.isEmpty()) {
param = map.get("foo")[0];
}
String bar;
// Simple if statement that assigns param to bar on true condition
int i = 196;
if ( (500/42) + i > 200 )
bar = param;
else bar = "This should never happen";
try {
double rand = java.security.SecureRandom.getInstance("SHA1PRNG").nextDouble();
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
}
}
|
gpl-2.0
|
mekolat/ManaPlus
|
src/gui/popups/skillpopup.cpp
|
7513
|
/*
* The ManaPlus Client
* Copyright (C) 2008 The Legend of Mazzeroth Development Team
* Copyright (C) 2008-2009 The Mana World Development Team
* Copyright (C) 2009-2010 The Mana Developers
* Copyright (C) 2011-2018 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gui/popups/skillpopup.h"
#include "gui/gui.h"
#include "gui/fonts/font.h"
#include "gui/widgets/label.h"
#include "gui/widgets/textbox.h"
#include "utils/gettext.h"
#include "utils/stringutils.h"
#include "resources/skill/skilldata.h"
#include "resources/skill/skillinfo.h"
#include "debug.h"
SkillPopup *skillPopup = nullptr;
SkillPopup::SkillPopup() :
Popup("SkillPopup", "skillpopup.xml"),
mSkillName(new Label(this)),
mSkillDesc(new TextBox(this)),
mSkillEffect(new TextBox(this)),
mSkillLevel(new TextBox(this)),
mSkillCastType(new TextBox(this)),
mCastType(CastType::Default),
mLastId(0U),
mLastLevel(-1),
mOffsetX(0),
mOffsetY(0)
{
mSkillName->setFont(boldFont);
mSkillName->setPosition(0, 0);
mSkillName->setForegroundColorAll(
getThemeColor(ThemeColorId::POPUP, 255U),
getThemeColor(ThemeColorId::POPUP_OUTLINE, 255U));
const int fontHeight = getFont()->getHeight();
mSkillDesc->setEditable(false);
mSkillDesc->setPosition(0, fontHeight);
mSkillDesc->setForegroundColorAll(
getThemeColor(ThemeColorId::POPUP, 255U),
getThemeColor(ThemeColorId::POPUP_OUTLINE, 255U));
mSkillEffect->setEditable(false);
mSkillEffect->setPosition(0, 2 * fontHeight);
mSkillEffect->setForegroundColorAll(
getThemeColor(ThemeColorId::POPUP, 255U),
getThemeColor(ThemeColorId::POPUP_OUTLINE, 255U));
mSkillLevel->setEditable(false);
mSkillLevel->setPosition(0, 3 * fontHeight);
mSkillLevel->setForegroundColorAll(
getThemeColor(ThemeColorId::POPUP, 255U),
getThemeColor(ThemeColorId::POPUP_OUTLINE, 255U));
mSkillCastType->setEditable(false);
mSkillCastType->setPosition(0, 4 * fontHeight);
mSkillCastType->setForegroundColorAll(
getThemeColor(ThemeColorId::POPUP, 255U),
getThemeColor(ThemeColorId::POPUP_OUTLINE, 255U));
}
void SkillPopup::postInit()
{
Popup::postInit();
add(mSkillName);
add(mSkillDesc);
add(mSkillEffect);
add(mSkillLevel);
add(mSkillCastType);
addMouseListener(this);
}
SkillPopup::~SkillPopup()
{
}
void SkillPopup::show(const SkillInfo *const skill,
const int level,
const CastTypeT castType,
const int offsetX,
const int offsetY)
{
if ((skill == nullptr) ||
(skill->data == nullptr) ||
(skill->id == mLastId &&
level == mLastLevel &&
castType == mCastType &&
offsetX == mOffsetX &&
offsetY == mOffsetY))
{
return;
}
mLastId = skill->id;
mLastLevel = level;
mCastType = castType;
mOffsetX = offsetX;
mOffsetY = offsetY;
mSkillName->setCaption(skill->data->dispName);
mSkillName->adjustSize();
mSkillName->setPosition(0, 0);
std::string description = skill->data->description;
std::string effect = skill->skillEffect;
if (description.empty())
{
description = effect;
effect.clear();
}
mSkillDesc->setTextWrapped(description, 196);
mSkillEffect->setTextWrapped(effect, 196);
if (level != 0)
{
mSkillLevel->setTextWrapped(strprintf(
// TRANSLATORS: skill level
_("Level: %d / %d"), level, skill->level),
196);
}
else
{
if (skill->level != 0)
{
mSkillLevel->setTextWrapped(strprintf(
// TRANSLATORS: skill level
_("Level: %d"), skill->level),
196);
}
else
{
mSkillLevel->setTextWrapped(
// TRANSLATORS: skill level for tmw fake skills
_("Level: Unknown"),
196);
}
}
std::string castStr;
switch (castType)
{
case CastType::Default:
default:
// TRANSLATORS: skill cast type
castStr = _("Default");
break;
case CastType::Target:
// TRANSLATORS: skill cast type
castStr = _("Target");
break;
case CastType::Position:
// TRANSLATORS: skill cast type
castStr = _("Mouse position");
break;
case CastType::Self:
// TRANSLATORS: skill cast type
castStr = _("Self position");
break;
}
if (offsetX != 0 ||
offsetY != 0)
{
castStr.append(strprintf(" (%+d,%+d)",
offsetX,
offsetY));
}
mSkillCastType->setTextWrapped(strprintf(
// TRANSLATORS: skill cast type
_("Cast type: %s"),
castStr.c_str()), 196);
int minWidth = mSkillName->getWidth();
if (mSkillName->getWidth() > minWidth)
minWidth = mSkillName->getWidth();
if (mSkillDesc->getMinWidth() > minWidth)
minWidth = mSkillDesc->getMinWidth();
if (mSkillEffect->getMinWidth() > minWidth)
minWidth = mSkillEffect->getMinWidth();
if (mSkillLevel->getMinWidth() > minWidth)
minWidth = mSkillLevel->getMinWidth();
if (mSkillCastType->getMinWidth() > minWidth)
minWidth = mSkillCastType->getMinWidth();
const int numRowsDesc = mSkillDesc->getNumberOfRows();
const int numRowsEffect = mSkillEffect->getNumberOfRows();
const int numRowsLevel = mSkillLevel->getNumberOfRows();
const int numRowsCast = mSkillCastType->getNumberOfRows();
const int height = getFont()->getHeight();
if (skill->skillEffect.empty())
{
setContentSize(minWidth,
(numRowsDesc + numRowsLevel + numRowsCast + 1) * height);
mSkillLevel->setPosition(0, (numRowsDesc + 1) * height);
mSkillCastType->setPosition(0, (numRowsDesc + 2) * height);
}
else
{
setContentSize(minWidth,
(numRowsDesc + numRowsLevel + numRowsEffect + numRowsCast + 1) *
height);
mSkillEffect->setPosition(0, (numRowsDesc + 1) * height);
mSkillLevel->setPosition(0,
(numRowsDesc + numRowsEffect + 1) * height);
mSkillCastType->setPosition(0,
(numRowsDesc + numRowsEffect + 2) * height);
}
mSkillDesc->setPosition(0, 1 * height);
}
void SkillPopup::mouseMoved(MouseEvent &event)
{
Popup::mouseMoved(event);
// When the mouse moved on top of the popup, hide it
setVisible(Visible_false);
mLastId = 0;
}
void SkillPopup::reset()
{
mLastId = 0;
mLastLevel = 0;
mCastType = CastType::Default;
mOffsetX = 0;
mOffsetY = 0;
}
|
gpl-2.0
|
stanfordreview/site
|
wp-content/plugins/subscribe2/classes/class-s2-admin.php
|
47206
|
<?php
class s2_admin extends s2class {
/* ===== WordPress menu registration and scripts ===== */
/**
Hook the menu
*/
function admin_menu() {
add_menu_page(__('Subscribe2', 'subscribe2'), __('Subscribe2', 'subscribe2'), apply_filters('s2_capability', "read", 'user'), 's2', NULL, S2URL . 'include/email_edit.png');
$s2user = add_submenu_page('s2', __('Your Subscriptions', 'subscribe2'), __('Your Subscriptions', 'subscribe2'), apply_filters('s2_capability', "read", 'user'), 's2', array(&$this, 'user_menu'), S2URL . 'include/email_edit.png');
add_action("admin_print_scripts-$s2user", array(&$this, 'checkbox_form_js'));
add_action("admin_print_styles-$s2user", array(&$this, 'user_admin_css'));
add_action('load-' . $s2user, array(&$this, 'user_help'));
if( file_exists(dirname(plugin_dir_path( __FILE__ ) ).'/readygraph-extension.php')) {
global $menu_slug;
$s2readygraph = add_submenu_page('s2', __('Readygraph App', 'subscribe2'), __('Readygraph App', 'subscribe2'), apply_filters('s2_capability', "manage_options", 'readygraph'), $menu_slug, array(&$this, 'readygraph_menu'));
}
else {
}
//add_action("admin_print_scripts-$s2readygraph", array(&$this, 'readygraph_js'));
$s2subscribers = add_submenu_page('s2', __('Subscribers', 'subscribe2'), __('Subscribers', 'subscribe2'), apply_filters('s2_capability', "manage_options", 'manage'), 's2_tools', array(&$this, 'subscribers_menu'));
add_action("admin_print_scripts-$s2subscribers", array(&$this, 'checkbox_form_js'));
add_action('load-' . $s2subscribers, array(&$this, 'subscribers_help'));
$s2settings = add_submenu_page('s2', __('Settings', 'subscribe2'), __('Settings', 'subscribe2'), apply_filters('s2_capability', "manage_options", 'settings'), 's2_settings', array(&$this, 'settings_menu'));
add_action("admin_print_scripts-$s2settings", array(&$this, 'checkbox_form_js'));
add_action("admin_print_scripts-$s2settings", array(&$this, 'option_form_js'));
add_filter('plugin_row_meta', array(&$this, 'plugin_links'), 10, 2);
add_action('load-' . $s2settings, array(&$this, 'settings_help'));
$s2mail = add_submenu_page('s2', __('Send Email', 'subscribe2'), __('Send Email', 'subscribe2'), apply_filters('s2_capability', "publish_posts", 'send'), 's2_posts', array(&$this, 'write_menu'));
add_action('load-' . $s2mail, array(&$this, 'mail_help'));
if( file_exists(dirname(plugin_dir_path( __FILE__ ) ).'/readygraph-extension.php')) {
global $menu_slug;
$s2readygraph = add_submenu_page('s2', __('Go Premium', 'subscribe2'), __('Go Premium', 'subscribe2'), apply_filters('s2_capability', "manage_options", 'readygraph'), 'readygraph-go-premium', array(&$this, 'readygraph_premium'));
}
else {
}
$s2nonce = wp_hash('subscribe2');
} // end admin_menu()
/**
Contextual Help
*/
function user_help() {
$screen = get_current_screen();
if ( $this->subscribe2_options['email_freq'] != 'never' ) {
$screen->add_help_tab(array(
'id' => 's2-user-help1',
'title' => __('Overview', 'subscribe2'),
'content' => '<p>' . __('From this page you can opt in or out of receiving a periodical digest style email of blog posts.', 'subscribe2') . '</p>'
));
} else {
$screen->add_help_tab(array(
'id' => 's2-user-help1',
'title' => __('Overview', 'subscribe2'),
'content' => '<p>' . __('From this page you can control your subscription preferences. Choose the email format you wish to receive, which categories you would like to receive notification for and depending on the site settings which authors you would like to read.', 'subscribe2') . '</p>'
));
}
} // end user_help()
function subscribers_help() {
$screen = get_current_screen();
$screen->add_help_tab(array(
'id' => 's2-subscribers-help1',
'title' => __('Overview', 'subscribe2'),
'content' => '<p>' . __('From this page you can manage your subscribers.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-subscribers-help2',
'title' => __('Public Subscribers', 'subscribe2'),
'content' => '<p>' . __('Public Subscribers are subscribers who have used the plugin form and only provided their email address.', 'subscribe2') . '</p><p>'. __('On this page public subscribers can be viewed, searched, deleted and also toggled between Confirmed and Unconfirmed status.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-subscribers-help3',
'title' => __('Registered Subscribers', 'subscribe2'),
'content' => '<p>' . __('Registered Subscribers are subscribers who have registered in WordPress and have a username and password.', 'subscribe2') .
'</p><p>'. __('Registered Subscribers have greater personal control over their subscription. They can change the format of the email and also select which categories and authors they want to receive notifications about.', 'subscribe2') .
'</p><p>'. __('On this page registered subscribers can be viewed and searched. User accounts can be deleted from here with any posts created by those users being assigned to the currently logged in user. Bulk changes can be applied to all user settings changing their subscription email format and categories.', 'subscribe2') . '</p>'
));
} // end subscribers_help()
function settings_help() {
$screen = get_current_screen();
$screen->add_help_tab(array(
'id' => 's2-settings-help1',
'title' => __('Overview', 'subscribe2'),
'content' => '<p>' . __('From this page you can adjust the Settings for Subscribe2.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-settings-help2',
'title' => __('Email Settings', 'subscribe2'),
'content' => '<p>' . __('This section allows you to specify settings that apply to the emails generated by the site.', 'subscribe2') .
'</p><p>'. __('Emails can be sent to individual subscribers by setting the number of recipients per email to 1. A setting greater than one will group recipients together and make use of the BCC emails header. A setting of 0 sends a single email with all subscribers in one large BCC group. A setting of 1 looks less like spam email to filters but takes longer to process.', 'subscribe2').
'</p><p>'. __('This section is also where the sender of the email on this page is chosen. You can choose Post Author or your Blogname but it is recommended to create a user account with an email address that really exists and shares the same domain name as your site (the bit after the @ should be the same as your sites web address) and then use this account.', 'subscribe2') .
'</p><p>'. __('This page also configures the frequency of emails. This can be at the time new posts are made (per post) or periodically with an excerpt of each post made (digest). Additionally the post types (pages, private, password protected) can also be configured here.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-settings-help3',
'title' => __('Templates', 'subscribe2'),
'content' => '<p>' . __('This section allows you to customise the content of your notification emails.', 'subscribe2') .
'</p><p>'. __('There are special {KEYWORDS} that are used by Subscribe2 to place content into the final email. The template also accepts regular text and HTML as desired in the final emails.', 'subscribe2') .
'</p><p>'. __('The {KEYWORDS} are listed on the right of the templates, note that some are for per post emails only and some are for digest emails only. Make sure the correct keywords are used based upon the Email Settings.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-settings-help4',
'title' => __('Registered Users', 'subscribe2'),
'content' => '<p>' . __('This section allows settings that apply to Registered Subscribers to be configured.', 'subscribe2') .
'</p><p>'. __('Categories can be made compulsory so emails are always sent for posts in these categories. They can also be excludes so that emails are not generated. Excluded categories take precedence over Compulsory categories.', 'subscribe2') .
'</p><p>'. __('A set of default settings for new users can also be specified using the Auto Subscribe section. Settings specified here will be applied to any newly created user accounts while Subscribe2 is activated.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-settings-help5',
'title' => __('Appearance', 'subscribe2'),
'content' => '<p>' . __('This section allows you to enable several aspect of the plugin such as Widgets and editor buttons.', 'subscribe2') .
'</p><p>'. __('AJAX mode can be enabled that is intended to work with the shortcode link parameter so that a dialog opens in the centre of the browser rather then using the regular form.', 'subscribe2') .
'</p><p>'. __('The email over ride check box can be set to be automatically checked for every new post and page from here to, this may be useful if you will only want to send very occasional notifications for specific posts. You can then uncheck this box just before you publish your content.', 'subscribe2') . '</p>'
));
$screen->add_help_tab(array(
'id' => 's2-settings-help6',
'title' => __('Miscellaneous', 'subscribe2'),
'content' => '<p>' . __('This section contains a place to bar specified domains from becoming Public Subscribers and links to help and support pages.', 'subscribe2') .
'</p><p>'. __('In the paid Subscribe2 HTML version there is also a place here to enter a license code so that updates can be accessed automatically.', 'subscribe2') .
'</p>'
));
} // end settings_help()
function mail_help() {
$screen = get_current_screen();
$screen->add_help_tab(array(
'id' => 's2-send-mail-help1',
'title' => __('Overview', 'subscribe2'),
'content' => '<p>' . __('From this page you can send emails to the recipients in the group selected in the drop down.', 'subscribe2') .
'</p><p>' . __('<strong>Preview</strong> will send a preview of the email to the currently logged in user. <strong>Send</strong> will send the email to the recipient list.', 'subscribe2') . '</p>'
));
} // end send_email_help()
/**
Hook for Admin Drop Down Icons
*/
function ozh_s2_icon() {
return S2URL . 'include/email_edit.png';
} // end ozh_s2_icon()
/**
Insert Javascript and CSS into admin_header
*/
function checkbox_form_js() {
wp_register_script('s2_checkbox', S2URL . 'include/s2_checkbox' . $this->script_debug . '.js', array('jquery'), '1.3');
wp_enqueue_script('s2_checkbox');
} //end checkbox_form_js()
function user_admin_css() {
wp_register_style('s2_user_admin', S2URL . 'include/s2_user_admin.css', array(), '1.0');
wp_enqueue_style('s2_user_admin');
} // end user_admin_css()
function option_form_js() {
wp_register_script('s2_edit', S2URL . 'include/s2_edit' . $this->script_debug . '.js', array('jquery'), '1.1');
wp_enqueue_script('s2_edit');
wp_enqueue_script('jquery-ui-datepicker');
wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css');
wp_register_script('s2_date_time', S2URL . 'include/s2_date_time' . $this->script_debug . '.js', array('jquery-ui-datepicker'), '1.0');
wp_enqueue_script('s2_date_time');
} // end option_form_js()
/**
Enqueue jQuery for ReadyGraph
*/
/* function readygraph_js() {
wp_enqueue_script('jquery');
wp_register_script('s2_readygraph', S2URL . 'include/s2_readygraph' . $this->script_debug . '.js', array('jquery'), '1.0');
wp_enqueue_script('s2_readygraph');
wp_localize_script('s2_readygraph', 'objectL10n', array(
'emailempty' => __('Email is empty!', 'subscribe2'),
'passwordempty' => __('Password is empty!', 'subscribe2'),
'urlempty' => __('Site URL is empty!', 'subscribe2'),
'passwordmatch' => __('Password is not matching!', 'subscribe2')
) );
} // end readygraph_js()
*/
/**
Adds a links directly to the settings page from the plugin page
*/
function plugin_links($links, $file) {
if ( $file == S2DIR.'subscribe2.php' ) {
$links[] = "<a href='admin.php?page=s2_settings'>" . __('Settings', 'subscribe2') . "</a>";
$links[] = "<a href='http://plugins.trac.wordpress.org/browser/subscribe2/i18n/'>" . __('Translation Files', 'subscribe2') . "</a>";
$links[] = "<a href='https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2387904'><b>" . __('Donate', 'subscribe2') . "</b></a>";
}
return $links;
} // end plugin_links()
/* ===== Menus ===== */
/**
Our subscriber management page
*/
function subscribers_menu() {
require_once(S2PATH . 'admin/subscribers.php');
} // end subscribers_menu()
/**
Our ReadyGraph API page
*/
function readygraph_menu() {
global $wpdb;
$current_page = isset($_GET['ac']) ? $_GET['ac'] : '';
switch($current_page)
{
case 'signup-popup':
include(S2PATH . 'extension/readygraph/signup-popup.php');
break;
case 'go-premium':
include(S2PATH . 'extension/readygraph/go-premium.php');
break;
case 'social-feed':
include(S2PATH . 'extension/readygraph/social-feed.php');
break;
case 'site-profile':
include(S2PATH . 'extension/readygraph/site-profile.php');
break;
case 'customize-emails':
include(S2PATH . 'extension/readygraph/customize-emails.php');
break;
case 'deactivate-readygraph':
include(S2PATH . 'extension/readygraph/deactivate-readygraph.php');
break;
case 'welcome-email':
include(S2PATH . 'extension/readygraph/welcome-email.php');
break;
case 'retention-email':
include(S2PATH . 'extension/readygraph/retention-email.php');
break;
case 'invitation-email':
include(S2PATH . 'extension/readygraph/invitation-email.php');
break;
case 'faq':
include(S2PATH . 'extension/readygraph/faq.php');
break;
default:
include(S2PATH . 'extension/readygraph/admin.php');
break;
}
} // end readygraph_menu()
/**
Our Readygraph Premium Page
*/
function readygraph_premium() {
include(S2PATH . 'extension/readygraph/go-premium.php');
} // end settings_menu()
/**
Our settings page
*/
function settings_menu() {
require_once(S2PATH . 'admin/settings.php');
} // end settings_menu()
/**
Our profile menu
*/
function user_menu() {
require_once(S2PATH . 'admin/your_subscriptions.php');
} // end user_menu()
/**
Display the Write sub-menu
*/
function write_menu() {
require_once(S2PATH . 'admin/send_email.php');
} // end write_menu()
/* ===== Write Toolbar Button Functions ===== */
/**
Register our button in the QuickTags bar
*/
function button_init() {
global $pagenow;
if ( !in_array($pagenow, array('post-new.php', 'post.php', 'page-new.php', 'page.php')) ) { return; }
if ( !current_user_can('edit_posts') && !current_user_can('edit_pages') ) { return; }
if ( 'true' == get_user_option('rich_editing') ) {
// Hook into the rich text editor
add_filter('mce_external_plugins', array(&$this, 'mce_plugin'));
add_filter('mce_buttons', array(&$this, 'mce_button'));
} else {
wp_enqueue_script('subscribe2_button', S2URL . 'include/s2_button' . $this->script_debug . '.js', array('quicktags'), '2.0' );
}
} // end button_init()
/**
Add buttons for Rich Text Editor
*/
function mce_plugin($arr) {
if ( version_compare($this->wp_release, '3.9', '<') ) {
$path = S2URL . 'tinymce/editor_plugin3' . $this->script_debug . '.js';
} else {
$path = S2URL . 'tinymce/editor_plugin4' . $this->script_debug . '.js';
}
$arr['subscribe2'] = $path;
return $arr;
} // end mce_plugin()
function mce_button($arr) {
$arr[] = 'subscribe2';
return $arr;
} // end mce_button()
/* ===== widget functions ===== */
/**
Function to add css and js files to admin header
*/
function widget_s2counter_css_and_js() {
// ensure we only add colorpicker js to widgets page
if ( stripos($_SERVER['REQUEST_URI'], 'widgets.php' ) !== false ) {
wp_enqueue_style('farbtastic');
wp_enqueue_script('farbtastic');
wp_register_script('s2_colorpicker', S2URL . 'include/s2_colorpicker' . $this->script_debug . '.js', array('farbtastic'), '1.2');
wp_enqueue_script('s2_colorpicker');
}
} // end widget_s2_counter_css_and_js()
/**
Function to to handle activate redirect
*/
/*function on_plugin_activated_redirect(){
$setting_url="admin.php?page=s2_readygraph";
if ( get_option('s2_do_activation_redirect', false) ) {
delete_option('s2_do_activation_redirect');
wp_redirect($setting_url);
}
} // end on_plugin_activated_redirect()
*/
/* ===== meta box functions to allow per-post override ===== */
/**
Create meta box on write pages
*/
function s2_meta_init() {
add_meta_box('subscribe2', __('Subscribe2 Notification Override', 'subscribe2' ), array(&$this, 's2_meta_box'), 'post', 'advanced');
add_meta_box('subscribe2', __('Subscribe2 Notification Override', 'subscribe2' ), array(&$this, 's2_meta_box'), 'page', 'advanced');
} // end s2_meta_init()
/**
Meta box code
*/
function s2_meta_box() {
global $post_ID;
$s2mail = get_post_meta($post_ID, '_s2mail', true);
echo "<input type=\"hidden\" name=\"s2meta_nonce\" id=\"s2meta_nonce\" value=\"" . wp_create_nonce(wp_hash(plugin_basename(__FILE__))) . "\" />";
echo __("Check here to disable sending of an email notification for this post/page", 'subscribe2');
echo " <input type=\"checkbox\" name=\"s2_meta_field\" value=\"no\"";
if ( $s2mail == 'no' || ($this->subscribe2_options['s2meta_default'] == "1" && $s2mail == "") ) {
echo " checked=\"checked\"";
}
echo " />";
} // end s2_meta_box()
/**
Meta box form handler
*/
function s2_meta_handler($post_id) {
if ( !isset($_POST['s2meta_nonce']) || !wp_verify_nonce($_POST['s2meta_nonce'], wp_hash(plugin_basename(__FILE__))) ) { return $post_id; }
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can('edit_page', $post_id) ) { return $post_id; }
} else {
if ( !current_user_can('edit_post', $post_id) ) { return $post_id; }
}
if ( isset($_POST['s2_meta_field']) && $_POST['s2_meta_field'] == 'no' ) {
update_post_meta($post_id, '_s2mail', $_POST['s2_meta_field']);
} else {
update_post_meta($post_id, '_s2mail', 'yes');
}
} // end s2_meta_box_handler()
/* ===== WordPress menu helper functions ===== */
/**
Collects the signup date for all public subscribers
*/
function signup_date($email = '') {
if ( '' == $email ) { return false; }
global $wpdb;
if ( !empty($this->signup_dates) ) {
return $this->signup_dates[$email];
} else {
$results = $wpdb->get_results("SELECT email, date FROM $this->public", ARRAY_N);
foreach ( $results as $result ) {
$this->signup_dates[$result[0]] = $result[1];
}
return $this->signup_dates[$email];
}
} // end signup_date()
/**
Collects the ip address for all public subscribers
*/
function signup_ip($email = '') {
if ( '' == $email ) {return false; }
global $wpdb;
if ( !empty($this->signup_ips) ) {
return $this->signup_ips[$email];
} else {
$results = $wpdb->get_results("SELECT email, ip FROM $this->public", ARRAY_N);
foreach ( $results as $result ) {
$this->signup_ips[$result[0]] = $result[1];
}
return $this->signup_ips[$email];
}
} // end signup_ip()
/**
Export subscriber emails and other details to CSV
*/
function prepare_export( $subscribers ) {
if ( empty($subscribers) ) { return; }
$subscribers = explode(",\r\n", $subscribers);
natcasesort($subscribers);
$exportcsv = _x('User Email,User Type,User Name,Confirm Date,IP', 'Comma Separated Column Header names for CSV Export' , 'subscribe2');
$all_cats = $this->all_cats(false, 'ID');
foreach ($all_cats as $cat) {
$exportcsv .= "," . html_entity_decode($cat->cat_name, ENT_QUOTES);
$cat_ids[] = $cat->term_id;
}
$exportcsv .= "\r\n";
if ( !function_exists('get_userdata') ) {
require_once(ABSPATH . WPINC . '/pluggable.php');
}
foreach ( $subscribers as $subscriber ) {
if ( $this->is_registered($subscriber) ) {
$user_ID = $this->get_user_id( $subscriber );
$user_info = get_userdata( $user_ID );
$cats = explode(',', get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true));
$subscribed_cats = '';
foreach ( $cat_ids as $cat ) {
(in_array($cat, $cats)) ? $subscribed_cats .= ",Yes" : $subscribed_cats .= ",No";
}
$exportcsv .= $subscriber . ',';
$exportcsv .= __('Registered User', 'subscribe2');
$exportcsv .= ',' . $user_info->display_name;
$exportcsv .= ',,' . $subscribed_cats . "\r\n";
} else {
if ( $this->is_public($subscriber) === '1' ) {
$exportcsv .= $subscriber . ',' . __('Confirmed Public Subscriber', 'subscribe2') . ',,' . $this->signup_date($subscriber) . ',' . $this->signup_ip($subscriber) . "\r\n";
} elseif ( $this->is_public($subscriber) === '0' ) {
$exportcsv .= $subscriber . ',' . __('Unconfirmed Public Subscriber', 'subscribe2') . ',,' . $this->signup_date($subscriber) . ',' . $this->signup_ip($subscriber) . "\r\n";
}
}
}
return $exportcsv;
} // end prepare_export()
/**
Display a table of categories with checkboxes
Optionally pre-select those categories specified
*/
function display_category_form($selected = array(), $override = 1, $compulsory = array(), $name = 'category') {
global $wpdb;
if ( $override == 0 ) {
$all_cats = $this->all_cats(true);
} else {
$all_cats = $this->all_cats(false);
}
$half = (count($all_cats) / 2);
$i = 0;
$j = 0;
echo "<table style=\"width: 100%; border-collapse: separate; border-spacing: 2px; *border-collapse: expression('separate', cellSpacing = '2px');\" class=\"editform\">\r\n";
echo "<tr><td style=\"text-align: left;\" colspan=\"2\">\r\n";
echo "<label><input type=\"checkbox\" name=\"checkall\" value=\"checkall_" . $name . "\" /> " . __('Select / Unselect All', 'subscribe2') . "</label>\r\n";
echo "</td></tr>\r\n";
echo "<tr style=\"vertical-align: top;\"><td style=\"width: 50%; text-align: left;\">\r\n";
foreach ( $all_cats as $cat ) {
if ( $i >= $half && 0 == $j ) {
echo "</td><td style=\"width: 50%; text-align: left;\">\r\n";
$j++;
}
$catName = '';
$parents = array_reverse( get_ancestors($cat->term_id, $cat->taxonomy) );
if ( $parents ) {
foreach ( $parents as $parent ) {
$parent = get_term($parent, $cat->taxonomy);
$catName .= $parent->name . ' » ';
}
}
$catName .= $cat->name;
if ( 0 == $j ) {
echo "<label><input class=\"checkall_" . $name . "\" type=\"checkbox\" name=\"" . $name . "[]\" value=\"" . $cat->term_id . "\"";
if ( in_array($cat->term_id, $selected) || in_array($cat->term_id, $compulsory) ) {
echo " checked=\"checked\"";
}
if ( in_array($cat->term_id, $compulsory) && $name === 'category' ) {
echo " DISABLED";
}
echo " /> <abbr title=\"" . $cat->slug . "\">" . $catName . "</abbr></label><br />\r\n";
} else {
echo "<label><input class=\"checkall_" . $name . "\" type=\"checkbox\" name=\"" . $name . "[]\" value=\"" . $cat->term_id . "\"";
if ( in_array($cat->term_id, $selected) || in_array($cat->term_id, $compulsory) ) {
echo " checked=\"checked\"";
}
if ( in_array($cat->term_id, $compulsory) && $name === 'category' ) {
echo " DISABLED";
}
echo " /> <abbr title=\"" . $cat->slug . "\">" . $catName . "</abbr></label><br />\r\n";
}
$i++;
}
if ( !empty($compulsory) ) {
foreach ($compulsory as $cat) {
echo "<input type=\"hidden\" name=\"" . $name . "[]\" value=\"" . $cat . "\">\r\n";
}
}
echo "</td></tr>\r\n";
echo "</table>\r\n";
} // end display_category_form()
/**
Display a table of post formats supported by the currently active theme
*/
function display_format_form($formats, $selected = array()) {
$half = (count($formats[0]) / 2);
$i = 0;
$j = 0;
echo "<table style=\"width: 100%; border-collapse: separate; border-spacing: 2px; *border-collapse: expression('separate', cellSpacing = '2px');\" class=\"editform\">\r\n";
echo "<tr><td style=\"text-align: left;\" colspan=\"2\">\r\n";
echo "<label><input type=\"checkbox\" name=\"checkall\" value=\"checkall_format\" /> " . __('Select / Unselect All', 'subscribe2') . "</label>\r\n";
echo "</td></tr>\r\n";
echo "<tr style=\"vertical-align: top;\"><td style=\"width: 50%; text-align: left\">\r\n";
foreach ( $formats[0] as $format ) {
if ( $i >= $half && 0 == $j ) {
echo "</td><td style=\"width: 50%; text-align: left\">\r\n";
$j++;
}
if ( 0 == $j ) {
echo "<label><input class=\"checkall_format\" type=\"checkbox\" name=\"format[]\" value=\"" . $format . "\"";
if ( in_array($format, $selected) ) {
echo " checked=\"checked\"";
}
echo " /> " . ucwords($format) . "</label><br />\r\n";
} else {
echo "<label><input class=\"checkall_format\" type=\"checkbox\" name=\"format[]\" value=\"" . $format . "\"";
if ( in_array($format, $selected) ) {
echo " checked=\"checked\"";
}
echo " /> " . ucwords($format) . "</label><br />\r\n";
}
$i++;
}
echo "</td></tr>\r\n";
echo "</table>\r\n";
} // end display_format_form()
/**
Display a table of authors with checkboxes
Optionally pre-select those authors specified
*/
function display_author_form($selected = array()) {
$all_authors = $this->get_authors();
$half = (count($all_authors) / 2);
$i = 0;
$j = 0;
echo "<table style=\"width: 100%; border-collapse: separate; border-spacing: 2px; *border-collapse: expression('separate', cellSpacing = '2px');\" class=\"editform\">\r\n";
echo "<tr><td style=\"text-align: left;\" colspan=\"2\">\r\n";
echo "<label><input type=\"checkbox\" name=\"checkall\" value=\"checkall_author\" /> " . __('Select / Unselect All', 'subscribe2') . "</label>\r\n";
echo "</td></tr>\r\n";
echo "<tr style=\"vertical-align: top;\"><td style=\"width: 50%; test-align: left;\">\r\n";
foreach ( $all_authors as $author ) {
if ( $i >= $half && 0 == $j ) {
echo "</td><td style=\"width: 50%; text-align: left;\">\r\n";
$j++;
}
if ( 0 == $j ) {
echo "<label><input class=\"checkall_author\" type=\"checkbox\" name=\"author[]\" value=\"" . $author->ID . "\"";
if ( in_array($author->ID, $selected) ) {
echo " checked=\"checked\"";
}
echo " /> " . $author->display_name . "</label><br />\r\n";
} else {
echo "<label><input class=\"checkall_author\" type=\"checkbox\" name=\"author[]\" value=\"" . $author->ID . "\"";
if ( in_array($author->ID, $selected) ) {
echo " checked=\"checked\"";
}
echo " /> " . $author->display_name . "</label><br />\r\n";
$i++;
}
}
echo "</td></tr>\r\n";
echo "</table>\r\n";
} // end display_author_form()
/**
Collect an array of all author level users and above
*/
function get_authors() {
if ( '' == $this->all_authors ) {
$role = array('fields' => array('ID', 'display_name'), 'role' => 'administrator');
$administrators = get_users( $role );
$role = array('fields' => array('ID', 'display_name'), 'role' => 'editor');
$editors = get_users( $role );
$role = array('fields' => array('ID', 'display_name'), 'role' => 'author');
$authors = get_users( $role );
$this->all_authors = array_merge($administrators, $editors, $authors);
}
return apply_filters('s2_authors', $this->all_authors);
} // end get_authors()
/**
Display a drop-down form to select subscribers
$selected is the option to select
$submit is the text to use on the Submit button
*/
function display_subscriber_dropdown($selected = 'registered', $submit = '', $exclude = array()) {
global $wpdb;
$who = array('all' => __('All Users and Subscribers', 'subscribe2'),
'public' => __('Public Subscribers', 'subscribe2'),
'confirmed' => ' ' . __('Confirmed', 'subscribe2'),
'unconfirmed' => ' ' . __('Unconfirmed', 'subscribe2'),
'all_users' => __('All Registered Users', 'subscribe2'),
'registered' => __('Registered Subscribers', 'subscribe2'));
$all_cats = $this->all_cats(false);
// count the number of subscribers
$count['confirmed'] = $wpdb->get_var("SELECT COUNT(id) FROM $this->public WHERE active='1'");
$count['unconfirmed'] = $wpdb->get_var("SELECT COUNT(id) FROM $this->public WHERE active='0'");
if ( in_array('unconfirmed', $exclude) ) {
$count['public'] = $count['confirmed'];
} elseif ( in_array('confirmed', $exclude) ) {
$count['public'] = $count['unconfirmed'];
} else {
$count['public'] = ($count['confirmed'] + $count['unconfirmed']);
}
if ( $this->s2_mu ) {
$count['all_users'] = $wpdb->get_var("SELECT COUNT(meta_key) FROM $wpdb->usermeta WHERE meta_key='" . $wpdb->prefix . "capabilities'");
} else {
$count['all_users'] = $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users");
}
if ( $this->s2_mu ) {
$count['registered'] = $wpdb->get_var($wpdb->prepare("SELECT COUNT(b.meta_key) FROM $wpdb->usermeta AS a INNER JOIN $wpdb->usermeta AS b ON a.user_id = b.user_id WHERE a.meta_key='" . $wpdb->prefix . "capabilities' AND b.meta_key=%s AND b.meta_value <> ''", $this->get_usermeta_keyname('s2_subscribed')));
} else {
$count['registered'] = $wpdb->get_var($wpdb->prepare("SELECT COUNT(meta_key) FROM $wpdb->usermeta WHERE meta_key=%s AND meta_value <> ''", $this->get_usermeta_keyname('s2_subscribed')));
}
$count['all'] = ($count['confirmed'] + $count['unconfirmed'] + $count['all_users']);
// get subscribers to individual categories but only if we are using per-post notifications
if ( $this->subscribe2_options['email_freq'] == 'never' ) {
$compulsory = explode(',', $this->subscribe2_options['compulsory']);
if ( $this->s2_mu ) {
foreach ( $all_cats as $cat ) {
if ( in_array($cat->term_id, $compulsory) ) {
$count[$cat->name] = $count['all_users'];
} else {
$count[$cat->name] = $wpdb->get_var($wpdb->prepare("SELECT COUNT(a.meta_key) FROM $wpdb->usermeta AS a INNER JOIN $wpdb->usermeta AS b ON a.user_id = b.user_id WHERE a.meta_key='" . $wpdb->prefix . "capabilities' AND b.meta_key=%s", $this->get_usermeta_keyname('s2_cat') . $cat->term_id));
}
}
} else {
foreach ( $all_cats as $cat ) {
if ( in_array($cat->term_id, $compulsory) ) {
$count[$cat->name] = $count['all_users'];
} else {
$count[$cat->name] = $wpdb->get_var($wpdb->prepare("SELECT COUNT(meta_value) FROM $wpdb->usermeta WHERE meta_key=%s", $this->get_usermeta_keyname('s2_cat') . $cat->term_id));
}
}
}
}
// do have actually have some subscribers?
if ( 0 == $count['confirmed'] && 0 == $count['unconfirmed'] && 0 == $count['all_users'] ) {
// no? bail out
return;
}
echo "<select name=\"what\">\r\n";
foreach ( $who as $whom => $display ) {
if ( in_array($whom, $exclude) ) { continue; }
if ( 0 == $count[$whom] ) { continue; }
echo "<option value=\"" . $whom . "\"";
if ( $whom == $selected ) { echo " selected=\"selected\" "; }
echo ">$display (" . ($count[$whom]) . ")</option>\r\n";
}
if ( $count['registered'] > 0 && $this->subscribe2_options['email_freq'] == 'never' ) {
foreach ( $all_cats as $cat ) {
if ( in_array($cat->term_id, $exclude) ) { continue; }
echo "<option value=\"" . $cat->term_id . "\"";
if ( $cat->term_id == $selected ) { echo " selected=\"selected\" "; }
echo "> " . $cat->name . " (" . $count[$cat->name] . ") </option>\r\n";
}
}
echo "</select>";
if ( false !== $submit ) {
echo " <input type=\"submit\" class=\"button-secondary\" value=\"$submit\" />\r\n";
}
} // end display_subscriber_dropdown()
/**
Display a drop down list of administrator level users and
optionally include a choice for Post Author
*/
function admin_dropdown($inc_author = false) {
global $wpdb;
$args = array('fields' => array('ID', 'display_name'), 'role' => 'administrator');
$wp_user_query = get_users( $args );
if ( !empty($wp_user_query) ) {
foreach ($wp_user_query as $user) {
$admins[] = $user;
}
} else {
$admins = array();
}
if ( $inc_author ) {
$author[] = (object)array('ID' => 'author', 'display_name' => __('Post Author', 'subscribe2'));
$author[] = (object)array('ID' => 'blogname', 'display_name' => html_entity_decode(get_option('blogname'), ENT_QUOTES));
$admins = array_merge($author, $admins);
}
echo "<select name=\"sender\">\r\n";
foreach ( $admins as $admin ) {
echo "<option value=\"" . $admin->ID . "\"";
if ( $admin->ID == $this->subscribe2_options['sender'] ) {
echo " selected=\"selected\"";
}
echo ">" . $admin->display_name . "</option>\r\n";
}
echo "</select>\r\n";
} // end admin_dropdown()
/**
Display a dropdown of choices for digest email frequency
and give user details of timings when event is scheduled
*/
function display_digest_choices() {
global $wpdb;
$cron_file = ABSPATH . 'wp-cron.php';
if ( !is_readable($cron_file) ) {
echo "<strong><em style=\"color: red\">" . __('The WordPress cron functions may be disabled on this server. Digest notifications may not work.', 'subscribe2') . "</em></strong><br />\r\n";
}
$scheduled_time = wp_next_scheduled('s2_digest_cron');
$offset = get_option('gmt_offset') * 60 * 60;
$schedule = (array)wp_get_schedules();
$schedule = array_merge(array('never' => array('interval' => 0, 'display' => __('For each Post', 'subscribe2'))), $schedule);
$sort = array();
foreach ( (array)$schedule as $key => $value ) {
$sort[$key] = $value['interval'];
}
asort($sort);
$schedule_sorted = array();
foreach ( $sort as $key => $value ) {
$schedule_sorted[$key] = $schedule[$key];
}
foreach ( $schedule_sorted as $key => $value ) {
echo "<label><input type=\"radio\" name=\"email_freq\" value=\"" . $key . "\"" . checked($this->subscribe2_options['email_freq'], $key, false) . " />";
echo " " . $value['display'] . "</label><br />\r\n";
}
if ( $scheduled_time ) {
$date_format = get_option('date_format');
$time_format = get_option('time_format');
echo "<p>" . __('Current UTC time is', 'subscribe2') . ": \r\n";
echo "<strong>" . date_i18n($date_format . " @ " . $time_format, false, 'gmt') . "</strong></p>\r\n";
echo "<p>" . __('Current blog time is', 'subscribe2') . ": \r\n";
echo "<strong>" . date_i18n($date_format . " @ " . $time_format) . "</strong></p>\r\n";
echo "<p>" . __('Next email notification will be sent when your blog time is after', 'subscribe2') . ": \r\n";
echo "<input type=\"hidden\" id=\"jscrondate\" value=\"" . date_i18n($date_format, $scheduled_time + $offset) . "\" />";
echo "<input type=\"hidden\" id=\"jscrontime\" value=\"" . date_i18n($time_format, $scheduled_time + $offset) . "\" />";
echo "<span id=\"s2cron_1\"><span id=\"s2crondate\" style=\"background-color: #FFFBCC\">" . date_i18n($date_format, $scheduled_time + $offset) . "</span>";
echo " @ <span id=\"s2crontime\" style=\"background-color: #FFFBCC\">" . date_i18n($time_format, $scheduled_time + $offset) . "</span> ";
echo "<a href=\"#\" onclick=\"s2_show('cron'); return false;\">" . __('Edit', 'subscribe2') . "</a></span>\n";
echo "<span id=\"s2cron_2\">\r\n";
echo "<input id=\"s2datepicker\" name=\"crondate\" value=\"" . date_i18n($date_format, $scheduled_time + $offset) . "\">\r\n";
$hours = array('12:00 am', '1:00 am', '2:00 am', '3:00 am', '4:00 am', '5:00 am', '6:00 am', '7:00 am', '8:00 am', '9:00 am', '10:00 am', '11:00 am', '12:00 pm', '1:00 pm', '2:00 pm', '3:00 pm', '4:00 pm', '5:00 pm', '6:00 pm', '7:00 pm', '8:00 pm', '9:00 pm', '10:00 pm', '11:00 pm');
$current_hour = intval(date_i18n('G', $scheduled_time + $offset));
echo "<select name=\"crontime\">\r\n";
foreach ( $hours as $key => $value ) {
echo "<option value=\"" . $key . "\"";
if ( !empty($scheduled_time) && $key === $current_hour ) {
echo " selected=\"selected\"";
}
echo ">" . $value . "</option>\r\n";
}
echo "</select>\r\n";
echo "<a href=\"#\" onclick=\"s2_cron_update('cron'); return false;\">". __('Update', 'subscribe2') . "</a>\n";
echo "<a href=\"#\" onclick=\"s2_cron_revert('cron'); return false;\">". __('Revert', 'subscribe2') . "</a></span>\n";
if ( !empty($this->subscribe2_options['last_s2cron']) ) {
echo "<p>" . __('Attempt to resend the last Digest Notification email', 'subscribe2') . ": ";
echo "<input type=\"submit\" class=\"button-secondary\" name=\"resend\" value=\"" . __('Resend Digest', 'subscribe2') . "\" /></p>\r\n";
}
} else {
echo "<br />";
}
} // end display_digest_choices()
/**
Create and display a dropdown list of pages
*/
function pages_dropdown($s2page) {
$pages = get_pages();
if ( empty($pages) ) { return; }
$option = '';
foreach ( $pages as $page ) {
$option .= "<option value=\"" . $page->ID . "\"";
if ( $page->ID == $s2page ) {
$option .= " selected=\"selected\"";
}
$option .= ">";
$parents = array_reverse( get_ancestors($page->ID, 'page') );
if ( $parents ) {
foreach ( $parents as $parent ) {
$option .= get_the_title($parent) . ' » ';
}
}
$option .= $page->post_title . "</option>\r\n";
}
echo $option;
} // end pages_dropdown()
/**
Subscribe all registered users to category selected on Admin Manage Page
*/
function subscribe_registered_users($emails = '', $cats = array()) {
if ( '' == $emails || '' == $cats ) { return false; }
global $wpdb;
$useremails = explode(",\r\n", $emails);
$useremails = implode(", ", array_map(array($this, 'prepare_in_data'), $useremails));
$sql = "SELECT ID FROM $wpdb->users WHERE user_email IN ($useremails)";
$user_IDs = $wpdb->get_col($sql);
foreach ( $user_IDs as $user_ID ) {
$old_cats = get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true);
if ( !empty($old_cats) ) {
$old_cats = explode(',', $old_cats);
$newcats = array_unique(array_merge($cats, $old_cats));
} else {
$newcats = $cats;
}
if ( !empty($newcats) && $newcats !== $old_cats) {
// add subscription to these cat IDs
foreach ( $newcats as $id ) {
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $id, $id);
}
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), implode(',', $newcats));
}
unset($newcats);
}
} // end subscribe_registered_users()
/**
Unsubscribe all registered users to category selected on Admin Manage Page
*/
function unsubscribe_registered_users($emails = '', $cats = array()) {
if ( '' == $emails || '' == $cats ) { return false; }
global $wpdb;
$useremails = explode(",\r\n", $emails);
$useremails = implode(", ", array_map(array($this, 'prepare_in_data'), $useremails));
$sql = "SELECT ID FROM $wpdb->users WHERE user_email IN ($useremails)";
$user_IDs = $wpdb->get_col($sql);
foreach ( $user_IDs as $user_ID ) {
$old_cats = explode(',', get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true));
$remain = array_diff($old_cats, $cats);
if ( !empty($remain) && $remain !== $old_cats) {
// remove subscription to these cat IDs and update s2_subscribed
foreach ( $cats as $id ) {
delete_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $id);
}
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), implode(',', $remain));
} else {
// remove subscription to these cat IDs and update s2_subscribed to ''
foreach ( $cats as $id ) {
delete_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $id);
}
delete_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'));
}
unset($remain);
}
} // end unsubscribe_registered_users()
/**
Handles bulk changes to email format for Registered Subscribers
*/
function format_change($emails, $format) {
if ( empty($format) ) { return; }
global $wpdb;
$useremails = explode(",\r\n", $emails);
$useremails = implode(", ", array_map(array($this,'prepare_in_data'), $useremails));
$ids = $wpdb->get_col("SELECT ID FROM $wpdb->users WHERE user_email IN ($useremails)");
$ids = implode(',', array_map(array($this, 'prepare_in_data'), $ids));
$sql = "UPDATE $wpdb->usermeta SET meta_value='{$format}' WHERE meta_key='" . $this->get_usermeta_keyname('s2_format') . "' AND user_id IN ($ids)";
$wpdb->query($sql);
} // end format_change()
/**
Handles bulk update to digest preferences
*/
function digest_change($emails, $digest) {
if ( empty($digest) ) { return; }
global $wpdb;
$useremails = explode(",\r\n", $emails);
$useremails = implode(", ", array_map(array($this, 'prepare_in_data'), $useremails));
$sql = "SELECT ID FROM $wpdb->users WHERE user_email IN ($useremails)";
$user_IDs = $wpdb->get_col($sql);
if ( $digest == 'digest' ) {
$exclude = explode(',', $this->subscribe2_options['exclude']);
if ( !empty($exclude) ) {
$all_cats = $this->all_cats(true, 'ID');
} else {
$all_cats = $this->all_cats(false, 'ID');
}
$cats_string = '';
foreach ( $all_cats as $cat ) {
('' == $cats_string) ? $cats_string = "$cat->term_id" : $cats_string .= ",$cat->term_id";
}
foreach ( $user_IDs as $user_ID ) {
foreach ( $all_cats as $cat ) {
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $cat->term_id, $cat->term_id);
}
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), $cats_string);
}
} elseif ( $digest == '-1' ) {
foreach ( $user_IDs as $user_ID ) {
$cats = explode(',', get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true));
foreach ( $cats as $id ) {
delete_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $id);
}
delete_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'));
}
}
} // end digest_change()
/* ===== functions to handle addition and removal of WordPress categories ===== */
/**
Autosubscribe registered users to newly created categories
if registered user has selected this option
*/
function new_category($new_category='') {
if ( 'no' == $this->subscribe2_options['show_autosub'] ) { return; }
global $wpdb;
if ( $this->subscribe2_options['email_freq'] != 'never' ) {
// if we are doing digests add new categories to users who are currently opted in
$sql = $wpdb->prepare("SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE meta_key=%s AND meta_value<>''", $this->get_usermeta_keyname('s2_subscribed'));
$user_IDs = $wpdb->get_col($sql);
foreach ( $user_IDs as $user_ID ) {
$old_cats = get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true);
$old_cats = explode(',', $old_cats);
$newcats = array_merge($old_cats, (array)$new_category);
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $new_category, $new_category);
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), implode(',', $newcats));
}
return;
}
if ( 'yes' == $this->subscribe2_options['show_autosub'] ) {
if ( $this->s2_mu ) {
$sql = $wpdb->prepare("SELECT DISTINCT a.user_id FROM $wpdb->usermeta AS a INNER JOIN $wpdb->usermeta AS b WHERE a.user_id = b.user_id AND a.meta_key=%s AND a.meta_value='yes' AND b.meta_key=%s", $this->get_usermeta_keyname('s2_autosub'), $this->get_usermeta_keyname('s2_subscribed'));
} else {
$sql = $wpdb->prepare("SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE $wpdb->usermeta.meta_key=%s AND $wpdb->usermeta.meta_value='yes'", $this->get_usermeta_keyname('s2_autosub'));
}
$user_IDs = $wpdb->get_col($sql);
if ( '' == $user_IDs ) { return; }
foreach ( $user_IDs as $user_ID ) {
$old_cats = get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true);
if ( empty($old_cats) ) {
$newcats = (array)$new_category;
} else {
$old_cats = explode(',', $old_cats);
$newcats = array_merge($old_cats, (array)$new_category);
}
// add subscription to these cat IDs
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $new_category, $new_category);
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), implode(',', $newcats));
}
} elseif ( 'exclude' == $this->subscribe2_options['show_autosub'] ) {
$excluded_cats = explode(',', $this->subscribe2_options['exclude']);
$excluded_cats[] = $new_category;
$this->subscribe2_options['exclude'] = implode(',', $excluded_cats);
update_option('subscribe2_options', $this->subscribe2_options);
}
} // end new_category()
/**
Automatically delete subscriptions to a category when it is deleted
*/
function delete_category($deleted_category='') {
global $wpdb;
if ( $this->s2_mu ) {
$sql = $wpdb->prepare("SELECT DISTINCT a.user_id FROM $wpdb->usermeta AS a INNER JOIN $wpdb->usermeta AS b WHERE a.user_id = b.user_id AND a.meta_key=%s AND b.meta_key=%s", $this->get_usermeta_keyname('s2_cat') . $deleted_category, $this->get_usermeta_keyname('s2_subscribed'));
} else {
$sql = $wpdb->prepare("SELECT DISTINCT user_id FROM $wpdb->usermeta WHERE meta_key=%s", $this->get_usermeta_keyname('s2_cat') . $deleted_category);
}
$user_IDs = $wpdb->get_col($sql);
if ( '' == $user_IDs ) { return; }
foreach ( $user_IDs as $user_ID ) {
$old_cats = explode(',', get_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), true));
if ( !is_array($old_cats) ) {
$old_cats = array($old_cats);
}
// add subscription to these cat IDs
delete_user_meta($user_ID, $this->get_usermeta_keyname('s2_cat') . $deleted_category);
$remain = array_diff($old_cats, (array)$deleted_category);
update_user_meta($user_ID, $this->get_usermeta_keyname('s2_subscribed'), implode(',', $remain));
}
} // end delete_category()
/* ===== functions to show & handle one-click subscription ===== */
/**
Show form for one-click subscription on user profile page
*/
function one_click_profile_form($user) {
echo "<h3>" . __('Email subscription', 'subscribe2') . "</h3>\r\n";
echo "<table class=\"form-table\">\r\n";
echo "<tr><th scope=\"row\">" . __('Subscribe / Unsubscribe', 'subscribe2') . "</th>\r\n";
echo "<td><label><input type=\"checkbox\" name=\"sub2-one-click-subscribe\" value=\"1\" " . checked( ! get_user_meta($user->ID, $this->get_usermeta_keyname('s2_subscribed'), true), false, false ) . " /> " . __('Receive notifications', 'subscribe2') . "</label><br />\r\n";
echo "<span class=\"description\">" . __('Check if you want to receive email notification when new posts are published', 'subscribe2') . "</span>\r\n";
echo "</td></tr></table>\r\n";
} // end one_click_profile_form()
/**
Handle submission from profile one-click subscription
*/
function one_click_profile_form_save($user_ID) {
if ( !current_user_can( 'edit_user', $user_ID ) ) {
return false;
}
if ( isset( $_POST['sub2-one-click-subscribe'] ) && 1 == $_POST['sub2-one-click-subscribe'] ) {
// Subscribe
$this->one_click_handler($user_ID, 'subscribe');
} else {
// Unsubscribe
$this->one_click_handler($user_ID, 'unsubscribe');
}
} // end one_click_profile_form_save()
}
?>
|
gpl-2.0
|
VisualIdeation/Nano-Construction-Kit
|
Triangle.cpp
|
5300
|
/***********************************************************************
Triangle - Class for carbon structural units (used to build nanotubes
and Buckyballs).
Copyright (c) 2003 Oliver Kreylos
***********************************************************************/
#include <Misc/ConfigurationFile.h>
#include <Misc/StandardValueCoders.h>
#include <Math/Math.h>
#include <GL/gl.h>
#include <GL/GLContextData.h>
#include <GL/GLGeometryWrappers.h>
#include <GL/GLTransformationWrappers.h>
#include "Triangle.h"
namespace NCK {
/*********************************
Methods of class TriangleRenderer:
*********************************/
void TriangleRenderer::initContext(GLContextData& contextData) const
{
/* Create context data item: */
DataItem* dataItem=new DataItem;
contextData.addDataItem(this,dataItem);
/* Create model display list: */
glNewList(dataItem->displayListId,GL_COMPILE);
/* Render triangle sides: */
glBegin(GL_QUADS);
glNormal(Triangle::renderNormals[0]);
glVertex(Triangle::renderVertices[0]);
glVertex(Triangle::renderVertices[1]);
glVertex(Triangle::renderVertices[4]);
glVertex(Triangle::renderVertices[3]);
glNormal(Triangle::renderNormals[1]);
glVertex(Triangle::renderVertices[1]);
glVertex(Triangle::renderVertices[2]);
glVertex(Triangle::renderVertices[5]);
glVertex(Triangle::renderVertices[4]);
glNormal(Triangle::renderNormals[2]);
glVertex(Triangle::renderVertices[2]);
glVertex(Triangle::renderVertices[0]);
glVertex(Triangle::renderVertices[3]);
glVertex(Triangle::renderVertices[5]);
glEnd();
/* Render triangle caps: */
glBegin(GL_TRIANGLES);
glNormal(Triangle::renderNormals[3]);
glVertex(Triangle::renderVertices[0]);
glVertex(Triangle::renderVertices[2]);
glVertex(Triangle::renderVertices[1]);
glNormal(Triangle::renderNormals[4]);
glVertex(Triangle::renderVertices[3]);
glVertex(Triangle::renderVertices[4]);
glVertex(Triangle::renderVertices[5]);
glEnd();
/* Finish model display list: */
glEndList();
}
/*********************************
Static elements of class Triangle:
*********************************/
Scalar Triangle::radius;
Scalar Triangle::radius2;
Scalar Triangle::width;
Scalar Triangle::mass;
Vector Triangle::vertexOffsets[3];
Point Triangle::renderVertices[6];
Vector Triangle::renderNormals[5];
TriangleRenderer* Triangle::unitRenderer=0;
/*************************
Methods of class Triangle:
*************************/
void Triangle::calculateShape(void)
{
/* Calculate vertex offset radius based on force parameters: */
Scalar vertexRadius=calcVertexRadius(radius);
/* Recalculate vertex offsets: */
Scalar c=Math::cos(Math::rad(Scalar(30)));
Scalar s=Math::sin(Math::rad(Scalar(30)));
Vector v[3];
v[0]=Vector(-c,-s,Scalar(0));
v[1]=Vector(c,-s,Scalar(0));
v[2]=Vector(Scalar(0),Scalar(1),Scalar(0));
for(int i=0;i<3;++i)
vertexOffsets[i]=v[i]*vertexRadius;
/* Recalculate render vertices and normals: */
Point bottom=Point(Scalar(0),Scalar(0),-width);
Point top=Point(Scalar(0),Scalar(0),width);
for(int i=0;i<3;++i)
{
renderVertices[i]=bottom+v[i]*radius;
renderVertices[3+i]=top+v[i]*radius;
}
for(int i=0;i<3;++i)
renderNormals[i]=-v[(i+2)%3];
renderNormals[3]=Vector(Scalar(0),Scalar(0),Scalar(-1));
renderNormals[4]=Vector(Scalar(0),Scalar(0),Scalar(1));
}
void Triangle::initClass(const Misc::ConfigurationFileSection& configFileSection)
{
/* Read class settings: */
radius=configFileSection.retrieveValue<Scalar>("./radius",1.550185);
radius2=Math::sqr(radius);
width=configFileSection.retrieveValue<Scalar>("./width",0.25);
mass=configFileSection.retrieveValue<Scalar>("./mass",1.0);
/* Calculate triangle shape: */
calculateShape();
/* Create triangle renderer: */
unitRenderer=new TriangleRenderer;
}
void Triangle::deinitClass(void)
{
/* Destroy triangle renderer: */
delete unitRenderer;
unitRenderer=0;
}
void Triangle::setRadius(Scalar newRadius)
{
/* Set radius: */
radius=newRadius;
radius2=Math::sqr(radius);
/* Re-calculate triangle shape: */
calculateShape();
}
void Triangle::setWidth(Scalar newWidth)
{
width=newWidth;
/* Re-calculate triangle shape: */
calculateShape();
}
void Triangle::setMass(Scalar newMass)
{
mass=newMass;
}
void Triangle::applyVertexForce(int index,const Vector& force,Scalar timeStep)
{
/* Apply linear acceleration: */
linearVelocity+=force*(timeStep/mass);
/* Calculate torque: */
Vector torque=Geometry::cross(orientation.transform(vertexOffsets[index]),force);
/* Apply angular acceleration: */
angularVelocity+=torque*(timeStep/mass); // Should be moment of inertia instead of mass here
}
void Triangle::applyCentralForce(const Vector& force,Scalar timeStep)
{
/* Apply linear acceleration: */
linearVelocity+=force*(timeStep/mass);
}
void Triangle::glRenderAction(GLContextData& contextData) const
{
/* Retrieve data item from GL context: */
TriangleRenderer::DataItem* dataItem=contextData.retrieveDataItem<TriangleRenderer::DataItem>(unitRenderer);
/* Move model coordinate system to triangle's position and orientation: */
glPushMatrix();
glTranslate(position.getComponents());
glRotate(orientation);
/* Render triangle: */
glCallList(dataItem->displayListId);
/* Reset model coordinates: */
glPopMatrix();
}
}
|
gpl-2.0
|
loadedcommerce/loaded7
|
catalog/install/includes/classes/order_total.php
|
2786
|
<?php
/**
@package catalog::install::classes
@author Loaded Commerce
@copyright Copyright 2003-2014 Loaded Commerce, LLC
@copyright Portions Copyright 2003 osCommerce
@license https://github.com/loadedcommerce/loaded7/blob/master/LICENSE.txt
@version $Id: order_total.php v1.0 2013-08-08 datazen $
*/
class lC_OrderTotal_Admin {
var $_group = 'order_total';
function install() {
global $lC_Database, $lC_Language;
$Qinstall = $lC_Database->query('insert into :table_templates_boxes (title, code, author_name, author_www, modules_group) values (:title, :code, :author_name, :author_www, :modules_group)');
$Qinstall->bindTable(':table_templates_boxes', TABLE_TEMPLATES_BOXES);
$Qinstall->bindValue(':title', $this->_title);
$Qinstall->bindValue(':code', $this->_code);
$Qinstall->bindValue(':author_name', $this->_author_name);
$Qinstall->bindValue(':author_www', $this->_author_www);
$Qinstall->bindValue(':modules_group', $this->_group);
$Qinstall->execute();
// foreach ($lC_Language->getAll() as $key => $value) {
if (file_exists(dirname(__FILE__) . '/../languages/en_US/modules/' . $this->_group . '/' . $this->_code . '.xml')) {
foreach ($lC_Language->extractDefinitions('en_US/modules/' . $this->_group . '/' . $this->_code . '.xml') as $def) {
$Qcheck = $lC_Database->query('select id from :table_languages_definitions where definition_key = :definition_key and content_group = :content_group and languages_id = :languages_id limit 1');
$Qcheck->bindTable(':table_languages_definitions', TABLE_LANGUAGES_DEFINITIONS);
$Qcheck->bindValue(':definition_key', $def['key']);
$Qcheck->bindValue(':content_group', $def['group']);
$Qcheck->bindInt(':languages_id', 1 /*$value['id']*/);
$Qcheck->execute();
if ($Qcheck->numberOfRows() === 1) {
$Qdef = $lC_Database->query('update :table_languages_definitions set definition_value = :definition_value where definition_key = :definition_key and content_group = :content_group and languages_id = :languages_id');
} else {
$Qdef = $lC_Database->query('insert into :table_languages_definitions (languages_id, content_group, definition_key, definition_value) values (:languages_id, :content_group, :definition_key, :definition_value)');
}
$Qdef->bindTable(':table_languages_definitions', TABLE_LANGUAGES_DEFINITIONS);
$Qdef->bindInt(':languages_id', 1 /*$value['id']*/);
$Qdef->bindValue(':content_group', $def['group']);
$Qdef->bindValue(':definition_key', $def['key']);
$Qdef->bindValue(':definition_value', $def['value']);
$Qdef->execute();
}
}
// }
}
}
?>
|
gpl-2.0
|
stevenzh/tourismwork
|
src/apps/portal/src/main/java/com/opentravelsoft/action/product/LineListAction.java
|
1083
|
package com.opentravelsoft.action.product;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.opentravelsoft.entity.Plan;
import com.opentravelsoft.service.portal.PlanListService;
import com.opentravelsoft.webapp.action.PortalAction;
/**
* 线路列表
*
* @author <a herf="mailto:zhangsitao@gmail.com">Steven Zhang</a>
*/
public class LineListAction extends PortalAction {
private static final long serialVersionUID = 1868553276414702703L;
@Autowired
private PlanListService planService;
private List<Plan> lines;
/** 显示行数 */
private long row = 1;
/** 区域 */
private String region;
public List<Plan> getLines() {
return lines;
}
public String execute() throws Exception {
lines = planService.getPlans(row, false, region);
return SUCCESS;
}
public long getRow() {
return row;
}
public void setRow(long row) {
this.row = row;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
|
gpl-2.0
|
timp21337/Melati
|
poem/src/main/java/org/melati/poem/ValueInfo.java
|
9202
|
/*
* $Source$
* $Revision$
*
* Copyright (C) 2000 William Chesters
*
* Part of Melati (http://melati.org), a framework for the rapid
* development of clean, maintainable web applications.
*
* Melati is free software; Permission is granted to copy, distribute
* and/or modify this software under the terms either:
*
* a) the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version,
*
* or
*
* b) any version of the Melati Software License, as published
* at http://melati.org
*
* You should have received a copy of the GNU General Public License and
* the Melati Software License along with this program;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
* GNU General Public License and visit http://melati.org to obtain the
* Melati Software License.
*
* Feel free to contact the Developers of Melati (http://melati.org),
* if you would like to work out a different arrangement than the options
* outlined here. It is our intention to allow Melati to be used by as
* wide an audience as possible.
*
* 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.
*
* Contact details for copyright holder:
*
* William Chesters <williamc At paneris.org>
* http://paneris.org/~williamc
* Obrechtstraat 114, 2517VX Den Haag, The Netherlands
*/
package org.melati.poem;
import org.melati.poem.generated.ValueInfoBase;
/**
* Abstract persistent generated from Poem.dsd
* and extended to cover {@link Setting} and {@link ColumnInfo}.
*
* Melati POEM generated, programmer modifiable stub
* for a <code>Persistent</code> <code>ValueInfo</code> object.
*
*
* <table>
* <tr><th colspan='3'>
* Field summary for SQL table <code>ValueInfo</code>
* </th></tr>
* <tr><th>Name</th><th>Type</th><th>Description</th></tr>
* <tr><td> displayname </td><td> String </td><td> A user-friendly name for
* the field </td></tr>
* <tr><td> description </td><td> String </td><td> A brief description of the
* field's function </td></tr>
* <tr><td> usereditable </td><td> Boolean </td><td> Whether it makes sense
* for the user to update the field's value </td></tr>
* <tr><td> typefactory </td><td> PoemTypeFactory </td><td> The field's
* Melati type </td></tr>
* <tr><td> nullable </td><td> Boolean </td><td> Whether the field can be
* empty </td></tr>
* <tr><td> size </td><td> Integer </td><td> For character fields, the
* maximum number of characters that can be stored, (-1 for unlimited)
* </td></tr>
* <tr><td> width </td><td> Integer </td><td> A sensible width for text boxes
* used for entering the field, where appropriate </td></tr>
* <tr><td> height </td><td> Integer </td><td> A sensible height for text
* boxes used for entering the field, where appropriate </td></tr>
* <tr><td> precision </td><td> Integer </td><td> Precision (total number of
* digits) for fixed-point numbers </td></tr>
* <tr><td> scale </td><td> Integer </td><td> Scale (number of digits after
* the decimal) for fixed-point numbers </td></tr>
* <tr><td> renderinfo </td><td> String </td><td> The name of the Melati
* templet (if not the default) to use for input controls for the field
* </td></tr>
* <tr><td> rangelow_string </td><td> String </td><td> The low end of the
* range of permissible values for the field </td></tr>
* <tr><td> rangelimit_string </td><td> String </td><td> The (exclusive)
* limit of the range of permissible values for the field </td></tr>
* </table>
*
* @generator org.melati.poem.prepro.TableDef#generateMainJava
*/
public class ValueInfo extends ValueInfoBase {
/**
* Constructor
* for a <code>Persistent</code> <code>ValueInfo</code> object.
*
* @generator org.melati.poem.prepro.TableDef#generateMainJava
*/
public ValueInfo() { }
// programmer's domain-specific code here
/**
* @return a Type Parameter based upon our size and nullability
*/
public PoemTypeFactory.Parameter toTypeParameter() {
final Boolean nullableL = getNullable_unsafe();
final Integer sizeL = getSize_unsafe();
return
new PoemTypeFactory.Parameter() {
public boolean getNullable() {
return nullableL == null || nullableL.booleanValue();
}
public int getSize() {
return sizeL == null ? -1 : sizeL.intValue();
}
};
}
private SQLPoemType<?> poemType = null;
/**
* NOTE A type cannot be changed once initialised.
* @return our SQLPoemType
*/
@SuppressWarnings("rawtypes")
public SQLPoemType<?> getType() {
if (poemType == null) {
PoemTypeFactory f = getTypefactory();
if (f == null) { // FIXME Test this, remove if possible
// this can happen before we have been fully initialised
// it's convenient to return the "most general" type available ...
return (SQLPoemType)StringPoemType.nullableInstance;
}
poemType = f.typeOf(getDatabase(), toTypeParameter());
}
return poemType;
}
/**
* @param nullableP whether nullable
* @return A type
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private SQLPoemType getRangeEndType(boolean nullableP) {
// FIXME a little inefficient, but rarely used; also relies on BasePoemType
// should have interface for ranged type ...
SQLPoemType t = getType();
if (t instanceof BasePoemType) {
BasePoemType unrangedType = (BasePoemType)((BasePoemType)t).clone();
unrangedType.setRawRange(null, null);
return (SQLPoemType)unrangedType.withNullable(nullableP);
}
else
return null;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private FieldAttributes<?> fieldAttributesRenamedAs(FieldAttributes<?> c,
PoemType<?> type) {
return new BaseFieldAttributes(
c.getName(), c.getDisplayName(), c.getDescription(), type,
width == null ? 12 : width.intValue(),
height == null ? 1 : height.intValue(),
renderinfo,
false, // indexed
usereditable == null ? true : usereditable.booleanValue(),
true // usercreateable
);
}
/**
* @param c a FieldAttributes eg a Field
* @return a new FieldAttributes
*/
public FieldAttributes<?> fieldAttributesRenamedAs(FieldAttributes<?> c) {
return fieldAttributesRenamedAs(c, getType());
}
/**
* @param c a Column with a Range
* @return a Field representing the end of the Range
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private Field<String> rangeEndField(Column<?> c) {
SQLPoemType<?> unrangedType = getRangeEndType(c.getType().getNullable());
if (unrangedType == null)
return null;
else {
Object raw;
try {
raw = unrangedType.rawOfString((String)c.getRaw_unsafe(this));
}
catch (Exception e) {
c.setRaw_unsafe(this, null);
raw = null;
throw new AppBugPoemException("Found a bad entry for " + c + " in " +
getTable().getName() + "/" + troid() + ": " +
"solution is to null it out ...", e);
}
return new Field(
raw,
fieldAttributesRenamedAs(c, unrangedType));
}
}
/**
* {@inheritDoc}
* @see org.melati.poem.generated.ValueInfoBase#getRangelow_stringField()
*/
public Field<String> getRangelow_stringField() {
Field<String> it = rangeEndField(getValueInfoTable().getRangelow_stringColumn());
return it != null ? it : super.getRangelow_stringField();
}
/**
* {@inheritDoc}
* @see org.melati.poem.generated.ValueInfoBase#getRangelimit_stringField()
*/
public Field<String> getRangelimit_stringField() {
Field<String> it = (Field<String>)rangeEndField(getValueInfoTable().getRangelimit_stringColumn());
return it != null ? it : super.getRangelimit_stringField();
}
/**
* {@inheritDoc}
* @see org.melati.poem.generated.ValueInfoBase#setRangelow_string(java.lang.String)
*/
public void setRangelow_string(String value) {
boolean nullableL = getValueInfoTable().getRangelow_stringColumn().
getType().getNullable();
PoemType<?> unrangedType = getRangeEndType(nullableL);
if (unrangedType != null)
value = unrangedType.stringOfRaw(unrangedType.rawOfString(value));
super.setRangelow_string(value);
}
/**
* {@inheritDoc}
* @see org.melati.poem.generated.ValueInfoBase#setRangelimit_string(java.lang.String)
*/
public void setRangelimit_string(String value) {
boolean nullableL = getValueInfoTable().getRangelimit_stringColumn().
getType().getNullable();
PoemType<?> unrangedType = getRangeEndType(nullableL);
if (unrangedType != null)
value = unrangedType.stringOfRaw(unrangedType.rawOfString(value));
super.setRangelimit_string(value);
}
}
|
gpl-2.0
|
jedwards1211/breakout
|
breakout-main/src/main/java/org/breakout/SearchMode.java
|
123
|
package org.breakout;
public enum SearchMode {
AUTO, SURVEY_DESIGNATION, STATION_REGEX, SURVEY_TEAM, TRIP_DESCRIPTION;
}
|
gpl-2.0
|
zdislaw/forestknollspool_wp
|
wp-content/plugins/wp-photo-album-plus/wppa-comment-widget.php
|
5211
|
<?php
/* wppa-comment-widget.php
* Package: wp-photo-album-plus
*
* display the recent commets on photos
* Version 6.3.17
*/
if ( ! defined( 'ABSPATH' ) ) die( "Can't load this file directly" );
class wppaCommentWidget extends WP_Widget {
/** constructor */
function __construct() {
$widget_ops = array('classname' => 'wppa_comment_widget', 'description' => __( 'WPPA+ Comments on Photos', 'wp-photo-album-plus') );
parent::__construct('wppa_comment_widget', __('Comments on Photos', 'wp-photo-album-plus'), $widget_ops);
}
/** @see WP_Widget::widget */
function widget($args, $instance) {
global $wpdb;
require_once(dirname(__FILE__) . '/wppa-links.php');
require_once(dirname(__FILE__) . '/wppa-styles.php');
require_once(dirname(__FILE__) . '/wppa-functions.php');
require_once(dirname(__FILE__) . '/wppa-thumbnails.php');
require_once(dirname(__FILE__) . '/wppa-boxes-html.php');
require_once(dirname(__FILE__) . '/wppa-slideshow.php');
wppa_initialize_runtime();
wppa( 'in_widget', 'com' );
wppa_bump_mocc();
// Hide widget if not logged in and login required to see comments
if ( wppa_switch( 'comment_view_login' ) && ! is_user_logged_in() ) {
return;
}
extract( $args );
$page = in_array( wppa_opt( 'comment_widget_linktype' ), wppa( 'links_no_page' ) ) ? '' : wppa_get_the_landing_page('wppa_comment_widget_linkpage', __('Recently commented photos', 'wp-photo-album-plus'));
$max = wppa_opt( 'comten_count' );
$widget_title = apply_filters('widget_title', $instance['title']);
$photo_ids = wppa_get_comten_ids( $max );
$widget_content = "\n".'<!-- WPPA+ Comment Widget start -->';
$maxw = wppa_opt( 'comten_size' );
$maxh = $maxw + 18;
if ( $photo_ids ) foreach( $photo_ids as $id ) {
// Make the HTML for current comment
$widget_content .= "\n".'<div class="wppa-widget" style="width:'.$maxw.'px; height:'.$maxh.'px; margin:4px; display:inline; text-align:center; float:left;">';
$image = wppa_cache_thumb( $id );
if ( $image ) {
$link = wppa_get_imglnk_a( 'comten', $id, '', '', true );
$file = wppa_get_thumb_path( $id );
$imgstyle_a = wppa_get_imgstyle_a( $id, $file, $maxw, 'center', 'comthumb' );
$imgstyle = $imgstyle_a['style'];
$width = $imgstyle_a['width'];
$height = $imgstyle_a['height'];
$cursor = $imgstyle_a['cursor'];
$imgurl = wppa_get_thumb_url($id, '', $width, $height);
$imgevents = wppa_get_imgevents('thumb', $id, true);
$title = '';
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `".WPPA_COMMENTS."` WHERE `photo` = %s ORDER BY `timestamp` DESC", $id ), ARRAY_A );
if ( $comments ) {
$first_comment = $comments['0'];
foreach ( $comments as $comment ) {
$title .= $comment['user'].' '.__( 'wrote' , 'wp-photo-album-plus' ).' '.wppa_get_time_since( $comment['timestamp'] ).":\n";
$title .= $comment['comment']."\n\n";
}
}
$title = esc_attr( strip_tags( trim ( $title ) ) );
$album = '0';
$display = 'thumbs';
$widget_content .= wppa_get_the_widget_thumb('comten', $image, $album, $display, $link, $title, $imgurl, $imgstyle_a, $imgevents);
}
else {
$widget_content .= __( 'Photo not found', 'wp-photo-album-plus' );
}
$widget_content .= "\n\t".'<span style="font-size:'.wppa_opt( 'fontsize_widget_thumb' ).'px; cursor:pointer;" title="'.esc_attr($first_comment['comment']).'" >'.$first_comment['user'].'</span>';
$widget_content .= "\n".'</div>';
}
else $widget_content .= __( 'There are no commented photos (yet)', 'wp-photo-album-plus' );
$widget_content .= '<div style="clear:both"></div>';
$widget_content .= "\n".'<!-- WPPA+ comment Widget end -->';
echo "\n" . $before_widget;
if ( ! empty( $widget_title ) ) { echo $before_title . $widget_title . $after_title; }
echo $widget_content . $after_widget;
wppa( 'in_widget', false );
}
/** @see WP_Widget::update */
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
return $instance;
}
/** @see WP_Widget::form */
function form($instance) {
//Defaults
$instance = wp_parse_args( (array) $instance, array( 'title' => __('Comments on Photos', 'wp-photo-album-plus') ) );
$widget_title = $instance['title'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:', 'wp-photo-album-plus'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $widget_title; ?>" /></p>
<p><?php _e('You can set the sizes in this widget in the <b>Photo Albums -> Settings</b> admin page.', 'wp-photo-album-plus'); ?></p>
<?php
}
} // class wppaCommentWidget
// register wppaCommentWidget widget
add_action('widgets_init', 'wppa_register_wppaCommentWidget' );
function wppa_register_wppaCommentWidget() {
register_widget("wppaCommentWidget");
}
|
gpl-2.0
|
iniverno/RnR-LLC
|
simics-3.0-install/simics-3.0.31/amd64-linux/lib/malta_components.py
|
10546
|
# MODULE: malta-components
# CLASS: malta-system
import time
from sim_core import *
from components import *
from base_components import find_device
### Malta System
class malta_system_component(component_object):
classname = 'malta-system'
basename = 'system'
description = ('The "malta-system" component represents a MIPS Malta '
'development board with a MIPS 4Kc or 5Kc processor and a '
'Galileo GT64120 system controller.')
connectors = {
'pci-slot-sb' : {'type' : 'pci-bus', 'direction' : 'down',
'empty_ok' : True, 'hotplug' : False,
'multi' : False},
'interrupt' : {'type' : 'sb-interrupt', 'direction' : 'down',
'empty_ok' : False, 'hotplug' : False,
'multi' : False}}
for i in range(1, 5):
connectors['pci-slot%d' % i] = {
'type' : 'pci-bus', 'direction' : 'down',
'empty_ok' : True, 'hotplug' : False, 'multi' : False}
def get_cpu_frequency(self, idx):
return self.freq_mhz
def set_cpu_frequency(self, val, idx):
if self.obj.configured:
return Sim_Set_Illegal_Value
self.freq_mhz = val
return Sim_Set_Ok
def get_cpu_class(self, idx):
return self.cpu_class
def set_cpu_class(self, val, idx):
if self.obj.configured:
return Sim_Set_Illegal_Value
if val not in ('mips-4kc', 'mips-5kc'):
SIM_attribute_error("Unsupported CPU class")
return Sim_Set_Illegal_Value
self.cpu_class = val
return Sim_Set_Ok
def get_rtc_time(self, idx):
return self.tod
def set_rtc_time(self, val, idx):
if self.obj.configured:
return Sim_Set_Illegal_Value
try:
time.strptime(val, '%Y-%m-%d %H:%M:%S %Z')
except Exception, msg:
SIM_attribute_error(str(msg))
self.tod = val
return Sim_Set_Ok
def add_objects(self):
self.o.hfs = pre_obj('hfs', 'hostfs')
self.o.phys_mem = pre_obj('phys_mem', 'memory-space')
self.o.cpu = pre_obj('cpu0', self.cpu_class)
self.o.cpu.physical_memory = self.o.phys_mem
self.o.cpu.freq_mhz = self.freq_mhz
self.o.cbus_space = pre_obj('cbus_space', 'memory-space')
self.o.ram_image = pre_obj('ram_image', 'image')
# TODO: configurable size?
self.o.ram_image.size = 0x08000000
self.o.ram = pre_obj('ram', 'ram')
self.o.ram.image = self.o.ram_image
self.o.rom_image = pre_obj('rom_image', 'image')
self.o.rom_image.size = 0x400000
self.o.rom = pre_obj('rom', 'rom')
self.o.rom.image = self.o.rom_image
#
self.o.gt_pci_0_0 = pre_obj('gt_pci_0_0', 'GT64120-pci')
self.o.gt_pci_0_0.bridge_num = 0
self.o.gt_pci_0_0.function_num = 0
self.o.gt_pci_0_1 = pre_obj('gt_pci_0_1', 'GT64120-pci')
self.o.gt_pci_0_1.bridge_num = 0
self.o.gt_pci_0_1.function_num = 1
# Dummies for non-existent pci-bus 1
self.o.gt_pci_1_0 = pre_obj('gt_pci_1_0', 'GT64120-pci')
self.o.gt_pci_1_0.bridge_num = 1
self.o.gt_pci_1_0.function_num = 0
self.o.gt_pci_1_1 = pre_obj('gt_pci_1_1', 'GT64120-pci')
self.o.gt_pci_1_1.bridge_num = 1
self.o.gt_pci_1_1.function_num = 1
#
self.o.pci_bus0_conf = pre_obj('pci_bus0_conf', 'memory-space')
self.o.pci_bus0_io = pre_obj('pci_bus0_io', 'memory-space')
self.o.pci_bus0_mem = pre_obj('pci_bus0_mem', 'memory-space')
#
self.o.pci_bus1_conf = pre_obj('pci_bus1_conf', 'memory-space')
self.o.pci_bus1_io = pre_obj('pci_bus1_io', 'memory-space')
self.o.pci_bus1_mem = pre_obj('pci_bus1_mem', 'memory-space')
#
self.o.pci_bus0 = pre_obj('pci_bus0', 'pci-bus')
self.o.pci_bus0.bridge = self.o.gt_pci_0_0
self.o.pci_bus0.interrupt = self.o.gt_pci_0_0
self.o.pci_bus0.conf_space = self.o.pci_bus0_conf
self.o.pci_bus0.io_space = self.o.pci_bus0_io
self.o.pci_bus0.io_space.map = []
self.o.pci_bus0.memory_space = self.o.pci_bus0_mem
self.o.pci_bus0.pci_devices = [[0, 0, self.o.gt_pci_0_0],
[0, 1, self.o.gt_pci_0_1]]
#
self.o.pci_bus1 = pre_obj('pci_bus1', 'pci-bus')
self.o.pci_bus1.bridge = self.o.gt_pci_1_0
self.o.pci_bus1.interrupt = self.o.gt_pci_1_0
self.o.pci_bus1.conf_space = self.o.pci_bus1_conf
self.o.pci_bus1.io_space = self.o.pci_bus1_io
self.o.pci_bus1.io_space.map = []
self.o.pci_bus1.memory_space = self.o.pci_bus1_mem
self.o.pci_bus1.pci_devices = [[0, 0, self.o.gt_pci_1_0],
[0, 1, self.o.gt_pci_1_1]]
#
self.o.gt_pci_0_0.pci_bus = self.o.pci_bus0
self.o.gt_pci_0_1.pci_bus = self.o.pci_bus0
#
self.o.gt_pci_1_0.pci_bus = self.o.pci_bus1
self.o.gt_pci_1_1.pci_bus = self.o.pci_bus1
#
self.o.gt = pre_obj('gt', 'GT64120')
self.o.gt.cpu_mem = self.o.phys_mem
self.o.gt.pci_0_0 = self.o.gt_pci_0_0
self.o.gt.pci_0_1 = self.o.gt_pci_0_1
self.o.gt.pci_1_0 = self.o.gt_pci_1_0
self.o.gt.pci_1_1 = self.o.gt_pci_1_1
self.o.gt.scs0 = self.o.ram
self.o.gt.cs3 = self.o.cbus_space
self.o.gt.bootcs = self.o.cbus_space
self.o.gt.pci_0_conf = self.o.pci_bus0_conf
self.o.gt.pci_0_io = self.o.pci_bus0_io
self.o.gt.pci_0_memory = self.o.pci_bus0_mem
self.o.gt.pci_1_conf = self.o.pci_bus1_conf
self.o.gt.pci_1_io = self.o.pci_bus1_io
self.o.gt.pci_1_memory = self.o.pci_bus1_mem
self.o.gt.irq_dev = self.o.cpu
self.o.gt.irq_level = 2
# Little endian
self.o.gt.cpu_interface_configuration = 0x00041000
# Map 128MB RAM.
self.o.gt.scs10_high_decode_address = 0x40
self.o.gt.scs0_low_decode_address = 0x0
self.o.gt.scs0_high_decode_address = 0x7f
# Map the internal registers at 0x1be00000.
self.o.gt.internal_space_decode = 0xdf
# Disable host-PCI mappings
self.o.gt.pci_0_io_high_decode_address = 0
self.o.gt.pci_0_io_low_decode_address = 1
self.o.gt.pci_0_io_remap = 1
self.o.gt.pci_0_memory_0_high_decode_address = 0
self.o.gt.pci_0_memory_0_low_decode_address = 1
self.o.gt.pci_0_memory_0_remap = 1
self.o.gt.pci_0_memory_1_high_decode_address = 0
self.o.gt.pci_0_memory_1_low_decode_address = 1
self.o.gt.pci_0_memory_1_remap = 1
self.o.gt.pci_1_io_high_decode_address = 0
self.o.gt.pci_1_io_low_decode_address = 1
self.o.gt.pci_1_io_remap = 1
self.o.gt.pci_1_memory_0_high_decode_address = 0
self.o.gt.pci_1_memory_0_low_decode_address = 1
self.o.gt.pci_1_memory_0_remap = 1
self.o.gt.pci_1_memory_1_high_decode_address = 0
self.o.gt.pci_1_memory_1_low_decode_address = 1
self.o.gt.pci_1_memory_1_remap = 1
# Disable PCI_host mappings
self.o.gt.pci_0_base_address_registers_enable = 0x1ff
self.o.gt.pci_1_base_address_registers_enable = 0x1ff
#
self.o.gt_pci_0_0.gt64120 = self.o.gt
self.o.gt_pci_0_1.gt64120 = self.o.gt
self.o.gt_pci_1_0.gt64120 = self.o.gt
self.o.gt_pci_1_1.gt64120 = self.o.gt
#
self.o.malta = pre_obj('malta', 'malta')
self.o.display = pre_obj('display', 'text-console')
self.o.display.title = "MALTA Display"
self.o.display.bg_color = "black"
self.o.display.fg_color = "red"
self.o.display.width = 8
self.o.display.height = 1
self.o.display.scrollbar = 0
self.o.display.x11_font = "-*-*-*-r-*-*-*-240-*-*-m-*-*-*"
self.o.display.win32_font = "Lucida Console:Bold:48"
self.o.display.output_timeout = 120
self.o.display.read_only = 1
self.o.malta.console = self.o.display
#
self.o.phys_mem.map = [
# the pci-io mapping should be created by the bios
[0x18000000, self.o.pci_bus0_io, 0, 0, 0x10000],
[0x1c000000, self.o.hfs, 0, 0, 16]]
self.o.cbus_space.map = [
[0x1f000000, self.o.malta, 0, 0, 0xc00000],
[0x1fc00000, self.o.rom, 0, 0, 0x400000]]
def add_connector_info(self):
# PCI device numbers:
# 10 South-bridge
# 11 Ethernet controller
# 12 Audio
# 17 Core Coard
# 18-21 PCI slot 1-4
self.connector_info['interrupt'] = [self.o.gt, None]
self.connector_info['pci-slot-sb'] = [10, self.o.pci_bus0]
for i in range(1, 5):
self.connector_info['pci-slot%d' % i] = [17 + i, self.o.pci_bus0]
def instantiation_done(self):
component_object.instantiation_done(self)
conf.sim.handle_outside_memory = 1
rtc = find_device(self.o.pci_bus0_io, 0x70)
if not rtc:
print "RTC device not found - can not write information."
return
m = re.match(r'(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)', self.tod)
eval_cli_line(('%s.set-date-time '
+ 'year=%s month=%s mday=%s hour=%s minute=%s second=%s'
) % ((rtc.name,) + m.groups()))
def connect_sb_interrupt(self, connector, pic):
# It seems like Linux expects the master 8259 to have VBA 0.
# Maybe that would be set up by YAMON?
pic.pic.vba = [0, 1]
def connect_pci_bus(self, connector, device_list):
slot = self.connector_info[connector][0]
pci_devices = self.o.pci_bus0.pci_devices
for d in device_list:
pci_devices += [[slot, d[0], d[1]]]
self.o.pci_bus0.pci_devices = pci_devices
def get_clock(self):
return self.o.cpu
def get_processors(self):
return [self.o.cpu]
register_component_class(
malta_system_component,
[['cpu_frequency', Sim_Attr_Required, 'i',
'Processor frequency in MHz.'],
['cpu_class', Sim_Attr_Required, 's',
'Processor type, one of "mips-4kc" and "mips-5kc"'],
['rtc_time', Sim_Attr_Required, 's',
'The data and time of the Real-Time clock.']],
top_level = True)
|
gpl-2.0
|
m-lassoued/testezp5Repo
|
ezpublish_legacy/kernel/classes/ezcollaborationprofile.php
|
5715
|
<?php
/**
* File containing the eZCollaborationProfile class.
*
* @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version 2013.11
* @package kernel
*/
/*!
\class eZCollaborationProfile ezcollaborationprofile.php
\brief The class eZCollaborationProfile does
*/
class eZCollaborationProfile extends eZPersistentObject
{
/*!
Constructor
*/
function eZCollaborationProfile( $row )
{
$this->eZPersistentObject( $row );
}
static function definition()
{
return array( 'fields' => array( 'id' => array( 'name' => 'ID',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'user_id' => array( 'name' => 'UserID',
'datatype' => 'integer',
'default' => 0,
'required' => true,
'foreign_class' => 'eZUser',
'foreign_attribute' => 'contentobject_id',
'multiplicity' => '1..*' ),
'main_group' => array( 'name' => 'MainGroup',
'datatype' => 'integer',
'default' => 0,
'required' => true,
'foreign_class' => 'eZCollaborationGroup',
'foreign_attribute' => 'id',
'multiplicity' => '1..*' ),
'data_text1' => array( 'name' => 'DataText1',
'datatype' => 'text',
'default' => '',
'required' => true ),
'created' => array( 'name' => 'Created',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'modified' => array( 'name' => 'Modified',
'datatype' => 'integer',
'default' => 0,
'required' => true ) ),
'keys' => array( 'id' ),
'increment_key' => 'id',
'class_name' => 'eZCollaborationProfile',
'name' => 'ezcollab_profile' );
}
static function create( $userID, $mainGroup = 0 )
{
$date_time = time();
$row = array( 'id' => null,
'user_id' => $userID,
'main_group' => $mainGroup,
'created' => $date_time,
'modified' => $date_time );
$newCollaborationProfile = new eZCollaborationProfile( $row );
return $newCollaborationProfile;
}
static function fetch( $id, $asObject = true )
{
$conditions = array( "id" => $id );
return eZPersistentObject::fetchObject( eZCollaborationProfile::definition(),
null,
$conditions,
$asObject );
}
static function fetchByUser( $userID, $asObject = true )
{
$conditions = array( "user_id" => $userID );
return eZPersistentObject::fetchObject( eZCollaborationProfile::definition(),
null,
$conditions,
$asObject );
}
/**
* Returns a shared instance of the eZCollaborationProfile class
* pr user id.
* note: Transaction unsafe. If you call several transaction unsafe methods you must enclose
* the calls within a db transaction; thus within db->begin and db->commit.
*
* @param int|false $userID Uses current user id if false.
* @return eZCollaborationProfile
*/
static function instance( $userID = false )
{
if ( $userID === false )
{
$user = eZUser::currentUser();
$userID = $user->attribute( 'contentobject_id' );
}
$instance =& $GLOBALS["eZCollaborationProfile-$userID"];
if ( !isset( $instance ) )
{
$instance = eZCollaborationProfile::fetchByUser( $userID );
if ( $instance === null )
{
$group = eZCollaborationGroup::instantiate( $userID, ezpI18n::tr( 'kernel/classes', 'Inbox' ) );
$instance = eZCollaborationProfile::create( $userID, $group->attribute( 'id' ) );
$instance->store();
}
}
return $instance;
}
}
?>
|
gpl-2.0
|
holtrop/pysdl2
|
tests/pixels.py
|
1554
|
#!/usr/bin/env python
import os
import sys
import time
for d in filter(lambda x: x.startswith('lib.'), os.listdir('build')):
sys.path = [os.path.sep.join([os.getcwd(), 'build', d])] + sys.path
import SDL
def invert_surface(surf):
i = 0
for y in range(surf.h):
for x in range(surf.w):
surf.pixels[i] ^= 0xFFFFFFFF
i += 1
SDL.Flip(surf)
def main():
SDL.Init(SDL.INIT_VIDEO)
surf = SDL.SetVideoMode(256, 256, 32, SDL.DOUBLEBUF)
if surf is not None:
SDL.WM_SetCaption("Pixels test", "Pixels test")
p = 0
for y in range(256):
for x in range(256):
surf.pixels[p] = SDL.MapRGB(surf.format, x, 0, y)
p += 1
SDL.Flip(surf)
while True:
evt = SDL.WaitEvent()
if evt.type == SDL.QUIT:
break
elif evt.type == SDL.KEYUP:
if evt.key.keysym.sym == SDL.K_q:
break
elif evt.key.keysym.sym == SDL.K_SPACE:
invert_surface(surf)
elif evt.key.keysym.sym == SDL.K_F1:
SDL.WM_ToggleFullScreen(surf)
elif evt.key.keysym.sym == SDL.K_F2:
grab = SDL.WM_GrabInput(SDL.GRAB_QUERY)
if grab == SDL.GRAB_ON:
grab = SDL.GRAB_OFF
else:
grab = SDL.GRAB_ON
SDL.WM_GrabInput(grab)
SDL.Quit()
if __name__ == '__main__':
main()
|
gpl-2.0
|
cjdru-association/d6-website
|
piwik/libs/jqplot/jqplot.tableLegendRenderer.js
|
13645
|
/**
* jqPlot
* Pure JavaScript plotting plugin using jQuery
*
* Version: @VERSION
*
* Copyright (c) 2009-2011 Chris Leonello
* jqPlot is currently available for use in all personal or commercial projects
* under both the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL
* version 2.0 (http://www.gnu.org/licenses/gpl-2.0.html) licenses. This means that you can
* choose the license that best suits your project and use it accordingly.
*
* Although not required, the author would appreciate an email letting him
* know of any substantial use of jqPlot. You can reach the author at:
* chris at jqplot dot com or see http://www.jqplot.com/info.php .
*
* If you are feeling kind and generous, consider supporting the project by
* making a donation at: http://www.jqplot.com/donate.php .
*
* sprintf functions contained in jqplot.sprintf.js by Ash Searle:
*
* version 2007.04.27
* author Ash Searle
* http://hexmen.com/blog/2007/03/printf-sprintf/
* http://hexmen.com/js/sprintf.js
* The author (Ash Searle) has placed this code in the public domain:
* "This code is unrestricted: you are free to use it however you like."
*
*/
(function($) {
// class $.jqplot.TableLegendRenderer
// The default legend renderer for jqPlot.
$.jqplot.TableLegendRenderer = function(){
//
};
$.jqplot.TableLegendRenderer.prototype.init = function(options) {
$.extend(true, this, options);
};
$.jqplot.TableLegendRenderer.prototype.addrow = function (label, color, pad, reverse) {
var rs = (pad) ? this.rowSpacing+'px' : '0px';
var tr;
var td;
var elem;
var div0;
var div1;
elem = document.createElement('tr');
tr = $(elem);
tr.addClass('jqplot-table-legend');
elem = null;
if (reverse){
tr.prependTo(this._elem);
}
else{
tr.appendTo(this._elem);
}
if (this.showSwatches) {
td = $(document.createElement('td'));
td.addClass('jqplot-table-legend');
td.css({textAlign: 'center', paddingTop: rs});
div0 = $(document.createElement('div'));
div1 = $(document.createElement('div'));
div1.addClass('jqplot-table-legend-swatch');
div1.css({backgroundColor: color, borderColor: color});
tr.append(td.append(div0.append(div1)));
// $('<td class="jqplot-table-legend" style="text-align:center;padding-top:'+rs+';">'+
// '<div><div class="jqplot-table-legend-swatch" style="background-color:'+color+';border-color:'+color+';"></div>'+
// '</div></td>').appendTo(tr);
}
if (this.showLabels) {
td = $(document.createElement('td'));
td.addClass('jqplot-table-legend');
td.css('paddingTop', rs);
tr.append(td);
// elem = $('<td class="jqplot-table-legend" style="padding-top:'+rs+';"></td>');
// elem.appendTo(tr);
if (this.escapeHtml) {
td.text(label);
}
else {
td.html(label);
}
}
td = null;
div0 = null;
div1 = null;
tr = null;
elem = null;
};
// called with scope of legend
$.jqplot.TableLegendRenderer.prototype.draw = function() {
if (this._elem) {
this._elem.emptyForce();
this._elem = null;
}
if (this.show) {
var series = this._series;
// make a table. one line label per row.
var elem = document.createElement('table');
this._elem = $(elem);
this._elem.addClass('jqplot-table-legend');
var ss = {position:'absolute'};
if (this.background) {
ss['background'] = this.background;
}
if (this.border) {
ss['border'] = this.border;
}
if (this.fontSize) {
ss['fontSize'] = this.fontSize;
}
if (this.fontFamily) {
ss['fontFamily'] = this.fontFamily;
}
if (this.textColor) {
ss['textColor'] = this.textColor;
}
if (this.marginTop != null) {
ss['marginTop'] = this.marginTop;
}
if (this.marginBottom != null) {
ss['marginBottom'] = this.marginBottom;
}
if (this.marginLeft != null) {
ss['marginLeft'] = this.marginLeft;
}
if (this.marginRight != null) {
ss['marginRight'] = this.marginRight;
}
var pad = false,
reverse = false,
s;
for (var i = 0; i< series.length; i++) {
s = series[i];
if (s._stack || s.renderer.constructor == $.jqplot.BezierCurveRenderer){
reverse = true;
}
if (s.show && s.showLabel) {
var lt = this.labels[i] || s.label.toString();
if (lt) {
var color = s.color;
if (reverse && i < series.length - 1){
pad = true;
}
else if (reverse && i == series.length - 1){
pad = false;
}
this.renderer.addrow.call(this, lt, color, pad, reverse);
pad = true;
}
// let plugins add more rows to legend. Used by trend line plugin.
for (var j=0; j<$.jqplot.addLegendRowHooks.length; j++) {
var item = $.jqplot.addLegendRowHooks[j].call(this, s);
if (item) {
this.renderer.addrow.call(this, item.label, item.color, pad);
pad = true;
}
}
lt = null;
}
}
}
return this._elem;
};
$.jqplot.TableLegendRenderer.prototype.pack = function(offsets) {
if (this.show) {
if (this.placement == 'insideGrid') {
switch (this.location) {
case 'nw':
var a = offsets.left;
var b = offsets.top;
this._elem.css('left', a);
this._elem.css('top', b);
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = offsets.top;
this._elem.css('left', a);
this._elem.css('top', b);
break;
case 'ne':
var a = offsets.right;
var b = offsets.top;
this._elem.css({right:a, top:b});
break;
case 'e':
var a = offsets.right;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:a, top:b});
break;
case 'se':
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 'sw':
var a = offsets.left;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 'w':
var a = offsets.left;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:a, top:b});
break;
default: // same as 'se'
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
}
}
else if (this.placement == 'outside'){
switch (this.location) {
case 'nw':
var a = this._plotDimensions.width - offsets.left;
var b = offsets.top;
this._elem.css('right', a);
this._elem.css('top', b);
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = this._plotDimensions.height - offsets.top;
this._elem.css('left', a);
this._elem.css('bottom', b);
break;
case 'ne':
var a = this._plotDimensions.width - offsets.right;
var b = offsets.top;
this._elem.css({left:a, top:b});
break;
case 'e':
var a = this._plotDimensions.width - offsets.right;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:a, top:b});
break;
case 'se':
var a = this._plotDimensions.width - offsets.right;
var b = offsets.bottom;
this._elem.css({left:a, bottom:b});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
var b = this._plotDimensions.height - offsets.bottom;
this._elem.css({left:a, top:b});
break;
case 'sw':
var a = this._plotDimensions.width - offsets.left;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
case 'w':
var a = this._plotDimensions.width - offsets.left;
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:a, top:b});
break;
default: // same as 'se'
var a = offsets.right;
var b = offsets.bottom;
this._elem.css({right:a, bottom:b});
break;
}
}
else {
switch (this.location) {
case 'nw':
this._elem.css({left:0, top:offsets.top});
break;
case 'n':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
this._elem.css({left: a, top:offsets.top});
break;
case 'ne':
this._elem.css({right:0, top:offsets.top});
break;
case 'e':
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({right:offsets.right, top:b});
break;
case 'se':
this._elem.css({right:offsets.right, bottom:offsets.bottom});
break;
case 's':
var a = (offsets.left + (this._plotDimensions.width - offsets.right))/2 - this.getWidth()/2;
this._elem.css({left: a, bottom:offsets.bottom});
break;
case 'sw':
this._elem.css({left:offsets.left, bottom:offsets.bottom});
break;
case 'w':
var b = (offsets.top + (this._plotDimensions.height - offsets.bottom))/2 - this.getHeight()/2;
this._elem.css({left:offsets.left, top:b});
break;
default: // same as 'se'
this._elem.css({right:offsets.right, bottom:offsets.bottom});
break;
}
}
}
};
})(jQuery);
|
gpl-2.0
|
gaugusto/CellAut3D
|
mainwindow.cpp
|
5045
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "jogodavida.h"
#include "flocosneve.h"
#include "testneighbors.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
glwidget = createGLWidget(ui->spinBoxRows->value(),
ui->spinBoxCols->value(),
ui->spinBoxSlices->value());
tr_implemented = jogo_da_vida;
iterationCounter = 0;
isRunning = false;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this,
SLOT(iterarButtonClicked()));
connect(ui->cbOnlyCubesHited, SIGNAL(clicked(bool)),
glwidget, SLOT(displayCubesNotHiteds(bool)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::iterarButtonClicked()
{
if (tr_implemented == jogo_da_vida)
{
JogoDaVida *jv = new JogoDaVida(this,
glwidget->getCubeRows(),
glwidget->getCubeCols(),
glwidget->getCubeSlices());
connect(jv, SIGNAL(iterated()), this,
SLOT(gridIterated()));
jv->setCubeList(glwidget->getCubeList());
jv->processRules();
glwidget->setCubeList(jv->getCubeList());
}
if (tr_implemented == flocos_de_neve)
{
FlocosNeve *fn = new FlocosNeve(this,
glwidget->getCubeRows(),
glwidget->getCubeCols(),
glwidget->getCubeSlices());
connect(fn, SIGNAL(iterated()), this,
SLOT(gridIterated()));
fn->setCubeList(glwidget->getCubeList());
fn->processRules();
glwidget->setCubeList(fn->getCubeList());
}
if (tr_implemented == testar_vizinhos)
{
TestNeighbors *tn = new TestNeighbors(this,
glwidget->getCubeRows(),
glwidget->getCubeCols(),
glwidget->getCubeSlices());
connect(tn, SIGNAL(iterated()), this,
SLOT(gridIterated()));
tn->setCubeList(glwidget->getCubeList());
tn->processRules();
glwidget->setCubeList(tn->getCubeList());
}
glwidget->updateGL();
}
void MainWindow::zerarButtonClicked()
{
glwidget->clearCubesHited();
ui->lblIteration->setText(tr("Iteração: %0").
arg(iterationCounter = 0));
timer->stop();
ui->btnPlay->setText("&Play ->");
}
void MainWindow::playButtonClicked()
{
if (!isRunning)
startRunning();
else
stopRunning();
}
void MainWindow::spinRowsChanged(int value)
{
stopRunning();
delete glwidget;
glwidget = createGLWidget(value,
ui->spinBoxCols->value(),
ui->spinBoxSlices->value());
}
void MainWindow::spinColsChanged(int value)
{
stopRunning();
delete glwidget;
glwidget = createGLWidget(ui->spinBoxRows->value(),
value,
ui->spinBoxSlices->value());
}
void MainWindow::spinSlicesChanged(int value)
{
stopRunning();
delete glwidget;
glwidget = createGLWidget(ui->spinBoxRows->value(),
ui->spinBoxCols->value(),
value);
}
void MainWindow::chooseRTChanged(int index)
{
switch(index)
{
case 0:
tr_implemented = jogo_da_vida;
break;
case 1:
tr_implemented = flocos_de_neve;
break;
case 2:
tr_implemented = testar_vizinhos;
break;
default:
tr_implemented = jogo_da_vida;
}
}
void MainWindow::gridIterated()
{
ui->lblIteration->setText(tr("Iteração: %0").
arg(++iterationCounter));
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_F11)
{
if (!isFullScreen())
showFullScreen();
else if (isFullScreen())
showNormal();
}
}
GLWidget *MainWindow::createGLWidget(int rows, int cols, int slices)
{
GLWidget *glwidget = new GLWidget(ui->centralWidget, rows, cols, slices);
glwidget->setObjectName(QStringLiteral("glwidget"));
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(glwidget->sizePolicy().hasHeightForWidth());
glwidget->setSizePolicy(sizePolicy);
ui->horizontalLayout_5->addWidget(glwidget);
return glwidget;
}
void MainWindow::startRunning()
{
if (isRunning)
return;
timer->start(500);
ui->btnPlay->setText("&Parar!");
isRunning = !isRunning;
}
void MainWindow::stopRunning()
{
if (!isRunning)
return;
timer->stop();
ui->btnPlay->setText("&Play ->");
isRunning = !isRunning;
}
|
gpl-2.0
|
Merlinium/server
|
src/game/ThreatManager.cpp
|
20927
|
/*
* This file is part of the Continued-MaNGOS Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ThreatManager.h"
#include "Unit.h"
#include "Creature.h"
#include "CreatureAI.h"
#include "Map.h"
#include "Player.h"
#include "ObjectAccessor.h"
#include "UnitEvents.h"
//==============================================================
//================= ThreatCalcHelper ===========================
//==============================================================
// The pHatingUnit is not used yet
float ThreatCalcHelper::CalcThreat(Unit* pHatedUnit, Unit* /*pHatingUnit*/, float threat, bool crit, SpellSchoolMask schoolMask, SpellEntry const* pThreatSpell)
{
// all flat mods applied early
if (!threat)
return 0.0f;
if (pThreatSpell)
{
if (pThreatSpell->HasAttribute(SPELL_ATTR_EX_NO_THREAT))
return 0.0f;
if (Player* modOwner = pHatedUnit->GetSpellModOwner())
modOwner->ApplySpellMod(pThreatSpell->Id, SPELLMOD_THREAT, threat);
if (crit)
threat *= pHatedUnit->GetTotalAuraMultiplierByMiscMask(SPELL_AURA_MOD_CRITICAL_THREAT, schoolMask);
}
threat = pHatedUnit->ApplyTotalThreatModifier(threat, schoolMask);
return threat;
}
//============================================================
//================= HostileReference ==========================
//============================================================
HostileReference::HostileReference(Unit* pUnit, ThreatManager* pThreatManager, float pThreat)
{
iThreat = pThreat;
iTempThreatModifyer = 0.0f;
link(pUnit, pThreatManager);
iUnitGuid = pUnit->GetObjectGuid();
iOnline = true;
iAccessible = true;
}
//============================================================
// Tell our refTo (target) object that we have a link
void HostileReference::targetObjectBuildLink()
{
getTarget()->addHatedBy(this);
}
//============================================================
// Tell our refTo (taget) object, that the link is cut
void HostileReference::targetObjectDestroyLink()
{
getTarget()->removeHatedBy(this);
}
//============================================================
// Tell our refFrom (source) object, that the link is cut (Target destroyed)
void HostileReference::sourceObjectDestroyLink()
{
setOnlineOfflineState(false);
}
//============================================================
// Inform the source, that the status of the reference changed
void HostileReference::fireStatusChanged(ThreatRefStatusChangeEvent& pThreatRefStatusChangeEvent)
{
if (getSource())
getSource()->processThreatEvent(&pThreatRefStatusChangeEvent);
}
//============================================================
void HostileReference::addThreat(float pMod)
{
iThreat += pMod;
// the threat is changed. Source and target unit have to be availabe
// if the link was cut before relink it again
if (!isOnline())
updateOnlineStatus();
if (pMod != 0.0f)
{
ThreatRefStatusChangeEvent event(UEV_THREAT_REF_THREAT_CHANGE, this, pMod);
fireStatusChanged(event);
}
if (isValid() && pMod >= 0)
{
Unit* victim_owner = getTarget()->GetOwner();
if (victim_owner && victim_owner->isAlive())
getSource()->addThreat(victim_owner, 0.0f); // create a threat to the owner of a pet, if the pet attacks
}
}
//============================================================
// check, if source can reach target and set the status
void HostileReference::updateOnlineStatus()
{
bool online = false;
bool accessible = false;
if (!isValid())
{
if (Unit* target = ObjectAccessor::GetUnit(*getSourceUnit(), getUnitGuid()))
link(target, getSource());
}
// only check for online status if
// ref is valid
// target is no player or not gamemaster
// target is not in flight
if (isValid() &&
((getTarget()->GetTypeId() != TYPEID_PLAYER || !((Player*)getTarget())->isGameMaster()) ||
!getTarget()->IsTaxiFlying()))
{
Creature* creature = (Creature*) getSourceUnit();
online = getTarget()->isInAccessablePlaceFor(creature);
if (!online)
{
if (creature->AI()->canReachByRangeAttack(getTarget()))
online = true; // not accessable but stays online
}
else
accessible = true;
}
setAccessibleState(accessible);
setOnlineOfflineState(online);
}
//============================================================
// set the status and fire the event on status change
void HostileReference::setOnlineOfflineState(bool pIsOnline)
{
if (iOnline != pIsOnline)
{
iOnline = pIsOnline;
if (!iOnline)
setAccessibleState(false); // if not online that not accessable as well
ThreatRefStatusChangeEvent event(UEV_THREAT_REF_ONLINE_STATUS, this);
fireStatusChanged(event);
}
}
//============================================================
void HostileReference::setAccessibleState(bool pIsAccessible)
{
if (iAccessible != pIsAccessible)
{
iAccessible = pIsAccessible;
ThreatRefStatusChangeEvent event(UEV_THREAT_REF_ASSECCIBLE_STATUS, this);
fireStatusChanged(event);
}
}
//============================================================
// prepare the reference for deleting
// this is called be the target
void HostileReference::removeReference()
{
invalidate();
ThreatRefStatusChangeEvent event(UEV_THREAT_REF_REMOVE_FROM_LIST, this);
fireStatusChanged(event);
}
//============================================================
Unit* HostileReference::getSourceUnit()
{
return (getSource()->getOwner());
}
//============================================================
//================ ThreatContainer ===========================
//============================================================
void ThreatContainer::clearReferences()
{
for (ThreatList::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i)
{
(*i)->unlink();
delete(*i);
}
iThreatList.clear();
}
//============================================================
// Return the HostileReference of NULL, if not found
HostileReference* ThreatContainer::getReferenceByTarget(Unit* pVictim)
{
HostileReference* result = NULL;
ObjectGuid guid = pVictim->GetObjectGuid();
for (ThreatList::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i)
{
if ((*i)->getUnitGuid() == guid)
{
result = (*i);
break;
}
}
return result;
}
//============================================================
// Add the threat, if we find the reference
HostileReference* ThreatContainer::addThreat(Unit* pVictim, float pThreat)
{
HostileReference* ref = getReferenceByTarget(pVictim);
if (ref)
ref->addThreat(pThreat);
return ref;
}
//============================================================
void ThreatContainer::modifyThreatPercent(Unit* pVictim, int32 pPercent)
{
if (HostileReference* ref = getReferenceByTarget(pVictim))
{
if (pPercent < -100)
{
ref->removeReference();
delete ref;
}
else
ref->addThreatPercent(pPercent);
}
}
//============================================================
bool HostileReferenceSortPredicate(const HostileReference* lhs, const HostileReference* rhs)
{
// std::list::sort ordering predicate must be: (Pred(x,y)&&Pred(y,x))==false
return lhs->getThreat() > rhs->getThreat(); // reverse sorting
}
//============================================================
// Check if the list is dirty and sort if necessary
void ThreatContainer::update()
{
if (iDirty && iThreatList.size() > 1)
{
iThreatList.sort(HostileReferenceSortPredicate);
}
iDirty = false;
}
//============================================================
// return the next best victim
// could be the current victim
HostileReference* ThreatContainer::selectNextVictim(Creature* pAttacker, HostileReference* pCurrentVictim)
{
HostileReference* pCurrentRef = NULL;
bool found = false;
bool onlySecondChoiceTargetsFound = false;
bool checkedCurrentVictim = false;
ThreatList::const_iterator lastRef = iThreatList.end();
--lastRef;
for (ThreatList::const_iterator iter = iThreatList.begin(); iter != iThreatList.end() && !found;)
{
pCurrentRef = (*iter);
Unit* pTarget = pCurrentRef->getTarget();
MANGOS_ASSERT(pTarget); // if the ref has status online the target must be there!
// some units are prefered in comparison to others
// if (checkThreatArea) consider IsOutOfThreatArea - expected to be only set for pCurrentVictim
// This prevents dropping valid targets due to 1.1 or 1.3 threat rule vs invalid current target
if (!onlySecondChoiceTargetsFound && pAttacker->IsSecondChoiceTarget(pTarget, pCurrentRef == pCurrentVictim))
{
if (iter != lastRef)
++iter;
else
{
// if we reached to this point, everyone in the threatlist is a second choice target. In such a situation the target with the highest threat should be attacked.
onlySecondChoiceTargetsFound = true;
iter = iThreatList.begin();
}
// current victim is a second choice target, so don't compare threat with it below
if (pCurrentRef == pCurrentVictim)
pCurrentVictim = NULL;
// second choice targets are only handled threat dependend if we have only have second choice targets
continue;
}
if (!pAttacker->IsOutOfThreatArea(pTarget)) // skip non attackable currently targets
{
if (pCurrentVictim) // select 1.3/1.1 better target in comparison current target
{
// normal case: pCurrentRef is still valid and most hated
if (pCurrentVictim == pCurrentRef)
{
found = true;
break;
}
// we found a valid target, but only compare its threat if the currect victim is also a valid target
// Additional check to prevent unneeded comparision in case of valid current victim
if (!checkedCurrentVictim)
{
Unit* pCurrentTarget = pCurrentVictim->getTarget();
MANGOS_ASSERT(pCurrentTarget);
if (pAttacker->IsSecondChoiceTarget(pCurrentTarget, true))
{
// CurrentVictim is invalid, so return CurrentRef
found = true;
break;
}
checkedCurrentVictim = true;
}
// list sorted and and we check current target, then this is best case
if (pCurrentRef->getThreat() <= 1.1f * pCurrentVictim->getThreat())
{
pCurrentRef = pCurrentVictim;
found = true;
break;
}
if (pCurrentRef->getThreat() > 1.3f * pCurrentVictim->getThreat() ||
(pCurrentRef->getThreat() > 1.1f * pCurrentVictim->getThreat() && pAttacker->CanReachWithMeleeAttack(pTarget)))
{
// implement 110% threat rule for targets in melee range
found = true; // and 130% rule for targets in ranged distances
break; // for selecting alive targets
}
}
else // select any
{
found = true;
break;
}
}
++iter;
}
if (!found)
pCurrentRef = NULL;
return pCurrentRef;
}
//============================================================
//=================== ThreatManager ==========================
//============================================================
ThreatManager::ThreatManager(Unit* owner)
: iCurrentVictim(NULL), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL), iUpdateNeed(false)
{
}
//============================================================
void ThreatManager::clearReferences()
{
iThreatContainer.clearReferences();
iThreatOfflineContainer.clearReferences();
iCurrentVictim = NULL;
iUpdateTimer.Reset(THREAT_UPDATE_INTERVAL);
iUpdateNeed = false;
}
//============================================================
void ThreatManager::addThreat(Unit* pVictim, float pThreat, bool crit, SpellSchoolMask schoolMask, SpellEntry const* pThreatSpell)
{
// function deals with adding threat and adding players and pets into ThreatList
// mobs, NPCs, guards have ThreatList and HateOfflineList
// players and pets have only InHateListOf
// HateOfflineList is used co contain unattackable victims (in-flight, in-water, GM etc.)
// not to self
if (pVictim == getOwner())
return;
// not to GM
if (!pVictim || (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster()))
return;
// not to dead and not for dead
if (!pVictim->isAlive() || !getOwner()->isAlive())
return;
MANGOS_ASSERT(getOwner()->GetTypeId() == TYPEID_UNIT);
float threat = ThreatCalcHelper::CalcThreat(pVictim, iOwner, pThreat, crit, schoolMask, pThreatSpell);
if (threat > 0.0f)
{
if (float redirectedMod = pVictim->getHostileRefManager().GetThreatRedirectionMod())
{
if (Unit* redirectedTarget = pVictim->getHostileRefManager().GetThreatRedirectionTarget())
{
if (redirectedTarget != getOwner() && redirectedTarget->isAlive())
{
float redirectedThreat = threat * redirectedMod;
threat -= redirectedThreat;
addThreatDirectly(redirectedTarget, redirectedThreat);
}
}
}
}
addThreatDirectly(pVictim, threat);
}
void ThreatManager::addThreatDirectly(Unit* pVictim, float threat)
{
HostileReference* ref = iThreatContainer.addThreat(pVictim, threat);
// Ref is online
if (ref)
iUpdateNeed = true;
// Ref is not in the online refs, search the offline refs next
else
ref = iThreatOfflineContainer.addThreat(pVictim, threat);
if (!ref) // there was no ref => create a new one
{
// threat has to be 0 here
HostileReference* hostileReference = new HostileReference(pVictim, this, 0);
iThreatContainer.addReference(hostileReference);
hostileReference->addThreat(threat); // now we add the real threat
iUpdateNeed = true;
if (pVictim->GetTypeId() == TYPEID_PLAYER && ((Player*)pVictim)->isGameMaster())
hostileReference->setOnlineOfflineState(false); // GM is always offline
}
}
//============================================================
void ThreatManager::modifyThreatPercent(Unit* pVictim, int32 pPercent)
{
iThreatContainer.modifyThreatPercent(pVictim, pPercent);
iUpdateNeed = true;
}
//============================================================
Unit* ThreatManager::getHostileTarget()
{
iThreatContainer.update();
HostileReference* nextVictim = iThreatContainer.selectNextVictim((Creature*) getOwner(), getCurrentVictim());
setCurrentVictim(nextVictim);
return getCurrentVictim() != NULL ? getCurrentVictim()->getTarget() : NULL;
}
//============================================================
float ThreatManager::getThreat(Unit* pVictim, bool pAlsoSearchOfflineList)
{
float threat = 0.0f;
HostileReference* ref = iThreatContainer.getReferenceByTarget(pVictim);
if (!ref && pAlsoSearchOfflineList)
ref = iThreatOfflineContainer.getReferenceByTarget(pVictim);
if (ref)
threat = ref->getThreat();
return threat;
}
//============================================================
void ThreatManager::tauntApply(Unit* pTaunter)
{
if (HostileReference* ref = iThreatContainer.getReferenceByTarget(pTaunter))
{
if (getCurrentVictim() && (ref->getThreat() < getCurrentVictim()->getThreat()))
{
// Ok, temp threat is unused
if (ref->getTempThreatModifyer() == 0.0f)
{
ref->setTempThreat(getCurrentVictim()->getThreat());
iUpdateNeed = true;
}
}
}
}
//============================================================
void ThreatManager::tauntFadeOut(Unit* pTaunter)
{
if (HostileReference* ref = iThreatContainer.getReferenceByTarget(pTaunter))
{
ref->resetTempThreat();
iUpdateNeed = true;
}
}
//============================================================
void ThreatManager::setCurrentVictim(HostileReference* pHostileReference)
{
// including NULL==NULL case
if (pHostileReference == iCurrentVictim)
return;
if (pHostileReference)
iOwner->SendHighestThreatUpdate(pHostileReference);
iCurrentVictim = pHostileReference;
iUpdateNeed = true;
}
//============================================================
// The hated unit is gone, dead or deleted
// return true, if the event is consumed
void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStatusChangeEvent)
{
threatRefStatusChangeEvent->setThreatManager(this); // now we can set the threat manager
HostileReference* hostileReference = threatRefStatusChangeEvent->getReference();
switch (threatRefStatusChangeEvent->getType())
{
case UEV_THREAT_REF_THREAT_CHANGE:
if ((getCurrentVictim() == hostileReference && threatRefStatusChangeEvent->getFValue() < 0.0f) ||
(getCurrentVictim() != hostileReference && threatRefStatusChangeEvent->getFValue() > 0.0f))
setDirty(true); // the order in the threat list might have changed
break;
case UEV_THREAT_REF_ONLINE_STATUS:
if (!hostileReference->isOnline())
{
if (hostileReference == getCurrentVictim())
{
setCurrentVictim(NULL);
setDirty(true);
}
iOwner->SendThreatRemove(hostileReference);
iThreatContainer.remove(hostileReference);
iUpdateNeed = true;
iThreatOfflineContainer.addReference(hostileReference);
}
else
{
if (getCurrentVictim() && hostileReference->getThreat() > (1.1f * getCurrentVictim()->getThreat()))
setDirty(true);
iThreatContainer.addReference(hostileReference);
iUpdateNeed = true;
iThreatOfflineContainer.remove(hostileReference);
}
break;
case UEV_THREAT_REF_REMOVE_FROM_LIST:
if (hostileReference == getCurrentVictim())
{
setCurrentVictim(NULL);
setDirty(true);
}
if (hostileReference->isOnline())
{
iOwner->SendThreatRemove(hostileReference);
iThreatContainer.remove(hostileReference);
iUpdateNeed = true;
}
else
iThreatOfflineContainer.remove(hostileReference);
break;
}
}
void ThreatManager::UpdateForClient(uint32 diff)
{
if (!iUpdateNeed || isThreatListEmpty())
return;
iUpdateTimer.Update(diff);
if (iUpdateTimer.Passed())
{
iOwner->SendThreatUpdate();
iUpdateTimer.Reset(THREAT_UPDATE_INTERVAL);
iUpdateNeed = false;
}
}
|
gpl-2.0
|
Venturi/cms
|
env/lib/python2.7/site-packages/djangocms_installer/django/__init__.py
|
17665
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import glob
import os
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
import zipfile
from copy import copy, deepcopy
from six import BytesIO
from ..compat import iteritems
from ..config import data, get_settings
from ..utils import chdir
try:
from shlex import quote as shlex_quote
except ImportError:
from pipes import quote as shlex_quote
def create_project(config_data):
"""
Call django-admin to create the project structure
"""
env = deepcopy(dict(os.environ))
env['DJANGO_SETTINGS_MODULE'] = ('{0}.settings'.format(config_data.project_name))
env['PYTHONPATH'] = os.pathsep.join(map(shlex_quote, sys.path))
kwargs = {}
args = []
if config_data.template:
kwargs['template'] = config_data.template
args.append(config_data.project_name)
if config_data.project_directory:
args.append(config_data.project_directory)
if not os.path.exists(config_data.project_directory):
os.makedirs(config_data.project_directory)
start_cmd = os.path.join(os.path.dirname(sys.executable), 'django-admin.py')
subprocess.check_call(' '.join([sys.executable, start_cmd, 'startproject'] + args), shell=True)
def _detect_migration_layout(vars, apps):
SOUTH_MODULES = {}
DJANGO_MODULES = {}
for module in vars.MIGRATIONS_CHECK_MODULES:
if module in apps:
try:
mod = __import__('%s.migrations_django' % module) # NOQA
DJANGO_MODULES[module] = '%s.migrations_django' % module
SOUTH_MODULES[module] = '%s.migrations' % module
except Exception:
pass
return DJANGO_MODULES, SOUTH_MODULES
def _install_aldryn(config_data): # pragma: no cover
import requests
media_project = os.path.join(config_data.project_directory, 'dist', 'media')
static_main = False
static_project = os.path.join(config_data.project_directory, 'dist', 'static')
template_target = os.path.join(config_data.project_directory, 'templates')
tmpdir = tempfile.mkdtemp()
aldrynzip = requests.get(data.ALDRYN_BOILERPLATE)
zip_open = zipfile.ZipFile(BytesIO(aldrynzip.content))
zip_open.extractall(path=tmpdir)
for component in os.listdir(os.path.join(tmpdir, 'aldryn-boilerplate-standard-master')):
src = os.path.join(tmpdir, 'aldryn-boilerplate-standard-master', component)
dst = os.path.join(config_data.project_directory, component)
if os.path.isfile(src):
shutil.copy(src, dst)
else:
shutil.copytree(src, dst)
shutil.rmtree(tmpdir)
return media_project, static_main, static_project, template_target
def copy_files(config_data):
"""
It's a little rude actually: it just overwrites the django-generated urls.py
with a custom version and put other files in the project directory.
"""
urlconf_path = os.path.join(os.path.dirname(__file__), '../config/urls.py')
share_path = os.path.join(os.path.dirname(__file__), '../share')
template_path = os.path.join(share_path, 'templates')
if config_data.aldryn: # pragma: no cover
media_project, static_main, static_project, template_target = _install_aldryn(config_data)
else:
media_project = os.path.join(config_data.project_directory, 'media')
static_main = os.path.join(config_data.project_path, 'static')
static_project = os.path.join(config_data.project_directory, 'static')
template_target = os.path.join(config_data.project_path, 'templates')
if config_data.templates and os.path.isdir(config_data.templates):
template_path = config_data.templates
elif config_data.bootstrap:
template_path = os.path.join(template_path, 'bootstrap')
else:
template_path = os.path.join(template_path, 'basic')
shutil.copy(urlconf_path, config_data.urlconf_path)
if media_project:
os.makedirs(media_project)
if static_main:
os.makedirs(static_main)
if not os.path.exists(static_project):
os.makedirs(static_project)
if not os.path.exists(template_target):
os.makedirs(template_target)
for filename in glob.glob(os.path.join(template_path, '*.html')):
if os.path.isfile(filename):
shutil.copy(filename, template_target)
if config_data.starting_page:
for filename in glob.glob(os.path.join(share_path, 'starting_page.*')):
if os.path.isfile(filename):
shutil.copy(filename, os.path.join(config_data.project_path, '..'))
def patch_settings(config_data):
"""
Modify the settings file created by Django injecting the django CMS
configuration
"""
overridden_settings = (
'MIDDLEWARE_CLASSES', 'INSTALLED_APPS', 'TEMPLATE_LOADERS', 'TEMPLATE_CONTEXT_PROCESSORS',
'TEMPLATE_DIRS', 'LANGUAGES'
)
extra_settings = ''
if not os.path.exists(config_data.settings_path):
sys.stdout.write('Error while creating target project, '
'please check the given configuration: %s' % config_data.settings_path)
return sys.exit(5)
with open(config_data.settings_path, 'r') as fd_original:
original = fd_original.read()
# extra settings reading
if config_data.extra_settings and os.path.exists(config_data.extra_settings):
with open(config_data.extra_settings, 'r') as fd_extra:
extra_settings = fd_extra.read()
original = original.replace('# -*- coding: utf-8 -*-\n', '')
if config_data.aldryn: # pragma: no cover
DATA_DIR = (
'DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \'dist\')\n'
)
STATICFILES_DIR = 'os.path.join(BASE_DIR, \'static\'),'
else:
DATA_DIR = 'DATA_DIR = os.path.dirname(os.path.dirname(__file__))\n'
STATICFILES_DIR = 'os.path.join(BASE_DIR, \'%s\', \'static\'),' % config_data.project_name
if original.find('BASE_DIR') == -1:
original = data.DEFAULT_PROJECT_HEADER + data.BASE_DIR + DATA_DIR + original
else:
original = data.DEFAULT_PROJECT_HEADER + DATA_DIR + original
if original.find('MEDIA_URL') > -1:
original = original.replace('MEDIA_URL = \'\'', 'MEDIA_URL = \'/media/\'')
else:
original += 'MEDIA_URL = \'/media/\'\n'
if original.find('MEDIA_ROOT') > -1:
original = original.replace(
'MEDIA_ROOT = \'\'', 'MEDIA_ROOT = os.path.join(DATA_DIR, \'media\')'
)
else:
original += 'MEDIA_ROOT = os.path.join(DATA_DIR, \'media\')\n'
if original.find('STATIC_ROOT') > -1:
original = original.replace(
'STATIC_ROOT = \'\'', 'STATIC_ROOT = os.path.join(DATA_DIR, \'static\')'
)
else:
original += 'STATIC_ROOT = os.path.join(DATA_DIR, \'static\')\n'
if original.find('STATICFILES_DIRS') > -1:
original = original.replace(data.STATICFILES_DEFAULT, '''
STATICFILES_DIRS = (
%s
)
''' % STATICFILES_DIR)
else:
original += '''
STATICFILES_DIRS = (
%s
)
''' % STATICFILES_DIR
original = original.replace('# -*- coding: utf-8 -*-\n', '')
# I18N
if config_data.i18n == 'no':
original = original.replace('I18N = True', 'I18N = False')
original = original.replace('L10N = True', 'L10N = False')
# TZ
if config_data.use_timezone == 'no':
original = original.replace('USE_TZ = True', 'USE_TZ = False')
if config_data.languages:
original = original.replace(
'LANGUAGE_CODE = \'en-us\'', 'LANGUAGE_CODE = \'%s\'' % config_data.languages[0]
)
if config_data.timezone:
# This is for Django 1.6 which changed the default timezone
original = original.replace(
'TIME_ZONE = \'UTC\'', 'TIME_ZONE = \'%s\'' % config_data.timezone
)
# This is for older django versions
original = original.replace(
'TIME_ZONE = \'America/Chicago\'', 'TIME_ZONE = \'%s\'' % config_data.timezone
)
for item in overridden_settings:
item_re = re.compile(r'%s = [^\)]+\)' % item, re.DOTALL | re.MULTILINE)
original = item_re.sub('', original)
if config_data.django_version >= 1.8:
# TEMPLATES is special, so custom regexp needed
item_re = re.compile(r'TEMPLATES = .+\]$', re.DOTALL | re.MULTILINE)
original = item_re.sub('', original)
# DATABASES is a dictionary, so different regexp needed
item_re = re.compile(r'DATABASES = [^\}]+\}[^\}]+\}', re.DOTALL | re.MULTILINE)
original = item_re.sub('', original)
if original.find('SITE_ID') == -1:
original += 'SITE_ID = 1\n\n'
original += _build_settings(config_data)
# Append extra settings at the end of the file
original += ('\n' + extra_settings)
with open(config_data.settings_path, 'w') as fd_dest:
fd_dest.write(original)
def _build_settings(config_data):
"""
Build the django CMS settings dictionary
"""
spacer = ' '
text = []
vars = get_settings()
if config_data.cms_version >= 3.2:
vars.MIDDLEWARE_CLASSES.insert(0, vars.APPHOOK_RELOAD_MIDDLEWARE_CLASS)
elif config_data.apphooks_reload:
vars.MIDDLEWARE_CLASSES.insert(0, vars.APPHOOK_RELOAD_MIDDLEWARE_CLASS_OLD)
if config_data.django_version < 1.6:
vars.MIDDLEWARE_CLASSES.extend(vars.MIDDLEWARE_CLASSES_DJANGO_15)
if config_data.cms_version < 3:
processors = vars.TEMPLATE_CONTEXT_PROCESSORS + vars.TEMPLATE_CONTEXT_PROCESSORS_2
else:
processors = vars.TEMPLATE_CONTEXT_PROCESSORS + vars.TEMPLATE_CONTEXT_PROCESSORS_3
if config_data.django_version < 1.8:
text.append('TEMPLATE_LOADERS = (\n%s%s\n)' % (
spacer, (',\n' + spacer).join(['\'%s\'' % var for var in vars.TEMPLATE_LOADERS])))
text.append('TEMPLATE_CONTEXT_PROCESSORS = (\n%s%s\n)' % (
spacer, (',\n' + spacer).join(['\'%s\'' % var for var in processors])))
if config_data.aldryn: # pragma: no cover
text.append('TEMPLATE_DIRS = (\n%s%s\n)' % (
spacer, 'os.path.join(BASE_DIR, \'templates\'),'))
else:
text.append('TEMPLATE_DIRS = (\n%s%s\n)' % (
spacer, 'os.path.join(BASE_DIR, \'%s\', \'templates\'),' % config_data.project_name
))
else:
text.append(data.TEMPLATES_1_8.format(
loaders=(',\n' + spacer).join(['\'%s\'' % var for var in vars.TEMPLATE_LOADERS]),
processors=(',\n' + spacer).join(['\'%s\'' % var for var in processors]),
dirs='os.path.join(BASE_DIR, \'%s\', \'templates\'),' % config_data.project_name
))
text.append('MIDDLEWARE_CLASSES = (\n%s%s\n)' % (
spacer, (',\n' + spacer).join(['\'%s\'' % var for var in vars.MIDDLEWARE_CLASSES])))
apps = list(vars.INSTALLED_APPS)
if config_data.cms_version == 2.4:
apps.extend(vars.CMS_2_APPLICATIONS)
apps.extend(vars.MPTT_APPS)
elif config_data.cms_version == 3.0:
apps = list(vars.CMS_3_HEAD) + apps
apps.extend(vars.MPTT_APPS)
apps.extend(vars.CMS_3_APPLICATIONS)
else:
apps = list(vars.CMS_3_HEAD) + apps
apps.extend(vars.TREEBEARD_APPS)
apps.extend(vars.CMS_3_APPLICATIONS)
if not config_data.no_plugins:
if config_data.cms_version == 2.4:
if config_data.filer:
apps.extend(vars.FILER_PLUGINS_2)
else:
apps.extend(vars.STANDARD_PLUGINS_2)
else:
if config_data.filer:
apps.extend(vars.FILER_PLUGINS_3)
else:
apps.extend(vars.STANDARD_PLUGINS_3)
if config_data.django_version <= 1.6:
apps.extend(vars.SOUTH_APPLICATIONS)
if config_data.aldryn: # pragma: no cover
apps.extend(vars.ALDRYN_APPLICATIONS)
if config_data.apphooks_reload and config_data.cms_version < 3.2:
apps.extend(vars.APPHOOK_RELOAD_APPLICATIONS)
if config_data.reversion:
apps.extend(vars.REVERSION_APPLICATIONS)
text.append('INSTALLED_APPS = (\n%s%s\n)' % (
spacer, (',\n' + spacer).join(['\'%s\'' % var for var in apps] + ['\'%s\'' % config_data.project_name]))) # NOQA
text.append('LANGUAGES = (\n%s%s\n%s%s\n)' % (
spacer, '## Customize this',
spacer, ('\n' + spacer).join(['(\'%s\', gettext(\'%s\')),' % (item, item) for item in config_data.languages]))) # NOQA
cms_langs = deepcopy(vars.CMS_LANGUAGES)
for lang in config_data.languages:
lang_dict = {'code': lang, 'name': lang}
lang_dict.update(copy(cms_langs['default']))
cms_langs[1].append(lang_dict)
cms_text = ['CMS_LANGUAGES = {']
cms_text.append('%s%s' % (spacer, '## Customize this',))
for key, value in iteritems(cms_langs):
if key == 'default':
cms_text.append('%s\'%s\': {' % (spacer, key))
for config_name, config_value in iteritems(value):
cms_text.append('%s\'%s\': %s,' % (spacer * 2, config_name, config_value))
cms_text.append('%s},' % spacer)
else:
cms_text.append('%s%s: [' % (spacer, key))
for lang in value:
cms_text.append('%s{' % (spacer * 2))
for config_name, config_value in iteritems(lang):
if config_name == 'code':
cms_text.append('%s\'%s\': \'%s\',' % (spacer * 3, config_name, config_value)) # NOQA
elif config_name == 'name':
cms_text.append('%s\'%s\': gettext(\'%s\'),' % (spacer * 3, config_name, config_value)) # NOQA
else:
cms_text.append('%s\'%s\': %s,' % (spacer * 3, config_name, config_value))
cms_text.append('%s},' % (spacer * 2))
cms_text.append('%s],' % spacer)
cms_text.append('}')
text.append('\n'.join(cms_text))
if config_data.bootstrap:
cms_templates = 'CMS_TEMPLATES_BOOTSTRAP'
else:
cms_templates = 'CMS_TEMPLATES'
text.append('CMS_TEMPLATES = (\n%s%s\n%s%s\n)' % (
spacer, '## Customize this',
spacer, (',\n' + spacer).join(['(\'%s\', \'%s\')' % item for item in getattr(vars, cms_templates)]))) # NOQA
text.append('CMS_PERMISSION = %s' % vars.CMS_PERMISSION)
text.append('CMS_PLACEHOLDER_CONF = %s' % vars.CMS_PLACEHOLDER_CONF)
text.append(textwrap.dedent('''
DATABASES = {
'default': {
%s
}
}''').strip() % (',\n' + spacer * 2).join(['\'%s\': \'%s\'' % (key, val) for key, val in sorted(config_data.db_parsed.items(), key=lambda x: x[0])])) # NOQA
DJANGO_MIGRATION_MODULES, SOUTH_MIGRATION_MODULES = _detect_migration_layout(vars, apps)
if config_data.django_version >= 1.7:
text.append('MIGRATION_MODULES = {\n%s%s\n}' % (
spacer, (',\n' + spacer).join(['\'%s\': \'%s\'' % item for item in DJANGO_MIGRATION_MODULES.items()]))) # NOQA
else:
text.append('SOUTH_MIGRATION_MODULES = {\n%s%s\n}' % (
spacer, (',\n' + spacer).join(['\'%s\': \'%s\'' % item for item in SOUTH_MIGRATION_MODULES.items()]))) # NOQA
if config_data.filer:
text.append('THUMBNAIL_PROCESSORS = (\n%s%s\n)' % (
spacer, (',\n' + spacer).join(['\'%s\'' % var for var in vars.THUMBNAIL_PROCESSORS])))
return '\n\n'.join(text)
def setup_database(config_data):
with chdir(config_data.project_directory):
env = deepcopy(dict(os.environ))
env['DJANGO_SETTINGS_MODULE'] = ('{0}.settings'.format(config_data.project_name))
env['PYTHONPATH'] = os.pathsep.join(map(shlex_quote, sys.path))
if config_data.django_version < 1.7:
try:
import south # NOQA
subprocess.check_call(
[sys.executable, '-W', 'ignore', 'manage.py', 'syncdb', '--all', '--noinput'],
env=env
)
subprocess.check_call(
[sys.executable, '-W', 'ignore', 'manage.py', 'migrate', '--fake'],
env=env
)
except ImportError:
subprocess.check_call(
[sys.executable, '-W', 'ignore', 'manage.py', 'syncdb', '--noinput'],
env=env
)
print('south not installed, migrations skipped')
else:
subprocess.check_call(
[sys.executable, '-W', 'ignore', 'manage.py', 'migrate', '--noinput'],
env=env
)
if not config_data.no_user and not config_data.noinput:
print('\n\nCreating admin user')
subprocess.check_call(
[sys.executable, '-W', 'ignore', 'manage.py', 'createsuperuser'],
env=env
)
def load_starting_page(config_data):
"""
Load starting page into the CMS
"""
with chdir(config_data.project_directory):
env = deepcopy(dict(os.environ))
env['DJANGO_SETTINGS_MODULE'] = ('{0}.settings'.format(config_data.project_name))
env['PYTHONPATH'] = os.pathsep.join(map(shlex_quote, sys.path))
subprocess.check_call([sys.executable, 'starting_page.py'],
env=env)
for ext in ['py', 'pyc', 'json']:
try:
os.remove('starting_page.%s' % ext)
except OSError:
pass
|
gpl-2.0
|
RoProducts/rastertheque
|
JAILibrary/src/com/sun/media/jai/opimage/MaxOpImage.java
|
18329
|
/*
* $RCSfile: MaxOpImage.java,v $
*
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
*
* Use is subject to license terms.
*
* $Revision: 1.1 $
* $Date: 2005/02/11 04:56:33 $
* $State: Exp $
*/
package com.sun.media.jai.opimage;
import java.awt.Rectangle;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import javax.media.jai.ImageLayout;
import javax.media.jai.OpImage;
import javax.media.jai.PointOpImage;
import javax.media.jai.RasterAccessor;
import javax.media.jai.RasterFormatTag;
import java.util.Map;
import java.lang.ref.SoftReference;
/**
* An <code>OpImage</code> implementing the "Max" operation as
* described in <code>javax.media.jai.operator.MaxDescriptor</code>.
*
* <p>This <code>OpImage</code> chooses the maximum pixel values of the
* two source images on a per-band basis. In case the two source images
* have different number of bands, the number of bands for the destination
* image is the smaller band number of the two source images. That is
* <code>dstNumBands = Math.min(src1NumBands, src2NumBands)</code>.
* In case the two source images have different data types, the data type
* for the destination image is the higher data type of the two source
* images.
*
* <p>The value of the pixel (x, y) in the destination image is defined as:
* <pre>
* for (b = 0; b < numBands; b++) {
* dst[y][x][b] = Math.max(src1[y][x][b], src2[y][x][b]);
* }
* </pre>
*
* @see javax.media.jai.operator.MaxDescriptor
* @see MaxRIF
*
*/
final class MaxOpImage extends PointOpImage {
private static long negativeZeroFloatBits = Float.floatToIntBits(-0.0f);
private static long negativeZeroDoubleBits = Double.doubleToLongBits(-0.0d);
private static byte[] byteTable = null;
private static SoftReference softRef = null;
private synchronized void allocByteTable() {
if ((softRef == null) || (softRef.get() == null)) {
//
// First time or reference has been cleared.
// Create the table and make a soft reference to it.
//
byteTable = new byte[256*256];
softRef = new SoftReference(byteTable);
// Initialize table which implements Min
int idx = 0;
for (int i1 = 0; i1 < 256; i1++) {
int base = i1 << 8;
for(int i2=0; i2<i1; i2++) {
byteTable[base+i2] = (byte)i1;
}
for (int i2=i1; i2<256; i2++) {
byteTable[base+i2] = (byte)i2;
}
}
}
}
/**
* Construct a <code>MaxOpImage</code>.
*
* @param source1 The first source image.
* @param source2 The second source image.
* @param layout The destination image layout.
*/
public MaxOpImage(RenderedImage source1,
RenderedImage source2,
Map config,
ImageLayout layout) {
super(source1, source2, layout, config, true);
if (sampleModel.getTransferType() == DataBuffer.TYPE_BYTE) {
allocByteTable();
}
// Set flag to permit in-place operation.
permitInPlaceOperation();
}
/**
* Return the maximum pixel value of the source images for a
* specified rectangle.
*
* @param sources Cobbled sources, guaranteed to provide all the
* source data necessary for computing the rectangle.
* @param dest The tile containing the rectangle to be computed.
* @param destRect The rectangle within the tile to be computed.
*/
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
// Retrieve format tags.
RasterFormatTag[] formatTags = getFormatTags();
/* For PointOpImage, srcRect = destRect. */
RasterAccessor s1 = new RasterAccessor(sources[0], destRect,
formatTags[0],
getSourceImage(0).getColorModel());
RasterAccessor s2 = new RasterAccessor(sources[1], destRect,
formatTags[1],
getSourceImage(1).getColorModel());
RasterAccessor d = new RasterAccessor(dest, destRect,
formatTags[2], getColorModel());
switch (d.getDataType()) {
case DataBuffer.TYPE_BYTE:
computeRectByte(s1, s2, d);
break;
case DataBuffer.TYPE_USHORT:
computeRectUShort(s1, s2, d);
break;
case DataBuffer.TYPE_SHORT:
computeRectShort(s1, s2, d);
break;
case DataBuffer.TYPE_INT:
computeRectInt(s1, s2, d);
break;
case DataBuffer.TYPE_FLOAT:
computeRectFloat(s1, s2, d);
break;
case DataBuffer.TYPE_DOUBLE:
computeRectDouble(s1, s2, d);
break;
}
if (d.isDataCopy()) {
d.clampDataArrays();
d.copyDataToRaster();
}
}
private void computeRectByte(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
byte[][] s1Data = src1.getByteDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
byte[][] s2Data = src2.getByteDataArrays();
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
byte[][] dData = dst.getByteDataArrays();
for (int b = 0; b < bands; b++) {
byte[] s1 = s1Data[b];
byte[] s2 = s2Data[b];
byte[] d = dData[b];
int s1LineOffset = s1BandOffsets[b];
int s2LineOffset = s2BandOffsets[b];
int dLineOffset = dBandOffsets[b];
for (int h = 0; h < dheight; h++) {
int s1PixelOffset = s1LineOffset;
int s2PixelOffset = s2LineOffset;
int dPixelOffset = dLineOffset;
s1LineOffset += s1LineStride;
s2LineOffset += s2LineStride;
dLineOffset += dLineStride;
int dstEnd = dPixelOffset + dwidth*dPixelStride;
while (dPixelOffset < dstEnd) {
int i1 = s1[s1PixelOffset]&0xFF;
int i2 = s2[s2PixelOffset]&0xFF;
d[dPixelOffset] = byteTable[(i1<<8) + i2];
s1PixelOffset += s1PixelStride;
s2PixelOffset += s2PixelStride;
dPixelOffset += dPixelStride;
}
}
}
}
private void computeRectUShort(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
short[][] s1Data = src1.getShortDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
short[][] s2Data = src2.getShortDataArrays();
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
short[][] dData = dst.getShortDataArrays();
for (int b = 0; b < bands; b++) {
short[] s1 = s1Data[b];
short[] s2 = s2Data[b];
short[] d = dData[b];
int s1LineOffset = s1BandOffsets[b];
int s2LineOffset = s2BandOffsets[b];
int dLineOffset = dBandOffsets[b];
for (int h = 0; h < dheight; h++) {
int s1PixelOffset = s1LineOffset;
int s2PixelOffset = s2LineOffset;
int dPixelOffset = dLineOffset;
s1LineOffset += s1LineStride;
s2LineOffset += s2LineStride;
dLineOffset += dLineStride;
for (int w = 0; w < dwidth; w++) {
d[dPixelOffset] = maxUShort(s1[s1PixelOffset],
s2[s2PixelOffset]);
s1PixelOffset += s1PixelStride;
s2PixelOffset += s2PixelStride;
dPixelOffset += dPixelStride;
}
}
}
}
private void computeRectShort(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
short[][] s1Data = src1.getShortDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
short[][] s2Data = src2.getShortDataArrays();
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
short[][] dData = dst.getShortDataArrays();
for (int b = 0; b < bands; b++) {
short[] s1 = s1Data[b];
short[] s2 = s2Data[b];
short[] d = dData[b];
int s1LineOffset = s1BandOffsets[b];
int s2LineOffset = s2BandOffsets[b];
int dLineOffset = dBandOffsets[b];
for (int h = 0; h < dheight; h++) {
int s1PixelOffset = s1LineOffset;
int s2PixelOffset = s2LineOffset;
int dPixelOffset = dLineOffset;
s1LineOffset += s1LineStride;
s2LineOffset += s2LineStride;
dLineOffset += dLineStride;
for (int w = 0; w < dwidth; w++) {
d[dPixelOffset] = maxShort(s1[s1PixelOffset],
s2[s2PixelOffset]);
s1PixelOffset += s1PixelStride;
s2PixelOffset += s2PixelStride;
dPixelOffset += dPixelStride;
}
}
}
}
private void computeRectInt(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
int[][] s1Data = src1.getIntDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
int[][] s2Data = src2.getIntDataArrays();
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
int[][] dData = dst.getIntDataArrays();
for (int b = 0; b < bands; b++) {
int[] s1 = s1Data[b];
int[] s2 = s2Data[b];
int[] d = dData[b];
int s1LineOffset = s1BandOffsets[b];
int s2LineOffset = s2BandOffsets[b];
int dLineOffset = dBandOffsets[b];
for (int h = 0; h < dheight; h++) {
int s1PixelOffset = s1LineOffset;
int s2PixelOffset = s2LineOffset;
int dPixelOffset = dLineOffset;
s1LineOffset += s1LineStride;
s2LineOffset += s2LineStride;
dLineOffset += dLineStride;
for (int w = 0; w < dwidth; w++) {
d[dPixelOffset] = maxInt(s1[s1PixelOffset],
s2[s2PixelOffset]);
s1PixelOffset += s1PixelStride;
s2PixelOffset += s2PixelStride;
dPixelOffset += dPixelStride;
}
}
}
}
private void computeRectFloat(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
float[][] s1Data = src1.getFloatDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
float[][] s2Data = src2.getFloatDataArrays();
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
float[][] dData = dst.getFloatDataArrays();
for (int b = 0; b < bands; b++) {
float[] s1 = s1Data[b];
float[] s2 = s2Data[b];
float[] d = dData[b];
int s1LineOffset = s1BandOffsets[b];
int s2LineOffset = s2BandOffsets[b];
int dLineOffset = dBandOffsets[b];
for (int h = 0; h < dheight; h++) {
int s1PixelOffset = s1LineOffset;
int s2PixelOffset = s2LineOffset;
int dPixelOffset = dLineOffset;
s1LineOffset += s1LineStride;
s2LineOffset += s2LineStride;
dLineOffset += dLineStride;
for (int w = 0; w < dwidth; w++) {
d[dPixelOffset] = maxFloat(s1[s1PixelOffset],
s2[s2PixelOffset]);
s1PixelOffset += s1PixelStride;
s2PixelOffset += s2PixelStride;
dPixelOffset += dPixelStride;
}
}
}
}
private void computeRectDouble(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
double[][] s1Data = src1.getDoubleDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
double[][] s2Data = src2.getDoubleDataArrays();
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
double[][] dData = dst.getDoubleDataArrays();
for (int b = 0; b < bands; b++) {
double[] s1 = s1Data[b];
double[] s2 = s2Data[b];
double[] d = dData[b];
int s1LineOffset = s1BandOffsets[b];
int s2LineOffset = s2BandOffsets[b];
int dLineOffset = dBandOffsets[b];
for (int h = 0; h < dheight; h++) {
int s1PixelOffset = s1LineOffset;
int s2PixelOffset = s2LineOffset;
int dPixelOffset = dLineOffset;
s1LineOffset += s1LineStride;
s2LineOffset += s2LineStride;
dLineOffset += dLineStride;
for (int w = 0; w < dwidth; w++) {
d[dPixelOffset] = maxDouble(s1[s1PixelOffset],
s2[s2PixelOffset]);
s1PixelOffset += s1PixelStride;
s2PixelOffset += s2PixelStride;
dPixelOffset += dPixelStride;
}
}
}
}
private final short maxUShort(short a, short b) {
return (a&0xFFFF) > (b&0xFFFF) ? a : b;
}
private final short maxShort(short a, short b) {
return a > b ? a : b;
}
private final int maxInt(int a, int b) {
return a > b ? a : b;
}
private final float maxFloat(float a, float b) {
if (a != a) return a; // a is NaN
if ((a == 0.0f) && (b == 0.0f)
&& (Float.floatToIntBits(a) == negativeZeroFloatBits)) {
return b;
}
return (a >= b) ? a : b;
}
private final double maxDouble(double a, double b) {
if (a != a) return a; // a is NaN
if ((a == 0.0d) && (b == 0.0d)
&& (Double.doubleToLongBits(a) == negativeZeroDoubleBits)) {
return b;
}
return (a >= b) ? a : b;
}
}
|
gpl-2.0
|
dpwrussell/openmicroscopy
|
components/tools/OmeroPy/src/omero/cli.py
|
81737
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python driver for OMERO
Provides access to various OMERO.blitz server- and client-side
utilities, including starting and stopping servers, running
analyses, configuration, and more.
Usable via the ./omero script provided with the distribution
as well as from python via "import omero.cli; omero.cli.argv()"
Arguments are taken from (in order of priority): the run method
arguments, sys.argv, and finally from standard-in using the
cmd.Cmd.cmdloop method.
Josh Moore, josh at glencoesoftware.com
Copyright (c) 2007-2016, Glencoe Software, Inc.
See LICENSE for details.
"""
sys = __import__("sys")
cmd = __import__("cmd")
import re
import os
import subprocess
import socket
import traceback
import glob
import platform
import time
import shlex
import errno
from threading import Lock
from path import path
from omero_ext.argparse import ArgumentError
from omero_ext.argparse import ArgumentTypeError
from omero_ext.argparse import ArgumentParser
from omero_ext.argparse import FileType
from omero_ext.argparse import Namespace
from omero_ext.argparse import _SubParsersAction
# Help text
from omero_ext.argparse import RawTextHelpFormatter
from omero_ext.argparse import SUPPRESS
from omero.util.concurrency import get_event
import omero
#
# Static setup
#
try:
from omero_version import omero_version
VERSION = omero_version
except ImportError:
VERSION = "Unknown" # Usually during testing
DEBUG = 0
if "DEBUG" in os.environ:
try:
DEBUG = int(os.environ["DEBUG"])
except ValueError:
DEBUG = 1
print "Deprecated warning: use the 'bin/omero --debug=x [args]' to debug"
print "Running omero with debugging == 1"
OMERODOC = """
Command-line tool for local and remote interactions with OMERO.
"""
OMEROSHELL = """OMERO Python Shell. Version %s""" % str(VERSION)
OMEROHELP = """Type "help" for more information, "quit" or Ctrl-D to exit"""
OMEROSUBS = """Use %(prog)s <subcommand> -h for more information."""
OMEROSUBM = """<subcommand>"""
OMEROCLI = path(__file__).expand().dirname()
OMERODIR = os.getenv('OMERODIR', None)
if OMERODIR is not None:
OMERODIR = path(OMERODIR)
else:
OMERODIR = OMEROCLI.dirname().dirname().dirname()
COMMENT = re.compile("^\s*#")
RELFILE = re.compile("^\w")
LINEWSP = re.compile("^\s*\w+\s+")
#
# Possibilities:
# - Always return and print any output
# - Have a callback on the fired event
# - how should state machine work?
# -- is the last control stored somwhere? in a stack history[3]
# -- or do they all share a central memory? self.ctx["MY_VARIABLE"]
# - In almost all cases, mark a flag in the CLI "lastError" and continue,
# allowing users to do something of the form: on_success or on_fail
#####################################################
#
# Exceptions
#
class NonZeroReturnCode(Exception):
def __init__(self, rv, *args):
self.rv = rv
Exception.__init__(self, *args)
#####################################################
#
class HelpFormatter(RawTextHelpFormatter):
"""
argparse.HelpFormatter subclass which cleans up our usage, preventing very
long lines in subcommands.
"""
def __init__(self, prog, indent_increment=2, max_help_position=40,
width=None):
RawTextHelpFormatter.__init__(
self, prog, indent_increment, max_help_position, width)
self._action_max_length = 20
def _split_lines(self, text, width):
return [text.splitlines()[0]]
class _Section(RawTextHelpFormatter._Section):
def __init__(self, formatter, parent, heading=None):
# if heading:
# heading = "\n%s\n%s" % ("=" * 40, heading)
RawTextHelpFormatter._Section.__init__(
self, formatter, parent, heading)
class WriteOnceNamespace(Namespace):
"""
Namespace subclass which prevents overwriting any values by accident.
"""
def __setattr__(self, name, value):
if hasattr(self, name):
raise Exception("%s already has field %s"
% (self.__class__.__name__, name))
else:
return Namespace.__setattr__(self, name, value)
class Parser(ArgumentParser):
"""
Extension of ArgumentParser for simplifying the
_configure() code in most Controls
"""
def __init__(self, *args, **kwargs):
kwargs["formatter_class"] = HelpFormatter
ArgumentParser.__init__(self, *args, **kwargs)
self._positionals.title = "Positional Arguments"
self._optionals.title = "Optional Arguments"
self._optionals.description = "In addition to any higher level options"
self._sort_args = True
def sub(self):
return self.add_subparsers(
title="Subcommands", description=OMEROSUBS, metavar=OMEROSUBM)
def add(self, sub, func, help=None, **kwargs):
if help is None:
help = func.__doc__
parser = sub.add_parser(
func.im_func.__name__, help=help, description=help)
parser.set_defaults(func=func, **kwargs)
return parser
def add_limit_arguments(self):
self.add_argument(
"--limit", help="maximum number of return values (default=25)",
type=int, default=25)
self.add_argument(
"--offset", help="number of entries to skip (default=0)",
type=int, default=0)
def add_style_argument(self):
from omero.util.text import list_styles
self.add_argument(
"--style", help="use alternative output style (default=sql)",
choices=list_styles())
def add_login_arguments(self):
group = self.add_argument_group(
'Login arguments', ENV_HELP + """
Optional session arguments:
""")
group.add_argument(
"-C", "--create", action="store_true",
help="Create a new session regardless of existing ones")
group.add_argument("-s", "--server", help="OMERO server hostname")
group.add_argument("-p", "--port", help="OMERO server port")
group.add_argument("-g", "--group", help="OMERO server default group")
group.add_argument("-u", "--user", help="OMERO username")
group.add_argument("-w", "--password", help="OMERO password")
group.add_argument(
"-k", "--key",
help="OMERO session key (UUID of an active session)")
group.add_argument(
"--sudo", metavar="ADMINUSER",
help="Create session as this admin. Changes meaning of password!")
group.add_argument(
"-q", "--quiet", action="store_true",
help="Quiet mode. Causes most warning and diagnostic messages to "
"be suppressed.")
def add_group_print_arguments(self):
printgroup = self.add_mutually_exclusive_group()
printgroup.add_argument(
"--long", action="store_true", default=True,
help="Print comma-separated list of all groups (default)")
printgroup.add_argument(
"--count", action="store_true", default=False,
help="Print count of all groups")
def add_user_print_arguments(self):
printgroup = self.add_mutually_exclusive_group()
printgroup.add_argument(
"--count", action="store_true", default=True,
help="Print count of all users and owners (default)")
printgroup.add_argument(
"--long", action="store_true", default=False,
help="Print comma-separated list of all users and owners")
def add_user_sorting_arguments(self):
sortgroup = self.add_mutually_exclusive_group()
sortgroup.add_argument(
"--sort-by-id", action="store_true", default=True,
help="Sort users by ID (default)")
sortgroup.add_argument(
"--sort-by-login", action="store_true", default=False,
help="Sort users by login")
sortgroup.add_argument(
"--sort-by-first-name", action="store_true", default=False,
help="Sort users by first name")
sortgroup.add_argument(
"--sort-by-last-name", action="store_true", default=False,
help="Sort users by last name")
sortgroup.add_argument(
"--sort-by-email", action="store_true", default=False,
help="Sort users by email")
def add_group_sorting_arguments(self):
sortgroup = self.add_mutually_exclusive_group()
sortgroup.add_argument(
"--sort-by-id", action="store_true", default=True,
help="Sort groups by ID (default)")
sortgroup.add_argument(
"--sort-by-name", action="store_true", default=False,
help="Sort groups by name")
def set_args_unsorted(self):
self._sort_args = False
def _check_value(self, action, value):
# converted value must be one of the choices (if specified)
if action.choices is not None and value not in action.choices:
msg = 'invalid choice: %r\n\nchoose from:\n' % value
choices = list(action.choices)
if self._sort_args:
choices = sorted(choices)
msg += self._format_list(choices)
raise ArgumentError(action, msg)
def _format_list(self, choices):
lines = ["\t"]
if choices:
while len(choices) > 1:
choice = choices.pop(0)
lines[-1] += ("%s, " % choice)
if len(lines[-1]) > 62:
lines.append("\t")
lines[-1] += choices.pop(0)
return "\n".join(lines)
class ProxyStringType(object):
"""
To make use of the omero.proxy_to_instance method,
an instance can be passed to add_argument with a default
value: add_argument(..., type=ProxyStringType("Image"))
which will take either a proxy string of the form:
"Image:1" or simply the ID itself: "1"
"""
def __init__(self, default=None):
self.default = default
def __call__(self, s):
try:
return omero.proxy_to_instance(s, default=self.default)
except omero.ClientError, ce:
raise ValueError(str(ce))
def __repr__(self):
return "proxy"
class NewFileType(FileType):
"""
Extension of the argparse.FileType to prevent
overwrite existing files.
"""
def __call__(self, s):
if s != "-" and os.path.exists(s):
raise ArgumentTypeError("File exists: %s" % s)
return FileType.__call__(self, s)
class ExistingFile(FileType):
"""
Extension of the argparse.FileType that requires
an existing file.
"""
def __call__(self, s):
if s != "-" and not os.path.exists(s):
raise ArgumentTypeError("File does not exist: %s" % s)
if s != "-":
return FileType.__call__(self, s)
else:
return s
class DirectoryType(FileType):
"""
Extension of the argparse.FileType to only allow
existing directories.
"""
def __call__(self, s):
p = path(s)
if not p.exists():
raise ArgumentTypeError("Directory does not exist: %s" % s)
elif not p.isdir():
raise ArgumentTypeError("Path is not a directory: %s" % s)
return str(p.abspath())
class ExceptionHandler(object):
"""
Location for all logic which maps from server exceptions
to specific states. This could likely be moved elsewhere
for general client-side usage.
"""
def is_constraint_violation(self, ve):
if isinstance(ve, omero.ValidationException):
if "org.hibernate.exception.ConstraintViolationException: " \
"could not insert" in str(ve):
return True
def handle_failed_request(self, rfe):
import Ice
if isinstance(rfe, Ice.OperationNotExistException):
return "Operation not supported by the server: %s" % rfe.operation
else:
return "Unknown Ice.RequestFailedException"
DEBUG_HELP = """
Set debug options for developers
The value to the debug argument is a comma-separated list of commands.
Available debugging choices:
'0' Disable debugging
'debug' Enable debugging at the first debug level
'1'-'9' Enable debugging at the specified debug level
'trace' Run the command with tracing enabled
'profile' Run the command with profiling enabled
Note "trace" and "profile" cannot be used simultaneously
Examples:
# Enabled debugging at level 1 and prints tracing
bin/omero --debug=debug,trace admin start
# Enabled debugging at level 1
bin/omero -d1 admin start
# Enabled debugging at level 3
bin/omero -d3 admin start
# Enable profiling
bin/omero -dp admin start
# Fails - cannot print tracing and profiling together
bin/omero -dt,p admin start
# Disable debugging
bin/omero -d0 admin start
"""
ENV_HELP = """Environment variables:
OMERO_USERDIR Set the base directory containing the user's files.
Default: $HOME/omero
OMERO_SESSIONDIR Set the base directory containing local sessions.
Default: $OMERO_USERDIR/sessions
OMERO_TMPDIR Set the base directory containing temporary files.
Default: $OMERO_USERDIR/tmp
"""
class Context:
"""Simple context used for default logic. The CLI registry which registers
the plugins installs itself as a fully functional Context.
The Context class is designed to increase pluggability. Rather than
making calls directly on other plugins directly, the pub() method
routes messages to other commands. Similarly, out() and err() should
be used for printing statements to the user, and die() should be
used for exiting fatally.
"""
def __init__(self, controls=None, params=None, prog=sys.argv[0]):
self.controls = controls
if self.controls is None:
self.controls = {}
self.params = params
if self.params is None:
self.params = {}
self.event = get_event(name="CLI")
self.dir = OMERODIR
self.isquiet = False
# This usage will go away and default will be False
self.isdebug = DEBUG
self.topics = {"debug": DEBUG_HELP, "env": ENV_HELP}
self.parser = Parser(prog=prog, description=OMERODOC)
self.subparsers = self.parser_init(self.parser)
def post_process(self):
"""
Runs further processing once all the controls have been added.
"""
sessions = self.controls["sessions"]
login = self.subparsers.add_parser(
"login", help="Shortcut for 'sessions login'",
description=sessions.login.__doc__)
login.set_defaults(func=lambda args: sessions.login(args))
sessions._configure_login(login)
logout = self.subparsers.add_parser(
"logout", help="Shortcut for 'sessions logout'")
logout.set_defaults(func=lambda args: sessions.logout(args))
sessions._configure_dir(logout)
def parser_init(self, parser):
parser.add_argument(
"-v", "--version", action="version",
version="%%(prog)s %s" % VERSION)
parser.add_argument(
"-d", "--debug",
help="Use 'help debug' for more information", default=SUPPRESS)
parser.add_argument(
"--path", action="append",
help="Add file or directory to plugin list. Supports globs.")
parser.add_login_arguments()
subparsers = parser.add_subparsers(
title="Subcommands", description=OMEROSUBS, metavar=OMEROSUBM)
return subparsers
def get(self, key, defvalue=None):
return self.params.get(key, defvalue)
def set(self, key, value=True):
self.params[key] = value
def safePrint(self, text, stream, newline=True):
"""
Prints text to a given string, capturing any exceptions.
"""
try:
stream.write(str(text))
if newline:
stream.write("\n")
else:
stream.flush()
except IOError, e:
if e.errno != errno.EPIPE:
raise
except:
print >>sys.stderr, "Error printing text"
print >>sys.stdout, text
if self.isdebug:
traceback.print_exc()
def pythonpath(self):
"""
Converts the current sys.path to a PYTHONPATH string
to be used by plugins which must start a new process.
Note: this was initially created for running during
testing when PYTHONPATH is not properly set.
"""
path = list(sys.path)
for i in range(0, len(path) - 1):
if path[i] == '':
path[i] = os.getcwd()
pythonpath = ":".join(path)
return pythonpath
def userdir(self):
"""
Returns a user directory (as path.path) which can be used
for storing configuration. The directory is guaranteed to
exist and be private (700) after execution.
"""
dir = path(os.path.expanduser("~")) / "omero" / "cli"
if not dir.exists():
dir.mkdir()
elif not dir.isdir():
raise Exception("%s is not a directory" % dir)
dir.chmod(0700)
return dir
def pub(self, args, strict=False):
self.safePrint(str(args), sys.stdout)
def input(self, prompt, hidden=False, required=False):
"""
Reads from standard in. If hidden == True, then
uses getpass
"""
try:
while True:
if hidden:
import getpass
rv = getpass.getpass(prompt)
else:
rv = raw_input(prompt)
if required and not rv:
self.out("Input required")
continue
return rv
except KeyboardInterrupt:
self.die(1, "Cancelled")
def out(self, text, newline=True):
"""
Expects a single string as argument.
"""
self.safePrint(text, sys.stdout, newline)
def err(self, text, newline=True):
"""
Expects a single string as argument.
"""
self.safePrint(text, sys.stderr, newline)
def dbg(self, text, newline=True, level=1):
"""
Passes text to err() if self.isdebug is set
"""
if self.isdebug >= level:
self.err(text, newline)
def die(self, rc, args):
raise Exception((rc, args))
def exit(self, args):
self.out(args)
self.interrupt_loop = True
def call(self, args):
self.out(str(args))
def popen(self, args):
self.out(str(args))
def sleep(self, time):
self.event.wait(time)
#####################################################
#
def admin_only(func):
"""
Checks that the current user is an admin or throws an exception.
"""
def _check_admin(*args, **kwargs):
args = list(args)
self = args[0]
plugin_args = args[1]
client = self.ctx.conn(plugin_args)
ec = client.sf.getAdminService().getEventContext()
if not ec.isAdmin:
self.error_admin_only(fatal=True)
return func(*args, **kwargs)
from omero.util.decorators import wraps
_check_admin = wraps(func)(_check_admin)
return _check_admin
class BaseControl(object):
"""Controls get registered with a CLI instance on loadplugins().
To create a new control, subclass BaseControl, implement _configure,
and end your module with::
try:
register("name", MyControl, HELP)
except:
if __name__ == "__main__":
cli = CLI()
cli.register("name", MyControl, HELP)
cli.invoke(sys.argv[1:])
This module should be put in the omero.plugins package.
All methods which do NOT begin with "_" are assumed to be accessible
to CLI users.
"""
###############################################
#
# Mostly reusable code
#
def __init__(self, ctx=None, dir=OMERODIR):
self.dir = path(dir) # Guaranteed to be a path
self.ctx = ctx
if self.ctx is None:
self.ctx = Context() # Prevents unncessary stop_event creation
def _isWindows(self):
p_s = platform.system()
if p_s == 'Windows':
return True
else:
return False
def _host(self):
"""
Return hostname of current machine. Termed to be the
value return from socket.gethostname() up to the first
decimal.
"""
if not hasattr(self, "hostname") or not self.hostname:
self.hostname = socket.gethostname()
if self.hostname.find(".") > 0:
self.hostname = self.hostname.split(".")[0]
return self.hostname
def _node(self, omero_node=None):
"""
Return the name of this node, using either the environment
vairable OMERO_NODE or _host(). Some subclasses may
override this functionality, most notably "admin" commands
which assume a node name of "master".
If the optional argument is not None, then the OMERO_NODE
environment variable will be set.
"""
if omero_node is not None:
os.environ["OMERO_NODE"] = omero_node
if "OMERO_NODE" in os.environ:
return os.environ["OMERO_NODE"]
else:
return self._host()
def _icedata(self, property):
"""
General data method for creating a path from an Ice property.
"""
try:
nodepath = self._properties()[property]
if RELFILE.match(nodepath):
nodedata = self.dir / path(nodepath)
else:
nodedata = path(nodepath)
created = False
if not nodedata.exists():
self.ctx.out("Creating "+nodedata)
nodedata.makedirs()
created = True
return (nodedata, created)
except KeyError, ke:
self.ctx.err(property + " is not configured")
self.ctx.die(4, str(ke))
def _initDir(self):
"""
Initialize the directory into which the current node will log.
"""
props = self._properties()
self._nodedata()
logdata = self.dir / path(props["Ice.StdOut"]).dirname()
if not logdata.exists():
self.ctx.out("Initializing %s" % logdata)
logdata.makedirs()
def _nodedata(self):
"""
Returns the data directory path for this node. This is determined
from the "IceGrid.Node.Data" property in the _properties()
map.
The directory will be created if it does not exist.
"""
data, created = self._icedata("IceGrid.Node.Data")
return data
def _regdata(self):
"""
Returns the data directory for the IceGrid registry.
This is determined from the "IceGrid.Registry.Data" property
in the _properties() map.
The directory will be created if it does not exist, and
a warning issued.
"""
data, created = self._icedata("IceGrid.Registry.Data")
def _pid(self):
"""
Returns a path of the form _nodedata() / (_node() + ".pid"),
i.e. a file named NODENAME.pid in the node's data directory.
"""
pidfile = self._nodedata() / (self._node() + ".pid")
return pidfile
def _cfglist(self):
"""
Returns a list of configuration files for this node. This
defaults to the internal configuration for all nodes,
followed by a file named NODENAME.cfg under the etc/
directory, following by PLATFORM.cfg if it exists.
"""
cfgs = self.dir / "etc"
internal = cfgs / "internal.cfg"
owncfg = cfgs / self._node() + ".cfg"
results = [internal, owncfg]
# Look for <platform>.cfg
p_s = platform.system()
p_c = cfgs / p_s + ".cfg"
if p_c.exists():
results.append(p_c)
return results
def _icecfg(self):
"""
Uses _cfglist() to return a string argument of the form
"--Ice.Config=..." suitable for passing to omero.client
as an argument.
"""
icecfg = "--Ice.Config=%s" % ",".join(self._cfglist())
return str(icecfg)
def _intcfg(self):
"""
Returns an Ice.Config string with only the internal configuration
file for connecting to the IceGrid Locator.
"""
intcfg = self.dir / "etc" / "internal.cfg"
intcfg.abspath()
return str("--Ice.Config=%s" % intcfg)
def _properties(self, prefix=""):
"""
Loads all files returned by _cfglist() into a new
Ice.Properties instance and return the map from
getPropertiesForPrefix(prefix) where the default is
to return all properties.
"""
import Ice
if getattr(self, "_props", None) is None:
self._props = Ice.createProperties()
for cfg in self._cfglist():
try:
self._props.load(str(cfg))
except Exception:
self.ctx.die(3, "Could not find file: " + cfg +
"\nDid you specify the proper node?")
return self._props.getPropertiesForPrefix(prefix)
def _ask_for_password(self, reason="", root_pass=None, strict=True):
while not root_pass or len(root_pass) < 1:
root_pass = self.ctx.input("Please enter password%s: "
% reason, hidden=True)
if not strict:
return root_pass
if root_pass is None or root_pass == "":
self.ctx.err("Password cannot be empty")
continue
confirm = self.ctx.input("Please re-enter password%s: "
% reason, hidden=True)
if root_pass != confirm:
root_pass = None
self.ctx.err("Passwords don't match")
continue
break
return root_pass
def get_subcommands(self):
"""Return a list of subcommands"""
parser = Parser()
self._configure(parser)
subparsers_actions = [action for action in parser._actions
if isinstance(action, _SubParsersAction)]
subcommands = []
for subparsers_action in subparsers_actions:
for choice, subparser in subparsers_action.choices.items():
subcommands.append(format(choice))
return subcommands
###############################################
#
# Methods likely to be implemented by subclasses
#
def _complete_file(self, f, dir=None):
"""
f: path part
"""
if dir is None:
dir = self.dir
else:
dir = path(dir)
p = path(f)
if p.exists() and p.isdir():
if not f.endswith(os.sep):
return [p.basename()+os.sep]
return [str(x)[len(f):] for x in p.listdir(
unreadable_as_empty=True)]
else:
results = [str(x.basename()) for x in dir.glob(f+"*")]
if len(results) == 1:
# Relative to cwd
maybe_dir = path(results[0])
if maybe_dir.exists() and maybe_dir.isdir():
return [results[0] + os.sep]
return results
def _complete(self, text, line, begidx, endidx):
try:
return self._complete2(text, line, begidx, endidx)
except:
self.ctx.dbg("Complete error: %s" % traceback.format_exc())
def _complete2(self, text, line, begidx, endidx):
items = shlex.split(line)
parser = getattr(self, "parser", None)
if parser:
result = []
actions = getattr(parser, "_actions")
if actions:
if len(items) > 1:
subparsers = [
x for x in actions
if x.__class__.__name__ == "_SubParsersAction"]
if subparsers:
subparsers = subparsers[0] # Guaranteed one
choice = subparsers.choices.get(items[-1])
if choice and choice._actions:
actions = choice._actions
if len(items) > 2:
actions = [] # TBD
for action in actions:
if action.__class__.__name__ == "_HelpAction":
result.append("-h")
elif action.__class__.__name__ == "_SubParsersAction":
result.extend(action.choices)
return ["%s " % x for x in result
if (not text or x.startswith(text)) and
line.find(" %s " % x) < 0]
# Fallback
completions = [method for method in dir(self)
if callable(getattr(self, method))]
return [str(method + " ") for method in completions
if method.startswith(text) and not method.startswith("_")]
def error_admin_only(self, msg="SecurityViolation: Admins only!",
code=111, fatal=True):
if fatal:
self.ctx.die(code, msg)
else:
self.ctx.err(msg)
def _order_and_range_ids(self, ids):
from itertools import groupby
from operator import itemgetter
out = ""
ids = sorted(ids)
for k, g in groupby(enumerate(ids), lambda (i, x): i-x):
g = map(str, map(itemgetter(1), g))
out += g[0]
if len(g) > 2:
out += "-" + g[-1]
elif len(g) == 2:
out += "," + g[1]
out += ","
return out.rstrip(",")
class CLI(cmd.Cmd, Context):
"""
Command line interface class. Supports various styles of executing the
registered plugins. Each plugin is given the chance to update this class
by adding methods of the form "do_<plugin name>".
"""
class PluginsLoaded(object):
"""
Thread-safe class for storing whether or not all the plugins
have been loaded
"""
def __init__(self):
self.lock = Lock()
self.done = False
def get(self):
self.lock.acquire()
try:
return self.done
finally:
self.lock.release()
def set(self):
self.lock.acquire()
try:
self.done = True
finally:
self.lock.release()
def __init__(self, prog=sys.argv[0]):
"""
Also sets the "_client" field for this instance to None. Each cli
maintains a single active client. The "session" plugin is responsible
for the loading of the client object.
"""
cmd.Cmd.__init__(self)
Context.__init__(self, prog=prog)
self.prompt = 'omero> '
self.interrupt_loop = False
self.rv = 0 #: Return value to be returned
self._stack = [] #: List of commands being processed
self._client = None #: Single client for all activities
#: Paths to be loaded; initially official plugins
self._plugin_paths = [OMEROCLI / "plugins"]
self._pluginsLoaded = CLI.PluginsLoaded()
def assertRC(self):
if self.rv != 0:
raise NonZeroReturnCode(self.rv, "assert failed")
def invoke(self, line, strict=False, previous_args=None):
"""
Copied from cmd.py
"""
try:
line = self.precmd(line)
stop = self.onecmd(line, previous_args)
stop = self.postcmd(stop, line)
if strict:
self.assertRC()
finally:
if len(self._stack) == 0:
self.close()
else:
self.dbg("Delaying close for stack: %s"
% len(self._stack), level=2)
def invokeloop(self):
# First we add a few special commands to the loop
class PWD(BaseControl):
def __call__(self, args):
self.ctx.out(os.getcwd())
class LS(BaseControl):
def __call__(self, args):
for p in sorted(path(os.getcwd()).listdir(
unreadable_as_empty=True)):
self.ctx.out(str(p.basename()))
class CD(BaseControl):
def _complete(self, text, line, begidx, endidx):
RE = re.compile("\s*cd\s*")
m = RE.match(line)
if m:
replaced = RE.sub('', line)
return self._complete_file(replaced, path(os.getcwd()))
return []
def _configure(self, parser):
parser.set_defaults(func=self.__call__)
parser.add_argument("dir", help="Target directory")
def __call__(self, args):
os.chdir(args.dir)
self.register("pwd", PWD, "Print the current directory")
self.register("ls", LS, "Print files in the current directory")
self.register("dir", LS, "Alias for 'ls'")
self.register("cd", CD, "Change the current directory")
try:
self.selfintro = "\n".join([OMEROSHELL, OMEROHELP])
if not self.stdin.isatty():
self.selfintro = ""
self.prompt = ""
while not self.interrupt_loop:
try:
# Calls the same thing as invoke
self.cmdloop(self.selfintro)
except KeyboardInterrupt:
self.selfintro = ""
self.out("Use quit to exit")
finally:
self.close()
def postloop(self):
# We've done the intro once now. Don't repeat yourself.
self.selfintro = ""
def onecmd(self, line, previous_args=None):
"""
Single command logic. Overrides the cmd.Cmd logic
by calling execute. Also handles various exception
conditions.
"""
try:
# Starting a new command. Reset the return value to 0
# If err or die are called, set rv non-0 value
self.rv = 0
try:
self._stack.insert(0, line)
self.dbg("Stack+: %s" % len(self._stack), level=2)
self.execute(line, previous_args)
return True
finally:
self._stack.pop(0)
self.dbg("Stack-: %s" % len(self._stack), level=2)
except SystemExit, exc: # Thrown by argparse
self.dbg("SystemExit raised\n%s" % traceback.format_exc())
self.rv = exc.code
return False
#
# This was perhaps only needed previously
# Omitting for the moment with the new
# argparse refactoring
#
# except AttributeError, ae:
# self.err("Possible error in plugin:")
# self.err(str(ae))
# if self.isdebug:
# traceback.print_exc()
except NonZeroReturnCode, nzrc:
self.dbg(traceback.format_exc())
self.rv = nzrc.rv
return False # Continue
def postcmd(self, stop, line):
"""
Checks interrupt_loop for True and return as much
which will end the call to cmdloop. Otherwise use
the default postcmd logic (which simply returns stop)
"""
if self.interrupt_loop:
return True
return cmd.Cmd.postcmd(self, stop, line)
def execute(self, line, previous_args):
"""
String/list handling as well as EOF and comment handling.
Otherwise, parses the arguments as shlexed and runs the
function returned by argparse.
"""
if isinstance(line, (str, unicode)):
if COMMENT.match(line):
return # EARLY EXIT!
args = shlex.split(line)
elif isinstance(line, (tuple, list)):
args = list(line)
else:
self.die(1, "Bad argument type: %s ('%s')" % (type(line), line))
if not args:
return
elif args == ["EOF"]:
self.exit("")
return
args = self.parser.parse_args(args, previous_args)
args.prog = self.parser.prog
self.waitForPlugins()
self.isquiet = getattr(args, "quiet", False)
debug_str = getattr(args, "debug", "")
debug_opts = set([x.lower() for x in debug_str.split(",")])
if "" in debug_opts:
debug_opts.remove("")
old_debug = self.isdebug
if "debug" in debug_opts:
self.isdebug = 1
debug_opts.remove("debug")
elif "0" in debug_opts:
self.isdebug = 0
debug_opts.remove("0")
for x in range(1, 9):
if str(x) in debug_opts:
self.isdebug = x
debug_opts.remove(str(x))
try:
if len(debug_opts) == 0:
args.func(args)
elif len(debug_opts) > 1:
self.die(9, "Conflicting debug options: %s"
% ", ".join(debug_opts))
elif "t" in debug_opts or "trace" in debug_opts:
import trace
tracer = trace.Trace()
tracer.runfunc(args.func, args)
elif "p" in debug_opts or "profile" in debug_opts:
from hotshot import stats, Profile
from omero.util import get_omero_userdir
profile_file = get_omero_userdir() / "hotshot_edi_stats"
prof = Profile(profile_file)
prof.runcall(lambda: args.func(args))
prof.close()
s = stats.load(profile_file)
s.sort_stats("time").print_stats()
else:
self.die(10, "Unknown debug action: %s" % debug_opts)
finally:
self.isdebug = old_debug
def completedefault(self, *args):
return []
def completenames(self, text, line, begidx, endidx):
names = self.controls.keys()
return [str(n + " ") for n in names if n.startswith(line)]
##########################################
##
# Context interface
##
def exit(self, args, newline=True):
self.out(args, newline)
self.interrupt_loop = True
def die(self, rc, text, newline=True):
self.err(text, newline)
self.rv = rc
# self.interrupt_loop = True
raise NonZeroReturnCode(rc, "die called: %s" % text)
def _env(self):
"""
Configure environment with PYTHONPATH as
setup by bin/omero
This list needs to be kept in line with OmeroPy/bin/omero
"""
lpy = str(self.dir / "lib" / "python")
ipy = str(self.dir / "lib" / "fallback")
vlb = str(self.dir / "var" / "lib")
paths = os.path.pathsep.join([lpy, vlb, ipy])
env = dict(os.environ)
pypath = env.get("PYTHONPATH", None)
if pypath is None:
pypath = paths
else:
if pypath.endswith(os.path.pathsep):
pypath = "%s%s" % (pypath, paths)
else:
pypath = "%s%s%s" % (pypath, os.path.pathsep, paths)
env["PYTHONPATH"] = pypath
return env
def _cwd(self, cwd):
if cwd is None:
cwd = str(self.dir)
else:
cwd = str(cwd)
return cwd
def call(self, args, strict=True, cwd=None):
"""
Calls the string in a subprocess and dies if the return value is not 0
"""
self.dbg("Executing: %s" % args)
rv = subprocess.call(args, env=self._env(), cwd=self._cwd(cwd))
if strict and not rv == 0:
raise NonZeroReturnCode(rv, "%s => %d" % (" ".join(args), rv))
return rv
def popen(self, args, cwd=None, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, **kwargs):
self.dbg("Returning popen: %s" % args)
env = self._env()
env.update(kwargs)
return subprocess.Popen(args, env=env, cwd=self._cwd(cwd),
stdout=stdout, stderr=stderr)
def readDefaults(self):
try:
f = path(self._cwd(None)) / "etc" / "omero.properties"
f = f.open()
output = "".join(f.readlines())
f.close()
except:
if self.isdebug:
raise
print "No omero.properties found"
output = ""
return output
def parsePropertyFile(self, data, output):
for line in output.splitlines():
if line.startswith(
"Listening for transport dt_socket at address"):
self.dbg(
"Ignoring stdout 'Listening for transport' from DEBUG=1")
continue
parts = line.split("=", 1)
if len(parts) == 2:
data.properties.setProperty(parts[0], parts[1])
self.dbg("Set property: %s=%s" % (parts[0], parts[1]))
else:
self.dbg("Bad property:"+str(parts))
return data
def initData(self, properties=None):
"""
Uses "omero prefs" to create an Ice.InitializationData().
"""
if properties is None:
properties = {}
from omero.plugins.prefs import getprefs
try:
output = getprefs(["get"], str(path(self._cwd(None)) / "lib"))
except OSError, err:
self.err("Error getting preferences")
self.dbg(err)
output = ""
import Ice
data = Ice.InitializationData()
data.properties = Ice.createProperties()
for k, v in properties.items():
data.properties.setProperty(k, v)
self.parsePropertyFile(data, output)
return data
def conn(self, args=None):
"""
Returns any active _client object. If one is present but
not alive, it will be removed.
If no client is found and arguments are available,
will use the current settings to connect.
If required attributes are missing, will delegate to the login
command.
FIXME: Currently differing setting sessions on the same CLI instance
will misuse a client.
"""
if self.get_client():
self.dbg("Found client")
try:
self.get_client().getSession().keepAlive(None)
self.dbg("Using client")
return self.get_client()
except KeyboardInterrupt:
raise
except Exception, e:
self.dbg("Removing client: %s" % e)
self.get_client().closeSession()
self.set_client(None)
if args is not None:
if "sessions" not in self.controls:
# Most likely to happen during development
self.die(111, "No sessions control! Cannot login")
self.controls["sessions"].login(args)
return self.get_client() # Possibly added by "login"
def close(self):
client = self.get_client()
if client:
self.dbg("Closing client: %s" % client)
client.__del__()
##
# Plugin registry
##
def register(self, name, Control, help, epilog=None):
self.register_only(name, Control, help, epilog=epilog)
self.configure_plugins()
def register_only(self, name, Control, help, epilog=None):
""" This method is added to the globals when execfile() is
called on each plugin. A Control class should be
passed to the register method which will be added to the CLI.
"""
self.controls[name] = (Control, help, epilog)
def configure_plugins(self):
"""
Run to instantiate and configure all plugins
which were registered via register_only()
"""
for name in sorted(self.controls):
control = self.controls[name]
if isinstance(control, tuple):
Control = control[0]
help = control[1]
epilog = control[2]
control = Control(ctx=self, dir=self.dir)
self.controls[name] = control
setattr(self, "complete_%s" % name, control._complete)
parser = self.subparsers.add_parser(name, help=help)
parser.description = help
parser.epilog = epilog
if hasattr(control, "_configure"):
control._configure(parser)
elif hasattr(control, "__call__"):
parser.set_defaults(func=control.__call__)
control.parser = parser
def waitForPlugins(self):
if True:
return # Disabling. See comment in argv
self.dbg("Starting waitForPlugins")
while not self._pluginsLoaded.get():
self.dbg("Waiting for plugins...")
time.sleep(0.1)
def loadplugins(self):
"""
Finds all plugins and gives them a chance to register
themselves with the CLI instance. Here register_only()
is used to guarantee the orderedness of the plugins
in the parser
"""
for plugin_path in self._plugin_paths:
self.loadpath(path(plugin_path))
self.configure_plugins()
self._pluginsLoaded.set()
self.post_process()
def loadpath(self, pathobj):
if pathobj.isdir():
for plugin in pathobj.walkfiles("*.py"):
if -1 == plugin.find("#"): # Omit emacs files
self.loadpath(path(plugin))
else:
if self.isdebug:
print "Loading %s" % pathobj
try:
loc = {"register": self.register_only}
execfile(str(pathobj), loc)
except KeyboardInterrupt:
raise
except:
self.err("Error loading: %s" % pathobj)
traceback.print_exc()
def get_event_context(self):
return getattr(self, '_event_context', None)
def set_event_context(self, ec):
setattr(self, '_event_context', ec)
def get_client(self):
return getattr(self, '_client', None)
def set_client(self, client):
setattr(self, '_client', client)
# End Cli
###########################################################
def argv(args=sys.argv):
"""
Main entry point for the OMERO command-line interface. First
loads all plugins by passing them the classes defined here
so they can register their methods.
Then the case where arguments are passed on the command line are
handled.
Finally, the cli enters a command loop reading from standard in.
"""
# Modiying the run-time environment
old_ice_config = os.getenv("ICE_CONFIG")
os.unsetenv("ICE_CONFIG")
try:
# Modifying the args list if the name of the file
# has arguments encoded in it
original_executable = path(args[0])
base_executable = str(original_executable.basename())
if base_executable.find("-") >= 0:
parts = base_executable.split("-")
for arg in args[1:]:
parts.append(arg)
args = parts
# Now load other plugins. After debugging is turned on, but before
# tracing.
cli = CLI(prog=original_executable.split("-")[0])
parser = Parser(add_help=False)
# parser.add_argument("-d", "--debug", help="Use 'help debug' for more
# information", default = SUPPRESS)
parser.add_argument(
"--path", action="append",
help="Add file or directory to plugin list. Supports globs.")
ns, args = parser.parse_known_args(args)
if getattr(ns, "path"):
for p in ns.path:
for g in glob.glob(p):
cli._plugin_paths.append(g)
# For argparse dispatch, this cannot be done lazily
cli.loadplugins()
if len(args) > 1:
cli.invoke(args[1:])
return cli.rv
else:
cli.invokeloop()
return cli.rv
finally:
if old_ice_config:
os.putenv("ICE_CONFIG", old_ice_config)
#####################################################
#
# Specific argument types
class ExperimenterArg(object):
def __init__(self, arg):
self.orig = arg
self.usr = None
try:
self.usr = long(arg)
except ValueError:
if ":" in arg:
parts = arg.split(":", 1)
if parts[0] == "User" or "Experimenter":
try:
self.usr = long(parts[1])
except ValueError:
pass
def lookup(self, client):
if self.usr is None:
import omero
a = client.sf.getAdminService()
try:
self.usr = a.lookupExperimenter(self.orig).id.val
except omero.ApiUsageException:
pass
return self.usr
class ExperimenterGroupArg(object):
def __init__(self, arg):
self.orig = arg
self.grp = None
try:
self.grp = long(arg)
except ValueError:
if ":" in arg:
parts = arg.split(":", 1)
if parts[0] == "Group" or "ExperimenterGroup":
try:
self.grp = long(parts[1])
except ValueError:
pass
def lookup(self, client):
if self.grp is None:
import omero
a = client.sf.getAdminService()
try:
self.grp = a.lookupGroup(self.orig).id.val
except omero.ApiUsageException:
pass
return self.grp
class GraphArg(object):
def __init__(self, cmd_type):
self.cmd_type = cmd_type
def __call__(self, arg):
cmd = self.cmd_type()
targetObjects = dict()
try:
parts = arg.split(":", 1)
assert len(parts) == 2
assert '+' not in parts[0]
parts[0] = parts[0].lstrip("/")
graph = parts[0].split("/")
ids = []
needsForce = False
for id in parts[1].split(","):
if "-" in id:
needsForce = True
low, high = map(long, id.split("-"))
if high < low:
raise ValueError("Bad range: %s", arg)
ids.extend(range(low, high+1))
else:
ids.append(long(id))
targetObjects[graph[0]] = ids
cmd.targetObjects = targetObjects
if len(graph) > 1:
skiphead = omero.cmd.SkipHead()
skiphead.request = cmd
skiphead.targetObjects = targetObjects
skiphead.startFrom = [graph[-1]]
cmd = skiphead
return cmd, needsForce
except:
raise ValueError("Bad object: %s", arg)
def __repr__(self):
return "argument"
#####################################################
#
# Specific superclasses for various controls
class CmdControl(BaseControl):
def cmd_type(self):
raise Exception("Must be overridden by subclasses")
def _configure(self, parser):
parser.set_defaults(func=self.main_method)
parser.add_argument(
"--wait", type=long,
help="Number of seconds to wait for the processing to complete "
"(Indefinite < 0; No wait=0).", default=-1)
def main_method(self, args):
client = self.ctx.conn(args)
req = self.cmd_type()
self._process_request(req, args, client)
def _process_request(self, req, args, client):
"""
Allow specific filling of parameters in the request.
"""
cb = None
try:
rsp, status, cb = self.response(client, req, wait=args.wait)
self.print_report(req, rsp, status, args.report)
finally:
if cb is not None:
cb.close(True) # Close handle
def get_error(self, rsp):
if not isinstance(rsp, omero.cmd.ERR):
return None
else:
sb = "failed: '%s'\n" % rsp.name
sb += self.create_error_report(rsp)
return sb
def create_error_report(self, rsp):
if isinstance(rsp, omero.cmd.GraphException):
return 'failed: %s' % rsp.message
"""
Generate default error report aggregating the response parameters
"""
sb = ""
if rsp.parameters:
for k in sorted(rsp.parameters):
v = rsp.parameters.get(k, "")
sb += "\t%s=%s\n" % (k, v)
return sb
def print_report(self, req, rsp, status, detailed):
self.ctx.out(self.print_request_description(req), newline=False)
err = self.get_error(rsp)
if err:
self.ctx.err(err)
else:
self.ctx.out("ok")
if detailed:
self.ctx.out("Steps: %s" % status.steps)
if status.stopTime > 0 and status.startTime > 0:
elapse = status.stopTime - status.startTime
self.ctx.out("Elapsed time: %s secs." % (elapse/1000.0))
else:
self.ctx.out("Unfinished.")
self.ctx.out("Flags: %s" % status.flags)
self.print_detailed_report(req, rsp, status)
def print_detailed_report(self, req, rsp, status):
"""
Extension point for subclasses.
"""
pass
def line_to_opts(self, line, opts):
if not line or line.startswith("#"):
return
parts = line.split("=", 1)
if len(parts) == 1:
parts.append("")
opts[parts[0].strip()] = parts[1].strip()
def response(self, client, req, loops=8, ms=500, wait=None):
import omero.callbacks
handle = client.sf.submit(req)
cb = omero.callbacks.CmdCallbackI(client, handle)
if wait is None:
cb.loop(loops, ms)
elif wait == 0:
self.ctx.out("Exiting immediately")
elif wait > 0:
ms = wait * 1000
ms = ms / loops
self.ctx.out("Waiting %s loops of %s ms" % (ms, loops))
cb.loop(loops, ms)
else:
try:
# Wait for finish
while True:
found = cb.block(ms)
if found:
break
# If user uses Ctrl-C, then cancel
except KeyboardInterrupt:
self.ctx.out("Attempting cancel...")
if handle.cancel():
self.ctx.out("Cancelled")
else:
self.ctx.out("Failed to cancel")
return cb.getResponse(), cb.getStatus(), cb
class GraphControl(CmdControl):
def cmd_type(self):
raise Exception("Must be overridden by subclasses")
def _configure(self, parser):
parser.set_defaults(func=self.main_method)
parser.add_argument(
"--wait", type=long,
help="Number of seconds to wait for the processing to complete "
"(Indefinite < 0; No wait=0).", default=-1)
parser.add_argument(
"--include",
help="Modifies the given option by including a list of objects")
parser.add_argument(
"--exclude",
help="Modifies the given option by excluding a list of objects")
parser.add_argument(
"--ordered", action="store_true",
help=("Pass multiple objects to commands strictly in the order "
"given, otherwise group into as few commands as possible."))
parser.add_argument(
"--list", action="store_true",
help="Print a list of all available graph specs")
parser.add_argument(
"--list-details", action="store_true", help=SUPPRESS)
parser.add_argument(
"--report", action="store_true",
help="Print more detailed report of each action")
parser.add_argument(
"--dry-run", action="store_true",
help=("Do a dry run of the command, providing a "
"report of what would have been done"))
parser.add_argument(
"--force", action="store_true",
help=("Force an action that otherwise defaults to a dry run"))
self._pre_objects(parser)
parser.add_argument(
"obj", nargs="*", type=GraphArg(self.cmd_type()),
help="Objects to be processed in the form <Class>:<Id>")
def _pre_objects(self, parser):
"""
Allows configuring before the "obj" n-argument is added.
"""
pass
def as_doall(self, req_or_doall):
if not isinstance(req_or_doall, omero.cmd.DoAll):
req_or_doall = omero.cmd.DoAll([req_or_doall])
return req_or_doall
def default_exclude(self):
"""
Return a list of types to exclude by default.
"""
return []
def main_method(self, args):
client = self.ctx.conn(args)
if args.list_details or args.list:
cb = None
req = omero.cmd.LegalGraphTargets(self.cmd_type()())
try:
try:
speclist, status, cb = self.response(client, req)
except omero.LockTimeout, lt:
self.ctx.die(446, "LockTimeout: %s" % lt.message)
finally:
if cb is not None:
cb.close(True) # Close handle
# Could be put in positive_response helper
err = self.get_error(speclist)
if err:
self.ctx.die(367, err)
specs = sorted([t.split(".")[-1] for t in speclist.targets])
self.ctx.out("\n".join(specs))
return # Early exit.
inc = []
if args.include:
inc = args.include.split(",")
exc = self.default_exclude()
if args.exclude:
exc.extend(args.exclude.split(","))
if inc or exc:
opt = omero.cmd.graphs.ChildOption()
if inc:
opt.includeType = inc
if exc:
opt.excludeType = exc
commands, forces = zip(*args.obj)
needsForce = any(forces)
for req in commands:
req.dryRun = args.dry_run or needsForce
if args.force:
req.dryRun = False
if inc or exc:
req.childOptions = [opt]
if isinstance(req, omero.cmd.SkipHead):
req.request.childOptions = req.childOptions
req.request.dryRun = req.dryRun
if not args.ordered and len(commands) > 1:
commands = self.combine_commands(commands)
for command_check in commands:
self._check_command(command_check)
if len(commands) == 1:
cmd = commands[0]
else:
cmd = omero.cmd.DoAll(commands)
self._process_request(cmd, args, client)
def _check_command(self, command_check):
query = self.ctx.get_client().sf.getQueryService()
ec = self.ctx.get_event_context()
own_id = ec.userId
if not command_check or not command_check.targetObjects:
return
for k, v in command_check.targetObjects.items():
query_str = (
"select "
"x.details.owner.id, "
"x.details.group.details.permissions "
"from %s x "
"where x.id = :id") % k
if not v:
return
for w in v:
try:
uid, perms = omero.rtypes.unwrap(
query.projection(
query_str,
omero.sys.ParametersI().addId(w),
{"omero.group": "-1"})[0])
perms = perms["perm"]
perms = omero.model.PermissionsI(perms)
if perms.isGroupWrite() and uid != own_id:
self.ctx.err(
"WARNING: %s:%s belongs to user %s" % (
k, w, uid))
except:
self.ctx.dbg(traceback.format_exc())
# Doing nothing since this is a best effort
def combine_commands(self, commands):
"""
Combine several commands into as few as possible.
For simple commands a single combined command is possible,
for a skiphead it is more complicated. Here skipheads are
combined using their startFrom object type.
"""
from omero.cmd import SkipHead
skipheads = [req for req in commands if isinstance(req, SkipHead)]
others = [req for req in commands if not isinstance(req, SkipHead)]
rv = []
# Combine all simple commands
if len(others) == 1:
rv.extend(others)
elif len(others) > 1:
for req in others[1:]:
type, ids = req.targetObjects.items()[0]
others[0].targetObjects.setdefault(type, []).extend(ids)
rv.append(others[0])
# Group skipheads by their startFrom attribute.
if len(skipheads) == 1:
rv.extend(skipheads)
elif len(skipheads) > 1:
shmap = {skipheads[0].startFrom[0]: skipheads[0]}
for req in skipheads[1:]:
if req.startFrom[0] in shmap:
type, ids = req.targetObjects.items()[0]
if type in shmap[req.startFrom[0]].targetObjects:
shmap[req.startFrom[0]].targetObjects[type].extend(ids)
else:
shmap[req.startFrom[0]].targetObjects[type] = ids
else:
shmap[req.startFrom[0]] = req
for req in shmap.values():
rv.append(req)
return rv
def print_request_description(self, request):
doall = self.as_doall(request)
cmd_type = self.cmd_type().ice_staticId()[2:].replace("::", ".")
objects = []
for req in doall.requests:
for type in req.targetObjects.keys():
ids = self._order_and_range_ids(req.targetObjects[type])
if isinstance(req, omero.cmd.SkipHead):
type += ("/" + req.startFrom[0])
objects.append('%s:%s' % (type, ids))
return "%s %s " % (cmd_type, ' '.join(objects))
def _get_object_ids(self, objDict):
import collections
objIds = {}
for k in objDict.keys():
if objDict[k]:
objIds[k] = self._order_and_range_ids(objDict[k])
newIds = collections.OrderedDict(sorted(objIds.items()))
objIds = collections.OrderedDict()
for k in newIds:
key = k[k.rfind('.')+1:]
objIds[key] = newIds[k]
return objIds
class UserGroupControl(BaseControl):
def error_no_input_group(self, msg="No input group is specified",
code=501, fatal=True):
if fatal:
self.ctx.die(code, msg)
else:
self.ctx.err(msg)
def error_invalid_groupid(self, group_id, msg="Not a valid group ID: %s",
code=502, fatal=True):
if fatal:
self.ctx.die(code, msg % group_id)
else:
self.ctx.err(msg % group_id)
def error_invalid_group(self, group, msg="Unknown group: %s", code=503,
fatal=True):
if fatal:
self.ctx.die(code, msg % group)
else:
self.ctx.err(msg % group)
def error_no_group_found(self, msg="No group found", code=504,
fatal=True):
if fatal:
self.ctx.die(code, msg)
else:
self.ctx.err(msg)
def error_ambiguous_group(self, id_or_name,
msg="Ambiguous group identifier: %s", code=505,
fatal=True):
if fatal:
self.ctx.die(code, msg % id_or_name)
else:
self.ctx.err(msg % id_or_name)
def error_no_input_user(self, msg="No input user is specified", code=511,
fatal=True):
if fatal:
self.ctx.die(code, msg)
else:
self.ctx.err(msg)
def error_invalid_userid(self, user_id, msg="Not a valid user ID: %s",
code=512, fatal=True):
if fatal:
self.ctx.die(code, msg % user_id)
else:
self.ctx.err(msg % user_id)
def error_invalid_user(self, user, msg="Unknown user: %s", code=513,
fatal=True):
if fatal:
self.ctx.die(code, msg % user)
else:
self.ctx.err(msg % user)
def error_no_user_found(self, msg="No user found", code=514, fatal=True):
if fatal:
self.ctx.die(code, msg)
else:
self.ctx.err(msg)
def error_ambiguous_user(self, id_or_name,
msg="Ambiguous user identifier: %s", code=515,
fatal=True):
if fatal:
self.ctx.die(code, msg % id_or_name)
else:
self.ctx.err(msg % id_or_name)
def find_group_by_id(self, admin, group_id, fatal=False):
import omero
try:
gid = long(group_id)
g = admin.getGroup(gid)
except ValueError:
self.error_invalid_groupid(group_id, fatal=fatal)
return None, None
except omero.ApiUsageException:
self.error_invalid_group(gid, fatal=fatal)
return None, None
return gid, g
def find_group_by_name(self, admin, group_name, fatal=False):
import omero
try:
g = admin.lookupGroup(group_name)
gid = g.id.val
except omero.ApiUsageException:
self.error_invalid_group(group_name, fatal=fatal)
return None, None
return gid, g
def find_group(self, admin, id_or_name, fatal=False):
import omero
# Find by group by name
try:
g1 = admin.lookupGroup(id_or_name)
except omero.ApiUsageException:
g1 = None
# Find by group by id
try:
g2 = admin.getGroup(long(id_or_name))
except (ValueError, omero.ApiUsageException):
g2 = None
# Test found groups
if g1 and g2:
if g1.id.val != g2.id.val:
self.error_ambiguous_group(id_or_name, fatal=fatal)
return None, None
else:
g = g1
elif g1:
g = g1
elif g2:
g = g2
else:
self.error_invalid_group(id_or_name, fatal=fatal)
return None, None
return g.id.val, g
def find_user_by_id(self, admin, user_id, fatal=False):
import omero
try:
uid = long(user_id)
u = admin.getExperimenter(uid)
except ValueError:
self.error_invalid_userid(user_id, fatal=fatal)
return None, None
except omero.ApiUsageException:
self.error_invalid_user(uid, fatal=fatal)
return None, None
return uid, u
def find_user_by_name(self, admin, user_name, fatal=False):
import omero
try:
u = admin.lookupExperimenter(user_name)
uid = u.id.val
except omero.ApiUsageException:
self.error_invalid_user(user_name, fatal=fatal)
return None, None
return uid, u
def find_user(self, admin, id_or_name, fatal=False):
import omero
# Find user by name
try:
u1 = admin.lookupExperimenter(id_or_name)
except omero.ApiUsageException:
u1 = None
# Find user by id
try:
u2 = admin.getExperimenter(long(id_or_name))
except (ValueError, omero.ApiUsageException):
u2 = None
# Test found users
if u1 and u2:
if u1.id.val != u2.id.val:
self.error_ambiguous_user(id_or_name, fatal=fatal)
return None, None
else:
u = u1
elif u1:
u = u1
elif u2:
u = u2
else:
self.error_invalid_user(id_or_name, fatal=fatal)
return None, None
return u.id.val, u
def addusersbyid(self, admin, group, users):
import omero
for user in list(users):
admin.addGroups(omero.model.ExperimenterI(user, False), [group])
self.ctx.out("Added %s to group %s" % (user, group.id.val))
def removeusersbyid(self, admin, group, users):
import omero
for user in list(users):
admin.removeGroups(omero.model.ExperimenterI(user, False), [group])
self.ctx.out("Removed %s from group %s" % (user, group.id.val))
def addownersbyid(self, admin, group, users):
import omero
for user in list(users):
admin.addGroupOwners(group,
[omero.model.ExperimenterI(user, False)])
self.ctx.out("Added %s to the owner list of group %s"
% (user, group.id.val))
def removeownersbyid(self, admin, group, users):
import omero
for user in list(users):
admin.removeGroupOwners(group,
[omero.model.ExperimenterI(user, False)])
self.ctx.out("Removed %s from the owner list of group %s"
% (user, group.id.val))
def getuserids(self, group):
ids = [x.child.id.val for x in group.copyGroupExperimenterMap()]
return ids
def getmemberids(self, group):
ids = [x.child.id.val for x in group.copyGroupExperimenterMap()
if not x.owner.val]
return ids
def getownerids(self, group):
ids = [x.child.id.val for x in group.copyGroupExperimenterMap()
if x.owner.val]
return ids
def output_users_list(self, admin, users, args):
roles = admin.getSecurityRoles()
user_group = roles.userGroupId
sys_group = roles.systemGroupId
from omero.util.text import TableBuilder
if args.count:
tb = TableBuilder("id", "login", "first name", "last name",
"email", "active", "ldap", "admin",
"# group memberships", "# group ownerships")
else:
tb = TableBuilder("id", "login", "first name", "last name",
"email", "active", "ldap", "admin", "member of",
"owner of")
if args.style:
tb.set_style(args.style)
# Sort users
if isinstance(users, list):
if args.sort_by_login:
users.sort(key=lambda x: x.omeName.val)
elif args.sort_by_first_name:
users.sort(key=lambda x: x.firstName.val)
elif args.sort_by_last_name:
users.sort(key=lambda x: x.lastName.val)
elif args.sort_by_email:
users.sort(key=lambda x: (x.email and x.email.val or ""))
elif args.sort_by_id:
users.sort(key=lambda x: x.id.val)
else:
users = [users]
for user in users:
row = [user.id.val, user.omeName.val, user.firstName.val,
user.lastName.val]
row.append(user.email and user.email.val or "")
active = ""
admin = ""
ldap = user.ldap.val
member_of = []
leader_of = []
for x in user.copyGroupExperimenterMap():
if not x:
continue
gid = x.parent.id.val
if user_group == gid:
active = "Yes"
elif sys_group == gid:
admin = "Yes"
elif x.owner.val:
leader_of.append(str(gid))
else:
member_of.append(str(gid))
row.append(active)
row.append(ldap)
row.append(admin)
if member_of:
if args.count:
row.append(len(member_of))
else:
row.append(",".join(member_of))
else:
row.append("")
if leader_of:
if args.count:
row.append(len(leader_of))
else:
row.append(",".join(leader_of))
else:
row.append("")
tb.row(*tuple(row))
self.ctx.out(str(tb.build()))
def output_groups_list(self, groups, args):
from omero.util.text import TableBuilder
# Sort groups
if args.sort_by_name:
groups.sort(key=lambda x: x.name.val)
elif args.sort_by_id:
groups.sort(key=lambda x: x.id.val)
if args.long:
tb = TableBuilder("id", "name", "perms", "ldap", "owner ids",
"member ids")
else:
tb = TableBuilder("id", "name", "perms", "ldap", "# of owners",
"# of members")
if args.style:
tb.set_style(args.style)
for group in groups:
row = [group.id.val, group.name.val,
str(group.details.permissions), group.ldap.val]
ownerids = self.getownerids(group)
memberids = self.getmemberids(group)
if args.long:
row.append(",".join(sorted([str(x) for x in ownerids])))
row.append(",".join(sorted([str(x) for x in memberids])))
else:
row.append(len(ownerids))
row.append(len(memberids))
tb.row(*tuple(row))
self.ctx.out(str(tb.build()))
def add_id_name_arguments(self, parser, objtype=""):
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--id", help="ID of the %s" % objtype)
group.add_argument(
"--name", help="Name of the %s" % objtype)
return group
def add_user_and_group_arguments(self, parser, *args,
**kwargs):
group = parser
try:
if kwargs.pop("exclusive"):
group = parser.add_mutually_exclusive_group()
except:
pass
group.add_argument("--user-id",
help="ID of the user.",
*args, **kwargs)
group.add_argument("--user-name",
help="Name of the user.",
*args, **kwargs)
group.add_argument("--group-id",
help="ID of the group.",
*args, **kwargs)
group.add_argument("--group-name",
help="Name of the group.",
*args, **kwargs)
def add_user_arguments(self, parser, action=""):
group = parser.add_argument_group('User arguments')
group.add_argument("user_id_or_name", metavar="user", nargs="*",
help="ID or name of the user(s)%s" % action)
group.add_argument("--user-id", metavar="user", nargs="+",
help="ID of the user(s)%s" % action)
group.add_argument("--user-name", metavar="user", nargs="+",
help="Name of the user(s)%s" % action)
return group
def list_users(self, a, args, use_context=False):
"""
Retrieve users from the arguments defined in
:meth:`add_user_arguments`
"""
# Check input arguments
has_user_arguments = (args.user_id_or_name or args.user_id
or args.user_name)
if (not use_context and not has_user_arguments):
self.error_no_input_user(fatal=True)
# Retrieve groups by id or name
uid_list = []
u_list = []
if args.user_id_or_name:
for user in args.user_id_or_name:
[uid, u] = self.find_user(a, user, fatal=False)
if uid is not None:
uid_list.append(uid)
u_list.append(u)
if args.user_id:
for user_id in args.user_id:
[uid, u] = self.find_user_by_id(a, user_id, fatal=False)
if uid is not None:
uid_list.append(uid)
u_list.append(u)
if args.user_name:
for user_name in args.user_name:
[uid, u] = self.find_user_by_name(a, user_name, fatal=False)
if uid is not None:
uid_list.append(uid)
u_list.append(u)
if not uid_list:
if not use_context or has_user_arguments:
self.error_no_user_found(fatal=True)
else:
ec = self.ctx.get_event_context()
[uid, u] = self.find_user_by_id(a, ec.userId, fatal=False)
uid_list.append(uid)
u_list.append(u)
return uid_list, u_list
def add_group_arguments(self, parser, action=""):
group = parser.add_argument_group('Group arguments')
group.add_argument(
"group_id_or_name", metavar="group", nargs="*",
help="ID or name of the group(s)%s" % action)
group.add_argument(
"--group-id", metavar="group", nargs="+",
help="ID of the group(s)%s" % action)
group.add_argument(
"--group-name", metavar="group", nargs="+",
help="Name of the group(s)%s" % action)
return group
def list_groups(self, a, args, use_context=False):
"""
Retrieve users from the arguments defined in
:meth:`add_user_arguments`
"""
# Check input arguments
has_group_arguments = (args.group_id_or_name or args.group_id
or args.group_name)
if (not use_context and not has_group_arguments):
self.error_no_input_group(fatal=True)
# Retrieve groups by id or name
gid_list = []
g_list = []
if args.group_id_or_name:
for group in args.group_id_or_name:
[gid, g] = self.find_group(a, group, fatal=False)
if g:
gid_list.append(gid)
g_list.append(g)
if args.group_id:
for group_id in args.group_id:
[gid, g] = self.find_group_by_id(a, group_id, fatal=False)
if g:
gid_list.append(gid)
g_list.append(g)
if args.group_name:
for group_name in args.group_name:
[gid, g] = self.find_group_by_name(a, group_name, fatal=False)
if g:
gid_list.append(gid)
g_list.append(g)
if not gid_list:
if not use_context or has_group_arguments:
self.error_no_group_found(fatal=True)
else:
ec = self.ctx.get_event_context()
[gid, g] = self.find_group_by_id(a, ec.groupId, fatal=False)
gid_list.append(gid)
g_list.append(g)
return gid_list, g_list
def get_users_groups(self, args, iadmin):
users = []
groups = []
if args.user_name:
for user_name in args.user_name:
uid, u = self.find_user_by_name(
iadmin, user_name, fatal=False)
if uid is not None:
users.append(uid)
if args.user_id:
for user_id in args.user_id:
uid, u = self.find_user_by_id(
iadmin, user_id, fatal=False)
if uid is not None:
users.append(uid)
if args.group_name:
for group_name in args.group_name:
gid, g = self.find_group_by_name(
iadmin, group_name, fatal=False)
if gid is not None:
groups.append(gid)
if args.group_id:
for group_id in args.group_id:
gid, g = self.find_group_by_id(
iadmin, group_id, fatal=False)
if gid is not None:
groups.append(gid)
return users, groups
|
gpl-2.0
|
max-dicson-cf/unas-erp
|
fiis-erp/src/java/com/max/oti/system/model/View.java
|
2683
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.max.oti.system.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author max
*/
@Entity
@Table(name = "view", catalog = "dbfiis", schema = "public")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "View.findAll", query = "SELECT v FROM View v")})
public class View implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Size(max = 2147483647)
@Column(name = "detail")
private String detail;
@Column(name = "number")
private Integer number;
@JoinColumn(name = "id_session", referencedColumnName = "id")
@ManyToOne
private Session idSession;
public View() {
}
public View(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Session getIdSession() {
return idSession;
}
public void setIdSession(Session idSession) {
this.idSession = idSession;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof View)) {
return false;
}
View other = (View) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.max.oti.system.model.View[ id=" + id + " ]";
}
}
|
gpl-2.0
|
opendatakosovo/odk-wp-theme
|
content-page.php
|
1500
|
<?php
/**
* The template used for displaying page content in page.php
*
* @package Spun
*/
?>
<?php
// Here we call post_class() and assign the echo into a variable so that we can str replace a styling class in it.
// Hacky, yes, but we don't want to change functions that are outside of the theme.
ob_start();
post_class();
$post_class = ob_get_clean();
$post_class = str_replace(' hentry', ' page-hentry', $post_class);
?>
<?php
render_sub_header();
?>
<article id="post-<?php the_ID(); ?>" <?php $post_class; ?>>
<!--
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header>
--><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-links">', 'after' => '</div>', 'link_before' => '<span class="active-link">', 'link_after' => '</span>' ) ); ?>
</div><!-- .entry-content -->
<footer class="entry-meta">
<?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?>
<span class="comments-link">
<a href="#comments-toggle">
<span class="tail"></span>
<?php echo comments_number( __( '+', 'spun' ), __( '1', 'spun' ), __( '%', 'spun' ) ); ?>
</a>
</span>
<?php endif; ?>
<div class="entry-meta-wrapper">
<?php edit_post_link( __( 'Edit', 'spun' ), '<span class="edit-link">', '</span>' ); ?>
</div>
</footer><!-- .entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->
|
gpl-2.0
|
tonglin/pdPm
|
public_html/typo3_src-6.1.7/typo3/sysext/felogin/pi1/class.tx_felogin_pi1.php
|
381
|
<?php
/*
* @deprecated since 6.0, the classname tx_felogin_pi1 and this file is obsolete
* and will be removed with 6.2. The class was renamed and is now located at:
* typo3/sysext/felogin/Classes/Controller/FrontendLoginController.php
*/
require_once \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('felogin') . 'Classes/Controller/FrontendLoginController.php';
?>
|
gpl-2.0
|
GregoryMorse/IslamSource
|
IslamSourceQuranViewer/Xam/App.xaml.cs
|
950
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
#if WINDOWS_UWP
namespace IslamSourceQuranViewer.Xam
{
public partial class App : Application
{
public App ()
{
InitializeComponent();
//AppSettings.InitDefaultSettings().Wait();
MainPage = new NavigationPage(new ISQV.Xam.ExtSplashScreen());
// The root page of your application
//MainPage = new ContentPage {
// Content = new StackLayout {
// VerticalOptions = LayoutOptions.Center,
// Children = {
// new Label {
// XAlign = TextAlignment.Center,
// Text = "Welcome to Xamarin Forms!"
// }
// }
// }
//};
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
}
}
#endif
|
gpl-2.0
|
rihjsantos/dgnp
|
app/models/entry.rb
|
1019
|
class Entry < ActiveRecord::Base
# relationships
belongs_to :category
has_many :taggings
has_many :tags, through: :taggings
accepts_nested_attributes_for :category
#validations
validates :entry, length: { maximum: 255 }
validates :picture_file_name, length: { maximum: 255 }
validates :picture_content_type, length: { maximum: 255 }
# picture manipulation
has_attached_file :picture, :styles => { :small => "150x150>" },
:url => "/assets/products/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/products/:id/:style/:basename.:extension"
validates_attachment_presence :picture
validates_attachment_size :picture, :less_than => 5.megabytes
validates_attachment_content_type :picture, :content_type => ['image/jpeg', 'image/png', 'image/gif']
# tag manipulation
def all_tags=(names)
self.tags = names.split(",").map do |description|
Tag.where(description: description.strip).first_or_create!
end
end
def all_tags
self.tags.map(&:description).join(", ")
end
end
|
gpl-2.0
|
doublesword/commuse
|
Source/W201621/GetProcThreadCpuUsage/CommLog.cpp
|
18946
|
#pragma once
#include "stdafx.h"
#include <Windows.h>
#include <io.h>
#include <stdio.h>
#include "CommLog.h"
#include <tchar.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <io.h>
#include <fstream>
#define MAX_BUFFER 5000
#define INVALID_FILE INVALID_HANDLE_VALUE
#ifdef UNICODE
# define TVSPINRTF vswprintf
#else
# define TVSPINRTF vsprintf
#endif
//-------------------------------------------------------------------------------
// Ä£Äâdebugview
#define USE_DBG_VIEW 0
#if USE_DBG_VIEW==1
//debug view
const static char* StrLog_Mutex = "DBWinMutex";
const static char* StrLog_Buf_Ready = "DBWIN_BUFFER_READY";
const static char* StrLog_Data_Ready = "DBWIN_DATA_READY";
const static char* StrLog_ShareName = "DBWIN_BUFFER";
#else
//custom
const static char* StrLog_Mutex = "CommLogDbgStrMutex";
const static char* StrLog_Buf_Ready = "CommLogDbgStrEvtBufReady";
const static char* StrLog_Data_Ready = "CommLogDbgStrEvtDataReady";
const static char* StrLog_ShareName = "CommLogDbgStrShareName";
#endif
static const int LogMemSize4K = 4096;
struct DBWIN_buffer // 4KB¹²ÏíÄÚ´æ
{
DWORD dwProcessId; // ½ø³Ì ID ÏÔʾÐÅÏ¢µÄÀ´Ô´
char data[LogMemSize4K - sizeof(DWORD)]; // ³ýÈ¥½ø³ÌIDÕ¼ÓõÄËÄ×Ö½ÚÒÔÍâµÄ×Ö½Ú¿Õ¼ä
};
static HANDLE hDbwinMutex = NULL;//»¥³âÁ¿
static HANDLE setup_mutex(void)
{
SID_IDENTIFIER_AUTHORITY SIAWindowsNT = SECURITY_NT_AUTHORITY;
SID_IDENTIFIER_AUTHORITY SIAWorld = SECURITY_WORLD_SID_AUTHORITY;
PSID pSidSYSTEM = 0;
PSID pSidAdmins = 0;
PSID pSidEveryone = 0;
AllocateAndInitializeSid(&SIAWindowsNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSidSYSTEM);
AllocateAndInitializeSid(&SIAWindowsNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&pSidAdmins);
AllocateAndInitializeSid(&SIAWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pSidEveryone);
const DWORD dwACLSize = GetLengthSid(pSidSYSTEM) + GetLengthSid(pSidAdmins) + GetLengthSid(pSidEveryone) + 32;
PACL pACL = (PACL)GlobalAlloc(0, dwACLSize);
InitializeAcl(pACL, dwACLSize, ACL_REVISION);
AddAccessAllowedAce(pACL, ACL_REVISION, SYNCHRONIZE | READ_CONTROL | MUTEX_MODIFY_STATE, pSidEveryone);
AddAccessAllowedAce(pACL, ACL_REVISION, MUTEX_ALL_ACCESS, pSidSYSTEM);
AddAccessAllowedAce(pACL, ACL_REVISION, MUTEX_ALL_ACCESS, pSidAdmins);
SECURITY_DESCRIPTOR sd;
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, TRUE, pACL, FALSE);
SECURITY_ATTRIBUTES sa;
ZeroMemory(&sa, sizeof(sa));
sa.bInheritHandle = FALSE;
sa.nLength = sizeof sa;
sa.lpSecurityDescriptor = &sd;
HANDLE hMutex = CreateMutexA(&sa, FALSE, StrLog_Mutex);
FreeSid(pSidAdmins);
FreeSid(pSidSYSTEM);
FreeSid(pSidEveryone);
GlobalFree(pACL);
return hMutex;
}
// pseudocode for OutputDebugString from KERNEL32.DLL ver 5.0.2195.6794
static void LogString(LPCSTR lpString)
{
DBWIN_buffer* pDBBuffer = 0;
HANDLE hFileMap = 0;
HANDLE hBufferEvent = 0;
HANDLE hDataEvent = 0;
// if we can't make or acquire the mutex, we're done
if (hDbwinMutex == 0)
hDbwinMutex = setup_mutex();
if (hDbwinMutex == 0)
return;
(void)WaitForSingleObject(hDbwinMutex, INFINITE);
// (entire file)
hBufferEvent = OpenEventA(SYNCHRONIZE, FALSE, StrLog_Buf_Ready);
hDataEvent = OpenEventA(EVENT_MODIFY_STATE, FALSE, StrLog_Data_Ready);
const char* p = lpString;
int len = strlen(lpString);
while (len > 0)
{
if (WaitForSingleObject(hBufferEvent, 10 * 1000) != WAIT_OBJECT_0)
{
break; // ERROR: give up
}
hFileMap = OpenFileMappingA(FILE_MAP_WRITE, FALSE, StrLog_ShareName);
pDBBuffer = (DBWIN_buffer*)MapViewOfFile(hFileMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, // file offset high
0, // file offset low
0); // # of bytes to map
if (!pDBBuffer)
{
SetEvent(hDataEvent);
break;
}
// populate the shared memory segment. The string
// is limited to 4k or so.
pDBBuffer->dwProcessId = GetCurrentProcessId();
int n = min(len, sizeof(pDBBuffer->data) - 1);
memcpy(pDBBuffer->data, p, n);
pDBBuffer->data[n] = '\0';
len -= n;
p += n;
SetEvent(hDataEvent);
}
ReleaseMutex(hDbwinMutex);
// cleanup after ourselves
CloseHandle(hBufferEvent);
CloseHandle(hDataEvent);
UnmapViewOfFile(pDBBuffer);
CloseHandle(hFileMap);
}
#if _MSC_VER < 1400
static int _vscwprintf(wchar_t* format,va_list vl){
std::wstring s ;
s.resize(1024,0);
int nRealSize = 0;
while ( (nRealSize=_vsnwprintf(&s[0],s.size(),format,vl) ) >= s.size() )
{
int nGrow = s.size()/2;
if (nGrow <= 0) nGrow = 1;
s.resize(s.size()+nGrow,0);
}
return nRealSize;
}
static int _vscprintf(char* format,va_list vl){
std::string s ;
s.resize(1024,0);
int nRealSize = 0;
while ( (nRealSize=_vsnprintf(&s[0],s.size(),format,vl) ) >= s.size() )
{
int nGrow = s.size()/2;
if (nGrow <= 0) nGrow = 1;
s.resize(s.size()+nGrow,0);
}
return nRealSize;
}
#endif
static wchar_t* MakeVAArgsLogW(wchar_t* format,va_list vl){
const int ntmplen = 100;
wchar_t tem [ntmplen];
wchar_t* pTmpVA = NULL;
SYSTEMTIME st;
GetLocalTime(&st);
_snwprintf(tem,ntmplen,L"[PID:%d,TID:%u] [%02d:%02d:%02d] ",
GetCurrentProcessId(),GetCurrentThreadId(),st.wHour,st.wMinute,st.wSecond);
int nFixedPrefixLen = wcslen(tem);
int nVALen = _vscwprintf(format,vl);
pTmpVA = new wchar_t[nVALen+nFixedPrefixLen+10];
if(pTmpVA){
pTmpVA[nVALen+nFixedPrefixLen] = L'\0';
wcsncpy(pTmpVA,tem,nFixedPrefixLen);
vswprintf(pTmpVA+nFixedPrefixLen,format,vl);
}
return pTmpVA;
}
static char* MakeVAArgsLogA(char* format,va_list vl){
const int ntmplen = 100;
char tem[ntmplen]={0};
char* pTmpVA = NULL;
SYSTEMTIME st;
GetLocalTime(&st);
_snprintf(tem,ntmplen,"[PID:%d,TID:%u] [%02d:%02d:%02d] ",
GetCurrentProcessId(),GetCurrentThreadId(),st.wHour,st.wMinute,st.wSecond);
int nFixedPrefixLen = strlen(tem);
int nVALen = _vscprintf(format,vl);
pTmpVA = new char[nVALen+nFixedPrefixLen+10];
if(pTmpVA){
pTmpVA[nVALen+nFixedPrefixLen] = '\0';
strncpy(pTmpVA,tem,nFixedPrefixLen);
vsprintf(pTmpVA+nFixedPrefixLen,format,vl);
}
return pTmpVA;
}
static void ReleaseVAArgsLog(void* pMakeVAArgsLog){
delete[] pMakeVAArgsLog;
}
static std::string MY_W2A(LPCWSTR szSrc)
{
std::string sOut = "";
LPSTR pszOut = NULL;
if(szSrc==NULL) return sOut;
int sLen = wcslen(szSrc);
if(sLen == 0) return sOut;
int len = ::WideCharToMultiByte(CP_ACP,0,szSrc,sLen,NULL,0,0,0);
pszOut = new char[len+1];
if (pszOut)
{
::WideCharToMultiByte(CP_ACP,0,szSrc,sLen,pszOut,len,0,0);
pszOut[len] = 0;
sOut.assign(pszOut,len) ;
delete[] pszOut;
}
return sOut;
}
//-------------------------------------------------------------------------------
#pragma warning(disable:4996)
namespace COMMUSE
{
HMODULE ThisModule()
{
return NULL;
static HMODULE h = NULL;
if (!h)
{
MEMORY_BASIC_INFORMATION mbi;
::VirtualQuery(ThisModule,&mbi,sizeof(mbi));
h = (HMODULE)mbi.AllocationBase;
}
return h;
}
//-------------------------------------------------------------------------------
ComPrintLog::ComPrintLog()
{
_LogFile = INVALID_FILE;
memset(_szLogFilePath,0,sizeof(_szLogFilePath));
memset(_szAppFileName,0,sizeof(_szAppFileName));
memset(_szLogStateIniPath,0,sizeof(_szLogStateIniPath));
_bLogMem = true;
PrintInit();
}
//-------------------------------------------------------------------------------
ComPrintLog::~ComPrintLog()
{
_LogFile = INVALID_FILE;
memset((void*)_szLogFilePath,0,sizeof(_szLogFilePath));
memset(_szAppFileName,0,sizeof(_szAppFileName));
PrintUnInit();
}
//-------------------------------------------------------------------------------
void ComPrintLog::PrintInit()
{
char* p = _szLogFilePath;
if(GetModuleFileNameA(NULL,_szLogFilePath,MAX_PATH))
{
p += strlen(_szLogFilePath);
while(*p != '\\')
{
p--;
}
memcpy(_szAppFileName , p+1 , strlen(p+1) );//È¡µ½³ÌÐòÃû
strncpy(_szLogStateIniPath,_szLogFilePath,MAX_PATH);
strrchr(_szLogStateIniPath,'\\')[1]=0;
strcat(_szLogStateIniPath,"CommLogOpt.ini");
memcpy(p+1,"Log\\\0",strlen("Log\\\0")+1 );//Ìí¼ÓĿ¼(_szLogFilePath·¾¶)
}
else
{
strcpy(_szLogFilePath,"Log\\");
strcpy(_szAppFileName,"TestLog");
strcpy(_szLogStateIniPath,"CommLogOpt.ini");
}
InitializeCriticalSection(&_cs_log);
InitLogState();
}
//-------------------------------------------------------------------------------
void ComPrintLog::PrintUnInit()
{
EnterCriticalSection(&_cs_log);
if ( _LogFile != INVALID_FILE )
{
CloseHandle( _LogFile );
_LogFile = INVALID_FILE;
}
LeaveCriticalSection(&_cs_log);
DeleteCriticalSection(&_cs_log);
}
void ComPrintLog::SetLogPath(const char* szLogPath)
{
if(szLogPath==NULL) return;
if(strlen(szLogPath)>=MAX_PATH) return;
_szLogFilePath[0] = 0;
if (szLogPath[strlen(szLogPath)-1] != '\\' && szLogPath[strlen(szLogPath)-1] != '/')
{
_snprintf(_szLogStateIniPath,MAX_PATH-1,"%s\\CommLogOpt.ini",szLogPath);
_snprintf(_szLogFilePath,MAX_PATH-1,"%s\\Log\\",szLogPath);
}
else
{
_snprintf(_szLogStateIniPath,MAX_PATH-1,"%sCommLogOpt.ini",szLogPath);
_snprintf(_szLogFilePath,MAX_PATH-1,"%sLog\\",szLogPath);
}
}
void ComPrintLog::EnableShareMemLog( bool b )
{
_bLogMem = b;
}
//-------------------------------------------------------------------------------
void ComPrintLog::InitLogState()
{
_nLogState = GetPrivateProfileIntA("CommLog", "Print", 0, _szLogStateIniPath);
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogEventW(wchar_t* format,...)
{
if (!_bLogMem)
{
InitLogState();
if(_nLogState == 0) return;
}
va_list vl;
va_start(vl,format);
wchar_t *tem = MakeVAArgsLogW(format,vl);
va_end(vl);
if(_nLogState == 1)
{
LogEvenDW(tem);
}
else
{
LogEvenFW(tem);
}
ReleaseVAArgsLog(tem);
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogEventA(char* format,...)
{
if (!_bLogMem)
{
InitLogState();
if(_nLogState == 0) return;
}
va_list vl;
va_start(vl,format);
char *tem = MakeVAArgsLogA(format,vl);
va_end(vl);
if(_nLogState == 1)
{
LogEvenDA(tem);
}
else
{
LogEvenFA(tem);
}
ReleaseVAArgsLog(tem);
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogForce_W(int ty,wchar_t* format,...)
{
va_list vl;
va_start(vl,format);
wchar_t *tem = MakeVAArgsLogW(format,vl);
va_end(vl);
if(ty == 1)
{
LogEvenDW(tem);
}
else if(ty == 2)
{
LogEvenFW(tem);
}
else if(ty == 3)
{
LogEventMW(tem);
}
ReleaseVAArgsLog(tem);
}
void ComPrintLog::LogForceVL_W( int ty,wchar_t* format,va_list vl )
{
wchar_t *tem = MakeVAArgsLogW(format,vl);
if(ty == 1)
{
LogEvenDW(tem);
}
else if(ty == 2)
{
LogEvenFW(tem);
}
else if(ty == 3)
{
LogEventMW(tem);
}
ReleaseVAArgsLog(tem);
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogForce_A(int ty,char* format,...)
{
va_list vl;
va_start(vl,format);
char *tem = MakeVAArgsLogA(format,vl);
va_end(vl);
if(ty == 1)
{
LogEvenDA(tem);
}
else if(ty == 2)
{
LogEvenFA(tem);
}
else if(ty == 3)
{
LogEventMA(tem);
}
ReleaseVAArgsLog(tem);
}
void ComPrintLog::LogForceVL_A( int ty,char* format,va_list vl )
{
char *tem = MakeVAArgsLogA(format,vl);
if(ty == 1)
{
LogEvenDA(tem);
}
else if(ty == 2)
{
LogEvenFA(tem);
}
else if(ty == 3)
{
LogEventMA(tem);
}
ReleaseVAArgsLog(tem);
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogEvenDW (wchar_t* message)
{
if (_bLogMem)
{
LogEventMW(message);
}
else
{
OutputDebugStringW(message);
}
}
void ComPrintLog::LogEvenDA (char* message)
{
if (_bLogMem)
{
LogEventMA(message);
}
else
{
OutputDebugStringA(message);
}
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogEvenFW (wchar_t* message)
{
if (_bLogMem)
{
LogEventMW(message);
return;
}
if (_access(_szLogFilePath,0) == -1)
{
CreateDirectoryA(_szLogFilePath,NULL); //´´½¨LOGÎļþĿ¼
}
char szLogFileName[MAX_PATH];//logÎļþÃû(ÁÙʱÓÃ)
SYSTEMTIME st;
GetLocalTime(&st);
//Éú³ÉÎļþÃû
_snprintf(szLogFileName , MAX_PATH , "%s%s[%d-%d-%d].log",
_szLogFilePath,_szAppFileName,st.wYear , st.wMonth , st.wDay );
//ÅжÏÊDz»ÊÇÐèÒªÖØÐ´´½¨Îļþ
EnterCriticalSection(&_cs_log);
if( -1 == _access(szLogFileName,0) )
{
HANDLE fileOld = _LogFile;
_LogFile = CreateFileA(szLogFileName,GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (fileOld != INVALID_FILE)
{
CloseHandle(fileOld);
}
}
else
{
if (_LogFile == INVALID_FILE)
{
_LogFile = CreateFileA(szLogFileName,GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
}
}
if (_LogFile != INVALID_FILE)//Îļþ¾ä±ú´æÔÚ
{
DWORD dwWritten = 0;
std::string sData = MY_W2A(message);
WriteFile(_LogFile, sData.data(), sData.size(),&dwWritten,NULL);
//FlushFileBuffers(_LogFile);
}
else
{
DWORD err = 0;
err = GetLastError();
}
LeaveCriticalSection(&_cs_log);
}
//-------------------------------------------------------------------------------
void ComPrintLog::LogEvenFA (char* message)
{
if (_bLogMem)
{
LogEventMA(message);
return;
}
if (_access(_szLogFilePath,0) == -1)
{
CreateDirectoryA(_szLogFilePath,NULL); //´´½¨LOGÎļþĿ¼
}
char szLogFileName[MAX_PATH];//logÎļþÃû(ÁÙʱÓÃ)
SYSTEMTIME st;
GetLocalTime(&st);
//Éú³ÉÎļþÃû
_snprintf(szLogFileName , MAX_PATH , "%s%s[%d-%d-%d].log",
_szLogFilePath,_szAppFileName,st.wYear , st.wMonth , st.wDay );
//ÅжÏÊDz»ÊÇÐèÒªÖØÐ´´½¨Îļþ
EnterCriticalSection(&_cs_log);
if( -1 == _access(szLogFileName,0) )
{
HANDLE fileOld = _LogFile;
_LogFile = CreateFileA(szLogFileName,GENERIC_WRITE,FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (fileOld != INVALID_FILE)
{
CloseHandle(fileOld);
}
}
else
{
if (_LogFile == INVALID_FILE)
{
_LogFile = CreateFileA(szLogFileName,GENERIC_WRITE,FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
}
}
if (_LogFile != INVALID_FILE)//Îļþ¾ä±ú´æÔÚ
{
DWORD dwWritten = 0;
WriteFile(_LogFile,message , strlen(message) ,&dwWritten,NULL);
//FlushFileBuffers(_LogFile);
}
else
{
DWORD err = 0;
err = GetLastError();
}
LeaveCriticalSection(&_cs_log);
}
void ComPrintLog::LogEventMW( wchar_t* message )
{
if(!message) return;
const int buflen = LogMemSize4K-sizeof(DWORD);
char szMsg[buflen];
int lmsglen = wcslen( message);
if( lmsglen*sizeof(wchar_t) >= buflen ) lmsglen = buflen/2-1;
*(message+lmsglen) = L'\0';
memset(szMsg,0,sizeof(szMsg));
WideCharToMultiByte(CP_ACP,0,message,lmsglen,szMsg,buflen-1,0,0);
LogEventMA(szMsg);
}
void ComPrintLog::LogEventMA( char* message )
{
if(!message) return;
LogString(message);
}
//-------------------------------------------------------------------------------
//# ifdef UNICODE
// void ComPrintLog::LogEvenE (wchar_t* format,...)
//# else
// void ComPrintLog::LogEvenE (char* format,...)
//# endif
// {
// if(_nLogState == 0) return;
//
// TCHAR tem[1024]={0};
// SYSTEMTIME st;
//
// GetLocalTime(&st);
//# ifdef UNICODE
// USES_CONVERSION;
// swprintf_s(tem,1024,TEXT("[%s][PID:%d] [%04d-%02d-%02d %02d:%02d:%02d] "),
// A2W(_szAppFileName),GetCurrentProcessId(),st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
//# else
// sprintf_s(tem,1024,"[%s][PID:%d] [%04d-%02d-%02d %02d:%02d:%02d] ",
// _szAppFileName,GetCurrentProcessId(),st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
//
//# endif
//
// va_list vl;
// va_start(vl,format);
// TVSPINRTF(&tem[_tcslen(tem)],format,vl);
// va_end(vl);
//
// OutputDebugString(tem);
// }
//-------------------------------------------------------------------------------
} // COMMUSE
#if _MSC_VER < 1400
void LOGF_MA( char* fmt,... )
{
va_list vl;
va_start(vl,fmt);
COMMUSE::ComPrintLog::GetInstance().LogForceVL_A(3,fmt,vl);
va_end(vl);
}
void LOGF_FA( char* fmt,... )
{
va_list vl;
va_start(vl,fmt);
COMMUSE::ComPrintLog::GetInstance().LogForceVL_A(2,fmt,vl);
va_end(vl);
}
void LOGF_VA( char* fmt,... )
{
va_list vl;
va_start(vl,fmt);
COMMUSE::ComPrintLog::GetInstance().LogForceVL_A(1,fmt,vl);
va_end(vl);
}
void LOGF_MW( wchar_t* fmt,... )
{
va_list vl;
va_start(vl,fmt);
COMMUSE::ComPrintLog::GetInstance().LogForceVL_W(3,fmt,vl);
va_end(vl);
}
void LOGF_FW( wchar_t* fmt,... )
{
va_list vl;
va_start(vl,fmt);
COMMUSE::ComPrintLog::GetInstance().LogForceVL_W(2,fmt,vl);
va_end(vl);
}
void LOGF_VW( wchar_t* fmt,... )
{
va_list vl;
va_start(vl,fmt);
COMMUSE::ComPrintLog::GetInstance().LogForceVL_W(1,fmt,vl);
va_end(vl);
}
#endif
|
gpl-2.0
|
piti118/SPR
|
include/StatPatternRecognition/SprVector.hh
|
8633
|
// -*- C++ -*-
// CLASSDOC OFF
// $Id: SprVector.hh,v 1.3 2007-11-07 00:56:14 narsky Exp $
// ---------------------------------------------------------------------------
// CLASSDOC ON
//
// This file is a part of the CLHEP - a Class Library for High Energy Physics.
//
//
// Copyright Cornell University 1993, 1996, All Rights Reserved.
//
// This software written by Nobu Katayama and Mike Smyth, Cornell University.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice and author attribution, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice and author attribution, this list of conditions and the
// following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the name of the University nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// Creation of derivative forms of this software for commercial
// utilization may be subject to restriction; written permission may be
// obtained from Cornell University.
//
// CORNELL MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. By way
// of example, but not limitation, CORNELL MAKES NO REPRESENTATIONS OR
// WARRANTIES OF MERCANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT
// THE USE OF THIS SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS,
// COPYRIGHTS, TRADEMARKS, OR OTHER RIGHTS. Cornell University shall not be
// held liable for any liability with respect to any claim by the user or any
// other party arising from use of the program.
//
// Although Vector and Matrix class are very much related, I like the typing
// information I get by making them different types. It is usually an error
// to use a Matrix where a Vector is expected, except in the case that the
// Matrix is a single column. But this case can be taken care of by using
// constructors as conversions. For this same reason, I don't want to make
// a Vector a derived class of Matrix.
//
#ifndef _SprVector_HH
#define _SprVector_HH
#include "StatPatternRecognition/SprGenMatrix.hh"
class SprMatrix;
class SprSymMatrix;
/**
* @author
* @ingroup matrix
*/
class SprVector : public SprGenMatrix {
public:
inline SprVector();
// Default constructor. Gives vector of length 0.
// Another Vector can be assigned to it.
// Constructor from std::vector
inline SprVector(const std::vector<double>& v);
explicit SprVector(int p);
SprVector(int p, int);
// Constructor. Gives vector of length p.
SprVector(const SprVector &v);
SprVector(const SprMatrix &m);
// Copy constructors.
// Note that there is an assignment operator for v = Hep3Vector.
virtual ~SprVector();
// Destructor.
// get std vector
inline std::vector<double> std() const;
inline const double & operator()(int row) const;
inline double & operator()(int row);
// Read or write a matrix element.
// ** Note that the indexing starts from (1). **
inline const double & operator[](int row) const;
inline double & operator[](int row);
// Read and write an element of a Vector.
// ** Note that the indexing starts from [0]. **
inline virtual const double & operator()(int row, int col) const;
inline virtual double & operator()(int row, int col);
// Read or write a matrix element.
// ** Note that the indexing starts from (1,1). **
// Allows accessing Vector using GenMatrix
SprVector & operator*=(double t);
// Multiply a Vector by a floating number.
SprVector & operator/=(double t);
// Divide a Vector by a floating number.
SprVector & operator+=( const SprMatrix &v2);
SprVector & operator+=( const SprVector &v2);
SprVector & operator-=( const SprMatrix &v2);
SprVector & operator-=( const SprVector &v2);
// Add or subtract a Vector.
SprVector & operator=( const SprVector &m2);
// Assignment operators.
SprVector& operator=(const SprMatrix &);
// assignment operators from other classes.
SprVector operator- () const;
// unary minus, ie. flip the sign of each element.
SprVector apply(double (*f)(double, int)) const;
// Apply a function to all elements.
SprVector sub(int min_row, int max_row) const;
// Returns a sub vector.
SprVector sub(int min_row, int max_row);
// SGI CC bug. I have to have both with/without const. I should not need
// one without const.
void sub(int row, const SprVector &v1);
// Replaces a sub vector of a Vector with v1.
inline double normsq() const;
// Returns norm squared.
inline double norm() const;
// Returns norm.
inline virtual int num_row() const;
// Returns number of rows.
inline virtual int num_col() const;
// Number of columns. Always returns 1. Provided for compatibility with
// GenMatrix.
SprMatrix T() const;
// Returns the transpose of a Vector. Note that the returning type is
// Matrix.
friend inline void swap(SprVector &v1, SprVector &v2);
// Swaps two vectors.
protected:
virtual inline int num_size() const;
private:
virtual void invert(int&);
// produces an error. Demanded by GenMatrix
friend class SprSymMatrix;
friend class SprMatrix;
// friend classes
friend double dot(const SprVector &v1, const SprVector &v2);
// f = v1 * v2;
friend SprVector operator+(const SprVector &v1, const SprVector &v2);
friend SprVector operator-(const SprVector &v1, const SprVector &v2);
friend SprVector operator*(const SprSymMatrix &m1, const SprVector &m2);
friend SprMatrix operator*(const SprVector &m1, const SprMatrix &m2);
friend SprVector operator*(const SprMatrix &m1, const SprVector &m2);
friend SprVector solve(const SprMatrix &a, const SprVector &v);
friend SprSymMatrix vT_times_v(const SprVector &v);
std::vector<double > m;
int nrow;
};
//
// Operations other than member functions
//
std::ostream& operator<<(std::ostream &s, const SprVector &v);
// Write out Matrix, SymMatrix, DiagMatrix and Vector into ostream.
SprVector operator*(const SprMatrix &m1, const SprVector &m2);
SprVector operator*(double t, const SprVector &v1);
SprVector operator*(const SprVector &v1, double t);
// Multiplication operators.
// Note that m *= x is always faster than m = m * x.
SprVector operator/(const SprVector &v1, double t);
// Divide by a real number.
SprVector operator+(const SprMatrix &m1, const SprVector &v2);
SprVector operator+(const SprVector &v1, const SprMatrix &m2);
SprVector operator+(const SprVector &v1, const SprVector &v2);
// Addition operators
SprVector operator-(const SprMatrix &m1, const SprVector &v2);
SprVector operator-(const SprVector &v1, const SprMatrix &m2);
SprVector operator-(const SprVector &v1, const SprVector &v2);
// subtraction operators
SprVector dsum(const SprVector &s1, const SprVector &s2);
// Direct sum of two vectors;
// -*- C++ -*-
// $Id: SprVector.hh,v 1.3 2007-11-07 00:56:14 narsky Exp $
// ---------------------------------------------------------------------------
//
#include <cmath>
#include <cstdlib>
// Swap two vectors without doing a full copy.
inline void swap(SprVector &v1,SprVector &v2) {
SprGenMatrix::swap(v1.m,v2.m);
SprGenMatrix::swap(v1.nrow,v2.nrow);
}
inline SprVector::SprVector()
: m(0), nrow(0)
{}
inline SprVector::SprVector(const std::vector<double>& v)
: m(v), nrow(v.size())
{}
inline double SprVector::normsq() const {return dot((*this),(*this));}
inline double SprVector::norm() const {return sqrt(normsq());}
inline int SprVector::num_row() const {return nrow;}
inline int SprVector::num_size() const {return nrow;}
inline int SprVector::num_col() const { return 1; }
inline std::vector<double> SprVector::std() const { return m; }
inline double & SprVector::operator()(int row)
{
return *(m.begin()+row-1);
}
inline const double & SprVector::operator()(int row) const
{
return *(m.begin()+row-1);
}
inline double & SprVector::operator[](int row)
{
return *(m.begin()+row);
}
inline const double & SprVector::operator[](int row) const
{
return *(m.begin()+row);
}
inline double & SprVector::operator()(int row, int)
{
return *(m.begin()+(row-1));
}
inline const double & SprVector::operator()(int row, int) const
{
return *(m.begin()+(row-1));
}
#endif /*!_Vector_H*/
|
gpl-2.0
|
melko/qtiplot
|
3rdparty/qwtplot3d/src/qwt3d_axis.cpp
|
8159
|
#include "qwt3d_axis.h"
#include "qwt3d_plot.h"
using namespace Qwt3D;
Axis::Axis()
{
init();
};
Axis::~Axis()
{
}
Axis::Axis(Triple beg, Triple end)
{
init();
setPosition(beg,end);
}
void Axis::init()
{
detachAll();
scale_ = qwt3d_ptr<Scale>(new LinearScale);
beg_ = Triple(0.0, 0.0, 0.0);
end_ = beg_;
majorintervals_ = 0;
minorintervals_ = 0;
setMajors(1);
setMinors(1);
setLimits(0,0);
setTicOrientation(0.0, 0.0, 0.0);
setTicLength(0.0, 0.0);
setColor(0.0, 0.0, 0.0);
setLineWidth(1.0);
symtics_ = false;
drawNumbers_ = false;
drawLabel_ = false;
drawTics_ = false;
autoscale_ = true;
markerLabel_.clear();
numberfont_ = QFont("Courier",12);
setLabelFont(QFont("Courier",14));
numbercolor_ = RGBA(0,0,0,0);
setNumberAnchor(Center);
numbergap_ = 0;
labelgap_ = 0;
decorate_ = true;
}
void Axis::setPosition(const Triple& beg, const Triple& end)
{
beg_ = beg;
end_ = end;
}
void Axis::setMajors(int val)
{
if (val == majorintervals_)
return;
majorintervals_ = (val<=0) ? 1 : val; // always >= 1
}
/*!
\see LogScale::setMinors().
*/
void Axis::setMinors(int val)
{
if (val == minorintervals_)
return;
minorintervals_ = (val<=0) ? 1 : val; // always >= 1
}
void Axis::setTicLength(double majorl, double minorl)
{
lmaj_ = majorl;
lmin_ = minorl;
}
void Axis::setTicOrientation(double tx, double ty, double tz)
{
setTicOrientation(Triple(tx,ty,tz));
}
void Axis::setTicOrientation(const Triple& val)
{
orientation_ = val;
orientation_.normalize();
}
/**
\param val thickness for axis base line
\param majfac relative thickness for axis major tics (majfac*val)
\param minfac relative thickness for axis minor tics (minfac*val)
*/
void Axis::setLineWidth(double val, double majfac, double minfac)
{
lineWidth_ = val;
majLineWidth_ = majfac * lineWidth_;
minLineWidth_ = minfac * lineWidth_;
}
void Axis::draw()
{
Drawable::draw();
saveGLState();
// GLStateBewarer sb(GL_LINE_SMOOTH, true);
// glBlendFunc(GL_ONE, GL_ZERO);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4d(color.r,color.g,color.b,color.a);
drawBase();
if ( decorate_ ) {
drawTics();
drawLabel();
}
restoreGLState();
}
/**
Always use AFTER drawNumbers() ! (Needs length of number string)
*/
void Axis::drawLabel()
{
if (!drawLabel_)
return;
label_.setPlot(plot());
double width = 0.0;
for (unsigned i = 0; i != markerLabel_.size(); i++){
double aux = markerLabel_[i].width();
if (aux > width)
width = aux;
}
Triple center = begin() + (end_ - beg_)/2;
Triple ticEnd = ViewPort2World(World2ViewPort(center + ticOrientation() * lmaj_));
double rap = (width + labelgap_ + label_.textHeight())/(World2ViewPort(ticEnd) - World2ViewPort(center)).length();
Triple pos = ViewPort2World(World2ViewPort(center + ticOrientation() * lmaj_*(1 + rap)));
setLabelPosition(pos, Center);
Triple end = World2ViewPort(end_);
Triple beg = World2ViewPort(beg_);
double angle = 360 - fabs(QLineF(beg.x, beg.y, end.x, end.y).angle());
int ax = 0;
Qwt3D::CoordinateSystem *coords = plot()->coordinates();
for (int i = 0; i < (int)coords->axes.size(); i++){
Qwt3D::Axis axis = coords->axes[i];
if (axis.begin() == beg_ && axis.end() == end_){
ax = i;
break;
}
}
if (ax != Qwt3D::Z1 && ax != Qwt3D::Z2 && ax != Qwt3D::Z3 && ax != Qwt3D::Z4){
if (angle > 90 && angle < 180)
angle += 180;
if (angle > 180 && angle < 270)
angle -= 180;
}
label_.draw(angle);
}
void Axis::drawBase()
{
setDeviceLineWidth( lineWidth_ );
glBegin( GL_LINES );
glVertex3d( beg_.x, beg_.y, beg_.z);
glVertex3d( end_.x, end_.y, end_.z);
glEnd();
}
bool Axis::prepTicCalculation(Triple& startpoint)
{
if (isPracticallyZero(start_, stop_))
return false;
autostart_ = start_;
autostop_ = stop_;
if (autoScale()) {
setMajors(scale_->autoscale(autostart_, autostop_, start_, stop_, majors()));
if (isPracticallyZero(autostart_, autostop_))
return false;
}
scale_->setLimits(start_,stop_);
scale_->setMajors(majors());
scale_->setMinors(minors());
scale_->setMajorLimits(autostart_,autostop_);
scale_->calculate();
Triple normal = (end_ - beg_);
//normal.normalize();
//Triple beg = beg_ + ((autostart_ - start_) / (stop_ - start_)) * normal;
//Triple end = end_ - ((stop_ - autostop_) / (stop_ - start_))* normal;
startpoint = end_ - beg_;
majorpos_.clear();
minorpos_.clear();
return true;
}
void Axis::recalculateTics()
{
Triple runningpoint;
if (false==prepTicCalculation(runningpoint))
return;
unsigned int i;
for (i = 0; i != scale_->majors_p.size(); ++i) {
double t = (scale_->majors_p[i] - start_) / (stop_-start_);
majorpos_.push_back(beg_ + t * runningpoint);
}
for (i = 0; i != scale_->minors_p.size(); ++i) {
double t = (scale_->minors_p[i] - start_) / (stop_-start_);
minorpos_.push_back(beg_ + t * runningpoint);
}
}
void Axis::drawTics()
{
Triple runningpoint;
if (!drawTics_ || false==prepTicCalculation(runningpoint))
return;
unsigned int i;
Triple nadir;
markerLabel_.resize(scale_->majors_p.size());
setDeviceLineWidth(majLineWidth_);
for (i = 0; i != scale_->majors_p.size(); ++i) {
double t = (scale_->majors_p[i] - start_) / (stop_-start_);
nadir = beg_ + t * runningpoint;
majorpos_.push_back(drawTic(nadir, lmaj_));
drawTicLabel(nadir + 1.2 * lmaj_ * orientation_, i);
}
setDeviceLineWidth(minLineWidth_);
for (i = 0; i != scale_->minors_p.size(); ++i) {
double t = (scale_->minors_p[i] - start_) / (stop_-start_);
nadir = beg_ + t * runningpoint;
minorpos_.push_back(drawTic(nadir, lmin_));
}
}
void Axis::drawTicLabel(Triple pos, int mtic)
{
if (!drawNumbers_ || (mtic < 0))
return;
markerLabel_[mtic].setFont(numberfont_.family(), numberfont_.pointSize(), numberfont_.weight(), numberfont_.italic());
markerLabel_[mtic].setColor(numbercolor_);
markerLabel_[mtic].setString(scale_->ticLabel(mtic));
markerLabel_[mtic].setPosition(pos, scaleNumberAnchor_);
markerLabel_[mtic].setPlot(plot());
markerLabel_[mtic].adjust(numbergap_);
markerLabel_[mtic].draw();
}
Triple Axis::drawTic(Triple nadir, double length)
{
double ilength = (symtics_) ? -length : 0.0;
glBegin( GL_LINES );
glColor4d(color.r,color.g,color.b,color.a);
glVertex3d( nadir.x + ilength * orientation_.x,
nadir.y + ilength * orientation_.y,
nadir.z + ilength * orientation_.z) ;
glVertex3d( nadir.x + length * orientation_.x,
nadir.y + length * orientation_.y,
nadir.z + length * orientation_.z);
glEnd();
return nadir;
}
void Axis::setNumberFont(QString const& family, int pointSize, int weight, bool italic)
{
numberfont_ = QFont(family, pointSize, weight, italic );
}
void Axis::setNumberFont(QFont const& font)
{
numberfont_ = font;
}
void Axis::setNumberColor(RGBA col)
{
numbercolor_ = col;
}
void Axis::setLabelFont(QString const& family, int pointSize, int weight, bool italic)
{
labelfont_ = QFont(family, pointSize, weight, italic );
label_.setFont(family, pointSize, weight, italic);
}
void Axis::setLabelFont(QFont const& font)
{
setLabelFont(font.family(), font.pointSize(), font.weight(), font.italic());
}
void Axis::setLabelString(QString const& name)
{
label_.setString(name);
}
/*!
Sets label position in conjunction with an anchoring strategy
*/
void Axis::setLabelPosition(const Triple& pos,Qwt3D::ANCHOR an)
{
label_.setPosition(pos, an);
}
//! Sets color for label
void Axis::setLabelColor(RGBA col)
{
label_.setColor(col);
}
/*!
This variant sets a user-defined scale object.
Use with a heap based initialized pointer only.
The axis adopts ownership.
*/
void Axis::setScale(Scale* val)
{
scale_ = qwt3d_ptr<Scale>(val);
}
/*!
Sets one of the predefined scaling types.
\warning Too small intervals in logarithmic scales lead to
empty scales (or perhaps a scale only containing an isolated
major tic). Better switch to linear scales in such cases.
*/
void Axis::setScale(Qwt3D::SCALETYPE val)
{
switch(val) {
case Qwt3D::LINEARSCALE:
setScale(new LinearScale);
break;
case Qwt3D::LOG10SCALE:
setScale(new LogScale);
setMinors(9);
break;
default:
break;
}
}
|
gpl-2.0
|
dennyli/HandySolution
|
Tools/Prism4.1/Prism/Modularity/AssemblyResolver.Desktop.cs
|
5800
|
//===================================================================================
// Microsoft patterns & practices
// Composite Application Guidance for Windows Presentation Foundation and Silverlight
//===================================================================================
// Copyright (c) Microsoft Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===================================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious. No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===================================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.Prism.Properties;
namespace Microsoft.Practices.Prism.Modularity
{
/// <summary>
/// Handles AppDomain's AssemblyResolve event to be able to load assemblies dynamically in
/// the LoadFrom context, but be able to reference the type from assemblies loaded in the Load context.
/// </summary>
public class AssemblyResolver : IAssemblyResolver, IDisposable
{
private readonly List<AssemblyInfo> registeredAssemblies = new List<AssemblyInfo>();
private bool handlesAssemblyResolve;
/// <summary>
/// Registers the specified assembly and resolves the types in it when the AppDomain requests for it.
/// </summary>
/// <param name="assemblyFilePath">The path to the assemly to load in the LoadFrom context.</param>
/// <remarks>This method does not load the assembly immediately, but lazily until someone requests a <see cref="Type"/>
/// declared in the assembly.</remarks>
public void LoadAssemblyFrom(string assemblyFilePath)
{
if (!this.handlesAssemblyResolve)
{
AppDomain.CurrentDomain.AssemblyResolve += this.CurrentDomain_AssemblyResolve;
this.handlesAssemblyResolve = true;
}
Uri assemblyUri = GetFileUri(assemblyFilePath);
if (assemblyUri == null)
{
throw new ArgumentException(Resources.InvalidArgumentAssemblyUri, "assemblyFilePath");
}
if (!File.Exists(assemblyUri.LocalPath))
{
throw new FileNotFoundException();
}
AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyUri.LocalPath);
AssemblyInfo assemblyInfo = this.registeredAssemblies.FirstOrDefault(a => assemblyName == a.AssemblyName);
if (assemblyInfo != null)
{
return;
}
assemblyInfo = new AssemblyInfo() { AssemblyName = assemblyName, AssemblyUri = assemblyUri };
this.registeredAssemblies.Add(assemblyInfo);
}
private static Uri GetFileUri(string filePath)
{
if (String.IsNullOrEmpty(filePath))
{
return null;
}
Uri uri;
if (!Uri.TryCreate(filePath, UriKind.Absolute, out uri))
{
return null;
}
if (!uri.IsFile)
{
return null;
}
return uri;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")]
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AssemblyName assemblyName = new AssemblyName(args.Name);
AssemblyInfo assemblyInfo = this.registeredAssemblies.FirstOrDefault(a => AssemblyName.ReferenceMatchesDefinition(assemblyName, a.AssemblyName));
if (assemblyInfo != null)
{
if (assemblyInfo.Assembly == null)
{
assemblyInfo.Assembly = Assembly.LoadFrom(assemblyInfo.AssemblyUri.LocalPath);
}
return assemblyInfo.Assembly;
}
return null;
}
private class AssemblyInfo
{
public AssemblyName AssemblyName { get; set; }
public Uri AssemblyUri { get; set; }
public Assembly Assembly { get; set; }
}
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <remarks>Calls <see cref="Dispose(bool)"/></remarks>.
/// <filterpriority>2</filterpriority>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the associated <see cref="AssemblyResolver"/>.
/// </summary>
/// <param name="disposing">When <see langword="true"/>, it is being called from the Dispose method.</param>
protected virtual void Dispose(bool disposing)
{
if (this.handlesAssemblyResolve)
{
AppDomain.CurrentDomain.AssemblyResolve -= this.CurrentDomain_AssemblyResolve;
this.handlesAssemblyResolve = false;
}
}
#endregion
}
}
|
gpl-2.0
|
PlanetLotus/Settings-Recall
|
SettingsRecall/RestoreService.cs
|
1155
|
using SettingsRecall.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using BackupDataModel = SettingsRecall.BackupService.BackupDataModel;
namespace SettingsRecall {
public class RestoreService {
/// <summary>
/// Overwrites files, but does not create directories.
/// </summary>
public static void RestoreBackup(IEnumerable<BackupDataModel> selectedPrograms, CopyHandler copyHandler) {
copyHandler.InitRestore(restoreLogFile);
foreach (BackupDataModel program in selectedPrograms) {
// This assumes that no backup paths were deleted. It's completely relying on the JSON data (this is preferred).
foreach (string restoreDest in program.SourceToDestPaths.Keys) {
string backupPathLocation = program.SourceToDestPaths[restoreDest];
copyHandler.Copy(backupPathLocation, restoreDest, OverwriteEnum.Overwrite);
}
}
copyHandler.CloseRestore();
}
private const string restoreLogFile = "restoreLog.txt";
}
}
|
gpl-2.0
|
lujianzhi/photoalbum
|
app/src/main/java/com/lujianzhi/photoalbum/view/photoview/Compat.java
|
511
|
package com.lujianzhi.photoalbum.view.photoview;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.view.View;
public class Compat {
private static final int SIXTY_FPS_INTERVAL = 1000 / 60;
public static void postOnAnimation(View view, Runnable runnable) {
if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
SDK16.postOnAnimation(view, runnable);
} else {
view.postDelayed(runnable, SIXTY_FPS_INTERVAL);
}
}
}
|
gpl-2.0
|
sirfreedom/ChessNet
|
frmPickupColor.cs
|
7400
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SrcChess {
/// <summary>Pickup the colors use to draw the chess control</summary>
public partial class frmPickupColor : Form {
private ChessControl m_chessCtl;
private ChessControl.ChessControlColorInfo m_colorInfo;
//*********************************************************
//
/// <summary>
/// Class constructor
/// </summary>
//
//*********************************************************
public frmPickupColor() {
InitializeComponent();
m_chessCtl = new ChessControl();
m_chessCtl.Location = new Point(0, 0);
m_chessCtl.Size = panel1.Size;
panel1.Controls.Add(m_chessCtl);
}
//*********************************************************
//
/// <summary>
/// Class constructor
/// </summary>
/// <param name="colorInfo"> Color info</param>
//
//*********************************************************
public frmPickupColor(ChessControl.ChessControlColorInfo colorInfo) {
InitializeComponent();
m_chessCtl = new ChessControl();
m_chessCtl.Location = new Point(0, 0);
m_chessCtl.Size = panel1.Size;
m_chessCtl.ColorInfo = colorInfo;
m_colorInfo = colorInfo;
panel1.Controls.Add(m_chessCtl);
}
//*********************************************************
//
/// <summary>
/// Chess control color information
/// </summary>
//
//*********************************************************
public ChessControl.ChessControlColorInfo ColorInfo {
get {
return(m_colorInfo);
}
set {
m_colorInfo = value;
}
}
//*********************************************************
//
/// <summary>
/// Called when form is loaded
/// </summary>
/// <param name="sender"> Sender object</param>
/// <param name="e"> Event handler</param>
//
//*********************************************************
private void frmPickupColor_Load(object sender, EventArgs e) {
butWhitePieceColor.BackColor = m_colorInfo.m_colWhitePiece;
butBlackPieceColor.BackColor = m_colorInfo.m_colBlackPiece;
butLiteSquareColor.BackColor = m_colorInfo.m_colLiteCase;
butDarkSquareColor.BackColor = m_colorInfo.m_colDarkCase;
}
//*********************************************************
//
/// <summary>
/// Called when the white piece color button is pressed.
/// </summary>
/// <param name="sender"> Sender object</param>
/// <param name="e"> Event handler</param>
//
//*********************************************************
private void butWhitePieceColor_Click(object sender, EventArgs e) {
colorDialog1.Color = m_colorInfo.m_colWhitePiece;
if (colorDialog1.ShowDialog(this) == DialogResult.OK) {
m_colorInfo.m_colWhitePiece = colorDialog1.Color;
butWhitePieceColor.BackColor = colorDialog1.Color;
m_chessCtl.ColorInfo = m_colorInfo;
}
}
//*********************************************************
//
/// <summary>
/// Called when the black piece color button is pressed.
/// </summary>
/// <param name="sender"> Sender object</param>
/// <param name="e"> Event handler</param>
//
//*********************************************************
private void butBlackPieceColor_Click(object sender, EventArgs e) {
colorDialog1.Color = m_colorInfo.m_colBlackPiece;
if (colorDialog1.ShowDialog(this) == DialogResult.OK) {
m_colorInfo.m_colBlackPiece = colorDialog1.Color;
butBlackPieceColor.BackColor = colorDialog1.Color;
m_chessCtl.ColorInfo = m_colorInfo;
}
}
//*********************************************************
//
/// <summary>
/// Called when the lite square color button is pressed.
/// </summary>
/// <param name="sender"> Sender object</param>
/// <param name="e"> Event handler</param>
//
//*********************************************************
private void butLiteSquareColor_Click(object sender, EventArgs e) {
colorDialog1.Color = m_colorInfo.m_colLiteCase;
if (colorDialog1.ShowDialog(this) == DialogResult.OK) {
m_colorInfo.m_colLiteCase = colorDialog1.Color;
butLiteSquareColor.BackColor = colorDialog1.Color;
m_chessCtl.ColorInfo = m_colorInfo;
}
}
//*********************************************************
//
/// <summary>
/// Called when the dark square color button is pressed.
/// </summary>
/// <param name="sender"> Sender object</param>
/// <param name="e"> Event handler</param>
//
//*********************************************************
private void butDarkSquareColor_Click(object sender, EventArgs e) {
colorDialog1.Color = m_colorInfo.m_colDarkCase;
if (colorDialog1.ShowDialog(this) == DialogResult.OK) {
m_colorInfo.m_colDarkCase = colorDialog1.Color;
butDarkSquareColor.BackColor = colorDialog1.Color;
m_chessCtl.ColorInfo = m_colorInfo;
}
}
//*********************************************************
//
/// <summary>
/// Called when the reset to default button is pressed
/// </summary>
/// <param name="sender"> Sender object</param>
/// <param name="e"> Event handler</param>
//
//*********************************************************
private void butResetToDefault_Click(object sender, EventArgs e) {
m_colorInfo.m_colLiteCase = Color.DarkGray;
butLiteSquareColor.BackColor = Color.DarkGray;
m_colorInfo.m_colDarkCase = Color.DarkRed;
butDarkSquareColor.BackColor = Color.DarkRed;
m_colorInfo.m_colBlackPiece = Color.Black;
butBlackPieceColor.BackColor = Color.Black;
m_colorInfo.m_colWhitePiece = Color.FromArgb(235, 235, 235);
butWhitePieceColor.BackColor = Color.FromArgb(235, 235, 235);
m_chessCtl.ColorInfo = m_colorInfo;
}
}
}
|
gpl-2.0
|
fvcproductions/CS-HU
|
CSC-152/Inheritance/Lesson I/Faculty.java
|
1312
|
/***************************************************
fvcproductions
july 2012
Faculty class extended from Person class
****************************************************/
public class Faculty extends Person {
//define attributes that are protected
//aka additional attributes
protected String department;
protected String position;
//1st constructor
public Faculty(String aFirstName, String aLastName, int aAge, double aMoney) {
super(aFirstName, aLastName, aAge, aMoney);
position = "unknown";
department = "unknown";
}
//2nd constructor
public Faculty (String aFirstName, String aLastName, int aAge, double aMoney, String pos, String dept) {
super(aFirstName, aLastName, aAge, aMoney); // call constructor of parent
position = pos; // local instance
department = dept; // local instance
}
//methods - accessor and mutator
public String getDepartment() {
return department;
}
public String getPosition() {
return position;
}
public void setDepartment(String aDept) {
department = aDept;
}
public void setPosition(String aPos) {
position = aPos;
}
//specific toString method for Faculty class
public String toString() {
String str = super.toString() + " \t" + position + " \t" + department;
return str;
}
}
|
gpl-2.0
|
freemed/freemed
|
ui/dojo/htdocs/dojo/src/collections/Set.js
|
3101
|
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.collections.Set");
dojo.require("dojo.collections.Collections");
dojo.require("dojo.collections.ArrayList");
dojo.collections.Set = new function () {
this.union = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var result = new dojo.collections.ArrayList(setA.toArray());
var e = setB.getIterator();
while (!e.atEnd()) {
var item = e.get();
if (!result.contains(item)) {
result.add(item);
}
}
return result;
};
this.intersection = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var result = new dojo.collections.ArrayList();
var e = setB.getIterator();
while (!e.atEnd()) {
var item = e.get();
if (setA.contains(item)) {
result.add(item);
}
}
return result;
};
this.difference = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var result = new dojo.collections.ArrayList();
var e = setA.getIterator();
while (!e.atEnd()) {
var item = e.get();
if (!setB.contains(item)) {
result.add(item);
}
}
return result;
};
this.isSubSet = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var e = setA.getIterator();
while (!e.atEnd()) {
if (!setB.contains(e.get())) {
return false;
}
}
return true;
};
this.isSuperSet = function (setA, setB) {
if (setA.constructor == Array) {
var setA = new dojo.collections.ArrayList(setA);
}
if (setB.constructor == Array) {
var setB = new dojo.collections.ArrayList(setB);
}
if (!setA.toArray || !setB.toArray) {
dojo.raise("Set operations can only be performed on array-based collections.");
}
var e = setB.getIterator();
while (!e.atEnd()) {
if (!setA.contains(e.get())) {
return false;
}
}
return true;
};
}();
|
gpl-2.0
|
anomen-s/programming-challenges
|
mff.cuni.cz/SWI080/jms/src/ExampleProducer.java
|
1648
|
import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
public class ExampleProducer {
public static void main(String[] args) {
Connection connection = null;
try {
// Create connection to the broker.
// Note that the factory is usually obtained from JNDI, this method is ActiveMQ-specific
// used here for simplicity
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
connection = connectionFactory.createConnection();
connection.start();
// Create a non-transacted, auto-acknowledged session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create a queue, name must match the queue created by consumer
// Note that this is also provider-specific and should be obtained from JNDI
Queue queue1 = session.createQueue("ExampleQueue1");
// Create a producer for the queue
MessageProducer producer1 = session.createProducer(queue1);
// Create a message
Message message1 = session.createTextMessage("ping");
// Send the message
producer1.send(message1);
// Repeat all this with another queue
Queue queue2 = session.createQueue("ExampleQueue2");
MessageProducer producer2 = session.createProducer(queue2);
Message message2 = session.createTextMessage("ping");
producer2.send(message2);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (Throwable ignore) {
}
}
}
}
|
gpl-2.0
|
laurenpenn/Website
|
content/plugins/addthis/js/options-page.32.js
|
12637
|
jQuery(document).ready(function($) {
$( "#config-error" ).hide();
$( "#share-error" ).hide();
$( "#tabs" ).tabs();
var thickDims, tbWidth, tbHeight;
thickDims = function() {
var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h;
w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90;
h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60;
if ( tbWindow.size() ) {
tbWindow.width(w).height(h);
$('#TB_iframeContent').width(w).height(h - 27);
tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top':'30px','margin-top':'0'});
}
};
$('a.thickbox-preview').click( function() {
var previewLink = this;
var $inputs = $('#addthis_settings :input');
var values = {};
$.each($('#addthis_settings').serializeArray(), function(i, field) {
var thisName = field.name
if (thisName.indexOf("addthis_settings[") != -1 )
{
thisName = thisName.replace("addthis_settings[", '');
thisName = thisName.replace("]", '');
}
values[thisName] = field.value;
});
var stuff = $.param(values, true);
var data = {
action: 'at_save_transient',
value : stuff
};
jQuery.post(ajaxurl, data, function(response) {
// Fix for WP 2.9's version of lightbox
if ( typeof tb_click != 'undefined' && $.isFunction(tb_click.call))
{
tb_click.call(previewLink);
}
var href = $(previewLink).attr('href');
var link = '';
if ( tbWidth = href.match(/&tbWidth=[0-9]+/) )
tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10);
else
tbWidth = $(window).width() - 90;
if ( tbHeight = href.match(/&tbHeight=[0-9]+/) )
tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10);
else
tbHeight = $(window).height() - 60;
$('#TB_title').css({'background-color':'#222','color':'#dfdfdf'});
$('#TB_closeAjaxWindow').css({'float':'left'});
$('#TB_ajaxWindowTitle').css({'float':'right'}).html(link);
$('#TB_iframeContent').width('100%');
thickDims();
});
return false;
});
/**
* Handle enable disable top and bottom share buttons
*/
$("#enable_above, #enable_below").click(enableShareIconsClickHandler);
function enableShareIconsClickHandler(){
toggleShareIconsContainer($(this));
}
function toggleShareIconsContainer(element){
var animationContainer = element.closest("td").find(".select_row");
if (!element.attr("checked")) {
animationContainer.css("opacity", 0.4);
animationContainer.find("input").attr("disabled", true);
} else {
animationContainer.css("opacity", 1);
animationContainer.find("input").attr("disabled", false);
}
}
toggleShareIconsContainer($("#enable_above"));
toggleShareIconsContainer($("#enable_below"));
var show_above = $('input[name="addthis_settings[show_above]"]');
var show_below = $('input[name="addthis_settings[show_below]"]');
if ( show_above.prop('checked') != "undefined" && show_above.prop('checked') == true)
{
$('.above_option').toggleClass('hide');
}
if ( show_below.prop('checked') != "undefined" && show_below.prop('checked') == true)
{
$('.below_option').toggleClass('hide');
}
$('input[name="addthis_settings[show_above]"]').change( function() {
$('.above_option').toggleClass('hide');
});
$('input[name="addthis_settings[show_below]"]').change( function() {
$('.below_option').toggleClass('hide');
});
var aboveCustom = $('#above_custom_button');
var aboveCustomShow = function(){
if ( aboveCustom.prop('checked') != 'undefined' && aboveCustom.prop('checked') == true)
{
$('.above_option_custom').removeClass('hidden');
}
else
{
$('.above_option_custom').addClass('hidden');
}
};
var belowCustom = $('#below_custom_button');
var belowCustomShow = function(){
if ( belowCustom.prop('checked') != 'undefined' && belowCustom.prop('checked') == true)
{
$('.below_option_custom').removeClass('hidden');
}
else
{
$('.below_option_custom').addClass('hidden');
}
};
var aboveCustomString = $('#above_custom_string');
var aboveCustomStringShow = function(){
if ( aboveCustomString.prop('checked') != 'undefined' && aboveCustomString.prop('checked') == true)
{
$('.above_custom_string_input').removeClass('hidden');
}
else
{
$('.above_custom_string_input').addClass('hidden');
}
};
var belowCustomString = $('#below_custom_string');
var belowCustomStringShow = function(){
if ( belowCustomString.prop('checked') != 'undefined' && belowCustomString.prop('checked') == true)
{
$('.below_custom_string_input').removeClass('hidden');
}
else
{
$('.below_custom_string_input').addClass('hidden');
}
};
aboveCustomShow();
belowCustomShow();
aboveCustomStringShow();
belowCustomStringShow();
$('input[name="addthis_settings[above]"]').change( function(){aboveCustomShow(); aboveCustomStringShow();} );
$('input[name="addthis_settings[below]"]').change( function(){belowCustomShow(); belowCustomStringShow();} );
/**
* Hide Theming and branding options when user selects version 3.0 or above
*/
var ATVERSION_250 = 250;
var AT_VERSION_300 = 300;
var MANUAL_UPDATE = -1;
var AUTO_UPDATE = 0;
var REVERTED = 1;
var atVersionUpdateStatus = $("#addthis_atversion_update_status").val();
if (atVersionUpdateStatus == REVERTED) {
$(".classicFeature").show();
} else {
$(".classicFeature").hide();
}
/**
* Revert to older version after the user upgrades
*/
$(".addthis-revert-atversion").click(function(){
$("#addthis_atversion_update_status").val(REVERTED);
$("#addthis_atversion_hidden").val(ATVERSION_250);
$(this).closest("form").submit();
return false;
});
/**
* Update to a newer version
*/
$(".addthis-update-atversion").click(function(){
$("#addthis_atversion_update_status").val(MANUAL_UPDATE);
$("#addthis_atversion_hidden").val(AT_VERSION_300);
$(this).closest("form").submit();
return false;
});
var addthis_credential_validation_status = $("#addthis_credential_validation_status");
var addthis_validation_message = $("#addthis-credential-validation-message");
var addthis_profile_validation_message = $("#addthis-profile-validation-message");
//Validate the Addthis credentials
window.skipValidationInternalError = false;
function validate_addthis_credentials() {
$.ajax(
{"url" : addthis_option_params.wp_ajax_url,
"type" : "post",
"data" : {"action" : addthis_option_params.addthis_validate_action,
"addthis_profile" : $("#addthis_profile").val(),
"addthis_username" : $("#addthis_username").val(),
"addthis_password" : $("#addthis_password").val()
},
"dataType" : "json",
"beforeSend" : function() {
$(".addthis-admin-loader").show();
addthis_validation_message.html("").next().hide();
addthis_profile_validation_message.html("").next().hide();
},
"success": function(data) {
addthis_validation_message.show();
addthis_profile_validation_message.show();
if (data.credentialmessage == "error" || (data.profileerror == "false" && data.credentialerror == "false")) {
if (data.credentialmessage != "error") {
addthis_credential_validation_status.val(1);
} else {
window.skipValidationInternalError = true;
}
$("#addthis_settings").submit();
} else {
addthis_validation_message.html(data.credentialmessage);
addthis_profile_validation_message.html(data.profilemessage);
if (data.profilemessage != "") {
$('html, body').animate({"scrollTop":0}, 'slow');
}
}
},
"complete" :function(data) {
$(".addthis-admin-loader").hide();
},
"error" : function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
//Prevent default form submission
$("#addthis_settings").submit(function(){
if(window.skipValidationInternalError) {
return true;
}
var isProfileEmpty = $.trim($("#addthis_profile").val()) == "";
var isUsernameEmpty = $.trim($("#addthis_username").val()) == "";
var isPasswordEmpty = $.trim($("#addthis_password").val()) == "";
var isAnyFieldEmpty = isProfileEmpty || isUsernameEmpty || isPasswordEmpty;
var validationRequired = addthis_credential_validation_status.val() == 0;
if(isUsernameEmpty != isPasswordEmpty) {
var emptyLabel = isUsernameEmpty ? "username" : "password";
addthis_validation_message.html("✖ AddThis " + emptyLabel + " is required to view analytics").next().hide();
return false;
} else if (isProfileEmpty && !isUsernameEmpty && !isPasswordEmpty) {
addthis_profile_validation_message.html("✖ AddThis profile ID is required to view analytics").next().hide();
$('html, body').animate({"scrollTop":0}, 'slow');
return false;
} else if (!validationRequired || isAnyFieldEmpty) {
return true;
} else if(!isAnyFieldEmpty && validationRequired) {
validate_addthis_credentials();
return false;
}
});
$("#addthis_username, #addthis_password, #addthis_profile").change(function(){
addthis_credential_validation_status.val(0);
if($.trim($("#addthis_profile").val()) == "") {
addthis_profile_validation_message.next().hide();
}
if(($.trim($("#addthis_username").val()) == "") || ($.trim($("#addthis_password").val()) == "")) {
addthis_validation_message.next().hide();
}
});
$('#addthis-config-json').focusout(function() {
var error = 0;
if ($('#addthis-config-json').val() != " ") {
try {
var addthis_config_json = jQuery.parseJSON($('#addthis-config-json').val());
}
catch (e) {
error = 1;
}
}
if (error == 0) {
$('#config-error').hide();
return true;
}
else {
$('#config-error').show();
return false;
}
});
$('#addthis-share-json').focusout(function() {
var error = 0;
if ($('#addthis-share-json').val() != " ") {
try {
var addthis_share_json = jQuery.parseJSON($('#addthis-share-json').val());
}
catch (e) {
error = 1;
}
}
if (error == 0) {
$('#share-error').hide();
return true;
}
else {
$('#share-error').show();
return false;
}
});
$('#submit-button').click(function() {
$('#config-error').hide();
$('#share-error').hide();
var error = 0;
if ($('#addthis-config-json').val() != " ") {
try {
var addthis_config_json = jQuery.parseJSON($('#addthis-config-json').val());
}
catch (e) {
$('#config-error').show();
error = 1;
}
}
if ($('#addthis-share-json').val() != " ") {
try {
var addthis_share_json = jQuery.parseJSON($('#addthis-share-json').val());
}
catch (e) {
$('#share-error').show();
error = 1;
}
}
if (error == 0) {
return true;
}
else {
return false;
}
});
});
|
gpl-2.0
|
eba2s/blog
|
static/admin/js/admin/RelatedObjectLookups.js
|
4465
|
// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.
function html_unescape(text) {
// Unescape a string that was escaped using django.utils.html.escape.
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/"/g, '"');
text = text.replace(/'/g, "'");
text = text.replace(/&/g, '&');
return text;
}
// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct
// element when the popup window is dismissed.
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAdminPopup(triggeringLink, name_regexp) {
var name = triggeringLink.id.replace(name_regexp, '');
name = id_to_windowname(name);
var href = triggeringLink.href;
if (href.indexOf('?') == -1) {
href += '?_popup=1';
} else {
href += '&_popup=1';
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function showRelatedObjectLookupPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^lookup_/);
}
function dismissRelatedLookupPopup(win, chosenId) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + chosenId;
} else {
document.getElementById(name).value = chosenId;
}
win.close();
}
function showRelatedObjectPopup(triggeringLink) {
var name = triggeringLink.id.replace(/^(change|add|delete)_/, '');
name = id_to_windowname(name);
var href = triggeringLink.href;
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function dismissAddRelatedObjectPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
// django.utils.html.escape.
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
var o;
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName == 'SELECT') {
o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
} else if (elemName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
// Trigger a change event to update related links if required.
django.jQuery(elem).trigger('change');
} else {
var toId = name + "_to";
o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) {
objId = html_unescape(objId);
newRepr = html_unescape(newRepr);
var id = windowname_to_id(win.name).replace(/^edit_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = django.jQuery(selectsSelector);
selects.find('option').each(function () {
if (this.value == objId) {
this.innerHTML = newRepr;
this.value = newId;
}
});
win.close();
};
function dismissDeleteRelatedObjectPopup(win, objId) {
objId = html_unescape(objId);
var id = windowname_to_id(win.name).replace(/^delete_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = django.jQuery(selectsSelector);
selects.find('option').each(function () {
if (this.value == objId) {
django.jQuery(this).remove();
}
}).trigger('change');
win.close();
};
// Kept for backward compatibility
showAddAnotherPopup = showRelatedObjectPopup;
dismissAddAnotherPopup = dismissAddRelatedObjectPopup;
|
gpl-2.0
|
TI-ECS/battleship
|
src/networkentity.cpp
|
4025
|
/*
Copyright (c) 2007 Paolo Capriotti <p.capriotti@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
#include "networkentity.h"
#include "battlefield.h"
#include "sea.h"
#include "shot.h"
#include "protocol.h"
#include <QIcon>
NetworkEntity::NetworkEntity(Sea::Player player, Sea* sea, Protocol* protocol, bool client)
: Entity(player)
, m_sea(sea)
, m_client(client)
{
m_protocol = protocol;
}
NetworkEntity::~NetworkEntity()
{
}
void NetworkEntity::start(bool ask)
{
connect(m_protocol, SIGNAL(received(MessagePtr)), this, SLOT(received(MessagePtr)));
connect(m_protocol, SIGNAL(disconnected()), this, SIGNAL(abortGame()));
if (ask)
m_protocol->send(MessagePtr(new RestartMessage()));
else
m_protocol->send(MessagePtr(new HeaderMessage()));
}
void NetworkEntity::notifyReady(Sea::Player player)
{
if (player != m_player) {
m_protocol->send(MessagePtr(new BeginMessage()));
}
}
void NetworkEntity::notifyGameOver(Sea::Player)
{
m_protocol->send(MessagePtr(new GameOverMessage));
}
void NetworkEntity::startPlaying()
{
}
void NetworkEntity::notify(Sea::Player player, const Coord& c, const HitInfo& info)
{
if (info.type == HitInfo::INVALID) {
return;
}
if (player == m_player) {
bool hit = info.type == HitInfo::HIT;
bool death = info.shipDestroyed != 0;
Coord begin = Coord::invalid();
Coord end = Coord::invalid();
if (death) {
begin = info.shipPos;
end = begin + info.shipDestroyed->increment() * (info.shipDestroyed->size() - 1);
}
m_protocol->send(MessagePtr(new NotificationMessage(c, hit, death, begin, end)));
}
else {
// the remote player already knows about the hit
// no need to notify it
}
}
void NetworkEntity::hit(Shot* shot)
{
if (shot->player() != m_player
&& m_sea->turn() == shot->player()
&& m_sea->valid(m_player, shot->pos())) {
m_pending_shot = shot;
m_protocol->send(MessagePtr(new MoveMessage(shot->pos())));
}
else {
shot->execute(HitInfo::INVALID);
}
}
void NetworkEntity::received(MessagePtr msg)
{
msg->accept(*this);
}
void NetworkEntity::visit(const HeaderMessage& msg)
{
if (msg.clientName() == "KBattleship" && msg.clientVersion().toFloat() >= 4.0) {
// m_level = COMPAT_KBS4;
}
}
void NetworkEntity::visit(const RejectMessage&)
{
}
void NetworkEntity::visit(const BeginMessage&)
{
m_sea->add(m_player, 4);
emit ready(m_player);
}
void NetworkEntity::visit(const MoveMessage& msg)
{
emit shoot(m_player, msg.move());
}
void NetworkEntity::visit(const NotificationMessage& msg)
{
if (m_pending_shot) {
if (m_pending_shot->pos() != msg.move()) {
m_pending_shot->execute(HitInfo::INVALID);
}
else {
HitInfo info = msg.hit() ? HitInfo::HIT : HitInfo::MISS;
if (msg.death()) {
// gather ship data
Coord delta = msg.stop() - msg.start();
int size = abs(delta.x) + abs(delta.y) + 1;
Ship::Direction direction = delta.x == 0 ? Ship::TOP_DOWN : Ship::LEFT_TO_RIGHT;
Coord shipPos = (delta.x < 0 || delta.y < 0) ? msg.stop() : msg.start();
Ship* ship = new Ship(size, direction);
info.shipDestroyed = ship;
info.shipPos = shipPos;
}
m_sea->forceHit(msg.move(), info);
m_pending_shot->execute(info);
}
m_pending_shot = 0;
}
}
void NetworkEntity::visit(const GameOverMessage&)
{
}
void NetworkEntity::visit(const RestartMessage&)
{
emit restartRequested();
}
QIcon NetworkEntity::icon() const
{
return QIcon("network-workgroup");
}
|
gpl-2.0
|
RyeBread90/ryesnewsite
|
wp-content/themes/ryes_new_site/inc/customizer.php
|
984
|
<?php
/**
* ryes_new_site Theme Customizer
*
* @package ryes_new_site
*/
/**
* Add postMessage support for site title and description for the Theme Customizer.
*
* @param WP_Customize_Manager $wp_customize Theme Customizer object.
*/
function ryes_new_site_customize_register( $wp_customize ) {
$wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
$wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
$wp_customize->get_setting( 'header_textcolor' )->transport = 'postMessage';
}
add_action( 'customize_register', 'ryes_new_site_customize_register' );
/**
* Binds JS handlers to make Theme Customizer preview reload changes asynchronously.
*/
function ryes_new_site_customize_preview_js() {
wp_enqueue_script( 'ryes_new_site_customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '20130508', true );
}
add_action( 'customize_preview_init', 'ryes_new_site_customize_preview_js' );
|
gpl-2.0
|
Muyadong/C-
|
第7章节 数组与集合/7.7.2数组参数的使用/7.7.2数组参数的使用/Program.cs
|
2455
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _7._7._2数组参数的使用
{
class Program
{
static void Main(string[] args)
{
int[] NewChangeArray = new int[5] { 1, 2, 3, 4, 5 };
NewChange(NewChangeArray);//调用重新创建数组并修改值得方法
Console.WriteLine("调用NewChange方法后的数组:"+ShowArray(NewChangeArray));
int[] OnlyChangeArray = new int[5] {1,2,3,4,5};
OnlyChange(OnlyChangeArray);//调用直接修改数组值得的方法
Console.WriteLine("调用OnlyChangeArray方法后的数组:"+ShowArray(OnlyChangeArray));
//ref关键字生命的数组参数必须在方法外部明确赋值
int[] RefArray = new int[] {6,7,8,9,10 };
MethodWithRefArrayParam(ref RefArray);//使用ref关键字声明数组参数
Console.WriteLine("调用MethodWithRefArrayParam方法后的数组:"+ShowArray(RefArray));
int[] OutArray = new int[] {20,21,22};
MethodWithOutArrayParam(out OutArray);//使用out关键字声明数组参数
Console.WriteLine("调用MethodWithOutArrayParam方法后的数组:"+ShowArray(OutArray));
Console.ReadLine();
}
static void NewChange(int[] arrayparam)
{
//在方法中使用new关键字重新创建数组
arrayparam = new int[] {1,2,3,4,5 };
arrayparam[2] = 6;
}
static void OnlyChange(int[] arrayparam)
{
arrayparam[2] = 6;
}
static void MethodWithRefArrayParam(ref int[] arrayparam)
{
//即使在方法中使用new关键字重新创建数组,数组仍然指向原先的内存空间
arrayparam = new int[] {32,33,34 };
arrayparam.SetValue(11,2);
}
static void MethodWithOutArrayParam(out int[] arrayparam)
{
//out关键字声明的数组参数必须在方法内部明确赋值
arrayparam = new int[] {11,12,13,14,15};
}
static string ShowArray(int[] ArrayWillShow)
{
string list = "";
foreach (int ivalue in ArrayWillShow)
{
list = list + ivalue.ToString() +",";
}
list = list.Remove(list.Length-1);
return list;
}
}
}
|
gpl-2.0
|
Droces/casabio
|
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Matroska/SignedElement.php
|
751
|
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Matroska;
use PHPExiftool\Driver\AbstractTag;
class SignedElement extends AbstractTag
{
protected $Id = 9522;
protected $Name = 'SignedElement';
protected $FullName = 'Matroska::Main';
protected $GroupName = 'Matroska';
protected $g0 = 'Matroska';
protected $g1 = 'Matroska';
protected $g2 = 'Video';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Signed Element';
protected $flag_Binary = true;
}
|
gpl-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.