code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
../../../../../../share/pyshared/ubuntu-sso-client/ubuntu_sso/xdg_base_directory/windows.py
|
Alberto-Beralix/Beralix
|
i386-squashfs-root/usr/lib/python2.7/dist-packages/ubuntu-sso-client/ubuntu_sso/xdg_base_directory/windows.py
|
Python
|
gpl-3.0
| 91
|
from __future__ import absolute_import
import requests
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.simplejson import dumps, loads
from common.models import Singleton
from lock_manager import Lock, LockError
from .literals import FORM_SUBMIT_URL, FORM_KEY, FORM_RECEIVER_FIELD, TIMEOUT
from .exceptions import AlreadyRegistered
class RegistrationSingleton(Singleton):
_cached_name = None
_registered = None
registered = models.BooleanField(default=False, verbose_name=_('registered'))
registration_data = models.TextField(verbose_name=_(u'registration data'), blank=True)
@classmethod
def registration_state(cls):
if cls._registered:
return cls._registered
else:
instance = cls.objects.get()
if instance.is_registered:
cls._registered = instance.is_registered
return instance.is_registered
@classmethod
def registered_name(cls):
if cls._cached_name:
return cls._cached_name
else:
instance = cls.objects.get()
try:
dictionary = loads(instance.registration_data)
except ValueError:
dictionary = {}
name_value = dictionary.get('company') or dictionary.get('name')
if name_value:
cls._cached_name = name_value
return name_value or _(u'No name')
@property
def is_registered(self):
return self.registered
def register(self, form):
from installation.models import Installation
if self.is_registered:
raise AlreadyRegistered
installation = Installation.objects.get()
dictionary = {}
dictionary.update(form.cleaned_data)
dictionary.update({
'uuid': installation.uuid
})
self.registration_data = dumps(dictionary)
self.save()
self.submit()
def submit(self):
try:
lock = Lock.acquire_lock('upload_registration')
except LockError:
pass
else:
try:
requests.post(FORM_SUBMIT_URL, data={'formkey': FORM_KEY, FORM_RECEIVER_FIELD: self.registration_data}, timeout=TIMEOUT)
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
pass
else:
self.registered = True
self.save()
finally:
lock.release()
class Meta:
verbose_name = verbose_name_plural = _(u'registration properties')
|
appsembler/mayan_appsembler
|
apps/registration/models.py
|
Python
|
gpl-3.0
| 2,647
|
/*
* This file is part of mod-host.
*
* mod-host 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.
*
* mod-host 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 mod-host. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
************************************************************************************************************************
*
************************************************************************************************************************
*/
#ifndef MONITOR_CLIENT_H
#define MONITOR_CLIENT_H
/*
************************************************************************************************************************
* INCLUDE FILES
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* DO NOT CHANGE THESE DEFINES
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* CONFIGURATION DEFINES
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* DATA TYPES
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* GLOBAL VARIABLES
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* MACRO'S
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* FUNCTION PROTOTYPES
************************************************************************************************************************
*/
bool monitor_client_init(void);
void monitor_client_stop(void);
bool monitor_client_setup_compressor(int mode, float release);
bool monitor_client_setup_volume(float volume);
/*
************************************************************************************************************************
* CONFIGURATION ERRORS
************************************************************************************************************************
*/
/*
************************************************************************************************************************
* END HEADER
************************************************************************************************************************
*/
#endif
|
moddevices/mod-host
|
src/monitor/monitor-client.h
|
C
|
gpl-3.0
| 3,678
|
from six import BytesIO
from pathod.language import actions, parse_pathoc, parse_pathod, serve
def parse_request(s):
return next(parse_pathoc(s))
def test_unique_name():
assert not actions.PauseAt(0, "f").unique_name
assert actions.DisconnectAt(0).unique_name
class TestDisconnects:
def test_parse_pathod(self):
a = next(parse_pathod("400:d0")).actions[0]
assert a.spec() == "d0"
a = next(parse_pathod("400:dr")).actions[0]
assert a.spec() == "dr"
def test_at(self):
e = actions.DisconnectAt.expr()
v = e.parseString("d0")[0]
assert isinstance(v, actions.DisconnectAt)
assert v.offset == 0
v = e.parseString("d100")[0]
assert v.offset == 100
e = actions.DisconnectAt.expr()
v = e.parseString("dr")[0]
assert v.offset == "r"
def test_spec(self):
assert actions.DisconnectAt("r").spec() == "dr"
assert actions.DisconnectAt(10).spec() == "d10"
class TestInject:
def test_parse_pathod(self):
a = next(parse_pathod("400:ir,@100")).actions[0]
assert a.offset == "r"
assert a.value.datatype == "bytes"
assert a.value.usize == 100
a = next(parse_pathod("400:ia,@100")).actions[0]
assert a.offset == "a"
def test_at(self):
e = actions.InjectAt.expr()
v = e.parseString("i0,'foo'")[0]
assert v.value.val == b"foo"
assert v.offset == 0
assert isinstance(v, actions.InjectAt)
v = e.parseString("ir,'foo'")[0]
assert v.offset == "r"
def test_serve(self):
s = BytesIO()
r = next(parse_pathod("400:i0,'foo'"))
assert serve(r, s, {})
def test_spec(self):
e = actions.InjectAt.expr()
v = e.parseString("i0,'foo'")[0]
assert v.spec() == "i0,'foo'"
def test_spec2(self):
e = actions.InjectAt.expr()
v = e.parseString("i0,@100")[0]
v2 = v.freeze({})
v3 = v2.freeze({})
assert v2.value.val == v3.value.val
class TestPauses:
def test_parse_pathod(self):
e = actions.PauseAt.expr()
v = e.parseString("p10,10")[0]
assert v.seconds == 10
assert v.offset == 10
v = e.parseString("p10,f")[0]
assert v.seconds == "f"
v = e.parseString("pr,f")[0]
assert v.offset == "r"
v = e.parseString("pa,f")[0]
assert v.offset == "a"
def test_request(self):
r = next(parse_pathod('400:p10,10'))
assert r.actions[0].spec() == "p10,10"
def test_spec(self):
assert actions.PauseAt("r", 5).spec() == "pr,5"
assert actions.PauseAt(0, 5).spec() == "p0,5"
assert actions.PauseAt(0, "f").spec() == "p0,f"
def test_freeze(self):
l = actions.PauseAt("r", 5)
assert l.freeze({}).spec() == l.spec()
class Test_Action:
def test_cmp(self):
a = actions.DisconnectAt(0)
b = actions.DisconnectAt(1)
c = actions.DisconnectAt(0)
assert a < b
assert a == c
l = sorted([b, a])
assert l[0].offset == 0
def test_resolve(self):
r = parse_request('GET:"/foo"')
e = actions.DisconnectAt("r")
ret = e.resolve({}, r)
assert isinstance(ret.offset, int)
def test_repr(self):
e = actions.DisconnectAt("r")
assert repr(e)
def test_freeze(self):
l = actions.DisconnectAt(5)
assert l.freeze({}).spec() == l.spec()
|
x2Ident/x2Ident_test
|
mitmproxy/test/pathod/test_language_actions.py
|
Python
|
gpl-3.0
| 3,653
|
Joruri GW
==========
Japan Originated Ruby-based RESTful and Integrated GW
GNU GENERAL PUBLIC LICENSE Version 3
Copyright (C) Tokushima Prefectural Government, IDS Inc.
|
ryoon/jorurigw
|
README.md
|
Markdown
|
gpl-3.0
| 180
|
/**
*
*/
package com.longevitysoft.android.rgbledsliders;
import at.abraxas.amarino.service.AmarinoService;
/**
* @author fbeachler
*
*/
public class BTService extends AmarinoService {
public static final String TAG = "BTService";
/*
* (non-Javadoc)
*
* @see at.abraxas.amarino.service.AmarinoService#onCreate()
*/
@Override
public void onCreate() {
super.setIntentConfig(new ServiceIntentConfig());
super.setNotifLaunchIntentClass(Main.class);
super.onCreate();
}
}
|
uestczhuyan/amarino-embed
|
amarino-examples/RGBLEDPickers/src/com/longevitysoft/android/rgbledsliders/BTService.java
|
Java
|
gpl-3.0
| 499
|
package info.hearthsim.brazier.abilities;
import info.hearthsim.brazier.game.Silencable;
import info.hearthsim.brazier.util.UndoAction;
/**
* Aura-aware int property, implemented by using an underlying {@link AuraAwarePropertyBase}.
* Fields {@code baseValue} and {@code minValue} are also included in this class, where {@code baseValue}
* will be used to computed the buffed value of this property and {@code minValue} designates the minimum
* of buffed value.
*/
public final class AuraAwareIntProperty implements Silencable {
private final int baseValue;
private final int minValue;
private final AuraAwarePropertyBase<IntPropertyBuff> impl;
/**
* Creates a {@code AuraAwareIntProperty} with the given {@code baseValue} and setting {@code minValue}
* to {@link Integer#MIN_VALUE}.
*/
public AuraAwareIntProperty(int baseValue) {
this(baseValue, Integer.MIN_VALUE);
}
/**
* Creates a {@code AuraAwareIntProperty} with the given {@code baseValue} and {@code minValue}.
*/
public AuraAwareIntProperty(int baseValue, int minValue) {
this.baseValue = baseValue;
this.minValue = minValue;
this.impl = new AuraAwarePropertyBase<>((buffs) -> {
return (prev) -> {
int result = prev;
for (AuraAwarePropertyBase.BuffRef<IntPropertyBuff> buffRef: buffs) {
result = buffRef.getBuff().buffProperty(result);
}
return result;
};
});
}
private AuraAwareIntProperty(AuraAwareIntProperty other) {
this.baseValue = other.baseValue;
this.minValue = other.minValue;
this.impl = other.impl.copy(false);
}
/**
* Returns a new copy of this {@code AuraAwareIntProperty}.
*/
public AuraAwareIntProperty copy() {
return new AuraAwareIntProperty(this);
}
/**
* Adds a new removable buff to this {@code AuraAwareIntProperty} which sets its buffed value to the
* given value.
*/
public UndoAction<AuraAwareIntProperty> setValueTo(int newValue) {
return addBuff((prev) -> newValue);
}
/**
* Adds a new removable buff to this {@code AuraAwareIntProperty} which adds the property with the given value.
*/
public UndoAction<AuraAwareIntProperty> addBuff(int toAdd) {
return addBuff((prev) -> prev + toAdd);
}
/**
* Adds a new removable buff to this {@code AuraAwareIntProperty} which adds the property with the given value.
*/
public UndoAction<AuraAwareIntProperty> addBuff(IntPropertyBuff toAdd) {
return addBuff(BuffArg.NORMAL_BUFF, toAdd);
}
/**
* Adds a new removable external buff to this {@code AuraAwareIntProperty} which adds the property
* with the given value.
*/
public UndoAction<AuraAwareIntProperty> addExternalBuff(int toAdd) {
return addExternalBuff((prev) -> prev + toAdd);
}
/**
* Adds a new removable external buff to this {@code AuraAwareIntProperty} which adds the property
* with the given value.
*/
public UndoAction<AuraAwareIntProperty> addExternalBuff(IntPropertyBuff toAdd) {
return addBuff(BuffArg.NORMAL_AURA_BUFF, toAdd);
}
/**
* Adds a new removable external buff to this {@code AuraAwareIntProperty} which adds the property
* with the given value.
*/
public UndoAction<AuraAwareIntProperty> setValueTo(BuffArg arg, int newValue) {
return addBuff(arg, (prev) -> newValue);
}
/**
* Adds a new removable buff to this {@code AuraAwareIntProperty} with the given {@code priority},
* {@code external} (contained in a {@code BuffArg}) and value to add.
*/
public UndoAction<AuraAwareIntProperty> addBuff(BuffArg arg, int toAdd) {
return addBuff(arg, (prev) -> prev + toAdd);
}
/**
* Adds a new removable buff to this {@code AuraAwareIntProperty} with the given {@code priority},
* {@code external} (contained in a {@code BuffArg}) and value to add.
*/
public UndoAction<AuraAwareIntProperty> addBuff(BuffArg arg, IntPropertyBuff toAdd) {
UndoAction<AuraAwarePropertyBase> undoRef = impl.addRemovableBuff(arg, toAdd);
return (aaip) -> undoRef.undo(aaip.impl);
}
/**
* Silences the property by removing all added buffs.
*/
@Override
public void silence() {
impl.silence();
}
/**
* Returns the buffed value of this property.
*/
public int getValue() {
int result = impl.getCombinedView().buffProperty(baseValue);
return result >= minValue ? result : minValue;
}
}
|
AlphaHearth/AlphaHearth
|
Brazier/src/main/java/info/hearthsim/brazier/abilities/AuraAwareIntProperty.java
|
Java
|
gpl-3.0
| 4,699
|
// This file is part of Hangfire.
// Copyright © 2013-2014 Sergey Odinokov.
//
// Hangfire is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3
// of the License, or any later version.
//
// Hangfire is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with Hangfire. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Messaging;
using System.Transactions;
namespace Hangfire.SqlServer.Msmq
{
internal class MsmqDtcTransaction : IMsmqTransaction
{
private readonly TransactionScope _scope;
private TransactionScope _suppressedScope;
public MsmqDtcTransaction()
{
_scope = new TransactionScope();
}
public void Dispose()
{
if (_suppressedScope != null)
{
_suppressedScope.Complete();
_suppressedScope.Dispose();
}
_scope.Dispose();
}
public Message Receive(MessageQueue queue, TimeSpan timeout)
{
var message = queue.Receive(timeout, MessageQueueTransactionType.Automatic);
_suppressedScope = new TransactionScope(TransactionScopeOption.Suppress);
return message;
}
public void Commit()
{
_scope.Complete();
}
public void Abort()
{
}
}
}
|
Excommunicated/Hangfire
|
src/Hangfire.SqlServer.Msmq/MsmqDtcTransaction.cs
|
C#
|
gpl-3.0
| 1,763
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Other changes to extensions</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="migration56.openssl.html">OpenSSL changes in PHP 5.6.x</a></div>
<div class="next" style="text-align: right; float: right;"><a href="migration56.constants.html">New global constants</a></div>
<div class="up"><a href="migration56.html">Migrating from PHP 5.5.x to PHP 5.6.x</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="migration56.extensions" class="sect1">
<h2 class="title">Other changes to extensions</h2>
<div class="sect2" id="migration56.extensions.oci8">
<h3 class="title"><a href="book.oci8.html" class="link">OCI8</a></h3>
<ul class="itemizedlist">
<li class="listitem">
<span class="simpara">
Support for implicit result sets for Oracle Database 12c has been added
via the new <span class="function"><a href="function.oci-get-implicit-resultset.html" class="function">oci_get_implicit_resultset()</a></span> function.
</span>
</li>
<li class="listitem">
<span class="simpara">
Using <em>oci_execute($s, OCI_NO_AUTO_COMMIT)</em> for a
SELECT no longer unnecessarily initiates an internal ROLLBACK during
connection close.
</span>
</li>
<li class="listitem">
<span class="simpara">
Added DTrace probes controlled by the <em>--enable-dtrace</em>
configure option.
</span>
</li>
<li class="listitem">
<span class="simpara">
<span class="function"><a href="function.oci-internal-debug.html" class="function">oci_internal_debug()</a></span> is now a no-op.
</span>
</li>
<li class="listitem">
<span class="simpara">
The <span class="function"><a href="function.phpinfo.html" class="function">phpinfo()</a></span> output format for OCI8 has changed.
</span>
</li>
</ul>
</div>
<div class="sect2" id="migration56.extensions.zip">
<h3 class="title"><a href="book.zip.html" class="link">Zip</a></h3>
<p class="para">
A <em>--with-libzip</em> configure option has been added to use
a system libzip installation. libzip version 0.11 is required, with 0.11.2
or later recommended.
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="migration56.openssl.html">OpenSSL changes in PHP 5.6.x</a></div>
<div class="next" style="text-align: right; float: right;"><a href="migration56.constants.html">New global constants</a></div>
<div class="up"><a href="migration56.html">Migrating from PHP 5.5.x to PHP 5.6.x</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
|
rafaelgou/the-phpjs-local-docs-collection
|
php/5.5/migration56.extensions.html
|
HTML
|
gpl-3.0
| 2,959
|
package org.usfirst.frc.team6162.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team6162.robot.commands.ExampleCommand;
import org.usfirst.frc.team6162.robot.subsystems.ExampleSubsystem;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
public static OI oi;
Command autonomousCommand;
SendableChooser<Command> chooser = new SendableChooser<>();
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
@Override
public void robotInit() {
oi = new OI();
chooser.addDefault("Default Auto", new ExampleCommand());
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
@Override
public void disabledInit() {
}
@Override
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable
* chooser code works with the Java SmartDashboard. If you prefer the
* LabVIEW Dashboard, remove all of the chooser code and uncomment the
* getString code to get the auto name from the text box below the Gyro
*
* You can add additional auto modes by adding additional commands to the
* chooser code above (like the commented example) or additional comparisons
* to the switch structure below with additional strings & commands.
*/
@Override
public void autonomousInit() {
autonomousCommand = chooser.getSelected();
/*
* String autoSelected = SmartDashboard.getString("Auto Selector",
* "Default"); switch(autoSelected) { case "My Auto": autonomousCommand
* = new MyAutoCommand(); break; case "Default Auto": default:
* autonomousCommand = new ExampleCommand(); break; }
*/
// schedule the autonomous command (example)
if (autonomousCommand != null)
autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
@Override
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
@Override
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null)
autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
@Override
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
@Override
public void testPeriodic() {
LiveWindow.run();
}
}
|
wjaneal/liastem
|
SampleMultiFunction/src/org/usfirst/frc/team6162/robot/Robot.java
|
Java
|
gpl-3.0
| 3,556
|
/*
* CMC Browser for Android
*
* Copyright (C) 2010 - 2011 J. Devauchelle and contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 3 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.cmc.providers;
import org.cmc.providers.WeaveColumns;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class WeaveContentProvider extends ContentProvider {
public static final String AUTHORITY = "org.cmc.providers.weavecontentprovider";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "weave.db";
public static final String WEAVE_BOOKMARKS_TABLE = "WEAVE_BOOKMARKS";
private static final String WEAVE_BOOKMARKS_TABLE_CREATE = "CREATE TABLE " + WEAVE_BOOKMARKS_TABLE + " (" +
WeaveColumns.WEAVE_BOOKMARKS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID + " TEXT, " +
WeaveColumns.WEAVE_BOOKMARKS_WEAVE_PARENT_ID + " TEXT, " +
WeaveColumns.WEAVE_BOOKMARKS_TITLE + " TEXT, " +
WeaveColumns.WEAVE_BOOKMARKS_URL + " TEXT, " +
WeaveColumns.WEAVE_BOOKMARKS_FOLDER + " BOOLEAN);";
private static final int WEAVE_BOOKMARKS = 1;
private static final int WEAVE_BOOKMARKS_BY_ID = 2;
private static final UriMatcher sUriMatcher;
private SQLiteDatabase mDb;
private DatabaseHelper mDbHelper;
private Context mContext;
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(AUTHORITY, WEAVE_BOOKMARKS_TABLE, WEAVE_BOOKMARKS);
sUriMatcher.addURI(AUTHORITY, WEAVE_BOOKMARKS_TABLE + "/#", WEAVE_BOOKMARKS_BY_ID);
}
@Override
public boolean onCreate() {
mContext = getContext();
mDbHelper = new DatabaseHelper(mContext);
mDb = mDbHelper.getWritableDatabase();
return true;
}
@Override
public int delete(Uri uri, String whereClause, String[] whereArgs) {
int count = 0;
switch (sUriMatcher.match(uri)) {
case WEAVE_BOOKMARKS:
count = mDb.delete(WEAVE_BOOKMARKS_TABLE, whereClause, whereArgs);
break;
default: throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
mContext.getContentResolver().notifyChange(uri, null);
}
return count;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case WEAVE_BOOKMARKS:
return WeaveColumns.CONTENT_TYPE;
case WEAVE_BOOKMARKS_BY_ID:
return WeaveColumns.CONTENT_ITEM_TYPE;
default: throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
switch (sUriMatcher.match(uri)) {
case WEAVE_BOOKMARKS:
long rowId = mDb.insert(WEAVE_BOOKMARKS_TABLE, null, values);
if (rowId > 0) {
Uri rowUri = ContentUris.withAppendedId(WeaveColumns.CONTENT_URI, rowId);
mContext.getContentResolver().notifyChange(rowUri, null);
return rowUri;
}
throw new SQLException("Failed to insert row into " + uri);
default: throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (sUriMatcher.match(uri)) {
case WEAVE_BOOKMARKS:
qb.setTables(WEAVE_BOOKMARKS_TABLE);
break;
case WEAVE_BOOKMARKS_BY_ID:
qb.setTables(WEAVE_BOOKMARKS_TABLE);
qb.appendWhere(WeaveColumns.WEAVE_BOOKMARKS_ID + " = " + uri.getPathSegments().get(1));
break;
default: throw new IllegalArgumentException("Unknown URI " + uri);
}
Cursor c = qb.query(mDb, projection, selection, selectionArgs, null, null, sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
switch (sUriMatcher.match(uri)) {
case WEAVE_BOOKMARKS:
count = mDb.update(WEAVE_BOOKMARKS_TABLE, values, selection, selectionArgs);
break;
default: throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
mContext.getContentResolver().notifyChange(uri, null);
}
return count;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(WEAVE_BOOKMARKS_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}
}
|
vanan08/android-browser-cmcsoft
|
src/org/cmc/providers/WeaveContentProvider.java
|
Java
|
gpl-3.0
| 5,258
|
/*
* Copyright 2014-2018 Friedemann Zenke
*
* This file is part of Auryn, a simulation package for plastic
* spiking neural networks.
*
* Auryn 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.
*
* Auryn 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 Auryn. If not, see <http://www.gnu.org/licenses/>.
*
* If you are using Auryn or parts of it for your work please cite:
* Zenke, F. and Gerstner, W., 2014. Limits to high-speed simulations
* of spiking neural networks using general-purpose computers.
* Front Neuroinform 8, 76. doi: 10.3389/fninf.2014.00076
*/
#include "PoissonStimulator.h"
using namespace auryn;
boost::mt19937 PoissonStimulator::gen = boost::mt19937();
PoissonStimulator::PoissonStimulator(NeuronGroup * target, AurynFloat rate, AurynWeight w ) : Device( )
{
init(target,rate,w);
}
void PoissonStimulator::init( NeuronGroup * target, AurynFloat rate, AurynWeight w )
{
auryn::sys->register_device(this);
dst = target;
set_target_state();
poisson_weight = w;
poisson_rate = rate;
std::stringstream oss;
oss << std::scientific << "PoissonStimulator:: initializing with mean " << get_lambda();
auryn::logger->msg(oss.str(),NOTIFICATION);
seed(61093*sys->mpi_rank());
dist = new boost::poisson_distribution<int> (get_lambda());
die = new boost::variate_generator<boost::mt19937&, boost::poisson_distribution<int> > ( gen, *dist );
}
void PoissonStimulator::free( )
{
delete dist;
delete die;
}
PoissonStimulator::~PoissonStimulator()
{
free();
}
void PoissonStimulator::execute()
{
if ( dst->evolve_locally() ) {
for ( NeuronID i = 0 ; i < dst->get_post_size() ; ++i ) {
int draw = (*die)();
target_vector->data[i] += draw*poisson_weight;
}
}
}
void PoissonStimulator::set_rate(AurynFloat rate) {
delete dist;
poisson_rate = rate;
dist = new boost::poisson_distribution<int> (get_lambda());
}
AurynFloat PoissonStimulator::get_rate() {
return poisson_rate;
}
AurynFloat PoissonStimulator::get_lambda() {
return get_rate()*auryn_timestep;
}
void PoissonStimulator::set_target_state(std::string state_name) {
target_vector = dst->get_state_vector(state_name);
}
void PoissonStimulator::seed(int s)
{
gen.seed(s);
}
|
sanjayankur31/auryn
|
src/auryn/PoissonStimulator.cpp
|
C++
|
gpl-3.0
| 2,643
|
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShopBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
/**
* Security Compiler pass: removed app{env}{..}.xml files from cache.
*/
class RemoveXmlCompiledContainerPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if ($container->getParameter('kernel.debug')) {
$filename = $container->getParameter('debug.container.dump');
$filesystem = new Filesystem();
try {
$filesystem->remove($filename);
} catch (IOException $e) {
// discard chmod failure (some filesystem may not support it)
}
}
}
}
|
boudel/pje
|
src/PrestaShopBundle/DependencyInjection/Compiler/RemoveXmlCompiledContainerPass.php
|
PHP
|
gpl-3.0
| 1,929
|
-----------------------------------
-- mob : Fomor Black mage
-- zone : Sacrarium
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
local kills = killer:getVar("FOMOR_HATE");
if (kills < 60) then
killer:setVar("FOMOR_HATE",kills + 2);
end
end;
|
hooksta4/darkstar
|
scripts/zones/zones/Sacrarium/mobs/Fomor_Black_Mage.lua
|
Lua
|
gpl-3.0
| 485
|
-----------------------------------
-- Area:
-- NPC: Viscount_Morax
-----------------------------------
-----------------------------------
require("scripts/globals/titles");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
killer:addTitle(HELLSBANE);
-- Set Viscount_Morax's Window Open Time
wait = math.random((3600),(28800));
SetServerVariable("[POP]Viscount_Morax", os.time(t) + wait); -- 1-8 hours
DeterMob(mob:getID(), true);
-- Set PH back to normal, then set to respawn spawn
PH = GetServerVariable("[PH]Viscount_Morax");
SetServerVariable("[PH]Viscount_Morax", 0);
DeterMob(PH, false);
GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH));
end;
|
Gwynthell/FFDB
|
scripts/zones/Castle_Zvahl_Keep/mobs/Viscount_Morax.lua
|
Lua
|
gpl-3.0
| 908
|
#include <stdlib.h>
#include <string.h>
struct ofasm_param
{
long long length;
long long elemCnt;
char *addr;
char *elemListAddr;
};
extern void OFASM_VM_ENTRY(const char *progName, ofasm_param param[], int paramCnt);
int ALY01(char* p_0, char* p_1, char* p_2)
{
int paramCnt;
ofasm_param param[4];
ofasm_param param1[1];
/* param[0] */
param[0].length = 6;
param[0].addr = p_0;
param[0].elemListAddr = NULL;
param[0].elemCnt = 0;
/* param[1] */
param[1].length = sizeof(int);
param[1].addr = p_1;
param[1].elemListAddr = (char*)¶m1;
param[1].elemCnt = 1;
/* param[1][0] */
param1[0].length = 6;
param1[0].addr = *(char**)p_1;
param1[0].elemListAddr = NULL;
param1[0].elemCnt = 0;
/* param[2] */
param[2].length = 2;
param[2].addr = p_2;
param[2].elemListAddr = NULL;
param[2].elemCnt = 0;
/* set param count */
paramCnt = 3;
/* call program */
OFASM_VM_ENTRY("ALY01", param, paramCnt);
return 1;
}
|
Tmaxsoft-Compiler/OFASM-test
|
Mtest/UNKNOWN/ALY01/ALY01_interface.cpp
|
C++
|
gpl-3.0
| 1,045
|
/*
* vector.c - This file contains all of the vector arithmetic functions.
*
* $Id: vector.c,v 1.8 2012/10/17 04:25:57 johns Exp $
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define TACHYON_INTERNAL 1
#include "tachyon.h"
#include "macros.h"
flt VDot(const vector *a, const vector *b) {
return (a->x*b->x + a->y*b->y + a->z*b->z);
}
void VCross(const vector * a, const vector * b, vector * c) {
c->x = (a->y * b->z) - (a->z * b->y);
c->y = (a->z * b->x) - (a->x * b->z);
c->z = (a->x * b->y) - (a->y * b->x);
}
flt VLength(const vector * a) {
return (flt) SQRT((a->x * a->x) + (a->y * a->y) + (a->z * a->z));
}
void VNorm(vector * a) {
flt len;
len=SQRT((a->x * a->x) + (a->y * a->y) + (a->z * a->z));
if (len != 0.0) {
a->x /= len;
a->y /= len;
a->z /= len;
}
}
void VAdd(const vector * a, const vector * b, vector * c) {
c->x = (a->x + b->x);
c->y = (a->y + b->y);
c->z = (a->z + b->z);
}
void VSub(const vector * a, const vector * b, vector * c) {
c->x = (a->x - b->x);
c->y = (a->y - b->y);
c->z = (a->z - b->z);
}
void VAddS(flt a, const vector * A, const vector * B, vector * C) {
C->x = (a * A->x) + B->x;
C->y = (a * A->y) + B->y;
C->z = (a * A->z) + B->z;
}
vector Raypnt(const ray * a, flt t) {
vector temp;
temp.x=a->o.x + (a->d.x * t);
temp.y=a->o.y + (a->d.y * t);
temp.z=a->o.z + (a->d.z * t);
return temp;
}
void VScale(vector * a, flt s) {
a->x *= s;
a->y *= s;
a->z *= s;
}
void ColorAddS(color * a, const color * b, flt s) {
a->r += b->r * s;
a->g += b->g * s;
a->b += b->b * s;
}
void ColorAccum(color * a, const color * b) {
a->r += b->r;
a->g += b->g;
a->b += b->b;
}
void ColorScale(color * a, flt s) {
a->r *= s;
a->g *= s;
a->b *= s;
}
|
bitzhuwei/OVITO_sureface
|
src/3rdparty/tachyon/tachyon/vector.c
|
C
|
gpl-3.0
| 1,807
|
/*
org.manalith.ircbot.plugin.calc/CalcRunner.java
ManalithBot - An open source IRC bot based on the PircBot Framework.
Copyright (C) 2011 Seong-ho, Cho <darkcircle.0426@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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.manalith.ircbot.plugin.calc;
import org.manalith.ircbot.plugin.calc.exceptions.EmptyTokenStreamException;
import org.manalith.ircbot.plugin.calc.exceptions.TokenAnalysisException;
public class CalcRunner {
public static String run(String expr) {
String result = "";
// Token analysis phase
TokenArray tArray = new TokenArray();
CalcTokenAnalyzer cta = new CalcTokenAnalyzer(expr);
try {
tArray = cta.getTokenArray();
} catch (EmptyTokenStreamException ets) {
return "입력 문자열이 비어있습니다.";
} catch (TokenAnalysisException e) {
result = " === 해석 오류! === " + e.getMessage();
return result;
}
ParseTreeUnit ptu = null;
try {
// Parse tree generation phase
ptu = CalcParseTreeGenerator.generateParseTree(tArray);
// Computation phase
if (ptu.getResultType().equals("Integer"))
result = " => " + ptu.getIntFpResult();
else
result = " => " + ptu.getFpResult();
} catch (Exception e) {
result = "Computation Error! : " + e.getMessage();
return result;
}
return result;
}
}
|
darkcircle/ManalithBot
|
ManalithBot/src/main/java/org/manalith/ircbot/plugin/calc/CalcRunner.java
|
Java
|
gpl-3.0
| 1,927
|
package kg.ash.javavi.readers;
import com.github.javaparser.Position;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.PackageDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import kg.ash.javavi.apache.logging.log4j.LogManager;
import kg.ash.javavi.apache.logging.log4j.Logger;
import kg.ash.javavi.cache.Cache;
import kg.ash.javavi.clazz.ClassConstructor;
import kg.ash.javavi.clazz.ClassField;
import kg.ash.javavi.clazz.ClassImport;
import kg.ash.javavi.clazz.ClassMethod;
import kg.ash.javavi.clazz.ClassTypeParameter;
import kg.ash.javavi.clazz.SourceClass;
import kg.ash.javavi.readers.source.ClassNamesFetcher;
import kg.ash.javavi.readers.source.CompilationUnitCreator;
import kg.ash.javavi.searchers.ClassSearcher;
import kg.ash.javavi.searchers.FqnSearcher;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Optional;
public class Parser implements ClassReader {
public static final Logger logger = LogManager.getLogger();
private String sources;
private String sourceFile = null;
private String sourceContent = null;
private ClassOrInterfaceDeclaration parentClass = null;
public Parser(String sources) {
this.sources = sources.replace('\\', '/');
}
public Parser(String sources, String sourceFile) {
this.sources = sources.replace('\\', '/');
this.sourceFile = sourceFile.replace('\\', '/');
}
public void setSourceContent(String sourceContent) {
this.sourceContent = sourceContent;
}
@Override
public ClassReader setTypeArguments(List<String> typeArguments) {
// Not supported yet.
return this;
}
@Override
public SourceClass read(String targetClass) {
if ((sourceFile == null || sourceFile.isEmpty()) && (sourceContent == null
|| sourceContent.isEmpty())) {
return null;
}
logger.debug("read class from sources: {}", targetClass);
if (targetClass.contains("$")) {
targetClass = targetClass.split("\\$")[0];
}
if (Cache.getInstance().getClasses().containsKey(targetClass)) {
return Cache.getInstance().getClasses().get(targetClass);
}
CompilationUnit cu = sourceFile != null
? CompilationUnitCreator.createFromFile(sourceFile)
: CompilationUnitCreator.createFromContent(sourceContent);
if (cu == null) {
return null;
}
SourceClass clazz = new SourceClass();
Cache.getInstance().getClasses().put(targetClass, clazz);
Optional<PackageDeclaration> packageDeclaration = cu.getPackageDeclaration();
if (packageDeclaration.isPresent()) {
clazz.setPackage(packageDeclaration.get().getNameAsString());
}
Optional<Position> beginning = cu.getBegin();
Optional<Position> ending = cu.getEnd();
if (beginning.isPresent() && ending.isPresent()) {
clazz.setRegion(beginning.get().line, beginning.get().column, ending.get().line,
ending.get().column);
}
if (cu.getImports() != null) {
for (ImportDeclaration id : cu.getImports()) {
clazz.addImport(
new ClassImport(id.getName().toString(), id.isStatic(), id.isAsterisk()));
}
}
ClassOrInterfaceVisitor coiVisitor = new ClassOrInterfaceVisitor(clazz);
coiVisitor.visit(cu, null);
clazz = coiVisitor.getClazz();
ClassVisitor visitor = new ClassVisitor(clazz);
visitChildren(parentClass.getChildNodes(), visitor);
clazz = visitor.getClazz();
List<String> impls = new ArrayList<>();
if (clazz.getSuperclass() != null) {
impls.add(clazz.getSuperclass());
}
impls.addAll(clazz.getInterfaces());
for (String impl : impls) {
ClassSearcher seacher = new ClassSearcher();
if (seacher.find(impl, sources)) {
SourceClass implClass = seacher.getReader().read(impl);
if (implClass != null) {
clazz.addLinkedClass(implClass);
for (ClassConstructor c : implClass.getConstructors()) {
if (implClass.getName().equals("java.lang.Object")) {
continue;
}
c.setDeclaration(
c.getDeclaration().replace(implClass.getName(), clazz.getName()));
c.setDeclaration(c.getDeclaration()
.replace(implClass.getSimpleName(), clazz.getSimpleName()));
clazz.addConstructor(c);
}
for (ClassMethod method : implClass.getMethods()) {
clazz.addMethod(method);
}
for (ClassField field : implClass.getFields()) {
clazz.addField(field);
}
}
}
}
return clazz;
}
private void visitChildren(List<Node> nodes, ClassVisitor visitor) {
for (Node n : nodes) {
if (n instanceof FieldDeclaration) {
visitor.visit((FieldDeclaration) n, null);
} else if (n instanceof MethodDeclaration) {
visitor.visit((MethodDeclaration) n, null);
} else if (n instanceof ConstructorDeclaration) {
visitor.visit((ConstructorDeclaration) n, null);
} else if (n instanceof ClassOrInterfaceDeclaration) {
visitor.visit((ClassOrInterfaceDeclaration) n, null);
}
}
}
public void setExtendedAndInterfaceTypes(SourceClass clazz, ClassOrInterfaceDeclaration n) {
NodeList<ClassOrInterfaceType> extendedTypes = n.getExtendedTypes();
if (extendedTypes != null && extendedTypes.size() > 0) {
String className = extendedTypes.get(0).getNameAsString();
clazz.setSuperclass(new FqnSearcher(sources).getFqn(clazz, className));
} else {
clazz.setSuperclass("java.lang.Object");
addConstructorIfNotEmpty(clazz);
}
NodeList<ClassOrInterfaceType> implementedTypes = n.getImplementedTypes();
if (implementedTypes != null) {
for (ClassOrInterfaceType iface : implementedTypes) {
clazz.addInterface(new FqnSearcher(sources).getFqn(clazz, iface.getNameAsString()));
}
}
}
private class ClassOrInterfaceVisitor extends VoidVisitorAdapter<Object> {
private SourceClass clazz;
public ClassOrInterfaceVisitor(SourceClass clazz) {
this.clazz = clazz;
}
public SourceClass getClazz() {
return clazz;
}
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
parentClass = n;
clazz.setName(n.getNameAsString());
clazz.setModifiers(n.getModifiers());
clazz.setIsInterface(n.isInterface());
Optional<Position> beginning = n.getBegin();
Optional<Position> ending = n.getEnd();
if (beginning.isPresent() && ending.isPresent()) {
clazz.setRegion(beginning.get().line, beginning.get().column, ending.get().line,
ending.get().column);
}
setExtendedAndInterfaceTypes(clazz, n);
}
}
private void addConstructorIfNotEmpty(SourceClass clazz) {
if (clazz.getConstructors().isEmpty()) {
ClassConstructor ctor = new ClassConstructor();
ctor.setDeclaration(String.format("public %s()", clazz.getName()));
ctor.setModifiers(EnumSet.of(Modifier.PUBLIC));
clazz.addConstructor(ctor);
}
}
private class ClassVisitor extends VoidVisitorAdapter<Object> {
private SourceClass clazz;
public ClassVisitor(SourceClass clazz) {
this.clazz = clazz;
}
public SourceClass getClazz() {
return clazz;
}
@Override
public void visit(ConstructorDeclaration n, Object arg) {
ClassConstructor constructor = new ClassConstructor();
constructor.setDeclaration(n.getDeclarationAsString());
constructor.setModifiers(n.getModifiers());
if (n.getTypeParameters() != null) {
for (TypeParameter parameter : n.getTypeParameters()) {
constructor.addTypeParameter(
new ClassTypeParameter(parameter.getNameAsString()));
}
}
clazz.addConstructor(constructor);
}
@Override
public void visit(MethodDeclaration n, Object arg) {
ClassMethod method = new ClassMethod();
method.setName(n.getNameAsString());
method.setModifiers(n.getModifiers());
method.setDeclaration(n.getDeclarationAsString());
String className = n.getType().toString();
method.setTypeName(new FqnSearcher(sources).getFqn(clazz, className));
if (n.getTypeParameters() != null) {
for (TypeParameter parameter : n.getTypeParameters()) {
method.addTypeParameter(new ClassTypeParameter(parameter.getNameAsString()));
}
}
if (n.getParameters() != null) {
for (Parameter parameter : n.getParameters()) {
method.addTypeParameter(new ClassTypeParameter(
parameter.getType().toString(ClassNamesFetcher.withoutComments())));
}
}
clazz.addMethod(method);
}
@Override
public void visit(FieldDeclaration n, Object arg) {
for (VariableDeclarator v : n.getVariables()) {
ClassField field = new ClassField();
field.setName(v.getNameAsString());
field.setModifiers(n.getModifiers());
String className = n.getElementType().asString();
field.setTypeName(new FqnSearcher(sources).getFqn(clazz, className));
clazz.addField(field);
}
}
@Override
public void visit(ClassOrInterfaceDeclaration n, Object arg) {
SourceClass clazz = new SourceClass();
clazz.setName(this.clazz.getSimpleName() + "$" + n.getName());
clazz.setModifiers(n.getModifiers());
clazz.setIsInterface(n.isInterface());
Optional<Position> beginning = n.getBegin();
Optional<Position> ending = n.getEnd();
if (beginning.isPresent() && ending.isPresent()) {
clazz.setRegion(beginning.get().line, beginning.get().column, ending.get().line,
ending.get().column);
}
setExtendedAndInterfaceTypes(clazz, n);
clazz.setPackage(this.clazz.getPackage());
ClassVisitor visitor = new ClassVisitor(clazz);
visitChildren(n.getChildNodes(), visitor);
this.clazz.addNestedClass(clazz.getName());
this.clazz.addLinkedClass(clazz);
Cache.getInstance().getClasses().put(clazz.getName(), clazz);
}
}
}
|
gotmanyacc/dotfiles
|
vim/bundle/vim-javacomplete2/libs/javavi/src/main/java/kg/ash/javavi/readers/Parser.java
|
Java
|
gpl-3.0
| 12,090
|
//
// SAXParser.h
//
// Library: XML
// Package: SAX
// Module: SAX
//
// Implementation of the XMLReader interface.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef SAX_SAXParser_INCLUDED
#define SAX_SAXParser_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/SAX/XMLReader.h"
#include "Poco/XML/ParserEngine.h"
namespace Poco {
namespace XML {
class XML_API SAXParser: public XMLReader
/// This class provides a SAX2 (Simple API for XML) interface to expat,
/// the XML parser toolkit.
/// The following SAX2 features and properties are supported:
/// * http://xml.org/sax/features/external-general-entities
/// * http://xml.org/sax/features/external-parameter-entities
/// * http://xml.org/sax/features/namespaces
/// * http://xml.org/sax/features/namespace-prefixes
/// * http://xml.org/sax/properties/lexical-handler
/// * http://xml.org/sax/properties/declaration-handler
///
/// The following proprietary extensions are supported:
/// * http://www.appinf.com/features/enable-partial-reads --
/// see ParserEngine::setEnablePartialReads()
{
public:
SAXParser();
/// Creates an SAXParser.
SAXParser(const XMLString& encoding);
/// Creates an SAXParser with the given encoding.
~SAXParser();
/// Destroys the SAXParser.
void setEncoding(const XMLString& encoding);
/// Sets the encoding used by the parser if no
/// encoding is specified in the XML document.
const XMLString& getEncoding() const;
/// Returns the name of the encoding used by
/// the parser if no encoding is specified in
/// the XML document.
void addEncoding(const XMLString& name, Poco::TextEncoding* pEncoding);
/// Adds an encoding to the parser. Does not take ownership of the pointer!
/// XMLReader
void setEntityResolver(EntityResolver* pResolver);
EntityResolver* getEntityResolver() const;
void setDTDHandler(DTDHandler* pDTDHandler);
DTDHandler* getDTDHandler() const;
void setContentHandler(ContentHandler* pContentHandler);
ContentHandler* getContentHandler() const;
void setErrorHandler(ErrorHandler* pErrorHandler);
ErrorHandler* getErrorHandler() const;
void setFeature(const XMLString& featureId, bool state);
bool getFeature(const XMLString& featureId) const;
void setProperty(const XMLString& propertyId, const XMLString& value);
void setProperty(const XMLString& propertyId, void* value);
void* getProperty(const XMLString& propertyId) const;
void parse(InputSource* pSource);
void parse(const XMLString& systemId);
void parseMemoryNP(const char* xml, std::size_t size);
/// Extensions
void parseString(const std::string& xml);
static const XMLString FEATURE_PARTIAL_READS;
protected:
void setupParse();
private:
ParserEngine _engine;
bool _namespaces;
bool _namespacePrefixes;
};
} } // namespace Poco::XML
#endif // SAX_SAXParser_INCLUDED
|
uksf/modpack
|
extensions/poco/XML/include/Poco/SAX/SAXParser.h
|
C
|
gpl-3.0
| 2,941
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Returns the ID of the last inserted row or sequence value</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="pdo.intransaction.html">PDO::inTransaction</a></div>
<div class="next" style="text-align: right; float: right;"><a href="pdo.prepare.html">PDO::prepare</a></div>
<div class="up"><a href="class.pdo.html">PDO</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="pdo.lastinsertid" class="refentry">
<div class="refnamediv">
<h1 class="refname">PDO::lastInsertId</h1>
<p class="verinfo">(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)</p><p class="refpurpose"><span class="refname">PDO::lastInsertId</span> — <span class="dc-title">
Returns the ID of the last inserted row or sequence value
</span></p>
</div>
<div class="refsect1 description" id="refsect1-pdo.lastinsertid-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="modifier">public</span> <span class="type">string</span> <span class="methodname"><strong>PDO::lastInsertId</strong></span>
([ <span class="methodparam"><span class="type">string</span> <code class="parameter">$name</code><span class="initializer"> = <strong><code>NULL</code></strong></span></span>
] )</div>
<p class="para rdfs-comment">
Returns the ID of the last inserted row, or the last value from a
sequence object, depending on the underlying driver. For example,
<a href="ref.pdo-pgsql.html" class="link">PDO_PGSQL</a> requires you to specify the name of
a sequence object for the <code class="parameter">name</code> parameter.
</p>
<blockquote class="note"><p><strong class="note">Note</strong>:
<p class="para">
This method may not return a meaningful or consistent result across
different PDO drivers, because the underlying database may not even
support the notion of auto-increment fields or sequences.
</p>
</p></blockquote>
</div>
<div class="refsect1 parameters" id="refsect1-pdo.lastinsertid-parameters">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<code class="parameter">name</code></dt>
<dd>
<p class="para">
Name of the sequence object from which the ID should be returned.
</p>
</dd>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-pdo.lastinsertid-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
If a sequence name was not specified for the <code class="parameter">name</code>
parameter, <span class="function"><strong>PDO::lastInsertId()</strong></span> returns a
string representing the row ID of the last row that was inserted into
the database.
</p>
<p class="para">
If a sequence name was specified for the <code class="parameter">name</code>
parameter, <span class="function"><strong>PDO::lastInsertId()</strong></span> returns a
string representing the last value retrieved from the specified sequence
object.
</p>
<p class="para">
If the PDO driver does not support this capability,
<span class="function"><strong>PDO::lastInsertId()</strong></span> triggers an
<em>IM001</em> SQLSTATE.
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="pdo.intransaction.html">PDO::inTransaction</a></div>
<div class="next" style="text-align: right; float: right;"><a href="pdo.prepare.html">PDO::prepare</a></div>
<div class="up"><a href="class.pdo.html">PDO</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
|
rafaelgou/the-phpjs-local-docs-collection
|
php/5.5/pdo.lastinsertid.html
|
HTML
|
gpl-3.0
| 3,927
|
<!DOCTYPE html>
<!--[if IEMobile 7]><html class="no-js iem7 oldie"><![endif]-->
<!--[if (IE 7)&!(IEMobile)]><html class="no-js ie7 oldie" lang="en"><![endif]-->
<!--[if (IE 8)&!(IEMobile)]><html class="no-js ie8 oldie" lang="en"><![endif]-->
<!--[if (IE 9)&!(IEMobile)]><html class="no-js ie9" lang="en"><![endif]-->
<!--[if (gt IE 9)|(gt IEMobile 7)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Developr</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- http://davidbcalhoun.com/2010/viewport-metatag -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- For all browsers -->
<link rel="stylesheet" href="css/reset.css?v=1">
<link rel="stylesheet" href="css/style.css?v=1">
<link rel="stylesheet" href="css/colors.css?v=1">
<link rel="stylesheet" media="print" href="css/print.css?v=1">
<!-- For progressively larger displays -->
<link rel="stylesheet" media="only all and (min-width: 480px)" href="css/480.css?v=1">
<link rel="stylesheet" media="only all and (min-width: 768px)" href="css/768.css?v=1">
<link rel="stylesheet" media="only all and (min-width: 992px)" href="css/992.css?v=1">
<link rel="stylesheet" media="only all and (min-width: 1200px)" href="css/1200.css?v=1">
<!-- For Retina displays -->
<link rel="stylesheet" media="only all and (-webkit-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (min-device-pixel-ratio: 1.5)" href="css/2x.css?v=1">
<!-- Webfonts -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300' rel='stylesheet' type='text/css'>
<!-- Additional styles -->
<link rel="stylesheet" href="css/styles/agenda.css?v=1">
<link rel="stylesheet" href="css/styles/switches.css?v=1">
<!-- JavaScript at bottom except for Modernizr -->
<script src="js/libs/modernizr.custom.js"></script>
<!-- For Modern Browsers -->
<link rel="shortcut icon" href="img/favicons/favicon.png">
<!-- For everything else -->
<link rel="shortcut icon" href="img/favicons/favicon.ico">
<!-- For retina screens -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/favicons/apple-touch-icon-retina.png">
<!-- For iPad 1-->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/favicons/apple-touch-icon-ipad.png">
<!-- For iPhone 3G, iPod Touch and Android -->
<link rel="apple-touch-icon-precomposed" href="img/favicons/apple-touch-icon.png">
<!-- iOS web-app metas -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- Startup image for web apps -->
<link rel="apple-touch-startup-image" href="img/splash/ipad-landscape.png" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)">
<link rel="apple-touch-startup-image" href="img/splash/ipad-portrait.png" media="screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)">
<link rel="apple-touch-startup-image" href="img/splash/iphone.png" media="screen and (max-device-width: 320px)">
<!-- Microsoft clear type rendering -->
<meta http-equiv="cleartype" content="on">
</head>
<body dir="rtl" class="clearfix with-menu with-shortcuts">
<!-- Prompt IE 6 users to install Chrome Frame -->
<!--[if lt IE 7]><p class="message red-gradient simpler">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]-->
<!-- Title bar -->
<header role="banner" id="title-bar">
<h2>Developr</h2>
</header>
<!-- Button to open/hide menu -->
<a href="#" id="open-menu"><span>Menu</span></a>
<!-- Button to open/hide shortcuts -->
<a href="#" id="open-shortcuts"><span class="icon-thumbs"></span></a>
<!-- Main content -->
<section role="main" id="main">
<noscript class="message black-gradient simpler">Your browser does not support JavaScript! Some features won't work as expected...</noscript>
<hgroup id="main-title" class="thin">
<h1>Agenda</h1>
</hgroup>
<div class="with-padding">
<div class="columns">
<div class="six-columns twelve-columns-tablet">
<h3 class="thin">Simple agenda</h3>
<p>This is the basic style, with only one day and no header.</p>
<div class="agenda">
<!-- Time markers -->
<ul class="agenda-time">
<li class="from-7 to-8"><span>7 AM</span></li>
<li class="from-8 to-9"><span>8 AM</span></li>
<li class="from-9 to-10"><span>9 AM</span></li>
<li class="from-10 to-11"><span>10 AM</span></li>
<li class="from-11 to-12"><span>11 AM</span></li>
<li class="from-12 to-13"><span>12 AM</span></li>
<li class="from-13 to-14"><span>1 PM</span></li>
<li class="from-14 to-15"><span>2 PM</span></li>
<li class="from-15 to-16"><span>3 PM</span></li>
<li class="from-16 to-17"><span>4 PM</span></li>
<li class="from-17 to-18"><span>5 PM</span></li>
<li class="from-18 to-19"><span>6 PM</span></li>
<li class="from-19 to-20"><span>7 PM</span></li>
<li class="at-20"><span>8 PM</span></li>
</ul>
<!-- Events list -->
<div class="agenda-events">
<a href="#" class="agenda-event from-7 to-10">
<time>7 AM - 10 AM</time>
Event description
</a>
<span class="agenda-event from-14 to-17 anthracite-gradient">
<time>2 PM - 5 PM</time>
Event description
</span>
</div>
</div>
</div>
<div class="six-columns twelve-columns-tablet">
<h3 class="thin">Advanced agenda</h3>
<p>Complete agenda with header and days browsing.</p>
<div class="agenda with-header auto-scroll" data-agenda-options='{"auto":false,"first":1}'>
<!-- Time markers -->
<ul class="agenda-time">
<li class="from-7 to-8"><span>7 AM</span></li>
<li class="from-8 to-9"><span>8 AM</span></li>
<li class="from-9 to-10"><span>9 AM</span></li>
<li class="from-10 to-11"><span>10 AM</span></li>
<li class="from-11 to-12"><span>11 AM</span></li>
<li class="from-12 to-13 blue"><span>NOON</span></li>
<li class="from-13 to-14"><span>1 PM</span></li>
<li class="from-14 to-15"><span>2 PM</span></li>
<li class="from-15 to-16"><span>3 PM</span></li>
<li class="from-16 to-17"><span>4 PM</span></li>
<li class="from-17 to-18"><span>5 PM</span></li>
<li class="from-18 to-19"><span>6 PM</span></li>
<li class="from-19 to-20"><span>7 PM</span></li>
<li class="at-20"><span>8 PM</span></li>
</ul>
<!-- Columns wrapper -->
<div class="agenda-wrapper">
<!-- Events list -->
<div class="agenda-events agenda-day1">
<div class="agenda-header">
Sunday
</div>
<span class="agenda-event anthracite-gradient from-16 to-17-30">
<time>4 PM - 5:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day2">
<div class="agenda-header">
Monday
</div>
<div class="dark-stripes from-12 to-14"></div>
<a href="#" class="agenda-event from-before to-9">
<time>5 AM - 9 AM</time>
Event description
</a>
<span class="agenda-event from-10 to-11-30 event-1-on-2">
<time>10 AM - 11:30 AM</time>
Event description
<span class="ribbon tiny"><span class="ribbon-inner red-gradient">High</span></span>
</span>
<span class="agenda-event from-11 to-13 event-2-on-2 anthracite-gradient">
<time>11 AM - 1 PM</time>
Event description
</span>
<span class="agenda-event from-16 to-17-30 event-1-on-3">
<time>4 PM - 5:30 PM</time>
Event description
</span>
<span class="agenda-event from-16-30 to-17-30 event-2-on-3 anthracite-gradient">
<time>4:30 PM - 5:30 PM</time>
Event description
</span>
<span class="agenda-event from-17 to-19-30 event-3-on-3 blue-gradient">
<time>5 PM - 7:30 PM</time>
Event description
</span>
<div class="agenda-now" style="top:63.75%"><span>03:23</span></div>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day3">
<div class="agenda-header">
Tuesday
</div>
<div class="dark-stripes from-12 to-18"></div>
<a href="#" class="agenda-event from-7 to-9">
<time>7 AM - 9 AM</time>
Event description
<span class="ribbon tiny"><span class="ribbon-inner orange-gradient">Priv</span></span>
</a>
<span class="agenda-event from-10 to-11-30 event-1-on-2">
<time>10 AM - 11:30 AM</time>
Event description
</span>
<span class="agenda-event from-11 to-13 event-2-on-2 anthracite-gradient">
<time>11 AM - 1 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day4">
<div class="agenda-header">
Wednesday
</div>
<div class="dark-stripes from-12 to-14"></div>
<a href="#" class="agenda-event from-9 to-10">
<time>9 AM - 10 AM</time>
Event description
</a>
<span class="agenda-event from-16 to-17-30 event-1-on-2">
<time>4 PM - 5:30 PM</time>
Event description
</span>
<span class="agenda-event from-17 to-19-30 event-2-on-2 blue-gradient">
<time>5 PM - 7:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day5">
<div class="agenda-header">
Thursday
</div>
<div class="dark-stripes from-12 to-14"></div>
<a href="#" class="agenda-event from-8 to-9">
<time>8 AM - 9 AM</time>
Event description
</a>
<span class="agenda-event from-11 to-13 anthracite-gradient">
<time>11 AM - 1 PM</time>
Event description
</span>
<span class="agenda-event from-17 to-19-30 blue-gradient">
<time>5 PM - 7:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day6">
<div class="agenda-header">
Friday
</div>
<div class="dark-stripes from-12 to-14"></div>
<span class="agenda-event from-10 to-13 anthracite-gradient">
<time>10 AM - 1 PM</time>
Event description
</span>
<span class="agenda-event from-16 to-18-30">
<time>4 PM - 6:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day7">
<div class="agenda-header">
Saturday
</div>
</div>
</div>
</div>
</div>
</div>
<h3 class="thin">Weekly agenda</h3>
<p>Wonder how it looks on smaller screens? Try resizing your browser!</p>
<div class="agenda with-header auto-scroll">
<!-- Time markers -->
<ul class="agenda-time">
<li class="from-7 to-8"><span>7 AM</span></li>
<li class="from-8 to-9"><span>8 AM</span></li>
<li class="from-9 to-10"><span>9 AM</span></li>
<li class="from-10 to-11"><span>10 AM</span></li>
<li class="from-11 to-12"><span>11 AM</span></li>
<li class="from-12 to-13 blue"><span>NOON</span></li>
<li class="from-13 to-14"><span>1 PM</span></li>
<li class="from-14 to-15"><span>2 PM</span></li>
<li class="from-15 to-16"><span>3 PM</span></li>
<li class="from-16 to-17"><span>4 PM</span></li>
<li class="from-17 to-18"><span>5 PM</span></li>
<li class="from-18 to-19"><span>6 PM</span></li>
<li class="from-19 to-20"><span>7 PM</span></li>
<li class="at-20"><span>8 PM</span></li>
</ul>
<!-- Columns wrapper -->
<div class="agenda-wrapper">
<!-- Events list -->
<div class="agenda-events agenda-day1">
<div class="agenda-header">
Sunday
</div>
<span class="agenda-event anthracite-gradient from-16 to-17-30">
<time>4 PM - 5:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day2">
<div class="agenda-header">
Monday
</div>
<div class="dark-stripes from-12 to-14"></div>
<a href="#" class="agenda-event from-8 to-11">
<time>8 AM - 11 AM</time>
Event description
</a>
<span class="agenda-event from-16-30 to-17-30">
<time>4:30 PM - 5:30 PM</time>
Event description
</span>
<div class="agenda-now" style="top:63.75%"><span>03:23</span></div>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day3">
<div class="agenda-header">
Tuesday
</div>
<div class="dark-stripes from-12 to-18"></div>
<a href="#" class="agenda-event from-7 to-9">
<time>7 AM - 9 AM</time>
Event description
<span class="ribbon tiny"><span class="ribbon-inner orange-gradient">Priv</span></span>
</a>
<span class="agenda-event from-10 to-11-30 event-1-on-2">
<time>10 AM - 11:30 AM</time>
Event description
</span>
<span class="agenda-event from-11 to-13 event-2-on-2 anthracite-gradient">
<time>11 AM - 1 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day4">
<div class="agenda-header">
Wednesday
</div>
<div class="dark-stripes from-12 to-14"></div>
<a href="#" class="agenda-event from-9 to-10">
<time>9 AM - 10 AM</time>
Event description
</a>
<span class="agenda-event from-16 to-17-30 event-1-on-2">
<time>4 PM - 5:30 PM</time>
Event description
</span>
<span class="agenda-event from-17 to-19-30 event-2-on-2 blue-gradient">
<time>5 PM - 7:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day5">
<div class="agenda-header">
Thursday
</div>
<div class="dark-stripes from-12 to-14"></div>
<a href="#" class="agenda-event from-8 to-9">
<time>8 AM - 9 AM</time>
Event description
</a>
<span class="agenda-event from-11 to-13 anthracite-gradient">
<time>11 AM - 1 PM</time>
Event description
</span>
<span class="agenda-event from-17 to-19-30 blue-gradient">
<time>5 PM - 7:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day6">
<div class="agenda-header">
Friday
</div>
<div class="dark-stripes from-12 to-14"></div>
<span class="agenda-event from-10 to-13 anthracite-gradient">
<time>10 AM - 1 PM</time>
Event description
</span>
<span class="agenda-event from-16 to-18-30">
<time>4 PM - 6:30 PM</time>
Event description
</span>
</div>
<!-- Events list -->
<div class="agenda-events agenda-day7">
<div class="agenda-header">
Saturday
</div>
</div>
</div>
</div>
</div>
</section>
<!-- End main content -->
<!-- Side tabs shortcuts -->
<ul id="shortcuts" role="complementary" class="children-tooltip tooltip-left">
<li><a href="./" class="shortcut-dashboard" title="Dashboard">Dashboard</a></li>
<li><a href="inbox.html" class="shortcut-messages" title="Messages">Messages</a></li>
<li class="current"><a href="agenda.html" class="shortcut-agenda" title="Agenda">Agenda</a></li>
<li><a href="tables.html" class="shortcut-contacts" title="Contacts">Contacts</a></li>
<li><a href="explorer.html" class="shortcut-medias" title="Medias">Medias</a></li>
<li><a href="sliders.html" class="shortcut-stats" title="Stats">Stats</a></li>
<li><a href="form.html" class="shortcut-settings" title="Settings">Settings</a></li>
<li><span class="shortcut-notes" title="Notes">Notes</span></li>
</ul>
<!-- Sidebar/drop-down menu -->
<section id="menu" role="complementary">
<!-- This wrapper is used by several responsive layouts -->
<div id="menu-content">
<header>
Administrator
</header>
<div id="profile">
<img src="img/user.png" width="64" height="64" alt="User name" class="user-icon">
Hello
<span class="name">John <b>Doe</b></span>
</div>
<!-- By default, this section is made for 4 icons, see the doc to learn how to change this, in "basic markup explained" -->
<ul id="access" class="children-tooltip">
<li><a href="inbox.html" title="Messages"><span class="icon-inbox"></span><span class="count">2</span></a></li>
<li><a href="calendars.html" title="Calendar"><span class="icon-calendar"></span></a></li>
<li><a href="login.html" title="Profile"><span class="icon-user"></span></a></li>
<li class="disabled"><span class="icon-gear"></span></li>
</ul>
<section class="navigable">
<ul class="big-menu">
<li class="with-left-arrow">
<span><span class="list-count">11</span>Main styles</span>
<ul class="big-menu">
<li><a href="typography.html">Typography</a></li>
<li><a href="columns.html">Columns</a></li>
<li><a href="tables.html">Tables</a></li>
<li><a href="colors.html">Colors & backgrounds</a></li>
<li><a href="icons.html">Icons</a></li>
<li><a href="files.html">Files & Gallery</a></li>
<li class="with-left-arrow">
<span><span class="list-count">4</span>Forms & buttons</span>
<ul class="big-menu">
<li><a href="buttons.html">Buttons</a></li>
<li><a href="form.html">Form elements</a></li>
<li><a href="textareas.html">Textareas & WYSIWYG</a></li>
<li><a href="form-layouts.html">Form layouts</a></li>
<li><a href="wizard.html">Wizard</a></li>
</ul>
</li>
<li class="with-left-arrow">
<span><span class="list-count">2</span>Agenda & Calendars</span>
<ul class="big-menu">
<li><a href="agenda.html" class="current navigable-current">Agenda</a></li>
<li><a href="calendars.html">Calendars</a></li>
</ul>
</li>
<li><a href="blocks.html">Blocks & infos</a></li>
</ul>
</li>
<li class="with-left-arrow">
<span><span class="list-count">8</span>Main features</span>
<ul class="big-menu">
<li><a href="auto-setup.html">Automatic setup</a></li>
<li><a href="responsive.html">Responsiveness</a></li>
<li><a href="tabs.html">Tabs</a></li>
<li><a href="sliders.html">Slider & progress</a></li>
<li><a href="modals.html">Modal windows</a></li>
<li class="with-left-arrow">
<span><span class="list-count">3</span>Messages & notifications</span>
<ul class="big-menu">
<li><a href="messages.html">Messages</a></li>
<li><a href="notifications.html">Notifications</a></li>
<li><a href="tooltips.html">Tooltips</a></li>
</ul>
</li>
</ul>
</li>
<li class="with-left-arrow">
<a href="ajax-demo/submenu.html" class="navigable-ajax" title="Menu title">With ajax sub-menu</a>
</li>
</ul>
</section>
<ul class="unstyled-list">
<li class="title-menu">Today's event</li>
<li>
<ul class="calendar-menu">
<li>
<a href="#" title="See event">
<time datetime="2011-02-24"><b>24</b> Feb</time>
<small class="green">10:30</small>
Event's description
</a>
</li>
</ul>
</li>
<li class="title-menu">New messages</li>
<li>
<ul class="message-menu">
<li>
<span class="message-status">
<a href="#" class="starred" title="Starred">Starred</a>
<a href="#" class="new-message" title="Mark as read">New</a>
</span>
<span class="message-info">
<span class="blue">17:12</span>
<a href="#" class="attach" title="Download attachment">Attachment</a>
</span>
<a href="#" title="Read message">
<strong class="blue">John Doe</strong><br>
<strong>Mail subject</strong>
</a>
</li>
<li>
<a href="#" title="Read message">
<span class="message-status">
<span class="unstarred">Not starred</span>
<span class="new-message">New</span>
</span>
<span class="message-info">
<span class="blue">15:47</span>
</span>
<strong class="blue">May Starck</strong><br>
<strong>Mail subject a bit longer</strong>
</a>
</li>
<li>
<span class="message-status">
<span class="unstarred">Not starred</span>
</span>
<span class="message-info">
<span class="blue">15:12</span>
</span>
<strong class="blue">May Starck</strong><br>
Read message
</li>
</ul>
</li>
</ul>
</div>
<!-- End content wrapper -->
<!-- This is optional -->
<footer id="menu-footer">
<p class="button-height">
<input type="checkbox" name="auto-refresh" id="auto-refresh" checked="checked" class="switch float-left">
<label for="auto-refresh">Auto-refresh</label>
</p>
</footer>
</section>
<!-- End sidebar/drop-down menu -->
<!-- JavaScript at the bottom for fast page loading -->
<!-- Scripts -->
<script src="js/libs/jquery-1.8.2.min.js"></script>
<script src="js/setup.js"></script>
<!-- Template functions -->
<script src="js/developr.input.js"></script>
<script src="js/developr.navigable.js"></script>
<script src="js/developr.notify.js"></script>
<script src="js/developr.scroll.js"></script>
<script src="js/developr.tooltip.js"></script>
<script src="js/developr.agenda.js"></script>
<script>
// Call template init (optional, but faster if called manually)
$.template.init();
</script>
</body>
</html>
|
woakes070048/crm-php
|
htdocs/man/themes/developr/html-rtl/agenda.html
|
HTML
|
gpl-3.0
| 23,353
|
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: multiplayer_sa/multiplayer_shotsync.cpp
* PURPOSE: Multiplayer module shooting sync methods
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
// These includes have to be fixed!
#include "../game_sa/CPedSA.h"
#include "../game_sa/CEventDamageSA.h"
#include "../game_sa/CColPointSA.h"
extern CMultiplayerSA* pMultiplayer;
using std::list;
list<CShotSyncData*> ShotSyncData;
CShotSyncData LocalShotSyncData;
float* fDirectionX;
float* fDirectionY;
CPedIKSAInterface* pPedIKInterface;
CPedSAInterface* pPedInterfaceTemp;
CPed* pPedTemp;
CPed* pLocalPedTemp;
CVector* vecOrigin;
CEntitySAInterface* pProjectileOwner = 0;
eWeaponType projectileWeaponType = WEAPONTYPE_UNARMED;
CVector* projectileOrigin = NULL;
float projectileForce = 0.0f;
CVector* projectileTarget = NULL;
CEntitySAInterface* projectileTargetEntityInterface = 0;
CEntity* projectileTargetEntity = 0;
class CProjectileSAInterface* pProjectile = 0;
DWORD dwProjectileInfoIndex;
bool bWeaponFire = false;
CColPointSAInterface** ppInstantHitColPoint;
CEntitySAInterface** ppInstantHitEntity;
CVector * pInstantHitStart = NULL, *pInstantHitEnd = NULL;
CVector vecLastOrigin;
CVector vecLastLocalPlayerBulletStart;
CVector vecLastLocalPlayerBulletEnd;
char cTempGunDirection;
DWORD vecTargetPosition;
DWORD vecAltPos;
CPedSAInterface* pShootingPed;
EDamageReasonType g_GenerateDamageEventReason = EDamageReason::OTHER;
CPedSAInterface* pBulletImpactInitiator;
CEntitySAInterface* pBulletImpactVictim;
CVector* pBulletImpactStartPosition;
CVector* pBulletImpactEndPosition;
CVector vecSavedBulletImpactEndPosition;
extern PreWeaponFireHandler* m_pPreWeaponFireHandler;
extern PostWeaponFireHandler* m_pPostWeaponFireHandler;
extern BulletImpactHandler* m_pBulletImpactHandler;
extern BulletFireHandler* m_pBulletFireHandler;
extern DamageHandler* m_pDamageHandler;
extern DeathHandler* m_pDeathHandler;
extern FireHandler* m_pFireHandler;
extern ProjectileHandler* m_pProjectileHandler;
extern ProjectileStopHandler* m_pProjectileStopHandler;
char szDebug[255] = {'\0'};
DWORD RETURN_CProjectile__AddProjectile = 0x401C3D;
DWORD RETURN_CProjectile__CProjectile = 0x4037B3;
CPools* m_pools = 0;
#define VAR_CWorld_IncludeCarTyres 0xb7cd70 // Used for CWorld_ProcessLineOfSight
void InitFireInstantHit_MidHooks(void);
void InitFireSniper_MidHooks(void);
VOID InitShotsyncHooks()
{
HookInstall(HOOKPOS_CWeapon__Fire, (DWORD)HOOK_CWeapon__Fire, 6);
HookInstall(HOOKPOS_CWeapon__PostFire, (DWORD)HOOK_CWeapon__PostFire, 6);
HookInstall(HOOKPOS_CWeapon__PostFire2, (DWORD)HOOK_CWeapon__PostFire2, 6);
HookInstall(HOOKPOS_CPedIK__PointGunInDirection, (DWORD)HOOK_CPedIK__PointGunInDirection, 7);
HookInstall(HOOKPOS_CTaskSimpleGangDriveBy__PlayerTarget, (DWORD)HOOK_CTaskSimpleGangDriveBy__PlayerTarget, 6);
HookInstall(HOOKPOS_CWeapon__Fire_Sniper, (DWORD)HOOK_CWeapon__Fire_Sniper, 6);
HookInstall(HOOKPOS_CEventDamage__AffectsPed, (DWORD)HOOK_CEventDamage__AffectsPed, 6);
HookInstall(HOOKPOS_CEventVehicleExplosion__AffectsPed, (DWORD)HOOK_CEventVehicleExplosion__AffectsPed, 5);
HookInstall(HOOKPOS_CFireManager__StartFire, (DWORD)HOOK_CFireManager__StartFire, 6);
HookInstall(HOOKPOS_CFireManager__StartFire_, (DWORD)HOOK_CFireManager__StartFire_, 6);
HookInstall(HOOKPOS_CProjectileInfo__AddProjectile, (DWORD)HOOK_CProjectileInfo__AddProjectile, 7);
HookInstall(HOOKPOS_CProjectile__CProjectile, (DWORD)HOOK_CProjectile__CProjectile, 7);
HookInstall(HOOKPOS_IKChainManager_PointArm, (DWORD)HOOK_IKChainManager_PointArm, 7);
HookInstall(HOOKPOS_IKChainManager_LookAt, (DWORD)HOOK_IKChainManager_LookAt, 7);
HookInstall(HOOKPOS_IKChainManager_SkipAim, (DWORD)HOOK_SkipAim, 6);
HookInstall(HOOKPOS_CTaskSimpleUsegun_ProcessPed, (DWORD)HOOK_CTaskSimpleUsegun_ProcessPed, 8);
HookInstall(HOOKPOS_CWeapon_FireInstantHit, (DWORD)HOOK_CWeapon_FireInstantHit, 9);
HookInstall(HOOKPOS_CWeapon_FireInstantHit_CameraMode, (DWORD)HOOK_CWeapon_FireInstantHit_CameraMode, 6);
HookInstall(HOOKPOS_CWeapon_FireInstantHit_IsPlayer, (DWORD)HOOK_CWeapon_FireInstantHit_IsPlayer, 7);
HookInstall(HOOKPOS_CWeapon_DoBulletImpact, (DWORD)HOOK_CWeapon_DoBulletImpact, 7);
InitFireInstantHit_MidHooks();
InitFireSniper_MidHooks();
/*
MemPut < BYTE > ( 0x73FDEC, 0x90 );
MemPut < BYTE > ( 0x73FDED, 0xE9 );
*/
m_pools = pGameInterface->GetPools();
}
CShotSyncData* GetLocalPedShotSyncData()
{
return &LocalShotSyncData;
}
bool IsLocalPlayer(CPed* pPed)
{
CPed* pLocalPed = m_pools->GetPedFromRef((DWORD)1);
return (pPed == pLocalPed);
}
bool IsLocalPlayer(CPedSAInterface* pPedInterface)
{
CPed* pPed = m_pools->GetPed((DWORD*)pPedInterface);
return IsLocalPlayer(pPed);
}
VOID WriteGunDirectionDataForPed(CPedSAInterface* pPedInterface, float* fGunDirectionX, float* fGunDirectionY, char* cGunDirection)
{
if (!IsLocalPlayer(pPedInterface))
{
CRemoteDataStorageSA* data = CRemoteDataSA::GetRemoteDataStorage(pPedInterface);
if (data)
{
if (data->ProcessPlayerWeapon())
{
if (fGunDirectionX && fGunDirectionY)
{
*fGunDirectionX = data->m_shotSyncData.m_fArmDirectionX;
*fGunDirectionY = data->m_shotSyncData.m_fArmDirectionY;
}
if (cGunDirection)
{
*cGunDirection = data->m_shotSyncData.m_cInVehicleAimDirection;
}
}
}
}
else
{
// store it
if (fGunDirectionX && fGunDirectionY)
{
// Make sure our pitch is updated (fixes first-person weapons not moving)
*fGunDirectionY = pGameInterface->GetCamera()->Find3rdPersonQuickAimPitch();
LocalShotSyncData.m_fArmDirectionX = *fGunDirectionX;
LocalShotSyncData.m_fArmDirectionY = *fGunDirectionY;
}
if (cGunDirection)
{
LocalShotSyncData.m_cInVehicleAimDirection = *cGunDirection;
}
}
}
// Return false to stop bullet impact to being calculated here
// (False also assumes lag compensation movement has not been performed)
bool WriteTargetDataForPed(CPedSAInterface* pPed, DWORD vecTargetPos, CVector* origin)
{
bool bDoBulletTraceHere = true;
vecLastOrigin = *origin;
// vecTargetPosition is a pointer to a vecTargetPosition*
CPed* pTargetingPed = m_pools->GetPed((DWORD*)pPed);
CPlayerPed* pTargetingPlayerPed = dynamic_cast<CPlayerPed*>(pTargetingPed);
if (!pTargetingPlayerPed)
return true;
if (m_pPreWeaponFireHandler && pTargetingPed)
{
bDoBulletTraceHere = m_pPreWeaponFireHandler(pTargetingPlayerPed, true);
}
if (!IsLocalPlayer(pTargetingPed))
{
CRemoteDataStorageSA* data = CRemoteDataSA::GetRemoteDataStorage(pTargetingPlayerPed);
if (data)
{
if (data->ProcessPlayerWeapon())
{
DWORD dwPointerToVector = (DWORD)&data->m_shotSyncData.m_vecShotTarget;
MemPutFast<DWORD>(vecTargetPos, dwPointerToVector);
if (data->m_shotSyncData.m_bUseOrigin)
*origin = data->m_shotSyncData.m_vecShotOrigin;
}
// If current weapon has bullet sync enabled, don't allow firing
return bDoBulletTraceHere;
}
}
else
{
// local ped firing
LocalShotSyncData.m_vecShotOrigin = *origin;
}
// Allow shot to be fired here
return true;
}
void Event_PostFire(void)
{
CPed* pTargetingPed = m_pools->GetPed((DWORD*)pShootingPed);
if (m_pPostWeaponFireHandler)
{
m_pPostWeaponFireHandler();
}
bWeaponFire = false;
}
static void Event_BulletImpact(void)
{
if (m_pBulletImpactHandler)
{
CPed* pInitiator = m_pools->GetPed((DWORD*)pBulletImpactInitiator);
if (pInitiator)
{
CEntity* pVictim = m_pools->GetEntity((DWORD*)pBulletImpactVictim);
if (IsLocalPlayer(pInitiator))
{
// Correct weapon range if local player
float fRange = pInitiator->GetCurrentWeaponRange();
CVector vecDir = *pBulletImpactEndPosition - *pBulletImpactStartPosition;
float fLength = vecDir.Length();
if (fRange < fLength)
{
vecDir.Normalize();
*pBulletImpactEndPosition = *pBulletImpactStartPosition + vecDir * fRange;
}
// These two will be the same when shooting without aiming, so correct them
if (vecLastLocalPlayerBulletStart == vecLastLocalPlayerBulletEnd)
{
vecLastLocalPlayerBulletStart = *pBulletImpactStartPosition;
vecLastLocalPlayerBulletEnd = *pBulletImpactEndPosition;
}
m_pBulletImpactHandler(pInitiator, pVictim, &vecLastLocalPlayerBulletStart, &vecLastLocalPlayerBulletEnd);
}
else
{
// Correct start postion if remote player
CRemoteDataStorageSA* data = CRemoteDataSA::GetRemoteDataStorage(pBulletImpactInitiator);
if (data)
{
if (data->ProcessPlayerWeapon())
{
if (data->m_shotSyncData.m_bRemoteBulletSyncVectorsValid)
{
*pBulletImpactStartPosition = data->m_shotSyncData.m_vecRemoteBulletSyncStart;
data->m_shotSyncData.m_bRemoteBulletSyncVectorsValid = false;
// Ensure weapon fire event gets the correct vectors
data->m_shotSyncData.m_vecShotOrigin = data->m_shotSyncData.m_vecRemoteBulletSyncStart;
data->m_shotSyncData.m_vecShotTarget = data->m_shotSyncData.m_vecRemoteBulletSyncEnd;
}
else
*pBulletImpactStartPosition = data->m_shotSyncData.m_vecShotOrigin;
}
}
m_pBulletImpactHandler(pInitiator, pVictim, pBulletImpactStartPosition, pBulletImpactEndPosition);
}
}
vecSavedBulletImpactEndPosition = *pBulletImpactEndPosition; // Saved for vehicle damage event parameters
}
}
CPedSAInterface* pAPed = NULL;
float fTempPosX = 0, fTempPosY = 0, fTempPosZ = 0;
CPed* pATargetingPed = NULL;
CVector* pTempVec;
bool* pSkipAim;
CRemoteDataStorageSA* pTempRemote;
VOID _declspec(naked) HOOK_CTaskSimpleUsegun_ProcessPed()
{
// We can use EAX
_asm
{
// Store the ped pointer for our later hook (SkipAim)
mov eax, [esp+4]
mov pAPed, eax
// Replace original code
push 0FFFFFFFFh
mov eax,dword ptr fs:[00000000h]
// Jump back to func. I think we can use EDX here
mov edx, HOOKPOS_CTaskSimpleUsegun_ProcessPed
add edx, 8
jmp edx
}
}
VOID _declspec(naked) HOOK_SkipAim()
{
// We can use ECX
// Return to 0x62AEED for normal aiming
// Return to 0x62A565 for arms up. Should probably set [esi+0Eh] to 1 too.
_asm
{
// Store the pointer to the skipaim argument
mov ecx, esi
add ecx, 0Eh
mov pSkipAim, ecx
// Store all the registers
pushad
}
// Grab the player for this interface
pATargetingPed = m_pools->GetPed((DWORD*)pAPed);
if (pATargetingPed)
{
// If this is the local player
if (IsLocalPlayer(pATargetingPed))
{
// Store wheter he's aiming up or not
pMultiplayer->m_bAkimboTargetUp = *pSkipAim;
}
else
{
// Grab his remote storage
pTempRemote = CRemoteDataSA::GetRemoteDataStorage(
pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed
if (pTempRemote)
{
if (pTempRemote->ProcessPlayerWeapon())
{
// If this is remote player, use the data in his remote storage
*pSkipAim = pTempRemote->m_bAkimboTargetUp;
}
}
else
*pSkipAim = false;
}
}
// Return to the correct place wheter we put our arms up or not
if (*pSkipAim)
{
_asm
{
// Restore all registers
popad
// Return to 0x62A565 (arms up)
mov ecx, 0x62A565
jmp ecx
}
}
else
{
_asm
{
// Restore all registers
popad
// Return to 0x62AEED (normal aim)
mov ecx, 0x62AEED
jmp ecx
}
}
}
float* pTargetVector;
VOID _declspec(naked) HOOK_IKChainManager_PointArm()
{
// We can use edx
_asm
{
// Grab the ped whose aiming the gun and the pointer to the vector we aim at
mov edx, [esp+24]
mov pTargetVector, edx
mov edx, [esp+12]
mov pAPed, edx
// Store all the registers on the stack
pushad
}
// Grab the player for this interface
pATargetingPed = m_pools->GetPed((DWORD*)pAPed);
if (pATargetingPed)
{
// If this is the local player
if (IsLocalPlayer(pATargetingPed))
{
// Store the position his aiming at
pMultiplayer->m_vecAkimboTarget.fX = pTargetVector[0];
pMultiplayer->m_vecAkimboTarget.fY = pTargetVector[1];
pMultiplayer->m_vecAkimboTarget.fZ = pTargetVector[2];
}
else
{
// Grab his remote storage
pTempRemote = CRemoteDataSA::GetRemoteDataStorage(
pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed
if (pTempRemote)
{
if (pTempRemote->ProcessPlayerWeapon())
{
// If this is remote player, use the data in his remote storage to point his aim position
pTargetVector[0] = pTempRemote->m_vecAkimboTarget.fX;
pTargetVector[1] = pTempRemote->m_vecAkimboTarget.fY;
pTargetVector[2] = pTempRemote->m_vecAkimboTarget.fZ;
}
}
}
}
_asm
{
// Restore all the registers from the stack
popad
// Run the instructions we replaced when this hook was added
push 0FFFFFFFFh
push 83F0D6h
// Continue execution where we intercepted
mov edx, HOOKPOS_IKChainManager_PointArm
add edx, 7
jmp edx
}
}
VOID _declspec(naked) HOOK_IKChainManager_LookAt()
{
// We can use eax
_asm
{
// Grab the player ped and the vector pointer from the stack
mov eax, [esp+24]
mov pTargetVector, eax
mov eax, [esp+8]
mov pAPed, eax
// Store all the registers on the stack
pushad
}
// Jax: this gets called on vehicle collision and pTargetVector is null
if (pTargetVector)
{
// Grab the player for this interface
pATargetingPed = m_pools->GetPed((DWORD*)pAPed);
if (pATargetingPed)
{
// If this is the local player
if (IsLocalPlayer(pATargetingPed))
{
// Store the position his aiming at
pMultiplayer->m_vecAkimboTarget.fX = pTargetVector[0];
pMultiplayer->m_vecAkimboTarget.fY = pTargetVector[1];
pMultiplayer->m_vecAkimboTarget.fZ = pTargetVector[2];
}
else
{
// Grab his remote storage
pTempRemote = CRemoteDataSA::GetRemoteDataStorage(
pAPed); // TODO: Can be optimized further by using the PlayerPed class. Not sure how to convert CPed to CPlayerPed
if (pTempRemote)
{
if (pTempRemote->ProcessPlayerWeapon())
{
// If this is remote player, use the data in his remote storage to point his aim position
pTargetVector[0] = pTempRemote->m_vecAkimboTarget.fX;
pTargetVector[1] = pTempRemote->m_vecAkimboTarget.fY;
pTargetVector[2] = pTempRemote->m_vecAkimboTarget.fZ;
}
}
}
}
}
_asm
{
// Restore all the registers from the stack
popad
// Run the instructions we replaced when this hook was added
push 0FFFFFFFFh
push 83F0B6h
// Continue execution where we intercepted
mov edx, HOOKPOS_IKChainManager_LookAt
add edx, 7
jmp edx
}
}
VOID _declspec(naked) HOOK_CWeapon__Fire()
{
_asm
{
push ebx
mov ebx, esp
add ebx, 0x18
mov vecTargetPosition, ebx
mov ebx, esp
add ebx, 0xC
mov ebx, [ebx]
mov vecOrigin, ebx
mov ebx, [esp+8]
mov pShootingPed, ebx
pop ebx
pushad
}
// Weapon inaccuracy and animations problems may be fixed by blanking out the CWeapon variables nTimer and beyond.
bWeaponFire = true;
if (!WriteTargetDataForPed(pShootingPed, vecTargetPosition, vecOrigin))
{
// Don't fire shot
_asm
{
popad
mov al, 1
retn 18h
}
}
_asm
{
popad
sub esp, 0x3c
push ebx
push esi
push edi
}
_asm
{
mov esi, HOOKPOS_CWeapon__Fire
add esi, 6
jmp esi
}
}
VOID _declspec(naked) HOOK_CWeapon__PostFire()
{
_asm
{
pushad
}
Event_PostFire();
_asm
{
popad
pop edi
pop esi
pop ebx
add esp, 3Ch
ret 18h
}
}
VOID _declspec(naked) HOOK_CWeapon__PostFire2() // handles the FALSE exit point at 0x074241E
{
_asm
{
pushad
}
Event_PostFire();
_asm
{
popad
add esp, 3Ch
ret 18h
}
}
static const DWORD CWeapon_DoBulletImpact_RET = 0x73B557;
void _declspec(naked) HOOK_CWeapon_DoBulletImpact()
{
_asm
{
mov eax, [esp+4]
mov pBulletImpactInitiator, eax
mov eax, [esp+8]
mov pBulletImpactVictim, eax
mov eax, [esp+12]
mov pBulletImpactStartPosition, eax
mov eax, [esp+16]
mov pBulletImpactEndPosition, eax
pushad
}
Event_BulletImpact();
_asm
{
popad
push 0xFFFFFFFF
push 0x00848E50
jmp CWeapon_DoBulletImpact_RET
}
}
VOID _declspec(naked) HOOK_CTaskSimpleGangDriveBy__PlayerTarget()
{
// Replacement code
_asm
{
mov cTempGunDirection, al
mov pPedInterfaceTemp, edi
pushad
}
// either store or change the data
WriteGunDirectionDataForPed(pPedInterfaceTemp, 0, 0, &cTempGunDirection);
// cTempGunDirection may be modified by the function, so write it back
_asm
{
popad
movsx eax, cTempGunDirection
mov edx, HOOKPOS_CTaskSimpleGangDriveBy__PlayerTarget
add edx, 6
cmp eax, 3 // have to do this down here or it doesn't work
jmp edx
}
}
VOID _declspec(naked) HOOK_CPedIK__PointGunInDirection()
{
_asm
{
mov pPedIKInterface, ecx
mov edx, esp
add edx, 4
mov fDirectionX, edx
add edx, 4
mov fDirectionY, edx
pushad
}
// either store or change the data
WriteGunDirectionDataForPed((CPedSAInterface*)((DWORD)pPedIKInterface - 1292), fDirectionX, fDirectionY, 0);
// replacement code
_asm
{
popad
sub esp, 0x10
push ebx
push ebp
mov ebp, ecx
// Let the hooked func resume
mov edx, HOOKPOS_CPedIK__PointGunInDirection
add edx, 7
jmp edx
}
}
// This hook prevents remote players always hitting local players if both players are targeting with sniper.
// This was because it then used the FireSniper mode rather than FireInstantHit so it appeared that the local
// player was shooting himself!
void _declspec(naked) HOOK_CWeapon__Fire_Sniper()
{
/*
007424A6 8B4424 14 MOV EAX,DWORD PTR SS:[ESP+14]
007424AA 85C0 TEST EAX,EAX
*/
_asm
{
mov pPedInterfaceTemp, edi
pushad
}
if (IsLocalPlayer(pPedInterfaceTemp))
{
// use sniper (local players)
_asm
{
popad
mov ecx, HOOKPOS_CWeapon__Fire_Sniper
add ecx, 6
mov eax, dword ptr [esp+0x14]
test eax, eax
jmp ecx
}
}
else
{
// use instanthit (remote players)
_asm
{
popad
mov ecx, HOOKRET_CWeapon__Fire_Sniper
jmp ecx
}
}
}
bool ProcessDamageEvent(CEventDamageSAInterface* event, CPedSAInterface* affectsPed)
{
if (m_pDamageHandler && event)
{
CPoolsSA* pPools = (CPoolsSA*)pGameInterface->GetPools();
CPed* pPed = pPools->GetPed((DWORD*)affectsPed);
CEntity* pInflictor = NULL;
if (pPed)
{
// This creates a CEventDamageSA for us
CEventDamage* pEvent = pGameInterface->GetEventList()->GetEventDamage(event);
pEvent->SetDamageReason(g_GenerateDamageEventReason);
// Call the event
bool bReturn = m_pDamageHandler(pPed, pEvent);
// Destroy the CEventDamageSA (so we dont get a leak)
pEvent->Destroy();
// Finally, return
return bReturn;
}
}
return true;
}
CPedSAInterface* affectsPed = 0;
CEventDamageSAInterface* event = 0;
void _declspec(naked) HOOK_CEventDamage__AffectsPed()
{
/*
004B35A0 83EC 0C SUB ESP,0C
004B35A3 56 PUSH ESI
004B35A4 8BF1 MOV ESI,ECX
*/
_asm
{
push esi
mov esi, [esp+8]
mov affectsPed, esi // store the ped
mov event, ecx // store the event pointer
pop esi
pushad
}
if (ProcessDamageEvent(event, affectsPed))
{
// they want the damage to happen!
_asm
{
popad
sub esp, 0xC // replacement code
push esi
mov esi, ecx
mov ecx, HOOKPOS_CEventDamage__AffectsPed
add ecx, 6
jmp ecx
}
}
else
{
// they want the player to escape unscathed
_asm
{
popad
xor eax, eax
retn 4 // return from the function
}
}
}
void ProcessStartFire(CFireSAInterface* fire)
{
if (m_pFireHandler)
{
DWORD dwID = ((DWORD)fire - 0xB71F80 /* CLASS_CFireManager */) / 40;
CFire* pFire = pGameInterface->GetFireManager()->GetFire(dwID);
if (pFire)
{
m_pFireHandler(pFire);
}
}
}
CFireSAInterface* tempFire;
DWORD dwStoredReturn;
// CFire* StartFire(CVector vecLocation, float fFireSize=DEFAULT_FIRE_PARTICLE_SIZE, bool8 bExtinguishEnabled=TRUE, CEntity* pStartedFireEntity = NULL, UInt32
// ArgBurnTime = FIRE_AVERAGE_BURNTIME, Int8 NumGenerationsAllowed = 100, Bool8 bReportFire = true);
void _declspec(naked) HOOK_CFireManager__StartFire()
{
// replacement code
_asm
{
mov edx, [esp]
mov dwStoredReturn, edx
mov edx, returnHere
mov [esp], edx
push ecx
push ebp
mov ebp, [esp+0x10]
mov edx, HOOKPOS_CFireManager__StartFire
add edx, 6
jmp edx
returnHere:
mov tempFire, eax
pushad
}
ProcessStartFire(tempFire);
_asm
{
popad
mov eax, tempFire
mov edx, dwStoredReturn
jmp edx
}
}
// CFire* StartFire(CEntity *pBurningEntity, CEntity *pStartedFireEntity, float fFireSize=DEFAULT_FIRE_PARTICLE_SIZE, bool8 bExtinguishEnabled=TRUE, UInt32
// ArgBurnTime = FIRE_AVERAGE_BURNTIME, Int8 NumGenerationsAllowed = 100);
void _declspec(naked) HOOK_CFireManager__StartFire_()
{
_asm
{
// replacement code
mov edx, [esp]
mov dwStoredReturn, edx
mov edx, returnHere
mov [esp], edx
push esi
push edi
mov edi, [esp+0xC]
//
mov edx, HOOKPOS_CFireManager__StartFire_
add edx, 6
jmp edx
returnHere:
mov tempFire, eax
pushad
}
ProcessStartFire(tempFire);
_asm
{
popad
mov eax, tempFire
jmp dwStoredReturn
}
}
bool ProcessProjectileAdd()
{
if (m_pProjectileStopHandler)
{
CPools* pPools = pGameInterface->GetPools();
CEntity* pOwner = NULL;
if (pProjectileOwner)
{
switch (pProjectileOwner->nType)
{
case ENTITY_TYPE_VEHICLE:
pOwner = pPools->GetVehicle((DWORD*)pProjectileOwner);
break;
case ENTITY_TYPE_PED:
pOwner = pPools->GetPed((DWORD*)pProjectileOwner);
break;
case ENTITY_TYPE_OBJECT:
// pPools->GetObject ( (DWORD *)event->inflictor );
default:
pOwner = NULL;
}
}
if (projectileTargetEntityInterface)
{
switch (projectileTargetEntityInterface->nType)
{
case ENTITY_TYPE_VEHICLE:
projectileTargetEntity = pPools->GetVehicle((DWORD*)projectileTargetEntityInterface);
break;
case ENTITY_TYPE_PED:
projectileTargetEntity = pPools->GetPed((DWORD*)projectileTargetEntityInterface);
break;
case ENTITY_TYPE_OBJECT:
// pPools->GetObject ( (DWORD *)event->inflictor );
default:
projectileTargetEntity = NULL;
}
}
return m_pProjectileStopHandler(pOwner, projectileWeaponType, projectileOrigin, projectileForce, projectileTarget, projectileTargetEntity);
}
return true;
}
void ProcessProjectile()
{
if (m_pProjectileHandler != NULL)
{
CPoolsSA* pPools = (CPoolsSA*)pGameInterface->GetPools();
CEntity* pOwner = NULL;
if (pProjectileOwner)
{
switch (pProjectileOwner->nType)
{
case ENTITY_TYPE_VEHICLE:
pOwner = pPools->GetVehicle((DWORD*)pProjectileOwner);
break;
case ENTITY_TYPE_PED:
pOwner = pPools->GetPed((DWORD*)pProjectileOwner);
break;
case ENTITY_TYPE_OBJECT:
// pPools->GetObject ( (DWORD *)event->inflictor );
default:
pOwner = NULL;
}
}
CProjectileInfo* projectileInfo = pGameInterface->GetProjectileInfo()->GetProjectileInfo(dwProjectileInfoIndex);
CProjectile* projectile = pGameInterface->GetProjectileInfo()->GetProjectile(pProjectile);
projectile->SetProjectileInfo(projectileInfo);
m_pProjectileHandler(pOwner, projectile, projectileInfo, projectileWeaponType, projectileOrigin, projectileForce, projectileTarget,
projectileTargetEntity);
projectileTargetEntity = NULL;
}
}
// CProjectileInfo::AddProjectile(class CEntity * owner,enum eWeaponType weapon type
// ,class CVector origin?,float 0?,class CVector * direction,class CEntity * target)
void _declspec(naked) HOOK_CProjectileInfo__AddProjectile()
{
_asm
{
mov edx, [esp+4]
mov pProjectileOwner, edx
mov edx, [esp+8]
mov projectileWeaponType, edx
lea edx, [esp+12]
mov projectileOrigin, edx
mov edx, [esp+24]
mov projectileForce, edx
mov edx, [esp+28]
mov projectileTarget, edx
mov edx, [esp+32]
mov projectileTargetEntityInterface, edx
pushad
}
if (ProcessProjectileAdd())
{ // projectile should be created
_asm
{
popad
push 0xFFFFFFFF
mov edx, RETURN_CProjectile__AddProjectile
jmp edx
}
}
else
{
_asm
{
popad
xor al, al
retn
}
}
}
void _declspec(naked) HOOK_CProjectile__CProjectile()
{
_asm
{
mov dwProjectileInfoIndex, ebx // it happens to be in here, luckily
mov pProjectile, ecx
pushad
}
ProcessProjectile();
_asm
{
popad
push 0xFFFFFFFF
mov edx, RETURN_CProjectile__CProjectile
jmp edx
}
}
static void CheckInVehicleDamage()
{
CPlayerPed* pPed = dynamic_cast<CPlayerPed*>(m_pools->GetPed((DWORD*)pShootingPed));
if (pPed && !IsLocalPlayer(pPed))
{
// Did he hit a vehicle?
if (*ppInstantHitEntity && (*ppInstantHitEntity)->nType == ENTITY_TYPE_VEHICLE)
{
// Lets do a windscreen shooting check
CWeapon* pWeapon = pPed->GetWeapon(pPed->GetCurrentWeaponSlot());
if (pWeapon)
{
eWeaponType weaponType = pWeapon->GetType();
DWORD dwFunc = FUNC_CWeapon_CheckForShootingVehicleOccupant;
_asm
{
push pInstantHitStart
push pInstantHitEnd
push weaponType
push ppInstantHitColPoint
push ppInstantHitEntity
call dwFunc
add esp, 0x14
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// CWeapon_FireInstantHit_Mid
//
// Called when the local player fires a bullet
// If using bullet sync, send the bullet vectors to the other players
//
//////////////////////////////////////////////////////////////////////////////////////////
void OnMy_CWeapon_FireInstantHit_Mid(CEntitySAInterface* pEntity, CVector* pvecNonAimedStart, CVector* pvecAimedStart, CVector* pvecEnd, bool bFlag)
{
CPed* pTargetingPed = m_pools->GetPed((DWORD*)pEntity);
if (IsLocalPlayer(pTargetingPed))
{
CVector vecEnd = *pvecEnd;
CVector vecStart = *pvecAimedStart;
CVector vecDif = vecEnd - vecStart;
vecDif.fZ = 0;
float fLength2D = vecDif.LengthSquared();
if (fLength2D < 0.0001f)
vecStart = *pvecNonAimedStart;
// Trim end point to weapon range
float fRange = pTargetingPed->GetCurrentWeaponRange();
CVector vecDir = vecEnd - vecStart;
float fLength = vecDir.Length();
if (fRange < fLength)
{
vecDir.Normalize();
vecEnd = vecStart + vecDir * fRange;
}
// Save these for BulletImpact
vecLastLocalPlayerBulletStart = vecStart;
vecLastLocalPlayerBulletEnd = vecEnd;
if (m_pBulletFireHandler)
m_pBulletFireHandler(pTargetingPed, &vecStart, &vecEnd);
}
}
// Hook info
#define HOOKPOS_CWeapon_FireInstantHit_Mid 0x740B89
#define HOOKSIZE_CWeapon_FireInstantHit_Mid 5
DWORD RETURN_CWeapon_FireInstantHit_Mid = 0x740B8E;
void _declspec(naked) HOOK_CWeapon_FireInstantHit_Mid()
{
_asm
{
pushad
mov ecx, esp
add ecx, 20h
push eax // flag
mov edx, ecx
add edx, 10h // end
push edx
mov edx, ecx
add edx, 38h // aimed start
push edx
mov edx, ecx
add edx, 78h // non aimed start
push edx
push edi
call OnMy_CWeapon_FireInstantHit_Mid
add esp, 4*5
popad
// Do original code and continue
mov ecx,dword ptr [esp+14h]
push eax
jmp RETURN_CWeapon_FireInstantHit_Mid
}
}
// Hook install
VOID InitFireInstantHit_MidHooks()
{
HookInstall(HOOKPOS_CWeapon_FireInstantHit_Mid, (DWORD)HOOK_CWeapon_FireInstantHit_Mid, HOOKSIZE_CWeapon_FireInstantHit_Mid);
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// CWeapon_FireSniper_Mid
//
// Called when the local player fires a sniper bullet
// If using bullet sync, send the bullet vectors to the other players
//
//////////////////////////////////////////////////////////////////////////////////////////
void OnMy_CWeapon_FireSniper_Mid(CEntitySAInterface* pEntity, CVector* pvecEndHit, CVector* pvecEndMaxRange, CVector* pvecStart, CVector* pvecDir)
{
CPed* pTargetingPed = m_pools->GetPed((DWORD*)pEntity);
if (IsLocalPlayer(pTargetingPed))
{
CVector vecEnd = *pvecEndMaxRange;
CVector vecStart = *pvecStart;
// Trim end point to weapon range
float fRange = pTargetingPed->GetCurrentWeaponRange();
CVector vecDir = vecEnd - vecStart;
float fLength = vecDir.Length();
if (fRange < fLength)
{
vecDir.Normalize();
vecEnd = vecStart + vecDir * fRange;
}
// Save these for BulletImpact
vecLastLocalPlayerBulletStart = vecStart;
vecLastLocalPlayerBulletEnd = vecEnd;
if (m_pBulletFireHandler)
m_pBulletFireHandler(pTargetingPed, &vecStart, &vecEnd);
}
}
// Hook info
#define HOOKPOS_CWeapon_FireSniper_Mid 0x73AE31
#define HOOKSIZE_CWeapon_FireSniper_Mid 5
DWORD RETURN_CWeapon_FireSniper_Mid = 0x73AE39;
void _declspec(naked) HOOK_CWeapon_FireSniper_Mid()
{
_asm
{
// Do original code
fstp dword ptr [esp+4Ch]
fstp dword ptr [esp+50h]
pushad
mov ecx, esp
add ecx, 20h
mov edx, ecx
add edx, 20h // dir
push edx
mov edx, ecx
add edx, 2Ch // start
push edx
mov edx, ecx
add edx, 3Ch // max range end
push edx
mov edx, ecx
add edx, 48h // hit end
push edx
push esi // Ped
call OnMy_CWeapon_FireSniper_Mid
add esp, 4*5
popad
// Continue
jmp RETURN_CWeapon_FireSniper_Mid
}
}
// Hook install
VOID InitFireSniper_MidHooks()
{
HookInstall(HOOKPOS_CWeapon_FireSniper_Mid, (DWORD)HOOK_CWeapon_FireSniper_Mid, HOOKSIZE_CWeapon_FireSniper_Mid);
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// HandleRemoteInstantHit
//
// Called when a remote player fires a bullet
//
//////////////////////////////////////////////////////////////////////////////////////////
void HandleRemoteInstantHit(void)
{
CPed* pTargetingPed = m_pools->GetPed((DWORD*)pShootingPed);
CPlayerPed* pTargetingPlayerPed = dynamic_cast<CPlayerPed*>(pTargetingPed);
if (!pTargetingPlayerPed)
return;
if (!IsLocalPlayer(pTargetingPed))
{
CRemoteDataStorageSA* data = CRemoteDataSA::GetRemoteDataStorage(pTargetingPlayerPed);
if (data)
{
if (data->ProcessPlayerWeapon())
{
// Replace start and end vectors if we have any bullet sync information
if (data->m_shotSyncData.m_bRemoteBulletSyncVectorsValid)
{
*pInstantHitStart = data->m_shotSyncData.m_vecRemoteBulletSyncStart;
*pInstantHitEnd = data->m_shotSyncData.m_vecRemoteBulletSyncEnd;
}
}
}
}
}
void _cdecl DoFireInstantHitPokes(void)
{
MemPutFast<unsigned char>(VAR_CWorld_IncludeCarTyres, 1);
}
DWORD dwFunc_CWeapon_FireInstantHit_ret = 0x740B6E;
DWORD dwFunc_CWorld_ProcessLineOfSight = 0x56BA00;
void _declspec(naked) HOOK_CWeapon_FireInstantHit()
{
/* CWeapon::FireInstantHit->CWorld::ProcessLineOfSight
00740B42 push 1
00740B44 push 0
00740B46 push 0
00740B48 push 1
00740B4A push 1
00740B4C push 1
00740B4E push 1
00740B50 push 1
00740B52 lea eax,[esp+58h]
00740B56 push eax
00740B57 lea ecx,[esp+0C4h]
00740B5E push ecx
00740B5F lea edx,[esp+48h]
00740B63 lea eax,[esp+64h]
00740B67 push edx
00740B68 push eax
00740B69 call 0056BA00
*/
_asm
{
push 1
push 0
push 0
push 1
push 1
push 1
push 1
push 1
lea eax,[esp+58h]
mov ppInstantHitEntity, eax
push eax
lea ecx,[esp+0C4h]
mov ppInstantHitColPoint, ecx
push ecx
lea edx,[esp+48h]
mov pInstantHitEnd, edx
lea eax,[esp+64h]
mov pInstantHitStart, eax
push edx
push eax
pushad
}
// Make sure we include car tyres in our ProcessLineOfSight check
_asm
{
call DoFireInstantHitPokes
}
HandleRemoteInstantHit();
_asm
{
popad
call dwFunc_CWorld_ProcessLineOfSight
pushad
}
CheckInVehicleDamage();
_asm
{
popad
jmp dwFunc_CWeapon_FireInstantHit_ret
}
}
bool FireInstantHit_CameraMode()
{
CPlayerPed* pPed = dynamic_cast<CPlayerPed*>(m_pools->GetPed((DWORD*)pShootingPed));
if (pPed && !IsLocalPlayer(pPed))
{
// Are we onfoot?
if (!pPed->GetVehicle())
{
return true;
}
}
return false;
}
DWORD dwFunc_CWeapon_FireInstantHit_CameraMode_ret = 0x7403C7;
DWORD dwAddr_FireInstantHit_CameraMode = 0x740389;
DWORD dwAddr_FireInstantHit_CameraMode_2 = 0x740373;
short sFireInstantHit_CameraMode_camMode = 0;
void _declspec(naked) HOOK_CWeapon_FireInstantHit_CameraMode()
{
/* CWeapon::FireInstantHit->'CameraMode switch'
0074036D cmp ax,35h (53) ** <hook>
00740371 je 00740389 ** <hook>
00740373 cmp ax,37h (55)
00740377 je 00740389
00740379 cmp ax,41h (65)
0074037D je 00740389
0074037F cmp ax,31h (39)
00740383 jne 007407C1
*/
_asm
{
mov sFireInstantHit_CameraMode_camMode, ax
pushad
}
if (FireInstantHit_CameraMode())
{
_asm
{
popad
jmp dwAddr_FireInstantHit_CameraMode
}
}
else
{
if (sFireInstantHit_CameraMode_camMode == 0x35)
{
_asm
{
popad
jmp dwAddr_FireInstantHit_CameraMode
}
}
else
{
_asm
{
popad
jmp dwAddr_FireInstantHit_CameraMode_2
}
}
}
}
CPedSAInterface* pFireInstantHit_IsPlayerPed = NULL;
bool FireInstantHit_IsPlayer()
{
CPlayerPed* pPed = dynamic_cast<CPlayerPed*>(m_pools->GetPed((DWORD*)pFireInstantHit_IsPlayerPed));
if (pPed)
{
if (IsLocalPlayer(pPed))
return true;
CRemoteDataStorageSA* data = CRemoteDataSA::GetRemoteDataStorage(pPed);
if (data)
{
if (data->ProcessPlayerWeapon())
{
return true;
}
}
}
return false;
}
DWORD RETURN_CWeapon_FireInstantHit_IsPlayer = 0x740353;
DWORD FUNC_CPlayer_IsPed = 0x5DF8F0;
void _declspec(naked) HOOK_CWeapon_FireInstantHit_IsPlayer()
{
/*
0074034C call 005DF8F0 <hook>
00740351 test al,al <hook>
00740353 je 007407C1 <return>
*/
/*
00740C3D call 005DF8F0
00740C42 mov eax,dword ptr [esp+1BCh]
00740C49 mov ecx,dword ptr [eax]
00740E66 call 005DF8F0
00740E6B test al,al
00740E6D je 00740E7E
*/
_asm
{
mov pFireInstantHit_IsPlayerPed, ecx
pushad
}
if (!FireInstantHit_IsPlayer())
{
_asm
{
popad
xor al, al
test al, al
jmp RETURN_CWeapon_FireInstantHit_IsPlayer
}
}
else
{
_asm
{
popad
call FUNC_CPlayer_IsPed
test al,al
jmp RETURN_CWeapon_FireInstantHit_IsPlayer
}
}
}
#if false
VOID _declspec(naked) HOOK_CCamera__Find3rdPersonCamTargetVector()
{
/*
0046FB36 |. 5D POP EBP
0046FB37 |. 5E POP ESI
0046FB38 |. 5B POP EBX
0046FB39 \. C2 1800 RETN 18
*/
_asm
{
mov ebp, esp
add ebp, 0x14
mov vecShotOrigin, ebp
add ebp, 0xC
mov esi, [ebp]
mov vecStartVector, esi
add ebp, 4
mov esi, [ebp]
mov vecTargetVector, esi
pushad
}
if(IsNotInLocalContext() && GetContextSwitchPedID())
{
// its a remote player, so replace the data with the net data
sprintf(szDebug, "Switched Target Vectors to %f %f %f",
RemotePlayerTargetVectors[GetContextSwitchPedID()].fX,
RemotePlayerTargetVectors[GetContextSwitchPedID()].fY,
RemotePlayerTargetVectors[GetContextSwitchPedID()].fZ);
OutputDebugString(szDebug);
sprintf(szDebug, "Switched Start Vectors to %f %f %f",
RemotePlayerStartVectors[GetContextSwitchPedID()].fX,
RemotePlayerStartVectors[GetContextSwitchPedID()].fY,
RemotePlayerStartVectors[GetContextSwitchPedID()].fZ);
OutputDebugString(szDebug);
MemCpy (vecTargetVector, &RemotePlayerTargetVectors[GetContextSwitchPedID()], sizeof(CVector));
MemCpy (vecStartVector, &RemotePlayerStartVectors[GetContextSwitchPedID()], sizeof(CVector));
}
else
{
// Its the Local Player, so save the data so it can be sent
MemCpy (&LocalPlayerShotOriginVector, vecShotOrigin, sizeof(CVector));
sprintf(szDebug, "Saved Local Shot Origin Vector %f %f %f",
LocalPlayerShotOriginVector.fX,
LocalPlayerShotOriginVector.fY,
LocalPlayerShotOriginVector.fZ);
OutputDebugString(szDebug);*/
/* MemCpy (&LocalPlayerTargetVector, vecTargetVector, sizeof(CVector));
MemCpy (&LocalPlayerStartVector, vecStartVector, sizeof(CVector));
sprintf(szDebug, "Saved Local Target Vectors %f %f %f",
LocalPlayerTargetVector.fX,
LocalPlayerTargetVector.fY,
LocalPlayerTargetVector.fZ);
OutputDebugString(szDebug);
sprintf(szDebug, "Saved Local Start Vectors %f %f %f",
LocalPlayerStartVector.fX,
LocalPlayerStartVector.fY,
LocalPlayerStartVector.fZ);
OutputDebugString(szDebug);*/
}
_asm
{
popad
pop ebp
pop esi
pop ebx
retn 0x18
}
}
VOID _declspec(naked) HOOK_CWeapon__FireShotgun()
{
// this is used to store and replace the CrossProduct
/*
005CDA99 . 50 PUSH EAX
005CDA9A . 8D8424 C4010000 LEA EAX,DWORD PTR SS:[ESP+1C4]
005CDAA1 . 51 PUSH ECX
005CDAA2 . 50 PUSH EAX
005CDAA3 . E8 0826F1FF CALL gta-vc.004E00B0
005CDAA8 . 89D8 MOV EAX,EBX
005CDAAA . 83C4 0C ADD ESP,0C
*/
_asm
{
pushad
}
if(IsNotInLocalContext() && GetContextSwitchPedID())
{
_asm
{
popad
push eax
lea eax, dword ptr [esp+0x1C4]
mov vecCrossProduct, eax
pop eax
pushad
}
sprintf(szDebug, "Switched Cross Products to %f %f %f (0x%X)",
RemotePlayerCrossProducts[GetContextSwitchPedID()].fX,
RemotePlayerCrossProducts[GetContextSwitchPedID()].fY,
RemotePlayerCrossProducts[GetContextSwitchPedID()].fZ, vecCrossProduct);
OutputDebugString(szDebug);
MemSet (vecCrossProduct,0,sizeof(CVector));
// MemCpy (vecCrossProduct, &RemotePlayerCrossProducts[GetContextSwitchPedID()], sizeof(CVector));
}
else
{
_asm
{
popad
push eax
lea eax, dword ptr [esp+0x1C4]
mov vecCrossProduct, eax
push ecx
push eax
mov eax, FUNC_CrossProduct
call eax
mov eax, ebx
add esp, 0xC
pushad
}
MemCpy (&LocalPlayerCrossProduct, vecCrossProduct, sizeof(CVector));
sprintf(szDebug, "SHOTGUN: Saved Local Cross Product %f %f %f",
LocalPlayerCrossProduct.fX,
LocalPlayerCrossProduct.fY,
LocalPlayerCrossProduct.fZ);
OutputDebugString(szDebug);
}
_asm
{
popad
mov edx, HOOKPOS_CWeapon__FireShotgun
add edx, 20
jmp edx
}
}
#endif
CPedSAInterface* CEventVehicleExplosion_pPed;
void CEventVehicleExplosion_NotifyDeathmatch()
{
if (m_pDeathHandler)
{
CPoolsSA* pPools = (CPoolsSA*)pGameInterface->GetPools();
CPed* pPed = pPools->GetPed((DWORD*)CEventVehicleExplosion_pPed);
if (pPed)
m_pDeathHandler(pPed, 63, 3);
}
}
void _declspec(naked) HOOK_CEventVehicleExplosion__AffectsPed()
{
_asm
{
// Save the ped
mov CEventVehicleExplosion_pPed, edi
// Replacement code for the hook
pop edi
setz al
pop esi
// Verify that the ped is affected
cmp al, 1
jnz return_from
// Verify that this call is from the correct location
cmp [esp], 0x4ab4c4
jnz return_from
pushad
}
// Notify Deathmatch about the death
CEventVehicleExplosion_NotifyDeathmatch();
_asm
{
popad
return_from:
retn 4
}
}
|
lex128/mtasa-blue
|
Client/multiplayer_sa/multiplayer_shotsync.cpp
|
C++
|
gpl-3.0
| 50,481
|
<?php
/**
* This file is a part of MyWebSQL package
* defines authentication mechanism for the application
*
* @file: config/auth.php
* @author Samnan ur Rehman
* @copyright (c) 2008-2012 Samnan ur Rehman
* @web http://mywebsql.net
* @license http://mywebsql.net/license
*
* Notes:
* Changing this file manually might break the application
* or create security issues.
* Please edit only if you know what you are doing !!!
*/
// AUTH_TYPE defines the login/startup behaviour of the application
// NONE = No userid/password is asked for (NOT recommended)
// BASIC = browser requests authentication dialog
// LOGIN = User enters userid and password manually
// CUSTOM = Use a custom authentication scheme (see docs for details)
define('AUTH_TYPE', 'LOGIN');
// avoid sending plain text login info for additional security (disabled for HTTPS automatically)
define('SECURE_LOGIN', TRUE);
// AUTH_SERVER defines the name of mysql server for connections and authenticating users
// if AUTH_TYPE is set to LOGIN and there is no server defined in configuration (config/servers.php),
// then this will be used as default
define('AUTH_SERVER', 'localhost|mysql5');
// other examples
//define('AUTH_SERVER', 'localhost:4040|mysql4');
//define('AUTH_SERVER', 'localhost|mysqli');
//define('AUTH_SERVER', 'c:/sqlitedb/|sqlite');
// for AUTH_TYPE NONE only
// use the following userid and password to connect to mysql server
define('AUTH_LOGIN', 'test');
define('AUTH_PASSWORD', 'test');
?>
|
onyxnz/quartzpos
|
mywebsql/config/auth.php
|
PHP
|
gpl-3.0
| 1,549
|
exports.prefix = '/forms';
//exports.before = function(request, response, next) { next() };
exports.general = function(request, response) {
response.render("forms/general", {
title: "General"
})
};
exports.advanced = function(request, response) {
response.render("forms/advanced", {
title: "Advanced"
})
};
exports.editors = function(request, response) {
response.render("forms/editors", {
title: "Editors"
})
};
|
RamEduard/admin-lte-express
|
server/admin-routes/forms/index.js
|
JavaScript
|
gpl-3.0
| 438
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Automatically generated strings for Moodle 2.3dev installer
*
* Do not edit this file manually! It contains just a subset of strings
* needed during the very first steps of installation. This file was
* generated automatically by export-installer.php (which is part of AMOS
* {@link http://docs.moodle.org/dev/Languages/AMOS}) using the
* list of strings defined in /install/stringnames.txt.
*
* @package installer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['language'] = 'Iaith';
$string['next'] = 'Nesaf';
$string['previous'] = 'Blaenorol';
$string['reload'] = 'Ail-lwytho';
|
jamesballard/moodle
|
install/lang/cy/moodle.php
|
PHP
|
gpl-3.0
| 1,364
|
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 4.7.1
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: support@keenthemes.com
Follow: www.twitter.com/keenthemes
Dribbble: www.dribbble.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
Renew Support: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>Metronic Admin Theme #4 | Scroller Extension</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="Preview page of Metronic Admin Theme #4 for scroller extension demos" name="description" />
<meta content="" name="author" />
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<link href="../assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="../assets/global/css/components-rounded.min.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="../assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<link href="../assets/layouts/layout4/css/layout.min.css" rel="stylesheet" type="text/css" />
<link href="../assets/layouts/layout4/css/themes/default.min.css" rel="stylesheet" type="text/css" id="style_color" />
<link href="../assets/layouts/layout4/css/custom.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME LAYOUT STYLES -->
<link rel="shortcut icon" href="favicon.ico" /> </head>
<!-- END HEAD -->
<body class="page-container-bg-solid page-header-fixed page-sidebar-closed-hide-logo">
<!-- BEGIN HEADER -->
<div class="page-header navbar navbar-fixed-top">
<!-- BEGIN HEADER INNER -->
<div class="page-header-inner ">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../assets/layouts/layout4/img/logo-light.png" alt="logo" class="logo-default" /> </a>
<div class="menu-toggler sidebar-toggler">
<!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header -->
</div>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse"> </a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN PAGE ACTIONS -->
<!-- DOC: Remove "hide" class to enable the page header actions -->
<div class="page-actions">
<div class="btn-group">
<button type="button" class="btn red-haze btn-sm dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="hidden-sm hidden-xs">Actions </span>
<i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;">
<i class="icon-docs"></i> New Post </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-tag"></i> New Comment </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-share"></i> Share </a>
</li>
<li class="divider"> </li>
<li>
<a href="javascript:;">
<i class="icon-flag"></i> Comments
<span class="badge badge-success">4</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-users"></i> Feedbacks
<span class="badge badge-danger">2</span>
</a>
</li>
</ul>
</div>
</div>
<!-- END PAGE ACTIONS -->
<!-- BEGIN PAGE TOP -->
<div class="page-top">
<!-- BEGIN HEADER SEARCH BOX -->
<!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box -->
<form class="search-form" action="page_general_search_2.html" method="GET">
<div class="input-group">
<input type="text" class="form-control input-sm" placeholder="Search..." name="query">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit">
<i class="icon-magnifier"></i>
</a>
</span>
</div>
</form>
<!-- END HEADER SEARCH BOX -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<li class="separator hide"> </li>
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<!-- DOC: Apply "dropdown-hoverable" class after "dropdown" and remove data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to enable hover dropdown mode -->
<!-- DOC: Remove "dropdown-hoverable" and add data-toggle="dropdown" data-hover="dropdown" data-close-others="true" attributes to the below A element with dropdown-toggle class -->
<li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-success"> 7 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>
<span class="bold">12 pending</span> notifications</h3>
<a href="page_user_profile_1.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span> New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span> Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span> Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span> Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span> System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span> Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<li class="separator hide"> </li>
<!-- BEGIN INBOX DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-envelope-open"></i>
<span class="badge badge-danger"> 4 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have
<span class="bold">7 New</span> Messages</h3>
<a href="app_inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="#">
<span class="photo">
<img src="../assets/layouts/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span>
<span class="subject">
<span class="from"> Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<li class="separator hide"> </li>
<!-- BEGIN TODO DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-primary"> 3 </span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have
<span class="bold">12 pending</span> tasks</h3>
<a href="?p=page_todo_2">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">40% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">65% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">98% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">10% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">58% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">85% Complete</span>
</span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100">
<span class="sr-only">38% Complete</span>
</span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-user dropdown-dark">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="username username-hide-on-mobile"> Nick </span>
<!-- DOC: Do not remove below empty space( ) as its purposely used -->
<img alt="" class="img-circle" src="../assets/layouts/layout4/img/avatar9.jpg" /> </a>
<ul class="dropdown-menu dropdown-menu-default">
<li>
<a href="page_user_profile_1.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="app_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="app_inbox.html">
<i class="icon-envelope-open"></i> My Inbox
<span class="badge badge-danger"> 3 </span>
</a>
</li>
<li>
<a href="app_todo_2.html">
<i class="icon-rocket"></i> My Tasks
<span class="badge badge-success"> 7 </span>
</a>
</li>
<li class="divider"> </li>
<li>
<a href="page_user_lock_1.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="page_user_login_1.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
<!-- BEGIN QUICK SIDEBAR TOGGLER -->
<li class="dropdown dropdown-extended quick-sidebar-toggler">
<span class="sr-only">Toggle Quick Sidebar</span>
<i class="icon-logout"></i>
</li>
<!-- END QUICK SIDEBAR TOGGLER -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
<!-- END PAGE TOP -->
</div>
<!-- END HEADER INNER -->
</div>
<!-- END HEADER -->
<!-- BEGIN HEADER & CONTENT DIVIDER -->
<div class="clearfix"> </div>
<!-- END HEADER & CONTENT DIVIDER -->
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<!-- BEGIN SIDEBAR -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<div class="page-sidebar navbar-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) -->
<!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode -->
<!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Set data-keep-expand="true" to keep the submenues expanded -->
<!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<ul class="page-sidebar-menu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="nav-item start ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item start ">
<a href="index.html" class="nav-link ">
<i class="icon-bar-chart"></i>
<span class="title">Dashboard 1</span>
</a>
</li>
<li class="nav-item start ">
<a href="dashboard_2.html" class="nav-link ">
<i class="icon-bulb"></i>
<span class="title">Dashboard 2</span>
<span class="badge badge-success">1</span>
</a>
</li>
<li class="nav-item start ">
<a href="dashboard_3.html" class="nav-link ">
<i class="icon-graph"></i>
<span class="title">Dashboard 3</span>
<span class="badge badge-danger">5</span>
</a>
</li>
</ul>
</li>
<li class="heading">
<h3 class="uppercase">Features</h3>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-diamond"></i>
<span class="title">UI Features</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="ui_colors.html" class="nav-link ">
<span class="title">Color Library</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_metronic_grid.html" class="nav-link ">
<span class="title">Metronic Grid System</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_general.html" class="nav-link ">
<span class="title">General Components</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_buttons.html" class="nav-link ">
<span class="title">Buttons</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_buttons_spinner.html" class="nav-link ">
<span class="title">Spinner Buttons</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_confirmations.html" class="nav-link ">
<span class="title">Popover Confirmations</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_sweetalert.html" class="nav-link ">
<span class="title">Bootstrap Sweet Alerts</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_icons.html" class="nav-link ">
<span class="title">Font Icons</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_socicons.html" class="nav-link ">
<span class="title">Social Icons</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_typography.html" class="nav-link ">
<span class="title">Typography</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_tabs_accordions_navs.html" class="nav-link ">
<span class="title">Tabs, Accordions & Navs</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_timeline.html" class="nav-link ">
<span class="title">Timeline 1</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_timeline_2.html" class="nav-link ">
<span class="title">Timeline 2</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_timeline_horizontal.html" class="nav-link ">
<span class="title">Horizontal Timeline</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_tree.html" class="nav-link ">
<span class="title">Tree View</span>
</a>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<span class="title">Page Progress Bar</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="ui_page_progress_style_1.html" class="nav-link "> Flash </a>
</li>
<li class="nav-item ">
<a href="ui_page_progress_style_2.html" class="nav-link "> Big Counter </a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="ui_blockui.html" class="nav-link ">
<span class="title">Block UI</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_bootstrap_growl.html" class="nav-link ">
<span class="title">Bootstrap Growl Notifications</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_notific8.html" class="nav-link ">
<span class="title">Notific8 Notifications</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_toastr.html" class="nav-link ">
<span class="title">Toastr Notifications</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_bootbox.html" class="nav-link ">
<span class="title">Bootbox Dialogs</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_alerts_api.html" class="nav-link ">
<span class="title">Metronic Alerts API</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_session_timeout.html" class="nav-link ">
<span class="title">Session Timeout</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_idle_timeout.html" class="nav-link ">
<span class="title">User Idle Timeout</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_modals.html" class="nav-link ">
<span class="title">Modals</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_extended_modals.html" class="nav-link ">
<span class="title">Extended Modals</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_tiles.html" class="nav-link ">
<span class="title">Tiles</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_datepaginator.html" class="nav-link ">
<span class="title">Date Paginator</span>
</a>
</li>
<li class="nav-item ">
<a href="ui_nestable.html" class="nav-link ">
<span class="title">Nestable List</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-puzzle"></i>
<span class="title">Components</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="components_date_time_pickers.html" class="nav-link ">
<span class="title">Date & Time Pickers</span>
</a>
</li>
<li class="nav-item ">
<a href="components_color_pickers.html" class="nav-link ">
<span class="title">Color Pickers</span>
<span class="badge badge-danger">2</span>
</a>
</li>
<li class="nav-item ">
<a href="components_select2.html" class="nav-link ">
<span class="title">Select2 Dropdowns</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_multiselect_dropdown.html" class="nav-link ">
<span class="title">Bootstrap Multiselect Dropdowns</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_select.html" class="nav-link ">
<span class="title">Bootstrap Select</span>
</a>
</li>
<li class="nav-item ">
<a href="components_multi_select.html" class="nav-link ">
<span class="title">Bootstrap Multiple Select</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_select_splitter.html" class="nav-link ">
<span class="title">Select Splitter</span>
</a>
</li>
<li class="nav-item ">
<a href="components_clipboard.html" class="nav-link ">
<span class="title">Clipboard</span>
</a>
</li>
<li class="nav-item ">
<a href="components_typeahead.html" class="nav-link ">
<span class="title">Typeahead Autocomplete</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_tagsinput.html" class="nav-link ">
<span class="title">Bootstrap Tagsinput</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_switch.html" class="nav-link ">
<span class="title">Bootstrap Switch</span>
<span class="badge badge-success">6</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_maxlength.html" class="nav-link ">
<span class="title">Bootstrap Maxlength</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_fileinput.html" class="nav-link ">
<span class="title">Bootstrap File Input</span>
</a>
</li>
<li class="nav-item ">
<a href="components_bootstrap_touchspin.html" class="nav-link ">
<span class="title">Bootstrap Touchspin</span>
</a>
</li>
<li class="nav-item ">
<a href="components_form_tools.html" class="nav-link ">
<span class="title">Form Widgets & Tools</span>
</a>
</li>
<li class="nav-item ">
<a href="components_context_menu.html" class="nav-link ">
<span class="title">Context Menu</span>
</a>
</li>
<li class="nav-item ">
<a href="components_editors.html" class="nav-link ">
<span class="title">Markdown & WYSIWYG Editors</span>
</a>
</li>
<li class="nav-item ">
<a href="components_code_editors.html" class="nav-link ">
<span class="title">Code Editors</span>
</a>
</li>
<li class="nav-item ">
<a href="components_ion_sliders.html" class="nav-link ">
<span class="title">Ion Range Sliders</span>
</a>
</li>
<li class="nav-item ">
<a href="components_noui_sliders.html" class="nav-link ">
<span class="title">NoUI Range Sliders</span>
</a>
</li>
<li class="nav-item ">
<a href="components_knob_dials.html" class="nav-link ">
<span class="title">Knob Circle Dials</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-settings"></i>
<span class="title">Form Stuff</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="form_controls.html" class="nav-link ">
<span class="title">Bootstrap Form
<br>Controls</span>
</a>
</li>
<li class="nav-item ">
<a href="form_controls_md.html" class="nav-link ">
<span class="title">Material Design
<br>Form Controls</span>
</a>
</li>
<li class="nav-item ">
<a href="form_validation.html" class="nav-link ">
<span class="title">Form Validation</span>
</a>
</li>
<li class="nav-item ">
<a href="form_validation_states_md.html" class="nav-link ">
<span class="title">Material Design
<br>Form Validation States</span>
</a>
</li>
<li class="nav-item ">
<a href="form_validation_md.html" class="nav-link ">
<span class="title">Material Design
<br>Form Validation</span>
</a>
</li>
<li class="nav-item ">
<a href="form_layouts.html" class="nav-link ">
<span class="title">Form Layouts</span>
</a>
</li>
<li class="nav-item ">
<a href="form_repeater.html" class="nav-link ">
<span class="title">Form Repeater</span>
</a>
</li>
<li class="nav-item ">
<a href="form_input_mask.html" class="nav-link ">
<span class="title">Form Input Mask</span>
</a>
</li>
<li class="nav-item ">
<a href="form_editable.html" class="nav-link ">
<span class="title">Form X-editable</span>
</a>
</li>
<li class="nav-item ">
<a href="form_wizard.html" class="nav-link ">
<span class="title">Form Wizard</span>
</a>
</li>
<li class="nav-item ">
<a href="form_icheck.html" class="nav-link ">
<span class="title">iCheck Controls</span>
</a>
</li>
<li class="nav-item ">
<a href="form_image_crop.html" class="nav-link ">
<span class="title">Image Cropping</span>
</a>
</li>
<li class="nav-item ">
<a href="form_fileupload.html" class="nav-link ">
<span class="title">Multiple File Upload</span>
</a>
</li>
<li class="nav-item ">
<a href="form_dropzone.html" class="nav-link ">
<span class="title">Dropzone File Upload</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-bulb"></i>
<span class="title">Elements</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="elements_steps.html" class="nav-link ">
<span class="title">Steps</span>
</a>
</li>
<li class="nav-item ">
<a href="elements_lists.html" class="nav-link ">
<span class="title">Lists</span>
</a>
</li>
<li class="nav-item ">
<a href="elements_ribbons.html" class="nav-link ">
<span class="title">Ribbons</span>
</a>
</li>
<li class="nav-item ">
<a href="elements_overlay.html" class="nav-link ">
<span class="title">Overlays</span>
</a>
</li>
<li class="nav-item ">
<a href="elements_cards.html" class="nav-link ">
<span class="title">User Cards</span>
</a>
</li>
</ul>
</li>
<li class="nav-item active open">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-briefcase"></i>
<span class="title">Tables</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="table_static_basic.html" class="nav-link ">
<span class="title">Basic Tables</span>
</a>
</li>
<li class="nav-item ">
<a href="table_static_responsive.html" class="nav-link ">
<span class="title">Responsive Tables</span>
</a>
</li>
<li class="nav-item ">
<a href="table_bootstrap.html" class="nav-link ">
<span class="title">Bootstrap Tables</span>
</a>
</li>
<li class="nav-item active open">
<a href="javascript:;" class="nav-link nav-toggle">
<span class="title">Datatables</span>
<span class="selected"></span>
<span class="arrow open"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="table_datatables_managed.html" class="nav-link "> Managed Datatables </a>
</li>
<li class="nav-item ">
<a href="table_datatables_buttons.html" class="nav-link "> Buttons Extension </a>
</li>
<li class="nav-item ">
<a href="table_datatables_colreorder.html" class="nav-link "> Colreorder Extension </a>
</li>
<li class="nav-item ">
<a href="table_datatables_rowreorder.html" class="nav-link "> Rowreorder Extension </a>
</li>
<li class="nav-item active open">
<a href="table_datatables_scroller.html" class="nav-link "> Scroller Extension </a>
</li>
<li class="nav-item ">
<a href="table_datatables_fixedheader.html" class="nav-link "> FixedHeader Extension </a>
</li>
<li class="nav-item ">
<a href="table_datatables_responsive.html" class="nav-link "> Responsive Extension </a>
</li>
<li class="nav-item ">
<a href="table_datatables_editable.html" class="nav-link "> Editable Datatables </a>
</li>
<li class="nav-item ">
<a href="table_datatables_ajax.html" class="nav-link "> Ajax Datatables </a>
</li>
</ul>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="?p=" class="nav-link nav-toggle">
<i class="icon-wallet"></i>
<span class="title">Portlets</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="portlet_boxed.html" class="nav-link ">
<span class="title">Boxed Portlets</span>
</a>
</li>
<li class="nav-item ">
<a href="portlet_light.html" class="nav-link ">
<span class="title">Light Portlets</span>
</a>
</li>
<li class="nav-item ">
<a href="portlet_solid.html" class="nav-link ">
<span class="title">Solid Portlets</span>
</a>
</li>
<li class="nav-item ">
<a href="portlet_ajax.html" class="nav-link ">
<span class="title">Ajax Portlets</span>
</a>
</li>
<li class="nav-item ">
<a href="portlet_draggable.html" class="nav-link ">
<span class="title">Draggable Portlets</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-bar-chart"></i>
<span class="title">Charts</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="charts_amcharts.html" class="nav-link ">
<span class="title">amChart</span>
</a>
</li>
<li class="nav-item ">
<a href="charts_flotcharts.html" class="nav-link ">
<span class="title">Flot Charts</span>
</a>
</li>
<li class="nav-item ">
<a href="charts_flowchart.html" class="nav-link ">
<span class="title">Flow Charts</span>
</a>
</li>
<li class="nav-item ">
<a href="charts_google.html" class="nav-link ">
<span class="title">Google Charts</span>
</a>
</li>
<li class="nav-item ">
<a href="charts_echarts.html" class="nav-link ">
<span class="title">eCharts</span>
</a>
</li>
<li class="nav-item ">
<a href="charts_morris.html" class="nav-link ">
<span class="title">Morris Charts</span>
</a>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<span class="title">HighCharts</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="charts_highcharts.html" class="nav-link "> HighCharts </a>
</li>
<li class="nav-item ">
<a href="charts_highstock.html" class="nav-link "> HighStock </a>
</li>
<li class="nav-item ">
<a href="charts_highmaps.html" class="nav-link "> HighMaps </a>
</li>
</ul>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-pointer"></i>
<span class="title">Maps</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="maps_google.html" class="nav-link ">
<span class="title">Google Maps</span>
</a>
</li>
<li class="nav-item ">
<a href="maps_vector.html" class="nav-link ">
<span class="title">Vector Maps</span>
</a>
</li>
</ul>
</li>
<li class="heading">
<h3 class="uppercase">Layouts</h3>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-layers"></i>
<span class="title">Page Layouts</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="layout_blank_page.html" class="nav-link ">
<span class="title">Blank Page</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_ajax_page.html" class="nav-link ">
<span class="title">Ajax Content Layout</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_language_bar.html" class="nav-link ">
<span class="title">Header Language Bar</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_footer_fixed.html" class="nav-link ">
<span class="title">Fixed Footer</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_boxed_page.html" class="nav-link ">
<span class="title">Boxed Page</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-feed"></i>
<span class="title">Sidebar Layouts</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="layout_sidebar_menu_hover.html" class="nav-link ">
<span class="title">Hover Sidebar Menu</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_sidebar_reversed.html" class="nav-link ">
<span class="title">Reversed Sidebar Page</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_sidebar_fixed.html" class="nav-link ">
<span class="title">Fixed Sidebar Layout</span>
</a>
</li>
<li class="nav-item ">
<a href="layout_sidebar_closed.html" class="nav-link ">
<span class="title">Closed Sidebar Layout</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class=" icon-wrench"></i>
<span class="title">Custom Layouts</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="layout_disabled_menu.html" class="nav-link ">
<span class="title">Disabled Menu Links</span>
</a>
</li>
</ul>
</li>
<li class="heading">
<h3 class="uppercase">Pages</h3>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-basket"></i>
<span class="title">eCommerce</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="ecommerce_index.html" class="nav-link ">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
</a>
</li>
<li class="nav-item ">
<a href="ecommerce_orders.html" class="nav-link ">
<i class="icon-basket"></i>
<span class="title">Orders</span>
</a>
</li>
<li class="nav-item ">
<a href="ecommerce_orders_view.html" class="nav-link ">
<i class="icon-tag"></i>
<span class="title">Order View</span>
</a>
</li>
<li class="nav-item ">
<a href="ecommerce_products.html" class="nav-link ">
<i class="icon-graph"></i>
<span class="title">Products</span>
</a>
</li>
<li class="nav-item ">
<a href="ecommerce_products_edit.html" class="nav-link ">
<i class="icon-graph"></i>
<span class="title">Product Edit</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-docs"></i>
<span class="title">Apps</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="app_todo.html" class="nav-link ">
<i class="icon-clock"></i>
<span class="title">Todo 1</span>
</a>
</li>
<li class="nav-item ">
<a href="app_todo_2.html" class="nav-link ">
<i class="icon-check"></i>
<span class="title">Todo 2</span>
</a>
</li>
<li class="nav-item ">
<a href="app_inbox.html" class="nav-link ">
<i class="icon-envelope"></i>
<span class="title">Inbox</span>
</a>
</li>
<li class="nav-item ">
<a href="app_calendar.html" class="nav-link ">
<i class="icon-calendar"></i>
<span class="title">Calendar</span>
</a>
</li>
<li class="nav-item ">
<a href="app_ticket.html" class="nav-link ">
<i class="icon-notebook"></i>
<span class="title">Support</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-user"></i>
<span class="title">User</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="page_user_profile_1.html" class="nav-link ">
<i class="icon-user"></i>
<span class="title">Profile 1</span>
</a>
</li>
<li class="nav-item ">
<a href="page_user_profile_1_account.html" class="nav-link ">
<i class="icon-user-female"></i>
<span class="title">Profile 1 Account</span>
</a>
</li>
<li class="nav-item ">
<a href="page_user_profile_1_help.html" class="nav-link ">
<i class="icon-user-following"></i>
<span class="title">Profile 1 Help</span>
</a>
</li>
<li class="nav-item ">
<a href="page_user_profile_2.html" class="nav-link ">
<i class="icon-users"></i>
<span class="title">Profile 2</span>
</a>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-notebook"></i>
<span class="title">Login</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="page_user_login_1.html" class="nav-link " target="_blank"> Login Page 1 </a>
</li>
<li class="nav-item ">
<a href="page_user_login_2.html" class="nav-link " target="_blank"> Login Page 2 </a>
</li>
<li class="nav-item ">
<a href="page_user_login_3.html" class="nav-link " target="_blank"> Login Page 3 </a>
</li>
<li class="nav-item ">
<a href="page_user_login_4.html" class="nav-link " target="_blank"> Login Page 4 </a>
</li>
<li class="nav-item ">
<a href="page_user_login_5.html" class="nav-link " target="_blank"> Login Page 5 </a>
</li>
<li class="nav-item ">
<a href="page_user_login_6.html" class="nav-link " target="_blank"> Login Page 6 </a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="page_user_lock_1.html" class="nav-link " target="_blank">
<i class="icon-lock"></i>
<span class="title">Lock Screen 1</span>
</a>
</li>
<li class="nav-item ">
<a href="page_user_lock_2.html" class="nav-link " target="_blank">
<i class="icon-lock-open"></i>
<span class="title">Lock Screen 2</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-social-dribbble"></i>
<span class="title">General</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="page_general_about.html" class="nav-link ">
<i class="icon-info"></i>
<span class="title">About</span>
</a>
</li>
<li class="nav-item ">
<a href="page_general_contact.html" class="nav-link ">
<i class="icon-call-end"></i>
<span class="title">Contact</span>
</a>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-notebook"></i>
<span class="title">Portfolio</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="page_general_portfolio_1.html" class="nav-link "> Portfolio 1 </a>
</li>
<li class="nav-item ">
<a href="page_general_portfolio_2.html" class="nav-link "> Portfolio 2 </a>
</li>
<li class="nav-item ">
<a href="page_general_portfolio_3.html" class="nav-link "> Portfolio 3 </a>
</li>
<li class="nav-item ">
<a href="page_general_portfolio_4.html" class="nav-link "> Portfolio 4 </a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-magnifier"></i>
<span class="title">Search</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="page_general_search.html" class="nav-link "> Search 1 </a>
</li>
<li class="nav-item ">
<a href="page_general_search_2.html" class="nav-link "> Search 2 </a>
</li>
<li class="nav-item ">
<a href="page_general_search_3.html" class="nav-link "> Search 3 </a>
</li>
<li class="nav-item ">
<a href="page_general_search_4.html" class="nav-link "> Search 4 </a>
</li>
<li class="nav-item ">
<a href="page_general_search_5.html" class="nav-link "> Search 5 </a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="page_general_pricing.html" class="nav-link ">
<i class="icon-tag"></i>
<span class="title">Pricing</span>
</a>
</li>
<li class="nav-item ">
<a href="page_general_faq.html" class="nav-link ">
<i class="icon-wrench"></i>
<span class="title">FAQ</span>
</a>
</li>
<li class="nav-item ">
<a href="page_general_blog.html" class="nav-link ">
<i class="icon-pencil"></i>
<span class="title">Blog</span>
</a>
</li>
<li class="nav-item ">
<a href="page_general_blog_post.html" class="nav-link ">
<i class="icon-note"></i>
<span class="title">Blog Post</span>
</a>
</li>
<li class="nav-item ">
<a href="page_general_invoice.html" class="nav-link ">
<i class="icon-envelope"></i>
<span class="title">Invoice</span>
</a>
</li>
<li class="nav-item ">
<a href="page_general_invoice_2.html" class="nav-link ">
<i class="icon-envelope"></i>
<span class="title">Invoice 2</span>
</a>
</li>
</ul>
</li>
<li class="nav-item ">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-settings"></i>
<span class="title">System</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item ">
<a href="page_cookie_consent_1.html" class="nav-link ">
<span class="title">Cookie Consent 1</span>
</a>
</li>
<li class="nav-item ">
<a href="page_cookie_consent_2.html" class="nav-link ">
<span class="title">Cookie Consent 2</span>
</a>
</li>
<li class="nav-item ">
<a href="page_system_coming_soon.html" class="nav-link " target="_blank">
<span class="title">Coming Soon</span>
</a>
</li>
<li class="nav-item ">
<a href="page_system_404_1.html" class="nav-link ">
<span class="title">404 Page 1</span>
</a>
</li>
<li class="nav-item ">
<a href="page_system_404_2.html" class="nav-link " target="_blank">
<span class="title">404 Page 2</span>
</a>
</li>
<li class="nav-item ">
<a href="page_system_404_3.html" class="nav-link " target="_blank">
<span class="title">404 Page 3</span>
</a>
</li>
<li class="nav-item ">
<a href="page_system_500_1.html" class="nav-link ">
<span class="title">500 Page 1</span>
</a>
</li>
<li class="nav-item ">
<a href="page_system_500_2.html" class="nav-link " target="_blank">
<span class="title">500 Page 2</span>
</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-folder"></i>
<span class="title">Multi Level Menu</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li class="nav-item">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="icon-settings"></i> Item 1
<span class="arrow"></span>
</a>
<ul class="sub-menu">
<li class="nav-item">
<a href="?p=dashboard-2" target="_blank" class="nav-link">
<i class="icon-user"></i> Arrow Toggle
<span class="arrow nav-toggle"></span>
</a>
<ul class="sub-menu">
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-power"></i> Sample Link 1</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-paper-plane"></i> Sample Link 1</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-star"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-camera"></i> Sample Link 1</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-link"></i> Sample Link 2</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-pointer"></i> Sample Link 3</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="?p=dashboard-2" target="_blank" class="nav-link">
<i class="icon-globe"></i> Arrow Toggle
<span class="arrow nav-toggle"></span>
</a>
<ul class="sub-menu">
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-tag"></i> Sample Link 1</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-pencil"></i> Sample Link 1</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-graph"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
<i class="icon-bar-chart"></i> Item 3 </a>
</li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
<!-- END SIDEBAR -->
</div>
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<!-- BEGIN CONTENT BODY -->
<div class="page-content">
<!-- BEGIN PAGE HEAD-->
<div class="page-head">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Scroller Extension
<small>scroller extension demos</small>
</h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
<!-- BEGIN THEME PANEL -->
<div class="btn-group btn-theme-panel">
<a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown">
<i class="icon-settings"></i>
</a>
<div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<h3>HEADER</h3>
<ul class="theme-colors">
<li class="theme-color theme-color-default active" data-theme="default">
<span class="theme-color-view"></span>
<span class="theme-color-name">Dark Header</span>
</li>
<li class="theme-color theme-color-light " data-theme="light">
<span class="theme-color-view"></span>
<span class="theme-color-name">Light Header</span>
</li>
</ul>
</div>
<div class="col-md-8 col-sm-8 col-xs-12 seperator">
<h3>LAYOUT</h3>
<ul class="theme-settings">
<li> Theme Style
<select class="layout-style-option form-control input-small input-sm">
<option value="square">Square corners</option>
<option value="rounded" selected="selected">Rounded corners</option>
</select>
</li>
<li> Layout
<select class="layout-option form-control input-small input-sm">
<option value="fluid" selected="selected">Fluid</option>
<option value="boxed">Boxed</option>
</select>
</li>
<li> Header
<select class="page-header-option form-control input-small input-sm">
<option value="fixed" selected="selected">Fixed</option>
<option value="default">Default</option>
</select>
</li>
<li> Top Dropdowns
<select class="page-header-top-dropdown-style-option form-control input-small input-sm">
<option value="light">Light</option>
<option value="dark" selected="selected">Dark</option>
</select>
</li>
<li> Sidebar Mode
<select class="sidebar-option form-control input-small input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</li>
<li> Sidebar Menu
<select class="sidebar-menu-option form-control input-small input-sm">
<option value="accordion" selected="selected">Accordion</option>
<option value="hover">Hover</option>
</select>
</li>
<li> Sidebar Position
<select class="sidebar-pos-option form-control input-small input-sm">
<option value="left" selected="selected">Left</option>
<option value="right">Right</option>
</select>
</li>
<li> Footer
<select class="page-footer-option form-control input-small input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- END THEME PANEL -->
</div>
<!-- END PAGE TOOLBAR -->
</div>
<!-- END PAGE HEAD-->
<!-- BEGIN PAGE BREADCRUMB -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Tables</a>
<i class="fa fa-circle"></i>
</li>
<li>
<span class="active">Datatables</span>
</li>
</ul>
<!-- END PAGE BREADCRUMB -->
<!-- BEGIN PAGE BASE CONTENT -->
<div class="m-heading-1 border-green m-bordered">
<h3>DataTables Scroller Extension</h3>
<p> Scroller is a virtual rendering plug-in for DataTables which allows large datasets to be drawn on screen every quickly. What the virtual rendering means is that only the visible portion of the table (and a bit to either side to
make the scrolling smooth) is drawn, while the scrolling container gives the visual impression that the whole table is visible. </p>
<p> For more info please check out
<a class="btn red btn-outline" href="http://datatables.net/extensions/scroller/" target="_blank">the official documentation</a>
</p>
</div>
<div class="row">
<div class="col-md-12">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-dark">
<i class="icon-settings font-dark"></i>
<span class="caption-subject bold uppercase">Default Scroller</span>
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover order-column" id="sample_1">
<thead>
<tr>
<th>First name</th>
<th>Lastname</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon@datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters@datatables.net</td>
</tr>
<tr>
<td>Ashton</td>
<td>Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
<td>1562</td>
<td>a.cox@datatables.net</td>
</tr>
<tr>
<td>Cedric</td>
<td>Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
<td>6224</td>
<td>c.kelly@datatables.net</td>
</tr>
<tr>
<td>Airi</td>
<td>Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
<td>5407</td>
<td>a.satou@datatables.net</td>
</tr>
<tr>
<td>Brielle</td>
<td>Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
<td>4804</td>
<td>b.williamson@datatables.net</td>
</tr>
<tr>
<td>Herrod</td>
<td>Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
<td>9608</td>
<td>h.chandler@datatables.net</td>
</tr>
<tr>
<td>Rhona</td>
<td>Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
<td>6200</td>
<td>r.davidson@datatables.net</td>
</tr>
<tr>
<td>Colleen</td>
<td>Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
<td>2360</td>
<td>c.hurst@datatables.net</td>
</tr>
<tr>
<td>Sonya</td>
<td>Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
<td>1667</td>
<td>s.frost@datatables.net</td>
</tr>
<tr>
<td>Jena</td>
<td>Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
<td>3814</td>
<td>j.gaines@datatables.net</td>
</tr>
<tr>
<td>Quinn</td>
<td>Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
<td>9497</td>
<td>q.flynn@datatables.net</td>
</tr>
<tr>
<td>Charde</td>
<td>Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
<td>6741</td>
<td>c.marshall@datatables.net</td>
</tr>
<tr>
<td>Haley</td>
<td>Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
<td>3597</td>
<td>h.kennedy@datatables.net</td>
</tr>
<tr>
<td>Tatyana</td>
<td>Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
<td>1965</td>
<td>t.fitzpatrick@datatables.net</td>
</tr>
<tr>
<td>Michael</td>
<td>Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
<td>1581</td>
<td>m.silva@datatables.net</td>
</tr>
<tr>
<td>Paul</td>
<td>Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
<td>3059</td>
<td>p.byrd@datatables.net</td>
</tr>
<tr>
<td>Gloria</td>
<td>Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
<td>1721</td>
<td>g.little@datatables.net</td>
</tr>
<tr>
<td>Bradley</td>
<td>Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
<td>2558</td>
<td>b.greer@datatables.net</td>
</tr>
<tr>
<td>Dai</td>
<td>Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
<td>2290</td>
<td>d.rios@datatables.net</td>
</tr>
<tr>
<td>Jenette</td>
<td>Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
<td>1937</td>
<td>j.caldwell@datatables.net</td>
</tr>
<tr>
<td>Yuri</td>
<td>Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
<td>6154</td>
<td>y.berry@datatables.net</td>
</tr>
<tr>
<td>Caesar</td>
<td>Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
<td>8330</td>
<td>c.vance@datatables.net</td>
</tr>
<tr>
<td>Doris</td>
<td>Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
<td>3023</td>
<td>d.wilder@datatables.net</td>
</tr>
<tr>
<td>Angelica</td>
<td>Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
<td>5797</td>
<td>a.ramos@datatables.net</td>
</tr>
<tr>
<td>Gavin</td>
<td>Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
<td>8822</td>
<td>g.joyce@datatables.net</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
<td>9239</td>
<td>j.chang@datatables.net</td>
</tr>
<tr>
<td>Brenden</td>
<td>Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
<td>1314</td>
<td>b.wagner@datatables.net</td>
</tr>
<tr>
<td>Fiona</td>
<td>Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
<td>2947</td>
<td>f.green@datatables.net</td>
</tr>
<tr>
<td>Shou</td>
<td>Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
<td>8899</td>
<td>s.itou@datatables.net</td>
</tr>
<tr>
<td>Michelle</td>
<td>House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
<td>2769</td>
<td>m.house@datatables.net</td>
</tr>
<tr>
<td>Suki</td>
<td>Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
<td>6832</td>
<td>s.burks@datatables.net</td>
</tr>
<tr>
<td>Prescott</td>
<td>Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
<td>3606</td>
<td>p.bartlett@datatables.net</td>
</tr>
<tr>
<td>Gavin</td>
<td>Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
<td>2860</td>
<td>g.cortez@datatables.net</td>
</tr>
<tr>
<td>Martena</td>
<td>Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
<td>8240</td>
<td>m.mccray@datatables.net</td>
</tr>
<tr>
<td>Unity</td>
<td>Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
<td>5384</td>
<td>u.butler@datatables.net</td>
</tr>
<tr>
<td>Howard</td>
<td>Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
<td>7031</td>
<td>h.hatfield@datatables.net</td>
</tr>
<tr>
<td>Hope</td>
<td>Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
<td>6318</td>
<td>h.fuentes@datatables.net</td>
</tr>
<tr>
<td>Vivian</td>
<td>Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
<td>9422</td>
<td>v.harrell@datatables.net</td>
</tr>
<tr>
<td>Timothy</td>
<td>Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
<td>7580</td>
<td>t.mooney@datatables.net</td>
</tr>
<tr>
<td>Jackson</td>
<td>Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
<td>1042</td>
<td>j.bradshaw@datatables.net</td>
</tr>
<tr>
<td>Olivia</td>
<td>Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
<td>2120</td>
<td>o.liang@datatables.net</td>
</tr>
<tr>
<td>Bruno</td>
<td>Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
<td>6222</td>
<td>b.nash@datatables.net</td>
</tr>
<tr>
<td>Sakura</td>
<td>Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
<td>9383</td>
<td>s.yamamoto@datatables.net</td>
</tr>
<tr>
<td>Thor</td>
<td>Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
<td>8327</td>
<td>t.walton@datatables.net</td>
</tr>
<tr>
<td>Finn</td>
<td>Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
<td>2927</td>
<td>f.camacho@datatables.net</td>
</tr>
<tr>
<td>Serge</td>
<td>Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
<td>8352</td>
<td>s.baldwin@datatables.net</td>
</tr>
<tr>
<td>Zenaida</td>
<td>Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
<td>7439</td>
<td>z.frank@datatables.net</td>
</tr>
<tr>
<td>Zorita</td>
<td>Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
<td>4389</td>
<td>z.serrano@datatables.net</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
<td>3431</td>
<td>j.acosta@datatables.net</td>
</tr>
<tr>
<td>Cara</td>
<td>Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
<td>3990</td>
<td>c.stevens@datatables.net</td>
</tr>
<tr>
<td>Hermione</td>
<td>Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
<td>1016</td>
<td>h.butler@datatables.net</td>
</tr>
<tr>
<td>Lael</td>
<td>Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
<td>6733</td>
<td>l.greer@datatables.net</td>
</tr>
<tr>
<td>Jonas</td>
<td>Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
<td>8196</td>
<td>j.alexander@datatables.net</td>
</tr>
<tr>
<td>Shad</td>
<td>Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
<td>6373</td>
<td>s.decker@datatables.net</td>
</tr>
<tr>
<td>Michael</td>
<td>Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
<td>5384</td>
<td>m.bruce@datatables.net</td>
</tr>
<tr>
<td>Donna</td>
<td>Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
<td>4226</td>
<td>d.snider@datatables.net</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- END EXAMPLE TABLE PORTLET-->
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-globe"></i>Server-side processing(5,000,000 rows) </div>
<div class="tools"> </div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover order-column" id="sample_2">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>ZIP / Post code</th>
<th>Country</th>
</tr>
</thead>
</table>
</div>
</div>
<!-- END EXAMPLE TABLE PORTLET-->
</div>
</div>
<div class="row">
<div class="col-md-6">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-green">
<i class="icon-settings font-green"></i>
<span class="caption-subject bold uppercase">Both Scrollbars</span>
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body table-both-scroll">
<table class="table table-striped table-bordered table-hover order-column" id="sample_3">
<thead>
<tr>
<th>First name</th>
<th>Lastname</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon@datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters@datatables.net</td>
</tr>
<tr>
<td>Ashton</td>
<td>Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
<td>1562</td>
<td>a.cox@datatables.net</td>
</tr>
<tr>
<td>Cedric</td>
<td>Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
<td>6224</td>
<td>c.kelly@datatables.net</td>
</tr>
<tr>
<td>Airi</td>
<td>Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
<td>5407</td>
<td>a.satou@datatables.net</td>
</tr>
<tr>
<td>Brielle</td>
<td>Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
<td>4804</td>
<td>b.williamson@datatables.net</td>
</tr>
<tr>
<td>Herrod</td>
<td>Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
<td>9608</td>
<td>h.chandler@datatables.net</td>
</tr>
<tr>
<td>Rhona</td>
<td>Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
<td>6200</td>
<td>r.davidson@datatables.net</td>
</tr>
<tr>
<td>Colleen</td>
<td>Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
<td>2360</td>
<td>c.hurst@datatables.net</td>
</tr>
<tr>
<td>Sonya</td>
<td>Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
<td>1667</td>
<td>s.frost@datatables.net</td>
</tr>
<tr>
<td>Jena</td>
<td>Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
<td>3814</td>
<td>j.gaines@datatables.net</td>
</tr>
<tr>
<td>Quinn</td>
<td>Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
<td>9497</td>
<td>q.flynn@datatables.net</td>
</tr>
<tr>
<td>Charde</td>
<td>Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
<td>6741</td>
<td>c.marshall@datatables.net</td>
</tr>
<tr>
<td>Haley</td>
<td>Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
<td>3597</td>
<td>h.kennedy@datatables.net</td>
</tr>
<tr>
<td>Tatyana</td>
<td>Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
<td>1965</td>
<td>t.fitzpatrick@datatables.net</td>
</tr>
<tr>
<td>Michael</td>
<td>Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
<td>1581</td>
<td>m.silva@datatables.net</td>
</tr>
<tr>
<td>Paul</td>
<td>Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
<td>3059</td>
<td>p.byrd@datatables.net</td>
</tr>
<tr>
<td>Gloria</td>
<td>Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
<td>1721</td>
<td>g.little@datatables.net</td>
</tr>
<tr>
<td>Bradley</td>
<td>Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
<td>2558</td>
<td>b.greer@datatables.net</td>
</tr>
<tr>
<td>Dai</td>
<td>Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
<td>2290</td>
<td>d.rios@datatables.net</td>
</tr>
<tr>
<td>Jenette</td>
<td>Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
<td>1937</td>
<td>j.caldwell@datatables.net</td>
</tr>
<tr>
<td>Yuri</td>
<td>Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
<td>6154</td>
<td>y.berry@datatables.net</td>
</tr>
<tr>
<td>Caesar</td>
<td>Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
<td>8330</td>
<td>c.vance@datatables.net</td>
</tr>
<tr>
<td>Doris</td>
<td>Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
<td>3023</td>
<td>d.wilder@datatables.net</td>
</tr>
<tr>
<td>Angelica</td>
<td>Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
<td>5797</td>
<td>a.ramos@datatables.net</td>
</tr>
<tr>
<td>Gavin</td>
<td>Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
<td>8822</td>
<td>g.joyce@datatables.net</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
<td>9239</td>
<td>j.chang@datatables.net</td>
</tr>
<tr>
<td>Brenden</td>
<td>Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
<td>1314</td>
<td>b.wagner@datatables.net</td>
</tr>
<tr>
<td>Fiona</td>
<td>Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
<td>2947</td>
<td>f.green@datatables.net</td>
</tr>
<tr>
<td>Shou</td>
<td>Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
<td>8899</td>
<td>s.itou@datatables.net</td>
</tr>
<tr>
<td>Michelle</td>
<td>House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
<td>2769</td>
<td>m.house@datatables.net</td>
</tr>
<tr>
<td>Suki</td>
<td>Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
<td>6832</td>
<td>s.burks@datatables.net</td>
</tr>
<tr>
<td>Prescott</td>
<td>Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
<td>3606</td>
<td>p.bartlett@datatables.net</td>
</tr>
<tr>
<td>Gavin</td>
<td>Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
<td>2860</td>
<td>g.cortez@datatables.net</td>
</tr>
<tr>
<td>Martena</td>
<td>Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
<td>8240</td>
<td>m.mccray@datatables.net</td>
</tr>
<tr>
<td>Unity</td>
<td>Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
<td>5384</td>
<td>u.butler@datatables.net</td>
</tr>
<tr>
<td>Howard</td>
<td>Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
<td>7031</td>
<td>h.hatfield@datatables.net</td>
</tr>
<tr>
<td>Hope</td>
<td>Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
<td>6318</td>
<td>h.fuentes@datatables.net</td>
</tr>
<tr>
<td>Vivian</td>
<td>Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
<td>9422</td>
<td>v.harrell@datatables.net</td>
</tr>
<tr>
<td>Timothy</td>
<td>Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
<td>7580</td>
<td>t.mooney@datatables.net</td>
</tr>
<tr>
<td>Jackson</td>
<td>Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
<td>1042</td>
<td>j.bradshaw@datatables.net</td>
</tr>
<tr>
<td>Olivia</td>
<td>Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
<td>2120</td>
<td>o.liang@datatables.net</td>
</tr>
<tr>
<td>Bruno</td>
<td>Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
<td>6222</td>
<td>b.nash@datatables.net</td>
</tr>
<tr>
<td>Sakura</td>
<td>Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
<td>9383</td>
<td>s.yamamoto@datatables.net</td>
</tr>
<tr>
<td>Thor</td>
<td>Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
<td>8327</td>
<td>t.walton@datatables.net</td>
</tr>
<tr>
<td>Finn</td>
<td>Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
<td>2927</td>
<td>f.camacho@datatables.net</td>
</tr>
<tr>
<td>Serge</td>
<td>Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
<td>8352</td>
<td>s.baldwin@datatables.net</td>
</tr>
<tr>
<td>Zenaida</td>
<td>Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
<td>7439</td>
<td>z.frank@datatables.net</td>
</tr>
<tr>
<td>Zorita</td>
<td>Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
<td>4389</td>
<td>z.serrano@datatables.net</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
<td>3431</td>
<td>j.acosta@datatables.net</td>
</tr>
<tr>
<td>Cara</td>
<td>Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
<td>3990</td>
<td>c.stevens@datatables.net</td>
</tr>
<tr>
<td>Hermione</td>
<td>Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
<td>1016</td>
<td>h.butler@datatables.net</td>
</tr>
<tr>
<td>Lael</td>
<td>Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
<td>6733</td>
<td>l.greer@datatables.net</td>
</tr>
<tr>
<td>Jonas</td>
<td>Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
<td>8196</td>
<td>j.alexander@datatables.net</td>
</tr>
<tr>
<td>Shad</td>
<td>Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
<td>6373</td>
<td>s.decker@datatables.net</td>
</tr>
<tr>
<td>Michael</td>
<td>Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
<td>5384</td>
<td>m.bruce@datatables.net</td>
</tr>
<tr>
<td>Donna</td>
<td>Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
<td>4226</td>
<td>d.snider@datatables.net</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<!-- BEGIN EXAMPLE TABLE PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-red">
<i class="icon-settings font-red"></i>
<span class="caption-subject bold uppercase">Both Scrollbars</span>
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body table-both-scroll">
<table class="table table-striped table-bordered table-hover order-column" id="sample_4">
<thead>
<tr>
<th>First name</th>
<th>Lastname</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
<th>Extn.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger</td>
<td>Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
<td>5421</td>
<td>t.nixon@datatables.net</td>
</tr>
<tr>
<td>Garrett</td>
<td>Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
<td>8422</td>
<td>g.winters@datatables.net</td>
</tr>
<tr>
<td>Ashton</td>
<td>Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
<td>1562</td>
<td>a.cox@datatables.net</td>
</tr>
<tr>
<td>Cedric</td>
<td>Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
<td>6224</td>
<td>c.kelly@datatables.net</td>
</tr>
<tr>
<td>Airi</td>
<td>Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
<td>5407</td>
<td>a.satou@datatables.net</td>
</tr>
<tr>
<td>Brielle</td>
<td>Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
<td>4804</td>
<td>b.williamson@datatables.net</td>
</tr>
<tr>
<td>Herrod</td>
<td>Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
<td>9608</td>
<td>h.chandler@datatables.net</td>
</tr>
<tr>
<td>Rhona</td>
<td>Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
<td>6200</td>
<td>r.davidson@datatables.net</td>
</tr>
<tr>
<td>Colleen</td>
<td>Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
<td>2360</td>
<td>c.hurst@datatables.net</td>
</tr>
<tr>
<td>Sonya</td>
<td>Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
<td>1667</td>
<td>s.frost@datatables.net</td>
</tr>
<tr>
<td>Jena</td>
<td>Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
<td>3814</td>
<td>j.gaines@datatables.net</td>
</tr>
<tr>
<td>Quinn</td>
<td>Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
<td>9497</td>
<td>q.flynn@datatables.net</td>
</tr>
<tr>
<td>Charde</td>
<td>Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
<td>6741</td>
<td>c.marshall@datatables.net</td>
</tr>
<tr>
<td>Haley</td>
<td>Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
<td>3597</td>
<td>h.kennedy@datatables.net</td>
</tr>
<tr>
<td>Tatyana</td>
<td>Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
<td>1965</td>
<td>t.fitzpatrick@datatables.net</td>
</tr>
<tr>
<td>Michael</td>
<td>Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
<td>1581</td>
<td>m.silva@datatables.net</td>
</tr>
<tr>
<td>Paul</td>
<td>Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
<td>3059</td>
<td>p.byrd@datatables.net</td>
</tr>
<tr>
<td>Gloria</td>
<td>Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
<td>1721</td>
<td>g.little@datatables.net</td>
</tr>
<tr>
<td>Bradley</td>
<td>Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
<td>2558</td>
<td>b.greer@datatables.net</td>
</tr>
<tr>
<td>Dai</td>
<td>Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
<td>2290</td>
<td>d.rios@datatables.net</td>
</tr>
<tr>
<td>Jenette</td>
<td>Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
<td>1937</td>
<td>j.caldwell@datatables.net</td>
</tr>
<tr>
<td>Yuri</td>
<td>Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
<td>6154</td>
<td>y.berry@datatables.net</td>
</tr>
<tr>
<td>Caesar</td>
<td>Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
<td>8330</td>
<td>c.vance@datatables.net</td>
</tr>
<tr>
<td>Doris</td>
<td>Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
<td>3023</td>
<td>d.wilder@datatables.net</td>
</tr>
<tr>
<td>Angelica</td>
<td>Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
<td>5797</td>
<td>a.ramos@datatables.net</td>
</tr>
<tr>
<td>Gavin</td>
<td>Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
<td>8822</td>
<td>g.joyce@datatables.net</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
<td>9239</td>
<td>j.chang@datatables.net</td>
</tr>
<tr>
<td>Brenden</td>
<td>Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
<td>1314</td>
<td>b.wagner@datatables.net</td>
</tr>
<tr>
<td>Fiona</td>
<td>Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
<td>2947</td>
<td>f.green@datatables.net</td>
</tr>
<tr>
<td>Shou</td>
<td>Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
<td>8899</td>
<td>s.itou@datatables.net</td>
</tr>
<tr>
<td>Michelle</td>
<td>House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
<td>2769</td>
<td>m.house@datatables.net</td>
</tr>
<tr>
<td>Suki</td>
<td>Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
<td>6832</td>
<td>s.burks@datatables.net</td>
</tr>
<tr>
<td>Prescott</td>
<td>Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
<td>3606</td>
<td>p.bartlett@datatables.net</td>
</tr>
<tr>
<td>Gavin</td>
<td>Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
<td>2860</td>
<td>g.cortez@datatables.net</td>
</tr>
<tr>
<td>Martena</td>
<td>Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
<td>8240</td>
<td>m.mccray@datatables.net</td>
</tr>
<tr>
<td>Unity</td>
<td>Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
<td>5384</td>
<td>u.butler@datatables.net</td>
</tr>
<tr>
<td>Howard</td>
<td>Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
<td>7031</td>
<td>h.hatfield@datatables.net</td>
</tr>
<tr>
<td>Hope</td>
<td>Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
<td>6318</td>
<td>h.fuentes@datatables.net</td>
</tr>
<tr>
<td>Vivian</td>
<td>Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
<td>9422</td>
<td>v.harrell@datatables.net</td>
</tr>
<tr>
<td>Timothy</td>
<td>Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
<td>7580</td>
<td>t.mooney@datatables.net</td>
</tr>
<tr>
<td>Jackson</td>
<td>Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
<td>1042</td>
<td>j.bradshaw@datatables.net</td>
</tr>
<tr>
<td>Olivia</td>
<td>Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
<td>2120</td>
<td>o.liang@datatables.net</td>
</tr>
<tr>
<td>Bruno</td>
<td>Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
<td>6222</td>
<td>b.nash@datatables.net</td>
</tr>
<tr>
<td>Sakura</td>
<td>Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
<td>9383</td>
<td>s.yamamoto@datatables.net</td>
</tr>
<tr>
<td>Thor</td>
<td>Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
<td>8327</td>
<td>t.walton@datatables.net</td>
</tr>
<tr>
<td>Finn</td>
<td>Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
<td>2927</td>
<td>f.camacho@datatables.net</td>
</tr>
<tr>
<td>Serge</td>
<td>Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
<td>8352</td>
<td>s.baldwin@datatables.net</td>
</tr>
<tr>
<td>Zenaida</td>
<td>Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
<td>7439</td>
<td>z.frank@datatables.net</td>
</tr>
<tr>
<td>Zorita</td>
<td>Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
<td>4389</td>
<td>z.serrano@datatables.net</td>
</tr>
<tr>
<td>Jennifer</td>
<td>Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
<td>3431</td>
<td>j.acosta@datatables.net</td>
</tr>
<tr>
<td>Cara</td>
<td>Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
<td>3990</td>
<td>c.stevens@datatables.net</td>
</tr>
<tr>
<td>Hermione</td>
<td>Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
<td>1016</td>
<td>h.butler@datatables.net</td>
</tr>
<tr>
<td>Lael</td>
<td>Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
<td>6733</td>
<td>l.greer@datatables.net</td>
</tr>
<tr>
<td>Jonas</td>
<td>Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
<td>8196</td>
<td>j.alexander@datatables.net</td>
</tr>
<tr>
<td>Shad</td>
<td>Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
<td>6373</td>
<td>s.decker@datatables.net</td>
</tr>
<tr>
<td>Michael</td>
<td>Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
<td>5384</td>
<td>m.bruce@datatables.net</td>
</tr>
<tr>
<td>Donna</td>
<td>Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
<td>4226</td>
<td>d.snider@datatables.net</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<!-- END CONTENT BODY -->
</div>
<!-- END CONTENT -->
<!-- BEGIN QUICK SIDEBAR -->
<a href="javascript:;" class="page-quick-sidebar-toggler">
<i class="icon-login"></i>
</a>
<div class="page-quick-sidebar-wrapper" data-close-on-body-click="false">
<div class="page-quick-sidebar">
<ul class="nav nav-tabs">
<li class="active">
<a href="javascript:;" data-target="#quick_sidebar_tab_1" data-toggle="tab"> Users
<span class="badge badge-danger">2</span>
</a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_2" data-toggle="tab"> Alerts
<span class="badge badge-success">7</span>
</a>
</li>
<li class="dropdown">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown"> More
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-bell"></i> Alerts </a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-info"></i> Notifications </a>
</li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-speech"></i> Activities </a>
</li>
<li class="divider"></li>
<li>
<a href="javascript:;" data-target="#quick_sidebar_tab_3" data-toggle="tab">
<i class="icon-settings"></i> Settings </a>
</li>
</ul>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane active page-quick-sidebar-chat" id="quick_sidebar_tab_1">
<div class="page-quick-sidebar-chat-users" data-rail-color="#ddd" data-wrapper-class="page-quick-sidebar-list">
<h3 class="list-heading">Staff</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-success">8</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar3.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Bob Nilson</h4>
<div class="media-heading-sub"> Project Manager </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar1.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Nick Larson</h4>
<div class="media-heading-sub"> Art Director </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">3</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar4.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Hubert</h4>
<div class="media-heading-sub"> CTO </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar2.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ella Wong</h4>
<div class="media-heading-sub"> CEO </div>
</div>
</li>
</ul>
<h3 class="list-heading">Customers</h3>
<ul class="media-list list-items">
<li class="media">
<div class="media-status">
<span class="badge badge-warning">2</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar6.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lara Kunis</h4>
<div class="media-heading-sub"> CEO, Loop Inc </div>
<div class="media-heading-small"> Last seen 03:10 AM </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="label label-sm label-success">new</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar7.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Ernie Kyllonen</h4>
<div class="media-heading-sub"> Project Manager,
<br> SmartBizz PTL </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar8.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Lisa Stone</h4>
<div class="media-heading-sub"> CTO, Keort Inc </div>
<div class="media-heading-small"> Last seen 13:10 PM </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-success">7</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar9.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Deon Portalatin</h4>
<div class="media-heading-sub"> CFO, H&D LTD </div>
</div>
</li>
<li class="media">
<img class="media-object" src="../assets/layouts/layout/img/avatar10.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Irina Savikova</h4>
<div class="media-heading-sub"> CEO, Tizda Motors Inc </div>
</div>
</li>
<li class="media">
<div class="media-status">
<span class="badge badge-danger">4</span>
</div>
<img class="media-object" src="../assets/layouts/layout/img/avatar11.jpg" alt="...">
<div class="media-body">
<h4 class="media-heading">Maria Gomez</h4>
<div class="media-heading-sub"> Manager, Infomatic Inc </div>
<div class="media-heading-small"> Last seen 03:10 AM </div>
</div>
</li>
</ul>
</div>
<div class="page-quick-sidebar-item">
<div class="page-quick-sidebar-chat-user">
<div class="page-quick-sidebar-nav">
<a href="javascript:;" class="page-quick-sidebar-back-to-list">
<i class="icon-arrow-left"></i>Back</a>
</div>
<div class="page-quick-sidebar-chat-user-messages">
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body"> When could you send me the report ? </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:15</span>
<span class="body"> Its almost done. I will be sending it shortly </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:15</span>
<span class="body"> Alright. Thanks! :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:16</span>
<span class="body"> You are most welcome. Sorry for the delay. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> No probs. Just take your time :) </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body"> Alright. I just emailed it to you. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> Great! Thanks. Will check it right away. </span>
</div>
</div>
<div class="post in">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar2.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Ella Wong</a>
<span class="datetime">20:40</span>
<span class="body"> Please let me know if you have any comment. </span>
</div>
</div>
<div class="post out">
<img class="avatar" alt="" src="../assets/layouts/layout/img/avatar3.jpg" />
<div class="message">
<span class="arrow"></span>
<a href="javascript:;" class="name">Bob Nilson</a>
<span class="datetime">20:17</span>
<span class="body"> Sure. I will check and buzz you if anything needs to be corrected. </span>
</div>
</div>
</div>
<div class="page-quick-sidebar-chat-user-form">
<div class="input-group">
<input type="text" class="form-control" placeholder="Type a message here...">
<div class="input-group-btn">
<button type="button" class="btn green">
<i class="icon-paper-clip"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane page-quick-sidebar-alerts" id="quick_sidebar_tab_2">
<div class="page-quick-sidebar-alerts-list">
<h3 class="list-heading">General</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 4 pending tasks.
<span class="label label-sm label-warning "> Take action
<i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> Just now </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Finance Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> New order received with
<span class="label label-sm label-success"> Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 30 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Web server hardware needs to be upgraded.
<span class="label label-sm label-warning"> Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 2 hours </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> IPO Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
</ul>
<h3 class="list-heading">System</h3>
<ul class="feeds list-items">
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-check"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 4 pending tasks.
<span class="label label-sm label-warning "> Take action
<i class="fa fa-share"></i>
</span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> Just now </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-danger">
<i class="fa fa-bar-chart-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Finance Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-default">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-shopping-cart"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> New order received with
<span class="label label-sm label-success"> Reference Number: DR23923 </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 30 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-success">
<i class="fa fa-user"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> You have 5 pending membership that requires a quick review. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 24 mins </div>
</div>
</li>
<li>
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-warning">
<i class="fa fa-bell-o"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> Web server hardware needs to be upgraded.
<span class="label label-sm label-default "> Overdue </span>
</div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 2 hours </div>
</div>
</li>
<li>
<a href="javascript:;">
<div class="col1">
<div class="cont">
<div class="cont-col1">
<div class="label label-sm label-info">
<i class="fa fa-briefcase"></i>
</div>
</div>
<div class="cont-col2">
<div class="desc"> IPO Report for year 2013 has been released. </div>
</div>
</div>
</div>
<div class="col2">
<div class="date"> 20 mins </div>
</div>
</a>
</li>
</ul>
</div>
</div>
<div class="tab-pane page-quick-sidebar-settings" id="quick_sidebar_tab_3">
<div class="page-quick-sidebar-settings-list">
<h3 class="list-heading">General Settings</h3>
<ul class="list-items borderless">
<li> Enable Notifications
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Allow Tracking
<input type="checkbox" class="make-switch" data-size="small" data-on-color="info" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Log Errors
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Auto Sumbit Issues
<input type="checkbox" class="make-switch" data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Enable SMS Alerts
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="success" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
</ul>
<h3 class="list-heading">System Settings</h3>
<ul class="list-items borderless">
<li> Security Level
<select class="form-control input-inline input-sm input-small">
<option value="1">Normal</option>
<option value="2" selected>Medium</option>
<option value="e">High</option>
</select>
</li>
<li> Failed Email Attempts
<input class="form-control input-inline input-sm input-small" value="5" /> </li>
<li> Secondary SMTP Port
<input class="form-control input-inline input-sm input-small" value="3560" /> </li>
<li> Notify On System Error
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="danger" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
<li> Notify On SMTP Error
<input type="checkbox" class="make-switch" checked data-size="small" data-on-color="warning" data-on-text="ON" data-off-color="default" data-off-text="OFF"> </li>
</ul>
<div class="inner-content">
<button class="btn btn-success">
<i class="icon-settings"></i> Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- END QUICK SIDEBAR -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="page-footer">
<div class="page-footer-inner"> 2016 © Metronic Theme By
<a target="_blank" href="http://keenthemes.com">Keenthemes</a> |
<a href="http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" title="Purchase Metronic just for 27$ and get lifetime updates for free" target="_blank">Purchase Metronic!</a>
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
</div>
<!-- END FOOTER -->
<!-- BEGIN QUICK NAV -->
<nav class="quick-nav">
<a class="quick-nav-trigger" href="#0">
<span aria-hidden="true"></span>
</a>
<ul>
<li>
<a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes" target="_blank" class="active">
<span>Purchase Metronic</span>
<i class="icon-basket"></i>
</a>
</li>
<li>
<a href="https://themeforest.net/item/metronic-responsive-admin-dashboard-template/reviews/4021469?ref=keenthemes" target="_blank">
<span>Customer Reviews</span>
<i class="icon-users"></i>
</a>
</li>
<li>
<a href="http://keenthemes.com/showcast/" target="_blank">
<span>Showcase</span>
<i class="icon-user"></i>
</a>
</li>
<li>
<a href="http://keenthemes.com/metronic-theme/changelog/" target="_blank">
<span>Changelog</span>
<i class="icon-graph"></i>
</a>
</li>
</ul>
<span aria-hidden="true" class="quick-nav-bg"></span>
</nav>
<div class="quick-nav-overlay"></div>
<!-- END QUICK NAV -->
<!--[if lt IE 9]>
<script src="../assets/global/plugins/respond.min.js"></script>
<script src="../assets/global/plugins/excanvas.min.js"></script>
<script src="../assets/global/plugins/ie8.fix.min.js"></script>
<![endif]-->
<!-- BEGIN CORE PLUGINS -->
<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script src="../assets/global/scripts/datatable.js" type="text/javascript"></script>
<script src="../assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
<script src="../assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="../assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../assets/pages/scripts/table-datatables-scroller.min.js" type="text/javascript"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS -->
<script src="../assets/layouts/layout4/scripts/layout.min.js" type="text/javascript"></script>
<script src="../assets/layouts/layout4/scripts/demo.min.js" type="text/javascript"></script>
<script src="../assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script>
<script src="../assets/layouts/global/scripts/quick-nav.min.js" type="text/javascript"></script>
<!-- END THEME LAYOUT SCRIPTS -->
</body>
</html>
|
FernandoUnix/AcessoRestrito
|
metronic_v4.7.1/theme/admin_4_rounded/table_datatables_scroller.html
|
HTML
|
gpl-3.0
| 280,649
|
// scanner.hpp -- interface and support classes
// Copyright (C) 2012-2015 SEIKO EPSON CORPORATION
//
// License: GPL-3.0+
// Author : EPSON AVASYS CORPORATION
//
// This file is part of the 'Utsushi' package.
// This package is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License or, at
// your option, any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You ought to have received a copy of the GNU General Public License
// along with this package. If not, see <http://www.gnu.org/licenses/>.
#ifndef utsushi_scanner_hpp_
#define utsushi_scanner_hpp_
#include <string>
#include "utsushi/connexion.hpp"
#include "utsushi/device.hpp"
#include "utsushi/option.hpp"
namespace utsushi {
class scanner
: public idevice
, protected option::map // FIXME idevice provides configurable
{
public:
typedef shared_ptr< scanner > ptr;
class info;
static ptr create (const scanner::info& info);
protected:
scanner (connexion::ptr cnx);
shared_ptr< connexion > cnx_;
};
//! @PACKAGE_NAME@ Device Information
/*! @PACKAGE_NAME@ device information combines a URI inspired syntax
* to uniquely pinpoint the device with configurable bits of mostly
* user-oriented information about the device.
*
* The user-oriented parts include model() and vendor() names as well
* as a nick name() and a place for some descriptive text(). This is
* the kind of informal information that may help users decide which
* device they want to use. Any programs require a much more formal
* piece of information to create a unique communication channel with
* a device. @PACKAGE_NAME@ has resorted to the URI syntax for that
* purpose and the remainder of this section will deal with how it is
* used by @PACKAGE_NAME@.
*
* The syntax for @PACKAGE_NAME@'s unique device identifiers (UDI's)
* stays as close as possible to the URI specification but there is
* one important difference. Rather than using a single \em scheme,
* UDI's use \em two. This comes about because access to a typical
* scanner device involves both a device protocol as well as a wire
* protocol. Using Augmented Backus-Naur Form (ABNF), one could
* define:
* \verbatim
UDI = scheme ":" URI
\endverbatim
* with \c URI defined as per RFC 3986. However this would introduce
* ambiguity as it is no longer clear which of the two schemes refers
* to what protocol. In addition, information available via the wire
* protocol may be used to infer a device protocol, so the latter can
* be optional. In rare cases, a driver may be able to establish the
* communication channel itself so the need for a wire protocol spec
* becomes optional as well. With these considerations in mind, the
* UDI definition becomes:
* \verbatim
UDI = protocols ":" hier-part [ "?" query ] [ "#" fragment ]
protocols = driver ":" connexion
/ driver ":"
/ ":" connexion
connexion = scheme
driver = scheme
\endverbatim
* where the \c driver and \c connexion parts refer to the device and
* wire protocols, respectively.
*
* \sa http://tools.ietf.org/html/rfc3986
*/
class scanner::info
{
public:
//! Create an instance from a given \a udi
info (const std::string& udi);
//! \name User-Oriented Information
//! @{
std::string name () const;
std::string text () const;
void name (const std::string& name);
void text (const std::string& text);
std::string type () const;
std::string model () const;
std::string vendor () const;
void type (const std::string& type);
void model (const std::string& model);
void vendor (const std::string& vendor);
//! @}
//! \name Interface-Specific Information
//! @{
uint16_t usb_vendor_id () const;
uint16_t usb_product_id () const;
void usb_vendor_id (const uint16_t& vid);
void usb_product_id (const uint16_t& pid);
//! @}
//! \name UDI Component Information
//! @{
std::string driver () const;
std::string connexion () const;
void driver (const std::string& driver);
void connexion (const std::string& connexion);
std::string host () const;
std::string port () const;
std::string path () const;
std::string query () const;
std::string fragment () const;
//! @}
//! Obtain a unique device identifier string
std::string udi () const;
//! Check whether the device protocol part has been specified
/*! Without a \c driver specified there is no way the application
* can intelligently communicate with the device.
*/
bool is_driver_set () const;
//! See if the device is attached to the machine we are running on
/*! Returns \c true if the \c hier-part starts with two slashes. A
* valid UDI with such a \c hier-part has a non-empty \c authority
* part and therefore a non-empty \c host specification.
*
* \todo Decide whether \c localhost UDI's should return true.
* \todo Decide what to require for drivers that establish the
* communication channel themselves.
*/
bool is_local () const;
//! check same usb device
bool is_same_usb_device (const uint16_t& vid, const uint16_t& pid) const;
//! set debug mode
void enable_debug (const bool debug);
//! check debug mode
bool enable_debug () const;
//! Check whether a given \a udi is syntactically valid
/*! \todo Implement parsing of the part that follows \c protocols
*/
static bool is_valid (const std::string& udi);
//! Character used to separate \c protocols and \c hier-part
static const char separator;
bool operator== (const scanner::info& rhs) const;
private:
std::string udi_;
std::string name_;
std::string text_;
std::string type_;
std::string model_;
std::string vendor_;
uint16_t usb_vendor_id_;
uint16_t usb_product_id_;
bool dump_connexion_;
};
} // namespace utsushi
namespace std {
template <>
struct less<utsushi::scanner::info>
{
bool operator() (const utsushi::scanner::info& x,
const utsushi::scanner::info& y) const
{
return x.udi () < y.udi ();
}
};
} // namespace std
#endif /* utsushi_scanner_hpp_ */
|
utsushi/imagescan
|
utsushi/scanner.hpp
|
C++
|
gpl-3.0
| 6,484
|
local log
local dz
local err = function(msg)
log(msg, dz.LOG_ERROR)
end
local tstMsg = function(msg, res)
print('HTTP trigger, ' .. msg .. ': ' .. tostring(res and 'OK' or 'FAILED'))
end
local expectEql = function(attr, test, marker)
if (attr ~= test) then
local msg = tostring(attr) .. '~=' .. tostring(test)
if (marker ~= nil) then
msg = msg .. ' (' .. tostring(marker) .. ')'
end
err(msg)
print(debug.traceback())
return false
end
return true
end
return {
on = {
devices = { 'vdHTTPSwitch' },
httpResponses = {'trigger1', 'trigger2','trigger3', 'vdHTTPSwitch'}
},
execute = function(domoticz, item)
dz = domoticz
log = dz.log
local res = true
if item.isHTTPResponse then
if item.callback == 'trigger1' then
res = res and expectEql(item.json.p, '1', 'p == 1')
res = res and expectEql(item.statusCode, 200, 'statusCode')
if (res) then
domoticz.globalData.httpTrigger = 'OK'
domoticz.openURL({
url = 'http://localhost:4000/testpost',
method = 'POST',
callback = 'trigger2',
postData = {
p = 2
}
})
end
elseif (item.callback == 'trigger2') then
res = res and expectEql(item.statusCode, 200, 'statusCode')
res = res and expectEql(item.json.p, 2, 'p == 2')
if (res) then domoticz.globalData.httpTrigger = domoticz.globalData.httpTrigger .. "OK" end
elseif (item.callback == 'trigger3') then
res = res and expectEql(item.statusCode, 6, 'statusCode')
if (res) then domoticz.globalData.httpTrigger = domoticz.globalData.httpTrigger .. "OK" end
elseif (item.callback == 'vdHTTPSwitch') then
res = res and expectEql(item.statusCode, 200, 'statusCode')
if (res) then domoticz.globalData.httpTrigger = domoticz.globalData.httpTrigger .. "OK" end
end
elseif item.isDevice then
domoticz.triggerHTTPResponse(item.name, 4, item.state )
domoticz.openURL({
url = 'http://localhost:4000/testget?p=1',
method = 'GET',
callback = 'trigger1',
})
domoticz.openURL({
url = 'http://noplaceToGo:4000/testget?p=1',
method = 'GET',
callback = 'trigger3',
}).afterSec(7)
end
end
}
|
gordonb3/domoticz
|
dzVents/runtime/integration-tests/httpResponseScript.lua
|
Lua
|
gpl-3.0
| 2,211
|
<?php
/**
* Logiciel : exemple d'utilisation de HTML2PDF
*
* Convertisseur HTML => PDF
* Distribué sous la licence LGPL.
*
* @author Laurent MINGUET <webmaster@html2pdf.fr>
*
* isset($_GET['vuehtml']) n'est pas obligatoire
* il permet juste d'afficher le résultat au format HTML
* si le paramètre 'vuehtml' est passé en paramètre _GET
*/
$content = '
<page>
<draw style="margin: auto; width:180mm; height:180mm; background: #444444; border: solid 0.5mm #777777;">
<g transform="translate(90mm,90mm) scale(1.5) translate(-250,-245)">
<path d="M 157.219 412.757 C 158.128 465.467 355.334 465.467 354.425 413.666 C 353.516 358.23 159.036 357.322 157.219 412.757 z " id="path749" sodipodi:nodetypes="ccc" style="fill:#623e35;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:bevel;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 212.655 306.43 L 211.746 413.665 C 219.694 425.479 288.517 427.298 299.898 412.757 L 299.898 305.521 C 289.901 320.97 232.647 326.423 212.655 306.43 z " id="path748" sodipodi:nodetypes="ccccc" style="fill:#623e35;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:4.76806;stroke-linejoin:bevel;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;" transform="matrix(0.618557,0.000000,0.000000,1.000000,98.94439,-0.908813)"/>
<path d="M 248.097 24.7078 C 244.462 35.6132 134.5 111.951 71.7941 150.119 C 109.053 250.994 394.412 247.359 425.31 150.121 C 371.692 134.671 250.823 34.7044 248.097 24.7078 z " id="path747" sodipodi:nodetypes="cccc" style="fill:#009500;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:bevel;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;" transform="translate(0.908775,139.0434)"/>
<path d="M 248.097 24.7078 C 244.462 35.6132 168.125 111.951 105.419 150.119 C 144.496 206.464 356.243 212.826 390.776 148.303 C 337.158 132.853 250.823 34.7044 248.097 24.7078 z " id="path746" sodipodi:nodetypes="cccc" style="fill:#009500;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:bevel;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;" transform="translate(-3.725290e-7,71.79367)"/>
<path d="M 157.343 412.757 L 158.596 431.841 C 201.308 481.824 340.324 469.226 353.047 431.966 L 354.205 412.757 C 356.023 466.375 160.07 463.649 157.343 412.757 z " id="path750" sodipodi:nodetypes="ccccc" style="fill:#623e35;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:bevel;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 248.097 24.7078 C 244.462 35.6132 207.202 107.407 144.497 145.575 C 181.756 190.106 322.618 193.742 357.151 146.485 C 303.533 131.035 250.823 34.7044 248.097 24.7078 z " id="path745" sodipodi:nodetypes="cccc" style="fill:#009500;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:bevel;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 247.188 38.3395 C 219.016 91.0487 170.85 136.488 151.766 145.575 C 159.946 160.116 206.293 174.657 225.378 171.931 C 213.564 141.032 216.289 111.951 247.188 38.3395 z " id="path751" sodipodi:nodetypes="cccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.5;"/>
<path d="M 179.938 171.93 C 168.124 181.927 125.412 215.552 114.506 222.822 C 106.327 223.731 157.219 251.903 175.395 251.903 C 135.408 228.275 217.199 177.383 179.938 171.93 z " id="path752" sodipodi:nodetypes="cccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.498039;"/>
<path d="M 140.861 250.994 C 126.321 260.082 102.692 277.349 78.1551 290.071 C 83.6078 310.065 123.594 335.511 132.682 338.237 C 96.331 292.798 175.395 260.082 140.861 250.994 z " id="path753" sodipodi:nodetypes="cccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.498039;"/>
<path d="M 233.308 366.285 C 234.121 379.008 231.643 403.487 233.623 413.293 C 247.255 420.056 256.276 418.554 266.962 418.114 C 253.33 412.661 242.329 402.388 233.308 366.285 z " id="path755" sodipodi:nodetypes="cccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.3;"/>
<path d="M 222.459 376.374 C 201.797 379.129 155.308 391.181 161.506 415.975 C 167.705 438.703 213.505 443.18 226.247 446.624 C 220.048 439.392 171.837 405.988 222.459 376.374 z " id="path756" sodipodi:nodetypes="cccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.3;"/>
<path d="M 161.162 428.028 C 163.573 429.061 172.871 441.803 208.685 456.955 C 193.532 452.822 163.228 440.425 161.162 428.028 z " id="path757" sodipodi:nodetypes="ccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.3;" transform=""/>
<path d="M 315.437 454.544 C 329.556 448.345 346.774 443.524 349.873 432.505 C 355.039 422.174 348.496 436.292 315.437 454.544 z " id="path758" sodipodi:nodetypes="ccc" style="fill:#000011;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.25;"/>
<path d="M 287.888 377.407 C 326.457 377.407 383.965 411.154 327.834 438.359 C 362.615 398.413 287.888 378.44 287.888 377.407 z " id="path759" sodipodi:nodetypes="ccc" style="fill:#000011;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.247059;"/>
<path d="M 259.65 366.043 C 259.65 366.043 279.967 363.288 281.345 365.698 C 282.722 368.109 281.689 387.049 281.001 391.87 C 279.968 382.572 282.378 368.798 259.65 366.043 z " id="path760" sodipodi:nodetypes="cccc" style="fill:#000011;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.247059;"/>
<path d="M 387.929 328.061 C 401.191 322.851 418.716 301.536 421.559 292.536 C 418.243 288.747 385.56 275.484 377.982 268.853 C 383.666 278.326 409.717 297.747 387.929 328.061 z " id="path761" sodipodi:nodetypes="cccc" style="fill:#000011;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.247059;"/>
<path d="M 352.404 245.644 C 370.876 238.539 382.244 229.065 384.613 222.908 C 375.613 219.119 355.246 205.856 345.299 200.172 C 352.878 208.224 368.509 221.487 352.404 245.644 z " id="path762" sodipodi:nodetypes="cccc" style="fill:#000011;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.247059;"/>
<path d="M 305.038 115.861 C 312.617 126.755 346.72 147.595 350.51 148.543 C 345.773 156.122 322.09 168.437 313.09 169.384 C 308.354 168.911 336.773 152.806 305.038 115.861 z " id="path763" sodipodi:nodetypes="cccc" style="fill:#000011;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.247059;"/>
<g id="g771" transform="translate(-249.1874,169.4743)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path772" sodipodi:nodetypes="ccc" style="fill:#ff0000;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path773" sodipodi:nodetypes="ccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.7;"/>
</g>
<g id="g774" transform="translate(-46.89011,243.8286)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path775" sodipodi:nodetypes="ccc" style="fill:#ff0000;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path776" sodipodi:nodetypes="ccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.7;"/>
</g>
<g id="g777" transform="translate(-226.4122,271.2928)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path778" sodipodi:nodetypes="ccc" style="fill:#ff0000;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path779" sodipodi:nodetypes="ccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.7;"/>
</g>
<g id="g780" transform="translate(-117.8951,83.73234)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path781" sodipodi:nodetypes="ccc" style="fill:#ff0000;fill-rule:evenodd;stroke:black;stroke-opacity:1;stroke-width:3.75;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:1;stroke-dasharray:none;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path782" sodipodi:nodetypes="ccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.7;"/>
</g>
<g id="g791" transform="translate(-236.4601,103.1582)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path792" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ff00ff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path793" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g794" transform="translate(-85.74192,124.5937)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path795" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ff00ff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path796" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g797" transform="translate(-144.0196,236.4601)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path798" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ff00ff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path799" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g808" transform="translate(-158.7565,60.28728)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path809" sodipodi:nodetypes="ccc" style="font-size:12;fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path810" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g811" transform="translate(-300.7665,212.3452)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path812" sodipodi:nodetypes="ccc" style="font-size:12;fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path813" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g814" transform="translate(-109.1869,185.5508)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path815" sodipodi:nodetypes="ccc" style="font-size:12;fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path816" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g822" transform="translate(-192.9193,111.8663)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path823" sodipodi:nodetypes="ccc" style="font-size:12;fill:#00ffff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path824" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g825" transform="translate(-101.1486,279.3311)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path826" sodipodi:nodetypes="ccc" style="font-size:12;fill:#00ffff;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path827" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g836" transform="translate(-293.3981,267.9435)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path837" sodipodi:nodetypes="ccc" style="font-size:12;fill:#00ff00;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path838" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g839" transform="translate(-203.6370,194.9289)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path840" sodipodi:nodetypes="ccc" style="font-size:12;fill:#00ff00;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path841" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g851" transform="translate(-81.05289,214.3548)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path852" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffff00;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path853" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g854" transform="translate(-146.0292,146.0292)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path855" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffff00;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path856" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g857" transform="translate(-231.7711,227.7519)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path858" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffff00;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path859" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g865" transform="translate(-202.9672,64.97627)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path866" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ff9300;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path867" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g868" transform="translate(-158.0866,287.3694)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path869" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ff9300;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path870" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g871" transform="translate(-152.7278,188.2303)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path872" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ff9300;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path873" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
<g id="g880" transform="translate(-140.0000,25.00000)">
<polygon id="polygon878" points="418.662,76.6493 399.532,56.5037 376.859,72.5587 390.107,48.1396 367.832,31.538 395.15,36.5918 404.055,10.2764 407.69,37.819 435.47,38.1568 410.399,50.1252 418.662,76.6493 " sodipodi:arg1="1.04002345" sodipodi:arg2="1.66834199" sodipodi:cx="400.575500" sodipodi:cy="45.8358383" sodipodi:r1="35.7292557" sodipodi:r2="10.7187767" sodipodi:sides="5" sodipodi:type="star" style="font-size:12;fill:#ff0000;fill-rule:evenodd;stroke-width:3.75;stroke:#000000;stroke-opacity:1;stroke-dasharray:none;fill-opacity:1;" transform="matrix(0.994342,-0.106230,0.106230,0.994342,-2.344353,42.91328)"/>
<path d="M 388.532 62.8101 C 401.79 40.713 380.796 41.775 381.792 39.3513 C 399.139 44.4405 399.022 35.5462 400.79 24.014 C 403.441 40.3242 406.708 43.765 388.532 62.8101 z " id="path879" sodipodi:nodetypes="cccc" style="fill:#ffffff;fill-rule:evenodd;stroke:none;stroke-opacity:1;stroke-width:1pt;stroke-linejoin:miter;stroke-linecap:butt;fill-opacity:0.5;"/>
</g>
<g id="g883" transform="translate(-216.1370,24.92889)">
<path d="M 424.69 52.5344 C 445.456 51.8645 445.456 82.0082 426.03 82.0082 C 401.245 82.678 404.594 53.2043 424.69 52.5344 z " id="path884" sodipodi:nodetypes="ccc" style="font-size:12;fill:#00ff00;fill-rule:evenodd;stroke:#000000;stroke-width:3.75;fill-opacity:1;"/>
<path d="M 425.36 55.2139 C 423.35 53.2043 401.915 63.922 415.982 75.3096 C 424.691 74.6397 427.37 57.2234 425.36 55.2139 z " id="path885" sodipodi:nodetypes="ccc" style="font-size:12;fill:#ffffff;fill-opacity:0.7;fill-rule:evenodd;stroke-width:1pt;"/>
</g>
</g>
</draw>
</page>';
// conversion HTML => PDF
require_once(dirname(__FILE__).'/../html2pdf.class.php');
$html2pdf = new HTML2PDF('L','A4','fr', false, 'ISO-8859-15', 10);
$html2pdf->pdf->SetDisplayMode('fullpage');
$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
$html2pdf->Output('sapin.pdf');
|
rotagraziosi/archi-wiki-inpeople
|
includes/framework/frameworkClasses/pdf/exemples/sapin.php
|
PHP
|
gpl-3.0
| 21,692
|
url: http://sanskrit.jnu.ac.in/sandhi/viccheda.jsp?itext=मरीचिश्च<html>
<title>Sanskrit Sandhi Splitter at J.N.U. New Delhi</title>
<META CONTENT='text/hetml CHARSET=UTF-8' HTTP-EQUIV='Content-Type'/>
<META NAME="Author" CONTENT="Dr. Girish Nath Jha">
<META NAME="Keywords" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<META NAME="Description" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<head>
<head>
<style>
<!--
div.Section1
{page:Section1;}
-->
</style>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<script language="JavaScript" src=../js/menuitems.js></script>
<script language="JavaScript" src="../js/mm_menu.js"></script>
<meta name=Author content="Dr. Girish Nath Jha, JNU, New Delhi">
</head>
<body lang=EN-US link=blue vlink=blue style='tab-interval:.5in'>
<div class=Section1>
<div align=center>
<table border=1 cellspacing=0 cellpadding=0 width=802 style='width:601.5pt;
border-collapse:collapse;border:none;mso-border-alt:outset navy .75pt'>
<tr>
<td width=800 style='width:600.0pt;border:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<script language="JavaScript1.2">mmLoadMenus();</script>
<img width=800 height=130 id="_x0000_i1028" src="../images/header1.jpg"
border=0>
</td>
</tr>
<tr>
<td width=818 style='width:613.5pt;border:inset navy .75pt;border-top:none;
mso-border-top-alt:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<p align="center"><a href="../"><span style='text-decoration:none;text-underline:
none'><img border=1 width=49 height=26 id="_x0000_i1037"
src="../images/backtohome.jpg"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171051_0,6,29,null,'image2')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image2 src="../images/lang_tool.jpg"
name=image2 width="192" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171909_0,6,29,null,'image3')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image3 src="../images/lexical.jpg"
name=image3 width="137" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171609_0,6,29,null,'image1')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image1 src="../images/elearning.jpg"
name=image1 width="77" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171809_0,6,29,null,'image4')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image4 src="../images/corpora.jpg"
name=image4 width="105" height="26"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171709_0,6,29,null,'image5')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image5 src="../images/rstudents.jpg"
name=image5 width="125" height="26"></span></a><span style='text-underline:
none'> </span>
<a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171409_0,6,29,null,'image6')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image6 src="../images/feedback.jpg"
name=image6 width="80" height="25"></span></a><span style='text-underline:
none'> </span>
<!---
<a href="../user/feedback.jsp"><img border="1" src="../images/feedback.jpg" width="80" height="25"></a>
--->
</td>
</tr>
<tr>
<td width="800">
<p align="center"><font color="#FF9933"><span style='font-size:18.0pt;
'><b>Sanskrit Sandhi Recognizer and Analyzer</b></span></font></p>
The Sanskrit sandhi splitter (VOWEL SANDHI) was developed as part of M.Phil. research by <a href="mailto:sachin.jnu@gmail.com">Sachin Kumar</a> (M.Phil. 2005-2007), and <a href=mailto:diwakarmishra@gmail.com>Diwakar Mishra</a> (M.Phil. 2007-2009) under the supervision of <a href=http://www.jnu.ac.in/faculty/gnjha>Dr. Girish Nath Jha</a>. The coding for this application has been done by Dr. Girish Nath Jha and Diwakar Mishra. <!---Please send feedback to to <a href="mailto:girishj@mail.jnu.ac.in">Dr. Girish Nath Jha</A>--->The Devanagari input mechanism has been developed in Javascript by Satyendra Kumar Chaube, Dr. Girish Nath Jha and Dharm Singh Rathore.
</center>
<table border=0 width=100%>
<tr>
<td valign=top width=48%>
<table>
<tr>
<td>
<FORM METHOD=get ACTION=viccheda.jsp#results name="iform" accept-Charset="UTF-8">
<font size=2><b>Enter Sanskrit text for sandhi processing (संधि-विच्छेद हेतु पाठ्य दें)
using adjacent keyboard OR Use our inbuilt <a href=../js/itrans.html target=_blank>iTRANS</a>-Devanagari unicode converter for fast typing<br>
<a href=sandhitest.txt>examples</a>
<TEXTAREA name=itext COLS=40 ROWS=9 onkeypress=checkKeycode(event) onkeyup=iu()> मरीचिश्च</TEXTAREA>
</td>
</tr>
<tr>
<td>
<font color=red size=2>Run in debug mode</font>
<input type=checkbox name="debug" value="ON">
<br>
<input type=submit value="Click to sandhi-split (संधि-विच्छेद करें)"></span><br>
</td>
</tr>
</table>
</td>
<td valign=top width=52%>
<table>
<tr>
<td>
<head>
<SCRIPT language=JavaScript src="../js/devkb.js"></SCRIPT>
<head>
<TEXTAREA name=itrans rows=5 cols=10 style="display:none"></TEXTAREA>
<INPUT name=lastChar type=hidden>
<table border=2 style="background-color:#fff;">
<tbody>
<tr >
<td>
<input type=button name="btn" style="width: 24px" value="अ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="आ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="इ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ई" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="उ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऊ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ए" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऐ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ओ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="औ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऍ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऑ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="्" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ा" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ि" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ी" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ु" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ू" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="े" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ै" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ो" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ौ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॅ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॉ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="क" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ख" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ग" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="घ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ङ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="च" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="छ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="झ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 100px" value="Backspace" onClick="BackSpace()">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="+" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ट" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ठ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ड" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ढ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ण" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="त" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="थ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="द" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ध" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="न" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="/" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="प" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="फ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ब" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="भ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="म" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="य" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ल" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="व" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="।" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="*" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="स" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ऋ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऌ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ृ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॄ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ह" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="॥" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="त्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज्ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="क्ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 200px" value="Space Bar" onClick="Space()">
<input type=button name="btn" style="width: 24px" value="ँ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="़" onClick="keyboard(this.value)">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
</table>
</form>
<a name=results>
<font size=4><b><u>Results</u></b></font>
<br>
<br>
<font color=red>
<br>
<hr>
<br>
</body>
</html>
|
sanskritiitd/sanskrit
|
uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/agnipuran-1-111-sandhi_ext.txt.out.dict_3765_jnu.html
|
HTML
|
gpl-3.0
| 16,529
|
package is.idega.idegaweb.tracker.data;
public interface DomainStatisticsHome extends com.idega.data.IDOHome
{
public DomainStatistics create() throws javax.ejb.CreateException;
public DomainStatistics createLegacy();
public DomainStatistics findByPrimaryKey(int id) throws javax.ejb.FinderException;
public DomainStatistics findByPrimaryKey(Object pk) throws javax.ejb.FinderException;
public DomainStatistics findByPrimaryKeyLegacy(int id) throws java.sql.SQLException;
}
|
idega/is.idega.idegaweb.tracker
|
src/java/is/idega/idegaweb/tracker/data/DomainStatisticsHome.java
|
Java
|
gpl-3.0
| 481
|
MODULE analysis_wavefield
!
! This module contains different routines to analyse (wave-by-wave) the wavefield
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! Copyright (C) 2014 - LHEEA Lab., Ecole Centrale de Nantes, UMR CNRS 6598
!
! This program is part of HOS-ocean
!
! HOS-ocean is free software: you can redistribute it and/or modify
! it under the terms of the GNU General Public License as published by
! the Free Software Foundation, either version 3 of the License, or
! (at your option) any later version.
!
! This program is distributed in the hope that it will be useful,
! but WITHOUT ANY WARRANTY; without even the implied warranty of
! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
! GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program. If not, see <http://www.gnu.org/licenses/>.
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
USE type
USE variables_3d
!
CONTAINS
!
!
!
SUBROUTINE wave_by_wave(signal,x,n1,n_waves,H_up,L_up,idx_up,H_down,L_down,idx_down,crest,idx_crest,trough,idx_trough)
!
! Wave-by-wave analysis of a periodic signal on n1 point
!
IMPLICIT NONE
!
INTEGER, INTENT(IN) :: n1
REAL(RP), DIMENSION(n1), INTENT(IN) :: signal, x
! Allocatable variables
INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: idx_crest,idx_trough
INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: idx_up,idx_down
REAL(RP), ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: crest,trough,H_up,H_down,L_up,L_down
!
! Local variables
INTEGER :: i1
INTEGER, DIMENSION(n1) :: idx_zeros ! indexes of zero-crossings
INTEGER :: n_zeros, n_waves ! number of zero crossings and waves
INTEGER :: shift, i_crest, i_trough, i_tmp, j1
!
! Initialize
idx_zeros = 0 ! Necessary since all n1 elements will not be evaluated (only n_zeros)
n_zeros = 0
!
! First step: locate zero-crossings
DO i1=2,n1
IF((signal(i1)*signal(i1-1)).LT.0.0_rp) THEN
n_zeros = n_zeros+1
idx_zeros(n_zeros) = i1-1
ENDIF
ENDDO
IF((signal(1)*signal(n1)).LT.0.0_rp) THEN
n_zeros = n_zeros+1
idx_zeros(n_zeros) = n1
ENDIF
!
! Check if we start with signal>0 (shift=1) or signal<0 (shift=0)?
IF (signal(1) > tiny) THEN
shift = 1
ELSE
shift = 0
ENDIF
!
! Number of waves inside the domain
IF(.NOT.iseven(n_zeros)) THEN
WRITE(*,*) 'n_zeros is not even... there is a problem'
STOP 1
ENDIF
n_waves = n_zeros/2
!
! Test on the number of waves detected
IF (n_waves < 2) THEN
PRINT*, 'Too small number of waves in wave-by-wave analysis'
PRINT*, 'If 3D analysis of wave-field, you should restrict to 2D'
STOP 1
ENDIF
!
! Allocation on the number of waves
!
ALLOCATE(idx_crest(n_waves),idx_trough(n_waves),crest(n_waves),trough(n_waves) &
, H_up(n_waves), H_down(n_waves), L_up(n_waves), L_down(n_waves) &
, idx_up(n_waves), idx_down(n_waves))
!
! Evaluate the index of each crest and trough and their amplitudes
DO j1=1,n_waves-1
i_crest = (2*j1+1)-shift ! beginning of a crest
i_trough = (2*j1)-shift ! beginning of a trough
! Indexes
idx_crest(j1) = idx_zeros(i_crest)-1 + MAXLOC(signal(idx_zeros(i_crest):idx_zeros(i_crest+1)),1)
idx_trough(j1) = idx_zeros(i_trough)-1 + MINLOC(signal(idx_zeros(i_trough):idx_zeros(i_trough+1)),1)
! Elevations
crest(j1) = MAXVAL(signal(idx_zeros(i_crest):idx_zeros(i_crest+1)),1)
trough(j1) = MINVAL(signal(idx_zeros(i_trough):idx_zeros(i_trough+1)),1)
ENDDO
!
! Different cases to treat with periodicity...
!
! Locate maximum of last wave w.r.t. periodic condition
! (n_zeros-shift) gives the last down crossing
! (2-shift) gives the first down-crossing
!IF(MAXVAL(signal(idx_zeros(n_zeros-shift):n1)).GT.(MAXVAL(signal(1:idx_zeros((3)-shift))))) THEN
IF(MAXVAL(signal(idx_zeros(n_zeros-shift):n1),1).GT.(MAXVAL(signal(1:idx_zeros(2-shift)),1))) THEN
i_tmp = MAXLOC(signal(idx_zeros(n_zeros-shift):n1),1)
idx_crest(n_waves) = idx_zeros(n_zeros-shift)-1+i_tmp
! Crest-amplitude
crest(n_waves) = MAXVAL(signal(idx_zeros(n_zeros-shift):n1),1)
ELSE
i_tmp = MAXLOC(signal(1:idx_zeros(2-shift)),1)
idx_crest(n_waves) = n1+i_tmp
! Crest-amplitude
crest(n_waves) = MAXVAL(signal(1:idx_zeros(2-shift)),1)
ENDIF
!
! Locate minimum of last wave w.r.t. periodic condition
! (n_zeros-shift) gives the last down crossing
! (2-shift) gives the first down-crossing
IF(MINVAL(signal(idx_zeros(n_zeros-shift):n1)).LT.MINVAL(signal(1:idx_zeros(2-shift)))) THEN
i_tmp = MINLOC(signal(idx_zeros((2*n_waves)-shift):n1),1)
idx_trough(n_waves) = idx_zeros(n_zeros-shift)-1+i_tmp
! Trough-amplitude
trough(n_waves) = MINVAL(signal(idx_zeros(n_zeros-shift):n1),1)
ELSE
i_tmp = MINLOC(signal(1:idx_zeros(2-shift)),1)
idx_trough(n_waves) = n1+i_tmp
! Trough-amplitude
trough(n_waves) = MINVAL(signal(1:idx_zeros(2-shift)),1)
ENDIF
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
DO j1=1,n_waves-2
i_crest = (2*j1+1)-shift ! beginning of a crest
i_trough = (2*j1)-shift ! beginning of a trough
! Heights up/down crossing
H_up(j1) = crest(j1) - trough(j1+1)
H_down(j1) = crest(j1) - trough(j1)
! Lengths up/down crossing
L_up(j1) = x(idx_zeros(i_crest+2))-x(idx_zeros(i_crest))
L_down(j1) = x(idx_zeros(i_trough+2))-x(idx_zeros(i_trough))
! Indexes up-crossing and down-crossing wave beginning
idx_up(j1) = idx_zeros(i_crest)
idx_down(j1) = idx_zeros(i_trough)
ENDDO
!
! Specific treatment of 2 last waves which may encounter periodic boundary
! n_waves-1
j1 = n_waves-1
i_crest = (2*j1+1)-shift ! beginning of a crest
i_trough = (2*j1)-shift ! beginning of a trough
! Heights and lengths up/down crossing
H_up(j1) = crest(j1) - trough(j1+1)
H_down(j1) = crest(j1) - trough(j1)
IF (shift == 1) THEN
L_up(j1) = x(idx_zeros(i_crest+2))-x(idx_zeros(i_crest))
ELSE
L_up(j1) = x(n1)-x(idx_zeros(i_crest))+x(idx_zeros(1))
ENDIF
!
L_down(j1) = x(idx_zeros(i_trough+2))-x(idx_zeros(i_trough))
! Indexes up-crossing and down-crossing wave beginning
idx_up(j1) = idx_zeros(i_crest)
idx_down(j1) = idx_zeros(i_trough)
!
! n_waves
j1 = n_waves
i_crest = (2*j1+1)-shift ! beginning of a crest
i_trough = (2*j1)-shift ! beginning of a trough
!
H_up(j1) = crest(j1) - trough(1)
H_down(j1) = crest(j1) - trough(j1)
! Longueurs up/down crossing
IF (shift == 1) THEN
L_up(j1) = x(n1)-x(idx_zeros(i_crest))+x(idx_zeros(1))
! Index up-crossing wave beginning
idx_up(j1) = idx_zeros(i_crest)
ELSE
L_up(j1) = x(idx_zeros(3))-x(idx_zeros(1))
! Index up-crossing wave beginning
idx_up(j1) = idx_zeros(1)
ENDIF
!
L_down(j1) = x(n1)-x(idx_zeros(i_trough))+x(idx_zeros(2-shift))
! Index down-crossing wave beginning
idx_down(j1) = idx_zeros(i_trough)
!
END SUBROUTINE wave_by_wave
!
!
!
SUBROUTINE wave_by_wave_3D(signal,x,y,n1,n2,n_waves,H_up,L_up,idx_up,H_down,crest,idx_crest,L_up_t,idx_up_t,idx_crest_t)
!
! Wave-by-wave analysis of a periodic signal on n1 point
!
IMPLICIT NONE
!
INTEGER, INTENT(IN) :: n1,n2
REAL(RP), DIMENSION(n1), INTENT(IN) :: x
REAL(RP), DIMENSION(n2), INTENT(IN) :: y
REAL(RP), DIMENSION(n1,n2), INTENT(IN) :: signal
! Allocatable variables
INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: idx_crest,idx_up
REAL(RP), ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: crest,H_up,H_down,L_up
!
INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: idx_crest_t,idx_up_t
REAL(RP), ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: L_up_t
!
! Local variables
INTEGER :: i1,i2,j1,j2
INTEGER :: n_waves ! number of waves
!
! Temp variables assuming at least 4 points per wavelength
INTEGER, DIMENSION(n2) :: n_waves_x
INTEGER, DIMENSION(n1/4,n2) :: idx_crest_x,idx_trough_x
INTEGER, DIMENSION(n1/4,n2) :: idx_up_x,idx_down_x
REAL(RP), DIMENSION(n1/4,n2) :: crest_x,trough_x,H_up_x,H_down_x,L_up_x,L_down_x
!
INTEGER, DIMENSION(n1) :: n_waves_y
INTEGER, DIMENSION(n1,n2/4) :: idx_crest_y,idx_trough_y
INTEGER, DIMENSION(n1,n2/4) :: idx_up_y,idx_down_y
REAL(RP), DIMENSION(n1,n2/4) :: crest_y,trough_y,H_up_y,H_down_y,L_up_y,L_down_y
! Allocatables temp variables
INTEGER, ALLOCATABLE, DIMENSION(:) :: idx_crest_tmp,idx_trough_tmp
INTEGER, ALLOCATABLE, DIMENSION(:) :: idx_up_tmp,idx_down_tmp
REAL(RP), ALLOCATABLE, DIMENSION(:) :: crest_tmp,trough_tmp,H_up_tmp,H_down_tmp,L_up_tmp,L_down_tmp
!
! one has to perform recursive analysis
DO i2=1,n2
CALL wave_by_wave(signal(:,i2),x,n1,n_waves_x(i2),H_up_tmp,L_up_tmp,idx_up_tmp,H_down_tmp,L_down_tmp,idx_down_tmp,&
crest_tmp,idx_crest_tmp,trough_tmp,idx_trough_tmp)
!
IF (n_waves_x(i2) > n1/4) THEN
PRINT*, 'Not enough points per wavelength in x'
PRINT*,'n_waves =', n_waves_x(i2), 'n1 =', n1
STOP 1
ENDIF
!
DO i1=1,n_waves_x(i2)
H_up_x(i1,i2) = H_up_tmp(i1)
L_up_x(i1,i2) = L_up_tmp(i1)
idx_up_x(i1,i2) = idx_up_tmp(i1)
H_down_x(i1,i2) = H_down_tmp(i1)
L_down_x(i1,i2) = L_down_tmp(i1)
idx_down_x(i1,i2) = idx_down_tmp(i1)
crest_x(i1,i2) = crest_tmp(i1)
idx_crest_x(i1,i2) = idx_crest_tmp(i1)
trough_x(i1,i2) = trough_tmp(i1)
idx_trough_x(i1,i2) = idx_trough_tmp(i1)
ENDDO
!
DEALLOCATE(H_up_tmp,L_up_tmp,idx_up_tmp,H_down_tmp,L_down_tmp,idx_down_tmp,crest_tmp,idx_crest_tmp,trough_tmp,idx_trough_tmp)
ENDDO
!
! transverse analysis
DO i1=1,n1
CALL wave_by_wave(signal(i1,:),y,n2,n_waves_y(i1),H_up_tmp,L_up_tmp,idx_up_tmp,H_down_tmp,L_down_tmp,idx_down_tmp,&
crest_tmp,idx_crest_tmp,trough_tmp,idx_trough_tmp)
!
IF (n_waves_y(i1) > n2/4) THEN
PRINT*, 'Not enough points per wavelength in y'
PRINT*,'n_waves =', n_waves_y(i1), 'n2 =', n2
STOP 1
ENDIF
!
DO i2=1,n_waves_y(i1)
H_up_y(i1,i2) = H_up_tmp(i2)
L_up_y(i1,i2) = L_up_tmp(i2)
idx_up_y(i1,i2) = idx_up_tmp(i2)
H_down_y(i1,i2) = H_down_tmp(i2)
L_down_y(i1,i2) = L_down_tmp(i2)
idx_down_y(i1,i2) = idx_down_tmp(i2)
crest_y(i1,i2) = crest_tmp(i2)
idx_crest_y(i1,i2) = idx_crest_tmp(i2)
trough_y(i1,i2) = trough_tmp(i2)
idx_trough_y(i1,i2) = idx_trough_tmp(i2)
ENDDO
!
DEALLOCATE(H_up_tmp,L_up_tmp,idx_up_tmp,H_down_tmp,L_down_tmp,idx_down_tmp,crest_tmp,idx_crest_tmp,trough_tmp,idx_trough_tmp)
ENDDO
!
! Determine the number of 3D-waves
n_waves=0
DO i1=1,n1
DO j1=1,n_waves_y(i1)
DO i2=1,n2
DO j2=1,n_waves_x(i2)
IF((i1.EQ.idx_crest_x(j2,i2)).AND.(i2.EQ.idx_crest_y(i1,j1))) THEN
n_waves = n_waves+1
ENDIF
ENDDO
ENDDO
ENDDO
ENDDO
!
! Allocate
ALLOCATE(H_up(n_waves),H_down(n_waves),crest(n_waves),L_up(n_waves),idx_up(n_waves),idx_crest(n_waves),&
L_up_t(n_waves),idx_up_t(n_waves),idx_crest_t(n_waves))
!
n_waves=0
DO i1=1,n1
DO j1=1,n_waves_y(i1)
DO i2=1,n2
DO j2=1,n_waves_x(i2)
IF((i1.EQ.idx_crest_x(j2,i2)).AND.(i2.EQ.idx_crest_y(i1,j1))) THEN
n_waves = n_waves+1
H_up(n_waves) = H_up_x(j2,i2)
H_down(n_waves) = H_down_x(j2,i2)
crest(n_waves) = crest_x(j2,i2)
L_up(n_waves) = L_up_x(j2,i2)
idx_up(n_waves) = idx_up_x(j2,i2)
idx_crest(n_waves) = idx_crest_x(j2,i2)
! transverse
L_up_t(n_waves) = L_up_y(i1,j1)
idx_up_t(n_waves) = idx_up_y(i1,j1)
idx_crest_t(n_waves) = idx_crest_y(i1,j1)
ENDIF
ENDDO
ENDDO
ENDDO
ENDDO
!
END SUBROUTINE wave_by_wave_3D
!
!
!
SUBROUTINE H_onethird(H,n_waves,H_1_3rd)
!
! Computation of H_1/3
!
REAL(RP), DIMENSION(n_waves), INTENT(IN) :: H
INTEGER, INTENT(IN) :: n_waves
REAL(RP), INTENT(OUT) :: H_1_3rd
!
! Local variables
REAL(RP), DIMENSION(n_waves) :: H_sorted
INTEGER :: twothird
!
H_sorted = H
twothird = NINT(2.0_rp/3.0_rp*n_waves)
!
! Sorting in increasing order
!
CALL sort_shell(H_sorted)
!
H_1_3rd = SUM(H_sorted(twothird:n_waves))/(n_waves-twothird+1)
!
END SUBROUTINE H_onethird
!
!
!
SUBROUTINE locate_freak(H,L,idx_crest,idx_start,n_waves,x,n1,H_lim,n_freak,H_freak,L_freak,x_freak,idx_freak)
!
! This subroutine locate the freak waves in a given 2D wavefield
!
REAL(RP), DIMENSION(n_waves), INTENT(IN) :: H, L
INTEGER, DIMENSION(n_waves), INTENT(IN) :: idx_crest, idx_start
INTEGER, INTENT(IN) :: n_waves, n1
REAL(RP), DIMENSION(n1), INTENT(IN) :: x
REAL(RP), INTENT(IN) :: H_lim
!
REAL(RP), ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: H_freak, x_freak, L_freak
INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: idx_freak
INTEGER, INTENT(OUT) :: n_freak
!
! Local variables
INTEGER :: j1, i_freak
!
!
! Number of freak waves
n_freak=0
DO j1=1,n_waves
IF(H(j1).GT.H_lim) THEN
n_freak = n_freak + 1
ENDIF
ENDDO
!
! Allocate freak waves parameters
IF(n_freak.NE.0) THEN
ALLOCATE(H_freak(n_freak),x_freak(n_freak),L_freak(n_freak), idx_freak(n_freak))
ELSE
n_freak=1
ALLOCATE(H_freak(n_freak),x_freak(n_freak),L_freak(n_freak), idx_freak(n_freak))
! Initialize
H_freak(n_freak) = 0.0_rp
x_freak(n_freak) = 0.0_rp
L_freak(n_freak) = 0.0_rp
idx_freak(n_freak) = 0
!
n_freak=0
ENDIF
!
i_freak = 0
!
DO j1=1,n_waves
IF(H(j1).GT.H_lim) THEN
i_freak = i_freak+1
H_freak(i_freak) = H(j1)
L_freak(i_freak) = L(j1)
IF (idx_crest(j1).GT.n1) THEN
x_freak(i_freak) = x(n1)+x(idx_crest(j1)-n1)
ELSE
x_freak(i_freak) = x(idx_crest(j1))
ENDIF
idx_freak(i_freak) = idx_start(j1) ! index of the beginning of the corresponding wave
ENDIF
ENDDO
!
!
END SUBROUTINE locate_freak
!
!
!
SUBROUTINE locate_freak_3D(H,L,idx_crest,idx_start,L_t,idx_crest_t,idx_start_t,n_waves,x,y,n1,n2,H_lim, &
n_freak,H_freak,L_freak,x_freak,idx_freak,L_freak_t,y_freak,idx_freak_t)
!
! This subroutine locate the freak waves in a given 3D wavefield
!
REAL(RP), DIMENSION(n_waves), INTENT(IN) :: H, L, L_t
INTEGER, DIMENSION(n_waves), INTENT(IN) :: idx_crest, idx_start, idx_crest_t, idx_start_t
INTEGER, INTENT(IN) :: n_waves, n1, n2
REAL(RP), DIMENSION(n1), INTENT(IN) :: x
REAL(RP), DIMENSION(n2), INTENT(IN) :: y
REAL(RP), INTENT(IN) :: H_lim
!
REAL(RP), ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: H_freak, x_freak, L_freak, y_freak, L_freak_t
INTEGER, ALLOCATABLE, DIMENSION(:), INTENT(OUT) :: idx_freak, idx_freak_t
INTEGER, INTENT(OUT) :: n_freak
!
! Local variables
INTEGER :: j1, i_freak
!
!
! Number of freak waves
n_freak=0
DO j1=1,n_waves
IF(H(j1).GT.H_lim) THEN
n_freak = n_freak + 1
ENDIF
ENDDO
!
! Allocate freak waves parameters
IF(n_freak.NE.0) THEN
ALLOCATE(H_freak(n_freak),x_freak(n_freak),L_freak(n_freak), idx_freak(n_freak))
ALLOCATE(y_freak(n_freak),L_freak_t(n_freak), idx_freak_t(n_freak))
ELSE
n_freak=1
ALLOCATE(H_freak(n_freak),x_freak(n_freak),L_freak(n_freak), idx_freak(n_freak))
ALLOCATE(y_freak(n_freak),L_freak_t(n_freak), idx_freak_t(n_freak))
! Initialize
H_freak(n_freak) = 0.0_rp
x_freak(n_freak) = 0.0_rp
L_freak(n_freak) = 0.0_rp
idx_freak(n_freak) = 0
y_freak(n_freak) = 0.0_rp
L_freak_t(n_freak) = 0.0_rp
idx_freak_t(n_freak) = 0
n_freak=0
ENDIF
!
i_freak = 0
!
DO j1=1,n_waves
IF(H(j1).GT.H_lim) THEN
i_freak = i_freak+1
H_freak(i_freak) = H(j1)
L_freak(i_freak) = L(j1)
IF (idx_crest(j1).GT.n1) THEN
x_freak(i_freak) = x(n1)+x(idx_crest(j1)-n1)
ELSE
x_freak(i_freak) = x(idx_crest(j1))
ENDIF
idx_freak(i_freak) = idx_start(j1) ! index of the beginning of the corresponding wave
! Transverse
L_freak_t(i_freak) = L_t(j1)
IF (idx_crest_t(j1).GT.n2) THEN
y_freak(i_freak) = y(n2)+y(idx_crest_t(j1)-n2)
ELSE
y_freak(i_freak) = y(idx_crest_t(j1))
ENDIF
idx_freak_t(i_freak) = idx_start_t(j1) ! index of the beginning of the corresponding wave
ENDIF
ENDDO
!
!
END SUBROUTINE locate_freak_3D
!
!
!
SUBROUTINE sort_shell(arr)
!
! From Numerical Recipies in Fortran
! This routine sorts an array arr into ascending order by Shell's method (diminishing increment
! sort). arr is replaced on output by its sorted arrangment
IMPLICIT NONE
!
REAL(RP), DIMENSION(:), INTENT(INOUT) :: arr
!
REAL(RP) :: v
INTEGER :: i,j,inc,n
!
n = SIZE(arr)
inc = 1
!
! Determine the starting increment
DO
inc = 3*inc+1
IF (inc > n) EXIT
ENDDO
!
! Loop over the partial sorts
DO
inc = inc / 3
! Outer loop of straight insertion
DO i = inc+1,n
v=arr(i)
j=i
! Inner loop of straight insertion
DO
IF (arr(j-inc) <= v) EXIT
arr(j) = arr(j-inc)
j=j-inc
IF (j<= inc) EXIT
ENDDO
arr(j)=v
ENDDO
IF (inc<= 1) EXIT
ENDDO
!
END SUBROUTINE
!
!
!
SUBROUTINE moment(n,data,ave,adev,sdev,var,skew,curt)
!
! From Numerical Recipies in Fortran
! Given an array of data, this routine returns its mean ave, average deviation adev, standard
! deviation sdev, variance var, skewness skew, and kurtosis curt.
!
USE type
!
IMPLICIT NONE
!
REAL(RP), INTENT(OUT) :: ave,adev,sdev,var,skew,curt
INTEGER, INTENT(IN) :: n
REAL(RP),INTENT(IN) :: data(n)
!
REAL(RP) :: ep
REAL(RP), DIMENSION(size(data)) :: p,s
!
IF (n <= 1) THEN
WRITE(*,*) 'ERREUR : moment: n must be at least 2'
STOP 1
ENDIF
!
! First pass to get the mean.
!
ave=sum(data(:))/n
!
! Second pass to get the first (absolute), second, third, and
! fourth moments of the deviation from the mean.
!
s(:)=data(:)-ave
ep=sum(s(:))
adev=sum(abs(s(:)))/n
p(:)=s(:)*s(:)
var=sum(p(:))
p(:)=p(:)*s(:)
skew=sum(p(:))
p(:)=p(:)*s(:)
curt=sum(p(:))
!
! Corrected two-pass formula.
!
var=(var-(ep**2.d0)/n)/REAL(n-1,RP)
!
sdev=sqrt(var)
!
IF (ABS(var) > tiny) THEN
skew=skew/(n*sdev**3)
curt=curt/(n*var**2)-3.0_sp
ELSE
WRITE(*,*) 'ERREUR : moment: no skew or kurtosis when zero variance'
STOP 1
ENDIF
!
END SUBROUTINE
!
END MODULE analysis_wavefield
|
LHEEA/HOS-ocean
|
sources/PostProcessing/analysis_wavefield.f90
|
FORTRAN
|
gpl-3.0
| 18,943
|
/* BEEBS rijndael benchmark
Copyright (C) 2014 Embecosm Limited and University of Bristol
This file is part of the Bristol/Embecosm Embedded Benchmark Suite.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* The original version of this file was released with the following
copyright, license and disclaimer:
-----------------------------------------------------------------------
Copyright (c) 2001 Dr Brian Gladman <brg@gladman.uk.net>, Worcester, UK
TERMS
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, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
This software is provided 'as is' with no guarantees of correctness or
fitness for purpose.
-----------------------------------------------------------------------
*/
/* Example of the use of the AES (Rijndael) algorithm for file */
/* encryption. Note that this is an example application, it is */
/* not intended for real operational use. The Command line is: */
/* */
/* aesxam input_file_name output_file_name [D|E] hexadecimalkey */
/* */
/* where E gives encryption and D decryption of the input file */
/* into the output file using the given hexadecimal key string */
/* The later is a hexadecimal sequence of 32, 48 or 64 digits */
/* Examples to encrypt or decrypt aes.c into aes.enc are: */
/* */
/* aesxam file.c file.enc E 0123456789abcdeffedcba9876543210 */
/* */
/* aesxam file.enc file2.c D 0123456789abcdeffedcba9876543210 */
/* */
/* which should return a file 'file2.c' identical to 'file.c' */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "aes.h"
#include "support.h"
/* This scale factor will be changed to equalise the runtime of the
benchmarks. */
#define SCALE_FACTOR (REPEAT_FACTOR >> 9)
#ifndef fpos_t
#define fpos_t size_t
#endif
#define FLEN flen
#define RAND(a,b) (((a = 36969 * (a & 65535) + (a >> 16)) << 16) + (b = 18000 * (b & 65535) + (b >> 16)) )
void fillrand(byte *buf, int len)
{
static unsigned long a[2], mt = 1, count = 4;
static char r[4];
int i;
if(mt) {
mt = 0;
/*cycles(a);*/
a[0]=0xeaf3;
a[1]=0x35fe;
}
for(i = 0; i < len; ++i)
{
if(count == 4)
{
*(unsigned long*)r = RAND(a[0], a[1]);
count = 0;
}
buf[i] = r[count++];
}
}
int encfile(aes *ctx, byte *outbuf)
{
byte inbuf[16];
fpos_t flen;
unsigned long i=0, j, k;
fillrand(outbuf, 16); /* set an IV for CBC mode */
FLEN = 4096;
fillrand(inbuf, 1); /* make top 4 bits of a byte random */
/* block in the lower 4 bits */
inbuf[0] = ((char)FLEN & 15) | (inbuf[0] & ~15);
for(j = 0; j <256; j++)
{ /* input 1st 16 bytes to buf[1..16] */
for(k = 0; k < 16; ++k)
inbuf[k] = rand();
for(i = 0; i < 16; ++i) /* xor in previous cipher text */
inbuf[i] ^= outbuf[i];
encrypt(inbuf, outbuf, ctx); /* and do the encryption */
/* in all but first round read 16 */
}
return 0;
}
int decfile(aes *ctx, byte *outbuf)
{
byte inbuf1[16], inbuf2[16], *bp1, *bp2, *tp;
int i,j, k;
fillrand(inbuf1, 16); /* set an IV for CBC mode */
for(k = 0; k < 16; ++k)
inbuf2[k] = rand();
decrypt(inbuf2, outbuf, ctx); /* decrypt it */
for(i = 0; i < 16; ++i) /* xor with previous input */
outbuf[i] ^= inbuf1[i];
bp1 = inbuf1; /* set up pointers to two input buffers */
bp2 = inbuf2;
for(j = 0; j < 256; ++j)
{
for(k = 0; k < 16; ++k)
bp1[k] = rand();
decrypt(bp1, outbuf, ctx); /* decrypt the new input block and */
for(i = 0; i < 16; ++i) /* xor it with previous input block */
outbuf[i] ^= bp2[i];
/* Swap buffer pointers. */
tp = bp1, bp1 = bp2, bp2 = tp;
}
return 0;
}
char *presetkey="ABCDEF1234567890ABCDEF1234567890";
int benchmark()
{
char *cp=0, ch=0;
byte key[32]={0};
int i=0, by=0, key_len=0, err=0;
byte encoutbuf[16], decoutbuf[16];
{
aes ctx = {0};
by=0; key_len=0; err = 0;
cp = presetkey; /* this is a pointer to the hexadecimal key digits */
i = 0; /* this is a count for the input digits processed */
while(i < 64 && *cp) /* the maximum key length is 32 bytes and */
{ /* hence at most 64 hexadecimal digits */
ch = *cp++; /* process a hexadecimal digit */
if(ch >= '0' && ch <= '9')
by = (by << 4) + ch - '0';
else if(ch >= 'A' && ch <= 'F')
by = (by << 4) + ch - 'A' + 10;
else /* error if not hexadecimal */
{
err = -2; goto exit;
}
/* store a key byte for each pair of hexadecimal digits */
if(i++ & 1)
key[i / 2 - 1] = by & 0xff;
}
if(*cp)
{
err = -3; goto exit;
}
else if(i < 32 || (i & 15))
{
err = -4; goto exit;
}
key_len = i / 2;
set_key(key, key_len, enc, &ctx);
err = encfile(&ctx, encoutbuf);
set_key(key, key_len, dec, &ctx);
err = decfile(&ctx, decoutbuf);
}
exit:
return err;
}
/* vim: set ts=3 sw=3 et: */
|
craigblackmore/beebs
|
src/rijndael/aesxam.c
|
C
|
gpl-3.0
| 6,774
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TabuSearch.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.bayes.net.search.global;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.bayes.BayesNet;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
/**
<!-- globalinfo-start -->
* This Bayes Network learning algorithm uses tabu search for finding a well scoring Bayes network structure. Tabu search is hill climbing till an optimum is reached. The following step is the least worst possible step. The last X steps are kept in a list and none of the steps in this so called tabu list is considered in taking the next step. The best network found in this traversal is returned.<br/>
* <br/>
* For more information see:<br/>
* <br/>
* R.R. Bouckaert (1995). Bayesian Belief Networks: from Construction to Inference. Utrecht, Netherlands.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @phdthesis{Bouckaert1995,
* address = {Utrecht, Netherlands},
* author = {R.R. Bouckaert},
* institution = {University of Utrecht},
* title = {Bayesian Belief Networks: from Construction to Inference},
* year = {1995}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -L <integer>
* Tabu list length</pre>
*
* <pre> -U <integer>
* Number of runs</pre>
*
* <pre> -P <nr of parents>
* Maximum number of parents</pre>
*
* <pre> -R
* Use arc reversal operation.
* (default false)</pre>
*
* <pre> -P <nr of parents>
* Maximum number of parents</pre>
*
* <pre> -R
* Use arc reversal operation.
* (default false)</pre>
*
* <pre> -N
* Initial structure is empty (instead of Naive Bayes)</pre>
*
* <pre> -mbc
* Applies a Markov Blanket correction to the network structure,
* after a network structure is learned. This ensures that all
* nodes in the network are part of the Markov blanket of the
* classifier node.</pre>
*
* <pre> -S [LOO-CV|k-Fold-CV|Cumulative-CV]
* Score type (LOO-CV,k-Fold-CV,Cumulative-CV)</pre>
*
* <pre> -Q
* Use probabilistic or 0/1 scoring.
* (default probabilistic scoring)</pre>
*
<!-- options-end -->
*
* @author Remco Bouckaert (rrb@xm.co.nz)
* @version $Revision: 8034 $
*/
public class TabuSearch
extends HillClimber
implements TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = 1176705618756672292L;
/** number of runs **/
int m_nRuns = 10;
/** size of tabu list **/
int m_nTabuList = 5;
/** the actual tabu list **/
Operation[] m_oTabuList = null;
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.PHDTHESIS);
result.setValue(Field.AUTHOR, "R.R. Bouckaert");
result.setValue(Field.YEAR, "1995");
result.setValue(Field.TITLE, "Bayesian Belief Networks: from Construction to Inference");
result.setValue(Field.INSTITUTION, "University of Utrecht");
result.setValue(Field.ADDRESS, "Utrecht, Netherlands");
return result;
}
/**
* search determines the network structure/graph of the network
* with the Tabu search algorithm.
*
* @param bayesNet the network to use
* @param instances the instances to use
* @throws Exception if something goes wrong
*/
protected void search(BayesNet bayesNet, Instances instances) throws Exception {
m_oTabuList = new Operation[m_nTabuList];
int iCurrentTabuList = 0;
// keeps track of score pf best structure found so far
double fBestScore;
double fCurrentScore = calcScore(bayesNet);
// keeps track of best structure found so far
BayesNet bestBayesNet;
// initialize bestBayesNet
fBestScore = fCurrentScore;
bestBayesNet = new BayesNet();
bestBayesNet.m_Instances = instances;
bestBayesNet.initStructure();
copyParentSets(bestBayesNet, bayesNet);
// go do the search
for (int iRun = 0; iRun < m_nRuns; iRun++) {
Operation oOperation = getOptimalOperation(bayesNet, instances);
performOperation(bayesNet, instances, oOperation);
// sanity check
if (oOperation == null) {
throw new Exception("Panic: could not find any step to make. Tabu list too long?");
}
// update tabu list
m_oTabuList[iCurrentTabuList] = oOperation;
iCurrentTabuList = (iCurrentTabuList + 1) % m_nTabuList;
fCurrentScore += oOperation.m_fScore;
// keep track of best network seen so far
if (fCurrentScore > fBestScore) {
fBestScore = fCurrentScore;
copyParentSets(bestBayesNet, bayesNet);
}
if (bayesNet.getDebug()) {
printTabuList();
}
if(Thread.interrupted())
break;
}
// restore current network to best network
copyParentSets(bayesNet, bestBayesNet);
// free up memory
bestBayesNet = null;
} // search
/** copyParentSets copies parent sets of source to dest BayesNet
* @param dest destination network
* @param source source network
*/
void copyParentSets(BayesNet dest, BayesNet source) {
int nNodes = source.getNrOfNodes();
// clear parent set first
for (int iNode = 0; iNode < nNodes; iNode++) {
dest.getParentSet(iNode).copy(source.getParentSet(iNode));
}
} // CopyParentSets
/** check whether the operation is not in the tabu list
* @param oOperation operation to be checked
* @return true if operation is not in the tabu list
*/
boolean isNotTabu(Operation oOperation) {
for (int iTabu = 0; iTabu < m_nTabuList; iTabu++) {
if (oOperation.equals(m_oTabuList[iTabu])) {
return false;
}
}
return true;
} // isNotTabu
/** print tabu list for debugging purposes.
*/
void printTabuList() {
for (int i = 0; i < m_nTabuList; i++) {
Operation o = m_oTabuList[i];
if (o != null) {
if (o.m_nOperation == 0) {System.out.print(" +(");} else {System.out.print(" -(");}
System.out.print(o.m_nTail + "->" + o.m_nHead + ")");
}
}
System.out.println();
} // printTabuList
/**
* @return number of runs
*/
public int getRuns() {
return m_nRuns;
} // getRuns
/**
* Sets the number of runs
* @param nRuns The number of runs to set
*/
public void setRuns(int nRuns) {
m_nRuns = nRuns;
} // setRuns
/**
* @return the Tabu List length
*/
public int getTabuList() {
return m_nTabuList;
} // getTabuList
/**
* Sets the Tabu List length.
* @param nTabuList The nTabuList to set
*/
public void setTabuList(int nTabuList) {
m_nTabuList = nTabuList;
} // setTabuList
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(4);
newVector.addElement(new Option("\tTabu list length", "L", 1, "-L <integer>"));
newVector.addElement(new Option("\tNumber of runs", "U", 1, "-U <integer>"));
newVector.addElement(new Option("\tMaximum number of parents", "P", 1, "-P <nr of parents>"));
newVector.addElement(new Option("\tUse arc reversal operation.\n\t(default false)", "R", 0, "-R"));
Enumeration enu = super.listOptions();
while (enu.hasMoreElements()) {
newVector.addElement(enu.nextElement());
}
return newVector.elements();
} // listOptions
/**
* Parses a given list of options. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -L <integer>
* Tabu list length</pre>
*
* <pre> -U <integer>
* Number of runs</pre>
*
* <pre> -P <nr of parents>
* Maximum number of parents</pre>
*
* <pre> -R
* Use arc reversal operation.
* (default false)</pre>
*
* <pre> -P <nr of parents>
* Maximum number of parents</pre>
*
* <pre> -R
* Use arc reversal operation.
* (default false)</pre>
*
* <pre> -N
* Initial structure is empty (instead of Naive Bayes)</pre>
*
* <pre> -mbc
* Applies a Markov Blanket correction to the network structure,
* after a network structure is learned. This ensures that all
* nodes in the network are part of the Markov blanket of the
* classifier node.</pre>
*
* <pre> -S [LOO-CV|k-Fold-CV|Cumulative-CV]
* Score type (LOO-CV,k-Fold-CV,Cumulative-CV)</pre>
*
* <pre> -Q
* Use probabilistic or 0/1 scoring.
* (default probabilistic scoring)</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
String sTabuList = Utils.getOption('L', options);
if (sTabuList.length() != 0) {
setTabuList(Integer.parseInt(sTabuList));
}
String sRuns = Utils.getOption('U', options);
if (sRuns.length() != 0) {
setRuns(Integer.parseInt(sRuns));
}
super.setOptions(options);
} // setOptions
/**
* Gets the current settings of the search algorithm.
*
* @return an array of strings suitable for passing to setOptions
*/
public String[] getOptions() {
String[] superOptions = super.getOptions();
String[] options = new String[7 + superOptions.length];
int current = 0;
options[current++] = "-L";
options[current++] = "" + getTabuList();
options[current++] = "-U";
options[current++] = "" + getRuns();
// insert options from parent class
for (int iOption = 0; iOption < superOptions.length; iOption++) {
options[current++] = superOptions[iOption];
}
// Fill up rest with empty strings, not nulls!
while (current < options.length) {
options[current++] = "";
}
return options;
} // getOptions
/**
* This will return a string describing the classifier.
* @return The string.
*/
public String globalInfo() {
return "This Bayes Network learning algorithm uses tabu search for finding a well scoring " +
"Bayes network structure. Tabu search is hill climbing till an optimum is reached. The " +
"following step is the least worst possible step. The last X steps are kept in a list and " +
"none of the steps in this so called tabu list is considered in taking the next step. " +
"The best network found in this traversal is returned.\n\n"
+ "For more information see:\n\n"
+ getTechnicalInformation().toString();
} // globalInfo
/**
* @return a string to describe the Runs option.
*/
public String runsTipText() {
return "Sets the number of steps to be performed.";
} // runsTipText
/**
* @return a string to describe the TabuList option.
*/
public String tabuListTipText() {
return "Sets the length of the tabu list.";
} // tabuListTipText
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision: 8034 $");
}
} // TabuSearch
|
dsibournemouth/autoweka
|
weka-3.7.7/src/main/java/weka/classifiers/bayes/net/search/global/TabuSearch.java
|
Java
|
gpl-3.0
| 12,267
|
<?php
namespace InstagramAPI\Response\Model;
use InstagramAPI\AutoPropertyHandler;
/**
* @method mixed getBlocking()
* @method mixed getFollowedBy()
* @method mixed getFollowing()
* @method mixed getIncomingRequest()
* @method mixed getIsBestie()
* @method mixed getIsBlockingReel()
* @method mixed getIsMutingReel()
* @method mixed getIsPrivate()
* @method mixed getOutgoingRequest()
* @method bool isBlocking()
* @method bool isFollowedBy()
* @method bool isFollowing()
* @method bool isIncomingRequest()
* @method bool isIsBestie()
* @method bool isIsBlockingReel()
* @method bool isIsMutingReel()
* @method bool isIsPrivate()
* @method bool isOutgoingRequest()
* @method setBlocking(mixed $value)
* @method setFollowedBy(mixed $value)
* @method setFollowing(mixed $value)
* @method setIncomingRequest(mixed $value)
* @method setIsBestie(mixed $value)
* @method setIsBlockingReel(mixed $value)
* @method setIsMutingReel(mixed $value)
* @method setIsPrivate(mixed $value)
* @method setOutgoingRequest(mixed $value)
*/
class FriendshipStatus extends AutoPropertyHandler
{
// NOTE: We must use full paths to all model objects in THIS class, because
// "FriendshipsShowResponse" re-uses this object and JSONMapper won't be
// able to find these sub-objects if the paths aren't absolute!
public $following;
public $followed_by;
public $incoming_request;
public $outgoing_request;
public $is_private;
public $is_blocking_reel;
public $is_muting_reel;
public $blocking;
public $is_bestie;
}
|
kotsios5/openclassifieds2
|
oc/vendor/Instagram-API/vendor/mgp25/instagram-php/src/Response/Model/FriendshipStatus.php
|
PHP
|
gpl-3.0
| 1,567
|
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Authorization\Test\Unit\Model\Acl;
use \Magento\Authorization\Model\Acl\AclRetriever;
use Magento\Authorization\Model\ResourceModel\Role\Collection as RoleCollection;
use Magento\Authorization\Model\ResourceModel\Role\CollectionFactory as RoleCollectionFactory;
use Magento\Authorization\Model\ResourceModel\Rules\Collection as RulesCollection;
use Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory as RulesCollectionFactory;
use Magento\Authorization\Model\Role;
use Magento\Authorization\Model\UserContextInterface;
class AclRetrieverTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AclRetriever
*/
protected $aclRetriever;
/** @var \PHPUnit_Framework_MockObject_MockObject|Role $roleMock */
protected $roleMock;
protected function setup()
{
$this->aclRetriever = $this->createAclRetriever();
}
public function testGetAllowedResourcesByUserTypeGuest()
{
$expectedResources = ['anonymous'];
$allowedResources = $this->aclRetriever->getAllowedResourcesByUser(UserContextInterface::USER_TYPE_GUEST, null);
$this->assertEquals(
$expectedResources,
$allowedResources,
'Allowed resources for guests should be \'anonymous\'.'
);
}
public function testGetAllowedResourcesByUserTypeCustomer()
{
$expectedResources = ['self'];
$allowedResources = $this->aclRetriever->getAllowedResourcesByUser(
UserContextInterface::USER_TYPE_CUSTOMER,
null
);
$this->assertEquals(
$expectedResources,
$allowedResources,
'Allowed resources for customers should be \'self\'.'
);
}
/**
* @expectedException \Magento\Framework\Exception\AuthorizationException
* @expectedExceptionMessage We can't find the role for the user you wanted.
*/
public function testGetAllowedResourcesByUserRoleNotFound()
{
$this->roleMock->expects($this->once())->method('getId')->will($this->returnValue(null));
$this->aclRetriever->getAllowedResourcesByUser(UserContextInterface::USER_TYPE_INTEGRATION, null);
}
public function testGetAllowedResourcesByUser()
{
$this->roleMock->expects($this->any())->method('getId')->will($this->returnValue(1));
$expectedResources = ['Magento_Backend::dashboard', 'Magento_Cms::page'];
$this->assertEquals(
$expectedResources,
$this->aclRetriever->getAllowedResourcesByUser(UserContextInterface::USER_TYPE_INTEGRATION, 1)
);
}
protected function createAclRetriever()
{
$this->roleMock = $this->getMock(
'Magento\Authorization\Model\Role',
['getId', '__wakeup'],
[],
'',
false
);
/** @var \PHPUnit_Framework_MockObject_MockObject|RoleCollection $roleCollectionMock */
$roleCollectionMock = $this->getMock(
'Magento\Authorization\Model\ResourceModel\Role\Collection',
['setUserFilter', 'getFirstItem'],
[],
'',
false
);
$roleCollectionMock->expects($this->any())->method('setUserFilter')->will($this->returnSelf());
$roleCollectionMock->expects($this->any())->method('getFirstItem')->will($this->returnValue($this->roleMock));
/** @var \PHPUnit_Framework_MockObject_MockObject|RoleCollectionFactory $roleCollectionFactoryMock */
$roleCollectionFactoryMock = $this->getMock(
'Magento\Authorization\Model\ResourceModel\Role\CollectionFactory',
['create'],
[],
'',
false
);
$roleCollectionFactoryMock->expects($this->any())->method('create')->will(
$this->returnValue($roleCollectionMock)
);
/** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Authorization\Model\Rules $rulesMock1 */
$rulesMock1 = $this->getMock(
'Magento\Authorization\Model\Rules',
['getResourceId', '__wakeup'],
[],
'',
false
);
$rulesMock1->expects($this->any())->method('getResourceId')->will(
$this->returnValue('Magento_Backend::dashboard')
);
/** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Authorization\Model\Rules $rulesMock1 */
$rulesMock2 = $this->getMock(
'Magento\Authorization\Model\Rules',
['getResourceId', '__wakeup'],
[],
'',
false
);
$rulesMock2->expects($this->any())->method('getResourceId')->will($this->returnValue('Magento_Cms::page'));
/** @var \PHPUnit_Framework_MockObject_MockObject|RulesCollection $rulesCollectionMock */
$rulesCollectionMock = $this->getMock(
'Magento\Authorization\Model\ResourceModel\Rules\Collection',
['getByRoles', 'load', 'getItems'],
[],
'',
false
);
$rulesCollectionMock->expects($this->any())->method('getByRoles')->will($this->returnSelf());
$rulesCollectionMock->expects($this->any())->method('load')->will($this->returnSelf());
$rulesCollectionMock->expects($this->any())->method('getItems')->will(
$this->returnValue([$rulesMock1, $rulesMock2])
);
/** @var \PHPUnit_Framework_MockObject_MockObject|RulesCollectionFactory $rulesCollectionFactoryMock */
$rulesCollectionFactoryMock = $this->getMock(
'Magento\Authorization\Model\ResourceModel\Rules\CollectionFactory',
['create'],
[],
'',
false
);
$rulesCollectionFactoryMock->expects($this->any())->method('create')->will(
$this->returnValue($rulesCollectionMock)
);
/** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Acl $aclMock */
$aclMock = $this->getMock('Magento\Framework\Acl', ['has', 'isAllowed'], [], '', false);
$aclMock->expects($this->any())->method('has')->will($this->returnValue(true));
$aclMock->expects($this->any())->method('isAllowed')->will($this->returnValue(true));
/** @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Acl\Builder $aclBuilderMock */
$aclBuilderMock = $this->getMock('Magento\Framework\Acl\Builder', ['getAcl'], [], '', false);
$aclBuilderMock->expects($this->any())->method('getAcl')->will($this->returnValue($aclMock));
return new AclRetriever(
$aclBuilderMock,
$roleCollectionFactoryMock,
$rulesCollectionFactoryMock,
$this->getMock('Psr\Log\LoggerInterface')
);
}
}
|
rajmahesh/magento2-master
|
vendor/magento/module-authorization/Test/Unit/Model/Acl/AclRetrieverTest.php
|
PHP
|
gpl-3.0
| 6,904
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
struct MultiTimerCallback : public Timer
{
MultiTimerCallback (const int tid, MultiTimer& mt) noexcept
: owner (mt), timerID (tid)
{
}
void timerCallback() override
{
owner.timerCallback (timerID);
}
MultiTimer& owner;
const int timerID;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultiTimerCallback)
};
//==============================================================================
MultiTimer::MultiTimer() noexcept {}
MultiTimer::MultiTimer (const MultiTimer&) noexcept {}
MultiTimer::~MultiTimer()
{
const SpinLock::ScopedLockType sl (timerListLock);
timers.clear();
}
//==============================================================================
Timer* MultiTimer::getCallback (int timerID) const noexcept
{
for (int i = timers.size(); --i >= 0;)
{
MultiTimerCallback* const t = static_cast<MultiTimerCallback*> (timers.getUnchecked(i));
if (t->timerID == timerID)
return t;
}
return nullptr;
}
void MultiTimer::startTimer (const int timerID, const int intervalInMilliseconds) noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
Timer* timer = getCallback (timerID);
if (timer == nullptr)
timers.add (timer = new MultiTimerCallback (timerID, *this));
timer->startTimer (intervalInMilliseconds);
}
void MultiTimer::stopTimer (const int timerID) noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
if (Timer* const t = getCallback (timerID))
t->stopTimer();
}
bool MultiTimer::isTimerRunning (const int timerID) const noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
if (Timer* const t = getCallback (timerID))
return t->isTimerRunning();
return false;
}
int MultiTimer::getTimerInterval (const int timerID) const noexcept
{
const SpinLock::ScopedLockType sl (timerListLock);
if (Timer* const t = getCallback (timerID))
return t->getTimerInterval();
return 0;
}
|
TheTechnobear/MEC
|
mec-vst/JuceLibraryCode/modules/juce_events/timers/juce_MultiTimer.cpp
|
C++
|
gpl-3.0
| 2,991
|
package org.thoughtcrime.securesms.preferences;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.preference.Preference;
import com.annimon.stream.Stream;
import org.signal.core.util.concurrent.SignalExecutors;
import org.thoughtcrime.securesms.R;
import org.thoughtcrime.securesms.components.settings.BaseSettingsAdapter;
import org.thoughtcrime.securesms.components.settings.BaseSettingsFragment;
import org.thoughtcrime.securesms.components.settings.CustomizableSingleSelectSetting;
import org.thoughtcrime.securesms.components.settings.SingleSelectSetting;
import org.thoughtcrime.securesms.components.settings.app.wrapped.SettingsWrapperFragment;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies;
import org.thoughtcrime.securesms.keyvalue.KeepMessagesDuration;
import org.thoughtcrime.securesms.keyvalue.SettingsValues;
import org.thoughtcrime.securesms.keyvalue.SignalStore;
import org.thoughtcrime.securesms.mediaoverview.MediaOverviewActivity;
import org.thoughtcrime.securesms.permissions.Permissions;
import org.thoughtcrime.securesms.preferences.widgets.StoragePreferenceCategory;
import org.thoughtcrime.securesms.util.MappingModelList;
import org.thoughtcrime.securesms.util.StringUtil;
import java.text.NumberFormat;
public class StoragePreferenceFragment extends ListSummaryPreferenceFragment {
private Preference keepMessages;
private Preference trimLength;
@Override
public void onCreate(@Nullable Bundle paramBundle) {
super.onCreate(paramBundle);
findPreference("pref_storage_clear_message_history")
.setOnPreferenceClickListener(new ClearMessageHistoryClickListener());
trimLength = findPreference(SettingsValues.THREAD_TRIM_LENGTH);
trimLength.setOnPreferenceClickListener(p -> {
updateToolbarTitle(R.string.preferences__conversation_length_limit);
pushFragment(BaseSettingsFragment.create(new ConversationLengthLimitConfiguration()));
return true;
});
keepMessages = findPreference(SettingsValues.KEEP_MESSAGES_DURATION);
keepMessages.setOnPreferenceClickListener(p -> {
updateToolbarTitle(R.string.preferences__keep_messages);
pushFragment(BaseSettingsFragment.create(new KeepMessagesConfiguration()));
return true;
});
StoragePreferenceCategory storageCategory = (StoragePreferenceCategory) findPreference("pref_storage_category");
FragmentActivity activity = requireActivity();
ApplicationPreferencesViewModel viewModel = ApplicationPreferencesViewModel.getApplicationPreferencesViewModel(activity);
storageCategory.setOnFreeUpSpace(() -> activity.startActivity(MediaOverviewActivity.forAll(activity)));
viewModel.getStorageBreakdown().observe(activity, storageCategory::setStorage);
}
@Override
public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
addPreferencesFromResource(R.xml.preferences_storage);
}
@Override
public void onResume() {
super.onResume();
updateToolbarTitle(R.string.preferences__storage);
FragmentActivity activity = requireActivity();
ApplicationPreferencesViewModel viewModel = ApplicationPreferencesViewModel.getApplicationPreferencesViewModel(activity);
viewModel.refreshStorageBreakdown(activity.getApplicationContext());
keepMessages.setSummary(SignalStore.settings().getKeepMessagesDuration().getStringResource());
trimLength.setSummary(SignalStore.settings().isTrimByLengthEnabled() ? getString(R.string.preferences_storage__s_messages, NumberFormat.getInstance().format(SignalStore.settings().getThreadTrimLength()))
: getString(R.string.preferences_storage__none));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Permissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
private void updateToolbarTitle(@StringRes int title) {
if (getParentFragment() instanceof SettingsWrapperFragment) {
((SettingsWrapperFragment) getParentFragment()).setTitle(title);
}
}
private void pushFragment(@NonNull Fragment fragment) {
getParentFragmentManager().beginTransaction()
.replace(R.id.wrapped_fragment, fragment)
.addToBackStack(null)
.commit();
}
private class ClearMessageHistoryClickListener implements Preference.OnPreferenceClickListener {
@Override
public boolean onPreferenceClick(@NonNull Preference preference) {
new AlertDialog.Builder(requireActivity())
.setTitle(R.string.preferences_storage__clear_message_history)
.setMessage(R.string.preferences_storage__this_will_delete_all_message_history_and_media_from_your_device)
.setPositiveButton(R.string.delete, (d, w) -> showAreYouReallySure())
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
}
private void showAreYouReallySure() {
new AlertDialog.Builder(requireActivity())
.setTitle(R.string.preferences_storage__are_you_sure_you_want_to_delete_all_message_history)
.setMessage(R.string.preferences_storage__all_message_history_will_be_permanently_removed_this_action_cannot_be_undone)
.setPositiveButton(R.string.preferences_storage__delete_all_now, (d, w) -> SignalExecutors.BOUNDED.execute(() -> DatabaseFactory.getThreadDatabase(ApplicationDependencies.getApplication()).deleteAllConversations()))
.setNegativeButton(android.R.string.cancel, null)
.show();
}
}
public static class KeepMessagesConfiguration extends BaseSettingsFragment.Configuration implements SingleSelectSetting.SingleSelectSelectionChangedListener {
@Override
public void configureAdapter(@NonNull BaseSettingsAdapter adapter) {
adapter.configureSingleSelect(this);
}
@Override
public @NonNull MappingModelList getSettings() {
KeepMessagesDuration currentDuration = SignalStore.settings().getKeepMessagesDuration();
return Stream.of(KeepMessagesDuration.values())
.map(duration -> new SingleSelectSetting.Item(duration, activity.getString(duration.getStringResource()), null, duration.equals(currentDuration)))
.collect(MappingModelList.toMappingModelList());
}
@Override
public void onSelectionChanged(@NonNull Object selection) {
KeepMessagesDuration currentDuration = SignalStore.settings().getKeepMessagesDuration();
KeepMessagesDuration newDuration = (KeepMessagesDuration) selection;
if (newDuration.ordinal() > currentDuration.ordinal()) {
new AlertDialog.Builder(activity)
.setTitle(R.string.preferences_storage__delete_older_messages)
.setMessage(activity.getString(R.string.preferences_storage__this_will_permanently_delete_all_message_history_and_media, activity.getString(newDuration.getStringResource())))
.setPositiveButton(R.string.delete, (d, w) -> updateTrimByTime(newDuration))
.setNegativeButton(android.R.string.cancel, null)
.show();
} else {
updateTrimByTime(newDuration);
}
}
private void updateTrimByTime(@NonNull KeepMessagesDuration newDuration) {
SignalStore.settings().setKeepMessagesForDuration(newDuration);
updateSettingsList();
ApplicationDependencies.getTrimThreadsByDateManager().scheduleIfNecessary();
}
}
public static class ConversationLengthLimitConfiguration extends BaseSettingsFragment.Configuration implements CustomizableSingleSelectSetting.CustomizableSingleSelectionListener {
private static final int CUSTOM_LENGTH = -1;
@Override
public void configureAdapter(@NonNull BaseSettingsAdapter adapter) {
adapter.configureSingleSelect(this);
adapter.configureCustomizableSingleSelect(this);
}
@Override
public @NonNull MappingModelList getSettings() {
int trimLength = SignalStore.settings().isTrimByLengthEnabled() ? SignalStore.settings().getThreadTrimLength() : 0;
int[] options = activity.getResources().getIntArray(R.array.conversation_length_limit);
boolean hasSelection = false;
MappingModelList settings = new MappingModelList();
for (int option : options) {
boolean isSelected = option == trimLength;
String text = option == 0 ? activity.getString(R.string.preferences_storage__none)
: activity.getString(R.string.preferences_storage__s_messages, NumberFormat.getInstance().format(option));
settings.add(new SingleSelectSetting.Item(option, text, null, isSelected));
hasSelection = hasSelection || isSelected;
}
int currentValue = SignalStore.settings().getThreadTrimLength();
settings.add(new CustomizableSingleSelectSetting.Item(CUSTOM_LENGTH,
activity.getString(R.string.preferences_storage__custom),
!hasSelection,
currentValue,
activity.getString(R.string.preferences_storage__s_messages, NumberFormat.getInstance().format(currentValue))));
return settings;
}
@SuppressLint("InflateParams")
@Override
public void onCustomizeClicked(@Nullable CustomizableSingleSelectSetting.Item item) {
boolean trimLengthEnabled = SignalStore.settings().isTrimByLengthEnabled();
int trimLength = trimLengthEnabled ? SignalStore.settings().getThreadTrimLength() : 0;
View view = LayoutInflater.from(activity).inflate(R.layout.customizable_setting_edit_text, null, false);
EditText editText = view.findViewById(R.id.customizable_setting_edit_text);
if (trimLength > 0) {
editText.setText(String.valueOf(trimLength));
}
AlertDialog dialog = new AlertDialog.Builder(activity)
.setTitle(R.string.preferences__conversation_length_limit)
.setView(view)
.setPositiveButton(android.R.string.ok, (d, w) -> onSelectionChanged(Integer.parseInt(editText.getText().toString())))
.setNegativeButton(android.R.string.cancel, (d, w) -> updateSettingsList())
.create();
dialog.setOnShowListener(d -> {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(!TextUtils.isEmpty(editText.getText()));
editText.requestFocus();
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(@NonNull Editable sequence) {
CharSequence trimmed = StringUtil.trimSequence(sequence);
if (TextUtils.isEmpty(trimmed)) {
sequence.replace(0, sequence.length(), "");
} else {
try {
Integer.parseInt(trimmed.toString());
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
return;
} catch (NumberFormatException e) {
String onlyDigits = trimmed.toString().replaceAll("[^\\d]", "");
if (!onlyDigits.equals(trimmed.toString())) {
sequence.replace(0, sequence.length(), onlyDigits);
}
}
}
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
}
@Override
public void beforeTextChanged(@NonNull CharSequence sequence, int start, int count, int after) {}
@Override
public void onTextChanged(@NonNull CharSequence sequence, int start, int before, int count) {}
});
});
dialog.show();
}
@Override
public void onSelectionChanged(@NonNull Object selection) {
boolean trimLengthEnabled = SignalStore.settings().isTrimByLengthEnabled();
int trimLength = trimLengthEnabled ? SignalStore.settings().getThreadTrimLength() : 0;
int newTrimLength = (Integer) selection;
if (newTrimLength > 0 && (!trimLengthEnabled || newTrimLength < trimLength)) {
new AlertDialog.Builder(activity)
.setTitle(R.string.preferences_storage__delete_older_messages)
.setMessage(activity.getString(R.string.preferences_storage__this_will_permanently_trim_all_conversations_to_the_d_most_recent_messages, NumberFormat.getInstance().format(newTrimLength)))
.setPositiveButton(R.string.delete, (d, w) -> updateTrimByLength(newTrimLength))
.setNegativeButton(android.R.string.cancel, null)
.show();
} else if (newTrimLength == CUSTOM_LENGTH) {
onCustomizeClicked(null);
} else {
updateTrimByLength(newTrimLength);
}
}
private void updateTrimByLength(int length) {
boolean restrictingChange = !SignalStore.settings().isTrimByLengthEnabled() || length < SignalStore.settings().getThreadTrimLength();
SignalStore.settings().setThreadTrimByLengthEnabled(length > 0);
SignalStore.settings().setThreadTrimLength(length);
updateSettingsList();
if (SignalStore.settings().isTrimByLengthEnabled() && restrictingChange) {
KeepMessagesDuration keepMessagesDuration = SignalStore.settings().getKeepMessagesDuration();
long trimBeforeDate = keepMessagesDuration != KeepMessagesDuration.FOREVER ? System.currentTimeMillis() - keepMessagesDuration.getDuration()
: ThreadDatabase.NO_TRIM_BEFORE_DATE_SET;
SignalExecutors.BOUNDED.execute(() -> DatabaseFactory.getThreadDatabase(ApplicationDependencies.getApplication()).trimAllThreads(length, trimBeforeDate));
}
}
}
}
|
cascheberg/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/preferences/StoragePreferenceFragment.java
|
Java
|
gpl-3.0
| 14,934
|
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<base href="./app/">
<link rel="stylesheet" href="app.css">
<link rel="stylesheet" href="../node_modules/ionicons/dist/css/ionicons.css">
</head>
<body>
<header id="appheader"></header>
<nav id="nav"></nav>
<aside id="subnav"></aside>
<div id="addressbar"></div>
<div id="history"></div>
<section id="frame"></section>
<section class="settings"></section>
<script src="app.js"></script>
</body>
|
tborychowski/tim
|
index.html
|
HTML
|
gpl-3.0
| 545
|
@extends('layouts.master')
@section('content')
<div class='row'>
<div class='col-md-12'>
<!-- Box -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">{{ trans('admin/permissions/general.page.create.section-title') }}</h3>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"><i class="fa fa-minus"></i></button>
</div>
</div>
<div class="box-body">
{!! Form::open( ['route' => 'admin.permissions.store'] ) !!}
@include('partials._permission_form')
<div class="form-group">
{!! Form::submit( trans('general.button.create'), ['class' => 'btn btn-primary'] ) !!}
<a href="{!! route('admin.permissions.index') !!}" title="{{ trans('general.button.cancel') }}" class='btn btn-default'>{{ trans('general.button.cancel') }}</a>
</div>
{!! Form::close() !!}
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
@endsection
|
ssv445/laravel-5.1-enterprise-starter-kit
|
resources/themes/default/views/admin/permissions/create.blade.php
|
PHP
|
gpl-3.0
| 1,332
|
<?php
/**
* NGINAD Project
*
* @link http://www.nginad.com
* @copyright Copyright (c) 2013-2016 NginAd Foundation. All Rights Reserved
* @license GPLv3
*/
namespace buyrtbfidelity\workflows\tasklets\video\insertionorderlineitem;
class VideoRestrictionsWorkflow {
public static function execute(&$Logger, &$ParentWorkflow, \model\openrtb\RtbBidRequest &$RtbBidRequest, \model\openrtb\RtbBidRequestImp &$RtbBidRequestImp, &$InsertionOrderLineItem, &$InsertionOrderLineItemVideoRestrictionsFactory) {
/*
* Check banner restrictions (optional fields)
*/
$params = array();
$params["InsertionOrderLineItemID"] = $InsertionOrderLineItem->InsertionOrderLineItemID;
$InsertionOrderLineItemVideoRestrictions = $InsertionOrderLineItemVideoRestrictionsFactory->get_row_cached($ParentWorkflow->config, $params);
// no banner restriction info to base rejection on
if ($InsertionOrderLineItemVideoRestrictions === null):
return true;
endif;
// Check video height and width match
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckVideoDimensions::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check video fold position
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckFoldPosition::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Duration
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckDuration::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Mime Types
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckMimeTypes::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Delivery Type
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckDelivery::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Playback Methods
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckPlayback::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Protocols
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckProtocols::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Start Delay
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckStartDelay::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check Supported APIs
if (\buyrtbfidelity\workflows\tasklets\video\insertionorderlineitemvideorestrictions\CheckSupportedApis::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check banner for https:// secure
if (\buyrtbfidelity\workflows\tasklets\common\insertionordermediarestrictions\CheckSecureOnly::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check user for Coppa opt out status
if (\buyrtbfidelity\workflows\tasklets\common\insertionordermediarestrictions\CheckCoppaOptOut::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check banner for it being in the right vertical
if (\buyrtbfidelity\workflows\tasklets\common\insertionordermediarestrictions\CheckVertical::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
// Check banner geography
if (\buyrtbfidelity\workflows\tasklets\common\insertionordermediarestrictions\CheckGeo::execute($Logger, $ParentWorkflow, $RtbBidRequest, $RtbBidRequestImp, $InsertionOrderLineItem, $InsertionOrderLineItemVideoRestrictions) === false):
return false;
endif;
return true;
}
}
|
kh0r/nginad
|
upload/module/BuyFidelityRTB/src/BuyFidelityRTB/common/workflows/tasklets/video/insertionorderlineitem/VideoRestrictionsWorkflow.php
|
PHP
|
gpl-3.0
| 5,008
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Main login page.
*
* @package core
* @subpackage auth
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require('../config.php');
redirect_if_major_upgrade_required();
$testsession = optional_param('testsession', 0, PARAM_INT); // test session works properly
$cancel = optional_param('cancel', 0, PARAM_BOOL); // redirect to frontpage, needed for loginhttps
if ($cancel) {
redirect(new moodle_url('/'));
}
//HTTPS is required in this page when $CFG->loginhttps enabled
$PAGE->https_required();
$context = get_context_instance(CONTEXT_SYSTEM);
$PAGE->set_url("$CFG->httpswwwroot/login/index.php");
$PAGE->set_context($context);
$PAGE->set_pagelayout('login');
/// Initialize variables
$errormsg = '';
$errorcode = 0;
// login page requested session test
if ($testsession) {
if ($testsession == $USER->id) {
if (isset($SESSION->wantsurl)) {
$urltogo = $SESSION->wantsurl;
} else {
$urltogo = $CFG->wwwroot.'/';
}
unset($SESSION->wantsurl);
redirect($urltogo);
} else {
// TODO: try to find out what is the exact reason why sessions do not work
$errormsg = get_string("cookiesnotenabled");
$errorcode = 1;
}
}
/// Check for timed out sessions
if (!empty($SESSION->has_timed_out)) {
$session_has_timed_out = true;
unset($SESSION->has_timed_out);
} else {
$session_has_timed_out = false;
}
/// auth plugins may override these - SSO anyone?
$frm = false;
$user = false;
$authsequence = get_enabled_auth_plugins(true); // auths, in sequence
foreach($authsequence as $authname) {
$authplugin = get_auth_plugin($authname);
$authplugin->loginpage_hook();
}
/// Define variables used in page
$site = get_site();
$loginsite = get_string("loginsite");
$PAGE->navbar->add($loginsite);
if ($user !== false or $frm !== false or $errormsg !== '') {
// some auth plugin already supplied full user, fake form data or prevented user login with error message
} else if (!empty($SESSION->wantsurl) && file_exists($CFG->dirroot.'/login/weblinkauth.php')) {
// Handles the case of another Moodle site linking into a page on this site
//TODO: move weblink into own auth plugin
include($CFG->dirroot.'/login/weblinkauth.php');
if (function_exists('weblink_auth')) {
$user = weblink_auth($SESSION->wantsurl);
}
if ($user) {
$frm->username = $user->username;
} else {
$frm = data_submitted();
}
} else {
$frm = data_submitted();
}
/// Check if the user has actually submitted login data to us
if ($frm and isset($frm->username)) { // Login WITH cookies
$frm->username = trim(moodle_strtolower($frm->username));
if (is_enabled_auth('none') ) {
if ($frm->username !== clean_param($frm->username, PARAM_USERNAME)) {
$errormsg = get_string('username').': '.get_string("invalidusername");
$errorcode = 2;
$user = null;
}
}
if ($user) {
//user already supplied by aut plugin prelogin hook
} else if (($frm->username == 'guest') and empty($CFG->guestloginbutton)) {
$user = false; /// Can't log in as guest if guest button is disabled
$frm = false;
} else {
if (empty($errormsg)) {
$user = authenticate_user_login($frm->username, $frm->password);
}
}
// Intercept 'restored' users to provide them with info & reset password
if (!$user and $frm and is_restored_user($frm->username)) {
$PAGE->set_title(get_string('restoredaccount'));
$PAGE->set_heading($site->fullname);
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('restoredaccount'));
echo $OUTPUT->box(get_string('restoredaccountinfo'), 'generalbox boxaligncenter');
require_once('restored_password_form.php'); // Use our "supplanter" login_forgot_password_form. MDL-20846
$form = new login_forgot_password_form('forgot_password.php', array('username' => $frm->username));
$form->display();
echo $OUTPUT->footer();
die;
}
update_login_count();
if ($user) {
// language setup
if (isguestuser($user)) {
// no predefined language for guests - use existing session or default site lang
unset($user->lang);
} else if (!empty($user->lang)) {
// unset previous session language - use user preference instead
unset($SESSION->lang);
}
if (empty($user->confirmed)) { // This account was never confirmed
$PAGE->set_title(get_string("mustconfirm"));
$PAGE->set_heading($site->fullname);
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string("mustconfirm"));
echo $OUTPUT->box(get_string("emailconfirmsent", "", $user->email), "generalbox boxaligncenter");
echo $OUTPUT->footer();
die;
}
/// Let's get them all set up.
add_to_log(SITEID, 'user', 'login', "view.php?id=$USER->id&course=".SITEID,
$user->id, 0, $user->id);
complete_user_login($user);
// sets the username cookie
if (!empty($CFG->nolastloggedin)) {
// do not store last logged in user in cookie
// auth plugins can temporarily override this from loginpage_hook()
// do not save $CFG->nolastloggedin in database!
} else if (empty($CFG->rememberusername) or ($CFG->rememberusername == 2 and empty($frm->rememberusername))) {
// no permanent cookies, delete old one if exists
set_moodle_cookie('');
} else {
set_moodle_cookie($USER->username);
}
/// Prepare redirection
if (user_not_fully_set_up($USER)) {
$urltogo = $CFG->wwwroot.'/user/edit.php';
// We don't delete $SESSION->wantsurl yet, so we get there later
} else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0 or strpos($SESSION->wantsurl, str_replace('http://', 'https://', $CFG->wwwroot)) === 0)) {
$urltogo = $SESSION->wantsurl; /// Because it's an address in this site
unset($SESSION->wantsurl);
} else {
// no wantsurl stored or external - go to homepage
$urltogo = $CFG->wwwroot.'/';
unset($SESSION->wantsurl);
$home_page = get_home_page();
// Go to my-moodle page instead of site homepage if defaulthomepage set to homepage_my
if ($home_page == HOMEPAGE_MY && !is_siteadmin() && !isguestuser()) {
if ($urltogo == $CFG->wwwroot or $urltogo == $CFG->wwwroot.'/' or $urltogo == $CFG->wwwroot.'/index.php') {
$urltogo = $CFG->wwwroot.'/my/';
}
}
}
/// check if user password has expired
/// Currently supported only for ldap-authentication module
$userauth = get_auth_plugin($USER->auth);
if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) {
if ($userauth->can_change_password()) {
$passwordchangeurl = $userauth->change_password_url();
if (!$passwordchangeurl) {
$passwordchangeurl = $CFG->httpswwwroot.'/login/change_password.php';
}
} else {
$passwordchangeurl = $CFG->httpswwwroot.'/login/change_password.php';
}
$days2expire = $userauth->password_expire($USER->username);
$PAGE->set_title("$site->fullname: $loginsite");
$PAGE->set_heading("$site->fullname");
if (intval($days2expire) > 0 && intval($days2expire) < intval($userauth->config->expiration_warning)) {
echo $OUTPUT->header();
echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
echo $OUTPUT->footer();
exit;
} elseif (intval($days2expire) < 0 ) {
echo $OUTPUT->header();
echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
echo $OUTPUT->footer();
exit;
}
}
reset_login_count();
// test the session actually works by redirecting to self
$SESSION->wantsurl = $urltogo;
redirect(new moodle_url(get_login_url(), array('testsession'=>$USER->id)));
} else {
if (empty($errormsg)) {
$errormsg = get_string("invalidlogin");
$errorcode = 3;
}
}
}
/// Detect problems with timedout sessions
if ($session_has_timed_out and !data_submitted()) {
$errormsg = get_string('sessionerroruser', 'error');
$errorcode = 4;
}
/// First, let's remember where the user was trying to get to before they got here
if (empty($SESSION->wantsurl)) {
$SESSION->wantsurl = (array_key_exists('HTTP_REFERER',$_SERVER) &&
$_SERVER["HTTP_REFERER"] != $CFG->wwwroot &&
$_SERVER["HTTP_REFERER"] != $CFG->wwwroot.'/' &&
$_SERVER["HTTP_REFERER"] != $CFG->httpswwwroot.'/login/' &&
$_SERVER["HTTP_REFERER"] != $CFG->httpswwwroot.'/login/index.php')
? $_SERVER["HTTP_REFERER"] : NULL;
}
/// Redirect to alternative login URL if needed
if (!empty($CFG->alternateloginurl)) {
$loginurl = $CFG->alternateloginurl;
if (strpos($SESSION->wantsurl, $loginurl) === 0) {
//we do not want to return to alternate url
$SESSION->wantsurl = NULL;
}
if ($errorcode) {
if (strpos($loginurl, '?') === false) {
$loginurl .= '?';
} else {
$loginurl .= '&';
}
$loginurl .= 'errorcode='.$errorcode;
}
redirect($loginurl);
}
// make sure we really are on the https page when https login required
$PAGE->verify_https_required();
/// Generate the login page with forms
if (!isset($frm) or !is_object($frm)) {
$frm = new stdClass();
}
if (empty($frm->username) && $authsequence[0] != 'shibboleth') { // See bug 5184
if (!empty($_GET["username"])) {
$frm->username = clean_param($_GET["username"], PARAM_RAW); // we do not want data from _POST here
} else {
$frm->username = get_moodle_cookie();
}
$frm->password = "";
}
if (!empty($frm->username)) {
$focus = "password";
} else {
$focus = "username";
}
if (!empty($CFG->registerauth) or is_enabled_auth('none') or !empty($CFG->auth_instructions)) {
$show_instructions = true;
} else {
$show_instructions = false;
}
$potentialidps = array();
foreach($authsequence as $authname) {
$authplugin = get_auth_plugin($authname);
$potentialidps = array_merge($potentialidps, $authplugin->loginpage_idp_list($SESSION->wantsurl));
}
$PAGE->set_title("$site->fullname: $loginsite");
$PAGE->set_heading("$site->fullname");
echo $OUTPUT->header();
if (isloggedin() and !isguestuser()) {
// prevent logging when already logged in, we do not want them to relogin by accident because sesskey would be changed
echo $OUTPUT->box_start();
$logout = new single_button(new moodle_url($CFG->httpswwwroot.'/login/logout.php', array('sesskey'=>sesskey(),'loginpage'=>1)), get_string('logout'), 'post');
$continue = new single_button(new moodle_url($CFG->httpswwwroot.'/login/index.php', array('cancel'=>1)), get_string('cancel'), 'get');
echo $OUTPUT->confirm(get_string('alreadyloggedin', 'error', fullname($USER)), $logout, $continue);
echo $OUTPUT->box_end();
} else {
include("index_form.html");
if (!empty($CFG->loginpageautofocus)) {
//focus username or password
$PAGE->requires->js_init_call('M.util.focus_login_form', null, true);
}
}
echo $OUTPUT->footer();
|
ankitml/moodle2.2
|
login/index.php
|
PHP
|
gpl-3.0
| 12,752
|
/*
* 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 tests.support;
import java.net.NetworkInterface;
public class Support_NetworkInterface {
/**
* On windows platforms with IPV6 enabled there are a number of pseudo
* interfaces which don't work with our tests. This function is called to
* make sure we only use the non-pseudo interfaces
*/
public static boolean useInterface(NetworkInterface theInterface) {
boolean result = true;
String platform = System.getProperty("os.name");
// only use these on windows platforms
if (platform.startsWith("Windows")) {
if ((theInterface.getDisplayName()
.equals("Teredo Tunneling Pseudo-Interface"))
|| (theInterface.getDisplayName()
.equals("6to4 Tunneling Pseudo-Interface"))
|| (theInterface.getDisplayName()
.equals("Automatic Tunneling Pseudo-Interface"))
|| (theInterface.getDisplayName()
.equals("Loopback Pseudo-Interface"))
|| (theInterface.getDisplayName().equals("MS TCP Loopback interface"))) {
result = false;
}
}
if (platform.startsWith("Linux")) {
if ((theInterface.getDisplayName().equals("lo"))
|| (theInterface.getDisplayName().equals("teredo"))) {
result = false;
}
}
return result;
}
}
|
s20121035/rk3288_android5.1_repo
|
external/apache-harmony/support/src/test/java/tests/support/Support_NetworkInterface.java
|
Java
|
gpl-3.0
| 2,267
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2006
* Sleepycat Software. All rights reserved.
*
* $Id: LogReadable.java,v 1.1 2006/05/06 08:59:54 ckaestne Exp $
*/
package com.sleepycat.je.log;
import java.nio.ByteBuffer;
/**
* A class that implements LogReadable knows how to read itself from the JE
* log.
*/
public interface LogReadable {
/**
* Initialize this object from the data in itemBuf.
* @param itemBuf the source buffer
*/
public void readFromLog(ByteBuffer itemBuffer, byte entryTypeVersion)
throws LogException;
/**
* Write the object into the string buffer for log dumping. Each object
* should be dumped without indentation or new lines and should be valid
* XML.
* @param sb destination string buffer
* @param verbose if true, dump the full, verbose version
*/
public void dumpLog(StringBuffer sb, boolean verbose);
/**
* @return true if the LogEntry is a transactional log entry type.
*/
public boolean logEntryIsTransactional();
/**
* @return return the transaction id if this log entry is transactional,
* 0 otherwise.
*/
public long getTransactionId();
}
|
ckaestne/CIDE
|
CIDE_Samples/cide_samples/Berkeley DB JE/src/com/sleepycat/je/log/LogReadable.java
|
Java
|
gpl-3.0
| 1,284
|
div {
padding: 1em;
width: 250px;
height: 30px;
color: #808080;
border: 55px solid #cd853f;
border-image-source: url(woodframe.jpg);
border-image-slice: 55 fill;
border-image-width: auto;
}
|
grtlinux/TAIN_WEB_TEST
|
WEB_TEST01/doc/HTML5_CSS3_DIC_2nd/css3/01_background-border/bd08.css
|
CSS
|
gpl-3.0
| 208
|
/***************************************************************************
File : LineNumberDisplay.h
Project : QtiPlot
--------------------------------------------------------------------
Copyright : (C) 2008 by Ion Vasilief
Email (use @ for *) : ion_vasilief*yahoo.fr
Description : A widget displaying line numbers for a QTextEdit
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, *
* Boston, MA 02110-1301 USA *
* *
***************************************************************************/
#ifndef LineNumberDisplay_H
#define LineNumberDisplay_H
#include <QTextEdit>
//! A QTextEdit displaying line numbers.
/**
* It must be used in connection with another "source" QTextEdit.
*/
class LineNumberDisplay : public QTextEdit {
Q_OBJECT
public:
//! Constructor
/**
* \param te the "source" QTextEdit for which we want to display the line
* numbers
* \param parent parent widget (only affects placement of the dialog)
*/
LineNumberDisplay(QTextEdit *te, QWidget *parent = nullptr);
public slots:
void updateLineNumbers(bool force = false);
void updateDocumentSelection();
private slots:
void changeCharFormat(const QTextCharFormat &);
private:
void showEvent(QShowEvent *) override;
QTextEdit *d_text_edit;
};
#endif
|
mganeva/mantid
|
MantidPlot/src/lib/include/LineNumberDisplay.h
|
C
|
gpl-3.0
| 2,637
|
//===- llvm/TableGen/Record.h - Classes for Table Records -------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the main TableGen data structures, including the TableGen
// types, values, and high-level data structures.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TABLEGEN_RECORD_H
#define LLVM_TABLEGEN_RECORD_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/TrailingObjects.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace llvm {
class ListRecTy;
struct MultiClass;
class Record;
class RecordKeeper;
class RecordVal;
class Resolver;
class StringInit;
class TypedInit;
//===----------------------------------------------------------------------===//
// Type Classes
//===----------------------------------------------------------------------===//
class RecTy {
public:
/// Subclass discriminator (for dyn_cast<> et al.)
enum RecTyKind {
BitRecTyKind,
BitsRecTyKind,
IntRecTyKind,
StringRecTyKind,
ListRecTyKind,
DagRecTyKind,
RecordRecTyKind
};
private:
RecTyKind Kind;
/// ListRecTy of the list that has elements of this type.
ListRecTy *ListTy = nullptr;
public:
RecTy(RecTyKind K) : Kind(K) {}
virtual ~RecTy() = default;
RecTyKind getRecTyKind() const { return Kind; }
virtual std::string getAsString() const = 0;
void print(raw_ostream &OS) const { OS << getAsString(); }
void dump() const;
/// Return true if all values of 'this' type can be converted to the specified
/// type.
virtual bool typeIsConvertibleTo(const RecTy *RHS) const;
/// Return true if 'this' type is equal to or a subtype of RHS. For example,
/// a bit set is not an int, but they are convertible.
virtual bool typeIsA(const RecTy *RHS) const;
/// Returns the type representing list<thistype>.
ListRecTy *getListTy();
};
inline raw_ostream &operator<<(raw_ostream &OS, const RecTy &Ty) {
Ty.print(OS);
return OS;
}
/// 'bit' - Represent a single bit
class BitRecTy : public RecTy {
static BitRecTy Shared;
BitRecTy() : RecTy(BitRecTyKind) {}
public:
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == BitRecTyKind;
}
static BitRecTy *get() { return &Shared; }
std::string getAsString() const override { return "bit"; }
bool typeIsConvertibleTo(const RecTy *RHS) const override;
};
/// 'bits<n>' - Represent a fixed number of bits
class BitsRecTy : public RecTy {
unsigned Size;
explicit BitsRecTy(unsigned Sz) : RecTy(BitsRecTyKind), Size(Sz) {}
public:
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == BitsRecTyKind;
}
static BitsRecTy *get(unsigned Sz);
unsigned getNumBits() const { return Size; }
std::string getAsString() const override;
bool typeIsConvertibleTo(const RecTy *RHS) const override;
bool typeIsA(const RecTy *RHS) const override;
};
/// 'int' - Represent an integer value of no particular size
class IntRecTy : public RecTy {
static IntRecTy Shared;
IntRecTy() : RecTy(IntRecTyKind) {}
public:
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == IntRecTyKind;
}
static IntRecTy *get() { return &Shared; }
std::string getAsString() const override { return "int"; }
bool typeIsConvertibleTo(const RecTy *RHS) const override;
};
/// 'string' - Represent an string value
class StringRecTy : public RecTy {
static StringRecTy Shared;
StringRecTy() : RecTy(StringRecTyKind) {}
public:
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == StringRecTyKind;
}
static StringRecTy *get() { return &Shared; }
std::string getAsString() const override;
bool typeIsConvertibleTo(const RecTy *RHS) const override;
};
/// 'list<Ty>' - Represent a list of element values, all of which must be of
/// the specified type. The type is stored in ElementTy.
class ListRecTy : public RecTy {
friend ListRecTy *RecTy::getListTy();
RecTy *ElementTy;
explicit ListRecTy(RecTy *T) : RecTy(ListRecTyKind), ElementTy(T) {}
public:
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == ListRecTyKind;
}
static ListRecTy *get(RecTy *T) { return T->getListTy(); }
RecTy *getElementType() const { return ElementTy; }
std::string getAsString() const override;
bool typeIsConvertibleTo(const RecTy *RHS) const override;
bool typeIsA(const RecTy *RHS) const override;
};
/// 'dag' - Represent a dag fragment
class DagRecTy : public RecTy {
static DagRecTy Shared;
DagRecTy() : RecTy(DagRecTyKind) {}
public:
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == DagRecTyKind;
}
static DagRecTy *get() { return &Shared; }
std::string getAsString() const override;
};
/// '[classname]' - Type of record values that have zero or more superclasses.
///
/// The list of superclasses is non-redundant, i.e. only contains classes that
/// are not the superclass of some other listed class.
class RecordRecTy final : public RecTy, public FoldingSetNode,
public TrailingObjects<RecordRecTy, Record *> {
friend class Record;
unsigned NumClasses;
explicit RecordRecTy(unsigned Num)
: RecTy(RecordRecTyKind), NumClasses(Num) {}
public:
RecordRecTy(const RecordRecTy &) = delete;
RecordRecTy &operator=(const RecordRecTy &) = delete;
// Do not use sized deallocation due to trailing objects.
void operator delete(void *p) { ::operator delete(p); }
static bool classof(const RecTy *RT) {
return RT->getRecTyKind() == RecordRecTyKind;
}
/// Get the record type with the given non-redundant list of superclasses.
static RecordRecTy *get(ArrayRef<Record *> Classes);
void Profile(FoldingSetNodeID &ID) const;
ArrayRef<Record *> getClasses() const {
return makeArrayRef(getTrailingObjects<Record *>(), NumClasses);
}
using const_record_iterator = Record * const *;
const_record_iterator classes_begin() const { return getClasses().begin(); }
const_record_iterator classes_end() const { return getClasses().end(); }
std::string getAsString() const override;
bool isSubClassOf(Record *Class) const;
bool typeIsConvertibleTo(const RecTy *RHS) const override;
bool typeIsA(const RecTy *RHS) const override;
};
/// Find a common type that T1 and T2 convert to.
/// Return 0 if no such type exists.
RecTy *resolveTypes(RecTy *T1, RecTy *T2);
//===----------------------------------------------------------------------===//
// Initializer Classes
//===----------------------------------------------------------------------===//
class Init {
protected:
/// Discriminator enum (for isa<>, dyn_cast<>, et al.)
///
/// This enum is laid out by a preorder traversal of the inheritance
/// hierarchy, and does not contain an entry for abstract classes, as per
/// the recommendation in docs/HowToSetUpLLVMStyleRTTI.rst.
///
/// We also explicitly include "first" and "last" values for each
/// interior node of the inheritance tree, to make it easier to read the
/// corresponding classof().
///
/// We could pack these a bit tighter by not having the IK_FirstXXXInit
/// and IK_LastXXXInit be their own values, but that would degrade
/// readability for really no benefit.
enum InitKind : uint8_t {
IK_First, // unused; silence a spurious warning
IK_FirstTypedInit,
IK_BitInit,
IK_BitsInit,
IK_DagInit,
IK_DefInit,
IK_FieldInit,
IK_IntInit,
IK_ListInit,
IK_FirstOpInit,
IK_BinOpInit,
IK_TernOpInit,
IK_UnOpInit,
IK_LastOpInit,
IK_CondOpInit,
IK_FoldOpInit,
IK_IsAOpInit,
IK_StringInit,
IK_VarInit,
IK_VarListElementInit,
IK_VarBitInit,
IK_VarDefInit,
IK_LastTypedInit,
IK_UnsetInit
};
private:
const InitKind Kind;
protected:
uint8_t Opc; // Used by UnOpInit, BinOpInit, and TernOpInit
private:
virtual void anchor();
public:
/// Get the kind (type) of the value.
InitKind getKind() const { return Kind; }
protected:
explicit Init(InitKind K, uint8_t Opc = 0) : Kind(K), Opc(Opc) {}
public:
Init(const Init &) = delete;
Init &operator=(const Init &) = delete;
virtual ~Init() = default;
/// Is this a complete value with no unset (uninitialized) subvalues?
virtual bool isComplete() const { return true; }
/// Is this a concrete and fully resolved value without any references or
/// stuck operations? Unset values are concrete.
virtual bool isConcrete() const { return false; }
/// Print this value.
void print(raw_ostream &OS) const { OS << getAsString(); }
/// Convert this value to a literal form.
virtual std::string getAsString() const = 0;
/// Convert this value to a literal form,
/// without adding quotes around a string.
virtual std::string getAsUnquotedString() const { return getAsString(); }
/// Debugging method that may be called through a debugger; just
/// invokes print on stderr.
void dump() const;
/// If this value is convertible to type \p Ty, return a value whose
/// type is \p Ty, generating a !cast operation if required.
/// Otherwise, return null.
virtual Init *getCastTo(RecTy *Ty) const = 0;
/// Convert to a value whose type is \p Ty, or return null if this
/// is not possible. This can happen if the value's type is convertible
/// to \p Ty, but there are unresolved references.
virtual Init *convertInitializerTo(RecTy *Ty) const = 0;
/// This function is used to implement the bit range
/// selection operator. Given a value, it selects the specified bits,
/// returning them as a new \p Init of type \p bits. If it is not legal
/// to use the bit selection operator on this value, null is returned.
virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
return nullptr;
}
/// This function is used to implement the list slice
/// selection operator. Given a value, it selects the specified list
/// elements, returning them as a new \p Init of type \p list. If it
/// is not legal to use the slice operator, null is returned.
virtual Init *convertInitListSlice(ArrayRef<unsigned> Elements) const {
return nullptr;
}
/// This function is used to implement the FieldInit class.
/// Implementors of this method should return the type of the named
/// field if they are of type record.
virtual RecTy *getFieldType(StringInit *FieldName) const {
return nullptr;
}
/// This function is used by classes that refer to other
/// variables which may not be defined at the time the expression is formed.
/// If a value is set for the variable later, this method will be called on
/// users of the value to allow the value to propagate out.
virtual Init *resolveReferences(Resolver &R) const {
return const_cast<Init *>(this);
}
/// Get the \p Init value of the specified bit.
virtual Init *getBit(unsigned Bit) const = 0;
};
inline raw_ostream &operator<<(raw_ostream &OS, const Init &I) {
I.print(OS); return OS;
}
/// This is the common superclass of types that have a specific,
/// explicit type, stored in ValueTy.
class TypedInit : public Init {
RecTy *ValueTy;
protected:
explicit TypedInit(InitKind K, RecTy *T, uint8_t Opc = 0)
: Init(K, Opc), ValueTy(T) {}
public:
TypedInit(const TypedInit &) = delete;
TypedInit &operator=(const TypedInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() >= IK_FirstTypedInit &&
I->getKind() <= IK_LastTypedInit;
}
/// Get the type of the Init as a RecTy.
RecTy *getType() const { return ValueTy; }
Init *getCastTo(RecTy *Ty) const override;
Init *convertInitializerTo(RecTy *Ty) const override;
Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
/// This method is used to implement the FieldInit class.
/// Implementors of this method should return the type of the named field if
/// they are of type record.
RecTy *getFieldType(StringInit *FieldName) const override;
};
/// '?' - Represents an uninitialized value.
class UnsetInit : public Init {
UnsetInit() : Init(IK_UnsetInit) {}
public:
UnsetInit(const UnsetInit &) = delete;
UnsetInit &operator=(const UnsetInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_UnsetInit;
}
/// Get the singleton unset Init.
static UnsetInit *get();
Init *getCastTo(RecTy *Ty) const override;
Init *convertInitializerTo(RecTy *Ty) const override;
Init *getBit(unsigned Bit) const override {
return const_cast<UnsetInit*>(this);
}
/// Is this a complete value with no unset (uninitialized) subvalues?
bool isComplete() const override { return false; }
bool isConcrete() const override { return true; }
/// Get the string representation of the Init.
std::string getAsString() const override { return "?"; }
};
/// 'true'/'false' - Represent a concrete initializer for a bit.
class BitInit final : public TypedInit {
bool Value;
explicit BitInit(bool V) : TypedInit(IK_BitInit, BitRecTy::get()), Value(V) {}
public:
BitInit(const BitInit &) = delete;
BitInit &operator=(BitInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_BitInit;
}
static BitInit *get(bool V);
bool getValue() const { return Value; }
Init *convertInitializerTo(RecTy *Ty) const override;
Init *getBit(unsigned Bit) const override {
assert(Bit < 1 && "Bit index out of range!");
return const_cast<BitInit*>(this);
}
bool isConcrete() const override { return true; }
std::string getAsString() const override { return Value ? "1" : "0"; }
};
/// '{ a, b, c }' - Represents an initializer for a BitsRecTy value.
/// It contains a vector of bits, whose size is determined by the type.
class BitsInit final : public TypedInit, public FoldingSetNode,
public TrailingObjects<BitsInit, Init *> {
unsigned NumBits;
BitsInit(unsigned N)
: TypedInit(IK_BitsInit, BitsRecTy::get(N)), NumBits(N) {}
public:
BitsInit(const BitsInit &) = delete;
BitsInit &operator=(const BitsInit &) = delete;
// Do not use sized deallocation due to trailing objects.
void operator delete(void *p) { ::operator delete(p); }
static bool classof(const Init *I) {
return I->getKind() == IK_BitsInit;
}
static BitsInit *get(ArrayRef<Init *> Range);
void Profile(FoldingSetNodeID &ID) const;
unsigned getNumBits() const { return NumBits; }
Init *convertInitializerTo(RecTy *Ty) const override;
Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
bool isComplete() const override {
for (unsigned i = 0; i != getNumBits(); ++i)
if (!getBit(i)->isComplete()) return false;
return true;
}
bool allInComplete() const {
for (unsigned i = 0; i != getNumBits(); ++i)
if (getBit(i)->isComplete()) return false;
return true;
}
bool isConcrete() const override;
std::string getAsString() const override;
Init *resolveReferences(Resolver &R) const override;
Init *getBit(unsigned Bit) const override {
assert(Bit < NumBits && "Bit index out of range!");
return getTrailingObjects<Init *>()[Bit];
}
};
/// '7' - Represent an initialization by a literal integer value.
class IntInit : public TypedInit {
int64_t Value;
explicit IntInit(int64_t V)
: TypedInit(IK_IntInit, IntRecTy::get()), Value(V) {}
public:
IntInit(const IntInit &) = delete;
IntInit &operator=(const IntInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_IntInit;
}
static IntInit *get(int64_t V);
int64_t getValue() const { return Value; }
Init *convertInitializerTo(RecTy *Ty) const override;
Init *convertInitializerBitRange(ArrayRef<unsigned> Bits) const override;
bool isConcrete() const override { return true; }
std::string getAsString() const override;
Init *getBit(unsigned Bit) const override {
return BitInit::get((Value & (1ULL << Bit)) != 0);
}
};
/// "foo" - Represent an initialization by a string value.
class StringInit : public TypedInit {
public:
enum StringFormat {
SF_String, // Format as "text"
SF_Code, // Format as [{text}]
};
private:
StringRef Value;
StringFormat Format;
explicit StringInit(StringRef V, StringFormat Fmt)
: TypedInit(IK_StringInit, StringRecTy::get()), Value(V), Format(Fmt) {}
public:
StringInit(const StringInit &) = delete;
StringInit &operator=(const StringInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_StringInit;
}
static StringInit *get(StringRef, StringFormat Fmt = SF_String);
static StringFormat determineFormat(StringFormat Fmt1, StringFormat Fmt2) {
return (Fmt1 == SF_Code || Fmt2 == SF_Code) ? SF_Code : SF_String;
}
StringRef getValue() const { return Value; }
StringFormat getFormat() const { return Format; }
bool hasCodeFormat() const { return Format == SF_Code; }
Init *convertInitializerTo(RecTy *Ty) const override;
bool isConcrete() const override { return true; }
std::string getAsString() const override {
if (Format == SF_String)
return "\"" + Value.str() + "\"";
else
return "[{" + Value.str() + "}]";
}
std::string getAsUnquotedString() const override {
return std::string(Value);
}
Init *getBit(unsigned Bit) const override {
llvm_unreachable("Illegal bit reference off string");
}
};
/// [AL, AH, CL] - Represent a list of defs
///
class ListInit final : public TypedInit, public FoldingSetNode,
public TrailingObjects<ListInit, Init *> {
unsigned NumValues;
public:
using const_iterator = Init *const *;
private:
explicit ListInit(unsigned N, RecTy *EltTy)
: TypedInit(IK_ListInit, ListRecTy::get(EltTy)), NumValues(N) {}
public:
ListInit(const ListInit &) = delete;
ListInit &operator=(const ListInit &) = delete;
// Do not use sized deallocation due to trailing objects.
void operator delete(void *p) { ::operator delete(p); }
static bool classof(const Init *I) {
return I->getKind() == IK_ListInit;
}
static ListInit *get(ArrayRef<Init *> Range, RecTy *EltTy);
void Profile(FoldingSetNodeID &ID) const;
Init *getElement(unsigned i) const {
assert(i < NumValues && "List element index out of range!");
return getTrailingObjects<Init *>()[i];
}
RecTy *getElementType() const {
return cast<ListRecTy>(getType())->getElementType();
}
Record *getElementAsRecord(unsigned i) const;
Init *convertInitListSlice(ArrayRef<unsigned> Elements) const override;
Init *convertInitializerTo(RecTy *Ty) const override;
/// This method is used by classes that refer to other
/// variables which may not be defined at the time they expression is formed.
/// If a value is set for the variable later, this method will be called on
/// users of the value to allow the value to propagate out.
///
Init *resolveReferences(Resolver &R) const override;
bool isConcrete() const override;
std::string getAsString() const override;
ArrayRef<Init*> getValues() const {
return makeArrayRef(getTrailingObjects<Init *>(), NumValues);
}
const_iterator begin() const { return getTrailingObjects<Init *>(); }
const_iterator end () const { return begin() + NumValues; }
size_t size () const { return NumValues; }
bool empty() const { return NumValues == 0; }
Init *getBit(unsigned Bit) const override {
llvm_unreachable("Illegal bit reference off list");
}
};
/// Base class for operators
///
class OpInit : public TypedInit {
protected:
explicit OpInit(InitKind K, RecTy *Type, uint8_t Opc)
: TypedInit(K, Type, Opc) {}
public:
OpInit(const OpInit &) = delete;
OpInit &operator=(OpInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() >= IK_FirstOpInit &&
I->getKind() <= IK_LastOpInit;
}
// Clone - Clone this operator, replacing arguments with the new list
virtual OpInit *clone(ArrayRef<Init *> Operands) const = 0;
virtual unsigned getNumOperands() const = 0;
virtual Init *getOperand(unsigned i) const = 0;
Init *getBit(unsigned Bit) const override;
};
/// !op (X) - Transform an init.
///
class UnOpInit : public OpInit, public FoldingSetNode {
public:
enum UnaryOp : uint8_t { CAST, NOT, HEAD, TAIL, SIZE, EMPTY, GETDAGOP };
private:
Init *LHS;
UnOpInit(UnaryOp opc, Init *lhs, RecTy *Type)
: OpInit(IK_UnOpInit, Type, opc), LHS(lhs) {}
public:
UnOpInit(const UnOpInit &) = delete;
UnOpInit &operator=(const UnOpInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_UnOpInit;
}
static UnOpInit *get(UnaryOp opc, Init *lhs, RecTy *Type);
void Profile(FoldingSetNodeID &ID) const;
// Clone - Clone this operator, replacing arguments with the new list
OpInit *clone(ArrayRef<Init *> Operands) const override {
assert(Operands.size() == 1 &&
"Wrong number of operands for unary operation");
return UnOpInit::get(getOpcode(), *Operands.begin(), getType());
}
unsigned getNumOperands() const override { return 1; }
Init *getOperand(unsigned i) const override {
assert(i == 0 && "Invalid operand id for unary operator");
return getOperand();
}
UnaryOp getOpcode() const { return (UnaryOp)Opc; }
Init *getOperand() const { return LHS; }
// Fold - If possible, fold this to a simpler init. Return this if not
// possible to fold.
Init *Fold(Record *CurRec, bool IsFinal = false) const;
Init *resolveReferences(Resolver &R) const override;
std::string getAsString() const override;
};
/// !op (X, Y) - Combine two inits.
class BinOpInit : public OpInit, public FoldingSetNode {
public:
enum BinaryOp : uint8_t { ADD, SUB, MUL, AND, OR, XOR, SHL, SRA, SRL, LISTCONCAT,
LISTSPLAT, STRCONCAT, INTERLEAVE, CONCAT, EQ,
NE, LE, LT, GE, GT, SETDAGOP };
private:
Init *LHS, *RHS;
BinOpInit(BinaryOp opc, Init *lhs, Init *rhs, RecTy *Type) :
OpInit(IK_BinOpInit, Type, opc), LHS(lhs), RHS(rhs) {}
public:
BinOpInit(const BinOpInit &) = delete;
BinOpInit &operator=(const BinOpInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_BinOpInit;
}
static BinOpInit *get(BinaryOp opc, Init *lhs, Init *rhs,
RecTy *Type);
static Init *getStrConcat(Init *lhs, Init *rhs);
static Init *getListConcat(TypedInit *lhs, Init *rhs);
void Profile(FoldingSetNodeID &ID) const;
// Clone - Clone this operator, replacing arguments with the new list
OpInit *clone(ArrayRef<Init *> Operands) const override {
assert(Operands.size() == 2 &&
"Wrong number of operands for binary operation");
return BinOpInit::get(getOpcode(), Operands[0], Operands[1], getType());
}
unsigned getNumOperands() const override { return 2; }
Init *getOperand(unsigned i) const override {
switch (i) {
default: llvm_unreachable("Invalid operand id for binary operator");
case 0: return getLHS();
case 1: return getRHS();
}
}
BinaryOp getOpcode() const { return (BinaryOp)Opc; }
Init *getLHS() const { return LHS; }
Init *getRHS() const { return RHS; }
// Fold - If possible, fold this to a simpler init. Return this if not
// possible to fold.
Init *Fold(Record *CurRec) const;
Init *resolveReferences(Resolver &R) const override;
std::string getAsString() const override;
};
/// !op (X, Y, Z) - Combine two inits.
class TernOpInit : public OpInit, public FoldingSetNode {
public:
enum TernaryOp : uint8_t { SUBST, FOREACH, FILTER, IF, DAG, SUBSTR };
private:
Init *LHS, *MHS, *RHS;
TernOpInit(TernaryOp opc, Init *lhs, Init *mhs, Init *rhs,
RecTy *Type) :
OpInit(IK_TernOpInit, Type, opc), LHS(lhs), MHS(mhs), RHS(rhs) {}
public:
TernOpInit(const TernOpInit &) = delete;
TernOpInit &operator=(const TernOpInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_TernOpInit;
}
static TernOpInit *get(TernaryOp opc, Init *lhs,
Init *mhs, Init *rhs,
RecTy *Type);
void Profile(FoldingSetNodeID &ID) const;
// Clone - Clone this operator, replacing arguments with the new list
OpInit *clone(ArrayRef<Init *> Operands) const override {
assert(Operands.size() == 3 &&
"Wrong number of operands for ternary operation");
return TernOpInit::get(getOpcode(), Operands[0], Operands[1], Operands[2],
getType());
}
unsigned getNumOperands() const override { return 3; }
Init *getOperand(unsigned i) const override {
switch (i) {
default: llvm_unreachable("Invalid operand id for ternary operator");
case 0: return getLHS();
case 1: return getMHS();
case 2: return getRHS();
}
}
TernaryOp getOpcode() const { return (TernaryOp)Opc; }
Init *getLHS() const { return LHS; }
Init *getMHS() const { return MHS; }
Init *getRHS() const { return RHS; }
// Fold - If possible, fold this to a simpler init. Return this if not
// possible to fold.
Init *Fold(Record *CurRec) const;
bool isComplete() const override {
return LHS->isComplete() && MHS->isComplete() && RHS->isComplete();
}
Init *resolveReferences(Resolver &R) const override;
std::string getAsString() const override;
};
/// !cond(condition_1: value1, ... , condition_n: value)
/// Selects the first value for which condition is true.
/// Otherwise reports an error.
class CondOpInit final : public TypedInit, public FoldingSetNode,
public TrailingObjects<CondOpInit, Init *> {
unsigned NumConds;
RecTy *ValType;
CondOpInit(unsigned NC, RecTy *Type)
: TypedInit(IK_CondOpInit, Type),
NumConds(NC), ValType(Type) {}
size_t numTrailingObjects(OverloadToken<Init *>) const {
return 2*NumConds;
}
public:
CondOpInit(const CondOpInit &) = delete;
CondOpInit &operator=(const CondOpInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_CondOpInit;
}
static CondOpInit *get(ArrayRef<Init*> C, ArrayRef<Init*> V,
RecTy *Type);
void Profile(FoldingSetNodeID &ID) const;
RecTy *getValType() const { return ValType; }
unsigned getNumConds() const { return NumConds; }
Init *getCond(unsigned Num) const {
assert(Num < NumConds && "Condition number out of range!");
return getTrailingObjects<Init *>()[Num];
}
Init *getVal(unsigned Num) const {
assert(Num < NumConds && "Val number out of range!");
return getTrailingObjects<Init *>()[Num+NumConds];
}
ArrayRef<Init *> getConds() const {
return makeArrayRef(getTrailingObjects<Init *>(), NumConds);
}
ArrayRef<Init *> getVals() const {
return makeArrayRef(getTrailingObjects<Init *>()+NumConds, NumConds);
}
Init *Fold(Record *CurRec) const;
Init *resolveReferences(Resolver &R) const override;
bool isConcrete() const override;
bool isComplete() const override;
std::string getAsString() const override;
using const_case_iterator = SmallVectorImpl<Init*>::const_iterator;
using const_val_iterator = SmallVectorImpl<Init*>::const_iterator;
inline const_case_iterator arg_begin() const { return getConds().begin(); }
inline const_case_iterator arg_end () const { return getConds().end(); }
inline size_t case_size () const { return NumConds; }
inline bool case_empty() const { return NumConds == 0; }
inline const_val_iterator name_begin() const { return getVals().begin();}
inline const_val_iterator name_end () const { return getVals().end(); }
inline size_t val_size () const { return NumConds; }
inline bool val_empty() const { return NumConds == 0; }
Init *getBit(unsigned Bit) const override;
};
/// !foldl (a, b, expr, start, lst) - Fold over a list.
class FoldOpInit : public TypedInit, public FoldingSetNode {
private:
Init *Start;
Init *List;
Init *A;
Init *B;
Init *Expr;
FoldOpInit(Init *Start, Init *List, Init *A, Init *B, Init *Expr, RecTy *Type)
: TypedInit(IK_FoldOpInit, Type), Start(Start), List(List), A(A), B(B),
Expr(Expr) {}
public:
FoldOpInit(const FoldOpInit &) = delete;
FoldOpInit &operator=(const FoldOpInit &) = delete;
static bool classof(const Init *I) { return I->getKind() == IK_FoldOpInit; }
static FoldOpInit *get(Init *Start, Init *List, Init *A, Init *B, Init *Expr,
RecTy *Type);
void Profile(FoldingSetNodeID &ID) const;
// Fold - If possible, fold this to a simpler init. Return this if not
// possible to fold.
Init *Fold(Record *CurRec) const;
bool isComplete() const override { return false; }
Init *resolveReferences(Resolver &R) const override;
Init *getBit(unsigned Bit) const override;
std::string getAsString() const override;
};
/// !isa<type>(expr) - Dynamically determine the type of an expression.
class IsAOpInit : public TypedInit, public FoldingSetNode {
private:
RecTy *CheckType;
Init *Expr;
IsAOpInit(RecTy *CheckType, Init *Expr)
: TypedInit(IK_IsAOpInit, IntRecTy::get()), CheckType(CheckType),
Expr(Expr) {}
public:
IsAOpInit(const IsAOpInit &) = delete;
IsAOpInit &operator=(const IsAOpInit &) = delete;
static bool classof(const Init *I) { return I->getKind() == IK_IsAOpInit; }
static IsAOpInit *get(RecTy *CheckType, Init *Expr);
void Profile(FoldingSetNodeID &ID) const;
// Fold - If possible, fold this to a simpler init. Return this if not
// possible to fold.
Init *Fold() const;
bool isComplete() const override { return false; }
Init *resolveReferences(Resolver &R) const override;
Init *getBit(unsigned Bit) const override;
std::string getAsString() const override;
};
/// 'Opcode' - Represent a reference to an entire variable object.
class VarInit : public TypedInit {
Init *VarName;
explicit VarInit(Init *VN, RecTy *T)
: TypedInit(IK_VarInit, T), VarName(VN) {}
public:
VarInit(const VarInit &) = delete;
VarInit &operator=(const VarInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_VarInit;
}
static VarInit *get(StringRef VN, RecTy *T);
static VarInit *get(Init *VN, RecTy *T);
StringRef getName() const;
Init *getNameInit() const { return VarName; }
std::string getNameInitAsString() const {
return getNameInit()->getAsUnquotedString();
}
/// This method is used by classes that refer to other
/// variables which may not be defined at the time they expression is formed.
/// If a value is set for the variable later, this method will be called on
/// users of the value to allow the value to propagate out.
///
Init *resolveReferences(Resolver &R) const override;
Init *getBit(unsigned Bit) const override;
std::string getAsString() const override { return std::string(getName()); }
};
/// Opcode{0} - Represent access to one bit of a variable or field.
class VarBitInit final : public TypedInit {
TypedInit *TI;
unsigned Bit;
VarBitInit(TypedInit *T, unsigned B)
: TypedInit(IK_VarBitInit, BitRecTy::get()), TI(T), Bit(B) {
assert(T->getType() &&
(isa<IntRecTy>(T->getType()) ||
(isa<BitsRecTy>(T->getType()) &&
cast<BitsRecTy>(T->getType())->getNumBits() > B)) &&
"Illegal VarBitInit expression!");
}
public:
VarBitInit(const VarBitInit &) = delete;
VarBitInit &operator=(const VarBitInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_VarBitInit;
}
static VarBitInit *get(TypedInit *T, unsigned B);
Init *getBitVar() const { return TI; }
unsigned getBitNum() const { return Bit; }
std::string getAsString() const override;
Init *resolveReferences(Resolver &R) const override;
Init *getBit(unsigned B) const override {
assert(B < 1 && "Bit index out of range!");
return const_cast<VarBitInit*>(this);
}
};
/// List[4] - Represent access to one element of a var or
/// field.
class VarListElementInit : public TypedInit {
TypedInit *TI;
unsigned Element;
VarListElementInit(TypedInit *T, unsigned E)
: TypedInit(IK_VarListElementInit,
cast<ListRecTy>(T->getType())->getElementType()),
TI(T), Element(E) {
assert(T->getType() && isa<ListRecTy>(T->getType()) &&
"Illegal VarBitInit expression!");
}
public:
VarListElementInit(const VarListElementInit &) = delete;
VarListElementInit &operator=(const VarListElementInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_VarListElementInit;
}
static VarListElementInit *get(TypedInit *T, unsigned E);
TypedInit *getVariable() const { return TI; }
unsigned getElementNum() const { return Element; }
std::string getAsString() const override;
Init *resolveReferences(Resolver &R) const override;
Init *getBit(unsigned Bit) const override;
};
/// AL - Represent a reference to a 'def' in the description
class DefInit : public TypedInit {
friend class Record;
Record *Def;
explicit DefInit(Record *D);
public:
DefInit(const DefInit &) = delete;
DefInit &operator=(const DefInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_DefInit;
}
static DefInit *get(Record*);
Init *convertInitializerTo(RecTy *Ty) const override;
Record *getDef() const { return Def; }
//virtual Init *convertInitializerBitRange(ArrayRef<unsigned> Bits);
RecTy *getFieldType(StringInit *FieldName) const override;
bool isConcrete() const override { return true; }
std::string getAsString() const override;
Init *getBit(unsigned Bit) const override {
llvm_unreachable("Illegal bit reference off def");
}
};
/// classname<targs...> - Represent an uninstantiated anonymous class
/// instantiation.
class VarDefInit final : public TypedInit, public FoldingSetNode,
public TrailingObjects<VarDefInit, Init *> {
Record *Class;
DefInit *Def = nullptr; // after instantiation
unsigned NumArgs;
explicit VarDefInit(Record *Class, unsigned N)
: TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class), NumArgs(N) {}
DefInit *instantiate();
public:
VarDefInit(const VarDefInit &) = delete;
VarDefInit &operator=(const VarDefInit &) = delete;
// Do not use sized deallocation due to trailing objects.
void operator delete(void *p) { ::operator delete(p); }
static bool classof(const Init *I) {
return I->getKind() == IK_VarDefInit;
}
static VarDefInit *get(Record *Class, ArrayRef<Init *> Args);
void Profile(FoldingSetNodeID &ID) const;
Init *resolveReferences(Resolver &R) const override;
Init *Fold() const;
std::string getAsString() const override;
Init *getArg(unsigned i) const {
assert(i < NumArgs && "Argument index out of range!");
return getTrailingObjects<Init *>()[i];
}
using const_iterator = Init *const *;
const_iterator args_begin() const { return getTrailingObjects<Init *>(); }
const_iterator args_end () const { return args_begin() + NumArgs; }
size_t args_size () const { return NumArgs; }
bool args_empty() const { return NumArgs == 0; }
ArrayRef<Init *> args() const { return makeArrayRef(args_begin(), NumArgs); }
Init *getBit(unsigned Bit) const override {
llvm_unreachable("Illegal bit reference off anonymous def");
}
};
/// X.Y - Represent a reference to a subfield of a variable
class FieldInit : public TypedInit {
Init *Rec; // Record we are referring to
StringInit *FieldName; // Field we are accessing
FieldInit(Init *R, StringInit *FN)
: TypedInit(IK_FieldInit, R->getFieldType(FN)), Rec(R), FieldName(FN) {
#ifndef NDEBUG
if (!getType()) {
llvm::errs() << "In Record = " << Rec->getAsString()
<< ", got FieldName = " << *FieldName
<< " with non-record type!\n";
llvm_unreachable("FieldInit with non-record type!");
}
#endif
}
public:
FieldInit(const FieldInit &) = delete;
FieldInit &operator=(const FieldInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_FieldInit;
}
static FieldInit *get(Init *R, StringInit *FN);
Init *getRecord() const { return Rec; }
StringInit *getFieldName() const { return FieldName; }
Init *getBit(unsigned Bit) const override;
Init *resolveReferences(Resolver &R) const override;
Init *Fold(Record *CurRec) const;
bool isConcrete() const override;
std::string getAsString() const override {
return Rec->getAsString() + "." + FieldName->getValue().str();
}
};
/// (v a, b) - Represent a DAG tree value. DAG inits are required
/// to have at least one value then a (possibly empty) list of arguments. Each
/// argument can have a name associated with it.
class DagInit final : public TypedInit, public FoldingSetNode,
public TrailingObjects<DagInit, Init *, StringInit *> {
friend TrailingObjects;
Init *Val;
StringInit *ValName;
unsigned NumArgs;
unsigned NumArgNames;
DagInit(Init *V, StringInit *VN, unsigned NumArgs, unsigned NumArgNames)
: TypedInit(IK_DagInit, DagRecTy::get()), Val(V), ValName(VN),
NumArgs(NumArgs), NumArgNames(NumArgNames) {}
size_t numTrailingObjects(OverloadToken<Init *>) const { return NumArgs; }
public:
DagInit(const DagInit &) = delete;
DagInit &operator=(const DagInit &) = delete;
static bool classof(const Init *I) {
return I->getKind() == IK_DagInit;
}
static DagInit *get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
ArrayRef<StringInit*> NameRange);
static DagInit *get(Init *V, StringInit *VN,
ArrayRef<std::pair<Init*, StringInit*>> Args);
void Profile(FoldingSetNodeID &ID) const;
Init *getOperator() const { return Val; }
Record *getOperatorAsDef(ArrayRef<SMLoc> Loc) const;
StringInit *getName() const { return ValName; }
StringRef getNameStr() const {
return ValName ? ValName->getValue() : StringRef();
}
unsigned getNumArgs() const { return NumArgs; }
Init *getArg(unsigned Num) const {
assert(Num < NumArgs && "Arg number out of range!");
return getTrailingObjects<Init *>()[Num];
}
StringInit *getArgName(unsigned Num) const {
assert(Num < NumArgNames && "Arg number out of range!");
return getTrailingObjects<StringInit *>()[Num];
}
StringRef getArgNameStr(unsigned Num) const {
StringInit *Init = getArgName(Num);
return Init ? Init->getValue() : StringRef();
}
ArrayRef<Init *> getArgs() const {
return makeArrayRef(getTrailingObjects<Init *>(), NumArgs);
}
ArrayRef<StringInit *> getArgNames() const {
return makeArrayRef(getTrailingObjects<StringInit *>(), NumArgNames);
}
Init *resolveReferences(Resolver &R) const override;
bool isConcrete() const override;
std::string getAsString() const override;
using const_arg_iterator = SmallVectorImpl<Init*>::const_iterator;
using const_name_iterator = SmallVectorImpl<StringInit*>::const_iterator;
inline const_arg_iterator arg_begin() const { return getArgs().begin(); }
inline const_arg_iterator arg_end () const { return getArgs().end(); }
inline size_t arg_size () const { return NumArgs; }
inline bool arg_empty() const { return NumArgs == 0; }
inline const_name_iterator name_begin() const { return getArgNames().begin();}
inline const_name_iterator name_end () const { return getArgNames().end(); }
inline size_t name_size () const { return NumArgNames; }
inline bool name_empty() const { return NumArgNames == 0; }
Init *getBit(unsigned Bit) const override {
llvm_unreachable("Illegal bit reference off dag");
}
};
//===----------------------------------------------------------------------===//
// High-Level Classes
//===----------------------------------------------------------------------===//
/// This class represents a field in a record, including its name, type,
/// value, and source location.
class RecordVal {
friend class Record;
public:
enum FieldKind {
FK_Normal, // A normal record field.
FK_NonconcreteOK, // A field that can be nonconcrete ('field' keyword).
FK_TemplateArg, // A template argument.
};
private:
Init *Name;
SMLoc Loc; // Source location of definition of name.
PointerIntPair<RecTy *, 2, FieldKind> TyAndKind;
Init *Value;
public:
RecordVal(Init *N, RecTy *T, FieldKind K);
RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K);
/// Get the name of the field as a StringRef.
StringRef getName() const;
/// Get the name of the field as an Init.
Init *getNameInit() const { return Name; }
/// Get the name of the field as a std::string.
std::string getNameInitAsString() const {
return getNameInit()->getAsUnquotedString();
}
/// Get the source location of the point where the field was defined.
const SMLoc &getLoc() const { return Loc; }
/// Is this a field where nonconcrete values are okay?
bool isNonconcreteOK() const {
return TyAndKind.getInt() == FK_NonconcreteOK;
}
/// Is this a template argument?
bool isTemplateArg() const {
return TyAndKind.getInt() == FK_TemplateArg;
}
/// Get the type of the field value as a RecTy.
RecTy *getType() const { return TyAndKind.getPointer(); }
/// Get the type of the field for printing purposes.
std::string getPrintType() const;
/// Get the value of the field as an Init.
Init *getValue() const { return Value; }
/// Set the value of the field from an Init.
bool setValue(Init *V);
/// Set the value and source location of the field.
bool setValue(Init *V, SMLoc NewLoc);
void dump() const;
/// Print the value to an output stream, possibly with a semicolon.
void print(raw_ostream &OS, bool PrintSem = true) const;
};
inline raw_ostream &operator<<(raw_ostream &OS, const RecordVal &RV) {
RV.print(OS << " ");
return OS;
}
class Record {
static unsigned LastID;
Init *Name;
// Location where record was instantiated, followed by the location of
// multiclass prototypes used.
SmallVector<SMLoc, 4> Locs;
SmallVector<Init *, 0> TemplateArgs;
SmallVector<RecordVal, 0> Values;
// Vector of [source location, condition Init, message Init].
SmallVector<std::tuple<SMLoc, Init *, Init *>, 0> Assertions;
// All superclasses in the inheritance forest in post-order (yes, it
// must be a forest; diamond-shaped inheritance is not allowed).
SmallVector<std::pair<Record *, SMRange>, 0> SuperClasses;
// Tracks Record instances. Not owned by Record.
RecordKeeper &TrackedRecords;
// The DefInit corresponding to this record.
DefInit *CorrespondingDefInit = nullptr;
// Unique record ID.
unsigned ID;
bool IsAnonymous;
bool IsClass;
void checkName();
public:
// Constructs a record.
explicit Record(Init *N, ArrayRef<SMLoc> locs, RecordKeeper &records,
bool Anonymous = false, bool Class = false)
: Name(N), Locs(locs.begin(), locs.end()), TrackedRecords(records),
ID(LastID++), IsAnonymous(Anonymous), IsClass(Class) {
checkName();
}
explicit Record(StringRef N, ArrayRef<SMLoc> locs, RecordKeeper &records,
bool Class = false)
: Record(StringInit::get(N), locs, records, false, Class) {}
// When copy-constructing a Record, we must still guarantee a globally unique
// ID number. Don't copy CorrespondingDefInit either, since it's owned by the
// original record. All other fields can be copied normally.
Record(const Record &O)
: Name(O.Name), Locs(O.Locs), TemplateArgs(O.TemplateArgs),
Values(O.Values), SuperClasses(O.SuperClasses),
TrackedRecords(O.TrackedRecords), ID(LastID++),
IsAnonymous(O.IsAnonymous), IsClass(O.IsClass) { }
static unsigned getNewUID() { return LastID++; }
unsigned getID() const { return ID; }
StringRef getName() const { return cast<StringInit>(Name)->getValue(); }
Init *getNameInit() const {
return Name;
}
const std::string getNameInitAsString() const {
return getNameInit()->getAsUnquotedString();
}
void setName(Init *Name); // Also updates RecordKeeper.
ArrayRef<SMLoc> getLoc() const { return Locs; }
void appendLoc(SMLoc Loc) { Locs.push_back(Loc); }
// Make the type that this record should have based on its superclasses.
RecordRecTy *getType();
/// get the corresponding DefInit.
DefInit *getDefInit();
bool isClass() const { return IsClass; }
ArrayRef<Init *> getTemplateArgs() const {
return TemplateArgs;
}
ArrayRef<RecordVal> getValues() const { return Values; }
ArrayRef<std::tuple<SMLoc, Init *, Init *>> getAssertions() const {
return Assertions;
}
ArrayRef<std::pair<Record *, SMRange>> getSuperClasses() const {
return SuperClasses;
}
/// Determine whether this record has the specified direct superclass.
bool hasDirectSuperClass(const Record *SuperClass) const;
/// Append the direct superclasses of this record to Classes.
void getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const;
bool isTemplateArg(Init *Name) const {
for (Init *TA : TemplateArgs)
if (TA == Name) return true;
return false;
}
const RecordVal *getValue(const Init *Name) const {
for (const RecordVal &Val : Values)
if (Val.Name == Name) return &Val;
return nullptr;
}
const RecordVal *getValue(StringRef Name) const {
return getValue(StringInit::get(Name));
}
RecordVal *getValue(const Init *Name) {
return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
}
RecordVal *getValue(StringRef Name) {
return const_cast<RecordVal *>(static_cast<const Record *>(this)->getValue(Name));
}
void addTemplateArg(Init *Name) {
assert(!isTemplateArg(Name) && "Template arg already defined!");
TemplateArgs.push_back(Name);
}
void addValue(const RecordVal &RV) {
assert(getValue(RV.getNameInit()) == nullptr && "Value already added!");
Values.push_back(RV);
}
void removeValue(Init *Name) {
for (unsigned i = 0, e = Values.size(); i != e; ++i)
if (Values[i].getNameInit() == Name) {
Values.erase(Values.begin()+i);
return;
}
llvm_unreachable("Cannot remove an entry that does not exist!");
}
void removeValue(StringRef Name) {
removeValue(StringInit::get(Name));
}
void addAssertion(SMLoc Loc, Init *Condition, Init *Message) {
Assertions.push_back(std::make_tuple(Loc, Condition, Message));
}
bool isSubClassOf(const Record *R) const {
for (const auto &SCPair : SuperClasses)
if (SCPair.first == R)
return true;
return false;
}
bool isSubClassOf(StringRef Name) const {
for (const auto &SCPair : SuperClasses) {
if (const auto *SI = dyn_cast<StringInit>(SCPair.first->getNameInit())) {
if (SI->getValue() == Name)
return true;
} else if (SCPair.first->getNameInitAsString() == Name) {
return true;
}
}
return false;
}
void addSuperClass(Record *R, SMRange Range) {
assert(!CorrespondingDefInit &&
"changing type of record after it has been referenced");
assert(!isSubClassOf(R) && "Already subclassing record!");
SuperClasses.push_back(std::make_pair(R, Range));
}
/// If there are any field references that refer to fields
/// that have been filled in, we can propagate the values now.
///
/// This is a final resolve: any error messages, e.g. due to undefined
/// !cast references, are generated now.
void resolveReferences();
/// Apply the resolver to the name of the record as well as to the
/// initializers of all fields of the record except SkipVal.
///
/// The resolver should not resolve any of the fields itself, to avoid
/// recursion / infinite loops.
void resolveReferences(Resolver &R, const RecordVal *SkipVal = nullptr);
RecordKeeper &getRecords() const {
return TrackedRecords;
}
bool isAnonymous() const {
return IsAnonymous;
}
void dump() const;
//===--------------------------------------------------------------------===//
// High-level methods useful to tablegen back-ends
//
///Return the source location for the named field.
SMLoc getFieldLoc(StringRef FieldName) const;
/// Return the initializer for a value with the specified name,
/// or throw an exception if the field does not exist.
Init *getValueInit(StringRef FieldName) const;
/// Return true if the named field is unset.
bool isValueUnset(StringRef FieldName) const {
return isa<UnsetInit>(getValueInit(FieldName));
}
/// This method looks up the specified field and returns
/// its value as a string, throwing an exception if the field does not exist
/// or if the value is not a string.
StringRef getValueAsString(StringRef FieldName) const;
/// This method looks up the specified field and returns
/// its value as a string, throwing an exception if the field if the value is
/// not a string and llvm::Optional() if the field does not exist.
llvm::Optional<StringRef> getValueAsOptionalString(StringRef FieldName) const;
/// This method looks up the specified field and returns
/// its value as a BitsInit, throwing an exception if the field does not exist
/// or if the value is not the right type.
BitsInit *getValueAsBitsInit(StringRef FieldName) const;
/// This method looks up the specified field and returns
/// its value as a ListInit, throwing an exception if the field does not exist
/// or if the value is not the right type.
ListInit *getValueAsListInit(StringRef FieldName) const;
/// This method looks up the specified field and
/// returns its value as a vector of records, throwing an exception if the
/// field does not exist or if the value is not the right type.
std::vector<Record*> getValueAsListOfDefs(StringRef FieldName) const;
/// This method looks up the specified field and
/// returns its value as a vector of integers, throwing an exception if the
/// field does not exist or if the value is not the right type.
std::vector<int64_t> getValueAsListOfInts(StringRef FieldName) const;
/// This method looks up the specified field and
/// returns its value as a vector of strings, throwing an exception if the
/// field does not exist or if the value is not the right type.
std::vector<StringRef> getValueAsListOfStrings(StringRef FieldName) const;
/// This method looks up the specified field and returns its
/// value as a Record, throwing an exception if the field does not exist or if
/// the value is not the right type.
Record *getValueAsDef(StringRef FieldName) const;
/// This method looks up the specified field and returns its value as a
/// Record, returning null if the field exists but is "uninitialized"
/// (i.e. set to `?`), and throwing an exception if the field does not
/// exist or if its value is not the right type.
Record *getValueAsOptionalDef(StringRef FieldName) const;
/// This method looks up the specified field and returns its
/// value as a bit, throwing an exception if the field does not exist or if
/// the value is not the right type.
bool getValueAsBit(StringRef FieldName) const;
/// This method looks up the specified field and
/// returns its value as a bit. If the field is unset, sets Unset to true and
/// returns false.
bool getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const;
/// This method looks up the specified field and returns its
/// value as an int64_t, throwing an exception if the field does not exist or
/// if the value is not the right type.
int64_t getValueAsInt(StringRef FieldName) const;
/// This method looks up the specified field and returns its
/// value as an Dag, throwing an exception if the field does not exist or if
/// the value is not the right type.
DagInit *getValueAsDag(StringRef FieldName) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Record &R);
class RecordKeeper {
friend class RecordRecTy;
using RecordMap = std::map<std::string, std::unique_ptr<Record>, std::less<>>;
using GlobalMap = std::map<std::string, Init *, std::less<>>;
std::string InputFilename;
RecordMap Classes, Defs;
mutable StringMap<std::vector<Record *>> ClassRecordsMap;
FoldingSet<RecordRecTy> RecordTypePool;
std::map<std::string, Init *, std::less<>> ExtraGlobals;
unsigned AnonCounter = 0;
// These members are for the phase timing feature. We need a timer group,
// the last timer started, and a flag to say whether the last timer
// is the special "backend overall timer."
TimerGroup *TimingGroup = nullptr;
Timer *LastTimer = nullptr;
bool BackendTimer = false;
public:
/// Get the main TableGen input file's name.
const std::string getInputFilename() const { return InputFilename; }
/// Get the map of classes.
const RecordMap &getClasses() const { return Classes; }
/// Get the map of records (defs).
const RecordMap &getDefs() const { return Defs; }
/// Get the map of global variables.
const GlobalMap &getGlobals() const { return ExtraGlobals; }
/// Get the class with the specified name.
Record *getClass(StringRef Name) const {
auto I = Classes.find(Name);
return I == Classes.end() ? nullptr : I->second.get();
}
/// Get the concrete record with the specified name.
Record *getDef(StringRef Name) const {
auto I = Defs.find(Name);
return I == Defs.end() ? nullptr : I->second.get();
}
/// Get the \p Init value of the specified global variable.
Init *getGlobal(StringRef Name) const {
if (Record *R = getDef(Name))
return R->getDefInit();
auto It = ExtraGlobals.find(Name);
return It == ExtraGlobals.end() ? nullptr : It->second;
}
void saveInputFilename(std::string Filename) {
InputFilename = Filename;
}
void addClass(std::unique_ptr<Record> R) {
bool Ins = Classes.insert(std::make_pair(std::string(R->getName()),
std::move(R))).second;
(void)Ins;
assert(Ins && "Class already exists");
}
void addDef(std::unique_ptr<Record> R) {
bool Ins = Defs.insert(std::make_pair(std::string(R->getName()),
std::move(R))).second;
(void)Ins;
assert(Ins && "Record already exists");
}
void addExtraGlobal(StringRef Name, Init *I) {
bool Ins = ExtraGlobals.insert(std::make_pair(std::string(Name), I)).second;
(void)Ins;
assert(!getDef(Name));
assert(Ins && "Global already exists");
}
Init *getNewAnonymousName();
/// Start phase timing; called if the --time-phases option is specified.
void startPhaseTiming() {
TimingGroup = new TimerGroup("TableGen", "TableGen Phase Timing");
}
/// Start timing a phase. Automatically stops any previous phase timer.
void startTimer(StringRef Name);
/// Stop timing a phase.
void stopTimer();
/// Start timing the overall backend. If the backend itself starts a timer,
/// then this timer is cleared.
void startBackendTimer(StringRef Name);
/// Stop timing the overall backend.
void stopBackendTimer();
/// Stop phase timing and print the report.
void stopPhaseTiming() {
if (TimingGroup)
delete TimingGroup;
}
//===--------------------------------------------------------------------===//
// High-level helper methods, useful for tablegen backends.
/// Get all the concrete records that inherit from the one specified
/// class. The class must be defined.
std::vector<Record *> getAllDerivedDefinitions(StringRef ClassName) const;
/// Get all the concrete records that inherit from all the specified
/// classes. The classes must be defined.
std::vector<Record *> getAllDerivedDefinitions(
ArrayRef<StringRef> ClassNames) const;
void dump() const;
};
/// Sorting predicate to sort record pointers by name.
struct LessRecord {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return StringRef(Rec1->getName()).compare_numeric(Rec2->getName()) < 0;
}
};
/// Sorting predicate to sort record pointers by their
/// unique ID. If you just need a deterministic order, use this, since it
/// just compares two `unsigned`; the other sorting predicates require
/// string manipulation.
struct LessRecordByID {
bool operator()(const Record *LHS, const Record *RHS) const {
return LHS->getID() < RHS->getID();
}
};
/// Sorting predicate to sort record pointers by their
/// name field.
struct LessRecordFieldName {
bool operator()(const Record *Rec1, const Record *Rec2) const {
return Rec1->getValueAsString("Name") < Rec2->getValueAsString("Name");
}
};
struct LessRecordRegister {
struct RecordParts {
SmallVector<std::pair< bool, StringRef>, 4> Parts;
RecordParts(StringRef Rec) {
if (Rec.empty())
return;
size_t Len = 0;
const char *Start = Rec.data();
const char *Curr = Start;
bool IsDigitPart = isDigit(Curr[0]);
for (size_t I = 0, E = Rec.size(); I != E; ++I, ++Len) {
bool IsDigit = isDigit(Curr[I]);
if (IsDigit != IsDigitPart) {
Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
Len = 0;
Start = &Curr[I];
IsDigitPart = isDigit(Curr[I]);
}
}
// Push the last part.
Parts.push_back(std::make_pair(IsDigitPart, StringRef(Start, Len)));
}
size_t size() { return Parts.size(); }
std::pair<bool, StringRef> getPart(size_t i) {
assert (i < Parts.size() && "Invalid idx!");
return Parts[i];
}
};
bool operator()(const Record *Rec1, const Record *Rec2) const {
RecordParts LHSParts(StringRef(Rec1->getName()));
RecordParts RHSParts(StringRef(Rec2->getName()));
size_t LHSNumParts = LHSParts.size();
size_t RHSNumParts = RHSParts.size();
assert (LHSNumParts && RHSNumParts && "Expected at least one part!");
if (LHSNumParts != RHSNumParts)
return LHSNumParts < RHSNumParts;
// We expect the registers to be of the form [_a-zA-Z]+([0-9]*[_a-zA-Z]*)*.
for (size_t I = 0, E = LHSNumParts; I < E; I+=2) {
std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
// Expect even part to always be alpha.
assert (LHSPart.first == false && RHSPart.first == false &&
"Expected both parts to be alpha.");
if (int Res = LHSPart.second.compare(RHSPart.second))
return Res < 0;
}
for (size_t I = 1, E = LHSNumParts; I < E; I+=2) {
std::pair<bool, StringRef> LHSPart = LHSParts.getPart(I);
std::pair<bool, StringRef> RHSPart = RHSParts.getPart(I);
// Expect odd part to always be numeric.
assert (LHSPart.first == true && RHSPart.first == true &&
"Expected both parts to be numeric.");
if (LHSPart.second.size() != RHSPart.second.size())
return LHSPart.second.size() < RHSPart.second.size();
unsigned LHSVal, RHSVal;
bool LHSFailed = LHSPart.second.getAsInteger(10, LHSVal); (void)LHSFailed;
assert(!LHSFailed && "Unable to convert LHS to integer.");
bool RHSFailed = RHSPart.second.getAsInteger(10, RHSVal); (void)RHSFailed;
assert(!RHSFailed && "Unable to convert RHS to integer.");
if (LHSVal != RHSVal)
return LHSVal < RHSVal;
}
return LHSNumParts < RHSNumParts;
}
};
raw_ostream &operator<<(raw_ostream &OS, const RecordKeeper &RK);
//===----------------------------------------------------------------------===//
// Resolvers
//===----------------------------------------------------------------------===//
/// Interface for looking up the initializer for a variable name, used by
/// Init::resolveReferences.
class Resolver {
Record *CurRec;
bool IsFinal = false;
public:
explicit Resolver(Record *CurRec) : CurRec(CurRec) {}
virtual ~Resolver() {}
Record *getCurrentRecord() const { return CurRec; }
/// Return the initializer for the given variable name (should normally be a
/// StringInit), or nullptr if the name could not be resolved.
virtual Init *resolve(Init *VarName) = 0;
// Whether bits in a BitsInit should stay unresolved if resolving them would
// result in a ? (UnsetInit). This behavior is used to represent instruction
// encodings by keeping references to unset variables within a record.
virtual bool keepUnsetBits() const { return false; }
// Whether this is the final resolve step before adding a record to the
// RecordKeeper. Error reporting during resolve and related constant folding
// should only happen when this is true.
bool isFinal() const { return IsFinal; }
void setFinal(bool Final) { IsFinal = Final; }
};
/// Resolve arbitrary mappings.
class MapResolver final : public Resolver {
struct MappedValue {
Init *V;
bool Resolved;
MappedValue() : V(nullptr), Resolved(false) {}
MappedValue(Init *V, bool Resolved) : V(V), Resolved(Resolved) {}
};
DenseMap<Init *, MappedValue> Map;
public:
explicit MapResolver(Record *CurRec = nullptr) : Resolver(CurRec) {}
void set(Init *Key, Init *Value) { Map[Key] = {Value, false}; }
Init *resolve(Init *VarName) override;
};
/// Resolve all variables from a record except for unset variables.
class RecordResolver final : public Resolver {
DenseMap<Init *, Init *> Cache;
SmallVector<Init *, 4> Stack;
public:
explicit RecordResolver(Record &R) : Resolver(&R) {}
Init *resolve(Init *VarName) override;
bool keepUnsetBits() const override { return true; }
};
/// Delegate resolving to a sub-resolver, but shadow some variable names.
class ShadowResolver final : public Resolver {
Resolver &R;
DenseSet<Init *> Shadowed;
public:
explicit ShadowResolver(Resolver &R)
: Resolver(R.getCurrentRecord()), R(R) {
setFinal(R.isFinal());
}
void addShadow(Init *Key) { Shadowed.insert(Key); }
Init *resolve(Init *VarName) override {
if (Shadowed.count(VarName))
return nullptr;
return R.resolve(VarName);
}
};
/// (Optionally) delegate resolving to a sub-resolver, and keep track whether
/// there were unresolved references.
class TrackUnresolvedResolver final : public Resolver {
Resolver *R;
bool FoundUnresolved = false;
public:
explicit TrackUnresolvedResolver(Resolver *R = nullptr)
: Resolver(R ? R->getCurrentRecord() : nullptr), R(R) {}
bool foundUnresolved() const { return FoundUnresolved; }
Init *resolve(Init *VarName) override;
};
/// Do not resolve anything, but keep track of whether a given variable was
/// referenced.
class HasReferenceResolver final : public Resolver {
Init *VarNameToTrack;
bool Found = false;
public:
explicit HasReferenceResolver(Init *VarNameToTrack)
: Resolver(nullptr), VarNameToTrack(VarNameToTrack) {}
bool found() const { return Found; }
Init *resolve(Init *VarName) override;
};
void EmitDetailedRecords(RecordKeeper &RK, raw_ostream &OS);
void EmitJSON(RecordKeeper &RK, raw_ostream &OS);
} // end namespace llvm
#endif // LLVM_TABLEGEN_RECORD_H
|
sabel83/metashell
|
3rd/templight/llvm/include/llvm/TableGen/Record.h
|
C
|
gpl-3.0
| 64,254
|
<?php
/**
Copyright 2011-2016 Nick Korbel
This file is part of Booked Scheduler.
Booked Scheduler 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.
Booked Scheduler 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 Booked Scheduler. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(ROOT_DIR . 'Presenters/Install/Installer.php');
require_once(ROOT_DIR . 'Presenters/Install/MySqlScript.php');
require_once(ROOT_DIR . 'Presenters/Install/InstallationResult.php');
require_once(ROOT_DIR . 'Presenters/Install/InstallSecurityGuard.php');
class InstallPresenter
{
/**
* @var IInstallPage
*/
private $page;
/**
* @var InstallSecurityGuard
*/
private $securityGuard;
public function __construct(IInstallPage $page, InstallSecurityGuard $securityGuard)
{
$this->page = $page;
$this->securityGuard = $securityGuard;
}
/**
* Get and Set data to be process by template engine
* @return void
*/
public function PageLoad()
{
if ($this->page->RunningInstall())
{
$this->RunInstall();
return;
}
if ($this->page->RunningUpgrade())
{
$this->RunUpgrade();
return;
}
$dbname = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_NAME);
$dbuser = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_USER);
$dbhost = Configuration::Instance()->GetSectionKey(ConfigSection::DATABASE, ConfigKeys::DATABASE_HOSTSPEC);
$this->page->SetDatabaseConfig($dbname, $dbuser, $dbhost);
$this->CheckForInstallPasswordInConfig();
$this->CheckForInstallPasswordProvided();
$this->CheckForAuthentication();
$this->CheckForUpgrade();
}
public function CheckForInstallPasswordInConfig()
{
$this->page->SetInstallPasswordMissing(!$this->securityGuard->CheckForInstallPasswordInConfig());
}
private function CheckForInstallPasswordProvided()
{
if ($this->securityGuard->IsAuthenticated())
{
return;
}
$installPassword = $this->page->GetInstallPassword();
if (empty($installPassword))
{
$this->page->SetShowPasswordPrompt(true);
return;
}
$validated = $this->Validate($installPassword);
if (!$validated)
{
$this->page->SetShowPasswordPrompt(true);
$this->page->SetShowInvalidPassword(true);
return;
}
$this->page->SetShowPasswordPrompt(false);
$this->page->SetShowInvalidPassword(false);
}
private function CheckForAuthentication()
{
if ($this->securityGuard->IsAuthenticated())
{
$this->page->SetShowDatabasePrompt(true);
return;
}
$this->page->SetShowDatabasePrompt(false);
}
private function Validate($installPassword)
{
return $this->securityGuard->ValidatePassword($installPassword);
}
private function RunInstall()
{
$install = new Installer($this->page->GetInstallUser(), $this->page->GetInstallUserPassword());
$results = $install->InstallFresh($this->page->GetShouldCreateDatabase(), $this->page->GetShouldCreateUser(), $this->page->GetShouldCreateSampleData());
$install->ClearCachedTemplates();
$this->page->SetInstallResults($results);
}
private function RunUpgrade()
{
$install = new Installer($this->page->GetInstallUser(), $this->page->GetInstallUserPassword());
$results = $install->Upgrade();
$install->ClearCachedTemplates();
$this->page->SetUpgradeResults($results, Configuration::VERSION);
}
private function CheckForUpgrade()
{
$install = new Installer($this->page->GetInstallUser(), $this->page->GetInstallUserPassword());
$currentVersion = $install->GetVersion();
if (!$currentVersion)
{
$this->page->ShowInstallOptions(true);
return;
}
if (floatval($currentVersion) < floatval(Configuration::VERSION))
{
$this->page->SetCurrentVersion($currentVersion);
$this->page->SetTargetVersion(Configuration::VERSION);
$this->page->ShowUpgradeOptions(true);
}
else
{
$this->page->ShowUpToDate(true);
$this->page->ShowInstallOptions(false);
$this->page->ShowUpgradeOptions(false);
$this->page->SetShowDatabasePrompt(false);
$this->page->SetShowPasswordPrompt(false);
$this->page->SetInstallPasswordMissing(false);
}
}
}
|
sdc/booked
|
Presenters/Install/InstallPresenter.php
|
PHP
|
gpl-3.0
| 4,597
|
/// <reference path="../_import/_fibjs.d.ts" />
/**
* @description json 编码与解码模块
* 引用方式:
* ```JavaScript
* var encoding = require('encoding');
* var json = encoding.json;
* ```
* 或者
* ```JavaScript
* var json = require('json');
* ```
*
*/
declare module 'json' {
/**
* @description 以 json 格式编码变量
* @param data 要编码的变量
* @return 返回编码的字符串
*
*/
function encode(data: any): string;
/**
* @description 以 json 方式解码字符串为一个变量
* @param data 要解码的字符串
* @return 返回解码的变量
*
*/
function decode(data: string): any;
}
|
fibjs/fibjs
|
npm/types/dts/module/json.d.ts
|
TypeScript
|
gpl-3.0
| 728
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var arrayify = require('array-back');
var option = require('./option');
var findReplace = require('find-replace');
var Argv = function () {
function Argv(argv) {
_classCallCheck(this, Argv);
if (argv) {
argv = arrayify(argv);
} else {
argv = process.argv.slice(0);
argv.splice(0, 2);
}
this.list = argv;
}
_createClass(Argv, [{
key: 'clear',
value: function clear() {
this.list.length = 0;
}
}, {
key: 'expandOptionEqualsNotation',
value: function expandOptionEqualsNotation() {
var _this = this;
var optEquals = option.optEquals;
if (this.list.some(optEquals.test.bind(optEquals))) {
(function () {
var expandedArgs = [];
_this.list.forEach(function (arg) {
var matches = arg.match(optEquals.re);
if (matches) {
expandedArgs.push(matches[1], matches[2]);
} else {
expandedArgs.push(arg);
}
});
_this.clear();
_this.list = expandedArgs;
})();
}
}
}, {
key: 'expandGetoptNotation',
value: function expandGetoptNotation() {
var combinedArg = option.combined;
var hasGetopt = this.list.some(combinedArg.test.bind(combinedArg));
if (hasGetopt) {
findReplace(this.list, combinedArg.re, function (arg) {
arg = arg.slice(1);
return arg.split('').map(function (letter) {
return '-' + letter;
});
});
}
}
}, {
key: 'validate',
value: function validate(definitions) {
var invalidOption = undefined;
var optionWithoutDefinition = this.list.filter(function (arg) {
return option.isOption(arg);
}).some(function (arg) {
if (definitions.get(arg) === undefined) {
invalidOption = arg;
return true;
}
});
if (optionWithoutDefinition) {
halt('UNKNOWN_OPTION', 'Unknown option: ' + invalidOption);
}
}
}]);
return Argv;
}();
function halt(name, message) {
var err = new Error(message);
err.name = name;
throw err;
}
module.exports = Argv;
|
klhdy/im-indepartment
|
packORGAN/client/sealtalk-desktop-ent-src/node_modules/command-line-args/es5/argv.js
|
JavaScript
|
gpl-3.0
| 3,008
|
url: http://sanskrit.jnu.ac.in/sandhi/viccheda.jsp?itext=वृद्धो वराकोऽप्रत्याशितं वराकोऽप्रत्याशितं परुषवचनं परुषवचनं वज्राघातनिभमुत्तरं वज्राघातनिभमुत्तरं निशम्य<html>
<title>Sanskrit Sandhi Splitter at J.N.U. New Delhi</title>
<META CONTENT='text/hetml CHARSET=UTF-8' HTTP-EQUIV='Content-Type'/>
<META NAME="Author" CONTENT="Dr. Girish Nath Jha">
<META NAME="Keywords" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<META NAME="Description" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<head>
<head>
<style>
<!--
div.Section1
{page:Section1;}
-->
</style>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<script language="JavaScript" src=../js/menuitems.js></script>
<script language="JavaScript" src="../js/mm_menu.js"></script>
<meta name=Author content="Dr. Girish Nath Jha, JNU, New Delhi">
</head>
<body lang=EN-US link=blue vlink=blue style='tab-interval:.5in'>
<div class=Section1>
<div align=center>
<table border=1 cellspacing=0 cellpadding=0 width=802 style='width:601.5pt;
border-collapse:collapse;border:none;mso-border-alt:outset navy .75pt'>
<tr>
<td width=800 style='width:600.0pt;border:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<script language="JavaScript1.2">mmLoadMenus();</script>
<img width=800 height=130 id="_x0000_i1028" src="../images/header1.jpg"
border=0>
</td>
</tr>
<tr>
<td width=818 style='width:613.5pt;border:inset navy .75pt;border-top:none;
mso-border-top-alt:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<p align="center"><a href="../"><span style='text-decoration:none;text-underline:
none'><img border=1 width=49 height=26 id="_x0000_i1037"
src="../images/backtohome.jpg"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171051_0,6,29,null,'image2')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image2 src="../images/lang_tool.jpg"
name=image2 width="192" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171909_0,6,29,null,'image3')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image3 src="../images/lexical.jpg"
name=image3 width="137" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171609_0,6,29,null,'image1')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image1 src="../images/elearning.jpg"
name=image1 width="77" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171809_0,6,29,null,'image4')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image4 src="../images/corpora.jpg"
name=image4 width="105" height="26"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171709_0,6,29,null,'image5')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image5 src="../images/rstudents.jpg"
name=image5 width="125" height="26"></span></a><span style='text-underline:
none'> </span>
<a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171409_0,6,29,null,'image6')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image6 src="../images/feedback.jpg"
name=image6 width="80" height="25"></span></a><span style='text-underline:
none'> </span>
<!---
<a href="../user/feedback.jsp"><img border="1" src="../images/feedback.jpg" width="80" height="25"></a>
--->
</td>
</tr>
<tr>
<td width="800">
<p align="center"><font color="#FF9933"><span style='font-size:18.0pt;
'><b>Sanskrit Sandhi Recognizer and Analyzer</b></span></font></p>
The Sanskrit sandhi splitter (VOWEL SANDHI) was developed as part of M.Phil. research by <a href="mailto:sachin.jnu@gmail.com">Sachin Kumar</a> (M.Phil. 2005-2007), and <a href=mailto:diwakarmishra@gmail.com>Diwakar Mishra</a> (M.Phil. 2007-2009) under the supervision of <a href=http://www.jnu.ac.in/faculty/gnjha>Dr. Girish Nath Jha</a>. The coding for this application has been done by Dr. Girish Nath Jha and Diwakar Mishra. <!---Please send feedback to to <a href="mailto:girishj@mail.jnu.ac.in">Dr. Girish Nath Jha</A>--->The Devanagari input mechanism has been developed in Javascript by Satyendra Kumar Chaube, Dr. Girish Nath Jha and Dharm Singh Rathore.
</center>
<table border=0 width=100%>
<tr>
<td valign=top width=48%>
<table>
<tr>
<td>
<FORM METHOD=get ACTION=viccheda.jsp#results name="iform" accept-Charset="UTF-8">
<font size=2><b>Enter Sanskrit text for sandhi processing (संधि-विच्छेद हेतु पाठ्य दें)
using adjacent keyboard OR Use our inbuilt <a href=../js/itrans.html target=_blank>iTRANS</a>-Devanagari unicode converter for fast typing<br>
<a href=sandhitest.txt>examples</a>
<TEXTAREA name=itext COLS=40 ROWS=9 onkeypress=checkKeycode(event) onkeyup=iu()> वृद्धो वराकोऽप्रत्याशितं वराकोऽप्रत्याशितं परुषवचनं परुषवचनं वज्राघातनिभमुत्तरं वज्राघातनिभमुत्तरं निशम्य</TEXTAREA>
</td>
</tr>
<tr>
<td>
<font color=red size=2>Run in debug mode</font>
<input type=checkbox name="debug" value="ON">
<br>
<input type=submit value="Click to sandhi-split (संधि-विच्छेद करें)"></span><br>
</td>
</tr>
</table>
</td>
<td valign=top width=52%>
<table>
<tr>
<td>
<head>
<SCRIPT language=JavaScript src="../js/devkb.js"></SCRIPT>
<head>
<TEXTAREA name=itrans rows=5 cols=10 style="display:none"></TEXTAREA>
<INPUT name=lastChar type=hidden>
<table border=2 style="background-color:#fff;">
<tbody>
<tr >
<td>
<input type=button name="btn" style="width: 24px" value="अ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="आ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="इ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ई" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="उ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऊ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ए" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऐ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ओ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="औ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऍ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऑ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="्" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ा" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ि" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ी" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ु" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ू" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="े" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ै" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ो" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ौ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॅ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॉ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="क" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ख" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ग" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="घ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ङ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="च" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="छ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="झ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 100px" value="Backspace" onClick="BackSpace()">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="+" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ट" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ठ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ड" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ढ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ण" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="त" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="थ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="द" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ध" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="न" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="/" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="प" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="फ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ब" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="भ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="म" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="य" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ल" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="व" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="।" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="*" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="स" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ऋ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऌ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ृ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॄ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ह" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="॥" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="त्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज्ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="क्ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 200px" value="Space Bar" onClick="Space()">
<input type=button name="btn" style="width: 24px" value="ँ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="़" onClick="keyboard(this.value)">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
</table>
</form>
<a name=results>
<font size=4><b><u>Results</u></b></font>
<br>
वृद्ध ऊ (गुणसन्धि आद् गुणः)<br> वृद्ध उ (गुणसन्धि आद् गुणः)<br> परुषो चनं (अयादिसन्धि एचोऽयवायावः)<br> परुषू चनं (यण् सन्धि इको यणचि)<br> परुषु चनं (यण् सन्धि इको यणचि)<br> परुष चनं (लोपः शाकल्यस्य)<br> परुषो चनं (अयादिसन्धि एचोऽयवायावः)<br> परुषू चनं (यण् सन्धि इको यणचि)<br> परुषु चनं (यण् सन्धि इको यणचि)<br> परुष चनं (लोपः शाकल्यस्य)<br>
<br>
<font color=red>
<br>
<hr>
<br>
</body>
</html>
|
sanskritiitd/sanskrit
|
uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/Sanskritkathakunj_ext.txt.out.dict_11368_jnu.html
|
HTML
|
gpl-3.0
| 17,914
|
var searchData=
[
['btserial',['BTSerial',['../control__2_80_8c.html#a14bb84b12818dd2f13acf63d4cb14d98',1,'control_2.0.c']]]
];
|
mora260/ie0117_III16
|
grupo7/Proyecto 1: Control/Documentacion/html/search/functions_0.js
|
JavaScript
|
gpl-3.0
| 130
|
"""Beautiful Soup
Elixir and Tonic
"The Screen-Scraper's Friend"
http://www.crummy.com/software/BeautifulSoup/
Beautiful Soup uses a pluggable XML or HTML parser to parse a
(possibly invalid) document into a tree representation. Beautiful Soup
provides provides methods and Pythonic idioms that make it easy to
navigate, search, and modify the parse tree.
Beautiful Soup works with Python 2.6 and up. It works better if lxml
and/or html5lib is installed.
For more than you ever wanted to know about Beautiful Soup, see the
documentation:
http://www.crummy.com/software/BeautifulSoup/bs4/doc/
"""
__author__ = "Leonard Richardson (leonardr@segfault.org)"
__version__ = "4.0.4"
__copyright__ = "Copyright (c) 2004-2012 Leonard Richardson"
__license__ = "MIT"
__all__ = ['BeautifulSoup']
import re
import warnings
from .builder import builder_registry
from .dammit import UnicodeDammit
from .element import (
CData,
Comment,
DEFAULT_OUTPUT_ENCODING,
Declaration,
Doctype,
NavigableString,
PageElement,
ProcessingInstruction,
ResultSet,
SoupStrainer,
Tag,
)
# The very first thing we do is give a useful error if someone is
# running this code under Python 3 without converting it.
syntax_error = u'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work. You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).'
class BeautifulSoup(Tag):
"""
This class defines the basic interface called by the tree builders.
These methods will be called by the parser:
reset()
feed(markup)
The tree builder may call these methods from its feed() implementation:
handle_starttag(name, attrs) # See note about return value
handle_endtag(name)
handle_data(data) # Appends to the current data node
endData(containerClass=NavigableString) # Ends the current data node
No matter how complicated the underlying parser is, you should be
able to build a tree using 'start tag' events, 'end tag' events,
'data' events, and "done with data" events.
If you encounter an empty-element tag (aka a self-closing tag,
like HTML's <br> tag), call handle_starttag and then
handle_endtag.
"""
ROOT_TAG_NAME = u'[document]'
# If the end-user gives no indication which tree builder they
# want, look for one with these features.
DEFAULT_BUILDER_FEATURES = ['html', 'fast']
# Used when determining whether a text node is all whitespace and
# can be replaced with a single space. A text node that contains
# fancy Unicode spaces (usually non-breaking) should be left
# alone.
STRIP_ASCII_SPACES = {9: None, 10: None, 12: None, 13: None, 32: None, }
def __init__(self, markup="", features=None, builder=None,
parse_only=None, from_encoding=None, **kwargs):
"""The Soup object is initialized as the 'root tag', and the
provided markup (which can be a string or a file-like object)
is fed into the underlying parser."""
if 'convertEntities' in kwargs:
warnings.warn(
"BS4 does not respect the convertEntities argument to the "
"BeautifulSoup constructor. Entities are always converted "
"to Unicode characters.")
if 'markupMassage' in kwargs:
del kwargs['markupMassage']
warnings.warn(
"BS4 does not respect the markupMassage argument to the "
"BeautifulSoup constructor. The tree builder is responsible "
"for any necessary markup massage.")
if 'smartQuotesTo' in kwargs:
del kwargs['smartQuotesTo']
warnings.warn(
"BS4 does not respect the smartQuotesTo argument to the "
"BeautifulSoup constructor. Smart quotes are always converted "
"to Unicode characters.")
if 'selfClosingTags' in kwargs:
del kwargs['selfClosingTags']
warnings.warn(
"BS4 does not respect the selfClosingTags argument to the "
"BeautifulSoup constructor. The tree builder is responsible "
"for understanding self-closing tags.")
if 'isHTML' in kwargs:
del kwargs['isHTML']
warnings.warn(
"BS4 does not respect the isHTML argument to the "
"BeautifulSoup constructor. You can pass in features='html' "
"or features='xml' to get a builder capable of handling "
"one or the other.")
def deprecated_argument(old_name, new_name):
if old_name in kwargs:
warnings.warn(
'The "%s" argument to the BeautifulSoup constructor '
'has been renamed to "%s."' % (old_name, new_name))
value = kwargs[old_name]
del kwargs[old_name]
return value
return None
parse_only = parse_only or deprecated_argument(
"parseOnlyThese", "parse_only")
from_encoding = from_encoding or deprecated_argument(
"fromEncoding", "from_encoding")
if len(kwargs) > 0:
arg = kwargs.keys().pop()
raise TypeError(
"__init__() got an unexpected keyword argument '%s'" % arg)
if builder is None:
if isinstance(features, basestring):
features = [features]
if features is None or len(features) == 0:
features = self.DEFAULT_BUILDER_FEATURES
builder_class = builder_registry.lookup(*features)
if builder_class is None:
raise ValueError(
"Couldn't find a tree builder with the features you "
"requested: %s. Do you need to install a parser library?"
% ",".join(features))
builder = builder_class()
self.builder = builder
self.is_xml = builder.is_xml
self.builder.soup = self
self.parse_only = parse_only
self.reset()
if hasattr(markup, 'read'): # It's a file-type object.
markup = markup.read()
(self.markup, self.original_encoding, self.declared_html_encoding,
self.contains_replacement_characters) = (
self.builder.prepare_markup(markup, from_encoding))
try:
self._feed()
except StopParsing:
pass
# Clear out the markup and remove the builder's circular
# reference to this object.
self.markup = None
self.builder.soup = None
def _feed(self):
# Convert the document to Unicode.
self.builder.reset()
self.builder.feed(self.markup)
# Close out any unfinished strings and close all the open tags.
self.endData()
while self.currentTag.name != self.ROOT_TAG_NAME:
self.popTag()
def reset(self):
Tag.__init__(self, self, self.builder, self.ROOT_TAG_NAME)
self.hidden = 1
self.builder.reset()
self.currentData = []
self.currentTag = None
self.tagStack = []
self.pushTag(self)
def new_tag(self, name, namespace=None, nsprefix=None, **attrs):
"""Create a new tag associated with this soup."""
return Tag(None, self.builder, name, namespace, nsprefix, attrs)
def new_string(self, s):
"""Create a new NavigableString associated with this soup."""
navigable = NavigableString(s)
navigable.setup()
return navigable
def insert_before(self, successor):
raise ValueError("BeautifulSoup objects don't support insert_before().")
def insert_after(self, successor):
raise ValueError("BeautifulSoup objects don't support insert_after().")
def popTag(self):
tag = self.tagStack.pop()
#print "Pop", tag.name
if self.tagStack:
self.currentTag = self.tagStack[-1]
return self.currentTag
def pushTag(self, tag):
#print "Push", tag.name
if self.currentTag:
self.currentTag.contents.append(tag)
self.tagStack.append(tag)
self.currentTag = self.tagStack[-1]
def endData(self, containerClass=NavigableString):
if self.currentData:
currentData = u''.join(self.currentData)
if (currentData.translate(self.STRIP_ASCII_SPACES) == '' and
not set([tag.name for tag in self.tagStack]).intersection(
self.builder.preserve_whitespace_tags)):
if '\n' in currentData:
currentData = '\n'
else:
currentData = ' '
self.currentData = []
if self.parse_only and len(self.tagStack) <= 1 and \
(not self.parse_only.text or \
not self.parse_only.search(currentData)):
return
o = containerClass(currentData)
self.object_was_parsed(o)
def object_was_parsed(self, o):
"""Add an object to the parse tree."""
o.setup(self.currentTag, self.previous_element)
if self.previous_element:
self.previous_element.next_element = o
self.previous_element = o
self.currentTag.contents.append(o)
def _popToTag(self, name, nsprefix=None, inclusivePop=True):
"""Pops the tag stack up to and including the most recent
instance of the given tag. If inclusivePop is false, pops the tag
stack up to but *not* including the most recent instqance of
the given tag."""
#print "Popping to %s" % name
if name == self.ROOT_TAG_NAME:
return
numPops = 0
mostRecentTag = None
for i in range(len(self.tagStack) - 1, 0, -1):
if (name == self.tagStack[i].name
and nsprefix == self.tagStack[i].nsprefix == nsprefix):
numPops = len(self.tagStack) - i
break
if not inclusivePop:
numPops = numPops - 1
for i in range(0, numPops):
mostRecentTag = self.popTag()
return mostRecentTag
def handle_starttag(self, name, namespace, nsprefix, attrs):
"""Push a start tag on to the stack.
If this method returns None, the tag was rejected by the
SoupStrainer. You should proceed as if the tag had not occured
in the document. For instance, if this was a self-closing tag,
don't call handle_endtag.
"""
# print "Start tag %s: %s" % (name, attrs)
self.endData()
if (self.parse_only and len(self.tagStack) <= 1
and (self.parse_only.text
or not self.parse_only.search_tag(name, attrs))):
return None
tag = Tag(self, self.builder, name, namespace, nsprefix, attrs,
self.currentTag, self.previous_element)
if tag is None:
return tag
if self.previous_element:
self.previous_element.next_element = tag
self.previous_element = tag
self.pushTag(tag)
return tag
def handle_endtag(self, name, nsprefix=None):
#print "End tag: " + name
self.endData()
self._popToTag(name, nsprefix)
def handle_data(self, data):
self.currentData.append(data)
def decode(self, pretty_print=False,
eventual_encoding=DEFAULT_OUTPUT_ENCODING,
formatter="minimal"):
"""Returns a string or Unicode representation of this document.
To get Unicode, pass None for encoding."""
if self.is_xml:
# Print the XML declaration
encoding_part = ''
if eventual_encoding != None:
encoding_part = ' encoding="%s"' % eventual_encoding
prefix = u'<?xml version="1.0"%s?>\n' % encoding_part
else:
prefix = u''
if not pretty_print:
indent_level = None
else:
indent_level = 0
return prefix + super(BeautifulSoup, self).decode(
indent_level, eventual_encoding, formatter)
class BeautifulStoneSoup(BeautifulSoup):
"""Deprecated interface to an XML parser."""
def __init__(self, *args, **kwargs):
kwargs['features'] = 'xml'
warnings.warn(
'The BeautifulStoneSoup class is deprecated. Instead of using '
'it, pass features="xml" into the BeautifulSoup constructor.')
super(BeautifulStoneSoup, self).__init__(*args, **kwargs)
class StopParsing(Exception):
pass
#By default, act as an HTML pretty-printer.
if __name__ == '__main__':
import sys
soup = BeautifulSoup(sys.stdin)
print soup.prettify()
|
heldergg/dre
|
lib/bs4/__init__.py
|
Python
|
gpl-3.0
| 12,881
|
---------------------------------------------------
-- Purulent Ooze
-- Family: Slugs
-- Description: Deals Water damage in a fan-shaped area of effect. Additional effect: Bio and Max HP Down
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Cone
-- Notes:
---------------------------------------------------
require("scripts/globals/monstertpmoves");
require("scripts/globals/settings");
require("scripts/globals/status");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1;
local baseDamage = mob:getWeaponDmg()*3;
local info = MobMagicalMove(mob,target,skill,baseDamage,ELE_WATER,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_WIPE_SHADOWS);
MobStatusEffectMove(mob, target, dsp.effects.BIO, 5, 3, 120, FLAG_ERASABLE, 10);
MobStatusEffectMove(mob, target, dsp.effects.MAX_HP_DOWN, 10, 0, 120);
target:delHP(dmg);
return dmg;
end;
|
Whitechaser/darkstar
|
scripts/globals/mobskills/purulent_ooze.lua
|
Lua
|
gpl-3.0
| 1,086
|
/**
* outline styles
*/
.djs-outline {
fill: none;
visibility: hidden;
}
.djs-element.hover .djs-outline,
.djs-element.selected .djs-outline {
visibility: visible;
shape-rendering: crispEdges;
stroke-dasharray: 3,3;
}
.djs-element.selected .djs-outline {
stroke: #8888FF;
stroke-width: 1px;
}
.djs-element.hover .djs-outline {
stroke: #FF8888;
stroke-width: 1px;
}
.djs-shape.connect-ok .djs-visual > :nth-child(1) {
fill: #DCFECC /* light-green */ !important;
}
.djs-shape.connect-not-ok .djs-visual > :nth-child(1),
.djs-shape.drop-not-ok .djs-visual > :nth-child(1) {
fill: #f9dee5 /* light-red */ !important;
}
.djs-shape.new-parent .djs-visual > :nth-child(1) {
fill: #F7F9FF !important;
}
svg.drop-not-ok {
background: #f9dee5 /* light-red */ !important;
}
svg.new-parent {
background: #F7F9FF /* light-blue */ !important;
}
.djs-connection.connect-ok .djs-visual > :nth-child(1),
.djs-connection.drop-ok .djs-visual > :nth-child(1) {
stroke: #90DD5F /* light-green */ !important;
}
.djs-connection.connect-not-ok .djs-visual > :nth-child(1),
.djs-connection.drop-not-ok .djs-visual > :nth-child(1) {
stroke: #E56283 /* light-red */ !important;
}
.drop-not-ok,
.connect-not-ok {
cursor: not-allowed;
}
.djs-element.attach-ok .djs-visual > :nth-child(1) {
stroke-width: 5px !important;
stroke: rgba(255, 116, 0, 0.7);
}
/**
* Selection box style
*
*/
.djs-lasso-overlay {
fill: rgb(255, 116, 0);
fill-opacity: 0.1;
stroke-dasharray: 5 1 3 1;
stroke: rgb(255, 116, 0);
shape-rendering: crispEdges;
pointer-events: none;
}
/**
* Resize styles
*/
.djs-resize-overlay {
fill: white;
fill-opacity: 0.8;
stroke-dasharray: 5 1 3 1;
stroke: rgb(255, 116, 0);
pointer-events: none;
}
.djs-resizer-hit {
fill: none;
pointer-events: all;
}
.djs-resizer-visual {
fill: white;
stroke-width: 1px;
stroke: black;
shape-rendering: crispEdges;
stroke-opacity: 0.2;
}
.djs-cursor-resize-nwse,
.djs-resizer-nw,
.djs-resizer-se {
cursor: nwse-resize;
}
.djs-cursor-resize-nesw,
.djs-resizer-ne,
.djs-resizer-sw {
cursor: nesw-resize;
}
.djs-shape.djs-resizing > .djs-outline {
visibility: hidden !important;
}
.djs-shape.djs-resizing > .djs-resizer {
visibility: hidden;
}
.djs-dragger > .djs-resizer {
visibility: hidden;
}
/**
* drag styles
*/
.djs-dragger {
fill: white;
fill-opacity: 0.6;
stroke: #333;
}
.djs-dragger .djs-visual > :first-child {
stroke: rgb(255, 116, 0) !important;
}
.djs-dragging {
opacity: 0.3;
}
.djs-dragging,
.djs-dragging > * {
pointer-events: none !important;
}
.djs-dragging .djs-context-pad,
.djs-dragging .djs-outline {
display: none !important;
}
/**
* no pointer events for visual
*/
.djs-visual,
.djs-outline {
pointer-events: none;
}
/**
* all pointer events for hit shape
*/
.djs-shape .djs-hit {
pointer-events: all;
}
.djs-connection .djs-hit {
pointer-events: stroke;
}
/**
* shape / connection basic styles
*/
.djs-connection .djs-visual {
stroke-width: 2px;
fill: none;
}
.djs-cursor-grab {
cursor: -webkit-grab;
cursor: -moz-grab;
cursor: grab;
}
.djs-cursor-grabbing {
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
cursor: grabbing;
}
.djs-cursor-crosshair {
cursor: crosshair;
}
.djs-cursor-move {
cursor: move;
}
.djs-cursor-resize-ns {
cursor: ns-resize;
}
.djs-cursor-resize-ew {
cursor: ew-resize;
}
/**
* snapping
*/
.djs-snap-line {
stroke: rgb(255, 195, 66);
stroke: rgba(255, 195, 66, 0.50);
stroke-linecap: round;
stroke-width: 2px;
pointer-events: none;
}
/**
* snapping
*/
.djs-crosshair {
stroke: #555;
stroke-linecap: round;
stroke-width: 1px;
pointer-events: none;
shape-rendering: crispEdges;
stroke-dasharray: 5, 5;
}
/**
* palette
*/
.djs-palette {
position: absolute;
left: 20px;
top: 20px;
}
.djs-palette:not(.open) {
overflow: hidden;
}
.djs-palette .entry,
.djs-palette .djs-palette-toggle {
width: 46px;
height: 46px;
line-height: 46px;
cursor: default;
}
.djs-palette .separator {
margin: 3px 5px 5px 5px;
border: none;
border-top: solid 1px #DDD;
}
.djs-palette .entry:before {
vertical-align: middle;
}
.djs-palette .djs-palette-toggle {
cursor: pointer;
}
.djs-palette .entry,
.djs-palette .djs-palette-toggle {
color: #333;
font-size: 30px;
text-align: center;
}
.djs-palette .entry img {
max-width: 100%;
}
.djs-palette.open .djs-palette-toggle {
height: 10px;
}
.djs-palette:not(.open) .djs-palette-entries {
display: none;
}
confirm
.djs-palette .djs-palette-toggle:hover {
background: #666;
}
.djs-palette .entry:hover {
color: rgb(255, 116, 0);
}
.highlighted-entry {
color: rgb(255, 116, 0) !important;
}
confirm
/**
* context-pad
*/
.djs-overlay-context-pad {
width: 72px;
}
.djs-context-pad {
position: absolute;
display: none;
pointer-events: none;
}
.djs-context-pad .entry {
width: 22px;
height: 22px;
text-align: center;
display: inline-block;
font-size: 22px;
margin: 0 2px 2px 0;
border-radius: 3px;
cursor: default;
background-color: #FEFEFE;
box-shadow: 0 0 2px 1px #FEFEFE;
pointer-events: all;
}
.djs-context-pad .entry:before {
vertical-align: top;
}
.djs-context-pad .entry:hover {
background: rgb(255, 252, 176);
}
.djs-context-pad.open {
display: block;
}
/**
* popup styles
*/
.djs-popup .entry {
line-height: 20px;
white-space: nowrap;
border: solid 1px transparent;
cursor: default;
}
/* larger font for prefixed icons */
.djs-popup .entry:before {
vertical-align: middle;
font-size: 20px;
}
.djs-popup .entry > span {
vertical-align: middle;
font-size: 14px;
}
.djs-popup .entry:hover,
.djs-popup .entry.active:hover {
background: rgb(255, 252, 176);
}
.djs-popup .entry.disabled {
background: inherit;
}
.djs-popup .entry.active {
color: rgb(255, 116, 0);
border: solid 1px rgb(255, 116, 0);
border-radius: 3px;
background-color: #F6F6F6;
}
.djs-popup-body .entry {
padding: 2px 10px 2px 5px;
}
.djs-popup-header .entry {
display: inline-block;
padding: 2px 3px 2px 3px;
}
.djs-popup-body .entry > span {
margin-left: 5px;
}
.djs-popup-body {
background-color: #FEFEFE;
}
.djs-popup-header {
border-bottom: 1px solid #DDD;
}
.djs-popup-header .entry {
margin: 1px;
margin-left: 3px;
}
.djs-popup-header .entry:last-child {
margin-right: 3px;
}
/**
* popup / palette styles
*/
.djs-popup, .djs-palette {
background: #FAFAFA;
border: solid 1px #CCC;
border-radius: 2px;
box-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
/**
* touch
*/
.djs-shape,
.djs-connection {
touch-action: none;
}
.djs-segment-dragger,
.djs-bendpoint {
display: none;
}
/**
* bendpoints
*/
.djs-segment-dragger .djs-visual {
fill: rgba(255, 255, 121, 0.2);
stroke-width: 1px;
stroke-opacity: 1;
stroke: rgba(255, 255, 121, 0.3);
}
.djs-bendpoint .djs-visual {
fill: rgba(255, 255, 121, 0.8);
stroke-width: 1px;
stroke-opacity: 0.5;
stroke: black;
}
.djs-segment-dragger:hover,
.djs-bendpoints.hover .djs-segment-dragger,
.djs-bendpoints.selected .djs-segment-dragger,
.djs-bendpoint:hover,
.djs-bendpoints.hover .djs-bendpoint,
.djs-bendpoints.selected .djs-bendpoint {
display: block;
}
.djs-drag-active .djs-bendpoints * {
display: none;
}
.djs-bendpoints:not(.hover) .floating {
display: none;
}
.djs-segment-dragger:hover .djs-visual,
.djs-segment-dragger.djs-dragging .djs-visual,
.djs-bendpoint:hover .djs-visual,
.djs-bendpoint.floating .djs-visual {
fill: yellow;
stroke-opacity: 0.5;
stroke: black;
}
.djs-bendpoint.floating .djs-hit {
pointer-events: none;
}
.djs-segment-dragger .djs-hit,
.djs-bendpoint .djs-hit {
pointer-events: all;
fill: none;
}
.djs-segment-dragger.horizontal .djs-hit {
cursor: ns-resize;
}
.djs-segment-dragger.vertical .djs-hit {
cursor: ew-resize;
}
.djs-segment-dragger.djs-dragging .djs-hit {
pointer-events: none;
}
.djs-updating,
.djs-updating > * {
pointer-events: none !important;
}
.djs-updating .djs-context-pad,
.djs-updating .djs-outline,
.djs-updating .djs-bendpoint,
.connect-ok .djs-bendpoint,
.connect-not-ok .djs-bendpoint,
.drop-ok .djs-bendpoint,
.drop-not-ok .djs-bendpoint {
display: none !important;
}
.djs-segment-dragger.djs-dragging,
.djs-bendpoint.djs-dragging {
display: block;
opacity: 1.0;
}
.djs-segment-dragger.djs-dragging .djs-visual,
.djs-bendpoint.djs-dragging .djs-visual {
fill: yellow;
stroke-opacity: 0.5;
}
/**
* tooltips
*/
.djs-tooltip-error {
font-size: 11px;
line-height: 18px;
text-align: left;
padding: 5px;
opacity: 0.7;
}
.djs-tooltip-error > * {
width: 160px;
background: rgb(252, 236, 240);
color: rgb(158, 76, 76);
padding: 3px 7px;
box-shadow: 0 1px 2px rgba(0,0,0, 0.2);
border-radius: 5px;
border-left: solid 5px rgb(174, 73, 73);
}
.djs-tooltip-error:hover {
opacity: 1;
}
|
zetaops/ulakbus-ui
|
app/admin/css/diagram-js.css
|
CSS
|
gpl-3.0
| 8,916
|
/**
* Copyright (C) 2015 Envidatec GmbH <info@envidatec.com>
*
* This file is part of JECommons.
*
* JECommons 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 in version 3.
*
* JECommons 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
* JECommons. If not, see <http://www.gnu.org/licenses/>.
*
* JECommons is part of the OpenJEVis project, further project information are
* published at <http://www.OpenJEVis.org/>.
*/
package org.jevis.commons.dataprocessing.function;
import java.util.ArrayList;
import java.util.List;
import org.jevis.api.JEVisSample;
import org.jevis.commons.dataprocessing.ProcessOption;
import org.jevis.commons.dataprocessing.BasicProcessOption;
import org.jevis.commons.dataprocessing.ProcessFunction;
import org.jevis.commons.dataprocessing.Process;
/**
*
* @author Florian Simon <florian.simon@envidatec.com>
*/
public class NullFunction implements ProcessFunction {
public static final String NAME = "null";
@Override
public void resetResult() {
}
@Override
public List<JEVisSample> getResult(Process task) {
System.out.println("Waring no Processor is set");
return new ArrayList<>();
}
@Override
public String getName() {
return NAME;
}
@Override
public List<ProcessOption> getAvailableOptions() {
List<ProcessOption> options = new ArrayList<>();
return options;
}
}
|
AIT-JEVis/JECommons
|
src/main/java/org/jevis/commons/dataprocessing/function/NullFunction.java
|
Java
|
gpl-3.0
| 1,785
|
package com.encens.khipus.action.fixedassets;
import com.encens.khipus.action.dashboard.PieGraphic;
import com.encens.khipus.action.dashboard.PieWidgetViewAction;
import com.encens.khipus.dashboard.component.sql.SqlQuery;
import com.encens.khipus.dashboard.module.fixedAssets.FixedAssetMaintenanceWidgetSql;
import com.encens.khipus.model.dashboard.Filter;
import com.encens.khipus.model.dashboard.Interval;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
* @author
* @version 2.26
*/
@Name("fixedAssetMaintenanceWidgetAction")
@Scope(ScopeType.EVENT)
public class FixedAssetMaintenanceWidgetAction extends PieWidgetViewAction<PieGraphic> {
public static final String XML_WIDGET_ID = "3";
private Integer executorUnitId;
@Create
public void initialize() {
setGraphic(new PieGraphic());
initializeWidget();
}
public byte[] createChart() {
return getGraphic().createChart();
}
@Override
protected String getXmlWidgetId() {
return XML_WIDGET_ID;
}
@Override
protected void applyConfigurationFilter(Filter filter, SqlQuery sqlQuery) {
if (filter instanceof Interval) {
((FixedAssetMaintenanceWidgetSql) sqlQuery).setStart(((Interval) filter).getMinValue());
((FixedAssetMaintenanceWidgetSql) sqlQuery).setEnd(((Interval) filter).getMaxValue());
}
}
@Override
protected void setFilters(SqlQuery sqlQuery) {
((FixedAssetMaintenanceWidgetSql) sqlQuery).setExecutorUnitId(executorUnitId);
}
@Override
protected SqlQuery getSqlQueryInstance() {
return new FixedAssetMaintenanceWidgetSql();
}
public void disableExecutorUnit() {
executorUnitId = null;
}
public void enableExecutorUnit(Integer executorUnitId) {
this.executorUnitId = executorUnitId;
}
}
|
borboton13/sisk13
|
src/main/com/encens/khipus/action/fixedassets/FixedAssetMaintenanceWidgetAction.java
|
Java
|
gpl-3.0
| 1,965
|
/*
* Copyright (c) 2021 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.opal.web.gwt.app.client.administration.datashield.profiles;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
import org.obiba.opal.web.gwt.app.client.administration.datashield.event.DataShieldProfileDeletedEvent;
import org.obiba.opal.web.gwt.app.client.administration.datashield.event.DataShieldProfileInitEvent;
import org.obiba.opal.web.gwt.app.client.administration.datashield.profiles.config.DataShieldMethodsPresenter;
import org.obiba.opal.web.gwt.app.client.administration.datashield.profiles.config.DataShieldROptionsPresenter;
import org.obiba.opal.web.gwt.app.client.event.ConfirmationEvent;
import org.obiba.opal.web.gwt.app.client.event.ConfirmationRequiredEvent;
import org.obiba.opal.web.gwt.app.client.event.ConfirmationTerminatedEvent;
import org.obiba.opal.web.gwt.app.client.i18n.TranslationMessages;
import org.obiba.opal.web.gwt.app.client.permissions.ResourcePermissionsPresenter;
import org.obiba.opal.web.gwt.app.client.permissions.support.ResourcePermissionRequestPaths;
import org.obiba.opal.web.gwt.app.client.permissions.support.ResourcePermissionType;
import org.obiba.opal.web.gwt.rest.client.*;
import org.obiba.opal.web.model.client.datashield.DataShieldProfileDto;
import org.obiba.opal.web.model.client.opal.r.RServerClusterDto;
import static com.google.gwt.http.client.Response.*;
public class DataShieldProfilePresenter
extends PresenterWidget<DataShieldProfilePresenter.Display>
implements DataShieldProfileUiHandlers {
private final Provider<ResourcePermissionsPresenter> resourcePermissionsProvider;
public static final Object AggregateEnvironmentSlot = new Object();
public static final Object AssignEnvironmentSlot = new Object();
public static final Object OptionsSlot = new Object();
public static Object PermissionsSlot = new Object();
private final TranslationMessages translationMessages;
private final Provider<DataShieldMethodsPresenter> methodsPresenterProvider;
private final Provider<DataShieldROptionsPresenter> optionsProvider;
private DataShieldProfileDto profile;
private RServerClusterDto cluster;
private ResourcePermissionsPresenter resourcePermissionsPresenter;
private Runnable removeProfileConfirmation;
@Inject
public DataShieldProfilePresenter(Display display, EventBus eventBus,
Provider<ResourcePermissionsPresenter> resourcePermissionsProvider,
TranslationMessages translationMessages, Provider<DataShieldMethodsPresenter> methodsPresenterProvider,
Provider<DataShieldROptionsPresenter> optionsProvider) {
super(eventBus, display);
this.translationMessages = translationMessages;
getView().setUiHandlers(this);
this.methodsPresenterProvider = methodsPresenterProvider;
this.resourcePermissionsProvider = resourcePermissionsProvider;
this.optionsProvider = optionsProvider;
}
@Override
public void onProfileDelete() {
removeProfileConfirmation = new Runnable() {
@Override
public void run() {
UriBuilder builder = UriBuilders.DATASHIELD_PROFILE.create();
if (profile.getName().equals(profile.getCluster()))
builder.query("force", "true");
ResourceRequestBuilderFactory.newBuilder()
.forResource(builder.build(profile.getName()))
.withCallback(new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
fireEvent(ConfirmationTerminatedEvent.create());
fireEvent(new DataShieldProfileDeletedEvent(profile));
}
}, SC_NO_CONTENT, SC_NOT_FOUND, SC_BAD_REQUEST, SC_BAD_GATEWAY, SC_INTERNAL_SERVER_ERROR)
.delete().send();
}
};
getEventBus().fireEvent(ConfirmationRequiredEvent
.createWithMessages(removeProfileConfirmation, translationMessages.removeDataShieldProfile(),
translationMessages.confirmDeleteDataShieldProfile(profile.getName())));
}
@Override
public void onProfileInitialize() {
fireEvent(new DataShieldProfileInitEvent(profile));
}
public void initialize(DataShieldProfileDto profile, RServerClusterDto cluster) {
this.profile = profile;
this.cluster = cluster;
DataShieldMethodsPresenter assignPresenter = methodsPresenterProvider.get();
assignPresenter.setEnvironment(DataShieldEnvironment.ASSIGN);
assignPresenter.setProfile(profile);
addToSlot(AssignEnvironmentSlot, assignPresenter);
DataShieldMethodsPresenter aggregatePresenter = methodsPresenterProvider.get();
aggregatePresenter.setEnvironment(DataShieldEnvironment.AGGREGATE);
aggregatePresenter.setProfile(profile);
addToSlot(AggregateEnvironmentSlot, aggregatePresenter);
DataShieldROptionsPresenter optionsPresenter = optionsProvider.get();
optionsPresenter.setProfile(profile);
addToSlot(OptionsSlot, optionsPresenter);
resourcePermissionsPresenter = resourcePermissionsProvider.get();
resourcePermissionsPresenter.initialize(ResourcePermissionType.DATASHIELD_PROFILE,
ResourcePermissionRequestPaths.UriBuilders.DATASHIELD_PROFILE_PERMISSIONS, profile.getName());
addToSlot(PermissionsSlot, resourcePermissionsPresenter);
getView().renderProfile(profile, cluster);
}
@Override
public void onProfileEnable(final boolean enabled) {
ResourceRequestBuilder<?> request = ResourceRequestBuilderFactory.newBuilder()
.forResource(UriBuilders.DATASHIELD_PROFILE_ENABLE.create().build(profile.getName()))
.withCallback(new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == SC_OK) {
profile.setEnabled(enabled);
}
getView().renderProfile(profile, cluster);
}
}, SC_OK, SC_NOT_FOUND, SC_BAD_REQUEST, SC_BAD_GATEWAY, SC_INTERNAL_SERVER_ERROR);
if (enabled)
request.put().send();
else
request.delete().send();
}
@Override
public void onProfileRestrictAccess(final boolean restricted) {
ResourceRequestBuilder<?> request = ResourceRequestBuilderFactory.newBuilder()
.forResource(UriBuilders.DATASHIELD_PROFILE_ACCESS.create().build(profile.getName()))
.withCallback(new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
if (response.getStatusCode() == SC_OK) {
profile.setRestrictedAccess(restricted);
}
getView().renderProfile(profile, cluster);
resourcePermissionsPresenter.refreshPermissions();
}
}, SC_OK, SC_NOT_FOUND, SC_BAD_REQUEST, SC_BAD_GATEWAY, SC_INTERNAL_SERVER_ERROR);
if (restricted)
request.put().send();
else
request.delete().send();
}
@Override
protected void onBind() {
addRegisteredHandler(ConfirmationEvent.getType(), new ConfirmationEvent.Handler() {
@Override
public void onConfirmation(ConfirmationEvent event) {
if (event.getSource().equals(removeProfileConfirmation) && event.isConfirmed()) {
removeProfileConfirmation.run();
removeProfileConfirmation = null;
}
}
});
}
public interface DataShieldEnvironment {
String ASSIGN = "assign";
String AGGREGATE = "aggregate";
}
public interface Display extends View, HasUiHandlers<DataShieldProfileUiHandlers> {
void renderProfile(DataShieldProfileDto profile, RServerClusterDto cluster);
}
}
|
kazoompa/opal
|
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/datashield/profiles/DataShieldProfilePresenter.java
|
Java
|
gpl-3.0
| 8,272
|
#!/usr/bin/env python3
# encoding: utf-8
from nose import with_setup
from tests.utils import *
@with_setup(usual_setup_func, usual_teardown_func)
def test_negative():
create_file('xxx', 'b.png')
create_file('xxx', 'a.png')
create_file('xxx', 'a')
head, *data, footer = run_rmlint('-i')
assert footer['total_files'] == 3
assert footer['total_lint_size'] == 0
assert footer['duplicates'] == 0
@with_setup(usual_setup_func, usual_teardown_func)
def test_positive():
create_file('xxx', 'a.png')
create_file('xxx', 'a.jpg')
head, *data, footer = run_rmlint('-i')
assert footer['total_files'] == 2
assert footer['total_lint_size'] == 3
assert footer['duplicates'] == 1
|
SeeSpotRun/rmlint
|
tests/test_options/test_match_without_extension.py
|
Python
|
gpl-3.0
| 718
|
/*
Copyright 2005-2010 Jakub Kruszona-Zawadzki, Gemius SA, 2013-2014 EditShare, 2013-2015 Skytechnology sp. z o.o..
This file was part of MooseFS and is part of LizardFS.
LizardFS 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 3.
LizardFS 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 LizardFS If not, see <http://www.gnu.org/licenses/>.
*/
#include "common/platform.h"
#include <stdio.h>
#include "chunkserver/chartsdata.h"
#include "chunkserver/hddspacemgr.h"
#include "chunkserver/masterconn.h"
#include "chunkserver/network_main_thread.h"
#include "common/random.h"
#define STR_AUX(x) #x
#define STR(x) STR_AUX(x)
/* Run Tab */
typedef int (*runfn)(void);
struct run_tab {
runfn fn;
const char *name;
};
run_tab RunTab[]={
{rnd_init,"random generator"},
{hdd_init,"hdd space manager"},
{mainNetworkThreadInit,"main server module"}, /* it has to be before "masterconn" */
{masterconn_init,"master connection module"},
{chartsdata_init,"charts module"},
{(runfn)0,"****"}
},LateRunTab[]={
{masterconn_init_threads,"master connection module - threads"},
{hdd_late_init,"hdd space manager - threads"},
{mainNetworkThreadInitThreads,"main server module - threads"},
{(runfn)0,"****"}
},EarlyRunTab[]={
{(runfn)0,"****"}
};
|
lizardfs/lizardfs
|
src/chunkserver/init.h
|
C
|
gpl-3.0
| 1,650
|
# -*- coding: utf-8 -*-
"""Copyright (c) 2009 Sergio Gabriel Teves
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from django import template
from django.conf import settings
from django.utils.encoding import smart_str, force_unicode
from django.utils.safestring import mark_safe
import string
import re
register = template.Library()
@register.inclusion_tag('tags/smileysrender.html')
def smileyrender():
list = []
for item in settings.SMILEYS_PACK:
list.append({'code': item[0],'img': settings.SMILEYS_ROOT + item[1]})
return {'list': list}
@register.filter
def smiley(value):
img = '<img src="%s"/>'
for item in settings.SMILEYS_PACK:
code = string.replace(string.replace(item[0], "(", "\("),")","\)")
pattern = r"(?i)%s" % code
value = re.sub(pattern, img % (settings.SMILEYS_ROOT + item[1]),value)
return mark_safe(value)
@register.filter
def bbcode(value):
"""
Generates (X)HTML from string with BBCode "markup".
By using the postmark lib from:
@see: http://code.google.com/p/postmarkup/
"""
try:
from postmarkup import render_bbcode
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
return force_unicode(value)
else:
return mark_safe(render_bbcode(value))
bbcode.is_save = True
@register.filter
def strip_bbcode(value):
"""
Strips BBCode tags from a string
By using the postmark lib from:
@see: http://code.google.com/p/postmarkup/
"""
try:
from postmarkup import strip_bbcode
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% bbcode %} filter: The Python postmarkup library isn't installed."
return force_unicode(value)
else:
return mark_safe(strip_bbcode(value))
bbcode.is_save = True
|
dahool/vertaal
|
djangoapp/templatetags/bbcodetag.py
|
Python
|
gpl-3.0
| 2,634
|
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickGear.
#
# SickGear 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.
#
# SickGear 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 SickGear. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
from collections import OrderedDict
import datetime
import io
import os.path
import re
from . import helpers as metadata_helpers
from .. import logger
import sg_helpers
from ..indexers import indexer_config
from ..indexers.indexer_config import TVINFO_TVDB, TVINFO_TMDB
from lib.tvinfo_base import TVInfoImage, TVInfoImageType, TVInfoImageSize
from lib.tvinfo_base.exceptions import *
import sickbeard
# noinspection PyPep8Naming
import encodingKludge as ek
from exceptions_helper import ex
from lib.fanart.core import Request as fanartRequest
import lib.fanart as fanart
from lxml_etree import etree
from _23 import filter_iter, list_keys
from six import iteritems, itervalues, string_types
# noinspection PyUnreachableCode
if False:
from typing import AnyStr, Dict, Generator, List, Optional, Tuple, Union
from lib.tvinfo_base import TVInfoShow
from ..tv import TVShow
map_image_types = {
'poster': TVInfoImageType.poster,
'banner': TVInfoImageType.banner,
'fanart': TVInfoImageType.fanart,
'poster_thumb': TVInfoImageType.poster,
'banner_thumb': TVInfoImageType.banner,
}
class ShowInfosDict(OrderedDict):
def __getitem__(self, k):
v = OrderedDict.__getitem__(self, k)
if callable(v):
v = v(k)
OrderedDict.__setitem__(self, k, v)
return v
class GenericMetadata(object):
"""
Base class for all metadata providers. Default behavior is meant to mostly
follow XBMC 12+ metadata standards. Has support for:
- show metadata file
- episode metadata file
- episode thumbnail
- show fanart
- show poster
- show banner
- season thumbnails (poster)
- season thumbnails (banner)
- season all poster
- season all banner
"""
def __init__(self,
show_metadata=False, # type: bool
episode_metadata=False, # type: bool
use_fanart=False, # type: bool
use_poster=False, # type: bool
use_banner=False, # type: bool
episode_thumbnails=False, # type: bool
season_posters=False, # type: bool
season_banners=False, # type: bool
season_all_poster=False, # type: bool
season_all_banner=False # type: bool
):
self.name = "Generic" # type: AnyStr
self._ep_nfo_extension = "nfo" # type: AnyStr
self._show_metadata_filename = "tvshow.nfo" # type: AnyStr
self.fanart_name = "fanart.jpg" # type: AnyStr
self.poster_name = "poster.jpg" # type: AnyStr
self.banner_name = "banner.jpg" # type: AnyStr
self.season_all_poster_name = "season-all-poster.jpg" # type: AnyStr
self.season_all_banner_name = "season-all-banner.jpg" # type: AnyStr
self.show_metadata = show_metadata
self.episode_metadata = episode_metadata
self.fanart = use_fanart
self.poster = use_poster
self.banner = use_banner
self.episode_thumbnails = episode_thumbnails
self.season_posters = season_posters
self.season_banners = season_banners
self.season_all_poster = season_all_poster
self.season_all_banner = season_all_banner
def get_config(self):
# type: (...) -> AnyStr
config_list = [self.show_metadata, self.episode_metadata, self.fanart, self.poster, self.banner,
self.episode_thumbnails, self.season_posters, self.season_banners, self.season_all_poster,
self.season_all_banner]
return '|'.join([str(int(x)) for x in config_list])
def get_id(self):
# type: (...) -> AnyStr
return GenericMetadata.makeID(self.name)
@staticmethod
def makeID(name):
# type: (AnyStr) -> AnyStr
name_id = re.sub("[+]", "plus", name)
name_id = re.sub(r"[^\w\d_]", "_", name_id).lower()
return name_id
def set_config(self, string):
# type: (AnyStr) -> None
config_list = [bool(int(x)) for x in string.split('|')]
self.show_metadata = config_list[0]
self.episode_metadata = config_list[1]
self.fanart = config_list[2]
self.poster = config_list[3]
self.banner = config_list[4]
self.episode_thumbnails = config_list[5]
self.season_posters = config_list[6]
self.season_banners = config_list[7]
self.season_all_poster = config_list[8]
self.season_all_banner = config_list[9]
def _has_show_metadata(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
result = ek.ek(os.path.isfile, self.get_show_file_path(show_obj))
logger.log(u"Checking if " + self.get_show_file_path(show_obj) + " exists: " + str(result), logger.DEBUG)
return result
def has_episode_metadata(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> AnyStr
result = ek.ek(os.path.isfile, self.get_episode_file_path(ep_obj))
logger.log(u"Checking if " + self.get_episode_file_path(ep_obj) + " exists: " + str(result), logger.DEBUG)
return result
def _has_fanart(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
result = ek.ek(os.path.isfile, self.get_fanart_path(show_obj))
logger.log(u"Checking if " + self.get_fanart_path(show_obj) + " exists: " + str(result), logger.DEBUG)
return result
def _has_poster(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
result = ek.ek(os.path.isfile, self.get_poster_path(show_obj))
logger.log(u"Checking if " + self.get_poster_path(show_obj) + " exists: " + str(result), logger.DEBUG)
return result
def _has_banner(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
result = ek.ek(os.path.isfile, self.get_banner_path(show_obj))
logger.log(u"Checking if " + self.get_banner_path(show_obj) + " exists: " + str(result), logger.DEBUG)
return result
def has_episode_thumb(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> AnyStr
location = self.get_episode_thumb_path(ep_obj)
result = None is not location and ek.ek(os.path.isfile, location)
if location:
logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG)
return result
def _has_season_poster(self, show_obj, season):
# type: (sickbeard.tv.TVShow,int) -> AnyStr
location = self.get_season_poster_path(show_obj, season)
result = None is not location and ek.ek(os.path.isfile, location)
if location:
logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG)
return result
def _has_season_banner(self, show_obj, season):
# type: (sickbeard.tv.TVShow,int) -> AnyStr
location = self.get_season_banner_path(show_obj, season)
result = None is not location and ek.ek(os.path.isfile, location)
if location:
logger.log(u"Checking if " + location + " exists: " + str(result), logger.DEBUG)
return result
def _has_season_all_poster(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
result = ek.ek(os.path.isfile, self.get_season_all_poster_path(show_obj))
logger.log(u"Checking if " + self.get_season_all_poster_path(show_obj) + " exists: " + str(result),
logger.DEBUG)
return result
def _has_season_all_banner(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
result = ek.ek(os.path.isfile, self.get_season_all_banner_path(show_obj))
logger.log(u"Checking if " + self.get_season_all_banner_path(show_obj) + " exists: " + str(result),
logger.DEBUG)
return result
@staticmethod
def get_show_year(show_obj, show_info, year_only=True):
# type: (sickbeard.tv.TVShow, Dict, bool) -> Optional[AnyStr]
if None is not getattr(show_info, 'firstaired', None):
try:
first_aired = datetime.datetime.strptime(show_info['firstaired'], '%Y-%m-%d')
if first_aired:
if year_only:
return str(first_aired.year)
return str(first_aired.date())
except (BaseException, Exception):
pass
if isinstance(show_obj, sickbeard.tv.TVShow):
if year_only and show_obj.startyear:
return '%s' % show_obj.startyear
if not show_obj.sxe_ep_obj.get(1, {}).get(1, None):
show_obj.get_all_episodes()
try:
first_ep_obj = show_obj.first_aired_regular_episode
except (BaseException, Exception):
first_ep_obj = None
if isinstance(first_ep_obj, sickbeard.tv.TVEpisode) \
and isinstance(first_ep_obj.airdate, datetime.date) and 1900 < first_ep_obj.airdate.year:
return '%s' % (first_ep_obj.airdate.year, first_ep_obj.airdate)[not year_only]
def get_show_file_path(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
return ek.ek(os.path.join, show_obj.location, self._show_metadata_filename)
def get_episode_file_path(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> AnyStr
return sg_helpers.replace_extension(ep_obj.location, self._ep_nfo_extension)
def get_fanart_path(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
return ek.ek(os.path.join, show_obj.location, self.fanart_name)
def get_poster_path(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
return ek.ek(os.path.join, show_obj.location, self.poster_name)
def get_banner_path(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
return ek.ek(os.path.join, show_obj.location, self.banner_name)
def get_episode_thumb_path(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> Optional[AnyStr]
"""
Returns the path where the episode thumbnail should be stored.
ep_obj: a TVEpisode instance for which to create the thumbnail
"""
if ek.ek(os.path.isfile, ep_obj.location):
tbn_filename = ep_obj.location.rpartition('.')
if '' == tbn_filename[0]:
tbn_filename = ep_obj.location
else:
tbn_filename = tbn_filename[0]
return tbn_filename + '-thumb.jpg'
def get_season_poster_path(self, show_obj, season):
# type: (sickbeard.tv.TVShow, int) -> AnyStr
"""
Returns the full path to the file for a given season poster.
show_obj: a TVShow instance for which to generate the path
season: a season number to be used for the path. Note that season 0
means specials.
"""
# Our specials thumbnail is, well, special
if 0 == season:
season_poster_filename = 'season-specials'
else:
season_poster_filename = 'season' + str(season).zfill(2)
return ek.ek(os.path.join, show_obj.location, season_poster_filename + '-poster.jpg')
def get_season_banner_path(self, show_obj, season):
# type: (sickbeard.tv.TVShow, int) -> AnyStr
"""
Returns the full path to the file for a given season banner.
show_obj: a TVShow instance for which to generate the path
season: a season number to be used for the path. Note that season 0
means specials.
"""
# Our specials thumbnail is, well, special
if 0 == season:
season_banner_filename = 'season-specials'
else:
season_banner_filename = 'season' + str(season).zfill(2)
return ek.ek(os.path.join, show_obj.location, season_banner_filename + '-banner.jpg')
def get_season_all_poster_path(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
return ek.ek(os.path.join, show_obj.location, self.season_all_poster_name)
def get_season_all_banner_path(self, show_obj):
# type: (sickbeard.tv.TVShow) -> AnyStr
return ek.ek(os.path.join, show_obj.location, self.season_all_banner_name)
def _show_data(self, show_obj):
# type: (sickbeard.tv.TVShow) -> Optional[Union[bool, etree.Element]]
"""
This should be overridden by the implementing class. It should
provide the content of the show metadata file.
"""
return None
@staticmethod
def _valid_show(fetched_show_info, show_obj):
# type: (Dict, sickbeard.tv.TVShow) -> bool
"""
Test the integrity of fetched show data
:param fetched_show_info: the object returned from the tvinfo source
:param show_obj: Show that the fetched data relates to
:return: True if fetched_show_obj is valid data otherwise False
"""
if not (isinstance(fetched_show_info, dict) and
isinstance(getattr(fetched_show_info, 'data', None), (list, dict)) and
'seriesname' in getattr(fetched_show_info, 'data', [])) and \
not hasattr(fetched_show_info, 'seriesname'):
logger.log(u'Show %s not found on %s ' %
(show_obj.name, sickbeard.TVInfoAPI(show_obj.tvid).name), logger.WARNING)
return False
return True
def _ep_data(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> Optional[Union[bool, etree.Element]]
"""
This should be overridden by the implementing class. It should
provide the content of the episode metadata file.
"""
return None
def create_show_metadata(self, show_obj, force=False):
# type: (sickbeard.tv.TVShow, bool) -> bool
result = False
if self.show_metadata and show_obj and (not self._has_show_metadata(show_obj) or force):
logger.debug('Metadata provider %s creating show metadata for %s' % (self.name, show_obj.unique_name))
try:
result = self.write_show_file(show_obj)
except BaseTVinfoError as e:
logger.log('Unable to find useful show metadata for %s on %s: %s' % (
self.name, sickbeard.TVInfoAPI(show_obj.tvid).name, ex(e)), logger.WARNING)
return result
def create_episode_metadata(self, ep_obj, force=False):
# type: (sickbeard.tv.TVEpisode, bool) -> bool
result = False
if self.episode_metadata and ep_obj and (not self.has_episode_metadata(ep_obj) or force):
logger.log('Metadata provider %s creating episode metadata for %s' % (self.name, ep_obj.pretty_name()),
logger.DEBUG)
try:
result = self.write_ep_file(ep_obj)
except BaseTVinfoError as e:
logger.log('Unable to find useful episode metadata for %s on %s: %s' % (
self.name, sickbeard.TVInfoAPI(ep_obj.show_obj.tvid).name, ex(e)), logger.WARNING)
return result
def update_show_indexer_metadata(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.show_metadata and show_obj and self._has_show_metadata(show_obj):
logger.debug(u'Metadata provider %s updating show indexer metadata file for %s' % (
self.name, show_obj.unique_name))
nfo_file_path = self.get_show_file_path(show_obj)
with ek.ek(io.open, nfo_file_path, 'r', encoding='utf8') as xmlFileObj:
show_xml = etree.ElementTree(file=xmlFileObj)
tvid = show_xml.find('indexer')
prodid = show_xml.find('id')
root = show_xml.getroot()
show_tvid = str(show_obj.tvid)
if None is not tvid:
tvid.text = '%s' % show_tvid
else:
etree.SubElement(root, 'indexer').text = '%s' % show_tvid
show_prodid = str(show_obj.prodid)
if None is not prodid:
prodid.text = '%s' % show_prodid
else:
etree.SubElement(root, 'id').text = '%s' % show_prodid
# Make it purdy
sg_helpers.indent_xml(root)
sg_helpers.write_file(nfo_file_path, show_xml, xmltree=True, utf8=True)
return True
def create_fanart(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.fanart and show_obj and not self._has_fanart(show_obj):
logger.debug(u'Metadata provider %s creating fanart for %s' % (self.name, show_obj.unique_name))
return self.save_fanart(show_obj)
return False
def create_poster(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.poster and show_obj and not self._has_poster(show_obj):
logger.debug(u'Metadata provider %s creating poster for %s' % (self.name, show_obj.unique_name))
return self.save_poster(show_obj)
return False
def create_banner(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.banner and show_obj and not self._has_banner(show_obj):
logger.debug(u'Metadata provider %s creating banner for %s' % (self.name, show_obj.unique_name))
return self.save_banner(show_obj)
return False
def create_episode_thumb(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> bool
if self.episode_thumbnails and ep_obj and not self.has_episode_thumb(ep_obj):
logger.log(u"Metadata provider " + self.name + " creating episode thumbnail for " + ep_obj.pretty_name(),
logger.DEBUG)
return self.save_thumbnail(ep_obj)
return False
def create_season_posters(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.season_posters and show_obj:
result = []
for season, _ in iteritems(show_obj.sxe_ep_obj):
if not self._has_season_poster(show_obj, season):
logger.debug(u'Metadata provider %s creating season posters for %s' % (
self.name, show_obj.unique_name))
result = result + [self.save_season_posters(show_obj, season)]
return all(result)
return False
def create_season_banners(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.season_banners and show_obj:
result = []
for season, _ in iteritems(show_obj.sxe_ep_obj):
if not self._has_season_banner(show_obj, season):
logger.debug(u'Metadata provider %s creating season banners for %s' % (
self.name, show_obj.unique_name))
result = result + [self.save_season_banners(show_obj, season)]
return all(result)
return False
def create_season_all_poster(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.season_all_poster and show_obj and not self._has_season_all_poster(show_obj):
logger.debug(u'Metadata provider %s creating season all posters for %s' % (
self.name, show_obj.unique_name))
return self.save_season_all_poster(show_obj)
return False
def create_season_all_banner(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
if self.season_all_banner and show_obj and not self._has_season_all_banner(show_obj):
logger.debug(u'Metadata provider %s creating season all banner for %s' % (
self.name, show_obj.unique_name))
return self.save_season_all_banner(show_obj)
return False
@staticmethod
def _get_episode_thumb_url(ep_obj):
# type: (sickbeard.tv.TVEpisode) -> Optional[AnyStr]
"""
Returns the URL to use for downloading an episode's thumbnail. Uses
theTVDB.com and TVRage.com data.
:param ep_obj: a TVEpisode object for which to grab the thumb URL
:return: URL to thumb
"""
ep_obj_list = [ep_obj] + ep_obj.related_ep_obj
# validate show
from .. import helpers
if not helpers.validate_show(ep_obj.show_obj):
return None
# try all included episodes in case some have thumbs and others don't
for cur_ep_obj in ep_obj_list:
if TVINFO_TVDB == cur_ep_obj.show_obj.tvid:
show_lang = cur_ep_obj.show_obj.lang
try:
tvinfo_config = sickbeard.TVInfoAPI(TVINFO_TVDB).api_params.copy()
tvinfo_config['dvdorder'] = 0 != cur_ep_obj.show_obj.dvdorder
tvinfo_config['no_dummy'] = True
if show_lang and not 'en' == show_lang:
tvinfo_config['language'] = show_lang
t = sickbeard.TVInfoAPI(TVINFO_TVDB).setup(**tvinfo_config)
ep_info = t[cur_ep_obj.show_obj.prodid][cur_ep_obj.season][cur_ep_obj.episode]
except (BaseTVinfoEpisodenotfound, BaseTVinfoSeasonnotfound, TypeError):
ep_info = None
else:
ep_info = helpers.validate_show(cur_ep_obj.show_obj, cur_ep_obj.season, cur_ep_obj.episode)
if not ep_info:
continue
thumb_url = getattr(ep_info, 'filename', None) \
or (isinstance(ep_info, dict) and ep_info.get('filename', None))
if thumb_url not in (None, False, ''):
return thumb_url
return None
def write_show_file(self, show_obj):
# type: (sickbeard.tv.TVShow) -> bool
"""
Generates and writes show_obj's metadata under the given path to the
filename given by get_show_file_path()
show_obj: TVShow object for which to create the metadata
path: An absolute or relative path where we should put the file. Note that
the file name will be the default show_file_name.
Note that this method expects that _show_data will return an ElementTree
object. If your _show_data returns data in another format you'll need to
override this method.
"""
data = self._show_data(show_obj)
if not data:
return False
nfo_file_path = self.get_show_file_path(show_obj)
logger.log(u'Writing show metadata file: %s' % nfo_file_path, logger.DEBUG)
return sg_helpers.write_file(nfo_file_path, data, xmltree=True, utf8=True)
def write_ep_file(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> bool
"""
Generates and writes ep_obj's metadata under the given path with the
given filename root. Uses the episode's name with the extension in
_ep_nfo_extension.
ep_obj: TVEpisode object for which to create the metadata
file_name_path: The file name to use for this metadata. Note that the extension
will be automatically added based on _ep_nfo_extension. This should
include an absolute path.
Note that this method expects that _ep_data will return an ElementTree
object. If your _ep_data returns data in another format you'll need to
override this method.
"""
data = self._ep_data(ep_obj)
if not data:
return False
nfo_file_path = self.get_episode_file_path(ep_obj)
logger.log(u'Writing episode metadata file: %s' % nfo_file_path, logger.DEBUG)
return sg_helpers.write_file(nfo_file_path, data, xmltree=True, utf8=True)
def save_thumbnail(self, ep_obj):
# type: (sickbeard.tv.TVEpisode) -> bool
"""
Retrieves a thumbnail and saves it to the correct spot. This method should not need to
be overridden by implementing classes, changing get_episode_thumb_path and
_get_episode_thumb_url should suffice.
ep_obj: a TVEpisode object for which to generate a thumbnail
"""
file_path = self.get_episode_thumb_path(ep_obj)
if not file_path:
logger.log(u"Unable to find a file path to use for this thumbnail, not generating it", logger.DEBUG)
return False
thumb_url = self._get_episode_thumb_url(ep_obj)
# if we can't find one then give up
if not thumb_url:
logger.log(u"No thumb is available for this episode, not creating a thumb", logger.DEBUG)
return False
thumb_data = metadata_helpers.getShowImage(thumb_url, show_name=ep_obj.show_obj.name)
result = self._write_image(thumb_data, file_path)
if not result:
return False
for cur_ep_obj in [ep_obj] + ep_obj.related_ep_obj:
cur_ep_obj.hastbn = True
return True
def save_fanart(self, show_obj, which=None):
# type: (sickbeard.tv.TVShow, Optional[AnyStr]) -> bool
"""
Downloads a fanart image and saves it to the filename specified by fanart_name
inside the show's root folder.
show_obj: a TVShow object for which to download fanart
"""
# use the default fanart name
fanart_path = self.get_fanart_path(show_obj)
fanart_data = self._retrieve_show_image('fanart', show_obj, which,
img_cache_type=sickbeard.image_cache.ImageCache.FANART)
if not fanart_data:
logger.log(u"No fanart image was retrieved, unable to write fanart", logger.DEBUG)
return False
return self._write_image(fanart_data, fanart_path)
def save_poster(self, show_obj, which=None):
# type: (sickbeard.tv.TVShow, Optional[AnyStr]) -> bool
"""
Downloads a poster image and saves it to the filename specified by poster_name
inside the show's root folder.
show_obj: a TVShow object for which to download a poster
"""
# use the default poster name
poster_path = self.get_poster_path(show_obj)
poster_data = self._retrieve_show_image('poster', show_obj, which,
img_cache_type=sickbeard.image_cache.ImageCache.POSTER)
if not poster_data:
logger.log(u"No show poster image was retrieved, unable to write poster", logger.DEBUG)
return False
return self._write_image(poster_data, poster_path)
def save_banner(self, show_obj, which=None):
# type: (sickbeard.tv.TVShow, Optional[AnyStr]) -> bool
"""
Downloads a banner image and saves it to the filename specified by banner_name
inside the show's root folder.
show_obj: a TVShow object for which to download a banner
"""
# use the default banner name
banner_path = self.get_banner_path(show_obj)
banner_data = self._retrieve_show_image('banner', show_obj, which,
img_cache_type=sickbeard.image_cache.ImageCache.BANNER)
if not banner_data:
logger.log(u"No show banner image was retrieved, unable to write banner", logger.DEBUG)
return False
return self._write_image(banner_data, banner_path)
def save_season_posters(self, show_obj, season):
# type: (sickbeard.tv.TVShow, int) -> bool
"""
Saves all season posters to disk for the given show.
show_obj: a TVShow object for which to save the season thumbs
Cycles through all seasons and saves the season posters if possible.
"""
season_dict = self._season_image_dict(show_obj, season, 'seasons')
result = []
# Returns a nested dictionary of season art with the season
# number as primary key. It's really overkill but gives the option
# to present to user via ui to pick down the road.
for cur_season in season_dict:
cur_season_art = season_dict[cur_season]
if 0 == len(cur_season_art):
continue
# Just grab whatever's there for now
art_id, season_url = cur_season_art.popitem()
season_poster_file_path = self.get_season_poster_path(show_obj, cur_season)
if not season_poster_file_path:
logger.log(u'Path for season ' + str(cur_season) + ' came back blank, skipping this season',
logger.DEBUG)
continue
season_data = metadata_helpers.getShowImage(season_url, show_name=show_obj.name)
if not season_data:
logger.log(u'No season poster data available, skipping this season', logger.DEBUG)
continue
result = result + [self._write_image(season_data, season_poster_file_path)]
if result:
return all(result)
return False
def save_season_banners(self, show_obj, season):
# type: (sickbeard.tv.TVShow, int) -> bool
"""
Saves all season banners to disk for the given show.
show_obj: a TVShow object for which to save the season thumbs
Cycles through all seasons and saves the season banners if possible.
"""
season_dict = self._season_image_dict(show_obj, season, 'seasonwides')
result = []
# Returns a nested dictionary of season art with the season
# number as primary key. It's really overkill but gives the option
# to present to user via ui to pick down the road.
for cur_season in season_dict:
cur_season_art = season_dict[cur_season]
if 0 == len(cur_season_art):
continue
# Just grab whatever's there for now
art_id, season_url = cur_season_art.popitem()
season_banner_file_path = self.get_season_banner_path(show_obj, cur_season)
if not season_banner_file_path:
logger.log(u'Path for season ' + str(cur_season) + ' came back blank, skipping this season',
logger.DEBUG)
continue
season_data = metadata_helpers.getShowImage(season_url, show_name=show_obj.name)
if not season_data:
logger.log(u'No season banner data available, skipping this season', logger.DEBUG)
continue
result = result + [self._write_image(season_data, season_banner_file_path)]
if result:
return all(result)
return False
def save_season_all_poster(self, show_obj, which=None):
# type: (sickbeard.tv.TVShow, Optional[AnyStr]) -> bool
# use the default season all poster name
poster_path = self.get_season_all_poster_path(show_obj)
poster_data = self._retrieve_show_image('poster', show_obj, which,
img_cache_type=sickbeard.image_cache.ImageCache.POSTER)
if not poster_data:
logger.log(u"No show poster image was retrieved, unable to write season all poster", logger.DEBUG)
return False
return self._write_image(poster_data, poster_path)
def save_season_all_banner(self, show_obj, which=None):
# type: (sickbeard.tv.TVShow, Optional[AnyStr]) -> bool
# use the default season all banner name
banner_path = self.get_season_all_banner_path(show_obj)
banner_data = self._retrieve_show_image('banner', show_obj, which,
img_cache_type=sickbeard.image_cache.ImageCache.BANNER)
if not banner_data:
logger.log(u"No show banner image was retrieved, unable to write season all banner", logger.DEBUG)
return False
return self._write_image(banner_data, banner_path)
@staticmethod
def _write_image(image_data, image_path, force=False):
# type: (bytes, AnyStr, bool) -> bool
"""
Saves the data in image_data to the location image_path. Returns True/False
to represent success or failure.
image_data: binary image data to write to file
image_path: file location to save the image to
"""
# don't bother overwriting it
if not force and ek.ek(os.path.isfile, image_path):
logger.log(u"Image already exists, not downloading", logger.DEBUG)
return False
if not image_data:
logger.log(u"Unable to retrieve image, skipping", logger.WARNING)
return False
image_dir = ek.ek(os.path.dirname, image_path)
try:
if not ek.ek(os.path.isdir, image_dir):
logger.log(u"Metadata dir didn't exist, creating it at " + image_dir, logger.DEBUG)
ek.ek(os.makedirs, image_dir)
sg_helpers.chmod_as_parent(image_dir)
outFile = ek.ek(open, image_path, 'wb')
outFile.write(image_data)
outFile.close()
sg_helpers.chmod_as_parent(image_path)
except IOError as e:
logger.log(
u"Unable to write image to " + image_path + " - are you sure the show folder is writable? " + ex(e),
logger.ERROR)
return False
return True
@staticmethod
def gen_show_infos_dict(show_obj):
# type: (TVShow) -> ShowInfosDict
show_infos = ShowInfosDict()
def _get_show_info(tv_id):
try:
show_lang = show_obj.lang
# There's gotta be a better way of doing this but we don't wanna
# change the language value elsewhere
tvinfo_config = sickbeard.TVInfoAPI(tv_id).api_params.copy()
tvinfo_config['fanart'] = True
tvinfo_config['posters'] = True
tvinfo_config['banners'] = True
tvinfo_config['dvdorder'] = 0 != show_obj.dvdorder
if show_lang and not 'en' == show_lang:
tvinfo_config['language'] = show_lang
t = sickbeard.TVInfoAPI(tv_id).setup(**tvinfo_config)
return t.get_show((show_obj.ids[tv_id]['id'], show_obj.prodid)[tv_src == show_obj.tvid],
load_episodes=False, banners=False, posters=False, fanart=True)
except (BaseTVinfoError, IOError) as e:
logger.log(u"Unable to look up show on " + sickbeard.TVInfoAPI(
tv_id).name + ", not downloading images: " + ex(e), logger.WARNING)
# todo: when tmdb is added as tv source remove the hardcoded TVINFO_TMDB
for tv_src in list(OrderedDict.fromkeys([show_obj.tvid] + list_keys(sickbeard.TVInfoAPI().search_sources) +
[TVINFO_TMDB])):
if tv_src != show_obj.tvid and not show_obj.ids.get(tv_src, {}).get('id'):
continue
if tv_src == show_obj.tvid:
show_infos[tv_src] = _get_show_info(tv_src)
else:
show_infos[tv_src] = _get_show_info
return show_infos
def _retrieve_image_urls(self, show_obj, image_type, show_infos):
# type: (TVShow, AnyStr, TVInfoShow) -> Generator
image_urls, alt_tvdb_urls, fanart_fetched, de_dupe, show_lang = [], [], False, set(), show_obj.lang
def build_url(s_o, image_mode):
_urls = [[], []]
_url = s_o[image_mode]
if _url and _url.startswith('http'):
if 'poster' == image_mode:
_url = re.sub('posters', '_cache/posters', _url)
elif 'banner' == image_mode:
_url = re.sub('graphical', '_cache/graphical', _url)
_urls[0].append(_url)
try:
alt_url = '%swww.%s%s' % re.findall(
r'(https?://)(?:artworks\.)?(thetvdb\.[^/]+/banners/[^\d]+[^.]+)(?:_t)(.*)', _url)[0][0:3]
if alt_url not in _urls[0]:
_urls[1].append(alt_url)
except (IndexError, Exception):
try:
alt_url = '%sartworks.%s_t%s' % re.findall(
r'(https?://)(?:www\.)?(thetvdb\.[^/]+/banners/[^\d]+[^.]+)(.*)', _url)[0][0:3]
if alt_url not in _urls[0]:
_urls[1].append(alt_url)
except (IndexError, Exception):
pass
return _urls
def _get_fanart_tv():
return [_de_dupe((f_item[2], (f_item[2], f_item[2]))[image_type in ('poster', 'banner')])
for f_item in self._fanart_urls_from_show(show_obj, image_type, show_lang) or []]
def _de_dupe(images_list):
# type:(Union[List[AnyStr], AnyStr]) -> Optional[Union[List[AnyStr], AnyStr]]
if not isinstance(images_list, list):
return_list = False
temp_list = [images_list]
else:
return_list = True
temp_list = images_list
images_list = [i for i in temp_list if i not in de_dupe]
[de_dupe.add(_i) for _i in images_list]
if not return_list:
if images_list:
return images_list[0]
return None
return images_list
if image_type.startswith('fanart'):
for r in _get_fanart_tv():
yield r
for tv_src in show_infos:
if not self._valid_show(show_infos[tv_src], show_obj):
continue
if 'poster_thumb' == image_type:
if None is not getattr(show_infos[tv_src], image_type, None):
image_urls, alt_tvdb_urls = build_url(show_infos[tv_src], image_type)
elif None is not getattr(show_infos[tv_src], 'poster', None):
image_urls, alt_tvdb_urls = build_url(show_infos[tv_src], 'poster')
image_urls, alt_tvdb_urls = _de_dupe(image_urls), _de_dupe(alt_tvdb_urls)
for item in image_urls + alt_tvdb_urls:
yield item
elif 'banner_thumb' == image_type:
if None is not getattr(show_infos[tv_src], image_type, None):
image_urls, alt_tvdb_urls = build_url(show_infos[tv_src], image_type)
elif None is not getattr(show_infos[tv_src], 'banner', None):
image_urls, alt_tvdb_urls = build_url(show_infos[tv_src], 'banner')
image_urls, alt_tvdb_urls = _de_dupe(image_urls), _de_dupe(alt_tvdb_urls)
for item in image_urls + alt_tvdb_urls:
yield item
else:
if None is not getattr(show_infos[tv_src], image_type, None):
image_url = show_infos[tv_src][image_type]
if image_type in ('poster', 'banner'):
if None is not getattr(show_infos[tv_src], '%s_thumb' % image_type, None):
thumb_url = show_infos[tv_src]['%s_thumb' % image_type]
else:
thumb_url = image_url
else:
thumb_url = None
if image_url:
r = _de_dupe(((image_url, thumb_url), image_url)[None is thumb_url])
if r:
yield r
# check extra provided images in '_banners' key
if None is not getattr(show_infos[tv_src], '_banners', None) and \
isinstance(show_infos[tv_src]['_banners'].get(image_type, None), (list, dict)):
for res, value in iteritems(show_infos[tv_src]['_banners'][image_type]):
for item in itervalues(value):
thumb = item['thumbnailpath']
if not thumb:
thumb = item['bannerpath']
r = _de_dupe((item['bannerpath'], (item['bannerpath'], thumb))[
image_type in ('poster', 'banner')])
if r:
yield r
# extra images via images property
tvinfo_type = map_image_types.get(image_type)
tvinfo_size = (TVInfoImageSize.original, TVInfoImageSize.medium)['_thumb' in image_type]
if tvinfo_type and getattr(show_infos[tv_src], 'images', None) and \
show_infos[tv_src].images.get(tvinfo_type):
for img in show_infos[tv_src].images[tvinfo_type]: # type: TVInfoImage
for img_size, img_url in iteritems(img.sizes):
if tvinfo_size == img_size:
img_url = _de_dupe(img_url)
if not img_url:
continue
if image_type in ('poster', 'banner'):
thumb_url = img.sizes.get(TVInfoImageSize.medium, img_url)
if thumb_url:
thumb_url = _de_dupe(thumb_url)
if not thumb_url:
thumb_url = img_url
yield (img_url, thumb_url)
elif img_url:
yield img_url
if not image_type.startswith('fanart'):
for r in _get_fanart_tv():
yield r
def _retrieve_show_image(self,
image_type, # type: AnyStr
show_obj, # type: sickbeard.tv.TVShow
which=None, # type: int
return_links=False, # type: bool
show_infos=None, # type: ShowInfosDict
img_cache_type=None # type: int
):
# type: (...) -> Optional[bytes, List[AnyStr]]
"""
Gets an image URL from theTVDB.com, fanart.tv and TMDB.com, downloads it and returns the data.
If type is fanart, multiple image src urls are returned instead of a single data image.
image_type: type of image to retrieve (currently supported: fanart, poster, banner, poster_thumb, banner_thumb)
show_obj: a TVShow object to use when searching for the image
which: optional, a specific numbered poster to look for
Returns: the binary image data if available, or else None
"""
if not show_infos:
show_infos = self.gen_show_infos_dict(show_obj)
if 'fanart_all' == image_type:
return_links = True
image_type = 'fanart'
if image_type not in ('poster', 'banner', 'fanart', 'poster_thumb', 'banner_thumb'):
logger.log(u"Invalid image type " + str(image_type) + ", couldn't find it in the " + sickbeard.TVInfoAPI(
show_obj.tvid).name + " object", logger.ERROR)
return
image_urls = self._retrieve_image_urls(show_obj, image_type, show_infos)
if image_urls:
if return_links:
return image_urls
else:
img_data = None
image_cache = sickbeard.image_cache.ImageCache()
for image_url in image_urls or []:
if image_type in ('poster', 'banner'):
if isinstance(image_url, tuple):
image_url = image_url[0]
img_data = metadata_helpers.getShowImage(image_url, which, show_obj.name)
if img_cache_type and img_cache_type != image_cache.which_type(img_data, is_binary=True):
img_data = None
continue
if None is not img_data:
break
if None is not img_data:
return img_data
def _season_image_dict(self, show_obj, season, image_type):
# type: (sickbeard.tv.TVShow, int, AnyStr) -> Dict[int, Dict[int, AnyStr]]
"""
image_type : Type of image to fetch, 'seasons' or 'seasonwides'
image_type type : String
Should return a dict like:
result = {<season number>:
{1: '<url 1>', 2: <url 2>, ...},}
"""
result = {}
try:
# There's gotta be a better way of doing this but we don't wanna
# change the language value elsewhere
tvinfo_config = sickbeard.TVInfoAPI(show_obj.tvid).api_params.copy()
tvinfo_config[image_type] = True
tvinfo_config['dvdorder'] = 0 != show_obj.dvdorder
if 'en' != getattr(show_obj, 'lang', None):
tvinfo_config['language'] = show_obj.lang
t = sickbeard.TVInfoAPI(show_obj.tvid).setup(**tvinfo_config)
tvinfo_obj_show = t[show_obj.prodid]
except (BaseTVinfoError, IOError) as e:
logger.log(u'Unable to look up show on ' + sickbeard.TVInfoAPI(
show_obj.tvid).name + ', not downloading images: ' + ex(e), logger.WARNING)
return result
if not self._valid_show(tvinfo_obj_show, show_obj):
return result
season_images = getattr(tvinfo_obj_show, 'banners', {}).get(
('season', 'seasonwide')['seasonwides' == image_type], {}).get(season, {})
for image_id in season_images:
if season not in result:
result[season] = {}
result[season][image_id] = season_images[image_id]['bannerpath']
return result
def retrieveShowMetadata(self, folder):
# type: (AnyStr) -> Union[Tuple[int, int, AnyStr], Tuple[None, None, None]]
"""
Used only when mass adding Existing Shows,
using previously generated Show metadata to reduce the need to query TVDB.
"""
from sickbeard.indexers.indexer_config import TVINFO_TVDB
empty_return = (None, None, None)
metadata_path = ek.ek(os.path.join, folder, self._show_metadata_filename)
if not ek.ek(os.path.isdir, folder) or not ek.ek(os.path.isfile, metadata_path):
logger.log(u"Can't load the metadata file from " + repr(metadata_path) + ", it doesn't exist", logger.DEBUG)
return empty_return
logger.log(u"Loading show info from metadata file in " + folder, logger.DEBUG)
try:
with ek.ek(io.open, metadata_path, 'r', encoding='utf8') as xmlFileObj:
showXML = etree.ElementTree(file=xmlFileObj)
if None is showXML.findtext('title') \
or all(None is _f for _f in (showXML.find('//uniqueid[@type]'),
showXML.findtext('tvdbid'),
showXML.findtext('id'),
showXML.findtext('indexer'))):
logger.log(u"Invalid info in tvshow.nfo (missing name or id):"
+ str(showXML.findtext('title')) + ' '
+ str(showXML.findtext('indexer')) + ' '
+ str(showXML.findtext('tvdbid')) + ' '
+ str(showXML.findtext('id')))
return empty_return
name = showXML.findtext('title')
try:
tvid = int(showXML.findtext('indexer'))
except (BaseException, Exception):
tvid = None
# handle v2 format of .nfo file
default_source = showXML.find('//uniqueid[@default="true"]')
if None is not default_source:
use_tvid = default_source.attrib.get('type') or tvid
if isinstance(use_tvid, string_types):
use_tvid = {sickbeard.TVInfoAPI(x).config['slug']: x
for x, _ in iteritems(sickbeard.TVInfoAPI().all_sources)}.get(use_tvid)
prodid = sg_helpers.try_int(default_source.text, None)
if use_tvid and None is not prodid:
return use_tvid, prodid, name
prodid = showXML.find('//uniqueid[@type="tvdb"]')
if None is not prodid:
prodid = int(prodid.text)
tvid = TVINFO_TVDB
elif None is not showXML.findtext('tvdbid'):
prodid = int(showXML.findtext('tvdbid'))
tvid = TVINFO_TVDB
elif None is not showXML.findtext('id'):
prodid = int(showXML.findtext('id'))
try:
tvid = TVINFO_TVDB if [s for s in showXML.findall('.//*')
if s.text and -1 != s.text.find('thetvdb.com')] else tvid
except (BaseException, Exception):
pass
else:
logger.log(u"Empty <id> or <tvdbid> field in NFO, unable to find a ID", logger.WARNING)
return empty_return
if None is prodid:
logger.log(u"Invalid Show ID (%s), not using metadata file" % prodid, logger.WARNING)
return empty_return
except (BaseException, Exception) as e:
logger.log(
u"There was an error parsing your existing metadata file: '" + metadata_path + "' error: " + ex(e),
logger.WARNING)
return empty_return
return tvid, prodid, name
def _fanart_urls_from_show(self, show_obj, image_type='banner', lang='en', thumb=False):
# type: (sickbeard.tv.TVShow, AnyStr, AnyStr, bool) -> Optional[List[int, int, AnyStr]]
try:
tvdb_id = show_obj.ids.get(indexer_config.TVINFO_TVDB, {}).get('id', None)
if tvdb_id:
return self._fanart_urls(tvdb_id, image_type, lang, thumb)
except (BaseException, Exception):
pass
logger.log(u'Could not find any %s images on Fanart.tv for %s' % (image_type, show_obj.name), logger.DEBUG)
@staticmethod
def _fanart_urls(tvdb_id, image_type='banner', lang='en', thumb=False):
# type: (int, AnyStr, AnyStr, bool) -> Optional[List[int, int, AnyStr]]
types = {'poster': fanart.TYPE.TV.POSTER,
'banner': fanart.TYPE.TV.BANNER,
'fanart': fanart.TYPE.TV.BACKGROUND,
'poster_thumb': fanart.TYPE.TV.POSTER,
'banner_thumb': fanart.TYPE.TV.BANNER}
try:
if tvdb_id:
request = fanartRequest(apikey=sickbeard.FANART_API_KEY, tvdb_id=tvdb_id, types=types[image_type])
resp = request.response()
itemlist = []
dedupe = []
for art in filter_iter(lambda i: 10 < len(i.get('url', '')) and (lang == i.get('lang', '')[0:2]),
# remove "[0:2]" ... to strictly use only data where "en" is at source
resp[types[image_type]]): # type: dict
try:
url = (art['url'], art['url'].replace('/fanart/', '/preview/'))[thumb]
if url not in dedupe:
dedupe += [url]
itemlist += [
[int(art['id']), int(art['likes']), url]
]
except (BaseException, Exception):
continue
itemlist.sort(key=lambda a: (a[1], a[0]), reverse=True)
return itemlist
except (BaseException, Exception):
raise
def retrieve_show_image(self, image_type, show_obj, which=None, return_links=False, show_infos=None):
# type: (AnyStr, sickbeard.tv.TVShow, bool, bool, ShowInfosDict) -> Optional[bytes]
return self._retrieve_show_image(image_type=image_type, show_obj=show_obj, which=which,
return_links=return_links, show_infos=show_infos)
def write_image(self, image_data, image_path, force=False):
# type: (bytes, AnyStr, bool) -> bool
return self._write_image(image_data=image_data, image_path=image_path, force=force)
|
SickGear/SickGear
|
sickbeard/metadata/generic.py
|
Python
|
gpl-3.0
| 53,307
|
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""External Python Shell widget: execute Python script in a separate process"""
import sys
import os
import os.path as osp
import socket
from spyderlib.qt.QtGui import QApplication, QMessageBox, QSplitter, QMenu
from spyderlib.qt.QtCore import QProcess, SIGNAL, Qt
from spyderlib.qt.compat import getexistingdirectory
# Local imports
from spyderlib.utils.qthelpers import (get_icon, get_std_icon, add_actions,
create_toolbutton, create_action,
DialogManager)
from spyderlib.utils.environ import RemoteEnvDialog
from spyderlib.utils.programs import get_python_args
from spyderlib.utils.misc import get_python_executable
from spyderlib.baseconfig import (_, get_module_source_path, DEBUG,
MAC_APP_NAME, running_in_mac_app)
from spyderlib.widgets.shell import PythonShellWidget
from spyderlib.widgets.externalshell.namespacebrowser import NamespaceBrowser
from spyderlib.utils.bsdsocket import communicate, write_packet
from spyderlib.widgets.externalshell.baseshell import (ExternalShellBase,
add_pathlist_to_PYTHONPATH)
from spyderlib.widgets.dicteditor import DictEditor
from spyderlib.py3compat import (is_text_string, to_text_string,
to_binary_string)
class ExtPythonShellWidget(PythonShellWidget):
def __init__(self, parent, history_filename, profile=False):
PythonShellWidget.__init__(self, parent, history_filename, profile)
self.path = []
def set_externalshell(self, externalshell):
# ExternalShellBase instance:
self.externalshell = externalshell
def clear_terminal(self):
"""Reimplement ShellBaseWidget method"""
self.clear()
self.emit(SIGNAL("execute(QString)"), "\n")
def execute_lines(self, lines):
"""
Execute a set of lines as multiple command
lines: multiple lines of text to be executed as single commands
"""
for line in lines.splitlines():
stripped_line = line.strip()
if stripped_line.startswith('#'):
continue
self.write(line+os.linesep, flush=True)
self.execute_command(line)
# Workaround for Issue 502
# Emmiting wait_for_ready_read was making the console hang
# in Mac OS X
if sys.platform.startswith("darwin"):
import time
time.sleep(0.025)
else:
self.emit(SIGNAL("wait_for_ready_read()"))
self.flush()
#------ Code completion / Calltips
def ask_monitor(self, command, settings=[]):
sock = self.externalshell.introspection_socket
if sock is None:
return
try:
return communicate(sock, command, settings=settings)
except socket.error:
# Process was just closed
pass
except MemoryError:
# Happens when monitor is not ready on slow machines
pass
def get_dir(self, objtxt):
"""Return dir(object)"""
return self.ask_monitor("__get_dir__('%s')" % objtxt)
def get_globals_keys(self):
"""Return shell globals() keys"""
return self.ask_monitor("get_globals_keys()")
def get_cdlistdir(self):
"""Return shell current directory list dir"""
return self.ask_monitor("getcdlistdir()")
def iscallable(self, objtxt):
"""Is object callable?"""
return self.ask_monitor("__iscallable__('%s')" % objtxt)
def get_arglist(self, objtxt):
"""Get func/method argument list"""
return self.ask_monitor("__get_arglist__('%s')" % objtxt)
def get__doc__(self, objtxt):
"""Get object __doc__"""
return self.ask_monitor("__get__doc____('%s')" % objtxt)
def get_doc(self, objtxt):
"""Get object documentation dictionary"""
return self.ask_monitor("__get_doc__('%s')" % objtxt)
def get_source(self, objtxt):
"""Get object source"""
return self.ask_monitor("__get_source__('%s')" % objtxt)
def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.ask_monitor("isdefined('%s', force_import=%s)"
% (objtxt, force_import))
def get_module_completion(self, objtxt):
"""Return module completion list associated to object name"""
return self.ask_monitor("getmodcomplist('%s', %s)" % \
(objtxt, self.path))
def get_cwd(self):
"""Return shell current working directory"""
return self.ask_monitor("getcwd()")
def set_cwd(self, dirname):
"""Set shell current working directory"""
return self.ask_monitor("setcwd(r'%s')" % dirname)
def get_env(self):
"""Return environment variables: os.environ"""
return self.ask_monitor("getenv()")
def set_env(self, env):
"""Set environment variables via os.environ"""
return self.ask_monitor('setenv()', settings=[env])
def get_syspath(self):
"""Return sys.path[:]"""
return self.ask_monitor("getsyspath()")
def set_spyder_breakpoints(self):
"""Set Spyder breakpoints into debugging session"""
return self.ask_monitor("set_spyder_breakpoints()")
class ExternalPythonShell(ExternalShellBase):
"""External Shell widget: execute Python script in a separate process"""
SHELL_CLASS = ExtPythonShellWidget
def __init__(self, parent=None, fname=None, wdir=None,
interact=False, debug=False, path=[], python_args='',
ipykernel=False, arguments='', stand_alone=None,
umr_enabled=True, umr_namelist=[], umr_verbose=True,
pythonstartup=None, pythonexecutable=None,
monitor_enabled=True, mpl_backend=None, ets_backend='qt4',
qt_api=None, pyqt_api=0,
ignore_sip_setapi_errors=False, merge_output_channels=False,
colorize_sys_stderr=False, autorefresh_timeout=3000,
autorefresh_state=True, light_background=True,
menu_actions=None, show_buttons_inside=True,
show_elapsed_time=True):
assert qt_api in (None, 'pyqt', 'pyside')
self.namespacebrowser = None # namespace browser widget!
self.dialog_manager = DialogManager()
self.stand_alone = stand_alone # stand alone settings (None: plugin)
self.interact = interact
self.is_ipykernel = ipykernel
self.pythonstartup = pythonstartup
self.pythonexecutable = pythonexecutable
self.monitor_enabled = monitor_enabled
self.mpl_backend = mpl_backend
self.ets_backend = ets_backend
self.qt_api = qt_api
self.pyqt_api = pyqt_api
self.ignore_sip_setapi_errors = ignore_sip_setapi_errors
self.merge_output_channels = merge_output_channels
self.colorize_sys_stderr = colorize_sys_stderr
self.umr_enabled = umr_enabled
self.umr_namelist = umr_namelist
self.umr_verbose = umr_verbose
self.autorefresh_timeout = autorefresh_timeout
self.autorefresh_state = autorefresh_state
self.namespacebrowser_button = None
self.cwd_button = None
self.env_button = None
self.syspath_button = None
self.terminate_button = None
self.notification_thread = None
ExternalShellBase.__init__(self, parent=parent, fname=fname, wdir=wdir,
history_filename='history.py',
light_background=light_background,
menu_actions=menu_actions,
show_buttons_inside=show_buttons_inside,
show_elapsed_time=show_elapsed_time)
if self.pythonexecutable is None:
self.pythonexecutable = get_python_executable()
self.python_args = None
if python_args:
assert is_text_string(python_args)
self.python_args = python_args
assert is_text_string(arguments)
self.arguments = arguments
self.connection_file = None
if self.is_ipykernel:
self.interact = False
# Running our custom startup script for IPython kernels:
# (see spyderlib/widgets/externalshell/start_ipython_kernel.py)
self.fname = get_module_source_path(
'spyderlib.widgets.externalshell', 'start_ipython_kernel.py')
self.shell.set_externalshell(self)
self.toggle_globals_explorer(False)
self.interact_action.setChecked(self.interact)
self.debug_action.setChecked(debug)
self.introspection_socket = None
self.is_interpreter = fname is None
if self.is_interpreter:
self.terminate_button.hide()
# Additional python path list
self.path = path
self.shell.path = path
def set_introspection_socket(self, introspection_socket):
self.introspection_socket = introspection_socket
if self.namespacebrowser is not None:
settings = self.namespacebrowser.get_view_settings()
communicate(introspection_socket,
'set_remote_view_settings()', settings=[settings])
def set_autorefresh_timeout(self, interval):
if self.introspection_socket is not None:
try:
communicate(self.introspection_socket,
"set_monitor_timeout(%d)" % interval)
except socket.error:
pass
def closeEvent(self, event):
self.quit_monitor()
ExternalShellBase.closeEvent(self, event)
def get_toolbar_buttons(self):
ExternalShellBase.get_toolbar_buttons(self)
if self.namespacebrowser_button is None \
and self.stand_alone is not None:
self.namespacebrowser_button = create_toolbutton(self,
text=_("Variables"), icon=get_icon('dictedit.png'),
tip=_("Show/hide global variables explorer"),
toggled=self.toggle_globals_explorer, text_beside_icon=True)
if self.terminate_button is None:
self.terminate_button = create_toolbutton(self,
text=_("Terminate"), icon=get_icon('stop.png'),
tip=_("Attempts to stop the process. The process\n"
"may not exit as a result of clicking this\n"
"button (it is given the chance to prompt\n"
"the user for any unsaved files, etc)."))
buttons = []
if self.namespacebrowser_button is not None:
buttons.append(self.namespacebrowser_button)
buttons += [self.run_button, self.terminate_button, self.kill_button,
self.options_button]
return buttons
def get_options_menu(self):
ExternalShellBase.get_options_menu(self)
self.interact_action = create_action(self, _("Interact"))
self.interact_action.setCheckable(True)
self.debug_action = create_action(self, _("Debug"))
self.debug_action.setCheckable(True)
self.args_action = create_action(self, _("Arguments..."),
triggered=self.get_arguments)
run_settings_menu = QMenu(_("Run settings"), self)
add_actions(run_settings_menu,
(self.interact_action, self.debug_action, self.args_action))
self.cwd_button = create_action(self, _("Working directory"),
icon=get_std_icon('DirOpenIcon'),
tip=_("Set current working directory"),
triggered=self.set_current_working_directory)
self.env_button = create_action(self, _("Environment variables"),
icon=get_icon('environ.png'),
triggered=self.show_env)
self.syspath_button = create_action(self,
_("Show sys.path contents"),
icon=get_icon('syspath.png'),
triggered=self.show_syspath)
actions = [run_settings_menu, self.show_time_action, None,
self.cwd_button, self.env_button, self.syspath_button]
if self.menu_actions is not None:
actions += [None]+self.menu_actions
return actions
def is_interpreter(self):
"""Return True if shellwidget is a Python interpreter"""
return self.is_interpreter
def get_shell_widget(self):
if self.stand_alone is None:
return self.shell
else:
self.namespacebrowser = NamespaceBrowser(self)
settings = self.stand_alone
self.namespacebrowser.set_shellwidget(self)
self.namespacebrowser.setup(**settings)
self.connect(self.namespacebrowser, SIGNAL('collapse()'),
lambda: self.toggle_globals_explorer(False))
# Shell splitter
self.splitter = splitter = QSplitter(Qt.Vertical, self)
self.connect(self.splitter, SIGNAL('splitterMoved(int, int)'),
self.splitter_moved)
splitter.addWidget(self.shell)
splitter.setCollapsible(0, False)
splitter.addWidget(self.namespacebrowser)
splitter.setStretchFactor(0, 1)
splitter.setStretchFactor(1, 0)
splitter.setHandleWidth(5)
splitter.setSizes([2, 1])
return splitter
def get_icon(self):
return get_icon('python.png')
def set_buttons_runnning_state(self, state):
ExternalShellBase.set_buttons_runnning_state(self, state)
self.interact_action.setEnabled(not state and not self.is_interpreter)
self.debug_action.setEnabled(not state and not self.is_interpreter)
self.args_action.setEnabled(not state and not self.is_interpreter)
if state:
if self.arguments:
argstr = _("Arguments: %s") % self.arguments
else:
argstr = _("No argument")
else:
argstr = _("Arguments...")
self.args_action.setText(argstr)
self.terminate_button.setVisible(not self.is_interpreter and state)
if not state:
self.toggle_globals_explorer(False)
for btn in (self.cwd_button, self.env_button, self.syspath_button):
btn.setEnabled(state and self.monitor_enabled)
if self.namespacebrowser_button is not None:
self.namespacebrowser_button.setEnabled(state)
def set_namespacebrowser(self, namespacebrowser):
"""
Set namespace browser *widget*
Note: this method is not used in stand alone mode
"""
self.namespacebrowser = namespacebrowser
self.configure_namespacebrowser()
def configure_namespacebrowser(self):
"""Connect the namespace browser to the notification thread"""
if self.notification_thread is not None:
self.connect(self.notification_thread,
SIGNAL('refresh_namespace_browser()'),
self.namespacebrowser.refresh_table)
signal = self.notification_thread.sig_process_remote_view
signal.connect(lambda data:
self.namespacebrowser.process_remote_view(data))
def create_process(self):
self.shell.clear()
self.process = QProcess(self)
if self.merge_output_channels:
self.process.setProcessChannelMode(QProcess.MergedChannels)
else:
self.process.setProcessChannelMode(QProcess.SeparateChannels)
self.connect(self.shell, SIGNAL("wait_for_ready_read()"),
lambda: self.process.waitForReadyRead(250))
# Working directory
if self.wdir is not None:
self.process.setWorkingDirectory(self.wdir)
#-------------------------Python specific-------------------------------
# Python arguments
p_args = ['-u']
if DEBUG >= 3:
p_args += ['-v']
p_args += get_python_args(self.fname, self.python_args,
self.interact_action.isChecked(),
self.debug_action.isChecked(),
self.arguments)
env = [to_text_string(_path)
for _path in self.process.systemEnvironment()]
if self.pythonstartup:
env.append('PYTHONSTARTUP=%s' % self.pythonstartup)
# Set standard input/output encoding for Python consoles
# (IPython handles it on its own)
# See http://stackoverflow.com/q/26312400/438386, specifically
# the comments of Martijn Pieters
if not self.is_ipykernel:
env.append('PYTHONIOENCODING=UTF-8')
# Monitor
if self.monitor_enabled:
env.append('SPYDER_SHELL_ID=%s' % id(self))
env.append('SPYDER_AR_TIMEOUT=%d' % self.autorefresh_timeout)
env.append('SPYDER_AR_STATE=%r' % self.autorefresh_state)
from spyderlib.widgets.externalshell import introspection
introspection_server = introspection.start_introspection_server()
introspection_server.register(self)
notification_server = introspection.start_notification_server()
self.notification_thread = notification_server.register(self)
self.connect(self.notification_thread, SIGNAL('pdb(QString,int)'),
lambda fname, lineno:
self.emit(SIGNAL('pdb(QString,int)'), fname, lineno))
self.connect(self.notification_thread,
SIGNAL('new_ipython_kernel(QString)'),
lambda args:
self.emit(SIGNAL('create_ipython_client(QString)'),
args))
self.connect(self.notification_thread,
SIGNAL('open_file(QString,int)'),
lambda fname, lineno:
self.emit(SIGNAL('open_file(QString,int)'),
fname, lineno))
if self.namespacebrowser is not None:
self.configure_namespacebrowser()
env.append('SPYDER_I_PORT=%d' % introspection_server.port)
env.append('SPYDER_N_PORT=%d' % notification_server.port)
# External modules options
env.append('ETS_TOOLKIT=%s' % self.ets_backend)
if self.mpl_backend:
env.append('MATPLOTLIB_BACKEND=%s' % self.mpl_backend)
if self.qt_api:
env.append('QT_API=%s' % self.qt_api)
env.append('COLORIZE_SYS_STDERR=%s' % self.colorize_sys_stderr)
# # Socket-based alternative (see input hook in sitecustomize.py):
# if self.install_qt_inputhook:
# from PyQt4.QtNetwork import QLocalServer
# self.local_server = QLocalServer()
# self.local_server.listen(str(id(self)))
if self.pyqt_api:
env.append('PYQT_API=%d' % self.pyqt_api)
env.append('IGNORE_SIP_SETAPI_ERRORS=%s'
% self.ignore_sip_setapi_errors)
# User Module Deleter
if self.is_interpreter:
env.append('UMR_ENABLED=%r' % self.umr_enabled)
env.append('UMR_NAMELIST=%s' % ','.join(self.umr_namelist))
env.append('UMR_VERBOSE=%r' % self.umr_verbose)
env.append('MATPLOTLIB_ION=True')
else:
if self.interact:
env.append('MATPLOTLIB_ION=True')
else:
env.append('MATPLOTLIB_ION=False')
# IPython kernel
env.append('IPYTHON_KERNEL=%r' % self.is_ipykernel)
# Add sitecustomize path to path list
pathlist = []
scpath = osp.dirname(osp.abspath(__file__))
pathlist.append(scpath)
# Adding Spyder path
pathlist += self.path
# Adding path list to PYTHONPATH environment variable
add_pathlist_to_PYTHONPATH(env, pathlist)
#-------------------------Python specific-------------------------------
self.connect(self.process, SIGNAL("readyReadStandardOutput()"),
self.write_output)
self.connect(self.process, SIGNAL("readyReadStandardError()"),
self.write_error)
self.connect(self.process, SIGNAL("finished(int,QProcess::ExitStatus)"),
self.finished)
self.connect(self, SIGNAL('finished()'), self.dialog_manager.close_all)
self.connect(self.terminate_button, SIGNAL("clicked()"),
self.process.terminate)
self.connect(self.kill_button, SIGNAL("clicked()"),
self.process.kill)
#-------------------------Python specific-------------------------------
# Fixes for our Mac app:
# 1. PYTHONPATH and PYTHONHOME are set while bootstrapping the app,
# but their values are messing sys.path for external interpreters
# (e.g. EPD) so we need to remove them from the environment.
# 2. Set PYTHONPATH again but without grabbing entries defined in the
# environment (Fixes Issue 1321)
# 3. Remove PYTHONOPTIMIZE from env so that we can have assert
# statements working with our interpreters (See Issue 1281)
if running_in_mac_app():
env.append('SPYDER_INTERPRETER=%s' % self.pythonexecutable)
if MAC_APP_NAME not in self.pythonexecutable:
env = [p for p in env if not (p.startswith('PYTHONPATH') or \
p.startswith('PYTHONHOME'))] # 1.
add_pathlist_to_PYTHONPATH(env, pathlist, drop_env=True) # 2.
env = [p for p in env if not p.startswith('PYTHONOPTIMIZE')] # 3.
self.process.setEnvironment(env)
self.process.start(self.pythonexecutable, p_args)
#-------------------------Python specific-------------------------------
running = self.process.waitForStarted(3000)
self.set_running_state(running)
if not running:
if self.is_ipykernel:
self.emit(SIGNAL("ipython_kernel_start_error(QString)"),
_("The kernel failed to start!! That's all we know... "
"Please close this console and open a new one."))
else:
QMessageBox.critical(self, _("Error"),
_("A Python console failed to start!"))
else:
self.shell.setFocus()
self.emit(SIGNAL('started()'))
return self.process
def finished(self, exit_code, exit_status):
"""Reimplement ExternalShellBase method"""
if self.is_ipykernel and exit_code == 1:
self.emit(SIGNAL("ipython_kernel_start_error(QString)"),
self.shell.get_text_with_eol())
ExternalShellBase.finished(self, exit_code, exit_status)
self.introspection_socket = None
#===============================================================================
# Input/Output
#===============================================================================
def write_error(self):
if os.name == 'nt':
#---This is apparently necessary only on Windows (not sure though):
# emptying standard output buffer before writing error output
self.process.setReadChannel(QProcess.StandardOutput)
if self.process.waitForReadyRead(1):
self.write_output()
self.shell.write_error(self.get_stderr())
QApplication.processEvents()
def send_to_process(self, text):
if not self.is_running():
return
if not is_text_string(text):
text = to_text_string(text)
if self.mpl_backend == 'Qt4Agg' and os.name == 'nt' and \
self.introspection_socket is not None:
communicate(self.introspection_socket,
"toggle_inputhook_flag(True)")
# # Socket-based alternative (see input hook in sitecustomize.py):
# while self.local_server.hasPendingConnections():
# self.local_server.nextPendingConnection().write('go!')
if any([text == cmd for cmd in ['%ls', '%pwd', '%scientific']]) or \
any([text.startswith(cmd) for cmd in ['%cd ', '%clear ']]):
text = 'evalsc(r"%s")\n' % text
if not text.endswith('\n'):
text += '\n'
self.process.write(to_binary_string(text, 'utf8'))
self.process.waitForBytesWritten(-1)
# Eventually write prompt faster (when hitting Enter continuously)
# -- necessary/working on Windows only:
if os.name == 'nt':
self.write_error()
def keyboard_interrupt(self):
if self.introspection_socket is not None:
communicate(self.introspection_socket, "thread.interrupt_main()")
def quit_monitor(self):
if self.introspection_socket is not None:
try:
write_packet(self.introspection_socket, "thread.exit()")
except socket.error:
pass
#===============================================================================
# Globals explorer
#===============================================================================
def toggle_globals_explorer(self, state):
if self.stand_alone is not None:
self.splitter.setSizes([1, 1 if state else 0])
self.namespacebrowser_button.setChecked(state)
if state and self.namespacebrowser is not None:
self.namespacebrowser.refresh_table()
def splitter_moved(self, pos, index):
self.namespacebrowser_button.setChecked( self.splitter.sizes()[1] )
#===============================================================================
# Misc.
#===============================================================================
def set_current_working_directory(self):
"""Set current working directory"""
cwd = self.shell.get_cwd()
self.emit(SIGNAL('redirect_stdio(bool)'), False)
directory = getexistingdirectory(self, _("Select directory"), cwd)
if directory:
self.shell.set_cwd(directory)
self.emit(SIGNAL('redirect_stdio(bool)'), True)
def show_env(self):
"""Show environment variables"""
get_func = self.shell.get_env
set_func = self.shell.set_env
self.dialog_manager.show(RemoteEnvDialog(get_func, set_func))
def show_syspath(self):
"""Show sys.path contents"""
editor = DictEditor()
editor.setup(self.shell.get_syspath(), title="sys.path", readonly=True,
width=600, icon='syspath.png')
self.dialog_manager.show(editor)
|
kenshay/ImageScript
|
ProgramData/SystemFiles/Python/Lib/site-packages/spyderlib/widgets/externalshell/pythonshell.py
|
Python
|
gpl-3.0
| 27,927
|
#ifndef EDGE_H
#define EDGE_H
//============================================================================
// Name : EdgeSimple.h
// Author : Tae-Hyuk (Ted) Ahn, JJ Crosskey, Abhishek Biswas
// Version : v1.2
// Copyright : 2015 Oak Ridge National Lab (ORNL). All rights reserved.
// Description : EdgeSimple header file
//============================================================================
#include "Config.h"
#include "Utils.h"
extern TLogLevel loglevel; /* verbosity level of logging */
typedef vector<pair<UINT32, UINT32> > t_vpair;
class EdgeSimple{
private:
/* ==================== DATA MEMBERS ======================================= */
UINT64 m_source;
UINT64 m_sourceLen;
UINT64 m_destination;
UINT64 m_destinationLen;
EdgeSimple *m_reverseEdge;
// Packed list of ordered reads in the current edge. NOT including u and v.
// First 32LSB ReadID
// First MSB orientation
/* Orientations of the ordered reads in the current edge.
* orientation is 0 or 1.
* 0 means read's reverse complement read.getStringReverse().
* 1 means read's forward string.
*/
/* Middle 31MSB overlap offsets of the ordered reads in the current edge.
* The offset of the destination read is calculated as
* m_overlapOffset - sum(getOverlapOffset(i)) or it can retrieved from the reverse edge
*/
UINT64 *m_listOfReads;
UINT32 m_listSize; // Size of m_listOfReads
/* overlap offset in the following example is 6
* 012345678901234567890123456789
* u ACTTACGGGATTATACCATCGAGA
* v GGGATTATACCATCGAGATTCAAT
*/
UINT32 m_overlapOffset;
/* 0 = u<-----------<v reverse of u to reverse of v
* 1 = u<----------->v reverse of u to forward of v
* 2 = u>-----------<v forward of u to reverse of v
* 3 = u>----------->v forward of u to forward of v
*/
UINT8 m_orient;
/* flag of edge that has these bits:
* 0x1: not dead end
* 0x2: loop
*/
INT8 m_flag;
/* flag of edge that has these bits:
* 0x0: valid edge
* 0x1: invalidated edge; to be deleted
*/
bool m_invalid;
/* ==================== METHODS ======================================= */
friend EdgeSimple* merge_forward_edges(const EdgeSimple & edge1, const EdgeSimple & edge2);
void copyEdge(const EdgeSimple &edge);
void clearEdge();
public:
/* ==================== LIFECYCLE ======================================= */
// Default constructor.
EdgeSimple(void);
// constructor for a non-empty edge
EdgeSimple(UINT64 source, UINT64 sourceLen, UINT64 destination, UINT64 destLen, UINT8 orient, UINT32 overlapOffset);
EdgeSimple(UINT64 source, UINT64 sourceLen, UINT64 destination, UINT64 destLen, UINT8 orient, UINT32 overlapOffset,
UINT64 *listOfReads, UINT32 listSize);
EdgeSimple(const EdgeSimple &edge);
// Destructor.
~EdgeSimple();
/* ==================== OPERATORS ======================================= */
EdgeSimple& operator=(const EdgeSimple &edge);
friend bool operator== (const EdgeSimple &subject, const EdgeSimple &query);
friend EdgeSimple* Add( const EdgeSimple *edge1, const EdgeSimple *edge2);
/* ==================== MUTATORS ======================================= */
// Set the pointer to the reverse edge, only if reverse edge is nullptr
void setReverseEdge(EdgeSimple * edge);
void markNotDeadEnd() {m_flag |= 1; m_reverseEdge->m_flag |= 1;}
void markLoop() {m_flag |= (1 << 1);}
void loadReadString(const std::string read_str, int index);
void make_nonComposite_reverseEdge();
void setInvalid() {m_invalid=true;}
/* ==================== ACCESSORS ======================================= */
// Get the read object of the source node.
UINT64 getSourceRead() const {return m_source;}
// Check if an edge is marked as not dead end
bool isNotDeadEnd() const { return (m_flag & 1);}
// Check if an edge is a loop
bool isLoop() const {return (m_flag >> 1) & 1;}
// Get the read object of the destination node.
UINT64 getDestinationRead() const {return m_destination; }
// Return the orientation of the edge.
UINT8 getOrientation() const {return m_orient;}
// Return the overlap offset.
UINT32 getOverlapOffset() const {return m_overlapOffset;}
UINT64 getInnerReadInfo(int indx) const
{
return m_listOfReads[indx];
}
UINT64 getInnerReadID(int indx) const
{
return (m_listOfReads[indx] & 0X00000000FFFFFFFF);
}
UINT32 getInnerOverlapOffset(int indx) const
{
return ((m_listOfReads[indx] >> 32) & 0X000000007FFFFFFF);
}
UINT8 getInnerOrientation(int indx) const
{
return (m_listOfReads[indx] >> 63);
}
bool isListofReads() const { return !(m_listOfReads==nullptr);}
size_t getListofReadsSize() const { return m_listSize; }
UINT32 getInnerOverlapSum(size_t start, size_t end) const;
// Return the pointer to the reverse edge.
EdgeSimple * getReverseEdge() const {return m_reverseEdge;}
UINT32 getOverlapLen() const;
UINT32 getFirstOverlapOffset() const
{
if (!m_listOfReads || m_listSize==0)
return m_overlapOffset;
else
return (getInnerOverlapOffset(0));
}
UINT64 getEdgeLength() const {return m_overlapOffset + m_destinationLen;}
UINT32 getLastOverlapOffset() const;
bool isSmallerEdge() const
{
if(m_source < m_destination)
return true;
else if (m_source > m_destination)
return false;
else if(this < m_reverseEdge)
return true;
else
return false;
}
INT8 getFlag() const {return m_flag;}
bool isInvalid() {return m_invalid;}
};
bool is_mergeable(const EdgeSimple *edge1, const EdgeSimple *edge2);
UINT8 mergedEdgeOrientation(const UINT8 &orient1, const UINT8 &orient2);
UINT8 get_twin_orient(const UINT8 &orient);
void mergeList(const EdgeSimple *edge1, const EdgeSimple *edge2,
UINT64 **listReads, UINT64 &lSize);
EdgeSimple * mergeEdges(const vector<EdgeSimple *> & list_edges);
template <typename T>
float get_mean(const vector<T> &numbers);
template <typename T>
float get_sd(const vector<T> &numbers);
#endif /* EDGE_H */
|
abiswas-odu/Disco
|
src/SimplifyGraph/src/EdgeSimple.h
|
C
|
gpl-3.0
| 6,129
|
----------------------------------
-- Area: Kuftal Tunnel
-- NM: Yowie
-----------------------------------
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
-- Set Yowie's Window Open Time
wait = math.random((2),(8)) * 3600
SetServerVariable("[POP]Yowie", os.time(t) + wait); -- 2-8 hours
DeterMob(mob:getID(), true);
-- Set PH back to normal, then set to respawn spawn
PH = GetServerVariable("[PH]Yowie");
SetServerVariable("[PH]Yowie", 0);
DeterMob(PH, false);
SpawnMob(PH, '', GetMobRespawnTime(PH));
end;
|
ffxinfinity/ffxinfinity
|
FFXI Server-Development/Build Files/scripts/zones/Kuftal_Tunnel/mobs/Yowie.lua
|
Lua
|
gpl-3.0
| 619
|
-- 31
-- PKCColumnE
-- ListElementExchanger with ChainedSupplier with PrimaryKeyConstraintSupplier and PrimaryKeyColumnsWithAlternativesSupplier - Exchanged categoryid with pos
CREATE TABLE "categorydef" (
"categoryid" DECIMAL(2, 0) NOT NULL,
"name" VARCHAR(32),
"pos" CHAR(1) PRIMARY KEY
)
CREATE TABLE "lexlinkref" (
"synset1id" DECIMAL(9, 0) NOT NULL,
"word1id" DECIMAL(6, 0) NOT NULL,
"synset2id" DECIMAL(9, 0) NOT NULL,
"word2id" DECIMAL(6, 0) NOT NULL,
"linkid" DECIMAL(2, 0) NOT NULL,
PRIMARY KEY ("word1id", "synset1id", "word2id", "synset2id", "linkid")
)
CREATE TABLE "linkdef" (
"linkid" DECIMAL(2, 0) PRIMARY KEY NOT NULL,
"name" VARCHAR(50),
"recurses" CHAR(1) NOT NULL
)
CREATE TABLE "sample" (
"synsetid" DECIMAL(9, 0) NOT NULL,
"sampleid" DECIMAL(2, 0) NOT NULL,
"sample" LONGVARCHAR NOT NULL,
PRIMARY KEY ("synsetid", "sampleid")
)
CREATE TABLE "semlinkref" (
"synset1id" DECIMAL(9, 0) NOT NULL,
"synset2id" DECIMAL(9, 0) NOT NULL,
"linkid" DECIMAL(2, 0) NOT NULL,
PRIMARY KEY ("synset1id", "synset2id", "linkid")
)
CREATE TABLE "sense" (
"wordid" DECIMAL(6, 0) NOT NULL,
"casedwordid" DECIMAL(6, 0),
"synsetid" DECIMAL(9, 0) NOT NULL,
"rank" DECIMAL(2, 0) NOT NULL,
"lexid" DECIMAL(2, 0) NOT NULL,
"tagcount" DECIMAL(5, 0),
PRIMARY KEY ("synsetid", "wordid")
)
CREATE TABLE "synset" (
"synsetid" DECIMAL(9, 0) PRIMARY KEY NOT NULL,
"pos" CHAR(1),
"categoryid" DECIMAL(2, 0) NOT NULL,
"definition" LONGVARCHAR
)
CREATE TABLE "word" (
"wordid" DECIMAL(6, 0) PRIMARY KEY NOT NULL,
"lemma" VARCHAR(80) UNIQUE NOT NULL
)
|
schemaanalyst-team/schemaanalyst
|
src/paper/ineffectivemutants/manualevaluation/mutants/WordNet_HyperSQL/31.sql
|
SQL
|
gpl-3.0
| 1,576
|
<?php
namespace Dogpatch;
////
// Via: http://www.php.net/manual/en/function.http-parse-headers.php#112986
///
function http_parse_headers($raw_headers) {
if (function_exists('http_parse_headers')) {
return \http_parse_headers($raw_headers);
}
$headers = array();
$key = '';
foreach (explode("\n", $raw_headers) as $i => $h) {
$h = explode(':', $h, 2);
if (isset($h[1])) {
if (!isset($headers[$h[0]])) {
$headers[$h[0]] = trim($h[1]);
} elseif (is_array($headers[$h[0]])) {
$headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1])));
} else {
$headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1])));
}
$key = $h[0];
} else {
if (substr($h[0], 0, 1) == "\t") {
$headers[$key] .= "\r\n\t" . trim($h[0]);
} elseif (!$key) {
$headers[0] = trim($h[0]);
}
trim($h[0]);
}
}
return $headers;
}
////
// Via: http://stackoverflow.com/a/4254008/425964
////
function isAssoc($array) {
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
////
// Via: http://stackoverflow.com/a/9776726/425964
////
function prettyPrintJson($json) {
$result = '';
$level = 0;
$prev_char = '';
$in_quotes = false;
$ends_line_level = null;
$json_length = strlen($json);
for ($i = 0; $i < $json_length; $i++) {
$char = $json[$i];
$new_line_level = null;
$post = "";
if ($ends_line_level !== null) {
$new_line_level = $ends_line_level;
$ends_line_level = null;
}
if ($char === '"' && $prev_char != '\\') {
$in_quotes = !$in_quotes;
} else {
if (!$in_quotes) {
switch ($char) {
case '}':
case ']':
$level--;
$ends_line_level = null;
$new_line_level = $level;
break;
case '{':
case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ":
case "\t":
case "\n":
case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = null;
break;
}
}
}
if ($new_line_level !== null) {
$result .= "\n" . str_repeat("\t", $new_line_level);
}
$result .= $char . $post;
$prev_char = $char;
}
return $result;
}
|
bodqhrohro/knp2014
|
src/test/Util.php
|
PHP
|
gpl-3.0
| 2,980
|
/*****************************************************************************
ATENTION
DO NOT EDIT THIS FILE.
THIS FILE IS AUTOMATIC GENERATED BY MARIAMOLE
ALL CHANGES IN THIS FILE WILL BE LOST
*****************************************************************************/
//---------------------------------------------------------------------------
#ifndef _MARIAMOLE_AUTOMATIC_CODE_H
#define _MARIAMOLE_AUTOMATIC_CODE_H
//---------------------------------------------------------------------------
#include <Arduino.h>
/*--MARIMOLE-DEF_BEGIN--*/
/*--MARIMOLE-DEF_END--*/
#endif
|
aporto/mariamole
|
installer/common_files/templates/mariamole_auto_generated.h
|
C
|
gpl-3.0
| 610
|
#!/bin/sh
# Try to remove '/' recursively.
# Copyright (C) 2013-2016 Free Software Foundation, 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 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
. "${srcdir=.}/tests/init.sh"; path_prepend_ ./src
print_ver_ rm
# POSIX mandates rm(1) to skip '/' arguments. This test verifies this mandated
# behavior as well as the --preserve-root and --no-preserve-root options.
# Especially the latter case is a live fire exercise as rm(1) is supposed to
# enter the unlinkat() system call. Therefore, limit the risk as much
# as possible -- if there's a bug this test would wipe the system out!
# Faint-hearted: skip this test for the 'root' user.
skip_if_root_
# Pull the teeth from rm(1) by intercepting the unlinkat() system call via the
# LD_PRELOAD environment variable. This requires shared libraries to work.
require_gcc_shared_
# Ensure this variable is unset as it's
# used later in the unlinkat() wrapper.
unset CU_TEST_SKIP_EXIT
# Use gdb to provide further protection by limiting calls to unlinkat().
( timeout 10s gdb --version ) > gdb.out 2>&1
case $(cat gdb.out) in
*'GNU gdb'*) ;;
*) skip_ "can't run gdb";;
esac
# Break on a line rather than a symbol, to cater for inline functions
break_src="$abs_top_srcdir/src/remove.c"
break_line=$(grep -n ^excise "$break_src") || framework_failure_
break_line=$(echo "$break_line" | cut -d: -f1) || framework_failure_
break_line="$break_src:$break_line"
cat > k.c <<'EOF' || framework_failure_
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int unlinkat (int dirfd, const char *pathname, int flags)
{
/* Prove that LD_PRELOAD works: create the evidence file "x". */
fclose (fopen ("x", "w"));
/* Immediately terminate, unless indicated otherwise. */
if (! getenv("CU_TEST_SKIP_EXIT"))
_exit (0);
/* Pretend success. */
return 0;
}
EOF
# Then compile/link it:
gcc_shared_ k.c k.so \
|| framework_failure_ 'failed to build shared library'
# Note breakpoint commands don't work in batch mode
# https://sourceware.org/bugzilla/show_bug.cgi?id=10079
# So we use python to script behavior upon hitting the breakpoint
cat > bp.py <<'EOF.py' || framework_failure_
def breakpoint_handler (event):
if not isinstance(event, gdb.BreakpointEvent):
return
hit_count = event.breakpoints[0].hit_count
if hit_count == 1:
gdb.execute('shell touch excise.break')
gdb.execute('continue')
elif hit_count > 2:
gdb.write('breakpoint hit twice already')
gdb.execute('quit 1')
else:
gdb.execute('continue')
gdb.events.stop.connect(breakpoint_handler)
EOF.py
# In order of the sed expressions below, this cleans:
#
# 1. gdb uses the full path when running rm, so remove the leading dirs.
# 2. For some of the "/" synonyms, the error diagnostic slightly differs from
# that of the basic "/" case (see gnulib's fts_open' and ROOT_DEV_INO_WARN):
# rm: it is dangerous to operate recursively on 'FILE' (same as '/')
# Strip that part off for the following comparison.
clean_rm_err_()
{
sed "s/.*rm: /rm: /; \
s/\(rm: it is dangerous to operate recursively on\).*$/\1 '\/'/"
}
#-------------------------------------------------------------------------------
# exercise_rm_r_root: shell function to test "rm -r '/'"
# The caller must provide the FILE to remove as well as any options
# which should be passed to 'rm'.
# Paranoia mode on:
# For the worst case where both rm(1) would fail to refuse to process the "/"
# argument (in the cases without the --no-preserve-root option), and
# intercepting the unlinkat(1) system call would fail (which actually already
# has been proven to work above), and the current non root user has
# write access to "/", limit the damage to the current file system via
# the --one-file-system option.
# Furthermore, run rm(1) via gdb that limits the number of unlinkat() calls.
exercise_rm_r_root ()
{
# Remove the evidence files; verify that.
rm -f x excise.break || framework_failure_
test -f x && framework_failure_
test -f excise.break && framework_failure_
local skip_exit=
if [ "$CU_TEST_SKIP_EXIT" = 1 ]; then
# Pass on this variable into 'rm's environment.
skip_exit='CU_TEST_SKIP_EXIT=1'
fi
gdb -nx --batch-silent -return-child-result \
--eval-command="set exec-wrapper \
env 'LD_PRELOAD=$LD_PRELOAD:./k.so' $skip_exit" \
--eval-command="break '$break_line'" \
--eval-command='source bp.py' \
--eval-command="run -rv --one-file-system $*" \
--eval-command='quit' \
rm < /dev/null > out 2> err.t
ret=$?
clean_rm_err_ < err.t > err || ret=$?
return $ret
}
# Verify that "rm -r dir" basically works.
mkdir dir || framework_failure_
rm -r dir || framework_failure_
test -d dir && framework_failure_
# Now verify that intercepting unlinkat() works:
# rm(1) must succeed as before, but this time both the evidence file "x"
# and the test file / directory must still exist afterward.
mkdir dir || framework_failure_
> file || framework_failure_
skip=
for file in dir file ; do
exercise_rm_r_root "$file" || skip=1
test -e "$file" || skip=1
test -f x || skip=1
test -f excise.break || skip=1 # gdb works and breakpoint hit
compare /dev/null err || skip=1
test "$skip" = 1 \
&& { cat out; cat err; \
skip_ "internal test failure: maybe LD_PRELOAD or gdb doesn't work?"; }
done
# "rm -r /" without --no-preserve-root should output the following
# diagnostic error message.
cat <<EOD > exp || framework_failure_
rm: it is dangerous to operate recursively on '/'
rm: use --no-preserve-root to override this failsafe
EOD
#-------------------------------------------------------------------------------
# Exercise "rm -r /" without and with the --preserve-root option.
# Exercise various synonyms of "/" including symlinks to it.
# Expect a non-Zero exit status.
# Prepare a few symlinks to "/".
ln -s / rootlink || framework_failure_
ln -s rootlink rootlink2 || framework_failure_
ln -sr / rootlink3 || framework_failure_
for opts in \
'/' \
'--preserve-root /' \
'//' \
'///' \
'////' \
'rootlink/' \
'rootlink2/' \
'rootlink3/' ; do
returns_ 1 exercise_rm_r_root $opts || fail=1
# Expect nothing in 'out' and the above error diagnostic in 'err'.
# As rm(1) should have skipped the "/" argument, it does not call unlinkat().
# Therefore, the evidence file "x" should not exist.
compare /dev/null out || fail=1
compare exp err || fail=1
test -f x && fail=1
# Do nothing more if this test failed.
test $fail = 1 && { cat out; cat err; Exit $fail; }
done
#-------------------------------------------------------------------------------
# Exercise with --no-preserve to ensure shortened equivalent is not allowed.
cat <<EOD > exp_opt || framework_failure_
rm: you may not abbreviate the --no-preserve-root option
EOD
returns_ 1 exercise_rm_r_root --no-preserve / || fail=1
compare exp_opt err || fail=1
test -f x && fail=1
#-------------------------------------------------------------------------------
# Exercise "rm -r file1 / file2".
# Expect a non-Zero exit status representing failure to remove "/",
# yet 'file1' and 'file2' should be removed.
> file1 || framework_failure_
> file2 || framework_failure_
# Now that we know that 'rm' won't call the unlinkat() system function for "/",
# we could probably execute it without the LD_PRELOAD'ed safety net.
# Nevertheless, it's still better to use it for this test.
# Tell the unlinkat() replacement function to not _exit(0) immediately
# by setting the following variable.
CU_TEST_SKIP_EXIT=1
returns_ 1 exercise_rm_r_root --preserve-root file1 '/' file2 || fail=1
unset CU_TEST_SKIP_EXIT
cat <<EOD > out_removed
removed 'file1'
removed 'file2'
EOD
# The above error diagnostic should appear in 'err'.
# Both 'file1' and 'file2' should be removed. Simply verify that in the
# "out" file, as the replacement unlinkat() dummy did not remove them.
# Expect the evidence file "x" to exist.
compare out_removed out || fail=1
compare exp err || fail=1
test -f x || fail=1
# Do nothing more if this test failed.
test $fail = 1 && { cat out; cat err; Exit $fail; }
#-------------------------------------------------------------------------------
# Exercise various synonyms of "/" having a trailing "." or ".." in the name.
# This triggers another check in the code first and therefore leads to a
# different diagnostic. However, we want to test anyway to protect against
# future reordering of the checks in the code.
# Expect that other error diagnostic in 'err' and nothing in 'out'.
# Expect a non-Zero exit status. The evidence file "x" should not exist.
for file in \
'//.' \
'/./' \
'/.//' \
'/../' \
'/.././' \
'/etc/..' \
'rootlink/..' \
'rootlink2/.' \
'rootlink3/./' ; do
test -d "$file" || continue # if e.g. /etc does not exist.
returns_ 1 exercise_rm_r_root --preserve-root "$file" || fail=1
grep "rm: refusing to remove '\.' or '\.\.' directory: skipping" err \
|| fail=1
compare /dev/null out || fail=1
test -f x && fail=1
# Do nothing more if this test failed.
test $fail = 1 && { cat out; cat err; Exit $fail; }
done
#-------------------------------------------------------------------------------
# Until now, it was all just fun.
# Now exercise the --no-preserve-root option with which rm(1) should enter
# the intercepted unlinkat() system call.
# As the interception code terminates the process immediately via _exit(0),
# the exit status should be 0.
# Use the option --interactive=never to bypass the following prompt:
# "rm: descend into write-protected directory '/'?"
exercise_rm_r_root --interactive=never --no-preserve-root '/' \
|| fail=1
# The 'err' file should not contain the above error diagnostic.
grep "rm: it is dangerous to operate recursively on '/'" err && fail=1
# Instead, rm(1) should have called the intercepted unlinkat() function,
# i.e., the evidence file "x" should exist.
test -f x || fail=1
test $fail = 1 && { cat out; cat err; }
Exit $fail
|
evaautomation/coreutils
|
tests/rm/r-root.sh
|
Shell
|
gpl-3.0
| 10,861
|
//===-- lldb.cpp ------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/lldb-python.h"
#include "lldb/lldb-private.h"
#include "lldb/lldb-private-log.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/Timer.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/Mutex.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "llvm/ADT/StringRef.h"
#include "Plugins/ABI/MacOSX-i386/ABIMacOSX_i386.h"
#include "Plugins/ABI/MacOSX-arm/ABIMacOSX_arm.h"
#include "Plugins/ABI/SysV-x86_64/ABISysV_x86_64.h"
#include "Plugins/Disassembler/llvm/DisassemblerLLVMC.h"
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#include "Plugins/SymbolVendor/MacOSX/SymbolVendorMacOSX.h"
#include "Plugins/SymbolVendor/ELF/SymbolVendorELF.h"
#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
#include "Plugins/SymbolFile/DWARF/SymbolFileDWARF.h"
#include "Plugins/SymbolFile/DWARF/SymbolFileDWARFDebugMap.h"
#include "Plugins/SymbolFile/Symtab/SymbolFileSymtab.h"
#include "Plugins/UnwindAssembly/x86/UnwindAssembly-x86.h"
#include "Plugins/UnwindAssembly/InstEmulation/UnwindAssemblyInstEmulation.h"
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
#include "Plugins/Platform/FreeBSD/PlatformFreeBSD.h"
#include "Plugins/Platform/Linux/PlatformLinux.h"
#include "Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.h"
#ifndef LLDB_DISABLE_PYTHON
#include "Plugins/OperatingSystem/Python/OperatingSystemPython.h"
#endif
#if defined (__APPLE__)
#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV1.h"
#include "Plugins/LanguageRuntime/ObjC/AppleObjCRuntime/AppleObjCRuntimeV2.h"
#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h"
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
#include "Plugins/Process/MacOSX-Kernel/ProcessKDP.h"
#include "Plugins/Platform/MacOSX/PlatformMacOSX.h"
#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
#include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
#include "Plugins/Platform/MacOSX/PlatformiOSSimulator.h"
#endif
#include "Plugins/Process/mach-core/ProcessMachCore.h"
#if defined(__linux__) or defined(__FreeBSD__)
#include "Plugins/Process/elf-core/ProcessElfCore.h"
#endif
#if defined (__linux__)
#include "Plugins/Process/Linux/ProcessLinux.h"
#endif
#if defined (__FreeBSD__)
#include "Plugins/Process/POSIX/ProcessPOSIX.h"
#include "Plugins/Process/FreeBSD/ProcessFreeBSD.h"
#endif
#include "Plugins/Platform/gdb-server/PlatformRemoteGDBServer.h"
#include "Plugins/Process/gdb-remote/ProcessGDBRemote.h"
#include "Plugins/DynamicLoader/Static/DynamicLoaderStatic.h"
using namespace lldb;
using namespace lldb_private;
void
lldb_private::Initialize ()
{
// Make sure we inialize only once
static Mutex g_inited_mutex(Mutex::eMutexTypeRecursive);
static bool g_inited = false;
Mutex::Locker locker(g_inited_mutex);
if (!g_inited)
{
g_inited = true;
Log::Initialize();
Timer::Initialize ();
Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
ABIMacOSX_i386::Initialize();
ABIMacOSX_arm::Initialize();
ABISysV_x86_64::Initialize();
DisassemblerLLVMC::Initialize();
ObjectContainerBSDArchive::Initialize();
ObjectFileELF::Initialize();
SymbolVendorELF::Initialize();
SymbolFileDWARF::Initialize();
SymbolFileSymtab::Initialize();
UnwindAssemblyInstEmulation::Initialize();
UnwindAssembly_x86::Initialize();
EmulateInstructionARM::Initialize ();
ObjectFilePECOFF::Initialize ();
DynamicLoaderPOSIXDYLD::Initialize ();
PlatformFreeBSD::Initialize();
PlatformLinux::Initialize();
SymbolFileDWARFDebugMap::Initialize();
ItaniumABILanguageRuntime::Initialize();
#ifndef LLDB_DISABLE_PYTHON
OperatingSystemPython::Initialize();
#endif
#if defined (__APPLE__)
//----------------------------------------------------------------------
// Apple/Darwin hosted plugins
//----------------------------------------------------------------------
DynamicLoaderMacOSXDYLD::Initialize();
DynamicLoaderDarwinKernel::Initialize();
AppleObjCRuntimeV2::Initialize();
AppleObjCRuntimeV1::Initialize();
ObjectContainerUniversalMachO::Initialize();
ObjectFileMachO::Initialize();
ProcessKDP::Initialize();
ProcessMachCore::Initialize();
SymbolVendorMacOSX::Initialize();
PlatformDarwinKernel::Initialize();
PlatformRemoteiOS::Initialize();
PlatformMacOSX::Initialize();
PlatformiOSSimulator::Initialize();
#endif
#if defined (__linux__)
//----------------------------------------------------------------------
// Linux hosted plugins
//----------------------------------------------------------------------
ProcessLinux::Initialize();
#endif
#if defined (__FreeBSD__)
ProcessFreeBSD::Initialize();
#endif
#if defined(__linux__) or defined(__FreeBSD__)
ProcessElfCore::Initialize();
#endif
//----------------------------------------------------------------------
// Platform agnostic plugins
//----------------------------------------------------------------------
PlatformRemoteGDBServer::Initialize ();
ProcessGDBRemote::Initialize();
DynamicLoaderStatic::Initialize();
// Scan for any system or user LLDB plug-ins
PluginManager::Initialize();
// The process settings need to know about installed plug-ins, so the Settings must be initialized
// AFTER PluginManager::Initialize is called.
Debugger::SettingsInitialize();
}
}
void
lldb_private::WillTerminate()
{
Host::WillTerminate();
}
void
lldb_private::Terminate ()
{
Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
// Terminate and unload and loaded system or user LLDB plug-ins
PluginManager::Terminate();
ABIMacOSX_i386::Terminate();
ABIMacOSX_arm::Terminate();
ABISysV_x86_64::Terminate();
DisassemblerLLVMC::Terminate();
ObjectContainerBSDArchive::Terminate();
ObjectFileELF::Terminate();
SymbolVendorELF::Terminate();
SymbolFileDWARF::Terminate();
SymbolFileSymtab::Terminate();
UnwindAssembly_x86::Terminate();
UnwindAssemblyInstEmulation::Terminate();
EmulateInstructionARM::Terminate ();
ObjectFilePECOFF::Terminate ();
DynamicLoaderPOSIXDYLD::Terminate ();
PlatformFreeBSD::Terminate();
PlatformLinux::Terminate();
SymbolFileDWARFDebugMap::Terminate();
ItaniumABILanguageRuntime::Terminate();
#ifndef LLDB_DISABLE_PYTHON
OperatingSystemPython::Terminate();
#endif
#if defined (__APPLE__)
DynamicLoaderMacOSXDYLD::Terminate();
DynamicLoaderDarwinKernel::Terminate();
AppleObjCRuntimeV2::Terminate();
AppleObjCRuntimeV1::Terminate();
ObjectContainerUniversalMachO::Terminate();
ObjectFileMachO::Terminate();
ProcessMachCore::Terminate();
ProcessKDP::Terminate();
SymbolVendorMacOSX::Terminate();
PlatformMacOSX::Terminate();
PlatformDarwinKernel::Terminate();
PlatformRemoteiOS::Terminate();
PlatformiOSSimulator::Terminate();
#endif
Debugger::SettingsTerminate ();
#if defined (__linux__)
ProcessLinux::Terminate();
#endif
#if defined (__FreeBSD__)
ProcessFreeBSD::Terminate();
#endif
#if defined(__linux__) or defined(__FreeBSD__)
ProcessElfCore::Terminate();
#endif
ProcessGDBRemote::Terminate();
DynamicLoaderStatic::Terminate();
Log::Terminate();
}
#if defined (__APPLE__)
extern "C" const unsigned char liblldb_coreVersionString[];
#else
#include "clang/Basic/Version.h"
static const char *
GetLLDBRevision()
{
#ifdef LLDB_REVISION
return LLDB_REVISION;
#else
return NULL;
#endif
}
static const char *
GetLLDBRepository()
{
#ifdef LLDB_REPOSITORY
return LLDB_REPOSITORY;
#else
return NULL;
#endif
}
#endif
const char *
lldb_private::GetVersion ()
{
#if defined (__APPLE__)
static char g_version_string[32];
if (g_version_string[0] == '\0')
{
const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:");
if (version_string)
version_string += sizeof("PROJECT:") - 1;
else
version_string = "unknown";
const char *newline_loc = strchr(version_string, '\n');
size_t version_len = sizeof(g_version_string);
if (newline_loc && (newline_loc - version_string < version_len))
version_len = newline_loc - version_string;
::strncpy(g_version_string, version_string, version_len);
}
return g_version_string;
#else
// On Linux/FreeBSD/Windows, report a version number in the same style as the clang tool.
static std::string g_version_str;
if (g_version_str.empty())
{
g_version_str += "lldb version ";
g_version_str += CLANG_VERSION_STRING;
const char * lldb_repo = GetLLDBRepository();
if (lldb_repo)
{
g_version_str += " (";
g_version_str += lldb_repo;
}
const char *lldb_rev = GetLLDBRevision();
if (lldb_rev)
{
g_version_str += " revision ";
g_version_str += lldb_rev;
}
std::string clang_rev (clang::getClangRevision());
if (clang_rev.length() > 0)
{
g_version_str += " clang revision ";
g_version_str += clang_rev;
}
std::string llvm_rev (clang::getLLVMRevision());
if (llvm_rev.length() > 0)
{
g_version_str += " llvm revision ";
g_version_str += llvm_rev;
}
if (lldb_repo)
g_version_str += ")";
}
return g_version_str.c_str();
#endif
}
const char *
lldb_private::GetVoteAsCString (Vote vote)
{
switch (vote)
{
case eVoteNo: return "no";
case eVoteNoOpinion: return "no opinion";
case eVoteYes: return "yes";
}
return "invalid";
}
const char *
lldb_private::GetSectionTypeAsCString (SectionType sect_type)
{
switch (sect_type)
{
case eSectionTypeInvalid: return "invalid";
case eSectionTypeCode: return "code";
case eSectionTypeContainer: return "container";
case eSectionTypeData: return "data";
case eSectionTypeDataCString: return "data-cstr";
case eSectionTypeDataCStringPointers: return "data-cstr-ptr";
case eSectionTypeDataSymbolAddress: return "data-symbol-addr";
case eSectionTypeData4: return "data-4-byte";
case eSectionTypeData8: return "data-8-byte";
case eSectionTypeData16: return "data-16-byte";
case eSectionTypeDataPointers: return "data-ptrs";
case eSectionTypeDebug: return "debug";
case eSectionTypeZeroFill: return "zero-fill";
case eSectionTypeDataObjCMessageRefs: return "objc-message-refs";
case eSectionTypeDataObjCCFStrings: return "objc-cfstrings";
case eSectionTypeDWARFDebugAbbrev: return "dwarf-abbrev";
case eSectionTypeDWARFDebugAranges: return "dwarf-aranges";
case eSectionTypeDWARFDebugFrame: return "dwarf-frame";
case eSectionTypeDWARFDebugInfo: return "dwarf-info";
case eSectionTypeDWARFDebugLine: return "dwarf-line";
case eSectionTypeDWARFDebugLoc: return "dwarf-loc";
case eSectionTypeDWARFDebugMacInfo: return "dwarf-macinfo";
case eSectionTypeDWARFDebugPubNames: return "dwarf-pubnames";
case eSectionTypeDWARFDebugPubTypes: return "dwarf-pubtypes";
case eSectionTypeDWARFDebugRanges: return "dwarf-ranges";
case eSectionTypeDWARFDebugStr: return "dwarf-str";
case eSectionTypeELFSymbolTable: return "elf-symbol-table";
case eSectionTypeELFDynamicSymbols: return "elf-dynamic-symbols";
case eSectionTypeELFRelocationEntries: return "elf-relocation-entries";
case eSectionTypeELFDynamicLinkInfo: return "elf-dynamic-link-info";
case eSectionTypeDWARFAppleNames: return "apple-names";
case eSectionTypeDWARFAppleTypes: return "apple-types";
case eSectionTypeDWARFAppleNamespaces: return "apple-namespaces";
case eSectionTypeDWARFAppleObjC: return "apple-objc";
case eSectionTypeEHFrame: return "eh-frame";
case eSectionTypeOther: return "regular";
}
return "unknown";
}
bool
lldb_private::NameMatches (const char *name,
NameMatchType match_type,
const char *match)
{
if (match_type == eNameMatchIgnore)
return true;
if (name == match)
return true;
if (name && match)
{
llvm::StringRef name_sref(name);
llvm::StringRef match_sref(match);
switch (match_type)
{
case eNameMatchIgnore:
return true;
case eNameMatchEquals: return name_sref == match_sref;
case eNameMatchContains: return name_sref.find (match_sref) != llvm::StringRef::npos;
case eNameMatchStartsWith: return name_sref.startswith (match_sref);
case eNameMatchEndsWith: return name_sref.endswith (match_sref);
case eNameMatchRegularExpression:
{
RegularExpression regex (match);
return regex.Execute (name);
}
break;
}
}
return false;
}
|
s20121035/rk3288_android5.1_repo
|
external/lldb/source/lldb.cpp
|
C++
|
gpl-3.0
| 14,145
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'fontsource-roboto';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
|
BrechtBa/homecon
|
frontend/src/index.js
|
JavaScript
|
gpl-3.0
| 247
|
/*
* Copyright (C) 2010 Canonical, Ltd.
*
* Authors:
* Olivier Tilloy <olivier.tilloy@canonical.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; version 3.
*
* 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/>.
*/
// unity-2d
#include <gnomesessionclient.h>
#include <launcherclient.h>
#include <unity2dapplication.h>
#include <propertybinder.h>
// libdconf-qt
#include "qconf.h"
// Qt
#include <QApplication>
#include <QDesktopWidget>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include <QDir>
#include <QGraphicsObject>
#include "config.h"
#include "launcherview.h"
#include "launcherdbus.h"
#include "visibilitycontroller.h"
#include "unity2ddebug.h"
#include "unity2dpanel.h"
#include "gesturehandler.h"
// libc
#include <stdlib.h>
static const char* LAUNCHER_DCONF_SCHEMA = "com.canonical.Unity2d.Launcher";
#if defined(QMLJSDEBUGGER)
#include <qt_private/qdeclarativedebughelper_p.h>
#endif
#if defined(QMLJSDEBUGGER) && !defined(NO_JSDEBUGGER)
#include <jsdebuggeragent.h>
#endif
#if defined(QMLJSDEBUGGER) && !defined(NO_QMLOBSERVER)
#include <qdeclarativeviewobserver.h>
#endif
#if defined(QMLJSDEBUGGER)
// Enable debugging before any QDeclarativeEngine is created
struct QmlJsDebuggingEnabler
{
QmlJsDebuggingEnabler()
{
QDeclarativeDebugHelper::enableDebugging();
}
};
// Execute code in constructor before first QDeclarativeEngine is instantiated
static QmlJsDebuggingEnabler enableDebuggingHelper;
#endif // QMLJSDEBUGGER
int main(int argc, char *argv[])
{
Unity2dApplication::earlySetup(argc, argv);
Unity2dApplication application(argc, argv);
application.setApplicationName("Unity 2D Launcher");
QSet<QString> arguments = QSet<QString>::fromList(QCoreApplication::arguments());
GnomeSessionClient client(INSTALL_PREFIX "/share/applications/unity-2d-launcher.desktop");
client.connectToSessionManager();
/* Configure "artwork:" prefix so that any access to a file whose name starts
with that prefix resolves properly. */
QDir::addSearchPath("artwork", unity2dDirectory() + "/launcher/artwork");
/* Panel containing the QML declarative view */
Unity2dPanel panel(true);
panel.setEdge(Unity2dPanel::LeftEdge);
panel.setFixedWidth(LauncherClient::MaximumWidth);
panel.setAccessibleName("Launcher");
VisibilityController* visibilityController = new VisibilityController(&panel);
/* QML declarative view */
LauncherView *launcherView = new LauncherView(&panel);
launcherView->setUseOpenGL(arguments.contains("-opengl"));
launcherView->setResizeMode(QDeclarativeView::SizeRootObjectToView);
launcherView->setFocus();
launcherView->engine()->addImportPath(unity2dImportPath());
/* Note: baseUrl seems to be picky: if it does not end with a slash,
setSource() will fail */
launcherView->engine()->setBaseUrl(QUrl::fromLocalFile(unity2dDirectory() + "/launcher/"));
if (!isRunningInstalled()) {
launcherView->engine()->addImportPath(unity2dDirectory() + "/libunity-2d-private/");
}
launcherView->rootContext()->setContextProperty("declarativeView", launcherView);
launcherView->rootContext()->setContextProperty("launcherView", launcherView);
launcherView->rootContext()->setContextProperty("panel", &panel);
launcherView->rootContext()->setContextProperty("visibilityController", visibilityController);
LauncherDBus launcherDBus(visibilityController, launcherView);
launcherDBus.connectToBus();
launcherView->setSource(QUrl("./Launcher.qml"));
/* Synchronise panel's "useStrut" property with its corresponding DConf key */
QConf dconfLauncher(LAUNCHER_DCONF_SCHEMA);
panel.setUseStrut(dconfLauncher.property("useStrut").toBool());
PropertyBinder useStrutBinder;
useStrutBinder.bind(&dconfLauncher, "useStrut", &panel, "useStrut");
/* Composing the QML declarative view inside the panel */
panel.addWidget(launcherView);
panel.show();
/* Unset DESKTOP_AUTOSTART_ID in order to avoid child processes (launched
applications) to use the same client id.
This would prevent some applications (e.g. nautilus) from launching when
the launcher itself was autostarted (which is the common case when
running installed).
For a discussion, see https://bugs.launchpad.net/upicek/+bug/684160. */
unsetenv("DESKTOP_AUTOSTART_ID");
/* Gesture handler instance in charge of listening to gesture events and
trigger appropriate actions in response. */
GestureHandler gestureHandler(&panel);
return application.exec();
}
|
hamaxx/unity-2d-for-xmonad
|
launcher/app/launcher.cpp
|
C++
|
gpl-3.0
| 5,096
|
#include "isobarDecayVertex_py.h"
#include<particle.h>
#include "rootConverters_py.h"
namespace bp = boost::python;
namespace {
struct isobarDecayVertexWrapper : public rpwa::isobarDecayVertex,
bp::wrapper<rpwa::isobarDecayVertex>
{
isobarDecayVertexWrapper(const rpwa::particlePtr& parent,
const rpwa::particlePtr& daughter1,
const rpwa::particlePtr& daughter2,
const unsigned int L = 0,
const unsigned int S = 0,
const rpwa::massDependencePtr& massDep = rpwa::massDependencePtr())
: rpwa::isobarDecayVertex(parent, daughter1, daughter2, L, S, massDep),
bp::wrapper<rpwa::isobarDecayVertex>() { }
isobarDecayVertexWrapper(const isobarDecayVertex& vert)
: rpwa::isobarDecayVertex(vert),
bp::wrapper<rpwa::isobarDecayVertex>() { }
bool addInParticle(const rpwa::particlePtr& part) {
if(bp::override addInParticle = this->get_override("addInParticle")) {
return addInParticle(part);
}
return rpwa::isobarDecayVertex::addInParticle(part);
}
bool default_addInParticle(const rpwa::particlePtr& part) {
return rpwa::isobarDecayVertex::addInParticle(part);
}
bool addOutParticle(const rpwa::particlePtr& part) {
if(bp::override addOutParticle = this->get_override("addOutParticle")) {
return addOutParticle(part);
}
return rpwa::isobarDecayVertex::addOutParticle(part);
}
bool default_addOutParticle(const rpwa::particlePtr& part) {
return rpwa::isobarDecayVertex::addOutParticle(part);
}
std::string name() const {
if(bp::override name = this->get_override("name")) {
return name();
}
return rpwa::isobarDecayVertex::name();
}
std::string default_name() const {
return rpwa::isobarDecayVertex::name();
}
};
rpwa::particlePtr isobarDecayVertex_parent(rpwa::isobarDecayVertex& self) {
return self.parent();
}
rpwa::particlePtr isobarDecayVertex_daughter1(rpwa::isobarDecayVertex& self) {
return self.daughter1();
}
rpwa::particlePtr isobarDecayVertex_daughter2(rpwa::isobarDecayVertex& self) {
return self.daughter2();
}
PyObject* isobarDecayVertex_calcParentLzVec(rpwa::isobarDecayVertex& self) {
return rpwa::py::convertToPy<TLorentzVector>(self.calcParentLzVec());
}
const rpwa::massDependence& isobarDecayVertex_massDependence(const rpwa::isobarDecayVertex& self) {
return *(self.massDependence());
}
}
void rpwa::py::exportIsobarDecayVertex() {
bp::class_<isobarDecayVertexWrapper, bp::bases<rpwa::interactionVertex> >("isobarDecayVertex", bp::no_init)
.def(bp::init<rpwa::particlePtr, rpwa::particlePtr, rpwa::particlePtr, bp::optional<unsigned int, unsigned int, rpwa::massDependencePtr> >())
.def(bp::self_ns::str(bp::self))
.def(
"clone"
, &rpwa::isobarDecayVertex::clone
, (bp::arg("cloneInParticles")=false,
bp::arg("cloneOutParticles")=false)
)
.def("addInParticle", &isobarDecayVertexWrapper::addInParticle, &isobarDecayVertexWrapper::default_addInParticle)
.def("addInParticle", &rpwa::isobarDecayVertex::addInParticle)
.def("addOutParticle", &isobarDecayVertexWrapper::addOutParticle, &isobarDecayVertexWrapper::default_addOutParticle)
.def("addInParticle", &rpwa::isobarDecayVertex::addOutParticle)
.def("parent", &isobarDecayVertex_parent)
.def("daughter1", &isobarDecayVertex_daughter1)
.def("daughter2", &isobarDecayVertex_daughter2)
.def("calcParentLzVec", &isobarDecayVertex_calcParentLzVec)
.def("calcParentCharge", &rpwa::isobarDecayVertex::calcParentCharge)
.def("calcParentBaryonNmb", &rpwa::isobarDecayVertex::calcParentBaryonNmb)
.add_property("L", &rpwa::isobarDecayVertex::L, &rpwa::isobarDecayVertex::setL)
.add_property("S", &rpwa::isobarDecayVertex::S, &rpwa::isobarDecayVertex::setS)
.def("massDepAmplitude", &rpwa::isobarDecayVertex::massDepAmplitude)
.def("massDependence", &isobarDecayVertex_massDependence, bp::return_internal_reference<>())
.def("setMassDependence", &rpwa::isobarDecayVertex::setMassDependence)
.def("checkConsistency", &rpwa::isobarDecayVertex::checkConsistency)
.def("name", &isobarDecayVertexWrapper::name, &isobarDecayVertexWrapper::default_name)
.def("name", &rpwa::isobarDecayVertex::name)
.add_static_property("debugIsobarDecayVertex", &rpwa::isobarDecayVertex::debug, &rpwa::isobarDecayVertex::setDebug);
bp::register_ptr_to_python<rpwa::isobarDecayVertexPtr>();
}
|
odrotleff/ROOTPWA
|
pyInterface/amplitude/isobarDecayVertex_py.cc
|
C++
|
gpl-3.0
| 4,554
|
package curso.dao;
import java.util.List;
import curso.modelo.Usuario;
public interface UsuarioDao {
public void saveUsuario(Usuario usuario);
public Usuario findUsuario(Integer id);
public void deleteUsuario(Integer id);
public List listAll();
public void saveListaUsuarios(Usuario[] usuario);
}
|
asanzdiego/curso-spring-2013
|
src/spring-05-dao/src/curso/dao/UsuarioDao.java
|
Java
|
gpl-3.0
| 335
|
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.
export const environment = {
production: false,
API_ENDPOINT: 'http://127.0.0.1:8000/api/v1/'
};
|
samsath/cpcc_backend
|
frontend/src/environments/environment.ts
|
TypeScript
|
gpl-3.0
| 436
|
/*******************************************************************************
* sdr-trunk
* Copyright (C) 2014-2018 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/
package io.github.dsheirer.dsp.psk;
import io.github.dsheirer.dsp.psk.pll.IPhaseLockedLoop;
import io.github.dsheirer.dsp.symbol.Dibit;
import io.github.dsheirer.sample.complex.Complex;
public class DQPSKGardnerDemodulator extends PSKDemodulator<Dibit>
{
protected DQPSKGardnerSymbolEvaluator mSymbolEvaluator = new DQPSKGardnerSymbolEvaluator();
private Complex mPreviousCurrentSample = new Complex(0, 0);
private Complex mPreviousMiddleSample = new Complex(0, 0);
private Complex mMiddleSymbol = new Complex(0, 0);
protected Complex mCurrentSymbol = new Complex(0, 0);
/**
* Implements a Differential QPSK demodulator using a Costas Loop (PLL) and a Gardner timing error detector.
*
* This decoder is optimized for P25 Linear Simulcast Modulation (LSM).
*
* @param phaseLockedLoop for tracking carrier frequency error
* @param interpolatingSampleBuffer to hold samples for interpolating a symbol
*/
public DQPSKGardnerDemodulator(IPhaseLockedLoop phaseLockedLoop, InterpolatingSampleBuffer interpolatingSampleBuffer)
{
super(interpolatingSampleBuffer, phaseLockedLoop);
}
public void dispose()
{
}
@Override
protected void calculateSymbol()
{
//Note: the interpolating sample buffer holds 2 symbols worth of samples and the current sample method points
//to the sample at the mid-point between those 2 symbol periods and the middle sample method points to the
//sample that is half a symbol period after the current sample. Since we need a middle sample and a current
//symbol sample for the gardner calculation, we'll treat the interpolating buffer's current sample as the
//gardner mid-point and we'll treat the interpolating buffer's mid-point sample as the current symbol
//sample (ie flip-flopped)
Complex middleSample = getInterpolatingSampleBuffer().getCurrentSample();
Complex currentSample = getInterpolatingSampleBuffer().getMiddleSample();
//Differential decode middle and current symbols by calculating the angular rotation between the previous and
//current samples (current sample x complex conjugate of previous sample).
mMiddleSymbol.setInphase(Complex.multiplyInphase(middleSample.inphase(), middleSample.quadrature(),
mPreviousMiddleSample.inphase(), -mPreviousMiddleSample.quadrature()));
mMiddleSymbol.setQuadrature(Complex.multiplyQuadrature(middleSample.inphase(), middleSample.quadrature(),
mPreviousMiddleSample.inphase(), -mPreviousMiddleSample.quadrature()));
mCurrentSymbol.setInphase(Complex.multiplyInphase(currentSample.inphase(), currentSample.quadrature(),
mPreviousCurrentSample.inphase(), -mPreviousCurrentSample.quadrature()));
mCurrentSymbol.setQuadrature(Complex.multiplyQuadrature(currentSample.inphase(), currentSample.quadrature(),
mPreviousCurrentSample.inphase(), -mPreviousCurrentSample.quadrature()));
//Set gain to unity before we calculate the error value
mMiddleSymbol.normalize();
mCurrentSymbol.normalize();
//Pass symbols to evaluator to determine timing and phase error and make symbol decision
mSymbolEvaluator.setSymbols(mMiddleSymbol, mCurrentSymbol);
//Update symbol timing error
getInterpolatingSampleBuffer().resetAndAdjust(mSymbolEvaluator.getTimingError());
//Update PLL phase error
getPLL().adjust(mSymbolEvaluator.getPhaseError());
//Store current samples/symbols for next symbol calculation
mPreviousMiddleSample.setValues(middleSample);
mPreviousCurrentSample.setValues(currentSample);
broadcast(mSymbolEvaluator.getSymbolDecision());
}
}
|
ImagoTrigger/sdrtrunk
|
src/main/java/io/github/dsheirer/dsp/psk/DQPSKGardnerDemodulator.java
|
Java
|
gpl-3.0
| 4,643
|
/* Copyright 1995 David C. Niemi
* Copyright 1996-2003,2005,2007-2009 Alain Knaff.
* This file is part of mtools.
*
* Mtools 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.
*
* Mtools 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 Mtools. If not, see <http://www.gnu.org/licenses/>.
*
* vfat.c
*
* Miscellaneous VFAT-related functions
*/
#include "sysincludes.h"
#include "msdos.h"
#include "mtools.h"
#include "vfat.h"
#include "file.h"
#include "dirCache.h"
#include "dirCacheP.h"
#include "file_name.h"
/* #define DEBUG */
const char *short_illegals=";+=[]',\"*\\<>/?:|";
const char *long_illegals = "\"*\\<>/?:|\005";
/* Automatically derive a new name */
static void autorename(char *name,
char tilda, char dot, const char *illegals,
int limit, int bump)
{
int tildapos, dotpos;
unsigned int seqnum=0, maxseq=0;
char tmp;
char *p;
#ifdef DEBUG
printf("In autorename for name=%s.\n", name);
#endif
tildapos = -1;
for(p=name; *p ; p++)
if (strchr(illegals, *p)) {
*p = '_';
bump = 0;
}
for(dotpos=0;
name[dotpos] && dotpos < limit && name[dotpos] != dot ;
dotpos++) {
if(name[dotpos] == tilda) {
tildapos = dotpos;
seqnum = 0;
maxseq = 1;
} else if (name[dotpos] >= '0' && name[dotpos] <= '9') {
seqnum = seqnum * 10 + name[dotpos] - '0';
maxseq = maxseq * 10;
} else
tildapos = -1; /* sequence number interrupted */
}
if(tildapos == -1) {
/* no sequence number yet */
if(dotpos > limit - 2) {
tildapos = limit - 2;
dotpos = limit;
} else {
tildapos = dotpos;
dotpos += 2;
}
seqnum = 1;
} else {
if(bump)
seqnum++;
if(seqnum > 999999) {
seqnum = 1;
tildapos = dotpos - 2;
/* this matches Win95's behavior, and also guarantees
* us that the sequence numbers never get shorter */
}
if (seqnum == maxseq) {
if(dotpos >= limit)
tildapos--;
else
dotpos++;
}
}
tmp = name[dotpos];
if((bump && seqnum == 1) || seqnum > 1 || mtools_numeric_tail)
sprintf(name+tildapos,"%c%d",tilda, seqnum);
if(dot)
name[dotpos]=tmp;
/* replace the character if it wasn't a space */
#ifdef DEBUG
printf("Out autorename for name=%s.\n", name);
#endif
}
void autorename_short(dos_name_t *name, int bump)
{
autorename(name->base, '~', ' ', short_illegals, 8, bump);
}
void autorename_long(char *name, int bump)
{
autorename(name, '-', '\0', long_illegals, 255, bump);
}
static __inline__ int unicode_read(struct unicode_char *in,
wchar_t *out, int num)
{
wchar_t *end_out = out+num;
while(out < end_out) {
#ifdef HAVE_WCHAR_H
*out = in->lchar | ((in->uchar) << 8);
#else
if (in->uchar)
*out = '_';
else
*out = in->lchar;
#endif
++out;
++in;
}
return num;
}
void clear_vfat(struct vfat_state *v)
{
v->subentries = 0;
v->status = 0;
v->present = 0;
}
/* sum_shortname
*
* Calculate the checksum that results from the short name in *dir.
*
* The sum is formed by circularly right-shifting the previous sum
* and adding in each character, from left to right, padding both
* the name and extension to maximum length with spaces and skipping
* the "." (hence always summing exactly 11 characters).
*
* This exact algorithm is required in order to remain compatible
* with Microsoft Windows-95 and Microsoft Windows NT 3.5.
* Thanks to Jeffrey Richter of Microsoft Systems Journal for
* pointing me to the correct algorithm.
*
* David C. Niemi (niemi@tuxers.net) 95.01.19
*/
static __inline__ unsigned char sum_shortname(const dos_name_t *dn)
{
unsigned char sum;
const char *name=dn->base;
const char *end = name+11;
for (sum=0; name<end; ++name)
sum = ((sum & 1) ? 0x80 : 0) + (sum >> 1)
+ *name;
return(sum);
}
/* check_vfat
*
* Inspect a directory and any associated VSEs.
* Return 1 if the VSEs comprise a valid long file name,
* 0 if not.
*/
static __inline__ void check_vfat(struct vfat_state *v, struct directory *dir)
{
dos_name_t dn;;
if (! v->subentries) {
#ifdef DEBUG
fprintf(stderr, "check_vfat: no VSEs.\n");
#endif
return;
}
memcpy(dn.base, (char *)dir->name, 8);
memcpy(dn.ext, (char *)dir->ext, 3);
if (v->sum != sum_shortname(&dn))
return;
if( (v->status & ((1<<v->subentries) - 1)) != (1<<v->subentries) - 1)
return; /* missing entries */
/* zero out byte following last entry, for good measure */
v->name[VSE_NAMELEN * v->subentries] = 0;
v->present = 1;
}
int clear_vses(Stream_t *Dir, int entrySlot, size_t last)
{
direntry_t entry;
dirCache_t *cache;
int error;
entry.Dir = Dir;
entry.entry = entrySlot;
/*maximize(last, entry.entry + MAX_VFAT_SUBENTRIES);*/
cache = allocDirCache(Dir, last);
if(!cache) {
fprintf(stderr, "Out of memory error in clear_vses\n");
exit(1);
}
addFreeEntry(cache, entry.entry, last);
for (; entry.entry < (signed int) last; ++entry.entry) {
#ifdef DEBUG
fprintf(stderr,"Clearing entry %d.\n", entry.entry);
#endif
dir_read(&entry, &error);
if(error)
return error;
if(!entry.dir.name[0] || entry.dir.name[0] == DELMARK)
break;
entry.dir.name[0] = DELMARK;
if (entry.dir.attr == 0xf)
entry.dir.attr = '\0';
low_level_dir_write(&entry);
}
return 0;
}
int write_vfat(Stream_t *Dir, dos_name_t *shortname, char *longname, int start,
direntry_t *mainEntry)
{
struct vfat_subentry *vse;
int vse_id, num_vses;
wchar_t *c;
direntry_t entry;
dirCache_t *cache;
wchar_t unixyName[13];
doscp_t *cp = GET_DOSCONVERT(Dir);
wchar_t wlongname[MAX_VNAMELEN+1];
int wlen;
if(longname) {
#ifdef DEBUG
printf("Entering write_vfat with longname=\"%s\", start=%d.\n",
longname,start);
#endif
entry.Dir = Dir;
vse = (struct vfat_subentry *) &entry.dir;
/* Fill in invariant part of vse */
vse->attribute = 0x0f;
vse->hash1 = vse->sector_l = vse->sector_u = 0;
vse->sum = sum_shortname(shortname);
#ifdef DEBUG
printf("Wrote checksum=%d for shortname %s.%s\n",
vse->sum,shortname->base,shortname->ext);
#endif
wlen = native_to_wchar(longname, wlongname, MAX_VNAMELEN+1,
0, 0);
num_vses = (wlen + VSE_NAMELEN - 1)/VSE_NAMELEN;
for (vse_id = num_vses; vse_id; --vse_id) {
int end = 0;
c = wlongname + (vse_id - 1) * VSE_NAMELEN;
c += unicode_write(c, vse->text1, VSE1SIZE, &end);
c += unicode_write(c, vse->text2, VSE2SIZE, &end);
c += unicode_write(c, vse->text3, VSE3SIZE, &end);
vse->id = (vse_id == num_vses) ? (vse_id | VSE_LAST) : vse_id;
#ifdef DEBUG
printf("Writing longname=(%s), VSE %d (%13s) at %d, end = %d.\n",
longname, vse_id, longname + (vse_id-1) * VSE_NAMELEN,
start + num_vses - vse_id, start + num_vses);
#endif
entry.entry = start + num_vses - vse_id;
low_level_dir_write(&entry);
}
} else {
num_vses = 0;
wlongname[0]='\0';
}
cache = allocDirCache(Dir, start + num_vses + 1);
if(!cache) {
fprintf(stderr, "Out of memory error\n");
exit(1);
}
unix_name(cp, shortname->base, shortname->ext, 0, unixyName);
addUsedEntry(cache, start, start + num_vses + 1, wlongname, unixyName,
&mainEntry->dir);
low_level_dir_write(mainEntry);
return start + num_vses;
}
void dir_write(direntry_t *entry)
{
dirCacheEntry_t *dce;
dirCache_t *cache;
if(entry->entry == -3) {
fprintf(stderr, "Attempt to write root directory pointer\n");
exit(1);
}
cache = allocDirCache(entry->Dir, entry->entry + 1);
if(!cache) {
fprintf(stderr, "Out of memory error in dir_write\n");
exit(1);
}
dce = cache->entries[entry->entry];
if(dce) {
if(entry->dir.name[0] == DELMARK) {
addFreeEntry(cache, dce->beginSlot, dce->endSlot);
} else {
dce->dir = entry->dir;
}
}
low_level_dir_write(entry);
}
/*
* The following function translates a series of vfat_subentries into
* data suitable for a dircache entry
*/
static __inline__ void parse_vses(direntry_t *entry,
struct vfat_state *v)
{
struct vfat_subentry *vse;
unsigned char id, last_flag;
wchar_t *c;
vse = (struct vfat_subentry *) &entry->dir;
id = vse->id & VSE_MASK;
last_flag = (vse->id & VSE_LAST);
if (id > MAX_VFAT_SUBENTRIES) {
fprintf(stderr, "parse_vses: invalid VSE ID %d at %d.\n",
id, entry->entry);
return;
}
/* 950819: This code enforced finding the VSEs in order. Well, Win95
* likes to write them in *reverse* order for some bizarre reason! So
* we pretty much have to tolerate them coming in any possible order.
* So skip this check, we'll do without it (What does this do, Alain?).
*
* 950820: Totally rearranged code to tolerate any order but to warn if
* they are not in reverse order like Win95 uses.
*
* 950909: Tolerate any order. We recognize new chains by mismatching
* checksums. In the event that the checksums match, new entries silently
* overwrite old entries of the same id. This should accept all valid
* entries, but may fail to reject invalid entries in some rare cases.
*/
/* bad checksum, begin new chain */
if(v->sum != vse->sum) {
clear_vfat(v);
v->sum = vse->sum;
}
#ifdef DEBUG
if(v->status & (1 << (id-1)))
fprintf(stderr,
"parse_vses: duplicate VSE %d\n", vse->id);
#endif
v->status |= 1 << (id-1);
if(last_flag)
v->subentries = id;
#ifdef DEBUG
if (id > v->subentries)
/* simple test to detect entries preceding
* the "last" entry (really the first) */
fprintf(stderr,
"parse_vses: new VSE %d sans LAST flag\n",
vse->id);
#endif
c = &(v->name[VSE_NAMELEN * (id-1)]);
c += unicode_read(vse->text1, c, VSE1SIZE);
c += unicode_read(vse->text2, c, VSE2SIZE);
c += unicode_read(vse->text3, c, VSE3SIZE);
#ifdef DEBUG
printf("Read VSE %d at %d, subentries=%d, = (%13ls).\n",
id,entry->entry,v->subentries,&(v->name[VSE_NAMELEN * (id-1)]));
#endif
if (last_flag)
*c = '\0'; /* Null terminate long name */
}
/**
* Read one complete entry from directory (main name plus any VSEs
* belonging to it)
*/
static dirCacheEntry_t *vfat_lookup_loop_common(doscp_t *cp,
direntry_t *direntry,
dirCache_t *cache,
int lookForFreeSpace,
int *io_error)
{
wchar_t newfile[13];
int initpos = direntry->entry + 1;
struct vfat_state vfat;
wchar_t *longname;
int error;
int endmarkSeen = 0;
/* not yet cached */
*io_error = 0;
clear_vfat(&vfat);
while(1) {
++direntry->entry;
if(!dir_read(direntry, &error)){
if(error) {
*io_error = error;
return NULL;
}
addFreeEndEntry(cache, initpos, direntry->entry,
endmarkSeen);
return addEndEntry(cache, direntry->entry);
}
if (endmarkSeen || direntry->dir.name[0] == ENDMARK){
/* the end of the directory */
if(lookForFreeSpace) {
endmarkSeen = 1;
continue;
}
return addEndEntry(cache, direntry->entry);
}
if(direntry->dir.name[0] != DELMARK &&
direntry->dir.attr == 0x0f)
parse_vses(direntry, &vfat);
else
/* the main entry */
break;
}
/* If we get here, it's a short name FAT entry, maybe erased.
* thus we should make sure that the vfat structure will be
* cleared before the next loop run */
/* deleted file */
if (direntry->dir.name[0] == DELMARK) {
return addFreeEntry(cache, initpos,
direntry->entry + 1);
}
check_vfat(&vfat, &direntry->dir);
if(!vfat.present)
vfat.subentries = 0;
/* mark space between last entry and this one as free */
addFreeEntry(cache, initpos,
direntry->entry - vfat.subentries);
if (direntry->dir.attr & 0x8){
/* Read entry as a label */
wchar_t *ptr = newfile;
ptr += dos_to_wchar(cp, direntry->dir.name, ptr, 8);
ptr += dos_to_wchar(cp, direntry->dir.ext, ptr, 3);
*ptr = '\0';
} else
unix_name(cp,
direntry->dir.name,
direntry->dir.ext,
direntry->dir.Case,
newfile);
if(vfat.present)
longname = vfat.name;
else
longname = 0;
return addUsedEntry(cache, direntry->entry - vfat.subentries,
direntry->entry + 1, longname,
newfile, &direntry->dir);
}
static __inline__ dirCacheEntry_t *vfat_lookup_loop_for_read(doscp_t *cp,
direntry_t *direntry,
dirCache_t *cache,
int *io_error)
{
int initpos = direntry->entry + 1;
dirCacheEntry_t *dce;
*io_error = 0;
dce = cache->entries[initpos];
if(dce) {
direntry->entry = dce->endSlot - 1;
return dce;
} else {
return vfat_lookup_loop_common(cp,
direntry, cache, 0, io_error);
}
}
typedef enum result_t {
RES_NOMATCH,
RES_MATCH,
RES_END,
RES_ERROR
} result_t;
/*
* 0 does not match
* 1 matches
* 2 end
*/
static result_t checkNameForMatch(struct direntry_t *direntry,
dirCacheEntry_t *dce,
const wchar_t *filename,
int length,
int flags)
{
switch(dce->type) {
case DCET_FREE:
return RES_NOMATCH;
case DCET_END:
return RES_END;
case DCET_USED:
break;
default:
fprintf(stderr, "Unexpected entry type %d\n",
dce->type);
return RES_ERROR;
}
direntry->dir = dce->dir;
/* make sure the entry is of an accepted type */
if((direntry->dir.attr & 0x8) && !(flags & ACCEPT_LABEL))
return RES_NOMATCH;
/*---------- multiple files ----------*/
if(!((flags & MATCH_ANY) ||
(dce->longName &&
match(dce->longName, filename, direntry->name, 0, length)) ||
match(dce->shortName, filename, direntry->name, 1, length))) {
return RES_NOMATCH;
}
/* entry of non-requested type, has to come after name
* checking because of clash handling */
if(IS_DIR(direntry) && !(flags & ACCEPT_DIR)) {
if(!(flags & (ACCEPT_LABEL|MATCH_ANY|NO_MSG))) {
char tmp[4*13+1];
wchar_to_native(dce->shortName,tmp,13);
fprintf(stderr, "Skipping \"%s\", is a directory\n",
tmp);
}
return RES_NOMATCH;
}
if(!(direntry->dir.attr & (ATTR_LABEL | ATTR_DIR)) &&
!(flags & ACCEPT_PLAIN)) {
if(!(flags & (ACCEPT_LABEL|MATCH_ANY|NO_MSG))) {
char tmp[4*13+1];
wchar_to_native(dce->shortName,tmp,13);
fprintf(stderr,
"Skipping \"%s\", is not a directory\n",
tmp);
}
return RES_NOMATCH;
}
return RES_MATCH;
}
/*
* vfat_lookup looks for filenames in directory dir.
* if a name if found, it is returned in outname
* if applicable, the file is opened and its stream is returned in File
*/
int vfat_lookup(direntry_t *direntry, const char *filename, int length,
int flags, char *shortname, char *longname)
{
dirCacheEntry_t *dce;
result_t result;
dirCache_t *cache;
int io_error;
wchar_t wfilename[MAX_VNAMELEN+1];
wchar_t *wfilenamep = wfilename;
doscp_t *cp = GET_DOSCONVERT(direntry->Dir);
if(length == -1 && filename)
length = strlen(filename);
if(filename != NULL)
length = native_to_wchar(filename, wfilename, MAX_VNAMELEN,
filename+length, 0);
else {
wfilenamep = NULL;
length = 0;
}
if (direntry->entry == -2)
return -1;
cache = allocDirCache(direntry->Dir, direntry->entry+1);
if(!cache) {
fprintf(stderr, "Out of memory error in vfat_lookup [0]\n");
exit(1);
}
do {
dce = vfat_lookup_loop_for_read(cp, direntry, cache, &io_error);
if(!dce) {
if (io_error)
return -2;
fprintf(stderr, "Out of memory error in vfat_lookup\n");
exit(1);
}
result = checkNameForMatch(direntry, dce,
wfilename,
length, flags);
} while(result == RES_NOMATCH);
if(result == RES_MATCH){
if(longname){
if(dce->longName)
wchar_to_native(dce->longName,
longname, MAX_VNAMELEN);
else
*longname ='\0';
}
if(shortname)
wchar_to_native(dce->shortName, shortname, 12);
direntry->beginSlot = dce->beginSlot;
direntry->endSlot = dce->endSlot-1;
return 0; /* file found */
} else {
direntry->entry = -2;
return -1; /* no file found */
}
}
static __inline__ dirCacheEntry_t *vfat_lookup_loop_for_insert(doscp_t *cp,
direntry_t *direntry,
int initpos,
dirCache_t *cache)
{
dirCacheEntry_t *dce;
int io_error;
dce = cache->entries[initpos];
if(dce && dce->type != DCET_END) {
return dce;
} else {
direntry->entry = initpos - 1;
dce = vfat_lookup_loop_common(cp,
direntry, cache, 1, &io_error);
if(!dce) {
if (io_error) {
return NULL;
}
fprintf(stderr,
"Out of memory error in vfat_lookup_loop\n");
exit(1);
}
return cache->entries[initpos];
}
}
static void accountFreeSlots(struct scan_state *ssp, dirCacheEntry_t *dce)
{
if(ssp->got_slots)
return;
if(ssp->free_end != dce->beginSlot) {
ssp->free_start = dce->beginSlot;
}
ssp->free_end = dce->endSlot;
if(ssp->free_end - ssp->free_start >= ssp->size_needed) {
ssp->got_slots = 1;
ssp->slot = ssp->free_start + ssp->size_needed - 1;
}
}
static void clear_scan(wchar_t *longname, int use_longname,
struct scan_state *s)
{
s->shortmatch = s->longmatch = s->slot = -1;
s->free_end = s->got_slots = s->free_start = 0;
if (use_longname & 1)
s->size_needed = 1 +
(wcslen(longname) + VSE_NAMELEN - 1)/VSE_NAMELEN;
else
s->size_needed = 1;
}
/* lookup_for_insert replaces the old scandir function. It directly
* calls into vfat_lookup_loop, thus eliminating the overhead of the
* normal vfat_lookup
*/
int lookupForInsert(Stream_t *Dir,
struct direntry_t *direntry,
dos_name_t *dosname,
char *longname,
struct scan_state *ssp,
int ignore_entry,
int source_entry,
int pessimisticShortRename,
int use_longname)
{
direntry_t entry;
int ignore_match;
dirCacheEntry_t *dce;
dirCache_t *cache;
int pos; /* position _before_ the next answered entry */
wchar_t shortName[13];
wchar_t wlongname[MAX_VNAMELEN+1];
doscp_t *cp = GET_DOSCONVERT(Dir);
native_to_wchar(longname, wlongname, MAX_VNAMELEN+1, 0, 0);
clear_scan(wlongname, use_longname, ssp);
ignore_match = (ignore_entry == -2 );
initializeDirentry(&entry, Dir);
ssp->match_free = 0;
/* hash bitmap of already encountered names. Speeds up batch appends
* to huge directories, because in the best case, we only need to scan
* the new entries rather than the whole directory */
cache = allocDirCache(Dir, 1);
if(!cache) {
fprintf(stderr, "Out of memory error in lookupForInsert\n");
exit(1);
}
if(!ignore_match)
unix_name(cp, dosname->base, dosname->ext, 0, shortName);
pos = cache->nrHashed;
if(source_entry >= 0 ||
(pos && isHashed(cache, wlongname))) {
pos = 0;
} else if(pos && !ignore_match && isHashed(cache, shortName)) {
if(pessimisticShortRename) {
ssp->shortmatch = -2;
return 1;
}
pos = 0;
} else if(growDirCache(cache, pos) < 0) {
fprintf(stderr, "Out of memory error in vfat_looup [0]\n");
exit(1);
}
do {
dce = vfat_lookup_loop_for_insert(cp, &entry, pos, cache);
switch(dce->type) {
case DCET_FREE:
accountFreeSlots(ssp, dce);
break;
case DCET_USED:
if(!(dce->dir.attr & 0x8) &&
(signed int)dce->endSlot-1 == source_entry)
accountFreeSlots(ssp, dce);
/* labels never match, neither does the
* ignored entry */
if( (dce->dir.attr & 0x8) ||
((signed int)dce->endSlot-1==ignore_entry))
break;
/* check long name */
if((dce->longName &&
!wcscasecmp(dce->longName, wlongname)) ||
(dce->shortName &&
!wcscasecmp(dce->shortName, wlongname))) {
ssp->longmatch = dce->endSlot - 1;
/* long match is a reason for
* immediate stop */
direntry->beginSlot = dce->beginSlot;
direntry->endSlot = dce->endSlot-1;
return 1;
}
/* Long name or not, always check for
* short name match */
if (!ignore_match &&
!wcscasecmp(shortName, dce->shortName))
ssp->shortmatch = dce->endSlot - 1;
break;
case DCET_END:
break;
}
pos = dce->endSlot;
} while(dce->type != DCET_END);
if (ssp->shortmatch > -1)
return 1;
ssp->max_entry = dce->beginSlot;
if (ssp->got_slots)
return 6; /* Success */
/* Need more room. Can we grow the directory? */
if(!isRootDir(Dir))
return 5; /* OK, try to grow the directory */
fprintf(stderr, "No directory slots\n");
return -1;
}
/* End vfat.c */
|
Distrotech/mtools
|
vfat.c
|
C
|
gpl-3.0
| 20,430
|
package Test::Protobuf;
use strict;
use warnings;
use base qw(Exporter);
use Test::More;
use Protobuf::Types;
our @EXPORT = qw(escaped bin_is);
sub escaped {
my $v = shift;
$v =~ s/([^[:print:]])/"\\x" . sprintf("%02x", ord($1))/eg if defined $v;
return $v;
}
sub bin_is ($$;$) {
my @args = @_;
foreach my $buf ( @args[0,1] ) { # copy because of readonly assignment
fail("found utf8 data") if utf8::is_utf8($buf);
$buf = escaped($buf);
}
@_ = @args;
goto \&is;
}
__PACKAGE__
__END__
|
vleo/vleo-notebook
|
protobuf/trunk/perl/t/lib/Test/Protobuf.pm
|
Perl
|
gpl-3.0
| 541
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* New messaging manager class.
*
* @package core_message
* @since Moodle 2.8
* @copyright 2014 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Petr Skoda <petr.skoda@totaralms.com>
*/
namespace core\message;
defined('MOODLE_INTERNAL') || die();
/**
* Class used for various messaging related stuff.
*
* Note: Do NOT use directly in your code, it is intended to be used from core code only.
*
* @access private
*
* @package core_message
* @since Moodle 2.8
* @copyright 2014 Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @author Petr Skoda <petr.skoda@totaralms.com>
*/
class manager {
/** @var array buffer of pending messages */
protected static $buffer = array();
/** @var array buffer of pending messages to conversations */
protected static $convmessagebuffer = array();
/**
* Used for calling processors, and generating event data when sending a message to a conversation.
*
* This is ONLY used for messages of type 'message' (notification=0), and is responsible for:
*
* 1. generation of per-user event data (to pass to processors)
* 2. generation of the processors for each recipient member of the conversation
* 3. calling said processors for each member, passing in the per-user (local) eventdata.
* 4. generation of an appropriate event for the message send, depending on the conversation type
* - messages to individual conversations generate a 'message_sent' event (as per legacy send_message())
* - messages to group conversations generate a 'group_message_sent' event.
*
* @param message $eventdata
* @param \stdClass $savemessage
* @return int
*/
public static function send_message_to_conversation(message $eventdata, \stdClass $savemessage) : int {
global $DB, $CFG, $SITE;
if (empty($eventdata->convid)) {
throw new \moodle_exception("Message is not being sent to a conversation. Please check event data.");
}
// Fetch default (site) preferences.
$defaultpreferences = get_message_output_default_preferences();
$preferencebase = $eventdata->component.'_'.$eventdata->name;
// Because we're dealing with multiple recipients, we need to send a localised (per-user) version of the eventdata to each
// processor, because of things like the language-specific subject. We're going to modify this, for each recipient member.
// Any time we're modifying the event data here, we should be using the localised version.
// This localised version is based on the generic event data, but we should keep that object intact, so we clone it.
$localisedeventdata = clone $eventdata;
// Get user records for all members of the conversation.
// We must fetch distinct users, because it's possible for a user to message themselves via bulk user actions.
// In such cases, there will be 2 records referring to the same user.
$sql = "SELECT u.*, mca.id as ismuted
FROM {user} u
LEFT JOIN {message_conversation_actions} mca
ON mca.userid = u.id AND mca.conversationid = ? AND mca.action = ?
WHERE u.id IN (
SELECT mcm.userid FROM {message_conversation_members} mcm
WHERE mcm.conversationid = ?
)";
$members = $DB->get_records_sql($sql, [$eventdata->convid, \core_message\api::CONVERSATION_ACTION_MUTED,
$eventdata->convid]);
if (empty($members)) {
throw new \moodle_exception("Conversation has no members or does not exist.");
}
if (!is_object($localisedeventdata->userfrom)) {
$localisedeventdata->userfrom = $members[$localisedeventdata->userfrom];
}
// This should now hold only the other users (recipients).
unset($members[$localisedeventdata->userfrom->id]);
$otherusers = $members;
// Get conversation type and name. We'll use this to determine which message subject to generate, depending on type.
$conv = $DB->get_record('message_conversations', ['id' => $eventdata->convid], 'id, type, name');
// We treat individual conversations the same as any direct message with 'userfrom' and 'userto' specified.
// We know the other user, so set the 'userto' field so that the event code will get access to this field.
// If this was a legacy caller (eventdata->userto is set), then use that instead, as we want to use the fields specified
// in that object instead of using one fetched from the DB.
$legacymessage = false;
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
if (isset($eventdata->userto)) {
$legacymessage = true;
} else {
$otheruser = reset($otherusers);
$eventdata->userto = $otheruser;
}
}
// Fetch enabled processors.
// If we are dealing with a message some processors may want to handle it regardless of user and site settings.
$processors = array_filter(get_message_processors(false), function($processor) {
if ($processor->object->force_process_messages()) {
return true;
}
return ($processor->enabled && $processor->configured);
});
// For each member of the conversation, other than the sender:
// 1. Set recipient specific event data (language specific, user prefs, etc)
// 2. Generate recipient specific processor list
// 3. Call send_message() to pass the message to processors and generate the relevant per-user events.
$eventprocmaps = []; // Init the event/processors buffer.
foreach ($otherusers as $recipient) {
// If this message was a legacy (1:1) message, then we use the userto.
if ($legacymessage) {
$ismuted = $recipient->ismuted;
$recipient = $eventdata->userto;
$recipient->ismuted = $ismuted;
}
$usertoisrealuser = (\core_user::is_real_user($recipient->id) != false);
// Using string manager directly so that strings in the message will be in the message recipients language rather than
// the sender's.
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL) {
$localisedeventdata->subject = get_string_manager()->get_string('unreadnewmessage', 'message',
fullname($localisedeventdata->userfrom), $recipient->lang);
} else if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
$stringdata = (object) ['name' => fullname($localisedeventdata->userfrom), 'conversationname' => $conv->name];
$localisedeventdata->subject = get_string_manager()->get_string('unreadnewgroupconversationmessage', 'message',
$stringdata, $recipient->lang);
}
// Spoof the userto based on the current member id.
$localisedeventdata->userto = $recipient;
$s = new \stdClass();
$s->sitename = format_string($SITE->shortname, true, array('context' => \context_course::instance(SITEID)));
$s->url = $CFG->wwwroot.'/message/index.php?id='.$eventdata->userfrom->id;
$emailtagline = get_string_manager()->get_string('emailtagline', 'message', $s, $recipient->lang);
$localisedeventdata->fullmessage = $eventdata->fullmessage;
$localisedeventdata->fullmessagehtml = $eventdata->fullmessagehtml;
if (!empty($localisedeventdata->fullmessage)) {
$localisedeventdata->fullmessage .= "\n\n---------------------------------------------------------------------\n"
. $emailtagline;
}
if (!empty($localisedeventdata->fullmessagehtml)) {
$localisedeventdata->fullmessagehtml .=
"<br><br>---------------------------------------------------------------------<br>" . $emailtagline;
}
// If recipient is internal user (noreply user), and emailstop is set then don't send any msg.
if (!$usertoisrealuser && !empty($recipient->emailstop)) {
debugging('Attempt to send msg to internal (noreply) user', DEBUG_NORMAL);
return false;
}
// Set the online state.
if (isset($CFG->block_online_users_timetosee)) {
$timetoshowusers = $CFG->block_online_users_timetosee * 60;
} else {
$timetoshowusers = 300;
}
// Work out if the user is logged in or not.
$userstate = 'loggedoff';
if (!empty($localisedeventdata->userto->lastaccess)
&& (time() - $timetoshowusers) < $localisedeventdata->userto->lastaccess) {
$userstate = 'loggedin';
}
// Fill in the array of processors to be used based on default and user preferences.
// This applies only to individual conversations. Messages to group conversations ignore processors.
// Do not process muted conversations.
$processorlist = [];
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_INDIVIDUAL && !$recipient->ismuted) {
foreach ($processors as $processor) {
// Skip adding processors for internal user, if processor doesn't support sending message to internal user.
if (!$usertoisrealuser && !$processor->object->can_send_to_any_users()) {
continue;
}
// First find out permissions.
$defaultpreference = $processor->name . '_provider_' . $preferencebase . '_permitted';
if (isset($defaultpreferences->{$defaultpreference})) {
$permitted = $defaultpreferences->{$defaultpreference};
} else {
// MDL-25114 They supplied an $eventdata->component $eventdata->name combination which doesn't
// exist in the message_provider table (thus there is no default settings for them).
$preferrormsg = "Could not load preference $defaultpreference. Make sure the component and name you supplied
to message_send() are valid.";
throw new coding_exception($preferrormsg);
}
// Find out if user has configured this output.
// Some processors cannot function without settings from the user.
$userisconfigured = $processor->object->is_user_configured($recipient);
// DEBUG: notify if we are forcing unconfigured output.
if ($permitted == 'forced' && !$userisconfigured) {
debugging('Attempt to force message delivery to user who has "' . $processor->name .
'" output unconfigured', DEBUG_NORMAL);
}
// Populate the list of processors we will be using.
if (!$eventdata->notification && $processor->object->force_process_messages()) {
$processorlist[] = $processor->name;
} else if ($permitted == 'forced' && $userisconfigured) {
// An admin is forcing users to use this message processor. Use this processor unconditionally.
$processorlist[] = $processor->name;
} else if ($permitted == 'permitted' && $userisconfigured && !$recipient->emailstop) {
// User has not disabled notifications.
// See if user set any notification preferences, otherwise use site default ones.
$userpreferencename = 'message_provider_' . $preferencebase . '_' . $userstate;
if ($userpreference = get_user_preferences($userpreferencename, null, $recipient)) {
if (in_array($processor->name, explode(',', $userpreference))) {
$processorlist[] = $processor->name;
}
} else if (isset($defaultpreferences->{$userpreferencename})) {
if (in_array($processor->name, explode(',', $defaultpreferences->{$userpreferencename}))) {
$processorlist[] = $processor->name;
}
}
}
}
}
// Batch up the localised event data and processor list for all users into a local buffer.
$eventprocmaps[] = [clone($localisedeventdata), $processorlist];
}
// Then pass it off as one item of work, to be processed by send_conversation_message_to_processors(), which will
// handle all transaction buffering logic.
self::send_conversation_message_to_processors($eventprocmaps, $eventdata, $savemessage);
return $savemessage->id;
}
/**
* Takes a list of localised event data, and tries to send them to their respective member's message processors.
*
* Input format:
* [CONVID => [$localisedeventdata, $savemessage, $processorlist], ].
*
* @param array $eventprocmaps the array of localised event data and processors for each member of the conversation.
* @param message $eventdata the original conversation message eventdata
* @param \stdClass $savemessage the saved message record.
* @throws \coding_exception
*/
protected static function send_conversation_message_to_processors(array $eventprocmaps, message $eventdata,
\stdClass $savemessage) {
global $DB;
// We cannot communicate with external systems in DB transactions,
// buffer the messages if necessary.
if ($DB->is_transaction_started()) {
// Buffer this group conversation message and it's record.
self::$convmessagebuffer[] = [$eventprocmaps, $eventdata, $savemessage];
return;
}
// Send each localised version of the event data to each member's respective processors.
foreach ($eventprocmaps as $eventprocmap) {
$eventdata = $eventprocmap[0];
$processorlist = $eventprocmap[1];
self::call_processors($eventdata, $processorlist);
}
// Trigger event for sending a message or notification - we need to do this before marking as read!
self::trigger_message_events($eventdata, $savemessage);
}
/**
* Do the message sending.
*
* NOTE: to be used from message_send() only.
*
* @param \core\message\message $eventdata fully prepared event data for processors
* @param \stdClass $savemessage the message saved in 'message' table
* @param array $processorlist list of processors for target user
* @return int $messageid the id from 'messages' (false is not returned)
*/
public static function send_message(message $eventdata, \stdClass $savemessage, array $processorlist) {
global $CFG;
require_once($CFG->dirroot.'/message/lib.php'); // This is most probably already included from messagelib.php file.
if (empty($processorlist)) {
// Trigger event for sending a message or notification - we need to do this before marking as read!
self::trigger_message_events($eventdata, $savemessage);
if ($eventdata->notification or empty($CFG->messaging)) {
// If they have deselected all processors and its a notification mark it read. The user doesn't want to be bothered.
// The same goes if the messaging is completely disabled.
if ($eventdata->notification) {
$savemessage->timeread = null;
\core_message\api::mark_notification_as_read($savemessage);
} else {
\core_message\api::mark_message_as_read($eventdata->userto->id, $savemessage);
}
}
return $savemessage->id;
}
// Let the manager do the sending or buffering when db transaction in progress.
return self::send_message_to_processors($eventdata, $savemessage, $processorlist);
}
/**
* Send message to message processors.
*
* @param \stdClass|\core\message\message $eventdata
* @param \stdClass $savemessage
* @param array $processorlist
* @return int $messageid
*/
protected static function send_message_to_processors($eventdata, \stdClass $savemessage, array
$processorlist) {
global $CFG, $DB;
// We cannot communicate with external systems in DB transactions,
// buffer the messages if necessary.
if ($DB->is_transaction_started()) {
// We need to clone all objects so that devs may not modify it from outside later.
$eventdata = clone($eventdata);
$eventdata->userto = clone($eventdata->userto);
$eventdata->userfrom = clone($eventdata->userfrom);
// Conserve some memory the same was as $USER setup does.
unset($eventdata->userto->description);
unset($eventdata->userfrom->description);
self::$buffer[] = array($eventdata, $savemessage, $processorlist);
return $savemessage->id;
}
// Send the message to processors.
self::call_processors($eventdata, $processorlist);
// Trigger event for sending a message or notification - we need to do this before marking as read!
self::trigger_message_events($eventdata, $savemessage);
if (empty($CFG->messaging)) {
// If they have deselected all processors and its a notification mark it read. The user doesn't want to be bothered.
// The same goes if the messaging is completely disabled.
if ($eventdata->notification) {
$savemessage->timeread = null;
\core_message\api::mark_notification_as_read($savemessage);
} else {
\core_message\api::mark_message_as_read($eventdata->userto->id, $savemessage);
}
}
return $savemessage->id;
}
/**
* Notification from DML layer.
*
* Note: to be used from DML layer only.
*/
public static function database_transaction_commited() {
if (!self::$buffer && !self::$convmessagebuffer) {
return;
}
self::process_buffer();
}
/**
* Notification from DML layer.
*
* Note: to be used from DML layer only.
*/
public static function database_transaction_rolledback() {
self::$buffer = array();
self::$convmessagebuffer = array();
}
/**
* Sent out any buffered messages if necessary.
*/
protected static function process_buffer() {
// Reset the buffers first in case we get exception from processor.
$messages = self::$buffer;
self::$buffer = array();
$convmessages = self::$convmessagebuffer;
self::$convmessagebuffer = array();
foreach ($messages as $message) {
list($eventdata, $savemessage, $processorlist) = $message;
self::send_message_to_processors($eventdata, $savemessage, $processorlist);
}
foreach ($convmessages as $convmessage) {
list($eventprocmap, $eventdata, $savemessage) = $convmessage;
self::send_conversation_message_to_processors($eventprocmap, $eventdata, $savemessage);
}
}
/**
* Trigger an appropriate message creation event, based on the supplied $eventdata and $savemessage.
*
* @param message $eventdata the eventdata for the message.
* @param \stdClass $savemessage the message record.
* @throws \coding_exception
*/
protected static function trigger_message_events(message $eventdata, \stdClass $savemessage) {
global $DB;
if ($eventdata->notification) {
\core\event\notification_sent::create_from_ids(
$eventdata->userfrom->id,
$eventdata->userto->id,
$savemessage->id,
$eventdata->courseid
)->trigger();
} else { // Must be a message.
// If the message is a group conversation, then trigger the 'group_message_sent' event.
if ($eventdata->convid) {
$conv = $DB->get_record('message_conversations', ['id' => $eventdata->convid], 'id, type');
if ($conv->type == \core_message\api::MESSAGE_CONVERSATION_TYPE_GROUP) {
\core\event\group_message_sent::create_from_ids(
$eventdata->userfrom->id,
$eventdata->convid,
$savemessage->id,
$eventdata->courseid
)->trigger();
return;
}
// Individual type conversations fall through to the default 'message_sent' event.
}
\core\event\message_sent::create_from_ids(
$eventdata->userfrom->id,
$eventdata->userto->id,
$savemessage->id,
$eventdata->courseid
)->trigger();
}
}
/**
* For each processor, call it's send_message() method.
*
* @param message $eventdata the message object.
* @param array $processorlist the list of processors for a single user.
*/
protected static function call_processors(message $eventdata, array $processorlist) {
foreach ($processorlist as $procname) {
// Let new messaging class add custom content based on the processor.
$proceventdata = ($eventdata instanceof message) ? $eventdata->get_eventobject_for_processor($procname) : $eventdata;
$stdproc = new \stdClass();
$stdproc->name = $procname;
$processor = \core_message\api::get_processed_processor_object($stdproc);
if (!$processor->object->send_message($proceventdata)) {
debugging('Error calling message processor ' . $procname);
}
}
}
}
|
ak4t0sh/moodle
|
lib/classes/message/manager.php
|
PHP
|
gpl-3.0
| 23,549
|
/****************************************************************************************************//**
* @file nRF51.h
*
* @brief CMSIS Cortex-M0 Peripheral Access Layer Header File for
* nRF51 from Nordic Semiconductor.
*
* @version V522
* @date 26. August 2014
*
* @note Generated with SVDConv V2.81d
* from CMSIS SVD File 'nRF51.xml' Version 522,
*
* @par Copyright (c) 2013, Nordic Semiconductor ASA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
*******************************************************************************************************/
/** @addtogroup Nordic Semiconductor
* @{
*/
/** @addtogroup nRF51
* @{
*/
#ifndef NRF51_H
#define NRF51_H
#ifdef __cplusplus
extern "C" {
#endif
/* ------------------------- Interrupt Number Definition ------------------------ */
typedef enum {
/* ------------------- Cortex-M0 Processor Exceptions Numbers ------------------- */
Reset_IRQn = -15, /*!< 1 Reset Vector, invoked on Power up and warm reset */
NonMaskableInt_IRQn = -14, /*!< 2 Non maskable Interrupt, cannot be stopped or preempted */
HardFault_IRQn = -13, /*!< 3 Hard Fault, all classes of Fault */
SVCall_IRQn = -5, /*!< 11 System Service Call via SVC instruction */
DebugMonitor_IRQn = -4, /*!< 12 Debug Monitor */
PendSV_IRQn = -2, /*!< 14 Pendable request for system service */
SysTick_IRQn = -1, /*!< 15 System Tick Timer */
/* ---------------------- nRF51 Specific Interrupt Numbers ---------------------- */
POWER_CLOCK_IRQn = 0, /*!< 0 POWER_CLOCK */
RADIO_IRQn = 1, /*!< 1 RADIO */
UART0_IRQn = 2, /*!< 2 UART0 */
SPI0_TWI0_IRQn = 3, /*!< 3 SPI0_TWI0 */
SPI1_TWI1_IRQn = 4, /*!< 4 SPI1_TWI1 */
GPIOTE_IRQn = 6, /*!< 6 GPIOTE */
ADC_IRQn = 7, /*!< 7 ADC */
TIMER0_IRQn = 8, /*!< 8 TIMER0 */
TIMER1_IRQn = 9, /*!< 9 TIMER1 */
TIMER2_IRQn = 10, /*!< 10 TIMER2 */
RTC0_IRQn = 11, /*!< 11 RTC0 */
TEMP_IRQn = 12, /*!< 12 TEMP */
RNG_IRQn = 13, /*!< 13 RNG */
ECB_IRQn = 14, /*!< 14 ECB */
CCM_AAR_IRQn = 15, /*!< 15 CCM_AAR */
WDT_IRQn = 16, /*!< 16 WDT */
RTC1_IRQn = 17, /*!< 17 RTC1 */
QDEC_IRQn = 18, /*!< 18 QDEC */
LPCOMP_IRQn = 19, /*!< 19 LPCOMP */
SWI0_IRQn = 20, /*!< 20 SWI0 */
SWI1_IRQn = 21, /*!< 21 SWI1 */
SWI2_IRQn = 22, /*!< 22 SWI2 */
SWI3_IRQn = 23, /*!< 23 SWI3 */
SWI4_IRQn = 24, /*!< 24 SWI4 */
SWI5_IRQn = 25 /*!< 25 SWI5 */
} IRQn_Type;
/** @addtogroup Configuration_of_CMSIS
* @{
*/
/* ================================================================================ */
/* ================ Processor and Core Peripheral Section ================ */
/* ================================================================================ */
/* ----------------Configuration of the Cortex-M0 Processor and Core Peripherals---------------- */
#define __CM0_REV 0x0301 /*!< Cortex-M0 Core Revision */
#define __MPU_PRESENT 0 /*!< MPU present or not */
#define __NVIC_PRIO_BITS 2 /*!< Number of Bits used for Priority Levels */
#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */
/** @} */ /* End of group Configuration_of_CMSIS */
#include "core_cm0.h" /*!< Cortex-M0 processor and core peripherals */
#include "system_nrf51.h" /*!< nRF51 System */
/* ================================================================================ */
/* ================ Device Specific Peripheral Section ================ */
/* ================================================================================ */
/** @addtogroup Device_Peripheral_Registers
* @{
*/
/* ------------------- Start of section using anonymous unions ------------------ */
#if defined(__CC_ARM)
#pragma push
#pragma anon_unions
#elif defined(__ICCARM__)
#pragma language=extended
#elif defined(__GNUC__)
/* anonymous unions are enabled by default */
#elif defined(__TMS470__)
/* anonymous unions are enabled by default */
#elif defined(__TASKING__)
#pragma warning 586
#else
#warning Not supported compiler type
#endif
typedef struct {
__IO uint32_t CPU0; /*!< Configurable priority configuration register for CPU0. */
__IO uint32_t SPIS1; /*!< Configurable priority configuration register for SPIS1. */
__IO uint32_t RADIO; /*!< Configurable priority configuration register for RADIO. */
__IO uint32_t ECB; /*!< Configurable priority configuration register for ECB. */
__IO uint32_t CCM; /*!< Configurable priority configuration register for CCM. */
__IO uint32_t AAR; /*!< Configurable priority configuration register for AAR. */
} AMLI_RAMPRI_Type;
typedef struct {
__O uint32_t EN; /*!< Enable channel group. */
__O uint32_t DIS; /*!< Disable channel group. */
} PPI_TASKS_CHG_Type;
typedef struct {
__IO uint32_t EEP; /*!< Channel event end-point. */
__IO uint32_t TEP; /*!< Channel task end-point. */
} PPI_CH_Type;
/* ================================================================================ */
/* ================ POWER ================ */
/* ================================================================================ */
/**
* @brief Power Control. (POWER)
*/
typedef struct { /*!< POWER Structure */
__I uint32_t RESERVED0[30];
__O uint32_t TASKS_CONSTLAT; /*!< Enable constant latency mode. */
__O uint32_t TASKS_LOWPWR; /*!< Enable low power mode (variable latency). */
__I uint32_t RESERVED1[34];
__IO uint32_t EVENTS_POFWARN; /*!< Power failure warning. */
__I uint32_t RESERVED2[126];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[61];
__IO uint32_t RESETREAS; /*!< Reset reason. */
__I uint32_t RESERVED4[9];
__I uint32_t RAMSTATUS; /*!< Ram status register. */
__I uint32_t RESERVED5[53];
__O uint32_t SYSTEMOFF; /*!< System off register. */
__I uint32_t RESERVED6[3];
__IO uint32_t POFCON; /*!< Power failure configuration. */
__I uint32_t RESERVED7[2];
__IO uint32_t GPREGRET; /*!< General purpose retention register. This register is a retained
register. */
__I uint32_t RESERVED8;
__IO uint32_t RAMON; /*!< Ram on/off. */
__I uint32_t RESERVED9[7];
__IO uint32_t RESET; /*!< Pin reset functionality configuration register. This register
is a retained register. */
__I uint32_t RESERVED10[3];
__IO uint32_t RAMONB; /*!< Ram on/off. */
__I uint32_t RESERVED11[8];
__IO uint32_t DCDCEN; /*!< DCDC converter enable configuration register. */
__I uint32_t RESERVED12[291];
__IO uint32_t DCDCFORCE; /*!< DCDC power-up force register. */
} NRF_POWER_Type;
/* ================================================================================ */
/* ================ CLOCK ================ */
/* ================================================================================ */
/**
* @brief Clock control. (CLOCK)
*/
typedef struct { /*!< CLOCK Structure */
__O uint32_t TASKS_HFCLKSTART; /*!< Start HFCLK clock source. */
__O uint32_t TASKS_HFCLKSTOP; /*!< Stop HFCLK clock source. */
__O uint32_t TASKS_LFCLKSTART; /*!< Start LFCLK clock source. */
__O uint32_t TASKS_LFCLKSTOP; /*!< Stop LFCLK clock source. */
__O uint32_t TASKS_CAL; /*!< Start calibration of LFCLK RC oscillator. */
__O uint32_t TASKS_CTSTART; /*!< Start calibration timer. */
__O uint32_t TASKS_CTSTOP; /*!< Stop calibration timer. */
__I uint32_t RESERVED0[57];
__IO uint32_t EVENTS_HFCLKSTARTED; /*!< HFCLK oscillator started. */
__IO uint32_t EVENTS_LFCLKSTARTED; /*!< LFCLK oscillator started. */
__I uint32_t RESERVED1;
__IO uint32_t EVENTS_DONE; /*!< Calibration of LFCLK RC oscillator completed. */
__IO uint32_t EVENTS_CTTO; /*!< Calibration timer timeout. */
__I uint32_t RESERVED2[124];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[63];
__I uint32_t HFCLKRUN; /*!< Task HFCLKSTART trigger status. */
__I uint32_t HFCLKSTAT; /*!< High frequency clock status. */
__I uint32_t RESERVED4;
__I uint32_t LFCLKRUN; /*!< Task LFCLKSTART triggered status. */
__I uint32_t LFCLKSTAT; /*!< Low frequency clock status. */
__I uint32_t LFCLKSRCCOPY; /*!< Clock source for the LFCLK clock, set when task LKCLKSTART is
triggered. */
__I uint32_t RESERVED5[62];
__IO uint32_t LFCLKSRC; /*!< Clock source for the LFCLK clock. */
__I uint32_t RESERVED6[7];
__IO uint32_t CTIV; /*!< Calibration timer interval. */
__I uint32_t RESERVED7[5];
__IO uint32_t XTALFREQ; /*!< Crystal frequency. */
} NRF_CLOCK_Type;
/* ================================================================================ */
/* ================ MPU ================ */
/* ================================================================================ */
/**
* @brief Memory Protection Unit. (MPU)
*/
typedef struct { /*!< MPU Structure */
__I uint32_t RESERVED0[330];
__IO uint32_t PERR0; /*!< Configuration of peripherals in mpu regions. */
__IO uint32_t RLENR0; /*!< Length of RAM region 0. */
__I uint32_t RESERVED1[52];
__IO uint32_t PROTENSET0; /*!< Erase and write protection bit enable set register. */
__IO uint32_t PROTENSET1; /*!< Erase and write protection bit enable set register. */
__IO uint32_t DISABLEINDEBUG; /*!< Disable erase and write protection mechanism in debug mode. */
__IO uint32_t PROTBLOCKSIZE; /*!< Erase and write protection block size. */
} NRF_MPU_Type;
/* ================================================================================ */
/* ================ PU ================ */
/* ================================================================================ */
/**
* @brief Patch unit. (PU)
*/
typedef struct { /*!< PU Structure */
__I uint32_t RESERVED0[448];
__IO uint32_t REPLACEADDR[8]; /*!< Address of first instruction to replace. */
__I uint32_t RESERVED1[24];
__IO uint32_t PATCHADDR[8]; /*!< Relative address of patch instructions. */
__I uint32_t RESERVED2[24];
__IO uint32_t PATCHEN; /*!< Patch enable register. */
__IO uint32_t PATCHENSET; /*!< Patch enable register. */
__IO uint32_t PATCHENCLR; /*!< Patch disable register. */
} NRF_PU_Type;
/* ================================================================================ */
/* ================ AMLI ================ */
/* ================================================================================ */
/**
* @brief AHB Multi-Layer Interface. (AMLI)
*/
typedef struct { /*!< AMLI Structure */
__I uint32_t RESERVED0[896];
AMLI_RAMPRI_Type RAMPRI; /*!< RAM configurable priority configuration structure. */
} NRF_AMLI_Type;
/* ================================================================================ */
/* ================ RADIO ================ */
/* ================================================================================ */
/**
* @brief The radio. (RADIO)
*/
typedef struct { /*!< RADIO Structure */
__O uint32_t TASKS_TXEN; /*!< Enable radio in TX mode. */
__O uint32_t TASKS_RXEN; /*!< Enable radio in RX mode. */
__O uint32_t TASKS_START; /*!< Start radio. */
__O uint32_t TASKS_STOP; /*!< Stop radio. */
__O uint32_t TASKS_DISABLE; /*!< Disable radio. */
__O uint32_t TASKS_RSSISTART; /*!< Start the RSSI and take one sample of the receive signal strength. */
__O uint32_t TASKS_RSSISTOP; /*!< Stop the RSSI measurement. */
__O uint32_t TASKS_BCSTART; /*!< Start the bit counter. */
__O uint32_t TASKS_BCSTOP; /*!< Stop the bit counter. */
__I uint32_t RESERVED0[55];
__IO uint32_t EVENTS_READY; /*!< Ready event. */
__IO uint32_t EVENTS_ADDRESS; /*!< Address event. */
__IO uint32_t EVENTS_PAYLOAD; /*!< Payload event. */
__IO uint32_t EVENTS_END; /*!< End event. */
__IO uint32_t EVENTS_DISABLED; /*!< Disable event. */
__IO uint32_t EVENTS_DEVMATCH; /*!< A device address match occurred on the last received packet. */
__IO uint32_t EVENTS_DEVMISS; /*!< No device address match occurred on the last received packet. */
__IO uint32_t EVENTS_RSSIEND; /*!< Sampling of the receive signal strength complete. A new RSSI
sample is ready for readout at the RSSISAMPLE register. */
__I uint32_t RESERVED1[2];
__IO uint32_t EVENTS_BCMATCH; /*!< Bit counter reached bit count value specified in BC register. */
__I uint32_t RESERVED2[53];
__IO uint32_t SHORTS; /*!< Shortcuts for the radio. */
__I uint32_t RESERVED3[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED4[61];
__I uint32_t CRCSTATUS; /*!< CRC status of received packet. */
__I uint32_t CD; /*!< Carrier detect. */
__I uint32_t RXMATCH; /*!< Received address. */
__I uint32_t RXCRC; /*!< Received CRC. */
__I uint32_t DAI; /*!< Device address match index. */
__I uint32_t RESERVED5[60];
__IO uint32_t PACKETPTR; /*!< Packet pointer. Decision point: START task. */
__IO uint32_t FREQUENCY; /*!< Frequency. */
__IO uint32_t TXPOWER; /*!< Output power. */
__IO uint32_t MODE; /*!< Data rate and modulation. */
__IO uint32_t PCNF0; /*!< Packet configuration 0. */
__IO uint32_t PCNF1; /*!< Packet configuration 1. */
__IO uint32_t BASE0; /*!< Radio base address 0. Decision point: START task. */
__IO uint32_t BASE1; /*!< Radio base address 1. Decision point: START task. */
__IO uint32_t PREFIX0; /*!< Prefixes bytes for logical addresses 0 to 3. */
__IO uint32_t PREFIX1; /*!< Prefixes bytes for logical addresses 4 to 7. */
__IO uint32_t TXADDRESS; /*!< Transmit address select. */
__IO uint32_t RXADDRESSES; /*!< Receive address select. */
__IO uint32_t CRCCNF; /*!< CRC configuration. */
__IO uint32_t CRCPOLY; /*!< CRC polynomial. */
__IO uint32_t CRCINIT; /*!< CRC initial value. */
__IO uint32_t TEST; /*!< Test features enable register. */
__IO uint32_t TIFS; /*!< Inter Frame Spacing in microseconds. */
__I uint32_t RSSISAMPLE; /*!< RSSI sample. */
__I uint32_t RESERVED6;
__I uint32_t STATE; /*!< Current radio state. */
__IO uint32_t DATAWHITEIV; /*!< Data whitening initial value. */
__I uint32_t RESERVED7[2];
__IO uint32_t BCC; /*!< Bit counter compare. */
__I uint32_t RESERVED8[39];
__IO uint32_t DAB[8]; /*!< Device address base segment. */
__IO uint32_t DAP[8]; /*!< Device address prefix. */
__IO uint32_t DACNF; /*!< Device address match configuration. */
__I uint32_t RESERVED9[56];
__IO uint32_t OVERRIDE0; /*!< Trim value override register 0. */
__IO uint32_t OVERRIDE1; /*!< Trim value override register 1. */
__IO uint32_t OVERRIDE2; /*!< Trim value override register 2. */
__IO uint32_t OVERRIDE3; /*!< Trim value override register 3. */
__IO uint32_t OVERRIDE4; /*!< Trim value override register 4. */
__I uint32_t RESERVED10[561];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_RADIO_Type;
/* ================================================================================ */
/* ================ UART ================ */
/* ================================================================================ */
/**
* @brief Universal Asynchronous Receiver/Transmitter. (UART)
*/
typedef struct { /*!< UART Structure */
__O uint32_t TASKS_STARTRX; /*!< Start UART receiver. */
__O uint32_t TASKS_STOPRX; /*!< Stop UART receiver. */
__O uint32_t TASKS_STARTTX; /*!< Start UART transmitter. */
__O uint32_t TASKS_STOPTX; /*!< Stop UART transmitter. */
__I uint32_t RESERVED0[3];
__O uint32_t TASKS_SUSPEND; /*!< Suspend UART. */
__I uint32_t RESERVED1[56];
__IO uint32_t EVENTS_CTS; /*!< CTS activated. */
__IO uint32_t EVENTS_NCTS; /*!< CTS deactivated. */
__IO uint32_t EVENTS_RXDRDY; /*!< Data received in RXD. */
__I uint32_t RESERVED2[4];
__IO uint32_t EVENTS_TXDRDY; /*!< Data sent from TXD. */
__I uint32_t RESERVED3;
__IO uint32_t EVENTS_ERROR; /*!< Error detected. */
__I uint32_t RESERVED4[7];
__IO uint32_t EVENTS_RXTO; /*!< Receiver timeout. */
__I uint32_t RESERVED5[46];
__IO uint32_t SHORTS; /*!< Shortcuts for UART. */
__I uint32_t RESERVED6[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED7[93];
__IO uint32_t ERRORSRC; /*!< Error source. Write error field to 1 to clear error. */
__I uint32_t RESERVED8[31];
__IO uint32_t ENABLE; /*!< Enable UART and acquire IOs. */
__I uint32_t RESERVED9;
__IO uint32_t PSELRTS; /*!< Pin select for RTS. */
__IO uint32_t PSELTXD; /*!< Pin select for TXD. */
__IO uint32_t PSELCTS; /*!< Pin select for CTS. */
__IO uint32_t PSELRXD; /*!< Pin select for RXD. */
__I uint32_t RXD; /*!< RXD register. On read action the buffer pointer is displaced.
Once read the character is consumed. If read when no character
available, the UART will stop working. */
__O uint32_t TXD; /*!< TXD register. */
__I uint32_t RESERVED10;
__IO uint32_t BAUDRATE; /*!< UART Baudrate. */
__I uint32_t RESERVED11[17];
__IO uint32_t CONFIG; /*!< Configuration of parity and hardware flow control register. */
__I uint32_t RESERVED12[675];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_UART_Type;
/* ================================================================================ */
/* ================ SPI ================ */
/* ================================================================================ */
/**
* @brief SPI master 0. (SPI)
*/
typedef struct { /*!< SPI Structure */
__I uint32_t RESERVED0[66];
__IO uint32_t EVENTS_READY; /*!< TXD byte sent and RXD byte received. */
__I uint32_t RESERVED1[126];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED2[125];
__IO uint32_t ENABLE; /*!< Enable SPI. */
__I uint32_t RESERVED3;
__IO uint32_t PSELSCK; /*!< Pin select for SCK. */
__IO uint32_t PSELMOSI; /*!< Pin select for MOSI. */
__IO uint32_t PSELMISO; /*!< Pin select for MISO. */
__I uint32_t RESERVED4;
__I uint32_t RXD; /*!< RX data. */
__IO uint32_t TXD; /*!< TX data. */
__I uint32_t RESERVED5;
__IO uint32_t FREQUENCY; /*!< SPI frequency */
__I uint32_t RESERVED6[11];
__IO uint32_t CONFIG; /*!< Configuration register. */
__I uint32_t RESERVED7[681];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_SPI_Type;
/* ================================================================================ */
/* ================ TWI ================ */
/* ================================================================================ */
/**
* @brief Two-wire interface master 0. (TWI)
*/
typedef struct { /*!< TWI Structure */
__O uint32_t TASKS_STARTRX; /*!< Start 2-Wire master receive sequence. */
__I uint32_t RESERVED0;
__O uint32_t TASKS_STARTTX; /*!< Start 2-Wire master transmit sequence. */
__I uint32_t RESERVED1[2];
__O uint32_t TASKS_STOP; /*!< Stop 2-Wire transaction. */
__I uint32_t RESERVED2;
__O uint32_t TASKS_SUSPEND; /*!< Suspend 2-Wire transaction. */
__O uint32_t TASKS_RESUME; /*!< Resume 2-Wire transaction. */
__I uint32_t RESERVED3[56];
__IO uint32_t EVENTS_STOPPED; /*!< Two-wire stopped. */
__IO uint32_t EVENTS_RXDREADY; /*!< Two-wire ready to deliver new RXD byte received. */
__I uint32_t RESERVED4[4];
__IO uint32_t EVENTS_TXDSENT; /*!< Two-wire finished sending last TXD byte. */
__I uint32_t RESERVED5;
__IO uint32_t EVENTS_ERROR; /*!< Two-wire error detected. */
__I uint32_t RESERVED6[4];
__IO uint32_t EVENTS_BB; /*!< Two-wire byte boundary. */
__I uint32_t RESERVED7[3];
__IO uint32_t EVENTS_SUSPENDED; /*!< Two-wire suspended. */
__I uint32_t RESERVED8[45];
__IO uint32_t SHORTS; /*!< Shortcuts for TWI. */
__I uint32_t RESERVED9[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED10[110];
__IO uint32_t ERRORSRC; /*!< Two-wire error source. Write error field to 1 to clear error. */
__I uint32_t RESERVED11[14];
__IO uint32_t ENABLE; /*!< Enable two-wire master. */
__I uint32_t RESERVED12;
__IO uint32_t PSELSCL; /*!< Pin select for SCL. */
__IO uint32_t PSELSDA; /*!< Pin select for SDA. */
__I uint32_t RESERVED13[2];
__I uint32_t RXD; /*!< RX data register. */
__IO uint32_t TXD; /*!< TX data register. */
__I uint32_t RESERVED14;
__IO uint32_t FREQUENCY; /*!< Two-wire frequency. */
__I uint32_t RESERVED15[24];
__IO uint32_t ADDRESS; /*!< Address used in the two-wire transfer. */
__I uint32_t RESERVED16[668];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_TWI_Type;
/* ================================================================================ */
/* ================ SPIS ================ */
/* ================================================================================ */
/**
* @brief SPI slave 1. (SPIS)
*/
typedef struct { /*!< SPIS Structure */
__I uint32_t RESERVED0[9];
__O uint32_t TASKS_ACQUIRE; /*!< Acquire SPI semaphore. */
__O uint32_t TASKS_RELEASE; /*!< Release SPI semaphore. */
__I uint32_t RESERVED1[54];
__IO uint32_t EVENTS_END; /*!< Granted transaction completed. */
__I uint32_t RESERVED2[8];
__IO uint32_t EVENTS_ACQUIRED; /*!< Semaphore acquired. */
__I uint32_t RESERVED3[53];
__IO uint32_t SHORTS; /*!< Shortcuts for SPIS. */
__I uint32_t RESERVED4[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED5[61];
__I uint32_t SEMSTAT; /*!< Semaphore status. */
__I uint32_t RESERVED6[15];
__IO uint32_t STATUS; /*!< Status from last transaction. */
__I uint32_t RESERVED7[47];
__IO uint32_t ENABLE; /*!< Enable SPIS. */
__I uint32_t RESERVED8;
__IO uint32_t PSELSCK; /*!< Pin select for SCK. */
__IO uint32_t PSELMISO; /*!< Pin select for MISO. */
__IO uint32_t PSELMOSI; /*!< Pin select for MOSI. */
__IO uint32_t PSELCSN; /*!< Pin select for CSN. */
__I uint32_t RESERVED9[7];
__IO uint32_t RXDPTR; /*!< RX data pointer. */
__IO uint32_t MAXRX; /*!< Maximum number of bytes in the receive buffer. */
__I uint32_t AMOUNTRX; /*!< Number of bytes received in last granted transaction. */
__I uint32_t RESERVED10;
__IO uint32_t TXDPTR; /*!< TX data pointer. */
__IO uint32_t MAXTX; /*!< Maximum number of bytes in the transmit buffer. */
__I uint32_t AMOUNTTX; /*!< Number of bytes transmitted in last granted transaction. */
__I uint32_t RESERVED11;
__IO uint32_t CONFIG; /*!< Configuration register. */
__I uint32_t RESERVED12;
__IO uint32_t DEF; /*!< Default character. */
__I uint32_t RESERVED13[24];
__IO uint32_t ORC; /*!< Over-read character. */
__I uint32_t RESERVED14[654];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_SPIS_Type;
/* ================================================================================ */
/* ================ GPIOTE ================ */
/* ================================================================================ */
/**
* @brief GPIO tasks and events. (GPIOTE)
*/
typedef struct { /*!< GPIOTE Structure */
__O uint32_t TASKS_OUT[4]; /*!< Tasks asssociated with GPIOTE channels. */
__I uint32_t RESERVED0[60];
__IO uint32_t EVENTS_IN[4]; /*!< Tasks asssociated with GPIOTE channels. */
__I uint32_t RESERVED1[27];
__IO uint32_t EVENTS_PORT; /*!< Event generated from multiple pins. */
__I uint32_t RESERVED2[97];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[129];
__IO uint32_t CONFIG[4]; /*!< Channel configuration registers. */
__I uint32_t RESERVED4[695];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_GPIOTE_Type;
/* ================================================================================ */
/* ================ ADC ================ */
/* ================================================================================ */
/**
* @brief Analog to digital converter. (ADC)
*/
typedef struct { /*!< ADC Structure */
__O uint32_t TASKS_START; /*!< Start an ADC conversion. */
__O uint32_t TASKS_STOP; /*!< Stop ADC. */
__I uint32_t RESERVED0[62];
__IO uint32_t EVENTS_END; /*!< ADC conversion complete. */
__I uint32_t RESERVED1[128];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED2[61];
__I uint32_t BUSY; /*!< ADC busy register. */
__I uint32_t RESERVED3[63];
__IO uint32_t ENABLE; /*!< ADC enable. */
__IO uint32_t CONFIG; /*!< ADC configuration register. */
__I uint32_t RESULT; /*!< Result of ADC conversion. */
__I uint32_t RESERVED4[700];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_ADC_Type;
/* ================================================================================ */
/* ================ TIMER ================ */
/* ================================================================================ */
/**
* @brief Timer 0. (TIMER)
*/
typedef struct { /*!< TIMER Structure */
__O uint32_t TASKS_START; /*!< Start Timer. */
__O uint32_t TASKS_STOP; /*!< Stop Timer. */
__O uint32_t TASKS_COUNT; /*!< Increment Timer (In counter mode). */
__O uint32_t TASKS_CLEAR; /*!< Clear timer. */
__O uint32_t TASKS_SHUTDOWN; /*!< Shutdown timer. */
__I uint32_t RESERVED0[11];
__O uint32_t TASKS_CAPTURE[4]; /*!< Capture Timer value to CC[n] registers. */
__I uint32_t RESERVED1[60];
__IO uint32_t EVENTS_COMPARE[4]; /*!< Compare event on CC[n] match. */
__I uint32_t RESERVED2[44];
__IO uint32_t SHORTS; /*!< Shortcuts for Timer. */
__I uint32_t RESERVED3[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED4[126];
__IO uint32_t MODE; /*!< Timer Mode selection. */
__IO uint32_t BITMODE; /*!< Sets timer behaviour. */
__I uint32_t RESERVED5;
__IO uint32_t PRESCALER; /*!< 4-bit prescaler to source clock frequency (max value 9). Source
clock frequency is divided by 2^SCALE. */
__I uint32_t RESERVED6[11];
__IO uint32_t CC[4]; /*!< Capture/compare registers. */
__I uint32_t RESERVED7[683];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_TIMER_Type;
/* ================================================================================ */
/* ================ RTC ================ */
/* ================================================================================ */
/**
* @brief Real time counter 0. (RTC)
*/
typedef struct { /*!< RTC Structure */
__O uint32_t TASKS_START; /*!< Start RTC Counter. */
__O uint32_t TASKS_STOP; /*!< Stop RTC Counter. */
__O uint32_t TASKS_CLEAR; /*!< Clear RTC Counter. */
__O uint32_t TASKS_TRIGOVRFLW; /*!< Set COUNTER to 0xFFFFFFF0. */
__I uint32_t RESERVED0[60];
__IO uint32_t EVENTS_TICK; /*!< Event on COUNTER increment. */
__IO uint32_t EVENTS_OVRFLW; /*!< Event on COUNTER overflow. */
__I uint32_t RESERVED1[14];
__IO uint32_t EVENTS_COMPARE[4]; /*!< Compare event on CC[n] match. */
__I uint32_t RESERVED2[109];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[13];
__IO uint32_t EVTEN; /*!< Configures event enable routing to PPI for each RTC event. */
__IO uint32_t EVTENSET; /*!< Enable events routing to PPI. The reading of this register gives
the value of EVTEN. */
__IO uint32_t EVTENCLR; /*!< Disable events routing to PPI. The reading of this register
gives the value of EVTEN. */
__I uint32_t RESERVED4[110];
__I uint32_t COUNTER; /*!< Current COUNTER value. */
__IO uint32_t PRESCALER; /*!< 12-bit prescaler for COUNTER frequency (32768/(PRESCALER+1)).
Must be written when RTC is STOPed. */
__I uint32_t RESERVED5[13];
__IO uint32_t CC[4]; /*!< Capture/compare registers. */
__I uint32_t RESERVED6[683];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_RTC_Type;
/* ================================================================================ */
/* ================ TEMP ================ */
/* ================================================================================ */
/**
* @brief Temperature Sensor. (TEMP)
*/
typedef struct { /*!< TEMP Structure */
__O uint32_t TASKS_START; /*!< Start temperature measurement. */
__O uint32_t TASKS_STOP; /*!< Stop temperature measurement. */
__I uint32_t RESERVED0[62];
__IO uint32_t EVENTS_DATARDY; /*!< Temperature measurement complete, data ready event. */
__I uint32_t RESERVED1[128];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED2[127];
__I int32_t TEMP; /*!< Die temperature in degC, 2's complement format, 0.25 degC pecision. */
__I uint32_t RESERVED3[700];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_TEMP_Type;
/* ================================================================================ */
/* ================ RNG ================ */
/* ================================================================================ */
/**
* @brief Random Number Generator. (RNG)
*/
typedef struct { /*!< RNG Structure */
__O uint32_t TASKS_START; /*!< Start the random number generator. */
__O uint32_t TASKS_STOP; /*!< Stop the random number generator. */
__I uint32_t RESERVED0[62];
__IO uint32_t EVENTS_VALRDY; /*!< New random number generated and written to VALUE register. */
__I uint32_t RESERVED1[63];
__IO uint32_t SHORTS; /*!< Shortcuts for the RNG. */
__I uint32_t RESERVED2[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register */
__I uint32_t RESERVED3[126];
__IO uint32_t CONFIG; /*!< Configuration register. */
__I uint32_t VALUE; /*!< RNG random number. */
__I uint32_t RESERVED4[700];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_RNG_Type;
/* ================================================================================ */
/* ================ ECB ================ */
/* ================================================================================ */
/**
* @brief AES ECB Mode Encryption. (ECB)
*/
typedef struct { /*!< ECB Structure */
__O uint32_t TASKS_STARTECB; /*!< Start ECB block encrypt. If a crypto operation is running, this
will not initiate a new encryption and the ERRORECB event will
be triggered. */
__O uint32_t TASKS_STOPECB; /*!< Stop current ECB encryption. If a crypto operation is running,
this will will trigger the ERRORECB event. */
__I uint32_t RESERVED0[62];
__IO uint32_t EVENTS_ENDECB; /*!< ECB block encrypt complete. */
__IO uint32_t EVENTS_ERRORECB; /*!< ECB block encrypt aborted due to a STOPECB task or due to an
error. */
__I uint32_t RESERVED1[127];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED2[126];
__IO uint32_t ECBDATAPTR; /*!< ECB block encrypt memory pointer. */
__I uint32_t RESERVED3[701];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_ECB_Type;
/* ================================================================================ */
/* ================ AAR ================ */
/* ================================================================================ */
/**
* @brief Accelerated Address Resolver. (AAR)
*/
typedef struct { /*!< AAR Structure */
__O uint32_t TASKS_START; /*!< Start resolving addresses based on IRKs specified in the IRK
data structure. */
__I uint32_t RESERVED0;
__O uint32_t TASKS_STOP; /*!< Stop resolving addresses. */
__I uint32_t RESERVED1[61];
__IO uint32_t EVENTS_END; /*!< Address resolution procedure completed. */
__IO uint32_t EVENTS_RESOLVED; /*!< Address resolved. */
__IO uint32_t EVENTS_NOTRESOLVED; /*!< Address not resolved. */
__I uint32_t RESERVED2[126];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[61];
__I uint32_t STATUS; /*!< Resolution status. */
__I uint32_t RESERVED4[63];
__IO uint32_t ENABLE; /*!< Enable AAR. */
__IO uint32_t NIRK; /*!< Number of Identity root Keys in the IRK data structure. */
__IO uint32_t IRKPTR; /*!< Pointer to the IRK data structure. */
__I uint32_t RESERVED5;
__IO uint32_t ADDRPTR; /*!< Pointer to the resolvable address (6 bytes). */
__IO uint32_t SCRATCHPTR; /*!< Pointer to a "scratch" data area used for temporary storage
during resolution. A minimum of 3 bytes must be reserved. */
__I uint32_t RESERVED6[697];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_AAR_Type;
/* ================================================================================ */
/* ================ CCM ================ */
/* ================================================================================ */
/**
* @brief AES CCM Mode Encryption. (CCM)
*/
typedef struct { /*!< CCM Structure */
__O uint32_t TASKS_KSGEN; /*!< Start generation of key-stream. This operation will stop by
itself when completed. */
__O uint32_t TASKS_CRYPT; /*!< Start encrypt/decrypt. This operation will stop by itself when
completed. */
__O uint32_t TASKS_STOP; /*!< Stop encrypt/decrypt. */
__I uint32_t RESERVED0[61];
__IO uint32_t EVENTS_ENDKSGEN; /*!< Keystream generation completed. */
__IO uint32_t EVENTS_ENDCRYPT; /*!< Encrypt/decrypt completed. */
__IO uint32_t EVENTS_ERROR; /*!< Error happened. */
__I uint32_t RESERVED1[61];
__IO uint32_t SHORTS; /*!< Shortcuts for the CCM. */
__I uint32_t RESERVED2[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[61];
__I uint32_t MICSTATUS; /*!< CCM RX MIC check result. */
__I uint32_t RESERVED4[63];
__IO uint32_t ENABLE; /*!< CCM enable. */
__IO uint32_t MODE; /*!< Operation mode. */
__IO uint32_t CNFPTR; /*!< Pointer to a data structure holding AES key and NONCE vector. */
__IO uint32_t INPTR; /*!< Pointer to the input packet. */
__IO uint32_t OUTPTR; /*!< Pointer to the output packet. */
__IO uint32_t SCRATCHPTR; /*!< Pointer to a "scratch" data area used for temporary storage
during resolution. A minimum of 43 bytes must be reserved. */
__I uint32_t RESERVED5[697];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_CCM_Type;
/* ================================================================================ */
/* ================ WDT ================ */
/* ================================================================================ */
/**
* @brief Watchdog Timer. (WDT)
*/
typedef struct { /*!< WDT Structure */
__O uint32_t TASKS_START; /*!< Start the watchdog. */
__I uint32_t RESERVED0[63];
__IO uint32_t EVENTS_TIMEOUT; /*!< Watchdog timeout. */
__I uint32_t RESERVED1[128];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED2[61];
__I uint32_t RUNSTATUS; /*!< Watchdog running status. */
__I uint32_t REQSTATUS; /*!< Request status. */
__I uint32_t RESERVED3[63];
__IO uint32_t CRV; /*!< Counter reload value in number of 32kiHz clock cycles. */
__IO uint32_t RREN; /*!< Reload request enable. */
__IO uint32_t CONFIG; /*!< Configuration register. */
__I uint32_t RESERVED4[60];
__O uint32_t RR[8]; /*!< Reload requests registers. */
__I uint32_t RESERVED5[631];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_WDT_Type;
/* ================================================================================ */
/* ================ QDEC ================ */
/* ================================================================================ */
/**
* @brief Rotary decoder. (QDEC)
*/
typedef struct { /*!< QDEC Structure */
__O uint32_t TASKS_START; /*!< Start the quadrature decoder. */
__O uint32_t TASKS_STOP; /*!< Stop the quadrature decoder. */
__O uint32_t TASKS_READCLRACC; /*!< Transfers the content from ACC registers to ACCREAD registers,
and clears the ACC registers. */
__I uint32_t RESERVED0[61];
__IO uint32_t EVENTS_SAMPLERDY; /*!< A new sample is written to the sample register. */
__IO uint32_t EVENTS_REPORTRDY; /*!< REPORTPER number of samples accumulated in ACC register, and
ACC register different than zero. */
__IO uint32_t EVENTS_ACCOF; /*!< ACC or ACCDBL register overflow. */
__I uint32_t RESERVED1[61];
__IO uint32_t SHORTS; /*!< Shortcuts for the QDEC. */
__I uint32_t RESERVED2[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[125];
__IO uint32_t ENABLE; /*!< Enable the QDEC. */
__IO uint32_t LEDPOL; /*!< LED output pin polarity. */
__IO uint32_t SAMPLEPER; /*!< Sample period. */
__I int32_t SAMPLE; /*!< Motion sample value. */
__IO uint32_t REPORTPER; /*!< Number of samples to generate an EVENT_REPORTRDY. */
__I int32_t ACC; /*!< Accumulated valid transitions register. */
__I int32_t ACCREAD; /*!< Snapshot of ACC register. Value generated by the TASKS_READCLEACC
task. */
__IO uint32_t PSELLED; /*!< Pin select for LED output. */
__IO uint32_t PSELA; /*!< Pin select for phase A input. */
__IO uint32_t PSELB; /*!< Pin select for phase B input. */
__IO uint32_t DBFEN; /*!< Enable debouncer input filters. */
__I uint32_t RESERVED4[5];
__IO uint32_t LEDPRE; /*!< Time LED is switched ON before the sample. */
__I uint32_t ACCDBL; /*!< Accumulated double (error) transitions register. */
__I uint32_t ACCDBLREAD; /*!< Snapshot of ACCDBL register. Value generated by the TASKS_READCLEACC
task. */
__I uint32_t RESERVED5[684];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_QDEC_Type;
/* ================================================================================ */
/* ================ LPCOMP ================ */
/* ================================================================================ */
/**
* @brief Low power comparator. (LPCOMP)
*/
typedef struct { /*!< LPCOMP Structure */
__O uint32_t TASKS_START; /*!< Start the comparator. */
__O uint32_t TASKS_STOP; /*!< Stop the comparator. */
__O uint32_t TASKS_SAMPLE; /*!< Sample comparator value. */
__I uint32_t RESERVED0[61];
__IO uint32_t EVENTS_READY; /*!< LPCOMP is ready and output is valid. */
__IO uint32_t EVENTS_DOWN; /*!< Input voltage crossed the threshold going down. */
__IO uint32_t EVENTS_UP; /*!< Input voltage crossed the threshold going up. */
__IO uint32_t EVENTS_CROSS; /*!< Input voltage crossed the threshold in any direction. */
__I uint32_t RESERVED1[60];
__IO uint32_t SHORTS; /*!< Shortcuts for the LPCOMP. */
__I uint32_t RESERVED2[64];
__IO uint32_t INTENSET; /*!< Interrupt enable set register. */
__IO uint32_t INTENCLR; /*!< Interrupt enable clear register. */
__I uint32_t RESERVED3[61];
__I uint32_t RESULT; /*!< Result of last compare. */
__I uint32_t RESERVED4[63];
__IO uint32_t ENABLE; /*!< Enable the LPCOMP. */
__IO uint32_t PSEL; /*!< Input pin select. */
__IO uint32_t REFSEL; /*!< Reference select. */
__IO uint32_t EXTREFSEL; /*!< External reference select. */
__I uint32_t RESERVED5[4];
__IO uint32_t ANADETECT; /*!< Analog detect configuration. */
__I uint32_t RESERVED6[694];
__IO uint32_t POWER; /*!< Peripheral power control. */
} NRF_LPCOMP_Type;
/* ================================================================================ */
/* ================ SWI ================ */
/* ================================================================================ */
/**
* @brief SW Interrupts. (SWI)
*/
typedef struct { /*!< SWI Structure */
__I uint32_t UNUSED; /*!< Unused. */
} NRF_SWI_Type;
/* ================================================================================ */
/* ================ NVMC ================ */
/* ================================================================================ */
/**
* @brief Non Volatile Memory Controller. (NVMC)
*/
typedef struct { /*!< NVMC Structure */
__I uint32_t RESERVED0[256];
__I uint32_t READY; /*!< Ready flag. */
__I uint32_t RESERVED1[64];
__IO uint32_t CONFIG; /*!< Configuration register. */
__IO uint32_t ERASEPAGE; /*!< Register for erasing a non-protected non-volatile memory page. */
__IO uint32_t ERASEALL; /*!< Register for erasing all non-volatile user memory. */
__IO uint32_t ERASEPROTECTEDPAGE; /*!< Register for erasing a protected non-volatile memory page. */
__IO uint32_t ERASEUICR; /*!< Register for start erasing User Information Congfiguration Registers. */
} NRF_NVMC_Type;
/* ================================================================================ */
/* ================ PPI ================ */
/* ================================================================================ */
/**
* @brief PPI controller. (PPI)
*/
typedef struct { /*!< PPI Structure */
PPI_TASKS_CHG_Type TASKS_CHG[4]; /*!< Channel group tasks. */
__I uint32_t RESERVED0[312];
__IO uint32_t CHEN; /*!< Channel enable. */
__IO uint32_t CHENSET; /*!< Channel enable set. */
__IO uint32_t CHENCLR; /*!< Channel enable clear. */
__I uint32_t RESERVED1;
PPI_CH_Type CH[16]; /*!< PPI Channel. */
__I uint32_t RESERVED2[156];
__IO uint32_t CHG[4]; /*!< Channel group configuration. */
} NRF_PPI_Type;
/* ================================================================================ */
/* ================ FICR ================ */
/* ================================================================================ */
/**
* @brief Factory Information Configuration. (FICR)
*/
typedef struct { /*!< FICR Structure */
__I uint32_t RESERVED0[4];
__I uint32_t CODEPAGESIZE; /*!< Code memory page size in bytes. */
__I uint32_t CODESIZE; /*!< Code memory size in pages. */
__I uint32_t RESERVED1[4];
__I uint32_t CLENR0; /*!< Length of code region 0 in bytes. */
__I uint32_t PPFC; /*!< Pre-programmed factory code present. */
__I uint32_t RESERVED2;
__I uint32_t NUMRAMBLOCK; /*!< Number of individualy controllable RAM blocks. */
union {
__I uint32_t SIZERAMBLOCK[4]; /*!< Deprecated array of size of RAM block in bytes. This name is
kept for backward compatinility purposes. Use SIZERAMBLOCKS
instead. */
__I uint32_t SIZERAMBLOCKS; /*!< Size of RAM blocks in bytes. */
};
__I uint32_t RESERVED3[5];
__I uint32_t CONFIGID; /*!< Configuration identifier. */
__I uint32_t DEVICEID[2]; /*!< Device identifier. */
__I uint32_t RESERVED4[6];
__I uint32_t ER[4]; /*!< Encryption root. */
__I uint32_t IR[4]; /*!< Identity root. */
__I uint32_t DEVICEADDRTYPE; /*!< Device address type. */
__I uint32_t DEVICEADDR[2]; /*!< Device address. */
__I uint32_t OVERRIDEEN; /*!< Radio calibration override enable. */
__I uint32_t NRF_1MBIT[5]; /*!< Override values for the OVERRIDEn registers in RADIO for NRF_1Mbit
mode. */
__I uint32_t RESERVED5[10];
__I uint32_t BLE_1MBIT[5]; /*!< Override values for the OVERRIDEn registers in RADIO for BLE_1Mbit
mode. */
} NRF_FICR_Type;
/* ================================================================================ */
/* ================ UICR ================ */
/* ================================================================================ */
/**
* @brief User Information Configuration. (UICR)
*/
typedef struct { /*!< UICR Structure */
__IO uint32_t CLENR0; /*!< Length of code region 0. */
__IO uint32_t RBPCONF; /*!< Readback protection configuration. */
__IO uint32_t XTALFREQ; /*!< Reset value for CLOCK XTALFREQ register. */
__I uint32_t RESERVED0;
__I uint32_t FWID; /*!< Firmware ID. */
__IO uint32_t BOOTLOADERADDR; /*!< Bootloader start address. */
} NRF_UICR_Type;
/* ================================================================================ */
/* ================ GPIO ================ */
/* ================================================================================ */
/**
* @brief General purpose input and output. (GPIO)
*/
typedef struct { /*!< GPIO Structure */
__I uint32_t RESERVED0[321];
__IO uint32_t OUT; /*!< Write GPIO port. */
__IO uint32_t OUTSET; /*!< Set individual bits in GPIO port. */
__IO uint32_t OUTCLR; /*!< Clear individual bits in GPIO port. */
__I uint32_t IN; /*!< Read GPIO port. */
__IO uint32_t DIR; /*!< Direction of GPIO pins. */
__IO uint32_t DIRSET; /*!< DIR set register. */
__IO uint32_t DIRCLR; /*!< DIR clear register. */
__I uint32_t RESERVED1[120];
__IO uint32_t PIN_CNF[32]; /*!< Configuration of GPIO pins. */
} NRF_GPIO_Type;
/* -------------------- End of section using anonymous unions ------------------- */
#if defined(__CC_ARM)
#pragma pop
#elif defined(__ICCARM__)
/* leave anonymous unions enabled */
#elif defined(__GNUC__)
/* anonymous unions are enabled by default */
#elif defined(__TMS470__)
/* anonymous unions are enabled by default */
#elif defined(__TASKING__)
#pragma warning restore
#else
#warning Not supported compiler type
#endif
/* ================================================================================ */
/* ================ Peripheral memory map ================ */
/* ================================================================================ */
#define NRF_POWER_BASE 0x40000000UL
#define NRF_CLOCK_BASE 0x40000000UL
#define NRF_MPU_BASE 0x40000000UL
#define NRF_PU_BASE 0x40000000UL
#define NRF_AMLI_BASE 0x40000000UL
#define NRF_RADIO_BASE 0x40001000UL
#define NRF_UART0_BASE 0x40002000UL
#define NRF_SPI0_BASE 0x40003000UL
#define NRF_TWI0_BASE 0x40003000UL
#define NRF_SPI1_BASE 0x40004000UL
#define NRF_TWI1_BASE 0x40004000UL
#define NRF_SPIS1_BASE 0x40004000UL
#define NRF_GPIOTE_BASE 0x40006000UL
#define NRF_ADC_BASE 0x40007000UL
#define NRF_TIMER0_BASE 0x40008000UL
#define NRF_TIMER1_BASE 0x40009000UL
#define NRF_TIMER2_BASE 0x4000A000UL
#define NRF_RTC0_BASE 0x4000B000UL
#define NRF_TEMP_BASE 0x4000C000UL
#define NRF_RNG_BASE 0x4000D000UL
#define NRF_ECB_BASE 0x4000E000UL
#define NRF_AAR_BASE 0x4000F000UL
#define NRF_CCM_BASE 0x4000F000UL
#define NRF_WDT_BASE 0x40010000UL
#define NRF_RTC1_BASE 0x40011000UL
#define NRF_QDEC_BASE 0x40012000UL
#define NRF_LPCOMP_BASE 0x40013000UL
#define NRF_SWI_BASE 0x40014000UL
#define NRF_NVMC_BASE 0x4001E000UL
#define NRF_PPI_BASE 0x4001F000UL
#define NRF_FICR_BASE 0x10000000UL
#define NRF_UICR_BASE 0x10001000UL
#define NRF_GPIO_BASE 0x50000000UL
/* ================================================================================ */
/* ================ Peripheral declaration ================ */
/* ================================================================================ */
#define NRF_POWER ((NRF_POWER_Type *) NRF_POWER_BASE)
#define NRF_CLOCK ((NRF_CLOCK_Type *) NRF_CLOCK_BASE)
#define NRF_MPU ((NRF_MPU_Type *) NRF_MPU_BASE)
#define NRF_PU ((NRF_PU_Type *) NRF_PU_BASE)
#define NRF_AMLI ((NRF_AMLI_Type *) NRF_AMLI_BASE)
#define NRF_RADIO ((NRF_RADIO_Type *) NRF_RADIO_BASE)
#define NRF_UART0 ((NRF_UART_Type *) NRF_UART0_BASE)
#define NRF_SPI0 ((NRF_SPI_Type *) NRF_SPI0_BASE)
#define NRF_TWI0 ((NRF_TWI_Type *) NRF_TWI0_BASE)
#define NRF_SPI1 ((NRF_SPI_Type *) NRF_SPI1_BASE)
#define NRF_TWI1 ((NRF_TWI_Type *) NRF_TWI1_BASE)
#define NRF_SPIS1 ((NRF_SPIS_Type *) NRF_SPIS1_BASE)
#define NRF_GPIOTE ((NRF_GPIOTE_Type *) NRF_GPIOTE_BASE)
#define NRF_ADC ((NRF_ADC_Type *) NRF_ADC_BASE)
#define NRF_TIMER0 ((NRF_TIMER_Type *) NRF_TIMER0_BASE)
#define NRF_TIMER1 ((NRF_TIMER_Type *) NRF_TIMER1_BASE)
#define NRF_TIMER2 ((NRF_TIMER_Type *) NRF_TIMER2_BASE)
#define NRF_RTC0 ((NRF_RTC_Type *) NRF_RTC0_BASE)
#define NRF_TEMP ((NRF_TEMP_Type *) NRF_TEMP_BASE)
#define NRF_RNG ((NRF_RNG_Type *) NRF_RNG_BASE)
#define NRF_ECB ((NRF_ECB_Type *) NRF_ECB_BASE)
#define NRF_AAR ((NRF_AAR_Type *) NRF_AAR_BASE)
#define NRF_CCM ((NRF_CCM_Type *) NRF_CCM_BASE)
#define NRF_WDT ((NRF_WDT_Type *) NRF_WDT_BASE)
#define NRF_RTC1 ((NRF_RTC_Type *) NRF_RTC1_BASE)
#define NRF_QDEC ((NRF_QDEC_Type *) NRF_QDEC_BASE)
#define NRF_LPCOMP ((NRF_LPCOMP_Type *) NRF_LPCOMP_BASE)
#define NRF_SWI ((NRF_SWI_Type *) NRF_SWI_BASE)
#define NRF_NVMC ((NRF_NVMC_Type *) NRF_NVMC_BASE)
#define NRF_PPI ((NRF_PPI_Type *) NRF_PPI_BASE)
#define NRF_FICR ((NRF_FICR_Type *) NRF_FICR_BASE)
#define NRF_UICR ((NRF_UICR_Type *) NRF_UICR_BASE)
#define NRF_GPIO ((NRF_GPIO_Type *) NRF_GPIO_BASE)
/** @} */ /* End of group Device_Peripheral_Registers */
/** @} */ /* End of group nRF51 */
/** @} */ /* End of group Nordic Semiconductor */
#ifdef __cplusplus
}
#endif
#endif /* nRF51_H */
|
DroneBucket/Drone_Bucket_CrazyFlie2_NRF_Firmware
|
nrf51_sdk/nrf51822/Include/nrf51.h
|
C
|
gpl-3.0
| 87,885
|
package cn.nukkit.entity.passive;
import cn.nukkit.Player;
import cn.nukkit.item.Item;
import cn.nukkit.level.format.FullChunk;
import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.network.protocol.AddEntityPacket;
/**
* Author: BeYkeRYkt
* Nukkit Project
*/
public class EntityChicken extends EntityAnimal {
public static final int NETWORK_ID = 10;
public EntityChicken(FullChunk chunk, CompoundTag nbt) {
super(chunk, nbt);
}
@Override
public float getWidth() {
return 0.4f;
}
@Override
public float getHeight() {
if (this.isBaby()) {
return 0.51f;
}
return 0.7f;
}
@Override
public float getEyeHeight() {
if (this.isBaby()) {
return 0.51f;
}
return 0.7f;
}
@Override
public String getName() {
return this.getNameTag();
}
@Override
public Item[] getDrops() {
return new Item[]{Item.get(Item.RAW_CHICKEN), Item.get(Item.FEATHER)};
}
@Override
public int getNetworkId() {
return NETWORK_ID;
}
@Override
protected void initEntity() {
super.initEntity();
setMaxHealth(4);
}
@Override
public boolean isBreedingItem(Item item) {
int id = item.getId();
return id == Item.WHEAT_SEEDS || id == Item.MELON_SEEDS || id == Item.PUMPKIN_SEEDS || id == Item.BEETROOT_SEEDS;
}
@Override
public void spawnTo(Player player) {
AddEntityPacket pk = new AddEntityPacket();
pk.type = this.getNetworkId();
pk.entityUniqueId = this.getId();
pk.entityRuntimeId = this.getId();
pk.x = (float) this.x;
pk.y = (float) this.y;
pk.z = (float) this.z;
pk.speedX = (float) this.motionX;
pk.speedY = (float) this.motionY;
pk.speedZ = (float) this.motionZ;
pk.metadata = this.dataProperties;
player.dataPacket(pk);
super.spawnTo(player);
}
}
|
SOTEDev/Nukkit
|
src/main/java/cn/nukkit/entity/passive/EntityChicken.java
|
Java
|
gpl-3.0
| 2,000
|
// Compiled using typings@0.6.8
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4de74cb527395c13ba20b438c3a7a419ad931f1c/requirejs/require.d.ts
// Type definitions for RequireJS 2.1.20
// Project: http://requirejs.org/
// Definitions by: Josh Baldwin <https://github.com/jbaldwin/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/*
require-2.1.8.d.ts may be freely distributed under the MIT license.
Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/require.d.ts
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
declare module 'module' {
var mod: {
config: () => any;
id: string;
uri: string;
}
export = mod;
}
interface RequireError extends Error {
/**
* The error ID that maps to an ID on a web page.
**/
requireType: string;
/**
* Required modules.
**/
requireModules: string[];
/**
* The original error, if there is one (might be null).
**/
originalError: Error;
}
interface RequireShim {
/**
* List of dependencies.
**/
deps?: string[];
/**
* Name the module will be exported as.
**/
exports?: string;
/**
* Initialize function with all dependcies passed in,
* if the function returns a value then that value is used
* as the module export value instead of the object
* found via the 'exports' string.
* @param dependencies
* @return
**/
init?: (...dependencies: any[]) => any;
}
interface RequireConfig {
// The root path to use for all module lookups.
baseUrl?: string;
// Path mappings for module names not found directly under
// baseUrl.
paths?: { [key: string]: any; };
// Dictionary of Shim's.
// does not cover case of key->string[]
shim?: { [key: string]: RequireShim; };
/**
* For the given module prefix, instead of loading the
* module with the given ID, substitude a different
* module ID.
*
* @example
* requirejs.config({
* map: {
* 'some/newmodule': {
* 'foo': 'foo1.2'
* },
* 'some/oldmodule': {
* 'foo': 'foo1.0'
* }
* }
* });
**/
map?: {
[id: string]: {
[id: string]: string;
};
};
/**
* Allows pointing multiple module IDs to a module ID that contains a bundle of modules.
*
* @example
* requirejs.config({
* bundles: {
* 'primary': ['main', 'util', 'text', 'text!template.html'],
* 'secondary': ['text!secondary.html']
* }
* });
**/
bundles?: { [key: string]: string[]; };
/**
* AMD configurations, use module.config() to access in
* define() functions
**/
config?: { [id: string]: {}; };
/**
* Configures loading modules from CommonJS packages.
**/
packages?: {};
/**
* The number of seconds to wait before giving up on loading
* a script. The default is 7 seconds.
**/
waitSeconds?: number;
/**
* A name to give to a loading context. This allows require.js
* to load multiple versions of modules in a page, as long as
* each top-level require call specifies a unique context string.
**/
context?: string;
/**
* An array of dependencies to load.
**/
deps?: string[];
/**
* A function to pass to require that should be require after
* deps have been loaded.
* @param modules
**/
callback?: (...modules: any[]) => void;
/**
* If set to true, an error will be thrown if a script loads
* that does not call define() or have shim exports string
* value that can be checked.
**/
enforceDefine?: boolean;
/**
* If set to true, document.createElementNS() will be used
* to create script elements.
**/
xhtml?: boolean;
/**
* Extra query string arguments appended to URLs that RequireJS
* uses to fetch resources. Most useful to cache bust when
* the browser or server is not configured correctly.
*
* @example
* urlArgs: "bust= + (new Date()).getTime()
**/
urlArgs?: string;
/**
* Specify the value for the type="" attribute used for script
* tags inserted into the document by RequireJS. Default is
* "text/javascript". To use Firefox's JavasScript 1.8
* features, use "text/javascript;version=1.8".
**/
scriptType?: string;
/**
* If set to true, skips the data-main attribute scanning done
* to start module loading. Useful if RequireJS is embedded in
* a utility library that may interact with other RequireJS
* library on the page, and the embedded version should not do
* data-main loading.
**/
skipDataMain?: boolean;
/**
* Allow extending requirejs to support Subresource Integrity
* (SRI).
**/
onNodeCreated?: (node: HTMLScriptElement, config: RequireConfig, moduleName: string, url: string) => void;
}
// todo: not sure what to do with this guy
interface RequireModule {
/**
*
**/
config(): {};
}
/**
*
**/
interface RequireMap {
/**
*
**/
prefix: string;
/**
*
**/
name: string;
/**
*
**/
parentMap: RequireMap;
/**
*
**/
url: string;
/**
*
**/
originalName: string;
/**
*
**/
fullName: string;
}
interface Require {
/**
* Configure require.js
**/
config(config: RequireConfig): Require;
/**
* CommonJS require call
* @param module Module to load
* @return The loaded module
*/
(module: string): any;
/**
* Start the main app logic.
* Callback is optional.
* Can alternatively use deps and callback.
* @param modules Required modules to load.
**/
(modules: string[]): void;
/**
* @see Require()
* @param ready Called when required modules are ready.
**/
(modules: string[], ready: Function): void;
/**
* @see http://requirejs.org/docs/api.html#errbacks
* @param ready Called when required modules are ready.
**/
(modules: string[], ready: Function, errback: Function): void;
/**
* Generate URLs from require module
* @param module Module to URL
* @return URL string
**/
toUrl(module: string): string;
/**
* Returns true if the module has already been loaded and defined.
* @param module Module to check
**/
defined(module: string): boolean;
/**
* Returns true if the module has already been requested or is in the process of loading and should be available at some point.
* @param module Module to check
**/
specified(module: string): boolean;
/**
* On Error override
* @param err
**/
onError(err: RequireError, errback?: (err: RequireError) => void): void;
/**
* Undefine a module
* @param module Module to undefine.
**/
undef(module: string): void;
/**
* Semi-private function, overload in special instance of undef()
**/
onResourceLoad(context: Object, map: RequireMap, depArray: RequireMap[]): void;
}
interface RequireDefine {
/**
* Define Simple Name/Value Pairs
* @param config Dictionary of Named/Value pairs for the config.
**/
(config: { [key: string]: any; }): void;
/**
* Define function.
* @param func: The function module.
**/
(func: () => any): void;
/**
* Define function with dependencies.
* @param deps List of dependencies module IDs.
* @param ready Callback function when the dependencies are loaded.
* callback param deps module dependencies
* callback return module definition
**/
(deps: string[], ready: Function): void;
/**
* Define module with simplified CommonJS wrapper.
* @param ready
* callback require requirejs instance
* callback exports exports object
* callback module module
* callback return module definition
**/
(ready: (require: Require, exports: { [key: string]: any; }, module: RequireModule) => any): void;
/**
* Define a module with a name and dependencies.
* @param name The name of the module.
* @param deps List of dependencies module IDs.
* @param ready Callback function when the dependencies are loaded.
* callback deps module dependencies
* callback return module definition
**/
(name: string, deps: string[], ready: Function): void;
/**
* Define a module with a name.
* @param name The name of the module.
* @param ready Callback function when the dependencies are loaded.
* callback return module definition
**/
(name: string, ready: Function): void;
/**
* Used to allow a clear indicator that a global define function (as needed for script src browser loading) conforms
* to the AMD API, any global define function SHOULD have a property called "amd" whose value is an object.
* This helps avoid conflict with any other existing JavaScript code that could have defined a define() function
* that does not conform to the AMD API.
* define.amd.jQuery is specific to jQuery and indicates that the loader is able to account for multiple version
* of jQuery being loaded simultaneously.
*/
amd: Object;
}
// Ambient declarations for 'require' and 'define'
declare var requirejs: Require;
declare var require: Require;
declare var define: RequireDefine;
|
Red1L/hub
|
frontend/typings/main/ambient/require/require.d.ts
|
TypeScript
|
mpl-2.0
| 9,535
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.WorkSpaces.CreateWorkspaces
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates one or more WorkSpaces.
--
-- This operation is asynchronous and returns before the WorkSpaces are
-- created.
--
--
--
-- <http://docs.aws.amazon.com/workspaces/latest/devguide/API_CreateWorkspaces.html>
module Network.AWS.WorkSpaces.CreateWorkspaces
(
-- * Request
CreateWorkspaces
-- ** Request constructor
, createWorkspaces
-- ** Request lenses
, cwWorkspaces
-- * Response
, CreateWorkspacesResponse
-- ** Response constructor
, createWorkspacesResponse
-- ** Response lenses
, cwrFailedRequests
, cwrPendingRequests
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.WorkSpaces.Types
import qualified GHC.Exts
newtype CreateWorkspaces = CreateWorkspaces
{ _cwWorkspaces :: List1 "Workspaces" WorkspaceRequest
} deriving (Eq, Read, Show, Semigroup)
-- | 'CreateWorkspaces' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cwWorkspaces' @::@ 'NonEmpty' 'WorkspaceRequest'
--
createWorkspaces :: NonEmpty WorkspaceRequest -- ^ 'cwWorkspaces'
-> CreateWorkspaces
createWorkspaces p1 = CreateWorkspaces
{ _cwWorkspaces = withIso _List1 (const id) p1
}
-- | An array of structures that specify the WorkSpaces to create.
cwWorkspaces :: Lens' CreateWorkspaces (NonEmpty WorkspaceRequest)
cwWorkspaces = lens _cwWorkspaces (\s a -> s { _cwWorkspaces = a }) . _List1
data CreateWorkspacesResponse = CreateWorkspacesResponse
{ _cwrFailedRequests :: List "FailedRequests" FailedCreateWorkspaceRequest
, _cwrPendingRequests :: List "PendingRequests" Workspace
} deriving (Eq, Read, Show)
-- | 'CreateWorkspacesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cwrFailedRequests' @::@ ['FailedCreateWorkspaceRequest']
--
-- * 'cwrPendingRequests' @::@ ['Workspace']
--
createWorkspacesResponse :: CreateWorkspacesResponse
createWorkspacesResponse = CreateWorkspacesResponse
{ _cwrFailedRequests = mempty
, _cwrPendingRequests = mempty
}
-- | An array of structures that represent the WorkSpaces that could not be
-- created.
cwrFailedRequests :: Lens' CreateWorkspacesResponse [FailedCreateWorkspaceRequest]
cwrFailedRequests =
lens _cwrFailedRequests (\s a -> s { _cwrFailedRequests = a })
. _List
-- | An array of structures that represent the WorkSpaces that were created.
--
-- Because this operation is asynchronous, the identifier in 'WorkspaceId' is not
-- immediately available. If you immediately call 'DescribeWorkspaces' with this
-- identifier, no information will be returned.
cwrPendingRequests :: Lens' CreateWorkspacesResponse [Workspace]
cwrPendingRequests =
lens _cwrPendingRequests (\s a -> s { _cwrPendingRequests = a })
. _List
instance ToPath CreateWorkspaces where
toPath = const "/"
instance ToQuery CreateWorkspaces where
toQuery = const mempty
instance ToHeaders CreateWorkspaces
instance ToJSON CreateWorkspaces where
toJSON CreateWorkspaces{..} = object
[ "Workspaces" .= _cwWorkspaces
]
instance AWSRequest CreateWorkspaces where
type Sv CreateWorkspaces = WorkSpaces
type Rs CreateWorkspaces = CreateWorkspacesResponse
request = post "CreateWorkspaces"
response = jsonResponse
instance FromJSON CreateWorkspacesResponse where
parseJSON = withObject "CreateWorkspacesResponse" $ \o -> CreateWorkspacesResponse
<$> o .:? "FailedRequests" .!= mempty
<*> o .:? "PendingRequests" .!= mempty
|
kim/amazonka
|
amazonka-workspaces/gen/Network/AWS/WorkSpaces/CreateWorkspaces.hs
|
Haskell
|
mpl-2.0
| 4,636
|
/* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
* See http://creativecommons.org/publicdomain/zero/1.0/ for more information. */
#include <signal.h>
#ifdef UA_NO_AMALGAMATION
#include "ua_types.h"
#include "ua_server.h"
#include "ua_config_standard.h"
#include "ua_network_tcp.h"
#else
#include "open62541.h"
#endif
UA_Boolean running = true;
static void stopHandler(int sig) {
running = false;
}
int main(void) {
signal(SIGINT, stopHandler);
signal(SIGTERM, stopHandler);
UA_ServerConfig config = UA_ServerConfig_standard;
UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664);
config.networkLayers = &nl;
config.networkLayersSize = 1;
UA_Server *server = UA_Server_new(config);
/* Create a rudimentary objectType
*
* BaseObjectType
* |
* +- (OT) MamalType
* + (V) Age
* + (OT) DogType
* |
* + (V) Name
*/
UA_StatusCode retval;
UA_ObjectTypeAttributes otAttr;
UA_ObjectTypeAttributes_init(&otAttr);
otAttr.description = UA_LOCALIZEDTEXT("en_US", "A mamal");
otAttr.displayName = UA_LOCALIZEDTEXT("en_US", "MamalType");
UA_Server_addObjectTypeNode(server, UA_NODEID_NUMERIC(1, 10000),
UA_NODEID_NUMERIC(0, UA_NS0ID_BASEOBJECTTYPE), UA_NODEID_NUMERIC(0, UA_NS0ID_HASSUBTYPE),
UA_QUALIFIEDNAME(1, "MamalType"), otAttr, NULL, NULL);
UA_VariableAttributes vAttr;
UA_VariableAttributes_init(&vAttr);
vAttr.description = UA_LOCALIZEDTEXT("en_US", "This mamals Age in months");
vAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Age");
UA_UInt32 ageVar = 0;
UA_Variant_setScalarCopy(&vAttr.value, &ageVar, &UA_TYPES[UA_TYPES_UINT32]);
UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, 10001),
UA_NODEID_NUMERIC(1, 10000), UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
UA_QUALIFIEDNAME(1, "Age"), UA_NODEID_NULL, vAttr, NULL, NULL);
UA_ObjectTypeAttributes_init(&otAttr);
otAttr.description = UA_LOCALIZEDTEXT("en_US", "A dog, subtype of mamal");
otAttr.displayName = UA_LOCALIZEDTEXT("en_US", "DogType");
UA_Server_addObjectTypeNode(server, UA_NODEID_NUMERIC(1, 10002),
UA_NODEID_NUMERIC(1, 10000), UA_NODEID_NUMERIC(0, UA_NS0ID_HASSUBTYPE),
UA_QUALIFIEDNAME(1, "DogType"), otAttr, NULL, NULL);
UA_VariableAttributes_init(&vAttr);
vAttr.description = UA_LOCALIZEDTEXT("en_US", "This mamals Age in months");
vAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Name");
UA_String defaultName = UA_STRING("unnamed dog");
UA_Variant_setScalarCopy(&vAttr.value, &defaultName, &UA_TYPES[UA_TYPES_STRING]);
UA_Server_addVariableNode(server, UA_NODEID_NUMERIC(1, 10003),
UA_NODEID_NUMERIC(1, 10002), UA_NODEID_NUMERIC(0, UA_NS0ID_HASPROPERTY),
UA_QUALIFIEDNAME(1, "Name"), UA_NODEID_NULL, vAttr, NULL, NULL);
/* Instatiate a dog named bello:
* (O) Objects
* + O Bello <DogType>
* + Age
* + Name
*/
UA_ObjectAttributes oAttr;
UA_ObjectAttributes_init(&oAttr);
oAttr.description = UA_LOCALIZEDTEXT("en_US", "A dog named Bello");
oAttr.displayName = UA_LOCALIZEDTEXT("en_US", "Bello");
UA_Server_addObjectNode(server, UA_NODEID_NUMERIC(1, 0),
UA_NODEID_NUMERIC(0, UA_NS0ID_OBJECTSFOLDER), UA_NODEID_NUMERIC(0, UA_NS0ID_HASCOMPONENT),
UA_QUALIFIEDNAME(1, "Bello"), UA_NODEID_NUMERIC(1, 10002), oAttr, NULL, NULL);
retval = UA_Server_run(server, &running);
UA_Server_delete(server);
nl.deleteMembers(&nl);
return (int)retval;
}
|
AGIsmail/open62541
|
examples/server_instantiation.c
|
C
|
mpl-2.0
| 3,893
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<TITLE>
Uses of Interface org.apache.poi.ss.usermodel.charts.LineChartData (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.apache.poi.ss.usermodel.charts.LineChartData (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/poi/ss/usermodel/charts/\class-useLineChartData.html" target="_top"><B>FRAMES</B></A>
<A HREF="LineChartData.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>org.apache.poi.ss.usermodel.charts.LineChartData</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts">LineChartData</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.ss.usermodel.charts"><B>org.apache.poi.ss.usermodel.charts</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.poi.xssf.usermodel.charts"><B>org.apache.poi.xssf.usermodel.charts</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.ss.usermodel.charts"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts">LineChartData</A> in <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/package-summary.html">org.apache.poi.ss.usermodel.charts</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/package-summary.html">org.apache.poi.ss.usermodel.charts</A> that return <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts">LineChartData</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts">LineChartData</A></CODE></FONT></TD>
<TD><CODE><B>ChartDataFactory.</B><B><A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/ChartDataFactory.html#createLineChartData()">createLineChartData</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.poi.xssf.usermodel.charts"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts">LineChartData</A> in <A HREF="../../../../../../../org/apache/poi/xssf/usermodel/charts/package-summary.html">org.apache.poi.xssf.usermodel.charts</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../../org/apache/poi/xssf/usermodel/charts/package-summary.html">org.apache.poi.xssf.usermodel.charts</A> that implement <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts">LineChartData</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/poi/xssf/usermodel/charts/XSSFLineChartData.html" title="class in org.apache.poi.xssf.usermodel.charts">XSSFLineChartData</A></B></CODE>
<BR>
Holds data for a XSSF Line Chart</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/poi/ss/usermodel/charts/LineChartData.html" title="interface in org.apache.poi.ss.usermodel.charts"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/poi/ss/usermodel/charts/\class-useLineChartData.html" target="_top"><B>FRAMES</B></A>
<A HREF="LineChartData.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2015 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
claywebb/java-bulletin
|
poi-3.13/docs/apidocs/org/apache/poi/ss/usermodel/charts/class-use/LineChartData.html
|
HTML
|
mpl-2.0
| 10,197
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.ocelotds.security;
import java.lang.reflect.Method;
/**
*
* @author hhfrancois
*/
public class InvocationContext {
final Method method;
final Object[] parameters;
public InvocationContext(Method method, Object[] parameters) {
this.method = method;
this.parameters = parameters;
}
public Method getMethod() {
return method;
}
public Object[] getParameters() {
return parameters;
}
@Override
public String toString() {
if(null != this.method) {
return this.method.getDeclaringClass().getName()+"."+this.method.getName();
}
return null;
}
}
|
hhdevelopment/ocelot
|
ocelot-core/src/main/java/org/ocelotds/security/InvocationContext.java
|
Java
|
mpl-2.0
| 801
|
<!DOCTYPE html>
<!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec mixed-content/` -->
<html>
<head>
<title>Mixed-Content: Blockable content</title>
<meta charset='utf-8'>
<meta name="description" content="Test behavior of blockable content.">
<link rel="author" title="Kristijan Burnik" href="burnik@chromium.org">
<link rel="help" href="http://www.w3.org/TR/mixed-content/#category-blockable">
<meta name="assert" content="Mixed-Content: Expects blocked for sharedworker-module to same-http origin and keep-scheme redirection from https context.">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/security-features/resources/common.sub.js"></script>
<script src="../../../../generic/test-case.sub.js"></script>
</head>
<body>
<script>
TestCase(
{
"expectation": "blocked",
"origin": "same-http",
"redirection": "keep-scheme",
"source_context_list": [],
"source_scheme": "https",
"subresource": "sharedworker-module",
"subresource_policy_deliveries": []
},
document.querySelector("meta[name=assert]").content,
new SanityChecker()
).start();
</script>
<div id="log"></div>
</body>
</html>
|
UK992/servo
|
tests/wpt/web-platform-tests/mixed-content/gen/top.meta/unset/sharedworker-module/same-http.keep-scheme.https.html
|
HTML
|
mpl-2.0
| 1,374
|
var path = require('path');
module.exports = {
entry: __dirname + '/src/main.jsx',
output: {
path: __dirname + '/build/js',
filename: '[name].bundle.js'
},
externals: {
'react': 'React',
'react/addons': 'React'
},
module: {
loaders: [
{
test: /\.js$/,
loaders: ['babel-loader'],
include: path.resolve(__dirname, 'src')
},
{
test: /\.jsx$/,
loaders: ['babel-loader', 'jsx-loader'],
include: path.resolve(__dirname, 'src')
},
{
test: /\.json$/,
loaders: ['json-loader'],
include: [path.resolve(__dirname, 'www_src'), path.resolve(__dirname, 'node_modules')]
}
]
}
};
|
gvn/webmaker-browser
|
webpack.config.js
|
JavaScript
|
mpl-2.0
| 713
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.SNS.ListTopics
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of the requester\'s topics. Each call returns a limited
-- list of topics, up to 100. If there are more topics, a 'NextToken' is
-- also returned. Use the 'NextToken' parameter in a new 'ListTopics' call
-- to get further results.
--
-- /See:/ <http://docs.aws.amazon.com/sns/latest/api/API_ListTopics.html AWS API Reference> for ListTopics.
--
-- This operation returns paginated results.
module Network.AWS.SNS.ListTopics
(
-- * Creating a Request
listTopics
, ListTopics
-- * Request Lenses
, ltNextToken
-- * Destructuring the Response
, listTopicsResponse
, ListTopicsResponse
-- * Response Lenses
, ltrsTopics
, ltrsNextToken
, ltrsResponseStatus
) where
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.SNS.Types
import Network.AWS.SNS.Types.Product
-- | /See:/ 'listTopics' smart constructor.
newtype ListTopics = ListTopics'
{ _ltNextToken :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListTopics' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltNextToken'
listTopics
:: ListTopics
listTopics =
ListTopics'
{ _ltNextToken = Nothing
}
-- | Token returned by the previous 'ListTopics' request.
ltNextToken :: Lens' ListTopics (Maybe Text)
ltNextToken = lens _ltNextToken (\ s a -> s{_ltNextToken = a});
instance AWSPager ListTopics where
page rq rs
| stop (rs ^. ltrsNextToken) = Nothing
| stop (rs ^. ltrsTopics) = Nothing
| otherwise =
Just $ rq & ltNextToken .~ rs ^. ltrsNextToken
instance AWSRequest ListTopics where
type Rs ListTopics = ListTopicsResponse
request = postQuery sNS
response
= receiveXMLWrapper "ListTopicsResult"
(\ s h x ->
ListTopicsResponse' <$>
(x .@? "Topics" .!@ mempty >>=
may (parseXMLList "member"))
<*> (x .@? "NextToken")
<*> (pure (fromEnum s)))
instance ToHeaders ListTopics where
toHeaders = const mempty
instance ToPath ListTopics where
toPath = const "/"
instance ToQuery ListTopics where
toQuery ListTopics'{..}
= mconcat
["Action" =: ("ListTopics" :: ByteString),
"Version" =: ("2010-03-31" :: ByteString),
"NextToken" =: _ltNextToken]
-- | Response for ListTopics action.
--
-- /See:/ 'listTopicsResponse' smart constructor.
data ListTopicsResponse = ListTopicsResponse'
{ _ltrsTopics :: !(Maybe [Topic])
, _ltrsNextToken :: !(Maybe Text)
, _ltrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListTopicsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltrsTopics'
--
-- * 'ltrsNextToken'
--
-- * 'ltrsResponseStatus'
listTopicsResponse
:: Int -- ^ 'ltrsResponseStatus'
-> ListTopicsResponse
listTopicsResponse pResponseStatus_ =
ListTopicsResponse'
{ _ltrsTopics = Nothing
, _ltrsNextToken = Nothing
, _ltrsResponseStatus = pResponseStatus_
}
-- | A list of topic ARNs.
ltrsTopics :: Lens' ListTopicsResponse [Topic]
ltrsTopics = lens _ltrsTopics (\ s a -> s{_ltrsTopics = a}) . _Default . _Coerce;
-- | Token to pass along to the next 'ListTopics' request. This element is
-- returned if there are additional topics to retrieve.
ltrsNextToken :: Lens' ListTopicsResponse (Maybe Text)
ltrsNextToken = lens _ltrsNextToken (\ s a -> s{_ltrsNextToken = a});
-- | The response status code.
ltrsResponseStatus :: Lens' ListTopicsResponse Int
ltrsResponseStatus = lens _ltrsResponseStatus (\ s a -> s{_ltrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-sns/gen/Network/AWS/SNS/ListTopics.hs
|
Haskell
|
mpl-2.0
| 4,692
|
@extends('layouts.master')
@section('content')
<article>
<h1>Are You Sure You Want To Delete {!!$artist->name!!}?</h1>
{!!Form::open(['route'=>["artists.destroy", $artist->id], 'method'=>'DELETE'])!!}
{!!Form::submit('destroy')!!}
{!!Form::close()!!}
</article>
@stop
|
jasperboyd/freshwax
|
laravel/resources/views/labels/delete.blade.php
|
PHP
|
mpl-2.0
| 289
|
// This package implements a provisioner for Packer that executes
// shell scripts within the remote machine.
package shell
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"strings"
"time"
"github.com/mitchellh/packer/common"
"github.com/mitchellh/packer/helper/config"
"github.com/mitchellh/packer/packer"
"github.com/mitchellh/packer/template/interpolate"
)
const DefaultRemotePath = "c:/Windows/Temp/script.bat"
var retryableSleep = 2 * time.Second
type Config struct {
common.PackerConfig `mapstructure:",squash"`
// If true, the script contains binary and line endings will not be
// converted from Windows to Unix-style.
Binary bool
// An inline script to execute. Multiple strings are all executed
// in the context of a single shell.
Inline []string
// The local path of the shell script to upload and execute.
Script string
// An array of multiple scripts to run.
Scripts []string
// An array of environment variables that will be injected before
// your command(s) are executed.
Vars []string `mapstructure:"environment_vars"`
// The remote path where the local shell script will be uploaded to.
// This should be set to a writable file that is in a pre-existing directory.
RemotePath string `mapstructure:"remote_path"`
// The command used to execute the script. The '{{ .Path }}' variable
// should be used to specify where the script goes, {{ .Vars }}
// can be used to inject the environment_vars into the environment.
ExecuteCommand string `mapstructure:"execute_command"`
// The timeout for retrying to start the process. Until this timeout
// is reached, if the provisioner can't start a process, it retries.
// This can be set high to allow for reboots.
StartRetryTimeout time.Duration `mapstructure:"start_retry_timeout"`
// This is used in the template generation to format environment variables
// inside the `ExecuteCommand` template.
EnvVarFormat string
ctx interpolate.Context
}
type Provisioner struct {
config Config
}
type ExecuteCommandTemplate struct {
Vars string
Path string
}
func (p *Provisioner) Prepare(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{
"execute_command",
},
},
}, raws...)
if err != nil {
return err
}
if p.config.EnvVarFormat == "" {
p.config.EnvVarFormat = `set "%s=%s" && `
}
if p.config.ExecuteCommand == "" {
p.config.ExecuteCommand = `{{.Vars}}"{{.Path}}"`
}
if p.config.Inline != nil && len(p.config.Inline) == 0 {
p.config.Inline = nil
}
if p.config.StartRetryTimeout == 0 {
p.config.StartRetryTimeout = 5 * time.Minute
}
if p.config.RemotePath == "" {
p.config.RemotePath = DefaultRemotePath
}
if p.config.Scripts == nil {
p.config.Scripts = make([]string, 0)
}
if p.config.Vars == nil {
p.config.Vars = make([]string, 0)
}
var errs error
if p.config.Script != "" && len(p.config.Scripts) > 0 {
errs = packer.MultiErrorAppend(errs,
errors.New("Only one of script or scripts can be specified."))
}
if p.config.Script != "" {
p.config.Scripts = []string{p.config.Script}
}
if len(p.config.Scripts) == 0 && p.config.Inline == nil {
errs = packer.MultiErrorAppend(errs,
errors.New("Either a script file or inline script must be specified."))
} else if len(p.config.Scripts) > 0 && p.config.Inline != nil {
errs = packer.MultiErrorAppend(errs,
errors.New("Only a script file or an inline script can be specified, not both."))
}
for _, path := range p.config.Scripts {
if _, err := os.Stat(path); err != nil {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("Bad script '%s': %s", path, err))
}
}
// Do a check for bad environment variables, such as '=foo', 'foobar'
for _, kv := range p.config.Vars {
vs := strings.SplitN(kv, "=", 2)
if len(vs) != 2 || vs[0] == "" {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("Environment variable not in format 'key=value': %s", kv))
}
}
if errs != nil {
return errs
}
return nil
}
// This function takes the inline scripts, concatenates them
// into a temporary file and returns a string containing the location
// of said file.
func extractScript(p *Provisioner) (string, error) {
temp, err := ioutil.TempFile(os.TempDir(), "packer-windows-shell-provisioner")
if err != nil {
log.Printf("Unable to create temporary file for inline scripts: %s", err)
return "", err
}
writer := bufio.NewWriter(temp)
for _, command := range p.config.Inline {
log.Printf("Found command: %s", command)
if _, err := writer.WriteString(command + "\n"); err != nil {
return "", fmt.Errorf("Error preparing shell script: %s", err)
}
}
if err := writer.Flush(); err != nil {
return "", fmt.Errorf("Error preparing shell script: %s", err)
}
temp.Close()
return temp.Name(), nil
}
func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
ui.Say(fmt.Sprintf("Provisioning with windows-shell..."))
scripts := make([]string, len(p.config.Scripts))
copy(scripts, p.config.Scripts)
if p.config.Inline != nil {
temp, err := extractScript(p)
if err != nil {
ui.Error(fmt.Sprintf("Unable to extract inline scripts into a file: %s", err))
}
scripts = append(scripts, temp)
}
for _, path := range scripts {
ui.Say(fmt.Sprintf("Provisioning with shell script: %s", path))
log.Printf("Opening %s for reading", path)
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("Error opening shell script: %s", err)
}
defer f.Close()
// Create environment variables to set before executing the command
flattendVars, err := p.createFlattenedEnvVars()
if err != nil {
return err
}
// Compile the command
p.config.ctx.Data = &ExecuteCommandTemplate{
Vars: flattendVars,
Path: p.config.RemotePath,
}
command, err := interpolate.Render(p.config.ExecuteCommand, &p.config.ctx)
if err != nil {
return fmt.Errorf("Error processing command: %s", err)
}
// Upload the file and run the command. Do this in the context of
// a single retryable function so that we don't end up with
// the case that the upload succeeded, a restart is initiated,
// and then the command is executed but the file doesn't exist
// any longer.
var cmd *packer.RemoteCmd
err = p.retryable(func() error {
if _, err := f.Seek(0, 0); err != nil {
return err
}
if err := comm.Upload(p.config.RemotePath, f, nil); err != nil {
return fmt.Errorf("Error uploading script: %s", err)
}
cmd = &packer.RemoteCmd{Command: command}
return cmd.StartWithUi(comm, ui)
})
if err != nil {
return err
}
// Close the original file since we copied it
f.Close()
if cmd.ExitStatus != 0 {
return fmt.Errorf("Script exited with non-zero exit status: %d", cmd.ExitStatus)
}
}
return nil
}
func (p *Provisioner) Cancel() {
// Just hard quit. It isn't a big deal if what we're doing keeps
// running on the other side.
os.Exit(0)
}
// retryable will retry the given function over and over until a
// non-error is returned.
func (p *Provisioner) retryable(f func() error) error {
startTimeout := time.After(p.config.StartRetryTimeout)
for {
var err error
if err = f(); err == nil {
return nil
}
// Create an error and log it
err = fmt.Errorf("Retryable error: %s", err)
log.Printf(err.Error())
// Check if we timed out, otherwise we retry. It is safe to
// retry since the only error case above is if the command
// failed to START.
select {
case <-startTimeout:
return err
default:
time.Sleep(retryableSleep)
}
}
}
func (p *Provisioner) createFlattenedEnvVars() (flattened string, err error) {
flattened = ""
envVars := make(map[string]string)
// Always available Packer provided env vars
envVars["PACKER_BUILD_NAME"] = p.config.PackerBuildName
envVars["PACKER_BUILDER_TYPE"] = p.config.PackerBuilderType
httpAddr := common.GetHTTPAddr()
if httpAddr != "" {
envVars["PACKER_HTTP_ADDR"] = httpAddr
}
// Split vars into key/value components
for _, envVar := range p.config.Vars {
keyValue := strings.SplitN(envVar, "=", 2)
if len(keyValue) != 2 || keyValue[0] == "" {
err = errors.New(fmt.Sprintf("Shell provisioner environment variables must be in key=value format. Currently it is '%s'", envVar))
return
}
envVars[keyValue[0]] = keyValue[1]
}
// Create a list of env var keys in sorted order
var keys []string
for k := range envVars {
keys = append(keys, k)
}
sort.Strings(keys)
// Re-assemble vars using OS specific format pattern and flatten
for _, key := range keys {
flattened += fmt.Sprintf(p.config.EnvVarFormat, key, envVars[key])
}
return
}
|
life360/packer
|
provisioner/windows-shell/provisioner.go
|
GO
|
mpl-2.0
| 8,780
|
export const basicSortDataModel = [
{
type: 'pand/address',
},
{
type: 'kadaster/kadastraal_object',
},
{
type: 'bag/pand',
},
]
export const basicDataModel = [
{
uri: 'https://acc.api.data.amsterdam.nl/',
label: 'Warmoesstraat 178',
categoryLabel: 'Adres',
type: 'pand/address',
parent: 'bag/pand',
},
{
uri: 'https://acc.api.data.amsterdam.nl/',
label: 'ASD04 F 06417 G 0000',
categoryLabel: 'Kadastraal object',
type: 'kadaster/kadastraal_object',
},
{
uri: 'https://acc.api.data.amsterdam.nl/',
label: '0363100012168052',
categoryLabel: 'Pand',
type: 'bag/pand',
},
]
export const expectedDataModel = [
{
categoryLabel: 'Pand',
results: [
{
categoryLabel: 'Pand',
label: '0363100012168052',
type: 'bag/pand',
uri: 'https://acc.api.data.amsterdam.nl/',
},
],
subCategories: [
{
categoryLabel: 'Adres',
results: [
{
categoryLabel: 'Adres',
label: 'Warmoesstraat 178',
parent: 'bag/pand',
type: 'pand/address',
uri: 'https://acc.api.data.amsterdam.nl/',
},
],
subCategories: [],
type: 'pand/address',
},
],
type: 'bag/pand',
},
{
categoryLabel: 'Kadastraal object',
results: [
{
categoryLabel: 'Kadastraal object',
label: 'ASD04 F 06417 G 0000',
type: 'kadaster/kadastraal_object',
uri: 'https://acc.api.data.amsterdam.nl/',
},
],
subCategories: [],
type: 'kadaster/kadastraal_object',
},
]
|
DatapuntAmsterdam/atlas_prototype
|
src/map/services/map-search-results/map-search-results.fixture.js
|
JavaScript
|
mpl-2.0
| 1,654
|
{# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/. -#}
{% add_lang_files "firefox/new/horizon" %}
{% extends "firefox/base-resp.html" %}
{% block page_title_prefix %}{{_('Download Firefox')}} — {% endblock %}
{% block page_title %}{{_('Free Web Browser')}}{% endblock %}
{% block page_desc %}{{_('Download Mozilla Firefox, a free Web browser. Firefox is created by a global non-profit dedicated to putting individuals in control online. Get Firefox for Windows, Mac OS X, Linux, Android and iOS today!')}}{% endblock %}
{#- This will appear as <meta property="og:title"> which can be used for social share -#}
{% block page_og_title %}
{{ _('Browse Freely') }}
{% endblock %}
{#- This will appear as <meta property="og:description"> which can be used for social share -#}
{% block page_og_desc %}
{{_('Firefox is non-profit, non-corporate, non-compromised. Choosing Firefox isn’t just choosing a browser. It’s a vote for personal freedom.')}}
{% endblock %}
{#- This will appear as <meta property="og:image"> which can be used for social share -#}
{% block page_image %}
{{ static('img/firefox/firefox-independent-1200.jpg') }}
{% endblock %}
{% block optimizely %}
{% if switch('firefox-new-optimizely') %}
{% include 'includes/optimizely.html' %}
{% endif %}
{% endblock %}
{% block body_id %}{% endblock %}
{% block body_class %}{% endblock %}
{% block site_header %}{% endblock %}
{% block site_css %}{% endblock %}
{% block extrahead %}{% endblock %}
{% block content %}{% endblock %}
{% block email_form %}{% endblock %}
{% block site_footer %}
{% with fx_footer_links=True %}
{% include 'firefox/includes/simple_footer.html' %}
{% endwith %}
{% endblock %}
{% block js %}{% endblock %}
|
analytics-pros/mozilla-bedrock
|
bedrock/firefox/templates/firefox/new/horizon/base.html
|
HTML
|
mpl-2.0
| 1,886
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ECS.ListServices
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Lists the services that are running in a specified cluster.
--
-- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListServices.html>
module Network.AWS.ECS.ListServices
(
-- * Request
ListServices
-- ** Request constructor
, listServices
-- ** Request lenses
, lsCluster
, lsMaxResults
, lsNextToken
-- * Response
, ListServicesResponse
-- ** Response constructor
, listServicesResponse
-- ** Response lenses
, lsrNextToken
, lsrServiceArns
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.ECS.Types
import qualified GHC.Exts
data ListServices = ListServices
{ _lsCluster :: Maybe Text
, _lsMaxResults :: Maybe Int
, _lsNextToken :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListServices' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lsCluster' @::@ 'Maybe' 'Text'
--
-- * 'lsMaxResults' @::@ 'Maybe' 'Int'
--
-- * 'lsNextToken' @::@ 'Maybe' 'Text'
--
listServices :: ListServices
listServices = ListServices
{ _lsCluster = Nothing
, _lsNextToken = Nothing
, _lsMaxResults = Nothing
}
-- | The short name or full Amazon Resource Name (ARN) of the cluster that hosts
-- the services you want to list. If you do not specify a cluster, the default
-- cluster is assumed..
lsCluster :: Lens' ListServices (Maybe Text)
lsCluster = lens _lsCluster (\s a -> s { _lsCluster = a })
-- | The maximum number of container instance results returned by 'ListServices' in
-- paginated output. When this parameter is used, 'ListServices' only returns 'maxResults' results in a single page along with a 'nextToken' response element. The
-- remaining results of the initial request can be seen by sending another 'ListServices' request with the returned 'nextToken' value. This value can be between 1 and
-- 100. If this parameter is not used, then 'ListServices' returns up to 100
-- results and a 'nextToken' value if applicable.
lsMaxResults :: Lens' ListServices (Maybe Int)
lsMaxResults = lens _lsMaxResults (\s a -> s { _lsMaxResults = a })
-- | The 'nextToken' value returned from a previous paginated 'ListServices' request
-- where 'maxResults' was used and the results exceeded the value of that
-- parameter. Pagination continues from the end of the previous results that
-- returned the 'nextToken' value. This value is 'null' when there are no more
-- results to return.
lsNextToken :: Lens' ListServices (Maybe Text)
lsNextToken = lens _lsNextToken (\s a -> s { _lsNextToken = a })
data ListServicesResponse = ListServicesResponse
{ _lsrNextToken :: Maybe Text
, _lsrServiceArns :: List "serviceArns" Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListServicesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lsrNextToken' @::@ 'Maybe' 'Text'
--
-- * 'lsrServiceArns' @::@ ['Text']
--
listServicesResponse :: ListServicesResponse
listServicesResponse = ListServicesResponse
{ _lsrServiceArns = mempty
, _lsrNextToken = Nothing
}
-- | The 'nextToken' value to include in a future 'ListServices' request. When the
-- results of a 'ListServices' request exceed 'maxResults', this value can be used
-- to retrieve the next page of results. This value is 'null' when there are no
-- more results to return.
lsrNextToken :: Lens' ListServicesResponse (Maybe Text)
lsrNextToken = lens _lsrNextToken (\s a -> s { _lsrNextToken = a })
-- | The list of full Amazon Resource Name (ARN) entries for each service
-- associated with the specified cluster.
lsrServiceArns :: Lens' ListServicesResponse [Text]
lsrServiceArns = lens _lsrServiceArns (\s a -> s { _lsrServiceArns = a }) . _List
instance ToPath ListServices where
toPath = const "/"
instance ToQuery ListServices where
toQuery = const mempty
instance ToHeaders ListServices
instance ToJSON ListServices where
toJSON ListServices{..} = object
[ "cluster" .= _lsCluster
, "nextToken" .= _lsNextToken
, "maxResults" .= _lsMaxResults
]
instance AWSRequest ListServices where
type Sv ListServices = ECS
type Rs ListServices = ListServicesResponse
request = post "ListServices"
response = jsonResponse
instance FromJSON ListServicesResponse where
parseJSON = withObject "ListServicesResponse" $ \o -> ListServicesResponse
<$> o .:? "nextToken"
<*> o .:? "serviceArns" .!= mempty
|
romanb/amazonka
|
amazonka-ecs/gen/Network/AWS/ECS/ListServices.hs
|
Haskell
|
mpl-2.0
| 5,564
|
//
// Copyright 2014, Sander van Harmelen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package cloudstack
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
)
type DedicatePublicIpRangeParams struct {
p map[string]interface{}
}
func (p *DedicatePublicIpRangeParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
return u
}
func (p *DedicatePublicIpRangeParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *DedicatePublicIpRangeParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *DedicatePublicIpRangeParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *DedicatePublicIpRangeParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
// You should always use this function to get a new DedicatePublicIpRangeParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewDedicatePublicIpRangeParams(domainid string, id string) *DedicatePublicIpRangeParams {
p := &DedicatePublicIpRangeParams{}
p.p = make(map[string]interface{})
p.p["domainid"] = domainid
p.p["id"] = id
return p
}
// Dedicates a Public IP range to an account
func (s *NetworkService) DedicatePublicIpRange(p *DedicatePublicIpRangeParams) (*DedicatePublicIpRangeResponse, error) {
resp, err := s.cs.newRequest("dedicatePublicIpRange", p.toURLValues())
if err != nil {
return nil, err
}
var r DedicatePublicIpRangeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type DedicatePublicIpRangeResponse struct {
Account string `json:"account,omitempty"`
Description string `json:"description,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Endip string `json:"endip,omitempty"`
Endipv6 string `json:"endipv6,omitempty"`
Forvirtualnetwork bool `json:"forvirtualnetwork,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkid string `json:"networkid,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Podid string `json:"podid,omitempty"`
Podname string `json:"podname,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Startip string `json:"startip,omitempty"`
Startipv6 string `json:"startipv6,omitempty"`
Vlan string `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type ReleasePublicIpRangeParams struct {
p map[string]interface{}
}
func (p *ReleasePublicIpRangeParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *ReleasePublicIpRangeParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new ReleasePublicIpRangeParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewReleasePublicIpRangeParams(id string) *ReleasePublicIpRangeParams {
p := &ReleasePublicIpRangeParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Releases a Public IP range back to the system pool
func (s *NetworkService) ReleasePublicIpRange(p *ReleasePublicIpRangeParams) (*ReleasePublicIpRangeResponse, error) {
resp, err := s.cs.newRequest("releasePublicIpRange", p.toURLValues())
if err != nil {
return nil, err
}
var r ReleasePublicIpRangeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ReleasePublicIpRangeResponse struct {
Displaytext string `json:"displaytext,omitempty"`
Success string `json:"success,omitempty"`
}
type CreateNetworkParams struct {
p map[string]interface{}
}
func (p *CreateNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["aclid"]; found {
u.Set("aclid", v.(string))
}
if v, found := p.p["acltype"]; found {
u.Set("acltype", v.(string))
}
if v, found := p.p["displaynetwork"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("displaynetwork", vv)
}
if v, found := p.p["displaytext"]; found {
u.Set("displaytext", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["endip"]; found {
u.Set("endip", v.(string))
}
if v, found := p.p["endipv6"]; found {
u.Set("endipv6", v.(string))
}
if v, found := p.p["gateway"]; found {
u.Set("gateway", v.(string))
}
if v, found := p.p["ip6cidr"]; found {
u.Set("ip6cidr", v.(string))
}
if v, found := p.p["ip6gateway"]; found {
u.Set("ip6gateway", v.(string))
}
if v, found := p.p["isolatedpvlan"]; found {
u.Set("isolatedpvlan", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["netmask"]; found {
u.Set("netmask", v.(string))
}
if v, found := p.p["networkdomain"]; found {
u.Set("networkdomain", v.(string))
}
if v, found := p.p["networkofferingid"]; found {
u.Set("networkofferingid", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
if v, found := p.p["startip"]; found {
u.Set("startip", v.(string))
}
if v, found := p.p["startipv6"]; found {
u.Set("startipv6", v.(string))
}
if v, found := p.p["subdomainaccess"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("subdomainaccess", vv)
}
if v, found := p.p["vlan"]; found {
u.Set("vlan", v.(string))
}
if v, found := p.p["vpcid"]; found {
u.Set("vpcid", v.(string))
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *CreateNetworkParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *CreateNetworkParams) SetAclid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["aclid"] = v
return
}
func (p *CreateNetworkParams) SetAcltype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["acltype"] = v
return
}
func (p *CreateNetworkParams) SetDisplaynetwork(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["displaynetwork"] = v
return
}
func (p *CreateNetworkParams) SetDisplaytext(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["displaytext"] = v
return
}
func (p *CreateNetworkParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *CreateNetworkParams) SetEndip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["endip"] = v
return
}
func (p *CreateNetworkParams) SetEndipv6(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["endipv6"] = v
return
}
func (p *CreateNetworkParams) SetGateway(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["gateway"] = v
return
}
func (p *CreateNetworkParams) SetIp6cidr(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["ip6cidr"] = v
return
}
func (p *CreateNetworkParams) SetIp6gateway(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["ip6gateway"] = v
return
}
func (p *CreateNetworkParams) SetIsolatedpvlan(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isolatedpvlan"] = v
return
}
func (p *CreateNetworkParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *CreateNetworkParams) SetNetmask(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["netmask"] = v
return
}
func (p *CreateNetworkParams) SetNetworkdomain(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkdomain"] = v
return
}
func (p *CreateNetworkParams) SetNetworkofferingid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkofferingid"] = v
return
}
func (p *CreateNetworkParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *CreateNetworkParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
func (p *CreateNetworkParams) SetStartip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startip"] = v
return
}
func (p *CreateNetworkParams) SetStartipv6(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startipv6"] = v
return
}
func (p *CreateNetworkParams) SetSubdomainaccess(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["subdomainaccess"] = v
return
}
func (p *CreateNetworkParams) SetVlan(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vlan"] = v
return
}
func (p *CreateNetworkParams) SetVpcid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vpcid"] = v
return
}
func (p *CreateNetworkParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new CreateNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewCreateNetworkParams(displaytext string, name string, networkofferingid string, zoneid string) *CreateNetworkParams {
p := &CreateNetworkParams{}
p.p = make(map[string]interface{})
p.p["displaytext"] = displaytext
p.p["name"] = name
p.p["networkofferingid"] = networkofferingid
p.p["zoneid"] = zoneid
return p
}
// Creates a network
func (s *NetworkService) CreateNetwork(p *CreateNetworkParams) (*CreateNetworkResponse, error) {
resp, err := s.cs.newRequest("createNetwork", p.toURLValues())
if err != nil {
return nil, err
}
if resp, err = getRawValue(resp); err != nil {
return nil, err
}
var r CreateNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type CreateNetworkResponse struct {
Account string `json:"account,omitempty"`
Aclid string `json:"aclid,omitempty"`
Acltype string `json:"acltype,omitempty"`
Broadcastdomaintype string `json:"broadcastdomaintype,omitempty"`
Broadcasturi string `json:"broadcasturi,omitempty"`
Canusefordeploy bool `json:"canusefordeploy,omitempty"`
Cidr string `json:"cidr,omitempty"`
Displaynetwork bool `json:"displaynetwork,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Dns1 string `json:"dns1,omitempty"`
Dns2 string `json:"dns2,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Ispersistent bool `json:"ispersistent,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Name string `json:"name,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkcidr string `json:"networkcidr,omitempty"`
Networkdomain string `json:"networkdomain,omitempty"`
Networkofferingavailability string `json:"networkofferingavailability,omitempty"`
Networkofferingconservemode bool `json:"networkofferingconservemode,omitempty"`
Networkofferingdisplaytext string `json:"networkofferingdisplaytext,omitempty"`
Networkofferingid string `json:"networkofferingid,omitempty"`
Networkofferingname string `json:"networkofferingname,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Related string `json:"related,omitempty"`
Reservediprange string `json:"reservediprange,omitempty"`
Restartrequired bool `json:"restartrequired,omitempty"`
Service []struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
} `json:"service,omitempty"`
Specifyipranges bool `json:"specifyipranges,omitempty"`
State string `json:"state,omitempty"`
Strechedl2subnet bool `json:"strechedl2subnet,omitempty"`
Subdomainaccess bool `json:"subdomainaccess,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Vlan string `json:"vlan,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
Zonesnetworkspans []string `json:"zonesnetworkspans,omitempty"`
}
type DeleteNetworkParams struct {
p map[string]interface{}
}
func (p *DeleteNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["forced"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("forced", vv)
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DeleteNetworkParams) SetForced(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["forced"] = v
return
}
func (p *DeleteNetworkParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DeleteNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewDeleteNetworkParams(id string) *DeleteNetworkParams {
p := &DeleteNetworkParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Deletes a network
func (s *NetworkService) DeleteNetwork(p *DeleteNetworkParams) (*DeleteNetworkResponse, error) {
resp, err := s.cs.newRequest("deleteNetwork", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeleteNetworkResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListNetworksParams struct {
p map[string]interface{}
}
func (p *ListNetworksParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["account"]; found {
u.Set("account", v.(string))
}
if v, found := p.p["acltype"]; found {
u.Set("acltype", v.(string))
}
if v, found := p.p["canusefordeploy"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("canusefordeploy", vv)
}
if v, found := p.p["displaynetwork"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("displaynetwork", vv)
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["forvpc"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("forvpc", vv)
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["isrecursive"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("isrecursive", vv)
}
if v, found := p.p["issystem"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("issystem", vv)
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["listall"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("listall", vv)
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["projectid"]; found {
u.Set("projectid", v.(string))
}
if v, found := p.p["restartrequired"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("restartrequired", vv)
}
if v, found := p.p["specifyipranges"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("specifyipranges", vv)
}
if v, found := p.p["supportedservices"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("supportedservices", vv)
}
if v, found := p.p["tags"]; found {
i := 0
for k, vv := range v.(map[string]string) {
u.Set(fmt.Sprintf("tags[%d].key", i), k)
u.Set(fmt.Sprintf("tags[%d].value", i), vv)
i++
}
}
if v, found := p.p["traffictype"]; found {
u.Set("traffictype", v.(string))
}
if v, found := p.p["type"]; found {
u.Set("type", v.(string))
}
if v, found := p.p["vpcid"]; found {
u.Set("vpcid", v.(string))
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *ListNetworksParams) SetAccount(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["account"] = v
return
}
func (p *ListNetworksParams) SetAcltype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["acltype"] = v
return
}
func (p *ListNetworksParams) SetCanusefordeploy(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["canusefordeploy"] = v
return
}
func (p *ListNetworksParams) SetDisplaynetwork(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["displaynetwork"] = v
return
}
func (p *ListNetworksParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *ListNetworksParams) SetForvpc(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["forvpc"] = v
return
}
func (p *ListNetworksParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListNetworksParams) SetIsrecursive(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isrecursive"] = v
return
}
func (p *ListNetworksParams) SetIssystem(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["issystem"] = v
return
}
func (p *ListNetworksParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListNetworksParams) SetListall(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["listall"] = v
return
}
func (p *ListNetworksParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListNetworksParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListNetworksParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *ListNetworksParams) SetProjectid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["projectid"] = v
return
}
func (p *ListNetworksParams) SetRestartrequired(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["restartrequired"] = v
return
}
func (p *ListNetworksParams) SetSpecifyipranges(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["specifyipranges"] = v
return
}
func (p *ListNetworksParams) SetSupportedservices(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["supportedservices"] = v
return
}
func (p *ListNetworksParams) SetTags(v map[string]string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["tags"] = v
return
}
func (p *ListNetworksParams) SetTraffictype(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["traffictype"] = v
return
}
func (p *ListNetworksParams) SetType(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkType"] = v
return
}
func (p *ListNetworksParams) SetVpcid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vpcid"] = v
return
}
func (p *ListNetworksParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new ListNetworksParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListNetworksParams() *ListNetworksParams {
p := &ListNetworksParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetNetworkID(keyword string) (string, error) {
p := &ListNetworksParams{}
p.p = make(map[string]interface{})
p.p["keyword"] = keyword
l, err := s.ListNetworks(p)
if err != nil {
return "", err
}
if l.Count == 0 {
// If no matches, search all projects
p.p["projectid"] = "-1"
l, err = s.ListNetworks(p)
if err != nil {
return "", err
}
}
if l.Count == 0 {
return "", fmt.Errorf("No match found for %s: %+v", keyword, l)
}
if l.Count == 1 {
return l.Networks[0].Id, nil
}
if l.Count > 1 {
for _, v := range l.Networks {
if v.Name == keyword {
return v.Id, nil
}
}
}
return "", fmt.Errorf("Could not find an exact match for %s: %+v", keyword, l)
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetNetworkByName(name string) (*Network, int, error) {
id, err := s.GetNetworkID(name)
if err != nil {
return nil, -1, err
}
r, count, err := s.GetNetworkByID(id)
if err != nil {
return nil, count, err
}
return r, count, nil
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetNetworkByID(id string) (*Network, int, error) {
p := &ListNetworksParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
l, err := s.ListNetworks(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
// If no matches, search all projects
p.p["projectid"] = "-1"
l, err = s.ListNetworks(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.Networks[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for Network UUID: %s!", id)
}
// Lists all available networks.
func (s *NetworkService) ListNetworks(p *ListNetworksParams) (*ListNetworksResponse, error) {
resp, err := s.cs.newRequest("listNetworks", p.toURLValues())
if err != nil {
return nil, err
}
var r ListNetworksResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListNetworksResponse struct {
Count int `json:"count"`
Networks []*Network `json:"network"`
}
type Network struct {
Account string `json:"account,omitempty"`
Aclid string `json:"aclid,omitempty"`
Acltype string `json:"acltype,omitempty"`
Broadcastdomaintype string `json:"broadcastdomaintype,omitempty"`
Broadcasturi string `json:"broadcasturi,omitempty"`
Canusefordeploy bool `json:"canusefordeploy,omitempty"`
Cidr string `json:"cidr,omitempty"`
Displaynetwork bool `json:"displaynetwork,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Dns1 string `json:"dns1,omitempty"`
Dns2 string `json:"dns2,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Ispersistent bool `json:"ispersistent,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Name string `json:"name,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkcidr string `json:"networkcidr,omitempty"`
Networkdomain string `json:"networkdomain,omitempty"`
Networkofferingavailability string `json:"networkofferingavailability,omitempty"`
Networkofferingconservemode bool `json:"networkofferingconservemode,omitempty"`
Networkofferingdisplaytext string `json:"networkofferingdisplaytext,omitempty"`
Networkofferingid string `json:"networkofferingid,omitempty"`
Networkofferingname string `json:"networkofferingname,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Related string `json:"related,omitempty"`
Reservediprange string `json:"reservediprange,omitempty"`
Restartrequired bool `json:"restartrequired,omitempty"`
Service []struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
} `json:"service,omitempty"`
Specifyipranges bool `json:"specifyipranges,omitempty"`
State string `json:"state,omitempty"`
Strechedl2subnet bool `json:"strechedl2subnet,omitempty"`
Subdomainaccess bool `json:"subdomainaccess,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Vlan string `json:"vlan,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
Zonesnetworkspans []string `json:"zonesnetworkspans,omitempty"`
}
type RestartNetworkParams struct {
p map[string]interface{}
}
func (p *RestartNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["cleanup"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("cleanup", vv)
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *RestartNetworkParams) SetCleanup(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["cleanup"] = v
return
}
func (p *RestartNetworkParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new RestartNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewRestartNetworkParams(id string) *RestartNetworkParams {
p := &RestartNetworkParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Restarts the network; includes 1) restarting network elements - virtual routers, DHCP servers 2) reapplying all public IPs 3) reapplying loadBalancing/portForwarding rules
func (s *NetworkService) RestartNetwork(p *RestartNetworkParams) (*RestartNetworkResponse, error) {
resp, err := s.cs.newRequest("restartNetwork", p.toURLValues())
if err != nil {
return nil, err
}
var r RestartNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type RestartNetworkResponse struct {
JobID string `json:"jobid,omitempty"`
Account string `json:"account,omitempty"`
Allocated string `json:"allocated,omitempty"`
Associatednetworkid string `json:"associatednetworkid,omitempty"`
Associatednetworkname string `json:"associatednetworkname,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Fordisplay bool `json:"fordisplay,omitempty"`
Forvirtualnetwork bool `json:"forvirtualnetwork,omitempty"`
Id string `json:"id,omitempty"`
Ipaddress string `json:"ipaddress,omitempty"`
Isportable bool `json:"isportable,omitempty"`
Issourcenat bool `json:"issourcenat,omitempty"`
Isstaticnat bool `json:"isstaticnat,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Networkid string `json:"networkid,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Purpose string `json:"purpose,omitempty"`
State string `json:"state,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Virtualmachinedisplayname string `json:"virtualmachinedisplayname,omitempty"`
Virtualmachineid string `json:"virtualmachineid,omitempty"`
Virtualmachinename string `json:"virtualmachinename,omitempty"`
Vlanid string `json:"vlanid,omitempty"`
Vlanname string `json:"vlanname,omitempty"`
Vmipaddress string `json:"vmipaddress,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
}
type UpdateNetworkParams struct {
p map[string]interface{}
}
func (p *UpdateNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["changecidr"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("changecidr", vv)
}
if v, found := p.p["customid"]; found {
u.Set("customid", v.(string))
}
if v, found := p.p["displaynetwork"]; found {
vv := strconv.FormatBool(v.(bool))
u.Set("displaynetwork", vv)
}
if v, found := p.p["displaytext"]; found {
u.Set("displaytext", v.(string))
}
if v, found := p.p["guestvmcidr"]; found {
u.Set("guestvmcidr", v.(string))
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["networkdomain"]; found {
u.Set("networkdomain", v.(string))
}
if v, found := p.p["networkofferingid"]; found {
u.Set("networkofferingid", v.(string))
}
return u
}
func (p *UpdateNetworkParams) SetChangecidr(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["changecidr"] = v
return
}
func (p *UpdateNetworkParams) SetCustomid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["customid"] = v
return
}
func (p *UpdateNetworkParams) SetDisplaynetwork(v bool) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["displaynetwork"] = v
return
}
func (p *UpdateNetworkParams) SetDisplaytext(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["displaytext"] = v
return
}
func (p *UpdateNetworkParams) SetGuestvmcidr(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["guestvmcidr"] = v
return
}
func (p *UpdateNetworkParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *UpdateNetworkParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *UpdateNetworkParams) SetNetworkdomain(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkdomain"] = v
return
}
func (p *UpdateNetworkParams) SetNetworkofferingid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkofferingid"] = v
return
}
// You should always use this function to get a new UpdateNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewUpdateNetworkParams(id string) *UpdateNetworkParams {
p := &UpdateNetworkParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Updates a network
func (s *NetworkService) UpdateNetwork(p *UpdateNetworkParams) (*UpdateNetworkResponse, error) {
resp, err := s.cs.newRequest("updateNetwork", p.toURLValues())
if err != nil {
return nil, err
}
var r UpdateNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UpdateNetworkResponse struct {
JobID string `json:"jobid,omitempty"`
Account string `json:"account,omitempty"`
Aclid string `json:"aclid,omitempty"`
Acltype string `json:"acltype,omitempty"`
Broadcastdomaintype string `json:"broadcastdomaintype,omitempty"`
Broadcasturi string `json:"broadcasturi,omitempty"`
Canusefordeploy bool `json:"canusefordeploy,omitempty"`
Cidr string `json:"cidr,omitempty"`
Displaynetwork bool `json:"displaynetwork,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Dns1 string `json:"dns1,omitempty"`
Dns2 string `json:"dns2,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Ispersistent bool `json:"ispersistent,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Name string `json:"name,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkcidr string `json:"networkcidr,omitempty"`
Networkdomain string `json:"networkdomain,omitempty"`
Networkofferingavailability string `json:"networkofferingavailability,omitempty"`
Networkofferingconservemode bool `json:"networkofferingconservemode,omitempty"`
Networkofferingdisplaytext string `json:"networkofferingdisplaytext,omitempty"`
Networkofferingid string `json:"networkofferingid,omitempty"`
Networkofferingname string `json:"networkofferingname,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Related string `json:"related,omitempty"`
Reservediprange string `json:"reservediprange,omitempty"`
Restartrequired bool `json:"restartrequired,omitempty"`
Service []struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
} `json:"service,omitempty"`
Specifyipranges bool `json:"specifyipranges,omitempty"`
State string `json:"state,omitempty"`
Strechedl2subnet bool `json:"strechedl2subnet,omitempty"`
Subdomainaccess bool `json:"subdomainaccess,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Vlan string `json:"vlan,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
Zonesnetworkspans []string `json:"zonesnetworkspans,omitempty"`
}
type CreatePhysicalNetworkParams struct {
p map[string]interface{}
}
func (p *CreatePhysicalNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["broadcastdomainrange"]; found {
u.Set("broadcastdomainrange", v.(string))
}
if v, found := p.p["domainid"]; found {
u.Set("domainid", v.(string))
}
if v, found := p.p["isolationmethods"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("isolationmethods", vv)
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["networkspeed"]; found {
u.Set("networkspeed", v.(string))
}
if v, found := p.p["tags"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("tags", vv)
}
if v, found := p.p["vlan"]; found {
u.Set("vlan", v.(string))
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *CreatePhysicalNetworkParams) SetBroadcastdomainrange(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["broadcastdomainrange"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetDomainid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["domainid"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetIsolationmethods(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["isolationmethods"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetNetworkspeed(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkspeed"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetTags(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["tags"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetVlan(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vlan"] = v
return
}
func (p *CreatePhysicalNetworkParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new CreatePhysicalNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewCreatePhysicalNetworkParams(name string, zoneid string) *CreatePhysicalNetworkParams {
p := &CreatePhysicalNetworkParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
p.p["zoneid"] = zoneid
return p
}
// Creates a physical network
func (s *NetworkService) CreatePhysicalNetwork(p *CreatePhysicalNetworkParams) (*CreatePhysicalNetworkResponse, error) {
resp, err := s.cs.newRequest("createPhysicalNetwork", p.toURLValues())
if err != nil {
return nil, err
}
var r CreatePhysicalNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type CreatePhysicalNetworkResponse struct {
JobID string `json:"jobid,omitempty"`
Broadcastdomainrange string `json:"broadcastdomainrange,omitempty"`
Domainid string `json:"domainid,omitempty"`
Id string `json:"id,omitempty"`
Isolationmethods string `json:"isolationmethods,omitempty"`
Name string `json:"name,omitempty"`
Networkspeed string `json:"networkspeed,omitempty"`
State string `json:"state,omitempty"`
Tags string `json:"tags,omitempty"`
Vlan string `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type DeletePhysicalNetworkParams struct {
p map[string]interface{}
}
func (p *DeletePhysicalNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DeletePhysicalNetworkParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DeletePhysicalNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewDeletePhysicalNetworkParams(id string) *DeletePhysicalNetworkParams {
p := &DeletePhysicalNetworkParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Deletes a Physical Network.
func (s *NetworkService) DeletePhysicalNetwork(p *DeletePhysicalNetworkParams) (*DeletePhysicalNetworkResponse, error) {
resp, err := s.cs.newRequest("deletePhysicalNetwork", p.toURLValues())
if err != nil {
return nil, err
}
var r DeletePhysicalNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeletePhysicalNetworkResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListPhysicalNetworksParams struct {
p map[string]interface{}
}
func (p *ListPhysicalNetworksParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *ListPhysicalNetworksParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListPhysicalNetworksParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListPhysicalNetworksParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *ListPhysicalNetworksParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListPhysicalNetworksParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListPhysicalNetworksParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new ListPhysicalNetworksParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListPhysicalNetworksParams() *ListPhysicalNetworksParams {
p := &ListPhysicalNetworksParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetPhysicalNetworkID(name string) (string, error) {
p := &ListPhysicalNetworksParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
l, err := s.ListPhysicalNetworks(p)
if err != nil {
return "", err
}
if l.Count == 0 {
return "", fmt.Errorf("No match found for %s: %+v", name, l)
}
if l.Count == 1 {
return l.PhysicalNetworks[0].Id, nil
}
if l.Count > 1 {
for _, v := range l.PhysicalNetworks {
if v.Name == name {
return v.Id, nil
}
}
}
return "", fmt.Errorf("Could not find an exact match for %s: %+v", name, l)
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetPhysicalNetworkByName(name string) (*PhysicalNetwork, int, error) {
id, err := s.GetPhysicalNetworkID(name)
if err != nil {
return nil, -1, err
}
r, count, err := s.GetPhysicalNetworkByID(id)
if err != nil {
return nil, count, err
}
return r, count, nil
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetPhysicalNetworkByID(id string) (*PhysicalNetwork, int, error) {
p := &ListPhysicalNetworksParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
l, err := s.ListPhysicalNetworks(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.PhysicalNetworks[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for PhysicalNetwork UUID: %s!", id)
}
// Lists physical networks
func (s *NetworkService) ListPhysicalNetworks(p *ListPhysicalNetworksParams) (*ListPhysicalNetworksResponse, error) {
resp, err := s.cs.newRequest("listPhysicalNetworks", p.toURLValues())
if err != nil {
return nil, err
}
var r ListPhysicalNetworksResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListPhysicalNetworksResponse struct {
Count int `json:"count"`
PhysicalNetworks []*PhysicalNetwork `json:"physicalnetwork"`
}
type PhysicalNetwork struct {
Broadcastdomainrange string `json:"broadcastdomainrange,omitempty"`
Domainid string `json:"domainid,omitempty"`
Id string `json:"id,omitempty"`
Isolationmethods string `json:"isolationmethods,omitempty"`
Name string `json:"name,omitempty"`
Networkspeed string `json:"networkspeed,omitempty"`
State string `json:"state,omitempty"`
Tags string `json:"tags,omitempty"`
Vlan string `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type UpdatePhysicalNetworkParams struct {
p map[string]interface{}
}
func (p *UpdatePhysicalNetworkParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["networkspeed"]; found {
u.Set("networkspeed", v.(string))
}
if v, found := p.p["state"]; found {
u.Set("state", v.(string))
}
if v, found := p.p["tags"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("tags", vv)
}
if v, found := p.p["vlan"]; found {
u.Set("vlan", v.(string))
}
return u
}
func (p *UpdatePhysicalNetworkParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *UpdatePhysicalNetworkParams) SetNetworkspeed(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["networkspeed"] = v
return
}
func (p *UpdatePhysicalNetworkParams) SetState(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["state"] = v
return
}
func (p *UpdatePhysicalNetworkParams) SetTags(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["tags"] = v
return
}
func (p *UpdatePhysicalNetworkParams) SetVlan(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vlan"] = v
return
}
// You should always use this function to get a new UpdatePhysicalNetworkParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewUpdatePhysicalNetworkParams(id string) *UpdatePhysicalNetworkParams {
p := &UpdatePhysicalNetworkParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Updates a physical network
func (s *NetworkService) UpdatePhysicalNetwork(p *UpdatePhysicalNetworkParams) (*UpdatePhysicalNetworkResponse, error) {
resp, err := s.cs.newRequest("updatePhysicalNetwork", p.toURLValues())
if err != nil {
return nil, err
}
var r UpdatePhysicalNetworkResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UpdatePhysicalNetworkResponse struct {
JobID string `json:"jobid,omitempty"`
Broadcastdomainrange string `json:"broadcastdomainrange,omitempty"`
Domainid string `json:"domainid,omitempty"`
Id string `json:"id,omitempty"`
Isolationmethods string `json:"isolationmethods,omitempty"`
Name string `json:"name,omitempty"`
Networkspeed string `json:"networkspeed,omitempty"`
State string `json:"state,omitempty"`
Tags string `json:"tags,omitempty"`
Vlan string `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type ListSupportedNetworkServicesParams struct {
p map[string]interface{}
}
func (p *ListSupportedNetworkServicesParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["provider"]; found {
u.Set("provider", v.(string))
}
if v, found := p.p["service"]; found {
u.Set("service", v.(string))
}
return u
}
func (p *ListSupportedNetworkServicesParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListSupportedNetworkServicesParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListSupportedNetworkServicesParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListSupportedNetworkServicesParams) SetProvider(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["provider"] = v
return
}
func (p *ListSupportedNetworkServicesParams) SetService(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["service"] = v
return
}
// You should always use this function to get a new ListSupportedNetworkServicesParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListSupportedNetworkServicesParams() *ListSupportedNetworkServicesParams {
p := &ListSupportedNetworkServicesParams{}
p.p = make(map[string]interface{})
return p
}
// Lists all network services provided by CloudStack or for the given Provider.
func (s *NetworkService) ListSupportedNetworkServices(p *ListSupportedNetworkServicesParams) (*ListSupportedNetworkServicesResponse, error) {
resp, err := s.cs.newRequest("listSupportedNetworkServices", p.toURLValues())
if err != nil {
return nil, err
}
var r ListSupportedNetworkServicesResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListSupportedNetworkServicesResponse struct {
Count int `json:"count"`
SupportedNetworkServices []*SupportedNetworkService `json:"supportednetworkservice"`
}
type SupportedNetworkService struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
}
type AddNetworkServiceProviderParams struct {
p map[string]interface{}
}
func (p *AddNetworkServiceProviderParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["destinationphysicalnetworkid"]; found {
u.Set("destinationphysicalnetworkid", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["servicelist"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("servicelist", vv)
}
return u
}
func (p *AddNetworkServiceProviderParams) SetDestinationphysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["destinationphysicalnetworkid"] = v
return
}
func (p *AddNetworkServiceProviderParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *AddNetworkServiceProviderParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *AddNetworkServiceProviderParams) SetServicelist(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["servicelist"] = v
return
}
// You should always use this function to get a new AddNetworkServiceProviderParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewAddNetworkServiceProviderParams(name string, physicalnetworkid string) *AddNetworkServiceProviderParams {
p := &AddNetworkServiceProviderParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
p.p["physicalnetworkid"] = physicalnetworkid
return p
}
// Adds a network serviceProvider to a physical network
func (s *NetworkService) AddNetworkServiceProvider(p *AddNetworkServiceProviderParams) (*AddNetworkServiceProviderResponse, error) {
resp, err := s.cs.newRequest("addNetworkServiceProvider", p.toURLValues())
if err != nil {
return nil, err
}
var r AddNetworkServiceProviderResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AddNetworkServiceProviderResponse struct {
JobID string `json:"jobid,omitempty"`
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
}
type DeleteNetworkServiceProviderParams struct {
p map[string]interface{}
}
func (p *DeleteNetworkServiceProviderParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DeleteNetworkServiceProviderParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DeleteNetworkServiceProviderParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewDeleteNetworkServiceProviderParams(id string) *DeleteNetworkServiceProviderParams {
p := &DeleteNetworkServiceProviderParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Deletes a Network Service Provider.
func (s *NetworkService) DeleteNetworkServiceProvider(p *DeleteNetworkServiceProviderParams) (*DeleteNetworkServiceProviderResponse, error) {
resp, err := s.cs.newRequest("deleteNetworkServiceProvider", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteNetworkServiceProviderResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeleteNetworkServiceProviderResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListNetworkServiceProvidersParams struct {
p map[string]interface{}
}
func (p *ListNetworkServiceProvidersParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["name"]; found {
u.Set("name", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["state"]; found {
u.Set("state", v.(string))
}
return u
}
func (p *ListNetworkServiceProvidersParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListNetworkServiceProvidersParams) SetName(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["name"] = v
return
}
func (p *ListNetworkServiceProvidersParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListNetworkServiceProvidersParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListNetworkServiceProvidersParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *ListNetworkServiceProvidersParams) SetState(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["state"] = v
return
}
// You should always use this function to get a new ListNetworkServiceProvidersParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListNetworkServiceProvidersParams() *ListNetworkServiceProvidersParams {
p := &ListNetworkServiceProvidersParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetNetworkServiceProviderID(name string) (string, error) {
p := &ListNetworkServiceProvidersParams{}
p.p = make(map[string]interface{})
p.p["name"] = name
l, err := s.ListNetworkServiceProviders(p)
if err != nil {
return "", err
}
if l.Count == 0 {
return "", fmt.Errorf("No match found for %s: %+v", name, l)
}
if l.Count == 1 {
return l.NetworkServiceProviders[0].Id, nil
}
if l.Count > 1 {
for _, v := range l.NetworkServiceProviders {
if v.Name == name {
return v.Id, nil
}
}
}
return "", fmt.Errorf("Could not find an exact match for %s: %+v", name, l)
}
// Lists network serviceproviders for a given physical network.
func (s *NetworkService) ListNetworkServiceProviders(p *ListNetworkServiceProvidersParams) (*ListNetworkServiceProvidersResponse, error) {
resp, err := s.cs.newRequest("listNetworkServiceProviders", p.toURLValues())
if err != nil {
return nil, err
}
var r ListNetworkServiceProvidersResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListNetworkServiceProvidersResponse struct {
Count int `json:"count"`
NetworkServiceProviders []*NetworkServiceProvider `json:"networkserviceprovider"`
}
type NetworkServiceProvider struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
}
type UpdateNetworkServiceProviderParams struct {
p map[string]interface{}
}
func (p *UpdateNetworkServiceProviderParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["servicelist"]; found {
vv := strings.Join(v.([]string), ",")
u.Set("servicelist", vv)
}
if v, found := p.p["state"]; found {
u.Set("state", v.(string))
}
return u
}
func (p *UpdateNetworkServiceProviderParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *UpdateNetworkServiceProviderParams) SetServicelist(v []string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["servicelist"] = v
return
}
func (p *UpdateNetworkServiceProviderParams) SetState(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["state"] = v
return
}
// You should always use this function to get a new UpdateNetworkServiceProviderParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewUpdateNetworkServiceProviderParams(id string) *UpdateNetworkServiceProviderParams {
p := &UpdateNetworkServiceProviderParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Updates a network serviceProvider of a physical network
func (s *NetworkService) UpdateNetworkServiceProvider(p *UpdateNetworkServiceProviderParams) (*UpdateNetworkServiceProviderResponse, error) {
resp, err := s.cs.newRequest("updateNetworkServiceProvider", p.toURLValues())
if err != nil {
return nil, err
}
var r UpdateNetworkServiceProviderResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UpdateNetworkServiceProviderResponse struct {
JobID string `json:"jobid,omitempty"`
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
}
type CreateStorageNetworkIpRangeParams struct {
p map[string]interface{}
}
func (p *CreateStorageNetworkIpRangeParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["endip"]; found {
u.Set("endip", v.(string))
}
if v, found := p.p["gateway"]; found {
u.Set("gateway", v.(string))
}
if v, found := p.p["netmask"]; found {
u.Set("netmask", v.(string))
}
if v, found := p.p["podid"]; found {
u.Set("podid", v.(string))
}
if v, found := p.p["startip"]; found {
u.Set("startip", v.(string))
}
if v, found := p.p["vlan"]; found {
vv := strconv.Itoa(v.(int))
u.Set("vlan", vv)
}
return u
}
func (p *CreateStorageNetworkIpRangeParams) SetEndip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["endip"] = v
return
}
func (p *CreateStorageNetworkIpRangeParams) SetGateway(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["gateway"] = v
return
}
func (p *CreateStorageNetworkIpRangeParams) SetNetmask(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["netmask"] = v
return
}
func (p *CreateStorageNetworkIpRangeParams) SetPodid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["podid"] = v
return
}
func (p *CreateStorageNetworkIpRangeParams) SetStartip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startip"] = v
return
}
func (p *CreateStorageNetworkIpRangeParams) SetVlan(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vlan"] = v
return
}
// You should always use this function to get a new CreateStorageNetworkIpRangeParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewCreateStorageNetworkIpRangeParams(gateway string, netmask string, podid string, startip string) *CreateStorageNetworkIpRangeParams {
p := &CreateStorageNetworkIpRangeParams{}
p.p = make(map[string]interface{})
p.p["gateway"] = gateway
p.p["netmask"] = netmask
p.p["podid"] = podid
p.p["startip"] = startip
return p
}
// Creates a Storage network IP range.
func (s *NetworkService) CreateStorageNetworkIpRange(p *CreateStorageNetworkIpRangeParams) (*CreateStorageNetworkIpRangeResponse, error) {
resp, err := s.cs.newRequest("createStorageNetworkIpRange", p.toURLValues())
if err != nil {
return nil, err
}
var r CreateStorageNetworkIpRangeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type CreateStorageNetworkIpRangeResponse struct {
JobID string `json:"jobid,omitempty"`
Endip string `json:"endip,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkid string `json:"networkid,omitempty"`
Podid string `json:"podid,omitempty"`
Startip string `json:"startip,omitempty"`
Vlan int `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type DeleteStorageNetworkIpRangeParams struct {
p map[string]interface{}
}
func (p *DeleteStorageNetworkIpRangeParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DeleteStorageNetworkIpRangeParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DeleteStorageNetworkIpRangeParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewDeleteStorageNetworkIpRangeParams(id string) *DeleteStorageNetworkIpRangeParams {
p := &DeleteStorageNetworkIpRangeParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Deletes a storage network IP Range.
func (s *NetworkService) DeleteStorageNetworkIpRange(p *DeleteStorageNetworkIpRangeParams) (*DeleteStorageNetworkIpRangeResponse, error) {
resp, err := s.cs.newRequest("deleteStorageNetworkIpRange", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteStorageNetworkIpRangeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeleteStorageNetworkIpRangeResponse struct {
JobID string `json:"jobid,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Success bool `json:"success,omitempty"`
}
type ListStorageNetworkIpRangeParams struct {
p map[string]interface{}
}
func (p *ListStorageNetworkIpRangeParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
if v, found := p.p["podid"]; found {
u.Set("podid", v.(string))
}
if v, found := p.p["zoneid"]; found {
u.Set("zoneid", v.(string))
}
return u
}
func (p *ListStorageNetworkIpRangeParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListStorageNetworkIpRangeParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListStorageNetworkIpRangeParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListStorageNetworkIpRangeParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
func (p *ListStorageNetworkIpRangeParams) SetPodid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["podid"] = v
return
}
func (p *ListStorageNetworkIpRangeParams) SetZoneid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["zoneid"] = v
return
}
// You should always use this function to get a new ListStorageNetworkIpRangeParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListStorageNetworkIpRangeParams() *ListStorageNetworkIpRangeParams {
p := &ListStorageNetworkIpRangeParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetStorageNetworkIpRangeByID(id string) (*StorageNetworkIpRange, int, error) {
p := &ListStorageNetworkIpRangeParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
l, err := s.ListStorageNetworkIpRange(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.StorageNetworkIpRange[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for StorageNetworkIpRange UUID: %s!", id)
}
// List a storage network IP range.
func (s *NetworkService) ListStorageNetworkIpRange(p *ListStorageNetworkIpRangeParams) (*ListStorageNetworkIpRangeResponse, error) {
resp, err := s.cs.newRequest("listStorageNetworkIpRange", p.toURLValues())
if err != nil {
return nil, err
}
var r ListStorageNetworkIpRangeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListStorageNetworkIpRangeResponse struct {
Count int `json:"count"`
StorageNetworkIpRange []*StorageNetworkIpRange `json:"storagenetworkiprange"`
}
type StorageNetworkIpRange struct {
Endip string `json:"endip,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkid string `json:"networkid,omitempty"`
Podid string `json:"podid,omitempty"`
Startip string `json:"startip,omitempty"`
Vlan int `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type UpdateStorageNetworkIpRangeParams struct {
p map[string]interface{}
}
func (p *UpdateStorageNetworkIpRangeParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["endip"]; found {
u.Set("endip", v.(string))
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["netmask"]; found {
u.Set("netmask", v.(string))
}
if v, found := p.p["startip"]; found {
u.Set("startip", v.(string))
}
if v, found := p.p["vlan"]; found {
vv := strconv.Itoa(v.(int))
u.Set("vlan", vv)
}
return u
}
func (p *UpdateStorageNetworkIpRangeParams) SetEndip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["endip"] = v
return
}
func (p *UpdateStorageNetworkIpRangeParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *UpdateStorageNetworkIpRangeParams) SetNetmask(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["netmask"] = v
return
}
func (p *UpdateStorageNetworkIpRangeParams) SetStartip(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["startip"] = v
return
}
func (p *UpdateStorageNetworkIpRangeParams) SetVlan(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["vlan"] = v
return
}
// You should always use this function to get a new UpdateStorageNetworkIpRangeParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewUpdateStorageNetworkIpRangeParams(id string) *UpdateStorageNetworkIpRangeParams {
p := &UpdateStorageNetworkIpRangeParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Update a Storage network IP range, only allowed when no IPs in this range have been allocated.
func (s *NetworkService) UpdateStorageNetworkIpRange(p *UpdateStorageNetworkIpRangeParams) (*UpdateStorageNetworkIpRangeResponse, error) {
resp, err := s.cs.newRequest("updateStorageNetworkIpRange", p.toURLValues())
if err != nil {
return nil, err
}
var r UpdateStorageNetworkIpRangeResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type UpdateStorageNetworkIpRangeResponse struct {
JobID string `json:"jobid,omitempty"`
Endip string `json:"endip,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkid string `json:"networkid,omitempty"`
Podid string `json:"podid,omitempty"`
Startip string `json:"startip,omitempty"`
Vlan int `json:"vlan,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
}
type ListPaloAltoFirewallNetworksParams struct {
p map[string]interface{}
}
func (p *ListPaloAltoFirewallNetworksParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["lbdeviceid"]; found {
u.Set("lbdeviceid", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
func (p *ListPaloAltoFirewallNetworksParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListPaloAltoFirewallNetworksParams) SetLbdeviceid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["lbdeviceid"] = v
return
}
func (p *ListPaloAltoFirewallNetworksParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListPaloAltoFirewallNetworksParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
// You should always use this function to get a new ListPaloAltoFirewallNetworksParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListPaloAltoFirewallNetworksParams(lbdeviceid string) *ListPaloAltoFirewallNetworksParams {
p := &ListPaloAltoFirewallNetworksParams{}
p.p = make(map[string]interface{})
p.p["lbdeviceid"] = lbdeviceid
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetPaloAltoFirewallNetworkID(keyword string, lbdeviceid string) (string, error) {
p := &ListPaloAltoFirewallNetworksParams{}
p.p = make(map[string]interface{})
p.p["keyword"] = keyword
p.p["lbdeviceid"] = lbdeviceid
l, err := s.ListPaloAltoFirewallNetworks(p)
if err != nil {
return "", err
}
if l.Count == 0 {
return "", fmt.Errorf("No match found for %s: %+v", keyword, l)
}
if l.Count == 1 {
return l.PaloAltoFirewallNetworks[0].Id, nil
}
if l.Count > 1 {
for _, v := range l.PaloAltoFirewallNetworks {
if v.Name == keyword {
return v.Id, nil
}
}
}
return "", fmt.Errorf("Could not find an exact match for %s: %+v", keyword, l)
}
// lists network that are using Palo Alto firewall device
func (s *NetworkService) ListPaloAltoFirewallNetworks(p *ListPaloAltoFirewallNetworksParams) (*ListPaloAltoFirewallNetworksResponse, error) {
resp, err := s.cs.newRequest("listPaloAltoFirewallNetworks", p.toURLValues())
if err != nil {
return nil, err
}
var r ListPaloAltoFirewallNetworksResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListPaloAltoFirewallNetworksResponse struct {
Count int `json:"count"`
PaloAltoFirewallNetworks []*PaloAltoFirewallNetwork `json:"paloaltofirewallnetwork"`
}
type PaloAltoFirewallNetwork struct {
Account string `json:"account,omitempty"`
Aclid string `json:"aclid,omitempty"`
Acltype string `json:"acltype,omitempty"`
Broadcastdomaintype string `json:"broadcastdomaintype,omitempty"`
Broadcasturi string `json:"broadcasturi,omitempty"`
Canusefordeploy bool `json:"canusefordeploy,omitempty"`
Cidr string `json:"cidr,omitempty"`
Displaynetwork bool `json:"displaynetwork,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Dns1 string `json:"dns1,omitempty"`
Dns2 string `json:"dns2,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Ispersistent bool `json:"ispersistent,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Name string `json:"name,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkcidr string `json:"networkcidr,omitempty"`
Networkdomain string `json:"networkdomain,omitempty"`
Networkofferingavailability string `json:"networkofferingavailability,omitempty"`
Networkofferingconservemode bool `json:"networkofferingconservemode,omitempty"`
Networkofferingdisplaytext string `json:"networkofferingdisplaytext,omitempty"`
Networkofferingid string `json:"networkofferingid,omitempty"`
Networkofferingname string `json:"networkofferingname,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Related string `json:"related,omitempty"`
Reservediprange string `json:"reservediprange,omitempty"`
Restartrequired bool `json:"restartrequired,omitempty"`
Service []struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
} `json:"service,omitempty"`
Specifyipranges bool `json:"specifyipranges,omitempty"`
State string `json:"state,omitempty"`
Strechedl2subnet bool `json:"strechedl2subnet,omitempty"`
Subdomainaccess bool `json:"subdomainaccess,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Vlan string `json:"vlan,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
Zonesnetworkspans []string `json:"zonesnetworkspans,omitempty"`
}
type ListNetscalerLoadBalancerNetworksParams struct {
p map[string]interface{}
}
func (p *ListNetscalerLoadBalancerNetworksParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["lbdeviceid"]; found {
u.Set("lbdeviceid", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
func (p *ListNetscalerLoadBalancerNetworksParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListNetscalerLoadBalancerNetworksParams) SetLbdeviceid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["lbdeviceid"] = v
return
}
func (p *ListNetscalerLoadBalancerNetworksParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListNetscalerLoadBalancerNetworksParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
// You should always use this function to get a new ListNetscalerLoadBalancerNetworksParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListNetscalerLoadBalancerNetworksParams(lbdeviceid string) *ListNetscalerLoadBalancerNetworksParams {
p := &ListNetscalerLoadBalancerNetworksParams{}
p.p = make(map[string]interface{})
p.p["lbdeviceid"] = lbdeviceid
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetNetscalerLoadBalancerNetworkID(keyword string, lbdeviceid string) (string, error) {
p := &ListNetscalerLoadBalancerNetworksParams{}
p.p = make(map[string]interface{})
p.p["keyword"] = keyword
p.p["lbdeviceid"] = lbdeviceid
l, err := s.ListNetscalerLoadBalancerNetworks(p)
if err != nil {
return "", err
}
if l.Count == 0 {
return "", fmt.Errorf("No match found for %s: %+v", keyword, l)
}
if l.Count == 1 {
return l.NetscalerLoadBalancerNetworks[0].Id, nil
}
if l.Count > 1 {
for _, v := range l.NetscalerLoadBalancerNetworks {
if v.Name == keyword {
return v.Id, nil
}
}
}
return "", fmt.Errorf("Could not find an exact match for %s: %+v", keyword, l)
}
// lists network that are using a netscaler load balancer device
func (s *NetworkService) ListNetscalerLoadBalancerNetworks(p *ListNetscalerLoadBalancerNetworksParams) (*ListNetscalerLoadBalancerNetworksResponse, error) {
resp, err := s.cs.newRequest("listNetscalerLoadBalancerNetworks", p.toURLValues())
if err != nil {
return nil, err
}
var r ListNetscalerLoadBalancerNetworksResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListNetscalerLoadBalancerNetworksResponse struct {
Count int `json:"count"`
NetscalerLoadBalancerNetworks []*NetscalerLoadBalancerNetwork `json:"netscalerloadbalancernetwork"`
}
type NetscalerLoadBalancerNetwork struct {
Account string `json:"account,omitempty"`
Aclid string `json:"aclid,omitempty"`
Acltype string `json:"acltype,omitempty"`
Broadcastdomaintype string `json:"broadcastdomaintype,omitempty"`
Broadcasturi string `json:"broadcasturi,omitempty"`
Canusefordeploy bool `json:"canusefordeploy,omitempty"`
Cidr string `json:"cidr,omitempty"`
Displaynetwork bool `json:"displaynetwork,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Dns1 string `json:"dns1,omitempty"`
Dns2 string `json:"dns2,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Ispersistent bool `json:"ispersistent,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Name string `json:"name,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkcidr string `json:"networkcidr,omitempty"`
Networkdomain string `json:"networkdomain,omitempty"`
Networkofferingavailability string `json:"networkofferingavailability,omitempty"`
Networkofferingconservemode bool `json:"networkofferingconservemode,omitempty"`
Networkofferingdisplaytext string `json:"networkofferingdisplaytext,omitempty"`
Networkofferingid string `json:"networkofferingid,omitempty"`
Networkofferingname string `json:"networkofferingname,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Related string `json:"related,omitempty"`
Reservediprange string `json:"reservediprange,omitempty"`
Restartrequired bool `json:"restartrequired,omitempty"`
Service []struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
} `json:"service,omitempty"`
Specifyipranges bool `json:"specifyipranges,omitempty"`
State string `json:"state,omitempty"`
Strechedl2subnet bool `json:"strechedl2subnet,omitempty"`
Subdomainaccess bool `json:"subdomainaccess,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Vlan string `json:"vlan,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
Zonesnetworkspans []string `json:"zonesnetworkspans,omitempty"`
}
type ListNiciraNvpDeviceNetworksParams struct {
p map[string]interface{}
}
func (p *ListNiciraNvpDeviceNetworksParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["nvpdeviceid"]; found {
u.Set("nvpdeviceid", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
func (p *ListNiciraNvpDeviceNetworksParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListNiciraNvpDeviceNetworksParams) SetNvpdeviceid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["nvpdeviceid"] = v
return
}
func (p *ListNiciraNvpDeviceNetworksParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListNiciraNvpDeviceNetworksParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
// You should always use this function to get a new ListNiciraNvpDeviceNetworksParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListNiciraNvpDeviceNetworksParams(nvpdeviceid string) *ListNiciraNvpDeviceNetworksParams {
p := &ListNiciraNvpDeviceNetworksParams{}
p.p = make(map[string]interface{})
p.p["nvpdeviceid"] = nvpdeviceid
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetNiciraNvpDeviceNetworkID(keyword string, nvpdeviceid string) (string, error) {
p := &ListNiciraNvpDeviceNetworksParams{}
p.p = make(map[string]interface{})
p.p["keyword"] = keyword
p.p["nvpdeviceid"] = nvpdeviceid
l, err := s.ListNiciraNvpDeviceNetworks(p)
if err != nil {
return "", err
}
if l.Count == 0 {
return "", fmt.Errorf("No match found for %s: %+v", keyword, l)
}
if l.Count == 1 {
return l.NiciraNvpDeviceNetworks[0].Id, nil
}
if l.Count > 1 {
for _, v := range l.NiciraNvpDeviceNetworks {
if v.Name == keyword {
return v.Id, nil
}
}
}
return "", fmt.Errorf("Could not find an exact match for %s: %+v", keyword, l)
}
// lists network that are using a nicira nvp device
func (s *NetworkService) ListNiciraNvpDeviceNetworks(p *ListNiciraNvpDeviceNetworksParams) (*ListNiciraNvpDeviceNetworksResponse, error) {
resp, err := s.cs.newRequest("listNiciraNvpDeviceNetworks", p.toURLValues())
if err != nil {
return nil, err
}
var r ListNiciraNvpDeviceNetworksResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListNiciraNvpDeviceNetworksResponse struct {
Count int `json:"count"`
NiciraNvpDeviceNetworks []*NiciraNvpDeviceNetwork `json:"niciranvpdevicenetwork"`
}
type NiciraNvpDeviceNetwork struct {
Account string `json:"account,omitempty"`
Aclid string `json:"aclid,omitempty"`
Acltype string `json:"acltype,omitempty"`
Broadcastdomaintype string `json:"broadcastdomaintype,omitempty"`
Broadcasturi string `json:"broadcasturi,omitempty"`
Canusefordeploy bool `json:"canusefordeploy,omitempty"`
Cidr string `json:"cidr,omitempty"`
Displaynetwork bool `json:"displaynetwork,omitempty"`
Displaytext string `json:"displaytext,omitempty"`
Dns1 string `json:"dns1,omitempty"`
Dns2 string `json:"dns2,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Gateway string `json:"gateway,omitempty"`
Id string `json:"id,omitempty"`
Ip6cidr string `json:"ip6cidr,omitempty"`
Ip6gateway string `json:"ip6gateway,omitempty"`
Isdefault bool `json:"isdefault,omitempty"`
Ispersistent bool `json:"ispersistent,omitempty"`
Issystem bool `json:"issystem,omitempty"`
Name string `json:"name,omitempty"`
Netmask string `json:"netmask,omitempty"`
Networkcidr string `json:"networkcidr,omitempty"`
Networkdomain string `json:"networkdomain,omitempty"`
Networkofferingavailability string `json:"networkofferingavailability,omitempty"`
Networkofferingconservemode bool `json:"networkofferingconservemode,omitempty"`
Networkofferingdisplaytext string `json:"networkofferingdisplaytext,omitempty"`
Networkofferingid string `json:"networkofferingid,omitempty"`
Networkofferingname string `json:"networkofferingname,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Related string `json:"related,omitempty"`
Reservediprange string `json:"reservediprange,omitempty"`
Restartrequired bool `json:"restartrequired,omitempty"`
Service []struct {
Capability []struct {
Canchooseservicecapability bool `json:"canchooseservicecapability,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
} `json:"capability,omitempty"`
Name string `json:"name,omitempty"`
Provider []struct {
Canenableindividualservice bool `json:"canenableindividualservice,omitempty"`
Destinationphysicalnetworkid string `json:"destinationphysicalnetworkid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Servicelist []string `json:"servicelist,omitempty"`
State string `json:"state,omitempty"`
} `json:"provider,omitempty"`
} `json:"service,omitempty"`
Specifyipranges bool `json:"specifyipranges,omitempty"`
State string `json:"state,omitempty"`
Strechedl2subnet bool `json:"strechedl2subnet,omitempty"`
Subdomainaccess bool `json:"subdomainaccess,omitempty"`
Tags []struct {
Account string `json:"account,omitempty"`
Customer string `json:"customer,omitempty"`
Domain string `json:"domain,omitempty"`
Domainid string `json:"domainid,omitempty"`
Key string `json:"key,omitempty"`
Project string `json:"project,omitempty"`
Projectid string `json:"projectid,omitempty"`
Resourceid string `json:"resourceid,omitempty"`
Resourcetype string `json:"resourcetype,omitempty"`
Value string `json:"value,omitempty"`
} `json:"tags,omitempty"`
Traffictype string `json:"traffictype,omitempty"`
Type string `json:"type,omitempty"`
Vlan string `json:"vlan,omitempty"`
Vpcid string `json:"vpcid,omitempty"`
Zoneid string `json:"zoneid,omitempty"`
Zonename string `json:"zonename,omitempty"`
Zonesnetworkspans []string `json:"zonesnetworkspans,omitempty"`
}
type ListNetworkIsolationMethodsParams struct {
p map[string]interface{}
}
func (p *ListNetworkIsolationMethodsParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["keyword"]; found {
u.Set("keyword", v.(string))
}
if v, found := p.p["page"]; found {
vv := strconv.Itoa(v.(int))
u.Set("page", vv)
}
if v, found := p.p["pagesize"]; found {
vv := strconv.Itoa(v.(int))
u.Set("pagesize", vv)
}
return u
}
func (p *ListNetworkIsolationMethodsParams) SetKeyword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["keyword"] = v
return
}
func (p *ListNetworkIsolationMethodsParams) SetPage(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["page"] = v
return
}
func (p *ListNetworkIsolationMethodsParams) SetPagesize(v int) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["pagesize"] = v
return
}
// You should always use this function to get a new ListNetworkIsolationMethodsParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListNetworkIsolationMethodsParams() *ListNetworkIsolationMethodsParams {
p := &ListNetworkIsolationMethodsParams{}
p.p = make(map[string]interface{})
return p
}
// Lists supported methods of network isolation
func (s *NetworkService) ListNetworkIsolationMethods(p *ListNetworkIsolationMethodsParams) (*ListNetworkIsolationMethodsResponse, error) {
resp, err := s.cs.newRequest("listNetworkIsolationMethods", p.toURLValues())
if err != nil {
return nil, err
}
var r ListNetworkIsolationMethodsResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListNetworkIsolationMethodsResponse struct {
Count int `json:"count"`
NetworkIsolationMethods []*NetworkIsolationMethod `json:"networkisolationmethod"`
}
type NetworkIsolationMethod struct {
Name string `json:"name,omitempty"`
}
type AddOpenDaylightControllerParams struct {
p map[string]interface{}
}
func (p *AddOpenDaylightControllerParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["password"]; found {
u.Set("password", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
if v, found := p.p["url"]; found {
u.Set("url", v.(string))
}
if v, found := p.p["username"]; found {
u.Set("username", v.(string))
}
return u
}
func (p *AddOpenDaylightControllerParams) SetPassword(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["password"] = v
return
}
func (p *AddOpenDaylightControllerParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
func (p *AddOpenDaylightControllerParams) SetUrl(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["url"] = v
return
}
func (p *AddOpenDaylightControllerParams) SetUsername(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["username"] = v
return
}
// You should always use this function to get a new AddOpenDaylightControllerParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewAddOpenDaylightControllerParams(password string, physicalnetworkid string, url string, username string) *AddOpenDaylightControllerParams {
p := &AddOpenDaylightControllerParams{}
p.p = make(map[string]interface{})
p.p["password"] = password
p.p["physicalnetworkid"] = physicalnetworkid
p.p["url"] = url
p.p["username"] = username
return p
}
// Adds an OpenDyalight controler
func (s *NetworkService) AddOpenDaylightController(p *AddOpenDaylightControllerParams) (*AddOpenDaylightControllerResponse, error) {
resp, err := s.cs.newRequest("addOpenDaylightController", p.toURLValues())
if err != nil {
return nil, err
}
var r AddOpenDaylightControllerResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type AddOpenDaylightControllerResponse struct {
JobID string `json:"jobid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Url string `json:"url,omitempty"`
Username string `json:"username,omitempty"`
}
type DeleteOpenDaylightControllerParams struct {
p map[string]interface{}
}
func (p *DeleteOpenDaylightControllerParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
return u
}
func (p *DeleteOpenDaylightControllerParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
// You should always use this function to get a new DeleteOpenDaylightControllerParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewDeleteOpenDaylightControllerParams(id string) *DeleteOpenDaylightControllerParams {
p := &DeleteOpenDaylightControllerParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
return p
}
// Removes an OpenDyalight controler
func (s *NetworkService) DeleteOpenDaylightController(p *DeleteOpenDaylightControllerParams) (*DeleteOpenDaylightControllerResponse, error) {
resp, err := s.cs.newRequest("deleteOpenDaylightController", p.toURLValues())
if err != nil {
return nil, err
}
var r DeleteOpenDaylightControllerResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
// If we have a async client, we need to wait for the async result
if s.cs.async {
b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
if err != nil {
if err == AsyncTimeoutErr {
return &r, err
}
return nil, err
}
b, err = getRawValue(b)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &r); err != nil {
return nil, err
}
}
return &r, nil
}
type DeleteOpenDaylightControllerResponse struct {
JobID string `json:"jobid,omitempty"`
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Url string `json:"url,omitempty"`
Username string `json:"username,omitempty"`
}
type ListOpenDaylightControllersParams struct {
p map[string]interface{}
}
func (p *ListOpenDaylightControllersParams) toURLValues() url.Values {
u := url.Values{}
if p.p == nil {
return u
}
if v, found := p.p["id"]; found {
u.Set("id", v.(string))
}
if v, found := p.p["physicalnetworkid"]; found {
u.Set("physicalnetworkid", v.(string))
}
return u
}
func (p *ListOpenDaylightControllersParams) SetId(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["id"] = v
return
}
func (p *ListOpenDaylightControllersParams) SetPhysicalnetworkid(v string) {
if p.p == nil {
p.p = make(map[string]interface{})
}
p.p["physicalnetworkid"] = v
return
}
// You should always use this function to get a new ListOpenDaylightControllersParams instance,
// as then you are sure you have configured all required params
func (s *NetworkService) NewListOpenDaylightControllersParams() *ListOpenDaylightControllersParams {
p := &ListOpenDaylightControllersParams{}
p.p = make(map[string]interface{})
return p
}
// This is a courtesy helper function, which in some cases may not work as expected!
func (s *NetworkService) GetOpenDaylightControllerByID(id string) (*OpenDaylightController, int, error) {
p := &ListOpenDaylightControllersParams{}
p.p = make(map[string]interface{})
p.p["id"] = id
l, err := s.ListOpenDaylightControllers(p)
if err != nil {
if strings.Contains(err.Error(), fmt.Sprintf(
"Invalid parameter id value=%s due to incorrect long value format, "+
"or entity does not exist", id)) {
return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
}
return nil, -1, err
}
if l.Count == 0 {
return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
}
if l.Count == 1 {
return l.OpenDaylightControllers[0], l.Count, nil
}
return nil, l.Count, fmt.Errorf("There is more then one result for OpenDaylightController UUID: %s!", id)
}
// Lists OpenDyalight controllers
func (s *NetworkService) ListOpenDaylightControllers(p *ListOpenDaylightControllersParams) (*ListOpenDaylightControllersResponse, error) {
resp, err := s.cs.newRequest("listOpenDaylightControllers", p.toURLValues())
if err != nil {
return nil, err
}
var r ListOpenDaylightControllersResponse
if err := json.Unmarshal(resp, &r); err != nil {
return nil, err
}
return &r, nil
}
type ListOpenDaylightControllersResponse struct {
Count int `json:"count"`
OpenDaylightControllers []*OpenDaylightController `json:"opendaylightcontroller"`
}
type OpenDaylightController struct {
Id string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Physicalnetworkid string `json:"physicalnetworkid,omitempty"`
Url string `json:"url,omitempty"`
Username string `json:"username,omitempty"`
}
|
ZZelle/terraform
|
vendor/github.com/xanzy/go-cloudstack/cloudstack/NetworkService.go
|
GO
|
mpl-2.0
| 116,376
|
/* The following code is the modified part of the libxml
* available at http://xmlsoft.org
* under the terms of the MIT License
* http://opensource.org/licenses/mit-license.html
*/
/*
* xinclude.c : Code to implement XInclude processing
*
* World Wide Web Consortium W3C Last Call Working Draft 10 November 2003
* http://www.w3.org/TR/2003/WD-xinclude-20031110
*
* See Copyright for the status of this software.
*
* daniel@veillard.com
*/
#define IN_LIBXML
#include "libxml.h"
#include <string.h>
#include <libxml/xmlmemory.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/uri.h>
#include <libxml/xpointer.h>
#include <libxml/parserInternals.h>
#include <libxml/xmlerror.h>
#include <libxml/encoding.h>
#include <libxml/globals.h>
#ifdef LIBXML_XINCLUDE_ENABLED
#include <libxml/xinclude.h>
#define XINCLUDE_MAX_DEPTH 40
/* #define DEBUG_XINCLUDE */
#ifdef DEBUG_XINCLUDE
#ifdef LIBXML_DEBUG_ENABLED
#include <libxml/debugXML.h>
#endif
#endif
/************************************************************************
* *
* XInclude context handling *
* *
************************************************************************/
/*
* An XInclude context
*/
typedef xmlChar *xmlURL;
typedef struct _xmlXIncludeRef xmlXIncludeRef;
typedef xmlXIncludeRef *xmlXIncludeRefPtr;
struct _xmlXIncludeRef {
xmlChar *URI; /* the fully resolved resource URL */
xmlChar *fragment; /* the fragment in the URI */
xmlDocPtr doc; /* the parsed document */
xmlNodePtr ref; /* the node making the reference in the source */
xmlNodePtr inc; /* the included copy */
int xml; /* xml or txt */
int count; /* how many refs use that specific doc */
xmlXPathObjectPtr xptr; /* the xpointer if needed */
int emptyFb; /* flag to show fallback empty */
};
struct _xmlXIncludeCtxt {
xmlDocPtr doc; /* the source document */
int incBase; /* the first include for this document */
int incNr; /* number of includes */
int incMax; /* size of includes tab */
xmlXIncludeRefPtr *incTab; /* array of included references */
int txtNr; /* number of unparsed documents */
int txtMax; /* size of unparsed documents tab */
xmlNodePtr *txtTab; /* array of unparsed text nodes */
xmlURL *txturlTab; /* array of unparsed text URLs */
xmlChar * url; /* the current URL processed */
int urlNr; /* number of URLs stacked */
int urlMax; /* size of URL stack */
xmlChar * *urlTab; /* URL stack */
int nbErrors; /* the number of errors detected */
int legacy; /* using XINCLUDE_OLD_NS */
int parseFlags; /* the flags used for parsing XML documents */
xmlChar * base; /* the current xml:base */
void *_private; /* application data */
};
static int
xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr tree);
/************************************************************************
* *
* XInclude error handler *
* *
************************************************************************/
/**
* xmlXIncludeErrMemory:
* @extra: extra information
*
* Handle an out of memory condition
*/
static void
xmlXIncludeErrMemory(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node,
const char *extra)
{
if (ctxt != NULL)
ctxt->nbErrors++;
__xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_XINCLUDE,
XML_ERR_NO_MEMORY, XML_ERR_ERROR, NULL, 0,
extra, NULL, NULL, 0, 0,
"Memory allocation failed : %s\n", extra);
}
/**
* xmlXIncludeErr:
* @ctxt: the XInclude context
* @node: the context node
* @msg: the error message
* @extra: extra information
*
* Handle an XInclude error
*/
static void
xmlXIncludeErr(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node, int error,
const char *msg, const xmlChar *extra)
{
if (ctxt != NULL)
ctxt->nbErrors++;
__xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_XINCLUDE,
error, XML_ERR_ERROR, NULL, 0,
(const char *) extra, NULL, NULL, 0, 0,
msg, (const char *) extra);
}
#if 0
/**
* xmlXIncludeWarn:
* @ctxt: the XInclude context
* @node: the context node
* @msg: the error message
* @extra: extra information
*
* Emit an XInclude warning.
*/
static void
xmlXIncludeWarn(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node, int error,
const char *msg, const xmlChar *extra)
{
__xmlRaiseError(NULL, NULL, NULL, ctxt, node, XML_FROM_XINCLUDE,
error, XML_ERR_WARNING, NULL, 0,
(const char *) extra, NULL, NULL, 0, 0,
msg, (const char *) extra);
}
#endif
/**
* xmlXIncludeGetProp:
* @ctxt: the XInclude context
* @cur: the node
* @name: the attribute name
*
* Get an XInclude attribute
*
* Returns the value (to be freed) or NULL if not found
*/
static xmlChar *
xmlXIncludeGetProp(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur,
const xmlChar *name) {
xmlChar *ret;
ret = xmlGetNsProp(cur, XINCLUDE_NS, name);
if (ret != NULL)
return(ret);
if (ctxt->legacy != 0) {
ret = xmlGetNsProp(cur, XINCLUDE_OLD_NS, name);
if (ret != NULL)
return(ret);
}
ret = xmlGetProp(cur, name);
return(ret);
}
/**
* xmlXIncludeFreeRef:
* @ref: the XInclude reference
*
* Free an XInclude reference
*/
static void
xmlXIncludeFreeRef(xmlXIncludeRefPtr ref) {
if (ref == NULL)
return;
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Freeing ref\n");
#endif
if (ref->doc != NULL) {
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Freeing doc %s\n", ref->URI);
#endif
xmlFreeDoc(ref->doc);
}
if (ref->URI != NULL)
xmlFree(ref->URI);
if (ref->fragment != NULL)
xmlFree(ref->fragment);
if (ref->xptr != NULL)
xmlXPathFreeObject(ref->xptr);
xmlFree(ref);
}
/**
* xmlXIncludeNewRef:
* @ctxt: the XInclude context
* @URI: the resource URI
*
* Creates a new reference within an XInclude context
*
* Returns the new set
*/
static xmlXIncludeRefPtr
xmlXIncludeNewRef(xmlXIncludeCtxtPtr ctxt, const xmlChar *URI,
xmlNodePtr ref) {
xmlXIncludeRefPtr ret;
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "New ref %s\n", URI);
#endif
ret = (xmlXIncludeRefPtr) xmlMalloc(sizeof(xmlXIncludeRef));
if (ret == NULL) {
xmlXIncludeErrMemory(ctxt, ref, "growing XInclude context");
return(NULL);
}
memset(ret, 0, sizeof(xmlXIncludeRef));
if (URI == NULL)
ret->URI = NULL;
else
ret->URI = xmlStrdup(URI);
ret->fragment = NULL;
ret->ref = ref;
ret->doc = NULL;
ret->count = 0;
ret->xml = 0;
ret->inc = NULL;
if (ctxt->incMax == 0) {
ctxt->incMax = 4;
ctxt->incTab = (xmlXIncludeRefPtr *) xmlMalloc(ctxt->incMax *
sizeof(ctxt->incTab[0]));
if (ctxt->incTab == NULL) {
xmlXIncludeErrMemory(ctxt, ref, "growing XInclude context");
xmlXIncludeFreeRef(ret);
return(NULL);
}
}
if (ctxt->incNr >= ctxt->incMax) {
ctxt->incMax *= 2;
ctxt->incTab = (xmlXIncludeRefPtr *) xmlRealloc(ctxt->incTab,
ctxt->incMax * sizeof(ctxt->incTab[0]));
if (ctxt->incTab == NULL) {
xmlXIncludeErrMemory(ctxt, ref, "growing XInclude context");
xmlXIncludeFreeRef(ret);
return(NULL);
}
}
ctxt->incTab[ctxt->incNr++] = ret;
return(ret);
}
/**
* xmlXIncludeNewContext:
* @doc: an XML Document
*
* Creates a new XInclude context
*
* Returns the new set
*/
xmlXIncludeCtxtPtr
xmlXIncludeNewContext(xmlDocPtr doc) {
xmlXIncludeCtxtPtr ret;
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "New context\n");
#endif
if (doc == NULL)
return(NULL);
ret = (xmlXIncludeCtxtPtr) xmlMalloc(sizeof(xmlXIncludeCtxt));
if (ret == NULL) {
xmlXIncludeErrMemory(NULL, (xmlNodePtr) doc,
"creating XInclude context");
return(NULL);
}
memset(ret, 0, sizeof(xmlXIncludeCtxt));
ret->doc = doc;
ret->incNr = 0;
ret->incBase = 0;
ret->incMax = 0;
ret->incTab = NULL;
ret->nbErrors = 0;
return(ret);
}
/**
* xmlXIncludeURLPush:
* @ctxt: the parser context
* @value: the url
*
* Pushes a new url on top of the url stack
*
* Returns -1 in case of error, the index in the stack otherwise
*/
static int
xmlXIncludeURLPush(xmlXIncludeCtxtPtr ctxt,
const xmlChar *value)
{
if (ctxt->urlNr > XINCLUDE_MAX_DEPTH) {
xmlXIncludeErr(ctxt, NULL, XML_XINCLUDE_RECURSION,
"detected a recursion in %s\n", value);
return(-1);
}
if (ctxt->urlTab == NULL) {
ctxt->urlMax = 4;
ctxt->urlNr = 0;
ctxt->urlTab = (xmlChar * *) xmlMalloc(
ctxt->urlMax * sizeof(ctxt->urlTab[0]));
if (ctxt->urlTab == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "adding URL");
return (-1);
}
}
if (ctxt->urlNr >= ctxt->urlMax) {
ctxt->urlMax *= 2;
ctxt->urlTab =
(xmlChar * *) xmlRealloc(ctxt->urlTab,
ctxt->urlMax *
sizeof(ctxt->urlTab[0]));
if (ctxt->urlTab == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "adding URL");
return (-1);
}
}
ctxt->url = ctxt->urlTab[ctxt->urlNr] = xmlStrdup(value);
return (ctxt->urlNr++);
}
/**
* xmlXIncludeURLPop:
* @ctxt: the parser context
*
* Pops the top URL from the URL stack
*/
static void
xmlXIncludeURLPop(xmlXIncludeCtxtPtr ctxt)
{
xmlChar * ret;
if (ctxt->urlNr <= 0)
return;
ctxt->urlNr--;
if (ctxt->urlNr > 0)
ctxt->url = ctxt->urlTab[ctxt->urlNr - 1];
else
ctxt->url = NULL;
ret = ctxt->urlTab[ctxt->urlNr];
ctxt->urlTab[ctxt->urlNr] = NULL;
if (ret != NULL)
xmlFree(ret);
}
/**
* xmlXIncludeFreeContext:
* @ctxt: the XInclude context
*
* Free an XInclude context
*/
void
xmlXIncludeFreeContext(xmlXIncludeCtxtPtr ctxt) {
int i;
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Freeing context\n");
#endif
if (ctxt == NULL)
return;
while (ctxt->urlNr > 0)
xmlXIncludeURLPop(ctxt);
if (ctxt->urlTab != NULL)
xmlFree(ctxt->urlTab);
for (i = 0;i < ctxt->incNr;i++) {
if (ctxt->incTab[i] != NULL)
xmlXIncludeFreeRef(ctxt->incTab[i]);
}
if (ctxt->txturlTab != NULL) {
for (i = 0;i < ctxt->txtNr;i++) {
if (ctxt->txturlTab[i] != NULL)
xmlFree(ctxt->txturlTab[i]);
}
}
if (ctxt->incTab != NULL)
xmlFree(ctxt->incTab);
if (ctxt->txtTab != NULL)
xmlFree(ctxt->txtTab);
if (ctxt->txturlTab != NULL)
xmlFree(ctxt->txturlTab);
if (ctxt->base != NULL) {
xmlFree(ctxt->base);
}
xmlFree(ctxt);
}
/**
* xmlXIncludeParseFile:
* @ctxt: the XInclude context
* @URL: the URL or file path
*
* parse a document for XInclude
*/
static xmlDocPtr
xmlXIncludeParseFile(xmlXIncludeCtxtPtr ctxt, const char *URL) {
xmlDocPtr ret;
xmlParserCtxtPtr pctxt;
char *directory = NULL;
xmlParserInputPtr inputStream;
xmlInitParser();
pctxt = xmlNewParserCtxt();
if (pctxt == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "cannot allocate parser context");
return(NULL);
}
/*
* pass in the application data to the parser context.
*/
pctxt->_private = ctxt->_private;
/*
* try to ensure that new documents included are actually
* built with the same dictionary as the including document.
*/
if ((ctxt->doc != NULL) && (ctxt->doc->dict != NULL) &&
(pctxt->dict != NULL)) {
xmlDictFree(pctxt->dict);
pctxt->dict = ctxt->doc->dict;
xmlDictReference(pctxt->dict);
}
xmlCtxtUseOptions(pctxt, ctxt->parseFlags | XML_PARSE_DTDLOAD);
inputStream = xmlLoadExternalEntity(URL, NULL, pctxt);
if (inputStream == NULL) {
xmlFreeParserCtxt(pctxt);
return(NULL);
}
inputPush(pctxt, inputStream);
if ((pctxt->directory == NULL) && (directory == NULL))
directory = xmlParserGetDirectory(URL);
if ((pctxt->directory == NULL) && (directory != NULL))
pctxt->directory = (char *) xmlStrdup((xmlChar *) directory);
pctxt->loadsubset |= XML_DETECT_IDS;
xmlParseDocument(pctxt);
if (pctxt->wellFormed) {
ret = pctxt->myDoc;
}
else {
ret = NULL;
if (pctxt->myDoc != NULL)
xmlFreeDoc(pctxt->myDoc);
pctxt->myDoc = NULL;
}
xmlFreeParserCtxt(pctxt);
return(ret);
}
/**
* xmlXIncludeAddNode:
* @ctxt: the XInclude context
* @cur: the new node
*
* Add a new node to process to an XInclude context
*/
static int
xmlXIncludeAddNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur) {
xmlXIncludeRefPtr ref;
xmlURIPtr uri;
xmlChar *URL;
xmlChar *fragment = NULL;
xmlChar *href;
xmlChar *parse;
xmlChar *base;
xmlChar *URI;
int xml = 1, i; /* default Issue 64 */
int local = 0;
if (ctxt == NULL)
return(-1);
if (cur == NULL)
return(-1);
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Add node\n");
#endif
/*
* read the attributes
*/
href = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_HREF);
if (href == NULL) {
href = xmlStrdup(BAD_CAST ""); /* @@@@ href is now optional */
if (href == NULL)
return(-1);
local = 1;
}
if (href[0] == '#')
local = 1;
parse = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE);
if (parse != NULL) {
if (xmlStrEqual(parse, XINCLUDE_PARSE_XML))
xml = 1;
else if (xmlStrEqual(parse, XINCLUDE_PARSE_TEXT))
xml = 0;
else {
xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_PARSE_VALUE,
"invalid value %s for 'parse'\n", parse);
if (href != NULL)
xmlFree(href);
if (parse != NULL)
xmlFree(parse);
return(-1);
}
}
/*
* compute the URI
*/
base = xmlNodeGetBase(ctxt->doc, cur);
if (base == NULL) {
URI = xmlBuildURI(href, ctxt->doc->URL);
} else {
URI = xmlBuildURI(href, base);
}
if (URI == NULL) {
xmlChar *escbase;
xmlChar *eschref;
/*
* Some escaping may be needed
*/
escbase = xmlURIEscape(base);
eschref = xmlURIEscape(href);
URI = xmlBuildURI(eschref, escbase);
if (escbase != NULL)
xmlFree(escbase);
if (eschref != NULL)
xmlFree(eschref);
}
if (parse != NULL)
xmlFree(parse);
if (href != NULL)
xmlFree(href);
if (base != NULL)
xmlFree(base);
if (URI == NULL) {
xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
"failed build URL\n", NULL);
return(-1);
}
fragment = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE_XPOINTER);
/*
* Check the URL and remove any fragment identifier
*/
uri = xmlParseURI((const char *)URI);
if (uri == NULL) {
xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", URI);
if (fragment != NULL)
xmlFree(fragment);
xmlFree(URI);
return(-1);
}
if (uri->fragment != NULL) {
if (ctxt->legacy != 0) {
if (fragment == NULL) {
fragment = (xmlChar *) uri->fragment;
} else {
xmlFree(uri->fragment);
}
} else {
xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_FRAGMENT_ID,
"Invalid fragment identifier in URI %s use the xpointer attribute\n",
URI);
if (fragment != NULL)
xmlFree(fragment);
xmlFreeURI(uri);
xmlFree(URI);
return(-1);
}
uri->fragment = NULL;
}
URL = xmlSaveUri(uri);
xmlFreeURI(uri);
xmlFree(URI);
if (URL == NULL) {
xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", URI);
if (fragment != NULL)
xmlFree(fragment);
return(-1);
}
/*
* Check the URL against the stack for recursions
*/
if ((!local) && (xml == 1)) {
for (i = 0;i < ctxt->urlNr;i++) {
if (xmlStrEqual(URL, ctxt->urlTab[i])) {
xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_RECURSION,
"detected a recursion in %s\n", URL);
return(-1);
}
}
}
ref = xmlXIncludeNewRef(ctxt, URL, cur);
if (ref == NULL) {
return(-1);
}
ref->fragment = fragment;
ref->doc = NULL;
ref->xml = xml;
ref->count = 1;
xmlFree(URL);
return(0);
}
/**
* xmlXIncludeRecurseDoc:
* @ctxt: the XInclude context
* @doc: the new document
* @url: the associated URL
*
* The XInclude recursive nature is handled at this point.
*/
static void
xmlXIncludeRecurseDoc(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
const xmlURL url ATTRIBUTE_UNUSED) {
xmlXIncludeCtxtPtr newctxt;
int i;
/*
* Avoid recursion in already substitued resources
for (i = 0;i < ctxt->urlNr;i++) {
if (xmlStrEqual(doc->URL, ctxt->urlTab[i]))
return;
}
*/
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Recursing in doc %s\n", doc->URL);
#endif
/*
* Handle recursion here.
*/
newctxt = xmlXIncludeNewContext(doc);
if (newctxt != NULL) {
/*
* Copy the private user data
*/
newctxt->_private = ctxt->_private;
/*
* Copy the existing document set
*/
newctxt->incMax = ctxt->incMax;
newctxt->incNr = ctxt->incNr;
newctxt->incTab = (xmlXIncludeRefPtr *) xmlMalloc(newctxt->incMax *
sizeof(newctxt->incTab[0]));
if (newctxt->incTab == NULL) {
xmlXIncludeErrMemory(ctxt, (xmlNodePtr) doc, "processing doc");
xmlFree(newctxt);
return;
}
/*
* copy the urlTab
*/
newctxt->urlMax = ctxt->urlMax;
newctxt->urlNr = ctxt->urlNr;
newctxt->urlTab = ctxt->urlTab;
/*
* Inherit the existing base
*/
newctxt->base = xmlStrdup(ctxt->base);
/*
* Inherit the documents already in use by other includes
*/
newctxt->incBase = ctxt->incNr;
for (i = 0;i < ctxt->incNr;i++) {
newctxt->incTab[i] = ctxt->incTab[i];
newctxt->incTab[i]->count++; /* prevent the recursion from
freeing it */
}
/*
* The new context should also inherit the Parse Flags
* (bug 132597)
*/
newctxt->parseFlags = ctxt->parseFlags;
xmlXIncludeDoProcess(newctxt, doc, xmlDocGetRootElement(doc));
for (i = 0;i < ctxt->incNr;i++) {
newctxt->incTab[i]->count--;
newctxt->incTab[i] = NULL;
}
/* urlTab may have been reallocated */
ctxt->urlTab = newctxt->urlTab;
ctxt->urlMax = newctxt->urlMax;
newctxt->urlMax = 0;
newctxt->urlNr = 0;
newctxt->urlTab = NULL;
xmlXIncludeFreeContext(newctxt);
}
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Done recursing in doc %s\n", url);
#endif
}
/**
* xmlXIncludeAddTxt:
* @ctxt: the XInclude context
* @txt: the new text node
* @url: the associated URL
*
* Add a new txtument to the list
*/
static void
xmlXIncludeAddTxt(xmlXIncludeCtxtPtr ctxt, xmlNodePtr txt, const xmlURL url) {
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Adding text %s\n", url);
#endif
if (ctxt->txtMax == 0) {
ctxt->txtMax = 4;
ctxt->txtTab = (xmlNodePtr *) xmlMalloc(ctxt->txtMax *
sizeof(ctxt->txtTab[0]));
if (ctxt->txtTab == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "processing text");
return;
}
ctxt->txturlTab = (xmlURL *) xmlMalloc(ctxt->txtMax *
sizeof(ctxt->txturlTab[0]));
if (ctxt->txturlTab == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "processing text");
return;
}
}
if (ctxt->txtNr >= ctxt->txtMax) {
ctxt->txtMax *= 2;
ctxt->txtTab = (xmlNodePtr *) xmlRealloc(ctxt->txtTab,
ctxt->txtMax * sizeof(ctxt->txtTab[0]));
if (ctxt->txtTab == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "processing text");
return;
}
ctxt->txturlTab = (xmlURL *) xmlRealloc(ctxt->txturlTab,
ctxt->txtMax * sizeof(ctxt->txturlTab[0]));
if (ctxt->txturlTab == NULL) {
xmlXIncludeErrMemory(ctxt, NULL, "processing text");
return;
}
}
ctxt->txtTab[ctxt->txtNr] = txt;
ctxt->txturlTab[ctxt->txtNr] = xmlStrdup(url);
ctxt->txtNr++;
}
/************************************************************************
* *
* Node copy with specific semantic *
* *
************************************************************************/
/**
* xmlXIncludeCopyNode:
* @ctxt: the XInclude context
* @target: the document target
* @source: the document source
* @elem: the element
*
* Make a copy of the node while preserving the XInclude semantic
* of the Infoset copy
*/
static xmlNodePtr
xmlXIncludeCopyNode(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
xmlDocPtr source, xmlNodePtr elem) {
xmlNodePtr result = NULL;
if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
(elem == NULL))
return(NULL);
if (elem->type == XML_DTD_NODE)
return(NULL);
result = xmlDocCopyNode(elem, target, 1);
return(result);
}
/**
* xmlXIncludeCopyNodeList:
* @ctxt: the XInclude context
* @target: the document target
* @source: the document source
* @elem: the element list
*
* Make a copy of the node list while preserving the XInclude semantic
* of the Infoset copy
*/
static xmlNodePtr
xmlXIncludeCopyNodeList(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
xmlDocPtr source, xmlNodePtr elem) {
xmlNodePtr cur, res, result = NULL, last = NULL;
if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
(elem == NULL))
return(NULL);
cur = elem;
while (cur != NULL) {
res = xmlXIncludeCopyNode(ctxt, target, source, cur);
if (res != NULL) {
if (result == NULL) {
result = last = res;
} else {
last->next = res;
res->prev = last;
last = res;
}
}
cur = cur->next;
}
return(result);
}
/**
* xmlXIncludeGetNthChild:
* @cur: the node
* @no: the child number
*
* Returns the @n'th element child of @cur or NULL
*/
static xmlNodePtr
xmlXIncludeGetNthChild(xmlNodePtr cur, int no) {
int i;
if (cur == NULL)
return(cur);
cur = cur->children;
for (i = 0;i <= no;cur = cur->next) {
if (cur == NULL)
return(cur);
if ((cur->type == XML_ELEMENT_NODE) ||
(cur->type == XML_DOCUMENT_NODE) ||
(cur->type == XML_HTML_DOCUMENT_NODE)) {
i++;
if (i == no)
break;
}
}
return(cur);
}
xmlNodePtr xmlXPtrAdvanceNode(xmlNodePtr cur, int *level); /* in xpointer.c */
/**
* xmlXIncludeCopyRange:
* @ctxt: the XInclude context
* @target: the document target
* @source: the document source
* @obj: the XPointer result from the evaluation.
*
* Build a node list tree copy of the XPointer result.
*
* Returns an xmlNodePtr list or NULL.
* The caller has to free the node tree.
*/
static xmlNodePtr
xmlXIncludeCopyRange(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
xmlDocPtr source, xmlXPathObjectPtr range) {
/* pointers to generated nodes */
xmlNodePtr list = NULL, last = NULL, listParent = NULL;
xmlNodePtr tmp, tmp2;
/* pointers to traversal nodes */
xmlNodePtr start, cur, end;
int index1, index2;
int level = 0, lastLevel = 0, endLevel = 0, endFlag = 0;
if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
(range == NULL))
return(NULL);
if (range->type != XPATH_RANGE)
return(NULL);
start = (xmlNodePtr) range->user;
if (start == NULL)
return(NULL);
end = range->user2;
if (end == NULL)
return(xmlDocCopyNode(start, target, 1));
cur = start;
index1 = range->index;
index2 = range->index2;
/*
* level is depth of the current node under consideration
* list is the pointer to the root of the output tree
* listParent is a pointer to the parent of output tree (within
the included file) in case we need to add another level
* last is a pointer to the last node added to the output tree
* lastLevel is the depth of last (relative to the root)
*/
while (cur != NULL) {
/*
* Check if our output tree needs a parent
*/
if (level < 0) {
while (level < 0) {
/* copy must include namespaces and properties */
tmp2 = xmlDocCopyNode(listParent, target, 2);
xmlAddChild(tmp2, list);
list = tmp2;
listParent = listParent->parent;
level++;
}
last = list;
lastLevel = 0;
}
/*
* Check whether we need to change our insertion point
*/
while (level < lastLevel) {
last = last->parent;
lastLevel --;
}
if (cur == end) { /* Are we at the end of the range? */
if (cur->type == XML_TEXT_NODE) {
const xmlChar *content = cur->content;
int len;
if (content == NULL) {
tmp = xmlNewTextLen(NULL, 0);
} else {
len = index2;
if ((cur == start) && (index1 > 1)) {
content += (index1 - 1);
len -= (index1 - 1);
index1 = 0;
} else {
len = index2;
}
tmp = xmlNewTextLen(content, len);
}
/* single sub text node selection */
if (list == NULL)
return(tmp);
/* prune and return full set */
if (level == lastLevel)
xmlAddNextSibling(last, tmp);
else
xmlAddChild(last, tmp);
return(list);
} else { /* ending node not a text node */
endLevel = level; /* remember the level of the end node */
endFlag = 1;
/* last node - need to take care of properties + namespaces */
tmp = xmlDocCopyNode(cur, target, 2);
if (list == NULL) {
list = tmp;
listParent = cur->parent;
} else {
if (level == lastLevel)
xmlAddNextSibling(last, tmp);
else {
xmlAddChild(last, tmp);
lastLevel = level;
}
}
last = tmp;
if (index2 > 1) {
end = xmlXIncludeGetNthChild(cur, index2 - 1);
index2 = 0;
}
if ((cur == start) && (index1 > 1)) {
cur = xmlXIncludeGetNthChild(cur, index1 - 1);
index1 = 0;
} else {
cur = cur->children;
}
level++; /* increment level to show change */
/*
* Now gather the remaining nodes from cur to end
*/
continue; /* while */
}
} else if (cur == start) { /* Not at the end, are we at start? */
if ((cur->type == XML_TEXT_NODE) ||
(cur->type == XML_CDATA_SECTION_NODE)) {
const xmlChar *content = cur->content;
if (content == NULL) {
tmp = xmlNewTextLen(NULL, 0);
} else {
if (index1 > 1) {
content += (index1 - 1);
index1 = 0;
}
tmp = xmlNewText(content);
}
last = list = tmp;
listParent = cur->parent;
} else { /* Not text node */
/*
* start of the range - need to take care of
* properties and namespaces
*/
tmp = xmlDocCopyNode(cur, target, 2);
list = last = tmp;
listParent = cur->parent;
if (index1 > 1) { /* Do we need to position? */
cur = xmlXIncludeGetNthChild(cur, index1 - 1);
level = lastLevel = 1;
index1 = 0;
/*
* Now gather the remaining nodes from cur to end
*/
continue; /* while */
}
}
} else {
tmp = NULL;
switch (cur->type) {
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_NODE:
/* Do not copy DTD informations */
break;
case XML_ENTITY_DECL:
/* handle crossing entities -> stack needed */
break;
case XML_XINCLUDE_START:
case XML_XINCLUDE_END:
/* don't consider it part of the tree content */
break;
case XML_ATTRIBUTE_NODE:
/* Humm, should not happen ! */
break;
default:
/*
* Middle of the range - need to take care of
* properties and namespaces
*/
tmp = xmlDocCopyNode(cur, target, 2);
break;
}
if (tmp != NULL) {
if (level == lastLevel)
xmlAddNextSibling(last, tmp);
else {
xmlAddChild(last, tmp);
lastLevel = level;
}
last = tmp;
}
}
/*
* Skip to next node in document order
*/
cur = xmlXPtrAdvanceNode(cur, &level);
if (endFlag && (level >= endLevel))
break;
}
return(list);
}
/**
* xmlXIncludeBuildNodeList:
* @ctxt: the XInclude context
* @target: the document target
* @source: the document source
* @obj: the XPointer result from the evaluation.
*
* Build a node list tree copy of the XPointer result.
* This will drop Attributes and Namespace declarations.
*
* Returns an xmlNodePtr list or NULL.
* the caller has to free the node tree.
*/
static xmlNodePtr
xmlXIncludeCopyXPointer(xmlXIncludeCtxtPtr ctxt, xmlDocPtr target,
xmlDocPtr source, xmlXPathObjectPtr obj) {
xmlNodePtr list = NULL, last = NULL;
int i;
if (source == NULL)
source = ctxt->doc;
if ((ctxt == NULL) || (target == NULL) || (source == NULL) ||
(obj == NULL))
return(NULL);
switch (obj->type) {
case XPATH_NODESET: {
xmlNodeSetPtr set = obj->nodesetval;
if (set == NULL)
return(NULL);
for (i = 0;i < set->nodeNr;i++) {
if (set->nodeTab[i] == NULL)
continue;
switch (set->nodeTab[i]->type) {
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_ELEMENT_NODE:
case XML_ENTITY_REF_NODE:
case XML_ENTITY_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
#ifdef LIBXML_DOCB_ENABLED
case XML_DOCB_DOCUMENT_NODE:
#endif
case XML_XINCLUDE_END:
break;
case XML_XINCLUDE_START: {
xmlNodePtr tmp, cur = set->nodeTab[i];
cur = cur->next;
while (cur != NULL) {
switch(cur->type) {
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_ELEMENT_NODE:
case XML_ENTITY_REF_NODE:
case XML_ENTITY_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
tmp = xmlXIncludeCopyNode(ctxt, target,
source, cur);
if (last == NULL) {
list = last = tmp;
} else {
xmlAddNextSibling(last, tmp);
last = tmp;
}
cur = cur->next;
continue;
default:
break;
}
break;
}
continue;
}
case XML_ATTRIBUTE_NODE:
case XML_NAMESPACE_DECL:
case XML_DOCUMENT_TYPE_NODE:
case XML_DOCUMENT_FRAG_NODE:
case XML_NOTATION_NODE:
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_DECL:
continue; /* for */
}
if (last == NULL)
list = last = xmlXIncludeCopyNode(ctxt, target, source,
set->nodeTab[i]);
else {
xmlAddNextSibling(last,
xmlXIncludeCopyNode(ctxt, target, source,
set->nodeTab[i]));
if (last->next != NULL)
last = last->next;
}
}
break;
}
case XPATH_LOCATIONSET: {
xmlLocationSetPtr set = (xmlLocationSetPtr) obj->user;
if (set == NULL)
return(NULL);
for (i = 0;i < set->locNr;i++) {
if (last == NULL)
list = last = xmlXIncludeCopyXPointer(ctxt, target, source,
set->locTab[i]);
else
xmlAddNextSibling(last,
xmlXIncludeCopyXPointer(ctxt, target, source,
set->locTab[i]));
if (last != NULL) {
while (last->next != NULL)
last = last->next;
}
}
break;
}
#ifdef LIBXML_XPTR_ENABLED
case XPATH_RANGE:
return(xmlXIncludeCopyRange(ctxt, target, source, obj));
#endif
case XPATH_POINT:
/* points are ignored in XInclude */
break;
default:
break;
}
return(list);
}
/************************************************************************
* *
* XInclude I/O handling *
* *
************************************************************************/
typedef struct _xmlXIncludeMergeData xmlXIncludeMergeData;
typedef xmlXIncludeMergeData *xmlXIncludeMergeDataPtr;
struct _xmlXIncludeMergeData {
xmlDocPtr doc;
xmlXIncludeCtxtPtr ctxt;
};
/**
* xmlXIncludeMergeOneEntity:
* @ent: the entity
* @doc: the including doc
* @nr: the entity name
*
* Inplements the merge of one entity
*/
static void
xmlXIncludeMergeEntity(xmlEntityPtr ent, xmlXIncludeMergeDataPtr data,
xmlChar *name ATTRIBUTE_UNUSED) {
xmlEntityPtr ret, prev;
xmlDocPtr doc;
xmlXIncludeCtxtPtr ctxt;
if ((ent == NULL) || (data == NULL))
return;
ctxt = data->ctxt;
doc = data->doc;
if ((ctxt == NULL) || (doc == NULL))
return;
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
case XML_INTERNAL_PREDEFINED_ENTITY:
return;
case XML_INTERNAL_GENERAL_ENTITY:
case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
break;
}
ret = xmlAddDocEntity(doc, ent->name, ent->etype, ent->ExternalID,
ent->SystemID, ent->content);
if (ret != NULL) {
if (ent->URI != NULL)
ret->URI = xmlStrdup(ent->URI);
} else {
prev = xmlGetDocEntity(doc, ent->name);
if (prev != NULL) {
if (ent->etype != prev->etype)
goto error;
if ((ent->SystemID != NULL) && (prev->SystemID != NULL)) {
if (!xmlStrEqual(ent->SystemID, prev->SystemID))
goto error;
} else if ((ent->ExternalID != NULL) &&
(prev->ExternalID != NULL)) {
if (!xmlStrEqual(ent->ExternalID, prev->ExternalID))
goto error;
} else if ((ent->content != NULL) && (prev->content != NULL)) {
if (!xmlStrEqual(ent->content, prev->content))
goto error;
} else {
goto error;
}
}
}
return;
error:
switch (ent->etype) {
case XML_INTERNAL_PARAMETER_ENTITY:
case XML_EXTERNAL_PARAMETER_ENTITY:
case XML_INTERNAL_PREDEFINED_ENTITY:
case XML_INTERNAL_GENERAL_ENTITY:
case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
return;
case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
break;
}
xmlXIncludeErr(ctxt, (xmlNodePtr) ent, XML_XINCLUDE_ENTITY_DEF_MISMATCH,
"mismatch in redefinition of entity %s\n",
ent->name);
}
/**
* xmlXIncludeMergeEntities:
* @ctxt: an XInclude context
* @doc: the including doc
* @from: the included doc
*
* Inplements the entity merge
*
* Returns 0 if merge succeeded, -1 if some processing failed
*/
static int
xmlXIncludeMergeEntities(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
xmlDocPtr from) {
xmlNodePtr cur;
xmlDtdPtr target, source;
if (ctxt == NULL)
return(-1);
if ((from == NULL) || (from->intSubset == NULL))
return(0);
target = doc->intSubset;
if (target == NULL) {
cur = xmlDocGetRootElement(doc);
if (cur == NULL)
return(-1);
target = xmlCreateIntSubset(doc, cur->name, NULL, NULL);
if (target == NULL)
return(-1);
}
source = from->intSubset;
if ((source != NULL) && (source->entities != NULL)) {
xmlXIncludeMergeData data;
data.ctxt = ctxt;
data.doc = doc;
xmlHashScan((xmlHashTablePtr) source->entities,
(xmlHashScanner) xmlXIncludeMergeEntity, &data);
}
source = from->extSubset;
if ((source != NULL) && (source->entities != NULL)) {
xmlXIncludeMergeData data;
data.ctxt = ctxt;
data.doc = doc;
/*
* don't duplicate existing stuff when external subsets are the same
*/
if ((!xmlStrEqual(target->ExternalID, source->ExternalID)) &&
(!xmlStrEqual(target->SystemID, source->SystemID))) {
xmlHashScan((xmlHashTablePtr) source->entities,
(xmlHashScanner) xmlXIncludeMergeEntity, &data);
}
}
return(0);
}
/**
* xmlXIncludeLoadDoc:
* @ctxt: the XInclude context
* @url: the associated URL
* @nr: the xinclude node number
*
* Load the document, and store the result in the XInclude context
*
* Returns 0 in case of success, -1 in case of failure
*/
static int
xmlXIncludeLoadDoc(xmlXIncludeCtxtPtr ctxt, const xmlChar *url, int nr) {
xmlDocPtr doc;
xmlURIPtr uri;
xmlChar *URL;
xmlChar *fragment = NULL;
int i = 0;
#ifdef LIBXML_XPTR_ENABLED
int saveFlags;
#endif
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "Loading doc %s:%d\n", url, nr);
#endif
/*
* Check the URL and remove any fragment identifier
*/
uri = xmlParseURI((const char *)url);
if (uri == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", url);
return(-1);
}
if (uri->fragment != NULL) {
fragment = (xmlChar *) uri->fragment;
uri->fragment = NULL;
}
if ((ctxt->incTab != NULL) && (ctxt->incTab[nr] != NULL) &&
(ctxt->incTab[nr]->fragment != NULL)) {
if (fragment != NULL) xmlFree(fragment);
fragment = xmlStrdup(ctxt->incTab[nr]->fragment);
}
URL = xmlSaveUri(uri);
xmlFreeURI(uri);
if (URL == NULL) {
if (ctxt->incTab != NULL)
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", url);
else
xmlXIncludeErr(ctxt, NULL,
XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", url);
if (fragment != NULL)
xmlFree(fragment);
return(-1);
}
/*
* Handling of references to the local document are done
* directly through ctxt->doc.
*/
if ((URL[0] == 0) || (URL[0] == '#') ||
((ctxt->doc != NULL) && (xmlStrEqual(URL, ctxt->doc->URL)))) {
doc = NULL;
goto loaded;
}
/*
* Prevent reloading twice the document.
*/
for (i = 0; i < ctxt->incNr; i++) {
if ((xmlStrEqual(URL, ctxt->incTab[i]->URI)) &&
(ctxt->incTab[i]->doc != NULL)) {
doc = ctxt->incTab[i]->doc;
#ifdef DEBUG_XINCLUDE
printf("Already loaded %s\n", URL);
#endif
goto loaded;
}
}
/*
* Load it.
*/
#ifdef DEBUG_XINCLUDE
printf("loading %s\n", URL);
#endif
#ifdef LIBXML_XPTR_ENABLED
/*
* If this is an XPointer evaluation, we want to assure that
* all entities have been resolved prior to processing the
* referenced document
*/
saveFlags = ctxt->parseFlags;
if (fragment != NULL) { /* if this is an XPointer eval */
ctxt->parseFlags |= XML_PARSE_NOENT;
}
#endif
doc = xmlXIncludeParseFile(ctxt, (const char *)URL);
#ifdef LIBXML_XPTR_ENABLED
ctxt->parseFlags = saveFlags;
#endif
if (doc == NULL) {
xmlFree(URL);
if (fragment != NULL)
xmlFree(fragment);
return(-1);
}
ctxt->incTab[nr]->doc = doc;
/*
* It's possible that the requested URL has been mapped to a
* completely different location (e.g. through a catalog entry).
* To check for this, we compare the URL with that of the doc
* and change it if they disagree (bug 146988).
*/
if (!xmlStrEqual(URL, doc->URL)) {
xmlFree(URL);
URL = xmlStrdup(doc->URL);
}
for (i = nr + 1; i < ctxt->incNr; i++) {
if (xmlStrEqual(URL, ctxt->incTab[i]->URI)) {
ctxt->incTab[nr]->count++;
#ifdef DEBUG_XINCLUDE
printf("Increasing %s count since reused\n", URL);
#endif
break;
}
}
/*
* Make sure we have all entities fixed up
*/
xmlXIncludeMergeEntities(ctxt, ctxt->doc, doc);
/*
* We don't need the DTD anymore, free up space
if (doc->intSubset != NULL) {
xmlUnlinkNode((xmlNodePtr) doc->intSubset);
xmlFreeNode((xmlNodePtr) doc->intSubset);
doc->intSubset = NULL;
}
if (doc->extSubset != NULL) {
xmlUnlinkNode((xmlNodePtr) doc->extSubset);
xmlFreeNode((xmlNodePtr) doc->extSubset);
doc->extSubset = NULL;
}
*/
xmlXIncludeRecurseDoc(ctxt, doc, URL);
loaded:
if (fragment == NULL) {
/*
* Add the top children list as the replacement copy.
*/
if (doc == NULL)
{
/* Hopefully a DTD declaration won't be copied from
* the same document */
ctxt->incTab[nr]->inc = xmlCopyNodeList(ctxt->doc->children);
} else {
ctxt->incTab[nr]->inc = xmlXIncludeCopyNodeList(ctxt, ctxt->doc,
doc, doc->children);
}
}
#ifdef LIBXML_XPTR_ENABLED
else {
/*
* Computes the XPointer expression and make a copy used
* as the replacement copy.
*/
xmlXPathObjectPtr xptr;
xmlXPathContextPtr xptrctxt;
xmlNodeSetPtr set;
if (doc == NULL) {
xptrctxt = xmlXPtrNewContext(ctxt->doc, ctxt->incTab[nr]->ref,
NULL);
} else {
xptrctxt = xmlXPtrNewContext(doc, NULL, NULL);
}
if (xptrctxt == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_XPTR_FAILED,
"could not create XPointer context\n", NULL);
xmlFree(URL);
xmlFree(fragment);
return(-1);
}
xptr = xmlXPtrEval(fragment, xptrctxt);
if (xptr == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_XPTR_FAILED,
"XPointer evaluation failed: #%s\n",
fragment);
xmlXPathFreeContext(xptrctxt);
xmlFree(URL);
xmlFree(fragment);
return(-1);
}
switch (xptr->type) {
case XPATH_UNDEFINED:
case XPATH_BOOLEAN:
case XPATH_NUMBER:
case XPATH_STRING:
case XPATH_POINT:
case XPATH_USERS:
case XPATH_XSLT_TREE:
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_XPTR_RESULT,
"XPointer is not a range: #%s\n",
fragment);
xmlXPathFreeContext(xptrctxt);
xmlFree(URL);
xmlFree(fragment);
return(-1);
case XPATH_NODESET:
if ((xptr->nodesetval == NULL) ||
(xptr->nodesetval->nodeNr <= 0)) {
xmlXPathFreeContext(xptrctxt);
xmlFree(URL);
xmlFree(fragment);
return(-1);
}
case XPATH_RANGE:
case XPATH_LOCATIONSET:
break;
}
set = xptr->nodesetval;
if (set != NULL) {
for (i = 0;i < set->nodeNr;i++) {
if (set->nodeTab[i] == NULL)
continue;
switch (set->nodeTab[i]->type) {
case XML_ELEMENT_NODE:
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
case XML_ENTITY_REF_NODE:
case XML_ENTITY_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
#ifdef LIBXML_DOCB_ENABLED
case XML_DOCB_DOCUMENT_NODE:
#endif
continue;
case XML_ATTRIBUTE_NODE:
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_XPTR_RESULT,
"XPointer selects an attribute: #%s\n",
fragment);
set->nodeTab[i] = NULL;
continue;
case XML_NAMESPACE_DECL:
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_XPTR_RESULT,
"XPointer selects a namespace: #%s\n",
fragment);
set->nodeTab[i] = NULL;
continue;
case XML_DOCUMENT_TYPE_NODE:
case XML_DOCUMENT_FRAG_NODE:
case XML_NOTATION_NODE:
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_DECL:
case XML_XINCLUDE_START:
case XML_XINCLUDE_END:
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_XPTR_RESULT,
"XPointer selects unexpected nodes: #%s\n",
fragment);
set->nodeTab[i] = NULL;
set->nodeTab[i] = NULL;
continue; /* for */
}
}
}
if (doc == NULL) {
ctxt->incTab[nr]->xptr = xptr;
ctxt->incTab[nr]->inc = NULL;
} else {
ctxt->incTab[nr]->inc =
xmlXIncludeCopyXPointer(ctxt, ctxt->doc, doc, xptr);
xmlXPathFreeObject(xptr);
}
xmlXPathFreeContext(xptrctxt);
xmlFree(fragment);
}
#endif
/*
* Do the xml:base fixup if needed
*/
if ((doc != NULL) && (URL != NULL) && (xmlStrchr(URL, (xmlChar) '/'))) {
xmlNodePtr node;
xmlChar *base;
xmlChar *curBase;
/*
* The base is only adjusted if "necessary", i.e. if the xinclude node
* has a base specified, or the URL is relative
*/
base = xmlGetNsProp(ctxt->incTab[nr]->ref, BAD_CAST "base",
XML_XML_NAMESPACE);
if (base == NULL) {
/*
* No xml:base on the xinclude node, so we check whether the
* URI base is different than (relative to) the context base
*/
curBase = xmlBuildRelativeURI(URL, ctxt->base);
if (curBase == NULL) { /* Error return */
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_HREF_URI,
"trying to build relative URI from %s\n", URL);
} else {
/* If the URI doesn't contain a slash, it's not relative */
if (!xmlStrchr(curBase, (xmlChar) '/'))
xmlFree(curBase);
else
base = curBase;
}
}
if (base != NULL) { /* Adjustment may be needed */
node = ctxt->incTab[nr]->inc;
while (node != NULL) {
/* Only work on element nodes */
if (node->type == XML_ELEMENT_NODE) {
curBase = xmlNodeGetBase(node->doc, node);
/* If no current base, set it */
if (curBase == NULL) {
xmlNodeSetBase(node, base);
} else {
/*
* If the current base is the same as the
* URL of the document, then reset it to be
* the specified xml:base or the relative URI
*/
if (xmlStrEqual(curBase, node->doc->URL)) {
xmlNodeSetBase(node, base);
} else {
/*
* If the element already has an xml:base
* set, then relativise it if necessary
*/
xmlChar *xmlBase;
xmlBase = xmlGetNsProp(node,
BAD_CAST "base",
XML_XML_NAMESPACE);
if (xmlBase != NULL) {
xmlChar *relBase;
relBase = xmlBuildURI(xmlBase, base);
if (relBase == NULL) { /* error */
xmlXIncludeErr(ctxt,
ctxt->incTab[nr]->ref,
XML_XINCLUDE_HREF_URI,
"trying to rebuild base from %s\n",
xmlBase);
} else {
xmlNodeSetBase(node, relBase);
xmlFree(relBase);
}
xmlFree(xmlBase);
}
}
xmlFree(curBase);
}
}
node = node->next;
}
xmlFree(base);
}
}
if ((nr < ctxt->incNr) && (ctxt->incTab[nr]->doc != NULL) &&
(ctxt->incTab[nr]->count <= 1)) {
#ifdef DEBUG_XINCLUDE
printf("freeing %s\n", ctxt->incTab[nr]->doc->URL);
#endif
xmlFreeDoc(ctxt->incTab[nr]->doc);
ctxt->incTab[nr]->doc = NULL;
}
xmlFree(URL);
return(0);
}
/**
* xmlXIncludeLoadTxt:
* @ctxt: the XInclude context
* @url: the associated URL
* @nr: the xinclude node number
*
* Load the content, and store the result in the XInclude context
*
* Returns 0 in case of success, -1 in case of failure
*/
static int
xmlXIncludeLoadTxt(xmlXIncludeCtxtPtr ctxt, const xmlChar *url, int nr) {
xmlParserInputBufferPtr buf;
xmlNodePtr node;
xmlURIPtr uri;
xmlChar *URL;
int i;
xmlChar *encoding = NULL;
xmlCharEncoding enc = (xmlCharEncoding) 0;
/*
* Check the URL and remove any fragment identifier
*/
uri = xmlParseURI((const char *)url);
if (uri == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", url);
return(-1);
}
if (uri->fragment != NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_TEXT_FRAGMENT,
"fragment identifier forbidden for text: %s\n",
(const xmlChar *) uri->fragment);
xmlFreeURI(uri);
return(-1);
}
URL = xmlSaveUri(uri);
xmlFreeURI(uri);
if (URL == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref, XML_XINCLUDE_HREF_URI,
"invalid value URI %s\n", url);
return(-1);
}
/*
* Handling of references to the local document are done
* directly through ctxt->doc.
*/
if (URL[0] == 0) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_TEXT_DOCUMENT,
"text serialization of document not available\n", NULL);
xmlFree(URL);
return(-1);
}
/*
* Prevent reloading twice the document.
*/
for (i = 0; i < ctxt->txtNr; i++) {
if (xmlStrEqual(URL, ctxt->txturlTab[i])) {
node = xmlCopyNode(ctxt->txtTab[i], 1);
goto loaded;
}
}
/*
* Try to get the encoding if available
*/
if ((ctxt->incTab[nr] != NULL) && (ctxt->incTab[nr]->ref != NULL)) {
encoding = xmlGetProp(ctxt->incTab[nr]->ref, XINCLUDE_PARSE_ENCODING);
}
if (encoding != NULL) {
/*
* TODO: we should not have to remap to the xmlCharEncoding
* predefined set, a better interface than
* xmlParserInputBufferCreateFilename should allow any
* encoding supported by iconv
*/
enc = xmlParseCharEncoding((const char *) encoding);
if (enc == XML_CHAR_ENCODING_ERROR) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_UNKNOWN_ENCODING,
"encoding %s not supported\n", encoding);
xmlFree(encoding);
xmlFree(URL);
return(-1);
}
xmlFree(encoding);
}
/*
* Load it.
*/
buf = xmlParserInputBufferCreateFilename((const char *)URL, enc);
if (buf == NULL) {
xmlFree(URL);
return(-1);
}
node = xmlNewText(NULL);
/*
* Scan all chars from the resource and add the to the node
*/
while (xmlParserInputBufferRead(buf, 128) > 0) {
int len;
const xmlChar *content;
content = xmlBufferContent(buf->buffer);
len = xmlBufferLength(buf->buffer);
for (i = 0;i < len;) {
int cur;
int l;
cur = xmlStringCurrentChar(NULL, &content[i], &l);
if (!IS_CHAR(cur)) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_INVALID_CHAR,
"%s contains invalid char\n", URL);
xmlFreeParserInputBuffer(buf);
xmlFree(URL);
return(-1);
} else {
xmlNodeAddContentLen(node, &content[i], l);
}
i += l;
}
xmlBufferShrink(buf->buffer, len);
}
xmlFreeParserInputBuffer(buf);
xmlXIncludeAddTxt(ctxt, node, URL);
loaded:
/*
* Add the element as the replacement copy.
*/
ctxt->incTab[nr]->inc = node;
xmlFree(URL);
return(0);
}
/**
* xmlXIncludeLoadFallback:
* @ctxt: the XInclude context
* @fallback: the fallback node
* @nr: the xinclude node number
*
* Load the content of the fallback node, and store the result
* in the XInclude context
*
* Returns 0 in case of success, -1 in case of failure
*/
static int
xmlXIncludeLoadFallback(xmlXIncludeCtxtPtr ctxt, xmlNodePtr fallback, int nr) {
xmlXIncludeCtxtPtr newctxt;
int ret = 0;
if ((fallback == NULL) || (ctxt == NULL))
return(-1);
if (fallback->children != NULL) {
/*
* It's possible that the fallback also has 'includes'
* (Bug 129969), so we re-process the fallback just in case
*/
newctxt = xmlXIncludeNewContext(ctxt->doc);
if (newctxt == NULL)
return (-1);
newctxt->_private = ctxt->_private;
newctxt->base = xmlStrdup(ctxt->base); /* Inherit the base from the existing context */
xmlXIncludeSetFlags(newctxt, ctxt->parseFlags);
ret = xmlXIncludeDoProcess(newctxt, ctxt->doc, fallback->children);
if (ctxt->nbErrors > 0)
ret = -1;
else if (ret > 0)
ret = 0; /* xmlXIncludeDoProcess can return +ve number */
xmlXIncludeFreeContext(newctxt);
ctxt->incTab[nr]->inc = xmlDocCopyNodeList(ctxt->doc,
fallback->children);
} else {
ctxt->incTab[nr]->inc = NULL;
ctxt->incTab[nr]->emptyFb = 1; /* flag empty callback */
}
return(ret);
}
/************************************************************************
* *
* XInclude Processing *
* *
************************************************************************/
/**
* xmlXIncludePreProcessNode:
* @ctxt: an XInclude context
* @node: an XInclude node
*
* Implement the XInclude preprocessing, currently just adding the element
* for further processing.
*
* Returns the result list or NULL in case of error
*/
static xmlNodePtr
xmlXIncludePreProcessNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
xmlXIncludeAddNode(ctxt, node);
return(NULL);
}
/**
* xmlXIncludeLoadNode:
* @ctxt: an XInclude context
* @nr: the node number
*
* Find and load the infoset replacement for the given node.
*
* Returns 0 if substitution succeeded, -1 if some processing failed
*/
static int
xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt, int nr) {
xmlNodePtr cur;
xmlChar *href;
xmlChar *parse;
xmlChar *base;
xmlChar *oldBase;
xmlChar *URI;
int xml = 1; /* default Issue 64 */
int ret;
if (ctxt == NULL)
return(-1);
if ((nr < 0) || (nr >= ctxt->incNr))
return(-1);
cur = ctxt->incTab[nr]->ref;
if (cur == NULL)
return(-1);
/*
* read the attributes
*/
href = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_HREF);
if (href == NULL) {
href = xmlStrdup(BAD_CAST ""); /* @@@@ href is now optional */
if (href == NULL)
return(-1);
}
parse = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE);
if (parse != NULL) {
if (xmlStrEqual(parse, XINCLUDE_PARSE_XML))
xml = 1;
else if (xmlStrEqual(parse, XINCLUDE_PARSE_TEXT))
xml = 0;
else {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_PARSE_VALUE,
"invalid value %s for 'parse'\n", parse);
if (href != NULL)
xmlFree(href);
if (parse != NULL)
xmlFree(parse);
return(-1);
}
}
/*
* compute the URI
*/
base = xmlNodeGetBase(ctxt->doc, cur);
if (base == NULL) {
URI = xmlBuildURI(href, ctxt->doc->URL);
} else {
URI = xmlBuildURI(href, base);
}
if (URI == NULL) {
xmlChar *escbase;
xmlChar *eschref;
/*
* Some escaping may be needed
*/
escbase = xmlURIEscape(base);
eschref = xmlURIEscape(href);
URI = xmlBuildURI(eschref, escbase);
if (escbase != NULL)
xmlFree(escbase);
if (eschref != NULL)
xmlFree(eschref);
}
if (URI == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_HREF_URI, "failed build URL\n", NULL);
if (parse != NULL)
xmlFree(parse);
if (href != NULL)
xmlFree(href);
if (base != NULL)
xmlFree(base);
return(-1);
}
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "parse: %s\n",
xml ? "xml": "text");
xmlGenericError(xmlGenericErrorContext, "URI: %s\n", URI);
#endif
/*
* Save the base for this include (saving the current one)
*/
oldBase = ctxt->base;
ctxt->base = base;
if (xml) {
ret = xmlXIncludeLoadDoc(ctxt, URI, nr);
/* xmlXIncludeGetFragment(ctxt, cur, URI); */
} else {
ret = xmlXIncludeLoadTxt(ctxt, URI, nr);
}
/*
* Restore the original base before checking for fallback
*/
ctxt->base = oldBase;
if (ret < 0) {
xmlNodePtr children;
/*
* Time to try a fallback if availble
*/
#ifdef DEBUG_XINCLUDE
xmlGenericError(xmlGenericErrorContext, "error looking for fallback\n");
#endif
children = cur->children;
while (children != NULL) {
if ((children->type == XML_ELEMENT_NODE) &&
(children->ns != NULL) &&
(xmlStrEqual(children->name, XINCLUDE_FALLBACK)) &&
((xmlStrEqual(children->ns->href, XINCLUDE_NS)) ||
(xmlStrEqual(children->ns->href, XINCLUDE_OLD_NS)))) {
ret = xmlXIncludeLoadFallback(ctxt, children, nr);
if (ret == 0)
break;
}
children = children->next;
}
}
if (ret < 0) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_NO_FALLBACK,
"could not load %s, and no fallback was found\n",
URI);
}
/*
* Cleanup
*/
if (URI != NULL)
xmlFree(URI);
if (parse != NULL)
xmlFree(parse);
if (href != NULL)
xmlFree(href);
if (base != NULL)
xmlFree(base);
return(0);
}
/**
* xmlXIncludeIncludeNode:
* @ctxt: an XInclude context
* @nr: the node number
*
* Inplement the infoset replacement for the given node
*
* Returns 0 if substitution succeeded, -1 if some processing failed
*/
static int
xmlXIncludeIncludeNode(xmlXIncludeCtxtPtr ctxt, int nr) {
xmlNodePtr cur, end, list, tmp;
if (ctxt == NULL)
return(-1);
if ((nr < 0) || (nr >= ctxt->incNr))
return(-1);
cur = ctxt->incTab[nr]->ref;
if (cur == NULL)
return(-1);
/*
* If we stored an XPointer a late computation may be needed
*/
if ((ctxt->incTab[nr]->inc == NULL) &&
(ctxt->incTab[nr]->xptr != NULL)) {
ctxt->incTab[nr]->inc =
xmlXIncludeCopyXPointer(ctxt, ctxt->doc, ctxt->doc,
ctxt->incTab[nr]->xptr);
xmlXPathFreeObject(ctxt->incTab[nr]->xptr);
ctxt->incTab[nr]->xptr = NULL;
}
list = ctxt->incTab[nr]->inc;
ctxt->incTab[nr]->inc = NULL;
/*
* Check against the risk of generating a multi-rooted document
*/
if ((cur->parent != NULL) &&
(cur->parent->type != XML_ELEMENT_NODE)) {
int nb_elem = 0;
tmp = list;
while (tmp != NULL) {
if (tmp->type == XML_ELEMENT_NODE)
nb_elem++;
tmp = tmp->next;
}
if (nb_elem > 1) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_MULTIPLE_ROOT,
"XInclude error: would result in multiple root nodes\n",
NULL);
return(-1);
}
}
if (ctxt->parseFlags & XML_PARSE_NOXINCNODE) {
/*
* Add the list of nodes
*/
while (list != NULL) {
end = list;
list = list->next;
xmlAddPrevSibling(cur, end);
}
xmlUnlinkNode(cur);
xmlFreeNode(cur);
} else {
/*
* Change the current node as an XInclude start one, and add an
* XInclude end one
*/
cur->type = XML_XINCLUDE_START;
end = xmlNewDocNode(cur->doc, cur->ns, cur->name, NULL);
if (end == NULL) {
xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
XML_XINCLUDE_BUILD_FAILED,
"failed to build node\n", NULL);
return(-1);
}
end->type = XML_XINCLUDE_END;
xmlAddNextSibling(cur, end);
/*
* Add the list of nodes
*/
while (list != NULL) {
cur = list;
list = list->next;
xmlAddPrevSibling(end, cur);
}
}
return(0);
}
/**
* xmlXIncludeTestNode:
* @ctxt: the XInclude processing context
* @node: an XInclude node
*
* test if the node is an XInclude node
*
* Returns 1 true, 0 otherwise
*/
static int
xmlXIncludeTestNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
if (node == NULL)
return(0);
if (node->type != XML_ELEMENT_NODE)
return(0);
if (node->ns == NULL)
return(0);
if ((xmlStrEqual(node->ns->href, XINCLUDE_NS)) ||
(xmlStrEqual(node->ns->href, XINCLUDE_OLD_NS))) {
if (xmlStrEqual(node->ns->href, XINCLUDE_OLD_NS)) {
if (ctxt->legacy == 0) {
#if 0 /* wait for the XML Core Working Group to get something stable ! */
xmlXIncludeWarn(ctxt, node, XML_XINCLUDE_DEPRECATED_NS,
"Deprecated XInclude namespace found, use %s",
XINCLUDE_NS);
#endif
ctxt->legacy = 1;
}
}
if (xmlStrEqual(node->name, XINCLUDE_NODE)) {
xmlNodePtr child = node->children;
int nb_fallback = 0;
while (child != NULL) {
if ((child->type == XML_ELEMENT_NODE) &&
(child->ns != NULL) &&
((xmlStrEqual(child->ns->href, XINCLUDE_NS)) ||
(xmlStrEqual(child->ns->href, XINCLUDE_OLD_NS)))) {
if (xmlStrEqual(child->name, XINCLUDE_NODE)) {
xmlXIncludeErr(ctxt, node,
XML_XINCLUDE_INCLUDE_IN_INCLUDE,
"%s has an 'include' child\n",
XINCLUDE_NODE);
return(0);
}
if (xmlStrEqual(child->name, XINCLUDE_FALLBACK)) {
nb_fallback++;
}
}
child = child->next;
}
if (nb_fallback > 1) {
xmlXIncludeErr(ctxt, node, XML_XINCLUDE_FALLBACKS_IN_INCLUDE,
"%s has multiple fallback children\n",
XINCLUDE_NODE);
return(0);
}
return(1);
}
if (xmlStrEqual(node->name, XINCLUDE_FALLBACK)) {
if ((node->parent == NULL) ||
(node->parent->type != XML_ELEMENT_NODE) ||
(node->parent->ns == NULL) ||
((!xmlStrEqual(node->parent->ns->href, XINCLUDE_NS)) &&
(!xmlStrEqual(node->parent->ns->href, XINCLUDE_OLD_NS))) ||
(!xmlStrEqual(node->parent->name, XINCLUDE_NODE))) {
xmlXIncludeErr(ctxt, node,
XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE,
"%s is not the child of an 'include'\n",
XINCLUDE_FALLBACK);
}
}
}
return(0);
}
/**
* xmlXIncludeDoProcess:
* @ctxt: the XInclude processing context
* @doc: an XML document
* @tree: the top of the tree to process
*
* Implement the XInclude substitution on the XML document @doc
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
static int
xmlXIncludeDoProcess(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr tree) {
xmlNodePtr cur;
int ret = 0;
int i, start;
if ((doc == NULL) || (tree == NULL))
return(-1);
if (ctxt == NULL)
return(-1);
if (doc->URL != NULL) {
ret = xmlXIncludeURLPush(ctxt, doc->URL);
if (ret < 0)
return(-1);
}
start = ctxt->incNr;
/*
* First phase: lookup the elements in the document
*/
cur = tree;
if (xmlXIncludeTestNode(ctxt, cur) == 1)
xmlXIncludePreProcessNode(ctxt, cur);
while ((cur != NULL) && (cur != tree->parent)) {
/* TODO: need to work on entities -> stack */
if ((cur->children != NULL) &&
(cur->children->type != XML_ENTITY_DECL) &&
(cur->children->type != XML_XINCLUDE_START) &&
(cur->children->type != XML_XINCLUDE_END)) {
cur = cur->children;
if (xmlXIncludeTestNode(ctxt, cur))
xmlXIncludePreProcessNode(ctxt, cur);
} else if (cur->next != NULL) {
cur = cur->next;
if (xmlXIncludeTestNode(ctxt, cur))
xmlXIncludePreProcessNode(ctxt, cur);
} else {
if (cur == tree)
break;
do {
cur = cur->parent;
if ((cur == NULL) || (cur == tree->parent))
break; /* do */
if (cur->next != NULL) {
cur = cur->next;
if (xmlXIncludeTestNode(ctxt, cur))
xmlXIncludePreProcessNode(ctxt, cur);
break; /* do */
}
} while (cur != NULL);
}
}
/*
* Second Phase : collect the infosets fragments
*/
for (i = start;i < ctxt->incNr; i++) {
xmlXIncludeLoadNode(ctxt, i);
ret++;
}
/*
* Third phase: extend the original document infoset.
*
* Originally we bypassed the inclusion if there were any errors
* encountered on any of the XIncludes. A bug was raised (bug
* 132588) requesting that we output the XIncludes without error,
* so the check for inc!=NULL || xptr!=NULL was put in. This may
* give some other problems in the future, but for now it seems to
* work ok.
*
*/
for (i = ctxt->incBase;i < ctxt->incNr; i++) {
if ((ctxt->incTab[i]->inc != NULL) ||
(ctxt->incTab[i]->xptr != NULL) ||
(ctxt->incTab[i]->emptyFb != 0)) /* (empty fallback) */
xmlXIncludeIncludeNode(ctxt, i);
}
if (doc->URL != NULL)
xmlXIncludeURLPop(ctxt);
return(ret);
}
/**
* xmlXIncludeSetFlags:
* @ctxt: an XInclude processing context
* @flags: a set of xmlParserOption used for parsing XML includes
*
* Set the flags used for further processing of XML resources.
*
* Returns 0 in case of success and -1 in case of error.
*/
int
xmlXIncludeSetFlags(xmlXIncludeCtxtPtr ctxt, int flags) {
if (ctxt == NULL)
return(-1);
ctxt->parseFlags = flags;
return(0);
}
/**
* xmlXIncludeProcessFlagsData:
* @doc: an XML document
* @flags: a set of xmlParserOption used for parsing XML includes
* @data: application data that will be passed to the parser context
* in the _private field of the parser context(s)
*
* Implement the XInclude substitution on the XML document @doc
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
int
xmlXIncludeProcessFlagsData(xmlDocPtr doc, int flags, void *data) {
xmlXIncludeCtxtPtr ctxt;
xmlNodePtr tree;
int ret = 0;
if (doc == NULL)
return(-1);
tree = xmlDocGetRootElement(doc);
if (tree == NULL)
return(-1);
ctxt = xmlXIncludeNewContext(doc);
if (ctxt == NULL)
return(-1);
ctxt->_private = data;
ctxt->base = xmlStrdup((xmlChar *)doc->URL);
xmlXIncludeSetFlags(ctxt, flags);
ret = xmlXIncludeDoProcess(ctxt, doc, tree);
if ((ret >= 0) && (ctxt->nbErrors > 0))
ret = -1;
xmlXIncludeFreeContext(ctxt);
return(ret);
}
/**
* xmlXIncludeProcessFlags:
* @doc: an XML document
* @flags: a set of xmlParserOption used for parsing XML includes
*
* Implement the XInclude substitution on the XML document @doc
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
int
xmlXIncludeProcessFlags(xmlDocPtr doc, int flags) {
return xmlXIncludeProcessFlagsData(doc, flags, NULL);
}
/**
* xmlXIncludeProcess:
* @doc: an XML document
*
* Implement the XInclude substitution on the XML document @doc
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
int
xmlXIncludeProcess(xmlDocPtr doc) {
return(xmlXIncludeProcessFlags(doc, 0));
}
/**
* xmlXIncludeProcessTreeFlags:
* @tree: a node in an XML document
* @flags: a set of xmlParserOption used for parsing XML includes
*
* Implement the XInclude substitution for the given subtree
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
int
xmlXIncludeProcessTreeFlags(xmlNodePtr tree, int flags) {
xmlXIncludeCtxtPtr ctxt;
int ret = 0;
if ((tree == NULL) || (tree->doc == NULL))
return(-1);
ctxt = xmlXIncludeNewContext(tree->doc);
if (ctxt == NULL)
return(-1);
ctxt->base = xmlNodeGetBase(tree->doc, tree);
xmlXIncludeSetFlags(ctxt, flags);
ret = xmlXIncludeDoProcess(ctxt, tree->doc, tree);
if ((ret >= 0) && (ctxt->nbErrors > 0))
ret = -1;
xmlXIncludeFreeContext(ctxt);
return(ret);
}
/**
* xmlXIncludeProcessTree:
* @tree: a node in an XML document
*
* Implement the XInclude substitution for the given subtree
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
int
xmlXIncludeProcessTree(xmlNodePtr tree) {
return(xmlXIncludeProcessTreeFlags(tree, 0));
}
/**
* xmlXIncludeProcessNode:
* @ctxt: an existing XInclude context
* @node: a node in an XML document
*
* Implement the XInclude substitution for the given subtree reusing
* the informations and data coming from the given context.
*
* Returns 0 if no substitution were done, -1 if some processing failed
* or the number of substitutions done.
*/
int
xmlXIncludeProcessNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr node) {
int ret = 0;
if ((node == NULL) || (node->doc == NULL) || (ctxt == NULL))
return(-1);
ret = xmlXIncludeDoProcess(ctxt, node->doc, node);
if ((ret >= 0) && (ctxt->nbErrors > 0))
ret = -1;
return(ret);
}
#else /* !LIBXML_XINCLUDE_ENABLED */
#endif
#define bottom_xinclude
#include "elfgcchack.h"
|
evilmucedin/tomita-parser
|
src/contrib/libs/libxml/srcs/xinclude.c
|
C
|
mpl-2.0
| 66,904
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwpd
* Version: MPL 2.0 / LGPLv2.1+
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Major Contributor(s):
* Copyright (C) 2002 William Lachance (wrlach@gmail.com)
* Copyright (C) 2002 Marc Maurer (uwog@uwog.net)
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#ifndef WP6UNDOGROUP_H
#define WP6UNDOGROUP_H
#include "WP6FixedLengthGroup.h"
class WP6UndoGroup : public WP6FixedLengthGroup
{
public:
WP6UndoGroup(WPXInputStream *input, WPXEncryption *encryption, uint8_t groupID);
void parse(WP6Listener *listener);
protected:
void _readContents(WPXInputStream *input, WPXEncryption *encryption);
private:
uint8_t m_undoType;
uint16_t m_undoLevel;
};
#endif /* WP6UNDOGROUP_H */
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
|
Distrotech/libpwd
|
src/lib/WP6UndoGroup.h
|
C
|
mpl-2.0
| 1,431
|
#include <FactExtract/Parser/common/libxmlutil.h>
#include "sentencerusprocessor.h"
#include "fragmentationrunner.h"
#include <FactExtract/Parser/afdocparser/rus/namefinder.h>
#include "filtercheck.h"
#include "situationssearcher.h"
#include "anaphoraresolution.h"
CSentenceRusProcessor::CSentenceRusProcessor()
: CSentence()
, m_MultiWordCreator(m_Words, GetWordSequences())
, m_clausesStructure(m_Words)
{
}
CSentenceRusProcessor::~CSentenceRusProcessor(void)
{
FreeData();
}
void CSentenceRusProcessor::FreeData()
{
CSentence::FreeData();
m_clausesStructure.Reset();
}
CMultiWordCreator& CSentenceRusProcessor::GetMultiWordCreator()
{
return m_MultiWordCreator;
}
bool CSentenceRusProcessor::RunFragmentation()
{
GetClauseStructureOrBuilt();
return true;
}
const CClauseVariant& CSentenceRusProcessor::GetClauseStructureOrBuilt()
{
if (m_clausesStructure.IsEmpty()) {
CFragmentationRunner fragmentator(this);
fragmentator.Run(FragmOptions);
fragmentator.GetFirstBestVar().Clone(m_clausesStructure);
fragmentator.freeFragmResults();
}
return m_clausesStructure;
}
void CSentenceRusProcessor::PutReferenceSearcher(CReferenceSearcher* pRefSeracher)
{
m_MultiWordCreator.PutReferenceSearcher(pRefSeracher);
}
bool CSentenceRusProcessor::SearchingOfSitWasPerformed(const Wtroka& strArt) const
{
return m_SitFoundByArticles.find(strArt) != m_SitFoundByArticles.end();
}
const yvector<SValenciesValues>* CSentenceRusProcessor::GetFoundVals(const SArtPointer& artPointer)
{
FindSituations(artPointer);
if (artPointer.HasKWType()) {
yhash<TKeyWordType, TValValuesPtr>::const_iterator ptr_it = m_KwType2FoundVals.find(artPointer.GetKWType());
if (ptr_it != m_KwType2FoundVals.end() && ptr_it->second.Get() != NULL && ptr_it->second->size() > 0)
return ptr_it->second.Get();
} else {
if (artPointer.HasStrType()) {
ymap<Wtroka, TValValuesPtr>::const_iterator it = m_article2FoundVals.find(artPointer.GetStrType());
if (it != m_article2FoundVals.end())
return it->second.Get();
}
}
return NULL; //empty
}
void CSentenceRusProcessor::AddToAlreadySearchedSit(const SArtPointer& artPointer)
{
if (artPointer.HasKWType()) {
TKeyWordType kwType = artPointer.GetKWType();
const yvector<int>* artIndexes = GlobalDictsHolder->GetDict(KW_DICT).GetAuxArticles(kwType);
YASSERT(artIndexes != NULL);
for (size_t i = 0; i < artIndexes->size(); ++i) {
const Wtroka& strArt = GlobalDictsHolder->GetAuxArticle(SDictIndex(KW_DICT, (*artIndexes)[i]))->get_title();
m_SitFoundByArticles.insert(strArt);
}
} else if (artPointer.HasStrType())
m_SitFoundByArticles.insert(artPointer.GetStrType());
}
void CSentenceRusProcessor::FindSituationsInner(const SArtPointer& artPointer)
{
bool bRun = true;
CFilterCheck filterCheck(m_MultiWordCreator);
if (artPointer.HasKWType() && !filterCheck.CheckFiltersWithoutOrder(GlobalDictsHolder->GetFilter(artPointer.GetKWType())))
bRun = false;
if (bRun) {
m_MultiWordCreator.m_bProcessedByGrammar = true;
CSituationsSearcher SituationsSearcher(this);
SituationsSearcher.Run(artPointer);
const yvector<SValenciesValues>& valValues = SituationsSearcher.GetFoundVals();
for (size_t i = 0; i < valValues.size(); ++i)
AddFoundVals(valValues[i]);
if (valValues.size() > 0 && artPointer.HasKWType())
m_KwType2FoundVals[artPointer.GetKWType()] = new yvector<SValenciesValues>(valValues);
}
AddToAlreadySearchedSit(artPointer);
}
void CSentenceRusProcessor::AddFoundVals(const SValenciesValues& valenciesValues)
{
const Wtroka& strArt = valenciesValues.m_pArt->get_title();
ymap<Wtroka, TValValuesPtr>::iterator it = m_article2FoundVals.find(strArt);
if (it == m_article2FoundVals.end()) {
TValValuesPtr& ptr = m_article2FoundVals[strArt];
ptr.Reset(new yvector<SValenciesValues>);
ptr->push_back(valenciesValues);
} else {
if (it->second.Get() == NULL)
it->second.Reset(new yvector<SValenciesValues>);
it->second->push_back(valenciesValues);
}
}
void CSentenceRusProcessor::FindSituations(const SArtPointer& artPointer)
{
if (artPointer.HasKWType()) {
TKeyWordType kwType = artPointer.GetKWType();
const yvector<int>* artIndexes = GlobalDictsHolder->GetDict(KW_DICT).GetAuxArticles(kwType);
YASSERT(artIndexes!= NULL);
yvector<SArtPointer> artToFind; // запихиваем сюда те статьи, которые
// не были найдены
bool bAllNotFound = true;
for (size_t i = 0; i < artIndexes->size(); i++) {
const Wtroka& strArt = GlobalDictsHolder->GetAuxArticle(SDictIndex(KW_DICT, (*artIndexes)[i]))->get_title();
if (!SearchingOfSitWasPerformed(strArt))
artToFind.push_back(SArtPointer(strArt));
else
bAllNotFound = false;
}
if (bAllNotFound)
FindSituationsInner(artPointer);
else
for (size_t i = 0; i < artToFind.size(); ++i)
FindSituationsInner(artToFind[i]);
} else if (artPointer.HasStrType() && !SearchingOfSitWasPerformed(artPointer.GetStrType()))
FindSituationsInner(artPointer);
}
void CSentenceRusProcessor::GetFoundMWInLinks(yvector<SMWAddressWithLink>& mwFounds, const SArtPointer& artPointer) const
{
if (!artPointer.IsForLink())
return;
if (m_SentMarkUps.size() == 0)
return;
yset<SSentMarkUp>::const_iterator it = m_SentMarkUps.begin();
for (; it != m_SentMarkUps.end(); it++) {
const SSentMarkUp& markUp = *it;
yvector<SWordHomonymNum> whs;
m_MultiWordCreator.GetFoundWordsInPeriod(artPointer, whs, markUp);
for (size_t i = 0; i < whs.size(); i++) {
mwFounds.push_back(SMWAddressWithLink(-1, whs[i]));
mwFounds.back().m_Link = markUp;
}
}
}
void CSentenceRusProcessor::FindMultiWordsInLink(const SArtPointer& artPointer)
{
yset<SSentMarkUp>::const_iterator it = m_SentMarkUps.begin();
for (; it != m_SentMarkUps.end(); it++) {
const SSentMarkUp& markUp = *it;
m_MultiWordCreator.FindWordsInPeriod(artPointer, markUp);
}
}
void CSentenceRusProcessor::FindMultiWords(const SArtPointer& artPointer)
{
try {
if (artPointer.IsForLink()) {
if (m_SentMarkUps.size() > 0)
FindMultiWordsInLink(artPointer);
} else
m_MultiWordCreator.FindKWWords(artPointer, KW_DICT);
} catch (yexception& e) {
PrintError("Error in CSentenceRusProcessor::FindMultiWords()", &e);
throw;
} catch (...) {
PrintError("Error in CSentenceRusProcessor::FindMultiWords()", NULL);
throw;
}
}
void CSentenceRusProcessor::FindMultiWordsByArticle(const Wtroka& strArtTitle, TKeyWordType kwType)
{
try {
SArtPointer artPointer;
if (kwType != NULL) {
artPointer.PutKWType(kwType);
}
if (!strArtTitle.empty()) {
artPointer.PutStrType(strArtTitle);
}
FindMultiWords(artPointer);
} catch (yexception& e) {
PrintError("Error in CSentenceRusProcessor::FindMultiWordsByArticle(), ", &e);
throw;
} catch (...) {
PrintError("Error in CSentenceRusProcessor::FindMultiWordsByArticle(), ", NULL);
throw;
}
}
const CFactFields& CSentenceRusProcessor::GetFact(const SFactAddress& factAddr) const
{
CHomonym& h = const_cast<CHomonym&>(m_Words[factAddr]);
CWordSequence* pWS = h.GetSourceWordSequence();
if (pWS == NULL)
ythrow yexception() << "Bad fact address in \"CSentenceRusProcessor::GetFact\"";
CFactsWS* pFactsWS = dynamic_cast<CFactsWS*>(pWS);
if (pFactsWS == NULL)
ythrow yexception() << "Bad CWordSequence subclass in \"CSentenceRusProcessor::GetFact\"";
return pFactsWS->GetFact(factAddr.m_iFactNum);
}
void CSentenceRusProcessor::FillFactAddresses(yset<SFactAddress>& factAddresses, SFactAddress& templateFactAddress)
{
for (size_t i = 0; i < m_Words.GetAllWordsCount(); ++i) {
const CWord& w = m_Words.GetAnyWord(i);
templateFactAddress.m_WordNum = i;
if (templateFactAddress.m_WordNum >= (int)m_Words.OriginalWordsCount())
templateFactAddress.m_WordNum -= m_Words.OriginalWordsCount();
if (w.IsMultiWord())
templateFactAddress.m_bOriginalWord = false;
else
templateFactAddress.m_bOriginalWord = true;
for (CWord::SHomIt it = w.IterHomonyms(); it.Ok(); ++it) {
CHomonym& h = (CHomonym&)(*it);
CWordSequence* pWS = h.GetSourceWordSequence();
CFactsWS* pFactsWS = dynamic_cast<CFactsWS*>(pWS);
if (pFactsWS == NULL)
continue;
templateFactAddress.m_HomNum = it.GetID();
for (int j = 0; j < pFactsWS->GetFactsCount(); j++) {
SFactAddress factAddress;
factAddress = templateFactAddress;
factAddress.m_iFactNum = j;
factAddresses.insert(factAddress);
}
}
}
}
Wtroka CSentenceRusProcessor::GetCapitalizedLemma(const CWord& w, int, Wtroka strLemma)
{
return CNormalization::GetCapitalizedLemma(w, strLemma);
}
void CSentenceRusProcessor::FindNames(yvector<CFioWordSequence>& foundNames,
yvector<int>& potentialSurnames)
{
#ifdef NDEBUG
try {
#endif
InitNameTypes();
CNameFinder nameFinder(m_Words);
nameFinder.Run(foundNames, potentialSurnames);
for (size_t i = 0; i < foundNames.size(); i++)
ChangeFirstName(foundNames[i].GetFio(), foundNames[i]);
yvector<SWordHomonymNum> foundWords;
DECLARE_STATIC_RUS_WORD(kMWFio, "многословное_фио_");
yvector<SWordHomonymNum>* pFoundWords = m_MultiWordCreator.GetFoundWords(SArtPointer(kMWFio), KW_DICT);
yvector<COccurrence> multiWordsOccurrences;
if (pFoundWords == NULL)
return;
foundWords = *pFoundWords;
yvector<CWordsPair> fiosToDelete;
for (size_t i = 0; i < foundWords.size(); i++) {
const CWord& pW = m_Words.GetWord(foundWords[i]);
COccurrence o(pW.GetSourcePair().FirstWord(), pW.GetSourcePair().LastWord() + 1, i);
multiWordsOccurrences.push_back(o);
if (IsBadMWNFio(m_Words[foundWords[i]].GetSourceWordSequence()))
fiosToDelete.push_back(pW.GetSourcePair());
}
std::multiset<CWordsPair, SSimplePeriodOrder> manuallyFoundFios;
for (size_t i = 0; i < foundNames.size(); i++) {
const CWordSequence& ws = foundNames[i];
COccurrence o(ws.FirstWord(), ws.LastWord() + 1, 0xFFFF);
manuallyFoundFios.insert(ws);
multiWordsOccurrences.push_back(o);
}
SolveAmbiguity(multiWordsOccurrences);
for (size_t i = 0; i < multiWordsOccurrences.size(); i++) {
COccurrence& occ = multiWordsOccurrences[i];
CWordsPair wp(occ.first, occ.second-1);
std::multiset<CWordsPair, SPeriodOrder>::iterator it = manuallyFoundFios.find(wp);
if (it != manuallyFoundFios.end()) {
const CWordsPair& manualFio = *it;
size_t k;
for (k = 0; k < fiosToDelete.size(); k++)
if (fiosToDelete[k] == manualFio)
break;
if (k >= fiosToDelete.size()) {
do
{
manuallyFoundFios.erase(it);
it = manuallyFoundFios.find(wp);
}
while (it != manuallyFoundFios.end());
}
} else {
SWordHomonymNum wh = foundWords[occ.m_GrammarRuleNo];
if (occ.m_GrammarRuleNo == 0xFFFF) {
std::cout << "Errors!" << std::endl;
continue; //не должно случиться
}
const CHomonym& h = m_Words[wh];
CFioWordSequence fioOcc;
if (!ConvertMWFioFactToFioWS(h.GetSourceWordSequence(), fioOcc.GetFio(), fioOcc))
continue;
fioOcc.m_NameMembers[Surname] = wh;
foundNames.push_back(fioOcc);
}
}
// удалим ФИО, которые построены руками, но не добавлены
if (manuallyFoundFios.size() > 0) {
for (int i = (int)foundNames.size() - 1; i >= 0; i--) {
std::multiset<CWordsPair, SPeriodOrder>::iterator it = manuallyFoundFios.find(foundNames[i]);
if (it != manuallyFoundFios.end()) {
foundNames.erase(foundNames.begin()+i);
manuallyFoundFios.erase(it);
}
}
}
#ifdef NDEBUG
} catch (yexception& e) {
PrintError("Error in CSentenceRusProcessor::FindNames()", &e);
throw;
} catch (...) {
PrintError("Error in CSentenceRusProcessor::FindNames()", NULL);
throw;
}
#endif
}
// predefined MWN field names
static const Stroka
kMWN = "MWN",
kDeleteManualFio = "DeleteManualFio",
k_fname = "fname",
k_mname = "mname",
k_lname = "lname",
k_bNominative = "bNominative",
k_bKnownLName = "bKnownLName";
bool CSentenceRusProcessor::ConvertMWFioFactToFioWS(CWordSequence* pWS, SFullFIO& fullFio, CFIOOccurence& fioOccurence)
{
CFactsWS* pFactsWS = dynamic_cast<CFactsWS*>(pWS);
if (pFactsWS == NULL)
return false;
int i;
for (i = 0; i < pFactsWS->GetFactsCount(); i++) {
if (pFactsWS->GetFact(i).GetFactName() == kMWN)
break;
}
if (i >= pFactsWS->GetFactsCount())
return false;
CFactFields& fact = pFactsWS->GetFact(i);
if (fact.GetBoolValue(kDeleteManualFio))
return false;
CTextWS* textWS = fact.GetTextValue(k_fname);
if (textWS)
fullFio.m_strName = textWS->GetCapitalizedLemma();
textWS = fact.GetTextValue(k_mname);
if (textWS)
fullFio.m_strPatronomyc = textWS->GetCapitalizedLemma();
textWS = fact.GetTextValue(k_lname);
if (textWS)
fullFio.m_strSurname = textWS ->GetCapitalizedLemma();
fullFio.m_bSurnameLemma = fact.GetBoolValue(k_bNominative);
fullFio.m_bFoundSurname = fact.GetBoolValue(k_bKnownLName);
(CWordSequence&)(fioOccurence) = (CWordSequence&)(*pFactsWS);
return true;
}
bool CSentenceRusProcessor::IsBadMWNFio(CWordSequence* pWS)
{
CFactsWS* pFactsWS = dynamic_cast<CFactsWS*>(pWS);
if (pFactsWS == NULL)
return false;
for (int i = 0; i < pFactsWS->GetFactsCount(); ++i)
if (pFactsWS->GetFact(i).GetFactName() == kMWN) {
CFactFields& fact = pFactsWS->GetFact(i);
return fact.GetBoolValue(kDeleteManualFio);
}
return false;
}
void CSentenceRusProcessor::SetFragmOptions(const SFragmOptions* fragmOptions)
{
FragmOptions = fragmOptions;
}
// у собранных вручную фио поменяем, если нужно, имя на лемму, указнную в статьях, где ТИП_КС = tl_variant
// (у фио, собранных грамматикой, имя заменяется автоматически)
void CSentenceRusProcessor::ChangeFirstName(SFullFIO& fullFio, CFIOOccurence& fioOccurence)
{
TKeyWordType kwtype_tl_variant = GlobalDictsHolder->BuiltinKWTypes().TlVariant;
if (fioOccurence.m_NameMembers[FirstName].IsValid()) {
const CWord& w = m_Words.GetWord(fioOccurence.m_NameMembers[FirstName]);
int iH = w.HasArticle_i(SArtPointer(kwtype_tl_variant));
if (iH != -1) {
const CHomonym& kw_h = w.GetRusHomonym(iH);
if (kw_h.GetLemma() == fullFio.m_strName) {
Wtroka lemma_text = GlobalDictsHolder->GetUnquotedDictionaryLemma(kw_h, KW_DICT);
if (!lemma_text.empty())
fullFio.m_strName = lemma_text;
}
}
} else if (fioOccurence.m_NameMembers[InitialName].IsValid()) {
const CWord& w = m_Words.GetWord(fioOccurence.m_NameMembers[InitialName]);
if (w.IsName(InitialName)) {
// TODO: gazetteer
const CIndexedDictionary& dict = GlobalDictsHolder->GetDict(KW_DICT);
yvector<CContentsCluster*> foundClusters;
if (dict.m_Contents.FindCluster(fullFio.m_strName, CompByLemma, foundClusters))
for (size_t i = 0; i < foundClusters.size(); ++i) {
const CContentsCluster* cl = foundClusters[i];
if (cl->size() == 1)
for (size_t j = 0; j < cl->m_IDs.size(); ++j) {
const article_t* pArt = dict[cl->m_IDs[j]];
if (pArt->get_kw_type() == kwtype_tl_variant)
fullFio.m_strName = pArt->get_lemma();
}
}
}
}
}
|
evilmucedin/tomita-parser
|
src/FactExtract/Parser/afdocparser/rusie/sentencerusprocessor.cpp
|
C++
|
mpl-2.0
| 17,534
|
<html xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:vim2="urn:vim2" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<script src="./commonRes.js" language="JavaScript"> type="text/javascript"></script>
<link href="doc-style.css" type="text/css" rel="StyleSheet">
</head>
<script src="dynamic-content.js" type="text/javascript"></script>
<body>
<table cellspacing="0" class="header-footer" id="top">
<tr>
<td>
<br>
</td><td></td><td></td><td></td>
</tr>
<tr>
<td><a href="index-mo_types.html">Managed Object Types</a></td><td><a href="index-do_types.html">Data Object Types</a></td><td><a href="index-properties.html">All Properties</a></td><td><a href="index-methods.html">All Methods</a></td>
</tr>
</table>
<br>
<a id="vim.cluster.DasAamNodeState.DasState" name="vim.cluster.DasAamNodeState.DasState"></a>
<h1>Enum -
ClusterDasAamNodeStateDasState</h1>
<dl>
<dt>Since </dt>
<dd>vSphere API 4.0</dd>
<p></p>
</dl>
<br>
<h2>Enum Description</h2>
<p></p>
The <a href="vim.cluster.DasAamNodeState.DasState.html">ClusterDasAamNodeStateDasState</a> enumerated type defines
values for host HA configuration and runtime state properties
(<a href="vim.cluster.DasAamNodeState.html#configState">configState</a> and
<a href="vim.cluster.DasAamNodeState.html#runtimeState">runtimeState</a>).
<p></p>
<a id="field_detail" name="field_detail"></a>
<p class="table-title">Enum Constants</p>
<table cellspacing="0">
<tr>
<th>Name</th><th>Description</th>
</tr>
<tr class="r1">
<td><a id="agentShutdown" name="agentShutdown"></a>agentShutdown</td><td>
The HA agent has been shut down.
<br>
</td>
</tr>
<tr class="r0">
<td><a id="configuring" name="configuring"></a>configuring</td><td>
HA configuration is in progress.
<br>
</td>
</tr>
<tr class="r1">
<td><a id="error" name="error"></a>error</td><td>
There is an error condition. This can represent a configuration
error or a host agent runtime error.
<br>
</td>
</tr>
<tr class="r0">
<td><a id="initialized" name="initialized"></a>initialized</td><td>
HA agents have been installed but are not running on the the host.
<br>
</td>
</tr>
<tr class="r1">
<td><a id="nodeFailed" name="nodeFailed"></a>nodeFailed</td><td>
The host is not reachable. This can represent a host failure
or an isolated host.
<br>
</td>
</tr>
<tr class="r0">
<td><a id="running" name="running"></a>running</td><td>
HA agent is running on this host.
<br>
</td>
</tr>
<tr class="r1">
<td><a id="unconfiguring" name="unconfiguring"></a>unconfiguring</td><td>
HA configuration is being removed.
<br>
</td>
</tr>
<tr class="r0">
<td><a id="uninitialized" name="uninitialized"></a>uninitialized</td><td>
HA has never been enabled on the the host.
<br>
</td>
</tr>
</table>
<br>
<a style="margin-bottom:10px; margin-top:10px; cursor:hand; cursor:pointer" onclick="resize_textarea('wsdl-textarea');expandcontent(this, 'wsdl-div')">Show WSDL type definition</a>
<div class="switchcontent" id="wsdl-div">
<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea"> <simpleType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="ClusterDasAamNodeStateDasState">
<restriction base="xsd:string">
<enumeration value="uninitialized"/>
<enumeration value="initialized"/>
<enumeration value="configuring"/>
<enumeration value="unconfiguring"/>
<enumeration value="running"/>
<enumeration value="error"/>
<enumeration value="agentShutdown"/>
<enumeration value="nodeFailed"/>
</restriction>
</simpleType></textarea>
</div>
<br>
<br>
<table cellspacing="0" class="header-footer" id="bottom">
<tr>
<td><a href="#top">Top of page</a></td><td></td><td></td><td></td>
</tr>
<tr>
<td><a href="index-mo_types.html">Managed Object Types</a></td><td><a href="index-do_types.html">Data Object Types</a></td><td><a href="index-properties.html">All Properties</a></td><td><a href="index-methods.html">All Methods</a></td>
</tr>
</table>
<br>
<script language="javascript">document.write(ID_Copyright);</script>
<br>
<script language="javascript">document.write(ID_VersionInformation);</script>
</body>
</html>
|
hooklift/govsphere
|
reference/vim.cluster.DasAamNodeState.DasState.html
|
HTML
|
mpl-2.0
| 4,605
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.