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
|
|---|---|---|---|---|---|
/*******************************************************************************************************
*
* msi.gaml.types.IType.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and simulation
* platform (v. 1.8.1)
*
* (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package msi.gaml.types;
import java.util.Map;
import msi.gama.common.interfaces.IGamlDescription;
import msi.gama.common.interfaces.ITyped;
import msi.gama.runtime.IScope;
import msi.gaml.descriptions.IDescription;
import msi.gaml.descriptions.OperatorProto;
import msi.gaml.descriptions.SpeciesDescription;
import msi.gaml.expressions.IExpression;
/**
* Written by drogoul Modified on 9 juin 2010
*
* @todo Description
*
*/
public interface IType<Support> extends IGamlDescription, ITyped {
String[] vowels = new String[] { "a", "e", "i", "o", "u", "y" };
/** Constant fields to indicate the types of facets */
int LABEL = -200;
int ID = -201;
int TYPE_ID = -202;
int NEW_VAR_ID = -203;
int NEW_TEMP_ID = -204;
int NONE = 0;
int INT = 1;
int FLOAT = 2;
int BOOL = 3;
int STRING = 4;
int LIST = 5;
int COLOR = 6;
int POINT = 7;
int MATRIX = 8;
int PAIR = 9;
int MAP = 10;
int AGENT = 11;
int FILE = 12;
int GEOMETRY = 13;
int SPECIES = 14;
int GRAPH = 15;
int CONTAINER = 16;
int PATH = 17;
int TOPOLOGY = 18;
int FONT = 19;
int IMAGE = 20;
int REGRESSION = 21;
int SKILL = 22;
int DATE = 23;
int MESSAGE = 24;
int MATERIAL = 25;
int ACTION = 26;
int ATTRIBUTES = 27;
int KML = 29;
// Represents the meta-type (type of values type)
int TYPE = 28;
int AVAILABLE_TYPES = 50;
int SPECIES_TYPES = 100;
Support cast(IScope scope, Object obj, Object param, boolean copy);
Support cast(IScope scope, Object obj, Object param, IType<?> keyType, IType<?> contentType, boolean copy);
int id();
Class<? extends Support> toClass();
Support getDefault();
int getVarKind();
OperatorProto getGetter(String name);
Map<String, OperatorProto> getFieldGetters();
boolean isAgentType();
boolean isSkillType();
boolean isParametricType();
boolean isParametricFormOf(final IType<?> l);
String getSpeciesName();
SpeciesDescription getSpecies();
boolean isAssignableFrom(IType<?> l);
boolean isTranslatableInto(IType<?> t);
void setParent(IType<? super Support> p);
IType<?> getParent();
IType<?> coerce(IType<?> expr, IDescription context);
/**
* returns the distance between two types
*
* @param originalChildType
* @return
*/
int distanceTo(IType<?> originalChildType);
/**
* @param n
* @param typeFieldExpression
*/
void setFieldGetters(Map<String, OperatorProto> map);
/**
* @param c
* @return
*/
boolean canBeTypeOf(IScope s, Object c);
void init(int varKind, final int id, final String name, final Class<Support> clazz);
/**
* Whether or not this type can be considered as having a contents. True for all containers and special types (like
* rgb, species, etc.)
*
* @return
*/
// public abstract boolean hasContents();
boolean isContainer();
/**
* Whether or not this type can be used in add or remove statements
*
* @return
*/
boolean isFixedLength();
/**
* Tries to find a common supertype shared between this and the argument.
*
* @param iType
* @return
*/
IType<? super Support> findCommonSupertypeWith(IType<?> iType);
boolean isParented();
void setSupport(Class<Support> clazz);
/**
* @param context
* When casting an expression, the type returned is usually that of this type. However, some types will
* compute another type based on the type of the expressoin to cast (for instance, species or agent)
* @param exp
* @return
*/
IType<?> typeIfCasting(final IExpression exp);
IType<?> getContentType();
IType<?> getKeyType();
/**
* @return
*/
boolean canCastToConst();
/**
* @return
*/
String asPattern();
/**
* @param plugin
* name
*/
void setDefiningPlugin(String plugin);
boolean isNumber();
/**
* @return
*/
boolean isDrawable();
default boolean isComparable() {
return Comparable.class.isAssignableFrom(toClass());
}
IType<?> getWrappedType();
SpeciesDescription getDenotedSpecies();
/**
* Denotes a type that has components which can be exctracted when casting it to a container (for instance, points
* have float components). The inner type is returned by getContentType(). Containers are compound types by default
*
* @return true if the type represents a compound value which components can be extracted
*/
boolean isCompoundType();
/**
* Returns the number of type parameters this type can accept (for instance list is 1, int is 0, map is 2, file
* depends on the wrapped buffer type, etc.)
*
* @return
*/
int getNumberOfParameters();
}
|
gama-platform/gama
|
msi.gama.core/src/msi/gaml/types/IType.java
|
Java
|
gpl-3.0
| 5,023
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import { bytesToHex, hex2Ascii } from '~/api/util/format';
import ABI from './abi/certifier.json';
const ZERO = '0x0000000000000000000000000000000000000000000000000000000000000000';
export default class BadgeReg {
constructor (api, registry) {
this._api = api;
this._registry = registry;
registry.getContract('badgereg');
this.certifiers = {}; // by name
this.contracts = {}; // by name
}
fetchCertifier (name) {
if (this.certifiers[name]) {
return Promise.resolve(this.certifiers[name]);
}
return this._registry.getContract('badgereg')
.then((badgeReg) => {
return badgeReg.instance.fromName.call({}, [name])
.then(([ id, address ]) => {
return Promise.all([
badgeReg.instance.meta.call({}, [id, 'TITLE']),
badgeReg.instance.meta.call({}, [id, 'IMG'])
])
.then(([ title, img ]) => {
title = bytesToHex(title);
title = title === ZERO ? null : hex2Ascii(title);
if (bytesToHex(img) === ZERO) img = null;
const data = { address, name, title, icon: img };
this.certifiers[name] = data;
return data;
});
});
});
}
checkIfCertified (certifier, address) {
if (!this.contracts[certifier]) {
this.contracts[certifier] = this._api.newContract(ABI, certifier);
}
const contract = this.contracts[certifier];
return contract.instance.certified.call({}, [address]);
}
}
|
immartian/musicoin
|
js/src/contracts/badgereg.js
|
JavaScript
|
gpl-3.0
| 2,237
|
/*
* State.cpp
*
* Created on: Nov 11, 2016
* Author: Denis Kudia
*/
#include "State.h"
namespace smachine {
namespace state {
State::State(const std::shared_ptr<StateMachineItf>& itf, const std::string& name) :
m_itf(itf), m_name(name)
{
}
State::~State(){
}
} /* namespace state */
} /* namespace smachine */
|
KDenisPi/pi-robot
|
pi-smachine/State.cpp
|
C++
|
gpl-3.0
| 331
|
<?php
/* *
* Ameden Web Engine Content Management System <http://engine.ameden.net/>
* Copyright © 2013 Vladislav Balandin <http://www.ameden.net/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*/
if(!defined('AMEDEN')) die('Ó âàñ íåò ïðàâ íà âûïîëíåíèå äàííîãî ôàéëà!');
if($user->check_logged()) {
$tmp->theme('comments.add.tpl','addcomments');
if(isset($_POST['comment_send'])) {
switch($user->check_comment($functions->strip($_POST['comment']))) {
case 1: $e = $tmp->info('error',MSG('COMMENT_REQUIRED')); break;
case 2:
if($db->getParam('send_mail_oncomment') == 'true') {
$mail->setHeaders(
'CP1251',
'KOI8-R',
$db->getParam('admin_mail'),
'Îïîâåùåíèå',
str_replace(
array(
'{name}',
'{mail}',
'{username}',
'{comment}',
'{sitename}',
'{newslink}'
),
array(
$functions->strip($user->get_array('name')),
$functions->strip($user->get_array('mail')),
$functions->strip($user->get_array('username')),
$functions->strip($_POST['comment'],true),
$db->getParam('title'),
'http://'.$_SERVER['HTTP_HOST'].'/news/'.$functions->strip($id)
),
MAIL_MSG('NEW_COMMENT')
),
'AWE_BOT@'.$_SERVER['HTTP_HOST']
);
$mail->send();
}
$db->query('INSERT INTO `'.DB_PREFIX.'_comments` (`author`, `comment`, `newsid`, `date`) VALUES (\''.$user->get_array('username').'\', \''.$functions->strip($_POST['comment'],true).'\', \''.$functions->strip($id).'\', \''.date('d.m.Y, â H:i').'\')');
$e = $tmp->info('success',MSG('COMMENT_WERE_ADDED'));
break;
}
} else $e = '';
echo $e.$tmp->display('addcomments');
} else echo $tmp->info('info',MSG('LOGIN_REQUIRED'));
?>
|
L1nQ/AWE-1
|
AWE v2.3/engine/modules/comments.add.php
|
PHP
|
gpl-3.0
| 2,372
|
/*
* R Cloud - R-based Cloud Platform for Computational Research
* at EMBL-EBI (European Bioinformatics Institute)
*
* Copyright (C) 2007-2015 European Bioinformatics Institute
* Copyright (C) 2009-2015 Andrew Tikhonov - andrew.tikhonov@gmail.com
* Copyright (C) 2007-2009 Karim Chine - karim.chine@m4x.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 uk.ac.ebi.rcloud.http.proxy;
/**
* Created by IntelliJ IDEA.
* User: andrew
* Date: Feb 14, 2011
* Time: 3:10:26 PM
* To change this template use File | Settings | File Templates.
*/
public interface HttpMarker {
public void stopThreads();
public void popActions();
}
|
andrewtikhonov/RCloud
|
rcloud-http-api/src/main/java/uk/ac/ebi/rcloud/http/proxy/HttpMarker.java
|
Java
|
gpl-3.0
| 1,251
|
import React from 'react';
import classnames from 'classnames';
const defaultButton = props =>
<button
type="button"
className="-btn"
{ ...props }>
{ props.children }
</button>
const PaginationRender = function() {
const {
// Computed
pages,
// Props
page,
showPageSizeOptions,
pageSizeOptions,
pageSize,
showPageJump,
canPrevious,
canNext,
onPageSizeChange,
className,
PreviousComponent = defaultButton,
NextComponent = defaultButton,
} = this.props;
return (
<div
className={ classnames(className, '-pagination') }
style={ this.props.paginationStyle }>
<div className="-previous">
<PreviousComponent
onClick={
e => {
if (!canPrevious) return;
this.changePage(page - 1);
}
}
disabled={ !canPrevious }>
{ this.props.previousText }
</PreviousComponent>
</div>
<div className="-center">
<span className="-pageInfo">
{ this.props.pageText }{ ' ' }
{ showPageJump
?
<div className="-pageJump">
<input
type={ this.state.page === '' ? 'text' : 'number' }
onChange={
e => {
const val = e.target.value;
this.changePage(val - 1);
}
}
value={ this.state.page === '' ? '' : this.state.page + 1 }
onBlur={ this.applyPage }
onKeyPress={
e => {
if (e.which === 13 ||
e.keyCode === 13) {
this.applyPage();
}
}
} />
</div>
:
<span className="-currentPage">
{ page + 1 }
</span>
}{ ' ' }
{ this.props.ofText }{ ' ' }
<span className="-totalPages">{ pages || 1 }</span>
</span>
{ showPageSizeOptions &&
<span className="select-wrap -pageSizeOptions">
<select
onChange={ e => onPageSizeChange(Number(e.target.value)) }
value={ pageSize }>
{ this.renderPageNav(pageSizeOptions) }
</select>
</span>
}
</div>
<div className="-next">
<NextComponent
onClick={
e => {
if (!canNext) return;
this.changePage(page + 1);
}
}
disabled={ !canNext }>
{ this.props.nextText }
</NextComponent>
</div>
</div>
)
};
export default PaginationRender;
|
pbca26/EasyDEX-GUI
|
react/src/components/dashboard/pagination/pagination.render.js
|
JavaScript
|
gpl-3.0
| 2,749
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include <atomic>
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <functional>
#include <list>
#include <memory>
#include <queue>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <boost/intrusive/list.hpp>
#include <glog/logging.h>
#include <folly/Executor.h>
#include <folly/Function.h>
#include <folly/Memory.h>
#include <folly/Portability.h>
#include <folly/ScopeGuard.h>
#include <folly/Synchronized.h>
#include <folly/executors/DrivableExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/executors/ScheduledExecutor.h>
#include <folly/executors/SequencedExecutor.h>
#include <folly/experimental/ExecutionObserver.h>
#include <folly/io/async/AsyncTimeout.h>
#include <folly/io/async/HHWheelTimer.h>
#include <folly/io/async/Request.h>
#include <folly/io/async/TimeoutManager.h>
#include <folly/portability/Event.h>
#include <folly/synchronization/CallOnce.h>
namespace folly {
class EventBaseBackendBase;
using Cob = Func; // defined in folly/Executor.h
template <typename Task, typename Consumer>
class EventBaseAtomicNotificationQueue;
template <typename MessageT>
class NotificationQueue;
namespace detail {
class EventBaseLocalBase;
class EventBaseLocalBaseBase {
public:
virtual void onEventBaseDestruction(EventBase& evb) = 0;
virtual ~EventBaseLocalBaseBase() = default;
};
} // namespace detail
template <typename T>
class EventBaseLocal;
class EventBaseObserver {
public:
virtual ~EventBaseObserver() = default;
virtual uint32_t getSampleRate() const = 0;
virtual void loopSample(int64_t busyTime, int64_t idleTime) = 0;
};
// Helper class that sets and retrieves the EventBase associated with a given
// request via RequestContext. See Request.h for that mechanism.
class RequestEventBase : public RequestData {
public:
static EventBase* get() {
auto data = dynamic_cast<RequestEventBase*>(
RequestContext::get()->getContextData(token()));
if (!data) {
return nullptr;
}
return data->eb_;
}
static void set(EventBase* eb) {
RequestContext::get()->setContextData(
token(), std::unique_ptr<RequestEventBase>(new RequestEventBase(eb)));
}
bool hasCallback() override { return false; }
private:
FOLLY_EXPORT static RequestToken const& token() {
static RequestToken const token(kContextDataName);
return token;
}
explicit RequestEventBase(EventBase* eb) : eb_(eb) {}
EventBase* eb_;
static constexpr const char* kContextDataName{"EventBase"};
};
class VirtualEventBase;
/**
* This class is a wrapper for all asynchronous I/O processing functionality
*
* EventBase provides a main loop that notifies EventHandler callback objects
* when I/O is ready on a file descriptor, and notifies AsyncTimeout objects
* when a specified timeout has expired. More complex, higher-level callback
* mechanisms can then be built on top of EventHandler and AsyncTimeout.
*
* A EventBase object can only drive an event loop for a single thread. To
* take advantage of multiple CPU cores, most asynchronous I/O servers have one
* thread per CPU, and use a separate EventBase for each thread.
*
* In general, most EventBase methods may only be called from the thread
* running the EventBase's loop. There are a few exceptions to this rule, for
* methods that are explicitly intended to allow communication with a
* EventBase from other threads. When it is safe to call a method from
* another thread it is explicitly listed in the method comments.
*/
class EventBase : public TimeoutManager,
public DrivableExecutor,
public IOExecutor,
public SequencedExecutor,
public ScheduledExecutor {
public:
friend class ScopedEventBaseThread;
using Func = folly::Function<void()>;
/**
* A callback interface to use with runInLoop()
*
* Derive from this class if you need to delay some code execution until the
* next iteration of the event loop. This allows you to schedule code to be
* invoked from the top-level of the loop, after your immediate callers have
* returned.
*
* If a LoopCallback object is destroyed while it is scheduled to be run in
* the next loop iteration, it will automatically be cancelled.
*/
class LoopCallback
: public boost::intrusive::list_base_hook<
boost::intrusive::link_mode<boost::intrusive::auto_unlink>> {
public:
virtual ~LoopCallback() = default;
virtual void runLoopCallback() noexcept = 0;
void cancelLoopCallback() {
context_.reset();
unlink();
}
bool isLoopCallbackScheduled() const { return is_linked(); }
private:
typedef boost::intrusive::
list<LoopCallback, boost::intrusive::constant_time_size<false>>
List;
// EventBase needs access to LoopCallbackList (and therefore to hook_)
friend class EventBase;
friend class VirtualEventBase;
std::shared_ptr<RequestContext> context_;
};
class FunctionLoopCallback : public LoopCallback {
public:
explicit FunctionLoopCallback(Func&& function)
: function_(std::move(function)) {}
void runLoopCallback() noexcept override {
function_();
delete this;
}
private:
Func function_;
};
// Like FunctionLoopCallback, but saves one allocation. Use with caution.
//
// The caller is responsible for maintaining the lifetime of this callback
// until after the point at which the contained function is called.
class StackFunctionLoopCallback : public LoopCallback {
public:
explicit StackFunctionLoopCallback(Func&& function)
: function_(std::move(function)) {}
void runLoopCallback() noexcept override { Func(std::move(function_))(); }
private:
Func function_;
};
// Base class for user callbacks to be run during EventBase destruction. As
// with LoopCallback, users may inherit from this class and provide a concrete
// implementation of onEventBaseDestruction(). (Alternatively, users may use
// the convenience method EventBase::runOnDestruction(Function<void()> f) to
// schedule a function f to be run on EventBase destruction.)
//
// The only thread-safety guarantees of OnDestructionCallback are as follows:
// - Users may call runOnDestruction() from any thread, provided the caller
// is the only user of the callback, i.e., the callback is not already
// scheduled and there are no concurrent calls to schedule or cancel the
// callback.
// - Users may safely cancel() from any thread. Multiple calls to cancel()
// may execute concurrently. The only caveat is that it is not safe to
// call cancel() within the onEventBaseDestruction() callback.
class OnDestructionCallback {
public:
OnDestructionCallback() = default;
OnDestructionCallback(OnDestructionCallback&&) = default;
OnDestructionCallback& operator=(OnDestructionCallback&&) = default;
virtual ~OnDestructionCallback();
// Attempt to cancel the callback. If the callback is running or has already
// finished running, cancellation will fail. If the callback is running when
// cancel() is called, cancel() will block until the callback completes.
bool cancel();
// Callback to be invoked during ~EventBase()
virtual void onEventBaseDestruction() noexcept = 0;
private:
boost::intrusive::list_member_hook<
boost::intrusive::link_mode<boost::intrusive::normal_link>>
listHook_;
Function<void(OnDestructionCallback&)> eraser_;
Synchronized<bool> scheduled_{in_place, false};
using List = boost::intrusive::list<
OnDestructionCallback,
boost::intrusive::member_hook<
OnDestructionCallback,
decltype(listHook_),
&OnDestructionCallback::listHook_>>;
void schedule(
FunctionRef<void(OnDestructionCallback&)> linker,
Function<void(OnDestructionCallback&)> eraser);
friend class EventBase;
friend class VirtualEventBase;
protected:
virtual void runCallback() noexcept;
};
class FunctionOnDestructionCallback : public OnDestructionCallback {
public:
explicit FunctionOnDestructionCallback(Function<void()> f)
: f_(std::move(f)) {}
void onEventBaseDestruction() noexcept final { f_(); }
protected:
void runCallback() noexcept override {
OnDestructionCallback::runCallback();
delete this;
}
private:
Function<void()> f_;
};
struct Options {
Options() {}
/**
* Skip measuring event base loop durations.
*
* Disabling it would likely improve performance, but will disable some
* features that rely on time-measurement, including: observer, max latency
* and avg loop time.
*/
bool skipTimeMeasurement{false};
Options& setSkipTimeMeasurement(bool skip) {
skipTimeMeasurement = skip;
return *this;
}
/**
* Factory function for creating the backend.
*/
using BackendFactory =
folly::Function<std::unique_ptr<folly::EventBaseBackendBase>()>;
BackendFactory::SharedProxy backendFactory{nullptr};
Options& setBackendFactory(BackendFactory factoryFn) {
backendFactory = std::move(factoryFn).asSharedProxy();
return *this;
}
/**
* Granularity of the wheel timer in the EventBase.
*/
std::chrono::milliseconds timerTickInterval{
HHWheelTimer::DEFAULT_TICK_INTERVAL};
Options& setTimerTickInterval(std::chrono::milliseconds interval) {
timerTickInterval = interval;
return *this;
}
};
/**
* Create a new EventBase object.
*
* Same as EventBase(true), which constructs an EventBase that measures time,
* except that this also allows the timer granularity to be specified
*/
explicit EventBase(std::chrono::milliseconds tickInterval);
/**
* Create a new EventBase object.
*
* Same as EventBase(true), which constructs an EventBase that measures time.
*/
EventBase() : EventBase(true) {}
/**
* Create a new EventBase object.
*
* @param enableTimeMeasurement Informs whether this event base should measure
* time. Disabling it would likely improve
* performance, but will disable some features
* that relies on time-measurement, including:
* observer, max latency and avg loop time.
*/
explicit EventBase(bool enableTimeMeasurement);
EventBase(const EventBase&) = delete;
EventBase& operator=(const EventBase&) = delete;
/**
* Create a new EventBase object that will use the specified libevent
* event_base object to drive the event loop.
*
* The EventBase will take ownership of this event_base, and will call
* event_base_free(evb) when the EventBase is destroyed.
*
* @param enableTimeMeasurement Informs whether this event base should measure
* time. Disabling it would likely improve
* performance, but will disable some features
* that relies on time-measurement, including:
* observer, max latency and avg loop time.
*/
explicit EventBase(event_base* evb, bool enableTimeMeasurement = true);
explicit EventBase(Options options);
~EventBase() override;
/**
* Runs the event loop.
*
* loop() will loop waiting for I/O or timeouts and invoking EventHandler
* and AsyncTimeout callbacks as their events become ready. loop() will
* only return when there are no more events remaining to process, or after
* terminateLoopSoon() has been called.
*
* loop() may be called again to restart event processing after a previous
* call to loop() or loopForever() has returned.
*
* Returns true if the loop completed normally (if it processed all
* outstanding requests, or if terminateLoopSoon() was called). If an error
* occurs waiting for events, false will be returned.
*/
bool loop();
/**
* Same as loop(), but doesn't wait for all keep-alive tokens to be released.
*/
[[deprecated("This should only be used in legacy unit tests")]] bool
loopIgnoreKeepAlive();
/**
* Wait for some events to become active, run them, then return.
*
* When EVLOOP_NONBLOCK is set in flags, the loop won't block if there
* are not any events to process.
*
* This is useful for callers that want to run the loop manually.
*
* Returns the same result as loop().
*/
bool loopOnce(int flags = 0);
/**
* Runs the event loop.
*
* loopForever() behaves like loop(), except that it keeps running even if
* when there are no more user-supplied EventHandlers or AsyncTimeouts
* registered. It will only return after terminateLoopSoon() has been
* called.
*
* This is useful for callers that want to wait for other threads to call
* runInEventBaseThread(), even when there are no other scheduled events.
*
* loopForever() may be called again to restart event processing after a
* previous call to loop() or loopForever() has returned.
*
* Throws a std::system_error if an error occurs.
*/
void loopForever();
/**
* Causes the event loop to exit soon.
*
* This will cause an existing call to loop() or loopForever() to stop event
* processing and return, even if there are still events remaining to be
* processed.
*
* It is safe to call terminateLoopSoon() from another thread to cause loop()
* to wake up and return in the EventBase loop thread. terminateLoopSoon()
* may also be called from the loop thread itself (for example, a
* EventHandler or AsyncTimeout callback may call terminateLoopSoon() to
* cause the loop to exit after the callback returns.) If the loop is not
* running, this will cause the next call to loop to terminate soon after
* starting. If a loop runs out of work (and so terminates on its own)
* concurrently with a call to terminateLoopSoon(), this may cause a race
* condition.
*
* Note that the caller is responsible for ensuring that cleanup of all event
* callbacks occurs properly. Since terminateLoopSoon() causes the loop to
* exit even when there are pending events present, there may be remaining
* callbacks present waiting to be invoked. If the loop is later restarted
* pending events will continue to be processed normally, however if the
* EventBase is destroyed after calling terminateLoopSoon() it is the
* caller's responsibility to ensure that cleanup happens properly even if
* some outstanding events are never processed.
*/
void terminateLoopSoon();
/**
* Adds the given callback to a queue of things run after the current pass
* through the event loop completes. Note that if this callback calls
* runInLoop() the new callback won't be called until the main event loop
* has gone through a cycle.
*
* This method may only be called from the EventBase's thread. This
* essentially allows an event handler to schedule an additional callback to
* be invoked after it returns.
*
* Use runInEventBaseThread() to schedule functions from another thread.
*
* The thisIteration parameter makes this callback run in this loop
* iteration, instead of the next one, even if called from a
* runInLoop callback (normal io callbacks that call runInLoop will
* always run in this iteration). This was originally added to
* support detachEventBase, as a user callback may have called
* terminateLoopSoon(), but we want to make sure we detach. Also,
* detachEventBase almost always must be called from the base event
* loop to ensure the stack is unwound, since most users of
* EventBase are not thread safe.
*
* Ideally we would not need thisIteration, and instead just use
* runInLoop with loop() (instead of terminateLoopSoon).
*/
void runInLoop(
LoopCallback* callback,
bool thisIteration = false,
std::shared_ptr<RequestContext> rctx = RequestContext::saveContext());
/**
* Convenience function to call runInLoop() with a folly::Function.
*
* This creates a LoopCallback object to wrap the folly::Function, and invoke
* the folly::Function when the loop callback fires. This is slightly more
* expensive than defining your own LoopCallback, but more convenient in
* areas that aren't too performance sensitive.
*
* This method may only be called from the EventBase's thread. This
* essentially allows an event handler to schedule an additional callback to
* be invoked after it returns.
*
* Use runInEventBaseThread() to schedule functions from another thread.
*/
void runInLoop(Func c, bool thisIteration = false);
/**
* Adds the given callback to a queue of things run before destruction
* of current EventBase.
*
* This allows users of EventBase that run in it, but don't control it, to be
* notified before EventBase gets destructed.
*
* Note: will be called from the thread that invoked EventBase destructor,
* before the final run of loop callbacks.
*/
void runOnDestruction(OnDestructionCallback& callback);
/**
* Convenience function that allows users to pass in a Function<void()> to be
* run on EventBase destruction.
*/
void runOnDestruction(Func f);
/**
* Adds a callback that will run immediately *before* the event loop.
* This is very similar to runInLoop(), but will not cause the loop to break:
* For example, this callback could be used to get loop times.
*/
void runBeforeLoop(LoopCallback* callback);
/**
* Run the specified function in the EventBase's thread.
*
* This method is thread-safe, and may be called from another thread.
*
* If runInEventBaseThread() is called when the EventBase loop is not
* running, the function call will be delayed until the next time the loop is
* started.
*
* If the loop is terminated (and never later restarted) before it has a
* chance to run the requested function, the function will be run upon the
* EventBase's destruction.
*
* If two calls to runInEventBaseThread() are made from the same thread, the
* functions will always be run in the order that they were scheduled.
* Ordering between functions scheduled from separate threads is not
* guaranteed.
*
* @param fn The function to run. The function must not throw any
* exceptions.
* @param arg An argument to pass to the function.
*/
template <typename T>
void runInEventBaseThread(void (*fn)(T*), T* arg) noexcept;
/**
* Run the specified function in the EventBase's thread
*
* This version of runInEventBaseThread() takes a folly::Function object.
* Note that this may be less efficient than the version that takes a plain
* function pointer and void* argument, if moving the function is expensive
* (e.g., if it wraps a lambda which captures some values with expensive move
* constructors).
*
* If the loop is terminated (and never later restarted) before it has a
* chance to run the requested function, the function will be run upon the
* EventBase's destruction.
*
* The function must not throw any exceptions.
*/
void runInEventBaseThread(Func fn) noexcept;
/**
* Run the specified function in the EventBase's thread.
*
* This method is thread-safe, and may be called from another thread.
*
* If runInEventBaseThreadAlwaysEnqueue() is called when the EventBase loop is
* not running, the function call will be delayed until the next time the loop
* is started.
*
* If the loop is terminated (and never later restarted) before it has a
* chance to run the requested function, the function will be run upon the
* EventBase's destruction.
*
* If two calls to runInEventBaseThreadAlwaysEnqueue() are made from the same
* thread, the functions will always be run in the order that they were
* scheduled. Ordering between functions scheduled from separate threads is
* not guaranteed. If a call is made from the EventBase thread, the function
* will not be executed inline and will be queued to the same queue as if the
* call would have been made from a different thread
*
* @param fn The function to run. The function must not throw any
* exceptions.
* @param arg An argument to pass to the function.
*/
template <typename T>
void runInEventBaseThreadAlwaysEnqueue(void (*fn)(T*), T* arg) noexcept;
/**
* Run the specified function in the EventBase's thread
*
* This version of runInEventBaseThreadAlwaysEnqueue() takes a folly::Function
* object. Note that this may be less efficient than the version that takes a
* plain function pointer and void* argument, if moving the function is
* expensive (e.g., if it wraps a lambda which captures some values with
* expensive move constructors).
*
* If the loop is terminated (and never later restarted) before it has a
* chance to run the requested function, the function will be run upon the
* EventBase's destruction.
*
* The function must not throw any exceptions.
*/
void runInEventBaseThreadAlwaysEnqueue(Func fn) noexcept;
/*
* Like runInEventBaseThread, but the caller waits for the callback to be
* executed.
*/
template <typename T>
void runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) noexcept;
/*
* Like runInEventBaseThread, but the caller waits for the callback to be
* executed.
*/
void runInEventBaseThreadAndWait(Func fn) noexcept;
/*
* Like runInEventBaseThreadAndWait, except if the caller is already in the
* event base thread, the functor is simply run inline.
*/
template <typename T>
void runImmediatelyOrRunInEventBaseThreadAndWait(
void (*fn)(T*), T* arg) noexcept;
/*
* Like runInEventBaseThreadAndWait, except if the caller is already in the
* event base thread, the functor is simply run inline.
*/
void runImmediatelyOrRunInEventBaseThreadAndWait(Func fn) noexcept;
/**
* Set the maximum desired latency in us and provide a callback which will be
* called when that latency is exceeded.
* OBS: This functionality depends on time-measurement.
*/
void setMaxLatency(std::chrono::microseconds maxLatency, Func maxLatencyCob) {
assert(enableTimeMeasurement_);
maxLatency_ = maxLatency;
maxLatencyCob_ = std::move(maxLatencyCob);
}
/**
* Set smoothing coefficient for loop load average; # of milliseconds
* for exp(-1) (1/2.71828...) decay.
*/
void setLoadAvgMsec(std::chrono::milliseconds ms);
/**
* reset the load average to a desired value
*/
void resetLoadAvg(double value = 0.0);
/**
* Get the average loop time in microseconds (an exponentially-smoothed ave)
*/
double getAvgLoopTime() const {
assert(enableTimeMeasurement_);
return avgLoopTime_.get();
}
/**
* Check if the event base loop is running.
*
* This may only be used as a sanity check mechanism; it cannot be used to
* make any decisions; for that, consider waitUntilRunning().
*/
bool isRunning() const {
return loopThread_.load(std::memory_order_relaxed) != std::thread::id();
}
/**
* wait until the event loop starts (after starting the event loop thread).
*/
void waitUntilRunning();
size_t getNotificationQueueSize() const;
void setMaxReadAtOnce(uint32_t maxAtOnce);
/**
* Verify that current thread is the EventBase thread, if the EventBase is
* running.
*/
bool isInEventBaseThread() const {
auto tid = loopThread_.load(std::memory_order_relaxed);
return tid == std::thread::id() || tid == std::this_thread::get_id();
}
bool inRunningEventBaseThread() const {
return loopThread_.load(std::memory_order_relaxed) ==
std::this_thread::get_id();
}
/**
* Equivalent to CHECK(isInEventBaseThread()) (and assert/DCHECK for
* dcheckIsInEventBaseThread), but it prints more information on
* failure.
*/
void checkIsInEventBaseThread() const;
void dcheckIsInEventBaseThread() const {
if (kIsDebug) {
checkIsInEventBaseThread();
}
}
HHWheelTimer& timer() {
if (!wheelTimer_) {
wheelTimer_ = HHWheelTimer::newTimer(this, intervalDuration_);
}
return *wheelTimer_.get();
}
EventBaseBackendBase* getBackend() { return evb_.get(); }
// --------- interface to underlying libevent base ------------
// Avoid using these functions if possible. These functions are not
// guaranteed to always be present if we ever provide alternative EventBase
// implementations that do not use libevent internally.
event_base* getLibeventBase() const;
static const char* getLibeventVersion();
static const char* getLibeventMethod();
/**
* only EventHandler/AsyncTimeout subclasses and ourselves should
* ever call this.
*
* This is used to mark the beginning of a new loop cycle by the
* first handler fired within that cycle.
*
*/
void bumpHandlingTime() final;
class SmoothLoopTime {
public:
explicit SmoothLoopTime(std::chrono::microseconds timeInterval)
: expCoeff_(-1.0 / timeInterval.count()), value_(0.0) {
VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
}
void setTimeInterval(std::chrono::microseconds timeInterval);
void reset(double value = 0.0);
void addSample(
std::chrono::microseconds total, std::chrono::microseconds busy);
double get() const {
// Add the outstanding buffered times linearly, to avoid
// expensive exponentiation
auto lcoeff = buffer_time_.count() * -expCoeff_;
return value_ * (1.0 - lcoeff) + lcoeff * busy_buffer_.count();
}
void dampen(double factor) { value_ *= factor; }
private:
double expCoeff_;
double value_;
std::chrono::microseconds buffer_time_{0};
std::chrono::microseconds busy_buffer_{0};
std::size_t buffer_cnt_{0};
static constexpr std::chrono::milliseconds buffer_interval_{10};
};
void setObserver(const std::shared_ptr<EventBaseObserver>& observer) {
assert(enableTimeMeasurement_);
observer_ = observer;
}
const std::shared_ptr<EventBaseObserver>& getObserver() { return observer_; }
/**
* Setup execution observation/instrumentation for every EventHandler
* executed in this EventBase.
*
* @param observer EventHandle's execution observer.
*/
void setExecutionObserver(ExecutionObserver* observer) {
executionObserver_ = observer;
}
/**
* Gets the execution observer associated with this EventBase.
*/
ExecutionObserver* getExecutionObserver() { return executionObserver_; }
/**
* Set the name of the thread that runs this event base.
*/
void setName(const std::string& name);
/**
* Returns the name of the thread that runs this event base.
*/
const std::string& getName();
/// Implements the Executor interface
void add(Cob fn) override { runInEventBaseThread(std::move(fn)); }
/// Implements the DrivableExecutor interface
void drive() override {
++loopKeepAliveCount_;
SCOPE_EXIT { --loopKeepAliveCount_; };
loopOnce();
}
// Implements the ScheduledExecutor interface
void scheduleAt(Func&& fn, TimePoint const& timeout) override;
// TimeoutManager
void attachTimeoutManager(
AsyncTimeout* obj, TimeoutManager::InternalEnum internal) final;
void detachTimeoutManager(AsyncTimeout* obj) final;
bool scheduleTimeout(
AsyncTimeout* obj, TimeoutManager::timeout_type timeout) final;
void cancelTimeout(AsyncTimeout* obj) final;
bool isInTimeoutManagerThread() final { return isInEventBaseThread(); }
// Returns a VirtualEventBase attached to this EventBase. Can be used to
// pass to APIs which expect VirtualEventBase. This VirtualEventBase will be
// destroyed together with the EventBase.
//
// Any number of VirtualEventBases instances may be independently constructed,
// which are backed by this EventBase. This method should be only used if you
// don't need to manage the life time of the VirtualEventBase used.
folly::VirtualEventBase& getVirtualEventBase();
/// Implements the IOExecutor interface
EventBase* getEventBase() override;
static std::unique_ptr<EventBaseBackendBase> getDefaultBackend();
protected:
bool keepAliveAcquire() noexcept override {
if (inRunningEventBaseThread()) {
loopKeepAliveCount_++;
} else {
loopKeepAliveCountAtomic_.fetch_add(1, std::memory_order_relaxed);
}
return true;
}
void keepAliveRelease() noexcept override {
if (!inRunningEventBaseThread()) {
return add([this] { loopKeepAliveCount_--; });
}
loopKeepAliveCount_--;
}
private:
class FuncRunner;
folly::VirtualEventBase* tryGetVirtualEventBase();
void applyLoopKeepAlive();
ssize_t loopKeepAliveCount();
/*
* Helper function that tells us whether we have already handled
* some event/timeout/callback in this loop iteration.
*/
bool nothingHandledYet() const noexcept;
typedef LoopCallback::List LoopCallbackList;
bool loopBody(int flags = 0, bool ignoreKeepAlive = false);
void runLoopCallbacks(LoopCallbackList& currentCallbacks);
// executes any callbacks queued by runInLoop(); returns false if none found
bool runLoopCallbacks();
void initNotificationQueue();
// Tick granularity to wheelTimer_
std::chrono::milliseconds intervalDuration_{
HHWheelTimer::DEFAULT_TICK_INTERVAL};
// should only be accessed through public getter
HHWheelTimer::UniquePtr wheelTimer_;
LoopCallbackList loopCallbacks_;
LoopCallbackList runBeforeLoopCallbacks_;
Synchronized<OnDestructionCallback::List> onDestructionCallbacks_;
// This will be null most of the time, but point to currentCallbacks
// if we are in the middle of running loop callbacks, such that
// runInLoop(..., true) will always run in the current loop
// iteration.
LoopCallbackList* runOnceCallbacks_;
// stop_ is set by terminateLoopSoon() and is used by the main loop
// to determine if it should exit
std::atomic<bool> stop_;
// The ID of the thread running the main loop.
// std::thread::id{} if loop is not running.
std::atomic<std::thread::id> loopThread_;
// A notification queue for runInEventBaseThread() to use
// to send function requests to the EventBase thread.
std::unique_ptr<EventBaseAtomicNotificationQueue<Func, FuncRunner>> queue_;
ssize_t loopKeepAliveCount_{0};
std::atomic<ssize_t> loopKeepAliveCountAtomic_{0};
bool loopKeepAliveActive_{false};
// limit for latency in microseconds (0 disables)
std::chrono::microseconds maxLatency_;
// exponentially-smoothed average loop time for latency-limiting
SmoothLoopTime avgLoopTime_;
// smoothed loop time used to invoke latency callbacks; differs from
// avgLoopTime_ in that it's scaled down after triggering a callback
// to reduce spamminess
SmoothLoopTime maxLatencyLoopTime_;
// callback called when latency limit is exceeded
Func maxLatencyCob_;
// Enables/disables time measurements in loopBody(). if disabled, the
// following functionality that relies on time-measurement, will not
// be supported: avg loop time, observer and max latency.
const bool enableTimeMeasurement_;
// Wrap-around loop counter to detect beginning of each loop
std::size_t nextLoopCnt_;
std::size_t latestLoopCnt_;
std::chrono::steady_clock::time_point startWork_;
// Prevent undefined behavior from invoking event_base_loop() reentrantly.
// This is needed since many projects use libevent-1.4, which lacks commit
// b557b175c00dc462c1fce25f6e7dd67121d2c001 from
// https://github.com/libevent/libevent/.
bool invokingLoop_{false};
// Observer to export counters
std::shared_ptr<EventBaseObserver> observer_;
uint32_t observerSampleCount_;
// EventHandler's execution observer.
ExecutionObserver* executionObserver_;
// Name of the thread running this EventBase
std::string name_;
// see EventBaseLocal
friend class detail::EventBaseLocalBase;
template <typename T>
friend class EventBaseLocal;
std::unordered_map<std::size_t, erased_unique_ptr> localStorage_;
std::unordered_set<detail::EventBaseLocalBaseBase*> localStorageToDtor_;
folly::once_flag virtualEventBaseInitFlag_;
std::unique_ptr<VirtualEventBase> virtualEventBase_;
// pointer to underlying backend class doing the heavy lifting
std::unique_ptr<EventBaseBackendBase> evb_;
};
template <typename T>
void EventBase::runInEventBaseThread(void (*fn)(T*), T* arg) noexcept {
return runInEventBaseThread([=] { fn(arg); });
}
template <typename T>
void EventBase::runInEventBaseThreadAlwaysEnqueue(
void (*fn)(T*), T* arg) noexcept {
return runInEventBaseThreadAlwaysEnqueue([=] { fn(arg); });
}
template <typename T>
void EventBase::runInEventBaseThreadAndWait(void (*fn)(T*), T* arg) noexcept {
return runInEventBaseThreadAndWait([=] { fn(arg); });
}
template <typename T>
void EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(
void (*fn)(T*), T* arg) noexcept {
return runImmediatelyOrRunInEventBaseThreadAndWait([=] { fn(arg); });
}
} // namespace folly
|
rneiss/PocketTorah
|
ios/Pods/Flipper-Folly/folly/io/async/EventBase.h
|
C
|
gpl-3.0
| 34,068
|
#!/usr/bin/env python
import random
from copy import copy
from cnfgen.formula.cnf import CNF
def Shuffle(F,
polarity_flips='shuffle',
variables_permutation='shuffle',
clauses_permutation='shuffle'):
"""Reshuffle the given formula F
Returns a formula logically equivalent to `F` with the
following transformations applied the following order:
1. Polarity flips, specified as one of the following
- string 'fixed': no flips is applied
- string 'shuffle': each variable is subjected
to a random flip of polarity
- a list of `-1` and `+1` of length equal to
the number of the variables in the formula `F`.
2. Variable shuffling, specified as one of the following
- string 'fixed': no shuffling
- string 'shuffle': the variable order is randomly permuted
- an sequence of integer which represents a permutation of [1,...,N],
where N is the number of the variable in the formula. The i-th variable
is mapped to the i-th index in the sequence.
3. Clauses shuffling, specified as one of the following
- string 'fixed': no shuffling
- string 'shuffle': the clauses are randomly permuted
- an sequence S of integer which represents a permutation of [0,...,M-1],
where M is the number of the variable in the formula. The i-th clause in F
is going to be at position S[i] in the new formula.
Parameters
----------
F : cnfgen.formula.cnf.CNF
formula to be shuffled
polarity_flips: string or iterable(int)
Specifies the flips of polarity
variables_permutation: string or iterable(int)
Specifies the permutation of the variables.
clauses_permutation: string or iterable(int)
Specifies the permutation of the clauses.
"""
# empty cnf
out = CNF()
out.header = copy(F.header)
if 'description' in out.header:
out.header['description'] += " (reshuffled)"
i = 1
while 'transformation {}'.format(i) in out.header:
i += 1
out.header['transformation {}'.format(i)] = "Formula reshuffling"
N = F.number_of_variables()
M = F.number_of_clauses()
out.update_variable_number(N)
# Manage the parameters
perr = 'polarity_flips is either \'fixed\', \'shuffle\' or in {-1,+1]}^n'
verr = 'variables_permutation is either \'fixed\', \'shuffle\' or a permutation of [1,...,N]'
cerr = 'clauses_permutation is either \'fixed\', \'shuffle\' or a permutation of [0,...,M-1]'
# polarity flips
if polarity_flips == 'fixed':
polarity_flips = [1] * N
elif polarity_flips == 'shuffle':
polarity_flips = [random.choice([-1, 1]) for x in range(N)]
else:
if len(polarity_flips) != N:
raise ValueError(perr)
for i in range(N):
if abs(polarity_flips[i]) != 1:
raise ValueError(perr)
# variables permutation
if variables_permutation == 'fixed':
variables_permutation = range(1, N+1)
elif variables_permutation == 'shuffle':
variables_permutation = list(range(1, N+1))
random.shuffle(variables_permutation)
else:
if len(variables_permutation) != N:
raise ValueError(verr)
tmp = sorted(variables_permutation)
for i in range(N):
if i+1 != tmp[i]:
raise ValueError(verr)
#
# permutation of clauses
#
if clauses_permutation == 'fixed':
clauses_mapping = ((i, i) for i in range(M))
elif clauses_permutation == 'shuffle':
tmp = list(range(M))
random.shuffle(tmp)
clauses_mapping = sorted(enumerate(tmp), key=lambda x: x[1])
else:
if len(clauses_permutation) != M:
raise ValueError(cerr)
tmp = sorted(clauses_permutation)
for i in range(M):
if i != tmp[i]:
raise ValueError(cerr)
clauses_mapping = sorted(enumerate(clauses_permutation), key=lambda x: x[1])
# precompute literal mapping
substitution = [None] * (2 * N + 1)
for i in range(1, N+1):
substitution[i] = polarity_flips[i-1] * variables_permutation[i-1]
substitution[-i] = -substitution[i]
# load clauses
for (old, new) in clauses_mapping:
assert new == out.number_of_clauses()
out.add_clause(substitution[lit] for lit in F[old])
return out
|
MassimoLauria/cnfgen
|
cnfgen/transformations/shuffle.py
|
Python
|
gpl-3.0
| 4,446
|
/* gbp-meson-toolchain-edition-preferences.c
*
* Copyright 2018 Corentin Noël <corentin.noel@collabora.com>
* Copyright 2018 Collabora Ltd.
*
* 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, eitIher 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/>.
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#define G_LOG_DOMAIN "gbp-meson-toolchain-edition-preferences-addin"
#include <glib/gi18n.h>
#include <libide-gui.h>
#include "gbp-meson-toolchain-edition-preferences-addin.h"
#include "gbp-meson-toolchain-edition-preferences-row.h"
struct _GbpMesonToolchainEditionPreferencesAddin
{
GObject parent_instance;
GArray *ids;
DzlPreferences *preferences;
GCancellable *cancellable;
};
static void
meson_toolchain_edition_preferences_add_new (GbpMesonToolchainEditionPreferencesAddin *self,
GtkWidget *emitter)
{
g_autofree gchar *user_folder_path = NULL;
g_autofree gchar *new_target = NULL;
g_autoptr(GError) error = NULL;
g_autoptr(GFile) file = NULL;
g_autoptr(GFileOutputStream) output_stream = NULL;
GbpMesonToolchainEditionPreferencesRow *pref_row;
guint id = 0;
g_assert (GBP_IS_MESON_TOOLCHAIN_EDITION_PREFERENCES_ADDIN (self));
g_assert (DZL_IS_PREFERENCES_BIN (emitter));
user_folder_path = g_build_filename (g_get_user_data_dir (), "meson", "cross", NULL);
if (g_mkdir_with_parents (user_folder_path, 0700) != 0)
{
g_critical ("Can't create %s", user_folder_path);
return;
}
for (uint i = 0; i < UINT_MAX; i++)
{
g_autofree gchar *possible_target = g_strdup_printf ("new_file%u", i);
g_autofree gchar *possible_path = g_build_filename (user_folder_path, possible_target, NULL);
if (!g_file_test (possible_path, G_FILE_TEST_EXISTS)) {
new_target = g_steal_pointer (&possible_path);
break;
}
}
pref_row = g_object_new (GBP_TYPE_MESON_TOOLCHAIN_EDITION_PREFERENCES_ROW,
"toolchain-path", new_target,
"visible", TRUE,
NULL);
file = g_file_new_for_path (new_target);
if ((output_stream = g_file_create (file, G_FILE_CREATE_NONE, NULL, &error)))
g_output_stream_close (G_OUTPUT_STREAM (output_stream), NULL, NULL);
id = dzl_preferences_add_custom (self->preferences, "sdk", "toolchain", GTK_WIDGET (pref_row), "", 1);
g_array_append_val (self->ids, id);
gbp_meson_toolchain_edition_preferences_row_show_popup (pref_row);
}
static GtkWidget *
toolchain_edition_preferences_get_add_widget (GbpMesonToolchainEditionPreferencesAddin *self)
{
GtkWidget *bin = NULL;
GtkWidget *grid = NULL;
GtkWidget *label = NULL;
GtkWidget *subtitle = NULL;
GtkWidget *image = NULL;
bin = g_object_new (DZL_TYPE_PREFERENCES_BIN,
"visible", TRUE,
NULL);
grid = g_object_new (GTK_TYPE_GRID,
"visible", TRUE,
NULL);
label = g_object_new (GTK_TYPE_LABEL,
"visible", TRUE,
"label", _("Add toolchain"),
"xalign", 0.0f,
"hexpand", TRUE,
NULL);
subtitle = g_object_new (GTK_TYPE_LABEL,
"visible", TRUE,
"label", g_markup_printf_escaped ("<small>%s</small>", _("Define a new custom toolchain targeting a specific platform")),
"use-markup", TRUE,
"xalign", 0.0f,
"hexpand", TRUE,
"wrap", TRUE,
NULL);
gtk_style_context_add_class (gtk_widget_get_style_context (subtitle), GTK_STYLE_CLASS_DIM_LABEL);
image = g_object_new (GTK_TYPE_IMAGE,
"visible", TRUE,
"icon-name", "list-add-symbolic",
"valign", GTK_ALIGN_CENTER,
NULL);
gtk_grid_attach (GTK_GRID (grid), label, 0, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), subtitle, 0, 1, 1, 1);
gtk_grid_attach (GTK_GRID (grid), image, 1, 0, 1, 2);
gtk_container_add (GTK_CONTAINER (bin), grid);
g_signal_connect_object (bin,
"preference-activated",
G_CALLBACK (meson_toolchain_edition_preferences_add_new),
self,
G_CONNECT_SWAPPED);
return bin;
}
static void
gbp_meson_toolchain_edition_preferences_addin_load_finish (GObject *object,
GAsyncResult *result,
gpointer user_data)
{
GFile *folder = (GFile *)object;
g_autoptr(GError) error = NULL;
g_autoptr(GPtrArray) ret = NULL;
GbpMesonToolchainEditionPreferencesAddin *self = (GbpMesonToolchainEditionPreferencesAddin *)user_data;
g_assert (G_IS_FILE (folder));
g_assert (G_IS_ASYNC_RESULT (result));
g_assert (GBP_IS_MESON_TOOLCHAIN_EDITION_PREFERENCES_ADDIN (self));
ret = ide_g_file_find_finish (folder, result, &error);
IDE_PTR_ARRAY_SET_FREE_FUNC (ret, g_object_unref);
if (ret == NULL)
return;
for (guint i = 0; i < ret->len; i++)
{
guint id = 0;
GFile *file = g_ptr_array_index (ret, i);
g_autoptr(GError) load_error = NULL;
g_autoptr(GbpMesonToolchainEditionPreferencesRow) pref_row = NULL;
g_autofree gchar *path = NULL;
pref_row = g_object_new (GBP_TYPE_MESON_TOOLCHAIN_EDITION_PREFERENCES_ROW,
"visible", TRUE,
NULL);
path = g_file_get_path (file);
if (!gbp_meson_toolchain_edition_preferences_row_load_file (g_object_ref_sink (pref_row), path, &load_error))
continue;
id = dzl_preferences_add_custom (self->preferences, "sdk", "toolchain", GTK_WIDGET (pref_row), NULL, i);
g_array_append_val (self->ids, id);
}
}
static void
gbp_meson_toolchain_edition_preferences_addin_load (IdePreferencesAddin *addin,
DzlPreferences *preferences)
{
GbpMesonToolchainEditionPreferencesAddin *self = (GbpMesonToolchainEditionPreferencesAddin *)addin;
GtkWidget *widget = NULL;
guint id = 0;
g_autofree gchar *user_folder_path = NULL;
g_autoptr(GFile) user_folder = NULL;
IDE_ENTRY;
g_assert (GBP_IS_MESON_TOOLCHAIN_EDITION_PREFERENCES_ADDIN (self));
g_assert (DZL_IS_PREFERENCES (preferences));
self->ids = g_array_new (FALSE, FALSE, sizeof (guint));
self->preferences = preferences;
self->cancellable = g_cancellable_new ();
dzl_preferences_add_list_group (preferences, "sdk", "toolchain", _("Toolchain"), GTK_SELECTION_NONE, 0);
widget = toolchain_edition_preferences_get_add_widget (self);
id = dzl_preferences_add_custom (preferences, "sdk", "toolchain", widget, "", 0);
g_array_append_val (self->ids, id);
user_folder_path = g_build_filename (g_get_user_data_dir (), "meson", "cross", NULL);
user_folder = g_file_new_for_path (user_folder_path);
ide_g_file_find_async (user_folder,
"*",
self->cancellable,
gbp_meson_toolchain_edition_preferences_addin_load_finish,
self);
IDE_EXIT;
}
static void
gbp_meson_toolchain_edition_preferences_addin_unload (IdePreferencesAddin *addin,
DzlPreferences *preferences)
{
GbpMesonToolchainEditionPreferencesAddin *self = (GbpMesonToolchainEditionPreferencesAddin *)addin;
IDE_ENTRY;
g_assert (GBP_IS_MESON_TOOLCHAIN_EDITION_PREFERENCES_ADDIN (self));
g_assert (DZL_IS_PREFERENCES (preferences));
/* Clear preferences so reload code doesn't try to
* make forward progress updating items.
*/
self->preferences = NULL;
for (guint i = 0; i < self->ids->len; i++)
{
guint id = g_array_index (self->ids, guint, i);
dzl_preferences_remove_id (preferences, id);
}
g_clear_pointer (&self->ids, g_array_unref);
g_clear_pointer (&self->cancellable, g_object_unref);
IDE_EXIT;
}
static void
preferences_addin_iface_init (IdePreferencesAddinInterface *iface)
{
iface->load = gbp_meson_toolchain_edition_preferences_addin_load;
iface->unload = gbp_meson_toolchain_edition_preferences_addin_unload;
}
G_DEFINE_TYPE_EXTENDED (GbpMesonToolchainEditionPreferencesAddin, gbp_meson_toolchain_edition_preferences_addin, G_TYPE_OBJECT, G_TYPE_FLAG_FINAL,
G_IMPLEMENT_INTERFACE (IDE_TYPE_PREFERENCES_ADDIN, preferences_addin_iface_init))
static void
gbp_meson_toolchain_edition_preferences_addin_class_init (GbpMesonToolchainEditionPreferencesAddinClass *klass)
{
}
static void
gbp_meson_toolchain_edition_preferences_addin_init (GbpMesonToolchainEditionPreferencesAddin *self)
{
}
|
GNOME/gnome-builder
|
src/plugins/meson/gbp-meson-toolchain-edition-preferences-addin.c
|
C
|
gpl-3.0
| 9,492
|
// Copyright 2017 voidALPHA, Inc.
// This file is part of the Haxxis video generation system and is provided
// by voidALPHA in support of the Cyber Grand Challenge.
// Haxxis 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.
// Haxxis 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
// Haxxis. If not, see <http://www.gnu.org/licenses/>.
using UnityEngine;
using Visualizers;
namespace Mutation.Mutators.TeamSpecific
{
public class TeamIdToCrsNameMutator : DataMutator
{
private MutableField<int> m_TeamId = new MutableField<int>()
{ AbsoluteKey = "TeamId" };
[Controllable(LabelText = "Team Id")]
public MutableField<int> TeamId { get { return m_TeamId; } }
private MutableTarget m_CrsName = new MutableTarget()
{ AbsoluteKey = "Crs Name" };
[Controllable(LabelText = "Crs Name Target")]
public MutableTarget CrsName { get { return m_CrsName; } }
public TeamIdToCrsNameMutator()
{
CrsName.SchemaParent = TeamId;
}
protected override MutableObject Mutate(MutableObject mutable)
{
foreach (var entry in TeamId.GetEntries(mutable))
{
CrsName.SetValue(
TeamSpecificDataHider.USE_REAL_TEAM_DATA ?
TeamIdToCrsNameCorrelation.TeamIdToName(
TeamId.GetValue(entry)) :
"CRS " + TeamId.GetValue(entry), entry);
}
return mutable;
}
}
}
|
voidALPHA/cgc_viz
|
Assets/Mutation/Mutators/TeamSpecific/TeamIdToCrsNameMutator.cs
|
C#
|
gpl-3.0
| 1,895
|
Bitrix 16.5 Business Demo = e8c762936c4bef2b27520b1d4cc577d9
|
gohdan/DFC
|
known_files/hashes/bitrix/modules/wiki/install/components/bitrix/wiki.history/templates/.default/lang/en/template.php
|
PHP
|
gpl-3.0
| 61
|
#!/usr/bin/python
#
# bravialib - Will Cooke - Whizzy Labs - @8none1
# http://www.whizzy.org
# Copyright Will Cooke 2016. Released under the GPL.
#
#
# My attempt to talk to the Sony Bravia web API.
#
# This is designed to be used by a long running process
# So there is a potentially slow start-up time but then it should be quick enough
# at the expense of some memory usage
#
# The TV will give you access based on the device_id and nickname once you are authorised I think.
# The TV will need to be already switched on for this to work.
#
#
# Thanks:
# https://github.com/aparraga/braviarc/
# https://docs.google.com/viewer?a=v&pid=sites&srcid=ZGlhbC1tdWx0aXNjcmVlbi5vcmd8ZGlhbHxneDoyNzlmNzY3YWJlMmY1MjZl
#
# Some useful resources:
# A tidied up packet capture I did from the iphone app: http://paste.ubuntu.com/23417464/plain/
#
#
# TODO:
# Move logging out of prints and in to logging
#
import requests
from requests.auth import HTTPBasicAuth
import json
from xml.dom import minidom
import socket
import struct
import time
class MockResponse(object):
def __init__(self, status_code):
self.status_code = status_code
class Bravia(object):
def __init__(self, hostname = None, ip_addr = None, mac_addr = None):
self.ip_addr = ip_addr
self.hostname = hostname
self.mac_addr = mac_addr # You don't *have* to specify the MAC address as once we are paired via IP we can find
# it from the TV but it will only be stored for this session. If the TV is off and you are running this script
# from cold - you will need the MAC to wake the TV up.
if self.ip_addr is None and self.hostname is not None:
self.ip_addr = self._lookup_ip_from_hostname(self.hostname)
self.device_id = "WebInterface:001"
self.nickname = "IoT Remote Controller Interface"
self.endpoint = 'http://'+self.ip_addr
self.cookies = None
self.x_auth_psk = None # If you're using PSK instead of cookies you need to set this.
self.DIAL_cookie = {}
self.packet_id = 1
self.device_friendly_name = ""
self._JSON_HEADER = {'content-type':'application/json', 'connection':'close'}
self._TIMEOUT = 10
self.remote_controller_code_lookup = {}
self.app_lookup = {}
self.input_map = {}
self.dvbt_channels = {}
self.paired = False
def _debug_request(self, r):
# Pass a Requests response in here to see what happened
print "\n\n\n"
print "------- What was sent out ---------"
print r.request.headers
print r.request.body
print "---------What came back -----------"
print r.status_code
print r.headers
print r.text
print "-----------------------------------"
print "\n\n\n"
def _lookup_ip_from_hostname(self, hostname):
ipaddr = socket.gethostbyname(hostname)
if ipaddr is not '127.0.0.1':
return ipaddr
else:
# IP lookup failed
return False
def _build_json_payload(self,method, params = [], version="1.0"):
return {"id":self.packet_id, "method":method, "params":params,
"version":version}
def is_available(self):
# Try to find out if the TV is actually on or not. Pinging the TV would require
# this script to run as root, so not doing that. This function return True or
# False depending on if the box is on or not.
payload = self._build_json_payload("getPowerStatus")
try:
# Using a shorter timeout here so we can return more quickly
r = self.do_POST(url="/sony/system", payload = payload, timeout=2)
data = r.json()
if data.has_key('result'):
if data['result'][0]['status'] == "standby":
# TV is in standby mode, and so not on.
return False
elif data['result'][0]['status'] == "active":
# TV really is on
return True
else:
# Assume it's not on.
print "Uncaught result"
return False
if data.has_key('error'):
if 404 in data['error']:
# TV is probably booting at this point - so not available yet
return False
elif 403 in data['error']:
# A 403 Forbidden is acceptable here, because it means the TV is responding to requests
return True
else:
print "Uncaught error"
return False
return True
except requests.exceptions.ConnectTimeout:
print "No response, TV is probably off"
return False
except requests.exceptions.ConnectionError:
print "TV is certainly off."
return False
except requests.exceptions.ReadTimeout:
print "TV is on but not accepting commands yet"
return False
except ValueError:
print "Didn't get back JSON as expected"
# This might lead to false negatives - need to check
return False
def do_GET(self, url=None, headers=None, auth=None, cookies=None, timeout=None):
if url is None: return False
if url[0:4] != "http": url=self.endpoint+url
if cookies is None and self.cookies is not None: cookies=self.cookies
if self.x_auth_psk is not None: headers['X-Auth-PSK']=self.x_auth_psk
if timeout is None: timeout = self._TIMEOUT
if headers is None:
r = requests.get(url, cookies=cookies, auth=auth, timeout=timeout)
else:
r = requests.get(url, headers=headers, cookies=cookies, auth=auth, timeout=timeout)
return r
def do_POST(self, url=None, payload=None, headers=None, auth=None, cookies=None, timeout=None):
if url is None: return False
if type(payload) is dict: payload = json.dumps(payload)
if headers is None: headers = self._JSON_HEADER # If you don't want any extra headers pass in ""
if cookies is None and self.cookies is not None: cookies=self.cookies
if self.x_auth_psk is not None: headers['X-Auth-PSK']=self.x_auth_psk
if timeout is None: timeout = self._TIMEOUT
if url[0:4] != "http": url = self.endpoint+url # if you want to pass just the path you can, otherwise pass a full url and it will be used
self.packet_id += 1 # From packet captures, this increments on each request, so its a good idea to use this method all the time
if auth is not None:
r = requests.post(url, data=payload, headers=headers, cookies=cookies, auth=self.auth, timeout=timeout)
else:
r = requests.post(url, data=payload, headers=headers, cookies=cookies, timeout=timeout)
print r
return r
def connect(self):
# TODO: What if the TV is off and we can't connect?
#
# From looking at packet captures what seems to happen is:
# 1. Try and connect to the accessControl interface with the "pinRegistration" part in the payload
# 2. If you get back a 200 *and* the return data looks OK then you have already authorised
# 3. If #2 is a 200 you get back an auth token. I think that this token will expire, so we might need to
# re-connect later on - given that this script will be running for a long time. Hopefully you won't
# need to get a new PIN number ever.
# 4. If #2 was a 401 then you need to authorise, and then you do that by sending the PIN on screen as
# a base64 encoded BasicAuth using a blank username (e.g. "<username>:<password" -> ":1234")
# If that works, you should get a cookie back.
# 5. Use the cookie in all subsequent requests. Note there is an issue with this. The cookie is for
# path "/sony/" *but* the Apps are run from a path "/DIAL/sony/" so I try and fix this by adding a
# second cookie with that path and the same auth data.
if self.x_auth_psk is None: # We have not specified a PSK therefore we have to use Cookies
payload = self._build_json_payload("actRegister",
[{"clientid":self.device_id,"nickname":self.nickname},
[{"value":"no","function":"WOL"},
{"value":"no","function":"pinRegistration"}]])
try:
r = self.do_POST(url='/sony/accessControl', payload=payload)
except requests.exceptions.ConnectTimeout:
print "No response, TV is probably off"
return None, False
except requests.exceptions.ConnectionError:
print "TV is certainly off."
return None, False
if r.status_code == 200:
# Rather handily, the TV returns a 200 if the TV is in stand-by but not really on :)
try:
if "error" in r.json(): #.keys():
if "not power-on" in r.json()['error']:
# TV isn't powered up
r = self.wakeonlan()
print "TV not on! Have sent wakeonlan, probably try again in a mo."
# TODO: make this less crap
return None,False
except:
raise
# If we get here then We are already paired so get the new token
self.paired = True
self.cookies = r.cookies
# Also add the /DIAL/ path cookie
# Looks like requests doesn't handle two cookies with the same name ('auth') in one jar
# so going to have a dict for the DIAL cookie and pass around as needed. :/
a = r.headers['Set-Cookie'].split(';') # copy the cookie data headers
for each in a:
if len(each) > 0:
b = each.split('=')
self.DIAL_cookie[b[0].strip()] = b[1]
elif r.status_code == 401:
print "We are not paired!"
return r,False
elif r.status_code == 404:
# Most likely the TV hasn't booted yet
print("TV probably hasn't booted yet")
return r,False
else: return None,False
else: # We are using a PSK
self.paired = True
self.cookies = None
self.DIAL_cookie = None
r = None
# Populate some data now automatically.
print "Getting DMR info..."
self.get_dmr()
print "Getting sysem info..."
self.get_system_info()
print "Populating remote control codes..."
self.populate_controller_lookup()
print "Enumerating TV inputs..."
self.get_input_map()
print "Populating apps list..."
self.populate_apps_lookup()
print "Populating channel list..."
self.get_channel_list()
print "Matching HD channels..."
self.create_HD_chan_lookups() # You might not want to do this if you don't use Freeview in the UK
print "Done initialising TV data."
return r,True
def start_pair(self):
# This should prompt the TV to display the pairing screen
payload = self._build_json_payload("actRegister",
[{"clientid":self.device_id,"nickname":self.nickname},
[{"value":"no","function":"WOL"}]])
r = self.do_POST(url='/sony/accessControl', payload=payload)
if r.status_code == 200:
print "Probably already paired"
return r,True
if r.status_code == 401:
return r,False
else:
return None,False
def complete_pair(self, pin):
# The user should have a PIN on the screen now, pass it in here to complete the pairing process
payload = self._build_json_payload("actRegister",
[{"clientid":self.device_id, "nickname":self.nickname},
[{"value":"no", "function":"WOL"}]])
self.auth = HTTPBasicAuth('',pin) # Going to keep this in the object, just in case we need it again later
r = self.do_POST(url='/sony/accessControl', payload=payload, auth=self.auth)
if r.status_code == 200:
print("have paired")
self.paired = True
# let's call connect again to get the cookies all set up properly
a,b = self.connect()
if b is True:
return r,True
else: return r,False
else:
return None,False
def get_system_info(self):
payload = self._build_json_payload("getSystemInformation")
r = self.do_POST(url="/sony/system", payload=payload)
if r.status_code == 200:
self.system_info = r.json()['result'][0]
if self.mac_addr == None: self.mac_addr = self.system_info['macAddr']
return self.system_info
else:
return False
def get_input_map(self):
payload = self._build_json_payload("getCurrentExternalInputsStatus")
r = self.do_POST(url="/sony/avContent", payload=payload)
if r.status_code == 200:
for each in r.json()['result'][0]:
self.input_map[each['title']] = {'label':each['label'], 'uri':each['uri']}
return True
else:
return False
def get_input_uri_from_label(self, label):
for each in self.input_map:
if self.input_map[each]['label'] == label:
return self.input_map[each]['uri']
print "Didnt match the input name."
return None
def set_external_input(self, uri):
payload = self._build_json_payload("setPlayContent", [{"uri":uri}])
r = self.do_POST(url="/sony/avContent", payload=payload)
if r.status_code == 200:
if "error" in r.json():
# Something didnt work. The JSON will tell you what.
return False
else:
return True
else:
return False
def get_dmr(self):
r = self.do_GET('http://'+self.ip_addr+':52323/dmr.xml')
self.dmr_data = minidom.parseString(r.text)
# XML. FFS. :(
self.device_friendly_name = self.dmr_data.getElementsByTagName('friendlyName')[0].childNodes[0].data
a = self.dmr_data.getElementsByTagNameNS('urn:schemas-sony-com:av','X_IRCCCode')
for each in a:
name = each.getAttribute("command")
value = each.firstChild.nodeValue
self.remote_controller_code_lookup[name.lower()] = value
# Not much more interesting stuff here really, but see: https://aydbe.com/assets/uploads/2014/11/json.txt
# and https://github.com/bunk3r/braviapy
# Maybe /sony/system/setLEDIndicatorStatus would be fun?
#"setLEDIndicatorStatus" -> {"mode":"string","status":"bool"}
# Maybe mode is a hex colour? and bool is on/off?
def populate_controller_lookup(self):
payload = self._build_json_payload("getRemoteControllerInfo")
r = self.do_POST(url='/sony/system', payload=payload)
if r.status_code == 200:
for each in r.json()['result'][1]:
self.remote_controller_code_lookup[each['name'].lower()] = each['value']
return True
else:
return False
def do_remote_control(self,action):
# Pass in the action name, such as:
# "PowerOff" "Mute" "Pause" "Play"
# You can probably guess what these would be, but if not:
# print <self>.remote_controller_code_lookup
action = action.lower()
if action in self.remote_controller_code_lookup: #.keys():
ircc_code = self.remote_controller_code_lookup[action]
else: return False
header = {'SOAPACTION': '"urn:schemas-sony-com:service:IRCC:1#X_SendIRCC"'}
url = "/sony/IRCC"
body = '<?xml version="1.0"?>' # Look at all this crap just to send a remote control code...
body += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
body += '<s:Body>'
body += '<u:X_SendIRCC xmlns:u="urn:schemas-sony-com:service:IRCC:1">'
body += '<IRCCCode>' + ircc_code + '</IRCCCode>'
body += '</u:X_SendIRCC>'
body += '</s:Body>'
body += '</s:Envelope>'
try:
r = self.do_POST(url=url, payload=body, headers=header)
except requests.exceptions.ConnectTimeout:
print("Connect timeout error")
r = MockResponse(200)
except requests.exceptions.ConnectionError:
print("Connect error")
r = MockResponse(200)
if r.status_code == 200:
return True
else:
return False
def populate_apps_lookup(self):
# Interesting note: If you don't do this (presumably just calling the
# URL is enough) then apps won't actually launch and you will get a 404
# error back from the TV. Once you've called this it starts working.
self.app_lookup={}
r = self.do_GET(url="/DIAL/sony/applist", cookies=self.DIAL_cookie)
if r.status_code == 200:
app_xml_data = minidom.parseString(r.text.encode('utf-8'))
for each in app_xml_data.getElementsByTagName('app'):
appid = each.getElementsByTagName('id')[0].firstChild.data
appname = each.getElementsByTagName('name')[0].firstChild.data
try: iconurl = each.getElementsByTagName('icon_url')[0].firstChild.data
except: iconurl = None
self.app_lookup[appname] = {'id':appid, 'iconurl':iconurl}
return True
else:
return False
def load_app(self, app_name):
# Pass in the name of the app, the most useful ones on my telly are:
# "Amazon Instant Video" , "Netflix", "BBC iPlayer", "Demand 5"
if self.app_lookup == {}: self.populate_apps_lookup() # This must happen before apps will launch
try:
app_id = self.app_lookup[app_name]['id']
except KeyError:
return False
print "Trying to load app:", app_id
headers = {'Connection':'close'}
r = self.do_POST(url="/DIAL/apps/"+app_id, headers=headers,
cookies=self.DIAL_cookie)
print r.status_code
print r.headers
print r
if r.status_code == 201:
return True
else:
return False
def get_app_status(self):
payload = self._build_json_payload("getApplicationStatusList")
r = self.do_POST(url="/sony/appControl", payload=payload)
return r.json()
def get_channel_list(self):
# This only supports dvbt for now...
# First, we find out how many channels there are
payload = self._build_json_payload("getContentCount",
[{"target":"all", "source":"tv:dvbt"}], version="1.1")
r = self.do_POST(url="/sony/avContent", payload=payload)
chan_count = int(r.json()['result'][0]['count'])
# It seems to only return the channels in lumps of 50, and some of those returned are blank?
chunk_size = 50
loops = int(chan_count / chunk_size) + (chan_count % chunk_size > 0) # Sneaky round up trick, the mod > 0 evaluates to int 1
chunk = 0
for x in range(loops):
payload = self._build_json_payload("getContentList",
[{"stIdx":chunk, "source":"tv:dvbt", "cnt":chunk_size,
"target":"all" }], version="1.2")
r = self.do_POST(url="/sony/avContent", payload=payload)
a = r.json()['result'][0]
for each in a:
if each['title'] == "": continue # We get back some blank entries, so just ignore them
if self.dvbt_channels.has_key(each['title']):
# Channel has already been added, we only want to keep the one with the lowest chan_num.
# The TV seems to return channel data for channels it can't actually receive (e.g. out of
# area local BBC channels). Trying to tune to these gives an error.
if int(each['dispNum']) > int(self.dvbt_channels[each['title']]['chan_num']):
# This is probably not a "real" channel we care about, so skip it.
continue
#self.dvbt_channels[each['title']] = {'chan_num':each['dispNum'], 'uri':each['uri']}
else:
self.dvbt_channels[each['title']] = {'chan_num':each['dispNum'], 'uri':each['uri']}
chunk += chunk_size
def create_HD_chan_lookups(self):
# This should probably be in the script that imports this library not in
# the library itself, but I wanted this feature, so I'm chucking it in
# here. This probably only works for Freeview in the UK.
# Use case to demonstrate why this is here: You want to use Alexa to
# switch the channel. Naturally, you want the HD channel if there is
# one but you don't want to have to say "BBC ONE HD" because that would
# be stupid. So you just say "BBC ONE" and the script does the work to
# find the HD version for you.
for each in self.dvbt_channels.iteritems():
hd_version = "%s HD" % each[0] # e.g. "BBC ONE" -> "BBC ONE HD"
if hd_version in self.dvbt_channels:
# Extend the schema by adding a "hd_uri" key
self.dvbt_channels[each[0]]['hd_uri'] = self.dvbt_channels[hd_version]['uri']
def get_channel_uri(self, title):
if self.dvbt_channels == {}: self.get_channel_list()
try:
return self.dvbt_channels[title]['uri']
except KeyError:
return False
def wakeonlan(self, mac=None):
# Thanks: Taken from https://github.com/aparraga/braviarc/blob/master/braviarc/braviarc.py
# Not using another library for this as it's pretty small...
if mac is None and self.mac_addr is not None:
mac = self.mac_addr
print "Waking MAC: " + mac
addr_byte = mac.split(':')
hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
int(addr_byte[1], 16),
int(addr_byte[2], 16),
int(addr_byte[3], 16),
int(addr_byte[4], 16),
int(addr_byte[5], 16))
msg = b'\xff' * 6 + hw_addr * 16
socket_instance = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
socket_instance.sendto(msg, ('<broadcast>', 9))
socket_instance.close()
return True
def poweron(self):
# Convenience function to switch the TV on and block until it's ready
# to accept commands.
if self.paired is False:
print "You can only call this function once paired with the TV"
return False
elif self.paired is True:
ready = False
if self.is_available() is True:
# If we're already on, return now.
return True
self.wakeonlan()
for x in range(10):
if self.is_available() is True:
print "TV now available"
return True
else:
print "Didn't get a response. Trying again in 10 seconds. (Attempt "+str(x+1)+" of 10)"
time.sleep(10)
if ready is False:
print "Couldnt connect in a timely manner. Giving up"
return False
else:
return True
def get_client_ip(self):
host_ip = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
return host_ip
|
8none1/bravialib
|
bravialib.py
|
Python
|
gpl-3.0
| 24,487
|
define(['./FloatText'], function(FloatText) {
var Hit = function(value) {
FloatText.call(this, value, {
font: 'bold 30px monospace',
fill: 0xff0000
});
};
extend(Hit, FloatText);
return Hit;
});
|
Jorisslagter/LD35
|
js/ui/Hit.js
|
JavaScript
|
gpl-3.0
| 253
|
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2018 Max Weller
## Copyright (C) 2019 DreamSourceLab <support@dreamsourcelab.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##
import re
import sigrokdecode as srd
ann_cmdbit, ann_databit, ann_cmd, ann_data, ann_warning = range(5)
class Decoder(srd.Decoder):
api_version = 3
id = 'sda2506'
name = 'SDA2506'
longname = 'Siemens SDA 2506-5'
desc = 'Serial nonvolatile 1-Kbit EEPROM.'
license = 'gplv2+'
inputs = ['logic']
outputs = []
tags = ['IC', 'Memory']
channels = (
{'id': 'clk', 'name': 'CLK', 'desc': 'Clock'},
{'id': 'd', 'name': 'DATA', 'desc': 'Data'},
{'id': 'ce', 'name': 'CE#', 'desc': 'Chip-enable'},
)
annotations = (
('cmdbit', 'Command bit'),
('databit', 'Data bit'),
('cmd', 'Command'),
('data', 'Data byte'),
('warnings', 'Human-readable warnings'),
)
annotation_rows = (
('bits', 'Bits', (ann_cmdbit, ann_databit)),
('commands', 'Commands', (ann_cmd,)),
('data', 'Data', (ann_data,)),
('warnings', 'Warnings', (ann_warning,)),
)
def __init__(self):
self.samplerate = None
self.reset()
def reset(self):
self.cmdbits = []
self.databits = []
def metadata(self, key, value):
if key == srd.SRD_CONF_SAMPLERATE:
self.samplerate = value
def start(self):
self.out_ann = self.register(srd.OUTPUT_ANN)
def putbit(self, ss, es, typ, value):
self.put(ss, es, self.out_ann, [typ, ['%s' % (value)]])
def putdata(self, ss, es):
value = 0
for i in range(8):
value = (value << 1) | self.databits[i]
self.put(ss, es, self.out_ann, [ann_data, ['%02X' % (value)]])
def decode_bits(self, offset, width):
out = 0
for i in range(width):
out = (out << 1) | self.cmdbits[offset + i][0]
return (out, self.cmdbits[offset + width - 1][1], self.cmdbits[offset][2])
def decode_field(self, name, offset, width):
val, ss, es = self.decode_bits(offset, width)
self.put(ss, es, self.out_ann, [ann_data, ['%s: %02X' % (name, val)]])
return val
def decode(self):
while True:
# Wait for CLK edge or CE edge.
(clk, d, ce) = self.wait([{0: 'e'}, {2: 'e'}])
if (self.matched & (0b1 << 0)) and ce == 1 and clk == 1:
# Rising clk edge and command mode.
bitstart = self.samplenum
self.wait({0: 'f'})
self.cmdbits = [(d, bitstart, self.samplenum)] + self.cmdbits
if len(self.cmdbits) > 24:
self.cmdbits = self.cmdbits[0:24]
self.putbit(bitstart, self.samplenum, ann_cmdbit, d)
elif (self.matched & (0b1 << 0)) and ce == 0 and clk == 0:
# Falling clk edge and data mode.
bitstart = self.samplenum
(clk, d, ce) = self.wait([{'skip': int(2.5 * (1e6 / self.samplerate))}, {0: 'r'}, {2: 'e'}]) # Wait 25 us for data ready.
if (self.matched & (0b1 << 2)) and not (self.matched & 0b011):
self.wait([{0: 'r'}, {2: 'e'}])
if len(self.databits) == 0:
self.datastart = bitstart
self.databits = [d] + self.databits
self.putbit(bitstart, self.samplenum, ann_databit, d)
if len(self.databits) == 8:
self.putdata(self.datastart, self.samplenum)
self.databits = []
elif (self.matched & (0b1 << 1)) and ce == 0:
# Chip enable edge.
try:
self.decode_field('addr', 1, 7)
self.decode_field('CB', 0, 1)
if self.cmdbits[0][0] == 0:
# Beginning read command.
self.decode_field('read', 1, 7)
self.put(self.cmdbits[7][1], self.samplenum,
self.out_ann, [ann_cmd, ['read' ]])
elif d == 0:
# Beginning write command.
self.decode_field('data', 8, 8)
addr, ss, es = self.decode_bits(1, 7)
data, ss, es = self.decode_bits(8, 8)
cmdstart = self.samplenum
self.wait({2: 'r'})
self.put(cmdstart, self.samplenum, self.out_ann,
[ann_cmd, ['Write to %02X: %02X' % (addr, data)]])
else:
# Beginning erase command.
val, ss, es = self.decode_bits(1, 7)
cmdstart = self.samplenum
self.wait({2: 'r'})
self.put(cmdstart, self.samplenum, self.out_ann,
[ann_cmd, ['Erase: %02X' % (val)]])
self.databits = []
except Exception as ex:
self.reset()
|
DreamSourceLab/DSView
|
libsigrokdecode4DSL/decoders/sda2506/pd.py
|
Python
|
gpl-3.0
| 5,750
|
getcontent("functions/get_basicinfo.php", "basicinfo");
autoupdate("functions/get_basicinfo.php", "basicinfo", 10);
getcontent("functions/get_players.php", "players");
autoupdate("functions/get_players.php", "players", 5);
|
NotoriousPyro/phpMCWeb
|
web/js/update.js
|
JavaScript
|
gpl-3.0
| 222
|
// ******************************************************************************
//
// Filename: guiwindow.h
// Project: Vogue
// Author: Steven Ball
//
// Purpose:
// A window container class, defines basic window functionality.
//
// Revision History:
// Initial Revision - 26/09/06
//
// Copyright (c) 2005-2006, Steven Ball
//
// ******************************************************************************
#pragma once
#include "container.h"
#include "titlebar.h"
// Forward declaration of GUIWindowList
class GUIWindow;
class OpenGLGUI;
typedef std::vector<GUIWindow*> GUIWindowList;
class GUIWindow : public Container, public MouseListener
{
public:
/* Public methods */
GUIWindow(Renderer* pRenderer, unsigned int GUIFont, const std::string &title);
GUIWindow(Renderer* pRenderer, unsigned int GUIFont, TitleBar* ptitleBar);
~GUIWindow();
void AddEventListeners();
void RemoveEventListeners();
virtual bool IsRootContainer() const;
void AddGUIWindow(GUIWindow *window);
void RemoveGUIWindow(GUIWindow *window);
void RemoveAllGUIWindows();
const GUIWindowList& GetGUIWindows() const;
TitleBar* GetTitleBar() const;
void SetTitleBarDimensions(int xOffset, int yOffset, int width, int height);
void SetTitleOffset(int xOffset, int yOffset);
void SetTitlebarBackgroundIcon(RenderRectangle *icon);
void SetBackgroundIcon(RenderRectangle *icon);
void AddComponent(Component* component);
void RemoveComponent(Component *component);
void SetDimensions(int x, int y, int width, int height);
void SetDimensions(const Dimensions& r);
void SetLocation(int x, int y);
void SetLocation(const Point& p);
void SetTitle(const std::string &title);
const std::string GetTitle() const;
void SetDebugRender(bool debug);
void SetOutlineRender(bool outline);
void Show();
void Hide();
bool GetMinimized() const;
void SetMinimized(bool minimized);
void SetMinimizedDefaultIcon(RenderRectangle *icon);
void SetMinimizedSelectedIcon(RenderRectangle *icon);
void SetMinimizedHoverIcon(RenderRectangle *icon);
void SetMinimizedDisabledIcon(RenderRectangle *icon);
void SetCloseDefaultIcon(RenderRectangle *icon);
void SetCloseSelectedIcon(RenderRectangle *icon);
void SetCloseHoverIcon(RenderRectangle *icon);
void SetCloseDisabledIcon(RenderRectangle *icon);
void AllowMoving(bool val);
void AllowClosing(bool val);
void AllowMinimizing(bool val);
void AllowScrolling(bool val);
void SnapToApplication(bool val);
void SetApplicationDimensions(int width, int height);
void SetApplicationBorder(int left, int right, int top, int bottom);
void SetRenderTitleBar(bool lbRender);
void SetRenderWindowBackground(bool lbRender);
void DepthSortGUIWindowChildren();
EComponentType GetComponentType() const;
void SetGUIParent(OpenGLGUI* pParent);
void SetFocusWindow();
void Update(float deltaTime);
// < Operator (Used for GUIWindow depth sorting)
bool operator<(const GUIWindow &w) const;
static bool DepthLessThan(const GUIWindow *lhs, const GUIWindow *rhs);
protected:
/* Protected methods */
void MousePressed(const MouseEvent& lEvent);
void DrawSelf();
void DrawChildrenFirst();
void DrawChildren();
private:
/* Private methods */
public:
/* Public members */
protected:
/* Protected members */
private:
/* Private members */
GUIWindowList m_vpGUIWindowList;
TitleBar* m_titleBar;
unsigned int m_GUIFont;
bool m_bMinimized;
// Bools to control functionality of window
bool m_bAllowMoving;
bool m_bAllowClosing;
bool m_bAllowMinimizing;
bool m_bAllowScrolling;
bool m_bSnapToWindow;
bool m_bRenderTitleBar;
bool m_bRenderWindowBackground;
bool mb_ownsTitleBar;
int m_applicationWidth;
int m_applicationHeight;
RenderRectangle *m_pBackgroundIcon;
bool m_outlineRender;
int m_applicationBorderLeft;
int m_applicationBorderRight;
int m_applicationBorderTop;
int m_applicationBorderBottom;
OpenGLGUI* m_pParentGUI;
// Friend classes
friend class TitleBar;
friend class GUIWindowMinimizeButton;
friend class GUIWindowCloseButton;
};
|
AlwaysGeeky/Vogue
|
source/gui/guiwindow.h
|
C
|
gpl-3.0
| 4,080
|
// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package tests
import (
"bytes"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
)
func checkLogs(tlog []Log, logs vm.Logs) error {
if len(tlog) != len(logs) {
return fmt.Errorf("log length mismatch. Expected %d, got %d", len(tlog), len(logs))
} else {
for i, log := range tlog {
if common.HexToAddress(log.AddressF) != logs[i].Address {
return fmt.Errorf("log address expected %v got %x", log.AddressF, logs[i].Address)
}
if !bytes.Equal(logs[i].Data, common.FromHex(log.DataF)) {
return fmt.Errorf("log data expected %v got %x", log.DataF, logs[i].Data)
}
if len(log.TopicsF) != len(logs[i].Topics) {
return fmt.Errorf("log topics length expected %d got %d", len(log.TopicsF), logs[i].Topics)
} else {
for j, topic := range log.TopicsF {
if common.HexToHash(topic) != logs[i].Topics[j] {
return fmt.Errorf("log topic[%d] expected %v got %x", j, topic, logs[i].Topics[j])
}
}
}
genBloom := common.LeftPadBytes(types.LogsBloom(vm.Logs{logs[i]}).Bytes(), 256)
if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
return fmt.Errorf("bloom mismatch")
}
}
}
return nil
}
type Account struct {
Balance string
Code string
Nonce string
Storage map[string]string
}
type Log struct {
AddressF string `json:"address"`
DataF string `json:"data"`
TopicsF []string `json:"topics"`
BloomF string `json:"bloom"`
}
func (self Log) Address() []byte { return common.Hex2Bytes(self.AddressF) }
func (self Log) Data() []byte { return common.Hex2Bytes(self.DataF) }
func (self Log) RlpData() interface{} { return nil }
func (self Log) Topics() [][]byte {
t := make([][]byte, len(self.TopicsF))
for i, topic := range self.TopicsF {
t[i] = common.Hex2Bytes(topic)
}
return t
}
func StateObjectFromAccount(db ethdb.Database, addr string, account Account) *state.StateObject {
obj := state.NewStateObject(common.HexToAddress(addr), db)
obj.SetBalance(common.Big(account.Balance))
if common.IsHex(account.Code) {
account.Code = account.Code[2:]
}
obj.SetCode(common.Hex2Bytes(account.Code))
obj.SetNonce(common.Big(account.Nonce).Uint64())
return obj
}
type VmEnv struct {
CurrentCoinbase string
CurrentDifficulty string
CurrentGasLimit string
CurrentNumber string
CurrentTimestamp interface{}
PreviousHash string
}
type VmTest struct {
Callcreates interface{}
//Env map[string]string
Env VmEnv
Exec map[string]string
Transaction map[string]string
Logs []Log
Gas string
Out string
Post map[string]Account
Pre map[string]Account
PostStateRoot string
}
type Env struct {
depth int
state *state.StateDB
skipTransfer bool
initial bool
Gas *big.Int
origin common.Address
parent common.Hash
coinbase common.Address
number *big.Int
time *big.Int
difficulty *big.Int
gasLimit *big.Int
logs []vm.StructLog
vmTest bool
}
func NewEnv(state *state.StateDB) *Env {
return &Env{
state: state,
}
}
func (self *Env) StructLogs() []vm.StructLog {
return self.logs
}
func (self *Env) AddStructLog(log vm.StructLog) {
self.logs = append(self.logs, log)
}
func NewEnvFromMap(state *state.StateDB, envValues map[string]string, exeValues map[string]string) *Env {
env := NewEnv(state)
env.origin = common.HexToAddress(exeValues["caller"])
env.parent = common.HexToHash(envValues["previousHash"])
env.coinbase = common.HexToAddress(envValues["currentCoinbase"])
env.number = common.Big(envValues["currentNumber"])
env.time = common.Big(envValues["currentTimestamp"])
env.difficulty = common.Big(envValues["currentDifficulty"])
env.gasLimit = common.Big(envValues["currentGasLimit"])
env.Gas = new(big.Int)
return env
}
func (self *Env) Origin() common.Address { return self.origin }
func (self *Env) BlockNumber() *big.Int { return self.number }
func (self *Env) Coinbase() common.Address { return self.coinbase }
func (self *Env) Time() *big.Int { return self.time }
func (self *Env) Difficulty() *big.Int { return self.difficulty }
func (self *Env) Db() vm.Database { return self.state }
func (self *Env) GasLimit() *big.Int { return self.gasLimit }
func (self *Env) VmType() vm.Type { return vm.StdVmTy }
func (self *Env) GetHash(n uint64) common.Hash {
return common.BytesToHash(crypto.Sha3([]byte(big.NewInt(int64(n)).String())))
}
func (self *Env) AddLog(log *vm.Log) {
self.state.AddLog(log)
}
func (self *Env) Depth() int { return self.depth }
func (self *Env) SetDepth(i int) { self.depth = i }
func (self *Env) CanTransfer(from common.Address, balance *big.Int) bool {
if self.skipTransfer {
if self.initial {
self.initial = false
return true
}
}
return self.state.GetBalance(from).Cmp(balance) >= 0
}
func (self *Env) MakeSnapshot() vm.Database {
return self.state.Copy()
}
func (self *Env) SetSnapshot(copy vm.Database) {
self.state.Set(copy.(*state.StateDB))
}
func (self *Env) Transfer(from, to vm.Account, amount *big.Int) {
if self.skipTransfer {
return
}
core.Transfer(from, to, amount)
}
func (self *Env) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
if self.vmTest && self.depth > 0 {
caller.ReturnGas(gas, price)
return nil, nil
}
ret, err := core.Call(self, caller, addr, data, gas, price, value)
self.Gas = gas
return ret, err
}
func (self *Env) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
if self.vmTest && self.depth > 0 {
caller.ReturnGas(gas, price)
return nil, nil
}
return core.CallCode(self, caller, addr, data, gas, price, value)
}
func (self *Env) DelegateCall(caller vm.ContractRef, addr common.Address, data []byte, gas, price *big.Int) ([]byte, error) {
if self.vmTest && self.depth > 0 {
caller.ReturnGas(gas, price)
return nil, nil
}
return core.DelegateCall(self, caller, addr, data, gas, price)
}
func (self *Env) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
if self.vmTest {
caller.ReturnGas(gas, price)
nonce := self.state.GetNonce(caller.Address())
obj := self.state.GetOrNewStateObject(crypto.CreateAddress(caller.Address(), nonce))
return nil, obj.Address(), nil
} else {
return core.Create(self, caller, data, gas, price, value)
}
}
type Message struct {
from common.Address
to *common.Address
value, gas, price *big.Int
data []byte
nonce uint64
}
func NewMessage(from common.Address, to *common.Address, data []byte, value, gas, price *big.Int, nonce uint64) Message {
return Message{from, to, value, gas, price, data, nonce}
}
func (self Message) Hash() []byte { return nil }
func (self Message) From() (common.Address, error) { return self.from, nil }
func (self Message) FromFrontier() (common.Address, error) { return self.from, nil }
func (self Message) To() *common.Address { return self.to }
func (self Message) GasPrice() *big.Int { return self.price }
func (self Message) Gas() *big.Int { return self.gas }
func (self Message) Value() *big.Int { return self.value }
func (self Message) Nonce() uint64 { return self.nonce }
func (self Message) Data() []byte { return self.data }
|
almindor/go-ethereum
|
tests/util.go
|
GO
|
gpl-3.0
| 8,627
|
#!/usr/bin/env python
from setuptools import setup
setup(name='edith',
version='0.1.0a1',
description='Edit-distance implementation with edit-path retrieval',
author='david weil (tenuki)',
author_email='tenuki@gmail.com',
url='https://github.com/tenuki/edith',
py_modules=['edith'],
license="GNU General Public License v3.0",
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2',
]
)
|
tenuki/edith
|
setup.py
|
Python
|
gpl-3.0
| 554
|
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/do';
import { SpinnerService } from './spinner.service';
@Injectable()
export class AjaxService {
private apiUrl = '/assets/api';
constructor(private http: Http, private spinner: SpinnerService) { }
public fetch (url): Observable<any> {
this.showSpinner();
return this.http.get(this.buildUrl(url))
.map(this.extractData)
.catch(this.handleError);
}
public post (url, data): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.showSpinner();
return this.http.post(this.buildUrl(url), data, options)
.map(this.extractData)
.catch(this.handleError);
}
public put (url, data): Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.showSpinner();
return this.http.put(this.buildUrl(url), data, options)
.map(this.extractData)
.catch(this.handleError);
}
public delete (url, data): Observable<any> {
this.showSpinner();
return this.http.delete(this.buildUrl(url))
.map(this.extractData)
.catch(this.handleError);
}
private buildUrl (url) {
return this.apiUrl + url;
}
private extractData = (res: Response) => {
let body = res.json();
this.showSpinner();
return body || { };
}
private handleError = (error: Response | any) => {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
this.hideSpinner();
return Observable.throw(errMsg, error);
}
private showSpinner () {
this.spinner.isLoading = true;
}
private hideSpinner () {
this.spinner.isLoading = false;
}
}
|
gowthamforever/angular2-base
|
src/app/shared/services/ajax.service.ts
|
TypeScript
|
gpl-3.0
| 2,412
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title>File Source for Tr.php</title>
<link rel="stylesheet" href="../media/stylesheet.css" />
</head>
<body>
<h1>Source for file Tr.php</h1>
<p>Documentation is available at <a href="../Elements/_Elements---Table---Tr.php.html">Tr.php</a></p>
<div class="src-code">
<div class="src-code"><ol><li><div class="src-line"><a name="a1"></a><span class="src-php"><?php</span></div></li>
<li><div class="src-line"><a name="a2"></a><span class="src-doc">/**</span></div></li>
<li><div class="src-line"><a name="a3"></a><span class="src-doc"> * The <tr> tag defines a row in an HTML table.</span></div></li>
<li><div class="src-line"><a name="a4"></a><span class="src-doc"> * </span></div></li>
<li><div class="src-line"><a name="a5"></a><span class="src-doc"> * A tr element contains one or more th or td elements.</span></div></li>
<li><div class="src-line"><a name="a6"></a><span class="src-doc"> * </span><span class="src-doc-inlinetag">{@link http://www.w3schools.com/tags/tag_tr.asp }</span></div></li>
<li><div class="src-line"><a name="a7"></a><span class="src-doc"> * </span></div></li>
<li><div class="src-line"><a name="a8"></a><span class="src-doc"> * PHP version 5</span></div></li>
<li><div class="src-line"><a name="a9"></a><span class="src-doc"> * </span></div></li>
<li><div class="src-line"><a name="a10"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@example</span><span class="src-doc"> simple.php How to use</span></div></li>
<li><div class="src-line"><a name="a11"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@filesource</span></div></li>
<li><div class="src-line"><a name="a12"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@category</span><span class="src-doc"> Element</span></div></li>
<li><div class="src-line"><a name="a13"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@package</span><span class="src-doc"> Elements</span></div></li>
<li><div class="src-line"><a name="a14"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@author</span><span class="src-doc"> Jens Peters <jens@history-archive.net></span></div></li>
<li><div class="src-line"><a name="a15"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@copyright</span><span class="src-doc"> 2011 Jens Peters</span></div></li>
<li><div class="src-line"><a name="a16"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@license</span><span class="src-doc"> http://www.gnu.org/licenses/lgpl.html GNU LGPL v3</span></div></li>
<li><div class="src-line"><a name="a17"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@version</span><span class="src-doc"> 1.1</span></div></li>
<li><div class="src-line"><a name="a18"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@link</span><span class="src-doc"> http://launchpad.net/htmlbuilder</span></div></li>
<li><div class="src-line"><a name="a19"></a><span class="src-doc"> */</span></div></li>
<li><div class="src-line"><a name="a20"></a>namespace <span class="src-id">HTMLBuilder</span>\<span class="src-id">Elements</span>\<span class="src-id"><a href="../Elements/General/Table.html">Table</a></span><span class="src-sym">;</span></div></li>
<li><div class="src-line"><a name="a21"></a>use <span class="src-id">HTMLBuilder</span>\<span class="src-id"><a href="../Main/Validator.html">Validator</a></span><span class="src-sym">;</span></div></li>
<li><div class="src-line"><a name="a22"></a>use <span class="src-id">HTMLBuilder</span>\<span class="src-id">Elements</span>\<span class="src-id"><a href="../Elements/Base/Root.html">Root</a></span><span class="src-sym">;</span></div></li>
<li><div class="src-line"><a name="a23"></a> </div></li>
<li><div class="src-line"><a name="a24"></a><span class="src-doc">/**</span></div></li>
<li><div class="src-line"><a name="a25"></a><span class="src-doc"> * The <tr> tag defines a row in an HTML table.</span></div></li>
<li><div class="src-line"><a name="a26"></a><span class="src-doc"> * </span></div></li>
<li><div class="src-line"><a name="a27"></a><span class="src-doc"> * A tr element contains one or more th or td elements.</span></div></li>
<li><div class="src-line"><a name="a28"></a><span class="src-doc"> * </span><span class="src-doc-inlinetag">{@link http://www.w3schools.com/tags/tag_tr.asp }</span></div></li>
<li><div class="src-line"><a name="a29"></a><span class="src-doc"> * </span></div></li>
<li><div class="src-line"><a name="a30"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@category</span><span class="src-doc"> Element</span></div></li>
<li><div class="src-line"><a name="a31"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@example</span><span class="src-doc"> simple.php see HOW TO USE</span></div></li>
<li><div class="src-line"><a name="a32"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@example</span><span class="src-doc"> debug.php see HOW TO DEBUG</span></div></li>
<li><div class="src-line"><a name="a33"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@package</span><span class="src-doc"> Elements</span></div></li>
<li><div class="src-line"><a name="a34"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@subpackage</span><span class="src-doc"> General</span></div></li>
<li><div class="src-line"><a name="a35"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@author</span><span class="src-doc"> Jens Peters <jens@history-archiv.net></span></div></li>
<li><div class="src-line"><a name="a36"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@license</span><span class="src-doc"> http://www.gnu.org/licenses/lgpl.html GNU LGPL v3</span></div></li>
<li><div class="src-line"><a name="a37"></a><span class="src-doc"> * </span><span class="src-doc-coretag">@link</span><span class="src-doc"> http://launchpad.net/htmlbuilder</span></div></li>
<li><div class="src-line"><a name="a38"></a><span class="src-doc"> */</span></div></li>
<li><div class="src-line"><a name="a39"></a><span class="src-key">class </span><a href="../Elements/General/Tr.html">Tr</a> <span class="src-key">extends </span><a href="../Elements/General/RootRow.html">RootRow</a> <span class="src-sym">{</span></div></li>
<li><div class="src-line"><a name="a40"></a> </div></li>
<li><div class="src-line"><a name="a41"></a> <span class="src-key">public </span><span class="src-key">function </span><a href="../Elements/General/Tr.html#methodinitElement">initElement</a><span class="src-sym">(</span><span class="src-sym">) </span><span class="src-sym">{</span></div></li>
<li><div class="src-line"><a name="a42"></a> </div></li>
<li><div class="src-line"><a name="a43"></a> <span class="src-var">$this</span><span class="src-sym">-></span><a href="../Elements/Base/Root.html#var$_allowedChildren">_allowedChildren</a> = <span class="src-key">array </span><span class="src-sym">(</span></div></li>
<li><div class="src-line"><a name="a44"></a> <span class="src-str">"th"</span><span class="src-sym">,</span></div></li>
<li><div class="src-line"><a name="a45"></a> <span class="src-str">"td"</span></div></li>
<li><div class="src-line"><a name="a46"></a> <span class="src-sym">)</span><span class="src-sym">;</span></div></li>
<li><div class="src-line"><a name="a47"></a> <span class="src-sym">}</span></div></li>
<li><div class="src-line"><a name="a48"></a><span class="src-sym">}</span></div></li>
</ol></div>
</div>
<p class="notes" id="credit">
Documentation generated on Sat, 22 Dec 2012 00:28:49 +0100 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.4</a>
</p>
</body>
</html>
|
lasso/textura
|
src/htmlbuilder/phpdoc/__filesource/fsource_Elements__ElementsTableTr.php.html
|
HTML
|
gpl-3.0
| 9,672
|
/*
Desura is the leading indie game distribution platform
Copyright (C) 2011 Mark Chandler (Desura Net Pty Ltd)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include "Common.h"
#include "BDManager.h"
#include "User.h"
namespace UserCore
{
BDManager::BDManager(UserCore::User* user)
{
m_pUser = user;
}
BDManager::~BDManager()
{
m_BannerLock.lock();
std::map<UserCore::Task::DownloadBannerTask*, UserCore::Misc::BannerNotifierI*>::iterator it;
for (it=m_mDownloadBannerTask.begin(); it != m_mDownloadBannerTask.end(); it++)
{
it->first->onDLCompleteEvent -= delegate(this, &BDManager::onBannerComplete);
}
m_BannerLock.unlock();
}
void BDManager::onBannerComplete(UserCore::Task::BannerCompleteInfo& bci)
{
m_BannerLock.lock();
std::map<UserCore::Task::DownloadBannerTask*, UserCore::Misc::BannerNotifierI*>::iterator it;
for (it=m_mDownloadBannerTask.begin(); it != m_mDownloadBannerTask.end(); it++)
{
if (it->first == bci.task)
{
if (bci.complete)
it->second->onBannerComplete(bci.info);
m_mDownloadBannerTask.erase(it);
break;
}
}
m_BannerLock.unlock();
}
void BDManager::downloadBanner(UserCore::Misc::BannerNotifierI* obj, MCFCore::Misc::DownloadProvider* provider)
{
m_BannerLock.lock();
UserCore::Task::DownloadBannerTask *task = new UserCore::Task::DownloadBannerTask(m_pUser, provider);
task->onDLCompleteEvent += delegate(this, &BDManager::onBannerComplete);
m_mDownloadBannerTask[task] = obj;
m_pUser->getThreadPool()->queueTask(task);
m_BannerLock.unlock();
}
void BDManager::cancelDownloadBannerHooks(UserCore::Misc::BannerNotifierI* obj)
{
m_BannerLock.lock();
std::map<UserCore::Task::DownloadBannerTask*, UserCore::Misc::BannerNotifierI*>::iterator it=m_mDownloadBannerTask.begin();
while (it != m_mDownloadBannerTask.end())
{
if (it->second == obj)
{
std::map<UserCore::Task::DownloadBannerTask*, UserCore::Misc::BannerNotifierI*>::iterator temp = it;
it++;
m_mDownloadBannerTask.erase(temp);
}
else
{
it++;
}
}
m_BannerLock.unlock();
}
}
|
desura/Desurium
|
src/shared/usercore/code/BDManager.cpp
|
C++
|
gpl-3.0
| 2,619
|
# AmbientSensorEval
Ambient Sensor evaluation project
|
AmbientSensorsEvaluation/Ambient-Sensors-Proximity-Evaluation
|
Android Code/AmbientSensorsEvalReader/README.md
|
Markdown
|
gpl-3.0
| 54
|
namespace Model.References
{
public class GoToReference : ProcedureReference
{
public GoToReference(string referencedProcedure) : base(referencedProcedure)
{
}
public override string ToString()
{
return string.Format("GO TO {0}", ReferencedProcedure);
}
}
}
|
JannikArndt/Canal
|
Model/References/GoToReference.cs
|
C#
|
gpl-3.0
| 334
|
#include "catch.hpp"
#include <string>
#include "flash_storage.h"
#include "dcd.h"
#include <string.h>
const int TestSectorSize = 16000;
const int TestSectorCount = 2;
const int TestBase = 4000;
using std::string;
using TestStore = RAMFlashStorage<TestBase, TestSectorCount, TestSectorSize>;
using TestDCD = DCD<TestStore, TestSectorSize, TestBase, TestBase+TestSectorSize>;
unsigned sum(TestStore& store, unsigned start, unsigned length)
{
const uint8_t* data = store.dataAt(start);
unsigned sum = 0;
for (unsigned i=0; i<length; i++)
{
sum += *data++;
}
return sum;
}
void assertMemoryEqual(const uint8_t* actual, const uint8_t* expected, size_t length)
{
int index = 0;
while (length --> 0)
{
CAPTURE(index);
REQUIRE(actual[index] == expected[index]);
index++;
}
}
SCENARIO("RAMRlashStore provides pointer to data", "[ramflash]")
{
TestStore store;
const uint8_t* data1 = store.dataAt(TestBase);
const uint8_t* data2 = store.dataAt(TestBase+100);
REQUIRE(data1 != nullptr);
REQUIRE(data2 != nullptr);
REQUIRE(long(data1+100) == long(data2));
}
SCENARIO("RAMFlashStore is initially random", "[ramflash]")
{
TestStore store;
int fingerprint = sum(store, TestBase, TestSectorSize*TestSectorCount);
REQUIRE(fingerprint != 0); // not all 0's
REQUIRE(fingerprint != (TestSectorSize*TestSectorCount)*0xFF);
}
SCENARIO("RAMFlashStore can be erased","[ramflash]")
{
TestStore store;
REQUIRE_FALSE(store.eraseSector(TestBase+100+TestSectorSize));
const uint8_t* data = store.dataAt(TestBase+TestSectorSize);
for (unsigned i=0; i<TestSectorSize; i++) {
CAPTURE(i);
CHECK(data[i] == 0xFF);
}
int fingerprint = sum(store, TestBase+TestSectorSize, TestSectorSize); // 2nd sector
REQUIRE(fingerprint != 0); // not all 0's
REQUIRE(fingerprint == (TestSectorSize)*0xFF);
}
SCENARIO("RAMFlashStore can store data", "[ramflash]")
{
TestStore store;
REQUIRE_FALSE(store.eraseSector(TestBase));
REQUIRE_FALSE(store.write(TestBase+3, (const uint8_t*)"batman", 7));
const char* expected = "\xFF\xFF\xFF" "batman" "\x00\xFF\xFF";
const char* actual = (const char*)store.dataAt(TestBase);
REQUIRE(string(actual,12) == string(expected,12));
}
SCENARIO("RAMFlashStore emulates NAND flash", "[ramflash]")
{
TestStore store;
REQUIRE_FALSE(store.eraseSector(TestBase));
REQUIRE_FALSE(store.write(TestBase+3, (const uint8_t*)"batman", 7));
REQUIRE_FALSE(store.write(TestBase+0, (const uint8_t*)"\xA8\xFF\x00", 3));
const char* actual = (const char*)store.dataAt(TestBase);
const char* expected = "\xA8\xFF\x00" "batman" "\x00\xFF\xFF";
REQUIRE(string(actual,12) == string(expected,12));
// no change to flash storage
REQUIRE_FALSE(store.write(TestBase, (const uint8_t*)"\xF7\x80\x00\xFF", 3));
expected = "\xA0\x80\0batman\x00\xFF\xFF";
REQUIRE(string(actual,12) == string(expected,12));
}
// DCD Tests
SCENARIO("DCD initialized returns 0xFF", "[dcd]")
{
TestDCD dcd;
const uint8_t* data = dcd.read(0);
for (unsigned i=0; i<dcd.Length; i++)
{
CAPTURE( i );
REQUIRE(data[i] == 0xFFu);
}
}
SCENARIO("DCD Length is SectorSize minus 8", "[dcd]")
{
TestDCD dcd;
REQUIRE(dcd.Length == TestSectorSize-8);
}
SCENARIO("DCD can save data", "[dcd]")
{
TestDCD dcd;
uint8_t expected[dcd.Length];
memset(expected, 0xFF, sizeof(expected));
memcpy(expected+23, "batman", 6);
REQUIRE_FALSE(dcd.write(23, "batman", 6));
const uint8_t* data = dcd.read(0);
assertMemoryEqual(data, expected, dcd.Length);
}
SCENARIO("DCD can write whole sector", "[dcd]")
{
TestDCD dcd;
uint8_t expected[dcd.Length];
for (int i=0; i<dcd.Length; i++)
expected[i] = rand();
dcd.write(0, expected, dcd.Length);
const uint8_t* data = dcd.read(0);
assertMemoryEqual(data, expected, dcd.Length);
}
SCENARIO("DCD can overwrite data", "[dcd]")
{
TestDCD dcd;
uint8_t expected[dcd.Length];
for (unsigned i=0; i<dcd.Length; i++)
expected[i] = 0xFF;
memmove(expected+23, "bbatman", 7);
// overwrite data swapping a b to an a and vice versa
REQUIRE_FALSE(dcd.write(23, "batman", 6));
REQUIRE_FALSE(dcd.write(24, "batman", 6));
const uint8_t* data = dcd.read(0);
assertMemoryEqual(data, expected, dcd.Length);
}
SCENARIO("DCD uses 2nd sector if both are valid", "[dcd]")
{
TestDCD dcd;
TestStore& store = dcd.store;
TestDCD::Header header;
header.make_valid();
// directly manipulate the flash to create desired state
store.eraseSector(TestBase);
store.eraseSector(TestBase+TestSectorSize);
store.write(TestBase, &header, sizeof(header));
store.write(TestBase+sizeof(header), "abcd", 4);
store.write(TestBase+TestSectorSize, &header, sizeof(header));
store.write(TestBase+TestSectorSize+sizeof(header), "1234", 4);
const uint8_t* result = dcd.read(0);
assertMemoryEqual(result, (const uint8_t*)"1234", 4);
}
SCENARIO("DCD write is atomic if partial failure", "[dcd]")
{
for (int write_count=1; write_count<5; write_count++)
{
TestDCD dcd;
REQUIRE_FALSE(dcd.write(23, "abcdef", 6));
REQUIRE_FALSE(dcd.write(23, "batman", 6));
assertMemoryEqual(dcd.read(23), (const uint8_t*)"batman", 6);
// mock a power failure after a certain number of writes
dcd.store.setWriteCount(write_count);
CAPTURE(write_count);
// write should fail
REQUIRE(dcd.write(23, "7890-!", 6));
// last write is unsuccessful
assertMemoryEqual(dcd.read(23), (const uint8_t*)"batman", 6);
}
}
|
ekarlso/firmware
|
user/tests/unit/dcd.cpp
|
C++
|
gpl-3.0
| 5,767
|
[(#SET{defaut_tri,#ARRAY{
statut,1,
multi nom,1,
site,1
}})
]<B_liste_aut>
#SET{afficher_lettres,#TRI|=={'multi nom'}|oui}
#SET{debut,#ENV{debutaut,#EVAL{_request("debutaut");}}}
#ANCRE_PAGINATION
[<h3><:info_resultat_recherche:> «(#ENV{recherche})»</h3>]
<div class="liste-objets visiteurs">
<table class='spip liste'>
[<caption><strong class="caption">(#ENV*{titre,#GRAND_TOTAL|singulier_ou_pluriel{info_1_visiteur,info_nb_visiteurs}})</strong></caption>]
<thead>
#SET{p,''}
<BOUCLE_lettre(AUTEURS){tout}{id_auteur?}{where?}{statut?}{recherche?}{par multi nom}{id_auteur==#GET{afficher_lettres}|?{'.*','A'}}>[
(#NOM**|extraire_multi|initiale|unique|oui)
[(#SET{p,#GET{p}|concat{
#SELF|parametre_url{debutaut,@#ID_AUTEUR}|ancre_url{paginationaut}|afficher_initiale{#NOM**|extraire_multi|initiale{},#COMPTEUR_BOUCLE,#GET{debut},#ENV{nb,10}}
}})]
]#SAUTER{#ENV{nb,10}|moins{#COMPTEUR_BOUCLE|=={1}|?{2,1}}}</BOUCLE_lettre>[
(#SET{p,
#GET{p}|concat{
#REM|afficher_initiale{#REM,#TOTAL_BOUCLE,#GET{debut},#ENV{nb,10}}
}
})]</B_lettre>
[<tr><td colspan="5"><p class='pagination'>(#GET{p})</p></td></tr>]
[<tr><td colspan="5"><p class='pagination'>(#PAGINATION{prive})</p></td></tr>]
<tr class='first_row'>
<th class='statut' scope='col'>[(#TRI{statut,#CHEMIN_IMAGE{auteur-0minirezo-16.png}|balise_img{<:lien_trier_statut|attribut_html:>},ajax})]</th>
<th class='messagerie' scope='col'></th>
<th class='nom' scope='col'>[(#TRI{multi nom,<:info_nom:>,ajax})]</th>
<th class='email' scope='col'>[(#TRI{email,<:email:>,ajax})]</th>
<th class='contributions' scope='col'><:info_contributions:></th>
</tr>
</thead>
<tbody>
<BOUCLE_liste_aut(AUTEURS){tout}{id_auteur?}{where?}{statut?}{recherche?}{tri #ENV{par,multi nom},#GET{defaut_tri}}{pagination #ENV{nb,10} aut}{!compteur_articles_filtres #ENV{filtre_statut_articles,poubelle}}>
<tr class="[(#COMPTEUR_BOUCLE|alterner{row_odd,row_even})][ (#EXPOSE|unique)][ (#NOM**|extraire_multi|initiale|=={#ENV{i}}|?{on}|unique)]">
<td class='statut'>[(#STATUT|puce_statut{auteur})]</td>
<td class="messagerie">[<a href="(#ID_AUTEUR|auteur_lien_messagerie{#EN_LIGNE,#STATUT,#IMESSAGE})">[(#CHEMIN{images/m_envoi.gif}|balise_img{<:info_envoyer_message_prive:>})]</a>]</td>
<td class='nom[ (#NOM|non)vide]'>[(#LOGO_AUTEUR|image_reduire{20,26})]<a href="[(#ID_AUTEUR|generer_url_entite{auteur})]"[ title="(#BIO*|couper{200}|attribut_html)"]>[(#RANG). ][(#NOM|sinon{<:texte_vide:>})]</a></td>
<td class='email'>[<a href='mailto:(#EMAIL)'>[(#EMAIL|couper{30})]</a>]</td>
<td class='contributions'>[(#COMPTEUR_ARTICLES|singulier_ou_pluriel{info_1_article,info_nb_articles})<br />][(#PIPELINE{'compter_contributions_auteur',#ARRAY{args,#ARRAY{id_auteur,#ID_AUTEUR},'data',#ARRAY{}}}|implode{'<br />'})]</td>
</tr>
</BOUCLE_liste_aut>
</tbody>
</table>
[<p class='pagination'>(#PAGINATION{prive})</p>]
</div>
</B_liste_aut>[
<div class="liste-objets auteurs caption-wrap"><strong class="caption">(#ENV*{sinon,''})</strong></div>
]<//B_liste_aut>
|
denisbz/SPIP
|
prive/objets/liste/visiteurs.html
|
HTML
|
gpl-3.0
| 3,062
|
package es.udc.tfg_es.clubtriatlon.web.pages.user.profile;
/* ClubTriatlon: a web app to management of administrative work of a triathlon club
Copyright (C) 2015 Alejandro Mikitinskis
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact here: alejandro.mikitinskis@udc.es */
import org.apache.shiro.SecurityUtils;
import es.udc.tfg_es.clubtriatlon.web.services.AuthenticationPolicy;
import es.udc.tfg_es.clubtriatlon.web.services.AuthenticationPolicyType;
@AuthenticationPolicy(AuthenticationPolicyType.AUTHENTICATED_USERS)
public class MyProfile {
public boolean isUser() {
return SecurityUtils.getSubject().hasRole("Usuario");
}
}
|
Al-Mikitinskis/ClubTriatlon
|
src/main/java/es/udc/tfg_es/clubtriatlon/web/pages/user/profile/MyProfile.java
|
Java
|
gpl-3.0
| 1,281
|
#!/bin/bash
# Tests bootstrapping from an incomplete dataset.
PISM_PATH=$1
MPIEXEC=$2
PISM_SOURCE_DIR=$3
# List of files to remove when done:
files="foo-28.nc bar-28.nc baz-28.nc"
rm -f $files
set -e
set -x
# create a (complete) dataset to bootstrap from:
$MPIEXEC -n 2 $PISM_PATH/pisms -y 100 -o foo-28.nc
OPTS="-i foo-28.nc -bootstrap -Mx 61 -My 61 -Mz 11 -y 10 -Lz 1000"
# bootstrap and run for 100 years:
$MPIEXEC -n 2 $PISM_PATH/pismr $OPTS -o bar-28.nc
# remove topg and tillwat (all contain zeros in the file and will default to zero):
ncks -x -v bmelt,tillwat,dbdt,lon,lat -O foo-28.nc foo-28.nc
# bootstrap and run for 100 years:
$MPIEXEC -n 2 $PISM_PATH/pismr $OPTS -o baz-28.nc
set +e
set +x
# Check results:
$PISM_PATH/nccmp.py bar-28.nc baz-28.nc
if [ $? != 0 ];
then
exit 1
fi
rm -f $files; exit 0
|
talbrecht/pism_pik07
|
test/regression/test_28.sh
|
Shell
|
gpl-3.0
| 828
|
###
# Copyright 2016 - 2022 Green River Data Analysis, LLC
#
# License detail: https://github.com/greenriver/boston-cas/blob/production/LICENSE.md
###
class SocialSecurityNumberQualityCode < ApplicationRecord
end
|
greenriver/boston-cas
|
app/models/social_security_number_quality_code.rb
|
Ruby
|
gpl-3.0
| 214
|
from setuptools import setup, find_packages
from fccsmap import __version__
test_requirements = []
with open('requirements-test.txt') as f:
test_requirements = [r for r in f.read().splitlines()]
setup(
name='fccsmap',
version=__version__,
author='Joel Dubowy',
license='GPLv3+',
author_email='jdubowy@gmail.com',
packages=find_packages(),
scripts=[
'bin/fccsmap'
],
package_data={
'fccsmap': ['data/*.nc']
},
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Programming Language :: Python :: 3.8",
"Operating System :: POSIX",
"Operating System :: MacOS"
],
url='https://github.com/pnwairfire/fccsmap/',
description='supports the look-up of FCCS fuelbed information by lat/lng or vector geo spatial data.',
install_requires=[
"afscripting>=2.0.0",
# Note: numpy and gdal must now be installed manually beforehand
"shapely==1.7.1",
"pyproj==3.0.0.post1",
"rasterstats==0.15.0"
],
dependency_links=[
"https://pypi.airfire.org/simple/afscripting/",
],
tests_require=test_requirements
)
|
pnwairfire/fccsmap
|
setup.py
|
Python
|
gpl-3.0
| 1,292
|
package com.apdlv.yahooweather;
//import java.util.Locale;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import com.venista.mjoy.api.exception.ExceptionFilter;
import com.apdlv.utils.URLCodec;
import com.apdlv.utils.WGet;
public class ForecastProvider
{
public static final String YAHOO_WEATHER_API_BASE_URL = "http://weather.yahooapis.com/forecastrss";
public static final String LOCATION_KEY = "p";
public static final String UNIT_KEY = "u";
public static final String UNIT_VALUE_CELSIUS = "c";
public static final String UNIT_VALUE_FARENHEIT = "f";
private static final int TRIALS_MAX = 3;
public WeatherConditions getForecast(String placeCode, /*Locale locale,*/ String tempUnit) throws Exception
{
WeatherConditions wc = null;
int trials = 0;
tempUnit = normalizeTempUnit(tempUnit);
while (trials<TRIALS_MAX && (null==wc || !wc.isAvailable()))
{
try
{
trials++;
String url = buildURL(placeCode, tempUnit);
String xml = wget.getString(url);
/* Simulate an error while getting the forecast data: */
/*
System.out.println(xml);
if (false) return null;
if (false) xml = "";
if (Math.random()>.3) xml = null;
*/
wc = new WeatherConditions(xml, /*locale,*/ tempUnit);
}
catch (Exception ex)
{
//ExceptionFilter.logFiltered(logger, ex);
System.err.println("getForecast: " + ex);
}
}
return wc;
}
private static String buildURL(String location, String degreesUnit)
{
StringBuilder sb = new StringBuilder(YAHOO_WEATHER_API_BASE_URL);
sb.append("?").append(LOCATION_KEY).append("=").append(URLCodec.encodeASCII(location));
sb.append("&").append(UNIT_KEY).append("=").append(URLCodec.encodeASCII(degreesUnit));
return sb.toString();
}
private static String normalizeTempUnit(String tempUnit)
{
if (null==tempUnit)
tempUnit = "c";
else
tempUnit = tempUnit.toLowerCase();
return (!tempUnit.matches("c") && !tempUnit.matches("f")) ? "c" : tempUnit;
}
//private static final Log logger = LogFactory.getLog(ForecastProvider.class);
//protected final Logger logger = LoggerFactory.getLogger(getClass());
private static final WGet wget = new WGet(true,5000);
}
|
apdlv72/Gardenoid
|
src/com/apdlv/yahooweather/ForecastProvider.java
|
Java
|
gpl-3.0
| 2,281
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>png++: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.4 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">png++ <span id="projectnumber">0.2.1</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacepng.html">png</a> </li>
<li class="navelem"><a class="el" href="classpng_1_1def__image__info__holder.html">def_image_info_holder</a> </li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<div class="title">png::def_image_info_holder Member List</div> </div>
</div>
<div class="contents">
This is the complete list of members for <a class="el" href="classpng_1_1def__image__info__holder.html">png::def_image_info_holder</a>, including all inherited members.<table>
<tr class="memlist"><td><a class="el" href="classpng_1_1def__image__info__holder.html#a9527f3f9207292565aba95493dfdce2f">def_image_info_holder</a>(image_info const &info)</td><td><a class="el" href="classpng_1_1def__image__info__holder.html">png::def_image_info_holder</a></td><td><code> [inline]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classpng_1_1def__image__info__holder.html#af595a47a56bdec6d68f7283f4e2efdef">get_info</a>()</td><td><a class="el" href="classpng_1_1def__image__info__holder.html">png::def_image_info_holder</a></td><td><code> [inline]</code></td></tr>
</table></div>
<hr class="footer"/><address class="footer"><small>Generated on Thu Apr 21 2011 22:55:13 for png++ by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address>
</body>
</html>
|
Nvveen/First-Sight
|
lib/png++/doc/html/classpng_1_1def__image__info__holder-members.html
|
HTML
|
gpl-3.0
| 2,853
|
/***************************************************************************
* GCOMEventBin.cpp - COMPTEL event bin class *
* ----------------------------------------------------------------------- *
* copyright (C) 2012 by Juergen Knoedlseder *
* ----------------------------------------------------------------------- *
* *
* 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/>. *
* *
***************************************************************************/
/**
* @file GCOMEventBin.cpp
* @brief COMPTEL event bin class implementation.
* @author Juergen Knoedlseder
*/
/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <string>
#include <cmath>
#include "GCOMEventBin.hpp"
#include "GTools.hpp"
/* __ Method name definitions ____________________________________________ */
/* __ Macros _____________________________________________________________ */
/* __ Coding definitions _________________________________________________ */
/* __ Debug definitions __________________________________________________ */
/*==========================================================================
= =
= Constructors/destructors =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Void constructor
***************************************************************************/
GCOMEventBin::GCOMEventBin(void) : GEventBin()
{
// Initialise class members for clean destruction
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Copy constructor
*
* @param[in] bin Event bin.
***************************************************************************/
GCOMEventBin::GCOMEventBin(const GCOMEventBin& bin) : GEventBin(bin)
{
// Initialise class members for clean destruction
init_members();
// Copy members
copy_members(bin);
// Return
return;
}
/***********************************************************************//**
* @brief Destructor
***************************************************************************/
GCOMEventBin::~GCOMEventBin(void)
{
// Free members
free_members();
// Return
return;
}
/*==========================================================================
= =
= Operators =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Assignment operator
*
* @param[in] bin Event bin.
* @return Event bin.
***************************************************************************/
GCOMEventBin& GCOMEventBin::operator= (const GCOMEventBin& bin)
{
// Execute only if object is not identical
if (this != &bin) {
// Copy base class members
this->GEventBin::operator=(bin);
// Free members
free_members();
// Initialise private members for clean destruction
init_members();
// Copy members
copy_members(bin);
} // endif: object was not identical
// Return this object
return *this;
}
/*==========================================================================
= =
= Public methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Clear instance
*
* This method properly resets the instance to an initial state.
***************************************************************************/
void GCOMEventBin::clear(void)
{
// Free class members (base and derived classes, derived class first)
free_members();
this->GEventBin::free_members();
this->GEvent::free_members();
// Initialise members
this->GEvent::init_members();
this->GEventBin::init_members();
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Clone instance
*
* @return Pointer to deep copy of event bin.
***************************************************************************/
GCOMEventBin* GCOMEventBin::clone(void) const
{
return new GCOMEventBin(*this);
}
/***********************************************************************//**
* @brief Return size of event bin
*
* @return Size of event bin (sr MeV s)
*
* The size of the event bin (units: sr MeV s) is given by
* \f[size = \Omega \times \Delta E \times \Delta T\f]
* where
* \f$\Omega\f$ is the size of the spatial bin in sr,
* \f$\Delta E\f$ is the size of the energy bin in MeV, and
* \f$\Delta T\f$ is the ontime of the observation in seconds.
***************************************************************************/
double GCOMEventBin::size(void) const
{
// Compute bin size
double size = omega() * ewidth().MeV() * ontime();
// Return bin size
return size;
}
/***********************************************************************//**
* @brief Return error in number of counts
*
* @return Error in number of counts in event bin.
*
* Returns \f$\sqrt(counts+delta)\f$ as the uncertainty in the number of
* counts in the bin. Adding delta avoids uncertainties of 0 which will
* lead in the optimisation step to the exlusion of the corresponding bin.
* In the actual implementation delta=1e-50.
*
* @todo The choice of delta has been made somewhat arbitrary, mainly
* because the optimizer routines filter error^2 below 1e-100.
***************************************************************************/
double GCOMEventBin::error(void) const
{
// Compute uncertainty
double error = sqrt(counts()+1.0e-50);
// Return error
return error;
}
/***********************************************************************//**
* @brief Print event information
*
* @return String containing event information.
***************************************************************************/
std::string GCOMEventBin::print(void) const
{
// Initialise result string
std::string result;
// Append number of counts
result.append(str(counts()));
// Return result
return result;
}
/*==========================================================================
= =
= Private methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Initialise class members
*
* This method allocates memory for all event bin attributes and intialises
* the attributes to well defined initial values.
*
* The method assumes that on entry no memory is hold by the member pointers.
***************************************************************************/
void GCOMEventBin::init_members(void)
{
// Allocate members
m_alloc = true;
m_index = -1; // Signals that event bin does not correspond to cube
m_counts = new double;
m_dir = new GCOMInstDir;
m_omega = new double;
m_time = new GTime;
m_ontime = new double;
m_energy = new GEnergy;
m_ewidth = new GEnergy;
// Initialise members
*m_counts = 0.0;
m_dir->clear();
*m_omega = 0.0;
m_time->clear();
*m_ontime = 0.0;
m_energy->clear();
m_ewidth->clear();
// Return
return;
}
/***********************************************************************//**
* @brief Copy class members
*
* @param[in] bin Event bin.
***************************************************************************/
void GCOMEventBin::copy_members(const GCOMEventBin& bin)
{
// Copy members by cloning
m_alloc = true;
m_index = bin.m_index;
m_counts = new double(*bin.m_counts);
m_dir = new GCOMInstDir(*bin.m_dir);
m_omega = new double(*bin.m_omega);
m_time = new GTime(*bin.m_time);
m_ontime = new double(*bin.m_ontime);
m_energy = new GEnergy(*bin.m_energy);
m_ewidth = new GEnergy(*bin.m_ewidth);
// Return
return;
}
/***********************************************************************//**
* @brief Delete class members
*
* This method frees all memory of the class attributes and sets the member
* pointers to NULL. This method should only be called if new memory is
* allocated immediately afterwards (for example by cloning another event
* bin), or upon destruction of the object.
*
* Note that some logic has been implemented that frees only memory that also
* has indeed been allocated by the class. Thus if the class only serves as
* container to hold memory pointer allocated by someone else (for example
* the GCOMEventCube class), no memory is freed.
***************************************************************************/
void GCOMEventBin::free_members(void)
{
// If memory was allocated then free members now
if (m_alloc) {
if (m_counts != NULL) delete m_counts;
if (m_dir != NULL) delete m_dir;
if (m_omega != NULL) delete m_omega;
if (m_time != NULL) delete m_time;
if (m_ontime != NULL) delete m_ontime;
if (m_energy != NULL) delete m_energy;
if (m_ewidth != NULL) delete m_ewidth;
}
// Signal member pointers as free
m_alloc = false;
m_counts = NULL;
m_dir = NULL;
m_omega = NULL;
m_time = NULL;
m_ontime = NULL;
m_energy = NULL;
m_ewidth = NULL;
// Return
return;
}
|
cdeil/gammalib
|
inst/com/src/GCOMEventBin.cpp
|
C++
|
gpl-3.0
| 11,450
|
#ifndef SHAPELOADER_GLOBAL_H
#define SHAPELOADER_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(SHAPELOADER_LIBRARY)
# define SHAPELOADERSHARED_EXPORT Q_DECL_EXPORT
#else
# define SHAPELOADERSHARED_EXPORT Q_DECL_IMPORT
#endif
#endif // SHAPELOADER_GLOBAL_H
|
Bramas/manet-viz
|
src/plugins/ShapeLoader/shapeloader_global.h
|
C
|
gpl-3.0
| 264
|
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - pygmaps </title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=visualization&sensor=true_or_false"></script>
<script type="text/javascript">
function initialize() {
var centerlatlng = new google.maps.LatLng(18.000000, 74.000000);
var myOptions = {
zoom: 10,
center: centerlatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var latlng = new google.maps.LatLng(17.940812, 73.866532);
var img = new google.maps.MarkerImage('/usr/local/lib/python3.5/dist-packages/gmplot/markers/000000.png');
var marker = new google.maps.Marker({
title: "no implementation",
icon: img,
position: latlng
});
marker.setMap(map);
var coords = [
new google.maps.LatLng(17.941261, 73.866532),
new google.maps.LatLng(17.941255, 73.866451),
new google.maps.LatLng(17.941234, 73.866371),
new google.maps.LatLng(17.941201, 73.866296),
new google.maps.LatLng(17.941156, 73.866229),
new google.maps.LatLng(17.941101, 73.866171),
new google.maps.LatLng(17.941037, 73.866124),
new google.maps.LatLng(17.940966, 73.866089),
new google.maps.LatLng(17.940890, 73.866068),
new google.maps.LatLng(17.940812, 73.866060),
new google.maps.LatLng(17.940734, 73.866068),
new google.maps.LatLng(17.940659, 73.866089),
new google.maps.LatLng(17.940588, 73.866124),
new google.maps.LatLng(17.940524, 73.866171),
new google.maps.LatLng(17.940468, 73.866229),
new google.maps.LatLng(17.940423, 73.866296),
new google.maps.LatLng(17.940390, 73.866371),
new google.maps.LatLng(17.940370, 73.866451),
new google.maps.LatLng(17.940363, 73.866532),
new google.maps.LatLng(17.940370, 73.866614),
new google.maps.LatLng(17.940390, 73.866694),
new google.maps.LatLng(17.940423, 73.866769),
new google.maps.LatLng(17.940468, 73.866836),
new google.maps.LatLng(17.940524, 73.866894),
new google.maps.LatLng(17.940588, 73.866941),
new google.maps.LatLng(17.940659, 73.866976),
new google.maps.LatLng(17.940734, 73.866997),
new google.maps.LatLng(17.940812, 73.867005),
new google.maps.LatLng(17.940890, 73.866997),
new google.maps.LatLng(17.940966, 73.866976),
new google.maps.LatLng(17.941037, 73.866941),
new google.maps.LatLng(17.941101, 73.866894),
new google.maps.LatLng(17.941156, 73.866836),
new google.maps.LatLng(17.941201, 73.866769),
new google.maps.LatLng(17.941234, 73.866694),
new google.maps.LatLng(17.941255, 73.866614),
];
var polygon = new google.maps.Polygon({
clickable: false,
geodesic: true,
fillColor: "#3B0B39",
fillOpacity: 0.300000,
paths: coords,
strokeColor: "#3B0B39",
strokeOpacity: 1.000000,
strokeWeight: 1
});
polygon.setMap(map);
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
|
Vijaysai005/KProject
|
vijay/DBSCAN/MAP/mymap_25-3-2017_9:37.html
|
HTML
|
gpl-3.0
| 3,005
|
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera (herrera@decsai.ugr.es)
L. Sánchez (luciano@uniovi.es)
J. Alcalá-Fdez (jalcala@decsai.ugr.es)
S. García (sglopez@ujaen.es)
A. Fernández (alberto.fernandez@ujaen.es)
J. Luengo (julianlm@decsai.ugr.es)
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 keel.Algorithms.Subgroup_Discovery.NMEEFSD.NMEEFSD;
/**
* <p> Class for a fuzzy set definition
* @author Written by Cristóbal J. Carmona (University of Jaen) 11/08/2008
* @version 1.0
* @since JDK1.5
* </p>
*/
public class Fuzzy {
/**
* <p>
* Values for a fuzzy set definition
* </p>
*/
private float x0,x1,x3;
private float y;
/**
* <p>
* Methods to get the value of x0
* </p>
* @return Value of x0
*/
public float getX0 () {
return x0;
}
/**
* <p>
* Methods to get the value of x1
* </p>
* @return Value of x1
*/
public float getX1 () {
return x1;
}
/**
* <p>
* Methods to get the value of x3
* </p>
* @return Value of x3
*/
public float getX3 () {
return x3;
}
/**
* <p>
* Method to set the values of x0, x1 y x3
* </p>
* @param vx0 Value for x0
* @param vx1 Value for x1
* @param vx3 Value for x3
* @param vy Value for y
*/
public void setVal (float vx0, float vx1, float vx3, float vy) {
x0 = vx0;
x1 = vx1;
x3 = vx3;
y = vy;
}
/**
* <p>
* Returns the belonging degree
* </p>
* @param X Value to obtain the belonging degree
* @return Belonging degree
*/
public float Fuzzy (float X) {
if ((X<=x0) || (X>=x3)) // If value of X is not into range x0..x3
return (0); // then pert. degree = 0
if (X<x1)
return ((X-x0)*(y/(x1-x0)));
if (X>x1)
return ((x3-X)*(y/(x3-x1)));
return (y);
}
/**
* <p>
* Creates a new instance of Fuzzy
* </p>
*/
public Fuzzy() {
}
}
|
SCI2SUGR/KEEL
|
src/keel/Algorithms/Subgroup_Discovery/NMEEFSD/NMEEFSD/Fuzzy.java
|
Java
|
gpl-3.0
| 3,163
|
#include "ExampleClusterObj.h"
#include "ExampleCluster.h"
ExampleClusterObj::ExampleClusterObj()
: ObjBase{{podio::ObjectID::untracked, podio::ObjectID::untracked}, 0},
data(), m_Hits(new std::vector<ConstExampleHit>()),
m_Clusters(new std::vector<ConstExampleCluster>()) {}
ExampleClusterObj::ExampleClusterObj(const podio::ObjectID id,
ExampleClusterData data)
: ObjBase{id, 0}, data(data) {}
ExampleClusterObj::ExampleClusterObj(const ExampleClusterObj &other)
: ObjBase{{podio::ObjectID::untracked, podio::ObjectID::untracked}, 0},
data(other.data),
m_Hits(new std::vector<ConstExampleHit>(*(other.m_Hits))),
m_Clusters(new std::vector<ConstExampleCluster>(*(other.m_Clusters))) {}
ExampleClusterObj::~ExampleClusterObj() {
if (id.index == podio::ObjectID::untracked) {
delete m_Hits;
delete m_Clusters;
}
}
|
HEP-FCC/podio
|
tests/src/ExampleClusterObj.cc
|
C++
|
gpl-3.0
| 908
|
package com.uklonewolf.exmorcraft.item.ingots;
import com.uklonewolf.exmorcraft.reference.Names;
public class ingot_Silica extends IngotsEC
{
public ingot_Silica()
{
super();
this.setUnlocalizedName(Names.Ingots.Ingot_Silica);
this.setMaxStackSize(64);
this.setTextureName(Names.Ingots.Ingot_Silica);
}
}
|
UKLoneWolf/ExmorCraft
|
src/main/java/com/uklonewolf/exmorcraft/item/ingots/ingot_Silica.java
|
Java
|
gpl-3.0
| 352
|
---
layout: post
title: Linux使用
category: Linux
descriptions: Linux
keywords: ubuntu vdi virtualenv virtualenvwrapper
---
今天看到虚拟机上ubuntu系统的磁盘不够用的时候,想要新建一个新的虚拟机并且分配更大的内存给它,结果把win上的c盘搞炸了,活生生100G的盘只剩下可怜的5G······重新放置软件和文件所在并安装新系统所需要的东西。
<!-- more -->
### virtualbox的vdi放置
以前的做法:把软件都安装在D盘,而虚拟机的文件等都放在了C盘。
更正:将软件安装在C盘,将虚拟机的vdi移至C盘外的盘区。下载
下面是在新安装的ubuntu上所作的一些配置和安装:
### 安装chrome
```
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*; sudo apt-get -f install
```
### 安装pycharm
从官网下载了安装包后:
```
mv pycharm-community-2017.2.1.tar.gz /opt
cd /opt && tar -xf pycharm-community-2017.2.tar.gz
sudo ln -s /opt/pycharm-community-2016.2/bin/pycharm.sh /usr/bin/pycharm
```
(好吧,到了这一步,我已经后悔安装中文的ubuntu了······在命令行使用起来各种蛋疼······深深的体会到英文的会比中文的顺手这么多·····决定修改回英文······)
### 安装virtualenv
```
$ pip install virtualenv
```
使用:
+ 为工程创建一个虚拟环境:
```
$ virtualenv virt_proj
```
此命令创建一个文件夹,包含了Python可执行文件, 以及 `pip` 库的一份拷贝。
可以选择使用一个Python解释器:
```
$ virtualenv -p /usr/bin/python3 virt_proj
```
+ 要开始使用虚拟环境,其需要被激活:
```
$ source virt_proj/bin/activate
```
+ 如果在虚拟环境中暂时完成了工作,则可以停用它:
```
$ deactivate
```
注意:
+ 运行带 `--no-site-packages` 选项的 `virtualenv` 将不会包括全局安装的包。
+ 为了保持环境的一致性,可以选择“冷冻住(freeze)”环境:
```
$ pip freeze > requirements.txt
```
可以使用 “pip list”在不产生requirements文件的情况下, 查看已安装包的列表。
在以后安装相同版本的相同包变得容易:
```
$ pip install -r requirements.txt
```
### 安装virtualenvwrapper
```
$ pip install virtualenvwrapper
$ export WORKON_HOME=~/Envs //WORKON_HOME 就是它将要用来存放各种虚拟环境目录的目录
$ source /usr/local/bin/virtualenvwrapper.sh
```
最后一步发现,文件在/home/ztt/.local/bin/virtualenvwrapper.sh??
使用:
+ 创建虚拟环境:
```
$ mkvirtualenv virt_proj
```
+ 在虚拟环境上工作:
```
$ workon virt_proj
```
+ 停止:
```
$ deactivate
```
+ 删除:
```
$ rmvirtualenv virt_proj
```
+ 列举所有的环境:
```
~/pyproj_folder$ lsvirtualenv
virt_proj
=========
```
+ `cdvirtualenv`导航到当前激活的虚拟环境的目录中
+ `cdsitepackages`和上面的类似,但是是直接进入到 `site-packages` 目录中.
+ `lssitepackages`显示 `site-packages` 目录中的内容。
### virtualenv-burrito
有了virtualenv-burrito,就能使用单行命令拥有virtualenv + virtualenvwrapper的环境。
## autoenv
当你 `cd` 进入一个包含 `.env` 的目录中,就会 [autoenv](https://github.com/kennethreitz/autoenv) 自动激活那个环境。
### 学习中遇到的问题
- [x] 1. 关于[virtualenv](http://pythonguidecn.readthedocs.io/zh/latest/dev/virtualenvs.html#virtualenvwrapper)的使用
"在任何你运行命令的目录中,这会创建Python的拷贝,并将之放在叫做 `my_project` 的文件中"?不太懂
【解惑】该虚拟环境是在python上做操作,使用了virtualenv可以与全局的python环境隔绝开,进入了虚拟环境,在任何运行命令的目录,都会生成python的拷贝,放在虚拟环境的目录下,而不影响全局python环境。
- [x] 2. virtualenvwrapper和virtualenv?
【搜索了解】virtualenv` 的一个最大的缺点就是,每次开启虚拟环境之前要去虚拟环境所在目录下的 `bin` 目录下 `source` 一下 `activate`,这就需要我们记住每个虚拟环境所在的目录。
一种可行的解决方案是,将所有的虚拟环境目录全都集中起来,并对不同的虚拟环境使用不同的目录来管理。`virtualenvwrapper` 正是这样做的。并且,它还省去了每次开启虚拟环境时候的 `source` 操作,使得虚拟环境更加好用。
- [x] 3. ubuntu改回英文,部分管理器侧栏中文却没有修改?
【解决】找到相应的文件管理器侧栏设置文件,发现并没有原来的信息,而是都被修改了,但是没有修改的中文还是停留在那里。所以尝试重启,发现重启后没有修改的中文都被修改成了英文。
- [x] 4. 安装virtualenvwrapper并没有安装在/usr/local/bin/下面,而是在/home/ztt/.local/bin/里?
【措施】把`export WORKON_HOME=~/Envs`和`source ~/.local/bin/virtualenvwrapper.sh`写进`.bashrc`,避免要重新export。
> [Python最佳实践指南](http://pythonguidecn.readthedocs.io/zh/latest/)
|
tingtinZ/tingtinZ.github.io
|
_posts/2017-08-17-linux_use.md
|
Markdown
|
gpl-3.0
| 5,326
|
// assign assertion library
var assert = chai.assert,
expect = chai.expect;
suite('live page testing', function (e) {
var a, spy;
console.log(e);
setup(function () {
spy = sinon.spy(window._gaq, 'push'),
factorySpy = sinon.spy(GA, 'processFactoryOptions');
});
test('body was found', function () {
var $_body = $('body');
assert.equal($_body.length, 1, 'body element was not found');
});
test ('Test Me Link', function () {
var $_link = $('a[data-analytics-type="testMe"]'),
info = $_link.data('analytics-info');
$_link.trigger('click');
expect(spy.calledWith(['_trackEvent', 'Test', 'current page', info])).to.equal(true);
});
test ('Social Link', function () {
var $_link = $('a[data-analytics-type="social"]'),
info = $_link.data('analytics-info');
$_link.trigger('click');
expect(spy.calledWith(['_trackSocial', info])).to.equal(true);
});
teardown(function () {
spy.restore();
factorySpy.restore();
});
});
|
mturnwall/Analytics_Class
|
test/integration_testing/integration_test2.js
|
JavaScript
|
gpl-3.0
| 955
|
from __future__ import with_statement
import os
import sys
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# We need to go back a dir to get the config.
_this_dir = os.path.dirname((os.path.abspath(__file__)))
_parent_dir = os.path.join(_this_dir, '../')
for _p in (_this_dir, _parent_dir):
if _p not in sys.path:
sys.path.append(_p)
from config import API, APP
# Bind some vars for our migrations to use for environmental setup
API_URL_WITH_SLASH = API.LISTEN_URL + "/"
#
# n.b. this is only currently doing API migrations
#
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def merged_ini_py_conf():
"""Update some settings that would be fetched from the ini with those from our
application config.
this could maybe be cleaner with some clever .setdefault('key', default_value)
:return: merged settings dict
"""
conf = config.get_section(config.config_ini_section)
if hasattr(API, 'SQLALCHEMY_DATABASE_URI'):
conf['sqlalchemy.url'] = API.SQLALCHEMY_DATABASE_URI
return conf
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
context.configure(
url=merged_ini_py_conf().get('sqlalchemy.url'),
target_metadata=target_metadata,
literal_binds=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
merged_ini_py_conf(),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
tristanfisher/yams
|
multidb/env.py
|
Python
|
gpl-3.0
| 2,875
|
<!DOCTYPE html>
<html>
<head>
<title>Setup web-component - CVE-Search</title>
<meta charset="utf-8">
<link href="./css/style.css" rel="stylesheet" />
</head>
<body>
<h1>Setup the web-component for CVE-Search</h1>
<p>
This document will explain how to set up the web-component for CVE-Search.
This documentation assumes you have installed all the components of CVE-Search and ran the first initialization scripts.
</p>
<h2>Settings</h2>
<p>
Before we start the web server, we will go over the settings in the configuration.ini file, and explain what every setting means.
The settings for the web-server can be found under the head <span class="highlight">[Webserver]</<pan>
<table>
<thead>
<tr><td>Setting</td> <td>Default setting</td> <td>Explanation</td></tr>
</thead>
<tr><td>Host</td> <td>127.0.0.1</td> <td>The address by which the web-server is accessible. Either loop-back or one of the machine's IP addresses</td> </tr>
<tr><td>Port</td> <td>5000</td> <td> The port on which the web-server will be running </td></tr>
<tr><td>Debug</td> <td>True</td> <td>When the server runs in <a href="#debug">debug mode</a>, SSL will be turned off and the web-server will be in <span title="The server will process only one request at a time and block the others until the current one is ready">Blocking Mode</span></td></tr>
<tr><td>PageLength</td> <td>50</td> <td>The amount of <abbr title="Common Vulnerability and Exposure">CVE's</abbr> that will be displayed per page</td></tr>
<tr><td>LoginRequired</td> <td>False</td> <td>Decides whether <a href="#users">users</a> have to log in to access <a href="#admin_pages">admin pages</a>.</td></tr>
<tr><td>SSL</td> <td>False</td> <td>Decides whether SSL is used to secure the connection. See <a href="#ssl">SSL</a> for more information on how to set this up</td></tr>
<tr><td>Certificate</td> <td>ssl/cve-search.crt</td> <td> The certificate used for the SSL connection. More info under <a href="#ssl">SSL</a></td></tr>
<tr><td>Key</td> <td>ssl/cve-search.key</td> <td> The key used for the SSL connection. More info under <a href="#ssl">SSL</a></td></tr>
</table>
</p>
<h2 id="debug">Debug mode</h2>
<p>
Running the server in debug mode allows for easier development of the server. By setting this value on <span class="code">True</span>, the server will only use the Flask module.
This means that the server will be set to <span title="The server will process only one request at a time and block the others until the current one is ready">Blocking Mode</span>, <a href="#ssl">SSL </a> will be disabled, overriding the configuration.ini settings, and the server will give more visual debug output. <br />
Setting this value on <span class="code">False</span>, the server will take the default SSL settings from the configuration.ini file and will enable the Tornado module, putting the server in <span title="The server will process multiple requests at the same time">Non-Blocking mode</span>, and reduce the visual debug output. <br />
It is advised not to run the server in debug mode when you run it in a production environment. However, when you are developing or testing CVE-Search alone or with a small group of people, it is advised to run it in debug mode, as it will give you a lot more information when the application crashes for some reason.
</p>
<h2 id="users">Users and Login</h2>
<p>
If you decide to make use of CVE-Search's login system, you will need to add users to the user-list. To do this, you'll be using the <span class="code">db_mgmt_admin.py</span> script. <br />
This script takes several parameters, as mentioned below:
<table>
<thead>
<tr><td>Parameter</td> <td>Arguments</td> <td>Explanation</td></tr>
</thead>
<tr><td>-h, --help</td> <td>None</td> <td>Displays the help page</td></tr>
<tr><td>-a A</td> <td>name of user</td> <td>Add a user account</td></tr>
<tr><td>-c C</td> <td>name of user</td> <td>Change the password of a user</td></tr>
<tr><td>-r R</td> <td>name of user</td> <td>Remove a user account</td></tr>
<tr><td>-p P</td> <td>name of user</td> <td>Promote a user account to <a href="#master">Master</a></td></tr>
<tr><td>-d D</td> <td>name of user</td> <td>Demote a user account to a normal user </td></tr>
</table>
</p>
<h3 id="master">Master accounts</h3>
<p>
The first account that you add will automatically be a Master account. Master accounts are accounts with the privilege to add, remove, promote and demote other user accounts.
Every user can access the admin panel, regardless whether he has a Master account or not.
</p>
<h3>Creating accounts</h3>
<p>
You can create a user account by using the command <span class="code">Python3 db_mgmt_admin.py -a user</span>, where user is the name of your account. <br />
If this is the first account in the database, the script will not require a <a href="#master">Master</a> password, and the account created will be a Master account.
If this is not the first account, the script will ask you to log in using a Master account, before you can proceed.<br />
Next, the script will ask you for a new password for the user. You will not see the characters when you type the password. This is to protect the user's password from spying eyes.
After verifying the password, the user account will be created.
</p>
<h3>Changing account passwords</h3>
<p>
Every user can change his or her password by typing <span class="code">Python3 db_mgmt_admin.py -c user</span>, where user is the name of your account. </br />
Running this script will ask you the current password of your user account. After entering this password, it will ask you to type your new password twice.
After you typed your new password, the user will be updated, and the new password will be stored.
</p>
<h3>Removing accounts</h3>
<p>
Master accounts can remove users by typing <span class="code">Python3 db_mgmt_admin.py -r user</span>, where user is the name of the account. <br />
Removing an account requires a Master account to log in. If the account you're trying to remove is not the last Master account, it will not be removed.
</p>
<h3>Promoting accounts</h3>
<p>
Master accounts can promote other accounts by typing <span class="code">Python3 db_mgmt_admin.py -p user</span>, where user is the name of the account. <br />
Promoting a user grants this user the privileges to add, remove, promote and demote other users.
</p>
<h3>Demoting accounts</h3>
<p>
Master accounts can demote him/herself or other accounts by typing <span class="code">Python3 db_mgmt_admin.py -d user</span>, where user is the name of the account. <br />
If the account you're trying to demote is the last Master account, it won't work. Demoting users reduces their privileges to that of a normal user, so he/she can only change his or her own password.
</p>
<h2 id="ssl">SSL - Secure Socket Layer</h2>
<p>
The use of SSL will make sure your users traffic can not be sniffed. This will make sure people with bad intentions can't get user passwords or any other information.
</p>
<h3>Setting up SSL</h3>
<p>
To set up SSL on your server, you need a certificate and a key. On Linux, you can create these by running the following command: <br />
<span class= "code">openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /ssl/cve-search.key -out /ssl/cve-search.crt</span> <br />
The parameter <span class="code">-days</span> lets you choose the duration the certificate must be valid. In this example, this is 365 days. <br />
The parameter <span class="code">-newkey</span> lets you choose the algorithm and length of the key and certificate. If you don't know what you're doing, use the default value. <br />
The parameter <span class="code">-keyout</span> is the output of your new SSL key. Make sure this location is the same as the <span class="code">Key</span> value of your configuration.ini file. <br />
The parameter <span class="code">-out</span> is the output for your new SSL certificate. Make sure this location is the same as the <span class="code">Certificate</span> value of your configuration.ini file. <br />
<br />
After hitting the Enter key, you'll be requested to fill out your organizational information. This will be visible on the certificate, and will be a way for your users to verify your certificate, as this will be <span title="Self-signed certificates are certificates that are not validated by external sources.">self-signed</span>.
When users surf to your website, they will get a warning, and they will have to accept this certificate.
</p>
<h2>Starting and stopping the web-server</h2>
<p>
Once you set up the configurations.ini file how you want it to be, you can start the webserver by simply running <span class="code">python3 web/index.py</span>. <br />
To stop the server, you can simply press the <abbr title="Hold down the Control key and the C key at the same time">CTRL+C</abbr> combination. <br />
<br />
Alternatively, on Linux, you can start the server by running <span class="code">nohup python3 web/index.py &</span>.
This will make the server run in the background. However, this makes it so you cannot use the <abbr title="Hold down the Control key and the C key at the same time">CTRL+C</abbr> combination.
Instead, you will have to find the processes related to the web-server, by using <span class="code">ps aux | grep web/index.py</span>. Then kill them using the <span class="code">kill -15</span> command on all the processes related to the server.
</p>
<h2>Using the web-server</h2>
<h3>Pages for normal users</h3>
<p>
All users will be able to view the recent CVE's, search for <abbr title="Common Vulnerability and Exposure">CVE's</abbr> related to a product and get all <abbr title="Common Vulnerability and Exposure">CVE</abbr> information. In the table below, you can find a short description of each page this user can go to.
<table>
<thead>
<tr><td>Page</td> <td>Description</td></tr>
</thead>
<tr><td>Recent</td> <td>An overview of all the CVE's, ordered from recent to old. You can use the filter to enhance your search.</td></tr>
<tr><td>CVE</td> <td>The overview of a CVE. You can find all the information that is in the CVE-Search database in here. </td></tr>
<tr><td>Browse per vendor</td> <td>Lets you search <abbr title="Common Vulnerability and Exposure">CVE's</abbr> per product. The result is ordered from new to old, sorted by Last Major Update</td></tr>
</table>
Every <abbr title="Common Vulnerability and Exposure">CVE</abbr> has a few base fields. These fields are:<br /><br />
<table>
<thead>
<tr><td>Field</td> <td>Explanation</td></tr>
</thead>
<tr><td>ID</td> <td>The identifier of a CVE</td></tr>
<tr><td>Summary</td> <td>The description of a CVE, with an explanation the attack vector and the result</td></tr>
<tr><td>References</td> <td>Links to other websites with information about the CVE. These can be vendor statements, explanations, etc</td></tr>
<tr><td>Vulnerable Configuration</td> <td>The products that are vulnerable to the CVE. This field can be empty if the <abbr title="Common Vulnerability and Exposure">CVE</abbr> is still new, and information is not complete yet.</td></tr>
<tr><td>CVSS</td> <td>The score given to a CVE. This score represents the risk and damage. If this field is not yet set by NIST's <abbr title="National Vulnerability Database">NVD</abbr>, the default value, specified in the configuration.ini file,will be used.</td></tr>
<tr><td>Last Major Update</td> <td>The last major update a <abbr title="Common Vulnerability and Exposure">CVE</abbr> had. This is set to the latest update where information is added or changed</td></tr>
<tr><td>Published</td> <td>The date the <abbr title="Common Vulnerability and Exposure">CVE</abbr> got published</td></tr>
<tr><td>Last Modified</td> <td>The date the <abbr title="Common Vulnerability and Exposure">CVE</abbr> got last modified. Modifications can be spelling changes, changes in wording etc.</td></tr>
</table>
</p>
<h3 id="admin_pages">Admin Pages</h3>
<p>
When login is required, admins have access to more pages then normal users. If login is not required, normal users will have access to these pages as well. <br />
The admin page is the main control panel for the admin. From this page, he can update the database, as well as view and manage the white/and blacklist. All the admin functions are accessible by using the navigation buttons.
</p>
<h4>Updating the database</h4>
<p>
Updating the database can be done by a press of the update button, on the admin panel. Alternatively, you can use the update script <span class="code">db_updater.py</span>. The button press runs <span class="code">python3 db_updater.py -civ</span>.
For more information on the scripts parameters, run <span class="code">Python3 db_updater -h</span>.<br />
The sources used by CVE-Search are listed in the configuration.ini file.
</p>
<h4>Managing white- and blacklists</h4>
<p>
The white- and blacklists can be used to manage the information your users see. Adding a <abbr title="Common Platform Enumeration">CPE</abbr> to the whitelist, any <abbr title="Common Vulnerability and Exposure">CVE</abbr> which has this <abbr title="Common Platform Enumeration">CPE</abbr> in its vulnerable configurations will be marked.
Adding a <abbr title="Common Platform Enumeration">CPE</abbr> to the blacklist will hide all the <abbr title="Common Vulnerability and Exposure">CVE's</abbr> which are only applicable to this CPE. This way you can hide <abbr title="Common Vulnerability and Exposure">CVE's</abbr> for products you're not interested in.
This default behavior can be overruled by the search filter on the "Recent" page, and by no means excludes these items from the database.<br />
CPE's have a specific format, and can be used as regular expression to mark or exclude CPE's. The default format of a <abbr title="Common Platform Enumeration">CPE</abbr> is: <br />
<span class="code">cpe:/type:vendor:product:version</span><br />
The type can be <span class="code">a</span> for application, <span class="code">h</span> for hardware or <span class="code">o</span> for operating system. <br />
<strong>Example:</strong><br />
<span class="code">cpe:/h:3com:3c13612:5.26.2</span> is a piece of hardware, produced by 3com. The product name is 3c13612, and the version is 5.26.2. Adding this to the whitelist will make CVE-Search mark all the <abbr title="Common Vulnerability and Exposure">CVE's</abbr> applicable to this specific setup.
However, if you don't want just this version number, you could add <span class="code">cpe:/h:3com:3c13612:</span>, for all the versions, or even <span class="code">cpe:/h:3com:</span> for all the hardware 3com produces.
</p>
<h2>Logging</h2>
<p>
Logging only occurs when Debug mode is set to <span class="code">False</span>. <br />
Logging can be useful when multiple people are using your server, and you cannot monitor it the entire time. When your server does not run in debug mode, you can use logging to still get reports of crashes or malfunctions.
The configurations.ini file contains a few options regarding logging, which are briefly explained below:
<table>
<thead>
<tr><td>Setting</td> <td>Default setting</td> <td>Explanation</td></tr>
</thead>
<tr><td>Logging</td> <td>True</td> <td>Setting this value to <span class="code">True</span> enables logging. <span class="code">False</span> turns logging off</td></tr>
<tr><td>Logfile</td> <td>log/cve-search.log</td> <td>The file the logs will be saved to</td></tr>
<tr><td>MaxSize</td> <td>100MB</td> <td>Maximum size of the logfile. Can take the format of <span class="code">100</span>, <span class="code">100 b</span> or <span class="code">100b</span>. b means bytes, mb means megabytes and gb means gigabytes.</td></tr>
<tr><td>Backlog</td> <td>5</td> <td>Amount of logfiles the server saves.</td></tr>
</table>
<br />
When the size of the logfile exceeds the amount set in MaxSize, a new file will be created. If the settings are like above, this file will be called log/cve-search.1.log.
If either MaxSize or Backlog is set to 0, this will not happen, and the logfile will have no maximum size.
</p>
</body>
</html>
|
deontp/misc
|
zenoic_api/cve-search-master/doc/html/Webcomponent.html
|
HTML
|
gpl-3.0
| 16,756
|
#ifndef METAIF_H
#define METAIF_H
#include "astElement.h"
#include <map>
class astIf : public astElement
{
public:
astIf();
//metaCall branchingBlock;
std::map<blocks::itemID, std::vector<astElement*> > branches;//branchPin and the branch itself
};
#endif // METAIF_H
|
nimrof/blocks
|
bcc/ast/astBranchIf.h
|
C
|
gpl-3.0
| 278
|
#!/usr/bin/env python
#
# !!!!!!!!! WARNING !!!!!!!!!!!!!!!
# This Script was bastardized To Read Password From /home/bspaans/.googlecode
#
#
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import http.client
import os.path
import optparse
import getpass
import base64
import sys
def get_svn_config_dir():
pass
def get_svn_auth(project_name, config_dir):
"""Return (username, password) for project_name in config_dir.
!!!!! CHANGED !!!!!!!!"""
f = open("/home/bspaans/.googlecode", 'r')
usr_data = f.read().split(":")
f.close()
return (usr_data[0], usr_data[1][:-1])
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = http.client.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
config_dir=None, user_name=None, tries=1):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
If config_dir is None, try get_svn_config_dir(); if it is 'none', skip
trying the Subversion configuration entirely. If user_name is not None, use
it for the first attempt; prompt for subsequent attempts.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
if config_dir != 'none':
# Try to load username/password from svn config for first try.
if config_dir is None:
config_dir = get_svn_config_dir()
(svn_username, password) = get_svn_auth(project_name, config_dir)
if user_name is None:
# If username was not supplied by caller, use svn config.
user_name = svn_username
else:
# Just initialize password for the first try.
password = None
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print('Please enter your googlecode.com password.')
print('** Note that this is NOT your Gmail account password! **')
print('It is the password you use to access Subversion repositories,')
print('and can be found here: http://code.google.com/hosting/settings')
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [http.client.FORBIDDEN]:
# Rest for another try.
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('--config-dir', dest='config_dir', metavar='DIR',
help='read svn auth data from DIR'
' ("none" means not to use svn auth data)')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of labels to attach to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.config_dir, options.user)
if url:
print('The file was uploaded successfully.')
print('URL: %s' % url)
return 0
else:
print('An error occurred. Your file was not uploaded.')
print('Google Code upload server said: %s (%s)' % (reason, status))
return 1
if __name__ == '__main__':
sys.exit(main())
|
anthonyt/mingus-counterpoint
|
googlecode_upload.py
|
Python
|
gpl-3.0
| 9,994
|
<div class="row">
<div class="col-lg-12"><br></div>
</div>
<div class="col-sm-4 col-sm-offset-4">
<div class="alert alert-danger" ng-if="registerError" role="alert">
<div ng-repeat="error in registerErrors">
{{error}}
</div>
</div>
<div class="well">
<h3>Register</h3>
<form name="loginForm" novalidate autocomplete="off">
<div class="form-group" show-errors>
<input type="text" name="name" class="form-control" placeholder="Name" ng-model="newUser.name" required >
<p class="help-block" ng-if="loginForm.name.$error.required">Name is required</p>
</div>
<div class="form-group" show-errors>
<input type="email" name="email" class="form-control" placeholder="Email" ng-model="newUser.email" required >
<p class="help-block" ng-if="loginForm.email.$error.required">Email is required</p>
<p class="help-block" ng-if="loginForm.email.$error.email">Email address is invalid</p>
</div>
<div class="form-group" show-errors>
<input type="password" name="password" class="form-control" placeholder="Password" ng-model="newUser.password" required >
<p class="help-block" ng-if="loginForm.password.$error.required">Password is required</p>
</div>
<div class="form-group" show-errors>
<input type="password" name="password_confirmation" class="form-control" placeholder="Password Confirmation" ng-model="newUser.password_confirmation" required >
<p class="help-block" ng-if="loginForm.password_confirmation.$error.required">Password Confirmation is required</p>
</div>
<button class="btn btn-primary" ng-click="register()">Register</button>
<a class="btn btn-danger pull-right" ui-sref="login">Back</a>
</form>
</div>
</div>
|
fpauer/Single-Page-Application-AngularJs
|
public/js/tpl/register.html
|
HTML
|
gpl-3.0
| 1,952
|
# Utilities ------------------------------------------------------------------ #
import math
def clamp(val, min, max):
if val <= min:
return min
elif val >= max:
return max
return val
def fixAngle(angle):
while angle > 180.0:
angle -= 360.0
while angle < -180.0:
angle += 360.0
return angle
def diffAngle(angle1, angle2):
return fixAngle(angle1 - angle2)
# Utilities ------------------------------------------------------------------ #
|
CertainlyUncertain/Kinetic-Gunner-Gunner-of-Angst
|
utils.py
|
Python
|
gpl-3.0
| 502
|
package com.baeldung.jpa.enums;
public enum Status {
OPEN, REVIEW, APPROVED, REJECTED;
}
|
Niky4000/UsefulUtils
|
projects/tutorials-master/tutorials-master/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/enums/Status.java
|
Java
|
gpl-3.0
| 94
|
//***********************************************************
//* vbat.c
//***********************************************************
//***********************************************************
//* Includes
//***********************************************************
#include <avr/io.h>
#include <stdlib.h>
#include <util/delay.h>
#include "io_cfg.h"
#include "adc.h"
//************************************************************
// Prototypes
//************************************************************
uint16_t GetVbat(void);
//************************************************************
// Code
//************************************************************
uint16_t GetVbat(void) // Get battery voltage (VBAT on ADC3)
{
uint16_t vBat; // Battery voltage
read_adc(AIN_VBAT); // Multiplication factor = (Display volts / 1024) / (Vbat / 11 / Vref)
vBat = ((ADCW * 21) >> 3); // For Vref = 2.45V, factor = 2.632 (21/8 = 2.625)
return vBat;
}
|
sndae/kk2glider
|
old_openaero2/src/vbat.c
|
C
|
gpl-3.0
| 1,012
|
#ifndef _MYACTIONGROUP_H_
#define _MYACTIONGROUP_H_
#include <QActionGroup>
#include <QWidget>
#include "myaction.h"
class MyActionGroup : public QActionGroup
{
Q_OBJECT
public:
MyActionGroup ( QObject * parent );
void setChecked(int ID);
int checked();
void clear(bool remove);
void setActionsEnabled(bool);
void addTo(QWidget *);
void removeFrom(QWidget *);
void uncheckAll();
signals:
void activated(int);
protected slots:
void itemTriggered(QAction *);
};
#endif
|
UbuntuKylin/youker-assistant
|
plugins/widgets/myactiongroup.h
|
C
|
gpl-3.0
| 518
|
/*
* FrameHorarioCiclo.java
* Encargado de un horario semanal para sesiones a grupo, asesorias u otras actividades
* Parte de proyecto: SADAA
* Author: Pedro Cardoso Rodriguez
* Mail: ingpedro@live.com
* Place: Zacatecas Mexico
*
Copyright © 2010 Pedro Cardoso Rodriguez
SADAA 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 any
later version.
SADAA 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 SADAA. If not, see <http://www.gnu.org/licenses/>
*/
package sistema;
import definiciones.TipoMensaje;
import iconos.Iconos;
/** Ventana con un control encargado de un horario semanal para
* sesiones a grupo, asesorias u otras actividades
*
* @author Pedro Cardoso Rdoriguez
*/
public class FrameHorarioCiclo extends sistema.ModeloFrameInterno{
private ControlDiasSemana horarioSemanal;
/** Crea un nuevo FrameHorarioCiclo
* @param ventana Referencia a la ventana principal contenedora (clase sistema.FramePrincipal)
*/
public FrameHorarioCiclo(sistema.FramePrincipal ventana){
super(ventana,"frmhorasem.png");
try {
initComponents();
btnActu.setText("");
btnActu.setIcon(Iconos.getIcono("cargar.png"));
horarioSemanal = new ControlDiasSemana("Distribucion de horario semanal vigente","",this);
add(horarioSemanal, java.awt.BorderLayout.CENTER);
cargaActividades();
}
catch (ControlDiasSemana.RefSuperiorInvalida ex){}
}
/**Carga los datos de horarios que aplican actualmente*/
private void cargaActividades(){
if(!horarioSemanal.cargaDatos()){
muestraMensaje("Error al consultar horario semanal vigente",horarioSemanal.obtenError(),TipoMensaje.ERROR);
return;
}
horarioSemanal.setTitulo("Horario semanal vigente");
empaqueta();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jToolBar1 = new javax.swing.JToolBar();
btnActu = new javax.swing.JButton();
setClosable(true);
setIconifiable(true);
setResizable(true);
setTitle("Horario semanal vigente");
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
btnActu.setText("Actualiza");
btnActu.setToolTipText("Actualizar tabla de actividades");
btnActu.setFocusable(false);
btnActu.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnActu.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnActu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnActuActionPerformed(evt);
}
});
jToolBar1.add(btnActu);
getContentPane().add(jToolBar1, java.awt.BorderLayout.NORTH);
pack();
}// </editor-fold>//GEN-END:initComponents
/** Vuelve a cargar los datos de horarios que aplican actualmente
* @param evt El ActionEvent que genero el evento
*/
private void btnActuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActuActionPerformed
cargaActividades();
}//GEN-LAST:event_btnActuActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnActu;
private javax.swing.JToolBar jToolBar1;
// End of variables declaration//GEN-END:variables
}
|
engcardso/SADAA-Tesis
|
src/sistema/FrameHorarioCiclo.java
|
Java
|
gpl-3.0
| 4,176
|
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo
* This benchmark is part of SWSC */
#include <assert.h>
#include <stdint.h>
#include <stdatomic.h>
#include <pthread.h>
atomic_int vars[3];
atomic_int atom_1_r1_1;
atomic_int atom_1_r12_1;
void *t0(void *arg){
label_1:;
atomic_store_explicit(&vars[0], 2, memory_order_seq_cst);
atomic_store_explicit(&vars[1], 1, memory_order_seq_cst);
return NULL;
}
void *t1(void *arg){
label_2:;
int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst);
int v3_r3 = v2_r1 ^ v2_r1;
atomic_store_explicit(&vars[2+v3_r3], 1, memory_order_seq_cst);
atomic_store_explicit(&vars[2], 2, memory_order_seq_cst);
int v5_r7 = atomic_load_explicit(&vars[2], memory_order_seq_cst);
int v6_r8 = v5_r7 ^ v5_r7;
atomic_store_explicit(&vars[0+v6_r8], 1, memory_order_seq_cst);
int v8_r11 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v10_r12 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v20 = (v2_r1 == 1);
atomic_store_explicit(&atom_1_r1_1, v20, memory_order_seq_cst);
int v21 = (v10_r12 == 1);
atomic_store_explicit(&atom_1_r12_1, v21, memory_order_seq_cst);
return NULL;
}
int main(int argc, char *argv[]){
pthread_t thr0;
pthread_t thr1;
atomic_init(&vars[0], 0);
atomic_init(&vars[2], 0);
atomic_init(&vars[1], 0);
atomic_init(&atom_1_r1_1, 0);
atomic_init(&atom_1_r12_1, 0);
pthread_create(&thr0, NULL, t0, NULL);
pthread_create(&thr1, NULL, t1, NULL);
pthread_join(thr0, NULL);
pthread_join(thr1, NULL);
int v11 = atomic_load_explicit(&vars[0], memory_order_seq_cst);
int v12 = (v11 == 2);
int v13 = atomic_load_explicit(&vars[2], memory_order_seq_cst);
int v14 = (v13 == 2);
int v15 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst);
int v16 = atomic_load_explicit(&atom_1_r12_1, memory_order_seq_cst);
int v17_conj = v15 & v16;
int v18_conj = v14 & v17_conj;
int v19_conj = v12 & v18_conj;
if (v19_conj == 1) assert(0);
return 0;
}
|
nidhugg/nidhugg
|
tests/litmus/C-tests/MP+PPO889.c
|
C
|
gpl-3.0
| 2,005
|
#ifndef ORBITALEQUATION_H
#define ORBITALEQUATION_H
// Local includes
#include <src/includes/defines.h>
#include <src/includes/lib.h>
#include <src/includes/binaryoperations.h>
#include <src/Interaction/interaction.h>
#include <src/OneParticleOperator/oneparticleoperator.h>
// Libraries
#include <libconfig.h++>
#include <armadillo>
#include <bitset>
#include <unordered_map>
using namespace libconfig;
using namespace std;
using namespace arma;
class OrbitalEquation
{
public:
OrbitalEquation(Config* cfg,
vector<bitset<BITS> > slaterDeterminants,
Interaction *V,
SingleParticleOperator *h);
const cx_mat &computeRightHandSide(const cx_mat &C, const cx_vec &A);
double getCorrelation();
const cx_mat &reCalculateRho1(const cx_vec &A);
vec getSvdRho1();
protected:
void computeProjector(const cx_mat &C);
cx_double findRho2(int p,int q, int r, int s);
void computeUMatrix(const cx_mat &C);
void computeOneParticleReducedDensity();
void computeOneParticleReducedDensityWithSpin();
void computeTwoParticleReducedDensity();
cx_double reducedOneParticleOperator(const int i, const int j);
cx_double reducedTwoParticleOperator(const int p, const int q,
const int r, const int s);
// Class variables
Config* cfg;
Interaction *V;
SingleParticleOperator* h;
vector<bitset<BITS> > slaterDeterminants;
int nOrbitals;
int nGrid;
int nSlaterDeterminants;
int nParticles;
cx_mat invRho;
unordered_map<int, cx_double> rho2;
const cx_vec* A;
const cx_mat* hC;
cx_mat U;
cx_mat Q;
cx_mat rightHandSide;
cx_mat rho1; // TMP
// MPI
imat allRH;
int myRank, nNodes;
vector<pair<int,int> > myRij;
ivec sizeRij;
};
#endif // ORBITALEQUATION_H
|
sigvebs/MCTDHF
|
src/OrbitalEquation/orbitalequation.h
|
C
|
gpl-3.0
| 1,876
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'sourcearea', 'tr', {
toolbar: 'Kaynak'
});
|
tsmaryka/hitc
|
public/javascripts/ckeditor/plugins/sourcearea/lang/tr.js
|
JavaScript
|
gpl-3.0
| 219
|
module Main where
import System.Environment(getArgs)
nonRepeatedChar :: [Char] -> Char
nonRepeatedChar = nonRepeatedChar' []
where nonRepeatedChar' xs (c:cs) =
if c `notElem` cs && c `notElem` xs then c
else nonRepeatedChar' (c:xs) cs
processLine :: String -> String
processLine line = [ nonRepeatedChar line ]
main :: IO ()
main = do
[inputFile] <- getArgs
input <- readFile inputFile
mapM_ putStrLn $ map processLine $ lines input
|
cryptica/CodeEval
|
Challenges/12_FirstNonRepeatingCharacter/main.hs
|
Haskell
|
gpl-3.0
| 478
|
use utf8;
package CollectiveAccess::PortaleMusica::Schema::Result::CaOccurrencesXVocabularyTerm;
# Created by DBIx::Class::Schema::Loader
# DO NOT MODIFY THE FIRST PART OF THIS FILE
=head1 NAME
CollectiveAccess::PortaleMusica::Schema::Result::CaOccurrencesXVocabularyTerm
=cut
use strict;
use warnings;
use base 'DBIx::Class::Core';
=head1 COMPONENTS LOADED
=over 4
=item * L<DBIx::Class::InflateColumn::DateTime>
=back
=cut
__PACKAGE__->load_components("InflateColumn::DateTime");
=head1 TABLE: C<ca_occurrences_x_vocabulary_terms>
=cut
__PACKAGE__->table("ca_occurrences_x_vocabulary_terms");
=head1 ACCESSORS
=head2 relation_id
data_type: 'integer'
extra: {unsigned => 1}
is_auto_increment: 1
is_nullable: 0
=head2 occurrence_id
data_type: 'integer'
extra: {unsigned => 1}
is_foreign_key: 1
is_nullable: 0
=head2 type_id
data_type: 'smallint'
extra: {unsigned => 1}
is_foreign_key: 1
is_nullable: 0
=head2 item_id
data_type: 'integer'
extra: {unsigned => 1}
is_foreign_key: 1
is_nullable: 0
=head2 source_info
accessor: 'column_source_info'
data_type: 'longtext'
is_nullable: 0
=head2 sdatetime
data_type: 'decimal'
is_nullable: 1
size: [30,20]
=head2 edatetime
data_type: 'decimal'
is_nullable: 1
size: [30,20]
=head2 label_left_id
data_type: 'integer'
extra: {unsigned => 1}
is_foreign_key: 1
is_nullable: 1
=head2 label_right_id
data_type: 'integer'
extra: {unsigned => 1}
is_foreign_key: 1
is_nullable: 1
=head2 rank
data_type: 'integer'
default_value: 0
extra: {unsigned => 1}
is_nullable: 0
=cut
__PACKAGE__->add_columns(
"relation_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_auto_increment => 1,
is_nullable => 0,
},
"occurrence_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_foreign_key => 1,
is_nullable => 0,
},
"type_id",
{
data_type => "smallint",
extra => { unsigned => 1 },
is_foreign_key => 1,
is_nullable => 0,
},
"item_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_foreign_key => 1,
is_nullable => 0,
},
"source_info",
{
accessor => "column_source_info",
data_type => "longtext",
is_nullable => 0,
},
"sdatetime",
{ data_type => "decimal", is_nullable => 1, size => [30, 20] },
"edatetime",
{ data_type => "decimal", is_nullable => 1, size => [30, 20] },
"label_left_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_foreign_key => 1,
is_nullable => 1,
},
"label_right_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_foreign_key => 1,
is_nullable => 1,
},
"rank",
{
data_type => "integer",
default_value => 0,
extra => { unsigned => 1 },
is_nullable => 0,
},
);
=head1 PRIMARY KEY
=over 4
=item * L</relation_id>
=back
=cut
__PACKAGE__->set_primary_key("relation_id");
=head1 UNIQUE CONSTRAINTS
=head2 C<u_all>
=over 4
=item * L</occurrence_id>
=item * L</type_id>
=item * L</sdatetime>
=item * L</edatetime>
=item * L</item_id>
=back
=cut
__PACKAGE__->add_unique_constraint(
"u_all",
["occurrence_id", "type_id", "sdatetime", "edatetime", "item_id"],
);
=head1 RELATIONS
=head2 item
Type: belongs_to
Related object: L<CollectiveAccess::PortaleMusica::Schema::Result::CaListItem>
=cut
__PACKAGE__->belongs_to(
"item",
"CollectiveAccess::PortaleMusica::Schema::Result::CaListItem",
{ item_id => "item_id" },
{ is_deferrable => 1, on_delete => "RESTRICT", on_update => "RESTRICT" },
);
=head2 label_left
Type: belongs_to
Related object: L<CollectiveAccess::PortaleMusica::Schema::Result::CaOccurrenceLabel>
=cut
__PACKAGE__->belongs_to(
"label_left",
"CollectiveAccess::PortaleMusica::Schema::Result::CaOccurrenceLabel",
{ label_id => "label_left_id" },
{
is_deferrable => 1,
join_type => "LEFT",
on_delete => "RESTRICT",
on_update => "RESTRICT",
},
);
=head2 label_right
Type: belongs_to
Related object: L<CollectiveAccess::PortaleMusica::Schema::Result::CaListItemLabel>
=cut
__PACKAGE__->belongs_to(
"label_right",
"CollectiveAccess::PortaleMusica::Schema::Result::CaListItemLabel",
{ label_id => "label_right_id" },
{
is_deferrable => 1,
join_type => "LEFT",
on_delete => "RESTRICT",
on_update => "RESTRICT",
},
);
=head2 occurrence
Type: belongs_to
Related object: L<CollectiveAccess::PortaleMusica::Schema::Result::CaOccurrence>
=cut
__PACKAGE__->belongs_to(
"occurrence",
"CollectiveAccess::PortaleMusica::Schema::Result::CaOccurrence",
{ occurrence_id => "occurrence_id" },
{ is_deferrable => 1, on_delete => "RESTRICT", on_update => "RESTRICT" },
);
=head2 type
Type: belongs_to
Related object: L<CollectiveAccess::PortaleMusica::Schema::Result::CaRelationshipType>
=cut
__PACKAGE__->belongs_to(
"type",
"CollectiveAccess::PortaleMusica::Schema::Result::CaRelationshipType",
{ type_id => "type_id" },
{ is_deferrable => 1, on_delete => "RESTRICT", on_update => "RESTRICT" },
);
# Created by DBIx::Class::Schema::Loader v0.07043 @ 2015-09-01 16:35:15
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:tPEH20ys+sCgh97Cimh3KA
# You can replace this text with custom code or comments, and it will be preserved on regeneration
1;
|
pro-memoria/caHarvester
|
lib/PortaleMusica/Schema/Result/CaOccurrencesXVocabularyTerm.pm
|
Perl
|
gpl-3.0
| 5,372
|
import re, shlex
import hangups
from hangupsbot.utils import text_to_segments
from hangupsbot.handlers import handler, StopEventHandling
from hangupsbot.commands import command
default_bot_alias = '/bot'
def find_bot_alias(aliases_list, text):
"""Return True if text starts with bot alias"""
command = text.split()[0].lower()
for alias in aliases_list:
if alias.lower().startswith('regex:') and re.search(alias[6:], command, re.IGNORECASE):
return True
elif command == alias.lower():
return True
return False
def is_bot_alias_too_long(text):
"""check whether the bot alias is too long or not"""
if default_bot_alias in text:
return True
else:
return False
@handler.register(priority=5, event=hangups.ChatMessageEvent)
def handle_command(bot, event):
"""Handle command messages"""
# Test if message is not empty
if not event.text:
return
# Get list of bot aliases
aliases_list = bot.get_config_suboption(event.conv_id, 'commands_aliases')
if not aliases_list:
aliases_list = [default_bot_alias]
# Test if message starts with bot alias
if not find_bot_alias(aliases_list, event.text):
return
# Test if command handling is enabled
if not bot.get_config_suboption(event.conv_id, 'commands_enabled'):
raise StopEventHandling
# Parse message
line_args = shlex.split(event.text, posix=False)
# Test if command length is sufficient
if len(line_args) < 2:
yield from event.conv.send_message(
text_to_segments(_('{}: 무엇을 도와드릴까요?').format(event.user.full_name))
)
raise StopEventHandling
# Test if user has permissions for running command
commands_admin_list = command.get_admin_commands(bot, event.conv_id)
if commands_admin_list and line_args[1].lower() in commands_admin_list:
admins_list = bot.get_config_suboption(event.conv_id, 'admins')
if event.user_id.chat_id not in admins_list:
yield from event.conv.send_message(
text_to_segments(_('{}: 권한이 없습니다.').format(event.user.full_name))
)
raise StopEventHandling
# Run command
yield from command.run(bot, event, *line_args[1:])
#Check whether the bot alias is too long or not
if is_bot_alias_too_long(event.text):
yield from event.conv.send_message(
text_to_segments(_('**Tip**: /bot 대신에 /b, /, ! 등을 사용할 수 있어요'))
)
# Prevent other handlers from processing event
raise StopEventHandling
|
ildelusion/JSBot
|
hangupsbot/handlers/commands.py
|
Python
|
gpl-3.0
| 2,643
|
#!/usr/bin/php -q
<?php
$PATH_TO_INCLUDES = dirname(dirname(dirname(__FILE__)));
require $PATH_TO_INCLUDES.'/phputils/EventScraper.php';
require $PATH_TO_INCLUDES.'/phputils/couchdb.php';
ini_set("display_errors", true);
error_reporting(E_ALL & ~E_NOTICE);
class HouseCommitteeTransportationInfrastructure extends EventScraper_Abstract
{
protected $url = 'http://www3.capwiz.com/c-span/dbq/officials/schedule.dbq?committee=htran&command=committee_schedules&chambername=House&chamber=H&period=';
public $parser_name = 'C-SPAN House Transportation and Infrastructure Committee Schedule Scraper';
public $parser_version = '0.1';
public $parser_frequency = '6.0';
public function __construct()
{
parent::__construct();
$this->year = date("Y");
}
public function run()
{
$events = $this->scrape();
//print_r($events);
$this->add_events($events);
}
protected function scrape()
{
$events = array();
$scrape_start = microtime_float();
$response = $this->urlopen($this->url);
$this->source_url = $this->url;
$this->source_text = $response;
$this->access_time = time();
preg_match_all('#<li>(.+?)<\/li>#is', $response, $li);
$i=0;
foreach($li[1] as $li_str) {
if(!preg_match('/<a href=/is',$li_str)) {
preg_match_all('#<span[^>]*>(.+?)<\/span>#is', $li_str, $span);
$_date_tmp = date("m/d/Y", strtotime(strip_tags($span[1][0])));
list($month, $day, $year) = explode('/',$_date_tmp);
$_date_str = strftime('%Y-%m-%dT%H:%M:%SZ', mktime(0, 0, 0, $month, $day, $year));
$events[$i]['couchdb_id'] = (string) $_date_str . ' - ' .$this->parser_name;
$events[$i]['datetime'] = (string) $_date_str;
$events[$i]['end_datetime'] = null;
$events[$i]['title'] = (string) strip_tags(trim($span[1][1]));
$events[$i]['description'] = null;
$events[$i]['branch'] = BranchName::$legislative;
$events[$i]['entity'] = EntityName::$house;
$events[$i]['source_url'] = $this->url;
$events[$i]['source_text'] = (string) trim($li_str);
$_access_time = date('D, d M Y H:i:s T', $this->access_time);
$events[$i]['access_datetime'] = $this->_vd_date_format($_access_time);
$events[$i]['parser_name'] = (string) $this->parser_name;
$events[$i]['parser_version'] = $this->parser_version;
$i++;
}
}
$scrape_end = microtime_float();
$this->parser_runtime = round(($scrape_end - $scrape_start), 4);
return $events;
}
}
$parser = new HouseCommitteeTransportationInfrastructure;
$parser->run();
|
onyxfish/votersdaily
|
scripts/legislative/house_committee_htran/scraper.php
|
PHP
|
gpl-3.0
| 2,882
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from statemachine import _Statemachine
class Windows8_1StateMachine(_Statemachine):
def __init__(self, params):
_Statemachine.__init__(self, params)
def _list_share(self):
return super(Windows8_1StateMachine, self)._list_share()
def _list_running(self):
return super(Windows8_1StateMachine, self)._list_running()
def _list_drives(self):
return super(Windows8_1StateMachine, self)._list_drives()
def _list_network_drives(self):
return super(Windows8_1StateMachine, self)._list_network_drives()
def _list_sessions(self):
return super(Windows8_1StateMachine, self)._list_sessions()
def _list_scheduled_jobs(self):
return super(Windows8_1StateMachine, self)._list_scheduled_jobs()
def _list_network_adapters(self):
return super(Windows8_1StateMachine, self)._list_network_adapters()
def _list_arp_table(self):
return super(Windows8_1StateMachine, self)._list_arp_table()
def _list_route_table(self):
return super(Windows8_1StateMachine, self)._list_route_table()
def _list_sockets_network(self):
return super(Windows8_1StateMachine, self)._list_sockets_network()
def _list_sockets_services(self):
return super(Windows8_1StateMachine, self)._list_services()
def _list_kb(self):
return super(Windows8_1StateMachine, self)._list_kb()
def csv_list_drives(self):
super(Windows8_1StateMachine, self)._csv_list_drives(self._list_drives())
def csv_list_network_drives(self):
super(Windows8_1StateMachine, self)._csv_list_network_drives(self._list_network_drives())
def csv_list_share(self):
super(Windows8_1StateMachine, self)._csv_list_share(self._list_share())
def csv_list_running_proccess(self):
super(Windows8_1StateMachine, self)._csv_list_running_process(self._list_running())
def csv_hash_running_proccess(self):
super(Windows10StateMachine, self)._csv_hash_running_process(self._list_running())
def csv_list_sessions(self):
super(Windows8_1StateMachine, self)._csv_list_sessions(self._list_sessions())
def csv_list_arp_table(self):
super(Windows8_1StateMachine, self)._csv_list_arp_table(self._list_arp_table())
def csv_list_route_table(self):
super(Windows8_1StateMachine, self)._csv_list_route_table(self._list_route_table())
def csv_list_sockets_networks(self):
super(Windows8_1StateMachine, self)._csv_list_sockets_network(self._list_sockets_network())
def csv_list_services(self):
super(Windows8_1StateMachine, self)._csv_list_services(self._list_services())
def csv_list_kb(self):
super(Windows8_1StateMachine, self)._csv_list_kb(self._list_kb())
|
SeungGiJeong/SK_FastIR
|
health/windows8_1StateMachine.py
|
Python
|
gpl-3.0
| 2,827
|
idad
====
Prints a random dad joke to the screen
Ethics
------
This is a counterpart application to another by the same developer which
intentionally frustrates the user with DRM-like behavior.
These were created in May 2014 for
[this event](https://www.defectivebydesign.org/day_against_drm_2014_announcement).
Legitimacy
----------
This program is not meant to be taken seriously. If you __really__ want a
program with this functionality, you may
[contact me](http://mcmackins.org/contact.html).
|
2mac/idad
|
README.md
|
Markdown
|
gpl-3.0
| 507
|
/*!
* jquery.scrollto.js 0.0.1 - https://github.com/yckart/jquery.scrollto.js
* Scroll smooth to any element in your DOM.
*
* Copyright (c) 2012 Yannick Albert (http://yckart.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
* 2013/02/17
**/
(function($) {
$.scrollTo = $.fn.scrollTo = function(x, y, options){
if (!(this instanceof $)) return $.fn.scrollTo.apply($('html, body'), arguments);
options = $.extend({}, {
gap: {
x: 0,
y: 0
},
animation: {
easing: 'swing',
duration: 600,
complete: $.noop,
step: $.noop
}
}, options);
return this.each(function(){
var elem = $(this);
elem.stop().animate({
scrollLeft: !isNaN(Number(x)) ? x : $(y).offset().left + options.gap.x,
scrollTop: !isNaN(Number(y)) ? y : $(y).offset().top + options.gap.y
}, options.animation);
});
};
})(jQuery);
|
TEDICpy/wp-tedic-theme
|
js/jquery.scrollto.js
|
JavaScript
|
gpl-3.0
| 1,009
|
/******************************************************************************
*
* Copyright © 2014 Anthony Mai Mai_Anthony@hotmail.com. All Rights Reserved.
*
* This software is written by Anthony Mai who retains full copyright of this
* work. As such any Copyright Notices contained in this code. are NOT to be
* removed or modified. If this package is used in a product, Anthony Mai
* should be given attribution as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or in
* documentation (online or textual) provided with the package.
*
* This library is free for commercial and non-commercial use as long as the
* following conditions are aheared to. The following conditions apply to
* all code found in this distribution:
*
* 1. Redistributions of source code must retain the 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.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* "This product contains software written by Anthony Mai (Mai_Anthony@hotmail.com)
* The original source code can obtained from such and such internet sites or by
* contacting the author directly."
*
* 4. This software may or may not contain patented technology owned by a third party.
* Obtaining a copy of this software, with or without explicit authorization from
* the author, does NOT imply that applicable patents have been licensed. It is up
* to you to make sure that utilization of this software package does not infringe
* on any third party's patents or other intellectual proerty rights.
*
* THIS SOFTWARE IS PROVIDED BY ANTHONY MAI "AS IS". 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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or derivative
* of this code cannot be changed. i.e. this code cannot simply be copied and put under
* another distribution licence [including the GNU Public Licence.]
*
******************************************************************************/
/******************************************************************************
*
* File Name: ssl.c
*
* Description: Implementation of SSL 3.0 and TLS 1.0 client.
*
* I initially used test case data from
* http://wp.netscape.com/ssl3/traces/
* The old netscape web page is no longer available but
* the same trace data can now be found at:
* http://www.mozilla.org/projects/security/pki/nss/ssl/traces/
*
* Programmers: Anthony Mai (am) mai_anthony@hotmail.com
*
* History: 6/28/2014 Initial creation
*
* Notes: This file uses 4 spaces indents
*
******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
#include "ssl.h"
#include "cipher.h"
#include "ssl_int.h"
#include "clientMsg.h"
#include "msecret.h"
#include "hmac.h"
#include "cert.h"
#ifndef FALSE
#define TRUE 1
#define FALSE 0
#endif //FALSE
#define CONTENT_HEADER_LEN 5
#define SSL_OVERHEAD (CONTENT_HEADER_LEN+MD5_SIZE)
//Static function protocol declarations
static void* MemAlloc(uint nSize);
static void MemFree(void* pData);
static uint CreateNetMsg(SSL* pSSL, uchar cContentType, const uchar* pData, uint nDataSize);
//Global data declarations
static uint nSSLInstanceCount = 0;
SSL_MALLOC gfMalloc = NULL; //Memory allocation function. Must NOT be NULL.
SSL_FREE gfFree = NULL; //Memory deallocate function. Must NOT be NULL.
SSL_RANDOM gfRandom = NULL; //Pseudo Random Number Generator function. Must NOT be NULL.
const CIPHERSET* gpCipherSet = NULL;
uint gSvrMsgSize = 0 ;
uint gAppMsgSize = 0 ;
//Used in SSL 3.0
static const uchar SENDER_CLIENT[] = "CLNT";
static const uchar SENDER_SERVER[] = "SRVR";
//Used in SSL 3.1 / TLS 1.0 and after.
static const char CLIENT_LABEL[] = "client finished";
static const char SERVER_LABEL[] = "server finished";
const uchar PAD1[PADSIZE_MD5] = //Size is MAX(PADSIZE_MD5, PADSIZE_SHA)
{
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
};
const uchar PAD2[PADSIZE_MD5] = //Size is MAX(PADSIZE_MD5, PADSIZE_SHA)
{
0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C
};
//**** Function implementations *********************************************
static void SSL_Reset(HSSL pSSL);
/******************************************************************************
* Function: SSL_Initialize
*
* Description: Initialize SSL module. This call must preceeds any other SSL
* calls. Application optionally provides memory allocation,
* memory free, and random number generator functions.
*
* Returns: SSL_OK if no error.
******************************************************************************/
SSL_RESULT SSL_Initialize
(
SSL_MALLOC pMallocFunc,
SSL_FREE pFreeFunc,
SSL_RANDOM pRandomFunc,
const CIPHERSET* pCipherSet,
uint nSvrMsgSize,
uint nAppMsgSize
)
{
gfMalloc = pMallocFunc;
gfFree = pFreeFunc;
gfRandom = pRandomFunc;
gpCipherSet = pCipherSet;
StartCerts(pMallocFunc, pFreeFunc, pCipherSet);
if( nSvrMsgSize > 0 )
{
gSvrMsgSize = nSvrMsgSize ;
}
if( nAppMsgSize > 0 )
{
gAppMsgSize = nAppMsgSize ;
}
return SSL_OK;
}
/******************************************************************************
* Function: SSL_AddRootCertificate
*
* Description: This function is used to add trusted root certificates.
* Selected *.cer files dumped from the InternetExplorer
* root certificates are OK, as long as the associated entities
* can continue to be trusted.
*
* Returns: SSL_OK if no error.
******************************************************************************/
SSL_RESULT SSL_AddRootCertificate
(
const uchar* pCertData,
uint nLen,
uint nUnixTime
)
{
CERT_STATUS eStatus = CS_ROOT;
uint nLen2;
CERT* pCert = NULL;
pCert = CreateCert(eStatus, nUnixTime);
nLen2 = ParseCert(pCert, pCertData, nLen);
if (nLen2 != nLen)
{
DestroyCert(pCert);
return SSL_ERROR_CERTIFICATE_BAD;
}
eStatus = AuthenticateCert(pCert, NULL);
if (NULL == InsertCert(pCert, NULL))
{
DestroyCert(pCert);
return SSL_ERROR_CERTIFICATE_EXISTS;
}
return SSL_OK;
}
/******************************************************************************
* Function: SSL_AddCRL
*
* Description: This function is used to add CRL (Certificate RevocationList).
* Application should obtain current (up to date) CRLs from the
* internet. One source is:
* http://www.geotrust.com/resources/crls/index.htm
*
* Returns: SSL_OK if no error.
******************************************************************************/
SSL_RESULT SSL_AddCRL(uchar* pCRL, uint nLen)
{
// TO be implemented.
return SSL_RESULT_NOT_APPLY;
}
void SSL_Reset(HSSL pSSL)
{
if (NULL == pSSL) return;
pSSL->nSessionIDLen = 0;
pSSL->serverMsgLen = 0;
pSSL->serverMsgOff = 0;
pSSL->nNetOutSize = 0;
pSSL->nAppOutSize = 0;
pSSL->pTemp = NULL;
pSSL->nTemp1 = 0;
pSSL->nTemp2 = 0;
pSSL->eLastError = SSL_OK;
if (pSSL->pServerCert != NULL)
{
DeleteCert(pSSL->pServerCert, &(pSSL->pMidCerts));
DestroyCert(pSSL->pServerCert);
pSSL->pServerCert = NULL;
}
if (pSSL->pMidCerts != NULL)
{
CleanupCerts(&(pSSL->pMidCerts));
}
pSSL->eState = SSLSTATE_INITIALIZED;
}
/******************************************************************************
* Function: SSL_Create
*
* Description: Create an instance of HSSL to be used in a HTTPS connection session.
*
* Returns: SSL_OK if successful.
******************************************************************************/
SSL_RESULT SSL_Create
(
HSSL* pHSSL,
CERTKEY_INFO* pCertKey
)
{
SSL* pSSL;
pSSL = gfMalloc(sizeof(*pSSL));
*pHSSL = NULL;
if (NULL != pSSL)
{
memset(pSSL, 0, sizeof(*pSSL));
pSSL->pCertKey = pCertKey;
pSSL->eState = SSLSTATE_INITIALIZED;
nSSLInstanceCount ++;
pSSL->serverMsg = gfMalloc( gSvrMsgSize );
if (gAppMsgSize > 0)
{
pSSL->appoutMsg = gfMalloc( gAppMsgSize );
}
if ((NULL != pSSL->serverMsg) && ((NULL != pSSL->appoutMsg) || (gAppMsgSize <= 0)))
{
pSSL->eLastError = SSL_OK;
*pHSSL = pSSL;
SSL_Reset(pSSL);
return SSL_OK;
}
else
{
SSL_Destroy(pSSL);
pSSL = NULL;
}
}
return SSL_ERROR_MEMORY;
}
/******************************************************************************
* Function: SSL_Destroy
*
* Description: Destroy an instance of HSSL. The instance should no longer be used.
*
* Returns: SSL_OK
******************************************************************************/
SSL_RESULT SSL_Destroy(HSSL pSSL)
{
if (NULL != pSSL)
{
if (pSSL->pServerCert)
{
CERT* pCert;
pCert = DeleteCert(pSSL->pServerCert, &(pSSL->pMidCerts));
DestroyCert(pSSL->pServerCert);
}
if (pSSL->pMidCerts != NULL)
{
CleanupCerts(&(pSSL->pMidCerts));
}
if ((NULL != pSSL->appoutMsg) && (gAppMsgSize != 0))
{
gfFree( pSSL->appoutMsg );
pSSL->appoutMsg = NULL;
}
if (NULL != pSSL->serverMsg)
{
gfFree( pSSL->serverMsg );
pSSL->serverMsg = NULL;
}
gfFree(pSSL);
nSSLInstanceCount--;
if (nSSLInstanceCount == 0)
{
//We no longer have any instance of SSL. What to do?
}
}
return SSL_OK;
}
/******************************************************************************
* Function: SSL_Process
*
* Description: The one big callback function that handles everything.
*
* Returns:
******************************************************************************/
//The filtering function that carries out all SSL operations.
SSL_RESULT SSL_Process
(
SSL_PARAMS* pParam,
HSSL pSSL
)
{
uint nAppOutBuffSize = gAppMsgSize;
if ((NULL == pSSL) || (NULL == pParam))
{
return SSL_ERROR_GENERIC;
}
pSSL->eLastError = SSL_OK;
//Reset return parameters so we do not unintentionally return something.
pParam->pNetOutData = NULL;
pParam->nNetOutSize = 0;
if (nAppOutBuffSize == 0)
{
pSSL->appoutMsg = pParam->pAppOutData;
nAppOutBuffSize = pParam->nAppOutSize;
}
pParam->pAppOutData = NULL;
pParam->nAppOutSize = 0;
pSSL->nNetOutSize = 0;
pSSL->nAppOutSize = 0;
//First update our time. The time is a UINT32 seconds since
//the EPOCH, 00:00AM 01/01/1970 UTC.
pSSL->nCurrentTime = pParam->nUnixTime;
//Second do we have a state change?
if (pParam->eState != pSSL->eState)
{
pSSL->eState = pParam->eState;
switch (pSSL->eState)
{
case SSLSTATE_RESET:
SSL_Reset(pSSL);
pSSL->eState = SSLSTATE_INITIALIZED;
break;
case SSLSTATE_TCPCONNECTED:
{
pSSL->nStartTime = pSSL->nCurrentTime;
pSSL->eClientCipher = CIPHER_NOTSET;
pSSL->eServerCipher = CIPHER_NOTSET;
pSSL->serverMsgOff = 0;
pSSL->serverMsgLen = 0;
pSSL->eState = SSLSTATE_HANDSHAKE_BEGIN;
}
break;
case SSLSTATE_DISCONNECT:
{
//We were told by the App to initiate disconnect sequence.
//This is done by sending a Close Alert to the server, then
//notify the App to disconnect the TCP.
CreateAlertMsg(pSSL, ALERT_WARNING, ALERT_NOTIFY_CLOSE);
pSSL->eState = SSLSTATE_DISCONNECTING;
}
break;
case SSLSTATE_DISCONNECTED:
{
//Do some cleanup and prepare for next connection.
pSSL->eState = SSLSTATE_UNCONNECTED;
}
break;
default:
break;
}
}
pParam->eState = pSSL->eState;
//Third do we have anything from the network?
while ((NULL != pParam->pNetInData) && (pParam->nNetInSize > 0))
{
uint nParse, nChunk = pParam->nNetInSize;
if (nAppOutBuffSize == 0)
{
//Neither Application provided the AppOut buffer, nor was it allocated
//internally. So we share the serverMsg buffer. Nothing to do here.
}
else
{
if (nChunk > ((nAppOutBuffSize)>>1))
{
nChunk = ((nAppOutBuffSize)>>1);
}
//Do we have big enough App Out buffer to parse the message
if ((nChunk + pSSL->nAppOutSize) > nAppOutBuffSize)
{
if ((SSL_OVERHEAD + pSSL->nAppOutSize) < nAppOutBuffSize)
{
nChunk = nAppOutBuffSize - pSSL->nAppOutSize;
}
else
{
//Buffer full. Can not parse anything.
nChunk = 0;
pSSL->eLastError = SSL_ERROR_BUFFER_FULL;
return pSSL->eLastError;
}
}
}
nParse = ParseServerMsg(
pSSL,
pParam->pNetInData,
nChunk
);
pParam->pNetInData += nParse;
pParam->nNetInSize -= nParse;
//Any error parsing server message?
if (pSSL->eLastError != SSL_OK)
{
return pSSL->eLastError;
}
}
//Fourth do we have any state change because of server message parsing?
do
{
pParam->eState = pSSL->eState;
switch (pSSL->eState)
{
case SSLSTATE_HANDSHAKE_BEGIN:
//We create a ClientHello message and ask App to send it.
pSSL->eState = SSLSTATE_CLIENT_HELLO;
pSSL->nNetOutSize += CreateClientHelloMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
//We now wait for a ServerHello message.
pSSL->eState = SSLSTATE_SERVER_HELLO;
break;
case SSLSTATE_CERTIFICATE_REQUEST:
pParam->eState = pSSL->eState = SSLSTATE_CERTIFICATE_REQUESTING;
break;
case SSLSTATE_CERTIFICATE_REQUESTING:
pSSL->eState = SSLSTATE_CERTIFICATE_NOTGIVEN;
break;
case SSLSTATE_CERTIFICATE_NOTGIVEN:
pSSL->eState = SSLSTATE_ABORTING;
break;
case SSLSTATE_CERTIFICATE_SUPPLIED:
//OK App gives up the client certificate.
//Take the client certificate that the application gives us here.
//Then do appropriate processing here.
pSSL->pTemp = (uchar*)pParam->nInXData.ptr; //Only place this is set.
pSSL->eState = SSLSTATE_CERTIFICATE_VERIFY;
break;
case SSLSTATE_CERTIFICATE_VERIFY:
{
//Verify server certificate.
CERT_STATUS eStatus;
eStatus = AuthenticateCert(pSSL->pServerCert, &(pSSL->pMidCerts));
//Give the HCERT to let App do something with it.
pParam->nOutXData.ptr = (void*)pSSL->pServerCert;
//Please note here. The certificate may or may not be verified,
//depends on eStatus. That information is passed to application
//using pParam->nOutXData. So upon seeing the state changing to
//SSLSTATE_CERTIFICATE_VERIFIED, the application should be able
//to look at the returned pParam->nOutXData, and decide what to
//do next if the verify status does not look good. By default it
//just continues on to SSLSTATE_CLIENT_KEYEXCHANGE, if no action
//is taken by application.
if ((eStatus & (CS_OK | CS_VERIFIED)) == (CS_OK | CS_VERIFIED))
{
//Certificate is OK and can be trusted.
pParam->eState = pSSL->eState = SSLSTATE_CERTIFICATE_VERIFIED;
}
else
{
//Certificate questionable. Prompt the application to decide
//either to goto
// SSLSTATE_CERTIFICATE_ACCEPTED
//or to goto
// SSLSTATE_CERTIFICATE_REJECTED
//Application should check pParam->nOutXData to decide.
pParam->eState = pSSL->eState = SSLSTATE_CERTIFICATE_ACCEPTING;
}
}
break;
case SSLSTATE_CERTIFICATE_VERIFIED:
//Certificate OK, valid and trusted. So go ahead.
pSSL->eState = SSLSTATE_CLIENT_KEYEXCHANGE;
if (pSSL->pTemp != NULL)
{
//If we are to supply client certificate, then do it first.
pSSL->eState = SSLSTATE_CLIENT_CERTIFICATE;
}
break;
case SSLSTATE_CERTIFICATE_ACCEPTED:
//Certificate may be questionable. But App accepted it any way.
pSSL->eState = SSLSTATE_CLIENT_KEYEXCHANGE;
if (pSSL->pTemp != NULL)
{
//If we are to supply client certificate, then do it first.
pSSL->eState = SSLSTATE_CLIENT_CERTIFICATE;
}
break;
case SSLSTATE_CERTIFICATE_ACCEPTING:
//The application undeciding on this one. So we do the default and
//prepare to disconnect the questionable connection.
//Fall through to SSLSTATE_CERTIFICATE_REJECTED as default.
case SSLSTATE_CERTIFICATE_REJECTED:
pSSL->eState = SSLSTATE_ABORTING;
break;
case SSLSTATE_CLIENT_CERTIFICATE:
//Same as SSLSTATE_CLIENT_KEYEXCHANGE but with extra messages, depending on pSSL->pTemp,
//namely the client certificate message and client certificate verify message.
pSSL->nNetOutSize += CreateClientKeyExchangeMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
pSSL->eState = SSLSTATE_CLIENT_FINISH1;
break;
case SSLSTATE_CLIENT_KEYEXCHANGE:
pSSL->nNetOutSize += CreateClientKeyExchangeMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
pSSL->eState = SSLSTATE_CLIENT_FINISH1;
break;
case SSLSTATE_CLIENT_FINISH1:
//First send the client ChangeCipherSpec message.
pSSL->nNetOutSize += CreateChangeCipherSpecMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
//Then send the ClientFinished message.
pSSL->nNetOutSize += CreateClientFinishedMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
if (pSSL->eServerCipher == CIPHER_NOTSET)
{
pSSL->eState = SSLSTATE_SERVER_FINISH2;
}
else
{
pSSL->eState = SSLSTATE_HANDSHAKE_DONE;
}
break;
case SSLSTATE_CLIENT_FINISH2:
//First send the client ChangeCipherSpec message.
pSSL->nNetOutSize += CreateChangeCipherSpecMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
//Then send the ClientFinished message.
pSSL->nNetOutSize += CreateClientFinishedMsg(
pSSL,
&(pSSL->netoutMsg[pSSL->nNetOutSize]),
(sizeof(pSSL->netoutMsg) - pSSL->nNetOutSize)
);
pSSL->eState = SSLSTATE_HANDSHAKE_DONE;
break;
case SSLSTATE_HANDSHAKE_DONE:
pSSL->eState = SSLSTATE_CONNECTED;
break;
case SSLSTATE_CONNECTED:
//We are fully connected. Hope to stay that way indefinitely.
break;
case SSLSTATE_ABORT:
//There is an internal error processing the incoming message, so bail out
pParam->eState = pSSL->eState = SSLSTATE_ABORTING;
break;
case SSLSTATE_ABORTING:
//TODO: May need to send an abort message to the server here.
//After the abort message is sent. Set the below state. Application then
//should disconnect the TCP, and change state to SSLSTATE_DISCONNECTED.
pSSL->eState = SSLSTATE_ABORTED;
break;
default:
break;
}
} while (pParam->eState != pSSL->eState);
//Fifth do we have any application data that needs to be sent out?
if ((pParam->nAppInSize > 0) && (NULL != pParam->pAppInData))
{
uint nMsgSize;
//if (pSSL->eState != SSLSTATE_CONNECTED)
if (pSSL->eClientCipher == CIPHER_NOTSET)
{
return SSL_ERROR_NOTREADY;
}
nMsgSize = CreateNetMsg(
pSSL,
CONTENT_APPLICATION_DATA,
pParam->pAppInData,
pParam->nAppInSize
);
if (nMsgSize > 0)
{
//The outgoing message is processed successfully
pParam->nAppInSize = 0;
}
}
//Finally return anything that needs to be returned to the caller.
if (pSSL->nNetOutSize > 0)
{
pParam->pNetOutData = pSSL->netoutMsg;
pParam->nNetOutSize = pSSL->nNetOutSize;
}
if (pSSL->nAppOutSize > 0)
{
pParam->pAppOutData = pSSL->appoutMsg;
pParam->nAppOutSize = pSSL->nAppOutSize;
}
if (gAppMsgSize == 0)
{
//The buffer was Application provided, so dis-own it.
pSSL->appoutMsg = NULL;
pSSL->nAppOutSize = 0;
}
return SSL_OK;
}
/******************************************************************************
* Function: SSL_Cleanup
*
* Description: The cleanup function that should be the last SSL function to be called.
*
* Returns: SSL_OK.
******************************************************************************/
SSL_RESULT SSL_Cleanup()
{
CleanupCerts(NULL);
gfRandom = NULL;
gfFree = NULL;
gfMalloc = NULL;
gSvrMsgSize = 0;
gAppMsgSize = 0;
return SSL_OK;
}
/******************************************************************************
* Function: DigestInit
*
* Description: Initialize the SSL message digests.
*
* Returns: None
******************************************************************************/
void DigestInit
(
SSL* pSSL
)
{
gpCipherSet->md5.Init(&(pSSL->md5Ctx), gpCipherSet->md5.pIData);
gpCipherSet->sha1.Init(&(pSSL->sha1Ctx), gpCipherSet->sha1.pIData);
}
/******************************************************************************
* Function: DigestMsg
*
* Description: Calculate accumulated SSL message digest
*
* Returns: None
******************************************************************************/
void DigestMsg
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgLen
)
{
gpCipherSet->md5.Input(&(pSSL->md5Ctx), pMsg, nMsgLen);
gpCipherSet->sha1.Input(&(pSSL->sha1Ctx), pMsg, nMsgLen);
}
/******************************************************************************
* Function: DigestInit1
*
* Description: Initialize message digest context in pBlock.
*
* Returns: None.
******************************************************************************/
void DigestInit1
(
EBLOCK* pBlock
)
{
gpCipherSet->md5.Init(&(pBlock->md5Hash), gpCipherSet->md5.pIData);
gpCipherSet->sha1.Init(&(pBlock->sha1Hash), gpCipherSet->sha1.pIData);
}
/******************************************************************************
* Function: DigestInit2
*
* Description: Transfer message digest context to pBlock.
*
* Returns: None.
******************************************************************************/
void DigestInit2
(
const SSL* pSSL,
EBLOCK* pBlock
)
{
pBlock->md5Hash = pSSL->md5Ctx;
pBlock->sha1Hash = pSSL->sha1Ctx;
}
/******************************************************************************
* Function: DigestBlock
*
* Description: Calculate the digest of previous digest results.
*
* Returns: None.
******************************************************************************/
void DigestBlock(EBLOCK* pBlock)
{
gpCipherSet->md5.Input(&(pBlock->md5Hash), pBlock->md5Digest, MD5_SIZE);
gpCipherSet->sha1.Input(&(pBlock->sha1Hash), pBlock->sha1Digest, SHA1_SIZE);
}
/******************************************************************************
* Function: DigestMsg2
*
* Description: Calculate message digest on pBlock.
*
* Returns: None.
******************************************************************************/
void DigestMsg2
(
EBLOCK* pBlock,
const uchar* pMsg,
uint nMsgLen
)
{
gpCipherSet->md5.Input(&(pBlock->md5Hash), pMsg, nMsgLen);
gpCipherSet->sha1.Input(&(pBlock->sha1Hash), pMsg, nMsgLen);
}
/******************************************************************************
* Function: DigestPad2
*
* Description: Digest pad bytes. Note number of bytes digested is different
* for MD5 and SHA1
*
* Returns: None
******************************************************************************/
void DigestPad2
(
EBLOCK* pBlock,
const uchar* pPad
)
{
gpCipherSet->md5.Input(&(pBlock->md5Hash), pPad, PADSIZE_MD5);
gpCipherSet->sha1.Input(&(pBlock->sha1Hash), pPad, PADSIZE_SHA);
}
/******************************************************************************
* Function: DigestOut2
*
* Description: Finalize and output the digests in pBlock
*
* Returns:
******************************************************************************/
void DigestOut2(EBLOCK* pBlock)
{
gpCipherSet->md5.Digest(&(pBlock->md5Hash), pBlock->md5Digest);
gpCipherSet->sha1.Digest(&(pBlock->sha1Hash), pBlock->sha1Digest);
}
/******************************************************************************
* Function: ParseServerMsg
*
* Description: Parse the server SSL message
*
* Returns: Number of bytes copied into serverMsg buffer.
******************************************************************************/
uint ParseServerMsg
(
SSL* pSSL,
const uchar* pServerMsg,
uint nMsgLen
)
{
uint nCopied = 0;
uint nParsed = 0;
uchar* pMsg;
int nCopySize = 0;
uchar cContentType, verMajor, verMinor;
uint nContentSize = 0, nMsgSize;
pSSL->eLastError = SSL_OK;
while (((nMsgLen > 0) || (nParsed > 0)) && (pSSL->eLastError == SSL_OK))
{
// First re-align any remainder server message to the beginning
// of buffer pSSL->serverMsg, if there is unaligned message
// data from previous parsing. But do it only when we are ready
// to copy more data from input.
if ((pSSL->serverMsgOff > 0) && (nMsgLen > 0))
{
if ((pSSL->nAppOutSize > 0) && (gAppMsgSize == 0))
{
//Can not memmove because we share a buffer. So can not reset
//pSSL->serverMsgOff to 0, even if pSSL->serverMsgLen is 0.
}
else
{
if (pSSL->serverMsgLen > 0)
{
memmove(
pSSL->serverMsg,
pSSL->serverMsg+pSSL->serverMsgOff,
pSSL->serverMsgLen
);
}
pSSL->serverMsgOff = 0;
}
}
// Second copy what we can from the input buffer into pSSL->serverMsg buffer.
nCopySize = gSvrMsgSize - pSSL->serverMsgLen - pSSL->serverMsgOff;
if (nCopySize > (int)nMsgLen)
{
nCopySize = nMsgLen;
}
if (nCopySize > 0)
{
memcpy(pSSL->serverMsg+pSSL->serverMsgOff+pSSL->serverMsgLen, pServerMsg, nCopySize);
pSSL->serverMsgLen += nCopySize;
pServerMsg += nCopySize;
nCopied += nCopySize;
nMsgLen -= nCopySize;
}
else if (nParsed == 0)
{
// The buffer is totally full or we have nothing more to copy.
// So do not process any more, unless in the last round we have
// just parsed portion of the message.
break;
}
// Third parse the message in pSSL->serverMsg. One at a time.
nParsed = 0;
pMsg = pSSL->serverMsg + pSSL->serverMsgOff;
// The CONTENT_HEADER_LEN = 5 bytes goes like this:
// 1 content type
// 1 major version
// 1 minor version
// 2 content length (MSB LSB)
if (pSSL->serverMsgLen < CONTENT_HEADER_LEN)
{
continue;
}
cContentType = *pMsg++;
verMajor = *pMsg++;
verMinor = *pMsg++;
nContentSize = *pMsg++;
nContentSize <<= 8;
nContentSize += *pMsg++;
if ((verMajor == SSL_VERSION_MAJOR) && (verMinor <= SSL_VERSION_MINOR))
{
// We are OK.
}
else
{
pSSL->eLastError = SSL_ERROR_PARSE;
break;
}
if (pSSL->serverMsgLen < CONTENT_HEADER_LEN + nContentSize)
{
// We do not have the complete message yet.
continue;
}
nMsgSize = nContentSize; //nMsgSize is nContentSize minus the MAC
//If the cipher has been turned on already. Then we need to decrypt
switch (pSSL->eServerCipher)
{
case CIPHER_NOTSET:
//No need to decrypt.
break;
case CIPHER_RSA_RC4_40_MD5:
case CIPHER_RSA_RC4_128_MD5:
case CIPHER_RSA_RC4_128_SHA:
RC4Code(&(pSSL->serverCipher), pMsg, nContentSize);
if (0 == VerifyServerMAC(pSSL, cContentType, pMsg, &nMsgSize))
{
//We are OK.
}
else
{
//Corrupted message. What to do?
pSSL->eLastError = SSL_ERROR_PARSE;
assert(0);
}
break;
default:
//Unsupported cipher.
pSSL->eLastError = SSL_ERROR_PARSE;
assert(0);
break;
}
if (pSSL->eLastError == SSL_OK) //Then do the switch
switch (cContentType)
{
case CONTENT_CHANGECIPHERSPEC:
ParseChangeCipherSpec(pSSL, pMsg, nMsgSize);
break;
case CONTENT_ALERT:
ParseAlertMsg(pSSL, pMsg, nMsgSize);
break;
case CONTENT_HANDSHAKE:
ParseHandshake(pSSL, pMsg, nMsgSize);
break;
case CONTENT_APPLICATION_DATA:
ParseAppData(pSSL, pMsg, nMsgSize);
break;
default:
break;
}
nParsed = CONTENT_HEADER_LEN + nContentSize;
pSSL->serverMsgOff += nParsed;
pSSL->serverMsgLen -= nParsed;
}
// Just for debugging
if( pSSL->serverMsgLen >= gSvrMsgSize )
{
// Buffer not big enough. Need to increase pSSL->serverMsg.
pSSL->eLastError = SSL_ERROR_PARSE;
assert(0);
}
return nCopied;
}
/******************************************************************************
* Function: ParseHandshake
*
* Description: Parse an incoming network message that belongs to CONTENT_HANDSHAKE
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseHandshake
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
uchar cMsgType;
uint nMsgLen;
uint nParsed = 0;
if (nMsgSize < 4)
{
return SSL_ERROR_PARSE;
}
while (nParsed < nMsgSize)
{
uint nParseSize;
const uchar* pHashData;
pHashData = pMsg;
cMsgType = *pMsg++;
nMsgLen = *pMsg++;
nMsgLen <<= 8;
nMsgLen += *pMsg++;
nMsgLen <<= 8;
nMsgLen += *pMsg++;
nParsed += 4;
if ((nParsed + nMsgLen) > nMsgSize)
{
return SSL_ERROR_PARSE;
}
nParseSize = nMsgLen;
switch (cMsgType)
{
case MSG_HELLO_REQUEST:
//Server request a hello message again, so re-start the handshake.
pSSL->eState = SSLSTATE_HANDSHAKE_BEGIN;
break;
case MSG_CLIENT_HELLO:
break;
case MSG_SERVER_HELLO:
nParseSize = ParseServerHello(pSSL, pMsg, nMsgLen);
break;
case MSG_CERTIFICATE:
nParseSize = ParseCertificateMsg(pSSL, pMsg, nMsgLen);
break;
case MSG_SERVER_KEY_EXCHANGE:
break;
case MSG_CERTIFICATE_REQUEST:
nParseSize = ParseCertificateRequest(pSSL, pMsg, nMsgLen);
break;
case MSG_SERVER_HELLO_DONE:
nParseSize = ParseServerHelloDone(pSSL, pMsg, nMsgLen);
break;
case MSG_CERTIFICATE_VERIFY:
break;
case MSG_CLIENT_KEY_EXCHANGE:
break;
case MSG_FINISHED:
if (0 == VerifyServerFinished(pSSL, pMsg, nMsgLen))
{
//ServerFinishedMessage verified OK.
if (pSSL->eState == SSLSTATE_SERVER_FINISH1)
{
pSSL->eState = SSLSTATE_CLIENT_FINISH2;
}
else if (pSSL->eState == SSLSTATE_SERVER_FINISH2)
{
pSSL->eState = SSLSTATE_HANDSHAKE_DONE;
}
else
{
//We are in the wrong state to have received
//the ServerFinished message. What to do?
assert(0);
}
}
else
{
//The serverFinished message mismatch. What to do?
assert(0);
}
break;
}
pMsg += nParseSize;
nParsed += nParseSize;
if (cMsgType == MSG_HELLO_REQUEST)
{
//http://www.ietf.org/rfc/rfc2246.txt
if ((pSSL->preMasterSecret[1] < SSL_VERSION_MINOR1) ||
(SSL_VERSION_MINOR < SSL_VERSION_MINOR1) )
{
//Note in RFC2246 it suggest that hello request message is not included in the handshake hask.
//So probably I should just do a continue here. But not verified yet
//so I comment out the continue here.
//See http://www.ietf.org/rfc/rfc2246.txt
//continue;
}
}
//Hash the handshake content. Hash every handshake message. NOTE
//for the purpose of calculating FinishedMessage, the HandshakeHash
//does not include the FinishedMessage itself. So we have to do
//the HandshakeHash right after we parse the handshake message.
DigestMsg(pSSL, pHashData, (uint)(pMsg-pHashData));
}
return nParsed;
}
/******************************************************************************
* Function: ParseChangeCipherSpec
*
* Description: Parse the Change Cipher Spec message. After this point all
* messages are encrypted.
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseChangeCipherSpec
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
if ((pSSL->preMasterSecret[1] < SSL_VERSION_MINOR1) ||
(SSL_VERSION_MINOR < SSL_VERSION_MINOR1) )
{
CalcKeysFromMaster(pSSL, ISSERVER);
}
else
{
CalcKeysFromMaster1(pSSL, ISSERVER);
}
//From now on any thing from the server is encrypted.
pSSL->eServerCipher = pSSL->ePendingCipher;
//Initialize the server write cipher.
if ((CIPHER_RSA_RC4_40_MD5 == pSSL->eServerCipher) ||
(CIPHER_RSA_RC4_128_MD5 == pSSL->eServerCipher) ||
(CIPHER_RSA_RC4_128_SHA == pSSL->eServerCipher) )
{
RC4Init(
&(pSSL->serverCipher),
pSSL->serverWriteKey,
sizeof(pSSL->serverWriteKey)
);
}
else
{
//Unsupported cipher.
}
//Reset the server write sequence number.
pSSL->serverSequenceL = 0;
pSSL->serverSequenceH = 0;
return nMsgSize;
}
/******************************************************************************
* Function: ParseServerHello
*
* Description: Parse the server hello message.
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseServerHello
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
uint nParsed = 0;
uint nSessionIDLen;
uint nPendingCipher;
uint nCompression;
uchar verMajor, verMinor;
verMajor = *pMsg++;
verMinor = *pMsg++;
nParsed += 2;
pSSL->preMasterSecret[0] = SSL_VERSION_MAJOR;
pSSL->preMasterSecret[1] = (verMinor<SSL_VERSION_MINOR)?verMinor:SSL_VERSION_MINOR;
// First in server hello msg, two bytes of server version.
// Do we require the server to be version 3.0, no more, no less?
// Next 32 bytes (SERVER_RANDOM_SIZE) of ServerRandom.
memcpy(pSSL->serverRandom, pMsg, SERVER_RANDOM_SIZE);
pMsg += SERVER_RANDOM_SIZE;
nParsed += SERVER_RANDOM_SIZE;
// Next byte tells session ID length
nSessionIDLen = (uint)(*pMsg++);
nParsed ++;
if (nSessionIDLen > 0)
{
if ((pSSL->nSessionIDLen == nSessionIDLen) &&
(0 == memcmp(pSSL->sessionID, pMsg, nSessionIDLen)) )
{
//No need to do ClientKeyExchange. We re-use the old
//Pre-Master Secret from the last connection session.
pSSL->eState = SSLSTATE_SERVER_FINISH1;
}
else
{
memcpy(pSSL->sessionID, pMsg, nSessionIDLen);
}
pMsg += nSessionIDLen;
nParsed += nSessionIDLen;
}
pSSL->nSessionIDLen = nSessionIDLen;
// Next two bytes is the pending ciphers.
nPendingCipher = *pMsg++;
nPendingCipher <<= 8;
nPendingCipher += *pMsg++;
//The final byte is Compression. We support only 0, no compression.
nCompression = *pMsg++;
pSSL->ePendingCipher = nPendingCipher;
nParsed += 3;
if (nParsed < nMsgSize)
{
//There are extentions to the message
uint nExtSize0 = 0;
nExtSize0 = *pMsg++;
nExtSize0 <<= 8;
nExtSize0 += *pMsg++;
nParsed += 2;
//Parse the message extention here.
if (nParsed + nExtSize0 <= nMsgSize)
{
uint nExtType = 0;
uint nExtSize = 0;
uint bAbort = FALSE;
nExtType = *pMsg++;
nExtType <<= 8;
nExtType += *pMsg++;
if (nExtType == ((MSG_EXTENTION<<8) | MSG_EXTENTION_RENEGOTIATION))
{
nExtSize = *pMsg++;
nExtSize <<= 8;
nExtSize += *pMsg++;
nExtSize --;
if (nExtSize != *pMsg++)
{
//Malformed extention message.
bAbort = TRUE;
}
else if (nExtSize > 0)
{
if (pSSL->eServerCipher == CIPHER_NOTSET)
{
//Not expecting a non-empty re-negotiation info message.
bAbort = TRUE;
}
else if (memcmp(pSSL->clientVerify, pMsg, (nExtSize>>1)))
{
bAbort = TRUE;
}
else if (memcmp(pSSL->serverVerify, pMsg+(nExtSize>>1), (nExtSize>>1)))
{
bAbort = TRUE;
}
else
{
//The expected renegotiation info message matches. So OK here.
bAbort = FALSE;
}
pMsg += nExtSize;
}
else if (pSSL->eServerCipher != CIPHER_NOTSET)
{
//We do expect a non-empty re-negotiation info message.
bAbort = TRUE;
}
else
{
//We expect an empty renegotiation info message. So OK here.
bAbort = FALSE;
}
}
if (bAbort)
{
//Something wrong with the re-negotiation info message. Bailout.
pSSL->eState = SSLSTATE_ABORT;
}
}
else
{
//Something not quite right here. So just bail out.
pSSL->eState = SSLSTATE_ABORT;
}
nParsed += nExtSize0;
}
//assert(nParsed == nMsgSize); // We should have parsed exactly all the bytes.
return nMsgSize;
}
/******************************************************************************
* Function: ParseServerHelloDone
*
* Description: Parse the server hellow done message.
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseServerHelloDone
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
// Not much to be parsed. Just carry out operations that is needed upon
// the ServerHelloDone.
//Make sure we are expecting a ServerHelloDone at this point.
//Upon receiving a ServerHelloDone, we should verify Server Certificate,
//Generate the client key exchange message and send out.
pSSL->pTemp = NULL; //We set it that we have no client certificate.
if (pSSL->eState == SSLSTATE_SERVER_CERTREQUEST)
{
pSSL->eState = SSLSTATE_CERTIFICATE_REQUEST;
}
else
{
pSSL->eState = SSLSTATE_CERTIFICATE_VERIFY;
}
return nMsgSize;
}
/******************************************************************************
* Function: VerifyServerFinished
*
* Description: Verify that the server finished message is correctly calculated
* thus the key exchange handshake is successful.
*
* Returns: ZERO if no error, else there is an error.
******************************************************************************/
uint VerifyServerFinished
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
uchar serverFinishedMsg[MD5_SIZE+SHA1_SIZE];
uint nMsgLen;
nMsgLen = CreateFinishedMsg(
pSSL,
ISSERVER, //We are constructing a server message
serverFinishedMsg,
sizeof(serverFinishedMsg)
);
return memcmp(pMsg, serverFinishedMsg, (nMsgLen|nMsgSize));
}
/******************************************************************************
* Function: ParseCertificateMsg
*
* Description: Parse the certificate message and extract certificate(s).
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseCertificateMsg
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
uint nParsed = 0;
uint nTotalSize;
uint nCurrentSize;
struct CERT* pCert = NULL;
// We are parsing a possible list of N certificates.
// First 3 bytes tells us the the total size we should be parsing.
//Not including the 3 bytes itself.
nTotalSize = *pMsg++;
nTotalSize<<= 8;
nTotalSize += *pMsg++;
nTotalSize<<= 8;
nTotalSize += *pMsg++;
nParsed += 3;
while (nParsed < nMsgSize)
{
uint nCertParsed;
//Next 3 bytes tells us the size of next certificate to be parsed.
nCurrentSize = *pMsg++;
nCurrentSize<<= 8;
nCurrentSize += *pMsg++;
nCurrentSize<<= 8;
nCurrentSize += *pMsg++;
nParsed += 3;
pCert = CreateCert(CS_UNKNOWN, pSSL->nCurrentTime);
nCertParsed = ParseCert(pCert, pMsg, nCurrentSize);
pMsg += nCurrentSize;
nParsed += nCurrentSize;
//The very first certificate is the server certificate. Anything that follows
//are CA certificates that need to be inserted.
if (pSSL->pServerCert == NULL)
{
pSSL->pServerCert = pCert;
}
else if (NULL == InsertCert(pCert, &(pSSL->pMidCerts)))
{
//Can not insert certificate since it exists already as root.
//So ignore the one coming from the network.
DestroyCert(pCert);
}
}
//We received server certificate so next to come is ServerHelloDone.
pSSL->eState = SSLSTATE_SERVER_HELLO_DONE;
return nParsed;
}
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
extern struct X509NAME gTempCA;
#ifdef __cplusplus
} //extern "C"
#endif //__cplusplus
/******************************************************************************
* Function: ParseCertificateRequest
*
* Description: Parse the certificate request message from the server. This message
* contains information on CAs whose certificates can be accepted.
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseCertificateRequest
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
uint i, nParse, nParsed = 0;
uint nTotalSize;
uint eCipherType;
uint nCipherTypes = 0;
nCipherTypes = *pMsg++; //Number of cipher types. Normally just two.
nParsed ++;
//Then a list of nCipherTypes entry of cipher types, one byte each.
for (i=0; i<nCipherTypes; i++)
{
//The server tells us what cipher types it accepts. For now we just ignore it
//The list is normally just 01 02.
eCipherType = *pMsg++;
nParsed ++;
}
//Then two bytes for total size of the CA list, in bytes.
nTotalSize = *pMsg++;
nTotalSize<<= 8;
nTotalSize += *pMsg++;
nParsed += 2;
while (nParsed < nMsgSize)
{
uint nCASize = 0;
//First the size of the CA Identity
nCASize = *pMsg++;
nCASize <<= 8;
nCASize += *pMsg++;
nParsed += 2;
//Parse each CA Identity. We are supposed to save this information X509NAME caName
//for later use to find the correct client certificate to use. For now ignore it.
nParse = ParseX509ID(&gTempCA, pMsg, nCASize);
//assert(nParse == nCASize);
pMsg += nParse;
nParsed += nParse;
}
//assert(nParsed == nMsgSize); //Make sure we parsed the exact size.
//We received server certificate so next to come is ServerHelloDone.
//We also need to set a flag to indicate we need to get the client certificate.
pSSL->eState = SSLSTATE_SERVER_CERTREQUEST; //Equivalent to SSLSTATE_SERVER_HELLO_DONE
return nParsed;
}
/******************************************************************************
* Function: ParseAppData
*
* Description: Parse incoming network message that is CONTENT_APPLICATION_DATA.
* since the data is not SSL handshake but application data to be
* interpretted by application level code, we simply copy it over.
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseAppData
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
if (pSSL->appoutMsg == NULL)
{
//No buffer. So we share the serverMsg buffer
pSSL->appoutMsg = (uchar*)pMsg;
}
else
{
memmove(
&(pSSL->appoutMsg[pSSL->nAppOutSize]),
pMsg,
nMsgSize
);
}
pSSL->nAppOutSize += nMsgSize;
return nMsgSize;
}
/******************************************************************************
* Function: CreateFinishedMsg
*
* Description: Create the Client Finished or Server Finished message. It can
* be used by both the client and server, depending on the flag.
*
* Returns: Number of bytes of constructed message.
******************************************************************************/
uint CreateFinishedMsg
(
SSL* pSSL,
uint bIsClient, //ISCLIENT=TRUE for Client, ISSERVER=FALSE for Server
uchar* pMsgBuff,
uint nBuffSize
)
{
int i;
uchar* pMsg = pMsgBuff;
MD5 md5Ctx;
SHA shaCtx;
const CIPHER* pMd5 = &(gpCipherSet->md5);
const CIPHER* pSha = &(gpCipherSet->sha1);
md5Ctx = pSSL->md5Ctx;
shaCtx = pSSL->sha1Ctx;
if ((pSSL->preMasterSecret[1] < SSL_VERSION_MINOR1) ||
(SSL_VERSION_MINOR < SSL_VERSION_MINOR1) )
{
//For SSL 3.0
pMd5->Input(&md5Ctx, bIsClient?SENDER_CLIENT:SENDER_SERVER, 4);
pMd5->Input(&md5Ctx, pSSL->masterSecret, sizeof(pSSL->masterSecret));
pMd5->Input(&md5Ctx, PAD1, PADSIZE_MD5);
pMd5->Digest(&md5Ctx, pMsg);
//Md5Init(&md5Ctx);
pMd5->Init(&md5Ctx, pMd5->pIData);
pMd5->Input(&md5Ctx, pSSL->masterSecret, sizeof(pSSL->masterSecret));
pMd5->Input(&md5Ctx, PAD2, PADSIZE_MD5);
pMd5->Input(&md5Ctx, pMsg, MD5_SIZE);
pMd5->Digest(&md5Ctx, pMsg);
//Done with MD5 hash calculation
pMsg += MD5_SIZE;
//Now we calculate the SHA1 Hash for the Finished Message.
pSha->Input(&shaCtx, bIsClient?SENDER_CLIENT:SENDER_SERVER, 4);
pSha->Input(&shaCtx, pSSL->masterSecret, sizeof(pSSL->masterSecret));
pSha->Input(&shaCtx, PAD1, PADSIZE_SHA);
pSha->Digest(&shaCtx, pMsg);
pSha->Input(&shaCtx, pSSL->masterSecret, sizeof(pSSL->masterSecret));
pSha->Input(&shaCtx, PAD2, PADSIZE_SHA);
pSha->Input(&shaCtx, pMsg, SHA1_SIZE);
pSha->Digest(&shaCtx, pMsg);
//Done with SHA1 hash calculation
pMsg += SHA1_SIZE;
}
else
{
//For SSL 3.1
#define pMD5HASH (&(dataBlock[0]))
#define pSHAHASH (&(dataBlock[MD5_SIZE]))
#define pMD5DIGEST (&(dataBlock[MD5_SIZE+SHA1_SIZE]))
#define pSHADIGEST (&(dataBlock[MD5_SIZE*2+SHA1_SIZE]))
const char* pClientLabel = CLIENT_LABEL; //"client finished";
const char* pServerLabel = SERVER_LABEL; //"server finished";
uchar dataBlock[MD5_SIZE*2+SHA1_SIZE*2]; //A worker data
VDATA vectBlocks[5] = {
{(const uchar*)pClientLabel, 15},
{NULL, 0},
{(const uchar*)pClientLabel, 15},
{pMD5DIGEST, MD5_SIZE+SHA1_SIZE},
{NULL, 0}
};
HMAC hMAC;
vectBlocks[0].pData = &(pSSL->masterSecret[0]);
vectBlocks[0].nSize = ((MASTER_SECRET_LEN+1)>>1);
HMAC_InitMD5(&hMAC, dataBlock, &(vectBlocks[0]));
vectBlocks[0].pData = &(pSSL->masterSecret[MASTER_SECRET_LEN>>1]);
vectBlocks[0].nSize = ((MASTER_SECRET_LEN+1)>>1);
HMAC_InitSHA1(&hMAC, dataBlock, &(vectBlocks[0]));
vectBlocks[0].pData = (const uchar*)((bIsClient)?pClientLabel:pServerLabel);
vectBlocks[0].nSize = 15; //strlen(vectBlocks[0].pData);
vectBlocks[2] = vectBlocks[0];
pMd5->Digest(&md5Ctx, pMD5DIGEST);
pSha->Digest(&shaCtx, pSHADIGEST);
//Calculate A(1) for HMAC_MD5 and HMAC_SHA1
HMAC_MD5 (&hMAC, pMD5HASH, &(vectBlocks[2]));
HMAC_SHA1(&hMAC, pSHAHASH, &(vectBlocks[2]));
//Calculate HMAC_MD5(1) and HMAC_SHA1(1)
vectBlocks[1].pData = pMD5HASH;
vectBlocks[1].nSize = MD5_SIZE;
HMAC_MD5 (&hMAC, pMD5HASH, &(vectBlocks[1]));
vectBlocks[1].pData = pSHAHASH;
vectBlocks[1].nSize = SHA1_SIZE;
HMAC_SHA1(&hMAC, pSHAHASH, &(vectBlocks[1]));
for (i=0; i<TLS_VERIFY_LEN; i++)
{
*pMsg++ = pMD5HASH[i] ^ pSHAHASH[i];
}
#undef pSHADIGEST //(&(dataBlock[MD5_SIZE*2+SHA1_SIZE]))
#undef pMD5DIGEST //(&(dataBlock[MD5_SIZE+SHA1_SIZE]))
#undef pSHAHASH //(&(dataBlock[MD5_SIZE]))
#undef pMD5HASH //(&(dataBlock[0]))
}
memcpy((bIsClient)?pSSL->clientVerify:pSSL->serverVerify, pMsgBuff, (pMsg-pMsgBuff));
return (pMsg - pMsgBuff);
}
/******************************************************************************
* Function: CalculateMAC
*
* Description: Calculate the MAC signature based on the state of the SSL engine.
*
* Returns: Size of MAC signature in bytes.
******************************************************************************/
uint CalculateMAC
(
SSL* pSSL,
uint bIsClient, //TRUE for Client, FALSE for Server
uchar* pMac,
uchar cMsgType,
const uchar* pMsg,
uint nMsgSize
)
{
SSL_CIPHER eCipher;
uint nMacSize = MD5_SIZE;
uchar* pMacSecret;
uint nSequenceL, nSequenceH;
uchar* pTemp;
uchar temp[16];
//Get the sequence number, and BTW increment it in pSSL.
if (bIsClient)
{
eCipher = pSSL->eClientCipher;
pMacSecret = pSSL->clientMacSecret;
nSequenceL = pSSL->clientSequenceL;
nSequenceH = pSSL->clientSequenceH;
if ((++(pSSL->clientSequenceL)) == 0)
{
pSSL->clientSequenceH ++;
}
}
else
{
eCipher = pSSL->eServerCipher;
pMacSecret = pSSL->serverMacSecret;
nSequenceL = pSSL->serverSequenceL;
nSequenceH = pSSL->serverSequenceH;
if ((++(pSSL->serverSequenceL)) == 0)
{
pSSL->serverSequenceH ++;
}
}
pTemp = temp;
*pTemp++ = (uchar)(nSequenceH>>24);
*pTemp++ = (uchar)(nSequenceH>>16);
*pTemp++ = (uchar)(nSequenceH>>8);
*pTemp++ = (uchar)(nSequenceH>>0);
*pTemp++ = (uchar)(nSequenceL>>24);
*pTemp++ = (uchar)(nSequenceL>>16);
*pTemp++ = (uchar)(nSequenceL>>8);
*pTemp++ = (uchar)(nSequenceL>>0);
*pTemp++ = cMsgType;
if ((pSSL->preMasterSecret[1] < SSL_VERSION_MINOR1) ||
(SSL_VERSION_MINOR < SSL_VERSION_MINOR1) )
{
//SSL 3.0 has no version info here.
}
else
{
//SSL 3.1 has the version bytes here
*pTemp++ = pSSL->preMasterSecret[0]; //SSL_VERSION_MAJOR;
*pTemp++ = pSSL->preMasterSecret[1]; //SSL_VERSION_MINOR1;
}
*pTemp++ = (uchar)(nMsgSize>>8);
*pTemp++ = (uchar)(nMsgSize>>0);
if ((pSSL->preMasterSecret[1] < SSL_VERSION_MINOR1) ||
(SSL_VERSION_MINOR < SSL_VERSION_MINOR1) )
//For SSL 3.0
switch (eCipher)
{
case CIPHER_RSA_RC4_40_MD5:
case CIPHER_RSA_RC4_128_MD5:
{
MD5 md5Ctx;
const CIPHER* pMd5 = &(gpCipherSet->md5);
nMacSize = MD5_SIZE;
//Md5Init(&md5Ctx);
pMd5->Init(&md5Ctx, pMd5->pIData);
pMd5->Input(&md5Ctx, pMacSecret, MAC_SECRET_LEN);
pMd5->Input(&md5Ctx, PAD1, PADSIZE_MD5);
pMd5->Input(&md5Ctx, temp, (uint)(pTemp-temp));
pMd5->Input(&md5Ctx, pMsg, nMsgSize);
pMd5->Digest(&md5Ctx, pMac);
//Md5Init(&md5Ctx);
pMd5->Init(&md5Ctx, pMd5->pIData);
pMd5->Input(&md5Ctx, pMacSecret, MAC_SECRET_LEN);
pMd5->Input(&md5Ctx, PAD2, PADSIZE_MD5);
pMd5->Input(&md5Ctx, pMac, nMacSize);
pMd5->Digest(&md5Ctx, pMac);
}
break;
case CIPHER_RSA_RC4_128_SHA:
{
SHA shaCtx;
const CIPHER* pSha = &(gpCipherSet->sha1);
nMacSize = SHA1_SIZE;
pSha->Init(&shaCtx, pSha->pIData);
pSha->Input(&shaCtx, pMacSecret, SHA1_SIZE);
pSha->Input(&shaCtx, PAD1, PADSIZE_SHA);
pSha->Input(&shaCtx, temp, (uint)(pTemp-temp));
pSha->Input(&shaCtx, pMsg, nMsgSize);
pSha->Digest(&shaCtx, pMac);
pSha->Init(&shaCtx, pSha->pIData);
pSha->Input(&shaCtx, pMacSecret, SHA1_SIZE);
pSha->Input(&shaCtx, PAD2, PADSIZE_SHA);
pSha->Input(&shaCtx, pMac, nMacSize);
pSha->Digest(&shaCtx, pMac);
}
break;
default:
//Unsupported cipher. Let's assume MAC size same as MD5.
assert(0);
nMacSize = 0;
break;
}
else
{
//For SSL 3.1
uchar hashBlock[BLOCK_LEN];
VDATA vectBlocks[4] = {
{pMacSecret, MAC_SECRET_LEN},
{temp, (uint)(pTemp-temp)},
{pMsg, nMsgSize},
{NULL, 0}
};
HMAC hMac;
switch (eCipher)
{
case CIPHER_RSA_RC4_40_MD5:
case CIPHER_RSA_RC4_128_MD5:
{
nMacSize = MD5_SIZE;
HMAC_InitMD5(&hMac, hashBlock, &(vectBlocks[0]));
HMAC_MD5(&hMac, pMac, &(vectBlocks[1]));
}
break;
case CIPHER_RSA_RC4_128_SHA:
{
nMacSize = SHA1_SIZE;
vectBlocks[0].nSize = SHA1_SIZE;
HMAC_InitSHA1(&hMac, hashBlock, &(vectBlocks[0]));
HMAC_SHA1(&hMac, pMac, &(vectBlocks[1]));
}
break;
default:
//Unsupported cipher. Let's assume MAC size same as MD5.
nMacSize = 0;
break;
}
}
return nMacSize;
}
/******************************************************************************
* Function: EncryptWithMAC
*
* Description: Calculate the MAC, attach to message and then encrypt.
*
* Returns: Bytes of the MAC block attached before encryption.
******************************************************************************/
uint EncryptWithMAC
(
SSL* pSSL,
uint bIsClient,
uchar cContentType,
uchar* pMsg,
uint nMsgSize
)
{
uint nMacSize = MD5_SIZE;
nMacSize = CalculateMAC(
pSSL,
bIsClient,
&(pMsg[nMsgSize]),
cContentType,
pMsg,
nMsgSize
);
//Now we do the encryption, after the MAC is appended.
RC4Code(
(bIsClient)?(&(pSSL->clientCipher)):(&(pSSL->serverCipher)),
pMsg,
nMsgSize+nMacSize
);
return nMacSize;
}
/******************************************************************************
* Function: CreateNetMsg
*
* Description: Package and encrypt an out-going network data package.
*
* Returns: Total size of the package when properly encrypted and packaged.
* ZERO if not enough space to put the package in.
******************************************************************************/
uint CreateNetMsg
(
SSL* pSSL,
uchar cContentType,
const uchar* pData,
uint nDataSize
)
{
uint nLen, nMacSize=MD5_SIZE, nEncryptSize;
uchar* pMsgBuff = &(pSSL->netoutMsg[pSSL->nNetOutSize]);
uchar* pMsg = pMsgBuff;
uchar* pEncryptData;
//Do we have enough space to contain the package?
nLen = 5 + nMacSize + nDataSize;
if ((nLen + pSSL->nNetOutSize) > sizeof(pSSL->netoutMsg))
{
return 0; //Not enough space. No package is added, so return 0.
}
*pMsg++ = cContentType;
*pMsg++ = pSSL->preMasterSecret[0]; //SSL_VERSION_MAJOR;
*pMsg++ = (SSL_VERSION_MINOR<pSSL->preMasterSecret[1])?SSL_VERSION_MINOR:pSSL->preMasterSecret[1];
nEncryptSize = nDataSize + nMacSize;
//This content size may not be correct. Will come back to fill in again.
*pMsg++ = (uchar)(nEncryptSize>>8);
*pMsg++ = (uchar)(nEncryptSize>>0);
//Starting here is data that needs to be encrypted.
pEncryptData = pMsg;
memcpy(pMsg, pData, nDataSize);
pMsg += nDataSize;
//Now calculate the MAC of the message and encrypt.
pMsg += nMacSize = EncryptWithMAC(
pSSL,
TRUE, //For Client
(*pMsgBuff),
pEncryptData,
nDataSize
);
nEncryptSize = nDataSize + nMacSize; //Now we added the size of MAC
pEncryptData[-2] = (uchar)(nEncryptSize>>8);
pEncryptData[-1] = (uchar)(nEncryptSize>>0);
nLen = pMsg - pMsgBuff;
pSSL->nNetOutSize += nLen;
return nLen;
}
/******************************************************************************
* Function: ParseAlertMsg
*
* Description: Parse incoming message that belongs to CONTENT_ALERT.
*
* Returns: Number of bytes parsed.
******************************************************************************/
uint ParseAlertMsg
(
SSL* pSSL,
const uchar* pMsg,
uint nMsgSize
)
{
uchar cCategory, cType;
cCategory = *pMsg++;
cType = *pMsg++;
switch (cType)
{
case ALERT_NOTIFY_CLOSE:
CreateAlertMsg(pSSL, ALERT_WARNING, ALERT_NOTIFY_CLOSE);
pSSL->eState = SSLSTATE_DISCONNECTING;
break;
default:
pSSL->eState = SSLSTATE_DISCONNECTING;
break;
}
return nMsgSize;
}
/******************************************************************************
* Function: CreateAlertMsg
*
* Description: Create a CONTENT_ALERT message.
*
* Returns: Bytes of constructed message.
******************************************************************************/
uint CreateAlertMsg
(
SSL* pSSL,
uchar cCategory,
uchar cType
)
{
uchar msg[2];
msg[0] = cCategory;
msg[1] = cType;
return CreateNetMsg(pSSL, CONTENT_ALERT, msg, sizeof(msg));
}
|
Anthony-Mai/tinySSL
|
src/ssl.c
|
C
|
gpl-3.0
| 64,132
|
#!/usr/bin/env python
# Copyright (C) 2012 nwmaltego Developer.
# This file is part of nwmaltego - https://github.com/bostonlink/nwmaltego
# See the file 'LICENSE' for copying permission.
# Netwitness Threat to Filename Maltego transform
# Author: David Bressler (@bostonlink)
import sys
import urllib2, urllib, json
from datetime import datetime, timedelta
from lib import nwmodule
# Maltego XML Header
trans_header = """<MaltegoMessage>
<MaltegoTransformResponseMessage>
<Entities>"""
# Authenticate to the NW Concentrator via HTTP basic auth
nwmodule.nw_http_auth()
# NW REST API Query amd results
risk_name = sys.argv[1]
fields = sys.argv[2].split('#')
date_t = datetime.today()
tdelta = timedelta(days=1)
diff = date_t - tdelta
diff = "'" + diff.strftime('%Y-%b-%d %H:%M:%S') + "'-'" + date_t.strftime('%Y-%b-%d %H:%M:%S') + "'"
for i in fields:
if 'ip' in i:
parse = i.split('=')
ip = parse[1]
where_clause = '(time=%s) && risk.warning="%s" && ip.src=%s || ip.dst=%s' % (diff, risk_name, ip, ip)
else:
where_clause = '(time=%s) && risk.warning="%s"' % (diff, risk_name)
field_name = 'attachment'
json_data = json.loads(nwmodule.nwValue(0, 0, 25, field_name, 'application/json', where_clause))
file_list = []
# Print the Maltego XML Header
print trans_header
for d in json_data['results']['fields']:
value = d['value'].decode('ascii')
if value in file_list:
continue
elif value == "<none>":
pass
else:
# Kind of a hack but hey it works!
print """ <Entity Type="netwitness.NWFilename">
<Value>%s</Value>
<AdditionalFields>
<Field Name="risk" DisplayName="Threat Name">%s</Field>
<Field Name="ip" DisplayName="IP Address">%s</Field>
<Field Name="metaid1" DisplayName="Meta id1">%s</Field>
<Field Name="metaid2" DisplayName="Meta id2">%s</Field>
<Field Name="type" DisplayName="Type">%s</Field>
<Field Name="count" DisplayName="Count">%s</Field>
</AdditionalFields>
</Entity>""" % (value, risk_name, ip, d['id1'], d['id2'], d['type'], d['count'])
file_list.append(value)
# Maltego transform XML footer
trans_footer = """ </Entities>
</MaltegoTransformResponseMessage>
</MaltegoMessage> """
print trans_footer
|
bostonlink/nwmaltego
|
nw_threat_2_file_attachment.py
|
Python
|
gpl-3.0
| 2,405
|
/*
* SPDX-License-Identifier: GPL-3.0
*
*
* (J)ava (M)iscellaneous (U)tilities (L)ibrary
*
* JMUL is a central repository for utilities which are used in my
* other public and private repositories.
*
* Copyright (C) 2013 Kristian Kutin
*
* 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/>.
*
* e-mail: kristian.kutin@arcor.de
*/
/*
* This section contains meta informations.
*
* $Id$
*/
package jmul.external;
import jmul.logging.Logger;
/**
* This class monitors an external process.
*
* @author Kristian Kutin
*/
public class ProcessMonitor {
/**
* A reference to an external process.
*/
private Process process;
/**
* A reference to a logger.
*/
private Logger logger;
/**
* A monitor for the standard output of the process.
*/
private InputStreamMonitor outputStreamMonitor;
/**
* A monitor for the error output of the process.
*/
private InputStreamMonitor errorStreamMonitor;
/**
* Creates a new instance according to the specified parameters.
*
* @param aProcess
* an external process
*/
ProcessMonitor(Process aProcess) {
this(aProcess, null);
}
/**
* Creates a new instance according to the specified parameters.
*
* @param aProcess
* an external process
* @param aLogger
* a reference to a logger
*/
ProcessMonitor(Process aProcess, Logger aLogger) {
super();
process = aProcess;
logger = aLogger;
outputStreamMonitor = new InputStreamMonitor(process.getInputStream(), logger);
errorStreamMonitor = new InputStreamMonitor(process.getErrorStream(), logger);
Thread t1 = new Thread(outputStreamMonitor);
Thread t2 = new Thread(errorStreamMonitor);
t1.start();
t2.start();
}
/**
* Returns the standard output of the external process.
*
* @return the standard output
*/
public String getOutputMessage() {
return outputStreamMonitor.getStreamContent();
}
/**
* Returns the error output of the external process.
*
* @return the error output
*/
public String getErrorMessage() {
return errorStreamMonitor.getStreamContent();
}
/**
* Checks if the console output (i.e. standard output and error output) is
* complete.
*
* @return <code>true</code> if both streams could be read, else <code>false</code>
*/
public boolean isCompleteOutput() {
return outputStreamMonitor.reachedEndOfStream() && errorStreamMonitor.reachedEndOfStream();
}
}
|
gammalgris/jmul
|
Utilities/External/src/jmul/external/ProcessMonitor.java
|
Java
|
gpl-3.0
| 3,265
|
/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (W) 2015 Wu Lin
* All rights reserved.
*
* 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 BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
*/
#ifdef USE_GPL_SHOGUN
#include <shogun/lib/config.h>
#ifdef HAVE_NLOPT
#ifndef NLOPTMINIMIZER_UNITTEST_H
#define NLOPTMINIMIZER_UNITTEST_H
#include <shogun/optimization/FirstOrderBoundConstraintsCostFunction.h>
#include <shogun/optimization/NLOPTMinimizer.h>
using namespace shogun;
class CPiecewiseQuadraticObject2;
class NLOPTTestCostFunction: public FirstOrderBoundConstraintsCostFunction
{
public:
NLOPTTestCostFunction();
virtual ~NLOPTTestCostFunction();
void set_target(CPiecewiseQuadraticObject2 *obj);
virtual float64_t get_cost();
virtual SGVector<float64_t> obtain_variable_reference();
virtual SGVector<float64_t> get_gradient();
virtual SGVector<float64_t> get_lower_bound();
virtual SGVector<float64_t> get_upper_bound();
private:
void init();
CPiecewiseQuadraticObject2 *m_obj;
};
class CPiecewiseQuadraticObject2: public CSGObject
{
friend class NLOPTTestCostFunction;
public:
CPiecewiseQuadraticObject2();
virtual ~CPiecewiseQuadraticObject2();
void set_init_x(SGVector<float64_t> init_x);
void set_truth_x(SGVector<float64_t> truth_x);
void set_x_lower_bound(float64_t lower_bound){m_x_lower_bound=lower_bound;}
void set_x_upper_bound(float64_t upper_bound){m_x_upper_bound=upper_bound;}
float64_t get_value();
virtual const char* get_name() const {return "PiecewiseQuadraticObject";}
private:
SGVector<float64_t> get_gradient(TParameter * param);
SGVector<float64_t> get_variable(TParameter * param);
SGVector<float64_t> get_upper_bound(TParameter * param);
SGVector<float64_t> get_lower_bound(TParameter * param);
void init();
SGVector<float64_t> m_init_x;
SGVector<float64_t> m_truth_x;
float64_t m_x_lower_bound;
float64_t m_x_upper_bound;
};
#endif /* NLOPTMINIMIZER_UNITTEST_H */
#endif /* HAVE_NLOPT */
#endif //USE_GPL_SHOGUN
|
curiousguy13/shogun
|
tests/unit/optimization/NLOPTMinimizer_unittest.h
|
C
|
gpl-3.0
| 3,436
|
<?php
include("header.php");
include("problem_category_init.php");
foreach ($key as $name => $id) {
if (mysql_num_rows(mysql_query("select id from category where name='".convert_str($name)."'"))==0) {
mysql_query("insert into category set name='".convert_str($name)."', id='$id', parent='".$fa[$name]."'");
}
}
include("simple_html_dom.php");
$html=file_get_html("http://acm.timus.ru/problemset.aspx");
$ta=$html->find("a");
foreach ($ta as $a) {
set_time_limit(20);
if (strstr($a->href,"problemset.aspx?space=1&tag=")==null||strstr($a->plaintext,"Problems")==null) continue;
echo $a->plaintext."<br />";
if (strstr($a->plaintext,"for Beginners")) $cat=$key["Beginner"];
else $cat=$key[$map[strstr($a->plaintext," Problems",true)]];
$html=file_get_html("http://acm.timus.ru/".html_entity_decode($a->href));
//echo "http://acm.timus.ru/".html_entity_decode($a->href);die();
$rows=$html->find("table.problemset tr");
for ($i=1;$i<sizeof($rows);$i++) {
$id=$rows[$i]->find("td",1)->plaintext;
list($pid)=mysql_fetch_array(mysql_query("select pid from problem where vname='URAL' and vid='$id'"));
$g=$cat;
while ($g!=-1) {
if (mysql_num_rows(mysql_query("select pcid from problem_category where pid='$pid' and catid='$g'"))==0) {
mysql_query("insert into problem_category set pid='$pid', catid='$g'");
}
$g=$fa[$g];
}
}
}
include("footer.php");
?>
|
51isoft/bnuoj-web-v1
|
crawler/problem_category_ural.php
|
PHP
|
gpl-3.0
| 1,500
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_30) on Wed Dec 12 05:23:57 UTC 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByteOrShort (Commons Imaging 1.0-SNAPSHOT API)
</TITLE>
<META NAME="date" CONTENT="2012-12-12">
<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 Class org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByteOrShort (Commons Imaging 1.0-SNAPSHOT API)";
}
}
</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/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos"><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/commons/imaging/formats/tiff/taginfos//class-useTagInfoByteOrShort.html" target="_top"><B>FRAMES</B></A>
<A HREF="TagInfoByteOrShort.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 Class<br>org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByteOrShort</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/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.commons.imaging.formats.tiff.constants"><B>org.apache.commons.imaging.formats.tiff.constants</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.commons.imaging.formats.tiff.write"><B>org.apache.commons.imaging.formats.tiff.write</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.commons.imaging.formats.tiff.constants"><!-- --></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/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A> in <A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/constants/package-summary.html">org.apache.commons.imaging.formats.tiff.constants</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">Fields in <A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/constants/package-summary.html">org.apache.commons.imaging.formats.tiff.constants</A> declared as <A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A></CODE></FONT></TD>
<TD><CODE><B>TiffTagConstants.</B><B><A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/constants/TiffTagConstants.html#TIFF_TAG_DOT_RANGE">TIFF_TAG_DOT_RANGE</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.commons.imaging.formats.tiff.write"><!-- --></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/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A> in <A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/write/package-summary.html">org.apache.commons.imaging.formats.tiff.write</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/commons/imaging/formats/tiff/write/package-summary.html">org.apache.commons.imaging.formats.tiff.write</A> with parameters of type <A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>TiffOutputDirectory.</B><B><A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/write/TiffOutputDirectory.html#add(org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByteOrShort, byte...)">add</A></B>(<A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A> tagInfo,
byte... values)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>TiffOutputDirectory.</B><B><A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/write/TiffOutputDirectory.html#add(org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByteOrShort, short...)">add</A></B>(<A HREF="../../../../../../../../org/apache/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos">TagInfoByteOrShort</A> tagInfo,
short... values)</CODE>
<BR>
</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/commons/imaging/formats/tiff/taginfos/TagInfoByteOrShort.html" title="class in org.apache.commons.imaging.formats.tiff.taginfos"><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/commons/imaging/formats/tiff/taginfos//class-useTagInfoByteOrShort.html" target="_top"><B>FRAMES</B></A>
<A HREF="TagInfoByteOrShort.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>
Copyright © 2007-2012 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
|
Diptychon/Diptychon
|
src/Diptychon/lib/apache_imaging/apidocs/org/apache/commons/imaging/formats/tiff/taginfos/class-use/TagInfoByteOrShort.html
|
HTML
|
gpl-3.0
| 11,796
|
#!/bin/bash
# Copyright (C) 2017 bsmelo.io
#
# This file is subject to the terms and conditions of the GNU General
# Public License v3.0. See the file LICENSE in the top level directory
# for more details.
# Dependencies: smartctl, grep, dd, ifind, ffind, debugfs, shred, awk
FS_TYPE="ext4" # "NTFS" or "ext4"
STARTING_BLOCK=16001024 # From `sudo fdisk -lu /dev/sda`
DEVICE="/dev/sda" # Target Physical Device
FS_DEVICE="/dev/sda2" # Target File System
AUTO_INODE="NOOOONE" # Known bad inode (useful for big files spanning multiple bad sectors)
# We assume a Block Size of 4086 bytes and a Sector of 512 bytes
run_dd_ntfs ()
{
(set -x; sudo dd seek="$1" count=1 oflag=direct if=/dev/zero of="${DEVICE}")
sudo sync
echo
echo
}
run_dd_ext3 ()
{
(set -x; sudo dd if=/dev/zero of="${FS_DEVICE}" bs=4096 count=1 seek="$1")
sudo sync
echo
echo
}
b=$((($1-${STARTING_BLOCK})/8))
echo "Block is ${b}"
if [ "${FS_TYPE}" == "NTFS" ]; then
inode=$(sudo ifind -d $b "${FS_DEVICE}")
echo "Inode is ${inode}"
if [[ $inode == "${AUTO_INODE}" ]]; then
echo "Auto"
run_dd_ntfs $1
else
fname=$(sudo ffind "${FS_DEVICE}" $inode)
echo "File is ${fname}"
read -r -p "Should we delete this block? " response
if [[ $response == "y" ]]
then
run_dd_ntfs $1
fi
fi
elif [ "${FS_TYPE}" == "ext4" ]; then
output=$(set -x; sudo debugfs -R "testb ${b}" "${FS_DEVICE}")
if [[ $output == *"not in use"* ]]; then
echo "Block is not in use"
read -r -p "Should we delete this block? " response
if [[ $response == "y" ]]
then
run_dd_ext3 $b
fi
exit 0
fi
inode=$(set -x; sudo debugfs -R "icheck ${b}" "${FS_DEVICE}" | awk 'NR == 2 {print $2}')
echo "Inode is ${inode}"
if [[ $inode == "${AUTO_INODE}" ]]; then
echo "Auto"
run_dd_ext3 $b
else
fname=$(set -x; sudo debugfs -R "ncheck ${inode}" "${FS_DEVICE}" | awk 'NR == 2 { s = ""; for (i = 2; i <= NF; i++) s = s $i " "; print s }')
echo "File is ${fname}"
read -r -p "Should we delete this block? " response
if [[ $response == "y" ]]
then
run_dd_ext3 $b
else
read -r -p "Should we shred this file? " response
if [[ $response == "y" ]]
then
(set -x; shred --iterations=2 --remove "${fname}")
fi
fi
fi
else
echo "Unsupported File System type"
exit 1
fi
|
bsmelo/badblocks
|
fixall.sh
|
Shell
|
gpl-3.0
| 2,609
|
<?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/>.
/**
* Theme tester tool
*
* @package tool_themetester
* @copyright Copyright (c) 2015 Moodlerooms Inc. (http://www.moodlerooms.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(__FILE__) . '/../../../../../../../config.php');
require_once($CFG->libdir . '/adminlib.php');
$strheading = 'Theme Tester: Bootstrap 4 CSS : Webpack';
$url = new moodle_url('/admin/tool/themetester/bootswatch4.php');
// Start setting up the page.
$params = array();
$PAGE->set_context(context_system::instance());
$PAGE->set_url($url);
$PAGE->set_title($strheading);
$PAGE->set_heading("Webpack");
$PAGE->requires->jquery();
$PAGE->requires->css('/admin/tool/themetester/docsearch.min.css');
$PAGE->requires->css('/admin/tool/themetester/assets/css/docs.min.css');
admin_externalpage_setup('toolthemetester');
echo $OUTPUT->header();
echo html_writer::link(new moodle_url('/admin/tool/themetester/index.php'), '« Back to index');
echo $OUTPUT->heading($strheading);
?>
<!-- Favicons -->
<link rel="apple-touch-icon" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/img/favicons/safari-pinned-tab.svg" color="#563d7c">
<link rel="icon" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/favicon.ico">
<meta name="msapplication-config" content="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/img/favicons/browserconfig.xml">
<meta name="theme-color" content="#563d7c">
<!-- Twitter -->
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@getbootstrap">
<meta name="twitter:creator" content="@getbootstrap">
<meta name="twitter:title" content="Webpack">
<meta name="twitter:description" content="Learn how to include Bootstrap in your project using Webpack 3.">
<meta name="twitter:image" content="/assets/brand/bootstrap-social-logo.png">
<!-- Facebook -->
<meta property="og:url" content="/docs/4.0/getting-started/webpack/">
<meta property="og:title" content="Webpack">
<meta property="og:description" content="Learn how to include Bootstrap in your project using Webpack 3.">
<meta property="og:type" content="website">
<meta property="og:image" content="/assets/brand/bootstrap-social.png">
<meta property="og:image:secure_url" content="/assets/brand/bootstrap-social.png">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<div class="container-fluid">
<div class="row flex-xl-nowrap">
<div class="col-12 col-md-3 col-xl-2 bd-sidebar">
<form class="bd-search d-flex align-items-center">
<input type="search" class="form-control" id="search-input" placeholder="Search..." aria-label="Search for..." autocomplete="off">
<button class="btn btn-link bd-search-docs-toggle d-md-none p-0 ml-3" type="button" data-toggle="collapse" data-target="#bd-docs-nav" aria-controls="bd-docs-nav" aria-expanded="false" aria-label="Toggle docs navigation"><svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30" width="30" height="30" focusable="false"><title>Menu</title><path stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" d="M4 7h22M4 15h22M4 23h22"/></svg>
</button>
</form>
<nav class="collapse bd-links" id="bd-docs-nav"><div class="bd-toc-item active">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/introduction/">
Getting started
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/introduction/">
Introduction
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/download/">
Download
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/contents/">
Contents
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/browsers-devices/">
Browsers & devices
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/javascript/">
JavaScript
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/theming/">
Theming
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/build-tools/">
Build tools
</a></li><li class="active bd-sidenav-active">
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/webpack/">
Webpack
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/accessibility/">
Accessibility
</a></li></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/layout/overview/">
Layout
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/layout/overview/">
Overview
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/layout/grid/">
Grid
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/layout/media-object/">
Media object
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/layout/utilities-for-layout/">
Utilities for layout
</a></li></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/reboot/">
Content
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/reboot/">
Reboot
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/typography/">
Typography
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/code/">
Code
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/images/">
Images
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/tables/">
Tables
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/content/figures/">
Figures
</a></li></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/alerts/">
Components
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/alerts/">
Alerts
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/badge/">
Badge
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/breadcrumb/">
Breadcrumb
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/buttons/">
Buttons
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/button-group/">
Button group
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/card/">
Card
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/carousel/">
Carousel
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/collapse/">
Collapse
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/dropdowns/">
Dropdowns
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/forms/">
Forms
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/input-group/">
Input group
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/jumbotron/">
Jumbotron
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/list-group/">
List group
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/modal/">
Modal
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/navs/">
Navs
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/navbar/">
Navbar
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/pagination/">
Pagination
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/popovers/">
Popovers
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/progress/">
Progress
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/scrollspy/">
Scrollspy
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/components/tooltips/">
Tooltips
</a></li></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/borders/">
Utilities
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/borders/">
Borders
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/clearfix/">
Clearfix
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/close-icon/">
Close icon
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/colors/">
Colors
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/display/">
Display
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/embed/">
Embed
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/flex/">
Flex
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/float/">
Float
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/image-replacement/">
Image replacement
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/position/">
Position
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/screenreaders/">
Screenreaders
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/sizing/">
Sizing
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/spacing/">
Spacing
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/text/">
Text
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/vertical-align/">
Vertical align
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/utilities/visibility/">
Visibility
</a></li></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/extend/approach/">
Extend
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/extend/approach/">
Approach
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/extend/icons/">
Icons
</a></li></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/migration/">
Migration
</a>
<ul class="nav bd-sidenav"></ul>
</div><div class="bd-toc-item">
<a class="bd-toc-link" href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/about/overview/">
About
</a>
<ul class="nav bd-sidenav"><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/about/overview/">
Overview
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/about/brand/">
Brand
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/about/license/">
License
</a></li><li>
<a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/about/translations/">
Translations
</a></li></ul>
</div></nav>
</div>
<div class="d-none d-xl-block col-xl-2 bd-toc">
<ul class="section-nav">
<li class="toc-entry toc-h2"><a href="#installing-bootstrap">Installing Bootstrap</a></li>
<li class="toc-entry toc-h2"><a href="#importing-javascript">Importing JavaScript</a></li>
<li class="toc-entry toc-h2"><a href="#importing-styles">Importing Styles</a>
<ul>
<li class="toc-entry toc-h3"><a href="#importing-precompiled-sass">Importing Precompiled Sass</a></li>
<li class="toc-entry toc-h3"><a href="#importing-compiled-css">Importing Compiled CSS</a></li>
</ul>
</li>
</ul>
</div>
<main class="col-12 col-md-9 col-xl-8 py-md-3 pl-md-5 bd-content" role="main">
<h1 class="bd-title" id="content">Webpack</h1>
<p class="bd-lead">Learn how to include Bootstrap in your project using Webpack 3.</p>
<h2 id="installing-bootstrap">Installing Bootstrap</h2>
<p><a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/download/#npm">Install bootstrap</a> as a Node.js module using npm.</p>
<h2 id="importing-javascript">Importing JavaScript</h2>
<p>Import <a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/javascript/">Bootstrap’s JavaScript</a> by adding this line to your app’s entry point (usually <code class="highlighter-rouge">index.js</code> or <code class="highlighter-rouge">app.js</code>):</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="k">import</span> <span class="s1">'bootstrap'</span><span class="p">;</span></code></pre></figure>
<p>Alternatively, you may <strong>import plugins individually</strong> as needed:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="k">import</span> <span class="s1">'bootstrap/js/dist/util'</span><span class="p">;</span>
<span class="k">import</span> <span class="s1">'bootstrap/js/dist/dropdown'</span><span class="p">;</span>
<span class="p">...</span></code></pre></figure>
<p>Bootstrap is dependent on <a href="https://jquery.com/">jQuery</a> and <a href="https://popper.js.org/">Popper</a>,
these are defined as <code class="highlighter-rouge">peerDependencies</code>, this means that you will have to make sure to add both of them
to your <code class="highlighter-rouge">package.json</code> using <code class="highlighter-rouge">npm install --save jquery popper.js</code>.</p>
<div class="bd-callout bd-callout-warning">
<p>Notice that if you chose to <strong>import plugins individually</strong>, you must also install <a href="https://github.com/webpack-contrib/exports-loader">exports-loader</a></p>
</div>
<h2 id="importing-styles">Importing Styles</h2>
<h3 id="importing-precompiled-sass">Importing Precompiled Sass</h3>
<p>To enjoy the full potential of Bootstrap and customize it to your needs, use the source files as a part of your project’s bundling process.</p>
<p>First, create your own <code class="highlighter-rouge">_custom.scss</code> and use it to override the <a href="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/docs/4.0/getting-started/options/">built-in custom variables</a>. Then, use your main sass file to import your custom variables, followed by Bootstrap:</p>
<figure class="highlight"><pre><code class="language-scss" data-lang="scss"><span class="k">@import</span> <span class="s2">"custom"</span><span class="p">;</span>
<span class="k">@import</span> <span class="s2">"~bootstrap/scss/bootstrap"</span><span class="p">;</span></code></pre></figure>
<p>For Bootstrap to compile, make sure you install and use the required loaders: <a href="https://github.com/webpack-contrib/sass-loader">sass-loader</a>, <a href="https://github.com/postcss/postcss-loader">postcss-loader</a> with <a href="https://github.com/postcss/autoprefixer#webpack">Autoprefixer</a>. With minimal setup, your webpack config should include this rule or similar:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"> <span class="p">...</span>
<span class="p">{</span>
<span class="nl">test</span><span class="p">:</span> <span class="sr">/</span><span class="se">\.(</span><span class="sr">scss</span><span class="se">)</span><span class="sr">$/</span><span class="p">,</span>
<span class="nx">use</span><span class="p">:</span> <span class="p">[{</span>
<span class="na">loader</span><span class="p">:</span> <span class="s1">'style-loader'</span><span class="p">,</span> <span class="c1">// inject CSS to page</span>
<span class="p">},</span> <span class="p">{</span>
<span class="na">loader</span><span class="p">:</span> <span class="s1">'css-loader'</span><span class="p">,</span> <span class="c1">// translates CSS into CommonJS modules</span>
<span class="p">},</span> <span class="p">{</span>
<span class="na">loader</span><span class="p">:</span> <span class="s1">'postcss-loader'</span><span class="p">,</span> <span class="c1">// Run post css actions</span>
<span class="na">options</span><span class="p">:</span> <span class="p">{</span>
<span class="na">plugins</span><span class="p">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> <span class="c1">// post css plugins, can be exported to postcss.config.js</span>
<span class="k">return</span> <span class="p">[</span>
<span class="nx">require</span><span class="p">(</span><span class="s1">'precss'</span><span class="p">),</span>
<span class="nx">require</span><span class="p">(</span><span class="s1">'autoprefixer'</span><span class="p">)</span>
<span class="p">];</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">},</span> <span class="p">{</span>
<span class="na">loader</span><span class="p">:</span> <span class="s1">'sass-loader'</span> <span class="c1">// compiles Sass to CSS</span>
<span class="p">}]</span>
<span class="p">},</span>
<span class="p">...</span></code></pre></figure>
<h3 id="importing-compiled-css">Importing Compiled CSS</h3>
<p>Alternatively, you may use Bootstrap’s ready-to-use css by simply adding this line to your project’s entry point:</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"><span class="k">import</span> <span class="s1">'bootstrap/dist/css/bootstrap.min.css'</span><span class="p">;</span></code></pre></figure>
<p>In this case you may use your existing rule for <code class="highlighter-rouge">css</code> without any special modifications to webpack config except you don’t need <code class="highlighter-rouge">sass-loader</code> just <a href="https://github.com/webpack-contrib/style-loader">style-loader</a> and <a href="https://github.com/webpack-contrib/css-loader">css-loader</a>.</p>
<figure class="highlight"><pre><code class="language-js" data-lang="js"> <span class="p">...</span>
<span class="nx">module</span><span class="p">:</span> <span class="p">{</span>
<span class="nl">rules</span><span class="p">:</span> <span class="p">[</span>
<span class="p">{</span>
<span class="na">test</span><span class="p">:</span> <span class="sr">/</span><span class="se">\.</span><span class="sr">css$/</span><span class="p">,</span>
<span class="na">use</span><span class="p">:</span> <span class="p">[</span><span class="s1">'style-loader'</span><span class="p">,</span> <span class="s1">'css-loader'</span><span class="p">]</span>
<span class="p">}</span>
<span class="p">]</span>
<span class="p">}</span>
<span class="p">...</span></code></pre></figure>
</main>
</div>
</div>
<script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/vendor/popper.min.js"></script><script src="https://cdn.jsdelivr.net/npm/docsearch.js@2/dist/cdn/docsearch.min.js"></script><script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/vendor/anchor.min.js"></script>
<script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/vendor/clipboard.min.js"></script>
<script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/vendor/holder.min.js"></script>
<script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/src/application.js"></script>
<script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/src/ie-emulation-modes-warning.js"></script>
<script src="<?php echo $CFG->wwwroot ?>/admin/tool/themetester/assets/js/src/pwa.js"></script>
</body>
</html>
|
davidscotson/moodle-tool_themetester
|
docs/4.0/getting-started/webpack/index.php
|
PHP
|
gpl-3.0
| 24,418
|
//
// MultiArp - Another step in the Great Midi Adventure!
// Copyright (C) 2017, 2018 Barry Neilsen
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
//////////////////////////////////////////////////////////////////////////////
#include "maNotes.h"
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include "maUtility.h"
using namespace std;
unordered_map<int, string> mapNumbersToNotes =
{
{-1, ""},
{0, "C"},
{1, "C#"},
{2, "D"},
{3, "Eb"},
{4, "E"},
{5, "F"},
{6, "Gb"},
{7, "G"},
{8, "Ab"},
{9, "A"},
{10, "Bb"},
{11, "B"},
};
unordered_map<string, int> mapNotesToNumbers =
{
{"R", -1}, {"Rest", -1}, {"-", -1},
{"B#0", 0},{"C0", 0},
{"C#0", 1},{"Db0", 1},
{"D0", 2},
{"D#0", 3},{"Eb0", 3},
{"E0", 4},{"Fb0", 4},
{"E#0", 5},{"F0", 5},
{"F#0", 6},{"Gb0", 6},
{"G0", 7},
{"G#0", 8},{"Ab0", 8},
{"A0", 9},
{"A#0", 10},{"Bb0", 10},
{"B0", 11},{"Cb0", 11},
{"B#1", 12},{"C1", 12},
{"C#1", 13},{"Db1", 13},
{"D1", 14},
{"D#1", 15},{"Eb1", 15},
{"E1", 16},{"Fb1", 16},
{"E#1", 17},{"F1", 17},
{"F#1", 18},{"Gb1", 18},
{"G1", 19},
{"G#1", 20},{"Ab1", 20},
{"A1", 21},
{"A#1", 22},{"Bb1", 22},
{"B1", 23},{"Cb1", 23},
{"B#2", 24},{"C2", 24},
{"C#2", 25},{"Db2", 25},
{"D2", 26},
{"D#2", 27},{"Eb2", 27},
{"E2", 28},{"Fb2", 28},
{"E#2", 29},{"F2", 29},
{"F#2", 30},{"Gb2", 30},
{"G2", 31},
{"G#2", 32},{"Ab2", 32},
{"A2", 33},
{"A#2", 34},{"Bb2", 35},
{"B2", 35},{"Cb2", 35},
{"B#3", 36},{"C3", 36},
{"C#3", 37},{"Db3", 37},
{"D3", 38},
{"D#3", 39},{"Eb3", 39},
{"E3", 40},{"Fb3", 40},
{"E#3", 41},{"F3", 41},
{"F#3", 42},{"Gb3", 42},
{"G3", 43},
{"G#3", 44},{"Ab3", 44},
{"A3", 45},
{"A#3", 46},{"Bb3", 46},
{"B3", 47},{"Cb3", 47},
{"B#4", 48},{"C4", 48},
{"C#4", 49},{"Db4", 49},
{"D4", 50},
{"D#4", 51},{"Eb4", 51},
{"E4", 52},{"Fb4", 52},
{"E#4", 53},{"F4", 53},
{"F#4", 54},{"Gb4", 54},
{"G4", 55},
{"G#4", 56},{"Ab4", 56},
{"A4", 57},
{"A#4", 58},{"Bb4", 58},
{"B4", 59},{"Cb4", 59},
{"B#5", 60},{"C5", 60},
{"C#5", 61},{"Db5", 61},
{"D5", 62},
{"D#5", 63},{"Eb5", 63},
{"E5", 64},{"Fb5", 64},
{"E#5", 65},{"F5", 65},
{"F#5", 66},{"Gb5", 66},
{"G5", 67},
{"G#5", 68},{"Ab5", 68},
{"A5", 69},
{"A#5", 70},{"Bb5", 70},
{"B5", 71},{"Cb5", 71},
// Note names without numbers default to middle octave
{"C", 60},
{"C#", 61},{"Db", 61},
{"D", 62},
{"D#", 63},{"Eb", 63},
{"E", 64},{"Fb", 64},
{"E#", 65},{"F", 65},
{"F#", 66},{"Gb", 66},
{"G", 67},
{"G#", 68},{"Ab", 68},
{"A", 69},
{"A#", 70},{"Bb", 70},
{"B", 71},{"Cb", 71},
{"B#6", 72},{"C6", 72},
{"C#6", 73},{"Db6", 73},
{"D6", 74},
{"D#6", 75},{"Eb6", 75},
{"E6", 76},{"Fb6", 76},
{"E#6", 77},{"F6", 77},
{"F#6", 78},{"Gb6", 78},
{"G6", 79},
{"G#6", 80},{"Ab6", 80},
{"A6", 81},
{"A#6", 82},{"Bb6", 82},
{"B6", 83},{"Cb6", 83},
{"B#7", 84},{"C7", 84},
{"C#7", 85},{"Db7", 85},
{"D7", 86},
{"D#7", 87},{"Eb7", 87},
{"E7", 88},{"Fb7", 88},
{"E#7", 89},{"F7", 89},
{"F#7", 90},{"Gb7", 90},
{"G7", 91},
{"G#7", 92},{"Ab7", 92},
{"A7", 93},
{"A#7", 94},{"Bb7", 94},
{"B7", 95},{"Cb7", 95},
{"B#8", 96},{"C8", 96},
{"C#8", 97},{"Db8", 97},
{"D8", 98},
{"D#8", 99},{"Eb8", 99},
{"E8", 100},{"Fb8", 100},
{"E#8", 101},{"F8", 101},
{"F#8", 102},{"Gb8", 102},
{"G8", 103},
{"G#8", 104},{"Ab8", 104},
{"A8", 105},
{"A#8", 106},{"Bb8", 106},
{"B8", 107},{"Cb8", 107},
{"B#9", 108},{"C9", 108},
{"C#9", 109},{"Db9", 109},
{"D9", 110},
{"D#9", 111},{"Eb9", 111},
{"E9", 112},{"Fb9", 112},
{"E#9", 113},{"F9", 113},
{"F#9", 114},{"Gb9", 114},
{"G9", 115},
{"G#9", 116},{"Ab9", 116},
{"A9", 117},
{"A#9", 118},{"Bb9", 118},
{"B9", 119},{"Cb9", 119},
{"B#10", 120},{"C10", 120},
{"C#10", 121},{"Db10", 121},
{"D10", 122},
{"D#10", 123},{"Eb10", 123},
{"E10", 124},{"Fb10", 124},
{"E#10", 125},{"F10", 125},
{"F#10", 126},{"Gb10", 126},
{"G10", 127}
};
//
// Note
//
//////////////////////////////////////////////////////////////////////////////////
const char * Note::NoteNameOnly(int n)
{
if ( n >= 0 )
return mapNumbersToNotes.at(n % 12).c_str();
else
return "-";
}
string Note::NoteString(int n)
{
if ( n >= 0 )
{
char buffer[25];
sprintf(buffer, "%s%i", mapNumbersToNotes.at(n % 12).c_str(), n / 12);
return buffer;
}
else
return "-";
}
int Note::NoteNumberFromString(string note)
{
try
{
return mapNotesToNumbers.at(note.c_str());
}
catch (...)
{
return -1;
}
}
string Note::ToString(bool fullFormat)
{
if ( m_NoteNumber == -1 )
return "-";
char buffer[25];
if ( fullFormat && m_NoteVelocity >= 0 )
sprintf(buffer, "%s%i:%i:%.3f:%.3f",
mapNumbersToNotes.at(m_NoteNumber % 12).c_str(),
m_NoteNumber / 12,
m_NoteVelocity,
m_Phase,
m_Length);
else
sprintf(buffer, "%s%i", mapNumbersToNotes.at(m_NoteNumber % 12).c_str(), m_NoteNumber / 12);
return buffer;
}
void Note::FromString(string s)
{
// We may have leading white space, which will throw the map look-up,
// so convert separators to white space and then parse on that.
replace( s.begin(), s.end(), ':', ' ');
vector<string> tokens = split(s.c_str(), ' ');
if ( tokens.size() >= 1 )
m_NoteNumber = mapNotesToNumbers.at(tokens.at(0));
else
m_NoteNumber = -1;
if ( tokens.size() >= 2 )
{
m_NoteVelocity = stoi(tokens.at(1));
if ( m_NoteVelocity < 0 || m_NoteVelocity > 127 )
m_NoteVelocity = -1;
}
else
m_NoteVelocity = -1;
if ( tokens.size() >= 3 )
m_Phase = stod(tokens.at(2));
else
m_Phase = 0.0;
if ( tokens.size() >= 4 )
m_Length = stod(tokens.at(3));
else
m_Length = 0.0;
}
void Note::SetStatus()
{
int pos = 0;
char buff[200];
m_FieldPositions.clear();
m_Highlights.clear();
sprintf(buff, "[Note %i] ", m_ItemID);
m_Status = buff;
pos = m_Status.size();
m_Status += ToString(false);
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Status += ", Vel ";
pos = m_Status.size();
if ( m_NoteVelocity > 0 )
{
sprintf(buff, "%i", m_NoteVelocity);
m_Status += buff;
}
else
m_Status += "Off";
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Status += ", Len ";
pos = m_Status.size();
if ( lround(100 * m_Length) > 0 )
{
sprintf(buff, "%.2f", m_Length);
m_Status += buff;
}
else
m_Status += "Off";
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Highlights.push_back(m_FieldPositions.at(m_NoteEditFocus));
}
bool Note::HandleKey(key_type_t k)
{
double inc = 0.1;
int note_inc = 1;
switch ( k )
{
case enter:
case back_space:
case escape:
ReturnFocus();
break;
case left:
if ( m_NoteEditFocus > 0 )
m_NoteEditFocus = static_cast<note_edit_menu_focus_t>(m_NoteEditFocus - 1);
break;
case right:
if ( m_NoteEditFocus < num_nef_types - 1 )
m_NoteEditFocus = static_cast<note_edit_menu_focus_t>(m_NoteEditFocus + 1);
break;
case shift_up:
inc = 0.01;
note_inc = 12;
case up:
switch ( m_NoteEditFocus )
{
case nef_note_number:
if ( m_NoteNumber + note_inc < 128 )
m_NoteNumber += note_inc;
break;
case nef_velocity:
if ( m_NoteVelocity < 127 )
m_NoteVelocity += 1;
break;
case nef_length:
m_Length += inc;
break;
default:
break;
}
break;
case shift_down:
inc = 0.01;
note_inc = 12;
case down:
switch ( m_NoteEditFocus )
{
case nef_note_number:
if ( m_NoteNumber - note_inc >= -1 )
m_NoteNumber -= note_inc;
break;
case nef_velocity:
if ( m_NoteVelocity > 0 )
m_NoteVelocity -= 1;
break;
case nef_length:
m_Length -= inc;
if ( m_Length < 0 )
m_Length = 0;
break;
default:
break;
}
break;
default:
return false;
}
m_FirstField = m_NoteEditFocus == 0;
SetStatus();
return true;
}
void Note::AdjustPhase( double multiplier, double phase, double globalPhase, double base )
{
double phaseOffset = (phase - m_Phase - base) / multiplier;
m_Phase = globalPhase - phaseOffset;
}
bool Note::IncrementAndCheckTarget()
{
if ( equals_3(m_Inc, 0) || equals_3(m_Target, 0) )
return false;
m_Moved += m_Inc;
return m_Moved >= m_Target;
}
//
// Cluster
//
///////////////////////////////////////////////////////////////////
bool Cluster::IsRest()
{
if ( Empty() )
return true;
// for ( vector<int>::size_type i = 0; i < m_Notes.size(); i++ )
// if ( m_Notes[i].m_NoteNumber >= 0 )
// return false;
for ( auto n = m_Notes.begin(); n != m_Notes.end(); n++ )
if ( n->m_NoteNumber >= 0 )
return false;
return true;
}
void Cluster::SetPhaseAllNotes(double phase)
{
for ( auto n = m_Notes.begin(); n != m_Notes.end(); n++ )
n->SetPhase(phase);
}
string Cluster::ToString(bool fullFormat)
{
string result;
for ( vector<Note>::iterator i = m_Notes.begin(); i != m_Notes.end(); i++ )
{
if ( result.size() > 0 )
result += '/';
result += i->ToString(fullFormat);
}
return result;
}
void Cluster::FromString(string s)
{
replace( s.begin(), s.end(), '/', ' '); // Support both spacers.
vector<string> noteStrings = split(s.c_str());
if ( noteStrings.size() == 0 )
{
// Empty notes are rests, so leave the note list empty.
return;
}
for ( vector<string>::iterator it = noteStrings.begin(); it != noteStrings.end(); it++ )
{
Note n;
try
{
n.FromString(*it);
m_Notes.push_back(n);
}
catch (...)
{
// Do nothing with this, we just want to
// carry on and try the next note.
}
}
}
Cluster * StepList::Step()
{
if ( m_Clusters.empty() )
return NULL;
m_LastRequestedPos = m_Pos;
Cluster *pCluster = & m_Clusters[m_Pos++];
// Look ahead for rests.
if ( !pCluster->IsRest() )
{
vector<int>::size_type p = m_Pos;
pCluster->m_StepLength = 0;
do
{
if ( p == m_Clusters.size() )
p = 0;
if ( m_Clusters[p++].IsRest() )
pCluster->m_StepLength += 1;
else
break;
} while ( true );
}
else
pCluster = NULL;
// Set completion flag.
if ( m_Pos >= m_Clusters.size() )
{
m_Complete = true;
m_Pos = 0;
}
else
{
m_Complete = false;
}
return pCluster;
}
void Cluster::SetStatus()
{
int pos = 0;
char buff[50];
m_FieldPositions.clear();
m_Highlights.clear();
sprintf(buff, "[Cluster %i] ", m_ItemID);
m_Status = buff;
for ( unsigned i = 0; i < m_Notes.size(); i++ )
{
if ( i > 0 )
m_Status += '/';
pos = m_Status.size();
m_Status += m_Notes.at(i).ToString(false);
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
}
if ( !m_FieldPositions.empty() )
m_Highlights.push_back(m_FieldPositions.at(m_PosEdit));
}
bool Cluster::HandleKey(key_type_t k)
{
switch ( k )
{
case enter:
if ( !m_Notes.empty() )
{
Note & n = m_Notes.at(m_PosEdit);
n.SetItemID(m_PosEdit + 1);
n.SetFocus();
n.SetStatus();
n.SetReturnFocus(this);
}
break;
case back_space:
case escape:
ReturnFocus();
break;
case left:
if ( m_PosEdit > 0 )
m_PosEdit -= 1;
break;
case right:
if ( m_PosEdit < m_Notes.size() - 1 )
m_PosEdit += 1;
break;
case up:
if ( m_ReturnFocus != NULL )
{
m_ReturnFocus->HandleKey(right);
m_ReturnFocus->HandleKey(enter);
}
return true;
case down:
if ( m_ReturnFocus != NULL )
{
m_ReturnFocus->HandleKey(left);
m_ReturnFocus->HandleKey(enter);
}
return true;
case ctrl_left:
if ( !m_Notes.empty() )
{
m_Notes.insert(m_Notes.begin() + m_PosEdit, m_Notes.at(m_PosEdit));
}
break;
case ctrl_right:
if ( !m_Notes.empty() )
{
m_Notes.insert(m_Notes.begin() + m_PosEdit + 1, m_Notes.at(m_PosEdit));
m_PosEdit += 1;
}
break;
case shift_left:
if ( m_Notes.empty() )
{
m_Notes.emplace_back();
m_PosEdit = 0;
}
else
m_Notes.insert(m_Notes.begin() + m_PosEdit, *(new Note()));
break;
case shift_delete:
if ( !m_Notes.empty() )
{
m_Notes.erase(m_Notes.begin() + m_PosEdit);
if ( m_PosEdit == m_Notes.size() )
m_PosEdit -= 1;
}
break;
case shift_right:
if ( m_Notes.empty() )
{
m_Notes.emplace_back();
m_PosEdit = 0;
}
else
{
m_Notes.insert(m_Notes.begin() + m_PosEdit + 1, *(new Note()));
m_PosEdit += 1;
}
break;
default:
return false;
}
m_FirstField = m_PosEdit == 0;
SetStatus();
return true;
}
//
// StepList
//
//////////////////////////////////////////////////////////////////////////
string StepList::ToString(bool fullFormat)
{
string result;
for ( vector<Cluster>::iterator i = m_Clusters.begin(); i != m_Clusters.end(); )
{
if ( fullFormat && (i - m_Clusters.begin()) % 4 == 0 )
result += " \\\n ";
result += Cluster(*i).ToString(fullFormat);
if ( ++i < m_Clusters.end() )
result += ", ";
}
return result;
}
string StepList::ToStringForDisplay(int & offset, int & length)
{
string result;
char buff[50];
offset = 0;
length = 0;
for ( unsigned i = 0; i < m_Clusters.size(); i++ )
{
if ( i > 0 )
result += ' ';
if ( i == m_LastRequestedPos )
{
sprintf(buff, "%3lu| ", m_LastRequestedPos + 1);
result += buff;
}
if ( i == 0 )
offset = result.size();
result += m_Clusters.at(i).ToString(false);
if ( i == 0 )
length = result.size() - offset;
}
return result;
}
string StepList::ToStringForDisplay2(int & offset, int & length, unsigned width)
{
string result;
offset = 0;
length = 0;
for ( unsigned i = 0; i < m_Clusters.size(); i++ )
{
if ( i > 0 )
result += ' ';
if ( i == m_LastRequestedPos )
{
offset = result.size();
}
result += m_Clusters.at(i).ToString(false);
if ( i == m_LastRequestedPos )
{
length = result.size() - offset;
}
}
// Scroll left if highlight is beyond width.
while ( static_cast<unsigned>(offset + length) > width )
{
int scroll = 3 * width / 4;
result.erase(0, scroll + 3);
result.insert(0, "...");
offset -= scroll;
}
// Truncate if line itself goes beyond width.
if ( result.size() > width )
{
result = result.substr(0, width - 4);
result += "... ";
}
return result;
}
void StepList::FromString(string s)
{
vector<string> chordStrings = split(s.c_str(), ',', true);
if ( chordStrings.size() == 0 )
throw string("Note List parse error: nothing found.");
Clear();
for ( vector<string>::iterator it = chordStrings.begin(); it != chordStrings.end(); it++ )
{
Cluster chord;
chord.FromString(*it);
m_Clusters.push_back(chord);
}
}
void StepList::SetStatus()
{
int pos = 0;
char buff[200];
m_FieldPositions.clear();
m_Highlights.clear();
sprintf(buff, "[Step List %i] ", m_ItemID);
m_Status = buff;
for ( unsigned i = 0; i < m_Clusters.size(); i++ )
{
if ( i > 0 )
m_Status += ", ";
pos = m_Status.size();
Cluster & c = m_Clusters.at(i);
if ( !c.Empty() )
m_Status += c.ToString(false);
else
m_Status += "(Empty)";
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
}
if ( !m_FieldPositions.empty() )
m_Highlights.push_back(m_FieldPositions.at(m_PosEdit));
}
bool StepList::HandleKey(key_type_t k)
{
switch ( k )
{
case enter:
if ( ! m_Clusters.empty() )
{
Cluster & c = m_Clusters.at(m_PosEdit);
c.SetItemID(m_PosEdit + 1);
c.SetFocus();
c.SetStatus();
c.SetReturnFocus(this);
}
break;
case back_space:
case escape:
ReturnFocus();
break;
case left:
if ( m_PosEdit > 0 )
m_PosEdit -= 1;
break;
case right:
if ( m_PosEdit < m_Clusters.size() - 1 )
m_PosEdit += 1;
break;
case up:
case down:
if ( m_ReturnFocus != NULL )
{
m_ReturnFocus->HandleKey(k);
m_ReturnFocus->HandleKey(enter);
}
return true;
case ctrl_left:
if ( !m_Clusters.empty() )
{
m_Clusters.insert(m_Clusters.begin() + m_PosEdit, m_Clusters.at(m_PosEdit));
}
break;
case ctrl_right:
if ( !m_Clusters.empty() )
{
m_Clusters.insert(m_Clusters.begin() + m_PosEdit + 1, m_Clusters.at(m_PosEdit));
m_PosEdit += 1;
}
break;
case shift_left:
if ( m_Clusters.empty() )
{
m_Clusters.emplace_back();
m_PosEdit = 0;
}
else
m_Clusters.insert(m_Clusters.begin() + m_PosEdit, *(new Cluster()));
break;
case shift_right:
if ( m_Clusters.empty() )
{
m_Clusters.emplace_back();
m_PosEdit = 0;
}
else
{
m_Clusters.insert(m_Clusters.begin() + m_PosEdit + 1, *(new Cluster()));
m_PosEdit += 1;
}
break;
case shift_delete:
if ( !m_Clusters.empty() )
{
m_Clusters.erase(m_Clusters.begin() + m_PosEdit);
if ( m_PosEdit == m_Clusters.size() )
m_PosEdit -= 1;
}
break;
default:
return false;
}
m_FirstField = m_PosEdit == 0;
SetStatus();
return true;
}
//
// RealTimeList
//
//////////////////////////////////////////////////////////////////////////
unordered_map<RealTimeListParams::rtp_window_mode_t, const char *> rtp_window_mode_names =
{
{RealTimeListParams::normal, "centered"},
{RealTimeListParams::small, "centered-small"},
{RealTimeListParams::look_ahead, "ahead"}
};
RealTimeListParams::rtp_window_mode_t rtp_window_mode_lookup(string s)
{
static unordered_map<string, RealTimeListParams::rtp_window_mode_t> map;
// Initialize on first use.
if ( map.size() == 0 )
for ( RealTimeListParams::rtp_window_mode_t m = static_cast<RealTimeListParams::rtp_window_mode_t>(0);
m < RealTimeListParams::num_rtp_window_modes;
m = static_cast<RealTimeListParams::rtp_window_mode_t>(static_cast<int>(m) + 1) )
{
map.insert(std::make_pair(rtp_window_mode_names.at(m), m));
}
return map.at(s);
}
void RealTimeListParams::NextWindowMode( int dir )
{
// Move up and down list but don't wrap.
int t = static_cast<int>(m_WindowMode) + dir;
if ( t >= 0 && t < static_cast<int>(num_rtp_window_modes))
{
m_WindowMode = static_cast<rtp_window_mode_t>(t);
}
}
void RealTimeListParams::SetStatus()
{
int pos = 0;
char buff[200];
m_FieldPositions.clear();
m_Highlights.clear();
sprintf(buff, "[RT List %i] ", m_ItemID);
m_Status = buff;
m_Status += " Loop - ";
m_Status += "S: ";
pos = m_Status.size();
sprintf(buff, "%.2f", m_LoopStart);
m_Status += buff;
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Status += " Q: ";
pos = m_Status.size();
sprintf(buff, "%.2f", m_Quantum);
m_Status += buff;
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Status += " Mul: ";
pos = m_Status.size();
sprintf(buff, "%.2f", m_Multiplier);
m_Status += buff;
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Status += " Window Mode: ";
pos = m_Status.size();
sprintf(buff, "%s", rtp_window_mode_names.at(m_WindowMode));
m_Status += buff;
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
m_Highlights.push_back(m_FieldPositions.at(m_RTParamsFocus));
}
bool RealTimeListParams::HandleKey(key_type_t k)
{
int temp;
double inc = 0.1;
switch ( k )
{
case enter:
case back_space:
case escape:
ReturnFocus();
break;
case left:
temp = static_cast<int>(m_RTParamsFocus) - 1;
if ( temp >= 0 && temp < num_rt_params_menu_focus_modes )
m_RTParamsFocus = static_cast<rt_params_menu_focus_t>(temp);
break;
case right:
temp = static_cast<int>(m_RTParamsFocus) + 1;
if ( temp >= 0 && temp < num_rt_params_menu_focus_modes )
m_RTParamsFocus = static_cast<rt_params_menu_focus_t>(temp);
break;
case del:
switch ( m_RTParamsFocus )
{
case rtp_loop_start:
m_LoopStart = 0;
break;
case rtp_local_quantum:
m_Quantum = m_QuantumAtCapture;
break;
case rtp_multiplier:
m_Multiplier = 1.0;
break;
default:
break;
}
break;
case shift_up:
inc = 0.01;
case up:
switch ( m_RTParamsFocus )
{
case rtp_loop_start:
m_LoopStart = tidy_3(m_LoopStart + inc);
break;
case rtp_local_quantum:
m_Quantum = tidy_3(m_Quantum + inc);
break;
case rtp_multiplier:
m_Multiplier = tidy_3(m_Multiplier + inc);
break;
case rtp_window_adjust:
NextWindowMode(-1);
break;
default:
break;
}
break;
case shift_down:
inc = 0.01;
case down:
switch ( m_RTParamsFocus )
{
case rtp_loop_start:
m_LoopStart = tidy_3(m_LoopStart - inc);
break;
case rtp_local_quantum:
m_Quantum = tidy_3(m_Quantum - inc);
if ( m_Quantum < 0.01 )
m_Quantum = 0.01;
break;
case rtp_multiplier:
m_Multiplier = tidy_3(m_Multiplier - inc);
break;
case rtp_window_adjust:
NextWindowMode(1);
break;
default:
break;
}
break;
default:
return false;
}
m_FirstField = m_RTParamsFocus == 0;
SetStatus();
return true;
}
map<double,Note>::iterator RealTimeList::MoveNote(map<double, Note>::iterator it, double newPhase)
{
// Avoid clashes.
while ( true )
{
if ( m_RealTimeList.find(newPhase) == m_RealTimeList.end() )
break;
newPhase += 0.001;
}
// Make a copy of the note and erase the original.
auto ret = m_RealTimeList.insert(make_pair(newPhase, it->second));
m_RealTimeList.erase(it);
// Increment phase.
ret.first->second.SetPhase(newPhase);
return ret.first;
}
map<double,Note>::iterator RealTimeList::CopyNote(map<double, Note>::iterator it)
{
double newPhase = it->second.m_Phase + 0.001;
while ( true )
{
if ( m_RealTimeList.find(newPhase) == m_RealTimeList.end() )
break;
newPhase += 0.001;
}
auto ret = m_RealTimeList.insert(make_pair(newPhase, it->second));
ret.first->second.SetPhase(newPhase);
return ret.first;
}
void RealTimeList::SetStatus()
{
int pos = 0;
char buff[200];
m_FieldPositions.clear();
m_Highlights.clear();
sprintf(buff, "[RT List %i] ", m_ItemID);
m_Status = buff;
pos = m_Status.size();
m_Status += "Params";
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
map<double, Note>::iterator it;
for ( it = m_RealTimeList.begin(); it != m_RealTimeList.end(); it++ )
{
pos = m_Status.size() + 1; // "+ 1" because there's a space before the phase value.
sprintf(buff, " %.2f:", it->first);
m_Status += buff;
m_Status += it->second.ToString(false);
m_FieldPositions.emplace_back(pos, static_cast<int>(m_Status.size() - pos));
}
m_Highlights.push_back(m_FieldPositions.at(m_RTListFocus));
}
bool RealTimeList::HandleKey(key_type_t k)
{
double inc = 0.1;
map<double, Note>::iterator it = m_RealTimeList.begin();
for ( int i = 0; i < m_RTListFocus - m_SubMenus; i++ )
it++; // There's no + operator on iterators for maps, apparently, so we move step-by-step.
switch ( k )
{
case enter:
if ( m_RTListFocus < m_SubMenus )
{
m_Params.SetItemID(m_ItemID);
m_Params.SetFocus();
m_Params.SetStatus();
m_Params.SetReturnFocus(this);
}
else
{
Note & n = it->second;
n.SetFocus();
n.SetStatus();
n.SetReturnFocus(this);
}
break;
case back_space:
case escape:
ReturnFocus();
break;
case left:
if ( m_RTListFocus > 0 )
m_RTListFocus -= 1;
break;
case right:
if ( static_cast<unsigned>(m_RTListFocus) < m_FieldPositions.size() - 1 )
m_RTListFocus += 1;
break;
case shift_up:
case shift_down:
inc = 0.01;
case up:
case down:
if ( m_RTListFocus < m_SubMenus && m_ReturnFocus != NULL )
{
m_ReturnFocus->HandleKey(k);
m_ReturnFocus->HandleKey(enter);
return true;
}
else if ( m_RTListFocus >= m_SubMenus ) // Update note start time (phase).
{
if ( k == down || k == shift_down )
inc *= -1;
auto result = MoveNote(it, it->second.Phase() + inc);
// We get back an iterator to the new entry. Set menu
// focus by counting backwards to start of map.
m_RTListFocus = m_SubMenus;
while ( m_RealTimeList.begin() != result-- )
m_RTListFocus += 1;
}
break;
case shift_delete:
if ( m_RTListFocus >= m_SubMenus )
{
m_UndoList.push_back(it->second);
m_RealTimeList.erase(it);
if ( m_RTListFocus - m_SubMenus >= static_cast<int>(m_RealTimeList.size()) )
m_RTListFocus -= 1;
}
break;
case ctrl_delete:
if ( !m_UndoList.empty() )
{
// Re-insert and reset our cursor position.
Note & n = m_UndoList.back();
pair<map<double,Note>::iterator, bool> result = m_RealTimeList.insert(make_pair(n.Phase(), n));
if ( result.second )
{
m_RTListFocus = m_SubMenus;
while ( m_RealTimeList.begin() != result.first-- )
m_RTListFocus += 1;
}
m_UndoList.pop_back();
}
break;
default:
return false;
}
m_FirstField = m_RTListFocus == 0;
SetStatus();
return true;
}
enum rtl_element_names_t
{
rtl_name_loop,
rtl_name_quantum,
rtl_name_multiplier,
rtl_name_window_adjust,
num_rtl_element_names
};
unordered_map<rtl_element_names_t, const char *> rtl_element_names = {
{rtl_name_loop, "Loop"},
{rtl_name_quantum, "Quantum"},
{rtl_name_multiplier, "Multiplier"},
{rtl_name_window_adjust, "Window"},
{num_rtl_element_names, ""}
};
void RealTimeList::FromString(string s)
{
vector<string> tokens = split(s.c_str(), ',', true);
if ( tokens.size() == 0 )
throw string("Note List parse error: nothing found.");
// Expect field list in first token ...
for ( rtl_element_names_t e = static_cast<rtl_element_names_t>(0);
e < num_rtl_element_names;
e = static_cast<rtl_element_names_t>(static_cast<int>(e) + 1) )
{
string token = find_token(tokens.at(0), rtl_element_names.at(e));
if ( token.empty() )
continue;
try
{
switch (e)
{
case rtl_name_loop:
m_Params.m_LoopStart = stod(token);
break;
case rtl_name_quantum:
m_Params.m_Quantum = stod(token);
break;
case rtl_name_multiplier:
m_Params.m_Multiplier = stod(token);
break;
case rtl_name_window_adjust:
m_Params.m_WindowMode = rtp_window_mode_lookup(token);
break;
default:
break;
}
}
catch(invalid_argument ex)
{
}
catch(out_of_range ex)
{
}
}
// Anything after that is a note.
if ( tokens.size() == 1 )
return; // Leave note list intact.
m_RealTimeList.clear();
for ( vector<string>::iterator it = tokens.begin() + 1; it != tokens.end(); it++ )
{
Note note;
note.FromString(*it);
// Check for existing entries and adjust start time if found.
while ( true )
{
// map<double,Note>::iterator it2 = m_RealTimeList.find(note.Phase());
if ( m_RealTimeList.find(note.Phase()) == m_RealTimeList.end() )
break;
note.SetPhase(note.Phase() + 0.0001);
}
m_RealTimeList.insert(make_pair(note.Phase(), note));
}
}
string RealTimeList::ToString()
{
string result;
char buff[200];
sprintf(buff, " %s %.3f %s %.3f %s %.3f %s '%s'",
rtl_element_names.at(rtl_name_loop), m_Params.m_LoopStart,
rtl_element_names.at(rtl_name_quantum), m_Params.m_Quantum,
rtl_element_names.at(rtl_name_multiplier), m_Params.m_Multiplier,
rtl_element_names.at(rtl_name_window_adjust), rtp_window_mode_names.at(m_Params.m_WindowMode)
);
result += buff;
int i = 0;
for (map<double,Note>::iterator it = m_RealTimeList.begin(); it != m_RealTimeList.end(); it++)
{
result += ", ";
if ( i++ % 4 == 0 )
result += "\\\n ";
result += it->second.ToString();
}
return result;
}
// Less efficient (probably) but easier to read (possibly) ...
string RealTimeList::ToStringForDisplay(int & offset, int & length, unsigned width)
{
offset = 0;
length = 0;
char buff[100];
sprintf(buff, "%05.2f ", m_LastRequestedPhase);
// sprintf(buff, "%05.2f ", m_InternalBeat);
string result = buff;
long topLimit = lround(1000 * m_Params.m_QuantumAtCapture);
long midLimit = lround(1000 * m_LastRequestedPhase);
double windowPos = m_LastRequestedPhase;
double windowStep = 4.0/m_LastRequestedStepValue;
Cluster notes;
while ( lround(1000 * windowPos) < topLimit )
{
double windowStart = windowPos - windowStep/2;
double windowEnd = windowPos + windowStep/2;
for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(windowStart);
it != m_RealTimeList.upper_bound(windowEnd); it++ )
notes.Add(it->second);
if ( !notes.Empty() )
{
result += notes.ToString(false);
notes.Clear();
}
else
result += '-';
windowPos += windowStep;
}
windowPos = 0;
while ( lround(1000 * windowPos) < midLimit )
{
double windowStart = windowPos - windowStep/2;
double windowEnd = windowPos + windowStep/2;
for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(windowStart);
it != m_RealTimeList.upper_bound(windowEnd); it++ )
notes.Add(it->second);
if ( windowPos == 0 )
offset = result.size();
if ( !notes.Empty() )
{
result += notes.ToString(false);
notes.Clear();
}
else
result += '-';
if ( windowPos == 0 )
length = result.size() - offset;
windowPos += windowStep;
}
if ( result.size() > width )
result.resize(width);
#if 0
sprintf(buff, "\n Multiplier %.2f, Loop Start %.2f, Loop Quantum %.2f, Window Adjust %s",
m_Params.m_Multiplier,
m_Params.m_LoopStart,
m_Params.m_LocalQuantum,
m_Params.m_AdjustWindowToStep ? "ON" : "OFF");
result += buff;
#endif
return result;
}
void RealTimeList::Step(Cluster & cluster, double phase, double stepValue)
{
bool localLoop = lround(m_Params.m_Quantum) > 0;
phase *= m_Params.m_Multiplier;
// Wrap to start of local loop.
if ( localLoop )
while ( phase > m_Params.m_Quantum )
phase -= m_Params.m_Quantum;
phase += m_Params.m_LoopStart;
// Wrap to start of capture loop loop.
if ( localLoop )
while ( phase > m_Params.m_QuantumAtCapture )
phase -= m_Params.m_QuantumAtCapture;
m_LastRequestedStepValue = stepValue;
m_LastRequestedPhase = phase;
double window = 4.0 * m_Params.m_Multiplier/stepValue;
double windowStart, windowEnd;
switch ( m_Params.m_WindowMode )
{
case RealTimeListParams::normal:
case RealTimeListParams::small:
if ( m_Params.m_WindowMode == RealTimeListParams::small && abs(m_Params.m_Multiplier) < 1.0 )
window *= m_Params.m_Multiplier;
windowStart = phase - window/2;
windowEnd = phase + window/2;
break;
case RealTimeListParams::look_ahead:
windowStart = phase;
windowEnd = phase + window;
break;
default:
break;
}
for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(windowStart);
it != m_RealTimeList.upper_bound(windowEnd); it++ )
{
cluster.Add(it->second);
}
// When phase is zero, window start will be negative, so we also need to
// look for notes at the top of the loop that would normally be quantized
// up to next beat zero.
// if ( windowStart < 0 )
// {
// windowStart += m_LinkQuantum;
// for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(windowStart);
// it != m_RealTimeList.upper_bound(m_LinkQuantum); it++ )
// m_Captured.Add(it->second);
// }
// return result;
}
void RealTimeList::BeginEcho(double inc, double target, int interval)
{
// Iterator here is a map pair.
// Make a set up references to current map members before duplicating
// them. Updating the map while we're traversing it leads to confusion!
vector<map<double,Note>::iterator> notes;
for ( auto p = m_RealTimeList.begin(); p != m_RealTimeList.end(); p++ )
notes.push_back(p);
for ( auto p = notes.begin(); p != notes.end(); p++ )
{
double newPhase = (*p)->second.m_Phase + inc;
pair<map<double,Note>::iterator,bool> ret = m_RealTimeList.insert(make_pair(newPhase, (*p)->second));
if ( ret.second )
{
Note & n = ret.first->second;
n.SetPhase(newPhase);
n.m_Inc = inc;
n.m_Moved = inc; // We already added increment to start phase, above.
n.m_Target = target;
n.m_Interval = interval;
n.m_NoteNumber += interval;
}
}
}
enum rte_target_action_mode_t
{
rteam_delete,
rteam_freeze,
rteam_echo_all,
rteam_echo_all_delete,
rteam_echo_all_freeze,
rteam_copy,
rteam_copy_freeze,
rteam_copy_freeze_target_multiplier,
num_rte_target_action_modes
};
bool RealTimeList::NoteTargetAction(map<double,Note>::iterator mapEntry, double newPhase)
{
bool result = false;
rte_target_action_mode_t mode = rteam_copy_freeze_target_multiplier;
switch(mode)
{
case rteam_delete:
m_RealTimeList.erase(mapEntry);
return true;
default:
break;
}
Note * note = & mapEntry->second;
// Echo tasks ...
switch(mode)
{
case rteam_echo_all:
case rteam_echo_all_delete:
case rteam_echo_all_freeze:
BeginEcho(note->m_Inc, note->m_Target, note->m_Interval);
break;
default:
break;
}
// The current note is copied ...
Note * newNote = NULL;
switch(mode)
{
case rteam_copy:
case rteam_copy_freeze:
case rteam_copy_freeze_target_multiplier:
newNote = & CopyNote(mapEntry)->second;
break;
default:
break;
}
// Copied note simple initialisation, including interval transpose.
switch(mode)
{
case rteam_copy:
case rteam_copy_freeze:
case rteam_copy_freeze_target_multiplier:
newNote->m_Moved = 0;
newNote->m_Phase = note->m_Phase + note->m_Inc;
newNote->m_NoteNumber += newNote->m_Interval;
break;
default:
break;
}
double targetMultiplier = 0.5;
switch(mode)
{
case rteam_copy_freeze_target_multiplier:
newNote->m_Target *= targetMultiplier;
break;
default:
break;
}
// Delete or freeze the original note?
switch(mode)
{
case rteam_echo_all_delete:
m_RealTimeList.erase(mapEntry);
result = true;
break;
case rteam_freeze:
case rteam_copy_freeze:
case rteam_copy_freeze_target_multiplier:
case rteam_echo_all_freeze:
note->m_Inc = 0;
note->m_Moved = 0;
break;
default:
break;
}
return result;
}
void RealTimeList::DoEchoes()
{
// Build a list of iterators to notes to be changed. (We
// shouldn't modify the map whilst traversing it!)
vector<map<double,Note>::iterator> entries;
for ( auto p = m_RealTimeList.begin(); p != m_RealTimeList.end(); p++ )
if ( !equals_3(p->second.m_Inc, 0))
entries.push_back(p);
for ( auto p = entries.begin(); p != entries.end(); p++ )
{
Note & note = (*p)->second;
double newPhase = note.m_Phase + note.m_Inc;
if ( newPhase >= m_Params.m_Quantum )
{
if ( m_Params.m_EchoesDeleteAtQuantum )
{
m_RealTimeList.erase(*p);
continue;
}
if ( m_Params.m_EchoesWrapAtQuantum )
newPhase -= m_Params.m_Quantum;
}
// Have we reached the target?
if ( note.IncrementAndCheckTarget() && NoteTargetAction(*p, newPhase) )
continue;
// MoveNote() inserts a copy at the new location. The previous
// map entry and its note is deleted.
/*Note & newNote =*/ MoveNote(*p, newPhase)->second;
// Any further processing on new note? If so, do it here.
}
}
unsigned long RealTimeList::PhaseLength()
{
// Lets do this with integers, return the result in thousanths of a beat. (mBeat?)
unsigned long adjustedQuantum = lround(1000.0 * m_Params.m_Multiplier * m_Params.m_Quantum);
unsigned long quantum = lround(1000.0 * m_Params.m_Quantum);
// Using lowest common multiple gives us the 'adjusted' result, which needs to be
// adjusted back to pattern time.
return lcm(quantum, adjustedQuantum)/adjustedQuantum * quantum;
// This method is unreliable: fmod() seems to return
// a whole value of m_Quantum for some values
// of adjustedQuantum, which means we don't find the
// lowest multiple. (Rounding errors, I guess.)
// double t = adjustedQuantum;
// int mod = 0;
//
// do
// {
// t += adjustedQuantum;
// mod = lround(1000.0 * fmod(t, m_Params.m_Quantum));
// } while ( mod != 0 );
// return 0.001 * static_cast<double>(t) / m_Params.m_Multiplier;
}
void RealTimeList::Step2(Cluster & cluster, double globalPhase, double stepValue, double patternBeat)
{
// double altPhase = fmod(m_Params.m_Multiplier * patternBeat, m_Params.m_Quantum);
long lTemp = lround(1000.0 * m_Params.m_Multiplier * patternBeat);
long lPhase = lTemp % lround(1000.0 * m_Params.m_Quantum);
double phase = static_cast<double>(lPhase)/1000;
m_LastRequestedStepValue = stepValue;
m_LastRequestedPhase = phase;
m_LastStepPhaseZero = lPhase == 0;
if ( m_LastStepPhaseZero )
DoEchoes();
// Window is defined in the list time scale, so use the multiplier.
double window = 4.0 * m_Params.m_Multiplier/stepValue;
double windowStart, windowEnd;
switch ( m_Params.m_WindowMode )
{
case RealTimeListParams::normal:
case RealTimeListParams::small:
// This doesn't make sense: window becomes 4 * mul-squared/stepValue.
if ( m_Params.m_WindowMode == RealTimeListParams::small && abs(m_Params.m_Multiplier) < 1.0 )
window *= m_Params.m_Multiplier;
windowStart = phase - window/2;
windowEnd = phase + window/2;
break;
case RealTimeListParams::look_ahead:
windowStart = phase;
windowEnd = phase + window;
break;
default:
windowStart = phase - window/2;
windowEnd = phase + window/2;
break;
}
// Swap round if negative multiplier (reverse play).
if ( windowStart > windowEnd )
{
double t = windowStart;
windowStart = windowEnd;
windowEnd = t;
}
// Step window may overlap either end of the original capture range (m_Params.m_Quantum), or may even
// be bigger than the capture window, in which case we need to repeat the captured data at new locations
// within the step window for playback. Here, N represents the capture window as it slides over the step
// window, starting with the value of N that contains windowStart, ending with the value of N that contains
// windowEnd. For each position of N, we grab the relevant events and map them to their playback location in
// the playback stream, marked by globalPhase.
for ( int N = ceil(windowStart/m_Params.m_Quantum) - 1; N < ceil(windowEnd/m_Params.m_Quantum); N++ )
{
double rangeOffset = N * m_Params.m_Quantum;
// Set bounds for the collection window applied to captured data.
double lower = max(windowStart, rangeOffset) - rangeOffset;
double upper = min(windowEnd, rangeOffset + m_Params.m_Quantum) - rangeOffset - 0.001;
// (Taking off 0.001 makes sure we test against the element at the top of
// the collection winow, as upper_bound() "Returns an iterator pointing to
// the first element whose key is considered to go *after* k.")
// Slide the collection window over the captured data. (This doesn't wrap if we slide
// over the end of the capture range.)
lower += m_Params.m_LoopStart;
upper += m_Params.m_LoopStart;
// lower = 0.001 * lround(lower * 1000);
// upper = 0.001 * lround(upper * 1000);
lower = tidy_3(lower);
upper = tidy_3(upper);
// Protect map from scans where lower > upper. This can happen due to rounding errors
// and/or imprecise floating point data. (If lower > upper executing the loop below
// seems to produce race conditions and/or stack corruption.)
if ( lower >= upper )
continue;
for ( map<double,Note>::iterator it = m_RealTimeList.lower_bound(lower);
it != m_RealTimeList.upper_bound(upper); it++ )
cluster.Add(it->second).AdjustPhase(m_Params.m_Multiplier, phase, globalPhase, rangeOffset);
}
}
|
BN701/Multi-Arp
|
maNotes.cpp
|
C++
|
gpl-3.0
| 46,045
|
import pytest
from learn.models import Task, ProblemSet, Domain
from learn.models import Student, TaskSession, Skill
from learn.mastery import has_mastered, get_level
from learn.mastery import get_first_unsolved_mission
from learn.mastery import get_first_unsolved_phase
from learn.mastery import get_current_mission_phase
# Django DB is always needed for many-to-many relations (chunks.tasks)
@pytest.mark.django_db
def test_has_mastered__initially_not():
ps = ProblemSet.objects.create()
ps.add_task()
student = Student.objects.create()
assert not has_mastered(student, ps)
# django db is always needed for many-to-many relations (student.skills)
# todo: find a way how to test the following without using db.
@pytest.mark.django_db
def test_has_mastered__when_skill_is_1():
ps = ProblemSet.objects.create()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=ps, value=1.0)
assert has_mastered(student, ps)
@pytest.mark.django_db
def test_has_mastered__mastered_parts():
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
p2 = m1.add_part()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=m1, value=1)
Skill.objects.create(student=student, chunk=p1, value=1)
Skill.objects.create(student=student, chunk=p2, value=1)
assert has_mastered(student, m1)
@pytest.mark.django_db
def test_has_mastered__not_when_skill_is_low():
ps = ProblemSet.objects.create()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=ps, value=0.5)
assert not has_mastered(student, ps)
@pytest.mark.django_db
def test_has_mastered__not_unmastered_subchunk():
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
p2 = m1.add_part()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=m1, value=1)
Skill.objects.create(student=student, chunk=p1, value=1)
Skill.objects.create(student=student, chunk=p2, value=0)
assert not has_mastered(student, m1)
@pytest.mark.django_db
def test_get_first_unsolved_mission__single():
mission = ProblemSet.objects.create()
domain = Domain.objects.create()
domain.problemsets.set([mission])
student = Student.objects.create()
assert get_first_unsolved_mission(domain, student) == mission
@pytest.mark.django_db
def test_get_first_unsolved_mission__all_unsolved():
mission1 = ProblemSet.objects.create(section='1')
mission2 = ProblemSet.objects.create(section='2')
domain = Domain.objects.create()
domain.problemsets.set([mission1, mission2])
student = Student.objects.create()
assert get_first_unsolved_mission(domain, student) == mission1
@pytest.mark.django_db
def test_get_first_unsolved_mission__first_solved():
mission1 = ProblemSet.objects.create(section='1')
mission2 = ProblemSet.objects.create(section='2')
domain = Domain.objects.create()
domain.problemsets.set([mission1, mission2])
student = Student.objects.create()
Skill.objects.create(student=student, chunk=mission1, value=1)
assert get_first_unsolved_mission(domain, student) == mission2
@pytest.mark.django_db
def test_get_first_unsolved_phase__all_unsolved():
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
m1.add_part()
student = Student.objects.create()
assert get_first_unsolved_phase(m1, student) == p1
@pytest.mark.django_db
def test_get_first_unsolved_phase__first_solved():
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
p2 = m1.add_part()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=p1, value=1)
assert get_first_unsolved_phase(m1, student) == p2
@pytest.mark.django_db
def test_get_first_unsolved_phase__all_solved():
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
student = Student.objects.create()
Skill.objects.create(student=student, chunk=p1, value=1)
Skill.objects.create(student=student, chunk=m1, value=1)
assert get_first_unsolved_phase(m1, student) == None
@pytest.mark.django_db
def test_get_mission_phase__all_solved():
domain = Domain.objects.create()
m1 = ProblemSet.objects.create()
p1 = m1.add_part()
domain.problemsets.set([m1, p1])
student = Student.objects.create()
Skill.objects.create(student=student, chunk=p1, value=1)
Skill.objects.create(student=student, chunk=m1, value=1)
assert get_current_mission_phase(domain, student) == (None, None)
@pytest.mark.django_db
def test_get_level_for_new_student():
mission = ProblemSet.objects.create()
domain = Domain.objects.create()
domain.problemsets.set([mission])
student = Student.objects.create()
assert get_first_unsolved_mission(domain, student) == mission
assert get_level(domain, student) == 1
@pytest.mark.django_db
def test_level_is_number_of_solved_missions_plus_1():
m1 = ProblemSet.objects.create()
m2 = ProblemSet.objects.create()
m3 = ProblemSet.objects.create()
domain = Domain.objects.create()
domain.problemsets.set([m1, m2, m3])
student = Student.objects.create()
Skill.objects.create(student=student, chunk=m1, value=1)
Skill.objects.create(student=student, chunk=m3, value=1)
assert get_level(domain, student) == 3
|
adaptive-learning/robomission
|
backend/learn/tests/test_mastery.py
|
Python
|
gpl-3.0
| 5,319
|
#!/usr/bin/env python
import os
import json
from flask import Flask, abort, jsonify, request, g, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
colors = json.load(file('colors.json', 'r'))
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy dog'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# extensions
db = SQLAlchemy(app)
auth = HTTPBasicAuth()
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), index=True)
password_hash = db.Column(db.String(64))
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return pwd_context.verify(password, self.password_hash)
def generate_auth_token(self, expiration=600):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id': self.id})
@staticmethod
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
user = User.query.get(data['id'])
return user
@auth.verify_password
def verify_password(username_or_token, password):
# first try to authenticate by token
user = User.verify_auth_token(username_or_token)
if not user:
# try to authenticate with username/password
user = User.query.filter_by(username=username_or_token).first()
if not user or not user.verify_password(password):
return False
g.user = user
return True
@app.route('/api/users', methods=['POST'])
def new_user():
username = request.json.get('username')
password = request.json.get('password')
if username is None or password is None:
abort(400) # missing arguments
if User.query.filter_by(username=username).first() is not None:
abort(400) # existing user
user = User(username=username)
user.hash_password(password)
db.session.add(user)
db.session.commit()
return (jsonify({'username': user.username}), 201,
{'Location': url_for('get_user', id=user.id, _external=True)})
@app.route('/api/users/<int:id>', methods = ['GET'])
def get_user(id):
user = User.query.get(id)
if not user:
abort(400)
return jsonify({'username': user.username})
@app.route('/api/token', methods = ['GET'])
@auth.login_required
def get_auth_token():
print(request.headers.get('Date'))
token = g.user.generate_auth_token(600)
return jsonify({'token': token.decode('ascii'), 'duration': 600})
@app.route('/api/resource')
@auth.login_required
def get_resource():
return jsonify({'data': 'Hello, %s!' % g.user.username})
@app.route('/api/colors', methods = ['GET'])
def get_colors():
print(colors)
return jsonify( { "data" : colors })
@app.route('/api/colors/<name>', methods = ['GET'])
def get_color(name):
for color in colors:
if color["name"] == name:
return jsonify( color )
return jsonify( { 'error' : True } )
@app.route('/api/colors', methods= ['POST'])
@auth.login_required
def create_color():
print('create color')
color = {
'name': request.json['name'],
'value': request.json['value']
}
print(color)
colors.append(color)
return jsonify( color ), 201
@app.route('/api/colors/<name>', methods= ['PUT'])
@auth.login_required
def update_color(name):
success = False
print('update color')
for color in colors:
if color["name"] == name:
color['value'] = request.json.get('value', color['value'])
print(color)
return jsonify( color )
return jsonify( { 'error' : True } )
@app.route('/api/colors/<name>', methods=['DELETE'])
@auth.login_required
def delete_color(name):
success = False
print('delete color')
for color in colors:
if color["name"] == name:
colors.remove(color)
print(color)
return jsonify(color)
return jsonify( { 'error' : True } )
if __name__ == '__main__':
if not os.path.exists('db.sqlite'):
db.create_all()
app.run(debug = True)
|
emilio-simoes/qt-rest-client
|
tools/test-service/server.py
|
Python
|
gpl-3.0
| 4,688
|
package dux.org.springframework.security.access.expression;
import org.junit.Test;
import org.springframework.security.core.Authentication;
import dum.org.springframework.security.core.DummyAuthentication;
public class AbstractSecurityExpressionHandlerTest {
@Test
public void test() {
DummyAbstractSecurityExpressionHandler daseh = new DummyAbstractSecurityExpressionHandler();
Authentication authentication = new DummyAuthentication();
String invocation = "invocation";
daseh.createEvaluationContext(authentication, invocation);
}
}
|
docteurdux/code
|
voters/src/test/java/dux/org/springframework/security/access/expression/AbstractSecurityExpressionHandlerTest.java
|
Java
|
gpl-3.0
| 567
|
package Mojo::Upload;
use Mojo::Base -base;
use Mojo::Asset::File;
use Mojo::Headers;
has asset => sub { Mojo::Asset::File->new };
has [qw(filename name)];
has headers => sub { Mojo::Headers->new };
sub move_to {
my $self = shift;
$self->asset->move_to(@_);
return $self;
}
sub size { shift->asset->size }
sub slurp { shift->asset->slurp }
1;
=head1 NAME
Mojo::Upload - Upload
=head1 SYNOPSIS
use Mojo::Upload;
my $upload = Mojo::Upload->new;
say $upload->filename;
$upload->move_to('/home/sri/foo.txt');
=head1 DESCRIPTION
L<Mojo::Upload> is a container for uploaded files.
=head1 ATTRIBUTES
L<Mojo::Upload> implements the following attributes.
=head2 asset
my $asset = $upload->asset;
$upload = $upload->asset(Mojo::Asset::File->new);
Asset containing the uploaded data, usually a L<Mojo::Asset::File> or
L<Mojo::Asset::Memory> object.
=head2 filename
my $filename = $upload->filename;
$upload = $upload->filename('foo.txt');
Name of the uploaded file.
=head2 headers
my $headers = $upload->headers;
$upload = $upload->headers(Mojo::Headers->new);
Headers for upload, defaults to a L<Mojo::Headers> object.
=head2 name
my $name = $upload->name;
$upload = $upload->name('foo');
Name of the upload.
=head1 METHODS
L<Mojo::Upload> inherits all methods from L<Mojo::Base> and implements the
following new ones.
=head2 move_to
$upload = $upload->move_to('/home/sri/foo.txt');
Move uploaded data into a specific file.
=head2 size
my $size = $upload->size;
Size of uploaded data in bytes.
=head2 slurp
my $bytes = $upload->slurp;
Read all uploaded data at once.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
=cut
|
dobrevg/webrsnapshot
|
lib/Mojo/Upload.pm
|
Perl
|
gpl-3.0
| 1,731
|
/*
* Copyright 2013 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/libyuv/include/libyuv/row.h"
#include "third_party/libyuv/include/libyuv/rotate_row.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// This module is for Visual C x86.
#if !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86) && \
defined(_MSC_VER) && !defined(__clang__)
__declspec(naked)
void TransposeWx8_SSSE3(const uint8* src, int src_stride,
uint8* dst, int dst_stride, int width) {
__asm {
push edi
push esi
push ebp
mov eax, [esp + 12 + 4] // src
mov edi, [esp + 12 + 8] // src_stride
mov edx, [esp + 12 + 12] // dst
mov esi, [esp + 12 + 16] // dst_stride
mov ecx, [esp + 12 + 20] // width
// Read in the data from the source pointer.
// First round of bit swap.
align 4
convertloop:
movq xmm0, qword ptr [eax]
lea ebp, [eax + 8]
movq xmm1, qword ptr [eax + edi]
lea eax, [eax + 2 * edi]
punpcklbw xmm0, xmm1
movq xmm2, qword ptr [eax]
movdqa xmm1, xmm0
palignr xmm1, xmm1, 8
movq xmm3, qword ptr [eax + edi]
lea eax, [eax + 2 * edi]
punpcklbw xmm2, xmm3
movdqa xmm3, xmm2
movq xmm4, qword ptr [eax]
palignr xmm3, xmm3, 8
movq xmm5, qword ptr [eax + edi]
punpcklbw xmm4, xmm5
lea eax, [eax + 2 * edi]
movdqa xmm5, xmm4
movq xmm6, qword ptr [eax]
palignr xmm5, xmm5, 8
movq xmm7, qword ptr [eax + edi]
punpcklbw xmm6, xmm7
mov eax, ebp
movdqa xmm7, xmm6
palignr xmm7, xmm7, 8
// Second round of bit swap.
punpcklwd xmm0, xmm2
punpcklwd xmm1, xmm3
movdqa xmm2, xmm0
movdqa xmm3, xmm1
palignr xmm2, xmm2, 8
palignr xmm3, xmm3, 8
punpcklwd xmm4, xmm6
punpcklwd xmm5, xmm7
movdqa xmm6, xmm4
movdqa xmm7, xmm5
palignr xmm6, xmm6, 8
palignr xmm7, xmm7, 8
// Third round of bit swap.
// Write to the destination pointer.
punpckldq xmm0, xmm4
movq qword ptr [edx], xmm0
movdqa xmm4, xmm0
palignr xmm4, xmm4, 8
movq qword ptr [edx + esi], xmm4
lea edx, [edx + 2 * esi]
punpckldq xmm2, xmm6
movdqa xmm6, xmm2
palignr xmm6, xmm6, 8
movq qword ptr [edx], xmm2
punpckldq xmm1, xmm5
movq qword ptr [edx + esi], xmm6
lea edx, [edx + 2 * esi]
movdqa xmm5, xmm1
movq qword ptr [edx], xmm1
palignr xmm5, xmm5, 8
punpckldq xmm3, xmm7
movq qword ptr [edx + esi], xmm5
lea edx, [edx + 2 * esi]
movq qword ptr [edx], xmm3
movdqa xmm7, xmm3
palignr xmm7, xmm7, 8
sub ecx, 8
movq qword ptr [edx + esi], xmm7
lea edx, [edx + 2 * esi]
jg convertloop
pop ebp
pop esi
pop edi
ret
}
}
__declspec(naked)
void TransposeUVWx8_SSE2(const uint8* src, int src_stride,
uint8* dst_a, int dst_stride_a,
uint8* dst_b, int dst_stride_b,
int w) {
__asm {
push ebx
push esi
push edi
push ebp
mov eax, [esp + 16 + 4] // src
mov edi, [esp + 16 + 8] // src_stride
mov edx, [esp + 16 + 12] // dst_a
mov esi, [esp + 16 + 16] // dst_stride_a
mov ebx, [esp + 16 + 20] // dst_b
mov ebp, [esp + 16 + 24] // dst_stride_b
mov ecx, esp
sub esp, 4 + 16
and esp, ~15
mov [esp + 16], ecx
mov ecx, [ecx + 16 + 28] // w
align 4
convertloop:
// Read in the data from the source pointer.
// First round of bit swap.
movdqu xmm0, [eax]
movdqu xmm1, [eax + edi]
lea eax, [eax + 2 * edi]
movdqa xmm7, xmm0 // use xmm7 as temp register.
punpcklbw xmm0, xmm1
punpckhbw xmm7, xmm1
movdqa xmm1, xmm7
movdqu xmm2, [eax]
movdqu xmm3, [eax + edi]
lea eax, [eax + 2 * edi]
movdqa xmm7, xmm2
punpcklbw xmm2, xmm3
punpckhbw xmm7, xmm3
movdqa xmm3, xmm7
movdqu xmm4, [eax]
movdqu xmm5, [eax + edi]
lea eax, [eax + 2 * edi]
movdqa xmm7, xmm4
punpcklbw xmm4, xmm5
punpckhbw xmm7, xmm5
movdqa xmm5, xmm7
movdqu xmm6, [eax]
movdqu xmm7, [eax + edi]
lea eax, [eax + 2 * edi]
movdqu [esp], xmm5 // backup xmm5
neg edi
movdqa xmm5, xmm6 // use xmm5 as temp register.
punpcklbw xmm6, xmm7
punpckhbw xmm5, xmm7
movdqa xmm7, xmm5
lea eax, [eax + 8 * edi + 16]
neg edi
// Second round of bit swap.
movdqa xmm5, xmm0
punpcklwd xmm0, xmm2
punpckhwd xmm5, xmm2
movdqa xmm2, xmm5
movdqa xmm5, xmm1
punpcklwd xmm1, xmm3
punpckhwd xmm5, xmm3
movdqa xmm3, xmm5
movdqa xmm5, xmm4
punpcklwd xmm4, xmm6
punpckhwd xmm5, xmm6
movdqa xmm6, xmm5
movdqu xmm5, [esp] // restore xmm5
movdqu [esp], xmm6 // backup xmm6
movdqa xmm6, xmm5 // use xmm6 as temp register.
punpcklwd xmm5, xmm7
punpckhwd xmm6, xmm7
movdqa xmm7, xmm6
// Third round of bit swap.
// Write to the destination pointer.
movdqa xmm6, xmm0
punpckldq xmm0, xmm4
punpckhdq xmm6, xmm4
movdqa xmm4, xmm6
movdqu xmm6, [esp] // restore xmm6
movlpd qword ptr [edx], xmm0
movhpd qword ptr [ebx], xmm0
movlpd qword ptr [edx + esi], xmm4
lea edx, [edx + 2 * esi]
movhpd qword ptr [ebx + ebp], xmm4
lea ebx, [ebx + 2 * ebp]
movdqa xmm0, xmm2 // use xmm0 as the temp register.
punpckldq xmm2, xmm6
movlpd qword ptr [edx], xmm2
movhpd qword ptr [ebx], xmm2
punpckhdq xmm0, xmm6
movlpd qword ptr [edx + esi], xmm0
lea edx, [edx + 2 * esi]
movhpd qword ptr [ebx + ebp], xmm0
lea ebx, [ebx + 2 * ebp]
movdqa xmm0, xmm1 // use xmm0 as the temp register.
punpckldq xmm1, xmm5
movlpd qword ptr [edx], xmm1
movhpd qword ptr [ebx], xmm1
punpckhdq xmm0, xmm5
movlpd qword ptr [edx + esi], xmm0
lea edx, [edx + 2 * esi]
movhpd qword ptr [ebx + ebp], xmm0
lea ebx, [ebx + 2 * ebp]
movdqa xmm0, xmm3 // use xmm0 as the temp register.
punpckldq xmm3, xmm7
movlpd qword ptr [edx], xmm3
movhpd qword ptr [ebx], xmm3
punpckhdq xmm0, xmm7
sub ecx, 8
movlpd qword ptr [edx + esi], xmm0
lea edx, [edx + 2 * esi]
movhpd qword ptr [ebx + ebp], xmm0
lea ebx, [ebx + 2 * ebp]
jg convertloop
mov esp, [esp + 16]
pop ebp
pop edi
pop esi
pop ebx
ret
}
}
#endif // !defined(LIBYUV_DISABLE_X86) && defined(_M_IX86)
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
|
ALEJANDROJ19/VTW-server
|
VpxEncoderRaw/third_party/libyuv/source/rotate_win.cc
|
C++
|
gpl-3.0
| 7,446
|
/**
* Copyright 2015 Markus Weippert <markus@gekmihesg.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*
**/
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Promise.jsm");
const COMMONJS_URI = 'resource://gre/modules/commonjs';
const { require } = Cu.import(COMMONJS_URI + '/toolkit/require.js', {});
var subprocess = require('sdk/system/child_process/subprocess');
XPCOMUtils.defineLazyModuleGetter(this, "LoginHelper",
"resource://gre/modules/LoginHelper.jsm");
// all these values are handled, but false values
// are not mapped automatically
const PropertyMap = {
username: true,
password: false,
hostname: true,
formSubmitURL: true,
httpRealm: true,
usernameField: true,
passwordField: true
};
// vars without "=" are copied from existing environment
const EnvironmentVars = [
"HOME", "USER", "DISPLAY", "PATH",
"GPG_AGENT_INFO",
"PASSWORD_STORE_DIR",
"PASSWORD_STORE_KEY",
"PASSWORD_STORE_GIT",
"PASSWORD_STORE_UMASK",
"TREE_COLORS=rs:0",
"TREE_CHARSET=ASCII"
];
const LoginInfo = new Components.Constructor(
"@mozilla.org/login-manager/loginInfo;1", Ci.nsILoginInfo);
RegExp.escape = function(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
};
function PassManager() {}
PassManager.prototype = {
classID: Components.ID("{1dadf2b7-f243-41b4-a2f2-e53207f29167}"),
QueryInterface: XPCOMUtils.generateQI([Ci.nsILoginManagerStorage]),
_environment: null,
_propMap: null,
_passCmd: "",
_realm: "",
_fuzzy: false,
_save_as_username: false,
_storage_json: null,
_strip_hostnames: [],
_cache: {
defaultLifetime: 300,
_entries: {},
get: function (key) {
if (this._entries[key]) {
return this._entries[key].value;
}
return null;
},
add: function (key, value, lifetime) {
lifetime = (lifetime ? lifetime : this.defaultLifetime) * 1000;
if (lifetime > 0) {
let entry = {
value: value,
notify: function (timer) {
this.cache.del(key);
}
};
let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
entry.timer = timer;
entry.cache = this;
this._entries[key] = entry;
timer.initWithCallback(entry, lifetime, Ci.nsITimer.TYPE_ONE_SHOT);
}
},
del: function (key) {
if (this._entries[key]) {
this._entries[key].timer.cancel();
delete this._entries[key];
}
},
clear: function () {
for (let key in this._entries) {
this.del(key);
}
}
},
_stub: function(arguments) {
throw Error('Not yet implemented: ' + arguments.callee.name + '()');
},
_pass: function (args, stdin) {
let result = null;
let o = '';
let pi = {
command: this._passCmd,
arguments: args,
charset: "UTF-8",
environment: this._environment,
done: function (r) { result = r; },
stdout: function (data) { o += data; },
stdin: stdin,
mergeStderr: false
}
let p = subprocess.call(pi);
let rc = p.wait();
if (p) {
p.exitCode = rc;
p.stdout = o;
}
return p;
},
// strip protocol, port and path from URL
_sanitizeHostname: function (url) {
return url.replace(/^.*:\/\/([^:\/]+)(?:[:\/].*)?$/, "$1");
},
// strip path from URL
_sanitizeURL: function (url) {
return url.replace(/^(.*:\/\/[^\/]+)(?:\/.*)?/, "$1");
},
_getHostnamePath: function (hostname, all) {
if (hostname) {
hostname = this._sanitizeHostname(hostname);
let options = [this._realm + "/" + hostname];
if (this._strip_hostnames.length > 0) {
for each (let sub in this._strip_hostnames) {
if (hostname.indexOf(sub + ".") == 0) {
options.unshift(this._realm + "/" +
hostname.substr(sub.length + 1));
break;
}
}
}
return all ? options : options[0];
}
return all ? [this._realm] : this._realm;
},
_loginToStr: function (login) {
let s = [];
s.push(login.password);
for (let prop in this._propMap) {
if (this._propMap[prop] && login[prop]) {
s.push(this._propMap[prop][0] + ": " + login[prop]);
}
}
return s.join("\n");
},
_strToLogin: function (s) {
let lines = s.split("\n");
let re = /^([a-zA-Z]+):\s*(.*)$/;
// init login with safe values
let login = new LoginInfo();
login.username = "";
login.hostname = "";
login.password = lines.shift();
// parse input to object
let props = {};
for each (let line in lines) {
let match = re.exec(line);
if(match) {
props[match[1].toLowerCase()] = match[2].trim();
}
}
// map object to login
for (let prop in this._propMap) {
if (this._propMap[prop]) {
for each (let name in this._propMap[prop]) {
if (props[name]) {
login[prop] = props[name];
break;
}
}
}
}
return login;
},
_saveLogin: function (loginPath, login) {
this._pass(["insert", "-m", "-f", loginPath],
this._loginToStr(login));
// update cache with logins clone
this._cache.add(loginPath, login.clone());
},
_loadLogin: function (loginPath) {
let login = this._cache.get(loginPath);
if (!login) {
let result = this._pass(["show", loginPath]);
if (result.exitCode == 0) {
login = this._strToLogin(result.stdout);
if (login) {
this._cache.add(loginPath, login);
}
}
}
if (login) {
// always return a clone!
// we need the original login cached!
return login.clone();
}
return null;
},
// return all paths to logins matching hostname,
// all logins if hostname is undefined
_getLoginPaths: function (hostname) {
let re = /^(.*[|`]+)-- (.*)$/;
let paths = [];
for each (let path in this._getHostnamePath(hostname, true)) {
result = this._pass(["ls", path]);
if (result.exitCode != 0) {
continue;
}
let lines = result.stdout.split("\n");
let tree = [];
let lastIndent = 0;
let lastNode = null;
for (let i = 0 ; i < lines.length; i++) {
let match = re.exec(lines[i]);
if(match) {
let indent = match[1].length;
if (lastNode) {
if (lastIndent < indent) {
tree.push(lastNode);
paths.pop();
} else if (lastIndent > indent) {
tree.pop();
}
}
lastIndent = indent;
lastNode = match[2];
paths.push(path + "/" +
tree.concat([lastNode]).join("/"));
}
}
}
return paths;
},
// for fuzzy option
_autocomplete: function (login, md, path) {
if (login.hostname) {
login.hostname = this._sanitizeURL(login.hostname);
} else if (md.hostname) {
login.hostname = md.hostname;
} else {
var re = new RegExp("^" + RegExp.escape(this._realm) + "\/([^\/]+).*$");
if ((match = re.exec(path)) !== null) {
// use hostname from path as fallback
login.hostname = "https://" + match[1];
} else {
login.hostname = "unknown";
}
}
if (login.formSubmitURL) {
login.formSubmitURL = this._sanitizeURL(login.formSubmitURL);
} else if (!login.formSubmitURL && !login.httpRealm) {
if (!md.formSubmitURL && !md.httpRealm) {
// no info if protocol or HTML login requested,
// choose HTML since we may return an empty string
// as wildcard here
login.formSubmitURL = "";
} else {
login.formSubmitURL = md.formSubmitURL;
login.httpRealm = md.httpRealm;
}
}
if (!login.usernameField) {
login.usernameField = md.usernameField;
}
if (!login.passwordField) {
login.passwordField = md.passwordField;
}
return login;
},
_filterLogins: function (matchData) {
// copy all handled fields from matchData
let md = {};
for (let prop in this._propMap) {
if (prop in matchData) {
md[prop] = matchData[prop];
}
}
let paths = [];
let logins = [];
for each (let path in this._getLoginPaths(md.hostname)) {
let login = this._loadLogin(path);
if (login) {
if (this._fuzzy) {
this._autocomplete(login, md, path);
}
let matches = true;
for (let prop in md) {
if (login[prop] != md[prop]) {
matches = false;
break;
}
}
if (matches) {
paths.push(path);
logins.push(login);
}
}
}
return [logins, paths];
},
_isFirefoxAccount: function(hostname, httpRealm) {
return hostname == "chrome://FirefoxAccounts" &&
httpRealm == "Firefox Accounts credentials"
},
// legacy function called by initialize
init: function init() {
// setup environment
e = Cc["@mozilla.org/process/environment;1"].
getService(Ci.nsIEnvironment)
this._environment = [];
for each (let env in EnvironmentVars) {
if (env.indexOf("=") > 0) {
this._environment.push(env);
} else if (e.exists(env)) {
this._environment.push(env + "=" + e.get(env));
}
}
this._storage_json = Cc["@mozilla.org/login-manager/storage/json;1"].
getService(Ci.nsILoginManagerStorage);
this._storage_json.initialize();
// load preferences
let prefObserver = {
register: function () {
let prefServ = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
this.branch = prefServ.getBranch("extensions.passmanager.");
this.branch.addObserver("", this, false);
// initial loading for preferences
this.observe(this.branch);
},
observe: function (subject, topic, data) {
this.pm._passCmd = subject.getCharPref("pass");
this.pm._fuzzy = subject.getBoolPref("fuzzy");
this.pm._save_as_username = subject.getBoolPref("save_as_username");
this.pm._strip_hostnames = subject.getCharPref("strip_hostnames").
toLowerCase().split(",");
this.pm._cache.defaultLifetime = subject.getIntPref("cache");
// construct realm
let realm = [subject.getCharPref("realm")];
if (subject.getBoolPref("realm.append_product")) {
realm.push(Services.appinfo.name.toLowerCase());
}
this.pm._realm = realm.join("/");
// load property map
this.pm._propMap = {};
for (prop in PropertyMap) {
if (PropertyMap[prop]) {
this.pm._propMap[prop] =
subject.getCharPref("map." + prop.toLowerCase()).
toLowerCase().split(",");
} else {
this.pm._propMap[prop] = false;
}
}
}
};
prefObserver.pm = this;
prefObserver.register();
},
initialize: function initialize() {
this.init();
return Promise.resolve();
},
terminate: function terminate() {
return Promise.resolve();
},
addLogin: function addLogin(login) {
LoginHelper.checkLoginValues(login);
if (this._isFirefoxAccount(login.hostname, login.httpRealm)) {
return this._storage_json.addLogin(login);
}
let paths = this._getLoginPaths(login.hostname);
let filename = "passmanager";
let separator = "";
let max = 0;
if (this._save_as_username) {
let tmp = login.username.replace(/[^a-zA-Z0-9@-_\.]/g, "_").
replace(/_+/g, "_").replace(/(^_|_$)/g, "");
if (tmp) {
filename = tmp;
separator = "_";
max = -1;
}
}
let re = new RegExp("\\/" + RegExp.escape(filename) +
"(?:" + separator + "([0-9]+))?$");
for each (let path in paths) {
let matches = re.exec(path);
if (matches) {
let num = matches[1] ? Number(matches[1]) : 0;
if (num > max) {
max = num;
}
}
}
let path = this._getHostnamePath(login.hostname);
filename = filename + (max >= 0 ? separator + (max + 1) : "");
this._saveLogin(path + "/" + filename, login);
},
removeLogin: function removeLogin(login) {
if (this._isFirefoxAccount(login.hostname, login.httpRealm)) {
return this._storage_json.removeLogin(login);
}
let [logins, paths] = this._filterLogins(login);
for each (let path in paths) {
this._pass(["rm", "-f", path]);
this._cache.del(path);
}
},
modifyLogin: function modifyLogin(oldLogin, newLogin) {
if (this._isFirefoxAccount(oldLogin.hostname, oldLogin.httpRealm)) {
return this._storage_json.modifyLogin(oldLogin, newLogin);
}
// try to find original login
let [logins, paths] = this._filterLogins(oldLogin);
if (logins.length == 0) {
return;
}
if (newLogin instanceof Ci.nsIPropertyBag) {
// we know what we are supposed to change,
// so we can load the original login, without
// autocompletion and only update what's requested
for each (let path in paths) {
let changed = false;
let login = this._loadLogin(path);
let propEnum = newLogin.enumerator;
while (propEnum.hasMoreElements()) {
let prop = propEnum.getNext().QueryInterface(Ci.nsIProperty);
if (prop.name in this._propMap &&
login[prop.name] != prop.value) {
login[prop.name] = prop.value;
changed = true;
}
}
if (changed) {
this._saveLogin(path, login);
}
}
} else {
// newLogin is nsLoginInfo, copy all properties if changed.
// this case does not seem to happen...
let changed = false;
for (let prop in this._propMap) {
if (newLogin[prop] && oldLogin[prop] != newLogin[prop]) {
oldLogin[prop] = newLogin[prop];
changed = true;
}
}
if (changed) {
for each (let path in paths) {
this._saveLogin(path, oldLogin);
}
}
}
},
getAllLogins: function getAllLogins(count) {
let [logins, paths] = this._filterLogins({});
count.value = logins.length;
return logins;
},
removeAllLogins: function removeAllLogins() {
this._pass(["rm", "-r", "-f", this._realm]);
this._cache.clear();
},
getAllDisabledHosts: function getAllDisabledHosts(count) {
this._stub(arguments);
},
getLoginSavingEnabled: function getLoginSavingEnabled(hostname) {
return true;
},
setLoginSavingEnabled: function setLoginSavingEnabled(hostname, enabled) {
this._stub(arguments);
},
searchLogins: function searchLogins(count, matchData) {
// extract from nsPropertyBag
let md = {};
let propEnum = matchData.enumerator;
while (propEnum.hasMoreElements()) {
let prop = propEnum.getNext().QueryInterface(Ci.nsIProperty);
md[prop.name] = prop.value;
}
if (this._isFirefoxAccount(md.hostname, md.httpRealm)) {
return this._storage_json.searchLogins(count, matchData);
}
let [logins, paths] = this._filterLogins(md);
count.value = logins.length;
return logins;
},
findLogins: function findLogins(count, hostname, formSubmitURL, httpRealm) {
if (this._isFirefoxAccount(hostname, httpRealm)) {
return this._storage_json.findLogins(count, hostname,
formSubmitURL, httpRealm);
}
let login= {
hostname: hostname,
formSubmitURL: formSubmitURL,
httpRealm: httpRealm
};
let md = {};
for each (let prop in ["hostname", "formSubmitURL", "httpRealm"]) {
// empty string means wildcard, null means null
if (login[prop] != "") {
md[prop] = login[prop];
}
}
let [logins, paths] = this._filterLogins(md);
count.value = logins.length;
return logins;
},
// called to check if its worth calling findLogins,
// which may prompt for master password or pinentry in our case
countLogins: function countLogins(hostname, formSubmitURL, httpRealm) {
if (this._isFirefoxAccount(hostname, httpRealm)) {
return this._storage_json.countLogins(hostname, formSubmitURL,
httpRealm);
}
// only way to check if we have logins without
// decrypting is by hostname
let paths = this._getLoginPaths(hostname);
return paths.length;
},
get uiBusy() {
return false;
},
get isLoggedIn() {
return true;
}
};
var NSGetFactory = XPCOMUtils.generateNSGetFactory([PassManager]);
|
gekmihesg/pass-manager
|
src/components/passmanager.js
|
JavaScript
|
gpl-3.0
| 15,982
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>QLowEnergyConnectionParameters — PyQt 5.8.2 Reference Guide</title>
<link rel="stylesheet" href="../_static/classic.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '5.8.2',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="shortcut icon" href="../_static/logo_tn.ico"/>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="QLowEnergyController" href="qlowenergycontroller.html" />
<link rel="prev" title="QLowEnergyCharacteristicData" href="qlowenergycharacteristicdata.html" />
</head>
<body role="document">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="qlowenergycontroller.html" title="QLowEnergyController"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="qlowenergycharacteristicdata.html" title="QLowEnergyCharacteristicData"
accesskey="P">previous</a> |</li>
<li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.8.2 Reference Guide</a> »</li>
<li class="nav-item nav-item-1"><a href="../class_reference.html" accesskey="U">PyQt5 Class Reference</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="qlowenergyconnectionparameters">
<h1>QLowEnergyConnectionParameters<a class="headerlink" href="#qlowenergyconnectionparameters" title="Permalink to this headline">¶</a></h1>
<dl class="class">
<dt id="PyQt5.QtBluetooth.QLowEnergyConnectionParameters">
<em class="property">class </em><code class="descclassname">PyQt5.QtBluetooth.</code><code class="descname">QLowEnergyConnectionParameters</code><a class="headerlink" href="#PyQt5.QtBluetooth.QLowEnergyConnectionParameters" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference external" href="https://doc.qt.io/qt-5/qlowenergyconnectionparameters.html">C++ documentation</a></p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="../index.html">
<img class="logo" src="../_static/logo.png" alt="Logo"/>
</a></p>
<h4>Previous topic</h4>
<p class="topless"><a href="qlowenergycharacteristicdata.html"
title="previous chapter">QLowEnergyCharacteristicData</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="qlowenergycontroller.html"
title="next chapter">QLowEnergyController</a></p>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<div><input type="text" name="q" /></div>
<div><input type="submit" value="Go" /></div>
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="qlowenergycontroller.html" title="QLowEnergyController"
>next</a> |</li>
<li class="right" >
<a href="qlowenergycharacteristicdata.html" title="QLowEnergyCharacteristicData"
>previous</a> |</li>
<li class="nav-item nav-item-0"><a href="../index.html">PyQt 5.8.2 Reference Guide</a> »</li>
<li class="nav-item nav-item-1"><a href="../class_reference.html" >PyQt5 Class Reference</a> »</li>
</ul>
</div>
<div class="footer" role="contentinfo">
© Copyright 2015 Riverbank Computing Limited.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.5.3.
</div>
</body>
</html>
|
baoboa/pyqt5
|
doc/html/api/qlowenergyconnectionparameters.html
|
HTML
|
gpl-3.0
| 5,525
|
<!DOCTYPE html>
<html>
<head>
<title>Graphical Equation Manipulator</title>
<link rel="stylesheet" type="text/css" href="./static/styles.min.css">
<link rel="stylesheet" type="text/css" href="./static/jquery-ui.min.css">
<link rel="stylesheet" type="text/css" href="./static/jquery-impromptu.min.css">
<link rel="stylesheet" type="text/css" href="./static/jquery.contextMenu.css">
</head>
<body>
<h1>
Graphical Equation Manipulator
</h1>
<div id="loader">
<p>
Loading... Please wait.<br>
If you see keep seeing this message, you might have JavaScript disabled.<br>
GEM requires JavaScript to run.
</p>
<div id="preloader">
<img src="./static/preloader/fakesun.png" id="preloader-sun">
<img src="./static/preloader/venus.png" id="preloader-venus">
<img src="./static/preloader/earth.png" id="preloader-earth">
<img src="./static/preloader/mars.png" id="preloader-mars">
<img src="./static/preloader/jupiter.png" id="preloader-jupiter">
</div>
<script type="text/javascript" src="./src/preloader.js"></script>
</div>
<div id="gem-window">
<div id="whiteboard-panel">
<div id="connection-space">
<!-- Connections will be dumped here, ensuring they appear behind variables. -->
</div>
</div>
<div id="search-panel">
<input type="text" id="search-box" placeholder="Search for equation">
<div id="search-results">
<ul>
</ul>
</div>
<div id="extra-options">
<button id="extra-add-comment">Add comment</button>
<button id="extra-uncertainties">Symbolic Uncertainties</button>
<button id="extra-clear">Clear Workspace</button>
</div>
</div>
</div>
<div id="footer">
Fork me on GitHub! <a href="http://github.com/MatthewJA">MatthewJA</a>/<strong><a href="http://github.com/MatthewJA/Graphical-Equation-Manipulator">Graphical-Equation-Manipulator</a></strong><br>
Utilises <a href="http://github.com/MatthewJA/Coffeequate">Coffeequate</a>, <a href="http://jquery.com">jQuery</a>, <a href="http://jqueryui.com">jQuery UI</a>, <a href="http://touchpunch.furf.com/">jQuery UI Touch Punch</a>, <a href="http://github.com/benmajor/jQuery-Mobile-Events">jQuery Mobile Events</a>, <a href="http://github.com/arnklint/jquery-contextMenu">jQuery Context Menu</a>, <a href="http://trentrichardson.com/Impromptu/">jQuery Impromptu</a>, <a href="http://www.mathjax.org/">MathJax</a>, </a>and <a href="http://requirejs.org">RequireJS</a>.
</div>
<script data-main="src/gem" src="./src/require.js"></script>
</body>
</html>
|
MatthewJA/Graphical-Equation-Manipulator
|
index.html
|
HTML
|
gpl-3.0
| 2,513
|
<?php
// --------------------------------------------------------------------------------
// PhpConcept Library - Tar Module 1.3.1
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - January 2003
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
// PclTar is a library that allow you to create a GNU TAR + GNU ZIP archive,
// to add files or directories, to extract all the archive or a part of it.
// So far tests show that the files generated by PclTar are readable by
// gzip tools and WinZip application.
//
// Description :
// See readme.txt (English & Fran�ais) and http://www.phpconcept.net
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// ----- Look for double include
if (!defined("PCL_TAR")) {
define("PCL_TAR", 1);
// ----- Configuration variable
// Theses values may be changed by the user of PclTar library
if (!isset($g_pcltar_lib_dir)) {
$g_pcltar_lib_dir = find_in_path("lib/pcltar");
}
// ----- Error codes
// -1 : Unable to open file in binary write mode
// -2 : Unable to open file in binary read mode
// -3 : Invalid parameters
// -4 : File does not exist
// -5 : Filename is too long (max. 99)
// -6 : Not a valid tar file
// -7 : Invalid extracted file size
// -8 : Unable to create directory
// -9 : Invalid archive extension
// -10 : Invalid archive format
// -11 : Unable to delete file (unlink)
// -12 : Unable to rename file (rename)
// -13 : Invalid header checksum
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------
// ----- Global variables
$g_pcltar_version = "1.3.1";
// ----- Extract extension type (.php3/.php/...)
$g_pcltar_extension = "php";
// ----- Include other libraries
// This library should be called by each script before the include of PhpZip
// Library in order to limit the potential 'lib' directory path problem.
if (!defined("PCLERROR_LIB")) {
include($g_pcltar_lib_dir . "/pclerror.lib." . $g_pcltar_extension);
}
if (!defined("PCLTRACE_LIB")) {
include($g_pcltar_lib_dir . "/pcltrace.lib." . $g_pcltar_extension);
}
// --------------------------------------------------------------------------------
// Function : PclTarCreate()
// Description :
// Creates a new archive with name $p_tarname containing the files and/or
// directories indicated in $p_list. If the tar filename extension is
// ".tar", the file will not be compressed. If it is ".tar.gz" or ".tgz"
// it will be a gzip compressed tar archive.
// If you want to use an other extension, you must indicate the mode in
// $p_mode ("tar" or "tgz").
// $p_add_dir and $p_remove_dir give you the ability to store a path
// which is not the real path of the files.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_mode : "tar" for normal tar archive, "tgz" for gzipped tar archive,
// if $p_mode is not specified, it will be determined by the extension.
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// Return Values :
// 1 on success, or an error code (see table at the beginning).
// --------------------------------------------------------------------------------
function PclTarCreate($p_tarname, $p_filelist = "", $p_mode = "", $p_add_dir = "", $p_remove_dir = "") {
TrFctStart(__FILE__, __LINE__, "PclTarCreate",
"tar=$p_tarname, file='$p_filelist', mode=$p_mode, add_dir='$p_add_dir', remove_dir='$p_remove_dir'");
$v_result = 1;
// ----- Look for default mode
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
// ----- Extract the tar format from the extension
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 1, "Auto mode selected : found $p_mode");
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Call the create fct
$v_result = PclTarHandleCreate($p_tarname, $p_filelist, $p_mode, $p_add_dir, $p_remove_dir);
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_filelist)) {
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the create fct
$v_result = PclTarHandleCreate($p_tarname, $v_list, $p_mode, $p_add_dir, $p_remove_dir);
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
$v_result = -3;
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarAdd()
// Description :
// PLEASE DO NOT USE ANY MORE THIS FUNCTION. Use PclTarAddList().
//
// This function is maintained only for compatibility reason
//
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// Return Values :
// 1 on success,
// Or an error code (see list on top).
// --------------------------------------------------------------------------------
function PclTarAdd($p_tarname, $p_filelist) {
TrFctStart(__FILE__, __LINE__, "PclTarAdd", "tar=$p_tarname, file=$p_filelist");
$v_result = 1;
$v_list_detail = array();
// ----- Extract the tar format from the extension
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Call the add fct
$v_result = PclTarHandleAppend($p_tarname, $p_filelist, $p_mode, $v_list_detail, "", "");
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_filelist)) {
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the add fct
$v_result = PclTarHandleAppend($p_tarname, $v_list, $p_mode, $v_list_detail, "", "");
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
$v_result = -3;
}
}
// ----- Cleaning
unset($v_list_detail);
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarAddList()
// Description :
// Add a list of files or directories ($p_filelist) in the tar archive $p_tarname.
// The list can be an array of file/directory names or a string with names
// separated by one space.
// $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
// different from the real path of the file. This is usefull if you want to have PclTar
// running in any directory, and memorize relative path from an other directory.
// If $p_mode is not set it will be automatically computed from the $p_tarname
// extension (.tar, .tar.gz or .tgz).
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// 1 on success,
// Or an error code (see list on top).
// --------------------------------------------------------------------------------
function PclTarAddList($p_tarname, $p_filelist, $p_add_dir = "", $p_remove_dir = "", $p_mode = "") {
TrFctStart(__FILE__, __LINE__, "PclTarAddList",
"tar=$p_tarname, file=$p_filelist, p_add_dir='$p_add_dir', p_remove_dir='$p_remove_dir', mode=$p_mode");
$v_result = 1;
$p_list_detail = array();
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Call the add fct
$v_result = PclTarHandleAppend($p_tarname, $p_filelist, $p_mode, $p_list_detail, $p_add_dir, $p_remove_dir);
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_filelist)) {
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the add fct
$v_result = PclTarHandleAppend($p_tarname, $v_list, $p_mode, $p_list_detail, $p_add_dir, $p_remove_dir);
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
$v_result = -3;
}
}
// ----- Return
if ($v_result != 1) {
TrFctEnd(__FILE__, __LINE__, 0);
return 0;
}
TrFctEnd(__FILE__, __LINE__, $p_list_detail);
return $p_list_detail;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarList()
// Description :
// Gives the list of all the files present in the tar archive $p_tarname.
// The list is the function result, it will be 0 on error.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// 0 on error (Use PclErrorCode() and PclErrorString() for more info)
// or
// An array containing file properties. Each file properties is an array of
// properties.
// The properties (array field names) are :
// filename, size, mode, uid, gid, mtime, typeflag, status
// Exemple : $v_list = PclTarList("my.tar");
// for ($i=0; $i<sizeof($v_list); $i++)
// echo "Filename :'".$v_list[$i][filename]."'<br>";
// --------------------------------------------------------------------------------
function PclTarList($p_tarname, $p_mode = "") {
TrFctStart(__FILE__, __LINE__, "PclTarList", "tar=$p_tarname, mode='$p_mode'");
$v_result = 1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = PclTarHandleExtract($p_tarname, 0, $p_list, "list", "", $p_mode, "")) != 1) {
unset($p_list);
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarExtract()
// Description :
// Extract all the files present in the archive $p_tarname, in the directory
// $p_path. The relative path of the archived files are keep and become
// relative to $p_path.
// If a file with the same name already exists it will be replaced.
// If the path to the file does not exist, it will be created.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file.
// $p_path : Path where the files will be extracted. The files will use
// their memorized path from $p_path.
// If $p_path is "", files will be extracted in "./".
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_path and $p_remove_path are commulative.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// Same as PclTarList()
// --------------------------------------------------------------------------------
function PclTarExtract($p_tarname, $p_path = "./", $p_remove_path = "", $p_mode = "") {
TrFctStart(__FILE__, __LINE__, "PclTarExtract",
"tar='$p_tarname', path='$p_path', remove_path='$p_remove_path', mode='$p_mode'");
$v_result = 1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtract($p_tarname, 0, $p_list, "complete", $p_path, $v_tar_mode,
$p_remove_path)) != 1
) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarExtractList()
// Description :
// Extract the files present in the archive $p_tarname and specified in
// $p_filelist, in the directory
// $p_path. The relative path of the archived files are keep and become
// relative to $p_path.
// If a directory is sp�cified in the list, all the files from this directory
// will be extracted.
// If a file with the same name already exists it will be replaced.
// If the path to the file does not exist, it will be created.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_path : Path where the files will be extracted. The files will use
// their memorized path from $p_path.
// If $p_path is "", files will be extracted in "./".
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_path and $p_remove_path are commulative.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// Same as PclTarList()
// --------------------------------------------------------------------------------
function PclTarExtractList($p_tarname, $p_filelist, $p_path = "./", $p_remove_path = "", $p_mode = "") {
TrFctStart(__FILE__, __LINE__, "PclTarExtractList",
"tar=$p_tarname, list, path=$p_path, remove_path='$p_remove_path', mode='$p_mode'");
$v_result = 1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtract($p_tarname, $p_filelist, $p_list, "partial", $p_path, $v_tar_mode,
$p_remove_path)) != 1
) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_filelist)) {
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtract($p_tarname, $v_list, $p_list, "partial", $p_path, $v_tar_mode,
$p_remove_path)) != 1
) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarExtractIndex()
// Description :
// Extract the files present in the archive $p_tarname and specified at
// the indexes in $p_index, in the directory
// $p_path. The relative path of the archived files are keep and become
// relative to $p_path.
// If a directory is specified in the list, the directory only is created. All
// the file stored in this archive for this directory
// are not extracted.
// If a file with the same name already exists it will be replaced.
// If the path to the file does not exist, it will be created.
// Depending on the $p_tarname extension (.tar, .tar.gz or .tgz) the
// function will determine the type of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_index : A single index (integer) or a string of indexes of files to
// extract. The form of the string is "0,4-6,8-12" with only numbers
// and '-' for range or ',' to separate ranges. No spaces or ';'
// are allowed.
// $p_path : Path where the files will be extracted. The files will use
// their memorized path from $p_path.
// If $p_path is "", files will be extracted in "./".
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_path and $p_remove_path are commulative.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// Same as PclTarList()
// --------------------------------------------------------------------------------
function PclTarExtractIndex($p_tarname, $p_index, $p_path = "./", $p_remove_path = "", $p_mode = "") {
TrFctStart(__FILE__, __LINE__, "PclTarExtractIndex",
"tar=$p_tarname, index='$p_index', path=$p_path, remove_path='$p_remove_path', mode='$p_mode'");
$v_result = 1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Look if the $p_index is really an integer
if (is_integer($p_index)) {
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtractByIndexList($p_tarname, "$p_index", $p_list, $p_path, $p_remove_path,
$v_tar_mode)) != 1
) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_index)) {
// ----- Call the extracting fct
if (($v_result = PclTarHandleExtractByIndexList($p_tarname, $p_index, $p_list, $p_path, $p_remove_path,
$v_tar_mode)) != 1
) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type $p_index");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarDelete()
// Description :
// This function deletes from the archive $p_tarname the files which are listed
// in $p_filelist. $p_filelist can be a string with file names separated by
// spaces, or an array containing the file names.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array or a string containing file names to remove from the
// archive.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// List of the files which are kept in the archive (same format as PclTarList())
// --------------------------------------------------------------------------------
function PclTarDelete($p_tarname, $p_filelist, $p_mode = "") {
TrFctStart(__FILE__, __LINE__, "PclTarDelete", "tar='$p_tarname', list='$p_filelist', mode='$p_mode'");
$v_result = 1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Call the extracting fct
if (($v_result = PclTarHandleDelete($p_tarname, $p_filelist, $p_list, $p_mode)) != 1) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_filelist)) {
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the extracting fct
if (($v_result = PclTarHandleDelete($p_tarname, $v_list, $p_list, $p_mode)) != 1) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarUpdate()
// Description :
// This function updates the files in $p_filelist which are already in the
// $p_tarname archive with an older last modified date. If the file does not
// exist, it is added at the end of the archive.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_filelist : An array or a string containing file names to update from the
// archive.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// Return Values :
// List of the files contained in the archive. The field status contains
// "updated", "not_updated", "added" or "ok" for the files not concerned.
// --------------------------------------------------------------------------------
function PclTarUpdate($p_tarname, $p_filelist, $p_mode = "", $p_add_dir = "", $p_remove_dir = "") {
TrFctStart(__FILE__, __LINE__, "PclTarUpdate", "tar='$p_tarname', list='$p_filelist', mode='$p_mode'");
$v_result = 1;
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Call the extracting fct
if (($v_result = PclTarHandleUpdate($p_tarname, $p_filelist, $p_list, $p_mode, $p_add_dir, $p_remove_dir)) != 1) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Look if the $p_filelist is a string
else {
if (is_string($p_filelist)) {
// ----- Create a list with the elements from the string
$v_list = explode(" ", $p_filelist);
// ----- Call the extracting fct
if (($v_result = PclTarHandleUpdate($p_tarname, $v_list, $p_list, $p_mode, $p_add_dir, $p_remove_dir)) != 1) {
TrFctEnd(__FILE__, __LINE__, 0, PclErrorString());
return (0);
}
} // ----- Invalid variable
else {
// ----- Error log
PclErrorLog(-3, "Invalid variable type p_filelist");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $p_list);
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarMerge()
// Description :
// This function add the content of $p_tarname_add at the end of $p_tarname.
// Parameters :
// $p_tarname : Name of an existing tar file
// $p_tarname_add : Name of an existing tar file taht will be added at the end
// of $p_tarname.
// $p_mode : 'tar' or 'tgz', if not set, will be determined by $p_tarname extension
// $p_mode_add : 'tar' or 'tgz', if not set, will be determined by $p_tarname_add
// extension
// Return Values :
// List of the files contained in the archive. The field status contains
// "updated", "not_updated", "added" or "ok" for the files not concerned.
// --------------------------------------------------------------------------------
function PclTarMerge($p_tarname, $p_tarname_add, $p_mode = "", $p_mode_add = "") {
TrFctStart(__FILE__, __LINE__, "PclTarMerge",
"tar='$p_tarname', tar_add='$p_tarname_add', mode='$p_mode', mode_add='$p_mode_add'");
$v_result = 1;
// ----- Check the parameters
if (($p_tarname == "") || ($p_tarname_add == "")) {
// ----- Error log
PclErrorLog(-3, "Invalid empty archive name");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Extract the tar format from the extension
if (($p_mode == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
if (($p_mode = PclTarHandleExtension($p_tarname)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
if (($p_mode_add == "") || (($p_mode_add != "tar") && ($p_mode_add != "tgz"))) {
if (($p_mode_add = PclTarHandleExtension($p_tarname_add)) == "") {
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return 0;
}
}
// ----- Clear filecache
clearstatcache();
// ----- Check the file size
if ((!is_file($p_tarname)) ||
(((($v_size = filesize($p_tarname)) % 512) != 0) && ($p_mode == "tar"))
) {
// ----- Error log
if (!is_file($p_tarname)) {
PclErrorLog(-4, "Archive '$p_tarname' does not exist");
} else {
PclErrorLog(-6, "Archive '$p_tarname' has invalid size " . filesize($p_tarname) . "(not a 512 block multiple)");
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
if ((!is_file($p_tarname_add)) ||
(((($v_size_add = filesize($p_tarname_add)) % 512) != 0) && ($p_mode_add == "tar"))
) {
// ----- Error log
if (!is_file($p_tarname_add)) {
PclErrorLog(-4, "Archive '$p_tarname_add' does not exist");
} else {
PclErrorLog(-6,
"Archive '$p_tarname_add' has invalid size " . filesize($p_tarname_add) . "(not a 512 block multiple)");
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Look for compressed archive
if ($p_mode == "tgz") {
// ----- Open the file in read mode
if (($p_tar = @gzopen($p_tarname, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open a temporary file in write mode
$v_temp_tarname = uniqid("pcltar-") . ".tmp";
TrFctMessage(__FILE__, __LINE__, 2, "Creating temporary archive file $v_temp_tarname");
if (($v_temp_tar = @gzopen($v_temp_tarname, "wb")) == 0) {
// ----- Close tar file
gzclose($p_tar);
// ----- Error log
PclErrorLog(-1, "Unable to open file '$v_temp_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Read the first 512 bytes block
$v_buffer = gzread($p_tar, 512);
// ----- Read the following blocks but not the last one
if (!gzeof($p_tar)) {
TrFctMessage(__FILE__, __LINE__, 3, "More than one 512 block file");
$i = 1;
// ----- Read new 512 block and write the already read
do {
// ----- Write the already read block
$v_binary_data = pack("a512", "$v_buffer");
gzputs($v_temp_tar, $v_binary_data);
$i++;
TrFctMessage(__FILE__, __LINE__, 3, "Reading block $i");
// ----- Read next block
$v_buffer = gzread($p_tar, 512);
} while (!gzeof($p_tar));
TrFctMessage(__FILE__, __LINE__, 3, "$i 512 bytes blocks");
}
} // ----- Look for uncompressed tar file
else {
if ($p_mode == "tar") {
// ----- Open the tar file
if (($p_tar = fopen($p_tarname, "r+b")) == 0) {
// ----- Error log
PclErrorLog(-1, "Unable to open file '$p_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Go to the beginning of last block
TrFctMessage(__FILE__, __LINE__, 4, "Position before :" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
fseek($p_tar, $v_size - 512);
TrFctMessage(__FILE__, __LINE__, 4, "Position after :" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
} // ----- Look for unknown type
else {
// ----- Error log
PclErrorLog(-3, "Invalid tar mode $p_mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
}
// ----- Look for type of archive to add
if ($p_mode_add == "tgz") {
TrFctMessage(__FILE__, __LINE__, 4, "Opening file $p_tarname_add");
// ----- Open the file in read mode
if (($p_tar_add = @gzopen($p_tarname_add, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname_add' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Read the first 512 bytes block
$v_buffer = gzread($p_tar_add, 512);
// ----- Read the following blocks but not the last one
if (!gzeof($p_tar_add)) {
TrFctMessage(__FILE__, __LINE__, 3, "More than one 512 block file");
$i = 1;
// ----- Read new 512 block and write the already read
do {
// ----- Write the already read block
$v_binary_data = pack("a512", "$v_buffer");
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data);
} else {
gzputs($v_temp_tar, $v_binary_data);
}
$i++;
TrFctMessage(__FILE__, __LINE__, 3, "Reading block $i");
// ----- Read next block
$v_buffer = gzread($p_tar_add, 512);
} while (!gzeof($p_tar_add));
TrFctMessage(__FILE__, __LINE__, 3, "$i 512 bytes blocks");
}
// ----- Close the files
gzclose($p_tar_add);
} // ----- Look for uncompressed tar file
else {
if ($p_mode == "tar") {
// ----- Open the file in read mode
if (($p_tar_add = @fopen($p_tarname_add, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname_add' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Read the first 512 bytes block
$v_buffer = fread($p_tar_add, 512);
// ----- Read the following blocks but not the last one
if (!feof($p_tar_add)) {
TrFctMessage(__FILE__, __LINE__, 3, "More than one 512 block file");
$i = 1;
// ----- Read new 512 block and write the already read
do {
// ----- Write the already read block
$v_binary_data = pack("a512", "$v_buffer");
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data);
} else {
gzputs($v_temp_tar, $v_binary_data);
}
$i++;
TrFctMessage(__FILE__, __LINE__, 3, "Reading block $i");
// ----- Read next block
$v_buffer = fread($p_tar_add, 512);
} while (!feof($p_tar_add));
TrFctMessage(__FILE__, __LINE__, 3, "$i 512 bytes blocks");
}
// ----- Close the files
fclose($p_tar_add);
}
}
// ----- Call the footer of the tar archive
$v_result = PclTarHandleFooter($p_tar, $p_mode);
// ----- Look for closing compressed archive
if ($p_mode == "tgz") {
// ----- Close the files
gzclose($p_tar);
gzclose($v_temp_tar);
// ----- Unlink tar file
if (!@unlink($p_tarname)) {
// ----- Error log
PclErrorLog(-11, "Error while deleting archive name $p_tarname");
}
// ----- Rename tar file
if (!@rename($v_temp_tarname, $p_tarname)) {
// ----- Error log
PclErrorLog(-12, "Error while renaming temporary file $v_temp_tarname to archive name $p_tarname");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
} // ----- Look for closing uncompressed tar file
else {
if ($p_mode == "tar") {
// ----- Close the tarfile
fclose($p_tar);
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleCreate()
// Description :
// Parameters :
// $p_tarname : Name of the tar file
// $p_list : An array containing the file or directory names to add in the tar
// $p_mode : "tar" for normal tar archive, "tgz" for gzipped tar archive
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleCreate($p_tarname, $p_list, $p_mode, $p_add_dir = "", $p_remove_dir = "") {
TrFctStart(__FILE__, __LINE__, "PclTarHandleCreate",
"tar=$p_tarname, list, mode=$p_mode, add_dir='$p_add_dir', remove_dir='$p_remove_dir'");
$v_result = 1;
$v_list_detail = array();
// ----- Check the parameters
if (($p_tarname == "") || (($p_mode != "tar") && ($p_mode != "tgz"))) {
// ----- Error log
if ($p_tarname == "") {
PclErrorLog(-3, "Invalid empty archive name");
} else {
PclErrorLog(-3, "Unknown mode '$p_mode'");
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Look for tar file
if ($p_mode == "tar") {
// ----- Open the tar file
if (($p_tar = fopen($p_tarname, "wb")) == 0) {
// ----- Error log
PclErrorLog(-1, "Unable to open file [$p_tarname] in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Call the adding fct inside the tar
if (($v_result = PclTarHandleAddList($p_tar, $p_list, $p_mode, $v_list_detail, $p_add_dir, $p_remove_dir)) == 1) {
// ----- Call the footer of the tar archive
$v_result = PclTarHandleFooter($p_tar, $p_mode);
}
// ----- Close the tarfile
fclose($p_tar);
} // ----- Look for tgz file
else {
// ----- Open the tar file
if (($p_tar = @gzopen($p_tarname, "wb")) == 0) {
// ----- Error log
PclErrorLog(-1, "Unable to open file [$p_tarname] in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Call the adding fct inside the tar
if (($v_result = PclTarHandleAddList($p_tar, $p_list, $p_mode, $v_list_detail, $p_add_dir, $p_remove_dir)) == 1) {
// ----- Call the footer of the tar archive
$v_result = PclTarHandleFooter($p_tar, $p_mode);
}
// ----- Close the tarfile
gzclose($p_tar);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleAppend()
// Description :
// Parameters :
// $p_tarname : Name of the tar file
// $p_list : An array containing the file or directory names to add in the tar
// $p_mode : "tar" for normal tar archive, "tgz" for gzipped tar archive
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleAppend($p_tarname, $p_list, $p_mode, &$p_list_detail, $p_add_dir, $p_remove_dir) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleAppend", "tar=$p_tarname, list, mode=$p_mode");
$v_result = 1;
// ----- Check the parameters
if ($p_tarname == "") {
// ----- Error log
PclErrorLog(-3, "Invalid empty archive name");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
clearstatcache();
// ----- Check the file size
if ((!is_file($p_tarname)) ||
(((($v_size = filesize($p_tarname)) % 512) != 0) && ($p_mode == "tar"))
) {
// ----- Error log
if (!is_file($p_tarname)) {
PclErrorLog(-4, "Archive '$p_tarname' does not exist");
} else {
PclErrorLog(-6, "Archive '$p_tarname' has invalid size " . filesize($p_tarname) . "(not a 512 block multiple)");
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Look for compressed archive
if ($p_mode == "tgz") {
// ----- Open the file in read mode
if (($p_tar = @gzopen($p_tarname, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open a temporary file in write mode
$v_temp_tarname = uniqid("pcltar-") . ".tmp";
TrFctMessage(__FILE__, __LINE__, 2, "Creating temporary archive file $v_temp_tarname");
if (($v_temp_tar = @gzopen($v_temp_tarname, "wb")) == 0) {
// ----- Close tar file
gzclose($p_tar);
// ----- Error log
PclErrorLog(-1, "Unable to open file '$v_temp_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Read the first 512 bytes block
$v_buffer = gzread($p_tar, 512);
// ----- Read the following blocks but not the last one
if (!gzeof($p_tar)) {
TrFctMessage(__FILE__, __LINE__, 3, "More than one 512 block file");
$i = 1;
// ----- Read new 512 block and write the already read
do {
// ----- Write the already read block
$v_binary_data = pack("a512", "$v_buffer");
gzputs($v_temp_tar, $v_binary_data);
$i++;
TrFctMessage(__FILE__, __LINE__, 3, "Reading block $i");
// ----- Read next block
$v_buffer = gzread($p_tar, 512);
} while (!gzeof($p_tar));
TrFctMessage(__FILE__, __LINE__, 3, "$i 512 bytes blocks");
}
// ----- Call the adding fct inside the tar
if (($v_result = PclTarHandleAddList($v_temp_tar, $p_list, $p_mode, $p_list_detail, $p_add_dir,
$p_remove_dir)) == 1
) {
// ----- Call the footer of the tar archive
$v_result = PclTarHandleFooter($v_temp_tar, $p_mode);
}
// ----- Close the files
gzclose($p_tar);
gzclose($v_temp_tar);
// ----- Unlink tar file
if (!@unlink($p_tarname)) {
// ----- Error log
PclErrorLog(-11, "Error while deleting archive name $p_tarname");
}
// ----- Rename tar file
if (!@rename($v_temp_tarname, $p_tarname)) {
// ----- Error log
PclErrorLog(-12, "Error while renaming temporary file $v_temp_tarname to archive name $p_tarname");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
} // ----- Look for uncompressed tar file
else {
if ($p_mode == "tar") {
// ----- Open the tar file
if (($p_tar = fopen($p_tarname, "r+b")) == 0) {
// ----- Error log
PclErrorLog(-1, "Unable to open file '$p_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Go to the beginning of last block
TrFctMessage(__FILE__, __LINE__, 4, "Position before :" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
fseek($p_tar, $v_size - 512);
TrFctMessage(__FILE__, __LINE__, 4, "Position after :" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
// ----- Call the adding fct inside the tar
if (($v_result = PclTarHandleAddList($p_tar, $p_list, $p_mode, $p_list_detail, $p_add_dir,
$p_remove_dir)) == 1
) {
// ----- Call the footer of the tar archive
$v_result = PclTarHandleFooter($p_tar, $p_mode);
}
// ----- Close the tarfile
fclose($p_tar);
} // ----- Look for unknown type
else {
// ----- Error log
PclErrorLog(-3, "Invalid tar mode $p_mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleAddList()
// Description :
// $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
// different from the real path of the file. This is usefull if you want to have PclTar
// running in any directory, and memorize relative path from an other directory.
// Parameters :
// $p_tar : File descriptor of the tar archive
// $p_list : An array containing the file or directory names to add in the tar
// $p_mode : "tar" for normal tar archive, "tgz" for gzipped tar archive
// $p_list_detail : list of added files with their properties (specially the status field)
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleAddList($p_tar, $p_list, $p_mode, &$p_list_detail, $p_add_dir, $p_remove_dir) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleAddList",
"tar='$p_tar', list, mode='$p_mode', add_dir='$p_add_dir', remove_dir='$p_remove_dir'");
$v_result = 1;
$v_header = array();
// ----- Recuperate the current number of elt in list
$v_nb = sizeof($p_list_detail);
// ----- Check the parameters
if ($p_tar == 0) {
// ----- Error log
PclErrorLog(-3, "Invalid file descriptor in file " . __FILE__ . ", line " . __LINE__);
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Check the arguments
if (sizeof($p_list) == 0) {
// ----- Error log
PclErrorLog(-3, "Invalid file list parameter (invalid or empty list)");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Loop on the files
for ($j = 0; ($j < count($p_list)) && ($v_result == 1); $j++) {
// ----- Recuperate the filename
$p_filename = $p_list[$j];
TrFctMessage(__FILE__, __LINE__, 2, "Looking for file [$p_filename]");
// ----- Skip empty file names
if ($p_filename == "") {
TrFctMessage(__FILE__, __LINE__, 2, "Skip empty filename");
continue;
}
// ----- Check the filename
if (!file_exists($p_filename)) {
// ----- Error log
TrFctMessage(__FILE__, __LINE__, 2, "File '$p_filename' does not exists");
PclErrorLog(-4, "File '$p_filename' does not exists");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Check the path length
if (strlen($p_filename) > 99) {
// ----- Error log
PclErrorLog(-5, "File name is too long (max. 99) : '$p_filename'");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
TrFctMessage(__FILE__, __LINE__, 4,
"File position before header =" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
// ----- Add the file
if (($v_result = PclTarHandleAddFile($p_tar, $p_filename, $p_mode, $v_header, $p_add_dir, $p_remove_dir)) != 1) {
// ----- Return status
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the file infos
$p_list_detail[$v_nb++] = $v_header;
// ----- Look for directory
if (is_dir($p_filename)) {
TrFctMessage(__FILE__, __LINE__, 2, "$p_filename is a directory");
// ----- Look for path
if ($p_filename != ".") {
$v_path = $p_filename . "/";
} else {
$v_path = "";
}
// ----- Read the directory for files and sub-directories
$p_hdir = opendir($p_filename);
$p_hitem = readdir($p_hdir); // '.' directory
$p_hitem = readdir($p_hdir); // '..' directory
while ($p_hitem = readdir($p_hdir)) {
// ----- Look for a file
if (is_file($v_path . $p_hitem)) {
TrFctMessage(__FILE__, __LINE__, 4, "Add the file '" . $v_path . $p_hitem . "'");
// ----- Add the file
if (($v_result = PclTarHandleAddFile($p_tar, $v_path . $p_hitem, $p_mode, $v_header, $p_add_dir,
$p_remove_dir)) != 1
) {
// ----- Return status
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Store the file infos
$p_list_detail[$v_nb++] = $v_header;
} // ----- Recursive call to PclTarHandleAddFile()
else {
TrFctMessage(__FILE__, __LINE__, 4, "'" . $v_path . $p_hitem . "' is a directory");
// ----- Need an array as parameter
$p_temp_list[0] = $v_path . $p_hitem;
$v_result = PclTarHandleAddList($p_tar, $p_temp_list, $p_mode, $p_list_detail, $p_add_dir, $p_remove_dir);
}
}
// ----- Free memory for the recursive loop
unset($p_temp_list);
unset($p_hdir);
unset($p_hitem);
} else {
TrFctMessage(__FILE__, __LINE__, 4,
"File position after blocks =" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleAddFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleAddFile($p_tar, $p_filename, $p_mode, &$p_header, $p_add_dir, $p_remove_dir) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleAddFile",
"tar='$p_tar', filename='$p_filename', p_mode='$p_mode', add_dir='$p_add_dir', remove_dir='$p_remove_dir'");
$v_result = 1;
// ----- Check the parameters
if ($p_tar == 0) {
// ----- Error log
PclErrorLog(-3, "Invalid file descriptor in file " . __FILE__ . ", line " . __LINE__);
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Skip empty file names
if ($p_filename == "") {
// ----- Error log
PclErrorLog(-3, "Invalid file list parameter (invalid or empty list)");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Calculate the stored filename
$v_stored_filename = $p_filename;
if ($p_remove_dir != "") {
if (substr($p_remove_dir, -1) != '/') {
$p_remove_dir .= "/";
}
if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) {
if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) {
$p_remove_dir = "./" . $p_remove_dir;
}
if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) {
$p_remove_dir = substr($p_remove_dir, 2);
}
}
if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) {
$v_stored_filename = substr($p_filename, strlen($p_remove_dir));
TrFctMessage(__FILE__, __LINE__, 3, "Remove path '$p_remove_dir' in file '$p_filename' = '$v_stored_filename'");
}
}
if ($p_add_dir != "") {
if (substr($p_add_dir, -1) == "/") {
$v_stored_filename = $p_add_dir . $v_stored_filename;
} else {
$v_stored_filename = $p_add_dir . "/" . $v_stored_filename;
}
TrFctMessage(__FILE__, __LINE__, 3, "Add path '$p_add_dir' in file '$p_filename' = '$v_stored_filename'");
}
// ----- Check the path length
if (strlen($v_stored_filename) > 99) {
// ----- Error log
PclErrorLog(-5, "Stored file name is too long (max. 99) : '$v_stored_filename'");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Look for a file
if (is_file($p_filename)) {
// ----- Open the source file
if (($v_file = fopen($p_filename, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_filename' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Call the header generation
if (($v_result = PclTarHandleHeader($p_tar, $p_filename, $p_mode, $p_header, $v_stored_filename)) != 1) {
// ----- Return status
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
TrFctMessage(__FILE__, __LINE__, 4,
"File position after header =" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
// ----- Read the file by 512 octets blocks
$i = 0;
while (($v_buffer = fread($v_file, 512)) != "") {
$v_binary_data = pack("a512", "$v_buffer");
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data);
} else {
gzputs($p_tar, $v_binary_data);
}
$i++;
}
TrFctMessage(__FILE__, __LINE__, 2, "$i 512 bytes blocks");
// ----- Close the file
fclose($v_file);
TrFctMessage(__FILE__, __LINE__, 4,
"File position after blocks =" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
} // ----- Look for a directory
else {
// ----- Call the header generation
if (($v_result = PclTarHandleHeader($p_tar, $p_filename, $p_mode, $p_header, $v_stored_filename)) != 1) {
// ----- Return status
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
TrFctMessage(__FILE__, __LINE__, 4,
"File position after header =" . ($p_mode == "tar" ? ftell($p_tar) : gztell($p_tar)));
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleHeader()
// Description :
// This function creates in the TAR $p_tar, the TAR header for the file
// $p_filename.
//
// 1. The informations needed to compose the header are recuperated and formatted
// 2. Two binary strings are composed for the first part of the header, before
// and after checksum field.
// 3. The checksum is calculated from the two binary strings
// 4. The header is write in the tar file (first binary string, binary string
// for checksum and last binary string).
// Parameters :
// $p_tar : a valid file descriptor, opened in write mode,
// $p_filename : The name of the file the header is for,
// $p_mode : The mode of the archive ("tar" or "tgz").
// $p_header : A pointer to a array where will be set the file properties
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleHeader($p_tar, $p_filename, $p_mode, &$p_header, $p_stored_filename) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleHeader",
"tar=$p_tar, file='$p_filename', mode='$p_mode', stored_filename='$p_stored_filename'");
$v_result = 1;
// ----- Check the parameters
if (($p_tar == 0) || ($p_filename == "")) {
// ----- Error log
PclErrorLog(-3, "Invalid file descriptor in file " . __FILE__ . ", line " . __LINE__);
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Filename (reduce the path of stored name)
if ($p_stored_filename == "") {
$p_stored_filename = $p_filename;
}
$v_reduce_filename = PclTarHandlePathReduction($p_stored_filename);
TrFctMessage(__FILE__, __LINE__, 2,
"Filename (reduced) '$v_reduce_filename', strlen " . strlen($v_reduce_filename));
// ----- Get file info
$v_info = stat($p_filename);
$v_uid = sprintf("%6s ", DecOct($v_info[4]));
$v_gid = sprintf("%6s ", DecOct($v_info[5]));
TrFctMessage(__FILE__, __LINE__, 3, "uid=$v_uid, gid=$v_gid");
$v_perms = sprintf("%6s ", DecOct(fileperms($p_filename)));
TrFctMessage(__FILE__, __LINE__, 3, "file permissions $v_perms");
// ----- File mtime
$v_mtime_data = filemtime($p_filename);
TrFctMessage(__FILE__, __LINE__, 2, "File mtime : $v_mtime_data");
$v_mtime = sprintf("%11s", DecOct($v_mtime_data));
// ----- File typeflag
// '0' or '\0' is the code for regular file
// '5' is directory
if (is_dir($p_filename)) {
$v_typeflag = "5";
$v_size = 0;
} else {
$v_typeflag = "";
// ----- Get the file size
clearstatcache();
$v_size = filesize($p_filename);
}
TrFctMessage(__FILE__, __LINE__, 2, "File size : $v_size");
$v_size = sprintf("%11s ", DecOct($v_size));
TrFctMessage(__FILE__, __LINE__, 2, "File typeflag : $v_typeflag");
// ----- Linkname
$v_linkname = "";
// ----- Magic
$v_magic = "";
// ----- Version
$v_version = "";
// ----- uname
$v_uname = "";
// ----- gname
$v_gname = "";
// ----- devmajor
$v_devmajor = "";
// ----- devminor
$v_devminor = "";
// ----- prefix
$v_prefix = "";
// ----- Compose the binary string of the header in two parts arround the checksum position
$v_binary_data_first = pack("a100a8a8a8a12A12", $v_reduce_filename, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime);
$v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname,
$v_gname, $v_devmajor, $v_devminor, $v_prefix, "");
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i = 0; $i < 148; $i++) {
$v_checksum += ord(substr($v_binary_data_first, $i, 1));
}
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i = 148; $i < 156; $i++) {
$v_checksum += ord(' ');
}
// ..... Last part of the header
for ($i = 156, $j = 0; $i < 512; $i++, $j++) {
$v_checksum += ord(substr($v_binary_data_last, $j, 1));
}
TrFctMessage(__FILE__, __LINE__, 3, "Calculated checksum : $v_checksum");
// ----- Write the first 148 bytes of the header in the archive
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data_first, 148);
} else {
gzputs($p_tar, $v_binary_data_first, 148);
}
// ----- Write the calculated checksum
$v_checksum = sprintf("%6s ", DecOct($v_checksum));
$v_binary_data = pack("a8", $v_checksum);
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data, 8);
} else {
gzputs($p_tar, $v_binary_data, 8);
}
// ----- Write the last 356 bytes of the header in the archive
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data_last, 356);
} else {
gzputs($p_tar, $v_binary_data_last, 356);
}
// ----- Set the properties in the header "structure"
$p_header[filename] = $v_reduce_filename;
$p_header[mode] = $v_perms;
$p_header[uid] = $v_uid;
$p_header[gid] = $v_gid;
$p_header[size] = $v_size;
$p_header[mtime] = $v_mtime;
$p_header[typeflag] = $v_typeflag;
$p_header[status] = "added";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleFooter()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleFooter($p_tar, $p_mode) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleFooter", "tar='$p_tar', p_mode=$p_mode");
$v_result = 1;
// ----- Write the last 0 filled block for end of archive
$v_binary_data = pack("a512", "");
if ($p_mode == "tar") {
fputs($p_tar, $v_binary_data);
} else {
gzputs($p_tar, $v_binary_data);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtract()
// Description :
// Parameters :
// $p_tarname : Filename of the tar (or tgz) archive
// $p_file_list : An array which contains the list of files to extract, this
// array may be empty when $p_mode is 'complete'
// $p_list_detail : An array where will be placed the properties of each extracted/listed file
// $p_mode : 'complete' will extract all files from the archive,
// 'partial' will look for files in $p_file_list
// 'list' will only list the files from the archive without any extract
// $p_path : Path to add while writing the extracted files
// $p_tar_mode : 'tar' for GNU TAR archive, 'tgz' for compressed archive
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtract(
$p_tarname,
$p_file_list,
&$p_list_detail,
$p_mode,
$p_path,
$p_tar_mode,
$p_remove_path
) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtract",
"archive='$p_tarname', list, mode=$p_mode, path=$p_path, tar_mode=$p_tar_mode, remove_path='$p_remove_path'");
$v_result = 1;
$v_nb = 0;
$v_extract_all = true;
$v_listing = false;
// ----- Check the path
if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../"))) {
$p_path = "./" . $p_path;
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) {
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Study the mode
switch ($p_mode) {
case "complete" :
// ----- Flag extract of all files
$v_extract_all = true;
$v_listing = false;
break;
case "partial" :
// ----- Flag extract of specific files
$v_extract_all = false;
$v_listing = false;
break;
case "list" :
// ----- Flag list of all files
$v_extract_all = false;
$v_listing = true;
break;
default :
// ----- Error log
PclErrorLog(-3, "Invalid extract mode ($p_mode)");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open the tar file
if ($p_tar_mode == "tar") {
TrFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
$v_tar = fopen($p_tarname, "rb");
} else {
TrFctMessage(__FILE__, __LINE__, 3, "Open file in gzip binary read mode");
$v_tar = @gzopen($p_tarname, "rb");
}
// ----- Check that the archive is open
if ($v_tar == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open archive '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Read the blocks
while (!($v_end_of_file = ($p_tar_mode == "tar" ? feof($v_tar) : gzeof($v_tar)))) {
TrFctMessage(__FILE__, __LINE__, 3, "Looking for next header ...");
// ----- Clear cache of file infos
clearstatcache();
// ----- Reset extract tag
$v_extract_file = false;
$v_extraction_stopped = 0;
// ----- Read the 512 bytes header
if ($p_tar_mode == "tar") {
$v_binary_data = fread($v_tar, 512);
} else {
$v_binary_data = gzread($v_tar, 512);
}
// ----- Read the header properties
if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1) {
// ----- Close the archive file
if ($p_tar_mode == "tar") {
fclose($v_tar);
} else {
gzclose($v_tar);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for empty blocks to skip
if ($v_header[filename] == "") {
TrFctMessage(__FILE__, __LINE__, 2, "Empty block found. End of archive ?");
continue;
}
TrFctMessage(__FILE__, __LINE__, 2, "Found file '$v_header[filename]', size '$v_header[size]'");
// ----- Look for partial extract
if ((!$v_extract_all) && (is_array($p_file_list))) {
TrFctMessage(__FILE__, __LINE__, 2, "Look if the file '$v_header[filename]' need to be extracted");
// ----- By default no unzip if the file is not found
$v_extract_file = false;
// ----- Look into the file list
for ($i = 0; $i < sizeof($p_file_list); $i++) {
TrFctMessage(__FILE__, __LINE__, 2,
"Compare archived file '$v_header[filename]' from asked list file '" . $p_file_list[$i] . "'");
// ----- Look if it is a directory
if (substr($p_file_list[$i], -1) == "/") {
TrFctMessage(__FILE__, __LINE__, 3, "Compare file '$v_header[filename]' with directory '$p_file_list[$i]'");
// ----- Look if the directory is in the filename path
if ((strlen($v_header[filename]) > strlen($p_file_list[$i])) && (substr($v_header[filename], 0,
strlen($p_file_list[$i])) == $p_file_list[$i])
) {
// ----- The file is in the directory, so extract it
TrFctMessage(__FILE__, __LINE__, 2,
"File '$v_header[filename]' is in directory '$p_file_list[$i]' : extract it");
$v_extract_file = true;
// ----- End of loop
break;
}
} // ----- It is a file, so compare the file names
else {
if ($p_file_list[$i] == $v_header[filename]) {
// ----- File found
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' should be extracted");
$v_extract_file = true;
// ----- End of loop
break;
}
}
}
// ----- Trace
if (!$v_extract_file) {
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' should not be extracted");
}
} else {
// ----- All files need to be extracted
$v_extract_file = true;
}
// ----- Look if this file need to be extracted
if (($v_extract_file) && (!$v_listing)) {
// ----- Look for path to remove
if (($p_remove_path != "")
&& (substr($v_header[filename], 0, $p_remove_path_size) == $p_remove_path)
) {
TrFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '$v_header[filename]'");
// ----- Remove the path
$v_header[filename] = substr($v_header[filename], $p_remove_path_size);
TrFctMessage(__FILE__, __LINE__, 3, "Reslting file is '$v_header[filename]'");
}
// ----- Add the path to the file
if (($p_path != "./") && ($p_path != "/")) {
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/") {
TrFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'");
$p_path = substr($p_path, 0, strlen($p_path) - 1);
TrFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]");
}
// ----- Add the path
if (substr($v_header[filename], 0, 1) == "/") {
$v_header[filename] = $p_path . $v_header[filename];
} else {
$v_header[filename] = $p_path . "/" . $v_header[filename];
}
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2,
"Extracting file (with path) '$v_header[filename]', size '$v_header[size]'");
// ----- Check that the file does not exists
if (file_exists($v_header[filename])) {
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' already exists");
// ----- Look if file is a directory
if (is_dir($v_header[filename])) {
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is a directory");
// ----- Change the file status
$v_header[status] = "already_a_directory";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
} // ----- Look if file is write protected
else {
if (!is_writeable($v_header[filename])) {
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is write protected");
// ----- Change the file status
$v_header[status] = "write_protected";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
} // ----- Look if the extracted file is older
else {
if (filemtime($v_header[filename]) > $v_header[mtime]) {
TrFctMessage(__FILE__, __LINE__, 2,
"Existing file '$v_header[filename]' is newer (" . date("l dS of F Y h:i:s A",
filemtime($v_header[filename])) . ") than the extracted file (" . date("l dS of F Y h:i:s A",
$v_header[mtime]) . ")");
// ----- Change the file status
$v_header[status] = "newer_exist";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
}
} // ----- Check the directory availability and create it if necessary
else {
if ($v_header[typeflag] == "5") {
$v_dir_to_check = $v_header[filename];
} else {
if (!strstr($v_header[filename], "/")) {
$v_dir_to_check = "";
} else {
$v_dir_to_check = dirname($v_header[filename]);
}
}
if (($v_result = PclTarHandlerDirCheck($v_dir_to_check)) != 1) {
TrFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '$v_header[filename]'");
// ----- Change the file status
$v_header[status] = "path_creation_fail";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
// ----- Do the extraction
if (($v_extract_file) && ($v_header[typeflag] != "5")) {
// ----- Open the destination file in write mode
if (($v_dest_file = @fopen($v_header[filename], "wb")) == 0) {
TrFctMessage(__FILE__, __LINE__, 2, "Error while opening '$v_header[filename]' in write binary mode");
// ----- Change the file status
$v_header[status] = "write_error";
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar") {
fseek($v_tar, ftell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
} else {
TrFctMessage(__FILE__, __LINE__, 2, "Start extraction of '$v_header[filename]'");
// ----- Read data
$n = floor($v_header[size] / 512);
for ($i = 0; $i < $n; $i++) {
TrFctMessage(__FILE__, __LINE__, 3, "Read complete 512 bytes block number " . ($i + 1));
if ($p_tar_mode == "tar") {
$v_content = fread($v_tar, 512);
} else {
$v_content = gzread($v_tar, 512);
}
fwrite($v_dest_file, $v_content, 512);
}
if (($v_header[size] % 512) != 0) {
TrFctMessage(__FILE__, __LINE__, 3, "Read last " . ($v_header[size] % 512) . " bytes in a 512 block");
if ($p_tar_mode == "tar") {
$v_content = fread($v_tar, 512);
} else {
$v_content = gzread($v_tar, 512);
}
fwrite($v_dest_file, $v_content, ($v_header[size] % 512));
}
// ----- Close the destination file
fclose($v_dest_file);
// ----- Change the file mode, mtime
touch($v_header[filename], $v_header[mtime]);
//chmod($v_header[filename], DecOct($v_header[mode]));
}
// ----- Check the file size
clearstatcache();
if (filesize($v_header[filename]) != $v_header[size]) {
// ----- Close the archive file
if ($p_tar_mode == "tar") {
fclose($v_tar);
} else {
gzclose($v_tar);
}
// ----- Error log
PclErrorLog(-7,
"Extracted file '$v_header[filename]' does not have the correct file size '" . filesize($v_filename) . "' ('$v_header[size]' expected). Archive may be corrupted.");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extraction done");
} else {
TrFctMessage(__FILE__, __LINE__, 2, "Extraction of file '$v_header[filename]' skipped.");
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar") {
fseek($v_tar, ftell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
}
} // ----- Look for file that is not to be unzipped
else {
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Jump file '$v_header[filename]'");
TrFctMessage(__FILE__, __LINE__, 4,
"Position avant jump [" . ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) . "]");
// ----- Jump to next file
if ($p_tar_mode == "tar") {
fseek($v_tar, ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
TrFctMessage(__FILE__, __LINE__, 4,
"Position apr�s jump [" . ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) . "]");
}
if ($p_tar_mode == "tar") {
$v_end_of_file = feof($v_tar);
} else {
$v_end_of_file = gzeof($v_tar);
}
// ----- File name and properties are logged if listing mode or file is extracted
if ($v_listing || $v_extract_file || $v_extraction_stopped) {
TrFctMessage(__FILE__, __LINE__, 2, "Memorize info about file '$v_header[filename]'");
// ----- Log extracted files
if (($v_file_dir = dirname($v_header[filename])) == $v_header[filename]) {
$v_file_dir = "";
}
if ((substr($v_header[filename], 0, 1) == "/") && ($v_file_dir == "")) {
$v_file_dir = "/";
}
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
// ----- Increment
$v_nb++;
}
}
// ----- Close the tarfile
if ($p_tar_mode == "tar") {
fclose($v_tar);
} else {
gzclose($v_tar);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtractByIndexList()
// Description :
// Extract the files which are at the indexes specified. If the 'file' at the
// index is a directory, the directory only is created, not all the files stored
// for that directory.
// Parameters :
// $p_index_string : String of indexes of files to extract. The form of the
// string is "0,4-6,8-12" with only numbers and '-' for
// for range, and ',' to separate ranges. No spaces or ';'
// are allowed.
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtractByIndexList(
$p_tarname,
$p_index_string,
&$p_list_detail,
$p_path,
$p_remove_path,
$p_tar_mode
) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtractByIndexList",
"archive='$p_tarname', index_string='$p_index_string', list, path=$p_path, remove_path='$p_remove_path', tar_mode=$p_tar_mode");
$v_result = 1;
$v_nb = 0;
// ----- TBC : I should check the string by a regexp
// ----- Check the path
if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 0,
2) != "./"))
) {
$p_path = "./" . $p_path;
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) {
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the tar file
if ($p_tar_mode == "tar") {
TrFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
$v_tar = @fopen($p_tarname, "rb");
} else {
TrFctMessage(__FILE__, __LINE__, 3, "Open file in gzip binary read mode");
$v_tar = @gzopen($p_tarname, "rb");
}
// ----- Check that the archive is open
if ($v_tar == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open archive '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Manipulate the index list
$v_list = explode(",", $p_index_string);
sort($v_list);
// ----- Loop on the index list
$v_index = 0;
for ($i = 0; ($i < sizeof($v_list)) && ($v_result); $i++) {
TrFctMessage(__FILE__, __LINE__, 3, "Looking for index part '$v_list[$i]'");
// ----- Extract range
$v_index_list = explode("-", $v_list[$i]);
$v_size_index_list = sizeof($v_index_list);
if ($v_size_index_list == 1) {
TrFctMessage(__FILE__, __LINE__, 3, "Only one index '$v_index_list[0]'");
// ----- Do the extraction
$v_result = PclTarHandleExtractByIndex($v_tar, $v_index, $v_index_list[0], $v_index_list[0], $p_list_detail,
$p_path, $p_remove_path, $p_tar_mode);
} else {
if ($v_size_index_list == 2) {
TrFctMessage(__FILE__, __LINE__, 3, "Two indexes '$v_index_list[0]' and '$v_index_list[1]'");
// ----- Do the extraction
$v_result = PclTarHandleExtractByIndex($v_tar, $v_index, $v_index_list[0], $v_index_list[1], $p_list_detail,
$p_path, $p_remove_path, $p_tar_mode);
}
}
}
// ----- Close the tarfile
if ($p_tar_mode == "tar") {
fclose($v_tar);
} else {
gzclose($v_tar);
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtractByIndex()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtractByIndex(
$p_tar,
&$p_index_current,
$p_index_start,
$p_index_stop,
&$p_list_detail,
$p_path,
$p_remove_path,
$p_tar_mode
) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtractByIndex",
"archive_descr='$p_tar', index_current=$p_index_current, index_start='$p_index_start', index_stop='$p_index_stop', list, path=$p_path, remove_path='$p_remove_path', tar_mode=$p_tar_mode");
$v_result = 1;
$v_nb = 0;
// TBC : I should replace all $v_tar by $p_tar in this function ....
$v_tar = $p_tar;
// ----- Look the number of elements already in $p_list_detail
$v_nb = sizeof($p_list_detail);
// ----- Read the blocks
while (!($v_end_of_file = ($p_tar_mode == "tar" ? feof($v_tar) : gzeof($v_tar)))) {
TrFctMessage(__FILE__, __LINE__, 3, "Looking for next file ...");
TrFctMessage(__FILE__, __LINE__, 3, "Index current=$p_index_current, range=[$p_index_start, $p_index_stop])");
if ($p_index_current > $p_index_stop) {
TrFctMessage(__FILE__, __LINE__, 2, "Stop extraction, past stop index");
break;
}
// ----- Clear cache of file infos
clearstatcache();
// ----- Reset extract tag
$v_extract_file = false;
$v_extraction_stopped = 0;
// ----- Read the 512 bytes header
if ($p_tar_mode == "tar") {
$v_binary_data = fread($v_tar, 512);
} else {
$v_binary_data = gzread($v_tar, 512);
}
// ----- Read the header properties
if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1) {
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for empty blocks to skip
if ($v_header[filename] == "") {
TrFctMessage(__FILE__, __LINE__, 2, "Empty block found. End of archive ?");
continue;
}
TrFctMessage(__FILE__, __LINE__, 2, "Found file '$v_header[filename]', size '$v_header[size]'");
// ----- Look if file is in the range to be extracted
if (($p_index_current >= $p_index_start) && ($p_index_current <= $p_index_stop)) {
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' is in the range to be extracted");
$v_extract_file = true;
} else {
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' is out of the range");
$v_extract_file = false;
}
// ----- Look if this file need to be extracted
if ($v_extract_file) {
if (($v_result = PclTarHandleExtractFile($v_tar, $v_header, $p_path, $p_remove_path, $p_tar_mode)) != 1) {
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
} // ----- Look for file that is not to be extracted
else {
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Jump file '$v_header[filename]'");
TrFctMessage(__FILE__, __LINE__, 4,
"Position avant jump [" . ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) . "]");
// ----- Jump to next file
if ($p_tar_mode == "tar") {
fseek($v_tar, ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
TrFctMessage(__FILE__, __LINE__, 4,
"Position apr�s jump [" . ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) . "]");
}
if ($p_tar_mode == "tar") {
$v_end_of_file = feof($v_tar);
} else {
$v_end_of_file = gzeof($v_tar);
}
// ----- File name and properties are logged if listing mode or file is extracted
if ($v_extract_file) {
TrFctMessage(__FILE__, __LINE__, 2, "Memorize info about file '$v_header[filename]'");
// ----- Log extracted files
if (($v_file_dir = dirname($v_header[filename])) == $v_header[filename]) {
$v_file_dir = "";
}
if ((substr($v_header[filename], 0, 1) == "/") && ($v_file_dir == "")) {
$v_file_dir = "/";
}
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
// ----- Increment
$v_nb++;
}
// ----- Increment the current file index
$p_index_current++;
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtractFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtractFile($p_tar, &$v_header, $p_path, $p_remove_path, $p_tar_mode) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtractFile",
"archive_descr='$p_tar', path=$p_path, remove_path='$p_remove_path', tar_mode=$p_tar_mode");
$v_result = 1;
// TBC : I should replace all $v_tar by $p_tar in this function ....
$v_tar = $p_tar;
$v_extract_file = 1;
$p_remove_path_size = strlen($p_remove_path);
// ----- Look for path to remove
if (($p_remove_path != "")
&& (substr($v_header[filename], 0, $p_remove_path_size) == $p_remove_path)
) {
TrFctMessage(__FILE__, __LINE__, 3, "Found path '$p_remove_path' to remove in file '$v_header[filename]'");
// ----- Remove the path
$v_header[filename] = substr($v_header[filename], $p_remove_path_size);
TrFctMessage(__FILE__, __LINE__, 3, "Resulting file is '$v_header[filename]'");
}
// ----- Add the path to the file
if (($p_path != "./") && ($p_path != "/")) {
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/") {
TrFctMessage(__FILE__, __LINE__, 3, "Destination path [$p_path] ends by '/'");
$p_path = substr($p_path, 0, strlen($p_path) - 1);
TrFctMessage(__FILE__, __LINE__, 3, "Modified to [$p_path]");
}
// ----- Add the path
if (substr($v_header[filename], 0, 1) == "/") {
$v_header[filename] = $p_path . $v_header[filename];
} else {
$v_header[filename] = $p_path . "/" . $v_header[filename];
}
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extracting file (with path) '$v_header[filename]', size '$v_header[size]'");
// ----- Check that the file does not exists
if (file_exists($v_header[filename])) {
TrFctMessage(__FILE__, __LINE__, 2, "File '$v_header[filename]' already exists");
// ----- Look if file is a directory
if (is_dir($v_header[filename])) {
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is a directory");
// ----- Change the file status
$v_header[status] = "already_a_directory";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
} // ----- Look if file is write protected
else {
if (!is_writeable($v_header[filename])) {
TrFctMessage(__FILE__, __LINE__, 2, "Existing file '$v_header[filename]' is write protected");
// ----- Change the file status
$v_header[status] = "write_protected";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
} // ----- Look if the extracted file is older
else {
if (filemtime($v_header[filename]) > $v_header[mtime]) {
TrFctMessage(__FILE__, __LINE__, 2,
"Existing file '$v_header[filename]' is newer (" . date("l dS of F Y h:i:s A",
filemtime($v_header[filename])) . ") than the extracted file (" . date("l dS of F Y h:i:s A",
$v_header[mtime]) . ")");
// ----- Change the file status
$v_header[status] = "newer_exist";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
}
} // ----- Check the directory availability and create it if necessary
else {
if ($v_header[typeflag] == "5") {
$v_dir_to_check = $v_header[filename];
} else {
if (!strstr($v_header[filename], "/")) {
$v_dir_to_check = "";
} else {
$v_dir_to_check = dirname($v_header[filename]);
}
}
if (($v_result = PclTarHandlerDirCheck($v_dir_to_check)) != 1) {
TrFctMessage(__FILE__, __LINE__, 2, "Unable to create path for '$v_header[filename]'");
// ----- Change the file status
$v_header[status] = "path_creation_fail";
// ----- Skip the extract
$v_extraction_stopped = 1;
$v_extract_file = 0;
}
}
// ----- Do the real bytes extraction (if not a directory)
if (($v_extract_file) && ($v_header[typeflag] != "5")) {
// ----- Open the destination file in write mode
if (($v_dest_file = @fopen($v_header[filename], "wb")) == 0) {
TrFctMessage(__FILE__, __LINE__, 2, "Error while opening '$v_header[filename]' in write binary mode");
// ----- Change the file status
$v_header[status] = "write_error";
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar") {
fseek($v_tar, ftell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
} else {
TrFctMessage(__FILE__, __LINE__, 2, "Start extraction of '$v_header[filename]'");
// ----- Read data
$n = floor($v_header[size] / 512);
for ($i = 0; $i < $n; $i++) {
TrFctMessage(__FILE__, __LINE__, 3, "Read complete 512 bytes block number " . ($i + 1));
if ($p_tar_mode == "tar") {
$v_content = fread($v_tar, 512);
} else {
$v_content = gzread($v_tar, 512);
}
fwrite($v_dest_file, $v_content, 512);
}
if (($v_header[size] % 512) != 0) {
TrFctMessage(__FILE__, __LINE__, 3, "Read last " . ($v_header[size] % 512) . " bytes in a 512 block");
if ($p_tar_mode == "tar") {
$v_content = fread($v_tar, 512);
} else {
$v_content = gzread($v_tar, 512);
}
fwrite($v_dest_file, $v_content, ($v_header[size] % 512));
}
// ----- Close the destination file
fclose($v_dest_file);
// ----- Change the file mode, mtime
touch($v_header[filename], $v_header[mtime]);
//chmod($v_header[filename], DecOct($v_header[mode]));
}
// ----- Check the file size
clearstatcache();
if (filesize($v_header[filename]) != $v_header[size]) {
// ----- Error log
PclErrorLog(-7,
"Extracted file '$v_header[filename]' does not have the correct file size '" . filesize($v_filename) . "' ('$v_header[size]' expected). Archive may be corrupted.");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Extraction done");
} else {
TrFctMessage(__FILE__, __LINE__, 2, "Extraction of file '$v_header[filename]' skipped.");
// ----- Jump to next file
TrFctMessage(__FILE__, __LINE__, 2, "Jump to next file");
if ($p_tar_mode == "tar") {
fseek($v_tar, ftell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleDelete()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleDelete($p_tarname, $p_file_list, &$p_list_detail, $p_tar_mode) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleDelete", "archive='$p_tarname', list, tar_mode=$p_tar_mode");
$v_result = 1;
$v_nb = 0;
// ----- Look for regular tar file
if ($p_tar_mode == "tar") {
// ----- Open file
TrFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_tar = @fopen($p_tarname, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open a temporary file in write mode
$v_temp_tarname = uniqid("pcltar-") . ".tmp";
TrFctMessage(__FILE__, __LINE__, 2, "Creating temporary archive file $v_temp_tarname");
if (($v_temp_tar = @fopen($v_temp_tarname, "wb")) == 0) {
// ----- Close tar file
fclose($v_tar);
// ----- Error log
PclErrorLog(-1, "Unable to open file '$v_temp_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
} // ----- Look for compressed tar file
else {
// ----- Open the file in read mode
TrFctMessage(__FILE__, __LINE__, 3, "Open file in gzip binary read mode");
if (($v_tar = @gzopen($p_tarname, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open a temporary file in write mode
$v_temp_tarname = uniqid("pcltar-") . ".tmp";
TrFctMessage(__FILE__, __LINE__, 2, "Creating temporary archive file $v_temp_tarname");
if (($v_temp_tar = @gzopen($v_temp_tarname, "wb")) == 0) {
// ----- Close tar file
gzclose($v_tar);
// ----- Error log
PclErrorLog(-1, "Unable to open file '$v_temp_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
}
// ----- Read the blocks
while (!($v_end_of_file = ($p_tar_mode == "tar" ? feof($v_tar) : gzeof($v_tar)))) {
TrFctMessage(__FILE__, __LINE__, 3, "Looking for next header ...");
// ----- Clear cache of file infos
clearstatcache();
// ----- Reset delete tag
$v_delete_file = false;
// ----- Read the first 512 block header
if ($p_tar_mode == "tar") {
$v_binary_data = fread($v_tar, 512);
} else {
$v_binary_data = gzread($v_tar, 512);
}
// ----- Read the header properties
if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1) {
// ----- Close the archive file
if ($p_tar_mode == "tar") {
fclose($v_tar);
fclose($v_temp_tar);
} else {
gzclose($v_tar);
gzclose($v_temp_tar);
}
@unlink($v_temp_tarname);
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for empty blocks to skip
if ($v_header[filename] == "") {
TrFctMessage(__FILE__, __LINE__, 2, "Empty block found. End of archive ?");
continue;
}
TrFctMessage(__FILE__, __LINE__, 2, "Found file '$v_header[filename]', size '$v_header[size]'");
// ----- Look for filenames to delete
for ($i = 0, $v_delete_file = false; ($i < sizeof($p_file_list)) && (!$v_delete_file); $i++) {
// ----- Compare the file names
// if ($p_file_list[$i] == $v_header[filename])
if (($v_len = strcmp($p_file_list[$i], $v_header[filename])) <= 0) {
if ($v_len == 0) {
TrFctMessage(__FILE__, __LINE__, 3, "Found that '$v_header[filename]' need to be deleted");
$v_delete_file = true;
} else {
TrFctMessage(__FILE__, __LINE__, 3, "Look if '$v_header[filename]' is a file in $p_file_list[$i]");
if (substr($v_header[filename], strlen($p_file_list[$i]), 1) == "/") {
TrFctMessage(__FILE__, __LINE__, 3, "'$v_header[filename]' is a file in $p_file_list[$i]");
$v_delete_file = true;
}
}
}
}
// ----- Copy files that do not need to be deleted
if (!$v_delete_file) {
TrFctMessage(__FILE__, __LINE__, 2, "Keep file '$v_header[filename]'");
// ----- Write the file header
if ($p_tar_mode == "tar") {
fputs($v_temp_tar, $v_binary_data, 512);
} else {
gzputs($v_temp_tar, $v_binary_data, 512);
}
// ----- Write the file data
$n = ceil($v_header[size] / 512);
for ($i = 0; $i < $n; $i++) {
TrFctMessage(__FILE__, __LINE__, 3, "Read complete 512 bytes block number " . ($i + 1));
if ($p_tar_mode == "tar") {
$v_content = fread($v_tar, 512);
fwrite($v_temp_tar, $v_content, 512);
} else {
$v_content = gzread($v_tar, 512);
gzwrite($v_temp_tar, $v_content, 512);
}
}
// ----- File name and properties are logged if listing mode or file is extracted
TrFctMessage(__FILE__, __LINE__, 2, "Memorize info about file '$v_header[filename]'");
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
$p_list_detail[$v_nb][status] = "ok";
// ----- Increment
$v_nb++;
} // ----- Look for file that is to be deleted
else {
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Start deletion of '$v_header[filename]'");
TrFctMessage(__FILE__, __LINE__, 4,
"Position avant jump [" . ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) . "]");
// ----- Jump to next file
if ($p_tar_mode == "tar") {
fseek($v_tar, ftell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_header[size] / 512)) * 512));
}
TrFctMessage(__FILE__, __LINE__, 4,
"Position apr�s jump [" . ($p_tar_mode == "tar" ? ftell($v_tar) : gztell($v_tar)) . "]");
}
// ----- Look for end of file
if ($p_tar_mode == "tar") {
$v_end_of_file = feof($v_tar);
} else {
$v_end_of_file = gzeof($v_tar);
}
}
// ----- Write the last empty buffer
PclTarHandleFooter($v_temp_tar, $p_tar_mode);
// ----- Close the tarfile
if ($p_tar_mode == "tar") {
fclose($v_tar);
fclose($v_temp_tar);
} else {
gzclose($v_tar);
gzclose($v_temp_tar);
}
// ----- Unlink tar file
if (!@unlink($p_tarname)) {
// ----- Error log
PclErrorLog(-11, "Error while deleting archive name $p_tarname");
}
// ----- Rename tar file
if (!@rename($v_temp_tarname, $p_tarname)) {
// ----- Error log
PclErrorLog(-12, "Error while renaming temporary file $v_temp_tarname to archive name $p_tarname");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleUpdate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleUpdate($p_tarname, $p_file_list, &$p_list_detail, $p_tar_mode, $p_add_dir, $p_remove_dir) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleUpdate", "archive='$p_tarname', list, tar_mode=$p_tar_mode");
$v_result = 1;
$v_nb = 0;
$v_found_list = array();
// ----- Look for regular tar file
if ($p_tar_mode == "tar") {
// ----- Open file
TrFctMessage(__FILE__, __LINE__, 3, "Open file in binary read mode");
if (($v_tar = @fopen($p_tarname, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open a temporary file in write mode
$v_temp_tarname = uniqid("pcltar-") . ".tmp";
TrFctMessage(__FILE__, __LINE__, 2, "Creating temporary archive file $v_temp_tarname");
if (($v_temp_tar = @fopen($v_temp_tarname, "wb")) == 0) {
// ----- Close tar file
fclose($v_tar);
// ----- Error log
PclErrorLog(-1, "Unable to open file '$v_temp_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
} // ----- Look for compressed tar file
else {
// ----- Open the file in read mode
TrFctMessage(__FILE__, __LINE__, 3, "Open file in gzip binary read mode");
if (($v_tar = @gzopen($p_tarname, "rb")) == 0) {
// ----- Error log
PclErrorLog(-2, "Unable to open file '$p_tarname' in binary read mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Open a temporary file in write mode
$v_temp_tarname = uniqid("pcltar-") . ".tmp";
TrFctMessage(__FILE__, __LINE__, 2, "Creating temporary archive file $v_temp_tarname");
if (($v_temp_tar = @gzopen($v_temp_tarname, "wb")) == 0) {
// ----- Close tar file
gzclose($v_tar);
// ----- Error log
PclErrorLog(-1, "Unable to open file '$v_temp_tarname' in binary write mode");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
}
// ----- Prepare the list of files
for ($i = 0; $i < sizeof($p_file_list); $i++) {
// ----- Reset the found list
$v_found_list[$i] = 0;
// ----- Calculate the stored filename
$v_stored_list[$i] = $p_file_list[$i];
if ($p_remove_dir != "") {
if (substr($p_file_list[$i], -1) != '/') {
$p_remove_dir .= "/";
}
if (substr($p_file_list[$i], 0, strlen($p_remove_dir)) == $p_remove_dir) {
$v_stored_list[$i] = substr($p_file_list[$i], strlen($p_remove_dir));
TrFctMessage(__FILE__, __LINE__, 3,
"Remove path '$p_remove_dir' in file '$p_file_list[$i]' = '$v_stored_list[$i]'");
}
}
if ($p_add_dir != "") {
if (substr($p_add_dir, -1) == "/") {
$v_stored_list[$i] = $p_add_dir . $v_stored_list[$i];
} else {
$v_stored_list[$i] = $p_add_dir . "/" . $v_stored_list[$i];
}
TrFctMessage(__FILE__, __LINE__, 3, "Add path '$p_add_dir' in file '$p_file_list[$i]' = '$v_stored_list[$i]'");
}
$v_stored_list[$i] = PclTarHandlePathReduction($v_stored_list[$i]);
TrFctMessage(__FILE__, __LINE__, 3, "After reduction '$v_stored_list[$i]'");
}
// ----- Update file cache
clearstatcache();
// ----- Read the blocks
while (!($v_end_of_file = ($p_tar_mode == "tar" ? feof($v_tar) : gzeof($v_tar)))) {
TrFctMessage(__FILE__, __LINE__, 3, "Looking for next header ...");
// ----- Clear cache of file infos
clearstatcache();
// ----- Reset current found filename
$v_current_filename = "";
// ----- Reset delete tag
$v_delete_file = false;
// ----- Read the first 512 block header
if ($p_tar_mode == "tar") {
$v_binary_data = fread($v_tar, 512);
} else {
$v_binary_data = gzread($v_tar, 512);
}
// ----- Read the header properties
if (($v_result = PclTarHandleReadHeader($v_binary_data, $v_header)) != 1) {
// ----- Close the archive file
if ($p_tar_mode == "tar") {
fclose($v_tar);
fclose($v_temp_tar);
} else {
gzclose($v_tar);
gzclose($v_temp_tar);
}
@unlink($v_temp_tarname);
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Look for empty blocks to skip
if ($v_header[filename] == "") {
TrFctMessage(__FILE__, __LINE__, 2, "Empty block found. End of archive ?");
continue;
}
TrFctMessage(__FILE__, __LINE__, 2, "Found file '$v_header[filename]', size '$v_header[size]'");
// ----- Look for filenames to update
for ($i = 0, $v_update_file = false, $v_found_file = false; ($i < sizeof($v_stored_list)) && (!$v_update_file); $i++) {
TrFctMessage(__FILE__, __LINE__, 4, "Compare with file '$v_stored_list[$i]'");
// ----- Compare the file names
if ($v_stored_list[$i] == $v_header[filename]) {
TrFctMessage(__FILE__, __LINE__, 3, "File '$v_stored_list[$i]' is present in archive");
TrFctMessage(__FILE__, __LINE__, 3,
"File '$v_stored_list[$i]' mtime=" . filemtime($p_file_list[$i]) . " " . date("l dS of F Y h:i:s A",
filemtime($p_file_list[$i])));
TrFctMessage(__FILE__, __LINE__, 3,
"Archived mtime=" . $v_header[mtime] . " " . date("l dS of F Y h:i:s A", $v_header[mtime]));
// ----- Store found informations
$v_found_file = true;
$v_current_filename = $p_file_list[$i];
// ----- Look if the file need to be updated
if (filemtime($p_file_list[$i]) > $v_header[mtime]) {
TrFctMessage(__FILE__, __LINE__, 3, "File '$p_file_list[$i]' need to be updated");
$v_update_file = true;
} else {
TrFctMessage(__FILE__, __LINE__, 3, "File '$p_file_list[$i]' does not need to be updated");
$v_update_file = false;
}
// ----- Flag the name in order not to add the file at the end
$v_found_list[$i] = 1;
} else {
TrFctMessage(__FILE__, __LINE__, 4, "File '$p_file_list[$i]' is not '$v_header[filename]'");
}
}
// ----- Copy files that do not need to be updated
if (!$v_update_file) {
TrFctMessage(__FILE__, __LINE__, 2, "Keep file '$v_header[filename]'");
// ----- Write the file header
if ($p_tar_mode == "tar") {
fputs($v_temp_tar, $v_binary_data, 512);
} else {
gzputs($v_temp_tar, $v_binary_data, 512);
}
// ----- Write the file data
$n = ceil($v_header[size] / 512);
for ($j = 0; $j < $n; $j++) {
TrFctMessage(__FILE__, __LINE__, 3, "Read complete 512 bytes block number " . ($j + 1));
if ($p_tar_mode == "tar") {
$v_content = fread($v_tar, 512);
fwrite($v_temp_tar, $v_content, 512);
} else {
$v_content = gzread($v_tar, 512);
gzwrite($v_temp_tar, $v_content, 512);
}
}
// ----- File name and properties are logged if listing mode or file is extracted
TrFctMessage(__FILE__, __LINE__, 2, "Memorize info about file '$v_header[filename]'");
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
$p_list_detail[$v_nb][status] = ($v_found_file ? "not_updated" : "ok");
// ----- Increment
$v_nb++;
} // ----- Look for file that need to be updated
else {
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Start update of file '$v_current_filename'");
// ----- Store the old file size
$v_old_size = $v_header[size];
// ----- Add the file
if (($v_result = PclTarHandleAddFile($v_temp_tar, $v_current_filename, $p_tar_mode, $v_header, $p_add_dir,
$p_remove_dir)) != 1
) {
// ----- Close the tarfile
if ($p_tar_mode == "tar") {
fclose($v_tar);
fclose($v_temp_tar);
} else {
gzclose($v_tar);
gzclose($v_temp_tar);
}
@unlink($p_temp_tarname);
// ----- Return status
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Trace
TrFctMessage(__FILE__, __LINE__, 2, "Skip old file '$v_header[filename]'");
// ----- Jump to next file
if ($p_tar_mode == "tar") {
fseek($v_tar, ftell($v_tar) + (ceil(($v_old_size / 512)) * 512));
} else {
gzseek($v_tar, gztell($v_tar) + (ceil(($v_old_size / 512)) * 512));
}
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
$p_list_detail[$v_nb][status] = "updated";
// ----- Increment
$v_nb++;
}
// ----- Look for end of file
if ($p_tar_mode == "tar") {
$v_end_of_file = feof($v_tar);
} else {
$v_end_of_file = gzeof($v_tar);
}
}
// ----- Look for files that does not exists in the archive and need to be added
for ($i = 0; $i < sizeof($p_file_list); $i++) {
// ----- Look if file not found in the archive
if (!$v_found_list[$i]) {
TrFctMessage(__FILE__, __LINE__, 3, "File '$p_file_list[$i]' need to be added");
// ----- Add the file
if (($v_result = PclTarHandleAddFile($v_temp_tar, $p_file_list[$i], $p_tar_mode, $v_header, $p_add_dir,
$p_remove_dir)) != 1
) {
// ----- Close the tarfile
if ($p_tar_mode == "tar") {
fclose($v_tar);
fclose($v_temp_tar);
} else {
gzclose($v_tar);
gzclose($v_temp_tar);
}
@unlink($p_temp_tarname);
// ----- Return status
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// ----- Add the array describing the file into the list
$p_list_detail[$v_nb] = $v_header;
$p_list_detail[$v_nb][status] = "added";
// ----- Increment
$v_nb++;
} else {
TrFctMessage(__FILE__, __LINE__, 3, "File '$p_file_list[$i]' was already updated if needed");
}
}
// ----- Write the last empty buffer
PclTarHandleFooter($v_temp_tar, $p_tar_mode);
// ----- Close the tarfile
if ($p_tar_mode == "tar") {
fclose($v_tar);
fclose($v_temp_tar);
} else {
gzclose($v_tar);
gzclose($v_temp_tar);
}
// ----- Unlink tar file
if (!@unlink($p_tarname)) {
// ----- Error log
PclErrorLog(-11, "Error while deleting archive name $p_tarname");
}
// ----- Rename tar file
if (!@rename($v_temp_tarname, $p_tarname)) {
// ----- Error log
PclErrorLog(-12, "Error while renaming temporary file $v_temp_tarname to archive name $p_tarname");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleReadHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleReadHeader($v_binary_data, &$v_header) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleReadHeader", "");
$v_result = 1;
// ----- Read the 512 bytes header
/*
if ($p_tar_mode == "tar")
$v_binary_data = fread($p_tar, 512);
else
$v_binary_data = gzread($p_tar, 512);
*/
// ----- Look for no more block
if (strlen($v_binary_data) == 0) {
$v_header[filename] = "";
$v_header[status] = "empty";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result, "End of archive found");
return $v_result;
}
// ----- Look for invalid block size
if (strlen($v_binary_data) != 512) {
$v_header[filename] = "";
$v_header[status] = "invalid_header";
TrFctMessage(__FILE__, __LINE__, 2, "Invalid block size : " . strlen($v_binary_data));
// ----- Error log
PclErrorLog(-10, "Invalid block size : " . strlen($v_binary_data));
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Calculate the checksum
$v_checksum = 0;
// ..... First part of the header
for ($i = 0; $i < 148; $i++) {
$v_checksum += ord(substr($v_binary_data, $i, 1));
}
// ..... Ignore the checksum value and replace it by ' ' (space)
for ($i = 148; $i < 156; $i++) {
$v_checksum += ord(' ');
}
// ..... Last part of the header
for ($i = 156; $i < 512; $i++) {
$v_checksum += ord(substr($v_binary_data, $i, 1));
}
TrFctMessage(__FILE__, __LINE__, 3, "Calculated checksum : $v_checksum");
// ----- Extract the values
TrFctMessage(__FILE__, __LINE__, 2, "Header : '$v_binary_data'");
$v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor",
$v_binary_data);
// ----- Extract the checksum for check
$v_header[checksum] = OctDec(trim($v_data[checksum]));
TrFctMessage(__FILE__, __LINE__, 3, "File checksum : $v_header[checksum]");
if ($v_header[checksum] != $v_checksum) {
TrFctMessage(__FILE__, __LINE__, 2,
"File checksum is invalid : $v_checksum calculated, $v_header[checksum] expected");
$v_header[filename] = "";
$v_header[status] = "invalid_header";
// ----- Look for last block (empty block)
if (($v_checksum == 256) && ($v_header[checksum] == 0)) {
$v_header[status] = "empty";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result, "End of archive found");
return $v_result;
}
// ----- Error log
PclErrorLog(-13, "Invalid checksum : $v_checksum calculated, $v_header[checksum] expected");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
TrFctMessage(__FILE__, __LINE__, 2, "File checksum is valid ($v_checksum)");
// ----- Extract the properties
$v_header[filename] = trim($v_data[filename]);
TrFctMessage(__FILE__, __LINE__, 2, "Name : '$v_header[filename]'");
$v_header[mode] = OctDec(trim($v_data[mode]));
TrFctMessage(__FILE__, __LINE__, 2, "Mode : '" . DecOct($v_header[mode]) . "'");
$v_header[uid] = OctDec(trim($v_data[uid]));
TrFctMessage(__FILE__, __LINE__, 2, "Uid : '$v_header[uid]'");
$v_header[gid] = OctDec(trim($v_data[gid]));
TrFctMessage(__FILE__, __LINE__, 2, "Gid : '$v_header[gid]'");
$v_header[size] = OctDec(trim($v_data[size]));
TrFctMessage(__FILE__, __LINE__, 2, "Size : '$v_header[size]'");
$v_header[mtime] = OctDec(trim($v_data[mtime]));
TrFctMessage(__FILE__, __LINE__, 2, "Date : " . date("l dS of F Y h:i:s A", $v_header[mtime]));
if (($v_header[typeflag] = $v_data[typeflag]) == "5") {
$v_header[size] = 0;
TrFctMessage(__FILE__, __LINE__, 2, "Size (folder) : '$v_header[size]'");
}
TrFctMessage(__FILE__, __LINE__, 2, "File typeflag : $v_header[typeflag]");
/* ----- All these fields are removed form the header because they do not carry interesting info
$v_header[link] = trim($v_data[link]);
TrFctMessage(__FILE__, __LINE__, 2, "Linkname : $v_header[linkname]");
$v_header[magic] = trim($v_data[magic]);
TrFctMessage(__FILE__, __LINE__, 2, "Magic : $v_header[magic]");
$v_header[version] = trim($v_data[version]);
TrFctMessage(__FILE__, __LINE__, 2, "Version : $v_header[version]");
$v_header[uname] = trim($v_data[uname]);
TrFctMessage(__FILE__, __LINE__, 2, "Uname : $v_header[uname]");
$v_header[gname] = trim($v_data[gname]);
TrFctMessage(__FILE__, __LINE__, 2, "Gname : $v_header[gname]");
$v_header[devmajor] = trim($v_data[devmajor]);
TrFctMessage(__FILE__, __LINE__, 2, "Devmajor : $v_header[devmajor]");
$v_header[devminor] = trim($v_data[devminor]);
TrFctMessage(__FILE__, __LINE__, 2, "Devminor : $v_header[devminor]");
*/
// ----- Set the status field
$v_header[status] = "ok";
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandlerDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check (without / at the end).
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function PclTarHandlerDirCheck($p_dir) {
$v_result = 1;
TrFctStart(__FILE__, __LINE__, "PclTarHandlerDirCheck", "$p_dir");
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == "")) {
TrFctEnd(__FILE__, __LINE__, "'$p_dir' is a directory");
return 1;
}
// ----- Look for file alone
/*
if (!strstr("$p_dir", "/"))
{
TrFctEnd(__FILE__, __LINE__, "'$p_dir' is a file with no directory");
return 1;
}
*/
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
TrFctMessage(__FILE__, __LINE__, 3, "Parent directory is '$p_parent_dir'");
// ----- Just a check
if ($p_parent_dir != $p_dir) {
// ----- Look for parent directory
if ($p_parent_dir != "") {
if (($v_result = PclTarHandlerDirCheck($p_parent_dir)) != 1) {
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
}
}
// ----- Create the directory
TrFctMessage(__FILE__, __LINE__, 3, "Create directory '$p_dir'");
if (!@mkdir($p_dir, 0777)) {
// ----- Error log
PclErrorLog(-8, "Unable to create directory '$p_dir'");
// ----- Return
TrFctEnd(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
return PclErrorCode();
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result, "Directory '$p_dir' created");
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandleExtension()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandleExtension($p_tarname) {
TrFctStart(__FILE__, __LINE__, "PclTarHandleExtension", "tar=$p_tarname");
// ----- Look for file extension
if ((substr($p_tarname, -7) == ".tar.gz") || (substr($p_tarname, -4) == ".tgz")) {
TrFctMessage(__FILE__, __LINE__, 2, "Archive is a gzip tar");
$v_tar_mode = "tgz";
} else {
if (substr($p_tarname, -4) == ".tar") {
TrFctMessage(__FILE__, __LINE__, 2, "Archive is a tar");
$v_tar_mode = "tar";
} else {
// ----- Error log
PclErrorLog(-9, "Invalid archive extension");
TrFctMessage(__FILE__, __LINE__, PclErrorCode(), PclErrorString());
$v_tar_mode = "";
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_tar_mode);
return $v_tar_mode;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTarHandlePathReduction()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function PclTarHandlePathReduction($p_dir) {
TrFctStart(__FILE__, __LINE__, "PclTarHandlePathReduction", "dir='$p_dir'");
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "") {
// ----- Explode path by directory names
$v_list = explode("/", $p_dir);
// ----- Study directories from last to first
for ($i = sizeof($v_list) - 1; $i >= 0; $i--) {
// ----- Look for current path
if ($v_list[$i] == ".") {
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
} else {
if ($v_list[$i] == "..") {
// ----- Ignore it and ignore the $i-1
$i--;
} else {
if (($v_list[$i] == "") && ($i != (sizeof($v_list) - 1)) && ($i != 0)) {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
} else {
$v_result = $v_list[$i] . ($i != (sizeof($v_list) - 1) ? "/" . $v_result : "");
}
}
}
}
}
// ----- Return
TrFctEnd(__FILE__, __LINE__, $v_result);
return $v_result;
}
// --------------------------------------------------------------------------------
// ----- End of double include look
}
|
ernestovi/ups
|
spip/plugins-dist/svp/inc/pcltar.php
|
PHP
|
gpl-3.0
| 117,832
|
/***************************************************************************
util.c - description
-------------------
begin : 01.11.2010
copyright : Copyright (c) 2011, Robert Bosch Engineering and Business Solutions. All rights reserved.
author : Saravanan
***************************************************************************/
/***************************************************************************
* *
* This program is free software, you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License *
* version 2.1 as published by the Free Software Foundation. *
* *
***************************************************************************/
/**
Library to talk to Tiny-CAN devices. You find the latest versions at
http://www.tiny-can.com/
**/
//#include "global.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include "util.h"
#ifdef __WIN32__
#define DIR_SEPARATOR '\\'
#define DIR_SEPARATOR_STR "\\"
#else
#define DIR_SEPARATOR '/'
#define DIR_SEPARATOR_STR "/"
#endif
/**************************************************************************/
/* F U N K T I O N E N */
/**************************************************************************/
/*
******************** strlwc ********************
Funktion : Einen String in Kleinbuchstaben umwandeln
Eingaben : str => Zu wandelnder String
Ausgaben : keine
Call's : tolower
*/
void strlwc(char *str)
{
while (*str)
{
*str = (char)tolower((int)*str);
str++;
}
}
/*
******************** strupc ********************
Funktion : Einen String in Grossbuchstaben umwandeln
Eingaben : str => Zu wandelnder String
Ausgaben : keine
Call's : toupper
*/
void strupc(char *str)
{
while (*str)
{
*str = (char)toupper((int)*str);
str++;
}
}
/*
******************** strskp ********************
Funktion : Fuehrende Leerzeichen des Strings ueberspringen
Eingaben : str => Input String
Ausgaben : keine
Call's : isspace
*/
void strskp(char **str)
{
char *s;
if (!str)
return;
s = *str;
while (isspace((int)*s))
s++;
*str = s;
}
/*
******************** strcrop ********************
Funktion : Abschliesende Leerzeichen des Strings loeschen
Eingaben : str => Zu bearbeitender String
Ausgaben : keine
Call's : strlen, isspace
*/
void strcrop(char *str)
{
char *last;
int len;
if (!str)
return;
len = strlen(str);
if (len == 0) return;
last = str + (len-1);
while ((last != str) && (isspace((int)*last)))
last--;
last++;
*last=0;
}
/*
******************** strstrip ********************
Funktion : Fuehrende Leerzeichen des Strings ueberspringen
und abschliesende Leerzeichen loeschen
Eingaben : str => Input String
Ausgaben : keine
Call's : isspace
*/
void strstrip(char **str)
{
char *last;
int len;
last = *str;
// Leerzeichen werden ignoriert
while (isspace((int)*last))
last++;
*str = last;
len = strlen(last);
if (len)
{
last += (len-1);
while ((len--) && (isspace((int)*last)))
last--;
last++;
*last = 0;
}
}
int str_has_char(char *s)
{
char c;
if (!s)
return(-1);
while ((c = *s++))
{
if (c != ' ')
break;
}
if (c)
return(0);
else
return(-1);
}
void *mhs_malloc(int size)
{
return(malloc(size));
}
void *mhs_calloc(int num, int size)
{
return(calloc(num, size));
}
void mhs_free(void *mem)
{
free(mem);
}
void *mhs_memdup(void const *mem, int size)
{
void *new_mem;
if (mem)
{
new_mem = mhs_malloc(size);
memcpy(new_mem, mem, size);
}
else
new_mem = NULL;
return(new_mem);
}
int save_strcmp(const char *s1, const char *s2)
{
if ((!s1) && (!s2))
return(0);
if ((!s1) || (!s2))
return(-1);
return(strcmp(s1, s2));
}
int save_strcasecmp(const char *s1, const char *s2)
{
char c1, c2;
if ((!s1) && (!s2))
return(0);
if ((!s1) || (!s2))
return(-1);
while ((c1 = *s1++))
{
c1 = (char)toupper((int)c1);
c2 = *s2++;
c2 = (char)toupper((int)c2);
if (c1 != c2)
return(-1);
}
if (*s2)
return(-1);
return(0);
//return(strcasecmp(s1, s2));
}
int find_item(char *s, char *list, char trenner)
{
int hit, idx;
char c, l;
char *in;
if ((!s) || (!list))
return(-1);
idx = 0;
while (*list)
{
in = s;
hit = 1;
while ((c = *in++))
{
c = (char)toupper((int)c);
l = *list++;
if (l == trenner)
{
if (c)
hit = 0;
break;
}
l = (char)toupper((int)l);
if (c != l)
{
hit = 0;
break;
}
}
if (hit)
return(idx);
idx++;
}
return(-1);
}
/*
******************** find_upc ********************
Funktion :
Eingaben :
Ausgaben : keine
Call's :
*/
char *find_upc(char *str, char *search)
{
char *s;
char c;
s = search;
while ((c = *str++))
{
c = (char)toupper((int)c);
if (c == *s++)
{
if (!*s)
return(str);
}
else
s = search;
}
return(NULL);
}
/*
******************** get_tick ********************
Funktion :
Eingaben :
Ausgaben : keine
Call's :
*/
#ifndef __WIN32__
unsigned long get_tick(void)
{
//struct timespec now;
struct timeval now;
//clock_gettime(CLOCK_REALTIME, &now);
//return((now.tv_sec * 1000) + (now.tv_nsec / 1000000));
gettimeofday(&now, NULL);
return((now.tv_sec * 1000) + (now.tv_usec / 1000));
}
#endif
/*
******************** get_unix_time ********************
Funktion : Unix Zeit unter Windows ermitteln
Eingaben : p => Buffer fuer Ergebnis
Ausgaben : *p => Unix Zeit
Call's : GetSystemTimeAsFileTime
*/
#ifdef __WIN32__
const ULONGLONG VALUE_10 = {10};
const ULONGLONG VALUE_1000000 = {1000000};
const ULONGLONG VALUE_10000000 = {10000000};
const ULONGLONG VALUE_116444736000000000 = {116444736000000000};
/*
const uint64_t VALUE_10 = {10};
const uint64_t VALUE_1000000 = {1000000};
const uint64_t VALUE_10000000 = {10000000};
const uint64_t VALUE_116444736000000000 = {116444736000000000};*/
void get_unix_time(struct timeval *p)
{
union
{
ULONGLONG ns100; // time since 1 Jan 1601 in 100ns units
FILETIME ft;
}
now;
#ifdef WINCE
SYSTEMTIME time;
GetSystemTime(&time);
// if SystemTimeToFileTime() fails, it returns zero.
if (!SystemTimeToFileTime(&time, &(now.ft)))
return;
#else
GetSystemTimeAsFileTime(&(now.ft));
#endif
p->tv_usec=(uint32_t)((now.ns100 / VALUE_10) % VALUE_1000000);
p->tv_sec= (uint32_t)((now.ns100-(VALUE_116444736000000000))/ VALUE_10000000);
}
#endif
/*void get_timestamp(struct TTime* time_stamp)
{
struct timeval t;
get_unix_time(&t);
time_stamp->USec = (uint32_t)t.tv_usec;
time_stamp->Sec = (uint32_t)t.tv_sec;
}*/
/*
******************** mhs_diff_time ********************
Funktion : Differenzeit zwischen now und stamp
berechnen unter beruecksichtigung eines
Ueberlaufs
Eingaben : now => Aktuelle Zeit
stamp => Zeitstempel in der Vergangenheit
Ausgaben : result => Differenz-Zeit x = now - stamp
Call's : keine
*/
unsigned long mhs_diff_time(unsigned long now, unsigned long stamp)
{
if (stamp > now)
return((0xFFFFFFFF - stamp) + now + 1);
else
return(now - stamp);
}
#define SET_RESULT(result, value) if ((result)) *(result) = (value)
char *get_item_as_string(char **str, char *trenner, int *result)
{
int hit, cnt, l;
char *s, *t, *start, *end, *item;
if ((!str) || (!trenner))
{
SET_RESULT(result, -1);
return(NULL);
}
s = *str;
if (!s)
{
SET_RESULT(result, -1);
return(NULL);
}
// Fuehrende Leerzeichen ueberspringen
while (*s == ' ')
s++;
if (*s == '\0')
{
SET_RESULT(result, -1);
return(NULL);
}
SET_RESULT(result, 0);
end = s;
item = s;
start = s;
// Eintrag in "xx" Zeichen
if ((s = strchr(s, '"')))
{
item = s + 1;
if ((s = strchr(item, '"')))
{
*s++ = '\0';
end = s;
}
}
hit = 0;
for (s = end; *s; s++)
{
cnt = 0;
for (t = trenner; *t; t++)
{
cnt++;
if (*s == *t)
{
*s++ = '\0';
end = s;
SET_RESULT(result, cnt);
hit = 1;
break;
}
}
if (hit)
break;
}
// Abschliesende Leerzeichen loeschen
if ((l = strlen(item)))
{
s = item + (l-1);
while ((l) && ((isspace((int)*s)) || (*s == '\n') || (*s == '\r')))
{
l--;
s--;
}
if (l)
s++;
*s = 0;
}
if (end == start)
*str = start + strlen(end);
else
*str = end;
return(item);
}
unsigned long get_item_as_ulong(char **str, char *trenner, int *result)
{
unsigned long v;
char *s;
int e;
char *endptr;
e = 0;
v = 0L;
s = get_item_as_string(str, trenner, NULL);
if (!s)
e = -1;
else
{
v = strtoul(s, (char**)&endptr, 0);
if (s == endptr)
e = -1;
}
SET_RESULT(result, e);
return(v);
}
long get_item_as_long(char **str, char *trenner, int *result)
{
long v;
char *s;
int e;
char *endptr;
e = 0;
v = 0L;
s = get_item_as_string(str, trenner, NULL);
if (!s)
e = -1;
else
{
v = strtol(s, (char**)&endptr, 0);
if (s == endptr)
e = -1;
}
SET_RESULT(result, e);
return(v);
}
double get_item_as_double(char **str, char *trenner, int *result)
{
double v;
char *s;
int e;
e = 0;
v = 0;
s = get_item_as_string(str, trenner, NULL);
if (!s)
e = -1;
else
v = atof(s);
SET_RESULT(result, e);
return(v);
}
char *mhs_stpcpy(char *dest, const char *src)
{
register char *d = dest;
register const char *s = src;
do
*d++ = *s;
while (*s++);
return(d - 1);
}
char *mhs_strdup(const char *str)
{
int len;
char *new_str;
if (str)
{
len = strlen(str) + 1;
new_str = (char *)mhs_malloc(len);
if (!new_str)
return(NULL);
memcpy(new_str, str, len);
return(new_str);
}
else
return(NULL);
}
char *mhs_strconcat(const char *string1, ...)
{
int l;
va_list args;
char *s, *concat, *ptr;
if (!string1)
return(NULL);
l = 1 + strlen(string1);
va_start(args, string1);
s = va_arg(args, char*);
while (s)
{
l += strlen(s);
s = va_arg(args, char*);
}
va_end(args);
concat = (char *)mhs_malloc(l);
if (!concat)
return(NULL);
ptr = concat;
ptr = mhs_stpcpy(ptr, string1);
va_start (args, string1);
s = va_arg (args, char*);
while (s)
{
ptr = mhs_stpcpy(ptr, s);
s = va_arg(args, char*);
}
va_end (args);
return(concat);
}
char *get_file_name(const char *file_name)
{
char *p;
if (!file_name)
return(NULL);
if ((p = strrchr(file_name, DIR_SEPARATOR)))
return(p+1);
else
return(NULL);
}
char *create_file_name(const char *dir, const char *file_name)
{
if ((!dir) || (!file_name))
return(NULL);
if (strchr(file_name, DIR_SEPARATOR))
return(mhs_strdup(file_name));
else
{
if (dir[strlen(dir)-1] == DIR_SEPARATOR)
return(mhs_strconcat(dir, file_name, NULL));
else
return(mhs_strconcat(dir, DIR_SEPARATOR_STR, file_name, NULL));
}
}
char *path_get_dirname(const char *file_name)
{
int len;
char *base;
if (!file_name)
return(NULL);
base = strrchr(file_name, DIR_SEPARATOR);
if (base)
{
while ((base > file_name) && (*base == DIR_SEPARATOR))
base--;
len = base - file_name + 1;
base = (char *)mhs_malloc(len + 1);
if (!base)
return(NULL);
memcpy(base, file_name, len);
base[len] = 0;
return(base);
}
else
return(mhs_strdup("."));
}
char *change_file_ext(const char *file_name, const char *ext)
{
char *last_period, *tmp, *new_filename;
tmp = mhs_strdup(file_name);
last_period = strrchr(tmp, '.');
if (last_period)
*last_period = '\0';
new_filename = mhs_strconcat(tmp, ".", ext, NULL);
save_free(tmp);
return(new_filename);
}
|
bentearadu/UDS_Lear
|
Sources/MHS_CNFG/src/util.c
|
C
|
gpl-3.0
| 11,735
|
<?php
require_once(__DIR__ . '/../../global.inc.php');
require_once(__DIR__ . '/../../database.inc.php');
trait InventarioProduto {
public function setIdInventario($value) { $this->idInventario = $value; return $this; }
public function getIdInventario() { return $this->idInventario; }
public function setIdProduto($value) { $this->idProduto = $value; return $this; }
public function getIdProduto() { return $this->idProduto; }
public function setDescricao($value) { $this->descricao = $value; return $this; }
public function getDescricao() { return $this->descricao; }
public function setGrade1($value) { $this->grade1 = $value; return $this; }
public function getGrade1() { return $this->grade1; }
public function setGrade2($value) { $this->grade2 = $value; return $this; }
public function getGrade2() { return $this->grade2; }
public function setIdCategoria($value) { $this->idCategoria = $value; return $this; }
public function getIdCategoria() { return $this->idCategoria; }
public function setCategoria($value) { $this->categoria = $value; return $this; }
public function getCategoria() { return $this->categoria; }
public function setIdFabricante($value) { $this->idFabricante = $value; return $this; }
public function getIdFabricante() { return $this->idFabricante; }
public function setFabricante($value) { $this->fabricante = $value; return $this; }
public function getFabricante() { return $this->fabricante; }
public function setQtdeEstoque($value) { $this->qtdeEstoque = $value; return $this; }
public function getQtdeEstoque() { return $this->qtdeEstoque; }
public function addQtdeEstoque($value) { $this->qtdeEstoque += $value; return $this; }
public function subQtdeEstoque($value) { $this->qtdeEstoque -= $value; return $this; }
public function setQtdeBloqueado($value) { $this->qtdeBloqueado = $value; return $this; }
public function getQtdeBloqueado() { return $this->qtdeBloqueado; }
public function addQtdeBloqueado($value) { $this->qtdeBloqueado += $value; return $this; }
public function subQtdeBloqueado($value) { $this->qtdeBloqueado -= $value; return $this; }
public function setQtdeEstoqueOld($value) { $this->qtdeEstoqueOld = $value; return $this; }
public function getQtdeEstoqueOld() { return $this->qtdeEstoqueOld; }
public function addQtdeEstoqueOld($value) { $this->qtdeEstoqueOld += $value; return $this; }
public function subQtdeEstoqueOld($value) { $this->qtdeEstoqueOld -= $value; return $this; }
public function setQtdeBloqueadoOld($value) { $this->qtdeBloqueadoOld = $value; return $this; }
public function getQtdeBloqueadoOld() { return $this->qtdeBloqueadoOld; }
public function addQtdeBloqueadoOld($value) { $this->qtdeBloqueadoOld += $value; return $this; }
public function subQtdeBloqueadoOld($value) { $this->qtdeBloqueadoOld -= $value; return $this; }
public function setPrecoVenda($value) { $this->precoVenda = $value; return $this; }
public function getPrecoVenda() { return $this->precoVenda; }
public function addPrecoVenda($value) { $this->precoVenda += $value; return $this; }
public function subPrecoVenda($value) { $this->precoVenda -= $value; return $this; }
}
class InventarioProdutoDAO extends ActiveRecord {
use InventarioProduto;
protected static $_includeHasMany = false;
function __construct() { parent::__construct("inventarioProduto"); }
public function loadPK($idInventario, $idProduto) { return $this->load('idInventario=? AND idProduto=?', array($idInventario, $idProduto)); }
public function loadLockedPK($idInventario, $idProduto) { return $this->LoadLocked('idInventario=? AND idProduto=?', array($idInventario, $idProduto)); }
/*
*/
}?>
|
glbatistabh/caixa
|
dbase/daos/inventarioProdutoDAO.php
|
PHP
|
gpl-3.0
| 3,672
|
package tmp.generated_cs;
import cide.gast.*;
import cide.gparser.*;
import cide.greferences.*;
import java.util.*;
public class overloadable_binary_operator6 extends overloadable_binary_operator {
public overloadable_binary_operator6(Token firstToken, Token lastToken) {
super(new Property[] {
}, firstToken, lastToken);
}
public overloadable_binary_operator6(Property[] properties, IToken firstToken, IToken lastToken) {
super(properties,firstToken,lastToken);
}
public IASTNode deepCopy() {
return new overloadable_binary_operator6(cloneProperties(),firstToken,lastToken);
}
}
|
ckaestne/CIDE
|
CIDE_Language_CS/src/tmp/generated_cs/overloadable_binary_operator6.java
|
Java
|
gpl-3.0
| 626
|
local ITEM = {}
ITEM.ID = "book_anarchistcookbook"
ITEM.Name = "Anarchist Cookbook"
ITEM.ClassSpawn = "all"
ITEM.Scrap = 0
ITEM.Small_Parts = 0
ITEM.Chemicals = 0
ITEM.Chance = 100
ITEM.Info = "A book describing in detail a variety of recipes for explosives firearms silencers etc."
ITEM.Type = "part"
ITEM.Remove = true
ITEM.Energy = 0
ITEM.Ent = "intm_anarchistcookbook"
ITEM.Model = "models/props_lab/bindergraylabel01b.mdl"
ITEM.Script = ""
ITEM.Weight = 1
ITEM.ShopHide = true
function ITEM.ToolCheck( p )
return true
end
function ITEM.Create( ply, class, pos )
local ent = ents.Create(class)
ent:SetAngles(Angle(0,0,0))
ent:SetPos(pos)
ent:Spawn()
end
function ITEM.Use( ply )
return true
end
PNRP.AddItem(ITEM)
|
AndyClausen/PNRP_HazG
|
postnukerp/Gamemode/items/books_code/book_anarchistcookbook.lua
|
Lua
|
gpl-3.0
| 769
|
/*
* Copyright © 2008-2010 Peter Colberg
*
* This file is part of HALMD.
*
* HALMD 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/>.
*/
#ifndef HALMD_OBSERVABLES_GPU_DENSITY_MODE_KERNEL_CUH
#define HALMD_OBSERVABLES_GPU_DENSITY_MODE_KERNEL_CUH
#include <cuda_wrapper/cuda_wrapper.hpp>
#include <halmd/mdsim/type_traits.hpp>
namespace halmd {
namespace observables {
namespace gpu {
template <int dimension>
struct density_mode_wrapper
{
typedef typename mdsim::type_traits<dimension, float>::gpu::vector_type vector_type;
typedef typename mdsim::type_traits<dimension, float>::gpu::coalesced_vector_type coalesced_vector_type;
/** list of wavevectors */
cuda::texture<coalesced_vector_type> q;
/** compute density_mode for all particles of a single species */
cuda::function<void (float4 const*, unsigned int const*, int, float*, float*, int)> compute;
/** finalise computation by summing block sums per wavevector */
cuda::function<void (float const*, float const*, float*, float*, int, int)> finalise;
static density_mode_wrapper const kernel;
};
template <int dimension>
density_mode_wrapper<dimension> const& get_density_mode_kernel()
{
return density_mode_wrapper<dimension>::kernel;
}
} // namespace observables
} // namespace gpu
} // namespace halmd
#endif /* ! HALMD_OBSERVABLES_GPU_DENSITY_MODE_KERNEL_CUH */
|
the-nic/halmd
|
halmd/observables/gpu/density_mode_kernel.hpp
|
C++
|
gpl-3.0
| 1,960
|
/*
Copyright (c) 2009 Dave Gamble
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.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
/* cJSON Types: */
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks {
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
extern int cJSON_HasObjectItem(cJSON *object,const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
/* Update array items. */
extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */
extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
extern void cJSON_Minify(char *json);
/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
/* Macro for iterating over an array */
#define cJSON_ArrayForEach(pos, head) for(pos = (head)->child; pos != NULL; pos = pos->next)
#ifdef __cplusplus
}
#endif
#endif
|
tazdij/odingine
|
src/odingine/utils/cJSON.h
|
C
|
gpl-3.0
| 7,781
|
/** \file src/cbmimage.c
* \brief Generic image handling
*
* Right now only contains a single function to create either a disk or a tape
* image file.
*/
/*
* cbmimage.c - Generic image handling.
*
* Written by
* Andreas Boose <viceteam@t-online.de>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA.
*
*/
#include "vice.h"
#include <stdio.h>
#include "diskimage.h"
#include "tape.h"
#include "cbmimage.h"
/** \brief Create a disk or tape image file
*
* \param[in] name name of/path to image
* \param[in] type disk/tape image type enumerator
*
* \return 0 on success, < 0 on failure
*/
int cbmimage_create_image(const char *name, unsigned int type)
{
switch (type) {
case DISK_IMAGE_TYPE_TAP:
return tape_image_create(name, type);
default:
break;
}
return disk_image_fsimage_create(name, type);
}
/** \brief Create a disk or tape image file
*
* \param[in] name name of/path to image
* \param[in] dname disk name and id
* \param[in] type disk/tape image type enumerator
*
* \return 0 on success, < 0 on failure
*/
int cbmimage_create_dxm_image(const char *name, const char *dname, unsigned int type)
{
return disk_image_fsimage_create_dxm(name, dname, type);
}
|
Rakashazi/emu-ex-plus-alpha
|
C64.emu/src/vice/cbmimage.c
|
C
|
gpl-3.0
| 2,063
|
<?php
/**
*
* @package mahara
* @subpackage module-framework
* @author Catalyst IT Ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
* @copyright For copyright information on Mahara, please see the README file distributed with this software.
*
*/
defined('INTERNAL') || die();
$config = new stdClass();
$config->version = 2017101600;
$config->release = '1.0.4';
|
MaharaProject/mahara
|
htdocs/module/framework/version.php
|
PHP
|
gpl-3.0
| 412
|
package URI_Problems_solution;
import java.util.Scanner;
/**
140
1 x 140 = 140
2 x 140 = 280
*/
public class URI_1078 {
public static void main(String[] args) {
int N;
Scanner input=new Scanner(System.in);
N =input.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.print(i+" x "+N+" = "+(i*N)+"\n");
}
}
}
|
ProgDan/maratona
|
URI/URI_1078.java
|
Java
|
gpl-3.0
| 364
|
<?php
use PLM\Validator\Exceptions\ValidationFailedException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use PLM\Repository\Interfaces\SlideshowRepositoryInterface;
class SlideshowExtController extends \BaseController {
/**
* @var SlideshowRepositoryInterface
*/
protected $slideshow;
/**
* Class constructor
*
* @param SlideshowRepositoryInterface $slideshow
*/
public function __construct(SlideshowRepositoryInterface $slideshow)
{
$this->slideshow = $slideshow;
}
/**
* Returns most recent resource
*
* @param int $count
* @return Model
*/
public function getRecent($count = 5)
{
return $this->slideshow->getRecent($count)->toJson();
}
}
|
plmhq/web-deprecated
|
app/controllers/slideshow/SlideshowExtController.php
|
PHP
|
gpl-3.0
| 701
|
const _ = require('lodash')
const BillingCycle = require('../billingCycle/billingCycle')
// Mais uma função de middleware
function getSummary(req, res){
BillingCycle.aggregate({
$project: {credit: {$sum: "$credits.value"}, debt: {$sum: "$debts.value"}}
}, {
$group: {_id: null, credit: {$sum: "$credit"}, debt: {$sum: "$debt"}}
}, {
$project: {_id: 0, credit: 1, debt: 1}
}, function(error, result){
if (error) {
res.status(500).json({errors: [error]})
} else {
res.json(_.defaults(result[0], {credit: 0, debt: 0}))
}
})
}
module.exports = { getSummary }
|
dacod/CursoMEAN
|
backend/api/billingSummary/billingSummaryService.js
|
JavaScript
|
gpl-3.0
| 605
|
#!/usr/bin/env python
# vim: sw=4:ts=4:sts=4:fdm=indent:fdl=0:
# -*- coding: UTF8 -*-
#
# A sword KJV indexed search module.
# Copyright (C) 2012-2013 Josiah Gordon <josiahg@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/>.
from collections import defaultdict
from xml.dom.minidom import parseString
from textwrap import fill
from os.path import dirname as os_dirname
from os.path import join as os_join
import dbm
import sys
import re
import Sword
from .utils import *
data_path = os_join(os_dirname(__file__), 'data')
def book_gen():
""" A Generator function that yields book names in order.
"""
# Yield a list of all the book names in the bible.
verse_key = Sword.VerseKey('Genesis 1:1')
for testament in [1, 2]:
for book in range(1, verse_key.bookCount(testament) + 1):
yield(verse_key.bookName(testament, book))
# book_list = list(book_gen())
try:
book_list = []
for book in book_gen():
book_list.append(book)
except:
pass
# Key function used to sort a list of verse references.
def sort_key(ref):
""" Sort verses by book.
"""
try:
book, chap_verse = ref.rsplit(' ', 1)
chap, verse = chap_verse.split(':')
val = '%02d%03d%03d' % (int(book_list.index(book)), int(chap),
int(verse))
return val
except Exception as err:
print('Error sorting "%s": %s' % (ref, err), file=sys.stderr)
sys.exit()
def parse_verse_range(verse_ref_list):
""" Uses VerseKey ParseVerseList to parse the reference list.
"""
# Make the argument a parseable string.
if isinstance(verse_ref_list, str):
verse_ref_str = verse_ref_list
else:
verse_ref_str = ' '.join(verse_ref_list)
verse_key = Sword.VerseKey()
# Parse the list.
# args: verse_list, default_key, expand_range, chapter_as_verse?
verse_list = verse_key.parseVerseList(verse_ref_str, 'Genesis 1:1', True,
False)
verse_set = set()
for i in range(verse_list.getCount()):
key = Sword.VerseKey(verse_list.getElement(i))
if key:
upper = key.getUpperBound().getText()
lower = key.getLowerBound().getText()
if upper != lower:
verse_set.update(VerseIter(lower, upper))
else:
verse_set.add(key.getText())
return verse_set
def add_context(ref_set, count=0):
""" Add count number of verses before and after each reference.
"""
if count == 0:
return ref_set
# Make a copy to work on.
clone_set = set(ref_set)
for ref in ref_set:
start = Sword.VerseKey(ref)
end = Sword.VerseKey(ref)
# Pass the beginning of the book.
start.decrement()
start.decrement(count - 1)
# Pass the end of the book.
end.increment()
end.increment(count - 1)
clone_set.update(VerseIter(start.getText(), end.getText()))
return clone_set
def mod_to_dbm(module: str, key_iter: iter, path: str) -> str:
""" Reads all the elements of key_iter from the module and saves them to a
dbm file.
"""
lookup = Lookup(module_name=module)
dbm_name = '%s/%s.dbm' % (path, module)
with IndexDbm(dbm_name, 'nf') as dbm_file:
for key in key_iter:
dbm_file[key] = lookup.get_raw_text(key)
return dbm_name
def make_daily_dbm(path: str=INDEX_PATH) -> str:
""" Saves the daily devotional to a dbm file.
"""
from datetime import date, timedelta
# Use a leap year to get all the days in February.
start = date(2012, 1, 1)
date_iter = ((start + timedelta(i)).strftime('%m.%d') for i in range(365))
return mod_to_dbm('Daily', date_iter, path)
def make_strongs_dbm(path: str=INDEX_PATH) -> str:
""" Saves the StrongsReal modules as dbms.
"""
keys = IndexDict('KJV')['_strongs_']
greek_keys = (i[1:] for i in keys if i.startswith('G'))
hebrew_keys = (i[1:] for i in keys if i.startswith('H'))
greek_file = mod_to_dbm('StrongsRealGreek', greek_keys, path)
hebrew_file = mod_to_dbm('StrongsRealHebrew', hebrew_keys, path)
return '\n'.join((greek_file, hebrew_file))
def make_robinson_dbm(path: str=INDEX_PATH) -> str:
""" Save robinson morph definitions in a dbm.
"""
keys = IndexDict('KJV')['_morph_']
robinson_keys = (i for i in keys if not i.startswith('TH'))
return mod_to_dbm('Robinson', robinson_keys, path)
def make_raw_kjv_dbm(path: str=INDEX_PATH) -> str:
""" Saves the KJV modules raw text as a dbm.
"""
verse_iter = VerseIter('Genesis 1:1')
return mod_to_dbm('KJV', verse_iter, path)
class Lookup(object):
""" A generic object to lookup refrences in differend sword modules.
"""
def __init__(self, module_name='KJV', markup=Sword.FMT_PLAIN):
""" Setup the module to look up information in.
"""
markup = Sword.MarkupFilterMgr(markup)
# We don't own this or it will segfault.
markup.thisown = False
self._library = Sword.SWMgr(markup)
self._module = self._library.getModule(module_name)
self._bold_regx = re.compile(r'<b>(\w+)</b>', re.I)
self._italic_regx = re.compile(r'''
(?:<i>|<hi\s*type="italic">)
([\w\s]+)(?:</i>|</hi>)
''', re.I | re.X)
self._br_regx = re.compile(r'(<br[\s]*/>|<lb/>)[\s]?', re.I)
self._cleanup_regx = re.compile(r'<[^>]*>')
self._brace_regx = re.compile(r'\{([\W]*)([\w]*)([\W]*)\}')
self._parenthesis_regx = re.compile(r'\(([\W]*)([\w]*)([\W]*)\)')
self._bracket_regx = re.compile(r'\[([\W]*)([\w ]*)([\W]*)\]')
self._verse_ref_regx = re.compile(r'''
<scripRef[^>]*>
([^<]*)
</scripRef>
''', re.I)
def get_text(self, key):
""" Get the text at the given key in the module.
i.e. get_text('3778') returns the greek strongs.
"""
encoding = get_encoding()
self._module.setKey(Sword.SWKey(key))
item_text = self._module.renderText()
# Make the text printable.
item_text = item_text.encode(encoding, 'replace')
item_text = item_text.decode(encoding, 'replace')
return fill(item_text, screen_size()[1])
def get_raw_text(self, key):
""" Get the text at the given key in the module.
i.e. get_text('3778') returns the greek strongs.
"""
encoding = get_encoding()
self._module.setKey(Sword.SWKey(key))
item_text = self._module.getRawEntry()
# Make the text printable.
item_text = item_text.encode(encoding, 'replace')
item_text = item_text.decode(encoding, 'replace')
return item_text
def get_formatted_text(self, key):
""" Returns the formated raw text of the specified key.
"""
text = self.get_raw_text(key)
# Format and highlight the text.
text = self._bold_regx.sub('\033[1m\\1\033[m', text)
text = self._italic_regx.sub('\033[36m\\1\033[m', text)
text = self._br_regx.sub('\n', text)
text = self._bracket_regx.sub('[\\1\033[33m\\2\033[m\\3]', text)
text = self._brace_regx.sub('{\\1\033[35m\\2\033[m\\3}', text)
text = self._parenthesis_regx.sub('(\\1\033[34m\\2\033[m\\3)', text)
text = self._verse_ref_regx.sub('\033[32m\\1\033[m', text)
text = self._cleanup_regx.sub('', text)
return text
class VerseTextIter(object):
""" An iterable object for accessing verses in the Bible. Maybe it will
be easier maybe not.
"""
def __init__(self, reference_iter, strongs=False, morph=False,
module='KJV', markup=Sword.FMT_PLAIN, render=''):
""" Initialize.
"""
markup = Sword.MarkupFilterMgr(markup)
# We don't own this or it will segfault.
markup.thisown = False
self._library = Sword.SWMgr(markup)
self._library.setGlobalOption("Headings", "On")
self._library.setGlobalOption("Cross-references", "Off")
if strongs:
self._library.setGlobalOption("Strong's Numbers", "On")
else:
self._library.setGlobalOption("Strong's Numbers", "Off")
if morph:
self._library.setGlobalOption("Morphological Tags", "On")
else:
self._library.setGlobalOption("Morphological Tags", "Off")
# Strings for finding the heading.
self._head_str = Sword.SWBuf('Heading')
self._preverse_str = Sword.SWBuf('Preverse')
self._canon_str = Sword.SWBuf('canonical')
self._module = self._library.getModule(module)
self._key = self._module.getKey()
if render.lower() == 'raw':
self._render_func = self._module.getRawEntry
elif render.lower() == 'render_raw':
self._fix_space_regx = re.compile(r'([^\.:\?!])\s+')
self._fix_end_regx = re.compile(r'\s+([\.:\?!,;])')
self._fix_start_tag_regx = re.compile(r'(<[npi]>)\s*')
self._fix_end_tag_regx = re.compile(r'\s*(</[npi]>)')
self._upper_divname_regx = re.compile(r'(\w+)([\'s]*)')
self._render_func = \
lambda: self._parse_raw(self._module.getRawEntry(),
strongs, morph)
else:
self._render_func = self._module.renderText
self._ref_iter = reference_iter
def next(self):
""" Returns the next verse reference and text.
"""
return self.__next__()
def __next__(self):
""" Returns a tuple of the next verse reference and text.
"""
# Retrieve the next reference.
verse_ref = next(self._ref_iter)
self._key.setText(verse_ref)
# Set the verse and render the text.
verse_text = self._get_text(verse_ref)
return (verse_ref, verse_text)
def __iter__(self):
""" Returns an iterator of self.
"""
return self
def _get_text(self, verse_ref):
""" Returns the verse text. Override this to produce formatted verse
text.
"""
verse_text = self._render_func()
if self._render_func == self._module.renderText:
verse_text = '%s %s' % (self._get_heading(), verse_text)
return verse_text
def _get_heading(self):
""" Returns the verse heading if there is one.
"""
attr_map = self._module.getEntryAttributesMap()
heading_list = []
head_str = self._head_str
preverse_str = self._preverse_str
canon_str = self._canon_str
if head_str in attr_map:
heading_attrs = attr_map[head_str]
if self._preverse_str in heading_attrs:
preverse_attrs = heading_attrs[preverse_str]
for k, val in preverse_attrs.items():
if canon_str in heading_attrs[k]:
if heading_attrs[k][canon_str].c_str() == 'true':
heading_list.append(val.c_str())
if heading_list:
return self._module.renderText(''.join(heading_list))
else:
return ''
def _parse_xml(self, xml_dom, strongs=False, morph=False):
""" Recursively parse all the childNodes in a xml minidom, and build
the verse text.
"""
# The string that will hold the verse.
verse_text = ''
# The name of the current tag.
name = xml_dom.localName if xml_dom.localName else ''
strongs_str = morph_str = ''
if xml_dom.attributes:
attr_dict = dict(xml_dom.attributes.items())
info_print(attr_dict, tag=4)
# Get any paragraph marker.
if 'marker' in attr_dict:
verse_text = '<p>%s</p> ' % attr_dict['marker']
else:
verse_text = ''
italic_str = '%s'
note_str = '%s'
for key, value in attr_dict.items():
# Italicize any added text.
if 'added' in value.lower():
italic_str = '<i>%s</i> '
# Label study notes.
elif 'study' in value.lower() or 'note' in name.lower():
note_str = '<n>%s</n>'
# Check for strongs.
elif 'lemma' in key.lower() and strongs:
for num in value.split():
strongs_str += ' <%s>' % num.split(':')[1]
# Check for morphology.
elif 'morph' in key.lower() and morph:
for tag in value.split():
morph_str += ' {%s}' % tag.split(':')[1]
# Recursively build the text from all the child nodes.
for node in xml_dom.childNodes:
child_s = self._parse_xml(node, strongs, morph)
if 'divine' in name.lower():
verse_text += \
' %s' % self._upper_divname_regx.sub(
lambda m: m.group(1).upper() + m.group(2),
child_s)
else:
verse_text += '%s' % child_s
if xml_dom.attributes:
return italic_str % note_str % '%s%s%s' % (verse_text, strongs_str,
morph_str)
if hasattr(xml_dom, 'data'):
info_print(xml_dom.data, tag=4)
return xml_dom.data
return verse_text.strip()
def _parse_raw(self, raw_text, strongs=False, morph=False):
""" Parse raw verse text and return a formated version.
"""
# A hack to make the raw text parse as xml.
xml_text = '''<?xml version="1.0"?>
<root xmlns="%s">
%s
</root>'''
# It works now we can parse the xml dom.
try:
parsed_xml = parseString(xml_text % ('verse', raw_text))
parsed_str = self._parse_xml(parsed_xml, strongs, morph)
except Exception as err:
print('Error %s while processing %s.\n' % (err, raw_text),
file=sys.stderr)
parsed_str = raw_text
# Make all the spacing correct.
fixed_str = self._fix_end_regx.sub('\\1', parsed_str)
fixed_str = self._fix_space_regx.sub('\\1 ', fixed_str)
fixed_str = self._fix_start_tag_regx.sub('\\1', fixed_str)
fixed_str = self._fix_end_tag_regx.sub('\\1', fixed_str)
return fixed_str.replace('\n', '')
class RawDict(object):
""" Parse raw verse text into a dictionary so it can easly be found out how
words are translated and how Strong's numbers are used.
"""
def __init__(self, reference_iter, module='KJV'):
""" Initialize the sword module.
"""
# This doesn't matter.
markup = Sword.MarkupFilterMgr(Sword.FMT_PLAIN)
# We don't own this or it will segfault.
markup.thisown = False
self._library = Sword.SWMgr(markup)
self._module = self._library.getModule(module)
self._key = self._module.getKey()
self._ref_iter = reference_iter
self._fix_space_regx = re.compile(r'([^\.:\?!])\s+')
self._fix_end_regx = re.compile(r'\s+([\.:\?!,;])')
self._remove_tag_regx = re.compile(r'(<i>\s?|\s?</i>)')
self._fix_start_tag_regx = re.compile(r'(<i>)\s*')
self._fix_end_tag_regx = re.compile(r'\s*(</i>)')
def next(self):
""" Returns the next verse reference and text.
"""
return self.__next__()
def __next__(self):
""" Returns a tuple of the next verse reference and text.
"""
# Retrieve the next reference.
verse_ref = next(self._ref_iter)
self._key.setText(verse_ref)
# Set the verse and render the text.
verse_dict = self.get_dict(verse_ref)
return (verse_ref, verse_dict)
def __iter__(self):
""" Returns an iterator of self.
"""
return self
def get_dict(self, verse_reference):
""" Lookup the verse reference in the sword module specified and
return a dictionary from it.
"""
self._key.setText(verse_reference)
raw_text = self._module.getRawEntry()
return self._get_parsed_dict(raw_text, True, True)
def _raw_to_dict(self, xml_dom, strongs=False, morph=False):
""" Recursively parse all the childNodes in a xml minidom, and build
a dictionary to use for telling what strongs numbers go to what words
and vise versa.
"""
# The dictionary that will hold the verse.
verse_dict = defaultdict(list)
verse_dict['_words'].append(defaultdict(list))
# Recursively build the text from all the child nodes.
child_s = ''
# The string that will hold the verse.
verse_text = ''
# The name of the current tag.
name = xml_dom.localName if xml_dom.localName else ''
# Build up the dictionary and verse text from the child nodes.
for node in xml_dom.childNodes:
child_s, child_d = self._raw_to_dict(node, strongs, morph)
if 'divine' in name.lower():
# Uppercase 'LORD's in the text.
verse_text += ' %s' % child_s.upper()
else:
verse_text += ' %s' % child_s
for key, value in child_d.items():
# Cleanup the items in the dictionary.
if value and not isinstance(value[0], dict):
new_list = set(value).union(verse_dict[key])
else:
new_list = value
if key == '_words':
# Update the words dictionary.
for words, lst in value[0].items():
new_list = filter(any, lst)
verse_dict['_words'][0][words].extend(new_list)
else:
# Make sure all items in the list are not None.
verse_dict[key].extend(filter(any, new_list))
if xml_dom.attributes:
attr_dict = dict(xml_dom.attributes.items())
# Cleanup and format the verse text.
verse_text = self._fix_end_regx.sub('\\1', verse_text)
verse_text = self._fix_space_regx.sub('\\1 ', verse_text)
verse_text = self._fix_start_tag_regx.sub('\\1', verse_text)
verse_text = self._fix_end_tag_regx.sub('\\1', verse_text)
verse_text = verse_text.replace('\n', '')
# Text clean of all italic tags.
clean_text = self._remove_tag_regx.sub('', verse_text)
italic_str = '%s'
# Dictionary to hold Strong's and Morphological attributes.
attrib_dict = defaultdict(list)
strongs_str = morph_str = ''
for key, value in attr_dict.items():
# Check for strongs.
if 'lemma' in key.lower():
for num in value.split():
# Get the number.
num = num.split(':')[1]
attrib_dict['strongs'].append(num)
# Associate the text with the number.
verse_dict[num].append(clean_text.strip())
if strongs:
strongs_str += ' <%s> ' % num
# Cleanup the attribute dictionary.
attrib_dict['strongs'] = list(set(attrib_dict['strongs']))
# Check for morphology.
elif 'morph' in key.lower():
for tag in value.split():
# Get the tag.
tag = tag.split(':')[1]
attrib_dict['morph'].append(tag)
# Associate the text with the tag.
verse_dict[tag].append(clean_text.strip())
if morph:
morph_str += ' {%s} ' % tag
# Cleanup the attribute dictionary.
attrib_dict['morph'] = list(set(attrib_dict['morph']))
if attrib_dict:
# Associate the numbers and tags with the text.
verse_dict['_words'][0][clean_text.strip()].append(attrib_dict)
elif 'type' in attr_dict or 'subType' in attr_dict:
_sub_type = attr_dict.get('subType', '')
_type = attr_dict.get('type', _sub_type)
if _type.lower() == 'x-p' or 'marker' in attr_dict:
# Get any paragraph marker.
verse_dict['_x-p'].append(attr_dict['marker'].strip())
elif 'study' in _type.lower() or 'note' in name.lower():
verse_dict['_notes'].append(verse_text.strip())
if 'added' in _type.lower() or 'added' in _sub_type.lower():
if 'marker' not in attr_dict:
# Italicize any added text.
italic_str = '<i>%s</i>'
verse_dict['_added'].append(verse_text.strip())
elif 'section' in _type.lower() or \
'preverse' in _sub_type.lower():
# Add the preverse heading.
verse_dict['_preverse'].append(verse_text.strip())
else:
# Don't include unwanted tags (e.g. strongs markup and
# notes) in the text.
verse_text = ''
elif 'xmlns' in attr_dict:
verse_text = verse_text.strip()
# Include the entire verse text in the dictionary.
verse_dict['_%s' % attr_dict['xmlns']].append(verse_text)
# Build up the verse string.
temp_str = '%s%s%s' % (verse_text, strongs_str, morph_str)
verse_text = italic_str % temp_str
if hasattr(xml_dom, 'data'):
return xml_dom.data, verse_dict
return verse_text, verse_dict
def _get_parsed_dict(self, raw_text, strongs=False, morph=False):
""" Parse raw verse text and return a formated version.
"""
info_print(raw_text, tag=31)
# A hack to make the raw text parse as xml.
xml_text = '''<?xml version="1.0"?>
<root xmlns="%s">
%s
</root>''' % ('verse_text', raw_text)
# It works now we can parse the xml dom.
try:
parsed_xml = parseString(xml_text)
return self._raw_to_dict(parsed_xml, strongs, morph)
except Exception as err:
info_print('Error %s while processing %s.\n' % (err, raw_text),
tag=31)
return raw_text, {'_verse_text': [raw_text],
'_words': [defaultdict(list)]}
class VerseIter(object):
""" Iterator of verse references.
"""
def __init__(self, start, end='Revelation of John 22:21'):
""" Setup the start and end references of the range.
"""
# Make sure the range is in order.
start, end = sorted([start, end], key=sort_key)
self._verse = Sword.VerseKey(start, end)
self._end_ref = self._verse.getUpperBound().getText()
self._verse_ref = ''
def __next__(self):
""" Returns the next verse reference.
"""
# End the iteration when we reach the end of the range.
if self._verse_ref == self._end_ref:
raise StopIteration()
# Get the current verse reference.
self._verse_ref = self._verse.getText()
# Load the next verse in the range.
self._verse.increment()
# Return only the reference.
return self._verse_ref
def __iter__(self):
""" Returns an iterator of self.
"""
return self
def next(self):
""" Returns the next verse reference.
"""
return self.__next__()
class ChapterIter(VerseIter):
""" Iterates over just one chapter.
"""
def __init__(self, book='Genesis', chapter=1):
""" Setup iterator.
"""
start = Sword.VerseKey('%s %s:1' % (book, chapter))
end = Sword.VerseKey(start.clone())
end.setVerse(end.getVerseMax())
super(ChapterIter, self).__init__(start.getText(), end.getText())
class BookIter(VerseIter):
""" Iterates over just one book.
"""
def __init__(self, book='Genesis'):
""" Setup iterator.
"""
start = Sword.VerseKey('%s 1:1' % book)
end = Sword.VerseKey(start.clone())
end.setChapter(end.getChapterMax())
end.setVerse(end.getVerseMax())
super(BookIter, self).__init__(start.getText(), end.getText())
class IndexBible(object):
""" Index the bible by Strong's Numbers, Morphological Tags, and words.
"""
def __init__(self, module='KJV', path=''):
""" Initialize the index dicts.
"""
self._module_name = module
self._path = path if path else INDEX_PATH
# Remove morphological and strongs information.
self._cleanup_regx = re.compile(r'\s*(<([GH]\d*)>|\{([A-Z\d-]*)\})')
# Note removal regular expression.
self._remove_notes_regex = re.compile(r'\s?<n>\s?(.*?)\s?</n>', re.S)
self._remove_tags_regex = re.compile(r'<[/]?[pin]>')
self._non_alnum_regx = re.compile(r'\W')
self._fix_regx = re.compile(r'\s+')
self._strongs_regx = re.compile(r'\s<([GH]\d+)>', re.I)
self._morph_regx = re.compile(r'\s\{([\w-]+)\}', re.I)
self._module_dict = defaultdict(list)
# lower_case is used to store lower_case words case sensitive
# counterpart. _Words_ is for easy key lookup for partial words.
self._words_set = set()
self._strongs_set = set()
self._morph_set = set()
self._module_dict.update({'lower_case': defaultdict(list)})
self._index_dict = {
'%s_index_i' % self._module_name: self._module_dict
}
self._index_built = False
def _book_gen(self):
""" A Generator function that yields book names in order.
"""
# Yield a list of all the book names in the bible.
verse_key = Sword.VerseKey('Genesis 1:1')
for testament in [1, 2]:
for book in range(1, verse_key.bookCount(testament) + 1):
yield(verse_key.bookName(testament, book))
def _index_strongs(self, verse_ref, verse_text):
""" Update the modules strongs dictionary from the verse text.
"""
strongs_list = set(self._strongs_regx.findall(verse_text))
for strongs_num in strongs_list:
self._strongs_set.add(strongs_num)
self._module_dict[strongs_num].append(verse_ref)
def _index_morph(self, verse_ref, verse_text):
""" Update the modules mophological dictionary from the verse text.
"""
morph_list = set(self._morph_regx.findall(verse_text))
for morph_num in morph_list:
self._morph_set.add(morph_num)
self._module_dict[morph_num].append(verse_ref)
def _index_words(self, verse_ref, verse_text):
""" Update the modules word dictionary from the verse text.
"""
# Remove all the morphological and strongs stuff.
clean_text = self._cleanup_regx.sub('', verse_text)
# Remove any non-alpha-numeric stuff.
clean_text = self._non_alnum_regx.sub(' ', clean_text)
# Replace runs of one or more spaces with just a single space.
clean_text = self._fix_regx.sub(' ', clean_text).strip()
# Remove the strongs and morphological stuff in such a way that
# split words are still split (i.e. where in, instead of wherein).
# So there are split versions and non-split versions just to be sure
# that the correct one is in there.
verse_text = self._strongs_regx.sub('', verse_text)
verse_text = self._morph_regx.sub('', verse_text)
# Strip out all unicode so we can search correctly.
verse_text = verse_text.encode('ascii', 'ignore')
verse_text = verse_text.decode('ascii', 'ignore')
verse_text = self._non_alnum_regx.sub(' ', verse_text)
verse_text = self._fix_regx.sub(' ', verse_text).strip()
# Include the capitalized words for case sensitive search.
word_set = set(verse_text.split())
word_set.update(set(clean_text.split()))
for word in word_set:
if word:
self._words_set.add(word)
self._module_dict[word].append(verse_ref)
l_word = word.lower()
if l_word != word:
# Map the lowercase word to the regular word for case
# insensitive searches.
if word not in self._module_dict['lower_case'][l_word]:
self._module_dict['lower_case'][l_word].append(word)
def _index_book(self, book_name="Genesis"):
""" Creates indexes for strongs, morphology and words.
"""
book_iter = BookIter(book_name)
verse_iter = VerseTextIter(book_iter, True, True, self._module_name,
render='render_raw')
for verse_ref, verse_text in verse_iter:
info_print('\033[%dD\033[KIndexing...%s' % \
(len(verse_ref) + 20, verse_ref), end='')
# Put the entire Bible in the index, so we can pull it out
# faster.
self._module_dict[verse_ref] = verse_text
# Remove the notes so we don't search them.
verse_text = self._remove_notes_regex.sub('', verse_text)
# Remove tags so they don't mess anything up.
verse_text = self._remove_tags_regex.sub('', verse_text)
# Index everything else.
self._index_strongs(verse_ref, verse_text)
self._index_morph(verse_ref, verse_text)
self._index_words(verse_ref, verse_text)
def build_index(self):
""" Create index files of the bible for strongs numbers,
morphological tags, and case (in)sensitive words.
"""
info_print("Indexing %s could take a while..." % self._module_name)
try:
for book in self._book_gen():
self._index_book(book)
except:
pass
self._module_dict['_words_'].extend(self._words_set)
self._module_dict['_strongs_'].extend(self._strongs_set)
self._module_dict['_morph_'].extend(self._morph_set)
info_print('\nDone.')
self._index_built = True
def write_index(self):
""" Write all the index dictionaries to their respective files. If
Any of the dictionaries is empty, then build the index.
The indexes are just json-ed dictionaries. The keys are the indexed
items and the values are the verse references that contain the key.
"""
if not self._index_built:
self.build_index()
# Build the index if it's not already built.
for name, dic in self._index_dict.items():
info_print("Writing %s.dbm..." % name)
# Save as just a plain text file. Has to be loaded all at once,
# so it is really slow.
#with open(name, 'w') as index_file:
#json.dump(dic, index_file, indent=4)
#return
# Save a dbm database that we can access without loading it all
# into memeory so it is fast.
dbm_name = '%s/%s.dbm' % (self._path, name)
with IndexDbm(dbm_name, 'nf') as index_file:
#with open(name, 'r') as i_file:
#dic =json.load(i_file)
index_file.update(dic)
|
zepto/biblesearch.web
|
sword_search.old/sword_verses.py
|
Python
|
gpl-3.0
| 32,753
|
/*
* Copyright (c) 1998-2000 Apple Computer, Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#include <IOKit/IOSharedDataQueue.h>
#include <IOKit/IODataQueueShared.h>
#include <IOKit/IOLib.h>
#include <IOKit/IOMemoryDescriptor.h>
#ifdef dequeue
#undef dequeue
#endif
#define super IODataQueue
OSDefineMetaClassAndStructors(IOSharedDataQueue, IODataQueue)
IOSharedDataQueue *IOSharedDataQueue::withCapacity(UInt32 size)
{
IOSharedDataQueue *dataQueue = new IOSharedDataQueue;
if (dataQueue) {
if (!dataQueue->initWithCapacity(size)) {
dataQueue->release();
dataQueue = 0;
}
}
return dataQueue;
}
IOSharedDataQueue *IOSharedDataQueue::withEntries(UInt32 numEntries, UInt32 entrySize)
{
IOSharedDataQueue *dataQueue = new IOSharedDataQueue;
if (dataQueue) {
if (!dataQueue->initWithEntries(numEntries, entrySize)) {
dataQueue->release();
dataQueue = 0;
}
}
return dataQueue;
}
Boolean IOSharedDataQueue::initWithCapacity(UInt32 size)
{
IODataQueueAppendix * appendix;
if (!super::init()) {
return false;
}
dataQueue = (IODataQueueMemory *)IOMallocAligned(round_page(size + DATA_QUEUE_MEMORY_HEADER_SIZE + DATA_QUEUE_MEMORY_APPENDIX_SIZE), PAGE_SIZE);
if (dataQueue == 0) {
return false;
}
dataQueue->queueSize = size;
dataQueue->head = 0;
dataQueue->tail = 0;
appendix = (IODataQueueAppendix *)((UInt8 *)dataQueue + size + DATA_QUEUE_MEMORY_HEADER_SIZE);
appendix->version = 0;
notifyMsg = &(appendix->msgh);
setNotificationPort(MACH_PORT_NULL);
return true;
}
void IOSharedDataQueue::free()
{
if (dataQueue) {
IOFreeAligned(dataQueue, round_page(dataQueue->queueSize + DATA_QUEUE_MEMORY_HEADER_SIZE + DATA_QUEUE_MEMORY_APPENDIX_SIZE));
dataQueue = NULL;
}
super::free();
}
IOMemoryDescriptor *IOSharedDataQueue::getMemoryDescriptor()
{
IOMemoryDescriptor *descriptor = 0;
if (dataQueue != 0) {
descriptor = IOMemoryDescriptor::withAddress(dataQueue, dataQueue->queueSize + DATA_QUEUE_MEMORY_HEADER_SIZE + DATA_QUEUE_MEMORY_APPENDIX_SIZE, kIODirectionOutIn);
}
return descriptor;
}
IODataQueueEntry * IOSharedDataQueue::peek()
{
IODataQueueEntry *entry = 0;
if (dataQueue && (dataQueue->head != dataQueue->tail)) {
IODataQueueEntry * head = 0;
UInt32 headSize = 0;
UInt32 headOffset = dataQueue->head;
UInt32 queueSize = dataQueue->queueSize;
head = (IODataQueueEntry *)((char *)dataQueue->queue + headOffset);
headSize = head->size;
// Check if there's enough room before the end of the queue for a header.
// If there is room, check if there's enough room to hold the header and
// the data.
if ((headOffset + DATA_QUEUE_ENTRY_HEADER_SIZE > queueSize) ||
((headOffset + headSize + DATA_QUEUE_ENTRY_HEADER_SIZE) > queueSize))
{
// No room for the header or the data, wrap to the beginning of the queue.
entry = dataQueue->queue;
} else {
entry = head;
}
}
return entry;
}
Boolean IOSharedDataQueue::dequeue(void *data, UInt32 *dataSize)
{
Boolean retVal = TRUE;
IODataQueueEntry * entry = 0;
UInt32 entrySize = 0;
UInt32 newHeadOffset = 0;
if (dataQueue) {
if (dataQueue->head != dataQueue->tail) {
IODataQueueEntry * head = 0;
UInt32 headSize = 0;
UInt32 headOffset = dataQueue->head;
UInt32 queueSize = dataQueue->queueSize;
head = (IODataQueueEntry *)((char *)dataQueue->queue + headOffset);
headSize = head->size;
// we wraped around to beginning, so read from there
// either there was not even room for the header
if ((headOffset + DATA_QUEUE_ENTRY_HEADER_SIZE > queueSize) ||
// or there was room for the header, but not for the data
((headOffset + headSize + DATA_QUEUE_ENTRY_HEADER_SIZE) > queueSize)) {
entry = dataQueue->queue;
entrySize = entry->size;
newHeadOffset = entrySize + DATA_QUEUE_ENTRY_HEADER_SIZE;
// else it is at the end
} else {
entry = head;
entrySize = entry->size;
newHeadOffset = headOffset + entrySize + DATA_QUEUE_ENTRY_HEADER_SIZE;
}
}
if (entry) {
if (data) {
if (dataSize) {
if (entrySize <= *dataSize) {
memcpy(data, &(entry->data), entrySize);
dataQueue->head = newHeadOffset;
} else {
retVal = FALSE;
}
} else {
retVal = FALSE;
}
} else {
dataQueue->head = newHeadOffset;
}
if (dataSize) {
*dataSize = entrySize;
}
} else {
retVal = FALSE;
}
} else {
retVal = FALSE;
}
return retVal;
}
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 0);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 1);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 2);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 3);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 4);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 5);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 6);
OSMetaClassDefineReservedUnused(IOSharedDataQueue, 7);
|
p01arst0rm/decorum-linux
|
_resources/kernels/xnu-arm/iokit/Kernel/IOSharedDataQueue.cpp
|
C++
|
gpl-3.0
| 7,141
|
package robotweb;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.DefaultCaret;
import socket.SocketConnexion;
/*
* Copyright (C) 2016 hux
*
* 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/>.
*/
/**
* Fenetre du programme
*
* @author hux
*/
public class windows extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;
/**
* Creates new form windows
*/
public windows() {
stop = false;
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jRadioButtonMenuItem1 = new javax.swing.JRadioButtonMenuItem();
jLabel1 = new javax.swing.JLabel();
input_url_request = new javax.swing.JTextField();
jButton_Start = new javax.swing.JButton();
jButton_Stop = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTxtPaneConsole = new javax.swing.JTextPane();
input_nb_threads = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
input_nb_requetes = new javax.swing.JTextField();
progressBar = new javax.swing.JProgressBar();
jLabel5 = new javax.swing.JLabel();
jLabelIP = new javax.swing.JLabel();
jTextIP = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jTextFieldPortClient = new javax.swing.JTextField();
jScrollPane3 = new javax.swing.JScrollPane();
jTextPaneConnexion = new javax.swing.JTextPane();
jButton1 = new javax.swing.JButton();
jTextFieldPortServeur = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jRadioButtonMenuItem1.setSelected(true);
jRadioButtonMenuItem1.setText("jRadioButtonMenuItem1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setText("Url :");
input_url_request.setText("http://www.google.com/");
input_url_request.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
input_url_requestActionPerformed(evt);
}
});
jButton_Start.setText("Start");
jButton_Start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_StartActionPerformed(evt);
}
});
jButton_Stop.setText("Stop");
jButton_Stop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_StopActionPerformed(evt);
}
});
jScrollPane2.setViewportView(jTxtPaneConsole);
DefaultCaret caret = (DefaultCaret)jTxtPaneConsole.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
input_nb_threads.setText("4");
input_nb_threads.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
input_nb_threadsActionPerformed(evt);
}
});
jLabel2.setText("Nb Threads :");
jLabel3.setText("Nb Requetes :");
input_nb_requetes.setText("1");
input_nb_requetes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
input_nb_requetesActionPerformed(evt);
}
});
progressBar.setMaximum(17576);
progressBar.setToolTipText("Progression : ");
jLabel5.setText("Nb de requêtes faites");
jLabelIP.setText("IP du client :");
jTextIP.setText("127.0.0.1");
jTextIP.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextIPActionPerformed(evt);
}
});
jLabel6.setText("Port du client:");
jTextFieldPortClient.setText("4024");
jTextFieldPortClient.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldPortClientActionPerformed(evt);
}
});
jScrollPane3.setViewportView(jTextPaneConnexion);
jButton1.setText("Start server");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextFieldPortServeur.setText("4025");
jTextFieldPortServeur.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldPortServeurActionPerformed(evt);
}
});
jLabel4.setText("Port du serveur :");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton_Stop)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton_Start))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(input_url_request))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(input_nb_threads, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(input_nb_requetes, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelIP)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldPortClient, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldPortServeur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addComponent(jScrollPane3))))))
.addGap(125, 125, 125))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(input_url_request, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(input_nb_threads, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(input_nb_requetes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelIP)
.addComponent(jTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6)
.addComponent(jTextFieldPortClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(jTextFieldPortServeur, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
.addComponent(jScrollPane3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Stop)
.addComponent(jButton_Start)))
.addContainerGap(17, Short.MAX_VALUE))
);
setBounds(0, 0, 1018, 515);
}// </editor-fold>//GEN-END:initComponents
private void jButton_StartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_StartActionPerformed
stop = false;//on réinitialise la variable stop
//variable à récupérer des champs
String url = input_url_request.getText();
String sNb_threads = input_nb_threads.getText();//nombre de thread
System.out.println(sNb_threads);
try {
int nb_threads = Integer.parseInt(sNb_threads);
nb_request = new AtomicInteger(0);//nb requetes faites
temps_moyen_threads = new AtomicLongArray(nb_threads);
debit_moyen_threads = new AtomicLongArray(nb_threads);
String sNb_requetes = input_nb_requetes.getText();//nombre de requête à faire
System.out.println(sNb_requetes);
int nb_requete_a_faire = Integer.parseInt(sNb_requetes);
//on fixe le maximum de la progress bar pour avoir un affichage correcte de la progression
progressBar.setMaximum(nb_requete_a_faire);
//execution de la thread chargé de l'affichage et du lancement des autres threads
Thread t = new Thread(new thread_print_graphique(nb_requete_a_faire, nb_threads, url));
t.start();
} catch (NumberFormatException e) {
jTxtPaneConsole.setText("Mauvais parmètre(s) renseigné(s)");
}
}//GEN-LAST:event_jButton_StartActionPerformed
private void input_nb_requetesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_input_nb_requetesActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_input_nb_requetesActionPerformed
private void input_url_requestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_input_url_requestActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_input_url_requestActionPerformed
private void jButton_StopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_StopActionPerformed
String previous_text_console = windows.jTxtPaneConsole.getText();
windows.jTxtPaneConsole.setText(previous_text_console + "\n Le serveur c'est arrêté");
progressBar.setValue(0);
stop = true;
}//GEN-LAST:event_jButton_StopActionPerformed
private void input_nb_threadsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_input_nb_threadsActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_input_nb_threadsActionPerformed
private void jTextFieldPortClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPortClientActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldPortClientActionPerformed
//Action qui va déclencher la création d'un server
//Le server va écouter sur le port passé en paramètre
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
//récupération depuis le formulaire
ip = jTextIP.getText();
portServeur = Integer.parseInt(jTextFieldPortServeur.getText());
portClient = Integer.parseInt(jTextFieldPortClient.getText());
try {
SocketConnexion.mainServer(portServeur);
String previous_text_console = windows.jTextPaneConnexion.getText();
windows.jTextPaneConnexion.setText(previous_text_console + "\n Serveur démarré correctement");
} catch (UnknownHostException ex) {
Logger.getLogger(windows.class.getName()).log(Level.SEVERE, null, ex);
String previous_text_console = windows.jTxtPaneConsole.getText();
windows.jTxtPaneConsole.setText(previous_text_console + "\n Le serveur a eu une erreur");
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTextIPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextIPActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextIPActionPerformed
private void jTextFieldPortServeurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPortServeurActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldPortServeurActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(windows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new windows().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField input_nb_requetes;
private javax.swing.JTextField input_nb_threads;
private javax.swing.JTextField input_url_request;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton_Start;
private javax.swing.JButton jButton_Stop;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabelIP;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItem1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField jTextFieldPortClient;
private javax.swing.JTextField jTextFieldPortServeur;
private javax.swing.JTextField jTextIP;
public static volatile javax.swing.JTextPane jTextPaneConnexion;
public static volatile javax.swing.JTextPane jTxtPaneConsole;
protected static volatile javax.swing.JProgressBar progressBar;
// End of variables declaration//GEN-END:variables
//déclaration variable volatile
// public static volatile int nb_request = 0;
// public static volatile double debit_moyen = 0.0;
// public static volatile double temps_moyen = 0.0;
public static AtomicInteger nb_request;
public static AtomicLongArray debit_moyen_threads;
public static AtomicLongArray temps_moyen_threads;
public static volatile String ip;
public static volatile int portClient;
public static volatile int portServeur;
public static volatile boolean stop;
}
|
MrHux/WebRobot
|
src/robotweb/windows.java
|
Java
|
gpl-3.0
| 21,807
|
#include <ah_platform.h>
#include <ah_services_impl.h>
// #############################################################################
// #############################################################################
LogSettingsItem *LogDispatcher::rootSettings = NULL;
// #############################################################################
// #############################################################################
LogDispatcher::LogDispatcher() {
// create default
configured = false;
rootSettings = logSettings.getDefaultSettings();
rootSettings -> setLogManager( &defaultLog );
}
LogDispatcher::~LogDispatcher() {
logMap.destroy();
LogDispatcher::rootSettings = NULL;
}
void LogDispatcher::configure( Xml config ) {
// init log settings
logSettings.load( config );
// create and configure logging
Xml xmlLoggers = config.getChildNode( "loggers" );
for( Xml xmlChild = xmlLoggers.getFirstChild( "logger" ); xmlChild.exists(); xmlChild = xmlChild.getNextChild( "logger" ) ) {
String name = xmlChild.getAttribute( "name" );
ASSERTMSG( logMap.get( name ) == NULL , "duplicate LogManager name=" + name );
LogManager *manager = new LogManager();
manager -> configure( xmlChild );
logMap.add( name , manager );
}
logSettings.attachLogManagers( this );
configured = true;
}
LogManager *LogDispatcher::getDefaultLogManager() {
return( getLogManager( "default" ) );
}
LogManager *LogDispatcher::getLogManager( String name ) {
LogManager *manager = logMap.get( name );
ASSERTMSG( manager != NULL , "not found LogManager name=" + name );
return( manager );
}
LogSettingsItem *LogDispatcher::getRootSettings() {
return( rootSettings );
}
LogSettingsItem *LogDispatcher::getObjectLogSettings( const char *className , const char *classInstance ) {
if( !configured )
return( rootSettings );
return( logSettings.getObjectSettings( className , classInstance ) );
}
LogSettingsItem *LogDispatcher::getServiceLogSettings( const char *serviceName ) {
if( !configured )
return( rootSettings );
return( logSettings.getServiceSettings( serviceName ) );
}
LogSettingsItem *LogDispatcher::getCustomLogSettings( const char *loggerName ) {
if( !configured )
return( rootSettings );
return( logSettings.getCustomSettings( loggerName ) );
}
LogSettingsItem *LogDispatcher::getCustomDefaultLogSettings() {
if( !configured )
return( rootSettings );
return( logSettings.getCustomDefaultSettings() );
}
bool LogDispatcher::start() {
bool result = defaultLog.start();
// start all log managers
for( int k = 0; k < logMap.count(); k++ ) {
LogManager *manager = logMap.getClassByIndex( k );
if( !manager -> start() )
result = false;
}
return( result );
}
void LogDispatcher::stop() {
defaultLog.stop();
// start all log managers
for( int k = 0; k < logMap.count(); k++ ) {
LogManager *manager = logMap.getClassByIndex( k );
manager -> stop();
}
}
void LogDispatcher::enableAsyncMode() {
// set logging to configured mode
for( int k = 0; k < logMap.count(); k++ ) {
LogManager *manager = logMap.getClassByIndex( k );
if( !manager -> getConfiguredSyncMode() )
manager -> setSyncMode( false );
}
}
void LogDispatcher::disableAsyncMode() {
// set logging to sync mode
for( int k = 0; k < logMap.count(); k++ ) {
LogManager *manager = logMap.getClassByIndex( k );
manager -> setSyncMode( true );
}
}
|
AbhishekGhosh/Artificial-Human
|
platform/src/services/logdispatcher.cpp
|
C++
|
gpl-3.0
| 3,503
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Formatter;
/**
* Formatter style class for defining styles.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*
* @api
*/
class OutputFormatterStyle implements OutputFormatterStyleInterface
{
private static $availableForegroundColors = array('black' => 30,
'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35,
'cyan' => 36, 'white' => 37);
private static $availableBackgroundColors = array('black' => 40,
'red' => 41, 'green' => 42, 'yellow' => 43, 'blue' => 44, 'magenta' => 45,
'cyan' => 46, 'white' => 47);
private static $availableOptions = array('bold' => 1, 'underscore' => 4,
'blink' => 5, 'reverse' => 7, 'conceal' => 8);
private $foreground;
private $background;
private $options = array();
/**
* Initializes output formatter style.
*
* @param string $foreground style foreground color name
* @param string $background style background color name
* @param array $options style options
*
* @api
*/
public function __construct ($foreground = null, $background = null,
array $options = array())
{
if (null !== $foreground) {
$this->setForeground($foreground);
}
if (null !== $background) {
$this->setBackground($background);
}
if (count($options)) {
$this->setOptions($options);
}
}
/**
* Sets style foreground color.
*
* @param string $color color name
*
* @api
*/
public function setForeground ($color = null)
{
if (null === $color) {
$this->foreground = null;
return;
}
if (! isset(static::$availableForegroundColors[$color])) {
throw new \InvalidArgumentException(
sprintf(
'Invalid foreground color specified: "%s". Expected one of (%s)',
$color,
implode(', ', array_keys(static::$availableForegroundColors))));
}
$this->foreground = static::$availableForegroundColors[$color];
}
/**
* Sets style background color.
*
* @param string $color color name
*
* @api
*/
public function setBackground ($color = null)
{
if (null === $color) {
$this->background = null;
return;
}
if (! isset(static::$availableBackgroundColors[$color])) {
throw new \InvalidArgumentException(
sprintf(
'Invalid background color specified: "%s". Expected one of (%s)',
$color,
implode(', ', array_keys(static::$availableBackgroundColors))));
}
$this->background = static::$availableBackgroundColors[$color];
}
/**
* Sets some specific style option.
*
* @param string $option option name
*
* @api
*/
public function setOption ($option)
{
if (! isset(static::$availableOptions[$option])) {
throw new \InvalidArgumentException(
sprintf('Invalid option specified: "%s". Expected one of (%s)',
$option, implode(', ', array_keys(static::$availableOptions))));
}
if (false ===
array_search(static::$availableOptions[$option], $this->options)) {
$this->options[] = static::$availableOptions[$option];
}
}
/**
* Unsets some specific style option.
*
* @param string $option option name
*/
public function unsetOption ($option)
{
if (! isset(static::$availableOptions[$option])) {
throw new \InvalidArgumentException(
sprintf('Invalid option specified: "%s". Expected one of (%s)',
$option, implode(', ', array_keys(static::$availableOptions))));
}
$pos = array_search(static::$availableOptions[$option], $this->options);
if (false !== $pos) {
unset($this->options[$pos]);
}
}
/**
* Set multiple style options at once.
*
* @param array $options
*/
public function setOptions (array $options)
{
$this->options = array();
foreach ($options as $option) {
$this->setOption($option);
}
}
/**
* Applies the style to a given text.
*
* @param string $text The text to style
*
* @return string
*/
public function apply ($text)
{
$codes = array();
if (null !== $this->foreground) {
$codes[] = $this->foreground;
}
if (null !== $this->background) {
$codes[] = $this->background;
}
if (count($this->options)) {
$codes = array_merge($codes, $this->options);
}
return sprintf("\033[%sm%s\033[0m", implode(';', $codes), $text);
}
}
|
abueldahab/medalyser
|
library/Symfony/Component/Console/Formatter/OutputFormatterStyle.php
|
PHP
|
gpl-3.0
| 5,274
|
var searchData=
[
['key',['key',['../d9/dcc/classnlohmann_1_1basic__json.html#aea1c863b719b4ca5b77188c171bbfafea3c6e0b8a9c15224a8228b9a98ca1531d',1,'nlohmann::basic_json']]]
];
|
blackmutzi/alexa-avs-prototype
|
docs/html/search/enumvalues_3.js
|
JavaScript
|
gpl-3.0
| 179
|
/*
* Copyright (C) 2008 Universidade Federal de Campina Grande
*
* This file is part of Commune.
*
* Commune is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package br.edu.ufcg.lsd.commune.functionaltests.data.parametersdeployment;
public class MyObject6 implements MyInterface6 {
public void hereIsParameter(MyParameter4 myParameter) {
}
}
|
OurGrid/commune
|
src/main/test/br/edu/ufcg/lsd/commune/functionaltests/data/parametersdeployment/MyObject6.java
|
Java
|
gpl-3.0
| 973
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_29) on Sat Mar 17 18:05:08 MSK 2012 -->
<TITLE>
ExtractorFactory (POI API Documentation)
</TITLE>
<META NAME="date" CONTENT="2012-03-17">
<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="ExtractorFactory (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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ExtractorFactory.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </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">
<A HREF="../../../../org/apache/poi/extractor/CommandLineTextExtractor.html" title="class in org.apache.poi.extractor"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/poi/extractor/ExtractorFactory.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExtractorFactory.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.poi.extractor</FONT>
<BR>
Class ExtractorFactory</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.poi.extractor.ExtractorFactory</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>ExtractorFactory</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
Figures out the correct POITextExtractor for your supplied
document, and returns it.
<P>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#CORE_DOCUMENT_REL">CORE_DOCUMENT_REL</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#ExtractorFactory()">ExtractorFactory</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(org.apache.poi.poifs.filesystem.DirectoryNode)">createExtractor</A></B>(<A HREF="../../../../org/apache/poi/poifs/filesystem/DirectoryNode.html" title="class in org.apache.poi.poifs.filesystem">DirectoryNode</A> poifsDir)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(org.apache.poi.poifs.filesystem.DirectoryNode, org.apache.poi.poifs.filesystem.POIFSFileSystem)">createExtractor</A></B>(<A HREF="../../../../org/apache/poi/poifs/filesystem/DirectoryNode.html" title="class in org.apache.poi.poifs.filesystem">DirectoryNode</A> poifsDir,
<A HREF="../../../../org/apache/poi/poifs/filesystem/POIFSFileSystem.html" title="class in org.apache.poi.poifs.filesystem">POIFSFileSystem</A> fs)</CODE>
<BR>
<B>Deprecated.</B> <I>Use <A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(org.apache.poi.poifs.filesystem.DirectoryNode)"><CODE>createExtractor(DirectoryNode)</CODE></A> instead</I></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(java.io.File)">createExtractor</A></B>(java.io.File f)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(java.io.InputStream)">createExtractor</A></B>(java.io.InputStream inp)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POIXMLTextExtractor.html" title="class in org.apache.poi">POIXMLTextExtractor</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(org.apache.poi.openxml4j.opc.OPCPackage)">createExtractor</A></B>(<A HREF="../../../../org/apache/poi/openxml4j/opc/OPCPackage.html" title="class in org.apache.poi.openxml4j.opc">OPCPackage</A> pkg)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POIOLE2TextExtractor.html" title="class in org.apache.poi">POIOLE2TextExtractor</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(org.apache.poi.poifs.filesystem.POIFSFileSystem)">createExtractor</A></B>(<A HREF="../../../../org/apache/poi/poifs/filesystem/POIFSFileSystem.html" title="class in org.apache.poi.poifs.filesystem">POIFSFileSystem</A> fs)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static java.lang.Boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#getAllThreadsPreferEventExtractors()">getAllThreadsPreferEventExtractors</A></B>()</CODE>
<BR>
Should all threads prefer event based over usermodel based extractors?
(usermodel extractors tend to be more accurate, but use more memory)
Default is to use the thread level setting, which defaults to false.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A>[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#getEmbededDocsTextExtractors(org.apache.poi.POIOLE2TextExtractor)">getEmbededDocsTextExtractors</A></B>(<A HREF="../../../../org/apache/poi/POIOLE2TextExtractor.html" title="class in org.apache.poi">POIOLE2TextExtractor</A> ext)</CODE>
<BR>
Returns an array of text extractors, one for each of
the embeded documents in the file (if there are any).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A>[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#getEmbededDocsTextExtractors(org.apache.poi.POIXMLTextExtractor)">getEmbededDocsTextExtractors</A></B>(<A HREF="../../../../org/apache/poi/POIXMLTextExtractor.html" title="class in org.apache.poi">POIXMLTextExtractor</A> ext)</CODE>
<BR>
Returns an array of text extractors, one for each of
the embeded documents in the file (if there are any).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected static boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#getPreferEventExtractor()">getPreferEventExtractor</A></B>()</CODE>
<BR>
Should this thread use event based extractors is available?
Checks the all-threads one first, then thread specific.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#getThreadPrefersEventExtractors()">getThreadPrefersEventExtractors</A></B>()</CODE>
<BR>
Should this thread prefer event based over usermodel based extractors?
(usermodel extractors tend to be more accurate, but use more memory)
Default is false.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#setAllThreadsPreferEventExtractors(java.lang.Boolean)">setAllThreadsPreferEventExtractors</A></B>(java.lang.Boolean preferEventExtractors)</CODE>
<BR>
Should all threads prefer event based over usermodel based extractors?
If set, will take preference over the Thread level setting.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#setThreadPrefersEventExtractors(boolean)">setThreadPrefersEventExtractors</A></B>(boolean preferEventExtractors)</CODE>
<BR>
Should this thread prefer event based over usermodel based extractors?
Will only be used if the All Threads setting is null.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="CORE_DOCUMENT_REL"><!-- --></A><H3>
CORE_DOCUMENT_REL</H3>
<PRE>
public static final java.lang.String <B>CORE_DOCUMENT_REL</B></PRE>
<DL>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../constant-values.html#org.apache.poi.extractor.ExtractorFactory.CORE_DOCUMENT_REL">Constant Field Values</A></DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="ExtractorFactory()"><!-- --></A><H3>
ExtractorFactory</H3>
<PRE>
public <B>ExtractorFactory</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getThreadPrefersEventExtractors()"><!-- --></A><H3>
getThreadPrefersEventExtractors</H3>
<PRE>
public static boolean <B>getThreadPrefersEventExtractors</B>()</PRE>
<DL>
<DD>Should this thread prefer event based over usermodel based extractors?
(usermodel extractors tend to be more accurate, but use more memory)
Default is false.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getAllThreadsPreferEventExtractors()"><!-- --></A><H3>
getAllThreadsPreferEventExtractors</H3>
<PRE>
public static java.lang.Boolean <B>getAllThreadsPreferEventExtractors</B>()</PRE>
<DL>
<DD>Should all threads prefer event based over usermodel based extractors?
(usermodel extractors tend to be more accurate, but use more memory)
Default is to use the thread level setting, which defaults to false.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setThreadPrefersEventExtractors(boolean)"><!-- --></A><H3>
setThreadPrefersEventExtractors</H3>
<PRE>
public static void <B>setThreadPrefersEventExtractors</B>(boolean preferEventExtractors)</PRE>
<DL>
<DD>Should this thread prefer event based over usermodel based extractors?
Will only be used if the All Threads setting is null.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setAllThreadsPreferEventExtractors(java.lang.Boolean)"><!-- --></A><H3>
setAllThreadsPreferEventExtractors</H3>
<PRE>
public static void <B>setAllThreadsPreferEventExtractors</B>(java.lang.Boolean preferEventExtractors)</PRE>
<DL>
<DD>Should all threads prefer event based over usermodel based extractors?
If set, will take preference over the Thread level setting.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getPreferEventExtractor()"><!-- --></A><H3>
getPreferEventExtractor</H3>
<PRE>
protected static boolean <B>getPreferEventExtractor</B>()</PRE>
<DL>
<DD>Should this thread use event based extractors is available?
Checks the all-threads one first, then thread specific.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="createExtractor(java.io.File)"><!-- --></A><H3>
createExtractor</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A> <B>createExtractor</B>(java.io.File f)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A>,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A></CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="createExtractor(java.io.InputStream)"><!-- --></A><H3>
createExtractor</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A> <B>createExtractor</B>(java.io.InputStream inp)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A>,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A></CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="createExtractor(org.apache.poi.openxml4j.opc.OPCPackage)"><!-- --></A><H3>
createExtractor</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POIXMLTextExtractor.html" title="class in org.apache.poi">POIXMLTextExtractor</A> <B>createExtractor</B>(<A HREF="../../../../org/apache/poi/openxml4j/opc/OPCPackage.html" title="class in org.apache.poi.openxml4j.opc">OPCPackage</A> pkg)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="createExtractor(org.apache.poi.poifs.filesystem.POIFSFileSystem)"><!-- --></A><H3>
createExtractor</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POIOLE2TextExtractor.html" title="class in org.apache.poi">POIOLE2TextExtractor</A> <B>createExtractor</B>(<A HREF="../../../../org/apache/poi/poifs/filesystem/POIFSFileSystem.html" title="class in org.apache.poi.poifs.filesystem">POIFSFileSystem</A> fs)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A>,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A></CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="createExtractor(org.apache.poi.poifs.filesystem.DirectoryNode, org.apache.poi.poifs.filesystem.POIFSFileSystem)"><!-- --></A><H3>
createExtractor</H3>
<PRE>
<FONT SIZE="-1">@Deprecated
</FONT>public static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A> <B>createExtractor</B>(<A HREF="../../../../org/apache/poi/poifs/filesystem/DirectoryNode.html" title="class in org.apache.poi.poifs.filesystem">DirectoryNode</A> poifsDir,
<A HREF="../../../../org/apache/poi/poifs/filesystem/POIFSFileSystem.html" title="class in org.apache.poi.poifs.filesystem">POIFSFileSystem</A> fs)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A>,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD><B>Deprecated.</B> <I>Use <A HREF="../../../../org/apache/poi/extractor/ExtractorFactory.html#createExtractor(org.apache.poi.poifs.filesystem.DirectoryNode)"><CODE>createExtractor(DirectoryNode)</CODE></A> instead</I>
<P>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A></CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="createExtractor(org.apache.poi.poifs.filesystem.DirectoryNode)"><!-- --></A><H3>
createExtractor</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A> <B>createExtractor</B>(<A HREF="../../../../org/apache/poi/poifs/filesystem/DirectoryNode.html" title="class in org.apache.poi.poifs.filesystem">DirectoryNode</A> poifsDir)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A>,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A></CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="getEmbededDocsTextExtractors(org.apache.poi.POIOLE2TextExtractor)"><!-- --></A><H3>
getEmbededDocsTextExtractors</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A>[] <B>getEmbededDocsTextExtractors</B>(<A HREF="../../../../org/apache/poi/POIOLE2TextExtractor.html" title="class in org.apache.poi">POIOLE2TextExtractor</A> ext)
throws java.io.IOException,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A>,
<A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A>,
org.apache.xmlbeans.XmlException</PRE>
<DL>
<DD>Returns an array of text extractors, one for each of
the embeded documents in the file (if there are any).
If there are no embeded documents, you'll get back an
empty array. Otherwise, you'll get one open
<A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi"><CODE>POITextExtractor</CODE></A> for each embeded file.
<P>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/InvalidFormatException.html" title="class in org.apache.poi.openxml4j.exceptions">InvalidFormatException</A></CODE>
<DD><CODE><A HREF="../../../../org/apache/poi/openxml4j/exceptions/OpenXML4JException.html" title="class in org.apache.poi.openxml4j.exceptions">OpenXML4JException</A></CODE>
<DD><CODE>org.apache.xmlbeans.XmlException</CODE></DL>
</DD>
</DL>
<HR>
<A NAME="getEmbededDocsTextExtractors(org.apache.poi.POIXMLTextExtractor)"><!-- --></A><H3>
getEmbededDocsTextExtractors</H3>
<PRE>
public static <A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi">POITextExtractor</A>[] <B>getEmbededDocsTextExtractors</B>(<A HREF="../../../../org/apache/poi/POIXMLTextExtractor.html" title="class in org.apache.poi">POIXMLTextExtractor</A> ext)</PRE>
<DL>
<DD>Returns an array of text extractors, one for each of
the embeded documents in the file (if there are any).
If there are no embeded documents, you'll get back an
empty array. Otherwise, you'll get one open
<A HREF="../../../../org/apache/poi/POITextExtractor.html" title="class in org.apache.poi"><CODE>POITextExtractor</CODE></A> for each embeded file.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ExtractorFactory.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </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">
<A HREF="../../../../org/apache/poi/extractor/CommandLineTextExtractor.html" title="class in org.apache.poi.extractor"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/apache/poi/extractor/ExtractorFactory.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExtractorFactory.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2012 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
|
gmchen/MosquitoSimulation
|
poi-3.8/docs/apidocs/org/apache/poi/extractor/ExtractorFactory.html
|
HTML
|
gpl-3.0
| 33,337
|
#include <iostream>
using namespace std;
int main() {
int a[5], b;
bool p = false;
for (int i = 0; i < 5; ++i) {
cin >> a[i];
b += a[i];
}
if ((b % 5 == 0) && (b != 0)) {
cout << b / 5;
} else {
cout << -1;
}
}
|
yamstudio/Codeforces
|
400/478A - Initial Bet.cpp
|
C++
|
gpl-3.0
| 241
|
package org.kuorum.service.reports.model;
/**
* Created by iduetxe on 22/06/17.
*/
public enum ReportType {
EXPORT_CONTACTS,
NEWSLETTER_EVENTS, CAMPAIGN_COLLECTION,
DEBATE_STATS,
EVENT_TICKET, EVENT_ASSISTANTS,
SURVEY_STATS
}
|
Kuorum/kuorumServices
|
serviceReports/src/main/java/org/kuorum/service/reports/model/ReportType.java
|
Java
|
gpl-3.0
| 250
|
/*
Copyright (C) 2015 PencilBlue, LLC
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/>.
*/
module.exports = function(pb) {
//pb dependencies
var util = pb.util;
/**
* Edits an article
*/
function EditArticle(){}
util.inherits(EditArticle, pb.BaseController);
EditArticle.prototype.render = function(cb) {
var self = this;
var vars = this.pathVars;
this.getJSONPostParams(function(err, post) {
post.publish_date = new Date(parseInt(post.publish_date));
post.publish_date2 = new Date(parseInt(post.publish_date2));
post.publish_date3 = new Date(parseInt(post.publish_date3));
post.publish_date4 = new Date(parseInt(post.publish_date4));
post.publish_date5 = new Date(parseInt(post.publish_date5));
post.id = vars.id;
delete post[pb.DAO.getIdField()];
var message = self.hasRequiredParams(post, self.getRequiredFields());
if (message) {
cb({
code: 400,
content: pb.BaseController.apiResponse(pb.BaseController.API_FAILURE, message)
});
return;
}
var dao = new pb.DAO();
dao.loadById(post.id, 'article', function(err, article) {
if(util.isError(err) || article === null) {
cb({
code: 400,
content: pb.BaseController.apiResponse(pb.BaseController.API_FAILURE, self.ls.get('INVALID_UID'))
});
return;
}
//TODO should we keep track of contributors (users who edit)?
if(self.session.authentication.user.admin < pb.SecurityService.ACCESS_EDITOR || !post.author) {
post.author = article.author;
}
post = pb.DocumentCreator.formatIntegerItems(post, ['draft']);
pb.DocumentCreator.update(post, article, ['meta_keywords']);
pb.RequestHandler.urlExists(article.url, post.id, function(error, exists) {
var testError = (error !== null && typeof error !== 'undefined');
if( testError || exists || article.url.indexOf('/admin') === 0) {
cb({
code: 400,
content: pb.BaseController.apiResponse(pb.BaseController.API_FAILURE, self.ls.get('EXISTING_URL'))
});
return;
}
dao.save(article, function(err, result) {
if(util.isError(err)) {
return cb({
code: 500,
content: pb.BaseController.apiResponse(pb.BaseController.API_FAILURE, self.ls.get('ERROR_SAVING'), result)
});
}
post.last_modified = new Date();
cb({content: pb.BaseController.apiResponse(pb.BaseController.API_SUCCESS, article.headline + ' ' + self.ls.get('EDITED'), post)});
});
});
});
});
};
EditArticle.prototype.getRequiredFields = function() {
return ['url', 'headline', 'article_layout', 'id'];
};
EditArticle.prototype.getSanitizationRules = function() {
return {
article_layout: pb.BaseController.getContentSanitizationRules()
};
};
//exports
return EditArticle;
};
|
janpetras/henley
|
plugins/pencilblue/controllers/actions/admin/content/articles/edit_article.js
|
JavaScript
|
gpl-3.0
| 4,245
|
package com.m4thg33k.tombmanygraves.core.commands;
import com.m4thg33k.tombmanygraves.core.handlers.FriendHandler;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import java.util.ArrayList;
import java.util.List;
public class CommandFriendList implements ICommand{
public final String COMMAND_NAME = "tmg_friendlist";
private final List<String> aliases;
public CommandFriendList()
{
aliases = new ArrayList<String>();
aliases.add("tmg_seefriends");
aliases.add("tmg_viewfriends");
aliases.add("tmg_listfriends");
aliases.add("tmg_list");
}
@Override
public String getCommandName() {
return COMMAND_NAME;
}
@Override
public String getCommandUsage(ICommandSender sender) {
return COMMAND_NAME;
}
@Override
public List<String> getCommandAliases() {
return this.aliases;
}
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
if (sender instanceof EntityPlayer)
{
FriendHandler.printFriendList(server,(EntityPlayer)sender);
}
}
@Override
public boolean checkPermission(MinecraftServer server, ICommandSender sender) {
return true;
}
@Override
public List<String> getTabCompletionOptions(MinecraftServer server, ICommandSender sender, String[] args, BlockPos pos) {
return args.length == 1 ? CommandBase.getListOfStringsMatchingLastWord(args, server.getAllUsernames()) : null;
}
@Override
public boolean isUsernameIndex(String[] args, int index) {
return index==0;
}
@Override
public int compareTo(ICommand o) {
return this.getCommandName().compareTo(o.getCommandName());
}
}
|
M4thG33k/TombManyGraves
|
src/main/java/com/m4thg33k/tombmanygraves/core/commands/CommandFriendList.java
|
Java
|
gpl-3.0
| 2,059
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.