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 |
|---|---|---|---|---|---|
/*
Copyright Jesus Perez <jesusprubio 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/>.
*/
'use strict';
// Private stuff
var credentialsJson = require('../artifacts/voipCredentials'),
HELP = {
description: 'Show common VoIP system default credentials',
options: null
};
// Public stuff
module.exports.help = HELP;
module.exports.run = function (options, callback) {
callback(null, credentialsJson);
};
| firebitsbr/bluebox-ng | modules/voipCredentials.js | JavaScript | gpl-3.0 | 1,058 |
<?php
/**
* Plugin Name: ConvertKit
* Plugin URI: https://convertkit.com/
* Description: Quickly and easily integrate ConvertKit forms into your site.
* Version: 1.9.2
* Author: ConvertKit
* Author URI: https://convertkit.com/
* Text Domain: convertkit
*/
if ( class_exists( 'WP_ConvertKit' ) ) {
return;
}
define( 'CONVERTKIT_PLUGIN_FILE', plugin_basename( __FILE__ ) );
define( 'CONVERTKIT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'CONVERTKIT_PLUGIN_PATH', __DIR__ );
define( 'CONVERTKIT_PLUGIN_VERSION', '1.9.2' );
require_once CONVERTKIT_PLUGIN_PATH . '/vendor/autoload.php';
require_once CONVERTKIT_PLUGIN_PATH . '/includes/class-convertkit.php';
require_once CONVERTKIT_PLUGIN_PATH . '/includes/class-convertkit-api.php';
require_once CONVERTKIT_PLUGIN_PATH . '/includes/class-ck-widget-form.php';
require_once CONVERTKIT_PLUGIN_PATH . '/includes/class-convertkit-custom-content.php';
require_once CONVERTKIT_PLUGIN_PATH . '/includes/integration/class-convertkit-wishlist-integration.php';
require_once CONVERTKIT_PLUGIN_PATH . '/includes/integration/class-convertkit-contactform7-integration.php';
if ( is_admin() ) {
require_once CONVERTKIT_PLUGIN_PATH . '/admin/class-convertkit-settings.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/class-multi-value-field-table.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/class-convertkit-tinymce.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/section/class-convertkit-settings-base.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/section/class-convertkit-settings-general.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/section/class-convertkit-settings-tools.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/section/class-convertkit-settings-wishlist.php';
require_once CONVERTKIT_PLUGIN_PATH . '/admin/section/class-convertkit-settings-contactform7.php';
$convertkit_settings = new ConvertKit_Settings();
}
WP_ConvertKit::init(); | nathanbarry/ConvertKit-WordPress | wp-convertkit.php | PHP | gpl-3.0 | 1,942 |
////////////////////////////////////////////////////////////////////
/// \file
/// \brief A class which can load and render meshes.
//
// CG-Beleg 2, by Felix Lauer (90404) & Simon Schneegans (90405)
////////////////////////////////////////////////////////////////////
# ifndef TEXTURE_HPP
# define TEXTURE_HPP
# include <string>
////////////////////////////////////////////////////////////////////
/// \brief A class representing texture.
///
/// This class allows to load texture data from a file and bind the
/// texture to an OpenGL context.
////////////////////////////////////////////////////////////////////
class Texture {
public:
////////////////////////////////////////////////////////////
/// \brief Constructor.
///
/// This constructs a new texture form a given file.
/// \param file The file which contains the texture data
////////////////////////////////////////////////////////////
Texture(std::string const& file);
////////////////////////////////////////////////////////////
/// \brief Destructor.
///
/// This will delete all associated buffers
////////////////////////////////////////////////////////////
~Texture();
////////////////////////////////////////////////////////////
/// \brief Bind the texture.
///
/// This will bind the texture to the current OpenGL context.
////////////////////////////////////////////////////////////
void bind(unsigned texPos);
////////////////////////////////////////////////////////////
/// \brief Unbind a texture.
///
/// This will unbind the texture with the given position.
/// \param texPos Position of the texture.
////////////////////////////////////////////////////////////
static void unbind(unsigned texPos);
private:
unsigned texID_;
};
# endif //TEXTURE_HPP
| thelaui/CG-Assignment | include/Texture.hpp | C++ | gpl-3.0 | 1,964 |
package models;
import orm.BaseModel;
public class Alert_Type extends BaseModel{
public String Description;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
| goeltanmay/DbmsProject | DBMSProject/src/models/Alert_Type.java | Java | gpl-3.0 | 259 |
package fr.harkame.banque.model.personne;
import java.util.ArrayList;
import fr.harkame.banque.model.compte.Compte;
import fr.harkame.banque.model.exception.OperationBancaireException;
import fr.harkame.banque.model.exception.PersonnelNonAutoriseException;
import fr.harkame.banque.model.operation.*;
public class Attache extends Personne
{
private final int idAttache;
private static int incr = 0;
private static ArrayList<Client> tabClient;
/**
* Constructeur - Attache, gerant des clients
*
* @param nom
* Nom de l'attache
*/
public Attache(String nom)
{
super(nom);
this.idAttache = Attache.incr++;
Attache.tabClient = new ArrayList<Client>();
System.out.println("Creation de l'attache ");
System.out.println(" - Nom : " + this.getNom());
System.out.println(" - identifiant " + this.getidAttache());
System.out.println("");
}
/**
* Getter - Nom d'un l'Attache (this)
*
* @return this.getNom()
*/
public String getNomAttache()
{
return this.getNom();
}
/**
* Getter - id d'un Attache (this)
*
* @return this.idAttache
*/
public int getidAttache()
{
return this.idAttache;
}
/**
* Attribut un client a un Attache (this) en le rajoutant dans son
* ArrayList de client
*
* @param client
* Client a associer
*/
public void SuivreClient(Client client)
{
this.gettabClient().add(client);
System.out.println("Association Attache - Client");
System.out.println(" - Attache : " + this.getidAttache());
System.out.println(" - Client : " + client.getidClient());
System.out.println("");
}
/**
* Permet de savoir si un compte appartient a un client suivit par un
* attache (this)
*
* @param compte
* Le compte a verifier
* @return true Si le compte appartient a un client suivit par un attache
* this
*/
public boolean estAssocie(Compte compte)
{
for(int i = 0; i < this.gettabClient().size(); i++)
{
if(this.gettabClient().get(i).appartient(compte))
{
return true;
}
}
return false;
}
/**
* Permet de recuperer tous les client suivit par l'attache (this)
*
* @return tabClient La liste des client suivit par l'attache (this)
*/
public ArrayList<Client> gettabClient()
{
return Attache.tabClient;
}
/**
* Permet a un attache (this) de forcer le debit
*
* @param debit
* Operation de debit a forcer
* @return debit.getCompte().getSolde() Le nouveau solde du compte
* @throws PersonnelNonAutoriseException
* Le compte n'appartient pas a un client suivit par cette
* attache
* @throws OperationBancaireException
* Montant negatif
*/
public double forcerDebit(Debit debit) throws PersonnelNonAutoriseException, OperationBancaireException
{
if(!(this.estAssocie(debit.getCompte())))
{
throw new PersonnelNonAutoriseException("Cette attache ne suit pas le client proprietaire de ce compte");
}
try
{
debit.DebitPossible();
debit.passerDebit();
}
catch(OperationBancaireException e)
{
debit.getCompte().Debiter(debit.getMontant());
}
return debit.getCompte().getSolde();
}
/**
* Permet a un attache (this) de forcer le credit
*
* @param credit
* Operation de credit a forcer
* @return credit.getCompte().getSolde() Le nouveau solde du compte
* @throws PersonnelNonAutoriseException
* compte n'appartient pas a un client suivit par cette
* attache
* @throws OperationBancaireException
* Montant negatif
*/
public double forcerCredit(Credit credit) throws PersonnelNonAutoriseException, OperationBancaireException
{
if(!(this.estAssocie(credit.getCompte())))
{
throw new PersonnelNonAutoriseException("Cette attache ne suit pas le client proprietaire de ce compte");
}
try
{
credit.CreditPossible();
credit.passerCredit();
}
catch(OperationBancaireException e)
{
credit.getCompte().Crediter(credit.getMontant());
}
return credit.getCompte().getSolde();
}
}
| Harkame/Banque | src/fr/harkame/banque/model/personne/Attache.java | Java | gpl-3.0 | 4,157 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66) on Mon Apr 18 22:42:05 PDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>InsertionSortDancerFirst</title>
<meta name="date" content="2016-04-18">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="InsertionSortDancerFirst";
}
}
catch(err) {
}
//-->
var methods = {"i0":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../cafedansadatabase/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/InsertionSortDancerFirst.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../cafedansadatabase/EditDancer.html" title="class in cafedansadatabase"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../cafedansadatabase/InsertionSortDancerLastName.html" title="class in cafedansadatabase"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?cafedansadatabase/InsertionSortDancerFirst.html" target="_top">Frames</a></li>
<li><a href="InsertionSortDancerFirst.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">cafedansadatabase</div>
<h2 title="Class InsertionSortDancerFirst" class="title">Class InsertionSortDancerFirst</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>cafedansadatabase.InsertionSortDancerFirst</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">InsertionSortDancerFirst</span>
extends java.lang.Object</pre>
<div class="block">This class implements a simple insertion sort,
to sort cities by first name.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../cafedansadatabase/InsertionSortDancerFirst.html#InsertionSortDancerFirst--">InsertionSortDancerFirst</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../cafedansadatabase/InsertionSortDancerFirst.html#sort-java.util.ArrayList-">sort</a></span>(java.util.ArrayList<<a href="../cafedansadatabase/Dancer.html" title="class in cafedansadatabase">Dancer</a>> list)</code>
<div class="block">Uses insertion sort to sort an ArrayList of Cities by name.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="InsertionSortDancerFirst--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>InsertionSortDancerFirst</h4>
<pre>public InsertionSortDancerFirst()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="sort-java.util.ArrayList-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>sort</h4>
<pre>public void sort(java.util.ArrayList<<a href="../cafedansadatabase/Dancer.html" title="class in cafedansadatabase">Dancer</a>> list)</pre>
<div class="block">Uses insertion sort to sort an ArrayList of Cities by name.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>list</code> - ArrayList of Dancer objects.</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../cafedansadatabase/package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/InsertionSortDancerFirst.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../cafedansadatabase/EditDancer.html" title="class in cafedansadatabase"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../cafedansadatabase/InsertionSortDancerLastName.html" title="class in cafedansadatabase"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?cafedansadatabase/InsertionSortDancerFirst.html" target="_top">Frames</a></li>
<li><a href="InsertionSortDancerFirst.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| SpaceKatt/cs143_project_one | dist/javadoc/cafedansadatabase/InsertionSortDancerFirst.html | HTML | gpl-3.0 | 9,741 |
---
title: Ubuntu – Copier coller avec MX Revolution
author: Deimos
type: post
date: 2009-05-10T09:37:44+00:00
url: /2009/05/10/ubuntu-copier-coller-avec-mx-revolution/
categories:
- Hi-Tech
- Linux
tags:
- Hi-Tech
- Linux
---
Depuis la version 8.10 d’Ubuntu, ma souris Logitech Revolution ne fonctionne plus comme avant. J’essaye donc de retrouver le petit petit à petit ce qui me manque. En gros :
* La sélection de texte qui copie automatiquement dans le presse papier (clipboard)
* Le bouton gauche de la souris qui effectue un coller du clipboard
Et bien ces 2 trucs là, je galère depuis longtemps à les retrouver et je pensais enfin avoir réussi.
Pour le bouton gauche, il faut utiliser BTNX et pour le texte qui se copie à la sélection xclip.
Mais tout ça n'est pas aussi simple que ça et avec une souris standart 3 bouttons, tout marche parfaitement.
C'est donc que tout est installé de base sans avoir besoins de rajouter des trucs supplémentaires. Et par chance, voici la solution :
{{< highlight bash >}}
xmodmap -e "pointer = 1 8 3 4 5 6 7 2 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32"
{{< /highlight >}}
J'ai trouvé la réponse [sur le forum d'ubuntu][1].
Pour ceux qui sont habitués à mon wiki, [il y a même un petit lien ici][2].
[1]: http://ubuntuforums.org/showthread.php?t=1115227
[2]: http://wiki.deimos.fr/Xmodmap_:_mapper_tous_les_boutons_de_sa_souris
| deimosfr/blog | content/post/2009-05-10-ubuntu-copier-coller-avec-mx-revolution.md | Markdown | gpl-3.0 | 1,452 |
# Contributing
In the following sections, the conventions and setup required for contributing to the NEAT project are outlined.
---
## Conventions
Below are standards set for the NEAT project to ensure ease, consistency, maintainability, and robustness for future development teams.
Changes made to these standards are purely to the desire of the current development team.
But note, that change for the sake of change is akin to failure.
### Versioning
The NEAT project strictly follows [Semantic Versioning 2.0.0](http://semver.org/) as proposed by [Tom Preston-Werner](http://tom.preston-werner.com/).
The in-house development period is to follow the 0.x.x standard until the initial release of a full scale product (at which time will change to its first major release).
### Coding Conventions
NEAT source follows the [PEP8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) the more recently named [pycodestyle](https://pypi.python.org/pypi/pycodestyle).
The only exception to this style guide is the rule on [line length](https://www.python.org/dev/peps/pep-0008/#maximum-line-length).
This rule has been omitted simply because of its occasional annoyance.
Code written in in this project should still try to adhere to the 79 character limit while documentation should stay under the 72 character limit.
You can disable the checking of line length by passing the error code `E501` as a value into the ignore list of `pep8`.
For example, `pep8 --ignore=E501 ./`.
We **highly** recommend you install a linter plugin for you editor that follows the pycodestyle (pep8) format.
### Documentation Conventions
In-code documentation utilizes Python's docstrings but does not follow [PEP 257](https://www.python.org/dev/peps/pep-0257/).
Instead, NEAT follows Sphinx's [info field lists](http://www.sphinx-doc.org/en/stable/domains.html#info-field-lists) as its docstring format.
Please adhere to this standard as future documentation builds become more and more difficult to accurately make the more deviations are made away from this format.
In addition, Python source files identify themselves using the following header.
```python
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright (c) {{year}} {{author}} ({{contact}})
# GNU GPLv3 <https://www.gnu.org/licenses/gpl-3.0.en.html>
```
_Where the following apply:_
<dl>
<dt><code>{{year}}</code></dt>
<dd>The current year of editing the file</dd>
<dt><code>{{author}}</code></dt>
<dd>The author of the file</dd>
<dt><code>{{contact}}</code></dt>
<dd>A method of contacting the author, most likely email</dd>
</dl>
We understand that this header is a pain to manually add on each commit.
That is why we suggest you use a modern code editor such as [Sublime Text 3](https://www.sublimetext.com/3) or more preferably [Atom](https://atom.io/) and utilize their respective file header plugins [FileHeader](https://packagecontrol.io/packages/FileHeader) and [file-header](https://atom.io/packages/file-header).
Please follow this standard as it makes documentation 10x easier for current and future documentation systems.
### Testing Conventions
NEAT tests are written using Python's standard [unittest](https://docs.python.org/3.6/library/unittest.html) module.
However, tests are executed via the [nose](https://nose.readthedocs.io/en/latest/) framework.
---
## Setup
Below is several sub-sections which talk about how to get started contributing to NEAT's development.
<!-- This section of the contributing document is continually subject to change -->
### Installing Dependencies
NEAT depends on several packages provided by [PyPi](https://pypi.python.org/pypi) which need to be installed for NEAT to function correctly.
These should be installed into a virtual Python environment by using the `virtualenv` package.
To set this up, first install the `virtualenv` and `virtualenvwrapper` packages via pip.
`pip install virtualenv virtualenvwrapper`
**Note**, if working on Windows, it may be necessary to install the `virtualenvwrapper-win` module as well.
This simply takes the functionality of `virtualenvwrapper` and translates it to batch scripts which Windows systems can run.
After installing these packages you should now have access to several scripts such as `mkvirtualenv`, `workon`, `rmvirtualenv`, and [others](https://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html).
However, it may also be necessary to set a environmental variable to tell the installed scripts where to setup all virtual environments.
This is typically done under the `WORKON_HOME` variable.
`export WORKON_HOME=~/.virtualenvs/`
This indicates that all virtual environments will be built and stored under the directory `~/.virtualenvs/`
NEAT is built and developed using Python 3, so it may be necessary to specify the version of Python to use when creating a virtual environment.
`mkvirtualenv --python=/usr/bin/python3 neat`
This will create and place your current shell into the context of a new virtual environment **neat** (if it doesn't exist already).
Note, most modern shells show an indication of what virtual environment you are currently located in. For example, a common shell prompt...
`/home/r/Documents/Github/neat $`
may be transformed to something resembling...
`(neat) /home/r/Documents/Github/neat $`
Once inside of this virtual environment it is possible to install dependencies.
All of NEATs dependencies are specified in the `requirements.txt` file located in the root of the repository.
This file follows pip's [requirements file format](https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format).
The dependencies listed in this file can be automatically installed using the virtual environment's pip script by passing the path to the requirements file after giving pip the `-r` flag.
`pip install -r ./requirements.txt`
If the pip installation goes successfully, then all listed requirements should be successfully installed to the virtual environment.
To get out of the virtual environment, simply use the `deactivate` command (only available inside of a virtual environment).
To re-enter a virtual environment, use the `workon neat` command, where _neat_ is the name of the virtual environment you created.
### Building Documentation
As stated previously, NEAT depends on Sphinx as its documentation builder.
This requires the sphinx toolkit to be installed on the user's system which is extremely easy to do.
By executing the following command outside of any Python virtual environments will ensure that the latest version of the Sphinx toolkit (and its dependencies) is installed and available on your system.
`pip install sphinx`
_This dependency is also already listed in the project's `requirements.txt`._
After you have the Sphinx toolkit, documentation can be built by executing the `make html` command within the documentation directory (docs).
However, changes outside of `autodoc`, which manages in-code docstrings, need to be written in [reStructuredText](http://www.sphinx-doc.org/en/stable/rest.html) and pointed to by the `index.rst`.
For more information, simply go through Sphinx's [First Steps with Sphinx](http://www.sphinx-doc.org/en/stable/tutorial.html).
### Writing Tests
We test all code using [nose](https://nose.readthedocs.io/en/latest/) but write all tests using the standard [unittest](https://docs.python.org/3/library/unittest.html) module included in Python.
We have given an example for how to write test cases in `nose/tests/_example.py`.
Please follow the standard of keeping multiple related test cases within the same source file.
### Running Tests
Tests can be run using the `nosetests` command (once the dependency has be installed).
NEAT also depends on the `coverage` module, and can report code test coverage through executing the `nosetests --with-coverage` command.
We use a continuous integration system, [TravisCI](https://travis-ci.org/), to continually check test cases on public pushes to the GitHub repository.
We also utilize [codecov](https://codecov.io/gh), which presents code coverage as reported by TravisCI after each public push.
The configuration for continuous integration can be found in the standard `.travis.yml` file, found in the root of the repository.
| ritashugisha/neat | .github/CONTRIBUTING.md | Markdown | gpl-3.0 | 8,308 |
/**
* Copyright (c) 2017, Monkey Brush
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
#include "PickingVisitor.hpp"
#include "../Scenegraph/Node.hpp"
#include "../Scenegraph/Group.hpp"
namespace mb
{
PickingVisitor::PickingVisitor( const Ray& ray,
Results &results, FilterType filter )
: _ray( ray )
, _results( results)
, _filter( filter )
{
}
void PickingVisitor::traverse( Node* n )
{
_results.reset( );
Visitor::traverse( n );
_results.sort( [ &] ( Node*, Node* ) -> bool
{
// TODO: Sort candidates using distance(_ray, n1->worldBound()->center) < distance(_ray, n2->worldBound()->center);
return false;
// TODO: return distance_ray_bound( _ray, n1->getWorldBound( )->getCenter( ) ) <
// distance_ray_bound( _ray, n2->getWorldBound( )->getCenter( ) );
} );
}
void PickingVisitor::visitNode( Node* n )
{
if ( _filter == nullptr || _filter( n ) )
{
_results.push( n );
}
}
void PickingVisitor::visitGroup( Group* group )
{
visitNode( group );
group->forEachNode( [ &] ( Node* n )
{
if ( _ray.intersect( n->getWorldBound( ) ) )
{
n->accept( *this );
}
} );
}
}
| MonkeyBrushDev/MonkeyBrushCpp | mb/Visitors/PickingVisitor.cpp | C++ | gpl-3.0 | 1,852 |
/*******************************************************************************
* HellFirePvP / Astral Sorcery 2017
*
* This project is licensed under GNU GENERAL PUBLIC LICENSE Version 3.
* The source code is available on github: https://github.com/HellFirePvP/AstralSorcery
* For further details, see the License file there.
******************************************************************************/
package hellfirepvp.astralsorcery.common.base;
import hellfirepvp.astralsorcery.AstralSorcery;
import hellfirepvp.astralsorcery.common.block.BlockCustomOre;
import hellfirepvp.astralsorcery.common.lib.BlocksAS;
import hellfirepvp.astralsorcery.common.util.ItemUtils;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/**
* This class is part of the Astral Sorcery Mod
* The complete source code for this mod can be found on github.
* Class: LightOreTransmutations
* Created by HellFirePvP
* Date: 30.01.2017 / 12:30
*/
public class LightOreTransmutations {
public static List<Transmutation> mtTransmutations = new LinkedList<>(); //Minetweaker cache
private static List<Transmutation> registeredTransmutations = new LinkedList<>();
private static List<Transmutation> localFallback = new LinkedList<>();
public static void init() {
registerTransmutation(new Transmutation(Blocks.MAGMA.getDefaultState(), Blocks.OBSIDIAN.getDefaultState(), 400.0D));
registerTransmutation(new Transmutation(Blocks.SAND.getDefaultState(), Blocks.CLAY.getDefaultState(), 400.0D));
registerTransmutation(new Transmutation(Blocks.DIAMOND_ORE.getDefaultState(), Blocks.EMERALD_ORE.getDefaultState(), 1000.0D));
registerTransmutation(new Transmutation(Blocks.NETHER_WART_BLOCK.getDefaultState(), Blocks.SOUL_SAND.getDefaultState(), 200.0D));
registerTransmutation(new Transmutation(Blocks.SEA_LANTERN.getDefaultState(), Blocks.LAPIS_BLOCK.getDefaultState(), 200.0D));
registerTransmutation(new Transmutation(Blocks.SANDSTONE.getDefaultState(), Blocks.END_STONE.getDefaultState(), 200.0D));
registerTransmutation(new Transmutation(Blocks.NETHERRACK.getDefaultState(), Blocks.NETHER_BRICK.getDefaultState(), 200.0D));
registerTransmutation(new Transmutation(Blocks.IRON_ORE.getDefaultState(), BlocksAS.customOre.getDefaultState().withProperty(BlockCustomOre.ORE_TYPE, BlockCustomOre.OreType.STARMETAL), 100));
registerTransmutation(new Transmutation(Blocks.PUMPKIN.getDefaultState(), Blocks.CAKE.getDefaultState(), new ItemStack(Blocks.PUMPKIN), new ItemStack(Items.CAKE), 600.0D));
cacheLocalFallback();
}
private static void cacheLocalFallback() {
if(localFallback.isEmpty()) {
localFallback.addAll(registeredTransmutations);
}
}
public static void loadFromFallback() {
registeredTransmutations.clear();
registeredTransmutations.addAll(localFallback);
}
public static Transmutation tryRemoveTransmutation(ItemStack outRemove, boolean matchMeta) {
Block b = Block.getBlockFromItem(outRemove.getItem());
if(b != Blocks.AIR) {
for (Transmutation tr : registeredTransmutations) {
if(tr.output.getBlock().equals(b)) {
if(!matchMeta || tr.output.getBlock().getMetaFromState(tr.output) == outRemove.getMetadata()) {
registeredTransmutations.remove(tr);
return tr;
}
}
}
}
for (Transmutation tr : registeredTransmutations) {
if(!tr.outStack.isEmpty() && ItemUtils.matchStackLoosely(tr.outStack, outRemove)) {
registeredTransmutations.remove(tr);
return tr;
}
}
return null;
}
//Will return itself if successful.
@Nullable
public static Transmutation registerTransmutation(Transmutation tr) {
for (Transmutation t : registeredTransmutations) {
if(t.input.equals(tr.input)) {
AstralSorcery.log.warn("Tried to register Transmutation that has the same input as an already existing one.");
return null;
}
}
if(tr.input == null) {
AstralSorcery.log.warn("Tried to register Transmutation with null input - Skipping!");
return null;
}
if(tr.input.getBlock().equals(Blocks.CRAFTING_TABLE)) {
AstralSorcery.log.warn("Cannot register Transmutation of iron workbench -> something. By default occupied by general crafting which is handled differently.");
return null;
}
if(tr.output == null) {
AstralSorcery.log.warn("Tried to register Transmutation with null output - Skipping!");
return null;
}
registeredTransmutations.add(tr);
return tr;
}
public static List<Transmutation> getRegisteredTransmutations() {
return Collections.unmodifiableList(registeredTransmutations);
}
@Nullable
public static Transmutation searchForTransmutation(IBlockState tryStateIn) {
for (Transmutation tr : registeredTransmutations) {
if(tr.input.equals(tryStateIn)) return tr;
}
for (Transmutation tr : mtTransmutations) {
if(tr.input.equals(tryStateIn)) return tr;
}
return null;
}
public static class Transmutation {
public final IBlockState input;
public final IBlockState output;
public final double cost;
@Nonnull
public final ItemStack outStack;
@Nonnull
public final ItemStack inStack;
public Transmutation(IBlockState input, IBlockState output, double cost) {
this(input, output, ItemStack.EMPTY, ItemStack.EMPTY, cost);
}
public Transmutation(IBlockState input, IBlockState output, @Nonnull ItemStack inputDisplay, @Nonnull ItemStack outputDisplay, double cost) {
this.input = input;
this.output = output;
this.cost = cost;
this.outStack = outputDisplay;
this.inStack = inputDisplay;
}
@Nonnull
public ItemStack getInputDisplayStack() {
if (!inStack.isEmpty()) {
return inStack.copy();
}
return ItemUtils.createBlockStack(input);
}
@Nonnull
public ItemStack getOutputDisplayStack() {
if(!outStack.isEmpty()) {
return outStack.copy();
}
return ItemUtils.createBlockStack(output);
}
}
}
| Saereth/AstralSorcery | src/main/java/hellfirepvp/astralsorcery/common/base/LightOreTransmutations.java | Java | gpl-3.0 | 6,984 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "sigmoid.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace energyScalingFunctions
{
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
defineTypeNameAndDebug(sigmoid, 0);
addToRunTimeSelectionTable
(
energyScalingFunction,
sigmoid,
dictionary
);
// * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * * //
scalar sigmoid::sigmoidScale
(
const scalar r,
const scalar shift,
const scalar scale
) const
{
return 1.0 / (1.0 + exp( scale * (r - shift)));
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
sigmoid::sigmoid
(
const word& name,
const dictionary& energyScalingFunctionProperties,
const pairPotential& pairPot
)
:
energyScalingFunction(name, energyScalingFunctionProperties, pairPot),
sigmoidCoeffs_
(
energyScalingFunctionProperties.subDict(typeName + "Coeffs")
),
shift_(readScalar(sigmoidCoeffs_.lookup("shift"))),
scale_(readScalar(sigmoidCoeffs_.lookup("scale")))
{}
// * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * //
void sigmoid::scaleEnergy(scalar& e, const scalar r) const
{
e *= sigmoidScale(r, shift_, scale_);
}
bool sigmoid::read(const dictionary& energyScalingFunctionProperties)
{
energyScalingFunction::read(energyScalingFunctionProperties);
sigmoidCoeffs_ =
energyScalingFunctionProperties.subDict(typeName + "Coeffs");
sigmoidCoeffs_.lookup("shift") >> shift_;
sigmoidCoeffs_.lookup("scale") >> shift_;
return true;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace energyScalingFunctions
} // End namespace Foam
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/lagrangian/molecularDynamics/potential/energyScalingFunction/derived/sigmoid/sigmoid.C | C++ | gpl-3.0 | 3,149 |
# Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'ecl_kw.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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.
#
# ERT 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 at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import AnalysisConfig, EclConfig, EnkfObs, EnKFState, LocalConfig, ModelConfig, EnsembleConfig, PlotConfig, SiteConfig, ENKF_LIB, EnkfSimulationRunner, EnkfFsManager, ErtWorkflowList, PostSimulationHook
from ert.enkf.enums import EnkfInitModeEnum
from ert.util import SubstitutionList, Log
class EnKFMain(BaseCClass):
def __init__(self, model_config, strict=True):
c_ptr = EnKFMain.cNamespace().bootstrap(model_config, strict, False)
super(EnKFMain, self).__init__(c_ptr)
self.__simulation_runner = EnkfSimulationRunner(self)
self.__fs_manager = EnkfFsManager(self)
@classmethod
def createCReference(cls, c_pointer, parent=None):
obj = super(EnKFMain, cls).createCReference(c_pointer, parent)
obj.__simulation_runner = EnkfSimulationRunner(obj)
obj.__fs_manager = EnkfFsManager(obj)
return obj
@staticmethod
def createNewConfig(config_file, storage_path, case_name, dbase_type, num_realizations):
EnKFMain.cNamespace().create_new_config(config_file, storage_path, case_name, dbase_type, num_realizations)
def getRealisation(self , iens):
""" @rtype: EnKFState """
if 0 <= iens < self.getEnsembleSize():
return EnKFMain.cNamespace().iget_state(self, iens).setParent(self)
else:
raise IndexError("iens value:%d invalid Valid range: [0,%d)" % (iens , len(self)))
def set_eclbase(self, eclbase):
EnKFMain.cNamespace().set_eclbase(self, eclbase)
def umount(self):
self.__fs_manager.umount()
def free(self):
self.umount()
EnKFMain.cNamespace().free(self)
def getEnsembleSize(self):
""" @rtype: int """
return EnKFMain.cNamespace().get_ensemble_size(self)
def resizeEnsemble(self, value):
EnKFMain.cNamespace().resize_ensemble(self, value)
def ensembleConfig(self):
""" @rtype: EnsembleConfig """
return EnKFMain.cNamespace().get_ens_config(self).setParent(self)
def analysisConfig(self):
""" @rtype: AnalysisConfig """
return EnKFMain.cNamespace().get_analysis_config(self).setParent(self)
def getModelConfig(self):
""" @rtype: ModelConfig """
return EnKFMain.cNamespace().get_model_config(self).setParent(self)
def logh(self):
""" @rtype: Log """
return EnKFMain.cNamespace().get_logh(self).setParent(self)
def local_config(self):
""" @rtype: LocalConfig """
return EnKFMain.cNamespace().get_local_config(self).setParent(self)
def siteConfig(self):
""" @rtype: SiteConfig """
return EnKFMain.cNamespace().get_site_config(self).setParent(self)
def eclConfig(self):
""" @rtype: EclConfig """
return EnKFMain.cNamespace().get_ecl_config(self).setParent(self)
def plotConfig(self):
""" @rtype: PlotConfig """
return EnKFMain.cNamespace().get_plot_config(self).setParent(self)
def set_datafile(self, datafile):
EnKFMain.cNamespace().set_datafile(self, datafile)
def get_schedule_prediction_file(self):
schedule_prediction_file = EnKFMain.cNamespace().get_schedule_prediction_file(self)
return schedule_prediction_file
def set_schedule_prediction_file(self, file):
EnKFMain.cNamespace().set_schedule_prediction_file(self, file)
def getDataKW(self):
""" @rtype: SubstitutionList """
return EnKFMain.cNamespace().get_data_kw(self)
def clearDataKW(self):
EnKFMain.cNamespace().clear_data_kw(self)
def addDataKW(self, key, value):
EnKFMain.cNamespace().add_data_kw(self, key, value)
def getMountPoint(self):
return EnKFMain.cNamespace().get_mount_point(self)
def del_node(self, key):
EnKFMain.cNamespace().del_node(self, key)
def getObservations(self):
""" @rtype: EnkfObs """
return EnKFMain.cNamespace().get_obs(self).setParent(self)
def load_obs(self, obs_config_file):
EnKFMain.cNamespace().load_obs(self, obs_config_file)
def reload_obs(self):
EnKFMain.cNamespace().reload_obs(self)
def get_pre_clear_runpath(self):
pre_clear = EnKFMain.cNamespace().get_pre_clear_runpath(self)
return pre_clear
def set_pre_clear_runpath(self, value):
EnKFMain.cNamespace().set_pre_clear_runpath(self, value)
def iget_keep_runpath(self, iens):
ikeep = EnKFMain.cNamespace().iget_keep_runpath(self, iens)
return ikeep
def iset_keep_runpath(self, iens, keep_runpath):
EnKFMain.cNamespace().iset_keep_runpath(self, iens, keep_runpath)
def get_templates(self):
return EnKFMain.cNamespace().get_templates(self).setParent(self)
def get_site_config_file(self):
site_conf_file = EnKFMain.cNamespace().get_site_config_file(self)
return site_conf_file
def getUserConfigFile(self):
""" @rtype: str """
config_file = EnKFMain.cNamespace().get_user_config_file(self)
return config_file
def getHistoryLength(self):
return EnKFMain.cNamespace().get_history_length(self)
def getMemberRunningState(self, ensemble_member):
""" @rtype: EnKFState """
return EnKFMain.cNamespace().iget_state(self, ensemble_member).setParent(self)
def get_observations(self, user_key, obs_count, obs_x, obs_y, obs_std):
EnKFMain.cNamespace().get_observations(self, user_key, obs_count, obs_x, obs_y, obs_std)
def get_observation_count(self, user_key):
return EnKFMain.cNamespace().get_observation_count(self, user_key)
def getEnkfSimulationRunner(self):
""" @rtype: EnkfSimulationRunner """
return self.__simulation_runner
def getEnkfFsManager(self):
""" @rtype: EnkfFsManager """
return self.__fs_manager
def getWorkflowList(self):
""" @rtype: ErtWorkflowList """
return EnKFMain.cNamespace().get_workflow_list(self).setParent(self)
def getPostSimulationHook(self):
""" @rtype: PostSimulationHook """
return EnKFMain.cNamespace().get_qc_module(self)
def exportField(self, keyword, path, iactive, file_type, report_step, state, enkfFs):
"""
@type keyword: str
@type path: str
@type iactive: BoolVector
@type file_type: EnkfFieldFileFormatEnum
@type report_step: int
@type state: EnkfStateType
@type enkfFs: EnkfFs
"""
assert isinstance(keyword, str)
return EnKFMain.cNamespace().export_field_with_fs(self, keyword, path, iactive, file_type, report_step, state, enkfFs)
def loadFromForwardModel(self, realization, iteration, fs):
EnKFMain.cNamespace().load_from_forward_model(self, iteration, realization, fs)
def submitSimulation(self , run_arg):
EnKFMain.cNamespace().submit_simulation( self , run_arg)
def getRunContextENSEMPLE_EXPERIMENT(self , fs , iactive , init_mode = EnkfInitModeEnum.INIT_CONDITIONAL , iteration = 0):
return EnKFMain.cNamespace().alloc_run_context_ENSEMBLE_EXPERIMENT( self , fs , iactive , init_mode , iteration )
##################################################################
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerType("enkf_main", EnKFMain)
cwrapper.registerType("enkf_main_ref", EnKFMain.createCReference)
EnKFMain.cNamespace().bootstrap = cwrapper.prototype("c_void_p enkf_main_bootstrap(char*, bool, bool)")
EnKFMain.cNamespace().free = cwrapper.prototype("void enkf_main_free(enkf_main)")
EnKFMain.cNamespace().get_ensemble_size = cwrapper.prototype("int enkf_main_get_ensemble_size( enkf_main )")
EnKFMain.cNamespace().get_ens_config = cwrapper.prototype("ens_config_ref enkf_main_get_ensemble_config( enkf_main )")
EnKFMain.cNamespace().get_model_config = cwrapper.prototype("model_config_ref enkf_main_get_model_config( enkf_main )")
EnKFMain.cNamespace().get_local_config = cwrapper.prototype("local_config_ref enkf_main_get_local_config( enkf_main )")
EnKFMain.cNamespace().get_analysis_config = cwrapper.prototype("analysis_config_ref enkf_main_get_analysis_config( enkf_main)")
EnKFMain.cNamespace().get_site_config = cwrapper.prototype("site_config_ref enkf_main_get_site_config( enkf_main)")
EnKFMain.cNamespace().get_ecl_config = cwrapper.prototype("ecl_config_ref enkf_main_get_ecl_config( enkf_main)")
EnKFMain.cNamespace().get_plot_config = cwrapper.prototype("plot_config_ref enkf_main_get_plot_config( enkf_main)")
EnKFMain.cNamespace().set_eclbase = cwrapper.prototype("ui_return_obj enkf_main_set_eclbase( enkf_main, char*)")
EnKFMain.cNamespace().set_datafile = cwrapper.prototype("void enkf_main_set_data_file( enkf_main, char*)")
EnKFMain.cNamespace().get_schedule_prediction_file = cwrapper.prototype("char* enkf_main_get_schedule_prediction_file( enkf_main )")
EnKFMain.cNamespace().set_schedule_prediction_file = cwrapper.prototype("void enkf_main_set_schedule_prediction_file( enkf_main , char*)")
EnKFMain.cNamespace().get_data_kw = cwrapper.prototype("subst_list_ref enkf_main_get_data_kw(enkf_main)")
EnKFMain.cNamespace().clear_data_kw = cwrapper.prototype("void enkf_main_clear_data_kw(enkf_main)")
EnKFMain.cNamespace().add_data_kw = cwrapper.prototype("void enkf_main_add_data_kw(enkf_main, char*, char*)")
EnKFMain.cNamespace().resize_ensemble = cwrapper.prototype("void enkf_main_resize_ensemble(enkf_main, int)")
EnKFMain.cNamespace().del_node = cwrapper.prototype("void enkf_main_del_node(enkf_main, char*)")
EnKFMain.cNamespace().get_obs = cwrapper.prototype("enkf_obs_ref enkf_main_get_obs(enkf_main)")
EnKFMain.cNamespace().load_obs = cwrapper.prototype("void enkf_main_load_obs(enkf_main, char*)")
EnKFMain.cNamespace().reload_obs = cwrapper.prototype("void enkf_main_reload_obs(enkf_main)")
EnKFMain.cNamespace().get_pre_clear_runpath = cwrapper.prototype("bool enkf_main_get_pre_clear_runpath(enkf_main)")
EnKFMain.cNamespace().set_pre_clear_runpath = cwrapper.prototype("void enkf_main_set_pre_clear_runpath(enkf_main, bool)")
EnKFMain.cNamespace().iget_keep_runpath = cwrapper.prototype("int enkf_main_iget_keep_runpath(enkf_main, int)")
EnKFMain.cNamespace().iset_keep_runpath = cwrapper.prototype("void enkf_main_iset_keep_runpath(enkf_main, int, int_vector)")
EnKFMain.cNamespace().get_templates = cwrapper.prototype("ert_templates_ref enkf_main_get_templates(enkf_main)")
EnKFMain.cNamespace().get_site_config_file = cwrapper.prototype("char* enkf_main_get_site_config_file(enkf_main)")
EnKFMain.cNamespace().get_history_length = cwrapper.prototype("int enkf_main_get_history_length(enkf_main)")
EnKFMain.cNamespace().get_observations = cwrapper.prototype("void enkf_main_get_observations(enkf_main, char*, int, long*, double*, double*)")
EnKFMain.cNamespace().get_observation_count = cwrapper.prototype("int enkf_main_get_observation_count(enkf_main, char*)")
EnKFMain.cNamespace().iget_state = cwrapper.prototype("enkf_state_ref enkf_main_iget_state(enkf_main, int)")
EnKFMain.cNamespace().get_workflow_list = cwrapper.prototype("ert_workflow_list_ref enkf_main_get_workflow_list(enkf_main)")
EnKFMain.cNamespace().get_qc_module = cwrapper.prototype("qc_module_ref enkf_main_get_qc_module(enkf_main)")
EnKFMain.cNamespace().fprintf_config = cwrapper.prototype("void enkf_main_fprintf_config(enkf_main)")
EnKFMain.cNamespace().create_new_config = cwrapper.prototype("void enkf_main_create_new_config(char* , char*, char* , char* , int)")
EnKFMain.cNamespace().get_user_config_file = cwrapper.prototype("char* enkf_main_get_user_config_file(enkf_main)")
EnKFMain.cNamespace().get_mount_point = cwrapper.prototype("char* enkf_main_get_mount_root( enkf_main )")
EnKFMain.cNamespace().export_field = cwrapper.prototype("bool enkf_main_export_field(enkf_main, char*, char*, bool_vector, enkf_field_file_format_enum, int, enkf_state_type_enum)")
EnKFMain.cNamespace().export_field_with_fs = cwrapper.prototype("bool enkf_main_export_field_with_fs(enkf_main, char*, char*, bool_vector, enkf_field_file_format_enum, int, enkf_state_type_enum, enkf_fs_manager)")
EnKFMain.cNamespace().load_from_forward_model = cwrapper.prototype("void enkf_main_load_from_forward_model_from_gui(enkf_main, int, bool_vector, enkf_fs)")
EnKFMain.cNamespace().submit_simulation = cwrapper.prototype("void enkf_main_isubmit_job(enkf_main , run_arg)")
EnKFMain.cNamespace().alloc_run_context_ENSEMBLE_EXPERIMENT= cwrapper.prototype("ert_run_context_obj enkf_main_alloc_ert_run_context_ENSEMBLE_EXPERIMENT( enkf_main , enkf_fs , bool_vector , enkf_init_mode_enum , int)")
| iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert/enkf/enkf_main.py | Python | gpl-3.0 | 13,314 |
/*
This file is part of MGEAN library.
MGEAN 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.
MGEAN 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 General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MGEAN library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010-2011 Pavel Procházka
*/
#ifndef COLLISION_H
#define COLLISION_H
int intersect_p_rect (SDL_Rect * rct1, SDL_Rect * rct2);
#endif
| mafiosso/mgean | src/collision.h | C | gpl-3.0 | 817 |
/*
Copyright (c) 2015 Colum Paget <colums.projects@googlemail.com>
* SPDX-License-Identifier: GPL-3.0
*/
#ifndef USBAUTH_COMMON_H
#define USBAUTH_COMMON_H
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <sys/types.h>
#define VERSION "1.9"
#define FALSE 0
#define TRUE 1
#define MATCH_NO 0
#define MATCH_WRONG_USER 1
#define MATCH_YES 3
#define MATCH_VALID 4
#define FLAG_SYSLOG 1
#define FLAG_DENY 4
#define FLAG_DENYALL 8
#define FLAG_LOGPASS 16
#define FLAG_FAILS 32
#define FLAG_NOTUSER 64
#define FLAG_NOTHOST 128
#define FLAG_IGNORE_BLANK 256
#define FLAG_LOGFOUND 512
typedef struct
{
int Flags;
char *Prompt;
char *CredsFiles;
char *SortedFiles;
char *User;
char *Host;
char *PamUser;
char *PamHost;
char *PamTTY;
char *Script;
} TSettings;
typedef struct
{
int Flags;
char *User;
char *Pass;
char *Salt;
} THoneyCred;
#endif
| ColumPaget/pam_honeycreds | common.h | C | gpl-3.0 | 904 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration | Version: 3.2
\\ / A nd | Web: http://www.foam-extend.org
\\/ M anipulation | For copyright notice see file Copyright
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend 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.
foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>.
Description
BlockCoeff norms static data
\*---------------------------------------------------------------------------*/
#include "blockCoeffNorms.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
defineNamedTemplateTypeNameAndDebug(blockScalarCoeffNorm, 0);
defineNamedTemplateTypeNameAndDebug(blockVectorCoeffNorm, 0);
defineNamedTemplateTypeNameAndDebug(blockTensorCoeffNorm, 0);
// Define the constructor function hash tables for symmetric solvers
defineTemplateRunTimeSelectionTable
(
blockScalarCoeffNorm,
dictionary
);
defineTemplateRunTimeSelectionTable
(
blockVectorCoeffNorm,
dictionary
);
defineTemplateRunTimeSelectionTable
(
blockTensorCoeffNorm,
dictionary
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2 | src/foam/primitives/BlockCoeff/BlockCoeffNorm/BlockCoeffNorm/blockCoeffNorms.C | C++ | gpl-3.0 | 2,164 |
using System;
namespace Eleflex
{
/// <summary>
/// Represents an object for a SecurityUserRole.
/// </summary>
public partial class SecurityUserRole : ISecurityUserRole
{
/// <summary>
/// The SecurityUserRoleKey.
/// </summary>
public virtual long SecurityUserRoleKey { get; set; }
/// <summary>
/// The SecurityUserKey.
/// </summary>
public virtual System.Guid SecurityUserKey { get; set; }
/// <summary>
/// The SecurityRoleKey.
/// </summary>
public virtual System.Guid SecurityRoleKey { get; set; }
/// <summary>
/// The Active.
/// </summary>
public virtual bool Active { get; set; }
/// <summary>
/// The EffectiveStartDate.
/// </summary>
public virtual Nullable<System.DateTimeOffset> EffectiveStartDate { get; set; }
/// <summary>
/// The EffectiveEndDate.
/// </summary>
public virtual Nullable<System.DateTimeOffset> EffectiveEndDate { get; set; }
/// <summary>
/// The Comment.
/// </summary>
public virtual string Comment { get; set; }
/// <summary>
/// The ExtraData.
/// </summary>
public virtual string ExtraData { get; set; }
}
}
| ProductionReady/Eleflex | V3.0/Modules/Core/Eleflex/Security/SecurityUserRole.cs | C# | gpl-3.0 | 1,130 |
/******************************************************************************
*
* Grim - Game engine library
* Copyright (C) 2009 Daniel Levin (dendy.ua@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.0 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.
*
* The GNU General Public License is contained in the file COPYING in the
* packaging of this file. Please review information in this file to ensure
* the GNU General Public License version 3.0 requirements will be met.
*
* Copy of GNU General Public License available at:
* http://www.gnu.org/copyleft/gpl.html
*
*****************************************************************************/
#include "audiolistener.h"
#include "audio_p.h"
#include "audiocontext.h"
namespace Grim {
AudioListenerPrivate::AudioListenerPrivate( AudioContext * audioContext ) :
audioContext_( audioContext ),
gain_( 1.0f ),
position_( 0.0f, 0.0f, 0.0f ),
velocity_( 0.0f, 0.0f, 0.0f ),
orientationAt_( 0.0f, 0.0f, -1.0f ),
orientationUp_( 0.0f, 1.0f, 0.0f )
{
}
AudioListenerPrivate::~AudioListenerPrivate()
{
Q_ASSERT_X( audioListener_ != audioContext_->d_->defaultAudioListener_,
"Grim::AudioListenerPrivate::~AudioListenerPrivate()",
"Destroying default listener is prohibited" );
// if this listener was current then set default listener as current
if ( audioListener_ == audioContext_->d_->currentAudioListener_ && audioContext_->d_->defaultAudioListener_ )
{
audioContext_->d_->currentAudioListener_ = audioContext_->d_->defaultAudioListener_;
audioContext_->d_->currentAudioListener_->d_->_applyAll();
}
if ( audioListener_ != audioContext_->d_->currentDestructingAudioListener_ )
audioContext_->d_->audioListeners_.removeOne( audioListener_ );
}
inline void AudioListenerPrivate::_applyGain()
{
alListenerf( AL_GAIN, gain_ );
}
inline void AudioListenerPrivate::_applyPosition()
{
AudioOpenALVector vector( position_ );
alListenerfv( AL_POSITION, vector.data );
}
inline void AudioListenerPrivate::_applyVelocity()
{
AudioOpenALVector vector( velocity_ );
alListenerfv( AL_VELOCITY, vector.data );
}
inline void AudioListenerPrivate::_applyOrientation()
{
AudioOpenALVector vector( orientationAt_, orientationUp_ );
alListenerfv( AL_ORIENTATION, vector.data );
}
inline void AudioListenerPrivate::_applyAll()
{
_applyGain();
_applyPosition();
_applyVelocity();
_applyOrientation();
}
bool AudioListenerPrivate::isCurrent() const
{
return audioContext_->d_->currentAudioListener_ == audioListener_;
}
void AudioListenerPrivate::setCurrent()
{
if ( audioContext_->d_->currentAudioListener_ == audioListener_ )
return;
audioContext_->d_->currentAudioListener_ = audioListener_;
audioContext_->d_->currentAudioListener_->d_->_applyAll();
}
void AudioListenerPrivate::setGain( float gain )
{
if ( gain_ == gain )
return;
gain_ = gain;
if ( isCurrent() )
{
AudioContextLocker contextLocker = audioContext_->d_->lock();
_applyGain();
}
}
void AudioListenerPrivate::setPosition( const AudioVector & position )
{
if ( position_ == position )
return;
position_ = position;
if ( isCurrent() )
{
AudioContextLocker contextLocker = audioContext_->d_->lock();
_applyPosition();
}
}
void AudioListenerPrivate::setVelocity( const AudioVector & velocity )
{
if ( velocity_ == velocity )
return;
velocity_ = velocity;
if ( isCurrent() )
{
AudioContextLocker contextLocker = audioContext_->d_->lock();
_applyVelocity();
}
}
void AudioListenerPrivate::setOrientation( const AudioVector & at, const AudioVector & up )
{
if ( orientationAt_ == at && orientationUp_ == up )
return;
orientationAt_ = at;
orientationUp_ = up;
if ( isCurrent() )
{
AudioContextLocker contextLocker = audioContext_->d_->lock();
_applyOrientation();
}
}
/**
* \class AudioListener
*
* \ingroup audio_module
*
* \brief The AudioListener class represents listener of audio sources.
*
* \reentrant
*
* Normally there is a single current audio listener per audio context.
* By audio context construction default one will be created for you automatically.
*
* You can create as many additional custom listeners as you want with AudioContext::createListener() and
* switch between them while context is running.
*
* \sa AudioContext::currentListener()
*/
/** \internal
*/
AudioListener::AudioListener( AudioListenerPrivate * d ) :
d_( d )
{
d_->audioListener_ = this;
}
/**
* Destroys custom audio listener instance.
* If this listener was current then a default one with be set as current.
* Destroying default audio listener is prohibited.
* If your own custom listener instances was not destroyed on audio context destruction -
* it will destroy them automatically.
*/
AudioListener::~AudioListener()
{
delete d_;
}
/**
* Returns whether this listener is set as current for audio context.
* All operations on non current listeners are valid and will be applied next time listener
* will be set as current.
*
* \sa setCurrent(), AudioContext::currentListener()
*/
bool AudioListener::isCurrent() const
{
return d_->isCurrent();
}
/**
* Set this listener as current for audio context.
*
* \sa isCurrent()
*/
void AudioListener::setCurrent()
{
d_->setCurrent();
}
/**
* Returns audio context instance this listener belongs to.
*
* \sa AudioContext::createListener()
*/
AudioContext * AudioListener::context() const
{
return d_->audioContext_;
}
/**
* Returns gain of this listener in range \c [0..1].
* You can think about gain as about master volume, where \c 0 is completely muted, while \c 1 is the maximum volume.
* By default gain equals to \a 1.
*
* \sa setGain()
*/
float AudioListener::gain() const
{
return d_->gain();
}
/**
* Set the gain of this listener to be the given \a gain.
*
* \sa gain()
*/
void AudioListener::setGain( float gain )
{
d_->setGain( gain );
}
/**
* Returns position of this listener in 3D space.
* This position will be calculated as relative to the audio sources.
* By default listener is at origin of 3D space (0,0,0).
*
* \sa setPosition(), AudioSource::position(), AudioSource::isRelativeToListener()
*/
AudioVector AudioListener::position() const
{
return d_->position();
}
/**
* Set position in 3D space of this listener to be the given \a position.
*
* \sa position(), AudioSource::setPosition(), AudioSource::isRelativeToListener()
*/
void AudioListener::setPosition( const AudioVector & position )
{
d_->setPosition( position );
}
/**
* Returns velocity vector of this listener.
* Together with audio sources velocities and audio context properties it implies on Doppler effect.
* By default listener is not moving and returns zero vector.
*
* \openal
*
* \sa setVelocity(), AudioSource::velocity(), AudioContext::dopplerFactor(), AudioContext::speedOfSound()
*/
AudioVector AudioListener::velocity() const
{
return d_->velocity();
}
/**
* Set the velocity vector of this listener to the given \a velocity.
*
* \openal
*
* \sa velocity(), AudioSource::setVelocity()
*/
void AudioListener::setVelocity( const AudioVector & velocity )
{
d_->setVelocity( velocity );
}
/**
* Returns orientation vector this listener is looking at.
* By default listener is looking forward to the -z coordinate (0,0,-1).
*
* \sa setOrientation(), orientationUp()
*/
AudioVector AudioListener::orientationAt() const
{
return d_->orientationAt();
}
/**
* Returns orientation vector this listener's "head" is looking up to.
* By default listener's "head" is up to the sky +y coordinate (0,1,0).
*
* \sa setOrientation(), orientationAt()
*/
AudioVector AudioListener::orientationUp() const
{
return d_->orientationUp();
}
/**
* Set this listener orientation where it look \a at and how it's "head" is \a up to.
*
* \sa orientationAt(), orientationUp()
*/
void AudioListener::setOrientation( const AudioVector & at, const AudioVector & up )
{
d_->setOrientation( at, up );
}
} // namespace Grim
| dendy/grim | src/audio/audiolistener.cpp | C++ | gpl-3.0 | 8,763 |
#include "scene.h"
#include "vector3.h"
namespace Solar {
Scene::Scene(Camera *SceneCamera) : mCam(SceneCamera) {}
void Scene::AddMesh (Mesh ToAdd) {
VecMeshes.push_back(ToAdd);
}
// TODO: Reduce parameters for less overhead?
inline void Scene::DrawPixel (Vector3 *Orientation, int x, int y, Color *Address) {
Dis SmallestDist = -1;
for(auto m : VecMeshes) {
for(int i=0; i < m.Size; i++) {
Dis temp = m.Atoms[i].DistanceToLineSqr(mCam->mPos, *Orientation);
if (temp < 3000) {
Dis Dist = (m.Atoms[i] - mCam->mPos).AbsSqr();
if (SmallestDist == -1 || Dist < SmallestDist) {
SmallestDist = Dist;
*Address = m.Colors[i];
}
}
}
}
if (SmallestDist == -1) {
Address->r = 0;
Address->g = 0;
Address->b = 0;
}
}
}
| ChriPiv/solar-engine | scene.cpp | C++ | gpl-3.0 | 907 |
/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
mpz.cpp
Abstract:
<abstract>
Author:
Leonardo de Moura (leonardo) 2010-06-17.
Revision History:
--*/
#include<sstream>
#include"mpz.h"
#include"buffer.h"
#include"trace.h"
#include"hash.h"
#include"bit_util.h"
#if defined(_MP_MSBIGNUM)
#define COMPILER COMPILER_VC
#ifndef NDEBUG
#define NDEBUG
#endif
#ifdef ARRAYSIZE
#undef ARRAYSIZE
#endif
#include "..\msbig_rational\msbignum.h"
#elif defined(_MP_INTERNAL)
#include"mpn.h"
#elif defined(_MP_GMP)
#include<gmp.h>
#else
#error No multi-precision library selected.
#endif
// Available GCD algorithms
// #define EUCLID_GCD
// #define BINARY_GCD
// #define LS_BINARY_GCD
// #define LEHMER_GCD
#if defined(_MP_GMP) || (defined(_MP_MSBIGNUM) && defined(_AMD64_))
// Use LEHMER only if not using GMP
// LEHMER assumes 32-bit digits, so it cannot be used with MSBIGNUM library + 64-bit binary
#define EUCLID_GCD
#else
#define LEHMER_GCD
#endif
template<typename T>
static T gcd_core(T u, T v) {
if (u == 0)
return v;
if (v == 0)
return u;
int k;
for (k = 0; ((u | v) & 1) == 0; ++k) {
u >>= 1;
v >>= 1;
}
while ((u & 1) == 0)
u >>= 1;
do {
while ((v & 1) == 0)
v >>= 1;
if (u < v) {
v -= u;
}
else {
T diff = u - v;
u = v;
v = diff;
}
v >>= 1;
} while (v != 0);
return u << k;
}
unsigned u_gcd(unsigned u, unsigned v) { return gcd_core(u, v); }
uint64 u64_gcd(uint64 u, uint64 v) { return gcd_core(u, v); }
template<bool SYNCH>
mpz_manager<SYNCH>::mpz_manager():
m_allocator("mpz_manager") {
if (SYNCH)
omp_init_nest_lock(&m_lock);
#ifndef _MP_GMP
if (sizeof(digit_t) == sizeof(uint64)) {
// 64-bit machine
m_init_cell_capacity = 4;
}
else {
m_init_cell_capacity = 6;
}
for (unsigned i = 0; i < 2; i++) {
m_tmp[i] = allocate(m_init_cell_capacity);
m_arg[i] = allocate(m_init_cell_capacity);
m_arg[i]->m_size = 1;
}
set(m_int_min, -static_cast<int64>(INT_MIN));
#else
// GMP
mpz_init(m_tmp);
mpz_init(m_tmp2);
mpz_init(m_two32);
mpz_set_ui(m_two32, UINT_MAX);
mpz_set_ui(m_tmp, 1);
mpz_add(m_two32, m_two32, m_tmp);
m_arg[0] = allocate();
m_arg[1] = allocate();
mpz_init(m_uint64_max);
unsigned max_l = static_cast<unsigned>(UINT64_MAX);
unsigned max_h = static_cast<unsigned>(UINT64_MAX >> 32);
mpz_set_ui(m_uint64_max, max_h);
mpz_mul(m_uint64_max, m_two32, m_uint64_max);
mpz_set_ui(m_tmp, max_l);
mpz_add(m_uint64_max, m_uint64_max, m_tmp);
mpz_init(m_int64_max);
max_l = static_cast<unsigned>(INT64_MAX % static_cast<int64>(UINT_MAX));
max_h = static_cast<unsigned>(INT64_MAX / static_cast<int64>(UINT_MAX));
mpz_set_ui(m_int64_max, max_h);
mpz_set_ui(m_tmp, UINT_MAX);
mpz_mul(m_int64_max, m_tmp, m_int64_max);
mpz_set_ui(m_tmp, max_l);
mpz_add(m_int64_max, m_tmp, m_int64_max);
#endif
mpz one(1);
set(m_two64, UINT64_MAX);
add(m_two64, one, m_two64);
}
template<bool SYNCH>
mpz_manager<SYNCH>::~mpz_manager() {
del(m_two64);
#ifndef _MP_GMP
del(m_int_min);
for (unsigned i = 0; i < 2; i++) {
deallocate(m_tmp[i]);
deallocate(m_arg[i]);
}
#else
mpz_clear(m_tmp);
mpz_clear(m_tmp2);
mpz_clear(m_two32);
deallocate(m_arg[0]);
deallocate(m_arg[1]);
mpz_clear(m_uint64_max);
mpz_clear(m_int64_max);
#endif
if (SYNCH)
omp_destroy_nest_lock(&m_lock);
}
template<bool SYNCH>
void mpz_manager<SYNCH>::set_big_i64(mpz & c, int64 v) {
#ifndef _MP_GMP
if (is_small(c)) {
c.m_ptr = allocate(m_init_cell_capacity);
}
SASSERT(capacity(c) >= m_init_cell_capacity);
uint64 _v;
if (v < 0) {
_v = -v;
c.m_val = -1;
}
else {
_v = v;
c.m_val = 1;
}
if (sizeof(digit_t) == sizeof(uint64)) {
// 64-bit machine
digits(c)[0] = static_cast<digit_t>(_v);
c.m_ptr->m_size = 1;
}
else {
// 32-bit machine
digits(c)[0] = static_cast<unsigned>(_v);
digits(c)[1] = static_cast<unsigned>(_v >> 32);
c.m_ptr->m_size = digits(c)[1] == 0 ? 1 : 2;
}
#else
if (is_small(c)) {
c.m_ptr = allocate();
}
uint64 _v;
bool sign;
if (v < 0) {
_v = -v;
sign = true;
}
else {
_v = v;
sign = false;
}
mpz_set_ui(*c.m_ptr, static_cast<unsigned>(_v));
mpz_set_ui(m_tmp, static_cast<unsigned>(_v >> 32));
mpz_mul(m_tmp, m_tmp, m_two32);
mpz_add(*c.m_ptr, *c.m_ptr, m_tmp);
if (sign)
mpz_neg(*c.m_ptr, *c.m_ptr);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::set_big_ui64(mpz & c, uint64 v) {
#ifndef _MP_GMP
if (is_small(c)) {
c.m_ptr = allocate(m_init_cell_capacity);
}
SASSERT(capacity(c) >= m_init_cell_capacity);
c.m_val = 1;
if (sizeof(digit_t) == sizeof(uint64)) {
// 64-bit machine
digits(c)[0] = static_cast<digit_t>(v);
c.m_ptr->m_size = 1;
}
else {
// 32-bit machine
digits(c)[0] = static_cast<unsigned>(v);
digits(c)[1] = static_cast<unsigned>(v >> 32);
c.m_ptr->m_size = digits(c)[1] == 0 ? 1 : 2;
}
#else
if (is_small(c)) {
c.m_ptr = allocate();
}
mpz_set_ui(*c.m_ptr, static_cast<unsigned>(v));
mpz_set_ui(m_tmp, static_cast<unsigned>(v >> 32));
mpz_mul(m_tmp, m_tmp, m_two32);
mpz_add(*c.m_ptr, *c.m_ptr, m_tmp);
#endif
}
#ifndef _MP_GMP
template<bool SYNCH>
template<int IDX>
void mpz_manager<SYNCH>::set(mpz & a, int sign, unsigned sz) {
#if 0
static unsigned max_sz = 0;
if (sz > max_sz) {
max_sz = sz;
verbose_stream() << "max_sz: " << max_sz << "\n";
}
#endif
unsigned i = sz;
for (; i > 0; --i) {
if (m_tmp[IDX]->m_digits[i-1] != 0)
break;
}
if (i == 0) {
// m_tmp[IDX] is zero
reset(a);
return;
}
if (i == 1 && m_tmp[IDX]->m_digits[0] <= INT_MAX) {
// m_tmp[IDX] fits is a fixnum
del(a);
a.m_val = sign < 0 ? -static_cast<int>(m_tmp[IDX]->m_digits[0]) : static_cast<int>(m_tmp[IDX]->m_digits[0]);
return;
}
a.m_val = sign;
std::swap(a.m_ptr, m_tmp[IDX]);
a.m_ptr->m_size = i;
if (!m_tmp[IDX]) // 'a' was a small number
m_tmp[IDX] = allocate(m_init_cell_capacity);
}
#endif
template<bool SYNCH>
void mpz_manager<SYNCH>::set(mpz & a, char const * val) {
reset(a);
mpz ten(10);
mpz tmp;
char const * str = val;
bool sign = false;
while (str[0] == ' ') ++str;
if (str[0] == '-')
sign = true;
while (str[0]) {
if ('0' <= str[0] && str[0] <= '9') {
SASSERT(str[0] - '0' <= 9);
mul(a, ten, tmp);
add(tmp, mk_z(str[0] - '0'), a);
}
++str;
}
del(tmp);
if (sign)
neg(a);
}
template<bool SYNCH>
void mpz_manager<SYNCH>::set(mpz & target, unsigned sz, digit_t const * digits) {
// remove zero digits
while (sz > 0 && digits[sz - 1] == 0)
sz--;
if (sz == 0)
reset(target);
else if (sz == 1)
set(target, digits[0]);
else {
#ifndef _MP_GMP
target.m_val = 1; // number is positive.
if (is_small(target)) {
unsigned c = sz < m_init_cell_capacity ? m_init_cell_capacity : sz;
target.m_ptr = allocate(c);
target.m_ptr->m_size = sz;
target.m_ptr->m_capacity = c;
memcpy(target.m_ptr->m_digits, digits, sizeof(digit_t) * sz);
}
else {
if (capacity(target) < sz) {
SASSERT(sz > m_init_cell_capacity);
deallocate(target.m_ptr);
target.m_ptr = allocate(sz);
target.m_ptr->m_size = sz;
target.m_ptr->m_capacity = sz;
memcpy(target.m_ptr->m_digits, digits, sizeof(digit_t) * sz);
}
else {
target.m_ptr->m_size = sz;
memcpy(target.m_ptr->m_digits, digits, sizeof(digit_t) * sz);
}
}
#else
mk_big(target);
// reset
mpz_set_ui(*target.m_ptr, digits[sz - 1]);
SASSERT(sz > 0);
unsigned i = sz - 1;
while (i > 0) {
--i;
mpz_mul_2exp(*target.m_ptr, *target.m_ptr, 32);
mpz_set_ui(m_tmp, digits[i]);
mpz_add(*target.m_ptr, *target.m_ptr, m_tmp);
}
#endif
}
}
#ifndef _MP_GMP
template<bool SYNCH>
template<bool SUB>
void mpz_manager<SYNCH>::big_add_sub(mpz const & a, mpz const & b, mpz & c) {
int sign_a;
int sign_b;
mpz_cell * cell_a;
mpz_cell * cell_b;
get_sign_cell<0>(a, sign_a, cell_a);
get_sign_cell<1>(b, sign_b, cell_b);
if (SUB)
sign_b = -sign_b;
size_t real_sz;
if (sign_a == sign_b) {
unsigned sz = max(cell_a->m_size, cell_b->m_size)+1;
ensure_tmp_capacity<0>(sz);
add_full(cell_a->m_digits,
cell_a->m_size,
cell_b->m_digits,
cell_b->m_size,
m_tmp[0]->m_digits,
sz,
&real_sz,
0);
SASSERT(real_sz <= sz);
set<0>(c, sign_a, static_cast<unsigned>(real_sz));
}
else {
digit_t borrow;
int r = compare_diff(cell_a->m_digits,
cell_a->m_size,
cell_b->m_digits,
cell_b->m_size);
if (r == 0) {
reset(c);
}
else if (r < 0) {
// a < b
unsigned sz = cell_b->m_size;
ensure_tmp_capacity<0>(sz);
sub_diff(cell_b->m_digits,
cell_b->m_size,
cell_a->m_digits,
cell_a->m_size,
m_tmp[0]->m_digits,
&borrow,
0);
SASSERT(borrow == 0);
set<0>(c, sign_b, sz);
}
else {
// a > b
unsigned sz = cell_a->m_size;
ensure_tmp_capacity<0>(sz);
sub_diff(cell_a->m_digits,
cell_a->m_size,
cell_b->m_digits,
cell_b->m_size,
m_tmp[0]->m_digits,
&borrow,
0);
SASSERT(borrow == 0);
set<0>(c, sign_a, sz);
}
}
}
#endif
template<bool SYNCH>
void mpz_manager<SYNCH>::big_add(mpz const & a, mpz const & b, mpz & c) {
#ifndef _MP_GMP
big_add_sub<false>(a, b, c);
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_add(*c.m_ptr, *arg0, *arg1);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::big_sub(mpz const & a, mpz const & b, mpz & c) {
#ifndef _MP_GMP
big_add_sub<true>(a, b, c);
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_sub(*c.m_ptr, *arg0, *arg1);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::big_mul(mpz const & a, mpz const & b, mpz & c) {
#ifndef _MP_GMP
int sign_a;
int sign_b;
mpz_cell * cell_a;
mpz_cell * cell_b;
get_sign_cell<0>(a, sign_a, cell_a);
get_sign_cell<1>(b, sign_b, cell_b);
unsigned sz = cell_a->m_size + cell_b->m_size;
ensure_tmp_capacity<0>(sz);
multiply(cell_a->m_digits,
cell_a->m_size,
cell_b->m_digits,
cell_b->m_size,
m_tmp[0]->m_digits,
0);
set<0>(c, sign_a == sign_b ? 1 : -1, sz);
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_mul(*c.m_ptr, *arg0, *arg1);
#endif
}
#ifndef _MP_GMP
template<bool SYNCH>
template<qr_mode MODE>
void mpz_manager<SYNCH>::quot_rem_core(mpz const & a, mpz const & b, mpz & q, mpz & r) {
/*
+26 / +7 = +3, remainder is +5
-26 / +7 = -3, remainder is -5
+26 / -7 = -3, remainder is +5
-26 / -7 = +3, remainder is -5
*/
int sign_a;
int sign_b;
mpz_cell * cell_a;
mpz_cell * cell_b;
get_sign_cell<0>(a, sign_a, cell_a);
get_sign_cell<1>(b, sign_b, cell_b);
if (cell_b->m_size > cell_a->m_size) {
if (MODE == REM_ONLY || MODE == QUOT_AND_REM)
set(r, a);
if (MODE == QUOT_ONLY || MODE == QUOT_AND_REM)
reset(q);
return;
}
unsigned q_sz = cell_a->m_size - cell_b->m_size + 1;
unsigned r_sz = cell_b->m_size;
ensure_tmp_capacity<0>(q_sz);
ensure_tmp_capacity<1>(r_sz);
divide(cell_a->m_digits,
cell_a->m_size,
cell_b->m_digits,
cell_b->m_size,
reciprocal_1_NULL,
m_tmp[0]->m_digits,
m_tmp[1]->m_digits,
0);
if (MODE == QUOT_ONLY || MODE == QUOT_AND_REM)
set<0>(q, sign_a == sign_b ? 1 : -1, q_sz);
if (MODE == REM_ONLY || MODE == QUOT_AND_REM)
set<1>(r, sign_a, r_sz);
}
#endif
template<bool SYNCH>
void mpz_manager<SYNCH>::big_div_rem(mpz const & a, mpz const & b, mpz & q, mpz & r) {
#ifndef _MP_GMP
quot_rem_core<QUOT_AND_REM>(a, b, q, r);
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(q);
mk_big(r);
mpz_tdiv_qr(*q.m_ptr, *r.m_ptr, *arg0, *arg1);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::big_div(mpz const & a, mpz const & b, mpz & c) {
#ifndef _MP_GMP
mpz dummy;
quot_rem_core<QUOT_ONLY>(a, b, c, dummy);
SASSERT(is_zero(dummy));
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_tdiv_q(*c.m_ptr, *arg0, *arg1);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::big_rem(mpz const & a, mpz const & b, mpz & c) {
#ifndef _MP_GMP
mpz dummy;
quot_rem_core<REM_ONLY>(a, b, dummy, c);
SASSERT(is_zero(dummy));
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_tdiv_r(*c.m_ptr, *arg0, *arg1);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::gcd(mpz const & a, mpz const & b, mpz & c) {
if (is_small(a) && is_small(b)) {
int _a = a.m_val;
int _b = b.m_val;
if (_a < 0) _a = -_a;
if (_b < 0) _b = -_b;
unsigned r = u_gcd(_a, _b);
// Remark: r is (INT_MAX + 1)
// If a == b == INT_MIN
set(c, r);
}
else {
#ifdef _MP_GMP
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_gcd(*c.m_ptr, *arg0, *arg1);
return;
#endif
if (is_zero(a)) {
set(c, b);
abs(c);
return;
}
if (is_zero(b)) {
set(c, a);
abs(c);
return;
}
#ifdef BINARY_GCD
// Binary GCD for big numbers
// - It doesn't use division
// - The initial experiments, don't show any performance improvement
// - It only works with _MP_INTERNAL and _MP_MSBIGNUM
mpz u, v, diff;
set(u, a);
set(v, b);
abs(u);
abs(v);
unsigned k_u = power_of_two_multiple(u);
unsigned k_v = power_of_two_multiple(v);
unsigned k = k_u < k_v ? k_u : k_v;
machine_div2k(u, k_u);
while (true) {
machine_div2k(v, k_v);
if (lt(u, v)) {
sub(v, u, v);
}
else {
sub(u, v, diff);
swap(u, v);
swap(v, diff);
}
if (is_zero(v) || is_one(v))
break;
// reset least significant bit
if (is_small(v))
v.m_val &= ~1;
else
v.m_ptr->m_digits[0] &= ~static_cast<digit_t>(1);
k_v = power_of_two_multiple(v);
}
mul2k(u, k, c);
del(u); del(v); del(diff);
#endif // BINARY_GCD
#ifdef EUCLID_GCD
mpz tmp1;
mpz tmp2;
mpz aux;
set(tmp1, a);
set(tmp2, b);
abs(tmp1);
abs(tmp2);
if (lt(tmp1, tmp2))
swap(tmp1, tmp2);
if (is_zero(tmp2)) {
swap(c, tmp1);
}
else {
while (true) {
if (is_uint64(tmp1) && is_uint64(tmp2)) {
set(c, u64_gcd(get_uint64(tmp1), get_uint64(tmp2)));
break;
}
rem(tmp1, tmp2, aux);
if (is_zero(aux)) {
swap(c, tmp2);
break;
}
swap(tmp1, tmp2);
swap(tmp2, aux);
}
}
del(tmp1); del(tmp2); del(aux);
#endif // EUCLID_GCD
#ifdef LS_BINARY_GCD
mpz u, v, t, u1, u2;
set(u, a);
set(v, b);
abs(u);
abs(v);
if (lt(u, v))
swap(u, v);
while (!is_zero(v)) {
// Basic idea:
// compute t = 2^e*v such that t <= u < 2t
// u := min{u - t, 2t - u}
//
// The assignment u := min{u - t, 2t - u}
// can be replaced with u := u - t
//
// Since u and v are positive, we have:
// 2^{log2(u)} <= u < 2^{(log2(u) + 1)}
// 2^{log2(v)} <= v < 2^{(log2(v) + 1)}
// -->
// 2^{log2(v)}*2^{log2(u)-log2(v)} <= v*2^{log2(u)-log2(v)} < 2^{log2(v) + 1}*2^{log2(u)-log2(v)}
// -->
// 2^{log2(u)} <= v*2^{log2(u)-log2(v)} < 2^{log2(u) + 1}
//
// Now, let t be v*2^{log2(u)-log2(v)}
// If t <= u, then we found t
// Otherwise t = t div 2
unsigned k_u = log2(u);
unsigned k_v = log2(v);
SASSERT(k_v <= k_u);
unsigned e = k_u - k_v;
mul2k(v, e, t);
sub(u, t, u1);
if (is_neg(u1)) {
// t is too big
machine_div2k(t, 1);
// Now, u1 contains u - 2t
neg(u1);
// Now, u1 contains 2t - u
sub(u, t, u2); // u2 := u - t
}
else {
// u1 contains u - t
mul2k(t, 1);
sub(t, u, u2);
// u2 contains 2t - u
}
SASSERT(is_nonneg(u1));
SASSERT(is_nonneg(u2));
if (lt(u1, u2))
swap(u, u1);
else
swap(u, u2);
if (lt(u, v))
swap(u,v);
}
swap(u, c);
del(u); del(v); del(t); del(u1); del(u2);
#endif // LS_BINARY_GCD
#ifdef LEHMER_GCD
// For now, it only works if sizeof(digit_t) == sizeof(unsigned)
COMPILE_TIME_ASSERT(sizeof(digit_t) == sizeof(unsigned));
int64 a_hat, b_hat, A, B, C, D, T, q, a_sz, b_sz;
mpz a1, b1, t, r, tmp;
set(a1, a);
set(b1, b);
abs(a1);
abs(b1);
if (lt(a1, b1))
swap(a1, b1);
while (true) {
SASSERT(ge(a1, b1));
if (is_small(b1)) {
if (is_small(a1)) {
unsigned r = u_gcd(a1.m_val, b1.m_val);
set(c, r);
break;
}
else {
while (!is_zero(b1)) {
SASSERT(ge(a1, b1));
rem(a1, b1, tmp);
swap(a1, b1);
swap(b1, tmp);
}
swap(c, a1);
break;
}
}
SASSERT(!is_small(a1));
SASSERT(!is_small(b1));
a_sz = a1.m_ptr->m_size;
b_sz = b1.m_ptr->m_size;
SASSERT(b_sz <= a_sz);
a_hat = a1.m_ptr->m_digits[a_sz - 1];
b_hat = (b_sz == a_sz) ? b1.m_ptr->m_digits[b_sz - 1] : 0;
A = 1;
B = 0;
C = 0;
D = 1;
while (true) {
// Loop invariants
SASSERT(a_hat + A <= static_cast<int64>(UINT_MAX) + 1);
SASSERT(a_hat + B < static_cast<int64>(UINT_MAX) + 1);
SASSERT(b_hat + C < static_cast<int64>(UINT_MAX) + 1);
SASSERT(b_hat + D <= static_cast<int64>(UINT_MAX) + 1);
// overflows can't happen since I'm using int64
if (b_hat + C == 0 || b_hat + D == 0)
break;
q = (a_hat + A)/(b_hat + C);
if (q != (a_hat + B)/(b_hat + D))
break;
T = A - q*C;
A = C;
C = T;
T = B - q*D;
B = D;
D = T;
T = a_hat - q*b_hat;
a_hat = b_hat;
b_hat = T;
}
SASSERT(ge(a1, b1));
if (B == 0) {
rem(a1, b1, t);
swap(a1, b1);
swap(b1, t);
SASSERT(ge(a1, b1));
}
else {
// t <- A*a1
set(tmp, A);
mul(a1, tmp, t);
// t <- t + B*b1
set(tmp, B);
addmul(t, tmp, b1, t);
// r <- C*a1
set(tmp, C);
mul(a1, tmp, r);
// r <- r + D*b1
set(tmp, D);
addmul(r, tmp, b1, r);
// a <- t
swap(a1, t);
// b <- r
swap(b1, r);
SASSERT(ge(a1, b1));
}
}
del(a1); del(b1); del(r); del(t); del(tmp);
#endif // LEHMER_GCD
}
}
template<bool SYNCH>
unsigned mpz_manager<SYNCH>::size_info(mpz const & a) {
if (is_small(a))
return 1;
#ifndef _MP_GMP
return a.m_ptr->m_size + 1;
#else
return mpz_size(*a.m_ptr);
#endif
}
template<bool SYNCH>
struct mpz_manager<SYNCH>::sz_lt {
mpz_manager<SYNCH> & m;
mpz const * m_as;
sz_lt(mpz_manager<SYNCH> & _m, mpz const * as):m(_m), m_as(as) {}
bool operator()(unsigned p1, unsigned p2) {
return m.size_info(m_as[p1]) < m.size_info(m_as[p2]);
}
};
template<bool SYNCH>
void mpz_manager<SYNCH>::gcd(unsigned sz, mpz const * as, mpz & g) {
#if 0
// Optimization: sort numbers by size. Motivation: compute the gcd of the small ones first.
// The optimization did not really help.
switch (sz) {
case 0:
reset(g);
return;
case 1:
set(g, as[0]);
abs(g);
return;
case 2:
gcd(as[0], as[1], g);
return;
default:
break;
}
unsigned i;
for (i = 0; i < sz; i++) {
if (!is_small(as[i]))
break;
}
if (i != sz) {
// array has big numbers
sbuffer<unsigned, 1024> p;
for (i = 0; i < sz; i++)
p.push_back(i);
sz_lt lt(*this, as);
std::sort(p.begin(), p.end(), lt);
TRACE("mpz_gcd", for (unsigned i = 0; i < sz; i++) tout << p[i] << ":" << size_info(as[p[i]]) << " "; tout << "\n";);
gcd(as[p[0]], as[p[1]], g);
for (i = 2; i < sz; i++) {
if (is_one(g))
return;
gcd(g, as[p[i]], g);
}
return;
}
else {
gcd(as[0], as[1], g);
for (unsigned i = 2; i < sz; i++) {
if (is_one(g))
return;
gcd(g, as[i], g);
}
}
#else
// Vanilla implementation
switch (sz) {
case 0:
reset(g);
return;
case 1:
set(g, as[0]);
abs(g);
return;
default:
break;
}
gcd(as[0], as[1], g);
for (unsigned i = 2; i < sz; i++) {
if (is_one(g))
return;
gcd(g, as[i], g);
}
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::gcd(mpz const & r1, mpz const & r2, mpz & a, mpz & b, mpz & r) {
mpz tmp1, tmp2;
mpz aux, quot;
set(tmp1, r1);
set(tmp2, r2);
set(a, 1);
set(b, 0);
mpz nexta, nextb;
set(nexta, 0);
set(nextb, 1);
abs(tmp1);
abs(tmp2);
if (lt(tmp1, tmp2)) {
swap(tmp1, tmp2);
swap(nexta, nextb);
swap(a, b);
}
// tmp1 >= tmp2 >= 0
// quot_rem in one function would be faster.
while (is_pos(tmp2)) {
SASSERT(ge(tmp1, tmp2));
// aux = tmp2
set(aux, tmp2);
// quot = div(tmp1, tmp2);
machine_div(tmp1, tmp2, quot);
// tmp2 = tmp1 % tmp2
rem(tmp1, tmp2, tmp2);
// tmp1 = aux
set(tmp1, aux);
// aux = nexta
set(aux, nexta);
// nexta = a - (quot*nexta)
mul(quot, nexta, nexta);
sub(a, nexta, nexta);
// a = axu
set(a, aux);
// aux = nextb
set(aux, nextb);
// nextb = b - (quot*nextb)
mul(nextb, quot, nextb);
sub(b, nextb, nextb);
// b = aux
set(b, aux);
}
if (is_neg(r1))
neg(a);
if (is_neg(r2))
neg(b);
// SASSERT((a*r1) + (b*r2) == tmp1);
#ifdef Z3DEBUG
mul(a, r1, nexta);
mul(b, r2, nextb);
add(nexta, nextb, nexta);
SASSERT(eq(nexta, tmp1));
#endif
set(r, tmp1);
del(tmp1);
del(tmp2);
del(aux);
del(quot);
del(nexta);
del(nextb);
}
template<bool SYNCH>
void mpz_manager<SYNCH>::lcm(mpz const & a, mpz const & b, mpz & c) {
if (is_one(b)) {
set(c, a);
TRACE("lcm_bug", tout << "1. lcm(" << to_string(a) << ", " << to_string(b) << ") = " << to_string(c) << "\n";);
}
else if (is_one(a) || eq(a, b)) {
set(c, b);
TRACE("lcm_bug", tout << "2. lcm(" << to_string(a) << ", " << to_string(b) << ") = " << to_string(c) << "\n";);
}
else {
mpz r;
gcd(a, b, r);
TRACE("lcm_bug", tout << "gcd(" << to_string(a) << ", " << to_string(b) << ") = " << to_string(r) << "\n";);
if (eq(r, a)) {
set(c, b);
TRACE("lcm_bug", tout << "3. lcm(" << to_string(a) << ", " << to_string(b) << ") = " << to_string(c) << "\n";);
}
else if (eq(r, b)) {
set(c, a);
TRACE("lcm_bug", tout << "4. lcm(" << to_string(a) << ", " << to_string(b) << ") = " << to_string(c) << "\n";);
}
else {
// c contains gcd(a, b)
// so c divides a, and machine_div(a, c) is equal to div(a, c)
machine_div(a, r, r);
mul(r, b, c);
TRACE("lcm_bug", tout << "5. lcm(" << to_string(a) << ", " << to_string(b) << ") = " << to_string(c) << "\n";);
}
del(r);
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::bitwise_or(mpz const & a, mpz const & b, mpz & c) {
SASSERT(is_nonneg(a));
SASSERT(is_nonneg(b));
TRACE("mpz", tout << "is_small(a): " << is_small(a) << ", is_small(b): " << is_small(b) << "\n";);
if (is_small(a) && is_small(b)) {
del(c);
c.m_val = a.m_val | b.m_val;
}
else {
#ifndef _MP_GMP
mpz a1, b1, a2, b2, m, tmp;
set(a1, a);
set(b1, b);
set(m, 1);
reset(c);
while (!is_zero(a1) && !is_zero(b1)) {
TRACE("mpz", tout << "a1: " << to_string(a1) << ", b1: " << to_string(b1) << "\n";);
mod(a1, m_two64, a2);
mod(b1, m_two64, b2);
TRACE("mpz", tout << "a2: " << to_string(a2) << ", b2: " << to_string(b2) << "\n";);
uint64 v = get_uint64(a2) | get_uint64(b2);
TRACE("mpz", tout << "uint(a2): " << get_uint64(a2) << ", uint(b2): " << get_uint64(b2) << "\n";);
set(tmp, v);
mul(tmp, m, tmp);
add(c, tmp, c); // c += m * v
mul(m, m_two64, m);
div(a1, m_two64, a1);
div(b1, m_two64, b1);
}
if (!is_zero(a1)) {
mul(a1, m, a1);
add(c, a1, c);
}
if (!is_zero(b1)) {
mul(b1, m, b1);
add(c, b1, c);
}
del(a1); del(b1); del(a2); del(b2); del(m); del(tmp);
#else
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_ior(*c.m_ptr, *arg0, *arg1);
#endif
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::bitwise_and(mpz const & a, mpz const & b, mpz & c) {
SASSERT(is_nonneg(a));
SASSERT(is_nonneg(b));
if (is_small(a) && is_small(b)) {
del(c);
c.m_val = a.m_val & b.m_val;
}
else {
#ifndef _MP_GMP
mpz a1, b1, a2, b2, m, tmp;
set(a1, a);
set(b1, b);
set(m, 1);
reset(c);
while (!is_zero(a1) && !is_zero(b1)) {
mod(a1, m_two64, a2);
mod(b1, m_two64, b2);
uint64 v = get_uint64(a2) & get_uint64(b2);
set(tmp, v);
mul(tmp, m, tmp);
add(c, tmp, c); // c += m * v
mul(m, m_two64, m);
div(a1, m_two64, a1);
div(b1, m_two64, b1);
}
del(a1); del(b1); del(a2); del(b2); del(m); del(tmp);
#else
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_and(*c.m_ptr, *arg0, *arg1);
#endif
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::bitwise_xor(mpz const & a, mpz const & b, mpz & c) {
SASSERT(is_nonneg(a));
SASSERT(is_nonneg(b));
if (is_small(a) && is_small(b)) {
set_i64(c, i64(a) ^ i64(b));
}
else {
#ifndef _MP_GMP
mpz a1, b1, a2, b2, m, tmp;
set(a1, a);
set(b1, b);
set(m, 1);
reset(c);
while (!is_zero(a1) && !is_zero(b1)) {
mod(a1, m_two64, a2);
mod(b1, m_two64, b2);
uint64 v = get_uint64(a2) ^ get_uint64(b2);
set(tmp, v);
mul(tmp, m, tmp);
add(c, tmp, c); // c += m * v
mul(m, m_two64, m);
div(a1, m_two64, a1);
div(b1, m_two64, b1);
}
if (!is_zero(a1)) {
mul(a1, m, a1);
add(c, a1, c);
}
if (!is_zero(b1)) {
mul(b1, m, b1);
add(c, b1, c);
}
del(a1); del(b1); del(a2); del(b2); del(m); del(tmp);
#else
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
mk_big(c);
mpz_xor(*c.m_ptr, *arg0, *arg1);
#endif
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::bitwise_not(unsigned sz, mpz const & a, mpz & c) {
SASSERT(is_nonneg(a));
if (is_small(a) && sz <= 63) {
int64 mask = (static_cast<int64>(1) << sz) - static_cast<int64>(1);
set_i64(c, (~ i64(a)) & mask);
}
else {
mpz a1, a2, m, tmp;
set(a1, a);
set(m, 1);
set(c, 0);
while (sz > 0) {
mod(a1, m_two64, a2);
uint64 n = get_uint64(a2);
uint64 v = ~n;
SASSERT(~v == n);
if (sz < 64) {
uint64 mask = (1ull << static_cast<uint64>(sz)) - 1ull;
v = mask & v;
}
TRACE("bitwise_not", tout << "sz: " << sz << ", v: " << v << ", n: " << n << "\n";);
set(tmp, v);
SASSERT(get_uint64(tmp) == v);
mul(tmp, m, tmp);
add(c, tmp, c); // c += m * v
mul(m, m_two64, m);
div(a1, m_two64, a1);
sz -= (sz<64) ? sz : 64;
}
del(a1); del(a2); del(m); del(tmp);
TRACE("bitwise_not", tout << "sz: " << sz << " a: " << to_string(a) << " c: " << to_string(c) << "\n";);
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::big_set(mpz & target, mpz const & source) {
#ifndef _MP_GMP
if (&target == &source)
return;
target.m_val = source.m_val;
if (is_small(target)) {
target.m_ptr = allocate(capacity(source));
target.m_ptr->m_size = size(source);
target.m_ptr->m_capacity = capacity(source);
memcpy(target.m_ptr->m_digits, source.m_ptr->m_digits, sizeof(digit_t) * size(source));
}
else {
if (capacity(target) < size(source)) {
deallocate(target.m_ptr);
target.m_ptr = allocate(capacity(source));
target.m_ptr->m_size = size(source);
target.m_ptr->m_capacity = capacity(source);
memcpy(target.m_ptr->m_digits, source.m_ptr->m_digits, sizeof(digit_t) * size(source));
}
else {
target.m_ptr->m_size = size(source);
memcpy(target.m_ptr->m_digits, source.m_ptr->m_digits, sizeof(digit_t) * size(source));
}
}
#else
// GMP version
mk_big(target);
mpz_set(*target.m_ptr, *source.m_ptr);
#endif
}
template<bool SYNCH>
int mpz_manager<SYNCH>::big_compare(mpz const & a, mpz const & b) {
#ifndef _MP_GMP
int sign_a;
int sign_b;
mpz_cell * cell_a;
mpz_cell * cell_b;
get_sign_cell<0>(a, sign_a, cell_a);
get_sign_cell<1>(b, sign_b, cell_b);
if (sign_a > 0) {
// a is positive
if (sign_b > 0) {
// a & b are positive
return compare_diff(cell_a->m_digits,
cell_a->m_size,
cell_b->m_digits,
cell_b->m_size);
}
else {
// b is negative
return 1; // a > b
}
}
else {
// a is negative
if (sign_b > 0) {
// b is positive
return -1; // a < b
}
else {
// a & b are negative
return compare_diff(cell_b->m_digits,
cell_b->m_size,
cell_a->m_digits,
cell_a->m_size);
}
}
#else
// GMP version
mpz_t * arg0;
mpz_t * arg1;
get_arg<0>(a, arg0);
get_arg<1>(b, arg1);
return mpz_cmp(*arg0, *arg1);
#endif
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::is_uint64(mpz const & a) const {
#ifndef _MP_GMP
if (a.m_val < 0)
return false;
if (is_small(a))
return true;
if (sizeof(digit_t) == sizeof(uint64)) {
return size(a) <= 1;
}
else {
return size(a) <= 2;
}
#else
// GMP version
if (is_small(a))
return a.m_val >= 0;
return is_nonneg(a) && mpz_cmp(*a.m_ptr, m_uint64_max) <= 0;
#endif
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::is_int64(mpz const & a) const {
if (is_small(a))
return true;
#ifndef _MP_GMP
if (!is_uint64(a))
return false;
uint64 num = get_uint64(a);
uint64 msb = static_cast<uint64>(1) << 63;
uint64 msb_val = msb & num;
if (a.m_val >= 0) {
// non-negative number.
return (0 == msb_val);
}
else {
// negative number.
// either the high bit is 0, or
// the number is 2^64 which can be represented.
//
return 0 == msb_val || (msb_val == num);
}
#else
// GMP version
return mpz_cmp(*a.m_ptr, m_int64_max) <= 0;
#endif
}
template<bool SYNCH>
uint64 mpz_manager<SYNCH>::get_uint64(mpz const & a) const {
if (is_small(a))
return static_cast<uint64>(a.m_val);
#ifndef _MP_GMP
SASSERT(a.m_ptr->m_size > 0);
if (a.m_ptr->m_size == 1)
return digits(a)[0];
if (sizeof(digit_t) == sizeof(uint64))
// 64-bit machine
return digits(a)[0];
else
// 32-bit machine
return ((static_cast<uint64>(digits(a)[1]) << 32) | (static_cast<uint64>(digits(a)[0])));
#else
// GMP version
if (sizeof(uint64) == sizeof(unsigned long)) {
return mpz_get_ui(*a.m_ptr);
}
else {
mpz_manager * _this = const_cast<mpz_manager*>(this);
mpz_set(_this->m_tmp, *a.m_ptr);
mpz_mod(_this->m_tmp, m_tmp, m_two32);
uint64 r = static_cast<uint64>(mpz_get_ui(m_tmp));
mpz_set(_this->m_tmp, *a.m_ptr);
mpz_div(_this->m_tmp, m_tmp, m_two32);
r += static_cast<uint64>(mpz_get_ui(m_tmp)) << static_cast<uint64>(32);
return r;
}
#endif
}
template<bool SYNCH>
int64 mpz_manager<SYNCH>::get_int64(mpz const & a) const {
if (is_small(a))
return static_cast<int64>(a.m_val);
#ifndef _MP_GMP
SASSERT(is_int64(a));
uint64 num = get_uint64(a);
if (a.m_val < 0) {
if (num != 0 && (num << 1) == 0)
return INT64_MIN;
return -static_cast<int64>(num);
}
return static_cast<int64>(num);
#else
// GMP
if (sizeof(int64) == sizeof(long) || mpz_fits_slong_p(*a.m_ptr)) {
return mpz_get_si(*a.m_ptr);
}
else {
mpz_manager * _this = const_cast<mpz_manager*>(this);
mpz_mod(_this->m_tmp, *a.m_ptr, m_two32);
int64 r = static_cast<int64>(mpz_get_ui(m_tmp));
mpz_div(_this->m_tmp, *a.m_ptr, m_two32);
r += static_cast<int64>(mpz_get_si(m_tmp)) << static_cast<int64>(32);
return r;
}
#endif
}
template<bool SYNCH>
double mpz_manager<SYNCH>::get_double(mpz const & a) const {
if (is_small(a))
return static_cast<double>(a.m_val);
#ifndef _MP_GMP
double r = 0.0;
double d = 1.0;
unsigned sz = size(a);
for (unsigned i = 0; i < sz; i++) {
r += d * static_cast<double>(digits(a)[i]);
if (sizeof(digit_t) == sizeof(uint64))
d *= static_cast<double>(UINT64_MAX); // 64-bit version
else
d *= static_cast<double>(UINT_MAX); // 32-bit version
}
return a.m_val < 0 ? -r : r;
#else
return mpz_get_d(*a.m_ptr);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::display(std::ostream & out, mpz const & a) const {
if (is_small(a)) {
out << a.m_val;
}
else {
#ifndef _MP_GMP
if (a.m_val < 0)
out << "-";
if (sizeof(digit_t) == 4) {
sbuffer<char, 1024> buffer(11*size(a), 0);
out << mp_decimal(digits(a), size(a), buffer.begin(), buffer.size(), 0);
}
else {
sbuffer<char, 1024> buffer(21*size(a), 0);
out << mp_decimal(digits(a), size(a), buffer.begin(), buffer.size(), 0);
}
#else
// GMP version
size_t sz = mpz_sizeinbase(*a.m_ptr, 10) + 2;
sbuffer<char, 1024> buffer(sz, 0);
mpz_get_str(buffer.c_ptr(), 10, *a.m_ptr);
out << buffer.c_ptr();
#endif
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::display_smt2(std::ostream & out, mpz const & a, bool decimal) const {
if (is_neg(a)) {
mpz_manager<SYNCH> * _this = const_cast<mpz_manager<SYNCH>*>(this);
_scoped_numeral<mpz_manager<SYNCH> > tmp(*_this);
_this->set(tmp, a);
_this->neg(tmp);
out << "(- ";
display(out, tmp);
if (decimal)
out << ".0";
out << ")";
}
else {
display(out, a);
if (decimal)
out << ".0";
}
}
template<bool SYNCH>
std::string mpz_manager<SYNCH>::to_string(mpz const & a) const {
std::ostringstream buffer;
display(buffer, a);
return buffer.str();
}
template<bool SYNCH>
unsigned mpz_manager<SYNCH>::hash(mpz const & a) {
if (is_small(a))
return a.m_val;
#ifndef _MP_GMP
unsigned sz = size(a);
if (sz == 1)
return static_cast<unsigned>(digits(a)[0]);
return string_hash(reinterpret_cast<char*>(digits(a)), sz * sizeof(digit_t), 17);
#else
return mpz_get_si(*a.m_ptr);
#endif
}
template<bool SYNCH>
void mpz_manager<SYNCH>::power(mpz const & a, unsigned p, mpz & b) {
#ifdef _MP_GMP
if (!is_small(a)) {
mk_big(b);
mpz_pow_ui(*b.m_ptr, *a.m_ptr, p);
return;
}
#endif
#ifndef _MP_GMP
if (is_small(a)) {
if (a.m_val == 2) {
if (p < 8 * sizeof(int) - 1) {
del(b);
b.m_val = 1 << p;
}
else {
unsigned sz = p/(8 * sizeof(digit_t)) + 1;
unsigned shift = p%(8 * sizeof(digit_t));
SASSERT(sz > 0);
allocate_if_needed(b, sz);
SASSERT(b.m_ptr->m_capacity >= sz);
b.m_ptr->m_size = sz;
for (unsigned i = 0; i < sz - 1; i++)
b.m_ptr->m_digits[i] = 0;
b.m_ptr->m_digits[sz-1] = 1 << shift;
b.m_val = 1;
}
return;
}
if (a.m_val == 0) {
SASSERT(p != 0);
reset(b);
return;
}
if (a.m_val == 1) {
set(b, 1);
return;
}
}
#endif
// general purpose
unsigned mask = 1;
mpz power;
set(power, a);
set(b, 1);
while (mask <= p) {
if (mask & p)
mul(b, power, b);
mul(power, power, power);
mask = mask << 1;
}
del(power);
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::is_power_of_two(mpz const & a) {
unsigned shift;
return is_power_of_two(a, shift);
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::is_power_of_two(mpz const & a, unsigned & shift) {
if (is_nonpos(a))
return false;
if (is_small(a)) {
if (::is_power_of_two(a.m_val)) {
shift = ::log2(a.m_val);
return true;
}
else {
return false;
}
}
#ifndef _MP_GMP
mpz_cell * c = a.m_ptr;
unsigned sz = c->m_size;
digit_t * ds = c->m_digits;
for (unsigned i = 0; i < sz - 1; i++) {
if (ds[i] != 0)
return false;
}
digit_t v = ds[sz-1];
if (!(v & (v - 1)) && v) {
shift = log2(a);
return true;
}
else {
return false;
}
#else
if (mpz_popcount(*a.m_ptr) == 1) {
shift = log2(a);
return true;
}
else {
return false;
}
#endif
}
// Expand capacity of a
#ifndef _MP_GMP
template<bool SYNCH>
void mpz_manager<SYNCH>::ensure_capacity(mpz & a, unsigned capacity) {
if (capacity <= 1)
return;
if (capacity < m_init_cell_capacity)
capacity = m_init_cell_capacity;
if (is_small(a)) {
a.m_ptr = allocate(capacity);
SASSERT(a.m_ptr->m_capacity == capacity);
if (a.m_val == INT_MIN) {
unsigned intmin_sz = m_int_min.m_ptr->m_size;
for (unsigned i = 0; i < intmin_sz; i++)
a.m_ptr->m_digits[i] = m_int_min.m_ptr->m_digits[i];
a.m_val = -1;
a.m_ptr->m_size = m_int_min.m_ptr->m_size;
}
else if (a.m_val < 0) {
a.m_ptr->m_digits[0] = -a.m_val;
a.m_val = -1;
a.m_ptr->m_size = 1;
}
else {
a.m_ptr->m_digits[0] = a.m_val;
a.m_val = 1;
a.m_ptr->m_size = 1;
}
}
else {
if (a.m_ptr->m_capacity >= capacity)
return;
mpz_cell * new_cell = allocate(capacity);
SASSERT(new_cell->m_capacity == capacity);
unsigned old_sz = a.m_ptr->m_size;
new_cell->m_size = old_sz;
for (unsigned i = 0; i < old_sz; i++)
new_cell->m_digits[i] = a.m_ptr->m_digits[i];
deallocate(a.m_ptr);
a.m_ptr = new_cell;
}
}
template<bool SYNCH>
void mpz_manager<SYNCH>::normalize(mpz & a) {
mpz_cell * c = a.m_ptr;
digit_t * ds = c->m_digits;
unsigned i = c->m_size;
for (; i > 0; --i) {
if (ds[i-1] != 0)
break;
}
if (i == 0) {
// a is zero...
reset(a);
return;
}
if (i == 1 && ds[0] <= INT_MAX) {
// a is small
int val = a.m_val < 0 ? -static_cast<int>(ds[0]) : static_cast<int>(ds[0]);
del(a);
a.m_val = val;
return;
}
// adjust size
c->m_size = i;
}
#endif
template<bool SYNCH>
void mpz_manager<SYNCH>::machine_div2k(mpz & a, unsigned k) {
if (k == 0 || is_zero(a))
return;
if (is_small(a)) {
if (k < 32) {
int twok = 1 << k;
a.m_val /= twok;
}
else {
a.m_val = 0;
}
return;
}
#ifndef _MP_GMP
unsigned digit_shift = k / (8 * sizeof(digit_t));
mpz_cell * c = a.m_ptr;
unsigned sz = c->m_size;
if (digit_shift >= sz) {
reset(a);
return;
}
unsigned bit_shift = k % (8 * sizeof(digit_t));
unsigned comp_shift = (8 * sizeof(digit_t)) - bit_shift;
unsigned new_sz = sz - digit_shift;
SASSERT(new_sz >= 1);
digit_t * ds = c->m_digits;
TRACE("mpz_2k", tout << "bit_shift: " << bit_shift << ", comp_shift: " << comp_shift << ", new_sz: " << new_sz << ", sz: " << sz << "\n";);
if (new_sz < sz) {
unsigned i = 0;
unsigned j = digit_shift;
if (bit_shift != 0) {
for (; i < new_sz - 1; i++, j++) {
ds[i] = ds[j];
ds[i] >>= bit_shift;
ds[i] |= (ds[j+1] << comp_shift);
}
ds[i] = ds[j];
ds[i] >>= bit_shift;
}
else {
for (; i < new_sz; i++, j++) {
ds[i] = ds[j];
}
}
}
else {
SASSERT(new_sz == sz);
SASSERT(bit_shift != 0);
unsigned i = 0;
for (; i < new_sz - 1; i++) {
ds[i] >>= bit_shift;
ds[i] |= (ds[i+1] << comp_shift);
}
ds[i] >>= bit_shift;
}
c->m_size = new_sz;
normalize(a);
#else
MPZ_BEGIN_CRITICAL();
mpz_t * arg0;
get_arg<0>(a, arg0);
mpz_tdiv_q_2exp(m_tmp, *arg0, k);
mk_big(a);
mpz_swap(*a.m_ptr, m_tmp);
MPZ_END_CRITICAL();
#endif
}
#ifndef _MP_GMP
static void display_bits(std::ostream & out, digit_t a) {
for (unsigned i = 0; i < sizeof(digit_t) * 8; i++) {
if (a % 2 == 0)
out << "0";
else
out << "1";
a /= 2;
}
}
#endif
template<bool SYNCH>
void mpz_manager<SYNCH>::mul2k(mpz & a, unsigned k) {
if (k == 0 || is_zero(a))
return;
if (is_small(a) && k < 32) {
set_i64(a, i64(a) * (static_cast<int64>(1) << k));
return;
}
#ifndef _MP_GMP
TRACE("mpz_mul2k", tout << "mul2k\na: " << to_string(a) << "\nk: " << k << "\n";);
unsigned word_shift = k / (8 * sizeof(digit_t));
unsigned bit_shift = k % (8 * sizeof(digit_t));
unsigned old_sz = is_small(a) ? 1 : a.m_ptr->m_size;
unsigned new_sz = old_sz + word_shift + 1;
ensure_capacity(a, new_sz);
TRACE("mpz_mul2k", tout << "word_shift: " << word_shift << "\nbit_shift: " << bit_shift << "\nold_sz: " << old_sz << "\nnew_sz: " << new_sz
<< "\na after ensure capacity:\n" << to_string(a) << "\n";);
SASSERT(!is_small(a));
mpz_cell * cell_a = a.m_ptr;
old_sz = cell_a->m_size;
digit_t * ds = cell_a->m_digits;
for (unsigned i = old_sz; i < new_sz; i++)
ds[i] = 0;
cell_a->m_size = new_sz;
if (word_shift > 0) {
unsigned j = old_sz;
unsigned i = old_sz + word_shift;
while (j > 0) {
--j; --i;
ds[i] = ds[j];
}
while (i > 0) {
--i;
ds[i] = 0;
}
}
if (bit_shift > 0) {
DEBUG_CODE({
for (unsigned i = 0; i < word_shift; i++) {
SASSERT(ds[i] == 0);
}
});
unsigned comp_shift = (8 * sizeof(digit_t)) - bit_shift;
digit_t prev = 0;
for (unsigned i = word_shift; i < new_sz; i++) {
digit_t new_prev = (ds[i] >> comp_shift);
ds[i] <<= bit_shift;
ds[i] |= prev;
prev = new_prev;
}
}
normalize(a);
TRACE("mpz_mul2k", tout << "mul2k result:\n" << to_string(a) << "\n";);
#else
mpz_t * arg0;
get_arg<0>(a, arg0);
mk_big(a);
mpz_mul_2exp(*a.m_ptr, *arg0, k);
#endif
}
#ifndef _MP_GMP
COMPILE_TIME_ASSERT(sizeof(digit_t) == 4 || sizeof(digit_t) == 8);
#endif
template<bool SYNCH>
unsigned mpz_manager<SYNCH>::power_of_two_multiple(mpz const & a) {
if (is_zero(a))
return 0;
if (is_small(a)) {
unsigned r = 0;
int v = a.m_val;
#define COUNT_DIGIT_RIGHT_ZEROS() \
if (v % (1 << 16) == 0) { \
r += 16; \
v /= (1 << 16); \
} \
if (v % (1 << 8) == 0) { \
r += 8; \
v /= (1 << 8); \
} \
if (v % (1 << 4) == 0) { \
r += 4; \
v /= (1 << 4); \
} \
if (v % (1 << 2) == 0) { \
r += 2; \
v /= (1 << 2); \
} \
if (v % 2 == 0) { \
r++; \
}
COUNT_DIGIT_RIGHT_ZEROS();
return r;
}
#ifndef _MP_GMP
mpz_cell * c = a.m_ptr;
unsigned sz = c->m_size;
unsigned r = 0;
digit_t * source = c->m_digits;
for (unsigned i = 0; i < sz; i++) {
if (source[i] != 0) {
digit_t v = source[i];
if (sizeof(digit_t) == 8) {
// TODO: we can remove this if after we move to MPN
// In MPN the digit_t is always an unsigned integer
if (static_cast<uint64>(v) % (static_cast<uint64>(1) << 32) == 0) {
r += 32;
v = static_cast<digit_t>(static_cast<uint64>(v) / (static_cast<uint64>(1) << 32));
}
}
COUNT_DIGIT_RIGHT_ZEROS();
return r;
}
r += (8 * sizeof(digit_t));
}
return r;
#else
return mpz_scan1(*a.m_ptr, 0);
#endif
}
template<bool SYNCH>
unsigned mpz_manager<SYNCH>::log2(mpz const & a) {
if (is_nonpos(a))
return 0;
if (is_small(a))
return ::log2(a.m_val);
#ifndef _MP_GMP
COMPILE_TIME_ASSERT(sizeof(digit_t) == 8 || sizeof(digit_t) == 4);
mpz_cell * c = a.m_ptr;
unsigned sz = c->m_size;
digit_t * ds = c->m_digits;
if (sizeof(digit_t) == 8)
return (sz - 1)*64 + uint64_log2(ds[sz-1]);
else
return (sz - 1)*32 + ::log2(static_cast<unsigned>(ds[sz-1]));
#else
unsigned r = mpz_sizeinbase(*a.m_ptr, 2);
SASSERT(r > 0);
return r - 1;
#endif
}
template<bool SYNCH>
unsigned mpz_manager<SYNCH>::mlog2(mpz const & a) {
if (is_nonneg(a))
return 0;
if (is_small(a))
return ::log2(-a.m_val);
#ifndef _MP_GMP
COMPILE_TIME_ASSERT(sizeof(digit_t) == 8 || sizeof(digit_t) == 4);
mpz_cell * c = a.m_ptr;
unsigned sz = c->m_size;
digit_t * ds = c->m_digits;
if (sizeof(digit_t) == 8)
return (sz - 1)*64 + uint64_log2(ds[sz-1]);
else
return (sz - 1)*32 + ::log2(static_cast<unsigned>(ds[sz-1]));
#else
mpz_neg(m_tmp, *a.m_ptr);
unsigned r = mpz_sizeinbase(m_tmp, 2);
SASSERT(r > 0);
return r - 1;
#endif
}
template<bool SYNCH>
unsigned mpz_manager<SYNCH>::bitsize(mpz const & a) {
if (is_nonneg(a))
return log2(a) + 1;
else
return mlog2(a) + 1;
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::is_perfect_square(mpz const & a, mpz & root) {
if (is_neg(a))
return false;
reset(root);
if (is_zero(a)) {
return true;
}
if (is_one(a)) {
set(root, 1);
return true;
}
mpz lo, hi, mid, sq_lo, sq_hi, sq_mid;
set(lo, 1);
set(hi, a);
set(sq_lo, 1);
mul(hi, hi, sq_hi);
bool result;
// lo*lo <= *this < hi*hi
while (true) {
SASSERT(lt(lo, hi));
SASSERT(le(sq_lo, a) && lt(a, sq_hi));
if (eq(sq_lo, a)) {
set(root, lo);
result = true;
break;
}
mpz & tmp = mid;
add(lo, mpz(1), tmp);
if (eq(tmp, hi)) {
set(root, hi);
result = false;
break;
}
add(hi, lo, tmp);
div(tmp, mpz(2), mid);
SASSERT(lt(lo, mid) && lt(mid, hi));
mul(mid, mid, sq_mid);
if (gt(sq_mid, a)) {
set(hi, mid);
set(sq_hi, sq_mid);
}
else {
set(lo, mid);
set(sq_lo, sq_mid);
}
}
del(lo);
del(hi);
del(mid);
del(sq_lo);
del(sq_hi);
del(sq_mid);
return result;
}
static unsigned div_l(unsigned k, unsigned n) {
return k/n;
}
static unsigned div_u(unsigned k, unsigned n) {
return k%n == 0 ? k/n : k/n + 1;
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::root(mpz & a, unsigned n) {
SASSERT(n % 2 != 0 || is_nonneg(a));
if (is_zero(a)) {
return true; // precise
}
// Initial approximation
//
// We have that:
// a > 0 -> 2^{log2(a)} <= a <= 2^{(log2(a) + 1)}
// a < 0 -> -2^{log2(a) + 1} <= a <= -2^{log2(a)}
//
// Thus
// a > 0 -> 2^{div_l(log2(a), n)} <= a^{1/n} <= 2^{div_u(log2(a) + 1, n)}
// a < 0 -> -2^{div_u(log2(a) + 1, n)} <= a^{1/n} <= -2^{div_l(log2(a), n)}
//
mpz lower;
mpz upper;
mpz mid;
mpz mid_n;
if (is_pos(a)) {
unsigned k = log2(a);
power(mpz(2), div_l(k, n), lower);
power(mpz(2), div_u(k + 1, n), upper);
}
else {
unsigned k = mlog2(a);
power(mpz(2), div_u(k + 1, n), lower);
power(mpz(2), div_l(k, n), upper);
neg(lower);
neg(upper);
}
bool result;
SASSERT(le(lower, upper));
if (eq(lower, upper)) {
swap(a, lower);
result = true;
}
else {
// Refine using bisection. TODO: use Newton's method if this is a bottleneck
while (true) {
add(upper, lower, mid);
machine_div2k(mid, 1);
TRACE("mpz", tout << "upper: "; display(tout, upper); tout << "\nlower: "; display(tout, lower); tout << "\nmid: "; display(tout, mid); tout << "\n";);
power(mid, n, mid_n);
if (eq(mid_n, a)) {
swap(a, mid);
result = true;
break;
}
if (eq(mid, lower) || eq(mid, upper)) {
swap(a, upper);
result = false;
break;
}
if (lt(mid_n, a)) {
// new lower bound
swap(mid, lower);
}
else {
SASSERT(lt(a, mid_n));
// new upper bound
swap(mid, upper);
}
}
}
del(lower);
del(upper);
del(mid);
del(mid_n);
return result;
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::decompose(mpz const & a, svector<digit_t> & digits) {
digits.reset();
if (is_small(a)) {
if (a.m_val < 0) {
digits.push_back(-a.m_val);
return true;
}
else {
digits.push_back(a.m_val);
return false;
}
}
else {
#ifndef _MP_GMP
mpz_cell * cell_a = a.m_ptr;
unsigned sz = cell_a->m_size;
for (unsigned i = 0; i < sz; i++) {
digits.push_back(cell_a->m_digits[i]);
}
return a.m_val < 0;
#else
bool r = is_neg(a);
mpz_set(m_tmp, *a.m_ptr);
mpz_abs(m_tmp, m_tmp);
while (mpz_sgn(m_tmp) != 0) {
mpz_tdiv_r_2exp(m_tmp2, m_tmp, 32);
unsigned v = mpz_get_ui(m_tmp2);
digits.push_back(v);
mpz_tdiv_q_2exp(m_tmp, m_tmp, 32);
}
return r;
#endif
}
}
template<bool SYNCH>
bool mpz_manager<SYNCH>::divides(mpz const & a, mpz const & b) {
_scoped_numeral<mpz_manager<SYNCH> > tmp(*this);
bool r;
if (is_zero(a)) {
// I assume 0 | 0.
// Remark a|b is a shorthand for (exists x. a x = b)
// If b is zero, any x will do. If b != 0, then a does not divide b
r = is_zero(b);
}
else {
rem(b, a, tmp);
r = is_zero(tmp);
}
STRACE("divides", tout << "[mpz] Divisible["; display(tout, b); tout << ", "; display(tout, a); tout << "] == " << (r?"True":"False") << "\n";);
TRACE("divides_bug", tout << "tmp: "; display(tout, tmp); tout << "\n";);
return r;
}
template class mpz_manager<true>;
template class mpz_manager<false>;
| cs-au-dk/Artemis | contrib/Z3/lib/mpz.cpp | C++ | gpl-3.0 | 59,447 |
# shortandsweet
This project will focus on learning web dev, git, etc.
html
css
javascript
nodejs
| attatt/shortandsweet | README.md | Markdown | gpl-3.0 | 99 |
<?php
/*
*
* _____ _____ __ _ _ _____ __ __ _____
* / ___| | ____| | \ | | | | / ___/ \ \ / / / ___/
* | | | |__ | \| | | | | |___ \ \/ / | |___
* | | _ | __| | |\ | | | \___ \ \ / \___ \
* | |_| | | |___ | | \ | | | ___| | / / ___| |
* \_____/ |_____| |_| \_| |_| /_____/ /_/ /_____/
*
* This program 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.
*
* @author iTX Technologies
* @link https://itxtech.org
*
*/
namespace pocketmine\command\defaults;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\event\TranslationContainer;
use pocketmine\Player;
class BanCidByNameCommand extends VanillaCommand{
public function __construct($name){
parent::__construct(
$name,
"%pocketmine.command.bancidbyname.description",
"%pocketmine.command.bancidbyname.usage"
);
$this->setPermission("pocketmine.command.bancidbyname");
}
public function execute(CommandSender $sender, $currentAlias, array $args){
if(!$this->testPermission($sender)){
return true;
}
if(count($args) === 0){
$sender->sendMessage(new TranslationContainer("commands.generic.usage", [$this->usageMessage]));
return false;
}
$name = array_shift($args);
$reason = implode(" ", $args);
if($sender->getServer()->getPlayer($name) instanceof Player) $target = $sender->getServer()->getPlayer($name);
else return false;
$sender->getServer()->getCIDBans()->addBan($target->getClientId(), $reason, null, $sender->getName());
$target->kick($reason !== "" ? "Banned by admin. Reason:" . $reason : "Banned by admin.");
Command::broadcastCommandMessage($sender, new TranslationContainer("%commands.bancidbyname.success", [$target !== null ? $target->getName() : $name]));
return true;
}
}
| Infernus101/Tesseract-Resurrected | src/pocketmine/command/defaults/BanCidByNameCommand.php | PHP | gpl-3.0 | 2,004 |
package fr.inserm.umr915.knime4ngs.nodes.vcf.context.das;
import java.io.IOException;
import java.io.StringReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.knime.base.data.append.column.AppendedColumnRow;
import org.knime.core.data.DataCell;
import org.knime.core.data.DataColumnSpec;
import org.knime.core.data.DataColumnSpecCreator;
import org.knime.core.data.DataRow;
import org.knime.core.data.DataTableSpec;
import org.knime.core.data.DataType;
import org.knime.core.data.container.CloseableRowIterator;
import org.knime.core.data.def.IntCell;
import org.knime.core.data.def.StringCell;
import org.knime.core.node.BufferedDataContainer;
import org.knime.core.node.BufferedDataTable;
import org.knime.core.node.ExecutionContext;
import org.knime.core.node.InvalidSettingsException;
import org.knime.core.node.defaultnodesettings.SettingsModel;
import org.knime.core.node.defaultnodesettings.SettingsModelColumnName;
import org.knime.core.node.defaultnodesettings.SettingsModelInteger;
import org.knime.core.node.defaultnodesettings.SettingsModelString;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import fr.inserm.umr915.knime4ngs.nodes.vcf.AbstractVCFNodeModel;
/**
* @author Pierre Lindenbaum
*/
public class DasContextNodeModel extends AbstractVCFNodeModel
{
/** chrom column */
static final String CHROM_COL_PROPERTY="chrom.col";
static final String CHROM_COL_DEFAULT="CHROM";
private final SettingsModelColumnName m_chromColumn = new SettingsModelColumnName(
CHROM_COL_PROPERTY,
CHROM_COL_DEFAULT
);
/** pos column */
static final String POS_COL_PROPERTY="pos.col";
static final String POS_COL_DEFAULT="POS";
private final SettingsModelColumnName m_posColumn = new SettingsModelColumnName(
POS_COL_PROPERTY,
POS_COL_DEFAULT
);
final static int DEFAULT_EXTEND=5;
static final String EXTEND_PROPERTY="extend";
private final SettingsModelInteger m_extend =
new SettingsModelInteger(EXTEND_PROPERTY,DEFAULT_EXTEND);
/** das URI */
static final String DAS_URI_PROPERTY="das.uri";
static final String DEFAULT_DAS_URI="http://genome.ucsc.edu/cgi-bin/das/hg19/dna";
private final SettingsModelString m_dasUri =new SettingsModelString(DAS_URI_PROPERTY,DEFAULT_DAS_URI);
/**
* Constructor for the node model.
*/
protected DasContextNodeModel()
{
super(1,1);
}
private static class DnaHandler extends DefaultHandler
{
StringBuilder dna=null;
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException
{
if(name.equals("DNA"))
{
this.dna=new StringBuilder();
}
}
@Override
public void endElement(String arg0, String arg1, String arg2)
throws SAXException
{
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException
{
if(this.dna==null) return;
for(int i=0;i< length;++i)
{
char c= Character.toUpperCase(ch[start+i]);
if(Character.isWhitespace(c)) continue;
this.dna.append(c);
}
}
}
@Override
protected BufferedDataTable[] execute(
final BufferedDataTable[] inData,
final ExecutionContext exec
) throws Exception
{
BufferedDataContainer container1=null;
try
{
// the data table spec of the single output table,
// the table will have three columns:
BufferedDataTable inTable=inData[0];
DataTableSpec inDataTableSpec = inTable.getDataTableSpec();
int chromColumn= inDataTableSpec.findColumnIndex(this.m_chromColumn.getStringValue());
int pos0Column= inDataTableSpec.findColumnIndex(this.m_posColumn.getStringValue());
int extend=this.m_extend.getIntValue();
if(extend<=0) extend=0;
container1 = exec.createDataContainer(createSpec(inDataTableSpec));
XMLReader xmlreader=XMLReaderFactory.createXMLReader();
xmlreader.setEntityResolver(new EntityResolver()
{
@Override
public InputSource resolveEntity(String arg0, String arg1)
throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
DnaHandler handler=new DnaHandler();
xmlreader.setContentHandler(handler);
double total=inTable.getRowCount();
int nRow=0;
CloseableRowIterator iter=null;
try {
iter=inTable.iterator();
while(iter.hasNext())
{
++nRow;
DataRow row=iter.next();
handler.dna=null;
DataCell cell=row.getCell(chromColumn);
if(cell.isMissing()) continue;
String chrom=StringCell.class.cast(cell).getStringValue();
cell=row.getCell(pos0Column);
if(cell.isMissing()) continue;
int pos0=IntCell.class.cast(cell).getIntValue();
int leftLen=extend;
if(pos0-leftLen<1) leftLen=pos0-1;
String uri=m_dasUri.getStringValue()+"?segment="+URLEncoder.encode(chrom, "UTF-8")
+":"+(pos0-leftLen)+","+(pos0+extend);
try
{
xmlreader.parse(uri);
row=new AppendedColumnRow(row,
new StringCell(handler.dna.substring(0, leftLen)),
new StringCell(handler.dna.substring(leftLen,leftLen+1)),
new StringCell(handler.dna.substring(leftLen+1))
);
}
catch(Exception err)
{
System.err.println("DAS ERROR:"+err.getMessage()+" "+uri);
row=new AppendedColumnRow(row,
DataType.getMissingCell(),
DataType.getMissingCell(),
DataType.getMissingCell()
);
}
container1.addRowToTable(row);
}
exec.checkCanceled();
exec.setProgress(nRow/total,"Getting DNA context");
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
safeClose(iter);
}
// once we are done, we close the container and return its table
safeClose(container1);
BufferedDataTable out1 = container1.getTable();
container1=null;
return new BufferedDataTable[]{out1};
}
catch(Exception err)
{
getLogger().error("Boum", err);
err.printStackTrace();
throw err;
}
finally
{
safeClose(container1);
}
}
@Override
protected DataTableSpec[] configure(DataTableSpec[] inSpecs)
throws InvalidSettingsException
{
if(inSpecs==null || inSpecs.length!=1)
{
throw new InvalidSettingsException("Expected one table");
}
findColumnIndex(inSpecs[0], m_chromColumn,StringCell.TYPE);
findColumnIndex(inSpecs[0], m_posColumn,IntCell.TYPE);
return new DataTableSpec[]{createSpec(inSpecs[0])};
}
private DataTableSpec createSpec(DataTableSpec in)
{
return new DataTableSpec(in,
new DataTableSpec(new DataColumnSpec[]{
new DataColumnSpecCreator("left.context",StringCell.TYPE).createSpec(),
new DataColumnSpecCreator("ref.context",StringCell.TYPE).createSpec(),
new DataColumnSpecCreator("right.context",StringCell.TYPE).createSpec()
}
)
);
}
@Override
protected List<SettingsModel> getSettingsModel() {
List<SettingsModel> L=new ArrayList<SettingsModel>( super.getSettingsModel());
L.add(this.m_chromColumn);
L.add(this.m_posColumn);
L.add(this.m_dasUri);
L.add(this.m_extend);
return L;
}
}
| lindenb/knime4bio | fr.inserm.umr915.knime4ngs.nodes/src/fr/inserm/umr915/knime4ngs/nodes/vcf/context/das/DasContextNodeModel.java | Java | gpl-3.0 | 8,205 |
package de.uzk.hki.da.at;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import de.uzk.hki.da.utils.FolderUtils;
/**
*
* @author Polina Gubaidullina
*
*/
public class ATSipBuilderCliEad {
private static File targetDir = new File("target/atTargetDir/");
private static File sourceDir = new File("src/test/resources/at/");
private static String singleSip = "ATBuildSingleEadSip.tgz";
private static String singleSipError = "ATBuildSingleEadSipWrongRefError.tgz";
private static Process p;
@Before
public void setUp() throws IOException{
FolderUtils.deleteDirectorySafe(targetDir);
}
@After
public void tearDown() throws IOException{
FolderUtils.deleteDirectorySafe(targetDir);
p.destroy();
}
@Test
public void testBuildSingleSipCorrectReferences() throws IOException {
File source = new File(sourceDir, "ATBuildSingleEadSip");
String cmd = "./SipBuilder-Unix.sh -rights=\""+ATWorkingDirectory.CONTRACT_RIGHT_LICENSED_ONLY_INST_PUB.getAbsolutePath()+"\" -source=\""+source.getAbsolutePath()+"/\" -destination=\""+targetDir.getAbsolutePath()+"/\" -single -alwaysOverwrite";
p=Runtime.getRuntime().exec(cmd,
null, new File("target/installation"));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
String s = "";
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
assertTrue(new File("target/atTargetDir/"+singleSip).exists());
}
/*
@Test
public void testBuildSingleSipErrorWrongReferences() throws IOException {
File source = new File(sourceDir, "ATBuildSingleEadSipWrongRefErrorCase/ATBuildSingleEadSipWrongRefError");
String cmd = "./SipBuilder-Unix.sh -source=\""+source.getAbsolutePath()+"/\" -destination=\""+targetDir.getAbsolutePath()+"/\" -single -alwaysOverwrite";
p=Runtime.getRuntime().exec(cmd,
null, new File("target/installation"));
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
boolean falseReferencesInFileMsg = false;
boolean fileListMsg = false;
boolean metsFile45Missed = false;
boolean identifiedMetadataType = false;
boolean noSipCreated = false;
String s = "";
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
if(s.contains("Identified metadata file") && s.contains("DNSCore/SIP-Builder/src/test/resources/at/ATBuildSingleEadSipWrongRefErrorCase/ATBuildSingleEadSipWrongRefError/EAD_Export.XML=EAD}")) {
identifiedMetadataType = true;
}
if(s.contains("EAD_Export.XML enthält falsche Referenzen")) {
falseReferencesInFileMsg = true;
}
if(s.contains("Folgende Dateien konnten nicht gefunden werden")) {
fileListMsg = true;
}
if(s.contains("[../mets_2_32045.xml]")); {
metsFile45Missed = true;
}
if(s.contains("Aus dem Verzeichnis") &&
s.contains("DNSCore/SIP-Builder/src/test/resources/at/ATBuildSingleEadSipWrongRefErrorCase/ATBuildSingleEadSipWrongRefError "
+ "wird kein SIP erstellt.")) {
noSipCreated = true;
}
}
assertTrue(identifiedMetadataType);
assertTrue(falseReferencesInFileMsg);
assertTrue(fileListMsg);
assertTrue(metsFile45Missed);
assertTrue(noSipCreated);
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
assertFalse(new File("target/atTargetDir/"+singleSipError).exists());
}
*/
}
| da-nrw/DNSCore | SIP-Builder/src/test/java/de/uzk/hki/da/at/ATSipBuilderCliEad.java | Java | gpl-3.0 | 4,628 |
<!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"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>RTTTL: stuff</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">RTTTL
 <span id="projectnumber">1.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('group___default.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">stuff</div> </div>
</div><!--header-->
<div class="contents">
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated on Sat Oct 28 2017 00:31:45 for RTTTL by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.9.1 </li>
</ul>
</div>
</body>
</html>
| netmonster/arduino_rtttl_parser | doc/html/group___default.html | HTML | gpl-3.0 | 4,436 |
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ai.h"
#include "controller.h"
#include "tools/misc.h"
#include "tools/rng.h"
#include "tools/str_ops.h"
//Settings that change the program's behaviour
//If you change one, remember to re-compile
#define COUNTER_CHAR 'O'
#define MIN_PILES 2
#define MAX_PILES 5
#define MIN_COUNTERS_PER_PILE 1
#define MAX_COUNTERS_PER_PILE 20
struct player_output getUserInput(struct game_data gameState)
{
bool inputValid = false;
char inputBuffer[4096];
char chosenPile[4096];
char countersToRemove[4096];
int chosenPileInt;
int countersToRemoveInt;
int *chosenPileCounters;
do {
printf("Which pile would you like to remove counters from? ");
fgets(inputBuffer, sizeof inputBuffer / sizeof(char), stdin);
strcpy(chosenPile, stripNewline(inputBuffer));
//Data validation
if (isStrInt(chosenPile) && !isStrEmpty(chosenPile)) {
chosenPileInt = atoi(chosenPile) - 1;
chosenPileCounters = &gameState.piles[chosenPileInt];
if (chosenPileInt < 0 || chosenPileInt > gameState.numPiles) {
putchar('\n');
puts("The pile you selected does not exist. Try again.");
} else if (*chosenPileCounters == 0) {
putchar('\n');
puts("You must choose a non-empty pile. Try again.");
} else
inputValid = true;
} else {
putchar('\n');
puts("That is not a valid number. Please try again.");
}
} while(!inputValid);
inputValid = false;
putchar('\n');
do {
printf("How many counters would you like to remove? ");
fgets(inputBuffer, sizeof inputBuffer / sizeof(char), stdin);
strcpy(countersToRemove, stripNewline(inputBuffer));
//Data validation
if (isStrInt(countersToRemove) && !isStrEmpty(countersToRemove)) {
countersToRemoveInt = atoi(countersToRemove);
if (countersToRemoveInt < 1) {
putchar('\n');
puts("Please remove at least one counter. Try again.");
} else if (countersToRemoveInt > *chosenPileCounters) {
countersToRemoveInt = *chosenPileCounters;
inputValid = true;
} else
inputValid = true;
} else {
putchar('\n');
puts("That is not a valid number. Please try again.");
}
} while(!inputValid);
struct player_output output;
output.pile = chosenPileInt;
output.countersToRemove = countersToRemoveInt;
return output;
}
void controller(player_type player1, player_type player2)
{
initRand(); //Seed random number generator with current time
const int numPiles = randNum(MIN_PILES - 1, MAX_PILES - 1);
int piles[numPiles];
//Initialize piles with counters
for (int i = 0; i <= numPiles; i++)
piles[i] = randNum(MIN_COUNTERS_PER_PILE, MAX_COUNTERS_PER_PILE);
//Control variables
int currPlayer = 1;
player_type currPlayerType;
bool isGameOver = false;
//Game loop
while (!isGameOver) {
printf("Player %d's turn\n\n", currPlayer);
//Display the piles
for (int i = 0; i <= numPiles; i++) {
printf("Pile %d: ", i + 1);
for (int j = 0; j < piles[i]; j++)
putchar(COUNTER_CHAR);
for (int j = piles[i]; j <= MAX_COUNTERS_PER_PILE; j++)
putchar(' ');
printf("%d\n", piles[i]);
}
putchar('\n');
currPlayerType = (currPlayer - 1) ? player2 : player1;
struct game_data game;
game.numPiles = numPiles;
game.pilesSize = sizeof piles;
game.piles = piles;
struct player_output output;
if (currPlayerType == HUMAN_PLAYER)
output = getUserInput(game);
else if (currPlayerType == AI_PLAYER) {
output = ai(game);
} else {
fputs("Unknown player type detected.", stderr);
exit(-1);
}
//Remove counters from pile
int beforeCounters = piles[output.pile];
piles[output.pile] -= output.countersToRemove;
putchar('\n');
printf(
"Player %d removed %d counters from pile %d.\n"
"Counters: %d -> %d\n\n"
"%s\n",
currPlayer, output.countersToRemove, output.pile + 1,
beforeCounters, piles[output.pile], hl()
);
if (piles[output.pile] < 0)
piles[output.pile] = 0;
//Check if player won
bool existsNonEmptyPile = false;
for (int i = 0; i <= numPiles; i++)
if (piles[i] != 0)
existsNonEmptyPile = true;
if (!existsNonEmptyPile)
isGameOver = true;
if (!isGameOver)
currPlayer = !(currPlayer - 1) + 1; //Toggle active player
}
printf("Congratulations, Player %d! You won the game!\n", currPlayer);
};
| ericw31415/terminal-nim | src/controller.c | C | gpl-3.0 | 5,098 |
/*
* Part of NDLA image-api.
* Copyright (C) 2017 NDLA
*
* See LICENSE
*/
package no.ndla.imageapi.auth
import no.ndla.imageapi.model.AccessDeniedException
import no.ndla.network.AuthUser
trait User {
val authUser: AuthUser
class AuthUser {
def assertHasId(): Unit = userOrClientid()
def userOrClientid(): String = {
if (AuthUser.get.isDefined) {
AuthUser.get.get
} else if (AuthUser.getClientId.isDefined) {
AuthUser.getClientId.get
} else throw new AccessDeniedException("User id or Client id required to perform this operation")
}
}
}
| NDLANO/image-api | src/main/scala/no/ndla/imageapi/auth/User.scala | Scala | gpl-3.0 | 603 |
/*
* 12/21/2008
*
* AbstractCompletion.java - Base class for possible completions.
*
* This library is distributed under a modified BSD license. See the included
* AutoComplete.License.txt file for details.
*/
package com.power.text.autocomplete;
import javax.swing.Icon;
import javax.swing.text.JTextComponent;
/**
* Base class for possible completions. Most, if not all, {@link Completion}
* implementations can extend this class. It remembers the
* <tt>CompletionProvider</tt> that returns this completion, and also implements
* <tt>Comparable</tt>, allowing such completions to be compared
* lexicographically (ignoring case).<p>
*
* This implementation assumes the input text and replacement text are the
* same value. It also returns the input text from its {@link #toString()}
* method (which is what <code>DefaultListCellRenderer</code> uses to render
* objects). Subclasses that wish to override any of this behavior can simply
* override the corresponding method(s) needed to do so.
*
* @author Robert Futrell
* @version 1.0
*/
public abstract class AbstractCompletion implements Completion {
/**
* The provider that created this completion;
*/
private CompletionProvider provider;
/**
* The icon to use for this completion.
*/
private Icon icon;
/**
* The relevance of this completion. Completion instances with higher
* "relevance" values are inserted higher into the list of possible
* completions than those with lower values. Completion instances with
* equal relevance values are sorted alphabetically.
*/
private int relevance;
/**
* Constructor.
*
* @param provider The provider that created this completion.
*/
protected AbstractCompletion(CompletionProvider provider) {
this.provider = provider;
}
/**
* Constructor.
*
* @param provider The provider that created this completion.
* @param icon The icon for this completion.
*/
protected AbstractCompletion(CompletionProvider provider, Icon icon) {
this(provider);
setIcon(icon);
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Completion c2) {
if (c2==this) {
return 0;
}
else if (c2!=null) {
return toString().compareToIgnoreCase(c2.toString());
}
return -1;
}
/**
* {@inheritDoc}
*/
@Override
public String getAlreadyEntered(JTextComponent comp) {
return provider.getAlreadyEnteredText(comp);
}
/**
* {@inheritDoc}
*/
@Override
public Icon getIcon() {
return icon;
}
/**
* Returns the text the user has to (start) typing for this completion
* to be offered. The default implementation simply returns
* {@link #getReplacementText()}.
*
* @return The text the user has to (start) typing for this completion.
* @see #getReplacementText()
*/
@Override
public String getInputText() {
return getReplacementText();
}
/**
* {@inheritDoc}
*/
@Override
public CompletionProvider getProvider() {
return provider;
}
/**
* {@inheritDoc}
*/
@Override
public int getRelevance() {
return relevance;
}
/**
* The default implementation returns <code>null</code>. Subclasses
* can override this method.
*
* @return The tool tip text.
*/
@Override
public String getToolTipText() {
return null;
}
/**
* Sets the icon to use for this completion.
*
* @param icon The icon to use.
* @see #getIcon()
*/
public void setIcon(Icon icon) {
this.icon = icon;
}
/**
* Sets the relevance of this completion.
*
* @param relevance The new relevance of this completion.
* @see #getRelevance()
*/
public void setRelevance(int relevance) {
this.relevance = relevance;
}
/**
* Returns a string representation of this completion. The default
* implementation returns {@link #getInputText()}.
*
* @return A string representation of this completion.
*/
@Override
public String toString() {
return getInputText();
}
} | Thecarisma/powertext | Power Text Code Completion/src/com/power/text/autocomplete/AbstractCompletion.java | Java | gpl-3.0 | 4,104 |
/*********************************************************************************************
*
* 'FlatButton.java, in plugin ummisco.gama.ui.shared, is part of the source code of the GAMA modeling and simulation
* platform. (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package ummisco.gama.ui.controls;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Path;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.TypedListener;
import ummisco.gama.ui.resources.GamaColors;
import ummisco.gama.ui.resources.GamaColors.GamaUIColor;
import ummisco.gama.ui.resources.GamaFonts;
import ummisco.gama.ui.resources.GamaIcons;
import ummisco.gama.ui.views.toolbar.GamaToolbarSimple;
public class FlatButton extends Canvas implements PaintListener, Listener {
public static FlatButton create(final Composite comp, final int style) {
return new FlatButton(comp, style);
}
public static FlatButton label(final Composite comp, final GamaUIColor color, final String text) {
return button(comp, color, text).disabled();
}
public static FlatButton label(final Composite comp, final GamaUIColor color, final String text,
final Image image) {
return label(comp, color, text).setImage(image);
}
public static FlatButton button(final Composite comp, final GamaUIColor color, final String text) {
return create(comp, SWT.None).setText(text).setColor(color);
}
public static FlatButton button(final Composite comp, final GamaUIColor color, final String text,
final Image image) {
return button(comp, color, text).setImage(image);
}
public static FlatButton menu(final Composite comp, final GamaUIColor color, final String text) {
return button(comp, color, text).setImageStyle(IMAGE_RIGHT)
.setImage(GamaIcons.create("small.dropdown").image());
}
private static int FIXED_HEIGHT = 20;
private int height = FIXED_HEIGHT;
private Image image;
private String text;
private RGB colorCode;
private static final int innerMarginWidth = 5;
private static final int imagePadding = 5;
private boolean enabled = true;
private boolean hovered = false;
private boolean down = false;
public static int IMAGE_LEFT = 0;
public static int IMAGE_RIGHT = 1;
private int imageStyle = IMAGE_LEFT;
private FlatButton(final Composite parent, final int style) {
super(parent, style | SWT.DOUBLE_BUFFERED);
setFont(GamaFonts.systemFont);
addPaintListener(this);
addListeners();
}
@Override
public void handleEvent(final Event e) {
switch (e.type) {
case SWT.MouseExit:
doHover(false);
break;
case SWT.MouseMove:
break;
case SWT.MouseEnter:
case SWT.MouseHover:
doHover(true);
e.doit = true;
break;
case SWT.MouseUp:
if (e.button == 1 && getClientArea().contains(e.x, e.y)) {
doButtonUp();
}
break;
case SWT.MouseDown:
if (e.button == 1 && getClientArea().contains(e.x, e.y))
doButtonDown();
break;
default:
;
}
}
/**
* SelectionListeners are notified when the button is clicked
*
* @param listener
*/
public void addSelectionListener(final SelectionListener listener) {
if (listener == null) { return; }
addListener(SWT.Selection, new TypedListener(listener));
}
public void removeSelectionListener(final SelectionListener listener) {
if (listener == null) { return; }
removeListener(SWT.Selection, listener);
}
public void doButtonDown() {
if (!enabled) { return; }
down = true;
redraw();
}
private void doButtonUp() {
if (!enabled) { return; }
final Event e = new Event();
e.item = this;
e.widget = this;
e.type = SWT.Selection;
notifyListeners(SWT.Selection, e);
down = false;
redraw();
}
private void doHover(final boolean hover) {
hovered = hover;
redraw();
}
private void drawBackground(final GC gc, final Rectangle rect) {
setBackground(getParent().getBackground());
final GamaUIColor color = GamaColors.get(colorCode);
final Color background = hovered ? color.lighter() : color.color();
final Color foreground = GamaColors.getTextColorForBackground(background).color();
gc.setForeground(foreground);
gc.setBackground(background);
if (down) {
gc.fillRoundRectangle(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2, 5, 5);
} else {
final Path path = createClipping(rect);
gc.setClipping(path);
gc.fillRectangle(rect);
gc.setClipping((Rectangle) null);
path.dispose();
}
}
private Path createClipping(final Rectangle rect) {
final AdvancedPath path = new AdvancedPath(Display.getCurrent());
path.addRoundRectangle(rect.x, rect.y, rect.width, rect.height, 8, 8);
return path;
}
@Override
public void paintControl(final PaintEvent e) {
// Init GC
final GC gc = e.gc;
gc.setAntialias(SWT.ON);
gc.setAdvanced(true);
gc.setFont(getFont());
final int width = getSize().x;
final int v_inset = (getBounds().height - height) / 2;
final Rectangle rect = new Rectangle(0, v_inset, width, height);
drawBackground(gc, rect);
int x = FlatButton.innerMarginWidth;
int y_image = 0;
final Image image = getImage();
if (image != null) {
y_image += (getBounds().height - image.getBounds().height) / 2;
}
int y_text = 0;
final String text = newText();
if (text != null) {
y_text += (getBounds().height - gc.textExtent(text).y) / 2;
}
if (imageStyle == IMAGE_RIGHT) {
gc.drawText(text, x, y_text, SWT.DRAW_TRANSPARENT);
if (image != null) {
x = rect.width - x - image.getBounds().width;
drawImage(gc, x, y_image);
}
} else {
x = drawImage(gc, x, y_image);
gc.drawText(text, x, y_text, SWT.DRAW_TRANSPARENT);
}
}
private int drawImage(final GC gc, final int x, final int y) {
if (getImage() == null) { return x; }
gc.drawImage(getImage(), x, y);
return x + getImage().getBounds().width + imagePadding;
}
@Override
public Point computeSize(final int wHint, final int hHint, final boolean changed) {
int width = 0;
if (wHint != SWT.DEFAULT) {
width = wHint;
} else {
width = computeMinWidth();
}
final Point result = new Point(width, height);
return result;
}
public int computeMinWidth() {
int width = 0;
final Image image = getImage();
if (image != null) {
final Rectangle bounds = image.getBounds();
width = bounds.width + imagePadding * 2;
}
if (text != null) {
final GC gc = new GC(this);
gc.setFont(getFont());
final Point extent = gc.textExtent(text);
gc.dispose();
width += extent.x + FlatButton.innerMarginWidth;
}
return width;
}
public String newText() {
if (text == null) { return null; }
final int parentWidth = getParent().getBounds().width;
final int width = computeMinWidth();
if (parentWidth < width) {
int imageWidth = 0;
final Image image = getImage();
if (image != null) {
final Rectangle bounds = image.getBounds();
imageWidth = bounds.width + imagePadding;
}
final float r = (float) (parentWidth - imageWidth) / (float) width;
final int nbChars = text.length();
final int newNbChars = Math.max(0, (int) (nbChars * r));
final String newText =
text.substring(0, newNbChars / 2) + "..." + text.substring(nbChars - newNbChars / 2, nbChars);
return newText;
}
return text;
}
/**
* This is an image that will be displayed to the side of the text inside the button (if any). By default the image
* will be to the left of the text; however, setImageStyle can be used to specify that it's either to the right or
* left. If there is no text, the image will be centered inside the button.
*
* @param image
*/
public FlatButton setImage(final Image image) {
if (this.image == image) { return this; }
this.image = image;
redraw();
return this;
}
/**
* Set the style with which the side image is drawn, either IMAGE_LEFT or IMAGE_RIGHT (default is IMAGE_LEFT).
*
* @param imageStyle
*/
public FlatButton setImageStyle(final int imageStyle) {
this.imageStyle = imageStyle;
return this;
}
public int getImageStyle() {
return imageStyle;
}
public String getText() {
return text;
}
public FlatButton setText(final String text) {
if (text == null) { return this; }
if (text.equals(this.text)) { return this; }
this.text = text;
redraw();
return this;
}
private void addListeners() {
addListener(SWT.MouseDown, this);
addListener(SWT.MouseExit, this);
addListener(SWT.MouseEnter, this);
addListener(SWT.MouseHover, this);
addListener(SWT.MouseUp, this);
addListener(SWT.MouseMove, this);
}
@Override
public void setEnabled(final boolean enabled) {
final boolean oldSetting = this.enabled;
this.enabled = enabled;
if (oldSetting != enabled) {
if (enabled) {
addListeners();
} else {
removeListener(SWT.MouseDown, (Listener) this);
removeListener(SWT.MouseExit, (Listener) this);
removeListener(SWT.MouseEnter, (Listener) this);
removeListener(SWT.MouseHover, (Listener) this);
removeListener(SWT.MouseUp, (Listener) this);
removeListener(SWT.MouseMove, (Listener) this);
}
redraw();
}
}
public ToolItem item() {
if (getParent() instanceof GamaToolbarSimple) {
final GamaToolbarSimple p = (GamaToolbarSimple) getParent();
return p.control(this, computeSize(SWT.DEFAULT, height, false).x + 4);
}
final ToolItem t = new ToolItem((ToolBar) getParent(), SWT.SEPARATOR);
final int width = this.computeSize(SWT.DEFAULT, height, false).x + 4;
t.setControl(this);
t.setWidth(width);
return t;
}
public FlatButton disabled() {
setEnabled(false);
return this;
}
public FlatButton enabled() {
setEnabled(true);
return this;
}
public FlatButton light() {
return this;
}
public FlatButton small() {
if (height == 20) { return this; }
height = 20;
redraw();
return this;
}
public FlatButton setColor(final GamaUIColor c) {
final RGB oldColorCode = colorCode;
final RGB newColorCode = c.getRGB();
if (newColorCode.equals(oldColorCode)) { return this; }
colorCode = c.getRGB();
redraw();
return this;
}
public int getHeight() {
return height;
}
public GamaUIColor getColor() {
return GamaColors.get(colorCode);
}
public Image getImage() {
return image;
}
} | SonTG/gama | ummisco.gama.ui.shared/src/ummisco/gama/ui/controls/FlatButton.java | Java | gpl-3.0 | 11,010 |
<?php
/*
* Photoframed, custom photoframe software
* Copyright (C) 2009-2010
* 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/>.
*/
session_start();
require_once("init.php");
if ($settings['rss.random'])
{
$old = (isset($_SESSION['rss.current']) ? $_SESSION['rss.current'] : 0);
do
{
$current = rand(0, count($settings['rss.feeds']) - 1);
} while ($current != $old && count($settings['rss.feeds']) > 1);
} else
{
$current = (isset($_SESSION['rss.current']) ? $_SESSION['rss.current'] + 1 : 0);
if ($current >= count($settings['rss.feeds'])) {
$current = 0;
}
}
$_SESSION['rss.current'] = $current;
// choose a RSS host
$feed = $settings['rss.feeds'][$current];
$cache = 'cache/' . $feed['cache'];
// load news file if older than 15 minutes
$time = file_exists($cache) ? filemtime($cache) : 0;
if ($time + 5 * 60 < time())
{
try
{
$context = stream_context_create(array('http' => array('timeout' => 2)));
$xml = file_get_contents($feed['url'], 0, $context);
if (empty($xml)) throw new Exception('empty xml');
$file = fopen($cache, "w");
fwrite($file, $xml);
fclose($file);
}
catch (Exception $e)
{
$xml = file_get_contents($cache);
}
}
else
{
$xml = file_get_contents($cache);
}
$data = simplexml_load_string($xml);
echo('<div class="holder logo"><div class="center">');
echo('<img src="' . $feed["logo"] . '""/>');
echo('</div></div>');
if (empty($data->channel->item))
{
@unlink($cache);
echo('<div class="holder"><div class="center">');
echo('<ul><li>' . $settings['rss.error_message'] . '</li></ul>');
echo('</div></div>');
exit();
}
$dataArray = array();
foreach ($data->channel->item as $item) {
$text = (isset($feed['all']) && $feed['all'] ? $item->description : $item->title);
if (empty($feed['adexp']) || !preg_match($feed['adexp'], $text)) {
$dataArray[] = array('text'=>$text, 'url'=>$item->link);
}
}
$lists = array_chunk($dataArray, isset($feed['listcount']) ? $feed['listcount'] : 3);
foreach ($lists as $list)
{
$customWidth = (isset($feed['width']) ? ' style="width: ' . $feed['width'] . '"' : '');
$noWrap = (isset($feed['nowrap']) && $feed['nowrap'] ? ' nowrap' : '');
echo('<div class="holder quote' . $noWrap . '"' . $customWidth . '><div class="center">');
echo('<ul>');
foreach ($list as $item)
{
$html = $item['text'];
if (!empty($item['url']))
{
$html = '<a href="' . $item['url'] . '" target="_blank">' . $html . '</a>';
}
echo('<li>' . $html . '</li>');
}
echo('</ul>');
echo('</div></div>');
}
| djneo92nl/photoframed | quote.php | PHP | gpl-3.0 | 3,232 |
/*
TiMidity++ -- MIDI to WAVE converter and player
Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
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
*/
#ifndef SYSDEP_H_INCLUDED
#define SYSDEP_H_INCLUDED 1
#include <limits.h>
#define DEFAULT_AUDIO_BUFFER_BITS 12
#define SAMPLE_LENGTH_BITS 32
#include <stdint.h> // int types are defined here
#include "t_swap.h"
namespace TimidityPlus
{
/* Instrument files are little-endian, MIDI files big-endian, so we
need to do some conversions. */
#define XCHG_SHORT(x) ((((x)&0xFF)<<8) | (((x)>>8)&0xFF))
#define LE_SHORT(x) LittleShort(x)
#define LE_LONG(x) LittleLong(x)
#define BE_SHORT(x) BigShort(x)
#define BE_LONG(x) BigLong(x)
/* max_channels is defined in "timidity.h" */
typedef struct _ChannelBitMask
{
uint32_t b; /* 32-bit bitvector */
} ChannelBitMask;
#define CLEAR_CHANNELMASK(bits) ((bits).b = 0)
#define FILL_CHANNELMASK(bits) ((bits).b = ~0)
#define IS_SET_CHANNELMASK(bits, c) ((bits).b & (1u << (c)))
#define SET_CHANNELMASK(bits, c) ((bits).b |= (1u << (c)))
#define UNSET_CHANNELMASK(bits, c) ((bits).b &= ~(1u << (c)))
#define TOGGLE_CHANNELMASK(bits, c) ((bits).b ^= (1u << (c)))
#define COPY_CHANNELMASK(dest, src) ((dest).b = (src).b)
#define REVERSE_CHANNELMASK(bits) ((bits).b = ~(bits).b)
#define COMPARE_CHANNELMASK(bitsA, bitsB) ((bitsA).b == (bitsB).b)
typedef int16_t sample_t;
typedef int32_t final_volume_t;
# define FINAL_VOLUME(v) (v)
# define MAX_AMP_VALUE ((1<<(AMP_BITS+1))-1)
#define MIN_AMP_VALUE (MAX_AMP_VALUE >> 9)
typedef uint32_t splen_t;
#define SPLEN_T_MAX (splen_t)((uint32_t)0xFFFFFFFF)
# define TIM_FSCALE(a,b) ((a) * (double)(1<<(b)))
# define TIM_FSCALENEG(a,b) ((a) * (1.0 / (double)(1<<(b))))
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif /* M_PI */
#if defined(_MSC_VER)
#define strncasecmp(a,b,c) _strnicmp((a),(b),(c))
#define strcasecmp(a,b) _stricmp((a),(b))
#endif /* _MSC_VER */
#define SAFE_CONVERT_LENGTH(len) (6 * (len) + 1)
}
#endif /* SYSDEP_H_INCUDED */
| Xane123/MaryMagicalAdventure | libraries/timidityplus/timiditypp/sysdep.h | C | gpl-3.0 | 2,760 |
package eu.siacs.conversations.entities;
import android.content.ContentValues;
import android.database.Cursor;
import net.java.otr4j.OtrException;
import net.java.otr4j.crypto.OtrCryptoException;
import net.java.otr4j.session.SessionID;
import net.java.otr4j.session.SessionImpl;
import net.java.otr4j.session.SessionStatus;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.interfaces.DSAPublicKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.xmpp.chatstate.ChatState;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
public class Conversation extends AbstractEntity implements Blockable {
public static final String TABLENAME = "conversations";
public static final int STATUS_AVAILABLE = 0;
public static final int STATUS_ARCHIVED = 1;
public static final int STATUS_DELETED = 2;
public static final int MODE_MULTI = 1;
public static final int MODE_SINGLE = 0;
public static final String NAME = "name";
public static final String ACCOUNT = "accountUuid";
public static final String CONTACT = "contactUuid";
public static final String CONTACTJID = "contactJid";
public static final String STATUS = "status";
public static final String CREATED = "created";
public static final String MODE = "mode";
public static final String ATTRIBUTES = "attributes";
public static final String ATTRIBUTE_NEXT_ENCRYPTION = "next_encryption";
public static final String ATTRIBUTE_MUC_PASSWORD = "muc_password";
public static final String ATTRIBUTE_MUTED_TILL = "muted_till";
public static final String ATTRIBUTE_LAST_MESSAGE_TRANSMITTED = "last_message_transmitted";
private String name;
private String contactUuid;
private String accountUuid;
private Jid contactJid;
private int status;
private long created;
private int mode;
private JSONObject attributes = new JSONObject();
private Jid nextCounterpart;
protected final ArrayList<Message> messages = new ArrayList<>();
protected Account account = null;
private transient SessionImpl otrSession;
private transient String otrFingerprint = null;
private Smp mSmp = new Smp();
private String nextMessage;
private transient MucOptions mucOptions = null;
private byte[] symmetricKey;
private Bookmark bookmark;
private boolean messagesLeftOnServer = true;
private ChatState mOutgoingChatState = Config.DEFAULT_CHATSTATE;
private ChatState mIncomingChatState = Config.DEFAULT_CHATSTATE;
private String mLastReceivedOtrMessageId = null;
public boolean hasMessagesLeftOnServer() {
return messagesLeftOnServer;
}
public void setHasMessagesLeftOnServer(boolean value) {
this.messagesLeftOnServer = value;
}
public Message findUnsentMessageWithUuid(String uuid) {
synchronized(this.messages) {
for (final Message message : this.messages) {
final int s = message.getStatus();
if ((s == Message.STATUS_UNSEND || s == Message.STATUS_WAITING) && message.getUuid().equals(uuid)) {
return message;
}
}
}
return null;
}
public void findWaitingMessages(OnMessageFound onMessageFound) {
synchronized (this.messages) {
for(Message message : this.messages) {
if (message.getStatus() == Message.STATUS_WAITING) {
onMessageFound.onMessageFound(message);
}
}
}
}
public void findUnreadMessages(OnMessageFound onMessageFound) {
synchronized (this.messages) {
for(Message message : this.messages) {
if (!message.isRead()) {
onMessageFound.onMessageFound(message);
}
}
}
}
public void findMessagesWithFiles(final OnMessageFound onMessageFound) {
synchronized (this.messages) {
for (final Message message : this.messages) {
if ((message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE)
&& message.getEncryption() != Message.ENCRYPTION_PGP) {
onMessageFound.onMessageFound(message);
}
}
}
}
public Message findMessageWithFileAndUuid(final String uuid) {
synchronized (this.messages) {
for (final Message message : this.messages) {
if ((message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE)
&& message.getEncryption() != Message.ENCRYPTION_PGP
&& message.getUuid().equals(uuid)) {
return message;
}
}
}
return null;
}
public void clearMessages() {
synchronized (this.messages) {
this.messages.clear();
}
}
public boolean setIncomingChatState(ChatState state) {
if (this.mIncomingChatState == state) {
return false;
}
this.mIncomingChatState = state;
return true;
}
public ChatState getIncomingChatState() {
return this.mIncomingChatState;
}
public boolean setOutgoingChatState(ChatState state) {
if (mode == MODE_MULTI) {
return false;
}
if (this.mOutgoingChatState != state) {
this.mOutgoingChatState = state;
return true;
} else {
return false;
}
}
public ChatState getOutgoingChatState() {
return this.mOutgoingChatState;
}
public void trim() {
synchronized (this.messages) {
final int size = messages.size();
final int maxsize = Config.PAGE_SIZE * Config.MAX_NUM_PAGES;
if (size > maxsize) {
this.messages.subList(0, size - maxsize).clear();
}
}
}
public void findUnsentMessagesWithEncryption(int encryptionType, OnMessageFound onMessageFound) {
synchronized (this.messages) {
for (Message message : this.messages) {
if ((message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_WAITING)
&& (message.getEncryption() == encryptionType)) {
onMessageFound.onMessageFound(message);
}
}
}
}
public void findUnsentTextMessages(OnMessageFound onMessageFound) {
synchronized (this.messages) {
for (Message message : this.messages) {
if (message.getType() != Message.TYPE_IMAGE
&& message.getStatus() == Message.STATUS_UNSEND) {
onMessageFound.onMessageFound(message);
}
}
}
}
public Message findSentMessageWithUuidOrRemoteId(String id) {
synchronized (this.messages) {
for (Message message : this.messages) {
if (id.equals(message.getUuid())
|| (message.getStatus() >= Message.STATUS_SEND
&& id.equals(message.getRemoteMsgId()))) {
return message;
}
}
}
return null;
}
public Message findSentMessageWithUuid(String id) {
synchronized (this.messages) {
for (Message message : this.messages) {
if (id.equals(message.getUuid())) {
return message;
}
}
}
return null;
}
public void populateWithMessages(final List<Message> messages) {
synchronized (this.messages) {
messages.clear();
messages.addAll(this.messages);
}
for(Iterator<Message> iterator = messages.iterator(); iterator.hasNext();) {
if (iterator.next().wasMergedIntoPrevious()) {
iterator.remove();
}
}
}
@Override
public boolean isBlocked() {
return getContact().isBlocked();
}
@Override
public boolean isDomainBlocked() {
return getContact().isDomainBlocked();
}
@Override
public Jid getBlockedJid() {
return getContact().getBlockedJid();
}
public String getLastReceivedOtrMessageId() {
return this.mLastReceivedOtrMessageId;
}
public void setLastReceivedOtrMessageId(String id) {
this.mLastReceivedOtrMessageId = id;
}
public int countMessages() {
synchronized (this.messages) {
return this.messages.size();
}
}
public interface OnMessageFound {
void onMessageFound(final Message message);
}
public Conversation(final String name, final Account account, final Jid contactJid,
final int mode) {
this(java.util.UUID.randomUUID().toString(), name, null, account
.getUuid(), contactJid, System.currentTimeMillis(),
STATUS_AVAILABLE, mode, "");
this.account = account;
}
public Conversation(final String uuid, final String name, final String contactUuid,
final String accountUuid, final Jid contactJid, final long created, final int status,
final int mode, final String attributes) {
this.uuid = uuid;
this.name = name;
this.contactUuid = contactUuid;
this.accountUuid = accountUuid;
this.contactJid = contactJid;
this.created = created;
this.status = status;
this.mode = mode;
try {
this.attributes = new JSONObject(attributes == null ? "" : attributes);
} catch (JSONException e) {
this.attributes = new JSONObject();
}
}
public boolean isRead() {
return (this.messages.size() == 0) || this.messages.get(this.messages.size() - 1).isRead();
}
public List<Message> markRead() {
final List<Message> unread = new ArrayList<>();
synchronized (this.messages) {
for(Message message : this.messages) {
if (!message.isRead()) {
message.markRead();
unread.add(message);
}
}
}
return unread;
}
public Message getLatestMarkableMessage() {
for (int i = this.messages.size() - 1; i >= 0; --i) {
if (this.messages.get(i).getStatus() <= Message.STATUS_RECEIVED
&& this.messages.get(i).markable) {
if (this.messages.get(i).isRead()) {
return null;
} else {
return this.messages.get(i);
}
}
}
return null;
}
public Message getLatestMessage() {
if (this.messages.size() == 0) {
Message message = new Message(this, "", Message.ENCRYPTION_NONE);
message.setTime(getCreated());
return message;
} else {
Message message = this.messages.get(this.messages.size() - 1);
message.setConversation(this);
return message;
}
}
public String getName() {
if (getMode() == MODE_MULTI) {
if (getMucOptions().getSubject() != null) {
return getMucOptions().getSubject();
} else if (bookmark != null && bookmark.getBookmarkName() != null) {
return bookmark.getBookmarkName();
} else {
String generatedName = getMucOptions().createNameFromParticipants();
if (generatedName != null) {
return generatedName;
} else {
return getJid().getLocalpart();
}
}
} else {
return this.getContact().getDisplayName();
}
}
public String getAccountUuid() {
return this.accountUuid;
}
public Account getAccount() {
return this.account;
}
public Contact getContact() {
return this.account.getRoster().getContact(this.contactJid);
}
public void setAccount(final Account account) {
this.account = account;
}
@Override
public Jid getJid() {
return this.contactJid;
}
public int getStatus() {
return this.status;
}
public long getCreated() {
return this.created;
}
public ContentValues getContentValues() {
ContentValues values = new ContentValues();
values.put(UUID, uuid);
values.put(NAME, name);
values.put(CONTACT, contactUuid);
values.put(ACCOUNT, accountUuid);
values.put(CONTACTJID, contactJid.toString());
values.put(CREATED, created);
values.put(STATUS, status);
values.put(MODE, mode);
values.put(ATTRIBUTES, attributes.toString());
return values;
}
public static Conversation fromCursor(Cursor cursor) {
Jid jid;
try {
jid = Jid.fromString(cursor.getString(cursor.getColumnIndex(CONTACTJID)), true);
} catch (final InvalidJidException e) {
// Borked DB..
jid = null;
}
return new Conversation(cursor.getString(cursor.getColumnIndex(UUID)),
cursor.getString(cursor.getColumnIndex(NAME)),
cursor.getString(cursor.getColumnIndex(CONTACT)),
cursor.getString(cursor.getColumnIndex(ACCOUNT)),
jid,
cursor.getLong(cursor.getColumnIndex(CREATED)),
cursor.getInt(cursor.getColumnIndex(STATUS)),
cursor.getInt(cursor.getColumnIndex(MODE)),
cursor.getString(cursor.getColumnIndex(ATTRIBUTES)));
}
public void setStatus(int status) {
this.status = status;
}
public int getMode() {
return this.mode;
}
public void setMode(int mode) {
this.mode = mode;
}
public SessionImpl startOtrSession(String presence, boolean sendStart) {
if (this.otrSession != null) {
return this.otrSession;
} else {
final SessionID sessionId = new SessionID(this.getJid().toBareJid().toString(),
presence,
"xmpp");
this.otrSession = new SessionImpl(sessionId, getAccount().getOtrService());
try {
if (sendStart) {
this.otrSession.startSession();
return this.otrSession;
}
return this.otrSession;
} catch (OtrException e) {
return null;
}
}
}
public SessionImpl getOtrSession() {
return this.otrSession;
}
public void resetOtrSession() {
this.otrFingerprint = null;
this.otrSession = null;
this.mSmp.hint = null;
this.mSmp.secret = null;
this.mSmp.status = Smp.STATUS_NONE;
}
public Smp smp() {
return mSmp;
}
public void startOtrIfNeeded() {
if (this.otrSession != null
&& this.otrSession.getSessionStatus() != SessionStatus.ENCRYPTED) {
try {
this.otrSession.startSession();
} catch (OtrException e) {
this.resetOtrSession();
}
}
}
public boolean endOtrIfNeeded() {
if (this.otrSession != null) {
if (this.otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
try {
this.otrSession.endSession();
this.resetOtrSession();
return true;
} catch (OtrException e) {
this.resetOtrSession();
return false;
}
} else {
this.resetOtrSession();
return false;
}
} else {
return false;
}
}
public boolean hasValidOtrSession() {
return this.otrSession != null;
}
public synchronized String getOtrFingerprint() {
if (this.otrFingerprint == null) {
try {
if (getOtrSession() == null || getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
return null;
}
DSAPublicKey remotePubKey = (DSAPublicKey) getOtrSession().getRemotePublicKey();
this.otrFingerprint = getAccount().getOtrService().getFingerprint(remotePubKey);
} catch (final OtrCryptoException | UnsupportedOperationException ignored) {
return null;
}
}
return this.otrFingerprint;
}
public boolean verifyOtrFingerprint() {
final String fingerprint = getOtrFingerprint();
if (fingerprint != null) {
getContact().addOtrFingerprint(fingerprint);
return true;
} else {
return false;
}
}
public boolean isOtrFingerprintVerified() {
return getContact().getOtrFingerprints().contains(getOtrFingerprint());
}
/**
* short for is Private and Non-anonymous
*/
public boolean isPnNA() {
return mode == MODE_SINGLE || (getMucOptions().membersOnly() && getMucOptions().nonanonymous());
}
public synchronized MucOptions getMucOptions() {
if (this.mucOptions == null) {
this.mucOptions = new MucOptions(this);
}
return this.mucOptions;
}
public void resetMucOptions() {
this.mucOptions = null;
}
public void setContactJid(final Jid jid) {
this.contactJid = jid;
}
public void setNextCounterpart(Jid jid) {
this.nextCounterpart = jid;
}
public Jid getNextCounterpart() {
return this.nextCounterpart;
}
private int getMostRecentlyUsedOutgoingEncryption() {
synchronized (this.messages) {
for(int i = this.messages.size() -1; i >= 0; --i) {
final Message m = this.messages.get(i);
if (!m.isCarbon() && m.getStatus() != Message.STATUS_RECEIVED) {
final int e = m.getEncryption();
if (e == Message.ENCRYPTION_DECRYPTED || e == Message.ENCRYPTION_DECRYPTION_FAILED) {
return Message.ENCRYPTION_PGP;
} else {
return e;
}
}
}
}
return Message.ENCRYPTION_NONE;
}
private int getMostRecentlyUsedIncomingEncryption() {
synchronized (this.messages) {
for(int i = this.messages.size() -1; i >= 0; --i) {
final Message m = this.messages.get(i);
if (m.getStatus() == Message.STATUS_RECEIVED) {
final int e = m.getEncryption();
if (e == Message.ENCRYPTION_DECRYPTED || e == Message.ENCRYPTION_DECRYPTION_FAILED) {
return Message.ENCRYPTION_PGP;
} else {
return e;
}
}
}
}
return Message.ENCRYPTION_NONE;
}
public int getNextEncryption() {
int next = this.getIntAttribute(ATTRIBUTE_NEXT_ENCRYPTION, -1);
if (next == -1) {
int outgoing = this.getMostRecentlyUsedOutgoingEncryption();
if (outgoing == Message.ENCRYPTION_NONE) {
return this.getMostRecentlyUsedIncomingEncryption();
} else {
return outgoing;
}
}
return next;
}
public void setNextEncryption(int encryption) {
this.setAttribute(ATTRIBUTE_NEXT_ENCRYPTION, String.valueOf(encryption));
}
public String getNextMessage() {
if (this.nextMessage == null) {
return "";
} else {
return this.nextMessage;
}
}
public boolean smpRequested() {
return smp().status == Smp.STATUS_CONTACT_REQUESTED;
}
public void setNextMessage(String message) {
this.nextMessage = message;
}
public void setSymmetricKey(byte[] key) {
this.symmetricKey = key;
}
public byte[] getSymmetricKey() {
return this.symmetricKey;
}
public void setBookmark(Bookmark bookmark) {
this.bookmark = bookmark;
this.bookmark.setConversation(this);
}
public void deregisterWithBookmark() {
if (this.bookmark != null) {
this.bookmark.setConversation(null);
}
}
public Bookmark getBookmark() {
return this.bookmark;
}
public boolean hasDuplicateMessage(Message message) {
synchronized (this.messages) {
for (int i = this.messages.size() - 1; i >= 0; --i) {
if (this.messages.get(i).equals(message)) {
return true;
}
}
}
return false;
}
public Message findSentMessageWithBody(String body) {
synchronized (this.messages) {
for (int i = this.messages.size() - 1; i >= 0; --i) {
Message message = this.messages.get(i);
if ((message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) && message.getBody() != null && message.getBody().equals(body)) {
return message;
}
}
return null;
}
}
public void resetLastMessageTransmitted() {
this.setAttribute(ATTRIBUTE_LAST_MESSAGE_TRANSMITTED,String.valueOf(-1));
}
public boolean setLastMessageTransmitted(long value) {
long before = getLastMessageTransmitted();
if (value - before > 1000) {
this.setAttribute(ATTRIBUTE_LAST_MESSAGE_TRANSMITTED, String.valueOf(value));
return true;
} else {
return false;
}
}
public long getLastMessageTransmitted() {
long timestamp = getLongAttribute(ATTRIBUTE_LAST_MESSAGE_TRANSMITTED,0);
if (timestamp == 0) {
synchronized (this.messages) {
for(int i = this.messages.size() - 1; i >= 0; --i) {
Message message = this.messages.get(i);
if (message.getStatus() == Message.STATUS_RECEIVED) {
return message.getTimeSent();
}
}
}
}
return timestamp;
}
public void setMutedTill(long value) {
this.setAttribute(ATTRIBUTE_MUTED_TILL, String.valueOf(value));
}
public boolean isMuted() {
return System.currentTimeMillis() < this.getLongAttribute(ATTRIBUTE_MUTED_TILL, 0);
}
public boolean setAttribute(String key, String value) {
try {
this.attributes.put(key, value);
return true;
} catch (JSONException e) {
return false;
}
}
public String getAttribute(String key) {
try {
return this.attributes.getString(key);
} catch (JSONException e) {
return null;
}
}
public int getIntAttribute(String key, int defaultValue) {
String value = this.getAttribute(key);
if (value == null) {
return defaultValue;
} else {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return defaultValue;
}
}
}
public long getLongAttribute(String key, long defaultValue) {
String value = this.getAttribute(key);
if (value == null) {
return defaultValue;
} else {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
return defaultValue;
}
}
}
public void add(Message message) {
message.setConversation(this);
synchronized (this.messages) {
this.messages.add(message);
}
}
public void addAll(int index, List<Message> messages) {
synchronized (this.messages) {
this.messages.addAll(index, messages);
}
}
public void sort() {
synchronized (this.messages) {
Collections.sort(this.messages, new Comparator<Message>() {
@Override
public int compare(Message left, Message right) {
if (left.getTimeSent() < right.getTimeSent()) {
return -1;
} else if (left.getTimeSent() > right.getTimeSent()) {
return 1;
} else {
return 0;
}
}
});
for(Message message : this.messages) {
message.untie();
}
}
}
public int unreadCount() {
synchronized (this.messages) {
int count = 0;
for(int i = this.messages.size() - 1; i >= 0; --i) {
if (this.messages.get(i).isRead()) {
return count;
}
++count;
}
return count;
}
}
public class Smp {
public static final int STATUS_NONE = 0;
public static final int STATUS_CONTACT_REQUESTED = 1;
public static final int STATUS_WE_REQUESTED = 2;
public static final int STATUS_FAILED = 3;
public static final int STATUS_VERIFIED = 4;
public String secret = null;
public String hint = null;
public int status = 0;
}
}
| whereau/where | src/main/java/com/way/where/entities/Conversation.java | Java | gpl-3.0 | 21,045 |
Documentation
=============
Project documentation is built using [Sphinx docs](http://sphinx-doc.org/), which uses [ReST](http://docutils.sf.net/rst.html) for markup. This allows the docs to cover a vast amount of topics without using a thousand-line README file.
Sphinx docs is pip-installable via `pip install sphinx`. Once installed, open a command line in the docs folder and run `make html`; the output files will be placed in the `_build/html/` directory, and can be browsed (locally) with any browser.
The docs can also be found online at http://bootstrap-datepicker.readthedocs.org/.
| Rih/transruta | code/template/datepicker/docs/REAME.md | Markdown | gpl-3.0 | 605 |
/*
* Copyright (C) 2011-2013 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2013 MaNGOS <http://getmangos.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/>.
*/
/* Script Data Start
SFName: Boss Glubtok
SFAuthor: JeanClaude
SF%Complete: 30
SFComment: TODO: clean up door events and 2 fix warnings@lines(140,146,184)
SFCategory: dungeon script
Script Data End */
#include "ScriptPCH.h"
#include "SpellScript.h"
#include "SpellAuraEffects.h"
#include "GameObject.h"
#include "deadmines.h"
enum Spells
{
//Glubtok these need checked http://www.wowhead.com/npc=47162#abilities
SPELL_FIRE_BLOSSOM = 88129, // Fireball explodes on the ground
SPELL_FROST_BLOSSOM = 88169, // Iceball explodes on the ground
SPELL_ARCANE_POWER = 88009, // Spell Phase 2
SPELL_FIST_OF_FLAME = 87859, // elemental_fists
SPELL_FIST_OF_FROST = 87861, // elemental_fists
SPELL_BLINK = 87925 // correct Blink spell
};
// Aggro start
#define SAY_AGGRO "Glubtok show you da power of de Arcane."
#define SOUND_AGGRO 21151
// Aggro End
// On Kill Start
#define SAY_KILL "Ha..Ha..Ha..Ha..Ah!"
#define SOUND_KILL 21152
// On Kill End
// Fist of Flame
#define SAY_FISTS_OF_FLAME "Fists of Flame!"
#define SOUND_FISTS_OF_FLAME 21153
// End Flames
// Fist Of Frost!!!!! :D
#define SAY_FISTS_OF_FROST "Fists of Frost!"
#define SOUND_FISTS_OF_FROST 21156
// Phase 2 Sounds And Texts
// "Glubtok ready?"
#define SAY_READY "Glubtok ready?"
#define SOUND_READY 21154
//
#define SAY_LETS_DO_IT "Let's do it!"
#define SOUND_LETS_DO_IT 21157
// ARCANE POWER!!!!!!!!!! :D
#define SAY_ARCANE_POWER "ARCANE POWER"
#define SOUND_ARCANE_POWER 21146
// On Death!
#define SAY_TOO_MUCH_POWER "TOO... MUCH... POWER"
#define SOUND_TOO_MUCH_POWER 21145
#define SAY_FLAME "Elemental Fists!"
/*
#define SAY_AGGRO "Let's do it!"
#define SAY_DIED "'Sploded dat one!"
#define SAY_FLAME "Elemental Fists!"
#define SAY_ARCANE "Glubtok show you da power of arcane!"
*/
#define spell_elemental_fists RAND(87859, 91273)
const Position pos[1] =
{
{-192.328003f, -450.244995f, 54.521500f, 0.00f}
};
enum Phases
{
PHASE_NORMAL = 1,
PHASE_50_PERCENT = 2,
};
class boss_glubtok : public CreatureScript
{
public:
boss_glubtok() : CreatureScript("boss_glubtok") {}
struct boss_glubtokAI : public ScriptedAI
{
boss_glubtokAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
}
InstanceScript* instance;
uint8 Phase;
uint32 phase;
uint32 SpellTimer;
uint32 elemental_fists;
uint32 ArcanePowerTimer;
uint32 blinkTimer;
uint32 PhaseChangeTimer;
uint32 NormalCastTimer;
uint8 BlossomSpell;
bool Phased;
void Reset()
{
Phased = false;
Phase = PHASE_NORMAL;
phase = 1;
SpellTimer = urand(10*IN_MILLISECONDS, 25*IN_MILLISECONDS);
elemental_fists = 20000;
blinkTimer = 12000;
NormalCastTimer = 3000;
}
void EnterCombat(Unit* /*who*/)
{
me->MonsterYell(SAY_AGGRO, LANGUAGE_UNIVERSAL, 0);
DoPlaySoundToSet(me, SOUND_AGGRO);
}
void JustDied(Unit* /*Killer*/)
{
me->MonsterYell(SAY_TOO_MUCH_POWER, LANGUAGE_UNIVERSAL, 0);
DoPlaySoundToSet(me, SOUND_TOO_MUCH_POWER);
}
void KilledUnit(Unit* Victim)
{
me->MonsterYell(SAY_KILL, LANGUAGE_UNIVERSAL, 0);
DoPlaySoundToSet(me, SOUND_KILL);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
if (phase == 1)
{
if (SpellTimer <= diff)
{
switch(urand(0, 1))
{
case 0:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(me, SPELL_FIST_OF_FLAME);
me->MonsterYell(SAY_FISTS_OF_FLAME, LANGUAGE_UNIVERSAL, 0);
DoPlaySoundToSet(me, SOUND_FISTS_OF_FLAME);
break;
case 1:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(me, SPELL_FIST_OF_FROST);
me->MonsterYell(SAY_FISTS_OF_FROST, LANGUAGE_UNIVERSAL, 0);
DoPlaySoundToSet(me, SOUND_FISTS_OF_FROST);
break;
}
SpellTimer = urand(10*IN_MILLISECONDS, 25*IN_MILLISECONDS);
} else SpellTimer -= diff;
if (HealthBelowPct(50))
{
phase = 2;
DoCast(me, SPELL_ARCANE_POWER);
me->MonsterYell(SAY_ARCANE_POWER, LANGUAGE_UNIVERSAL, 0);
DoPlaySoundToSet(me, SOUND_ARCANE_POWER);
}
DoMeleeAttackIfReady();
}
else
{
if (SpellTimer <= diff)
{
DoCast(me, urand(1, 2) == 1 ? SPELL_FROST_BLOSSOM : SPELL_FIRE_BLOSSOM);
SpellTimer = urand(10*IN_MILLISECONDS, 25*IN_MILLISECONDS);
} else SpellTimer -= diff;
}
if (PhaseChangeTimer <= diff && Phase == PHASE_NORMAL)
{
if (PhaseChangeTimer<= diff)
{
me->SetReactState(REACT_AGGRESSIVE);
elemental_fists = 20000;
blinkTimer = 12000;
Phase = PHASE_NORMAL;
} else PhaseChangeTimer -= diff;
if (elemental_fists <= diff && Phase == PHASE_NORMAL)
{
if (elemental_fists<= diff)
{
DoCast(me, elemental_fists);
me->MonsterYell(SAY_FLAME, LANGUAGE_UNIVERSAL, NULL);
elemental_fists = 20000;
} else elemental_fists -= diff;
}
if (blinkTimer <= diff && Phase == PHASE_NORMAL)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1,10.0f, true))
DoCast(me, SPELL_BLINK);
blinkTimer = 12000;
} else blinkTimer -= diff;
DoMeleeAttackIfReady();
}
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_glubtokAI(creature);
}
};
void AddSC_boss_glubtok()
{
new boss_glubtok();
}
| Crash911/RaptoredSkyFire | src/server/scripts/EasternKingdoms/Deadmines/boss_glubtok.cpp | C++ | gpl-3.0 | 7,827 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Description of imgs_spec_ratio2E0fO</title>
<meta name="keywords" content="imgs_spec_ratio2E0fO">
<meta name="description" content="imgs_spec_ratio2E0fO - estimate characteristic e^- energy and depletion of O">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="generator" content="m2html © 2003 Guillaume Flandin">
<meta name="robots" content="index, follow">
<link type="text/css" rel="stylesheet" href="../m2html.css">
</head>
<body>
<a name="_top"></a>
<!-- menu.html Imgtools -->
<h1>imgs_spec_ratio2E0fO
</h1>
<h2><a name="_name"></a>PURPOSE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="box"><strong>imgs_spec_ratio2E0fO - estimate characteristic e^- energy and depletion of O</strong></div>
<h2><a name="_synopsis"></a>SYNOPSIS <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="box"><strong>function [img_E0,img_fO] = imgs_spec_ratio2E0fO(img4278,img6300,img8446,img4278b) </strong></div>
<h2><a name="_description"></a>DESCRIPTION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="fragment"><pre class="comment"> imgs_spec_ratio2E0fO - estimate characteristic e^- energy and depletion of O
By the method of Strickland, Hecht, Christensen and Meyer [] from
images at 4278, 6300 and 8446 A.
Calling:
[img_E0,img_fO] = imgs_spec_ratio2E0fO(img4278,img6300,img8446,img4278b)
Output parameters:
IMG_E0 - image of characteristic electron energy
IMG_FO - image of scaling factor of atomic Oxygen (an O not 2-1-1)
Input parameters:
IMG4278 - image at 4278 A, corrected and calibrated in Rayleighs
IMG6300 - image at 6300 A, corrected and calibrated in Rayleighs
IMG8446 - image at 8446 A, corrected and calibrated in Rayleighs
optional:
IMG4278b - second image at 4278 A, corrected and calibrated in
Rayleighs for interpolation in time sequence
See also: Strickland, D. J., R. R. Meier, J. H. Hecht, and
A. B. Christensen, Deducing composition and incident
electron spectra from ground-based auroral optical
measurements: theory and model results,
J. Geophys. Res., 94, 13527-13539, 1989. or
@Article{hecht1999jgr,
author = "Hecht, J. H. and Christensen, A. B. and Strickland,
D. J. and Majeed, T. and Gattinger, R. L. and
Vallance Jones, A.",
title = "A comparison between auroral particle
characteristics and atmospheric composition inferred
from analysing optical emission measurements alone
and in combination with incoherent scatter radar
measurements",
journal = jgr,
year = 1999,
volume = 104,
number = "A1",
pages = "33-44",
month = "January"
}</pre></div>
<!-- crossreference -->
<h2><a name="_cross"></a>CROSS-REFERENCE INFORMATION <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
This function calls:
<ul style="list-style-image:url(../matlabicon.gif)">
</ul>
This function is called by:
<ul style="list-style-image:url(../matlabicon.gif)">
<li><a href="../ALIS/alis_imgs_movie_r.html" class="code" title="function [M,Tstrs,caxout,exptimes,wl] = alis_imgs_movie_r(files,reg,cax,opptp,PREPROC_OPS,rgbFilters)">alis_imgs_movie_r</a> ALIS_IMGS_MOVIE_R - produce a matlab movie M from a series of image files.</li><li><a href="../ALIS/alis_imgs_movie_rgb.html" class="code" title="function [M] = alis_imgs_movie_rgb(files,reg,cax,opptp,PREPROC_OPS,rgbFilters)">alis_imgs_movie_rgb</a> ALIS_IMGS_MOVIE_RGB - produce a matlab movie M from a series of image files.</li></ul>
<!-- crossreference -->
<h2><a name="_source"></a>SOURCE CODE <a href="#_top"><img alt="^" border="0" src="../up.png"></a></h2>
<div class="fragment"><pre>0001 <a name="_sub0" href="#_subfunctions" class="code">function [img_E0,img_fO] = imgs_spec_ratio2E0fO(img4278,img6300,img8446,img4278b)</a>
0002 <span class="comment">% imgs_spec_ratio2E0fO - estimate characteristic e^- energy and depletion of O</span>
0003 <span class="comment">% By the method of Strickland, Hecht, Christensen and Meyer [] from</span>
0004 <span class="comment">% images at 4278, 6300 and 8446 A.</span>
0005 <span class="comment">%</span>
0006 <span class="comment">% Calling:</span>
0007 <span class="comment">% [img_E0,img_fO] = imgs_spec_ratio2E0fO(img4278,img6300,img8446,img4278b)</span>
0008 <span class="comment">%</span>
0009 <span class="comment">% Output parameters:</span>
0010 <span class="comment">% IMG_E0 - image of characteristic electron energy</span>
0011 <span class="comment">% IMG_FO - image of scaling factor of atomic Oxygen (an O not 2-1-1)</span>
0012 <span class="comment">%</span>
0013 <span class="comment">% Input parameters:</span>
0014 <span class="comment">% IMG4278 - image at 4278 A, corrected and calibrated in Rayleighs</span>
0015 <span class="comment">% IMG6300 - image at 6300 A, corrected and calibrated in Rayleighs</span>
0016 <span class="comment">% IMG8446 - image at 8446 A, corrected and calibrated in Rayleighs</span>
0017 <span class="comment">% optional:</span>
0018 <span class="comment">% IMG4278b - second image at 4278 A, corrected and calibrated in</span>
0019 <span class="comment">% Rayleighs for interpolation in time sequence</span>
0020 <span class="comment">%</span>
0021 <span class="comment">% See also: Strickland, D. J., R. R. Meier, J. H. Hecht, and</span>
0022 <span class="comment">% A. B. Christensen, Deducing composition and incident</span>
0023 <span class="comment">% electron spectra from ground-based auroral optical</span>
0024 <span class="comment">% measurements: theory and model results,</span>
0025 <span class="comment">% J. Geophys. Res., 94, 13527-13539, 1989. or</span>
0026 <span class="comment">% @Article{hecht1999jgr,</span>
0027 <span class="comment">% author = "Hecht, J. H. and Christensen, A. B. and Strickland,</span>
0028 <span class="comment">% D. J. and Majeed, T. and Gattinger, R. L. and</span>
0029 <span class="comment">% Vallance Jones, A.",</span>
0030 <span class="comment">% title = "A comparison between auroral particle</span>
0031 <span class="comment">% characteristics and atmospheric composition inferred</span>
0032 <span class="comment">% from analysing optical emission measurements alone</span>
0033 <span class="comment">% and in combination with incoherent scatter radar</span>
0034 <span class="comment">% measurements",</span>
0035 <span class="comment">% journal = jgr,</span>
0036 <span class="comment">% year = 1999,</span>
0037 <span class="comment">% volume = 104,</span>
0038 <span class="comment">% number = "A1",</span>
0039 <span class="comment">% pages = "33-44",</span>
0040 <span class="comment">% month = "January"</span>
0041 <span class="comment">%}</span>
0042
0043 <span class="comment">% Copyright � 20050110 Bjorn Gustavsson, <bjorn.gustavsson@irf.se></span>
0044 <span class="comment">% This is free software, licensed under GNU GPL version 2 or later</span>
0045
0046
0047 fO = [.1 .25 .5 1];
0048 E0 = [.1 .3 .6 1 3 6];
0049
0050 E0_2d = E0'*ones(1,4);
0051 fO_2d = fO'*ones(1,6);
0052
0053 Y6300 = [1200 1950 3100 5200;<span class="keyword">...</span>
0054 500 800 1400 2400;<span class="keyword">...</span>
0055 260 400 700 1100;<span class="keyword">...</span>
0056 150 220 350 600;<span class="keyword">...</span>
0057 32 50 80 150;<span class="keyword">...</span>
0058 13 20 32 58];
0059
0060 Y4278 = [230 198 170 120;<span class="keyword">...</span>
0061 243 230 205 170;<span class="keyword">...</span>
0062 250 240 220 193;<span class="keyword">...</span>
0063 250 245 230 208;<span class="keyword">...</span>
0064 250 248 245 235;<span class="keyword">...</span>
0065 250 250 248 245];
0066
0067 Y8446 = [245 570 1000 1600;<span class="keyword">...</span>
0068 150 350 600 1100;<span class="keyword">...</span>
0069 100 240 430 780;<span class="keyword">...</span>
0070 80 170 310 580;<span class="keyword">...</span>
0071 48 87 150 270;<span class="keyword">...</span>
0072 40 62 100 170];
0073
0074 irb = Y8446./Y4278;
0075 rb = Y6300./Y4278;
0076
0077 <span class="keyword">if</span> nargin == 4
0078 r_b = img6300./(.5*img4278+.5*img4278b);
0079 ir_b = img8446./(.75*img4278+.25*img4278b);
0080 <span class="keyword">else</span>
0081 r_b = img6300./(img4278);
0082 ir_b = img8446./(img4278);
0083 <span class="keyword">end</span>
0084
0085 img_E0 = exp(griddata(log(rb),log(irb),log(E0_2d),log(r_b),log(ir_b)));
0086 <span class="keyword">if</span> nargout > 1
0087 img_fO = exp(griddata(log(rb),log(irb),log(fO_2d'),log(r_b),log(ir_b)));
0088 <span class="keyword">end</span></pre></div>
<hr><address>Generated on Sat 09-Feb-2013 12:20:36 by <strong>B. Gustavsson</strong> with <strong><a href="http://www.artefact.tk/software/matlab/m2html/" target="_parent">m2html</a></strong> © 2003</address>
</body>
</html> | scienceopen/AIDA-tools | Html-docs/Imgtools/imgs_spec_ratio2E0fO.html | HTML | gpl-3.0 | 9,547 |
$(document).ready(function(){
$("#slidetopcontentShower").click(function() {
$("#slidetopcontent").slideToggle();
$(this).toggleClass("showed");
});
}); | desarrollosimagos/puroextremo.com.ve | modules/slidetopcontent/slidetopcontent.js | JavaScript | gpl-3.0 | 166 |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Author: Morgan W. Davis III
//Project: openTill Point of Sale System
//Date: 24 Feb 2014
//Revisions: 4/6/2014 Added Documentation | Curtis Reinhold
namespace openTill.Domain.DTO
{
/// <summary>
/// Employee data transfer object used to move an employee around the layers of the program.
/// </summary>
[ExcludeFromCodeCoverage ] //Added By Blaine 4/18/2014
public class EmployeeDTO
{
#region Properties
public int ID;
public string FName;
public string LName;
public int PositionID;
public int AddressID;
public int PhoneID;
public decimal Wage;
public string SSN;
public DateTime BirthDate;
public DateTime StartDate;
public DateTime EndDate;
public String UserName;
public Guid PasswordHash;
public Guid PinHash;
public Phone PhoneNumber;
public Address EmployeeAddress;
public Position EmployeePosition;
#endregion
}
}
| CIT275DevGroup/openTill | openTill/openTill.Domain/DTO/EmployeeDTO.cs | C# | gpl-3.0 | 1,169 |
/*
* Copyright (C) 2011-2012 DarkCore <http://www.darkpeninsula.eu/>
* Copyright (C) 2011-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.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/>.
*/
#include "vmapexport.h"
#include "model.h"
#include "wmo.h"
#include "mpq_libmpq04.h"
#include <cassert>
#include <algorithm>
#include <cstdio>
Model::Model(std::string &filename) : filename(filename)
{
}
bool Model::open()
{
MPQFile f(filename.c_str());
ok = !f.isEof();
if (!ok)
{
f.close();
printf("Error loading model %s\n", filename.c_str());
return false;
}
memcpy(&header, f.getBuffer(), sizeof(ModelHeader));
if (header.nBoundingTriangles > 0)
{
f.seek(0);
f.seekRelative(header.ofsBoundingVertices);
vertices = new Vec3D[header.nBoundingVertices];
f.read(vertices, header.nBoundingVertices*12);
for (uint32 i=0; i<header.nBoundingVertices; i++)
{
vertices[i] = fixCoordSystem(vertices[i]);
}
f.seek(0);
f.seekRelative(header.ofsBoundingTriangles);
indices = new uint16[header.nBoundingTriangles];
f.read(indices, header.nBoundingTriangles*2);
f.close();
}
else
{
//printf("not included %s\n", filename.c_str());
f.close();
return false;
}
return true;
}
bool Model::ConvertToVMAPModel(char * outfilename)
{
int N[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
FILE * output=fopen(outfilename, "wb");
if (!output)
{
printf("Can't create the output file '%s'\n", outfilename);
return false;
}
fwrite("VMAP003", 8, 1, output);
uint32 nVertices = 0;
nVertices = header.nBoundingVertices;
fwrite(&nVertices, sizeof(int), 1, output);
uint32 nofgroups = 1;
fwrite(&nofgroups, sizeof(uint32), 1, output);
fwrite(N, 4*3, 1, output);// rootwmoid, flags, groupid
fwrite(N, sizeof(float), 3*2, output);//bbox, only needed for WMO currently
fwrite(N, 4, 1, output);// liquidflags
fwrite("GRP ", 4, 1, output);
uint32 branches = 1;
int wsize;
wsize = sizeof(branches) + sizeof(uint32) * branches;
fwrite(&wsize, sizeof(int), 1, output);
fwrite(&branches, sizeof(branches), 1, output);
uint32 nIndexes = 0;
nIndexes = header.nBoundingTriangles;
fwrite(&nIndexes, sizeof(uint32), 1, output);
fwrite("INDX", 4, 1, output);
wsize = sizeof(uint32) + sizeof(unsigned short) * nIndexes;
fwrite(&wsize, sizeof(int), 1, output);
fwrite(&nIndexes, sizeof(uint32), 1, output);
if (nIndexes >0)
{
fwrite(indices, sizeof(unsigned short), nIndexes, output);
}
fwrite("VERT", 4, 1, output);
wsize = sizeof(int) + sizeof(float) * 3 * nVertices;
fwrite(&wsize, sizeof(int), 1, output);
fwrite(&nVertices, sizeof(int), 1, output);
if (nVertices >0)
{
for (uint32 vpos=0; vpos <nVertices; ++vpos)
{
float sy = vertices[vpos].y;
vertices[vpos].y = vertices[vpos].z;
vertices[vpos].z = sy;
}
fwrite(vertices, sizeof(float)*3, nVertices, output);
}
delete[] vertices;
delete[] indices;
fclose(output);
return true;
}
Model::~Model()
{
}
Vec3D fixCoordSystem(Vec3D v)
{
return Vec3D(v.x, v.z, -v.y);
}
Vec3D fixCoordSystem2(Vec3D v)
{
return Vec3D(v.x, v.z, v.y);
}
ModelInstance::ModelInstance(MPQFile &f, const char* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile)
{
float ff[3];
f.read(&id, 4);
f.read(ff, 12);
pos = fixCoords(Vec3D(ff[0], ff[1], ff[2]));
f.read(ff, 12);
rot = Vec3D(ff[0], ff[1], ff[2]);
f.read(&scale, 4);
// scale factor - divide by 1024. blizzard devs must be on crack, why not just use a float?
sc = scale / 1024.0f;
char tempname[512];
sprintf(tempname, "%s/%s", szWorkDirWmo, ModelInstName);
FILE *input;
input = fopen(tempname, "r+b");
if (!input)
{
//printf("ModelInstance::ModelInstance couldn't open %s\n", tempname);
return;
}
fseek(input, 8, SEEK_SET); // get the correct no of vertices
int nVertices;
fread(&nVertices, sizeof (int), 1, input);
fclose(input);
if (nVertices == 0)
return;
uint16 adtId = 0;// not used for models
uint32 flags = MOD_M2;
if (tileX == 65 && tileY == 65) flags |= MOD_WORLDSPAWN;
//write mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, name
fwrite(&mapID, sizeof(uint32), 1, pDirfile);
fwrite(&tileX, sizeof(uint32), 1, pDirfile);
fwrite(&tileY, sizeof(uint32), 1, pDirfile);
fwrite(&flags, sizeof(uint32), 1, pDirfile);
fwrite(&adtId, sizeof(uint16), 1, pDirfile);
fwrite(&id, sizeof(uint32), 1, pDirfile);
fwrite(&pos, sizeof(float), 3, pDirfile);
fwrite(&rot, sizeof(float), 3, pDirfile);
fwrite(&sc, sizeof(float), 1, pDirfile);
uint32 nlen=strlen(ModelInstName);
fwrite(&nlen, sizeof(uint32), 1, pDirfile);
fwrite(ModelInstName, sizeof(char), nlen, pDirfile);
/* int realx1 = (int) ((float) pos.x / 533.333333f);
int realy1 = (int) ((float) pos.z / 533.333333f);
int realx2 = (int) ((float) pos.x / 533.333333f);
int realy2 = (int) ((float) pos.z / 533.333333f);
fprintf(pDirfile, "%s/%s %f, %f, %f_%f, %f, %f %f %d %d %d, %d %d\n",
MapName,
ModelInstName,
(float) pos.x, (float) pos.y, (float) pos.z,
(float) rot.x, (float) rot.y, (float) rot.z,
sc,
nVertices,
realx1, realy1,
realx2, realy2
); */
} | Darkpeninsula/Darkcore-Rebase | src/tools/vmap3_extractor/model.cpp | C++ | gpl-3.0 | 6,343 |
/**
* @version 02/11/2003 <BR>
* @author Setpoint Informática Ltda./Fernando Oliveira da Silva <BR>
*
* Projeto: Freedom <BR>
*
* Pacote: org.freedom.modulos.std <BR>
* Classe: @(#)FRResumoDiario.java <BR>
*
* Este arquivo é parte do sistema Freedom-ERP, o Freedom-ERP é um software livre; você pode redistribui-lo e/ou <BR>
* modifica-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação do Software Livre (FSF); <BR>
* na versão 2 da Licença, ou (na sua opnião) qualquer versão. <BR>
* Este programa é distribuido na esperança que possa ser util, mas SEM NENHUMA GARANTIA; <BR>
* sem uma garantia implicita de ADEQUAÇÂO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. <BR>
* Veja a Licença Pública Geral GNU para maiores detalhes. <BR>
* Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este programa, se não, <BR>
* escreva para a Fundação do Software Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA <BR>
* <BR>
*
* Comentários sobre a classe...
*
*/
package org.freedom.modulos.std.view.frame.report;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import org.freedom.infra.functions.StringFunctions;
import org.freedom.library.component.ImprimeOS;
import org.freedom.library.functions.Funcoes;
import org.freedom.library.persistence.ListaCampos;
import org.freedom.library.swing.component.JLabelPad;
import org.freedom.library.swing.component.JRadioGroup;
import org.freedom.library.swing.component.JTextFieldPad;
import org.freedom.library.swing.frame.Aplicativo;
import org.freedom.library.swing.frame.AplicativoPD;
import org.freedom.library.swing.frame.FRelatorio;
import org.freedom.library.type.TYPE_PRINT;
public class FREstatAtend extends FRelatorio {
private static final long serialVersionUID = 1L;
private JTextFieldPad txtDataini = new JTextFieldPad( JTextFieldPad.TP_DATE, 10, 0 );
private JTextFieldPad txtDatafim = new JTextFieldPad( JTextFieldPad.TP_DATE, 10, 0 );
private Vector<String> vLabs = new Vector<String>();
private Vector<String> vVals = new Vector<String>();
private JRadioGroup<?, ?> rgFormato = null;
private int iLinha = 1;
private int iCol = 1;
public FREstatAtend() {
setTitulo( "Resumo Diario" );
setAtribos( 80, 80, 295, 200 );
txtDataini.setVlrDate( new Date() );
txtDatafim.setVlrDate( new Date() );
JLabelPad lbLinha = new JLabelPad();
lbLinha.setBorder( BorderFactory.createEtchedBorder() );
adic( new JLabelPad( "Periodo:" ), 7, 5, 100, 20 );
adic( lbLinha, 60, 15, 210, 2 );
adic( new JLabelPad( "De:" ), 7, 30, 30, 20 );
adic( txtDataini, 32, 30, 97, 20 );
adic( new JLabelPad( "Até:" ), 140, 30, 30, 20 );
adic( txtDatafim, 170, 30, 100, 20 );
vLabs.addElement( "Detalhado" );
vLabs.addElement( "Resumido" );
vVals.addElement( "D" );
vVals.addElement( "R" );
rgFormato = new JRadioGroup<String, String>( 1, 2, vLabs, vVals );
rgFormato.setVlrString( "D" );
adic( rgFormato, 7, 80, 265, 25 );
}
public void imprimir( TYPE_PRINT bVisualizar ) {
if ( txtDatafim.getVlrDate().before( txtDataini.getVlrDate() ) ) {
Funcoes.mensagemInforma( this, "Data final maior que a data inicial!" );
return;
}
ImprimeOS imp = new ImprimeOS( "", con );
int linPag = imp.verifLinPag() - 1;
boolean bFimDia = false;
String sSQL = "";
BigDecimal bTotalDiaVal = new BigDecimal( "0" );
BigDecimal bTotalDiaDesc = new BigDecimal( "0" );
BigDecimal bTotalDiaLiq = new BigDecimal( "0" );
BigDecimal bTotalVal = new BigDecimal( "0" );
BigDecimal bTotalDesc = new BigDecimal( "0" );
BigDecimal bTotalLiq = new BigDecimal( "0" );
imp.montaCab();
String sDataini = "";
String sDatafim = "";
String sDtemitvenda = "";
sDataini = txtDataini.getVlrString();
sDatafim = txtDatafim.getVlrString();
imp.setTitulo( "Resumo Diário de Vendas" );
if ( rgFormato.getVlrString().equals( "D" ) ) {
sSQL = "SELECT V.DTEMITVENDA,V.CODTIPOMOV,V.CODVENDA,V.DOCVENDA,V.SERIE," + "V.STATUSVENDA,V.DOCVENDA," + "V.DTEMITVENDA,V.VLRPRODVENDA,V.VLRLIQVENDA," + "V.CODPLANOPAG,P.DESCPLANOPAG," + "V.VLRCOMISVENDA,V.VLRDESCITVENDA," + "V.CODCLI,C.RAZCLI,V.STATUSVENDA"
+ " FROM VDVENDA V,VDCLIENTE C,FNPLANOPAG P, EQTIPOMOV TM " + "WHERE TM.CODTIPOMOV=V.CODTIPOMOV" + " AND TM.CODEMP=V.CODEMPTM" + " AND TM.CODFILIAL=V.CODFILIALTM" + " AND C.CODCLI=V.CODCLI" + " AND C.CODEMP=V.CODEMPCL AND C.CODFILIAL=V.CODFILIALCL"
+ " AND V.DTEMITVENDA BETWEEN ? AND ? AND " + "P.CODPLANOPAG=V.CODPLANOPAG AND V.FLAG IN " + AplicativoPD.carregaFiltro( con, org.freedom.library.swing.frame.Aplicativo.iCodEmp ) + " AND V.CODEMP=? AND V.CODFILIAL=?" + " AND TM.TIPOMOV IN ('VD','PV','VT','SE')"
+ " AND NOT SUBSTR(V.STATUSVENDA,1,1)='C' ORDER BY V.DTEMITVENDA,V.DOCVENDA";
}
else if ( rgFormato.getVlrString().equals( "R" ) ) {
sSQL = "SELECT V.DTEMITVENDA,SUM(V.VLRLIQVENDA) FROM VDVENDA V," + " EQTIPOMOV TM WHERE V.DTEMITVENDA BETWEEN ? AND ? AND V.FLAG IN " + AplicativoPD.carregaFiltro( con, org.freedom.library.swing.frame.Aplicativo.iCodEmp ) + " AND TM.CODEMP=V.CODEMPTM" + " AND TM.CODFILIAL=V.CODFILIALTM"
+ " AND TM.CODTIPOMOV=V.CODTIPOMOV" + " AND TM.TIPOMOV IN ('VD','PV','VT','SE')" + " AND V.CODEMP=? AND V.CODFILIAL=? GROUP BY V.DTEMITVENDA";
System.out.println( sSQL );
}
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement( sSQL );
ps.setDate( 1, Funcoes.dateToSQLDate( txtDataini.getVlrDate() ) );
ps.setDate( 2, Funcoes.dateToSQLDate( txtDatafim.getVlrDate() ) );
ps.setInt( 3, Aplicativo.iCodEmp );
ps.setInt( 4, ListaCampos.getMasterFilial( "VDVENDA" ) );
rs = ps.executeQuery();
imp.limpaPags();
if ( rgFormato.getVlrString().equals( "D" ) ) {
while ( rs.next() ) {
if ( ( !StringFunctions.sqlDateToStrDate( rs.getDate( "dtemitvenda" ) ).equals( sDtemitvenda ) ) & ( bFimDia ) ) {
imp.impCab( 136, false );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
imp.say( imp.pRow() + 0, 61, "Totais do Dia-> " + sDtemitvenda + " |" + Funcoes.strDecimalToStrCurrency( 10, 2, "" + bTotalDiaVal ) + Funcoes.strDecimalToStrCurrency( 10, 2, "" + bTotalDiaDesc ) + Funcoes.strDecimalToStrCurrency( 11, 2, "" + bTotalDiaLiq ) );
imp.say( imp.pRow(), 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
bTotalDiaVal = new BigDecimal( "0" );
bTotalDiaDesc = new BigDecimal( "0" );
bTotalDiaLiq = new BigDecimal( "0" );
bFimDia = false;
}
if ( imp.pRow() >= ( linPag - 1 ) ) {
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.incPags();
imp.eject();
}
if ( imp.pRow() == 0 ) {
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "+" + StringFunctions.replicate( "-", 134 ) + "+" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "| Emitido em :" + Funcoes.dateToStrDate( new Date() ) );
imp.say( imp.pRow() + 0, 120, "Pagina : " + ( imp.getNumPags() ) );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
imp.say( imp.pRow() + 0, 5, "RESUMO DIARIO DE VENDAS - PERIODO DE :" + sDataini + " Até: " + sDatafim );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "| Dt. Emissao" );
imp.say( imp.pRow() + 0, 17, "NF./Ped." );
imp.say( imp.pRow() + 0, 31, "Cliente" );
imp.say( imp.pRow() + 0, 88, "| Valor Desconto " + " Liquido F.Pagto." );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
}
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
if ( !StringFunctions.sqlDateToStrDate( rs.getDate( "dtemitvenda" ) ).equals( sDtemitvenda ) ) {
imp.say( imp.pRow() + 0, 3, StringFunctions.sqlDateToStrDate( rs.getDate( "dtemitvenda" ) ) );
}
imp.say( imp.pRow() + 0, 17, rs.getString( "StatusVenda" ).substring( 0, 1 ).equals( "P" ) ? "P-" + Funcoes.copy( rs.getString( "codvenda" ), 0, 6 ) : "V-" + Funcoes.copy( rs.getString( "docvenda" ), 0, 6 ) );
imp.say( imp.pRow() + 0, 31, Funcoes.copy( rs.getString( "codcli" ), 0, 7 ) + "-" + Funcoes.copy( rs.getString( "razcli" ), 0, 49 ) + "|" + Funcoes.strDecimalToStrCurrency( 10, 2, rs.getString( "vlrprodvenda" ) )
+ Funcoes.strDecimalToStrCurrency( 10, 2, rs.getString( "vlrdescitvenda" ) ) + Funcoes.strDecimalToStrCurrency( 11, 2, rs.getString( "vlrliqvenda" ) ) + " " + Funcoes.copy( rs.getString( "descplanopag" ), 0, 15 ) + "|" );
if ( rs.getString( "VlrProdVenda" ) != null ) {
bTotalDiaVal = bTotalDiaVal.add( new BigDecimal( rs.getString( "VlrProdVenda" ) ) );
bTotalVal = bTotalVal.add( new BigDecimal( rs.getString( "VlrProdVenda" ) ) );
}
if ( rs.getString( "VlrDescitvenda" ) != null ) {
bTotalDiaDesc = bTotalDiaDesc.add( new BigDecimal( rs.getString( "VlrDescitVenda" ) ) );
bTotalDesc = bTotalDesc.add( new BigDecimal( rs.getString( "VlrDescitVenda" ) ) );
}
if ( rs.getString( "VlrLiqVenda" ) != null ) {
bTotalDiaLiq = bTotalDiaLiq.add( new BigDecimal( rs.getString( "VlrLiqVenda" ) ) );
bTotalLiq = bTotalLiq.add( new BigDecimal( rs.getString( "VlrLiqVenda" ) ) );
}
bFimDia = true;
sDtemitvenda = StringFunctions.sqlDateToStrDate( rs.getDate( "Dtemitvenda" ) );
}
if ( bFimDia ) {
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
imp.say( imp.pRow() + 0, 61, "Totais do Dia-> " + sDtemitvenda + " |" + Funcoes.strDecimalToStrCurrency( 10, 2, "" + bTotalDiaVal ) + Funcoes.strDecimalToStrCurrency( 10, 2, "" + bTotalDiaDesc ) + Funcoes.strDecimalToStrCurrency( 11, 2, "" + bTotalDiaLiq ) );
imp.say( imp.pRow(), 136, "|" );
}
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow(), 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
imp.say( imp.pRow() + 0, 72, "Totais Geral |" + Funcoes.strDecimalToStrCurrency( 10, 2, "" + bTotalVal ) + Funcoes.strDecimalToStrCurrency( 10, 2, "" + bTotalDesc ) + Funcoes.strDecimalToStrCurrency( 11, 2, "" + bTotalLiq ) );
imp.say( imp.pRow(), 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
}
else if ( rgFormato.getVlrString().equals( "R" ) ) {
iLinha = 1;
iCol = 0;
while ( rs.next() ) {
if ( imp.pRow() >= ( linPag - 1 ) ) {
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.incPags();
imp.eject();
}
if ( imp.pRow() == 0 ) {
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "+" + StringFunctions.replicate( "-", 134 ) + "+" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "| Emitido em :" + Funcoes.dateToStrDate( new Date() ) );
imp.say( imp.pRow() + 0, 120, "Pagina : " + ( imp.getNumPags() ) );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "|" );
imp.say( imp.pRow() + 0, 5, "RESUMO DE TOTAL DE VENDAS - PERIODO DE :" + sDataini + " Até: " + sDatafim );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
imp.say( imp.pRow() + 1, 0, "" + imp.comprimido() );
imp.say( imp.pRow() + 0, 0, "| Data" );
imp.say( imp.pRow() + 0, 14, " Valor" );
imp.say( imp.pRow() + 0, 35, "| Data" );
imp.say( imp.pRow() + 0, 49, " Valor" );
imp.say( imp.pRow() + 0, 70, "| Data" );
imp.say( imp.pRow() + 0, 84, " Valor" );
imp.say( imp.pRow() + 0, 105, "| Data" );
imp.say( imp.pRow() + 0, 119, " Valor" );
imp.say( imp.pRow() + 0, 136, "|" );
imp.say( imp.pRow() + 1, 0, "|" + StringFunctions.replicate( "-", 134 ) + "|" );
}
imp.say( imp.pRow() + iLinha, iCol, "| " + StringFunctions.sqlDateToStrDate( rs.getDate( 1 ) ) );
imp.say( imp.pRow() + 0, iCol + 14, " " + Funcoes.strDecimalToStrCurrency( 15, 2, "" + rs.getString( 2 ) ) );
if ( iCol == 0 ) {
iLinha = 0;
iCol = 35;
}
else if ( iCol == 35 )
iCol = 70;
else if ( iCol == 70 )
iCol = 105;
else {
imp.say( imp.pRow() + 0, 136, "|" );
iCol = 0;
iLinha = 1;
}
if ( rs.getString( 2 ) != null ) {
bTotalDiaLiq = bTotalDiaLiq.add( new BigDecimal( rs.getString( 2 ) ) );
bTotalLiq = bTotalLiq.add( new BigDecimal( rs.getString( 2 ) ) );
}
}
}
if ( ( iCol < 105 ) && ( iLinha == 0 ) ) {
imp.say( imp.pRow() + 0, 136, "|" );
}
imp.say( imp.pRow() + 1, 0, "+" + StringFunctions.replicate( "-", 134 ) + "+" );
imp.say( imp.pRow() + 1, 0, "|" );
imp.say( imp.pRow() + 0, 88, "| Total Geral do Período | " + Funcoes.strDecimalToStrCurrency( 11, 2, "" + bTotalLiq ) );
imp.say( imp.pRow(), 136, "|" );
imp.say( imp.pRow() + 1, 0, "+" + StringFunctions.replicate( "-", 134 ) + "+" );
imp.eject();
imp.fechaGravacao();
// rs.close();
// ps.close();
con.commit();
// dl.dispose();
} catch ( SQLException err ) {
Funcoes.mensagemErro( this, "Erro consulta tabela de vendas!" + err.getMessage(), true, con, err );
}
if ( bVisualizar==TYPE_PRINT.VIEW ) {
imp.preview( this );
}
else {
imp.print();
}
}
}
| cams7/erp | freedom/src/main/java/org/freedom/modulos/std/view/frame/report/FREstatAtend.java | Java | gpl-3.0 | 15,087 |
/*
This file is part of closest, a library for k-nearest neighbors (kNN) search
in n-dimensions.
Copyright (C) 2011-2016 Daniel Pena <trifling.github@gmail.com>
Closest 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.
Closest 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
closest. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <unistd.h>
#include <time.h>
#include "auxf.h"
typedef struct {
int index;
double value;
} closest_rank_t;
#define RANK_PREFIX double
#define RANK_DATA_TYPE double
#define HEAP_PREFIX result
#define HEAP_DATA_TYPE result_t
#define HEAP_CMP(x,y) ((x->r) < (y->r) ? -1 : ((x->r) == (y->r) ? 0 : 1))
#include "maxheap.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#define DEFAULT_PROBABILITY 0.3
/* types */
typedef struct {
double *xi;
int *bmap;
int *fmap;
double *oset;
int ni;
int nd;
double *llim;
double *ulim;
double *side;
int *ix;
int *lst;
char *use;
double prob;
double eps;
metric Lfun;
void *Ldata;
} cull_t;
/* uniform distribution epsilon for a sphere */
/*static double hsphere( int nd, double *ext, int ni, double p ) {*/
/*double eps = nd*tgamma(nd/2.0)/(2.0*pow(M_PI,nd/2.0))*(1.0-pow(1.0-p,1.0/ni));*/
/*for( int k=0; k<nd; k++ ) */
/*eps *= ext[k];*/
/*return pow(eps,1.0/nd);*/
/*}*/
/* uniform distribution epsilon for a cube */
static double hcube( int nd, double *ext, int ni, double p ) {
double eps = pow(0.5,nd)*(1.0-pow(1.0-p,1.0/ni));
for( int k=0; k<nd; k++ )
eps *= ext[k];
return pow(eps,1.0/nd);
}
void cull_set_metric( cull_t *cull, metric fun, void *data ) {
cull->Ldata = data;
if( fun == NULL )
cull->Lfun = L2metric;
else
cull->Lfun = fun;
}
/* pre-process the node set to obtain an ordered set, along with a forward and backwards mapping. */
cull_t *cull_init( int nd, int ni, double *xi, double prob ) {
cull_t *c;
c = malloc( sizeof(cull_t) );
c->nd = nd;
c->ni = ni;
c->xi = xi;
c->bmap = calloc( ni, sizeof(int) );
c->fmap = calloc( ni*nd, sizeof(int) );
c->oset = calloc( ni*nd, sizeof(double) );
c->llim = calloc( nd, sizeof(double) );
c->ulim = calloc( nd, sizeof(double) );
c->side = calloc( nd, sizeof(double) );
c->use = calloc( c->ni, sizeof(char) );
c->ix = calloc( c->ni, sizeof(int) );
c->lst = calloc( c->ni, sizeof(int) );
c->Lfun = L2metric;
c->Ldata = NULL;
/* limits */
for( int k=0; k<nd; k++ ) {
c->llim[k] = dminval( ni, nd, xi+k );
c->ulim[k] = dmaxval( ni, nd, xi+k );
c->side[k] = c->ulim[k] - c->llim[k];
}
/* create backward and forward maps and ordered sets */
int *idx = calloc( ni, sizeof(int) );
double *tmp = calloc( ni, sizeof(double) );
for( int k=0; k<nd; k++ ) {
/* order taking into account the stride */
for( int i=0; i<ni; i++ ) {
idx[i] = i;
tmp[i] = c->xi[k+i*nd];
}
double_rank( idx, tmp, ni );
/*closest_rank( xi+k, ni, idx ); */
for( int i=0; i<ni; i++ ) {
c->oset[k*ni+i] = c->xi[k+idx[i]*nd];
c->fmap[k*ni+idx[i]] = i;
/*c->oset[k*ni+i] = c->xi[k+idx[i]*nd];*/
/*c->fmap[k*ni+idx[i]] = i;*/
}
if( k==0 ) {
for( int i=0; i<ni; i++ ) {
c->bmap[i] = idx[i];
}
}
}
free( idx );
/* numerical parameters */
if( prob <= 0.0 )
c->prob = DEFAULT_PROBABILITY;
else
c->prob = prob;
c->eps = hcube( c->nd, c->side, c->ni, c->prob );
return( c );
}
void cull_free( cull_t *c ) {
free( c->bmap );
free( c->fmap );
free( c->oset );
free( c->llim );
free( c->ulim );
free( c->side );
free( c->use );
free( c->ix );
free( c->lst );
free( c );
}
/* bin search with lower bias */
static inline int bbinsearch( size_t n, double *ordered, double val ) {
int b = 0;
int t = n-1;
if( val > ordered[n-1] )
return n-1;
while( t > b+1 ) {
int c = (b + t) / 2;
if( val < ordered[c] )
t = c;
else
b = c;
}
return b;
}
/* bin search with upper bias */
static inline int tbinsearch( size_t n, double *ordered, double val ) {
int b = 0;
int t = n-1;
if( val < ordered[0] )
return 0;
while( t > b+1 ) {
int c = (b + t) / 2;
if( val > ordered[c] )
b = c;
else
t = c;
}
return t;
}
static inline int hyperrect( cull_t *c, double *x, double eps, int *lst ) {
/* l - index from the ordered set to original set (bmap) */
/* i - index in the original set */
/* j - index from original set to ordered set */
/* k - index in dimensions */
/* m, n, o - running indexes */
/* initial culling along dim 0, add candidates to the list */
int bot = bbinsearch( c->ni, c->oset, x[0]-eps );
int top = tbinsearch( c->ni, c->oset, x[0]+eps );
int n = 0;
for( int l=bot; l<=top; l++ ) {
int i = c->bmap[l];
if( c->use[i] == 0 )
lst[n++] = c->bmap[l];
}
/* trim list with binary searches along the other dims */
for( int k=1; k<c->nd; k++ ) {
bot = bbinsearch( c->ni, c->oset+k*c->ni, x[k]-eps );
top = tbinsearch( c->ni, c->oset+k*c->ni, x[k]+eps );
int m = n; n = 0;
for( int o=0; o<m; o++ ) {
int i = lst[o];
int j = c->fmap[k*c->ni+i];
if( j < bot || j > top )
continue;
lst[n++] = i;
}
}
/* mark points already used */
for( int l=0; l<n; l++ )
c->use[lst[l]] = 1;
return n;
}
int cull_knearest( cull_t *c, int nq, double *xq, int no, int *index, double *distance ) {
/* epsilon estimation */
double eps = c->eps * pow((double)no,1.0/(double)c->nd);
result_heap_t *heap = result_heap_init( no, -1 );
for( int iq=0; iq<nq; iq++ ) {
result_heap_reset( heap );
double *x = xq + iq*c->nd;
/* reset points already used array */
for( int i=0; i<c->ni; i++ )
c->use[i] = 0;
double rmax = DBL_MAX;
int n = 0;
do {
int m = hyperrect( c, x, eps, c->lst+n );
for( int j=n; j<n+m; j++ ) {
int i = c->lst[j];
double r = c->Lfun( c->nd, x, c->xi+i*c->nd, c->Ldata );
if( r < rmax ) {
result_heap_insert( heap, result_init(i,r) );
if( heap->len == no )
rmax = result_heap_peek( heap )->r;
}
}
n += m;
if( n >= no )
break;
eps *= 1.2;
} while(1);
if( rmax > eps )
eps = rmax;
else
eps = sqrt((double)c->nd)*eps;
int m = hyperrect( c, x, eps, c->lst+n );
for( int j=n; j<n+m; j++ ) {
int i = c->lst[j];
double r = c->Lfun( c->nd, x, c->xi+i*c->nd, c->Ldata );
if( r < rmax ) {
result_heap_insert( heap, result_init(i,r) );
if( heap->len == no )
rmax = result_heap_peek( heap )->r;
}
}
n += m;
/* sort the list according to metric */
for( int i=no-1; i>=0; i-- ) {
result_t *e = result_heap_pop( heap );
if(e) {
index[i+iq*no] = e->i;
distance[i+iq*no] = e->r;
free(e);
}
}
}
return no*nq;
}
| trifling/closest | src/cull.c | C | gpl-3.0 | 8,033 |
# FluentOMatic
FluentOMatic is a fluent syntax generator for .NET.
| aaubry/FluentOMatic | README.md | Markdown | gpl-3.0 | 71 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <mail@vanit.as>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.graphic.like.palette;
import android.animation.ArgbEvaluator;
import android.graphics.Color;
import de.vanita5.twittnuker.graphic.like.LikeAnimationDrawable;
public final class LikePalette implements LikeAnimationDrawable.Palette {
private final ArgbEvaluator evaluator = new ArgbEvaluator();
private final float[] hsv = new float[3];
@Override
public int getParticleColor(int count, int index, float progress) {
final double degree = 360.0 / count * index;
hsv[0] = (float) degree;
hsv[1] = 0.4f;
hsv[2] = 1f;
return Color.HSVToColor(hsv);
}
@Override
public int getCircleColor(float progress) {
return (Integer) evaluator.evaluate(progress, 0xFFDE4689, 0xFFCD8FF5);
}
} | vanita5/twittnuker | twittnuker/src/main/java/de/vanita5/twittnuker/graphic/like/palette/LikePalette.java | Java | gpl-3.0 | 1,671 |
// Called each time there's new content
window.tweak_content=function() {
$('a:not(.internal-link, .anchor-link)').attr('target','_blank');
}
// The "OnLoad"
$(function() {
$.manageAjax.create('flocks',{queue:true});
$('.flashes li').each(function() {
$(this).prepend($('<a/>').attr('href','#').click(function() {
$(this).parent().remove(); return false;}).addClass(
'internal-link important').append('<b/>').text('X')).css('opacity',.9)});
$('body').append($('<a/>').attr('id','top-link').attr('href','#').addClass('internal-link').click(function() {
$('html,body').animate({scrollTop:0},'slow');
return false;
}).html('⬆ Top'));
$('#feed-url, #flockshare').click(function() {$(this).select()});
$('.focusme:first').focus();
window.tweak_content();
if (window.SCROLLTO!=undefined && window.SCROLLTO) {
$('html,body').animate({scrollTop: $("#"+window.SCROLLTO).offset().top-60},'slow');
}
});
window.populate_from_feed=function(ul,data) {
for (e in data['entries']) {
if (e>=window.MAX_FEED_ENTRIES) { break; }
entry=data['entries'][e];
feed_dir=entry['feed_rtl']?'rtl':'ltr';
var item_header=$('<div/>').addClass('toggler-label').addClass(feed_dir);
item_header.append($('<div/>').addClass('item-time').text(entry['friendly_time']));
item_header.append($('<span/>').addClass('feed-reference').text(entry['feed_title']).append(
window.BUTTON_HTML[entry['feed_url']]));
item_header.append($('<a/>').addClass('entry-title').attr(
'href',entry['link']).html(entry['title']));
var toggler = $('<input/>').addClass('toggler').attr('type','checkbox');
if (window.EXPAND_ALL_ENTRIES) {toggler.attr('checked','checked');}
var li=$('<li/>').attr('id',entry['id']).addClass('feed-entry').append(item_header).append(toggler);
li.append($('<div/>').addClass('entry-description').addClass(feed_dir).html(entry['description']));
li.data('modified',entry['modified']);
var sameold=ul.find('#'+li.attr('id'));
if (sameold.length) {
// if it's hard to find out whether a checkbox is checked, might as well take the whole element :)
li.find('input.toggler').replaceWith(sameold.find('input.toggler'));
sameold.replaceWith(li);
} else {
var older=ul.find('li').filter(function() {
return $(this).data('modified')<li.data('modified');
});
if (older.length) {
older.eq(0).before(li);
} else {
ul.append(li);
}
};
ul.children(':gt('+(window.MAX_PAGE_ENTRIES-1)+')').remove();
}
}
window.fetch_from_feed=function(ul_id,feed_title,feed_url) {
var ul=$('#'+ul_id);
var loading=$('<li/>').addClass('fetching-ajax').html(AJAX_LOADER_HTML).append(feed_title).data('modified','');
$('#loading-list').append(loading);
$.manageAjax.add('flocks',{
url:window.AJAX_FEED_URL,
type:'POST',
data:{url:feed_url},
ul:ul,
refresh:"window.fetch_from_feed('"+ul_id+"','"+feed_title+"','"+feed_url+"')",
refresh_seconds:1000*window.FEED_REFRESH_SECONDS,
loading:loading,
success:function(data,textStatus,xhr,options){
options['loading'].slideUp(500).remove();
populate_from_feed(options['ul'],data);
window.tweak_content();
setTimeout(options['refresh'],options['refresh_seconds']);
},
error:function(data,textStatus,xhr,options){
options['loading'].find('img').replaceWith('Failed! ');
options['loading'].prependTo($('#loading-list')).addClass(
'hilite').click(function() {$(this).slideUp(1000).remove();});
setTimeout(options['refresh'],options['refresh_seconds']);
},
abort:function(data,textStatus,xhr,options){
options['loading'].find('img').replaceWith('Aborted! ');
options['loading'].prependTo($('#loading-list')).addClass(
'hilite').click(function() {$(this).slideUp(1000).remove();});
setTimeout(options['refresh'],options['refresh_seconds']);
}
});
}
window.abort_all_fetches = function() {
$.manageAjax.clear('flocks');
$('.fetching-ajax').slideUp(500).remove();
}
| dotandimet/Flocks | static/flocks.js | JavaScript | gpl-3.0 | 4,441 |
/**************************************************************************
* *
* Copyright (C) 2015 Felix Rohrbach <kde@fxrh.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/>. *
* *
**************************************************************************/
#include "logindialog.h"
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLabel>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QFormLayout>
#include <QtCore/QUrl>
#include "quaternionconnection.h"
#include "settings.h"
LoginDialog::LoginDialog(QWidget* parent)
: QDialog(parent)
, m_connection(nullptr)
{
serverEdit = new QLineEdit("https://matrix.org");
userEdit = new QLineEdit();
passwordEdit = new QLineEdit();
passwordEdit->setEchoMode( QLineEdit::Password );
saveTokenCheck = new QCheckBox("Stay logged in");
statusLabel = new QLabel("Welcome to Quaternion");
loginButton = new QPushButton("Login");
QFormLayout* formLayout = new QFormLayout();
formLayout->addRow("Server", serverEdit);
formLayout->addRow("User", userEdit);
formLayout->addRow("Password", passwordEdit);
formLayout->addRow(saveTokenCheck);
QVBoxLayout* mainLayout = new QVBoxLayout();
mainLayout->addLayout(formLayout);
mainLayout->addWidget(loginButton);
mainLayout->addWidget(statusLabel);
setLayout(mainLayout);
{
// Fill defaults
using namespace QMatrixClient;
QStringList accounts { SettingsGroup("Accounts").childGroups() };
if ( !accounts.empty() )
{
AccountSettings account { accounts.front() };
QUrl homeserver = account.homeserver();
QString username = account.userId();
if (username.startsWith('@'))
{
QString serverpart = ":" + homeserver.host();
if (homeserver.port() != -1)
serverpart += ":" + QString::number(homeserver.port());
if (username.endsWith(serverpart))
{
// Keep only the local part of the user id
username.remove(0, 1).chop(serverpart.size());
}
}
serverEdit->setText(homeserver.toString());
userEdit->setText(username);
saveTokenCheck->setChecked(account.keepLoggedIn());
}
else
{
serverEdit->setText("https://matrix.org");
saveTokenCheck->setChecked(false);
}
}
if (userEdit->text().isEmpty())
userEdit->setFocus();
else
passwordEdit->setFocus();
connect( loginButton, &QPushButton::clicked, this, &LoginDialog::login );
}
void LoginDialog::setStatusMessage(const QString& msg)
{
statusLabel->setText(msg);
}
QuaternionConnection* LoginDialog::connection() const
{
return m_connection;
}
bool LoginDialog::keepLoggedIn() const
{
return saveTokenCheck->isChecked();
}
void LoginDialog::login()
{
setStatusMessage("Connecting and logging in, please wait");
setDisabled(true);
QUrl url = QUrl::fromUserInput(serverEdit->text());
QString user = userEdit->text();
QString password = passwordEdit->text();
setConnection(new QuaternionConnection(url));
connect( m_connection, &QMatrixClient::Connection::connected, this, &QDialog::accept );
connect( m_connection, &QMatrixClient::Connection::loginError, this, &LoginDialog::error );
m_connection->connectToServer(user, password);
}
void LoginDialog::error(QString error)
{
setStatusMessage( error );
setConnection(nullptr);
setDisabled(false);
}
void LoginDialog::setConnection(QuaternionConnection* connection)
{
if (m_connection != nullptr) {
m_connection->deleteLater();
}
m_connection = connection;
}
| KitsuneRal/Quaternion | client/logindialog.cpp | C++ | gpl-3.0 | 4,923 |
<html>
<head>
<title><?= $config['site_name'] ?></title>
<?
if(isset($redirect)) {
echo '<META HTTP-EQUIV="Refresh" CONTENT="0;URL=' . $redirect . '">';
}
?>
</head>
<body>
<ul>
<?
for($i = 0; $i < count($page_display); $i++) {
echo '<li><a href="' . $page_display[$i] . '">' . $page_display_names[$i] . '</a></li>';
}
?>
</ul>
| uakfdotb/oneapp | style/basic/header.php | PHP | gpl-3.0 | 332 |
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Relative path conversion top directories.
SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/kdbanman/browseRDF/tulip-3.8.0-src/thirdparty/sip-4.13.2/sipgen")
SET(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/kdbanman/browseRDF/tulip-3.8.0-src/build/thirdparty/sip-4.13.2/sipgen")
# Force unix paths in dependencies.
SET(CMAKE_FORCE_UNIX_PATHS 1)
# The C and CXX include file search paths:
SET(CMAKE_C_INCLUDE_PATH
"/usr/include/python2.7"
)
SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
SET(CMAKE_ASM_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH})
# The C and CXX include file regular expressions for this directory.
SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$")
SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$")
SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN})
SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
| kdbanman/browseRDF | tulip-3.8.0-src/build/thirdparty/sip-4.13.2/sipgen/CMakeFiles/CMakeDirectoryInformation.cmake | CMake | gpl-3.0 | 978 |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18408
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Kerppi.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| ohel/kerppi | Kerppi/Properties/Settings.Designer.cs | C# | gpl-3.0 | 1,093 |
package blank.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="User")
public class User {
@Id
private String code;
private String name;
private String email;
private String password;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return name + " ( " + code + ", " + email + " )";
}
}
| codingore/TDD-Spring-Blank | TDD-Spring-Blank/src/java/blank/models/User.java | Java | gpl-3.0 | 916 |
Student Details
===============
|Name | ID |
|----------------|-----------|
|Timothy Kiyui | 4316886 |
|Brian Sim | 4316878 |
Features
========
NA
Bugs
====
NA
Missing
=======
NA
Resources
=========
tree.hh and tree_util.hh were acquired from http://tree.phi-sci.com/
tree.hh was slightly modified for extra requirements, needed to
simplify the making of this application. As always, it remains GPL.
License
=======
These programs are released under the GNU GPL V3 in compliance with
used libraries and developers will
Compile
=======
To compile the code, make sure you have sfml set up on your system.
Get it here: http://www.sfml-dev.org/download.php
After that, run make and everything should compile fine.
Usage
=====
Run the main file as so:
./maze_solver MAP ALGORITHM [FPS: 1 | 2 | etc] [-v]
Algorithms:
-bfs Breadth First Search
-dfs Depth First Search
-gdfs Greedy Best First Search
-ass A* Search
-bs Beam Search
-hs Hill Climbing
| TimurKiyivinski/ai-maze-tree | README.md | Markdown | gpl-3.0 | 998 |
<?php
/*
.---------------------------------------------------------------------------.
| Software: N3O CMS (frontend and backend) |
| Version: 2.2.2 |
| Contact: contact author (also http://blaz.at/home) |
| ------------------------------------------------------------------------- |
| Author: Blaž Kristan (blaz@kristan-sp.si) |
| Copyright (c) 2007-2014, Blaž Kristan. All Rights Reserved. |
| ------------------------------------------------------------------------- |
| License: Distributed under the Lesser General Public License (LGPL) |
| http://www.gnu.org/copyleft/lesser.html |
| ------------------------------------------------------------------------- |
| This file is part of N3O CMS (backend). |
| |
| N3O CMS 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. |
| |
| N3O CMS 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. |
'---------------------------------------------------------------------------'
*/
setcookie("img_upload",'0');
setcookie("img_path", "");
if ( isset($_POST['Who']) ) {
switch ( $_POST['Who'] ) {
case "all": $filter = 'Enabled <> 0'; break;
case "new": $filter = 'Enabled <> 0 AND LastVisit IS NULL'; break;
case "subscribed": $filter = 'Enabled <> 0 AND MailList <> 0'; break;
case "moderators": $filter = 'Enabled <> 0 AND AccessLeel > 2'; break;
default: $filter = 'ID = '.(int)$_POST['ID']; break;
}
$MailList = $db->get_results(
"SELECT Name, Nickname, Email
FROM frmMembers
WHERE $filter"
);
$Body = $_POST['Body'];
$Body = str_replace(" ", " ", $Body);
$Body = str_replace("š", "š", $Body);
$Body = str_replace("Š", "Š", $Body);
$AltBody = preg_replace( "/<([\/]*)DIV([^>]*)>/i", "<\1p>", $Body );
$AltBody = str_ireplace( '<li>', "* ", $AltBody );
$AltBody = preg_replace( "/<([\/]*)([^>]*)>/i", "", $AltBody );
$Body = "<style>" . file_get_contents('./mail.css') . "</style>\n" . $Body;
if ( $MailList ) foreach ( $MailList as $User ) {
$SMTPServer->AddAddress( $User->Email, $User->Name );
$SMTPServer->Subject = AppName . " : " . $_POST['Subj'];
$SMTPServer->AltBody = $AltBody;
$SMTPServer->MsgHTML( $Body );
if ( !$SMTPServer->Send() )
echo "<!-- mail send error (".$User->Email.") -->\n";
$SMTPServer->ClearAddresses();
}
}
?>
<SCRIPT language="javascript" type="text/javascript">
<!--
function customResize() {
// vertically resize edit child divs
frame = $("#divContent").height(0).height( $("#divEdit").height() + $("#divEdit").position().top - $("#divContent").position().top );
edit = $("#HTMLeditor").parent(); // TD element
if ( edit.html() ) {
edit.height( frame.height() + frame.position().top - edit.position().top - 16 );
edit.width( frame.width() + frame.position().left - edit.position().left );
$("#HTMLeditor").height( edit.innerHeight() - 10 );
$("#HTMLeditor_ifr").height( $("#HTMLeditor").height() - $("#HTMLeditor_toolbargroup").height() );
}
}
$(document).ready(function(){
window.customResize = customResize;
// bind to the form's submit event
$("form[name='Vnos']").each(function(){
$(this).submit(function(){
this.Body.value = $("textarea[name='Body']").html();
$(this).ajaxSubmit({
target: '#divEdit',
beforeSubmit: function( formDataArr, jqObj, options ) {
var fObj = jqObj[0]; // form object
if (empty(fObj.Subj)) {alert("Please enter subject!"); fObj.Subj.focus(); return false;}
return true;
} // pre-submit callback
});
return false;
});
});
// resize content div
window.customResize();
// enable TinyMCE
$("textarea[name='Body']").tinymce({
script_url : '<?php echo $js ?>/tiny_mce/tiny_mce.js',
mode : "exact",
//language : "si",
elements : "HTMLeditor",
element_format : "html",
theme : "advanced",
content_css : "editor_css.php",
plugins : "inlinepopups,safari,contextmenu",
auto_cleanup_word : true,
extended_valid_elements : "a[href|target|title],hr[size|noshade],font[face|size|color|style],div[class|align|style],span[class|style],ol[type],ul[type]",
invalid_elements : "iframe,layer,script,link",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_buttons1 : "bold,italic,underline,sub,sup,separator,bullist,numlist,outdent,indent,blockquote,separator",
theme_advanced_buttons1_add : "justifyleft,justifycenter,justifyright,justifyfull,separator,link,unlink",
theme_advanced_buttons2 : "",
theme_advanced_buttons3 : "",
theme_advanced_styles : ""
});
});
//-->
</SCRIPT>
<DIV CLASS="subtitle">
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="100%">
<TR>
<td><div id="ToggleFrame" style="display:none;"> <A HREF="javascript:toggleFrame()"><img src="pic/control.frame.gif" height="14" width="14" alt="Preklop celo/zmanjۡno okno" border="0" align="absmiddle" class="icon"> List</a></div></td>
<?php if ( isset($_POST['Who']) ) : ?>
<TD id="editNote"><B CLASS="red">Message sent!</B></TD>
<?php else : ?>
<TD id="editNote" ALIGN="right"><?php echo $_GET['Izbor'] ?> - Send message </TD>
<?php endif ?>
</TR>
</TABLE>
</DIV>
<DIV ID="divContent" style="margin: 5px;">
<FORM NAME="Vnos" ACTION="<?php echo $_SERVER['PHP_SELF']?>?<?php echo $_SERVER['QUERY_STRING'] ?>" METHOD="post">
<TABLE BORDER="0" CELLPADDING="2" CELLSPACING="0" WIDTH="100%">
<?php if ( isset($_GET['ID']) ) : ?>
<INPUT TYPE="Hidden" NAME="ID" VALUE="<?php echo $_GET['ID'] ?>">
<INPUT TYPE="Hidden" NAME="Who" VALUE="single">
<?php else : ?>
<TR>
<TD ALIGN="right"><b>Send to</b>: </TD>
<TD CLASS="a10" VALIGN="top">
<INPUT TYPE="Radio" NAME="Who" CHECKED VALUE="subscribed"> subscribed
<INPUT TYPE="Radio" NAME="Who" value="moderators"> moderators
<INPUT TYPE="Radio" NAME="Who" VALUE="all"> all
<INPUT TYPE="Radio" NAME="Who" VALUE="new"> new members
</TD>
<TD ALIGN="right"><INPUT TYPE="Submit" NAME="what" VALUE=" Send " CLASS="but"></TD>
</TR>
<?php endif ?>
<TR>
<TD ALIGN="right"><b>Subject</b>: </TD>
<TD><INPUT NAME="Subj" CLASS="Txt" MAXLENGTH="64" STYLE="width:100%;"></TD>
</TR>
<TR>
<TD ALIGN="center" COLSPAN="3">
<TEXTAREA NAME="Body" ID="HTMLeditor" STYLE="width:100%;height:100%;"></TEXTAREA>
</TD>
</TR>
</TABLE>
</FORM>
<DIV>
| blazoncek/n3o_phpcms | servis/_template/inc_frmEmail.php | PHP | gpl-3.0 | 7,387 |
'''
This file is part of pyShop
pyShop 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.
pyShop 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 pyShop. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) Steve "Uru" West 2012 <uruwolf@gmail.com>
'''
from products.models import Catergory, Product
from django.contrib import admin
#Catergories get the generic admin treatment
admin.site.register(Catergory)
class ProductAdmin(admin.ModelAdmin):
'''Contains the admin panel settings for product objects
Currently set to display the name and catergory,
be filterable by catergory
and searchable via name and description.'''
list_display = ('name', 'catergory')
list_filter = ['catergory']
search_fields = ['name', 'description']
admin.site.register(Product, ProductAdmin)
| Uruwolf/pyshop | products/admin.py | Python | gpl-3.0 | 1,218 |
# Copyright (C) 2010 Canonical
#
# Authors:
# Didier Roche <didrocks@ubuntu.com>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import hashlib
import json
import logging
import os
LOG = logging.getLogger(__name__)
from oneconf.hosts import Hosts, HostError
from oneconf.distributor import get_distro
from oneconf.paths import ONECONF_CACHE_DIR, PACKAGE_LIST_PREFIX
class PackageSetHandler(object):
"""
Direct access to database for getting and updating the list
"""
def __init__(self, hosts=None):
self.hosts = hosts
if not hosts:
self.hosts = Hosts()
self.distro = get_distro()
self.last_storage_sync = None
# create cache for storage package list, indexed by hostid
self.package_list = {}
def update(self):
'''update the store with package list'''
hostid = self.hosts.current_host['hostid']
LOG.debug("Updating package list")
newpkg_list = self.distro.compute_local_packagelist()
LOG.debug("Creating the checksum")
checksum = hashlib.sha224(str(newpkg_list)).hexdigest()
LOG.debug("Package list need refresh")
self.package_list[hostid] = {'valid': True, 'package_list': newpkg_list}
with open(os.path.join(self.hosts.get_currenthost_dir(), '%s_%s' % (PACKAGE_LIST_PREFIX, hostid)), 'w') as f:
json.dump(self.package_list[hostid]['package_list'], f)
if self.hosts.current_host['packages_checksum'] != checksum:
self.hosts.current_host['packages_checksum'] = checksum
self.hosts.save_current_host()
LOG.debug("Update done")
def get_packages(self, hostid=None, hostname=None, only_manual=False):
'''get all installed packages from the storage'''
hostid = self.hosts.get_hostid_from_context(hostid, hostname)
LOG.debug ("Request for package list for %s with only manual packages reduced scope to: %s", hostid, only_manual)
package_list = self._get_installed_packages(hostid)
if only_manual:
package_list = [package_elem for package_elem in package_list if package_list[package_elem]["auto"] == False]
return package_list
def _get_installed_packages(self, hostid):
'''get installed packages from the storage or cache
Return: uptodate package_list'''
need_reload = False
try:
if self.package_list[hostid]['valid']:
LOG.debug("Hit cache for package list")
package_list = self.package_list[hostid]['package_list']
else:
need_reload = True
except KeyError:
need_reload = True
if need_reload:
self.package_list[hostid] = {'valid': True, 'package_list': self._get_packagelist_from_store(hostid)}
return self.package_list[hostid]['package_list']
def diff(self, distant_hostid=None, distant_hostname=None):
'''get a diff from current package state from another host
This function can be use to make a diff between all packages installed on both computer
, use_cache
Return: (packages_to_install (packages in distant_hostid not in local_hostid),
packages_to_remove (packages in local hostid not in distant_hostid))
'''
distant_hostid = self.hosts.get_hostid_from_context(distant_hostid, distant_hostname)
LOG.debug("Collecting all installed packages on this system")
local_package_list = set(self.get_packages(self.hosts.current_host['hostid'], False))
LOG.debug("Collecting all installed packages on the other system")
distant_package_list = set(self.get_packages(distant_hostid, False))
LOG.debug("Comparing")
packages_to_install = [x for x in distant_package_list if x not in local_package_list]
packages_to_remove = [x for x in local_package_list if x not in distant_package_list]
# for Dbus which doesn't like empty list
if not packages_to_install:
packages_to_install = ''
if not packages_to_remove:
packages_to_remove = ''
return(packages_to_install, packages_to_remove)
def _get_packagelist_from_store(self, hostid):
'''load package list for every computer in cache'''
LOG.debug('get package list from store for hostid: %s' % hostid)
# load current content in cache
try:
with open(os.path.join(self.hosts.get_currenthost_dir(), '%s_%s' % (PACKAGE_LIST_PREFIX, hostid)), 'r') as f:
# can be none in corrupted null file
pkg_list = json.load(f)
except (IOError, ValueError):
LOG.warning ("no valid package list stored for hostid: %s" % hostid)
pkg_list = None
if pkg_list is None:
pkg_list = {}
# there is no way that no package is installed in current host
# At least, there is oneconf ;) Ask for refresh
if hostid == self.hosts.current_host['hostid']:
LOG.debug ("Processing first update for current host")
self.update()
pkg_list = self.package_list[hostid]['package_list']
return pkg_list
| Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/oneconf/packagesethandler.py | Python | gpl-3.0 | 6,034 |
// -----------------------------------------
// SoundScribe (TM) and related software.
//
// Copyright (C) 2007-2011 Vannatech
// http://www.vannatech.com
// All rights reserved.
//
// This source code is subject to the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
// 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.
// -----------------------------------------
using System;
using System.Runtime.InteropServices;
namespace Vannatech.CoreAudio.Structures
{
/// <summary>
/// Describes a change in the volume level or muting state of an audio endpoint device.
/// </summary>
/// <remarks>
/// MSDN Reference: http://msdn.microsoft.com/en-us/library/dd370799.aspx
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public struct AUDIO_VOLUME_NOTIFICATION_DATA
{
/// <summary>
/// The user event context supplied during the change request.
/// </summary>
public Guid EventContext;
/// <summary>
/// Specifies whether the audio stream is currently muted.
/// </summary>
[MarshalAs(UnmanagedType.Bool)]
public bool IsMuted;
/// <summary>
/// The current master volume level of the audio stream.
/// </summary>
[MarshalAs(UnmanagedType.R4)]
public float MasterVolume;
/// <summary>
/// Specifies the number of channels in the audio stream.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public UInt32 ChannelCount;
/// <summary>
/// The volume level of each channel in the stream.
/// </summary>
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.R4)]
public float[] ChannelVolumes;
}
}
| aadfPT/StreamsMaster | netcoreaudio-master/CoreAudio/Structures/AUDIO_VOLUME_NOTIFICATION_DATA.cs | C# | gpl-3.0 | 2,191 |
/* Message catalogs for internationalization.
Copyright (C) 1995-1997, 2000-2015 Free Software Foundation,
Inc.
This program 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 2.1 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/>. */
#ifndef _LIBINTL_H
#define _LIBINTL_H 1
#include <locale.h>
#if (defined __APPLE__ && defined __MACH__) && 1
# include <xlocale.h>
#endif
/* The LC_MESSAGES locale category is the category used by the functions
gettext() and dgettext(). It is specified in POSIX, but not in ANSI C.
On systems that don't define it, use an arbitrary value instead.
On Solaris, <locale.h> defines __LOCALE_H (or _LOCALE_H in Solaris 2.5)
then includes <libintl.h> (i.e. this file!) and then only defines
LC_MESSAGES. To avoid a redefinition warning, don't define LC_MESSAGES
in this case. */
#if !defined LC_MESSAGES && !(defined __LOCALE_H || (defined _LOCALE_H && defined __sun))
# define LC_MESSAGES 1729
#endif
/* We define an additional symbol to signal that we use the GNU
implementation of gettext. */
#define __USE_GNU_GETTEXT 1
/* Provide information about the supported file formats. Returns the
maximum minor revision number supported for a given major revision. */
#define __GNU_GETTEXT_SUPPORTED_REVISION(major) \
((major) == 0 || (major) == 1 ? 1 : -1)
/* Resolve a platform specific conflict on DJGPP. GNU gettext takes
precedence over _conio_gettext. */
#ifdef __DJGPP__
# undef gettext
#endif
#ifdef __cplusplus
extern "C"
{
#endif
/* Version number: (major<<16) + (minor<<8) + subminor */
#define LIBINTL_VERSION 0x001306
extern int libintl_version;
/* We redirect the functions to those prefixed with "libintl_". This is
necessary, because some systems define gettext/textdomain/... in the C
library (namely, Solaris 2.4 and newer, and GNU libc 2.0 and newer).
If we used the unprefixed names, there would be cases where the
definition in the C library would override the one in the libintl.so
shared library. Recall that on ELF systems, the symbols are looked
up in the following order:
1. in the executable,
2. in the shared libraries specified on the link command line, in order,
3. in the dependencies of the shared libraries specified on the link
command line,
4. in the dlopen()ed shared libraries, in the order in which they were
dlopen()ed.
The definition in the C library would override the one in libintl.so if
either
* -lc is given on the link command line and -lintl isn't, or
* -lc is given on the link command line before -lintl, or
* libintl.so is a dependency of a dlopen()ed shared library but not
linked to the executable at link time.
Since Solaris gettext() behaves differently than GNU gettext(), this
would be unacceptable.
The redirection happens by default through macros in C, so that &gettext
is independent of the compilation unit, but through inline functions in
C++, in order not to interfere with the name mangling of class fields or
class methods called 'gettext'. */
/* The user can define _INTL_REDIRECT_INLINE or _INTL_REDIRECT_MACROS.
If he doesn't, we choose the method. A third possible method is
_INTL_REDIRECT_ASM, supported only by GCC. */
#if !(defined _INTL_REDIRECT_INLINE || defined _INTL_REDIRECT_MACROS)
# if defined __GNUC__ && __GNUC__ >= 2 && !(defined __APPLE_CC__ && __APPLE_CC__ > 1) && !defined __MINGW32__ && !(__GNUC__ == 2 && defined _AIX) && (defined __STDC__ || defined __cplusplus)
# define _INTL_REDIRECT_ASM
# else
# ifdef __cplusplus
# define _INTL_REDIRECT_INLINE
# else
# define _INTL_REDIRECT_MACROS
# endif
# endif
#endif
/* Auxiliary macros. */
#ifdef _INTL_REDIRECT_ASM
# define _INTL_ASM(cname) __asm__ (_INTL_ASMNAME (__USER_LABEL_PREFIX__, #cname))
# define _INTL_ASMNAME(prefix,cnamestring) _INTL_STRINGIFY (prefix) cnamestring
# define _INTL_STRINGIFY(prefix) #prefix
#else
# define _INTL_ASM(cname)
#endif
/* _INTL_MAY_RETURN_STRING_ARG(n) declares that the given function may return
its n-th argument literally. This enables GCC to warn for example about
printf (gettext ("foo %y")). */
#if defined __GNUC__ && __GNUC__ >= 3 && !(defined __APPLE_CC__ && __APPLE_CC__ > 1 && defined __cplusplus)
# define _INTL_MAY_RETURN_STRING_ARG(n) __attribute__ ((__format_arg__ (n)))
#else
# define _INTL_MAY_RETURN_STRING_ARG(n)
#endif
/* Look up MSGID in the current default message catalog for the current
LC_MESSAGES locale. If not found, returns MSGID itself (the default
text). */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_gettext (const char *__msgid)
_INTL_MAY_RETURN_STRING_ARG (1);
static inline char *gettext (const char *__msgid)
{
return libintl_gettext (__msgid);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define gettext libintl_gettext
#endif
extern char *gettext (const char *__msgid)
_INTL_ASM (libintl_gettext) _INTL_MAY_RETURN_STRING_ARG (1);
#endif
/* Look up MSGID in the DOMAINNAME message catalog for the current
LC_MESSAGES locale. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_dgettext (const char *__domainname,
const char *__msgid)
_INTL_MAY_RETURN_STRING_ARG (2);
static inline char *dgettext (const char *__domainname, const char *__msgid)
{
return libintl_dgettext (__domainname, __msgid);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define dgettext libintl_dgettext
#endif
extern char *dgettext (const char *__domainname, const char *__msgid)
_INTL_ASM (libintl_dgettext) _INTL_MAY_RETURN_STRING_ARG (2);
#endif
/* Look up MSGID in the DOMAINNAME message catalog for the current CATEGORY
locale. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_dcgettext (const char *__domainname,
const char *__msgid,
int __category)
_INTL_MAY_RETURN_STRING_ARG (2);
static inline char *dcgettext (const char *__domainname,
const char *__msgid, int __category)
{
return libintl_dcgettext (__domainname, __msgid, __category);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define dcgettext libintl_dcgettext
#endif
extern char *dcgettext (const char *__domainname, const char *__msgid,
int __category)
_INTL_ASM (libintl_dcgettext) _INTL_MAY_RETURN_STRING_ARG (2);
#endif
/* Similar to 'gettext' but select the plural form corresponding to the
number N. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_ngettext (const char *__msgid1, const char *__msgid2,
unsigned long int __n)
_INTL_MAY_RETURN_STRING_ARG (1) _INTL_MAY_RETURN_STRING_ARG (2);
static inline char *ngettext (const char *__msgid1, const char *__msgid2,
unsigned long int __n)
{
return libintl_ngettext (__msgid1, __msgid2, __n);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define ngettext libintl_ngettext
#endif
extern char *ngettext (const char *__msgid1, const char *__msgid2,
unsigned long int __n)
_INTL_ASM (libintl_ngettext)
_INTL_MAY_RETURN_STRING_ARG (1) _INTL_MAY_RETURN_STRING_ARG (2);
#endif
/* Similar to 'dgettext' but select the plural form corresponding to the
number N. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_dngettext (const char *__domainname,
const char *__msgid1, const char *__msgid2,
unsigned long int __n)
_INTL_MAY_RETURN_STRING_ARG (2) _INTL_MAY_RETURN_STRING_ARG (3);
static inline char *dngettext (const char *__domainname,
const char *__msgid1, const char *__msgid2,
unsigned long int __n)
{
return libintl_dngettext (__domainname, __msgid1, __msgid2, __n);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define dngettext libintl_dngettext
#endif
extern char *dngettext (const char *__domainname,
const char *__msgid1, const char *__msgid2,
unsigned long int __n)
_INTL_ASM (libintl_dngettext)
_INTL_MAY_RETURN_STRING_ARG (2) _INTL_MAY_RETURN_STRING_ARG (3);
#endif
/* Similar to 'dcgettext' but select the plural form corresponding to the
number N. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_dcngettext (const char *__domainname,
const char *__msgid1, const char *__msgid2,
unsigned long int __n, int __category)
_INTL_MAY_RETURN_STRING_ARG (2) _INTL_MAY_RETURN_STRING_ARG (3);
static inline char *dcngettext (const char *__domainname,
const char *__msgid1, const char *__msgid2,
unsigned long int __n, int __category)
{
return libintl_dcngettext (__domainname, __msgid1, __msgid2, __n,
__category);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define dcngettext libintl_dcngettext
#endif
extern char *dcngettext (const char *__domainname,
const char *__msgid1, const char *__msgid2,
unsigned long int __n, int __category)
_INTL_ASM (libintl_dcngettext)
_INTL_MAY_RETURN_STRING_ARG (2) _INTL_MAY_RETURN_STRING_ARG (3);
#endif
/* Set the current default message catalog to DOMAINNAME.
If DOMAINNAME is null, return the current default.
If DOMAINNAME is "", reset to the default of "messages". */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_textdomain (const char *__domainname);
static inline char *textdomain (const char *__domainname)
{
return libintl_textdomain (__domainname);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define textdomain libintl_textdomain
#endif
extern char *textdomain (const char *__domainname)
_INTL_ASM (libintl_textdomain);
#endif
/* Specify that the DOMAINNAME message catalog will be found
in DIRNAME rather than in the system locale data base. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_bindtextdomain (const char *__domainname,
const char *__dirname);
static inline char *bindtextdomain (const char *__domainname,
const char *__dirname)
{
return libintl_bindtextdomain (__domainname, __dirname);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define bindtextdomain libintl_bindtextdomain
#endif
extern char *bindtextdomain (const char *__domainname,
const char *__dirname)
_INTL_ASM (libintl_bindtextdomain);
#endif
/* Specify the character encoding in which the messages from the
DOMAINNAME message catalog will be returned. */
#ifdef _INTL_REDIRECT_INLINE
extern char *libintl_bind_textdomain_codeset (const char *__domainname,
const char *__codeset);
static inline char *bind_textdomain_codeset (const char *__domainname,
const char *__codeset)
{
return libintl_bind_textdomain_codeset (__domainname, __codeset);
}
#else
#ifdef _INTL_REDIRECT_MACROS
# define bind_textdomain_codeset libintl_bind_textdomain_codeset
#endif
extern char *bind_textdomain_codeset (const char *__domainname,
const char *__codeset)
_INTL_ASM (libintl_bind_textdomain_codeset);
#endif
/* Support for format strings with positions in *printf(), following the
POSIX/XSI specification.
Note: These replacements for the *printf() functions are visible only
in source files that #include <libintl.h> or #include "gettext.h".
Packages that use *printf() in source files that don't refer to _()
or gettext() but for which the format string could be the return value
of _() or gettext() need to add this #include. Oh well. */
#if !1
#include <stdio.h>
#include <stddef.h>
/* Get va_list. */
#if (defined __STDC__ && __STDC__) || defined __cplusplus || defined _MSC_VER
# include <stdarg.h>
#else
# include <varargs.h>
#endif
#if !(defined fprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef fprintf
#define fprintf libintl_fprintf
extern int fprintf (FILE *, const char *, ...);
#endif
#if !(defined vfprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef vfprintf
#define vfprintf libintl_vfprintf
extern int vfprintf (FILE *, const char *, va_list);
#endif
#if !(defined printf && defined _GL_STDIO_H) /* don't override gnulib */
#undef printf
#if defined __NetBSD__ || defined __BEOS__ || defined __CYGWIN__ || defined __MINGW32__
/* Don't break __attribute__((format(printf,M,N))).
This redefinition is only possible because the libc in NetBSD, Cygwin,
mingw does not have a function __printf__.
Alternatively, we could have done this redirection only when compiling with
__GNUC__, together with a symbol redirection:
extern int printf (const char *, ...)
__asm__ (#__USER_LABEL_PREFIX__ "libintl_printf");
But doing it now would introduce a binary incompatibility with already
distributed versions of libintl on these systems. */
# define libintl_printf __printf__
#endif
#define printf libintl_printf
extern int printf (const char *, ...);
#endif
#if !(defined vprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef vprintf
#define vprintf libintl_vprintf
extern int vprintf (const char *, va_list);
#endif
#if !(defined sprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef sprintf
#define sprintf libintl_sprintf
extern int sprintf (char *, const char *, ...);
#endif
#if !(defined vsprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef vsprintf
#define vsprintf libintl_vsprintf
extern int vsprintf (char *, const char *, va_list);
#endif
#if 1
#if !(defined snprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef snprintf
#define snprintf libintl_snprintf
extern int snprintf (char *, size_t, const char *, ...);
#endif
#if !(defined vsnprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef vsnprintf
#define vsnprintf libintl_vsnprintf
extern int vsnprintf (char *, size_t, const char *, va_list);
#endif
#endif
#if 1
#if !(defined asprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef asprintf
#define asprintf libintl_asprintf
extern int asprintf (char **, const char *, ...);
#endif
#if !(defined vasprintf && defined _GL_STDIO_H) /* don't override gnulib */
#undef vasprintf
#define vasprintf libintl_vasprintf
extern int vasprintf (char **, const char *, va_list);
#endif
#endif
#if 0
#undef fwprintf
#define fwprintf libintl_fwprintf
extern int fwprintf (FILE *, const wchar_t *, ...);
#undef vfwprintf
#define vfwprintf libintl_vfwprintf
extern int vfwprintf (FILE *, const wchar_t *, va_list);
#undef wprintf
#define wprintf libintl_wprintf
extern int wprintf (const wchar_t *, ...);
#undef vwprintf
#define vwprintf libintl_vwprintf
extern int vwprintf (const wchar_t *, va_list);
#undef swprintf
#define swprintf libintl_swprintf
extern int swprintf (wchar_t *, size_t, const wchar_t *, ...);
#undef vswprintf
#define vswprintf libintl_vswprintf
extern int vswprintf (wchar_t *, size_t, const wchar_t *, va_list);
#endif
#endif
/* Support for the locale chosen by the user. */
#if (defined __APPLE__ && defined __MACH__) || defined _WIN32 || defined __WIN32__ || defined __CYGWIN__
#ifndef GNULIB_defined_setlocale /* don't override gnulib */
#undef setlocale
#define setlocale libintl_setlocale
extern char *setlocale (int, const char *);
#endif
#if 1
#undef newlocale
#define newlocale libintl_newlocale
extern locale_t newlocale (int, const char *, locale_t);
#endif
#endif
/* Support for relocatable packages. */
/* Sets the original and the current installation prefix of the package.
Relocation simply replaces a pathname starting with the original prefix
by the corresponding pathname with the current prefix instead. Both
prefixes should be directory names without trailing slash (i.e. use ""
instead of "/"). */
#define libintl_set_relocation_prefix libintl_set_relocation_prefix
extern void
libintl_set_relocation_prefix (const char *orig_prefix,
const char *curr_prefix);
#ifdef __cplusplus
}
#endif
#endif /* libintl.h */
| KubaKaszycki/libMhO | intl/libintl.h | C | gpl-3.0 | 16,209 |
.upshot {
text-align: center;
margin-top: 8em;
margin-bottom: 8em;
}
.output {
max-width: 40em;
margin-left: auto;
margin-right: auto;
}
.programmer-hours {
text-align: right;
} | ostewart/shouldioptimize | public/stylesheets/main.css | CSS | gpl-3.0 | 207 |
.page-wrap{
background: #ffffff;
padding: 10px 0 25px 0;
}
.payment-tips{
height: 40px;
line-height: 40px;
font-size: 18px;
font-weight: bold;
color: #666666;
text-align: center;
}
.payment-tips.enhance{
color: #c60023;
}
.img-con{
margin: 0 auto;
width:300px;
height: 300px;
background: #ffffff;
border: 1px solid #ffffff;
}
.img-con .qr-code{
width: 100%;
height: 100%;
} | Liweimin0512/mmall-fe | src/page/payment/index.css | CSS | gpl-3.0 | 437 |
/*
* Copyright (C) 2007 Eric Seidel <eric@webkit.org>
* Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2008 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SVGGlyphElement_h
#define SVGGlyphElement_h
#if ENABLE(SVG_FONTS)
#include "SVGGlyph.h"
#include "SVGStyledElement.h"
namespace WebCore {
class SVGFontData;
class SVGGlyphElement : public SVGStyledElement {
public:
static PassRefPtr<SVGGlyphElement> create(const QualifiedName&, Document*);
SVGGlyph buildGlyphIdentifier() const;
// Helper function used by SVGFont
static void inheritUnspecifiedAttributes(SVGGlyph&, const SVGFontData*);
static String querySVGFontLanguage(const SVGElement*);
// Helper function shared between SVGGlyphElement & SVGMissingGlyphElement
static SVGGlyph buildGenericGlyphIdentifier(const SVGElement*);
private:
SVGGlyphElement(const QualifiedName&, Document*);
// FIXME: svgAttributeChanged missing.
virtual void parseAttribute(Attribute*) OVERRIDE;
virtual InsertionNotificationRequest insertedInto(Node*) OVERRIDE;
virtual void removedFrom(Node*) OVERRIDE;
virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
void invalidateGlyphCache();
};
} // namespace WebCore
#endif // ENABLE(SVG_FONTS)
#endif
| cs-au-dk/Artemis | WebKit/Source/WebCore/svg/SVGGlyphElement.h | C | gpl-3.0 | 2,077 |
# comhuayra-xul-ext-webmenu
Añade un botón que despliega un menú de navegación para acceder a los sitios de Comunidad Huayra
- Problemas conocidos
- En temas del sistema muy oscuros se confunde el ícono del botón
| ComunidadHuayra/Navegadores | comhuayra-xul-ext-webmenu/README.md | Markdown | gpl-3.0 | 224 |
@echo off
echo Windows | christianspecht/scm-backup | src/ScmBackup.Tests.Integration/Scm/FakeCommandLineScmTools/FakeCommandLineScm-Command-Windows.bat | Batchfile | gpl-3.0 | 22 |
<?php
/**
* TrcIMPLAN Sitio Web - Turismo urbano como motor en las ciudades
*
* Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package TrcIMPLANSitioWeb
*/
namespace Blog;
/**
* Clase TurismoUrbanoComoMotorEnLasCiudades
*/
class TurismoUrbanoComoMotorEnLasCiudades extends \Base\PublicacionSchemaBlogPosting {
/**
* Constructor
*/
public function __construct() {
// Ejecutar constructor en el padre
parent::__construct();
// Título, autor y fecha
$this->nombre = 'Turismo urbano como motor en las ciudades';
$this->autor = 'Arq. Ángeles Melisa Rodríguez Salas';
$this->fecha = '2015-08-13T10:40';
// El nombre del archivo a crear
$this->archivo = 'turismo-urbano-como-motor-en-las-ciudades';
// La descripción y claves dan información a los buscadores y redes sociales
$this->descripcion = 'Los patrimonios históricos de las ciudades se pueden convertir en atractivos turísticos. Promoviendo más actividades y servicios comerciales, la modernización de la infraestructura, enbellecimiento de la imagen urbana y mejor calidad de vida.';
$this->claves = 'IMPLAN, Torreon';
// Ruta al archivo markdown con el contenido
$this->contenido_archivo_markdown = 'lib/Blog/TurismoUrbanoComoMotorEnLasCiudades.md';
// Para el Organizador
$this->categorias = array('Cultura', 'Infraestructura', 'Sector Automotriz');
$this->fuentes = array();
$this->regiones = array('Torreón', 'Gómez Palacio', 'Lerdo', 'Matamoros', 'La Laguna');
} // constructor
} // Clase TurismoUrbanoComoMotorEnLasCiudades
?>
| TRCIMPLAN/trcimplan.github.io | lib/Blog/TurismoUrbanoComoMotorEnLasCiudades.php | PHP | gpl-3.0 | 2,518 |
<?php echo $message; ?>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-group"></i> Daftar Dokumen</h3>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th>Created</th>
<th>Title</th>
<th>Type</th>
<th style="width: 80px;"><a href="<?= site_url('group/add') ?>"> <button class="btn btn-primary btn-xs" type="button" ><i class="fa fa-plus-circle"></i> Tambah </button> </a></th>
</tr>
</thead>
<?php $i = 0; ?>
<?php
if ($dokumens->num_rows() > 0)
{
foreach ($dokumens->result() as $dokumen):
?>
<tbody>
<tr class="gradeA">
<td><?= ++$i; ?></td>
<td><?= ucfirst($dokumen->created) ?></td>
<td><?= ucfirst($dokumen->title) ?></td>
<td><?= $dokumen->type?></td>
<td>
<a href="<?= site_url("dokumen/detail/{$dokumen->id}")?>"><i class="fa fa-eye fa-fw"></i></a>
<a href="<?= site_url("dokumen/edit/{$dokumen->id}")?>"><i class="fa fa-edit fa-fw"></i></a>
<a href="<?= site_url("dokumen/delete/{$dokumen->id}")?>"><i class="fa fa-trash-o fa-fw"></i></a>
</td>
</tr>
</tbody>
<?php endforeach; ?>
<?php
}else
{
echo "<tr><td colspan='7' align='center'>Data Record Dokumen Masih Kosong!</td></tr>";
}
?>
</table>
</div>
</div>
<div class="panel-footer"></div>
</div>
<ul class="pagination">
<li class="disabled"><a href="#">«</a></li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li><a href="#">»</a></li>
</ul>
</div>
</div> | mdestafadilah/akh | app/modules/dokumen/views/index_dokumen.php | PHP | gpl-3.0 | 3,048 |
/*
DA-NRW Software Suite | SIP-Builder
Copyright (C) 2014 Historisch-Kulturwissenschaftliche Informationsverarbeitung
Universität zu Köln
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 de.uzk.hki.da.sb;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import de.uzk.hki.da.metadata.ContractRights;
import de.uzk.hki.da.metadata.FileExtensions;
import de.uzk.hki.da.metadata.LidoLicense;
import de.uzk.hki.da.metadata.LidoParser;
import de.uzk.hki.da.metadata.MetsLicense;
import de.uzk.hki.da.metadata.MetsParser;
import de.uzk.hki.da.metadata.NullLastComparator;
import de.uzk.hki.da.metadata.PremisXmlWriter;
import de.uzk.hki.da.pkg.BagitUtils;
import de.uzk.hki.da.pkg.CopyUtility;
import de.uzk.hki.da.pkg.NestedContentStructure;
import de.uzk.hki.da.pkg.SipArchiveBuilder;
import de.uzk.hki.da.utils.C;
import de.uzk.hki.da.utils.FolderUtils;
import de.uzk.hki.da.utils.FormatDetectionService;
import de.uzk.hki.da.utils.Utilities;
import de.uzk.hki.da.utils.XMLUtils;
import gov.loc.repository.bagit.creator.BagCreator;
import gov.loc.repository.bagit.domain.Bag;
import gov.loc.repository.bagit.reader.BagReader;
import gov.loc.repository.bagit.verify.BagVerifier;
/**
* The central SIP production class
*
* @author Trebunski Eugen
* @author Thomas Kleinke
*/
public class SIPFactory {
private Logger logger = LogManager.getLogger(SIPFactory.class);
private String sourcePath = null;
private String destinationPath = null;
private String workingPath = null;
private KindOfSIPBuilding kindofSIPBuilding = null;
private String name = null;
private boolean createCollection;
private String collectionName = null;
private File collectionFolder = null;
private ContractRights contractRights = new ContractRights();
// DANRW-1515
private FileExtensions fileExtensions = new FileExtensions();
private HashMap<String, List<String>> fileExtensionsList = new HashMap<String, List<String>>();
private File rightsSourcePremisFile = null;
private SipBuildingProcess sipBuildingProcess;
private boolean alwaysOverwrite;
private boolean skippedFiles;
private boolean ignoreZeroByteFiles = false;
private boolean compress;
// DANRW-1416: Extension for disable tar - function
private boolean tar = true;
private String destDir = null;
// DANRW-1352: to disable bagit creation
private boolean bagit = true;
// DANRW-1515: Extension for allowDuplicateFilename
private boolean allowDuplicateFilename = false;
private boolean checkFileExtensionOff = false;
private List<String> forbiddenFileExtensions = null;
private File listCreationTempFolder = null;
private MessageWriter messageWriter;
private ProgressManager progressManager;
private Feedback returnCode;
public enum KindOfSIPBuilding {
MULTIPLE_FOLDERS, SINGLE_FOLDER, NESTED_FOLDERS
};
/**
* Creates and starts a new SIP building process
*/
public void startSIPBuilding() {
sipBuildingProcess = new SipBuildingProcess();
sipBuildingProcess.start();
}
/**
* Creates a list of source folders
*
* @param folderPath
* The main source folder path
* @throws Exception
*/
HashMap<File, String> createFolderList(String folderPath) throws Exception {
HashMap<File, String> folderListWithFolderNames = new HashMap<File, String>();
File sourceFolder = new File(folderPath);
switch (kindofSIPBuilding) {
case MULTIPLE_FOLDERS:
List<File> folderContent = Arrays.asList(sourceFolder.listFiles());
for (File file : folderContent) {
if (!file.isHidden() && file.isDirectory())
folderListWithFolderNames.put(file, null);
}
break;
case SINGLE_FOLDER:
folderListWithFolderNames.put(sourceFolder, null);
break;
case NESTED_FOLDERS:
NestedContentStructure ncs;
try {
TreeMap<File, String> metadataFileWithType = new FormatDetectionService(
sourceFolder).getMetadataFileWithType();
if (!metadataFileWithType.isEmpty()
&& (!metadataFileWithType.get(
metadataFileWithType.firstKey()).equals(
C.CB_PACKAGETYPE_METS))) {
messageWriter
.showMessage("Es wurde eine Metadatendatei des Typs "
+ metadataFileWithType
.get(metadataFileWithType
.firstKey())
+ " auf der obersten Ebene gefunden. "
+ "\nBitte wählen Sie diese Option ausschließlich für die Erstellung von SIPs des Typs METS.");
} else {
ncs = new NestedContentStructure(sourceFolder);
folderListWithFolderNames = ncs.getSipCandidates();
if (folderListWithFolderNames.isEmpty()) {
messageWriter
.showMessage("Es wurde kein Unterverzeichnis mit einer METS-Metadatendatei gefunden.");
}
break;
}
} catch (IOException e) {
throw new Exception(e);
}
default:
break;
}
return folderListWithFolderNames;
}
/**
* Starts the progress manager and creates a progress manager job for each
* SIP to build
*
* @param folderList
* The source folder list
* @return The method result as a Feedback enum
*/
private Feedback initializeProgressManager(List<File> folderList) {
progressManager.reset();
if (createCollection)
progressManager.addJob(-1, collectionName, 0);
int i = 0;
for (File folder : folderList) {
if (!folder.exists()) {
logger.error("Folder " + folder.getAbsolutePath()
+ " does not exist anymore.");
return Feedback.COPY_ERROR;
}
progressManager.addJob(i, folder.getName(),
FileUtils.sizeOfDirectory(folder));
i++;
}
progressManager.calculateProgressParts(createCollection);
progressManager.createStartMessage();
return Feedback.SUCCESS;
}
private String getTempFolderPath() {
if (workingPath == null || workingPath.length() == 0) {
return destinationPath + File.separator + getTempFolderName();
} else
return workingPath + File.separator + getTempFolderName();
}
/**
* Creates a SIP out of the given source folder
*
* @param jobId
* The job ID
* @param sourceFolder
* The source folder
* @return The method result as a Feedback enum
*/
private Feedback buildSIP(int jobId, File sourceFolder,
String newPackageName) {
progressManager.startJob(jobId);
Feedback feedback;
String packageName = "";
if (newPackageName != null) {
packageName = newPackageName;
} else {
packageName = getPackageName(sourceFolder);
}
File tempFolder = new File(getTempFolderPath());
File packageFolder = new File(tempFolder, packageName);
if ((feedback = copyFolder(jobId, sourceFolder, packageFolder)) != Feedback.SUCCESS) {
rollback(tempFolder);
return feedback;
}
if ((feedback = checkMetadataForLicense(jobId, sourceFolder, packageFolder)) != Feedback.SUCCESS) {
rollback(tempFolder);
return feedback;
}
if ((feedback = createPremisFile(jobId, packageFolder, packageName)) != Feedback.SUCCESS) {
rollback(tempFolder);
return feedback;
}
// DANRW-1352
if (bagit) {
if ((feedback = createBag(jobId, packageFolder)) != Feedback.SUCCESS) {
rollback(tempFolder);
return feedback;
}
}
return packageFolder(jobId,sourceFolder,packageFolder,tempFolder,packageName);
}
public Feedback packageFolder(int jobId, File sourceFolder, File packageFolder, File tempFolder, String packageName){// DANRW-1416
Feedback feedback;
if (tar) {
String archiveFileName = packageName;
if (compress)
archiveFileName += ".tgz";
else
archiveFileName += ".tar";
File archiveFile = new File(destinationPath + File.separator
+ archiveFileName);
if (!checkForExistingSip(archiveFile)) {
progressManager.skipJob(jobId);
skippedFiles = true;
return Feedback.SUCCESS;
}
File tmpArchiveFile = null;
tmpArchiveFile = new File(workingPath + File.separator
+ archiveFileName);
if (tmpArchiveFile.exists())
tmpArchiveFile.delete();
if (Utilities.checkForZeroByteFiles(sourceFolder, packageName,
messageWriter)) {
if (!ignoreZeroByteFiles) {
String message = "WARNING: Found zero byte files in folder "
+ sourceFolder + ":\n";
for (String s : messageWriter.getZeroByteFiles()) {
message += s;
message += "\n";
}
logger.info(message);
return Feedback.ZERO_BYTES_ERROR;
}
}
if ((feedback = buildArchive(jobId, packageFolder, tmpArchiveFile)) != Feedback.SUCCESS) {
rollback(tempFolder, tmpArchiveFile);
return feedback;
}
if (!getWorkingPath().equals(getDestinationPath())) {
if ((feedback = moveFile(tmpArchiveFile, archiveFile)) != Feedback.SUCCESS) {
rollback(tmpArchiveFile);
rollback(archiveFile);
return feedback;
}
}
if ((feedback = deleteTempFolder(jobId, tempFolder)) != Feedback.SUCCESS)
return feedback;
if (createCollection) {
if ((feedback = moveSipToCollectionFolder(jobId, archiveFile)) != Feedback.SUCCESS)
return feedback;
}
} else {
logger.debug("TempFolder : " + tempFolder + " -- destinationPath : " + getDestinationPath());
if ((feedback = copyFolder(jobId, tempFolder, new File(getDestinationPath()))) != Feedback.SUCCESS)
return feedback;
if ((feedback = deleteTempFolder(jobId, tempFolder)) != Feedback.SUCCESS)
return feedback;
}
return feedback;
}
private Feedback moveFile(File tmpArchiveFile, File archiveFile) {
try {
try {
FileUtils.moveFile(tmpArchiveFile, archiveFile);
} catch (FileExistsException e) {
archiveFile.delete();
FileUtils.moveFile(tmpArchiveFile, archiveFile);
}
} catch (IOException e) {
logger.error("Failed to copy " + tmpArchiveFile + " to "
+ archiveFile);
return Feedback.ARCHIVE_ERROR;
}
return Feedback.SUCCESS;
}
/**
* Copies the contents of the given source folder to a newly created temp
* folder
*
* @param jobId
* The job ID
* @param sourceFolder
* The source folder
* @param tempFolder
* The temp folder
* @return The method result as a Feedback enum
*/
private Feedback copyFolder(int jobId, File sourceFolder, File tempFolder) {
progressManager.copyProgress(jobId, 0);
File dataFolder = new File(tempFolder, "data");
dataFolder.mkdirs();
CopyUtility copyUtility = new CopyUtility();
copyUtility.setProgressManager(progressManager);
copyUtility.setJobId(jobId);
copyUtility.setSipBuildingProcess(sipBuildingProcess);
try {
if (!copyUtility.copyDirectory(sourceFolder, dataFolder,
forbiddenFileExtensions))
return Feedback.ABORT;
} catch (Exception e) {
logger.error(
"Failed to copy folder " + sourceFolder.getAbsolutePath()
+ " to " + tempFolder.getAbsolutePath(), e);
return Feedback.COPY_ERROR;
}
return Feedback.SUCCESS;
}
private Feedback checkMetadataForLicense(int jobId, File sourceFolder, File packageFolder) {
boolean premisLicenseBool=contractRights.getCclincense()!=null;
boolean metsLicenseBool=false;
boolean lidoLicenseBool=false;
boolean hasPipMetadataBool=false;
boolean publicationBool=contractRights.getPublicRights().getAllowPublication();
boolean instPublicationBool=contractRights.getInstitutionRights().getAllowPublication();
//activate to be able to create wrong licensed test sips
//publicationBool=false;
//instPublicationBool=false;
//end
//Nur bei publikationen Lizenzauswertungen vornehmen
if(publicationBool || instPublicationBool){
TreeMap<File, String> metadataFileWithType;
try {
metadataFileWithType = new FormatDetectionService(sourceFolder).getMetadataFileWithType();
if (metadataFileWithType.containsValue(C.CB_PACKAGETYPE_METS)) {
ArrayList<File> metsFiles = new ArrayList<File>();
ArrayList<MetsLicense> licenseMetsFile = new ArrayList<MetsLicense>();
for (File f : metadataFileWithType.keySet()) {
if (metadataFileWithType.get(f).equals(C.CB_PACKAGETYPE_METS)) {
metsFiles.add(f);
}
}
for (File f : metsFiles) {// assuming more as usual mets is allowed (check is done by FormatDetectionService) e.g. publicMets for testcase-creation
SAXBuilder builder = XMLUtils.createValidatingSaxBuilder();
Document metsDoc = builder.build(f);
MetsParser mp = new MetsParser(metsDoc);
licenseMetsFile.addAll(mp.getLicensesForWholeMets());
}
Collections.sort(licenseMetsFile, new NullLastComparator<MetsLicense>());
if (licenseMetsFile.get(0) == null) // all licenses are null
metsLicenseBool = false;
else if (!licenseMetsFile.get(0).equals(licenseMetsFile.get(licenseMetsFile.size() - 1))) // first and last lic have to be same in sorted array
return Feedback.INVALID_LICENSE_DATA_IN_METADATA;
else
metsLicenseBool = true;
hasPipMetadataBool=true;
}else if (metadataFileWithType.containsValue(C.CB_PACKAGETYPE_LIDO)) {
ArrayList<File> lidoFiles = new ArrayList<File>();
ArrayList<LidoLicense> licenseLidoFile = new ArrayList<LidoLicense>();
for (File f : metadataFileWithType.keySet())
if (metadataFileWithType.get(f).equals(C.CB_PACKAGETYPE_LIDO))
lidoFiles.add(f);
for (File f : lidoFiles) {// assuming more as one metadata is allowed (check is done by FormatDetectionService)
SAXBuilder builder = XMLUtils.createValidatingSaxBuilder();
Document metsDoc = builder.build(f);
LidoParser lp = new LidoParser(metsDoc);
licenseLidoFile.add(lp.getLicenseForWholeLido());
}
Collections.sort(licenseLidoFile, new NullLastComparator<LidoLicense>());
if (licenseLidoFile.get(0) == null) // all licenses are null
lidoLicenseBool = false;
else if (!licenseLidoFile.get(0).equals(licenseLidoFile.get(licenseLidoFile.size() - 1))) // first and last lic have to be same in sorted array
return Feedback.INVALID_LICENSE_DATA_IN_METADATA;
else
lidoLicenseBool = true;
hasPipMetadataBool=true;
}else {
hasPipMetadataBool=false;
}
} catch (Exception e) {
e.printStackTrace();
return Feedback.INVALID_LICENSE_DATA_IN_METADATA;
}
}
//activate to be able to create non licensed test sips
//publicationBool=false;
//premisLicenseBool=false;
//publicationBool=false;
//end
if(publicationBool && premisLicenseBool && (metsLicenseBool || lidoLicenseBool)){
return Feedback.DUPLICATE_LICENSE_DATA;
}
if(publicationBool && !premisLicenseBool && !metsLicenseBool&& !lidoLicenseBool){
return Feedback.PUBLICATION_NO_LICENSE;
}
if(publicationBool && !hasPipMetadataBool){
return Feedback.NO_METADATA_FOR_PIP;
}
logger.info("License is satisfiable: Premis-License:"+premisLicenseBool+" Mets-License:"+metsLicenseBool+" Lido-License:"+lidoLicenseBool+ " Publication-Decision:"+publicationBool+" InstPublication-Decision:"+instPublicationBool);
return Feedback.SUCCESS;
}
/**
* Creates the premis.xml file
*
* @param jobId
* The job ID
* @param folder
* The temp folder
* @param packageName
* The package name
* @return The method result as a Feedback enum
*/
private Feedback createPremisFile(int jobId, File folder, String packageName) {
progressManager.premisProgress(jobId, 0.0);
File premisFile = null;
// DANRW-1416
if (tar) {
premisFile = new File(folder, "data" + File.separator
+ "premis.xml");
} else {
premisFile = new File(folder,"data" + File.separator + "premis.xml");
}
// ENDE DANRW-1416
PremisXmlWriter premisWriter = new PremisXmlWriter();
try {
if (rightsSourcePremisFile != null)
premisWriter.createPremisFile(this, premisFile,
rightsSourcePremisFile, packageName);
else{
if(this.getContractRights().getMinimalIngestQuality()>0)
logger.info("Take over minimal ingest quality: "+this.getContractRights().getMinimalIngestQuality());
premisWriter.createPremisFile(this, premisFile, packageName);
}
} catch (Exception e) {
logger.error(
"Failed to create premis file "
+ premisFile.getAbsolutePath(), e);
return Feedback.PREMIS_ERROR;
}
progressManager.premisProgress(jobId, 100.0);
if (sipBuildingProcess.isAborted())
return Feedback.ABORT;
return Feedback.SUCCESS;
}
/**
* Creates BagIt checksums and metadata for the files in the given folder
*
* @param jobId
* The job ID
* @param folder
* The temp folder
* @return The method result as a Feedback enum
*/
public Feedback createBag(int jobId, File folder) {
progressManager.bagitProgress(jobId, 0.0);
Bag bag;
try {
bag = BagCreator.bagInPlace(Paths.get(folder.toURI()), Arrays.asList(BagitUtils.DEFAULT_BAGIT_ALGORITHM), false);
} catch (Exception e) {
//e.printStackTrace();
logger.error("Bag in folder " + folder.getAbsolutePath()+ " can not be created.\n" + e.getMessage());
}
progressManager.bagitProgress(jobId, 10.0);
if (sipBuildingProcess.isAborted())
return Feedback.ABORT;
try {
BagReader reader = new BagReader();
Bag bagVer = reader.read(Paths.get(folder.getAbsolutePath()));
progressManager.bagitProgress(jobId, 40.0);
if (sipBuildingProcess.isAborted())
return Feedback.ABORT;
BagVerifier sut = new BagVerifier();
sut.isValid(bagVer, false);
progressManager.bagitProgress(jobId, 50.0);
return Feedback.SUCCESS;
} catch (Exception e) {
//e.printStackTrace();
logger.error("Bag in folder " + folder.getAbsolutePath()+ " is not valid.\n" + e.getMessage());
return Feedback.BAGIT_ERROR;
}
}
/**
* Creates a tar oder tgz archive file out of the given folder. The value of
* the field 'compress' determines if a tar or tgz file is created.
*
* @param jobId
* The job ID
* @param folder
* The folder to archive
* @param archiveFile
* The target archive file
* @return The method result as a Feedback enum
*/
public Feedback buildArchive(int jobId, File folder, File archiveFile) {
progressManager.setJobFolderSize(jobId,
FileUtils.sizeOfDirectory(folder));
progressManager.archiveProgress(jobId, 0);
SipArchiveBuilder archiveBuilder = null;
try {
archiveBuilder = new SipArchiveBuilder();
archiveBuilder.setProgressManager(progressManager);
archiveBuilder.setJobId(jobId);
archiveBuilder.setSipBuildingProcess(sipBuildingProcess);
} catch (Exception e) {
logger.error("Failed to instantiate the ArchiveBuilder ", e);
return Feedback.ABORT;
}
try {
if (!archiveBuilder.archiveFolder(folder, archiveFile, true,
compress))
return Feedback.ABORT;
} catch (Exception e) {
logger.error("Failed to archive folder " + folder.getAbsolutePath()
+ " to archive " + archiveFile.getAbsolutePath(), e);
return Feedback.ARCHIVE_ERROR;
}
return Feedback.SUCCESS;
}
/**
* Deletes the temp folder and its contents
*
* @param jobId
* The job ID
* @param folder
* The temp folder to delete
* @return The method result as a Feedback enum
*/
private Feedback deleteTempFolder(int jobId, File folder) {
progressManager.deleteTempProgress(jobId, 0.0);
try {
FolderUtils.deleteDirectorySafe(folder);
} catch (IOException e) {
logger.warn(
"Failed to delete temp folder " + folder.getAbsolutePath(),
e);
return Feedback.DELETE_TEMP_FOLDER_WARNING;
}
progressManager.deleteTempProgress(jobId, 100.0);
return Feedback.SUCCESS;
}
/**
* Moves the given archived SIP file to the collection folder
*
* @param jobId
* The job ID
* @param archiveFile
* The SIP file
* @return The method result as a Feedback enum
*/
private Feedback moveSipToCollectionFolder(int jobId, File archiveFile) {
try {
FileUtils.moveFileToDirectory(archiveFile, new File(
collectionFolder, "data"), false);
} catch (IOException e) {
logger.error("Failed to move file " + archiveFile.getAbsolutePath()
+ " to folder " + collectionFolder.getAbsolutePath(), e);
return Feedback.MOVE_TO_COLLECTION_FOLDER_ERROR;
}
return Feedback.SUCCESS;
}
/**
* Checks if the given SIP file already exists at the destination path. If
* an existing SIP is found, the user may decide to overwrite it or abort
* the process.
*
* @param archiveFileName
* The name of the folder to check
* @return true if no existing SIP for the given folderName is found or the
* user decides to overwrite the existing SIP
* @return false if a SIP for the given folderName already exists and the
* user decides to abort the SIP creation process
*/
private boolean checkForExistingSip(File sip) {
if (alwaysOverwrite)
return true;
if (sip.exists()) {
MessageWriter.UserInput userInput = messageWriter
.showOverwriteDialog("Im Ordner \"" + destinationPath
+ "\" existiert bereits ein SIP mit\n"
+ "dem Namen \""
+ FilenameUtils.getBaseName(sip.getAbsolutePath())
+ "\".\n\n"
+ "Möchten Sie das bestehende SIP überschreiben?");
switch (userInput) {
case YES:
return true;
case NO:
return false;
case ALWAYS_OVERWRITE:
alwaysOverwrite = true;
return true;
}
}
return true;
}
private String getPackageName(File folder) {
String packageName;
if (name != null && !name.equals(""))
packageName = name;
else
packageName = folder.getName();
return packageName;
}
private String getTempFolderName() {
String baseName = "temp";
if (!new File(destinationPath + File.separator + baseName).exists())
return baseName;
String tempFolderName;
int i = 0;
do {
tempFolderName = baseName + "_" + i++;
} while (new File(destinationPath + File.separator + tempFolderName)
.exists());
return tempFolderName;
}
private void rollback(File folder) {
rollback(folder, null);
}
private void rollback(File folder, File archiveFile) {
FolderUtils.deleteQuietlySafe(folder);
if (archiveFile != null)
FolderUtils.deleteQuietlySafe(archiveFile);
}
/**
* This method is called by the SIP building process. It deletes partially
* created collections and aborts the progress manager.
*/
private void abortSipBuilding() {
if (listCreationTempFolder != null && listCreationTempFolder.exists())
FolderUtils.deleteQuietlySafe(listCreationTempFolder);
FolderUtils.deleteQuietlySafe(collectionFolder);
progressManager.abort();
}
/**
* Aborts the SIP building process
*/
public void abort() {
sipBuildingProcess.abort();
}
/**
* @return true if the SIP building process is working, otherwise false
*/
public boolean isWorking() {
if (sipBuildingProcess == null || !sipBuildingProcess.isAlive())
return false;
else
return true;
}
public String getSourcePath() {
return sourcePath;
}
public void setSourcePath(String sourcePath) {
this.sourcePath = sourcePath;
}
public String getDestinationPath() {
return destinationPath;
}
public void setDestinationPath(String destinationPath) {
this.destinationPath = destinationPath;
}
public KindOfSIPBuilding getKindofSIPBuilding() {
return kindofSIPBuilding;
}
public void setKindofSIPBuilding(KindOfSIPBuilding kindofSIPBuilding) {
this.kindofSIPBuilding = kindofSIPBuilding;
}
public void setKindofSIPBuilding(String kindofSIPBuildingName) {
this.kindofSIPBuilding = Utilities
.translateKindOfSIPBuilding(kindofSIPBuildingName);
}
public ContractRights getContractRights() {
return contractRights;
}
public void setContractRights(ContractRights contractRights) {
this.contractRights = contractRights;
}
public void setProgressManager(ProgressManager progressManager) {
this.progressManager = progressManager;
}
public void setMessageWriter(MessageWriter messageWriter) {
this.messageWriter = messageWriter;
}
public boolean getCreateCollection() {
return createCollection;
}
public void setCreateCollection(boolean createCollection) {
this.createCollection = createCollection;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
public File getRightsSourcePremisFile() {
return rightsSourcePremisFile;
}
public void setRightsSourcePremisFile(File rightsSourcePremisFile) {
this.rightsSourcePremisFile = rightsSourcePremisFile;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getForbiddenFileExtensions() {
return forbiddenFileExtensions;
}
public void setForbiddenFileExtensions(List<String> forbiddenFileExtensions) {
this.forbiddenFileExtensions = forbiddenFileExtensions;
}
public File getListCreationTempFolder() {
return listCreationTempFolder;
}
public void setListCreationTempFolder(File listCreationTempFolder) {
this.listCreationTempFolder = listCreationTempFolder;
}
public void setIgnoreZeroByteFiles(boolean ignoreZeroByteFiles) {
this.ignoreZeroByteFiles = ignoreZeroByteFiles;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public Feedback getReturnCode() {
return returnCode;
}
public ProgressManager getProgressManager(){
return progressManager;
}
public boolean getCompress() {
return compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
public String getWorkingPath() {
return workingPath;
}
public void setWorkingPath(String workingPath) {
this.workingPath = workingPath;
}
public boolean isTar() {
return tar;
}
public void setTar(boolean tar) {
this.tar = tar;
}
public String getDestDir() {
return destDir;
}
public void setDestDir(String destDir) {
this.destDir = destDir;
}
// DANRW-1515
public boolean isAllowDuplicateFilename() {
return allowDuplicateFilename;
}
public void setAllowDuplicateFilename(boolean allowDuplicateFilename) {
this.allowDuplicateFilename = allowDuplicateFilename;
}
public boolean isCheckFileExtensionOff() {
return checkFileExtensionOff;
}
public void setCheckFileExtensionOff(boolean checkFileExtensionOff) {
this.checkFileExtensionOff = checkFileExtensionOff;
}
public FileExtensions getFileExtensions() {
return fileExtensions;
}
public void setFileExtensions(FileExtensions fileExtensions) {
this.fileExtensions = fileExtensions;
}
public HashMap<String, List<String>> getFileExtensionsList() {
return fileExtensionsList;
}
public void setFileExtensionsList(HashMap<String, List<String>> hashMap) {
this.fileExtensionsList = hashMap;
}
// End of DANRW-1515
public boolean isBagit() {
return bagit;
}
public void setBagit(boolean bagit) {
this.bagit = bagit;
}
/**
* The SIP building procedure is run in its own thread to prevent GUI
* freezing
*
* @author Thomas Kleinke
*/
public class SipBuildingProcess extends Thread {
private boolean abortRequested = false;
/**
* Creates one ore more SIPs as specified by the user
*/
public void run() {
alwaysOverwrite = false;
skippedFiles = false;
messageWriter.resetZeroByteFiles();
progressManager.reset();
if (createCollection) {
collectionFolder = new File(new File(destinationPath),
collectionName);
if (collectionFolder.exists()) {
MessageWriter.UserInput answer = messageWriter
.showCollectionOverwriteDialog("Eine Lieferung mit dem Namen \""
+ collectionName
+ "\""
+ "existiert bereits.\n"
+ "Möchten Sie die bestehende Lieferung überschreiben?");
switch (answer) {
case YES:
FolderUtils.deleteQuietlySafe(collectionFolder);
break;
case NO:
progressManager.abort();
return;
default:
break;
}
}
new File(collectionFolder, "data").mkdirs();
}
HashMap<File, String> folderListWithNames = null;
try {
folderListWithNames = createFolderList(sourcePath);
@SuppressWarnings("unchecked")
HashMap<File, String> tmpFolderListWithNames = (HashMap<File, String>) folderListWithNames
.clone();
for (File f : folderListWithNames.keySet()) {
String metadataType = "";
try {
TreeMap<File, String> metadataFileWithType = new FormatDetectionService(
f).getMetadataFileWithType();
if (!metadataFileWithType.isEmpty()) {
File file = metadataFileWithType.firstKey();
metadataType = metadataFileWithType.get(file);
if (!duplicateFileNames(f, tmpFolderListWithNames)) {
Utilities.validateFileReferencesInMetadata(file, metadataType);
}
} else {
duplicateFileNames(f, tmpFolderListWithNames);
}
} catch (Error e) {
if (metadataType.equals(C.CB_PACKAGETYPE_EAD)) {
String msg = "Aus dem Verzeichnis " + f
+ " wird kein SIP erstellt. \n"
+ e.getMessage();
messageWriter.showLongErrorMessage(msg);
tmpFolderListWithNames.remove(f);
returnCode = Feedback.WRONG_REFERENCES_IN_METADATA;
} else {
String msg = e.getMessage()
+ " \nMöchten Sie die SIP-Erstellung dennoch fortsetzen?";
logger.error(msg);
MessageWriter.UserInput answer = messageWriter
.showWrongReferencesInMetadataDialog(msg);
returnCode = Feedback.WRONG_REFERENCES_IN_METADATA;
switch (answer) {
case YES:
break;
case NO:
messageWriter
.showMessage("Aus dem Verzeichnis " + f
+ " wird kein SIP erstellt.");
tmpFolderListWithNames.remove(f);
break;
default:
break;
}
}
}
}
folderListWithNames = tmpFolderListWithNames;
if (folderListWithNames.isEmpty()) {
abortSipBuilding();
return;
}
} catch (Exception e) {
messageWriter
.showLongErrorMessage("Das SIP konnte nicht erstellt werden.\n\n"
+ "Ihre Daten sind möglicherweise nicht valide. \n\n"
+ e.getMessage());
returnCode = Feedback.INVALID_METADATA;
abortSipBuilding();
return;
}
List<File> folderList = new ArrayList<File>();
for (File f : folderListWithNames.keySet()) {
folderList.add(f);
}
if (initializeProgressManager(folderList) != Feedback.SUCCESS) {
messageWriter
.showMessage(
"Das SIP konnte nicht erstellt werden.\n\n"
+ "Der angegebene Ordner existiert nicht mehr. ",
JOptionPane.ERROR_MESSAGE);
abortSipBuilding();
return;
}
int id = 0;
for (File folder : folderListWithNames.keySet()) {
returnCode = buildSIP(id, folder,
folderListWithNames.get(folder));
if (returnCode != Feedback.SUCCESS
&& returnCode != Feedback.DELETE_TEMP_FOLDER_WARNING)
abortSipBuilding();
switch (returnCode) {
case COPY_ERROR:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte nicht erstellt werden.\n\n"
+ "Während des Kopiervorgangs ist ein Fehler aufgetreten.",
JOptionPane.ERROR_MESSAGE);
return;
case ZERO_BYTES_ERROR:
messageWriter.showZeroByteFileMessage();
return;
case PREMIS_ERROR:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte nicht erstellt werden.\n\n"
+ "Während der Erstellung der Premis-Datei ist ein Fehler aufgetreten.",
JOptionPane.ERROR_MESSAGE);
return;
case BAGIT_ERROR:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte nicht erstellt werden.\n\n"
+ "Während der Erzeugung des Bags ist ein Fehler aufgetreten.",
JOptionPane.ERROR_MESSAGE);
return;
case ARCHIVE_ERROR:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte nicht erstellt werden.\n\n"
+ "Während der tgz-Archivierung ist ein Fehler aufgetreten.",
JOptionPane.ERROR_MESSAGE);
return;
case DELETE_TEMP_FOLDER_WARNING:
messageWriter
.showMessage(
"Während der Bereinigung temporärer Daten ist ein Fehler aufgetreten.\n\n"
+ "Bitte löschen Sie nicht benötigte verbleibende Verzeichnisse\n"
+ "im Ordner \"" + destinationPath
+ "\" manuell.",
JOptionPane.ERROR_MESSAGE);
break;
case MOVE_TO_COLLECTION_FOLDER_ERROR:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte der Lieferung nicht hinzugefügt werden.",
JOptionPane.ERROR_MESSAGE);
return;
case INVALID_LICENSE_DATA_IN_METADATA:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte der Lieferung nicht hinzugefügt werden.\n"+
"Die Lizenzangaben in den Metadaten sind ungültig: Lizenzen nicht eindeutig interpretierbar.",
JOptionPane.ERROR_MESSAGE);
return;
case DUPLICATE_LICENSE_DATA:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte der Lieferung nicht hinzugefügt werden.\n"+
"Die Lizenzangaben sind nicht eindeutig: Lizenangaben dürfen nicht gleichzeitig im SIP-Builder und in den Metadaten angegeben werden.",
JOptionPane.ERROR_MESSAGE);
return;
case PUBLICATION_NO_LICENSE:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte der Lieferung nicht hinzugefügt werden.\n"+
"Die Lizenzangaben sind nicht vorhanden: Um publizieren zu können, muss eine gültige Lizenz angegeben werden.",
JOptionPane.ERROR_MESSAGE);
return;
case NO_METADATA_FOR_PIP:
messageWriter
.showMessage(
"Das SIP \""
+ folder.getName()
+ "\" konnte der Lieferung nicht hinzugefügt werden.\n"+
"Für eine Publikation sind portalrelevante Metadaten (z.B. METS,LIDO) zwingend erforderlich",
JOptionPane.ERROR_MESSAGE);
return;
case ABORT:
return;
default:
break;
}
id++;
}
if (listCreationTempFolder != null
&& listCreationTempFolder.exists())
FolderUtils.deleteQuietlySafe(listCreationTempFolder);
if (createCollection) {
progressManager.startJob(-1);
if (createBag(-1, collectionFolder) == Feedback.BAGIT_ERROR)
messageWriter
.showMessage(
"Die Lieferung \""
+ collectionName
+ "\" konnte nicht erstellt werden.\n\n"
+ "Während der Erzeugung des Bags ist ein Fehler aufgetreten.",
JOptionPane.ERROR_MESSAGE);
}
progressManager.createSuccessMessage(skippedFiles);
if (ignoreZeroByteFiles
&& messageWriter.getZeroByteFiles().size() > 0) {
String message = "WARNING: Found zero byte files:";
for (String s : messageWriter.getZeroByteFiles()) {
message += "\n";
message += s;
}
logger.info(message);
messageWriter.showZeroByteFileMessage();
}
}
public void abort() {
abortRequested = true;
}
public boolean isAborted() {
return abortRequested;
}
/**
* duplicateFileNames:
* @param f
* @param tmpFolderListWithNames
* @return
*/
private boolean duplicateFileNames(File f,
HashMap<File, String> tmpFolderListWithNames) {
HashMap<String, List<File>> duplicateFileNames = getFilesWithDuplicateFileNames(f);
if (!duplicateFileNames.isEmpty()) {
if (!allowDuplicateFilename) {
String msg = "Aus dem Verzeichnis "
+ f
+ " wird kein SIP erstellt. \nDer Ordner enthält gleichnamige Dateien: \n"
+ duplicateFileNames;
messageWriter.showLongErrorMessage(msg);
tmpFolderListWithNames.remove(f);
returnCode = Feedback.DUPLICATE_FILENAMES;
return true;
} else {
// DANRW-1515: erlauben von doppelten Dateiname für unterschiedliche Formate (z.B. xml und Image)
Iterator<String> it = duplicateFileNames.keySet().iterator();
while (it.hasNext()) {
List<String> oldKeysExtension = new ArrayList<String>();
String key = (it.next());
List<File> listDupFileNames = duplicateFileNames.get(key);
for (int i = 0; listDupFileNames.size() > i; i++) {
String extOfFile = FilenameUtils.getExtension(listDupFileNames.get(i)
.getAbsolutePath());
if (!checkFileExtensionOff) {
Iterator<String> itExtensions = getFileExtensionsList().keySet().iterator();
while(itExtensions.hasNext()) {
String keyExtensions = (itExtensions.next());
if (getFileExtensionsList().get(keyExtensions).contains(extOfFile)) {
if (oldKeysExtension.contains(keyExtensions)) {
String msg = "Aus dem Verzeichnis "
+ f
+ " wird kein SIP erstellt. \nDer Ordner enthält gleichnamige Dateien: \n"
+ duplicateFileNames.get(key);
messageWriter.showLongErrorMessage(msg);
tmpFolderListWithNames.remove(f);
returnCode = Feedback.DUPLICATE_FILENAMES;
return true;
} else {
oldKeysExtension.add(keyExtensions);
break;
}
}
}
// } else {
// String msg = "Aus dem Verzeichnis "
// + f
// + " wird kein SIP erstellt. \nDer Ordner enthält gleichnamige Dateien: \n"
// + duplicateFileNames.get(key);
// messageWriter.showLongErrorMessage(msg);
// tmpFolderListWithNames.remove(f);
// returnCode = Feedback.DUPLICATE_FILENAMES;
// return true;
}
}
}
}
}
return false;
}
private HashMap<String, List<File>> getFilesWithDuplicateFileNames(
File folder) {
logger.debug("Search for duplicate file names in folder " + folder);
HashMap<String, List<File>> duplicateFilenamesWithFiles = new HashMap<String, List<File>>();
HashMap<String, File> filenamesWithFiles = new HashMap<String, File>();
for (File f : folder.listFiles()) {
logger.debug("getFilesWithDuplicateFileNames: Check file " + f);
if (f.isDirectory()) {
HashMap<String, List<File>> rekursivResult = getFilesWithDuplicateFileNames(f);
for (String rekf : rekursivResult.keySet())
if (duplicateFilenamesWithFiles.containsKey(rekf))
duplicateFilenamesWithFiles.get(rekf).addAll(
rekursivResult.get(rekf));
else
duplicateFilenamesWithFiles.put(rekf,
rekursivResult.get(rekf));
} else {
File file = new File(f.getAbsolutePath());
String ext = FilenameUtils.getExtension(file
.getAbsolutePath());
String relFilePathWithoutExtension = new File(
f.getAbsolutePath())
.getAbsolutePath()
.toString()
.replace(
new File(f.getParent()).getAbsolutePath()
+ File.separator, "")
;
//.replace(ext, "");
relFilePathWithoutExtension=relFilePathWithoutExtension.substring(0,relFilePathWithoutExtension.length()-ext.length());
logger.debug("relFilePathWithoutExtension: "
+ relFilePathWithoutExtension);
if (filenamesWithFiles.get(relFilePathWithoutExtension) == null) {
logger.debug("New file name "
+ relFilePathWithoutExtension);
filenamesWithFiles.put(relFilePathWithoutExtension, f);
} else {
if (duplicateFilenamesWithFiles
.get(relFilePathWithoutExtension) != null) {
logger.debug("One more file with file name "
+ relFilePathWithoutExtension
+ "\nFirst file is "
+ duplicateFilenamesWithFiles
.get(relFilePathWithoutExtension));
duplicateFilenamesWithFiles.get(
relFilePathWithoutExtension).add(f);
} else {
List<File> duplicateFilenames = new ArrayList<File>();
logger.debug("Second file with the same file name. "
+ "\n First file is "
+ filenamesWithFiles
.get(relFilePathWithoutExtension));
duplicateFilenames.add(filenamesWithFiles
.get(relFilePathWithoutExtension));
duplicateFilenames.add(f);
duplicateFilenamesWithFiles.put(
relFilePathWithoutExtension,
duplicateFilenames);
}
}
}
}
return duplicateFilenamesWithFiles;
}
}
public void setSipBuildingProcess(SipBuildingProcess sipBuildingProcess2) {
this.sipBuildingProcess=sipBuildingProcess2;
};
}
| da-nrw/DNSCore | SIP-Builder/src/main/java/de/uzk/hki/da/sb/SIPFactory.java | Java | gpl-3.0 | 41,636 |
/*
* Copyright (c) 2014-2015, Julien Bernard
*
* 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 GAME_WINDOW_GEOMETRY_H
#define GAME_WINDOW_GEOMETRY_H
#include <SFML/Graphics.hpp>
namespace game {
class WindowGeometry {
public:
WindowGeometry(float width, float height)
: m_width(width)
, m_height(height)
{
}
void update(sf::Event& event);
float getXCentered(float width);
float getXFromRight(float width);
float getXRatio(float r, float width);
float getYCentered(float height);
float getYFromBottom(float height);
float getYRatio(float r, float height);
sf::Vector2f getCornerPosition(const sf::Vector2f& pos);
private:
float m_width;
float m_height;
};
}
#endif // GAME_WINDOW_GEOMETRY_H
| DeadPixelsSociety/SonOfMars | src/game/WindowGeometry.h | C | gpl-3.0 | 1,804 |
<?php
////////////////////////////////////////////////////////////////////////////////
// project : XOS-Shop, open source e-commerce system
// http://www.xos-shop.com
//
// filename : products_attributes.php
// author : Hanspeter Zeller <hpz@xos-shop.com>
// copyright : Copyright (c) 2007 Hanspeter Zeller
// license : This file is part of XOS-Shop.
//
// XOS-Shop 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.
//
// XOS-Shop 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 XOS-Shop. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------
// this file is based on:
// osCommerce, Open Source E-Commerce Solutions
// http://www.oscommerce.com
// Copyright (c) 2003 osCommerce
// filename: products_attributes.php
//
// Released under the GNU General Public License
////////////////////////////////////////////////////////////////////////////////
require('includes/application_top.php');
if (!((@include DIR_FS_SMARTY . 'admin/templates/' . ADMIN_TPL . '/php/' . FILENAME_PRODUCTS_ATTRIBUTES) == 'overwrite_all')) :
$languages = xos_get_languages();
$pID = (isset($_GET['pID']) && is_numeric($_GET['pID'])) ? $_GET['pID'] : 0;
$cPath = (isset($_GET['cPath']) && !empty($_GET['cPath'])) ? $_GET['cPath'] : 0;
$categories_or_pages_id = (isset($_GET['categories_or_pages_id']) && is_numeric($_GET['categories_or_pages_id'])) ? $_GET['categories_or_pages_id'] : 0;
$manufacturers_id = (isset($_GET['manufacturers_id']) && is_numeric($_GET['manufacturers_id'])) ? $_GET['manufacturers_id'] : 0;
$action = (isset($_GET['action']) ? $_GET['action'] : '');
$option_page = (isset($_GET['option_page']) && is_numeric($_GET['option_page'])) ? $_GET['option_page'] : 1;
$value_page = (isset($_GET['value_page']) && is_numeric($_GET['value_page'])) ? $_GET['value_page'] : 1;
$attribute_page = (isset($_GET['attribute_page']) && is_numeric($_GET['attribute_page'])) ? $_GET['attribute_page'] : 1;
$parameter_string = 'categories_or_pages_id=' . $categories_or_pages_id . '&manufacturers_id=' . $manufacturers_id . '&max_rows=' . $_GET['max_rows'] . '&max_products_in_pullwown=' . $_GET['max_products_in_pullwown'] . '&selected_tax_rate_id=' . $_GET['selected_tax_rate_id'] . '&option_page=' . $option_page . '&value_page=' . $value_page . '&attribute_page=' . $attribute_page . (($pID && $cPath) ? '&pID=' . $pID . '&cPath=' . $cPath : '');
$cmm_parameter_string = 'categories_or_pages_id=' . $categories_or_pages_id . '&manufacturers_id=' . $manufacturers_id . '&max_rows=' . $_GET['max_rows'] . '&max_products_in_pullwown=' . $_GET['max_products_in_pullwown'] . '&selected_tax_rate_id=' . $_GET['selected_tax_rate_id'] . (($pID && $cPath) ? '&pID=' . $pID . '&cPath=' . $cPath : '');
if (xos_not_null($action)) {
switch ($action) {
case 'add_product_options':
$products_options_id = xos_db_prepare_input($_POST['products_options_id']);
$option_name_array = $_POST['option_name'];
$products_options_name_error = array();
$error_options_name = false;
for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
$check_query = xos_db_query("select products_options_name from " . TABLE_PRODUCTS_OPTIONS . " where language_id = '" . (int)$languages[$i]['id'] . "' and products_options_name = '" . xos_db_input(htmlspecialchars($option_name_array[$languages[$i]['id']])) . "'");
if (xos_db_num_rows($check_query) || $option_name_array[$languages[$i]['id']] == '') {
$error_options_name = true;
$products_options_name_error[$languages[$i]['id']] = $option_name_array[$languages[$i]['id']];
}
}
if ($error_options_name) {
$products_options_name_error_array = urlencode(serialize($products_options_name_error));
$products_options_name_array = urlencode(serialize($option_name_array));
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&options_name=' . $products_options_name_array . '&options_name_error=' . $products_options_name_error_array . '&' . $parameter_string));
} else {
for ($i=0, $n=sizeof($languages); $i<$n; $i ++) {
$option_name = xos_db_prepare_input(htmlspecialchars($option_name_array[$languages[$i]['id']]));
xos_db_query("insert into " . TABLE_PRODUCTS_OPTIONS . " (products_options_id, products_options_name, language_id) values ('" . (int)$products_options_id . "', '" . xos_db_input($option_name) . "', '" . (int)$languages[$i]['id'] . "')");
}
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&' . $parameter_string));
}
break;
case 'add_product_option_values':
$value_name_array = $_POST['value_name'];
$value_id = xos_db_prepare_input($_POST['value_id']);
$option_id = xos_db_prepare_input($_POST['option_id']);
$products_options_value_error = array();
$error_options_value = false;
for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
$check_query = xos_db_query("select pov.products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov, " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " pov2po where pov2po.products_options_id = '" . $option_id . "' and pov2po.products_options_values_id = pov.products_options_values_id and pov.products_options_values_name = '" . xos_db_input(htmlspecialchars($value_name_array[$languages[$i]['id']])) . "' and pov.language_id = '" . (int)$languages[$i]['id'] . "'");
if (xos_db_num_rows($check_query) || $value_name_array[$languages[$i]['id']] == '') {
$error_options_value = true;
$products_options_value_error[$languages[$i]['id']] = $value_name_array[$languages[$i]['id']];
}
}
if ($error_options_value) {
$products_options_value_error_array = urlencode(serialize($products_options_value_error));
$products_options_value_array = urlencode(serialize($value_name_array));
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&option_id=' . $option_id . '&options_value=' . $products_options_value_array . '&options_value_error=' . $products_options_value_error_array . '&' . $parameter_string));
} else {
for ($i=0, $n=sizeof($languages); $i<$n; $i ++) {
$value_name = xos_db_prepare_input(htmlspecialchars($value_name_array[$languages[$i]['id']]));
xos_db_query("insert into " . TABLE_PRODUCTS_OPTIONS_VALUES . " (products_options_values_id, language_id, products_options_values_name) values ('" . (int)$value_id . "', '" . (int)$languages[$i]['id'] . "', '" . xos_db_input($value_name) . "')");
}
xos_db_query("insert into " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " (products_options_id, products_options_values_id) values ('" . (int)$option_id . "', '" . (int)$value_id . "')");
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&' . $parameter_string));
}
break;
case 'add_product_attributes':
$products_id = xos_db_prepare_input($_POST['products_id']);
$options_id = xos_db_prepare_input($_POST['options_id']);
$values_id = xos_db_prepare_input($_POST['values_id']);
$value_price = xos_db_prepare_input($_POST['value_price']);
$price_prefix = ($_POST['price_prefix'] == '-' && $value_price > 0) ? '-' : '+';
$count_query = xos_db_query("select options_values_id, options_sort_order from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "' and options_id = '" . (int)$options_id . "'");
$existing_option = false;
$existing_value = false;
$options_sort_order = 0;
while($count = xos_db_fetch_array($count_query)) {
if ($count['options_values_id'] == $values_id) $existing_value = true;
$existing_option = true;
$options_sort_order = $count['options_sort_order'];
}
if (isset($_POST['values_id']) && !$existing_value) {
xos_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES . " values (null, '" . (int)$products_id . "', '" . (int)$options_id . "', '" . (int)$values_id . "', '" . max(1,(int)$options_sort_order) . "', 1, '" . (float)xos_db_input($value_price) . "', '" . xos_db_input($price_prefix) . "')");
if (DOWNLOAD_ENABLED == 'true') {
$products_attributes_id = xos_db_insert_id();
$products_attributes_filename = xos_db_prepare_input($_POST['products_attributes_filename']);
$products_attributes_maxdays = xos_db_prepare_input($_POST['products_attributes_maxdays']);
$products_attributes_maxcount = xos_db_prepare_input($_POST['products_attributes_maxcount']);
if (xos_not_null($products_attributes_filename)) {
xos_db_query("insert into " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " values (" . (int)$products_attributes_id . ", '" . xos_db_input($products_attributes_filename) . "', '" . xos_db_input($products_attributes_maxdays) . "', '" . xos_db_input($products_attributes_maxcount) . "')");
}
}
if (!$existing_option) {
xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '0', products_last_modified = now(), attributes_quantity = null, attributes_combinations = null, attributes_not_updated = null where products_id = '" . (int)$products_id . "'");
if (STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT == 'false') {
xos_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . (int)$products_id . "'");
}
$smarty_cache_control->clearAllCache();
} else {
$attributes_query = xos_db_query("select attributes_combinations, attributes_not_updated from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
$attributes = xos_db_fetch_array($attributes_query);
if (xos_not_null($attributes['attributes_combinations'])) {
$attributes_not_updated = xos_get_attributes_not_updated($attributes['attributes_not_updated']);
$attributes_not_updated[] = (int)$options_id . ',' . (int)$values_id;
if (!empty($attributes_not_updated)) xos_db_query("update " . TABLE_PRODUCTS . " set products_last_modified = now(), attributes_not_updated = '" . xos_db_input(serialize($attributes_not_updated)) . "' where products_id = '" . (int)$products_id . "'");
}
}
$smarty_cache_control->clearCache(null, 'L3|cc_product_info');
}
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $parameter_string));
break;
case 'update_option_name':
$option_name_array = $_POST['option_name'];
$option_id = xos_db_prepare_input($_POST['option_id']);
$actual_option_name_array = xos_db_prepare_input($_POST['actual_option_name']);
$products_options_name_error = array();
$error_options_name = false;
for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
if (mb_strtolower($actual_option_name_array[$languages[$i]['id']], 'UTF-8') != mb_strtolower($option_name_array[$languages[$i]['id']], 'UTF-8') || $option_name_array[$languages[$i]['id']] == '') {
$check_query = xos_db_query("select products_options_name from " . TABLE_PRODUCTS_OPTIONS . " where language_id = '" . (int)$languages[$i]['id'] . "' and products_options_name = '" . xos_db_input(htmlspecialchars($option_name_array[$languages[$i]['id']])) . "'");
if (xos_db_num_rows($check_query) || $option_name_array[$languages[$i]['id']] == '') {
$error_options_name = true;
$products_options_name_error[$languages[$i]['id']] = $option_name_array[$languages[$i]['id']];
}
}
}
if ($error_options_name) {
$products_options_name_error_array = urlencode(serialize($products_options_name_error));
$products_options_name_array = urlencode(serialize($option_name_array));
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&action=update_option&option_id=' . $option_id . '&options_name=' . $products_options_name_array . '&options_name_error=' . $products_options_name_error_array . '&' . $parameter_string));
} else {
for ($i=0, $n=sizeof($languages); $i<$n; $i ++) {
$option_name = xos_db_prepare_input(htmlspecialchars($option_name_array[$languages[$i]['id']]));
xos_db_query("update " . TABLE_PRODUCTS_OPTIONS . " set products_options_name = '" . xos_db_input($option_name) . "' where products_options_id = '" . (int)$option_id . "' and language_id = '" . (int)$languages[$i]['id'] . "'");
}
$smarty_cache_control->clearCache(null, 'L3|cc_product_info');
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&' . $parameter_string));
}
break;
case 'update_value':
$value_name_array = $_POST['value_name'];
$value_id = xos_db_prepare_input($_POST['value_id']);
$option_id = xos_db_prepare_input($_POST['option_id']);
$actual_option_value_array = xos_db_prepare_input($_POST['actual_value_name']);
$products_options_value_error = array();
$error_options_value = false;
for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
if (mb_strtolower($actual_option_value_array[$languages[$i]['id']], 'UTF-8') != mb_strtolower($value_name_array[$languages[$i]['id']], 'UTF-8') || $value_name_array[$languages[$i]['id']] == '') {
$check_query = xos_db_query("select products_options_name from " . TABLE_PRODUCTS_OPTIONS . " where language_id = '" . (int)$languages[$i]['id'] . "' and products_options_name = '" . xos_db_input(htmlspecialchars($option_name_array[$languages[$i]['id']])) . "'");
$check_query = xos_db_query("select pov.products_options_values_name from " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov, " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " pov2po where pov2po.products_options_id = '" . $option_id . "' and pov2po.products_options_values_id = pov.products_options_values_id and pov.products_options_values_name = '" . xos_db_input(htmlspecialchars($value_name_array[$languages[$i]['id']])) . "' and pov.language_id = '" . (int)$languages[$i]['id'] . "'");
if (xos_db_num_rows($check_query) || $value_name_array[$languages[$i]['id']] == '') {
$error_options_value = true;
$products_options_value_error[$languages[$i]['id']] = $value_name_array[$languages[$i]['id']];
}
}
}
if ($error_options_value) {
$products_options_value_error_array = urlencode(serialize($products_options_value_error));
$products_options_value_array = urlencode(serialize($value_name_array));
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&action=update_option_value&option_id=' . $option_id . '&value_id=' . $value_id . '&options_value=' . $products_options_value_array . '&options_value_error=' . $products_options_value_error_array . '&' . $parameter_string));
} else {
for ($i=0, $n=sizeof($languages); $i<$n; $i ++) {
$value_name = xos_db_prepare_input(htmlspecialchars($value_name_array[$languages[$i]['id']]));
xos_db_query("update " . TABLE_PRODUCTS_OPTIONS_VALUES . " set products_options_values_name = '" . xos_db_input($value_name) . "' where products_options_values_id = '" . xos_db_input($value_id) . "' and language_id = '" . (int)$languages[$i]['id'] . "'");
}
$smarty_cache_control->clearCache(null, 'L3|cc_product_info');
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&' . $parameter_string));
}
break;
case 'update_product_attribute':
$products_id = xos_db_prepare_input($_POST['products_id']);
$options_id = xos_db_prepare_input($_POST['options_id']);
$values_id = xos_db_prepare_input($_POST['values_id']);
$value_price = xos_db_prepare_input($_POST['value_price']);
$price_prefix = ($_POST['price_prefix'] == '-' && $value_price > 0) ? '-' : '+';
$attribute_id = xos_db_prepare_input($_POST['attribute_id']);
$current_options_id = xos_db_prepare_input($_POST['current_options_id']);
$current_options_values_id = xos_db_prepare_input($_POST['current_options_values_id']);
$count_query = xos_db_query("select options_values_id, options_sort_order from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$products_id . "' and options_id = '" . (int)$options_id . "'");
$existing_option = false;
$existing_value = false;
$options_sort_order = 0;
while($count = xos_db_fetch_array($count_query)) {
if ($count['options_values_id'] == $values_id && $values_id != $current_options_values_id) $existing_value = true;
$existing_option = true;
$options_sort_order = $count['options_sort_order'];
}
if (isset($_POST['values_id']) && !$existing_value) {
if (!$existing_option) {
xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '0', products_last_modified = now(), attributes_quantity = null, attributes_combinations = null, attributes_not_updated = null where products_id = '" . (int)$products_id . "'");
if (STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT == 'false') {
xos_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . (int)$products_id . "'");
}
} else {
$combinations_query = xos_db_query("select products_quantity, attributes_quantity, attributes_combinations, attributes_not_updated from " . TABLE_PRODUCTS . " where products_id = '" . (int)$products_id . "'");
$combinations = xos_db_fetch_array($combinations_query);
$qty = 0;
if (xos_not_null($combinations['attributes_combinations'])) {
$attributes_not_updated = xos_get_attributes_not_updated($combinations['attributes_not_updated']);
if ($values_id != $current_options_values_id) {
foreach ($attributes_not_updated as $key_not_updated => $val_not_updated) {
if ($val_not_updated == $current_options_id . ',' . $current_options_values_id) unset($attributes_not_updated[$key_not_updated]);
}
$attributes_not_updated[] = (int)$options_id . ',' . (int)$values_id;
ksort($attributes_not_updated);
if (empty($attributes_not_updated)) {
$not_updated = ", attributes_not_updated = null";
} else {
$not_updated = ", attributes_not_updated = '". xos_db_input(serialize($attributes_not_updated)) . "'";
}
} else {
$not_updated = "";
}
$qty = $combinations['products_quantity'];
$attributes_quantity = xos_get_attributes_quantity($combinations['attributes_quantity']);
$combinations['attributes_combinations'] = trim($combinations['attributes_combinations'], '|');
$elements_comb = explode('|', $combinations['attributes_combinations']);
for ($i=0, $n=sizeof($elements_comb); $i<$n; $i++) {
if (strpos($elements_comb[$i], $current_options_id . ',' . $current_options_values_id) !== false && $values_id != $current_options_values_id) {
$qty -= $attributes_quantity[$elements_comb[$i]] > 0 ? $attributes_quantity[$elements_comb[$i]] : 0;
unset($attributes_quantity[$elements_comb[$i]]);
unset($elements_comb[$i]);
}
}
ksort($attributes_quantity);
ksort($elements_comb);
$comb_str = '';
$comb_str = implode('|', $elements_comb);
$qty < 1 || $comb_str == '' ? $qty = 0 : '';
if ($comb_str != '') {
$comb_str .= '|';
xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . (int)$qty . "', products_last_modified = now(), attributes_quantity = '" . xos_db_input(serialize($attributes_quantity)) . "', attributes_combinations = '" . xos_db_input($comb_str) . "'" . $not_updated . " where products_id = '" . (int)$products_id . "'");
} else {
xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . (int)$qty . "', products_last_modified = now(), attributes_quantity = null, attributes_combinations = null, attributes_not_updated = null where products_id = '" . (int)$products_id . "'");
}
}
if ($qty < 1 && STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT == 'false') {
xos_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . (int)$products_id . "'");
}
}
xos_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES . " set options_id = '" . (int)$options_id . "', options_values_id = '" . (int)$values_id . "', options_sort_order = '" . max(1,(int)$options_sort_order) . "', " . ($current_options_id != $options_id ? 'options_values_sort_order = 1,' : '') . " options_values_price = '" . (float)xos_db_input($value_price) . "', price_prefix = '" . xos_db_input($price_prefix) . "' where products_attributes_id = '" . (int)$attribute_id . "'");
if (DOWNLOAD_ENABLED == 'true') {
$products_attributes_filename = xos_db_prepare_input($_POST['products_attributes_filename']);
$products_attributes_maxdays = xos_db_prepare_input($_POST['products_attributes_maxdays']);
$products_attributes_maxcount = xos_db_prepare_input($_POST['products_attributes_maxcount']);
if (xos_not_null($products_attributes_filename)) {
xos_db_query("replace into " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " set products_attributes_id = '" . (int)$attribute_id . "', products_attributes_filename = '" . xos_db_input($products_attributes_filename) . "', products_attributes_maxdays = '" . xos_db_input($products_attributes_maxdays) . "', products_attributes_maxcount = '" . xos_db_input($products_attributes_maxcount) . "'");
} else {
xos_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id = '" . (int)$attribute_id . "'");
}
}
$smarty_cache_control->clearAllCache();
}
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $parameter_string));
break;
case 'update_options_sort_order':
reset($_POST['option_sort_order'][(int)$_GET['products_id']]);
while (list($key, $value) = each($_POST['option_sort_order'][(int)$_GET['products_id']])) {
$value = xos_db_prepare_input($value);
if ((int)$value > 0) xos_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES . " set options_sort_order = '" . (int)$value . "' where products_id = '" . (int)$_GET['products_id'] . "' and options_id = '" . (int)$key . "'");
}
$combinations_query = xos_db_query("select attributes_combinations from " . TABLE_PRODUCTS . " where products_id = '" . (int)$_GET['products_id'] . "'");
$combinations = xos_db_fetch_array($combinations_query);
if (xos_not_null($combinations['attributes_combinations'])) {
$sort_query = xos_db_query("select distinct options_id from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$_GET['products_id'] . "' order by options_sort_order asc, options_id asc");
$c_str = '';
$sorted_options_id = array();
while($sort = xos_db_fetch_array($sort_query)) {
$sorted_options_id[] = $sort['options_id'];
}
$attributes_quantity = array();
$c_str = '';
reset($_POST['string_fragment'][(int)$_GET['products_id']]);
while (list($key, $value) = @each($_POST['string_fragment'][(int)$_GET['products_id']])) {
$qty = isset($_POST['attributes_quantity'][(int)$_GET['products_id']][$value]) ? (int)$_POST['attributes_quantity'][(int)$_GET['products_id']][$value] : 0;
$elements_in = explode('_', $value);
for ($i=0, $n=sizeof($elements_in); $i<$n; $i++) {
for ($ii=0, $m=sizeof($sorted_options_id); $ii<$m; $ii++) {
if (strpos($elements_in[$i], $sorted_options_id[$ii] . ',') !== false) $elements_out[$ii] = $elements_in[$i];
}
}
ksort($elements_out);
$value = implode('_', $elements_out);
$attributes_quantity[$value] = $qty;
$c_str .= $value . '|';
}
if ($c_str != '') xos_db_query("update " . TABLE_PRODUCTS . " set products_last_modified = now(), attributes_quantity = '" . xos_db_input(serialize($attributes_quantity)) . "', attributes_combinations = '" . xos_db_input($c_str) . "' where products_id = '" . (int)$_GET['products_id'] . "'");
}
$smarty_cache_control->clearCache(null, 'L3|cc_product_info');
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $parameter_string));
break;
case 'update_options_values_sort_order':
$sort_query = xos_db_query("select products_attributes_id from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_id = '" . (int)$_GET['products_id'] . "' and options_id = '" . (int)$_GET['options_id'] . "'");
while($sort = xos_db_fetch_array($sort_query)) {
$option_value_sort_order = xos_db_prepare_input($_POST['option_value_sort_order'][(int)$sort['products_attributes_id']]);
if ((int)$option_value_sort_order > 0) xos_db_query("update " . TABLE_PRODUCTS_ATTRIBUTES . " set options_values_sort_order = '" . (int)$option_value_sort_order . "' where products_attributes_id = '" . (int)$sort['products_attributes_id'] . "'");
}
$smarty_cache_control->clearCache(null, 'L3|cc_product_info');
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $parameter_string));
break;
case 'update_combinations':
$attributes_quantity = array();
$c_str = '';
$qty = 0;
reset($_POST['string_fragment'][(int)$_GET['products_id']]);
while (list($key, $value) = @each($_POST['string_fragment'][(int)$_GET['products_id']])) {
$attributes_quantity[$value] = isset($_POST['attributes_quantity'][(int)$_GET['products_id']][$value]) ? (int)$_POST['attributes_quantity'][(int)$_GET['products_id']][$value] : 0;
$qty += $attributes_quantity[$value] > 0 ? $attributes_quantity[$value] : 0;
$c_str .= $value . '|';
}
if ($c_str != '') xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . (int)$qty . "', products_last_modified = now(), products_status = '" . (int)xos_db_prepare_input($_POST['products_status'][(int)$_GET['products_id']]) . "', attributes_quantity = '" . xos_db_input(serialize($attributes_quantity)) . "', attributes_combinations = '" . xos_db_input($c_str) . "', attributes_not_updated = null where products_id = '" . (int)$_GET['products_id'] . "'");
if ($qty < 1 && STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT == 'false') {
xos_db_query("update " . TABLE_PRODUCTS . " set products_last_modified = now(), products_status = '0' where products_id = '" . (int)$_GET['products_id'] . "'");
}
$smarty_cache_control->clearAllCache();
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $parameter_string));
break;
case 'delete_option':
$option_id = xos_db_prepare_input($_GET['option_id']);
xos_db_query("delete from " . TABLE_PRODUCTS_OPTIONS . " where products_options_id = '" . (int)$option_id . "'");
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&' . $parameter_string));
break;
case 'delete_value':
$value_id = xos_db_prepare_input($_GET['value_id']);
xos_db_query("delete from " . TABLE_PRODUCTS_OPTIONS_VALUES . " where products_options_values_id = '" . (int)$value_id . "'");
xos_db_query("delete from " . TABLE_PRODUCTS_OPTIONS_VALUES_TO_PRODUCTS_OPTIONS . " where products_options_values_id = '" . (int)$value_id . "'");
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, 'options_page=1&' . $parameter_string));
break;
case 'delete_attribute':
$attribute_id = xos_db_prepare_input($_GET['attribute_id']);
$products_id = xos_db_prepare_input($_GET['products_id']);
$combinations_query = xos_db_query("select p.products_quantity, p.attributes_quantity, p.attributes_combinations, p.attributes_not_updated, pa.options_id, pa.options_values_id from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_ATTRIBUTES . " pa where p.products_id = '" . (int)$products_id . "' and pa.products_attributes_id = '" . (int)$attribute_id . "'");
$combinations = xos_db_fetch_array($combinations_query);
$qty = 0;
if (xos_not_null($combinations['attributes_combinations'])) {
$attributes_not_updated = xos_get_attributes_not_updated($combinations['attributes_not_updated']);
foreach ($attributes_not_updated as $key_not_updated => $val_not_updated) {
if ($val_not_updated == $combinations['options_id'] . ',' . $combinations['options_values_id']) unset($attributes_not_updated[$key_not_updated]);
}
ksort($attributes_not_updated);
if (empty($attributes_not_updated)) {
$not_updated = "attributes_not_updated = null";
} else {
$not_updated = "attributes_not_updated = '". xos_db_input(serialize($attributes_not_updated)) . "'";
}
$qty = $combinations['products_quantity'];
$attributes_quantity = xos_get_attributes_quantity($combinations['attributes_quantity']);
$combinations['attributes_combinations'] = trim($combinations['attributes_combinations'], '|');
$elements_comb = explode('|', $combinations['attributes_combinations']);
for ($i=0, $n=sizeof($elements_comb); $i<$n; $i++) {
if (strpos($elements_comb[$i], $combinations['options_id'] . ',' . $combinations['options_values_id']) !== false) {
$qty -= $attributes_quantity[$elements_comb[$i]] > 0 ? $attributes_quantity[$elements_comb[$i]] : 0;
unset($attributes_quantity[$elements_comb[$i]]);
unset($elements_comb[$i]);
}
}
ksort($attributes_quantity);
ksort($elements_comb);
$comb_str = '';
$comb_str = implode('|', $elements_comb);
$qty < 1 || $comb_str == '' ? $qty = 0 : '';
if ($comb_str != '') {
$comb_str .= '|';
xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . (int)$qty . "', products_last_modified = now(), attributes_quantity = '" . xos_db_input(serialize($attributes_quantity)) . "', attributes_combinations = '" . xos_db_input($comb_str) . "', " . $not_updated . " where products_id = '" . (int)$products_id . "'");
} else {
xos_db_query("update " . TABLE_PRODUCTS . " set products_quantity = '" . (int)$qty . "', products_last_modified = now(), attributes_quantity = null, attributes_combinations = null, attributes_not_updated = null where products_id = '" . (int)$products_id . "'");
}
$smarty_cache_control->clearAllCache();
}
xos_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES . " where products_attributes_id = '" . (int)$attribute_id . "'");
// added for DOWNLOAD_ENABLED. Always try to remove attributes, even if downloads are no longer enabled
xos_db_query("delete from " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " where products_attributes_id = '" . (int)$attribute_id . "'");
if ($qty < 1 && STOCK_CHECK == 'true' && STOCK_ALLOW_CHECKOUT == 'false') {
xos_db_query("update " . TABLE_PRODUCTS . " set products_status = '0' where products_id = '" . (int)$products_id . "'");
$smarty_cache_control->clearAllCache();
}
$smarty_cache_control->clearCache(null, 'L3|cc_product_info');
xos_redirect(xos_href_link(FILENAME_PRODUCTS_ATTRIBUTES, $parameter_string));
break;
}
}
define('MAX_ROW_LISTS_OPTIONS', 15);
define('MAX_PRODUCTS_IN_PULLDOWN', 50);
$max_display_rows_array = array();
$max_display_rows_array[] = array('id' => MAX_ROW_LISTS_OPTIONS, 'text' => MAX_ROW_LISTS_OPTIONS);
for ($i = 20; $i <=200 ; $i=$i+20) {
$max_display_rows_array[] = array('id' => $i, 'text' => $i);
}
$max_display_products_in_pulldown_array = array();
$max_display_products_in_pulldown_array[] = array('id' => MAX_PRODUCTS_IN_PULLDOWN, 'text' => MAX_PRODUCTS_IN_PULLDOWN);
for ($i = 100; $i <=500 ; $i=$i+50) {
$max_display_products_in_pulldown_array[] = array('id' => $i, 'text' => $i);
}
$manufacturers_array = array(array('id' => '', 'text' => TEXT_ALL));
$manufacturers_query = xos_db_query("select manufacturers_id, manufacturers_name from " . TABLE_MANUFACTURERS_INFO . " where languages_id = '" . (int)$_SESSION['used_lng_id'] . "' order by manufacturers_name");
while ($manufacturers = xos_db_fetch_array($manufacturers_query)) {
$manufacturers_array[] = array('id' => $manufacturers['manufacturers_id'],
'text' => $manufacturers['manufacturers_name']);
}
$tax_class_array = array(array('id' => '0', 'text' => TEXT_NONE));
$tax_class_query = xos_db_query("select distinct tc.tax_class_id, tc.tax_class_title from " . TABLE_TAX_CLASS . " tc, " . TABLE_TAX_RATES . " tr where tc.tax_class_id = tr.tax_class_id order by tc.tax_class_title");
while ($tax_class = xos_db_fetch_array($tax_class_query)) {
$tax_class_array[] = array('id' => $tax_class['tax_class_id'],
'text' => $tax_class['tax_class_title']);
}
$tax_rates_final_array = array(array('id' => '0', 'text' => TEXT_NONE));
$tax_rates_final_query = xos_db_query("select tr.tax_rates_final_id, tc.tax_class_title, gz.geo_zone_name, tr.tax_rate_final from " . TABLE_TAX_RATES_FINAL . " tr, " . TABLE_TAX_CLASS . " tc, " . TABLE_GEO_ZONES . " gz where tr.tax_class_id = tc.tax_class_id and tr.tax_zone_id = gz.geo_zone_id order by tc.tax_class_title, gz.geo_zone_name");
while ($tax_rates_final= xos_db_fetch_array($tax_rates_final_query)) {
$tax_rates_final_array[] = array('id' => $tax_rates_final['tax_rates_final_id'],
'text' => $tax_rates_final['tax_class_title'] . ' (' . $tax_rates_final['geo_zone_name'] . ') [' . $tax_rates_final['tax_rate_final'] . '%]',
'value' => $tax_rates_final['tax_rate_final']);
}
function xos_get_categories_string($parent_id = '', $entrance = false, $categories_string = '') {
if ($entrance) {
$categories_string = " p2c.categories_or_pages_id = '" . $parent_id . "'";
}
$categories_query = xos_db_query("select c.categories_or_pages_id, cpd.categories_or_pages_name, c.parent_id from " . TABLE_CATEGORIES_OR_PAGES . " c, " . TABLE_CATEGORIES_OR_PAGES_DATA . " cpd where c.categories_or_pages_id = cpd.categories_or_pages_id and cpd.language_id = '" . (int)$_SESSION['used_lng_id'] . "' and c.parent_id = '" . (int)$parent_id . "' order by c.sort_order, cpd.categories_or_pages_name");
while ($categories = xos_db_fetch_array($categories_query)) {
$categories_string .= " or p2c.categories_or_pages_id = '" . $categories['categories_or_pages_id'] . "'";
$categories_string = xos_get_categories_string($categories['categories_or_pages_id'], '', $categories_string);
}
return $categories_string;
}
$javascript = '<script type="text/javascript">' . "\n" .
'/* <![CDATA[ */' . "\n\n" .
'function toggle() {' . "\n" .
' if (document.getElementById("options").style.display == "none"){' . "\n" .
' document.getElementById("filter").style.display="none";' . "\n" .
' document.getElementById("no-filter").style.display="";' . "\n" .
' document.getElementById("options").style.display="";' . "\n" .
' document.getElementById("attributes").style.display="none";' . "\n" .
' } else {' . "\n" .
' document.getElementById("filter").style.display="";' . "\n" .
' document.getElementById("no-filter").style.display="none";' . "\n" .
' document.getElementById("options").style.display="none";' . "\n" .
' document.getElementById("attributes").style.display="";' . "\n" .
' }' . "\n" .
'}' . "\n\n" .
'/* ]]> */' . "\n" .
'</script>' . "\n";
require(DIR_WS_INCLUDES . 'html_header.php');
require(DIR_WS_INCLUDES . 'header.php');
require(DIR_WS_INCLUDES . 'column_left.php');
require(DIR_WS_INCLUDES . 'footer.php');
if ($pID) {
$smarty->assign(array('single_product' => true,
'text_new_product' => sprintf(TEXT_NEW_PRODUCT_3, ($form_action == 'insert_product' ? TEXT_NEW_PRODUCT_1 : TEXT_NEW_PRODUCT_2), xos_output_generated_category_path($current_category_id)),
'link_back_to_product_list' => xos_href_link(FILENAME_CATEGORIES, 'cPath=' . $cPath . '&pID=' . $pID),
'form_begin_filter_products_attributes' => xos_draw_form('filter_products_attributes', FILENAME_PRODUCTS_ATTRIBUTES, '','get'),
'pull_down_menu_max_rows' => xos_draw_pull_down_menu('max_rows', $max_display_rows_array, $_GET['max_rows'], 'style="width: 75px;"'),
'hidden_fields_page_info' => xos_draw_hidden_field('pID', $pID) . xos_draw_hidden_field('cPath', $cPath) . xos_draw_hidden_field('selected_tax_rate_id', $_GET['selected_tax_rate_id']) . xos_draw_hidden_field('option_page', $_GET['option_page']) . xos_draw_hidden_field('value_page', $_GET['value_page']) . xos_draw_hidden_field('attribute_page', $_GET['attribute_page']),
'form_end_filter' => '</form>'));
} else{
$smarty->assign(array('form_begin_filter_products_attributes' => xos_draw_form('filter_products_attributes', FILENAME_PRODUCTS_ATTRIBUTES, '','get'),
'pull_down_menu_categories_or_pages_id' => xos_draw_pull_down_menu('categories_or_pages_id', xos_get_category_tree(), $categories_or_pages_id),
'pull_down_menu_manufacturers_id' => xos_draw_pull_down_menu('manufacturers_id', $manufacturers_array, $manufacturers_id),
'pull_down_menu_max_rows' => xos_draw_pull_down_menu('max_rows', $max_display_rows_array, $_GET['max_rows'], 'style="width: 75px;"'),
'pull_down_menu_max_products' => xos_draw_pull_down_menu('max_products_in_pullwown', $max_display_products_in_pulldown_array, $_GET['max_products_in_pullwown'], 'style="width: 155px;"'),
'hidden_fields_page_info' => xos_draw_hidden_field('selected_tax_rate_id', $_GET['selected_tax_rate_id']) . xos_draw_hidden_field('option_page', $_GET['option_page']) . xos_draw_hidden_field('value_page', $_GET['value_page']) . xos_draw_hidden_field('attribute_page', $_GET['attribute_page']),
'form_end_filter' => '</form>'));
}
if (SID) {
$smarty->assign('hidden_field_session', xos_draw_hidden_field(xos_session_name(), xos_session_id()));
}
$js_init_style = '<script type="text/javascript">' . "\n" .
'/* <![CDATA[ */' . "\n\n";
if ($_GET['first_entrance']) {
$js_init_style .= ' document.getElementById("filter").style.display="";' . "\n" .
' document.getElementById("no-filter").style.display="none";' . "\n" .
' document.getElementById("options").style.display="none";' . "\n" .
' document.getElementById("attributes").style.display="none";' . "\n\n";
} elseif ($_GET['options_page']) {
$js_init_style .= ' document.getElementById("filter").style.display="none";' . "\n" .
' document.getElementById("no-filter").style.display="";' . "\n" .
' document.getElementById("options").style.display="";' . "\n" .
' document.getElementById("attributes").style.display="none";' . "\n\n";
} else {
$js_init_style .= ' document.getElementById("filter").style.display="";' . "\n" .
' document.getElementById("no-filter").style.display="none";' . "\n" .
' document.getElementById("options").style.display="none";' . "\n" .
' document.getElementById("attributes").style.display="";' . "\n\n";
}
$js_init_style .= '/* ]]> */' . "\n" .
'</script>' . "\n";
$smarty->assign('js_init_style', $js_init_style);
if (!$_GET['first_entrance']) {
require(DIR_WS_MODULES . 'attributes_options.php');
require(DIR_WS_MODULES . 'attributes_values.php');
require(DIR_WS_MODULES . 'attributes_products.php');
}
$smarty->configLoad('languages/' . $_SESSION['language'] . '.conf', 'products_attributes');
$output_products_attributes = $smarty->fetch(ADMIN_TPL . '/products_attributes.tpl');
$smarty->assign('central_contents', $output_products_attributes);
$smarty->display(ADMIN_TPL . '/frame.tpl');
require(DIR_WS_INCLUDES . 'application_bottom.php');
endif;
?>
| hpzeller/xos_shop_system | shop/admin/products_attributes.php | PHP | gpl-3.0 | 44,403 |
/**
******************************************************************************
* @file stm32f7xx_ll_utils.h
* @author MCD Application Team
* @version V1.2.1
* @date 24-March-2017
* @brief Header file of UTILS LL module.
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The LL UTILS driver contains a set of generic APIs that can be
used by user:
(+) Device electronic signature
(+) Timing functions
(+) PLL configuration functions
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* 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.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F7xx_LL_UTILS_H
#define __STM32F7xx_LL_UTILS_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f7xx.h"
/** @addtogroup STM32F7xx_LL_Driver
* @{
*/
/** @defgroup UTILS_LL UTILS
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/** @defgroup UTILS_LL_Private_Constants UTILS Private Constants
* @{
*/
/* Max delay can be used in LL_mDelay */
#define LL_MAX_DELAY 0xFFFFFFFFU
/**
* @brief Unique device ID register base address
*/
#define UID_BASE_ADDRESS UID_BASE
/**
* @brief Flash size data register base address
*/
#define FLASHSIZE_BASE_ADDRESS FLASHSIZE_BASE
/**
* @brief Package data register base address
*/
#define PACKAGE_BASE_ADDRESS PACKAGE_BASE
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/** @defgroup UTILS_LL_Private_Macros UTILS Private Macros
* @{
*/
/**
* @}
*/
/* Exported types ------------------------------------------------------------*/
/** @defgroup UTILS_LL_ES_INIT UTILS Exported structures
* @{
*/
/**
* @brief UTILS PLL structure definition
*/
typedef struct
{
uint32_t PLLM; /*!< Division factor for PLL VCO input clock.
This parameter can be a value of @ref RCC_LL_EC_PLLM_DIV
This feature can be modified afterwards using unitary function
@ref LL_RCC_PLL_ConfigDomain_SYS(). */
uint32_t PLLN; /*!< Multiplication factor for PLL VCO output clock.
This parameter must be a number between Min_Data = 50 and Max_Data = 432
This feature can be modified afterwards using unitary function
@ref LL_RCC_PLL_ConfigDomain_SYS(). */
uint32_t PLLP; /*!< Division for the main system clock.
This parameter can be a value of @ref RCC_LL_EC_PLLP_DIV
This feature can be modified afterwards using unitary function
@ref LL_RCC_PLL_ConfigDomain_SYS(). */
} LL_UTILS_PLLInitTypeDef;
/**
* @brief UTILS System, AHB and APB buses clock configuration structure definition
*/
typedef struct
{
uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK).
This parameter can be a value of @ref RCC_LL_EC_SYSCLK_DIV
This feature can be modified afterwards using unitary function
@ref LL_RCC_SetAHBPrescaler(). */
uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK).
This parameter can be a value of @ref RCC_LL_EC_APB1_DIV
This feature can be modified afterwards using unitary function
@ref LL_RCC_SetAPB1Prescaler(). */
uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK).
This parameter can be a value of @ref RCC_LL_EC_APB2_DIV
This feature can be modified afterwards using unitary function
@ref LL_RCC_SetAPB2Prescaler(). */
} LL_UTILS_ClkInitTypeDef;
/**
* @}
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup UTILS_LL_Exported_Constants UTILS Exported Constants
* @{
*/
/** @defgroup UTILS_EC_HSE_BYPASS HSE Bypass activation
* @{
*/
#define LL_UTILS_HSEBYPASS_OFF 0x00000000U /*!< HSE Bypass is not enabled */
#define LL_UTILS_HSEBYPASS_ON 0x00000001U /*!< HSE Bypass is enabled */
/**
* @}
*/
/** @defgroup UTILS_EC_PACKAGETYPE PACKAGE TYPE
* @{
*/
#define LL_UTILS_PACKAGETYPE_LQFP100 0x00000100U /*!< LQFP100 package type */
#define LL_UTILS_PACKAGETYPE_LQFP144_WLCSP143 0x00000200U /*!< LQFP144 or WLCSP143 package type */
#define LL_UTILS_PACKAGETYPE_WLCSP180_LQFP176_UFBGA176 0x00000300U /*!< WLCSP180, LQFP176 or UFBGA176 package type */
#define LL_UTILS_PACKAGETYPE_LQFP176_LQFP208_TFBGA216 0x00000400U /*!< LQFP176, LQFP208 or TFBGA216 package type */
#define LL_UTILS_PACKAGETYPE_TFBGA216_LQFP176_LQFP208 0x00000500U /*!< LQFP176, LQFP208 or TFBGA216 package type */
#define LL_UTILS_PACKAGETYPE_LQFP176_TFBGA216_LQFP208 0x00000600U /*!< LQFP176, LQFP208 or TFBGA216 package type */
#define LL_UTILS_PACKAGETYPE_LQFP208_LQFP176_TFBGA216 0x00000700U /*!< LQFP176, LQFP208 or TFBGA216 package type */
/**
* @}
*/
/**
* @}
*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup UTILS_LL_Exported_Functions UTILS Exported Functions
* @{
*/
/** @defgroup UTILS_EF_DEVICE_ELECTRONIC_SIGNATURE DEVICE ELECTRONIC SIGNATURE
* @{
*/
/**
* @brief Get Word0 of the unique device identifier (UID based on 96 bits)
* @retval UID[31:0]
*/
__STATIC_INLINE uint32_t LL_GetUID_Word0(void)
{
return (uint32_t)(READ_REG(*((uint32_t *)UID_BASE_ADDRESS)));
}
/**
* @brief Get Word1 of the unique device identifier (UID based on 96 bits)
* @retval UID[63:32]
*/
__STATIC_INLINE uint32_t LL_GetUID_Word1(void)
{
return (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE_ADDRESS + 4U))));
}
/**
* @brief Get Word2 of the unique device identifier (UID based on 96 bits)
* @retval UID[95:64]
*/
__STATIC_INLINE uint32_t LL_GetUID_Word2(void)
{
return (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE_ADDRESS + 8U))));
}
/**
* @brief Get Flash memory size
* @note This bitfield indicates the size of the device Flash memory expressed in
* Kbytes. As an example, 0x040 corresponds to 64 Kbytes.
* @retval FLASH_SIZE[15:0]: Flash memory size
*/
__STATIC_INLINE uint32_t LL_GetFlashSize(void)
{
return (uint16_t)(READ_REG(*((uint32_t *)FLASHSIZE_BASE_ADDRESS)));
}
/**
* @brief Get Package type
* @retval Returned value can be one of the following values:
* @arg @ref LL_UTILS_PACKAGETYPE_LQFP100
* @arg @ref LL_UTILS_PACKAGETYPE_LQFP144_WLCSP143 (*)
* @arg @ref LL_UTILS_PACKAGETYPE_WLCSP180_LQFP176_UFBGA176 (*)
* @arg @ref LL_UTILS_PACKAGETYPE_LQFP176_LQFP208_TFBGA216 (*)
*
* (*) value not defined in all devices.
*/
__STATIC_INLINE uint32_t LL_GetPackageType(void)
{
return (uint16_t)(READ_REG(*((uint32_t *)PACKAGE_BASE_ADDRESS)) & 0x0700U);
}
/**
* @}
*/
/** @defgroup UTILS_LL_EF_DELAY DELAY
* @{
*/
/**
* @brief This function configures the Cortex-M SysTick source of the time base.
* @param HCLKFrequency HCLK frequency in Hz (can be calculated thanks to RCC helper macro)
* @note When a RTOS is used, it is recommended to avoid changing the SysTick
* configuration by calling this function, for a delay use rather osDelay RTOS service.
* @param Ticks Number of ticks
* @retval None
*/
__STATIC_INLINE void LL_InitTick(uint32_t HCLKFrequency, uint32_t Ticks)
{
/* Configure the SysTick to have interrupt in 1ms time base */
SysTick->LOAD = (uint32_t)((HCLKFrequency / Ticks) - 1UL); /* set reload register */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable the Systick Timer */
}
void LL_Init1msTick(uint32_t HCLKFrequency);
void LL_mDelay(uint32_t Delay);
/**
* @}
*/
/** @defgroup UTILS_EF_SYSTEM SYSTEM
* @{
*/
void LL_SetSystemCoreClock(uint32_t HCLKFrequency);
ErrorStatus LL_PLL_ConfigSystemClock_HSI(LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct,
LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct);
ErrorStatus LL_PLL_ConfigSystemClock_HSE(uint32_t HSEFrequency, uint32_t HSEBypass,
LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct, LL_UTILS_ClkInitTypeDef *UTILS_ClkInitStruct);
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32F7xx_LL_UTILS_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| dammstanger/cleanflight | lib/main/STM32F7xx_HAL_Driver/Inc/stm32f7xx_ll_utils.h | C | gpl-3.0 | 11,411 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.blockprocessors import BlockProcessor
import re
from markdown import util
import xml.etree.ElementTree as ET
import copy
from markdown.inlinepatterns import IMAGE_LINK_RE
class InFigureParser(object):
def transform(self, parent, element, legend, index, InP = False):
if InP:
lelems = list(element.iter())
oldImg = lelems[-1]
element.remove(oldImg)
else:
oldImg = element
nFig = util.etree.Element("figure")
nFigCaption = util.etree.Element("figcaption")
contentLegend = legend.items()
for el in legend:
legend.remove(el)
nFigCaption.append(el)
nFig.append(oldImg)
nFig.append(nFigCaption)
parent.remove(element)
parent.remove(legend)
parent.insert(index, nFig)
class FigureParser(InFigureParser):
def __init__(self, ignoringImg):
InFigureParser.__init__(self)
self.ignoringImg = ignoringImg
self.ree = re.compile(r"^" + IMAGE_LINK_RE + r"(\n|$)")
def detect(self, element, type):
if element == None:
return False
lelems = list(element.iter())
#print repr(element.text)
return (type == "unknown" or type == "Figure") \
and element.tag=="p" \
and( ( element.text is not None \
and self.ree.search(element.text)) \
or ( (element.text is None or element.text.strip() == "") \
and (len(lelems) == 1 or (len(lelems)==2 and lelems[0] is element)) \
and lelems[-1].tag == "img" \
and (lelems[-1].attrib["src"] not in self.ignoringImg)))
def transform(self, parent, element, legend, index):
InFigureParser.transform(self, parent, element, legend, index, True)
class EquationParser(InFigureParser):
def detect(self, element, type):
if element == None:
return False
lelems = list(element.iter())
return (type == "unknown" or type == "Equation") \
and element.tag=="p" \
and (element.text is None or element.text.strip() == "") \
and (len(lelems) == 1 or (len(lelems)==2 and lelems[0] is element)) \
and lelems[-1].tag == "mathjax"
def transform(self, parent, element, legend, index):
InFigureParser.transform(self, parent, element, legend, index, True)
class CodeParser(InFigureParser):
def __init__(self, md):
self.md = md
def detect(self, element, type):
if element == None:
return False
if (type == "unknown" or type == "Code") and element.tag=="p" :
hs = self.md.htmlStash
for i in range(hs.html_counter):
if element.text == hs.get_placeholder(i) :
Teste = ET.fromstring(hs.rawHtmlBlocks[i][0].encode('utf-8'))
if Teste is not None and Teste.tag=="table" and "class" in Teste.attrib and Teste.attrib["class"] == "codehilitetable":
return True
else:
return False
return False
class QuoteParser(InFigureParser):
def detect(self, element, type):
if element == None:
return False
return (type == "unknown" or type == "Source") and element.tag=="blockquote"
class TableParser(object):
def detect(self, element, type):
if element == None:
return False
return (type == "unknown" or type == "Table") and element.tag=="table"
def transform(self, parent, element, legend, index):
parent.remove(legend)
cap = util.etree.Element('caption')
contentLegend = legend.items()
for el in legend:
legend.remove(el)
cap.append(el)
element.insert(0, cap)
class VideoParser(InFigureParser):
def detect(self, element, type):
if element == None:
return False
lelems = list(element.iter())
return (type == "unknown" or type == "Video") \
and element.tag=="iframe"
class SmartLegendProcessor(Treeprocessor):
def __init__(self, parser, configs, md):
Treeprocessor.__init__(self, parser)
self.configs = configs
self.processors = ( FigureParser(configs["IGNORING_IMG"]),
EquationParser(),
CodeParser(md),
TableParser(),
VideoParser(),
QuoteParser())
def run(self, root):
root = self.parse_legend(root)
root = self.parse_autoimg(root)
return root
def parse_legend(self, root):
elemsToInspect = [root]
while len(elemsToInspect) > 0:
elem = elemsToInspect.pop()
Restart=True
while Restart:
Restart = False
precedent = None
i=0
for nelem in elem:
if nelem.tag in self.configs["PARENTS"] and nelem not in elemsToInspect:
elemsToInspect.append(nelem)
if nelem.tag == "customlegend" and precedent is not None : # and len(list(nelem.itertext())) == 0 :
proc = self.detectElement(precedent, nelem.attrib["type"])
if proc is not None:
proc.transform(elem, precedent, nelem, i-1)
Restart = True
break
precedent = nelem
i+=1
return root
def parse_autoimg(self, root):
elemsToInspect = [root]
while len(elemsToInspect) > 0:
elem = elemsToInspect.pop()
Restart=True
while Restart:
Restart = False
i=0
for nelem in elem:
if nelem.tag in self.configs["PARENTS"] and nelem not in elemsToInspect:
elemsToInspect.append(nelem)
#Auto Legend for image
if nelem.tag == 'p' and len(list(nelem.itertext())) == 0 :
lelems = list(nelem.iter())
if (len(lelems) == 1 or (len(lelems)==2 and lelems[0] is nelem)) \
and lelems[-1].tag == "img" \
and lelems[-1].attrib["alt"] != "" \
and not (lelems[-1].attrib["src"] in self.configs["IGNORING_IMG"]):
oldImg = lelems[-1]
nelem.remove(oldImg)
nFig = util.etree.Element("figure")
nFigCaption = util.etree.Element("figcaption")
nFigCaption.text = oldImg.attrib["alt"]
oldImg.attrib["alt"]=""
nFig.append(oldImg)
nFig.append(nFigCaption)
nelem.insert(i-1, nFig)
Restart = True
break
i+=1
return root
def detectElement(self, elem, legend):
for proc in self.processors:
if proc.detect(elem, legend) :
return proc
return None
class LegendProcessor(BlockProcessor):
def __init__(self, parser, md, configs):
BlockProcessor.__init__(self, parser)
self.md = md
self.configs = configs
self.processors = ( FigureParser(configs["IGNORING_IMG"]),
EquationParser(),
CodeParser(md),
TableParser(),
VideoParser(),
QuoteParser())
self.RE = re.compile(r'(^|(?<=\n))((?P<typelegend>Figure|Table|Code|Equation|Video|Source)\s?)*\:\s?(?P<txtlegend>.*?)(\n|$)')
def detectElement(self, elem, legend):
for proc in self.processors:
if proc.detect(elem, legend) :
return proc
return None
def test(self, parent, block):
mLeg = self.RE.search(block)
if not bool(mLeg):
return False
else:
return True
def test_complete(self, parent, block):
mLeg = self.RE.search(block)
gd = mLeg.groupdict()
if gd["typelegend"] is None:
type = "unknown"
else:
type = gd["typelegend"]
sibling = self.lastChild(parent)
return self.detectElement(sibling, type) is not None
def run(self, parent, blocks):
block = blocks.pop(0)
mLeg = self.RE.search(block)
before = block[:mLeg.start()]
after = block[mLeg.end():]
contentStart = block[mLeg.start():mLeg.start("txtlegend")]
cpp = None
if before:
cpp = copy.copy(parent)
self.parser.parseBlocks(cpp, [before])
else:
cpp = parent
if not self.test_complete(cpp, block):
blocks.insert(0, block)
return False
elif before:
self.parser.parseBlocks(parent, [before])
nLegend = util.etree.Element("customlegend")
self.parser.parseChunk(nLegend, mLeg.group('txtlegend'))
gd = mLeg.groupdict()
if gd["typelegend"] is None:
nLegend.set("type", "unknown")
else:
nLegend.set("type", gd["typelegend"])
nLegend.set("rawStart", contentStart)
parent.append(nLegend)
if after:
blocks.insert(0,after)
class SmartLegendExtension(markdown.extensions.Extension):
def __init__(self, configs={}):
self.configs = {
"IGNORING_IMG" : [],
"PARENTS" : [],
}
for key, value in configs.items():
self.configs[key] = value
if "div" not in self.configs["PARENTS"]:
self.configs["PARENTS"].append("div")
pass
def extendMarkdown(self, md, md_globals):
md.registerExtension(self)
md.treeprocessors.add('smart-legend', SmartLegendProcessor(md.parser,self.configs, md),"_end")
md.parser.blockprocessors.add('legend-processor', LegendProcessor(md.parser,md, self.configs),"_begin")
def makeExtension(configs={}):
return SmartImgExtension(configs=configs)
| the-new-sky/BlogInPy | markdown/extensions/smartLegend.py | Python | gpl-3.0 | 10,615 |
package tcp
import (
"net"
"net/url"
"strings"
"github.com/nadoo/glider/pkg/log"
"github.com/nadoo/glider/proxy"
)
// TCP struct.
type TCP struct {
addr string
dialer proxy.Dialer
proxy proxy.Proxy
}
func init() {
proxy.RegisterDialer("tcp", NewTCPDialer)
proxy.RegisterServer("tcp", NewTCPServer)
}
// NewTCP returns a tcp struct.
func NewTCP(s string, d proxy.Dialer, p proxy.Proxy) (*TCP, error) {
u, err := url.Parse(s)
if err != nil {
log.F("[tcp] parse url err: %s", err)
return nil, err
}
t := &TCP{
dialer: d,
proxy: p,
addr: u.Host,
}
return t, nil
}
// NewTCPDialer returns a tcp dialer.
func NewTCPDialer(s string, d proxy.Dialer) (proxy.Dialer, error) {
return NewTCP(s, d, nil)
}
// NewTCPServer returns a tcp transport layer before the real server.
func NewTCPServer(s string, p proxy.Proxy) (proxy.Server, error) {
return NewTCP(s, nil, p)
}
// ListenAndServe listens on server's addr and serves connections.
func (s *TCP) ListenAndServe() {
l, err := net.Listen("tcp", s.addr)
if err != nil {
log.Fatalf("[tcp] failed to listen on %s: %v", s.addr, err)
return
}
defer l.Close()
log.F("[tcp] listening TCP on %s", s.addr)
for {
c, err := l.Accept()
if err != nil {
log.F("[tcp] failed to accept: %v", err)
continue
}
go s.Serve(c)
}
}
// Serve serves a connection.
func (s *TCP) Serve(c net.Conn) {
defer c.Close()
if c, ok := c.(*net.TCPConn); ok {
c.SetKeepAlive(true)
}
rc, dialer, err := s.proxy.Dial("tcp", "")
if err != nil {
log.F("[tcp] %s <-> %s via %s, error in dial: %v", c.RemoteAddr(), s.addr, dialer.Addr(), err)
s.proxy.Record(dialer, false)
return
}
defer rc.Close()
log.F("[tcp] %s <-> %s", c.RemoteAddr(), dialer.Addr())
if err = proxy.Relay(c, rc); err != nil {
log.F("[tcp] %s <-> %s, relay error: %v", c.RemoteAddr(), dialer.Addr(), err)
// record remote conn failure only
if !strings.Contains(err.Error(), s.addr) {
s.proxy.Record(dialer, false)
}
}
}
// Addr returns forwarder's address.
func (s *TCP) Addr() string {
if s.addr == "" {
return s.dialer.Addr()
}
return s.addr
}
// Dial connects to the address addr on the network net via the proxy.
func (s *TCP) Dial(network, addr string) (net.Conn, error) {
return s.dialer.Dial("tcp", s.addr)
}
// DialUDP connects to the given address via the proxy.
func (s *TCP) DialUDP(network, addr string) (net.PacketConn, net.Addr, error) {
return nil, nil, proxy.ErrNotSupported
}
| nadoo/glider | proxy/tcp/tcp.go | GO | gpl-3.0 | 2,478 |
#!../bin/rshell
#Test cases used: (manually inputted)
echo hello #0to100realquick
ls -l #swag
ls #-l
echo food && echo bard #test
#idkbro
test main.cpp #this
test -e main.cpp #is
test -f main.cpp #just
test -d main.cpp #a
test main.cpp #test
echo hello && #ayylmao
echo hello && #echo hi
| liujustinh/rshell | test cases/commented_command.sh | Shell | gpl-3.0 | 294 |
require "rspec"
extend RSpec::Matchers
describe "Bad Unit Tests" do
it "should show an example of forced passes" do
# Doesn't matter what happens here, since assertion always passes
expect(true).to be true
end
end
| chefsim/bad-units | Ruby/spec/bad_units.rb | Ruby | gpl-3.0 | 230 |
<?php
namespace Alchemy\Tests\Phrasea\Controller\Api;
use Alchemy\Phrasea\Application;
use Alchemy\Phrasea\Border\File;
use Alchemy\Phrasea\Controller\Api\V1Controller;
use Alchemy\Phrasea\ControllerProvider\Api\V1;
use Alchemy\Phrasea\Core\PhraseaEvents;
use Alchemy\Phrasea\Authentication\Context;
use Alchemy\Phrasea\Model\Entities\ApiOauthToken;
use Alchemy\Phrasea\Model\Entities\LazaretSession;
use Alchemy\Phrasea\Model\Entities\Task;
use Alchemy\Phrasea\Model\Entities\User;
use Alchemy\Phrasea\SearchEngine\SearchEngineOptions;
use Doctrine\Common\Collections\ArrayCollection;
use Guzzle\Common\Exception\GuzzleException;
use Rhumsaa\Uuid\Uuid;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpFoundation\Response;
abstract class ApiTestCase extends \PhraseanetWebTestCase
{
abstract protected function getParameters(array $parameters = []);
abstract protected function unserialize($data);
abstract protected function getAcceptMimeType();
private $adminAccessToken;
private $userAccessToken;
public function tearDown()
{
$this->unsetToken();
parent::tearDown();
}
public function getApplicationPath()
{
return '/lib/Alchemy/Phrasea/Application/Api.php';
}
public function setUp()
{
parent::setUp();
if (null === $this->adminAccessToken) {
$tokens = self::$DI['app']['repo.api-oauth-tokens']->findOauthTokens(self::$DI['oauth2-app-acc-user']);
if (count($tokens) === 0) {
$this->fail(sprintf('No access token generated between user %s & application %s',
self::$DI['oauth2-app-acc-user']->getUser()->getLogin(),
self::$DI['oauth2-app-acc-user']->getApplication()->getName()
));
}
$this->adminAccessToken = current($tokens);
}
if (null === $this->userAccessToken) {
$tokens = self::$DI['app']['repo.api-oauth-tokens']->findOauthTokens(self::$DI['oauth2-app-acc-user-not-admin']);
if (count($tokens) === 0) {
$this->fail(sprintf('No access token generated between user %s & application %s',
self::$DI['oauth2-app-acc-user-not-admin']->getUser()->getLogin(),
self::$DI['oauth2-app-acc-user-not-admin']->getApplication()->getName()
));
}
$this->userAccessToken = current($tokens);
}
}
public function testAddStory()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/stories';
$story['base_id'] = self::$DI['collection']->get_base_id();
$story['title'] = uniqid('story');
$file = new File(
self::$DI['app'],
self::$DI['app']['mediavorus']->guess(__DIR__ . '/../../../../../files/p4logo.jpg'),
self::$DI['collection']
);
$record = \record_adapter::createFromFile($file, self::$DI['app']);
$story['story_records'] = array(array(
'databox_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id()
));
self::$DI['client']->request(
'POST',
$route,
$this->getParameters(),
$this->getAddRecordFile(),
[
'HTTP_ACCEPT' => $this->getAcceptMimeType(),
'CONTENT_TYPE' => 'application/json',
],
json_encode(array('stories' => array($story)))
);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$data = $content['response'];
$this->assertArrayHasKey('stories', $data);
$this->assertCount(1, $data['stories']);
list($empty, $path, $databox_id, $story_id) = explode('/', current($data['stories']));
$databox = self::$DI['app']['phraseanet.appbox']->get_databox($databox_id);
$story = $databox->get_record($story_id);
$story->delete();
$record->delete();
}
public function testAddRecordToStory()
{
$this->setToken($this->userAccessToken);
$story = \record_adapter::createStory(self::$DI['app'], self::$DI['collection']);
$route = sprintf('/api/v1/stories/%s/%s/addrecords', $story->get_sbas_id(), $story->get_record_id());
$file = new File(
self::$DI['app'],
self::$DI['app']['mediavorus']->guess(__DIR__ . '/../../../../../files/extractfile.jpg'),
self::$DI['collection']
);
$record = \record_adapter::createFromFile($file, self::$DI['app']);
$records = array(
'databox_id' => $record->get_sbas_id(),
'record_id' => $record->get_record_id()
);
self::$DI['client']->request(
'POST',
$route,
$this->getParameters(),
$this->getAddRecordFile(),
[
'HTTP_ACCEPT' => $this->getAcceptMimeType(),
'CONTENT_TYPE' => 'application/json',
],
json_encode(array('story_records' => array($records)))
);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$data = $content['response'];
$this->assertArrayHasKey('records', $data);
$this->assertCount(1, $data['records']);
$story->delete();
$record->delete();
}
/**
* @dataProvider provideEventNames
*/
public function testThatEventsAreDispatched($eventName, $className, $route, $context)
{
$preEvent = 0;
self::$DI['app']['dispatcher']->addListener($eventName, function ($event) use (&$preEvent, $className, $context) {
$preEvent++;
$this->assertInstanceOf($className, $event);
if (null !== $context) {
$this->assertEquals($context, $event->getContext()->getContext());
}
});
$this->setToken($this->userAccessToken);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$this->assertEquals(1, $preEvent);
}
public function testThatSessionIsClosedAfterRequest()
{
$this->assertCount(0, self::$DI['app']['orm.em']->getRepository('Phraseanet:Session')->findAll());
$this->setToken($this->userAccessToken);
self::$DI['client']->request('GET', '/api/v1/databoxes/list/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$this->assertCount(0, self::$DI['app']['orm.em']->getRepository('Phraseanet:Session')->findAll());
}
public function provideEventNames()
{
return [
[PhraseaEvents::PRE_AUTHENTICATE, 'Alchemy\Phrasea\Core\Event\PreAuthenticate', '/api/v1/databoxes/list/', Context::CONTEXT_OAUTH2_TOKEN],
[PhraseaEvents::API_OAUTH2_START, 'Alchemy\Phrasea\Core\Event\ApiOAuth2StartEvent', '/api/v1/databoxes/list/', null],
[PhraseaEvents::API_OAUTH2_END, 'Alchemy\Phrasea\Core\Event\ApiOAuth2EndEvent', '/api/v1/databoxes/list/', null],
[PhraseaEvents::API_RESULT, 'Alchemy\Phrasea\Core\Event\ApiResultEvent', '/api/v1/databoxes/list/', null],
[PhraseaEvents::API_RESULT, 'Alchemy\Phrasea\Core\Event\ApiResultEvent', '/api/v1/no-route', null],
];
}
public function testRouteNotFound()
{
$route = '/api/v1/nothinghere';
$this->setToken($this->userAccessToken);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseNotFound(self::$DI['client']->getResponse());
$this->evaluateMetaNotFound($content);
}
public function testDataboxListRoute()
{
$this->setToken($this->userAccessToken);
self::$DI['client']->request('GET', '/api/v1/databoxes/list/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('databoxes', $content['response']);
foreach ($content['response']['databoxes'] as $databox) {
$this->assertTrue(is_array($databox), 'Une databox est un objet');
$this->assertArrayHasKey('databox_id', $databox);
$this->assertArrayHasKey('name', $databox);
$this->assertArrayHasKey('viewname', $databox);
$this->assertArrayHasKey('labels', $databox);
$this->assertArrayHasKey('fr', $databox['labels']);
$this->assertArrayHasKey('en', $databox['labels']);
$this->assertArrayHasKey('de', $databox['labels']);
$this->assertArrayHasKey('nl', $databox['labels']);
$this->assertArrayHasKey('version', $databox);
break;
}
}
public function testCheckNativeApp()
{
$value = self::$DI['app']['conf']->get(['registry', 'api-clients', 'navigator-enabled']);
self::$DI['app']['conf']->set(['registry', 'api-clients', 'navigator-enabled'], false);
$fail = null;
try {
$nativeApp = self::$DI['app']['repo.api-applications']->findByClientId(\API_OAuth2_Application_Navigator::CLIENT_ID);
if (null === $nativeApp) {
throw new \Exception(sprintf('%s not found', \API_OAuth2_Application_Navigator::CLIENT_ID));
}
$account = self::$DI['app']['manipulator.api-account']->create($nativeApp, self::$DI['user']);
$token = self::$DI['app']['manipulator.api-oauth-token']->create($account);
$this->setToken($token);
self::$DI['client']->request('GET', '/api/v1/databoxes/list/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
if (403 != $content['meta']['http_code']) {
$fail = new \Exception('Result does not match expected 403, returns ' . $content['meta']['http_code']);
}
} catch (\Exception $e) {
$fail = $e;
}
self::$DI['app']['conf']->set(['registry', 'api-clients', 'navigator-enabled'], $value);
if ($fail) {
throw $fail;
}
}
/**
* Covers mustBeAdmin route middleware
*/
public function testAdminOnlyShedulerState()
{
$this->setToken($this->userAccessToken);
self::$DI['client']->request('GET', '/api/v1/monitor/tasks/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
self::$DI['client']->request('GET', '/api/v1/monitor/scheduler/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
self::$DI['client']->request('GET', '/api/v1/monitor/task/1/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
self::$DI['client']->request('POST', '/api/v1/monitor/task/1/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
self::$DI['client']->request('POST', '/api/v1/monitor/task/1/start/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
self::$DI['client']->request('POST', '/api/v1/monitor/task/1/stop/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
self::$DI['client']->request('GET', '/api/v1/monitor/phraseanet/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(401, $content['meta']['http_code']);
}
/**
* Route GET /API/V1/monitor/task
*/
public function testGetMonitorTasks()
{
$this->setToken($this->adminAccessToken);
$route = '/api/v1/monitor/tasks/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$response = $content['response'];
$tasks = self::$DI['app']['repo.tasks']->findAll();
$this->assertEquals(count($tasks), count($response['tasks']));
foreach ($response['tasks'] as $task) {
$this->evaluateGoodTask($task);
}
}
/**
* Route GET /API/V1/monitor/scheduler
*/
public function testGetScheduler()
{
$this->setToken($this->adminAccessToken);
$route = '/api/v1/monitor/scheduler/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$response = $content['response'];
$this->assertInternalType('array', $response['scheduler']);
$this->assertArrayHasKey('state', $response['scheduler']);
$this->assertArrayHasKey('pid', $response['scheduler']);
$this->assertArrayHasKey('updated_on', $response['scheduler']);
$this->assertArrayHasKey('status', $response['scheduler']);
$this->assertArrayHasKey('configuration', $response['scheduler']);
$this->assertArrayHasKey('process-id', $response['scheduler']);
$this->assertEquals(6, count($response['scheduler']));
if (null !== $response['scheduler']['updated_on']) {
$this->assertDateAtom($response['scheduler']['updated_on']);
}
if (null !== $response['scheduler']['pid']) {
$this->assertTrue(is_int($response['scheduler']['pid']));
}
$this->assertTrue('' !== $response['scheduler']['state']);
}
protected function evaluateGoodTask($task)
{
$this->assertArrayHasKey('id', $task);
$this->assertArrayHasKey('name', $task);
$this->assertArrayHasKey('state', $task);
$this->assertArrayHasKey('status', $task);
$this->assertArrayHasKey('actual-status', $task);
$this->assertArrayHasKey('pid', $task);
$this->assertArrayHasKey('process-id', $task);
$this->assertArrayHasKey('title', $task);
$this->assertArrayHasKey('crashed', $task);
$this->assertArrayHasKey('auto_start', $task);
$this->assertArrayHasKey('last_exec_time', $task);
$this->assertArrayHasKey('last_execution', $task);
$this->assertArrayHasKey('updated', $task);
$this->assertArrayHasKey('created', $task);
$this->assertArrayHasKey('period', $task);
$this->assertArrayHasKey('jobId', $task);
$this->assertInternalType('integer', $task['id']);
if (!is_null($task['pid'])) {
$this->assertInternalType('integer', $task['pid']);
}
$av_states = [
Task::STATUS_STARTED,
Task::STATUS_STOPPED,
];
$this->assertContains($task['state'], $av_states);
$this->assertInternalType('string', $task['name']);
$this->assertInternalType('string', $task['title']);
if (!is_null($task['last_exec_time'])) {
$this->assertDateAtom($task['last_exec_time']);
}
}
public function testGetMonitorTaskById()
{
$tasks = self::$DI['app']['repo.tasks']->findAll();
if (!count($tasks)) {
$this->markTestSkipped('no tasks created for the current instance');
}
$this->setToken($this->adminAccessToken);
$idTask = $tasks[0]->getId();
$route = '/api/v1/monitor/task/' . $idTask . '/';
$this->evaluateMethodNotAllowedRoute($route, ['PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('task', $content['response']);
$this->evaluateGoodTask($content['response']['task']);
}
public function testPostMonitorTaskById()
{
$tasks = self::$DI['app']['repo.tasks']->findAll();
if (!count($tasks)) {
$this->markTestSkipped('no tasks created for the current instance');
}
$this->setToken($this->adminAccessToken);
$idTask = $tasks[0]->getId();
$route = '/api/v1/monitor/task/' . $idTask . '/';
$this->evaluateMethodNotAllowedRoute($route, ['PUT', 'DELETE']);
$title = 'newTitle' . mt_rand();
self::$DI['client']->request('POST', $route, $this->getParameters(['title' => $title]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('task', $content['response']);
$this->evaluateGoodTask($content['response']['task']);
$this->assertEquals($title, $content['response']['task']['title']);
}
public function testUnknowGetMonitorTaskById()
{
if (null === $this->adminAccessToken) {
$this->markTestSkipped('no tasks created for the current instance');
}
$this->setToken($this->adminAccessToken);
self::$DI['client']->followRedirects();
self::$DI['client']->request('GET', '/api/v1/monitor/task/0/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateMetaNotFound($content);
}
public function testPostMonitorStartTask()
{
$tasks = self::$DI['app']['repo.tasks']->findAll();
if (!count($tasks)) {
$this->markTestSkipped('no tasks created for the current instance');
}
$this->setToken($this->adminAccessToken);
$idTask = $tasks[0]->getId();
$route = '/api/v1/monitor/task/' . $idTask . '/start/';
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('task', $content['response']);
$this->evaluateGoodTask($content['response']['task']);
$task = self::$DI['app']['repo.tasks']->find($idTask);
$this->assertEquals(Task::STATUS_STARTED, $task->getStatus());
}
public function testPostMonitorStopTask()
{
$tasks = self::$DI['app']['repo.tasks']->findAll();
if (!count($tasks)) {
$this->markTestSkipped('no tasks created for the current instance');
}
$this->setToken($this->adminAccessToken);
$idTask = $tasks[0]->getId();
$route = '/api/v1/monitor/task/' . $idTask . '/stop/';
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('task', $content['response']);
$this->evaluateGoodTask($content['response']['task']);
$task = self::$DI['app']['repo.tasks']->find($idTask);
$this->assertEquals(Task::STATUS_STOPPED, $task->getStatus());
}
public function testgetMonitorPhraseanet()
{
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$this->setToken($this->adminAccessToken);
self::$DI['client']->request('GET', '/api/v1/monitor/phraseanet/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('global_values', $content['response']);
$this->assertArrayHasKey('cache', $content['response']);
$this->assertArrayHasKey('phraseanet', $content['response']);
$this->assertInternalType('array', $content['response']['global_values']);
$this->assertInternalType('array', $content['response']['cache']);
$this->assertInternalType('array', $content['response']['phraseanet']);
}
public function testRecordRoute()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateGoodRecord($content['response']['record']);
$route = '/api/v1/records/1234567890/1/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/records/kjslkz84spm/sfsd5qfsd5/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testStoryRoute()
{
$this->setToken($this->userAccessToken);
self::$DI['app']['session']->set('usr_id', self::$DI['user']->getId());
if (false === self::$DI['record_story_1']->hasChild(self::$DI['record_1'])) {
self::$DI['record_story_1']->appendChild(self::$DI['record_1']);
}
self::$DI['app']['session']->remove('usr_id');
$route = '/api/v1/stories/' . self::$DI['record_story_1']->get_sbas_id() . '/' . self::$DI['record_story_1']->get_record_id() . '/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateGoodStory($content['response']['story']);
$this->assertGreaterThan(0, $content['response']['story']['records']);
$route = '/api/v1/stories/1234567890/1/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/stories/kjslkz84spm/sfsd5qfsd5/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['record_story_1']->removeChild(self::$DI['record_1']);
}
public function testDataboxCollectionRoute()
{
$this->setToken($this->userAccessToken);
$databox_id = self::$DI['record_1']->get_sbas_id();
$route = '/api/v1/databoxes/' . $databox_id . '/collections/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('collections', $content['response']);
foreach ($content['response']['collections'] as $collection) {
$this->assertTrue(is_array($collection), 'Une collection est un objet');
$this->assertArrayHasKey('base_id', $collection);
$this->assertArrayHasKey('collection_id', $collection);
$this->assertArrayHasKey('name', $collection);
$this->assertArrayHasKey('labels', $collection);
$this->assertArrayHasKey('fr', $collection['labels']);
$this->assertArrayHasKey('en', $collection['labels']);
$this->assertArrayHasKey('de', $collection['labels']);
$this->assertArrayHasKey('nl', $collection['labels']);
$this->assertArrayHasKey('record_amount', $collection);
$this->assertTrue(is_int($collection['base_id']));
$this->assertGreaterThan(0, $collection['base_id']);
$this->assertTrue(is_int($collection['collection_id']));
$this->assertGreaterThan(0, $collection['collection_id']);
$this->assertTrue(is_string($collection['name']));
$this->assertTrue(is_int($collection['record_amount']));
break;
}
$route = '/api/v1/databoxes/24892534/collections/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/databoxes/any_bad_id/collections/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testDataboxStatusRoute()
{
$this->setToken($this->userAccessToken);
$databox_id = self::$DI['record_1']->get_sbas_id();
$databox = self::$DI['app']['phraseanet.appbox']->get_databox($databox_id);
$statusStructure = $databox->getStatusStructure();
$route = '/api/v1/databoxes/' . $databox_id . '/status/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('status', $content['response']);
foreach ($content['response']['status'] as $status) {
$this->assertTrue(is_array($status), 'Un bloc status est un objet');
$this->assertArrayHasKey('bit', $status);
$this->assertTrue(is_int($status['bit']));
$this->assertGreaterThan(3, $status['bit']);
$this->assertLessThan(65, $status['bit']);
$this->assertArrayHasKey('label_on', $status);
$this->assertArrayHasKey('label_off', $status);
$this->assertArrayHasKey('labels', $status);
$this->assertArrayHasKey('fr', $status['labels']);
$this->assertArrayHasKey('en', $status['labels']);
$this->assertArrayHasKey('de', $status['labels']);
$this->assertArrayHasKey('nl', $status['labels']);
$this->assertArrayHasKey('img_on', $status);
$this->assertArrayHasKey('img_off', $status);
$this->assertArrayHasKey('searchable', $status);
$this->assertArrayHasKey('printable', $status);
$this->assertTrue(is_bool($status['searchable']));
$this->assertTrue($status['searchable'] === (bool) $statusStructure->getStatus($status['bit'])['searchable']);
$this->assertTrue(is_bool($status['printable']));
$this->assertTrue($status['printable'] === (bool) $statusStructure->getStatus($status['bit'])['printable']);
$this->assertTrue($status['label_on'] === $statusStructure->getStatus($status['bit'])['labelon']);
$this->assertTrue($status['img_off'] === $statusStructure->getStatus($status['bit'])['img_off']);
$this->assertTrue($status['img_on'] === $statusStructure->getStatus($status['bit'])['img_on']);
break;
}
$route = '/api/v1/databoxes/24892534/status/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/databoxes/any_bad_id/status/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testDataboxMetadatasRoute()
{
$this->setToken($this->userAccessToken);
$databox_id = self::$DI['record_1']->get_sbas_id();
$databox = self::$DI['app']['phraseanet.appbox']->get_databox($databox_id);
$ref_structure = $databox->get_meta_structure();
try {
$ref_structure->get_element('idbarbouze');
$this->fail('An expected exception has not been raised.');
} catch (\Exception_Databox_FieldNotFound $e) {
}
$route = '/api/v1/databoxes/' . $databox_id . '/metadatas/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('document_metadatas', $content['response']);
foreach ($content['response']['document_metadatas'] as $metadatas) {
$this->assertTrue(is_array($metadatas), 'Un bloc metadata est un objet');
$this->assertArrayHasKey('id', $metadatas);
$this->assertArrayHasKey('namespace', $metadatas);
$this->assertArrayHasKey('source', $metadatas);
$this->assertArrayHasKey('tagname', $metadatas);
$this->assertArrayHasKey('name', $metadatas);
$this->assertArrayHasKey('separator', $metadatas);
$this->assertArrayHasKey('thesaurus_branch', $metadatas);
$this->assertArrayHasKey('type', $metadatas);
$this->assertArrayHasKey('labels', $metadatas);
$this->assertArrayHasKey('indexable', $metadatas);
$this->assertArrayHasKey('multivalue', $metadatas);
$this->assertArrayHasKey('readonly', $metadatas);
$this->assertArrayHasKey('required', $metadatas);
$this->assertTrue(is_int($metadatas['id']));
$this->assertTrue(is_string($metadatas['namespace']));
$this->assertTrue(is_string($metadatas['name']));
$this->assertTrue(is_array($metadatas['labels']));
$this->assertTrue(is_null($metadatas['source']) || is_string($metadatas['source']));
$this->assertTrue(is_string($metadatas['tagname']));
$this->assertTrue((strlen($metadatas['name']) > 0));
$this->assertTrue(is_string($metadatas['separator']));
$this->assertEquals(['fr', 'en', 'de', 'nl'], array_keys($metadatas['labels']));
if ($metadatas['multivalue']) {
$this->assertTrue((strlen($metadatas['separator']) > 0));
}
$this->assertTrue(is_string($metadatas['thesaurus_branch']));
$this->assertTrue(in_array($metadatas['type'], [\databox_field::TYPE_DATE, \databox_field::TYPE_STRING, \databox_field::TYPE_NUMBER, \databox_field::TYPE_TEXT]));
$this->assertTrue(is_bool($metadatas['indexable']));
$this->assertTrue(is_bool($metadatas['multivalue']));
$this->assertTrue(is_bool($metadatas['readonly']));
$this->assertTrue(is_bool($metadatas['required']));
$element = $ref_structure->get_element($metadatas['id']);
$this->assertTrue($element->is_indexable() === $metadatas['indexable']);
$this->assertTrue($element->is_required() === $metadatas['required']);
$this->assertTrue($element->is_readonly() === $metadatas['readonly']);
$this->assertTrue($element->is_multi() === $metadatas['multivalue']);
$this->assertTrue($element->get_type() === $metadatas['type']);
$this->assertTrue($element->get_tbranch() === $metadatas['thesaurus_branch']);
$this->assertTrue($element->get_separator() === $metadatas['separator']);
$this->assertTrue($element->get_name() === $metadatas['name']);
$this->assertTrue($element->get_tag()->getName() === $metadatas['tagname']);
$this->assertTrue($element->get_tag()->getTagname() === $metadatas['source']);
$this->assertTrue($element->get_tag()->getGroupName() === $metadatas['namespace']);
break;
}
$route = '/api/v1/databoxes/24892534/metadatas/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/databoxes/any_bad_id/metadatas/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testDataboxTermsOfUseRoute()
{
$this->setToken($this->userAccessToken);
$databox_id = self::$DI['record_1']->get_sbas_id();
$route = '/api/v1/databoxes/' . $databox_id . '/termsOfUse/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('termsOfUse', $content['response']);
foreach ($content['response']['termsOfUse'] as $terms) {
$this->assertTrue(is_array($terms), 'Une bloc cgu est un objet');
$this->assertArrayHasKey('locale', $terms);
$this->assertTrue(in_array($terms['locale'], array_keys(Application::getAvailableLanguages())));
$this->assertArrayHasKey('terms', $terms);
break;
}
$route = '/api/v1/databoxes/24892534/termsOfUse/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/databoxes/any_bad_id/termsOfUse/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testSearchRoute()
{
self::$DI['app']['manipulator.user'] = $this->getMockBuilder('Alchemy\Phrasea\Model\Manipulator\UserManipulator')
->setConstructorArgs([self::$DI['app']['model.user-manager'], self::$DI['app']['auth.password-encoder'], self::$DI['app']['geonames.connector'], self::$DI['app']['repo.users'], self::$DI['app']['random.low']])
->setMethods(['logQuery'])
->getMock();
self::$DI['app']['manipulator.user']->expects($this->once())->method('logQuery');
$this->setToken($this->userAccessToken);
self::$DI['client']->request('POST', '/api/v1/search/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$response = $content['response'];
$this->evaluateSearchResponse($response);
$this->assertArrayHasKey('stories', $response['results']);
$this->assertArrayHasKey('records', $response['results']);
$this->assertTrue(count($response['results']['records']) > 0);
}
public function testSearchRouteWithStories()
{
$this->setToken($this->userAccessToken);
self::$DI['record_story_1'];
self::$DI['client']->request('POST', '/api/v1/search/', $this->getParameters(['search_type' => SearchEngineOptions::RECORD_GROUPING]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$response = $content['response'];
$this->evaluateSearchResponse($response);
$this->assertArrayHasKey('stories', $response['results']);
$this->assertArrayHasKey('records', $response['results']);
$found = false;
foreach ($response['results']['stories'] as $story) {
$this->evaluateGoodStory($story);
$found = true;
break;
}
if (!$found) {
$this->fail('Unable to find story back');
}
}
public function testRecordsSearchRoute()
{
$this->setToken($this->userAccessToken);
self::$DI['client']->request('POST', '/api/v1/records/search/', $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$response = $content['response'];
$this->evaluateSearchResponse($response);
foreach ($response['results'] as $record) {
$this->evaluateGoodRecord($record);
break;
}
}
/**
* @dataProvider provideAvailableSearchMethods
*/
public function testRecordsSearchRouteWithQuery($method)
{
$this->setToken($this->userAccessToken);
$searchEngine = $this->getMockBuilder('Alchemy\Phrasea\SearchEngine\SearchEngineResult')
->disableOriginalConstructor()
->getMock();
$searchEngine->expects($this->any())
->method('getSuggestions')
->will($this->returnValue(new ArrayCollection()));
self::$DI['app']['phraseanet.SE'] = $this->getMock('Alchemy\Phrasea\SearchEngine\SearchEngineInterface');
self::$DI['app']['phraseanet.SE']->expects($this->once())
->method('query')
->with('koala', 0, 10)
->will($this->returnValue(
$this->getMockBuilder('Alchemy\Phrasea\SearchEngine\SearchEngineResult')
->disableOriginalConstructor()
->getMock()
));
self::$DI['client']->request($method, '/api/v1/records/search/', $this->getParameters(['query' => 'koala']), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
}
public function provideAvailableSearchMethods()
{
return [['POST'], ['GET']];
}
public function testRecordsCaptionRoute()
{
$this->setToken($this->userAccessToken);
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$this->injectMetadatas(self::$DI['record_1']);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/caption/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateRecordsCaptionResponse($content);
$route = '/api/v1/records/24892534/51654651553/caption/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/records/any_bad_id/sfsd5qfsd5/caption/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testRecordsMetadatasRoute()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/metadatas/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateRecordsMetadataResponse($content);
$route = '/api/v1/records/24892534/51654651553/metadatas/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/records/any_bad_id/sfsd5qfsd5/metadatas/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testRecordsStatusRoute()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/status/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateRecordsStatusResponse(self::$DI['record_1'], $content);
$route = '/api/v1/records/24892534/51654651553/status/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/records/any_bad_id/sfsd5qfsd5/status/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testRecordsEmbedRoute()
{
$this->setToken($this->userAccessToken);
self::$DI['app']['acl']->get(self::$DI['user_notAdmin'])->update_rights_to_base(self::$DI['collection']->get_base_id(), array(
'candwnldpreview' => 1,
'candwnldhd' => 1
));
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/embed/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('embed', $content['response']);
$embedTypes = array_flip(array_map(function($subdef) {return $subdef['name'];}, $content['response']['embed']));
//access to all subdefs
$this->assertArrayHasKey('document', $embedTypes);
$this->assertArrayHasKey('preview', $embedTypes);
$this->assertArrayHasKey('thumbnail', $embedTypes);
foreach ($content['response']['embed'] as $embed) {
$this->checkEmbed($embed, self::$DI['record_1']);
}
$route = '/api/v1/records/24892534/51654651553/embed/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/records/any_bad_id/sfsd5qfsd5/embed/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testRecordsEmbedRouteNoHdRights()
{
$this->setToken($this->userAccessToken);
self::$DI['app']['acl']->get(self::$DI['user_notAdmin'])->update_rights_to_base(self::$DI['collection']->get_base_id(), array(
'candwnldpreview' => 1,
'candwnldhd' => 0
));
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/embed/';
self::$DI['client']->request('GET', $route, $this->getParameters(), array(), array('HTTP_Accept' => $this->getAcceptMimeType()));
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('embed', $content['response']);
// no hd subdef
$embedTypes = array_flip(array_map(function($subdef) {return $subdef['name'];},$content['response']['embed']));
$this->assertArrayHasKey('preview', $embedTypes);
$this->assertArrayNotHasKey('document', $embedTypes);
}
public function testRecordsEmbedRouteNoPreviewAndHdRights()
{
$this->setToken($this->userAccessToken);
self::$DI['app']['acl']->get(self::$DI['user_notAdmin'])->update_rights_to_base(self::$DI['collection']->get_base_id(), array(
'candwnldpreview' => 0,
'candwnldhd' => 0
));
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/embed/';
self::$DI['client']->request('GET', $route, $this->getParameters(), array(), array('HTTP_Accept' => $this->getAcceptMimeType()));
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('embed', $content['response']);
// no preview
$this->assertArrayNotHasKey('document', array_flip(array_map(function($subdef) {return $subdef['name'];},$content['response']['embed'])));
$this->assertArrayNotHasKey('preview', array_flip(array_map(function($subdef) {return $subdef['name'];},$content['response']['embed'])));
}
/**
* @covers \API_V1_adapter::get_record_embed
* @covers \API_V1_adapter::list_embedable_media
* @covers \API_V1_adapter::list_permalink
*/
public function testStoriesEmbedRoute()
{
$this->setToken($this->userAccessToken);
$story = self::$DI['record_story_1'];
$route = '/api/v1/stories/' . $story->get_sbas_id() . '/' . $story->get_record_id() . '/embed/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('embed', $content['response']);
foreach ($content['response']['embed'] as $embed) {
$this->checkEmbed($embed, $story);
}
$route = '/api/v1/stories/24892534/51654651553/embed/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/stories/any_bad_id/sfsd5qfsd5/embed/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testRecordsEmbedRouteMimeType()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/embed/';
self::$DI['client']->request('GET', $route, $this->getParameters(['mimes' => ['image/png']]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertArrayHasKey('embed', $content['response']);
$this->assertEquals(0, count($content['response']['embed']));
}
public function testRecordsEmbedRouteDevices()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/embed/';
self::$DI['client']->request('GET', $route, $this->getParameters(['devices' => ['nodevice']]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertEquals(0, count($content['response']['embed']));
}
public function testRecordsRelatedRoute()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/related/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey("baskets", $content['response']);
foreach ($content['response']['baskets'] as $basket) {
$this->evaluateGoodBasket($basket, self::$DI['user_notAdmin']);
}
$route = '/api/v1/records/24892534/51654651553/related/';
$this->evaluateNotFoundRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
$route = '/api/v1/records/any_bad_id/sfsd5qfsd5/related/';
$this->evaluateBadRequestRoute($route, ['GET']);
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
}
public function testRecordsSetMetadatas()
{
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$this->setToken($this->userAccessToken);
$record = self::$DI['record_1'];
$route = '/api/v1/records/' . $record->get_sbas_id() . '/' . $record->get_record_id() . '/setmetadatas/';
$caption = $record->get_caption();
$toupdate = [];
foreach ($record->get_databox()->get_meta_structure()->get_elements() as $field) {
try {
$values = $record->get_caption()->get_field($field->get_name())->get_values();
$value = array_pop($values);
$meta_id = $value->getId();
} catch (\Exception $e) {
$meta_id = null;
}
$toupdate[$field->get_id()] = [
'meta_id' => $meta_id
, 'meta_struct_id' => $field->get_id()
, 'value' => 'podom pom pom ' . $field->get_id()
];
}
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(['metadatas' => $toupdate]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey("record_metadatas", $content['response']);
foreach ($caption->get_fields() as $field) {
foreach ($field->get_values() as $value) {
if ($field->is_readonly() === false && $field->is_multi() === false) {
$saved_value = $toupdate[$field->get_meta_struct_id()]['value'];
$this->assertEquals($value->getValue(), $saved_value);
}
}
}
$this->evaluateRecordsMetadataResponse($content);
foreach ($content['response']['record_metadatas'] as $metadata) {
if (!in_array($metadata['meta_id'], array_keys($toupdate)))
continue;
$saved_value = $toupdate[$metadata['meta_structure_id']]['value'];
$this->assertEquals($saved_value, $metadata['value']);
}
}
public function testRecordsSetStatus()
{
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . self::$DI['record_1']->get_sbas_id() . '/' . self::$DI['record_1']->get_record_id() . '/setstatus/';
$record_status = strrev(self::$DI['record_1']->get_status());
$statusStructure = self::$DI['record_1']->getStatusStructure();
$tochange = [];
foreach ($statusStructure as $n => $datas) {
$tochange[$n] = substr($record_status, ($n - 1), 1) == '0' ? '1' : '0';
}
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(['status' => $tochange]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
/**
* Get fresh record_1
*/
$testRecord = new \record_adapter(self::$DI['app'], self::$DI['record_1']->get_sbas_id(), self::$DI['record_1']->get_record_id());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateRecordsStatusResponse($testRecord, $content);
$record_status = strrev($testRecord->get_status());
foreach ($statusStructure as $n => $datas) {
$this->assertEquals(substr($record_status, ($n), 1), $tochange[$n]);
}
foreach ($tochange as $n => $value) {
$tochange[$n] = $value == '0' ? '1' : '0';
}
self::$DI['client']->request('POST', $route, $this->getParameters(['status' => $tochange]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
/**
* Get fresh record_1
*/
$testRecord = new \record_adapter(self::$DI['app'], $testRecord->get_sbas_id(), $testRecord->get_record_id());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->evaluateRecordsStatusResponse($testRecord, $content);
$record_status = strrev($testRecord->get_status());
foreach ($statusStructure as $n => $datas) {
$this->assertEquals(substr($record_status, ($n), 1), $tochange[$n]);
}
self::$DI['record_1']->set_binary_status(str_repeat('0', 32));
}
public function testMoveRecordToCollection()
{
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$file = new File(self::$DI['app'], self::$DI['app']['mediavorus']->guess(__DIR__ . '/../../../../../files/test001.jpg'), self::$DI['collection']);
$record = \record_adapter::createFromFile($file, self::$DI['app']);
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/' . $record->get_sbas_id() . '/' . $record->get_record_id() . '/setcollection/';
$base_id = false;
foreach ($record->get_databox()->get_collections() as $collection) {
if ($collection->get_base_id() != $record->get_base_id()) {
$base_id = $collection->get_base_id();
break;
}
}
if (!$base_id) {
$this->markTestSkipped('No collection');
}
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(['base_id' => $base_id]), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$record->delete();
}
public function testSearchBaskets()
{
$this->setToken($this->adminAccessToken);
$route = '/api/v1/baskets/list/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey("baskets", $content['response']);
foreach ($content['response']['baskets'] as $basket) {
$this->evaluateGoodBasket($basket, self::$DI['user']);
}
}
public function testAddBasket()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/baskets/add/';
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(['name' => 'un Joli Nom']), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertEquals(1, count($content['response']));
$this->assertArrayHasKey("basket", $content['response']);
$this->evaluateGoodBasket($content['response']['basket'], self::$DI['user_notAdmin']);
$this->assertEquals('un Joli Nom', $content['response']['basket']['name']);
}
public function testBasketContent()
{
$this->setToken($this->adminAccessToken);
$basketElement = self::$DI['app']['orm.em']->find('Phraseanet:BasketElement', 1);
$basket = $basketElement->getBasket();
$route = '/api/v1/baskets/' . $basket->getId() . '/content/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertEquals(2, count((array) $content['response']));
$this->assertArrayHasKey("basket_elements", $content['response']);
$this->assertArrayHasKey("basket", $content['response']);
$this->evaluateGoodBasket($content['response']['basket'], self::$DI['user']);
foreach ($content['response']['basket_elements'] as $basket_element) {
$this->assertArrayHasKey('basket_element_id', $basket_element);
$this->assertArrayHasKey('order', $basket_element);
$this->assertArrayHasKey('record', $basket_element);
$this->assertArrayHasKey('validation_item', $basket_element);
$this->assertTrue(is_bool($basket_element['validation_item']));
$this->assertTrue(is_int($basket_element['order']));
$this->assertTrue(is_int($basket_element['basket_element_id']));
$this->evaluateGoodRecord($basket_element['record']);
}
}
public function testSetBasketTitle()
{
$this->setToken($this->adminAccessToken);
$basket = self::$DI['app']['orm.em']->find('Phraseanet:Basket', 1);
$route = '/api/v1/baskets/' . $basket->getId() . '/setname/';
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(['name' => 'un Joli Nom']), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertEquals(1, count((array) $content['response']));
$this->assertArrayHasKey("basket", $content['response']);
$this->evaluateGoodBasket($content['response']['basket'], self::$DI['user']);
$this->assertEquals($content['response']['basket']['name'], 'un Joli Nom');
self::$DI['client']->request('POST', $route, $this->getParameters(['name' => 'un Joli Nom']), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertEquals(1, count((array) $content['response']));
$this->assertArrayHasKey("basket", $content['response']);
$this->evaluateGoodBasket($content['response']['basket'], self::$DI['user']);
$this->assertEquals($content['response']['basket']['name'], 'un Joli Nom');
self::$DI['client']->request('POST', $route, $this->getParameters(['name' => '<strong>aéaa']), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertEquals(1, count((array) $content['response']));
$this->assertArrayHasKey("basket", $content['response']);
$this->evaluateGoodBasket($content['response']['basket'], self::$DI['user']);
$this->assertEquals($content['response']['basket']['name'], '<strong>aéaa');
}
public function testSetBasketDescription()
{
$this->setToken($this->adminAccessToken);
$basket = self::$DI['app']['orm.em']->find('Phraseanet:Basket', 1);
$route = '/api/v1/baskets/' . $basket->getId() . '/setdescription/';
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(['description' => 'une belle desc']), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertEquals(1, count((array) $content['response']));
$this->assertArrayHasKey("basket", $content['response']);
$this->evaluateGoodBasket($content['response']['basket'], self::$DI['user']);
$this->assertEquals($content['response']['basket']['description'], 'une belle desc');
}
public function testDeleteBasket()
{
$this->setToken($this->adminAccessToken);
$route = '/api/v1/baskets/1/delete/';
$this->evaluateMethodNotAllowedRoute($route, ['GET', 'PUT', 'DELETE']);
self::$DI['client']->request('POST', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey("baskets", $content['response']);
$found = false;
foreach ($content['response']['baskets'] as $basket) {
$this->evaluateGoodBasket($basket, self::$DI['user']);
$found = true;
break;
}
if (!$found) {
$this->fail('There should be four baskets left');
}
}
public function testAddRecord()
{
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
$params = $this->getAddRecordParameters();
$params['status'] = '0b10000';
self::$DI['client']->request('POST', $route, $this->getParameters($params), $this->getAddRecordFile(), ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$datas = $content['response'];
$this->assertArrayHasKey('entity', $datas);
$this->assertArrayHasKey('url', $datas);
}
public function testAddRecordForceRecord()
{
self::$DI['app']['phraseanet.SE'] = $this->createSearchEngineMock();
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
$params = $this->getAddRecordParameters();
$params['forceBehavior'] = '0';
self::$DI['client']->request('POST', $route, $this->getParameters($params), $this->getAddRecordFile(), ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$datas = $content['response'];
$this->assertArrayHasKey('entity', $datas);
$this->assertArrayHasKey('url', $datas);
$this->assertRegExp('/\/records\/\d+\/\d+\//', $datas['url']);
// if forced, there is no reason
$this->assertEquals('0', $datas['entity']);
}
public function testAddRecordForceLazaret()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
$params = $this->getAddRecordParameters();
$params['forceBehavior'] = '1';
self::$DI['client']->request('POST', $route, $this->getParameters($params), $this->getAddRecordFile(), ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$datas = $content['response'];
$this->assertArrayHasKey('entity', $datas);
$this->assertArrayHasKey('url', $datas);
$this->assertRegExp('/\/quarantine\/item\/\d+\//', $datas['url']);
$this->assertEquals('1', $datas['entity']);
}
public function testAddRecordWrongBehavior()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
$params = $this->getAddRecordParameters();
$params['forceBehavior'] = '2';
self::$DI['client']->request('POST', $route, $this->getParameters($params), $this->getAddRecordFile(), ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseBadRequest(self::$DI['client']->getResponse());
$this->evaluateMetaBadRequest($content);
}
public function testAddRecordWrongBaseId()
{
$this->setToken($this->adminAccessToken);
$route = '/api/v1/records/add/';
$params = $this->getAddRecordParameters();
$params['base_id'] = self::$DI['collection_no_access']->get_base_id();
self::$DI['client']->request('POST', $route, $this->getParameters($params), $this->getAddRecordFile(), ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseForbidden(self::$DI['client']->getResponse());
$this->evaluateMetaForbidden($content);
}
public function testAddRecordNoBaseId()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
$params = $this->getAddRecordParameters();
unset($params['base_id']);
self::$DI['client']->request('POST', $route, $this->getParameters($params), $this->getAddRecordFile(), ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseBadRequest(self::$DI['client']->getResponse());
$this->evaluateMetaBadRequest($content);
}
public function testAddRecordMultipleFiles()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
$file = [
new \Symfony\Component\HttpFoundation\File\UploadedFile(self::$DI['app']['root.path'].'/tests/files/recta_logo.gif' , 'recta_logo.gif'),
new \Symfony\Component\HttpFoundation\File\UploadedFile(self::$DI['app']['root.path'].'/tests/files/rectb_logo.gif', 'rectb_logo.gif'),
];
self::$DI['client']->request('POST', $route, $this->getParameters($this->getAddRecordParameters()), ['file' => $file], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseBadRequest(self::$DI['client']->getResponse());
$this->evaluateMetaBadRequest($content);
}
public function testAddRecordNofile()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/records/add/';
self::$DI['client']->request('POST', $route, $this->getParameters($this->getAddRecordParameters()), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseBadRequest(self::$DI['client']->getResponse());
$this->evaluateMetaBadRequest($content);
}
public function testFeedList()
{
$created_feed = self::$DI['app']['orm.em']->find('Phraseanet:Feed', 1);
$this->setToken($this->userAccessToken);
$route = '/api/v1/feeds/list/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('feeds', $content['response']);
$found = false;
foreach ($content['response']['feeds'] as $feed) {
$this->evaluateGoodFeed($feed);
if ($feed['id'] == $created_feed->getId()) {
$found = true;
$this->assertEquals('Feed test, YOLO!', $feed['title']);
break;
}
}
if (!$found) {
$this->fail('feed not found !');
}
}
public function testFeedsContent()
{
self::$DI['app']['notification.deliverer'] = $this->getMockBuilder('Alchemy\Phrasea\Notification\Deliverer')
->disableOriginalConstructor()
->getMock();
$entry_title = 'Superman';
$entry_subtitle = 'Wonder Woman';
$author = "W. Shakespeare";
$author_email = "gontran.bonheur@gmail.com";
$feed = self::$DI['app']['orm.em']->find('Phraseanet:Feed', 1);
$created_entry = $feed->getEntries()->first();
$created_entry->setAuthorEmail($author_email);
$created_entry->setAuthorName($author);
$created_entry->setTitle($entry_title);
$created_entry->setSubtitle($entry_subtitle);
self::$DI['app']['orm.em']->persist($created_entry);
self::$DI['app']['orm.em']->flush();
$this->setToken($this->userAccessToken);
$route = '/api/v1/feeds/content/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('total_entries', $content['response']);
$this->assertArrayHasKey('offset_start', $content['response']);
$this->assertArrayHasKey('per_page', $content['response']);
$this->assertArrayHasKey('entries', $content['response']);
$found = false;
foreach ($content['response']['entries'] as $entry) {
$this->assertGoodEntry($entry);
if ($entry['id'] == $created_entry->getId()) {
$found = true;
$this->assertEquals($author_email, $entry['author_email']);
$this->assertEquals($author, $entry['author_name']);
$this->assertEquals($entry_title, $entry['title']);
$this->assertEquals($entry_subtitle, $entry['subtitle']);
break;
}
}
if (!$found) {
$this->fail('entry not found !');
}
}
public function testFeedEntry()
{
self::$DI['app']['notification.deliverer'] = $this->getMockBuilder('Alchemy\Phrasea\Notification\Deliverer')
->disableOriginalConstructor()
->getMock();
$feed = self::$DI['app']['orm.em']->find('Phraseanet:Feed', 1);
$created_entry = $feed->getEntries()->first();
$this->setToken($this->userAccessToken);
$route = '/api/v1/feeds/entry/' . $created_entry->getId() . '/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('entry', $content['response']);
$this->assertGoodEntry($content['response']['entry']);
$this->assertEquals($created_entry->getId(), $content['response']['entry']['id']);
}
public function testFeedEntryNoAccess()
{
self::$DI['app']['notification.deliverer'] = $this->getMockBuilder('Alchemy\Phrasea\Notification\Deliverer')
->disableOriginalConstructor()
->getMock();
$created_feed = self::$DI['app']['orm.em']->find('Phraseanet:Feed', 1);
$created_entry = $created_feed->getEntries()->first();
$created_feed->setCollection(self::$DI['collection_no_access']);
$this->setToken($this->adminAccessToken);
$route = '/api/v1/feeds/entry/' . $created_entry->getId() . '/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseForbidden(self::$DI['client']->getResponse());
$this->evaluateMetaForbidden($content);
}
public function testFeedContent()
{
self::$DI['app']['notification.deliverer'] = $this->getMockBuilder('Alchemy\Phrasea\Notification\Deliverer')
->disableOriginalConstructor()
->getMock();
$entry_title = 'Superman';
$entry_subtitle = 'Wonder Woman';
$created_feed = self::$DI['app']['orm.em']->find('Phraseanet:Feed', 1);
$created_entry = $created_feed->getEntries()->first();
$created_entry->setTitle($entry_title);
$created_entry->setSubtitle($entry_subtitle);
self::$DI['app']['orm.em']->persist($created_entry);
self::$DI['app']['orm.em']->flush();
$this->setToken($this->userAccessToken);
$route = '/api/v1/feeds/' . $created_feed->getId() . '/content/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponse200(self::$DI['client']->getResponse());
$this->evaluateMeta200($content);
$this->assertArrayHasKey('feed', $content['response']);
$this->assertArrayHasKey('entries', $content['response']);
$this->evaluateGoodFeed($content['response']['feed']);
$found = false;
foreach ($content['response']['entries'] as $entry) {
$this->assertGoodEntry($entry);
if ($entry['id'] == $created_entry->getId()) {
$this->assertEquals($entry_title, $entry['title']);
$this->assertEquals($entry_subtitle, $entry['subtitle']);
$found = true;
break;
}
}
$this->assertEquals($created_feed->getId(), $content['response']['feed']['id']);
if (!$found) {
$this->fail('Entry not found');
}
}
public function testQuarantineList()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/quarantine/list/';
$quarantineItemId = self::$DI['lazaret_1']->getId();
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertArrayHasKey('offset_start', $content['response']);
$this->assertArrayHasKey('per_page', $content['response']);
$this->assertArrayHasKey('quarantine_items', $content['response']);
$found = false;
foreach ($content['response']['quarantine_items'] as $item) {
$this->evaluateGoodQuarantineItem($item);
if ($item['id'] == $quarantineItemId) {
$found = true;
break;
}
}
if (!$found) {
$this->fail('should find the quarantine item');
}
}
public function testQuarantineContent()
{
$this->setToken($this->userAccessToken);
$quarantineItemId = self::$DI['lazaret_1']->getId();
$route = '/api/v1/quarantine/item/' . $quarantineItemId . '/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertArrayHasKey('quarantine_item', $content['response']);
$this->evaluateGoodQuarantineItem($content['response']['quarantine_item']);
$this->assertEquals($quarantineItemId, $content['response']['quarantine_item']['id']);
}
protected function getQuarantineItem()
{
$lazaretSession = new LazaretSession();
self::$DI['app']['orm.em']->persist($lazaretSession);
$quarantineItem = null;
$callback = function ($element, $visa, $code) use (&$quarantineItem) {
$quarantineItem = $element;
};
$tmpname = tempnam(sys_get_temp_dir(), 'test_quarantine');
copy(__DIR__ . '/../../../../files/iphone_pic.jpg', $tmpname);
$file = File::buildFromPathfile($tmpname, self::$DI['collection'], self::$DI['app']);
self::$DI['app']['border-manager']->process($lazaretSession, $file, $callback, Manager::FORCE_LAZARET);
return $quarantineItem;
}
protected function evaluateGoodQuarantineItem($item)
{
$this->assertArrayHasKey('id', $item);
$this->assertArrayHasKey('quarantine_session', $item);
$session = $item['quarantine_session'];
$this->assertArrayHasKey('id', $session);
$this->assertArrayHasKey('usr_id', $session);
$this->assertArrayHasKey('user', $session);
if ($session['user'] !== null) {
$this->evaluateGoodUserItem($session['user'], self::$DI['user']);
}
$this->assertArrayHasKey('base_id', $item);
$this->assertArrayHasKey('original_name', $item);
$this->assertArrayHasKey('sha256', $item);
$this->assertArrayHasKey('uuid', $item);
$this->assertArrayHasKey('forced', $item);
$this->assertArrayHasKey('checks', $item);
$this->assertArrayHasKey('created_on', $item);
$this->assertArrayHasKey('updated_on', $item);
$this->assertInternalType('boolean', $item['forced']);
$this->assertDateAtom($item['updated_on']);
$this->assertDateAtom($item['created_on']);
}
public function testRouteMe()
{
$this->setToken($this->userAccessToken);
$route = '/api/v1/me/';
$this->evaluateMethodNotAllowedRoute($route, ['POST', 'PUT', 'DELETE']);
self::$DI['client']->request('GET', $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertArrayHasKey('user', $content['response']);
$this->evaluateGoodUserItem($content['response']['user'], self::$DI['user_notAdmin']);
}
protected function evaluateGoodUserItem($data, User $user)
{
foreach ([
'@entity@' => V1Controller::OBJECT_TYPE_USER,
'id' => $user->getId(),
'email' => $user->getEmail() ?: null,
'login' => $user->getLogin() ?: null,
'first_name' => $user->getFirstName() ?: null,
'last_name' => $user->getLastName() ?: null,
'display_name' => $user->getDisplayName() ?: null,
'address' => $user->getAddress() ?: null,
'zip_code' => $user->getZipCode() ?: null,
'city' => $user->getCity() ?: null,
'country' => $user->getCountry() ?: null,
'phone' => $user->getPhone() ?: null,
'fax' => $user->getFax() ?: null,
'job' => $user->getJob() ?: null,
'position' => $user->getActivity() ?: null,
'company' => $user->getCompany() ?: null,
'geoname_id' => $user->getGeonameId() ?: null,
'last_connection' => $user->getLastConnection() ? $user->getLastConnection()->format(DATE_ATOM) : null,
'created_on' => $user->getCreated() ? $user->getCreated()->format(DATE_ATOM) : null,
'updated_on' => $user->getUpdated() ? $user->getUpdated()->format(DATE_ATOM) : null,
'locale' => $user->getLocale() ?: null,
] as $key => $value) {
$this->assertArrayHasKey($key, $data, 'Assert key is present '.$key);
if ($value) {
$this->assertEquals($value, $data[$key], 'Check key '.$key);
}
}
}
protected function evaluateGoodFeed($feed)
{
$this->assertArrayHasKey('id', $feed);
$this->assertArrayHasKey('title', $feed);
$this->assertArrayHasKey('subtitle', $feed);
$this->assertArrayHasKey('total_entries', $feed);
$this->assertArrayHasKey('icon', $feed);
$this->assertArrayHasKey('public', $feed);
$this->assertArrayHasKey('readonly', $feed);
$this->assertArrayHasKey('deletable', $feed);
$this->assertArrayHasKey('created_on', $feed);
$this->assertArrayHasKey('updated_on', $feed);
$this->assertInternalType('integer', $feed['id']);
$this->assertInternalType('string', $feed['title']);
$this->assertInternalType('string', $feed['subtitle']);
$this->assertInternalType('integer', $feed['total_entries']);
$this->assertInternalType('boolean', $feed['icon']);
$this->assertInternalType('boolean', $feed['public']);
$this->assertInternalType('boolean', $feed['readonly']);
$this->assertInternalType('boolean', $feed['deletable']);
$this->assertInternalType('string', $feed['created_on']);
$this->assertInternalType('string', $feed['updated_on']);
$this->assertDateAtom($feed['created_on']);
$this->assertDateAtom($feed['updated_on']);
}
protected function assertGoodEntry($entry)
{
$this->assertArrayHasKey('id', $entry);
$this->assertArrayHasKey('author_email', $entry);
$this->assertArrayHasKey('author_name', $entry);
$this->assertArrayHasKey('created_on', $entry);
$this->assertArrayHasKey('updated_on', $entry);
$this->assertArrayHasKey('title', $entry);
$this->assertArrayHasKey('subtitle', $entry);
$this->assertArrayHasKey('items', $entry);
$this->assertArrayHasKey('url', $entry);
$this->assertArrayHasKey('feed_url', $entry);
$this->assertInternalType('string', $entry['author_email']);
$this->assertInternalType('string', $entry['author_name']);
$this->assertDateAtom($entry['created_on']);
$this->assertDateAtom($entry['updated_on']);
$this->assertInternalType('string', $entry['title']);
$this->assertInternalType('string', $entry['subtitle']);
$this->assertInternalType('array', $entry['items']);
foreach ($entry['items'] as $item) {
$this->assertInternalType('integer', $item['item_id']);
$this->evaluateGoodRecord($item['record']);
}
$this->assertRegExp('/\/feeds\/entry\/[0-9]+\//', $entry['url']);
$this->assertRegExp('/\/feeds\/[0-9]+\/content\//', $entry['feed_url']);
}
protected function getAddRecordParameters()
{
return [
'base_id' => self::$DI['collection']->get_base_id()
];
}
protected function getAddRecordFile()
{
$file = tempnam(sys_get_temp_dir(), 'upload');
copy(__DIR__ . '/../../../../../files/iphone_pic.jpg', $file);
return [
'file' => new \Symfony\Component\HttpFoundation\File\UploadedFile($file, 'upload.jpg')
];
}
protected function checkLazaretFile($file)
{
$this->assertArrayHasKey('id', $file);
$this->assertArrayHasKey('session', $file);
$this->assertArrayHasKey('base_id', $file);
$this->assertArrayHasKey('original_name', $file);
$this->assertArrayHasKey('sha256', $file);
$this->assertArrayHasKey('uuid', $file);
$this->assertArrayHasKey('forced', $file);
$this->assertArrayHasKey('checks', $file);
$this->assertArrayHasKey('created_on', $file);
$this->assertArrayHasKey('updated_on', $file);
$this->assertInternalType('integer', $file['id']);
$this->assertInternalType('array', $file['session']);
$this->assertInternalType('integer', $file['base_id']);
$this->assertInternalType('string', $file['original_name']);
$this->assertInternalType('string', $file['sha256']);
$this->assertInternalType('string', $file['uuid']);
$this->assertInternalType('boolean', $file['forced']);
$this->assertInternalType('array', $file['checks']);
$this->assertInternalType('string', $file['updated_on']);
$this->assertInternalType('string', $file['created_on']);
$this->assertArrayHasKey('id', $file['session']);
$this->assertArrayHasKey('usr_id', $file['session']);
$this->assertRegExp('/[a-f0-9]{64}/i', $file['sha256']);
$this->assertRegExp('/[a-f0-9-]+/i', $file['uuid']);
foreach ($file['checks'] as $check) {
$this->assertInternalType('string', $check);
}
$this->assertDateAtom($file['updated_on']);
$this->assertDateAtom($file['created_on']);
}
protected function evaluateNotFoundRoute($route, $methods)
{
foreach ($methods as $method) {
self::$DI['client']->request($method, $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseNotFound(self::$DI['client']->getResponse());
$this->evaluateMetaNotFound($content);
}
}
protected function checkEmbed($embed, \record_adapter $record)
{
if ($embed['filesize'] === 0) {
var_dump($embed);
}
$subdef = $record->get_subdef($embed['name']);
$this->assertArrayHasKey("name", $embed);
$this->assertArrayHasKey("permalink", $embed);
$this->checkPermalink($embed['permalink'], $subdef);
$this->assertArrayHasKey("height", $embed);
$this->assertEquals($embed['height'], $subdef->get_height());
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $embed['height']);
$this->assertArrayHasKey("width", $embed);
$this->assertEquals($embed['width'], $subdef->get_width());
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $embed['width']);
$this->assertArrayHasKey("filesize", $embed);
$this->assertEquals($embed['filesize'], $subdef->get_size());
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $embed['filesize']);
$this->assertArrayHasKey("player_type", $embed);
$this->assertEquals($embed['player_type'], $subdef->get_type());
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $embed['player_type']);
$this->assertArrayHasKey("mime_type", $embed);
$this->assertEquals($embed['mime_type'], $subdef->get_mime());
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $embed['mime_type']);
$this->assertArrayHasKey("devices", $embed);
$this->assertEquals($embed['devices'], $subdef->getDevices());
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_ARRAY, $embed['devices']);
}
protected function checkPermalink($permalink, \media_subdef $subdef)
{
if (!$subdef->is_physically_present()) {
return;
}
$start = microtime(true);
$this->assertNotNull($subdef->get_permalink());
$this->assertInternalType('array', $permalink);
$this->assertArrayHasKey("created_on", $permalink);
$now = new \Datetime($permalink['created_on']);
$interval = $now->diff($subdef->get_permalink()->get_created_on());
$this->assertTrue(abs($interval->format('U')) < 2);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['created_on']);
$this->assertDateAtom($permalink['created_on']);
$this->assertArrayHasKey("id", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_INT, $permalink['id']);
$this->assertEquals($subdef->get_permalink()->get_id(), $permalink['id']);
$this->assertArrayHasKey("is_activated", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_BOOL, $permalink['is_activated']);
$this->assertEquals($subdef->get_permalink()->get_is_activated(), $permalink['is_activated']);
$this->assertArrayHasKey("label", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['label']);
$this->assertArrayHasKey("updated_on", $permalink);
$expected = $subdef->get_permalink()->get_last_modified();
$found = \DateTime::createFromFormat(DATE_ATOM, $permalink['updated_on']);
$this->assertLessThanOrEqual(1, $expected->diff($found)->format('U'));
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['updated_on']);
$this->assertDateAtom($permalink['updated_on']);
$this->assertArrayHasKey("page_url", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['page_url']);
$this->assertEquals($subdef->get_permalink()->get_page(), $permalink['page_url']);
$this->checkUrlCode200($permalink['page_url']);
$this->assertPermalinkHeaders($permalink['page_url'], $subdef);
$this->assertArrayHasKey("url", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['url']);
$this->assertEquals($subdef->get_permalink()->get_url(), $permalink['url']);
$this->checkUrlCode200($permalink['url']);
$this->assertPermalinkHeaders($permalink['url'], $subdef, "url");
$this->assertArrayHasKey("download_url", $permalink);
$this->assertInternalType(\PHPUnit_Framework_Constraint_IsType::TYPE_STRING, $permalink['download_url']);
$this->assertEquals($subdef->get_permalink()->get_url() . '&download=1', $permalink['download_url']);
$this->checkUrlCode200($permalink['download_url']);
$this->assertPermalinkHeaders($permalink['download_url'], $subdef, "download_url");
}
private function executeRequest($url)
{
static $request = [];
if (isset($request[$url])) {
return $request[$url];
}
static $webserver;
if (null === $webserver) {
try {
$code = self::$DI['local-guzzle']->head('/api/')->send()->getStatusCode();
} catch (GuzzleException $e) {
$code = null;
}
$webserver = ($code < 200 || $code >= 400) ? false : rtrim(self::$DI['app']['conf']->get('servername'), '/');
}
if (false === $webserver) {
$this->markTestSkipped('Install does not seem to rely on a webserver');
}
if (0 === strpos($url, $webserver)) {
$url = substr($url, strlen($webserver));
}
return $request[$url] = self::$DI['local-guzzle']->head($url)->send();
}
protected function assertPermalinkHeaders($url, \media_subdef $subdef, $type_url = "page_url")
{
$response = $this->executeRequest($url);
$this->assertEquals(200, $response->getStatusCode());
switch ($type_url) {
case "page_url" :
$this->assertTrue(strpos((string) $response->getHeader('content-type'), "text/html") === 0);
if ($response->hasHeader('content-length')) {
$this->assertNotEquals($subdef->get_size(), (string) $response->getHeader('content-length'));
}
break;
case "url" :
$this->assertTrue(strpos((string) $response->getHeader('content-type'), $subdef->get_mime()) === 0, 'Verify that header ' . (string) $response->getHeader('content-type') . ' contains subdef mime type ' . $subdef->get_mime());
if ($response->hasHeader('content-length')) {
$this->assertEquals($subdef->get_size(), (string) $response->getHeader('content-length'));
}
break;
case "download_url" :
$this->assertTrue(strpos((string) $response->getHeader('content-type'), $subdef->get_mime()) === 0, 'Verify that header ' . (string) $response->getHeader('content-type') . ' contains subdef mime type ' . $subdef->get_mime());
if ($response->hasHeader('content-length')) {
$this->assertEquals($subdef->get_size(), (string) $response->getHeader('content-length'));
}
break;
}
}
protected function checkUrlCode200($url)
{
$response = $this->executeRequest($url);
$code = $response->getStatusCode();
$this->assertEquals(200, $code, sprintf('verification de url %s', $url));
}
protected function evaluateMethodNotAllowedRoute($route, $methods)
{
foreach ($methods as $method) {
self::$DI['client']->request($method, $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->assertTrue(self::$DI['client']->getResponse()->headers->has('Allow'));
$this->evaluateResponseMethodNotAllowed(self::$DI['client']->getResponse());
$this->evaluateMetaMethodNotAllowed($content);
}
}
protected function evaluateBadRequestRoute($route, $methods)
{
foreach ($methods as $method) {
self::$DI['client']->request($method, $route, $this->getParameters(), [], ['HTTP_Accept' => $this->getAcceptMimeType()]);
$content = $this->unserialize(self::$DI['client']->getResponse()->getContent());
$this->evaluateResponseBadRequest(self::$DI['client']->getResponse());
$this->evaluateMetaBadRequest($content);
}
}
protected function evaluateMeta($content)
{
$this->assertTrue(is_array($content), 'La reponse est un objet');
$this->assertArrayHasKey('meta', $content);
$this->assertArrayHasKey('response', $content);
$this->assertTrue(is_array($content['meta']), 'Le bloc meta est un array');
$this->assertTrue(is_array($content['response']), 'Le bloc reponse est un array');
$this->assertEquals('1.4.1', $content['meta']['api_version']);
$this->assertNotNull($content['meta']['response_time']);
$this->assertEquals('UTF-8', $content['meta']['charset']);
}
protected function evaluateMeta200($content)
{
$this->evaluateMeta($content);
$this->assertEquals(200, $content['meta']['http_code']);
$this->assertNull($content['meta']['error_type']);
$this->assertNull($content['meta']['error_message']);
$this->assertNull($content['meta']['error_details']);
}
protected function evaluateMetaBadRequest($content)
{
$this->evaluateMeta($content);
$this->assertNotNull($content['meta']['error_type']);
$this->assertNotNull($content['meta']['error_message']);
$this->assertEquals(400, $content['meta']['http_code']);
}
protected function evaluateMetaForbidden($content)
{
$this->evaluateMeta($content);
$this->assertNotNull($content['meta']['error_type']);
$this->assertNotNull($content['meta']['error_message']);
$this->assertEquals(403, $content['meta']['http_code']);
}
protected function evaluateMetaNotFound($content)
{
$this->evaluateMeta($content);
$this->assertNotNull($content['meta']['error_type']);
$this->assertNotNull($content['meta']['error_message']);
$this->assertEquals(404, $content['meta']['http_code']);
}
protected function evaluateMetaMethodNotAllowed($content)
{
$this->evaluateMeta($content);
$this->assertNotNull($content['meta']['error_type']);
$this->assertNotNull($content['meta']['error_message']);
$this->assertEquals(405, $content['meta']['http_code']);
}
protected function evaluateResponse200(Response $response)
{
$this->assertEquals('UTF-8', $response->getCharset(), 'Test charset response');
$this->assertEquals(200, $response->getStatusCode(), 'Test status code 200 ' . $response->getContent());
}
protected function evaluateResponseBadRequest(Response $response)
{
$this->assertEquals('UTF-8', $response->getCharset(), 'Test charset response');
$this->assertEquals(400, $response->getStatusCode(), 'Test status code 400 ' . $response->getContent());
}
protected function evaluateResponseForbidden(Response $response)
{
$this->assertEquals('UTF-8', $response->getCharset(), 'Test charset response');
$this->assertEquals(403, $response->getStatusCode(), 'Test status code 403 ' . $response->getContent());
}
protected function evaluateResponseNotFound(Response $response)
{
$this->assertEquals('UTF-8', $response->getCharset(), 'Test charset response');
$this->assertEquals(404, $response->getStatusCode(), 'Test status code 404 ' . $response->getContent());
}
protected function evaluateResponseMethodNotAllowed(Response $response)
{
$this->assertEquals('UTF-8', $response->getCharset(), 'Test charset response');
$this->assertEquals(405, $response->getStatusCode(), 'Test status code 405 ' . $response->getContent());
}
protected function evaluateGoodBasket($basket, User $user)
{
$this->assertTrue(is_array($basket));
$this->assertArrayHasKey('basket_id', $basket);
$this->assertArrayHasKey('owner', $basket);
$this->evaluateGoodUserItem($basket['owner'], $user);
$this->assertArrayHasKey('pusher', $basket);
$this->assertArrayHasKey('created_on', $basket);
$this->assertArrayHasKey('description', $basket);
$this->assertArrayHasKey('name', $basket);
$this->assertArrayHasKey('pusher_usr_id', $basket);
$this->assertArrayHasKey('updated_on', $basket);
$this->assertArrayHasKey('unread', $basket);
if (!is_null($basket['pusher_usr_id'])) {
$this->assertTrue(is_int($basket['pusher_usr_id']));
$this->evaluateGoodUserItem($basket['pusher'], self::$DI['user_notAdmin']);
}
$this->assertTrue(is_string($basket['name']));
$this->assertTrue(is_string($basket['description']));
$this->assertTrue(is_bool($basket['unread']));
$this->assertDateAtom($basket['created_on']);
$this->assertDateAtom($basket['updated_on']);
}
protected function evaluateGoodRecord($record)
{
$this->assertArrayHasKey('databox_id', $record);
$this->assertTrue(is_int($record['databox_id']));
$this->assertArrayHasKey('record_id', $record);
$this->assertTrue(is_int($record['record_id']));
$this->assertArrayHasKey('mime_type', $record);
$this->assertTrue(is_string($record['mime_type']));
$this->assertArrayHasKey('title', $record);
$this->assertTrue(is_string($record['title']));
$this->assertArrayHasKey('original_name', $record);
$this->assertTrue(is_string($record['original_name']));
$this->assertArrayHasKey('updated_on', $record);
$this->assertDateAtom($record['updated_on']);
$this->assertArrayHasKey('created_on', $record);
$this->assertDateAtom($record['created_on']);
$this->assertArrayHasKey('collection_id', $record);
$this->assertTrue(is_int($record['collection_id']));
$this->assertArrayHasKey('thumbnail', $record);
$this->assertArrayHasKey('sha256', $record);
$this->assertTrue(is_string($record['sha256']));
$this->assertArrayHasKey('technical_informations', $record);
$this->assertArrayHasKey('phrasea_type', $record);
$this->assertTrue(is_string($record['phrasea_type']));
$this->assertTrue(in_array($record['phrasea_type'], ['audio', 'document', 'image', 'video', 'flash', 'unknown']));
$this->assertArrayHasKey('uuid', $record);
$this->assertTrue(Uuid::isValid($record['uuid']));
if (!is_null($record['thumbnail'])) {
$this->assertTrue(is_array($record['thumbnail']));
$this->assertArrayHasKey('player_type', $record['thumbnail']);
$this->assertTrue(is_string($record['thumbnail']['player_type']));
$this->assertArrayHasKey('permalink', $record['thumbnail']);
$this->assertArrayHasKey('mime_type', $record['thumbnail']);
$this->assertTrue(is_string($record['thumbnail']['mime_type']));
$this->assertArrayHasKey('height', $record['thumbnail']);
$this->assertTrue(is_int($record['thumbnail']['height']));
$this->assertArrayHasKey('width', $record['thumbnail']);
$this->assertTrue(is_int($record['thumbnail']['width']));
$this->assertArrayHasKey('filesize', $record['thumbnail']);
$this->assertTrue(is_int($record['thumbnail']['filesize']));
}
$this->assertTrue(is_array($record['technical_informations']));
foreach ($record['technical_informations'] as $technical) {
$this->assertArrayHasKey('value', $technical);
$this->assertArrayHasKey('name', $technical);
$value = $technical['value'];
if (is_string($value)) {
$this->assertFalse(ctype_digit($value));
$this->assertEquals(0, preg_match('/[0-9]?\.[0-9]+/', $value));
} elseif (is_float($value)) {
$this->assertTrue(is_float($value));
} elseif (is_int($value)) {
$this->assertTrue(is_int($value));
} else {
$this->fail('unrecognized technical information');
}
}
}
protected function evaluateGoodStory($story)
{
$this->assertArrayHasKey('databox_id', $story);
$this->assertTrue(is_int($story['databox_id']));
$this->assertArrayHasKey('story_id', $story);
$this->assertTrue(is_int($story['story_id']));
$this->assertArrayHasKey('updated_on', $story);
$this->assertDateAtom($story['updated_on']);
$this->assertArrayHasKey('created_on', $story);
$this->assertDateAtom($story['created_on']);
$this->assertArrayHasKey('collection_id', $story);
$this->assertTrue(is_int($story['collection_id']));
$this->assertArrayHasKey('thumbnail', $story);
$this->assertArrayHasKey('uuid', $story);
$this->assertArrayHasKey('@entity@', $story);
$this->assertEquals(V1Controller::OBJECT_TYPE_STORY, $story['@entity@']);
$this->assertTrue(Uuid::isValid($story['uuid']));
if ( ! is_null($story['thumbnail'])) {
$this->assertTrue(is_array($story['thumbnail']));
$this->assertArrayHasKey('player_type', $story['thumbnail']);
$this->assertTrue(is_string($story['thumbnail']['player_type']));
$this->assertArrayHasKey('permalink', $story['thumbnail']);
$this->assertArrayHasKey('mime_type', $story['thumbnail']);
$this->assertTrue(is_string($story['thumbnail']['mime_type']));
$this->assertArrayHasKey('height', $story['thumbnail']);
$this->assertTrue(is_int($story['thumbnail']['height']));
$this->assertArrayHasKey('width', $story['thumbnail']);
$this->assertTrue(is_int($story['thumbnail']['width']));
$this->assertArrayHasKey('filesize', $story['thumbnail']);
$this->assertTrue(is_int($story['thumbnail']['filesize']));
}
$this->assertArrayHasKey('records', $story);
$this->assertInternalType('array', $story['records']);
foreach ($story['metadatas'] as $key => $metadata) {
if (null !== $metadata) {
$this->assertInternalType('string', $metadata);
}
if ($key === '@entity@') {
continue;
}
$this->assertEquals(0, strpos($key, 'dc:'));
}
$this->assertArrayHasKey('@entity@', $story['metadatas']);
$this->assertEquals(V1Controller::OBJECT_TYPE_STORY_METADATA_BAG, $story['metadatas']['@entity@']);
foreach ($story['records'] as $record) {
$this->evaluateGoodRecord($record);
}
}
protected function evaluateRecordsCaptionResponse($content)
{
$this->assertArrayHasKey('caption_metadatas', $content['response']);
$this->assertGreaterThan(0, count($content['response']['caption_metadatas']));
foreach ($content['response']['caption_metadatas'] as $field) {
$this->assertTrue(is_array($field), 'Un bloc field est un objet');
$this->assertArrayHasKey('meta_structure_id', $field);
$this->assertTrue(is_int($field['meta_structure_id']));
$this->assertArrayHasKey('name', $field);
$this->assertTrue(is_string($field['name']));
$this->assertArrayHasKey('value', $field);
$this->assertTrue(is_string($field['value']));
}
}
protected function evaluateRecordsMetadataResponse($content)
{
if (!array_key_exists("record_metadatas", $content['response'])) {
var_dump($content['response']);
}
$this->assertArrayHasKey("record_metadatas", $content['response']);
foreach ($content['response']['record_metadatas'] as $meta) {
$this->assertTrue(is_array($meta), 'Un bloc meta est un objet');
$this->assertArrayHasKey('meta_id', $meta);
$this->assertTrue(is_int($meta['meta_id']));
$this->assertArrayHasKey('meta_structure_id', $meta);
$this->assertTrue(is_int($meta['meta_structure_id']));
$this->assertArrayHasKey('name', $meta);
$this->assertTrue(is_string($meta['name']));
$this->assertArrayHasKey('value', $meta);
$this->assertArrayHasKey('labels', $meta);
$this->assertTrue(is_array($meta['labels']));
$this->assertEquals(['fr', 'en', 'de', 'nl'], array_keys($meta['labels']));
if (is_array($meta['value'])) {
foreach ($meta['value'] as $val) {
$this->assertTrue(is_string($val));
}
} else {
$this->assertTrue(is_string($meta['value']));
}
}
}
protected function evaluateRecordsStatusResponse(\record_adapter $record, $content)
{
$statusStructure = $record->get_databox()->getStatusStructure();
$r_status = strrev($record->get_status());
$this->assertArrayHasKey('status', $content['response']);
$this->assertEquals(count((array) $content['response']['status']), count($statusStructure->toArray()));
foreach ($content['response']['status'] as $status) {
$this->assertTrue(is_array($status));
$this->assertArrayHasKey('bit', $status);
$this->assertArrayHasKey('state', $status);
$this->assertTrue(is_int($status['bit']));
$this->assertTrue(is_bool($status['state']));
$retrieved = !!substr($r_status, ($status['bit']), 1);
$this->assertEquals($retrieved, $status['state']);
}
}
protected function injectMetadatas(\record_adapter $record)
{
foreach ($record->get_databox()->get_meta_structure()->get_elements() as $field) {
try {
$values = $record->get_caption()->get_field($field->get_name())->get_values();
$value = array_pop($values);
$meta_id = $value->getId();
} catch (\Exception $e) {
$meta_id = null;
}
$toupdate[$field->get_id()] = [
'meta_id' => $meta_id
, 'meta_struct_id' => $field->get_id()
, 'value' => 'podom pom pom ' . $field->get_id()
];
}
$record->set_metadatas($toupdate);
}
protected function setToken(ApiOauthToken $token)
{
self::resetUsersRights(self::$DI['app'], $token->getAccount()->getUser());
$_GET['oauth_token'] = $token->getOauthToken();
}
protected function unsetToken()
{
unset($_GET['oauth_token']);
}
private function evaluateSearchResponse($response)
{
$this->assertArrayHasKey('available_results', $response);
$this->assertArrayHasKey('total_results', $response);
$this->assertArrayHasKey('error', $response);
$this->assertArrayHasKey('warning', $response);
$this->assertArrayHasKey('query_time', $response);
$this->assertArrayHasKey('search_indexes', $response);
$this->assertArrayHasKey('suggestions', $response);
$this->assertArrayHasKey('results', $response);
$this->assertArrayHasKey('query', $response);
$this->assertTrue(is_int($response['available_results']), 'Le nombre de results dispo est un int');
$this->assertTrue(is_int($response['total_results']), 'Le nombre de results est un int');
$this->assertTrue(is_string($response['error']), 'Error est une string');
$this->assertTrue(is_string($response['warning']), 'Warning est une string');
$this->assertTrue(is_string($response['search_indexes']));
$this->assertTrue(is_array($response['suggestions']));
$this->assertTrue(is_array($response['results']));
$this->assertTrue(is_string($response['query']));
}
}
| kwemi/Phraseanet | tests/Alchemy/Tests/Phrasea/Controller/Api/ApiTestCase.php | PHP | gpl-3.0 | 116,146 |
/*
* Copyright 2012 Aarhus University
*
* Licensed under the GNU General Public License, Version 3 (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.gnu.org/licenses/gpl-3.0.html
*
* 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.
*/
// AUTO GENERATED - DO NOT MODIFY
#ifdef ARTEMIS
#include "constantinteger.h"
namespace Symbolic
{
ConstantInteger::ConstantInteger(double value) :
IntegerExpression(),
m_value(value)
{
}
void ConstantInteger::accept(Visitor* visitor)
{
visitor->visit(this, NULL);
}
void ConstantInteger::accept(Visitor* visitor, void* arg)
{
visitor->visit(this, arg);
}
}
#endif
| cs-au-dk/Artemis | WebKit/Source/JavaScriptCore/symbolic/expression/constantinteger.cpp | C++ | gpl-3.0 | 1,005 |
package vd.server.network;
import vd.core.log.Logger;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NetworkEngine
{
private ServerSocket server;
private Logger logger;
private Thread thread;
private boolean running;
private int port;
private List<ClientInstance> clients = new ArrayList<>();
public NetworkEngine(Logger l)
{
logger = l;
}
public void init(int p)
{
port = p;
}
public void start()
{
thread = new Thread(() -> {
try
{
server = new ServerSocket(port);
Socket ns;
while(running)
{
ns = server.accept();
}
}
catch (Exception e)
{
}
});
thread.start();
}
public void stop()
{
running = false;
}
}
| JimiVacarians/void | server/src/vd/server/network/NetworkEngine.java | Java | gpl-3.0 | 1,035 |
# This file is part of DevParrot.
#
# Author: Matthieu Gautier <matthieu.gautier@devparrot.org>
#
# DevParrot 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.
#
# DevParrot 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 DevParrot. If not, see <http://www.gnu.org/licenses/>.
#
#
# Copyright 2011-2013 Matthieu Gautier
import tkinter, tkinter.ttk
import logging
from devparrot.core import session, userLogging
class StatusBar(tkinter.Frame, logging.Handler):
def __init__(self, parent):
tkinter.Frame.__init__(self, parent)
logging.Handler.__init__(self)
self.pack(side=tkinter.BOTTOM, fill=tkinter.X)
self['relief'] = 'sunken'
session.userLogger.addHandler(self)
self.label = tkinter.Label(self)
self.label.pack(side='left', fill=tkinter.BOTH, expand=True)
self.defaultColor = self['background']
self.label['anchor'] = 'nw'
separator = tkinter.ttk.Separator(self, orient="vertical")
separator.pack(side='left', fill='y')
self.insertLabel = tkinter.ttk.Label(self)
self.insertLabel.pack(side='right', expand=False, fill="none")
session.eventSystem.connect('mark_set', self.on_mark_set)
self.currentLevel = 0
self.callbackId = 0
def flush(self):
"""overide logging.Handler.flush"""
pass
def clear(self):
self.currentLevel = 0
self.label['text'] = ""
self.label['background'] = self.defaultColor
self.callbackId = 0
def emit(self,record):
"""overide logging.Handler.emit"""
if record.levelno >= self.currentLevel:
self.currentLevel = record.levelno
self.label['text'] = record.getMessage()
if self.currentLevel == userLogging.INFO:
self.label['background'] = session.config.get('ok_color')
if self.currentLevel == userLogging.ERROR:
self.label['background'] = session.config.get('error_color')
if self.currentLevel == userLogging.INVALID:
self.label['background'] = session.config.get('invalid_color')
if self.callbackId:
self.after_cancel(self.callbackId)
self.callbackId = self.after(5000, self.clear)
def on_mark_set(self, model, name, index):
if name == "insert":
if model.sel_isSelection():
self.insertLabel['text'] = "[%s:%s]"%(model.index("sel.first"), model.index("sel.last"))
else:
self.insertLabel['text'] = str(model.index("insert"))
| mgautierfr/devparrot | devparrot/core/ui/statusBar.py | Python | gpl-3.0 | 3,065 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="fr">
<head>
<!-- Generated by javadoc (1.8.0_40) on Sun Mar 29 23:47:23 CEST 2015 -->
<title>All Classes</title>
<meta name="date" content="2015-03-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="com/novar/ui/AccDetailsPanel.html" title="class in com.novar.ui">AccDetailsPanel</a></li>
<li><a href="com/novar/ui/AccessoriesPanel.html" title="class in com.novar.ui">AccessoriesPanel</a></li>
<li><a href="com/novar/business/Accessory.html" title="class in com.novar.business">Accessory</a></li>
<li><a href="com/novar/persist/AccessoryJdbc.html" title="class in com.novar.persist">AccessoryJdbc</a></li>
<li><a href="com/novar/business/AccessoryManager.html" title="class in com.novar.business">AccessoryManager</a></li>
<li><a href="com/novar/persist/AccessoryManagerJdbc.html" title="class in com.novar.persist">AccessoryManagerJdbc</a></li>
<li><a href="com/novar/ui/ActDetailsPanel.html" title="class in com.novar.ui">ActDetailsPanel</a></li>
<li><a href="com/novar/ui/ActivitiesPanel.html" title="class in com.novar.ui">ActivitiesPanel</a></li>
<li><a href="com/novar/business/Activity.html" title="class in com.novar.business">Activity</a></li>
<li><a href="com/novar/business/ActivityEventFacade.html" title="class in com.novar.business">ActivityEventFacade</a></li>
<li><a href="com/novar/persist/ActivityJdbc.html" title="class in com.novar.persist">ActivityJdbc</a></li>
<li><a href="com/novar/exception/ActivityLoadException.html" title="class in com.novar.exception">ActivityLoadException</a></li>
<li><a href="com/novar/business/ActivityManager.html" title="class in com.novar.business">ActivityManager</a></li>
<li><a href="com/novar/persist/ActivityManagerJDBC.html" title="class in com.novar.persist">ActivityManagerJDBC</a></li>
<li><a href="com/novar/ui/AddAccDialog.html" title="class in com.novar.ui">AddAccDialog</a></li>
<li><a href="com/novar/ui/AddRegPanel.html" title="class in com.novar.ui">AddRegPanel</a></li>
<li><a href="com/novar/ui/AddUserPanel.html" title="class in com.novar.ui">AddUserPanel</a></li>
<li><a href="com/novar/business/AdminFacade.html" title="class in com.novar.business">AdminFacade</a></li>
<li><a href="com/novar/business/Administrator.html" title="class in com.novar.business">Administrator</a></li>
<li><a href="com/novar/business/Basket.html" title="class in com.novar.business">Basket</a></li>
<li><a href="com/novar/business/BasketFacade.html" title="class in com.novar.business">BasketFacade</a></li>
<li><a href="com/novar/persist/BasketJdbc.html" title="class in com.novar.persist">BasketJdbc</a></li>
<li><a href="com/novar/business/BasketLine.html" title="class in com.novar.business">BasketLine</a></li>
<li><a href="com/novar/persist/BasketLineJdbc.html" title="class in com.novar.persist">BasketLineJdbc</a></li>
<li><a href="com/novar/ui/BasketPanel.html" title="class in com.novar.ui">BasketPanel</a></li>
<li><a href="com/novar/ui/CategoriesPanel.html" title="class in com.novar.ui">CategoriesPanel</a></li>
<li><a href="com/novar/business/Category.html" title="class in com.novar.business">Category</a></li>
<li><a href="com/novar/ui/CategoryDetailsPanel.html" title="class in com.novar.ui">CategoryDetailsPanel</a></li>
<li><a href="com/novar/business/CategoryFacade.html" title="class in com.novar.business">CategoryFacade</a></li>
<li><a href="com/novar/business/CategoryManager.html" title="class in com.novar.business">CategoryManager</a></li>
<li><a href="com/novar/persist/CategoryManagerJdbc.html" title="class in com.novar.persist">CategoryManagerJdbc</a></li>
<li><a href="com/novar/ui/CategoryPanel.html" title="class in com.novar.ui">CategoryPanel</a></li>
<li><a href="com/novar/business/ClassRoom.html" title="class in com.novar.business">ClassRoom</a></li>
<li><a href="com/novar/ui/ConnectedWindow.html" title="class in com.novar.ui">ConnectedWindow</a></li>
<li><a href="com/novar/util/ConnectionUtil.html" title="class in com.novar.util">ConnectionUtil</a></li>
<li><a href="com/novar/ui/DeleteAccDialog.html" title="class in com.novar.ui">DeleteAccDialog</a></li>
<li><a href="com/novar/ui/DeleteActDialog.html" title="class in com.novar.ui">DeleteActDialog</a></li>
<li><a href="com/novar/ui/DeleteCategoryDialog.html" title="class in com.novar.ui">DeleteCategoryDialog</a></li>
<li><a href="com/novar/ui/DeleteEvDialog.html" title="class in com.novar.ui">DeleteEvDialog</a></li>
<li><a href="com/novar/ui/DeleteManagerDialog.html" title="class in com.novar.ui">DeleteManagerDialog</a></li>
<li><a href="com/novar/ui/DeleteMemberDialog.html" title="class in com.novar.ui">DeleteMemberDialog</a></li>
<li><a href="com/novar/ui/DeleteProductDialog.html" title="class in com.novar.ui">DeleteProductDialog</a></li>
<li><a href="com/novar/ui/DeleteRegDialog.html" title="class in com.novar.ui">DeleteRegDialog</a></li>
<li><a href="com/novar/ui/DeleteRoomDialog.html" title="class in com.novar.ui">DeleteRoomDialog</a></li>
<li><a href="com/novar/ui/DeleteSpeakerDialog.html" title="class in com.novar.ui">DeleteSpeakerDialog</a></li>
<li><a href="com/novar/ui/DescribeActivityPanel.html" title="class in com.novar.ui">DescribeActivityPanel</a></li>
<li><a href="com/novar/ui/EvDetailsPanel.html" title="class in com.novar.ui">EvDetailsPanel</a></li>
<li><a href="com/novar/business/Event.html" title="class in com.novar.business">Event</a></li>
<li><a href="com/novar/persist/EventJdbc.html" title="class in com.novar.persist">EventJdbc</a></li>
<li><a href="com/novar/business/EventManager.html" title="class in com.novar.business">EventManager</a></li>
<li><a href="com/novar/persist/EventManagerJdbc.html" title="class in com.novar.persist">EventManagerJdbc</a></li>
<li><a href="com/novar/ui/EventsPanel.html" title="class in com.novar.ui">EventsPanel</a></li>
<li><a href="com/novar/exception/FalseFieldsException.html" title="class in com.novar.exception">FalseFieldsException</a></li>
<li><a href="com/novar/ui/ForgottenPasswordDialog.html" title="class in com.novar.ui">ForgottenPasswordDialog</a></li>
<li><a href="com/novar/business/Have.html" title="class in com.novar.business">Have</a></li>
<li><a href="com/novar/persist/HaveJdbc.html" title="class in com.novar.persist">HaveJdbc</a></li>
<li><a href="com/novar/exception/InvalidEmailException.html" title="class in com.novar.exception">InvalidEmailException</a></li>
<li><a href="com/novar/persist/JdbcKit.html" title="class in com.novar.persist">JdbcKit</a></li>
<li><a href="com/novar/ui/ListOfEventsPanel.html" title="class in com.novar.ui">ListOfEventsPanel</a></li>
<li><a href="com/novar/exception/LoginFailedException.html" title="class in com.novar.exception">LoginFailedException</a></li>
<li><a href="com/novar/ui/LoginWindow.html" title="class in com.novar.ui">LoginWindow</a></li>
<li><a href="com/novar/business/MainCategory.html" title="class in com.novar.business">MainCategory</a></li>
<li><a href="com/novar/persist/MainCategoryJdbc.html" title="class in com.novar.persist">MainCategoryJdbc</a></li>
<li><a href="com/novar/business/MainFacade.html" title="class in com.novar.business">MainFacade</a></li>
<li><a href="com/novar/business/Manager.html" title="class in com.novar.business">Manager</a></li>
<li><a href="com/novar/ui/ManagerDetailsPanel.html" title="class in com.novar.ui">ManagerDetailsPanel</a></li>
<li><a href="com/novar/business/ManagerFacade.html" title="class in com.novar.business">ManagerFacade</a></li>
<li><a href="com/novar/business/ManagerManager.html" title="class in com.novar.business">ManagerManager</a></li>
<li><a href="com/novar/persist/ManagerManagerJdbc.html" title="class in com.novar.persist">ManagerManagerJdbc</a></li>
<li><a href="com/novar/ui/ManagerPanel.html" title="class in com.novar.ui">ManagerPanel</a></li>
<li><a href="com/novar/business/Member.html" title="class in com.novar.business">Member</a></li>
<li><a href="com/novar/ui/MemberDetailsPanel.html" title="class in com.novar.ui">MemberDetailsPanel</a></li>
<li><a href="com/novar/ui/MemberPanel.html" title="class in com.novar.ui">MemberPanel</a></li>
<li><a href="com/novar/ui/MyActivitiesPanel.html" title="class in com.novar.ui">MyActivitiesPanel</a></li>
<li><a href="com/novar/ui/NewCategoryDialog.html" title="class in com.novar.ui">NewCategoryDialog</a></li>
<li><a href="com/novar/business/Notification.html" title="class in com.novar.business">Notification</a></li>
<li><a href="com/novar/business/NotificationFacade.html" title="class in com.novar.business">NotificationFacade</a></li>
<li><a href="com/novar/persist/NotificationJdbc.html" title="class in com.novar.persist">NotificationJdbc</a></li>
<li><a href="com/novar/business/NotificationManager.html" title="class in com.novar.business">NotificationManager</a></li>
<li><a href="com/novar/persist/NotificationManagerJdbc.html" title="class in com.novar.persist">NotificationManagerJdbc</a></li>
<li><a href="com/novar/ui/NotificationsPanel.html" title="class in com.novar.ui">NotificationsPanel</a></li>
<li><a href="com/novar/business/NotifyTo.html" title="class in com.novar.business">NotifyTo</a></li>
<li><a href="com/novar/persist/NotifyToJdbc.html" title="class in com.novar.persist">NotifyToJdbc</a></li>
<li><a href="com/novar/business/Office.html" title="class in com.novar.business">Office</a></li>
<li><a href="com/novar/persist/PersistKit.html" title="interface in com.novar.persist"><span class="interfaceName">PersistKit</span></a></li>
<li><a href="com/novar/business/Planning.html" title="class in com.novar.business">Planning</a></li>
<li><a href="com/novar/business/PlanningFacade.html" title="class in com.novar.business">PlanningFacade</a></li>
<li><a href="com/novar/business/PlanningManager.html" title="class in com.novar.business">PlanningManager</a></li>
<li><a href="com/novar/persist/PlanningManagerJdbc.html" title="class in com.novar.persist">PlanningManagerJdbc</a></li>
<li><a href="com/novar/ui/PlanningPanel.html" title="class in com.novar.ui">PlanningPanel</a></li>
<li><a href="com/novar/business/Product.html" title="class in com.novar.business">Product</a></li>
<li><a href="com/novar/ui/ProductDetailsPanel.html" title="class in com.novar.ui">ProductDetailsPanel</a></li>
<li><a href="com/novar/business/ProductFacade.html" title="class in com.novar.business">ProductFacade</a></li>
<li><a href="com/novar/persist/ProductJdbc.html" title="class in com.novar.persist">ProductJdbc</a></li>
<li><a href="com/novar/business/ProductManager.html" title="class in com.novar.business">ProductManager</a></li>
<li><a href="com/novar/persist/ProductManagerJdbc.html" title="class in com.novar.persist">ProductManagerJdbc</a></li>
<li><a href="com/novar/ui/ProductsPanel.html" title="class in com.novar.ui">ProductsPanel</a></li>
<li><a href="com/novar/ui/ProfilePanel.html" title="class in com.novar.ui">ProfilePanel</a></li>
<li><a href="com/novar/ui/RegDetailsPanel.html" title="class in com.novar.ui">RegDetailsPanel</a></li>
<li><a href="com/novar/exception/RegisterFailedException.html" title="class in com.novar.exception">RegisterFailedException</a></li>
<li><a href="com/novar/ui/RegisterWindow.html" title="class in com.novar.ui">RegisterWindow</a></li>
<li><a href="com/novar/business/Registration.html" title="class in com.novar.business">Registration</a></li>
<li><a href="com/novar/persist/RegistrationJdbc.html" title="class in com.novar.persist">RegistrationJdbc</a></li>
<li><a href="com/novar/business/RegistrationManager.html" title="class in com.novar.business">RegistrationManager</a></li>
<li><a href="com/novar/persist/RegistrationManagerJdbc.html" title="class in com.novar.persist">RegistrationManagerJdbc</a></li>
<li><a href="com/novar/ui/RegistrationsMemberPanel.html" title="class in com.novar.ui">RegistrationsMemberPanel</a></li>
<li><a href="com/novar/ui/RegistrationsPanel.html" title="class in com.novar.ui">RegistrationsPanel</a></li>
<li><a href="com/novar/business/Role.html" title="interface in com.novar.business"><span class="interfaceName">Role</span></a></li>
<li><a href="com/novar/business/Room.html" title="class in com.novar.business">Room</a></li>
<li><a href="com/novar/business/RoomAccessoryFacade.html" title="class in com.novar.business">RoomAccessoryFacade</a></li>
<li><a href="com/novar/ui/RoomDetailsPanel.html" title="class in com.novar.ui">RoomDetailsPanel</a></li>
<li><a href="com/novar/persist/RoomJdbc.html" title="class in com.novar.persist">RoomJdbc</a></li>
<li><a href="com/novar/business/RoomManager.html" title="class in com.novar.business">RoomManager</a></li>
<li><a href="com/novar/persist/RoomManagerJdbc.html" title="class in com.novar.persist">RoomManagerJdbc</a></li>
<li><a href="com/novar/ui/RoomsPanel.html" title="class in com.novar.ui">RoomsPanel</a></li>
<li><a href="com/novar/ui/SeeMoreUserPanel.html" title="class in com.novar.ui">SeeMoreUserPanel</a></li>
<li><a href="com/novar/util/SendMail.html" title="class in com.novar.util">SendMail</a></li>
<li><a href="com/novar/ui/ShopPanel.html" title="class in com.novar.ui">ShopPanel</a></li>
<li><a href="com/novar/business/Speaker.html" title="class in com.novar.business">Speaker</a></li>
<li><a href="com/novar/ui/SpeakerDetailsPanel.html" title="class in com.novar.ui">SpeakerDetailsPanel</a></li>
<li><a href="com/novar/ui/SpeakerPanel.html" title="class in com.novar.ui">SpeakerPanel</a></li>
<li><a href="com/novar/ui/Splash.html" title="class in com.novar.ui">Splash</a></li>
<li><a href="com/novar/util/StringUtil.html" title="class in com.novar.util">StringUtil</a></li>
<li><a href="com/novar/business/SubCategory.html" title="class in com.novar.business">SubCategory</a></li>
<li><a href="com/novar/persist/SubCategoryJdbc.html" title="class in com.novar.persist">SubCategoryJdbc</a></li>
<li><a href="com/novar/exception/SyntaxException.html" title="class in com.novar.exception">SyntaxException</a></li>
<li><a href="com/novar/business/TypeRoom.html" title="class in com.novar.business">TypeRoom</a></li>
<li><a href="com/novar/ui/UpdatePasswordPanel.html" title="class in com.novar.ui">UpdatePasswordPanel</a></li>
<li><a href="com/novar/ui/UpdateProfilePanel.html" title="class in com.novar.ui">UpdateProfilePanel</a></li>
<li><a href="com/novar/ui/UpdateUserPanel.html" title="class in com.novar.ui">UpdateUserPanel</a></li>
<li><a href="com/novar/business/User.html" title="class in com.novar.business">User</a></li>
<li><a href="com/novar/persist/UserJdbc.html" title="class in com.novar.persist">UserJdbc</a></li>
<li><a href="com/novar/business/UserManager.html" title="class in com.novar.business">UserManager</a></li>
<li><a href="com/novar/persist/UserManagerJdbc.html" title="class in com.novar.persist">UserManagerJdbc</a></li>
<li><a href="com/novar/business/UsersFacade.html" title="class in com.novar.business">UsersFacade</a></li>
<li><a href="com/novar/business/UsersManager.html" title="class in com.novar.business">UsersManager</a></li>
<li><a href="com/novar/persist/UsersManagerJdbc.html" title="class in com.novar.persist">UsersManagerJdbc</a></li>
<li><a href="com/novar/ui/UsersPanel.html" title="class in com.novar.ui">UsersPanel</a></li>
</ul>
</div>
</body>
</html>
| Polytech-NOVAR/GoFit | doc/allclasses-noframe.html | HTML | gpl-3.0 | 15,426 |
<!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_20) on Fri Sep 10 14:26:19 CEST 2010 -->
<TITLE>
X-Index
</TITLE>
<META NAME="date" CONTENT="2010-09-10">
<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="X-Index";
}
}
</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"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </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="index-19.html"><B>PREV LETTER</B></A>
<A HREF="index-21.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-20.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-20.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 ========= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">F</A> <A HREF="index-6.html">G</A> <A HREF="index-7.html">H</A> <A HREF="index-8.html">I</A> <A HREF="index-9.html">L</A> <A HREF="index-10.html">M</A> <A HREF="index-11.html">N</A> <A HREF="index-12.html">O</A> <A HREF="index-13.html">P</A> <A HREF="index-14.html">R</A> <A HREF="index-15.html">S</A> <A HREF="index-16.html">T</A> <A HREF="index-17.html">U</A> <A HREF="index-18.html">V</A> <A HREF="index-19.html">W</A> <A HREF="index-20.html">X</A> <A HREF="index-21.html">Y</A> <HR>
<A NAME="_X_"><!-- --></A><H2>
<B>X</B></H2>
<DL>
<DT><A HREF="../psd/layer/PsdLayerFrameInfo.html#xOffset"><B>xOffset</B></A> -
Variable in class psd.layer.<A HREF="../psd/layer/PsdLayerFrameInfo.html" title="class in psd.layer">PsdLayerFrameInfo</A>
<DD>The x offset.
</DL>
<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"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </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="index-19.html"><B>PREV LETTER</B></A>
<A HREF="index-21.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-20.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-20.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 ======= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">F</A> <A HREF="index-6.html">G</A> <A HREF="index-7.html">H</A> <A HREF="index-8.html">I</A> <A HREF="index-9.html">L</A> <A HREF="index-10.html">M</A> <A HREF="index-11.html">N</A> <A HREF="index-12.html">O</A> <A HREF="index-13.html">P</A> <A HREF="index-14.html">R</A> <A HREF="index-15.html">S</A> <A HREF="index-16.html">T</A> <A HREF="index-17.html">U</A> <A HREF="index-18.html">V</A> <A HREF="index-19.html">W</A> <A HREF="index-20.html">X</A> <A HREF="index-21.html">Y</A> <HR>
</BODY>
</HTML>
| RoederProjects/promeda | lib/java-psd-library-master/psdlibrary/doc/index-files/index-20.html | HTML | gpl-3.0 | 6,697 |
/*
Copyright © 2013 FreeUFG.
This file is part of BonusTeoComp.
BonusTeoComp 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.
BonusTeoComp 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 BonusTeoComp. If not, see <http://www.gnu.org/licenses/>.
*/
package br.org.freeUFG.teoComp2013;
import java.util.ArrayList;
public class MaquinaTuring {
private ArrayList<Character> fita;
private ArrayList<String> delta; //Pensar na função delta
private int cabeca;
//Pensar no construtor
public MaquinaTuring(){
}
//Necessário implementar este método
public String rodar(String cadeia){
this.recebeEntrada(cadeia);
return "aceita";
}
private void recebeEntrada(String w){
this.cabeca = 0;
this.fita = new ArrayList<> ();
for(int i=0; i<w.length(); i++){
Character c = new Character(w.charAt(i));
this.fita.add(c);
}
}
private void moverCabeça(String direcao){
if(direcao.equals("direita")){
this.cabeca++;
//Caso em que se move para uma célula em branco
if(this.cabeca >= this.fita.size()){
Character c = new Character('_');
this.fita.add(c);
}
}
if(direcao.equals("esquerda")){
if(this.cabeca > 0){
this.cabeca--;
}
}
}
private void escreveNaFita(char s){
Character c = new Character(s);
this.fita.set(this.cabeca, c);
}
} | FreeUFG/bonus-teo-comp | src/br/org/freeUFG/teoComp2013/MaquinaTuring.java | Java | gpl-3.0 | 2,040 |
/*
* This program 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/>.
*/
/**
* @brief Some macro definitions necessary
* @authors Ratnadip Choudhury, Pradeep Kadoor
* @copyright Copyright (c) 2011, Robert Bosch Engineering and Business Solutions. All rights reserved.
*
* Some macro definitions necessary
*/
#pragma once
#define LOG_ERR_MSG() sg_pIlog->logMessage(A2T(__FILE__), __LINE__, A2T((LPSTR) (sg_acErrStr.c_str())))
#define VALIDATE_POINTER_RETURN_VAL(Ptr, RetVal) if (Ptr == NULL) {return RetVal;}
#define VALIDATE_VALUE_RETURN_VAL(Val1, Val2, RetVal) if (Val1 != Val2) {return RetVal;}
#define VALIDATE_POINTER_RETURN_VOID(Ptr) if (Ptr == NULL) {return;}
#define VALIDATE_POINTER_NO_RETURN_LOG(Ptr) if (Ptr == NULL) {LOG_ERR_MSG();}
#define VALIDATE_POINTER_RETURN_VOID_LOG(Ptr) if (Ptr == NULL) {LOG_ERR_MSG(); return;}
#define VALIDATE_POINTER_RETURN_VALUE_LOG(Ptr, RetVal) if (Ptr == NULL) {LOG_ERR_MSG(); return RetVal;}
| Huigang610/busmaster-1 | Sources/Include/DIL_CommonDefs.h | C | gpl-3.0 | 1,599 |
/*
* Copyright 2010 Andreas Tasoulas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.lukeyboy1.interactivity;
/**
* The end of match object. Its type is used as a flag for denoting that the end of match has been reached
*
* @author Andreas Tasoulas
*
*/
public class EndOfMatch extends Signal {
public EndOfMatch(int time) {
super(time);
}
public String toString() {
return "End of match signal";
}
}
| lukecampbell99/OpenSoccer | src/com/lukeyboy1/interactivity/EndOfMatch.java | Java | gpl-3.0 | 1,030 |
/* $Id: rtcp_xr.h 2394 2008-12-23 17:27:53Z bennylp $ */
/*
* Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Additional permission under GNU GPL version 3 section 7:
*
* If you modify this program, or any covered work, by linking or
* combining it with the OpenSSL project's OpenSSL library (or a
* modified version of that library), containing parts covered by the
* terms of the OpenSSL or SSLeay licenses, Teluu Inc. (http://www.teluu.com)
* grants you additional permission to convey the resulting work.
* Corresponding Source for a non-source form of such a combination
* shall include the source code for the parts of OpenSSL used as well
* as that of the covered work.
*/
#ifndef __PJMEDIA_RTCP_XR_H__
#define __PJMEDIA_RTCP_XR_H__
/**
* @file rtcp_xr.h
* @brief RTCP XR implementation.
*/
#include <pjmedia/types.h>
#include <pj/math.h>
PJ_BEGIN_DECL
/**
* @defgroup PJMED_RTCP_XR RTCP Extended Report (XR) - RFC 3611
* @ingroup PJMEDIA_SESSION
* @brief RTCP XR extension to RTCP session
* @{
*
* PJMEDIA implements subsets of RTCP XR specification (RFC 3611) to monitor
* the quality of the real-time media (audio/video) transmission.
*/
/**
* Enumeration of report types of RTCP XR. Useful for user to enable varying
* combinations of RTCP XR report blocks.
*/
typedef enum {
PJMEDIA_RTCP_XR_LOSS_RLE = (1 << 0),
PJMEDIA_RTCP_XR_DUP_RLE = (1 << 1),
PJMEDIA_RTCP_XR_RCPT_TIMES = (1 << 2),
PJMEDIA_RTCP_XR_RR_TIME = (1 << 3),
PJMEDIA_RTCP_XR_DLRR = (1 << 4),
PJMEDIA_RTCP_XR_STATS = (1 << 5),
PJMEDIA_RTCP_XR_VOIP_METRICS = (1 << 6)
} pjmedia_rtcp_xr_type;
/**
* Enumeration of info need to be updated manually to RTCP XR. Most info
* could be updated automatically each time RTP received.
*/
typedef enum {
PJMEDIA_RTCP_XR_INFO_SIGNAL_LVL = 1,
PJMEDIA_RTCP_XR_INFO_NOISE_LVL = 2,
PJMEDIA_RTCP_XR_INFO_RERL = 3,
PJMEDIA_RTCP_XR_INFO_R_FACTOR = 4,
PJMEDIA_RTCP_XR_INFO_MOS_LQ = 5,
PJMEDIA_RTCP_XR_INFO_MOS_CQ = 6,
PJMEDIA_RTCP_XR_INFO_CONF_PLC = 7,
PJMEDIA_RTCP_XR_INFO_CONF_JBA = 8,
PJMEDIA_RTCP_XR_INFO_CONF_JBR = 9,
PJMEDIA_RTCP_XR_INFO_JB_NOM = 10,
PJMEDIA_RTCP_XR_INFO_JB_MAX = 11,
PJMEDIA_RTCP_XR_INFO_JB_ABS_MAX = 12
} pjmedia_rtcp_xr_info;
/**
* Enumeration of PLC types definitions for RTCP XR report.
*/
typedef enum {
PJMEDIA_RTCP_XR_PLC_UNK = 0,
PJMEDIA_RTCP_XR_PLC_DIS = 1,
PJMEDIA_RTCP_XR_PLC_ENH = 2,
PJMEDIA_RTCP_XR_PLC_STD = 3
} pjmedia_rtcp_xr_plc_type;
/**
* Enumeration of jitter buffer types definitions for RTCP XR report.
*/
typedef enum {
PJMEDIA_RTCP_XR_JB_UNKNOWN = 0,
PJMEDIA_RTCP_XR_JB_FIXED = 2,
PJMEDIA_RTCP_XR_JB_ADAPTIVE = 3
} pjmedia_rtcp_xr_jb_type;
#pragma pack(1)
/**
* This type declares RTCP XR Report Header.
*/
typedef struct pjmedia_rtcp_xr_rb_header
{
pj_uint8_t bt; /**< Block type. */
pj_uint8_t specific; /**< Block specific data. */
pj_uint16_t length; /**< Block length. */
} pjmedia_rtcp_xr_rb_header;
/**
* This type declares RTCP XR Receiver Reference Time Report Block.
*/
typedef struct pjmedia_rtcp_xr_rb_rr_time
{
pjmedia_rtcp_xr_rb_header header; /**< Block header. */
pj_uint32_t ntp_sec; /**< NTP time, seconds part. */
pj_uint32_t ntp_frac; /**< NTP time, fractions part. */
} pjmedia_rtcp_xr_rb_rr_time;
/**
* This type declares RTCP XR DLRR Report Sub-block
*/
typedef struct pjmedia_rtcp_xr_rb_dlrr_item
{
pj_uint32_t ssrc; /**< receiver SSRC */
pj_uint32_t lrr; /**< last receiver report */
pj_uint32_t dlrr; /**< delay since last receiver
report */
} pjmedia_rtcp_xr_rb_dlrr_item;
/**
* This type declares RTCP XR DLRR Report Block
*/
typedef struct pjmedia_rtcp_xr_rb_dlrr
{
pjmedia_rtcp_xr_rb_header header; /**< Block header. */
pjmedia_rtcp_xr_rb_dlrr_item item; /**< Block contents,
variable length list */
} pjmedia_rtcp_xr_rb_dlrr;
/**
* This type declares RTCP XR Statistics Summary Report Block
*/
typedef struct pjmedia_rtcp_xr_rb_stats
{
pjmedia_rtcp_xr_rb_header header; /**< Block header. */
pj_uint32_t ssrc; /**< Receiver SSRC */
pj_uint16_t begin_seq; /**< Begin RTP sequence reported */
pj_uint16_t end_seq; /**< End RTP sequence reported */
pj_uint32_t lost; /**< Number of packet lost in this
interval */
pj_uint32_t dup; /**< Number of duplicated packet in
this interval */
pj_uint32_t jitter_min; /**< Minimum jitter in this interval */
pj_uint32_t jitter_max; /**< Maximum jitter in this interval */
pj_uint32_t jitter_mean; /**< Average jitter in this interval */
pj_uint32_t jitter_dev; /**< Jitter deviation in this
interval */
pj_uint32_t toh_min:8; /**< Minimum ToH in this interval */
pj_uint32_t toh_max:8; /**< Maximum ToH in this interval */
pj_uint32_t toh_mean:8; /**< Average ToH in this interval */
pj_uint32_t toh_dev:8; /**< ToH deviation in this interval */
} pjmedia_rtcp_xr_rb_stats;
/**
* This type declares RTCP XR VoIP Metrics Report Block
*/
typedef struct pjmedia_rtcp_xr_rb_voip_mtc
{
pjmedia_rtcp_xr_rb_header header; /**< Block header. */
pj_uint32_t ssrc; /**< Receiver SSRC */
pj_uint8_t loss_rate; /**< Packet loss rate */
pj_uint8_t discard_rate; /**< Packet discarded rate */
pj_uint8_t burst_den; /**< Burst density */
pj_uint8_t gap_den; /**< Gap density */
pj_uint16_t burst_dur; /**< Burst duration */
pj_uint16_t gap_dur; /**< Gap duration */
pj_uint16_t rnd_trip_delay;/**< Round trip delay */
pj_uint16_t end_sys_delay; /**< End system delay */
pj_uint8_t signal_lvl; /**< Signal level */
pj_uint8_t noise_lvl; /**< Noise level */
pj_uint8_t rerl; /**< Residual Echo Return Loss */
pj_uint8_t gmin; /**< The gap threshold */
pj_uint8_t r_factor; /**< Voice quality metric carried
over this RTP session */
pj_uint8_t ext_r_factor; /**< Voice quality metric carried
outside of this RTP session*/
pj_uint8_t mos_lq; /**< Mean Opinion Score for
Listening Quality */
pj_uint8_t mos_cq; /**< Mean Opinion Score for
Conversation Quality */
pj_uint8_t rx_config; /**< Receiver configuration */
pj_uint8_t reserved2; /**< Not used */
pj_uint16_t jb_nom; /**< Current delay by jitter
buffer */
pj_uint16_t jb_max; /**< Maximum delay by jitter
buffer */
pj_uint16_t jb_abs_max; /**< Maximum possible delay by
jitter buffer */
} pjmedia_rtcp_xr_rb_voip_mtc;
/**
* This structure declares RTCP XR (Extended Report) packet.
*/
typedef struct pjmedia_rtcp_xr_pkt
{
struct {
#if defined(PJ_IS_BIG_ENDIAN) && PJ_IS_BIG_ENDIAN!=0
unsigned version:2; /**< packet type */
unsigned p:1; /**< padding flag */
unsigned count:5; /**< varies by payload type */
unsigned pt:8; /**< payload type */
#else
unsigned count:5; /**< varies by payload type */
unsigned p:1; /**< padding flag */
unsigned version:2; /**< packet type */
unsigned pt:8; /**< payload type */
#endif
unsigned length:16; /**< packet length */
pj_uint32_t ssrc; /**< SSRC identification */
} common;
pj_int8_t buf[PJMEDIA_MAX_MTU];/**< Content buffer */
} pjmedia_rtcp_xr_pkt;
#pragma pack()
/**
* This structure describes RTCP XR statitic.
*/
typedef struct pjmedia_rtcp_xr_stream_stat
{
struct {
pj_time_val update; /**< Time of last update. */
pj_uint32_t begin_seq; /**< Begin # seq of this interval. */
pj_uint32_t end_seq; /**< End # seq of this interval. */
unsigned count; /**< Number of packets. */
/**
* Flags represent whether the such report is valid/updated
*/
unsigned l:1; /**< Lost flag */
unsigned d:1; /**< Duplicated flag */
unsigned j:1; /**< Jitter flag */
unsigned t:2; /**< TTL or Hop Limit,
0=none, 1=TTL, 2=HL */
unsigned lost; /**< Number of packets lost */
unsigned dup; /**< Number of duplicated packets */
pj_math_stat jitter; /**< Jitter statistics (in usec) */
pj_math_stat toh; /**< TTL of hop limit statistics. */
} stat_sum;
struct {
pj_time_val update; /**< Time of last update. */
pj_uint8_t loss_rate; /**< Packet loss rate */
pj_uint8_t discard_rate; /**< Packet discarded rate */
pj_uint8_t burst_den; /**< Burst density */
pj_uint8_t gap_den; /**< Gap density */
pj_uint16_t burst_dur; /**< Burst duration */
pj_uint16_t gap_dur; /**< Gap duration */
pj_uint16_t rnd_trip_delay; /**< Round trip delay */
pj_uint16_t end_sys_delay; /**< End system delay */
pj_int8_t signal_lvl; /**< Signal level */
pj_int8_t noise_lvl; /**< Noise level */
pj_uint8_t rerl; /**< Residual Echo Return Loss */
pj_uint8_t gmin; /**< The gap threshold */
pj_uint8_t r_factor; /**< Voice quality metric carried
over this RTP session */
pj_uint8_t ext_r_factor; /**< Voice quality metric carried
outside of this RTP session*/
pj_uint8_t mos_lq; /**< Mean Opinion Score for
Listening Quality */
pj_uint8_t mos_cq; /**< Mean Opinion Score for
Conversation Quality */
pj_uint8_t rx_config; /**< Receiver configuration */
pj_uint16_t jb_nom; /**< Current delay by jitter
buffer */
pj_uint16_t jb_max; /**< Maximum delay by jitter
buffer */
pj_uint16_t jb_abs_max; /**< Maximum possible delay by
jitter buffer */
} voip_mtc;
} pjmedia_rtcp_xr_stream_stat;
typedef struct pjmedia_rtcp_xr_stat
{
pjmedia_rtcp_xr_stream_stat rx; /**< Decoding direction statistics. */
pjmedia_rtcp_xr_stream_stat tx; /**< Encoding direction statistics. */
pj_math_stat rtt; /**< Round-trip delay stat (in usec)
the value is calculated from
receiver side. */
} pjmedia_rtcp_xr_stat;
/**
* Forward declaration of RTCP session
*/
struct pjmedia_rtcp_session;
/**
* RTCP session is used to monitor the RTP session of one endpoint. There
* should only be one RTCP session for a bidirectional RTP streams.
*/
struct pjmedia_rtcp_xr_session
{
char *name; /**< Name identification. */
pjmedia_rtcp_xr_pkt pkt; /**< Cached RTCP XR packet. */
pj_uint32_t rx_lrr; /**< NTP ts in last RR received. */
pj_timestamp rx_lrr_time;/**< Time when last RR is received. */
pj_uint32_t rx_last_rr; /**< # pkt received since last
sending RR time. */
pjmedia_rtcp_xr_stat stat; /**< RTCP XR statistics. */
/* The reference sequence number is an extended sequence number
* that serves as the basis for determining whether a new 16 bit
* sequence number comes earlier or later in the 32 bit sequence
* space.
*/
pj_uint32_t src_ref_seq;
pj_bool_t uninitialized_src_ref_seq;
/* This structure contains variables needed for calculating
* burst metrics.
*/
struct {
pj_uint32_t pkt;
pj_uint32_t lost;
pj_uint32_t loss_count;
pj_uint32_t discard_count;
pj_uint32_t c11;
pj_uint32_t c13;
pj_uint32_t c14;
pj_uint32_t c22;
pj_uint32_t c23;
pj_uint32_t c33;
} voip_mtc_stat;
unsigned ptime; /**< Packet time. */
unsigned frames_per_packet; /**< # frames per packet. */
struct pjmedia_rtcp_session *rtcp_session;
/**< Parent/RTCP session. */
};
typedef struct pjmedia_rtcp_xr_session pjmedia_rtcp_xr_session;
/**
* Build an RTCP XR packet which contains one or more RTCP XR report blocks.
* There are seven report types as defined in RFC 3611.
*
* @param session The RTCP XR session.
* @param rpt_types Report types to be included in the packet, report types
* are defined in pjmedia_rtcp_xr_type, set this to zero
* will make this function build all reports appropriately.
* @param rtcp_pkt Upon return, it will contain pointer to the RTCP XR packet.
* @param len Upon return, it will indicate the size of the generated
* RTCP XR packet.
*/
PJ_DECL(void) pjmedia_rtcp_build_rtcp_xr( pjmedia_rtcp_xr_session *session,
unsigned rpt_types,
void **rtcp_pkt, int *len);
/**
* Call this function to manually update some info needed by RTCP XR to
* generate report which could not be populated directly when receiving
* RTP.
*
* @param session The RTCP XR session.
* @param info Info type to be updated, @see pjmedia_rtcp_xr_info.
* @param val Value.
*/
PJ_DECL(pj_status_t) pjmedia_rtcp_xr_update_info(
pjmedia_rtcp_xr_session *session,
unsigned info,
pj_int32_t val);
/*
* Private APIs:
*/
/**
* This function is called internally by RTCP session when RTCP XR is enabled
* to initialize the RTCP XR session.
*
* @param session RTCP XR session.
* @param r_session RTCP session.
* @param gmin Gmin value (defined in RFC 3611), set to 0 for default (16).
* @param ptime Packet time.
* @param frames_per_packet
Number of frames per packet.
*/
void pjmedia_rtcp_xr_init( pjmedia_rtcp_xr_session *session,
struct pjmedia_rtcp_session *r_session,
pj_uint8_t gmin,
unsigned frames_per_packet);
/**
* This function is called internally by RTCP session to destroy
* the RTCP XR session.
*
* @param session RTCP XR session.
*/
void pjmedia_rtcp_xr_fini( pjmedia_rtcp_xr_session *session );
/**
* This function is called internally by RTCP session when it receives
* incoming RTCP XR packets.
*
* @param session RTCP XR session.
* @param rtcp_pkt The received RTCP XR packet.
* @param size Size of the incoming packet.
*/
void pjmedia_rtcp_xr_rx_rtcp_xr( pjmedia_rtcp_xr_session *session,
const void *rtcp_xr_pkt,
pj_size_t size);
/**
* This function is called internally by RTCP session whenever an RTP packet
* is received or lost to let the RTCP XR session update its statistics.
* Data passed to this function is a result of analyzation by RTCP and the
* jitter buffer. Whenever some info is available, the value should be zero
* or more (no negative info), otherwise if info is not available the info
* should be -1 so no update will be done for this info in the RTCP XR session.
*
* @param session RTCP XR session.
* @param seq Sequence number of RTP packet.
* @param lost Info if this packet is lost.
* @param dup Info if this packet is a duplication.
* @param discarded Info if this packet is discarded
* (not because of duplication).
* @param jitter Info jitter of this packet.
* @param toh Info Time To Live or Hops Limit of this packet.
* @param toh_ipv4 Set PJ_TRUE if packet is transported over IPv4.
*/
void pjmedia_rtcp_xr_rx_rtp( pjmedia_rtcp_xr_session *session,
unsigned seq,
int lost,
int dup,
int discarded,
int jitter,
int toh, pj_bool_t toh_ipv4);
/**
* This function is called internally by RTCP session whenever an RTP
* packet is sent to let the RTCP XR session do its internal calculations.
*
* @param session RTCP XR session.
* @param ptsize Size of RTP payload being sent.
*/
void pjmedia_rtcp_xr_tx_rtp( pjmedia_rtcp_xr_session *session,
unsigned ptsize );
/**
* @}
*/
PJ_END_DECL
#endif /* __PJMEDIA_RTCP_XR_H__ */
| max3903/SFLphone | daemon/libs/pjproject/pjmedia/include/pjmedia/rtcp_xr.h | C | gpl-3.0 | 16,696 |
import React, { Component } from 'react';
import BottomPart from '../../planting/BottomPart';
import Article from '../../planting/customPlantPage/Article';
import ArticleDesc from '../../planting/customPlantPage/ArticleDesc';
import ButtonBar from './ButtonBar';
export default class PlantCustom extends Component {
constructor() {
super();
this.state = {
overallPrice: 0
};
this.updatePrice = this.updatePrice.bind(this);
}
updatePlantBag() {
var projectItems = {};
for (var article in this.props.articles) {
if (this.refs['article_' + article].getAmount() != null && this.refs['article_' + article].getAmount() > 0) {
projectItems[this.props.articles[article].treeType.name] = {
amount: parseInt(this.refs['article_' + article].getAmount()),
price: parseInt(this.props.articles[article].price.priceAsLong),
imageFile: this.props.articles[article].treeType.imageFile
};
}
}
this.props.updatePlantBag(this.state.overallPrice, projectItems, this.props.projectName);
}
updatePrice() {
var price = 0;
for (var article in this.props.articles) {
if (this.refs['article_' + article].getAmount() != null && this.refs['article_' + article].getAmount() > 0) {
price = price + parseInt(this.refs['article_' + article].getAmount()) * parseInt(this.props.articles[article].price.priceAsLong);
}
}
this.state.overallPrice = price;
this.forceUpdate();
}
render() {
var that = this;
return (
<div className="plantCustom">
<ButtonBar chosen={this.props.amount} setAmount={this.props.setAmount.bind(this)} />
<ArticleDesc />
<div className={'plantItems align-center'}>
{this.props.articles.filter(article => (article.amount - article.alreadyPlanted) > 0).map(function(article, i) {
return <Article key={i} article={article} ref={'article_' + i} updatePrice={that.updatePrice.bind(this)} />;
})}
</div>
<BottomPart updatePlantBag={this.updatePlantBag.bind(this)} overallPrice={this.state.overallPrice} />
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
| Dica-Developer/weplantaforest | ui/src/js/project/planting/PlantCustom.js | JavaScript | gpl-3.0 | 2,208 |
--
-- H2H Messenger Database Schema
--
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `failed_logins`
--
DROP TABLE IF EXISTS `failed_logins`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `failed_logins` (
`IP_address` varchar(45) NOT NULL,
`timestamp` datetime NOT NULL,
`attempts` int(4) NOT NULL,
PRIMARY KEY (`IP_address`),
UNIQUE KEY `IP_address_UNIQUE` (`IP_address`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `msg`
--
DROP TABLE IF EXISTS `msg`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `msg` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`sender` tinyint(5) NOT NULL,
`recip` tinyint(5) NOT NULL,
`msg_details` varchar(150) DEFAULT NULL,
`msg` text NOT NULL,
`iread` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=139 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `public_msg`
--
DROP TABLE IF EXISTS `public_msg`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `public_msg` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user` int(10) DEFAULT NULL,
`recv_date` datetime DEFAULT NULL,
`msg_details` varchar(150) DEFAULT NULL,
`msg` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `public_profile`
--
DROP TABLE IF EXISTS `public_profile`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `public_profile` (
`user` int(10) DEFAULT NULL,
`nick` varchar(100) DEFAULT NULL,
`url` varchar(57) DEFAULT NULL,
`on_off` tinyint(1) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `sms`
--
DROP TABLE IF EXISTS `sms`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sms` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`gateway` varchar(30) NOT NULL,
`provider` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `uprofile`
--
DROP TABLE IF EXISTS `uprofile`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `uprofile` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`user` tinyint(5) NOT NULL,
`upub_key` tinyint(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=58 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`email` varchar(50) NOT NULL,
`delivery` char(1) DEFAULT NULL,
`upass` varchar(152) DEFAULT NULL,
`priv_key` text NOT NULL,
`pub_key` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM AUTO_INCREMENT=91 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping events for database 'h2Hmessenger'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `clear_old_logins` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client = utf8 */ ;;
/*!50003 SET character_set_results = utf8 */ ;;
/*!50003 SET collation_connection = utf8_general_ci */ ;;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;
/*!50003 SET sql_mode = '' */ ;;
/*!50003 SET @saved_time_zone = @@time_zone */ ;;
/*!50003 SET time_zone = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clear_old_logins` ON SCHEDULE EVERY 30 SECOND STARTS '2015-12-23 13:50:35' ON COMPLETION NOT PRESERVE ENABLE DO DELETE FROM failed_logins WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW())>14 */ ;;
/*!50003 SET time_zone = @saved_time_zone */ ;;
/*!50003 SET sql_mode = @saved_sql_mode */ ;;
/*!50003 SET character_set_client = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection = @saved_col_connection */ ;;
DELIMITER ;
/*!50106 SET TIME_ZONE= @save_time_zone */ ;
-- Dump completed on 2015-12-23 18:19:58
| pugilist/h2HMessenger | enc.sql | SQL | gpl-3.0 | 5,512 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Send action to the service and set value</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.gupnp-service-proxy-action-get.html">gupnp_service_proxy_action_get</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.gupnp-service-proxy-add-notify.html">gupnp_service_proxy_add_notify</a></div>
<div class="up"><a href="ref.gupnp.html">Gupnp Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="function.gupnp-service-proxy-action-set" class="refentry">
<div class="refnamediv">
<h1 class="refname">gupnp_service_proxy_action_set</h1>
<p class="verinfo">(PECL gupnp >= 0.1.0)</p><p class="refpurpose"><span class="refname">gupnp_service_proxy_action_set</span> — <span class="dc-title">Send action to the service and set value</span></p>
</div>
<div class="refsect1 description" id="refsect1-function.gupnp-service-proxy-action-set-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="type">bool</span> <span class="methodname"><strong>gupnp_service_proxy_action_set</strong></span>
( <span class="methodparam"><span class="type">resource</span> <code class="parameter">$proxy</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$action</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$name</code></span>
, <span class="methodparam"><span class="type"><a href="language.pseudo-types.html#language.types.mixed" class="type mixed">mixed</a></span> <code class="parameter">$value</code></span>
, <span class="methodparam"><span class="type">int</span> <code class="parameter">$type</code></span>
)</div>
<p class="para rdfs-comment">
Send action with parameters to the service exposed by proxy synchronously and set value.
</p>
</div>
<div class="refsect1 parameters" id="refsect1-function.gupnp-service-proxy-action-set-parameters">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<span class="term"><em><code class="parameter">proxy</code></em></span>
<dd>
<p class="para">
A service proxy identifier.
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">action</code></em></span>
<dd>
<p class="para">
An action.
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">name</code></em></span>
<dd>
<p class="para">
The action name.
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">value</code></em></span>
<dd>
<p class="para">
The action value.
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">type</code></em></span>
<dd>
<p class="para">
The type of the action. Type can be one of the following values:
<dl>
<dt>
<span class="term"><strong><code>GUPNP_TYPE_BOOLEAN</code></strong></span>
<dd>
<span class="simpara">
Type of the variable is boolean.
</span>
</dd>
</dt>
<dt>
<span class="term"><strong><code>GUPNP_TYPE_INT</code></strong></span>
<dd>
<span class="simpara">
Type of the variable is integer.
</span>
</dd>
</dt>
<dt>
<span class="term"><strong><code>GUPNP_TYPE_LONG</code></strong></span>
<dd>
<span class="simpara">
Type of the variable is long.
</span>
</dd>
</dt>
<dt>
<span class="term"><strong><code>GUPNP_TYPE_DOUBLE</code></strong></span>
<dd>
<span class="simpara">
Type of the variable is double.
</span>
</dd>
</dt>
<dt>
<span class="term"><strong><code>GUPNP_TYPE_FLOAT</code></strong></span>
<dd>
<span class="simpara">
Type of the variable is float.
</span>
</dd>
</dt>
<dt>
<span class="term"><strong><code>GUPNP_TYPE_STRING</code></strong></span>
<dd>
<span class="simpara">
Type of the variable is string.
</span>
</dd>
</dt>
</dl>
</p>
</dd>
</dt>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-function.gupnp-service-proxy-action-set-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
Returns <strong><code>TRUE</code></strong> on success or <strong><code>FALSE</code></strong> on failure.
</p>
</div>
<div class="refsect1 errors" id="refsect1-function.gupnp-service-proxy-action-set-errors">
<h3 class="title">Errors/Exceptions</h3>
<p class="para">
Issues E_WARNING with either not correctly defined type of the action or unable to send action.
</p>
</div>
<div class="refsect1 seealso" id="refsect1-function.gupnp-service-proxy-action-set-seealso">
<h3 class="title">See Also</h3>
<p class="para">
<ul class="simplelist">
<li class="member"><span class="function"><a href="function.gupnp-service-proxy-action-get.html" class="function" rel="rdfs-seeAlso">gupnp_service_proxy_action_get()</a> - Send action to the service and get value</span></li>
<li class="member"><span class="function"><a href="gupnp-service-proxy-send-action.html" class="function" rel="rdfs-seeAlso">gupnp_service_proxy_send_action()</a> - Send action with multiple parameters synchronously</span></li>
</ul>
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="function.gupnp-service-proxy-action-get.html">gupnp_service_proxy_action_get</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.gupnp-service-proxy-add-notify.html">gupnp_service_proxy_add_notify</a></div>
<div class="up"><a href="ref.gupnp.html">Gupnp Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| Sliim/sleemacs | php-manual/function.gupnp-service-proxy-action-set.html | HTML | gpl-3.0 | 6,549 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Add various search limits</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="ref.mnogosearch.html">mnoGoSearch Functions</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.udm-alloc-agent-array.html">udm_alloc_agent_array</a></div>
<div class="up"><a href="ref.mnogosearch.html">mnoGoSearch Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="function.udm-add-search-limit" class="refentry">
<div class="refnamediv">
<h1 class="refname">udm_add_search_limit</h1>
<p class="verinfo">(PHP 4 >= 4.0.5, PHP 5 <= 5.0.5, PECL mnogosearch >= 1.0.0)</p><p class="refpurpose"><span class="refname">udm_add_search_limit</span> — <span class="dc-title">Add various search limits</span></p>
</div>
<div class="refsect1 description" id="refsect1-function.udm-add-search-limit-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="type">bool</span> <span class="methodname"><strong>udm_add_search_limit</strong></span>
( <span class="methodparam"><span class="type">resource</span> <code class="parameter">$agent</code></span>
, <span class="methodparam"><span class="type">int</span> <code class="parameter">$var</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$val</code></span>
)</div>
<p class="para rdfs-comment">
<span class="function"><strong>udm_add_search_limit()</strong></span> adds search restrictions.
</p>
</div>
<div class="refsect1 parameters" id="refsect1-function.udm-add-search-limit-parameters">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<span class="term"><em><code class="parameter">agent</code></em></span>
<dd>
<p class="para">
A link to Agent, received after call to
<span class="function"><a href="function.udm-alloc-agent.html" class="function">udm_alloc_agent()</a></span>.
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">var</code></em></span>
<dd>
<p class="para">
Defines the parameter, indicating limits.
Possible <em><code class="parameter">var</code></em> values:
<ul class="itemizedlist">
<li class="listitem">
<span class="simpara">
<strong><code>UDM_LIMIT_URL</code></strong> - defines document URL limitations to limit the search
through subsection of the database. It supports SQL % and _ LIKE wildcards,
where % matches any number of characters, even zero characters,
and _ matches exactly one character. E.g. http://www.example.___/catalog
may stand for http://www.example.com/catalog and http://www.example.net/catalog.
</span>
</li>
<li class="listitem">
<span class="simpara">
<strong><code>UDM_LIMIT_TAG</code></strong> - defines site TAG limitations. In indexer-conf you can
assign specific TAGs to various sites and parts of a site. Tags in
mnoGoSearch 3.1.x are lines, that may contain metasymbols % and _.
Metasymbols allow searching among groups of tags.
E.g. there are links with tags ABCD and ABCE, and search restriction
is by ABC_ - the search will be made among both of the tags.
</span>
</li>
<li class="listitem">
<span class="simpara">
<strong><code>UDM_LIMIT_LANG</code></strong> - defines document language limitations.
</span>
</li>
<li class="listitem">
<span class="simpara">
<strong><code>UDM_LIMIT_CAT</code></strong> - defines document category limitations. Categories are
similar to tag feature, but nested. So you can have one category inside
another and so on. You have to use two characters for each level. Use a
hex number going from 0-F or a 36 base number going from 0-Z.
Therefore a top-level category like 'Auto' would be 01. If it has a
subcategory like 'Ford', then it would be 01 (the parent category) and then
'Ford' which we will give 01. Put those together and you get 0101. If 'Auto'
had another subcategory named 'VW', then it's id would be 01 because it
belongs to the 'Ford' category and then 02 because it's the next category.
So it's id would be 0102. If VW had a sub category called 'Engine' then it's
id would start at 01 again and it would get the 'VW' id 02 and 'Auto' id of
01, making it 010201. If you want to search for sites under that category
then you pass it cat=010201 in the URL.
</span>
</li>
<li class="listitem">
<p class="para">
<strong><code>UDM_LIMIT_DATE</code></strong> - defines limitation by date the document was modified.
</p>
<p class="para">
Format of parameter value: a string with first character < or >,
then with no space - date in unixtime format, for example:
</p>
<p class="para">
<div class="example" id="example-4304">
<div class="example-contents">
<div class="phpcode"><code><span style="color: #000000">
<span style="color: #0000BB"><?php<br />udm_add_search_limit</span><span style="color: #007700">(</span><span style="color: #0000BB">$udm</span><span style="color: #007700">, </span><span style="color: #0000BB">UDM_LIMIT_DATE</span><span style="color: #007700">, </span><span style="color: #DD0000">"&lt;908012006"</span><span style="color: #007700">);<br /></span><span style="color: #0000BB">?></span>
</span>
</code></div>
</div>
</div>
</p>
<p class="para">
If > character is used, then the search will be restricted to those
documents having a modification date greater than entered, if <, then smaller.
</p>
</li>
</ul>
</p>
</dd>
</dt>
<dt>
<span class="term"><em><code class="parameter">val</code></em></span>
<dd>
<p class="para">
Defines the value of the current parameter.
</p>
</dd>
</dt>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-function.udm-add-search-limit-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
Returns <strong><code>TRUE</code></strong> on success or <strong><code>FALSE</code></strong> on failure.
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="ref.mnogosearch.html">mnoGoSearch Functions</a></div>
<div class="next" style="text-align: right; float: right;"><a href="function.udm-alloc-agent-array.html">udm_alloc_agent_array</a></div>
<div class="up"><a href="ref.mnogosearch.html">mnoGoSearch Functions</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| Sliim/sleemacs | php-manual/function.udm-add-search-limit.html | HTML | gpl-3.0 | 7,487 |
<?php
if (!defined('VALID_REQUEST')) die ('Access Denied.'); // Security
require_once(PATH_INCLUDE . 'highlight.inc.php');
class HighlightBaseItems {
public static function GetCommentLightItems() {
$items = array();
return $items;
}
public static function GetCommentItems() {
$items = array();
$items[] = new HighlightItem('$1┨$2', '$1 ($3)', '$4', '/(?<alias>.+)(.*?)(注:\k<alias>[==]([- \w]+)[,。]([^()]+))/', 'comment');
$items[] = new HighlightItem('$1┨$2', '$1', '$3', '/(?<alias>.+)(.*?)(?:<\/p>\r\n<p>)?(注:(?:\k<alias>[,。:]|「\k<alias>」|\k<alias>=)([^()]+))/', 'comment');
$items[] = new HighlightItem('$1┨$2', NULL, '$3', '/([^<>?! ,。?!:;…—「」“”]+)([,。?!:;…—」”)]*)(?:<\/p>\r\n<p>)?(注:([^()]+))/', 'comment');
$items[] = new HighlightItem('$1', '$2', NULL, '/([^<>?! 、,。?!:;…—「」“”『』‘’()]+)(\g{-1}[==]([ .\'\w]+))/', 'comment');
return $items;
}
public static function GetCommentEndItems() {
$items = array();
$items[] = new HighlightItem('$1┠$2┨$4', '$3', NULL, '/(「|『)([^<> 、,。?!:;…—「」“”『』‘’(){}]+)(([ \w]+))(』|」)/', 'comment');
$items[] = new HighlightItem('亟需', null, '强调客观上的需要迫不及待', null, 'comment');
return $items;
}
public static function GetIdiomItems() {
$items = array();
$items[] = New_Highlight__Re('奈米', '奈米公尺');
$items[] = New_Highlight__Re('米', '公尺');
$items[] = New_Highlight__Re('厘米', '公分');
$items[] = New_Highlight__Re('厘米', '公厘');
$items[] = New_Highlight__Re('奥斯曼', '鄂图曼');
$items[] = New_Highlight__Re('超市', '超商');
return $items;
}
}
?>
| FalconIA/falconia-light-novel-viewer | highlight/base.highlight.php | PHP | gpl-3.0 | 1,893 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta name="generator" content=
"HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 16.1), see www.w3.org" />
<title>Mouse-bound Commands - Untitled</title>
<meta http-equiv="Content-Type" content="text/html" />
<meta name="description" content="Untitled" />
<meta name="generator" content="makeinfo 4.13" />
<link title="Top" rel="start" href="index.html#Top" />
<link rel="up" href="Commands.html#Commands" title="Commands" />
<link href="http://www.gnu.org/software/texinfo/" rel=
"generator-home" title="Texinfo Homepage" /><!--
Copyright (C) 1995, 1996, 1997, 2001, 2002, 2003, 2004,
2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this
document under the terms of the GNU Free Documentation License,
Version 1.3 or any later version published by the Free Software
Foundation; with no Invariant Sections, with the Front-Cover texts
being ``A GNU Manual'', and with the Back-Cover Texts as in (a)
below. A copy of the license is included in the section entitled
``GNU Free Documentation License''.
(a) The FSF's Back-Cover Text is: ``You have the freedom to copy
and modify this GNU manual. Buying copies from the FSF supports
it in developing GNU and promoting software freedom.''
-->
<meta http-equiv="Content-Style-Type" content="text/css" />
<style type="text/css">
/*<![CDATA[*/
<!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
-->
/*]]>*/
</style>
</head>
<body>
<div class="node">
<a name="Mouse-bound-Commands" id="Mouse-bound-Commands"></a>
<a name="Mouse_002dbound-Commands" id=
"Mouse_002dbound-Commands"></a>
<p>Up: <a rel="up" accesskey="u" href=
"Commands.html#Commands">Commands</a></p>
<hr />
</div>
<h3 class="section">4.9 Mouse-bound Commands</h3>
<p>The following two mouse actions are normally bound to special
search and insert commands in of Viper:</p>
<dl>
<dt><kbd>S-Mouse-1</kbd></dt>
<dd>Holding Shift and clicking mouse button 1 will initiate
search for a region under the mouse pointer. This command can
take a prefix argument. Note: Viper sets this binding only if
this mouse action is not already bound to something else. See
<a href="Viper-Specials.html#Viper-Specials">Viper
Specials</a>, for more information.<br /></dd>
<dt><kbd>S-Mouse-2</kbd></dt>
<dd>Holding Shift and clicking button 2 of the mouse will
insert a region surrounding the mouse pointer. This command can
also take a prefix argument. Note: Viper sets this binding only
if this mouse action is not already bound to something else.
See <a href="Viper-Specials.html#Viper-Specials">Viper
Specials</a>, for more details.</dd>
</dl><a name="index-g_t_0040kbd_007bS_002dMouse_002d1_007d-627"
id=
"index-g_t_0040kbd_007bS_002dMouse_002d1_007d-627"></a><a name="index-g_t_0040kbd_007bS_002dMouse_002d2_007d-628"
id=
"index-g_t_0040kbd_007bS_002dMouse_002d2_007d-628"></a><a name="index-g_t_0040kbd_007bmeta-button1up_007d-629"
id="index-g_t_0040kbd_007bmeta-button1up_007d-629"></a><a name=
"index-g_t_0040kbd_007bmeta-button2up_007d-630" id=
"index-g_t_0040kbd_007bmeta-button2up_007d-630"></a>
</body>
</html>
| davidswelt/aquamacs-emacs | aquamacs/doc/Aquamacs Help/viper/Mouse_002dbound-Commands.html | HTML | gpl-3.0 | 3,911 |
{% extends "website/base.html" %}
{% load i18n %}
{% load difficulties_splitter %}
{% load osu_images %}
{% block title %}{{ beatmap.id }} {{ beatmap.artist }} - {{ beatmap.title }}{% endblock %}
{% block nav_line %}
<li class="nav_item"><a href="{% url 'website:index' %}">{% trans 'Home' %}</a></li>
<li class="right">»</li>
<li class="nav_item"><a
href="{% url 'website:listing' 0 0 1 %}">{% trans 'Listing' %}</a></li>
<li class="right">»</li>
<li class="nav_item nav_item_selected"><a
href="{% url 'website:item' beatmap.id %}">{{ beatmap.id }} {{ beatmap.artist }} - {{ beatmap.title }}</a>
</li>
{% endblock %}
{% block content %}
<header class="bm_title"><span>{{ beatmap.artist }} - {{ beatmap.title }}</span></header>
<article class="bm_info_content">
<div id="bm_info_table_container">
<table id="bm_info_table" width="100%" cellspacing="0">
<tr>
<td class="t_key">{% trans 'Artist' %}</td>
<td class="t_value">{{ beatmap.artist }}</td>
<td class="t_key">{% trans 'Genre' %}</td>
<td class="t_value"><a
href="{% url 'website:listing' beatmap.genre.id 0 1 %}">{% trans beatmap.genre.caption %}</a>
</td>
</tr>
<tr>
<td class="t_key">{% trans 'Title' %}</td>
<td class="t_value">{{ beatmap.title }}</td>
<td class="t_key">{% trans 'Language' %}</td>
<td class="t_value"><a
href="{% url 'website:listing' 0 beatmap.language.id 1 %}">{% trans beatmap.language.caption %}</a>
</td>
</tr>
<tr>
<td class="t_key">{% trans 'Creator' %}</td>
<td class="t_value"><a href="{% url 'website:user' beatmap.creator %}">{{ beatmap.creator }}</a>
</td>
<td class="t_key">{% trans 'Submitted On' %}</td>
<td class="t_value">{{ beatmap.date_submitted }}</td>
</tr>
<tr>
<td class="t_key">{% trans 'Source' %}</td>
<td class="t_value">{{ beatmap.source }}</td>
<td class="t_key">{% trans 'Ranked On' %}</td>
<td class="t_value">{{ beatmap.date_ranked }}</td>
</tr>
<tr>
<td class="t_key">{% trans 'Difficulties' %}</td>
<td colspan="3">
{% for difficulty in beatmap.difficulties|split_difficulties %}
<div class="difficulty d_{{ difficulty }} item_difficulty"></div>
{% endfor %}
</td>
</tr>
</table>
</div>
<div id="bm_buttons">
<div id="bm_download" class="btn_container">
<a id="bm_download_link" class="no_select cbutton" href="{% url 'website:download' beatmap.id %}"><span
id="bm_download_icon" class="icon"></span><span
class="text">{% trans 'Download' %}</span></a>
</div>
<div id="bm_details" class="btn_container">
<a id="bm_details_link" class="no_select cbutton" href="{% url 'website:detail' beatmap.id %}"><span
id="bm_details_icon" class="icon"></span><span
class="text">{% trans 'Detail' %}</span></a>
</div>
</div>
<div id="bm_info_description_container">
<div id="bm_info_description_left">
<div id="bm_info_preview_img">
<img src="{{ beatmap.id|osu_thumb_large }}" width="160" height="120" alt="Preview Image"
/></div>
<div id="bm_info_description_preview_audio"><a href="#">Click to play</a></div>
</div>
<div id="bm_info_description_content">
{{ beatmap.description|safe }}
</div>
</div>
</article>
{% endblock %} | IndeedPlusPlus/osubeatmaps | website/templates/website/item.html | HTML | gpl-3.0 | 4,212 |
/*
Copyright (C) 2012 Andreolli Cédric, Boulanger Chloé, Cléro Olivier, Guellier Antoine, Guilloux Sébastien, Templé Arthur
This file is part of chemicalmozart.
chemicalmozart 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.
chemicalmozart 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 chemicalmozart. If not, see <http://www.gnu.org/licenses/>
*/
package org.chemicalmozart.model.interfaces;
import java.util.HashSet;
import org.chemicalmozart.controler.Observable;
/**
* Description of the interface Chord.
*
*
*/
public interface Chord extends Observable {
/**
* Description of the method getDegrees.
*
*
* @return null
*/
public HashSet<Degree> getDegrees() ;
} | Legroupesuper/Objets--Chimiques--Java---INSA-4info | chemicalforall/chemicalmozart/src/main/java/org/chemicalmozart/model/interfaces/Chord.java | Java | gpl-3.0 | 1,220 |
require_relative "element_base"
class DropdownMenu < ElementBase
def get_count_of_options
if exist?
arrOption = @@element.find_elements(:xpath, ".//ul[contains(@class,'dropdown-menu')]/li/a")
Common.logger_step "Execute - get count of options in #{self.class} - success."
arrOption.length
else
Common.logger_error "Execute - get count of options in #{self.class} - failed. can't find element by #{@@type} and #{@@value}"
end
end
def open_dropdown_menu
begin
@@element ||= element
# scroll into view to top window before open menu
$driver.execute_script("arguments[0].scrollIntoView(true);", @@element) rescue false
unless @@element.attribute("class").include? "open"
load_options
# @@element.find_element(:xpath, "./button[@data-toggle='dropdown']").click
$driver.execute_script("$(arguments[0]).click();", @@element.find_element(:xpath, "./button[contains(@class,'dropdown-toggle')]"))
end
rescue Exception => e
Common.logger_error "Execute - open dropdown menu of #{self.class} - failed. get error #{e}"
end
end
def select_by_index(index)
open_dropdown_menu
if enabled? and "#{@@element.find_element(:xpath, ".//button").attribute("disabled")}" != "true"
arrOption = @@element.find_elements(:xpath, ".//ul[contains(@class,'dropdown-menu')]/li/a")
if arrOption.length > index
arrOption[index.to_i].click
Common.logger_step "Execute - select item in #{self.class} by index. - success. select item [#{index}]."
else
Common.logger_error "Execute - select item in #{self.class} by index - failed. the index [#{index}] is our of range"
end
else
Common.logger_error "Execute - select item in #{self.class} by index - failed. the element is disalbled or can't find element by #{@@type} and #{@@value}"
end
end
def select_by_item_text(text)
open_dropdown_menu
if enabled? and "#{@@element.find_element(:xpath, ".//button").attribute("disabled")}" != "true"
obj = @@element.find_element(:xpath, ".//ul[contains(@class,'dropdown-menu')]//a[.='#{text}']") rescue nil
obj = @@element.find_element(:xpath, ".//ul[contains(@class,'dropdown-menu')]//a[contains(.,'#{text}')]") if obj == nil
# $driver.execute_script("arguments[0].scrollIntoView(false);", obj) rescue false
obj.click
$driver.execute_script("arguments[0].click();",obj) rescue false
Common.logger_step "Execute - select item in #{self.class} by text. - success. select item [#{text}]"
else
Common.logger_error "Execute - select item in #{self.class} by text - failed. the element is disalbled or can't find element by #{@@type} and #{@@value}"
end
end
def select_by_value(value)
open_dropdown_menu
if enabled? and "#{@@element.find_element(:xpath, ".//button").attribute("disabled")}" != "true"
begin
@@element.find_element(:xpath, ".//ul[contains(@class,'dropdown-menu')]//a[contains(@data-value,'#{value}')]").click
Common.logger_step "Execute - select item in #{self.class} by text. - success. select item [#{value}]"
rescue Exception => e
Common.logger_error "Execute - select item in #{self.class} by text - failed. failed to select item [#{value}], get error #{e}"
end
else
Common.logger_error "Execute - select item in #{self.class} by text - failed. the element is disalbled or can't find element by #{@@type} and #{@@value}"
end
end
def check_selected_item(expected_value)
selected_item = get_selected_item
if selected_item.strip == expected_value.strip
Common.logger_step "Assert - check seleted item in #{self.class} - success."
true
else
Common.logger_error "Assert - check seleted item in #{self.class} - failed. get item [#{selected_item.strip}] while [#{expected_value.strip}] is expected"
end
end
def check_item_by_index(index, expected_value)
item_by_index = get_item_by_index(index).strip
if item_by_index == expected_value.strip
Common.logger_step "Assert - check item in #{self.class} by index - success."
return true
else
Common.logger_error "Assert - check item in #{self.class} by index - failed. get [#{item_by_index}] for item [#{index}] while [#{expected_value.strip}] is expected"
end
end
def get_selected_item
if exist?
item = @@element.find_element(:xpath, ".//button/span[@data-bind='label']")
Common.logger_step "Execute - get selected item in #{self.class} - sucess. get item [#{item.text}]."
item.text
else
Common.logger_error "Execute - get selected item in #{self.class} - failed. can't find element by #{@@type} and #{@@value}"
end
end
def get_all_items
if exist?
items = []
options = @@element.find_elements(:xpath, ".//ul[contains(@class,'dropdown-menu')]/li/a")
options.each{|option| items << $driver.execute_script("return $(arguments[0]).text()",option).to_s.strip}
Common.logger_step "Execute - get all items in #{self.class} - sucess."
items
else
Common.logger_error "Execute - get all items in #{self.class} - failed. can't find element by #{@@type} and #{@@value}"
end
end
def get_item_by_index(index)
all_items = get_all_items
if all_items.length > index
all_items[index]
else
Common.logger_error "Execute - get item from #{self.class} by index - success. get item [#{all_items[index]}]"
end
end
def get_index_by_item_text(text)
get_all_items.each_with_index do |item_text, index|
if item_text.strip.include? text.strip
Common.logger_step "Execute - get index of item in #{self.class} - success. the index of [#{text}] is #{index}"
return index
end
end
Common.logger_error "Execute - get index of item in #{self.class} - failed. the item [#{text}] is not found"
end
def check_included_item(text)
load_options
all_items = get_all_items
index = all_items.index text.strip
unless index.nil?
Common.logger_step "Assert - check item exist in #{self.class} - success."
else
Common.logger_error "Assert - check item exist in #{self.class} - failed. the item [#{text}] is not found"
end
end
def check_not_included_item(text)
load_options
all_items = get_all_items
index = all_items.index text.strip
if index.nil?
Common.logger_step "Assert - check item not exist in #{self.class} - success."
else
Common.logger_error "Assert - check item not exist in #{self.class} - failed. the item [#{text}] is found"
end
end
def check_selected_item_value(expected_value)
if exist?
item_value = @@element.find_element(:xpath, ".//button/span[@data-bind='label']").attribute("data-value")
if item_value == expected_value
Common.logger_step "Assert - check value of seleted item in #{self.class} - success."
true
else
Common.logger_error "Assert - check value of selected item for #{self.class} - failed. get value [#{item_value.strip}] while [#{expected_value.strip}] is expected"
end
else
Common.logger_error "Assert - check value of selected item for #{self.class} - failed. can't find element by #{@@type} and #{@@value}"
end
end
def get_property(string_property)
if exist?
result = @@element.attribute(string_property)
Common.logger_step "Execute - get #{string_property} of #{self.class} - success. get [#{result}] from page."
if result.nil?
result = @@element.find_element(:xpath, ".//button").attribute(string_property)
Common.logger_step "Execute - reget #{string_property} of #{self.class} - success. get [#{result}] from page."
end
result.nil? ? result : result.strip
else
Common.logger_info "Execute ERROR - get #{string_property} of #{self.class} - failed. can't find element by #{@@type} and #{@@value}"
false
end
end
def check_property(string_property,expected_result)
actual_result = get_property(string_property)
if expected_result == actual_result
Common.logger_step "Assert - check #{string_property} of #{self.class} - success."
return true
else
Common.logger_error "Assert - check #{string_property} of #{self.class} - failed. the expected value is #{expected_result}. the actual result is #{actual_result}"
end
end
def load_options(timeout=10,option_text=nil)
wait_element_present
timeout.times.each do |i|
if get_count_of_options > 1
unless option_text.nil?
next if get_all_items.index(option_text).nil?
end
Common.logger_step "load options for #{self.class} successfully"
return true
else
sleep 1
Common.logger_step "load options for #{self.class} time:#{i}"
end
end
Common.logger_info "load options for #{self.class} failed, timeout:#{timeout}"
false
end
def enabled?
property = get_property("disabled")
if property.to_s == "true"
return false
else
return true
end
end
end
| workhardsmile/docker-appium-grid | rtest-framework/common/elements/dropdown_menu.rb | Ruby | gpl-3.0 | 9,191 |
---
layout: post
category: Papyri
title: Advanced Search
group: manual
---
From the simple search page, click Advanced
{% pic advanced %}
On this page, any terms (space-separated) that you type must all be matched for a search result to match.
The fields that are searched are:
* Date From
* Date To
* General Note
* Inventory Number
* Language Note
* Lines of Text
* Origin Details
* Original Text
* Paleographic Description
* Preservation Note
* Recto Verso Note
* Source of Acquisition
* Summary
* Translated Text
As with the simple search, the results are ordered by MQT number and pagination is at the bottom of the page.
To modify your search, edit the fields and click "Search" again.
| IntersectAustralia/dc12c | manual/_posts/0000-03-04-advanced-search.md | Markdown | gpl-3.0 | 696 |
ALTER TABLE `#__poe_product` ADD `tabs` VARCHAR( 50 ) NULL AFTER `description` | lion01/poe-com | admin/sql/updates/mysql/2.5.4.sql | SQL | gpl-3.0 | 81 |
# CyberAttacksVisualization
CyberAttacksVisualization Tool
Plese check the project page http://sumeetkr.github.io/CyberAttacksVisualization/
| sumeetkr/CyberAttacksVisualization | README.md | Markdown | gpl-3.0 | 141 |
//
// DetailViewController.h
// OwnCloud Notes
//
// Created by Markus Klepp on 22/03/14.
// Copyright (c) 2014 AyKit. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController <UISplitViewControllerDelegate>
@property (strong, nonatomic) NSDictionary *detailItem;
@property (weak, nonatomic) IBOutlet UILabel *detailDateLabel;
@property (weak, nonatomic) IBOutlet UITextView *detailContentTextView;
@property (weak, nonatomic) IBOutlet UIButton *offlineInfoButton;
- (IBAction)showOfflineMessage:(id)sender;
@end | aykit/myownnotes-ios | OwnCloud Notes/DetailViewController.h | C | gpl-3.0 | 564 |
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.facebook.android.R;
/**
* This Activity is a necessary part of the overall Facebook login process
* but is not meant to be used directly. Add this activity to your
* AndroidManifest.xml to ensure proper handling of Facebook login.
* <pre>
* {@code
* <activity android:name="com.facebook.LoginActivity"
* android:theme="@android:style/Theme.Translucent.NoTitleBar"
* android:label="@string/app_name" />
* }
* </pre>
* Do not start this activity directly.
*/
public class LoginActivity extends Activity {
static final String RESULT_KEY = "com.facebook.LoginActivity:Result";
private static final String TAG = LoginActivity.class.getName();
private static final String NULL_CALLING_PKG_ERROR_MSG =
"Cannot call LoginActivity with a null calling package. " +
"This can occur if the launchMode of the caller is singleInstance.";
private static final String SAVED_CALLING_PKG_KEY = "callingPackage";
private static final String SAVED_AUTH_CLIENT = "authorizationClient";
private static final String EXTRA_REQUEST = "request";
private String callingPackage;
private AuthorizationClient authorizationClient;
private AuthorizationClient.AuthorizationRequest request;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.com_facebook_login_activity_layout);
Log.d("AndroidNative", "LoginActivity create");
if (savedInstanceState != null) {
callingPackage = savedInstanceState.getString(SAVED_CALLING_PKG_KEY);
authorizationClient = (AuthorizationClient) savedInstanceState.getSerializable(SAVED_AUTH_CLIENT);
Log.d("AndroidNative", "1. " + callingPackage);
} else {
callingPackage = getCallingPackage();
authorizationClient = new AuthorizationClient();
request = (AuthorizationClient.AuthorizationRequest) getIntent().getSerializableExtra(EXTRA_REQUEST);
Log.d("AndroidNative", "2. " + callingPackage);
}
authorizationClient.setContext(this);
authorizationClient.setOnCompletedListener(new AuthorizationClient.OnCompletedListener() {
@Override
public void onCompleted(AuthorizationClient.Result outcome) {
onAuthClientCompleted(outcome);
}
});
authorizationClient.setBackgroundProcessingListener(new AuthorizationClient.BackgroundProcessingListener() {
@Override
public void onBackgroundProcessingStarted() {
findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.VISIBLE);
}
@Override
public void onBackgroundProcessingStopped() {
findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.GONE);
}
});
}
private void onAuthClientCompleted(AuthorizationClient.Result outcome) {
request = null;
int resultCode = (outcome.code == AuthorizationClient.Result.Code.CANCEL) ?
RESULT_CANCELED : RESULT_OK;
Bundle bundle = new Bundle();
bundle.putSerializable(RESULT_KEY, outcome);
Intent resultIntent = new Intent();
resultIntent.putExtras(bundle);
setResult(resultCode, resultIntent);
finish();
}
@Override
public void onResume() {
super.onResume();
// If the calling package is null, this generally means that the callee was started
// with a launchMode of singleInstance. Unfortunately, Android does not allow a result
// to be set when the callee is a singleInstance, so we log an error and return.
if (callingPackage == null) {
Log.e(TAG, NULL_CALLING_PKG_ERROR_MSG);
finish();
return;
}
authorizationClient.startOrContinueAuth(request);
}
@Override
public void onPause() {
super.onPause();
authorizationClient.cancelCurrentHandler();
findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.GONE);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVED_CALLING_PKG_KEY, callingPackage);
outState.putSerializable(SAVED_AUTH_CLIENT, authorizationClient);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
authorizationClient.onActivityResult(requestCode, resultCode, data);
}
static Bundle populateIntentExtras(AuthorizationClient.AuthorizationRequest request) {
Bundle extras = new Bundle();
extras.putSerializable(EXTRA_REQUEST, request);
return extras;
}
}
| manakpp/Mage-Command | Project/Assets/Plugins/Android/facebook/src/com/facebook/LoginActivity.java | Java | gpl-3.0 | 5,699 |
package org.modula.helpers.index.stubs;
import com.intellij.psi.stubs.StubElement;
import org.modula.parsing.definition.psi.DefinitionModuleHeader;
/**
* Aggregates the interfaces for module stubs
*/
public interface ModuleStub extends StubElement<DefinitionModuleHeader>, Module, SerializableStub {
}
| miracelwhipp/idea-modula-support | ims-plugin/src/main/java/org/modula/helpers/index/stubs/ModuleStub.java | Java | gpl-3.0 | 318 |
# Install script for directory: /home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/src
# Set the install prefix
IF(NOT DEFINED CMAKE_INSTALL_PREFIX)
SET(CMAKE_INSTALL_PREFIX "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install")
ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX)
STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
# Set the install configuration name.
IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
IF(BUILD_TYPE)
STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
ELSE(BUILD_TYPE)
SET(CMAKE_INSTALL_CONFIG_NAME "")
ENDIF(BUILD_TYPE)
MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
# Set the component getting installed.
IF(NOT CMAKE_INSTALL_COMPONENT)
IF(COMPONENT)
MESSAGE(STATUS "Install component: \"${COMPONENT}\"")
SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
ELSE(COMPONENT)
SET(CMAKE_INSTALL_COMPONENT)
ENDIF(COMPONENT)
ENDIF(NOT CMAKE_INSTALL_COMPONENT)
# Install shared libraries without execute permission?
IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
SET(CMAKE_INSTALL_SO_NO_EXE "1")
ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
if (NOT EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}")
file(MAKE_DIRECTORY "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}")
endif()
if (NOT EXISTS "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/.catkin")
file(WRITE "$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}/.catkin" "")
endif()
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install/_setup_util.py")
IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
FILE(INSTALL DESTINATION "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install" TYPE PROGRAM FILES "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/catkin_generated/installspace/_setup_util.py")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install/env.sh")
IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
FILE(INSTALL DESTINATION "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install" TYPE PROGRAM FILES "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/catkin_generated/installspace/env.sh")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install/setup.bash")
IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
FILE(INSTALL DESTINATION "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install" TYPE FILE FILES "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/catkin_generated/installspace/setup.bash")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install/setup.sh")
IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
FILE(INSTALL DESTINATION "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install" TYPE FILE FILES "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/catkin_generated/installspace/setup.sh")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install/setup.zsh")
IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
FILE(INSTALL DESTINATION "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install" TYPE FILE FILES "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/catkin_generated/installspace/setup.zsh")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
list(APPEND CMAKE_ABSOLUTE_DESTINATION_FILES
"/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install/.rosinstall")
IF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
message(WARNING "ABSOLUTE path INSTALL DESTINATION : ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION)
IF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
message(FATAL_ERROR "ABSOLUTE path INSTALL DESTINATION forbidden (by caller): ${CMAKE_ABSOLUTE_DESTINATION_FILES}")
ENDIF (CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION)
FILE(INSTALL DESTINATION "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/install" TYPE FILE FILES "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/catkin_generated/installspace/.rosinstall")
ENDIF(NOT CMAKE_INSTALL_COMPONENT OR "${CMAKE_INSTALL_COMPONENT}" STREQUAL "Unspecified")
IF(NOT CMAKE_INSTALL_LOCAL_ONLY)
# Include the install script for each subdirectory.
INCLUDE("/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/gtest/cmake_install.cmake")
INCLUDE("/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/helloworld/cmake_install.cmake")
INCLUDE("/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/loadcell_calibration/cmake_install.cmake")
ENDIF(NOT CMAKE_INSTALL_LOCAL_ONLY)
IF(CMAKE_INSTALL_COMPONENT)
SET(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt")
ELSE(CMAKE_INSTALL_COMPONENT)
SET(CMAKE_INSTALL_MANIFEST "install_manifest.txt")
ENDIF(CMAKE_INSTALL_COMPONENT)
FILE(WRITE "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/${CMAKE_INSTALL_MANIFEST}" "")
FOREACH(file ${CMAKE_INSTALL_MANIFEST_FILES})
FILE(APPEND "/home/ethietter/fiore-ipp/ipp-15-16/catkin_ws/build/${CMAKE_INSTALL_MANIFEST}" "${file}\n")
ENDFOREACH(file)
| fioreinc/ipp-15-16 | deprecated/catkin_ws/build/cmake_install.cmake | CMake | gpl-3.0 | 8,073 |
from Sire.Base import *
from Sire.IO import *
from Sire.Mol import *
from glob import glob
from nose.tools import assert_equal, assert_almost_equal
# Check that we have Mol2 support in this version of Sire.
has_mol2 = True
try:
p = Mol2()
except:
# No Mol2 support.
has_mol2 = False
# General test of ability to read and write Mol2 files.
# All Mol2 files in the "../io/" directory are parsed.
# Once the input file is parsed we then check that the parser constructs a
# Sire Molecule from the parsed data. Following this, we then check that the
# parser can convert the molecule back into the correct data format, ready to
# be written to file.
def test_read_write(verbose=False):
if not has_mol2:
return
# Glob all of the Mol2 files in the example file directory.
mol2files = glob('../io/*mol2')
# Loop over all test files.
for file in mol2files:
# Test in parallel and serial mode.
for use_par in [True, False]:
if verbose:
print("Reading Mol2 file: %s" % file)
print("Parallel = %s" % use_par)
# Parse the file into a Mol2 object.
p = Mol2(file, {"parallel" : wrap(use_par)})
if verbose:
print("Constructing molecular system...")
# Construct a Sire molecular system.
s = p.toSystem()
if verbose:
print("Reconstructing Mol2 data from molecular system...")
# Now re-parse the molecular system.
p = Mol2(s, {"parallel" : wrap(use_par)})
if verbose:
print("Passed!\n")
# Specific atom coordinate data validation test for file "../io/complex.mol2".
def test_atom_coords(verbose=False):
if not has_mol2:
return
# Test atoms.
atoms = ["N", "CA", "C", "O", "CB"]
# Test coordinates.
coords = [[ -2.9880, -2.0590, -2.6220],
[ -3.8400, -2.0910, -7.4260],
[ -6.4250, -3.9190, -10.9580],
[ -6.1980, -6.0090, -14.2910],
[ -9.8700, -6.5500, -15.2480]]
# Test in parallel and serial mode.
for use_par in [True, False]:
if verbose:
print("Reading Mol2 file: ../io/complex.mol2")
print("Parallel = %s" % use_par)
# Parse the Mol2 file.
p = Mol2('../io/complex.mol2', {"parallel" : wrap(use_par)})
if verbose:
print("Constructing molecular system...")
# Create a molecular system.
s = p.toSystem()
# Get the first molecule.
m = s[MolIdx(0)]
if verbose:
print("Checking atomic coordinates...")
# Loop over all of the atoms.
for i in range(0, len(atoms)):
# Extract the atom from the residue "i + 1".
a = m.atom(AtomName(atoms[i]) + ResNum(i+1))
# Extract the atom coordinates.
c = a.property("coordinates")
# Validate parsed coordinates against known values.
assert_almost_equal( c[0], coords[i][0] )
assert_almost_equal( c[1], coords[i][1] )
assert_almost_equal( c[2], coords[i][2] )
if verbose:
print("Passed!\n")
# Residue and chain validation test for file "../io/complex.mol2".
def test_residues(verbose=False):
if not has_mol2:
return
# Test in parallel and serial mode.
for use_par in [True, False]:
if verbose:
print("Reading Mol2 file: ../io/complex.mol2")
print("Parallel = %s" % use_par)
# Parse the Mol2 file.
p = Mol2('../io/complex.mol2', {"parallel" : wrap(use_par)})
if verbose:
print("Constructing molecular system...")
# Create a molecular system.
s = p.toSystem()
# Get the two molecules.
m1 = s[MolIdx(0)]
m2 = s[MolIdx(1)]
# Get the chains from the molecules.
c1 = m1.chains()
c2 = m2.chains()
if verbose:
print("Checking chain and residue data...")
# Check the number of chains in each molecule.
assert_equal( len(c1), 3 )
assert_equal( len(c2), 1 )
# Check the number of residues in each chain of the first molecule.
assert_equal( len(c1[0].residues()), 118 )
assert_equal( len(c1[1].residues()), 114 )
assert_equal( len(c1[2].residues()), 118 )
# Check the number of residues in the single chain of the second molecule.
assert_equal( len(c2[0].residues()), 1 )
# Check some specific residue names in the first chain from the first molecule.
assert_equal( c1[0].residues()[0].name().toString(), "ResName('PRO1')" )
assert_equal( c1[1].residues()[1].name().toString(), "ResName('MET2')" )
assert_equal( c1[1].residues()[2].name().toString(), "ResName('PHE3')" )
if verbose:
print("Passed!\n")
if __name__ == "__main__":
test_read_write(True)
test_atom_coords(True)
test_residues(True)
| michellab/SireUnitTests | unittests/SireIO/test_mol2.py | Python | gpl-3.0 | 5,051 |
/*
Copyright 2016-2017, Guenther Charwat
WWW: <http://dbai.tuwien.ac.at/proj/decodyn/dynqbf>.
This file is part of dynQBF.
dynQBF 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.
dynQBF 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 dynQBF. If not, see <http://www.gnu.org/licenses/>.
*/
#include <htd/main.hpp>
namespace decomposer {
class JoinNodeChildRememberedProductFitnessFunction : public htd::ITreeDecompositionFitnessFunction {
public:
JoinNodeChildRememberedProductFitnessFunction(void);
~JoinNodeChildRememberedProductFitnessFunction();
htd::FitnessEvaluation * fitness(const htd::IMultiHypergraph & graph, const htd::ITreeDecomposition & decomposition) const override;
JoinNodeChildRememberedProductFitnessFunction * clone(void) const override;
};
}
| gcharwat/dynqbf | src/decomposer/JoinNodeChildRememberedProductFitnessFunction.h | C | gpl-3.0 | 1,247 |
<?php
/**
* Script to manage sections
*************************************************/
/* required functions */
require_once('../../functions/functions.php');
/* verify that user is admin */
checkAdmin();
/* filter input */
$_POST = filter_user_input($_POST, true, true, false);
/* get size of subnets - $_POST /4 */
$size = sizeof($_POST) / 4;
/* get unique keys for subnets because they are not sequential of deleted!!! */
foreach($_POST as $key=>$line) {
if (strlen(strstr($key,"subnet"))>0) {
$allSubnets[] = $key;
}
}
/* import each record to database */
foreach($allSubnets as $subnet) {
//get number
$m = str_replace("subnet-", "", $subnet);
//set subnet details
$subnetDetails['action'] = "add";
$subnetDetails['subnet'] = $_POST['subnet-' . $m];
$subnetDetails['sectionId'] = $_POST['section-' . $m];
$subnetDetails['description'] = $_POST['description-' . $m];
$subnetDetails['VLAN'] = $_POST['vlan-' . $m];
$subnetDetails['masterSubnetId'] = 0;
//cidr
if(verifyCidr ($subnetDetails['subnet'])) {
$errors[] = verifyCidr ($subnetDetails['subnet']);
}
//overlapping
else if (verifySubnetOverlapping ($subnetDetails['sectionId'], $subnetDetails['subnet'],"000")) {
$errors[] = verifySubnetOverlapping ($subnetDetails['sectionId'], $subnetDetails['subnet'],"000");
}
//nested overlapping
else if (verifyNestedSubnetOverlapping ($subnetDetails['sectionId'], $subnetDetails['subnet'],"000")) {
$errors[] = verifyNestedSubnetOverlapping ($subnetDetails['sectionId'], $subnetDetails['subnet'],"000");
}
//set insert
else {
$subnetInsert[] = $subnetDetails;
}
}
/* print errors if they exist or success */
if(!isset($errors)) {
$errors2 = 0;
//insert if all other is ok!
foreach($subnetInsert as $subnetDetails) {
if(!modifySubnetDetails ($subnetDetails)) {
print '<div class="alert alert-danger alert-absolute">'._('Failed to import subnet').' '. $subnetDetails['subnet'] .'</div>';
$errors2++;
}
}
//check if all is ok and print it!
if($errors2 == 0) {
print '<div class="alert alert-success alert-absolute">'._('Import successfull').'!</div>';
}
}
else {
print '<div class="alert alert-danger alert-absolute">'._('Please fix the following errors before inserting').':<hr>'. "\n";
foreach ($errors as $line) {
print $line.'<br>';
}
print '</div>';
}
?> | datacentred/phpipam | site/admin/ripeImportResult.php | PHP | gpl-3.0 | 2,362 |
/*
* Copyright 2010-2013 OpenXcom Developers.
*
* This file is part of OpenXcom.
*
* OpenXcom 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.
*
* OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef OPENXCOM_INTERCEPTSTATE_H
#define OPENXCOM_INTERCEPTSTATE_H
#include <vector>
#include "../Engine/State.h"
namespace OpenXcom
{
class TextButton;
class Window;
class Text;
class TextList;
class Base;
class Globe;
class Craft;
class Target;
/**
* Intercept window that lets the player launch
* crafts into missions from the Geoscape.
*/
class InterceptState : public State
{
private:
TextButton *_btnCancel, *_btnGotoBase;
Window *_window;
Text *_txtTitle, *_txtCraft, *_txtStatus, *_txtBase, *_txtWeapons;
TextList *_lstCrafts;
Globe *_globe;
Base *_base;
Target *_target;
std::vector<Craft*> _crafts;
public:
/// Creates the Intercept state.
InterceptState(Game *game, Globe *globe, Base *base = 0, Target *target = 0);
/// Cleans up the Intercept state.
~InterceptState();
/// Handler for clicking the Cancel button.
void btnCancelClick(Action *action);
/// Handler for clicking the Go To Base button.
void btnGotoBaseClick(Action *action);
/// Handler for clicking the Crafts list.
void lstCraftsLeftClick(Action *action);
/// Handler for right clicking the Crafts list.
void lstCraftsRightClick(Action *action);
};
}
#endif
| IvanDogovich/OpenXcom | src/Geoscape/InterceptState.h | C | gpl-3.0 | 1,890 |
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitfdb164856dfc594f414468682b7d2d57::getLoader();
| JoseSulbaran/laravel-project | vendor/autoload.php | PHP | gpl-3.0 | 178 |
/* pdf417_tabs.h - PDF417 tables and coefficients */
/*
libzint - the open source barcode library
Copyright (C) 2008-2021 Robin Stuart <rstuart114@gmail.com>
Portions Copyright (C) 2004 Grandzebu
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.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
/* vim: set ts=4 sw=4 et : */
/* this file contains the character table, the pre-calculated coefficients and the
codeword patterns taken from lines 416 to 454 of pdf417.frm */
/* See "pdf417.h" for declarations */
#ifndef __PDF417_TABS_H
#define __PDF417_TABS_H
/* PDF417 error correction coefficients from Grand Zebu */
INTERNAL_DATA const unsigned short pdf_coefrs[1022] = {
/* k = 2 */
27, 917,
/* k = 4 */
522, 568, 723, 809,
/* k = 8 */
237, 308, 436, 284, 646, 653, 428, 379,
/* k = 16 */
274, 562, 232, 755, 599, 524, 801, 132, 295, 116, 442, 428, 295, 42, 176, 65,
/* k = 32 */
361, 575, 922, 525, 176, 586, 640, 321, 536, 742, 677, 742, 687, 284, 193, 517,
273, 494, 263, 147, 593, 800, 571, 320, 803, 133, 231, 390, 685, 330, 63, 410,
/* k = 64 */
539, 422, 6, 93, 862, 771, 453, 106, 610, 287, 107, 505, 733, 877, 381, 612,
723, 476, 462, 172, 430, 609, 858, 822, 543, 376, 511, 400, 672, 762, 283, 184,
440, 35, 519, 31, 460, 594, 225, 535, 517, 352, 605, 158, 651, 201, 488, 502,
648, 733, 717, 83, 404, 97, 280, 771, 840, 629, 4, 381, 843, 623, 264, 543,
/* k = 128 */
521, 310, 864, 547, 858, 580, 296, 379, 53, 779, 897, 444, 400, 925, 749, 415,
822, 93, 217, 208, 928, 244, 583, 620, 246, 148, 447, 631, 292, 908, 490, 704,
516, 258, 457, 907, 594, 723, 674, 292, 272, 96, 684, 432, 686, 606, 860, 569,
193, 219, 129, 186, 236, 287, 192, 775, 278, 173, 40, 379, 712, 463, 646, 776,
171, 491, 297, 763, 156, 732, 95, 270, 447, 90, 507, 48, 228, 821, 808, 898,
784, 663, 627, 378, 382, 262, 380, 602, 754, 336, 89, 614, 87, 432, 670, 616,
157, 374, 242, 726, 600, 269, 375, 898, 845, 454, 354, 130, 814, 587, 804, 34,
211, 330, 539, 297, 827, 865, 37, 517, 834, 315, 550, 86, 801, 4, 108, 539,
/* k = 256 */
524, 894, 75, 766, 882, 857, 74, 204, 82, 586, 708, 250, 905, 786, 138, 720,
858, 194, 311, 913, 275, 190, 375, 850, 438, 733, 194, 280, 201, 280, 828, 757,
710, 814, 919, 89, 68, 569, 11, 204, 796, 605, 540, 913, 801, 700, 799, 137,
439, 418, 592, 668, 353, 859, 370, 694, 325, 240, 216, 257, 284, 549, 209, 884,
315, 70, 329, 793, 490, 274, 877, 162, 749, 812, 684, 461, 334, 376, 849, 521,
307, 291, 803, 712, 19, 358, 399, 908, 103, 511, 51, 8, 517, 225, 289, 470,
637, 731, 66, 255, 917, 269, 463, 830, 730, 433, 848, 585, 136, 538, 906, 90,
2, 290, 743, 199, 655, 903, 329, 49, 802, 580, 355, 588, 188, 462, 10, 134,
628, 320, 479, 130, 739, 71, 263, 318, 374, 601, 192, 605, 142, 673, 687, 234,
722, 384, 177, 752, 607, 640, 455, 193, 689, 707, 805, 641, 48, 60, 732, 621,
895, 544, 261, 852, 655, 309, 697, 755, 756, 60, 231, 773, 434, 421, 726, 528,
503, 118, 49, 795, 32, 144, 500, 238, 836, 394, 280, 566, 319, 9, 647, 550,
73, 914, 342, 126, 32, 681, 331, 792, 620, 60, 609, 441, 180, 791, 893, 754,
605, 383, 228, 749, 760, 213, 54, 297, 134, 54, 834, 299, 922, 191, 910, 532,
609, 829, 189, 20, 167, 29, 872, 449, 83, 402, 41, 656, 505, 579, 481, 173,
404, 251, 688, 95, 497, 555, 642, 543, 307, 159, 924, 558, 648, 55, 497, 10,
/* k = 512 */
352, 77, 373, 504, 35, 599, 428, 207, 409, 574, 118, 498, 285, 380, 350, 492,
197, 265, 920, 155, 914, 299, 229, 643, 294, 871, 306, 88, 87, 193, 352, 781,
846, 75, 327, 520, 435, 543, 203, 666, 249, 346, 781, 621, 640, 268, 794, 534,
539, 781, 408, 390, 644, 102, 476, 499, 290, 632, 545, 37, 858, 916, 552, 41,
542, 289, 122, 272, 383, 800, 485, 98, 752, 472, 761, 107, 784, 860, 658, 741,
290, 204, 681, 407, 855, 85, 99, 62, 482, 180, 20, 297, 451, 593, 913, 142,
808, 684, 287, 536, 561, 76, 653, 899, 729, 567, 744, 390, 513, 192, 516, 258,
240, 518, 794, 395, 768, 848, 51, 610, 384, 168, 190, 826, 328, 596, 786, 303,
570, 381, 415, 641, 156, 237, 151, 429, 531, 207, 676, 710, 89, 168, 304, 402,
40, 708, 575, 162, 864, 229, 65, 861, 841, 512, 164, 477, 221, 92, 358, 785,
288, 357, 850, 836, 827, 736, 707, 94, 8, 494, 114, 521, 2, 499, 851, 543,
152, 729, 771, 95, 248, 361, 578, 323, 856, 797, 289, 51, 684, 466, 533, 820,
669, 45, 902, 452, 167, 342, 244, 173, 35, 463, 651, 51, 699, 591, 452, 578,
37, 124, 298, 332, 552, 43, 427, 119, 662, 777, 475, 850, 764, 364, 578, 911,
283, 711, 472, 420, 245, 288, 594, 394, 511, 327, 589, 777, 699, 688, 43, 408,
842, 383, 721, 521, 560, 644, 714, 559, 62, 145, 873, 663, 713, 159, 672, 729,
624, 59, 193, 417, 158, 209, 563, 564, 343, 693, 109, 608, 563, 365, 181, 772,
677, 310, 248, 353, 708, 410, 579, 870, 617, 841, 632, 860, 289, 536, 35, 777,
618, 586, 424, 833, 77, 597, 346, 269, 757, 632, 695, 751, 331, 247, 184, 45,
787, 680, 18, 66, 407, 369, 54, 492, 228, 613, 830, 922, 437, 519, 644, 905,
789, 420, 305, 441, 207, 300, 892, 827, 141, 537, 381, 662, 513, 56, 252, 341,
242, 797, 838, 837, 720, 224, 307, 631, 61, 87, 560, 310, 756, 665, 397, 808,
851, 309, 473, 795, 378, 31, 647, 915, 459, 806, 590, 731, 425, 216, 548, 249,
321, 881, 699, 535, 673, 782, 210, 815, 905, 303, 843, 922, 281, 73, 469, 791,
660, 162, 498, 308, 155, 422, 907, 817, 187, 62, 16, 425, 535, 336, 286, 437,
375, 273, 610, 296, 183, 923, 116, 667, 751, 353, 62, 366, 691, 379, 687, 842,
37, 357, 720, 742, 330, 5, 39, 923, 311, 424, 242, 749, 321, 54, 669, 316,
342, 299, 534, 105, 667, 488, 640, 672, 576, 540, 316, 486, 721, 610, 46, 656,
447, 171, 616, 464, 190, 531, 297, 321, 762, 752, 533, 175, 134, 14, 381, 433,
717, 45, 111, 20, 596, 284, 736, 138, 646, 411, 877, 669, 141, 919, 45, 780,
407, 164, 332, 899, 165, 726, 600, 325, 498, 655, 357, 752, 768, 223, 849, 647,
63, 310, 863, 251, 366, 304, 282, 738, 675, 410, 389, 244, 31, 121, 303, 263
};
INTERNAL_DATA const unsigned short pdf_bitpattern[2787] = {
0xEAE0, 0xF578, 0xFABE, 0xEA70, 0xF53C, 0xFA9F, 0xD460, 0xEA38, 0xD430, 0xA820,
0xD418, 0xA810, 0xD6E0, 0xEB78, 0xF5BE, 0xD670, 0xEB3C, 0xF59F, 0xAC60, 0xD638,
0xAC30, 0xAEE0, 0xD778, 0xEBBE, 0xAE70, 0xD73C, 0xEB9F, 0xAE38, 0xD71E, 0xAF78,
0xD7BE, 0xAF3C, 0xD79F, 0xAFBE, 0xFAFD, 0xE970, 0xF4BC, 0xFA5F, 0xD260, 0xE938,
0xF49E, 0xD230, 0xE91C, 0xA420, 0xD218, 0xE90E, 0xA410, 0xD20C, 0xA408, 0xD370,
0xE9BC, 0xF4DF, 0xA660, 0xD338, 0xE99E, 0xA630, 0xD31C, 0xE98F, 0xA618, 0xD30E,
0xA770, 0xD3BC, 0xE9DF, 0xA738, 0xD39E, 0xA71C, 0xD38F, 0xA7BC, 0xD3DF, 0xA79E,
0xA78F, 0xD160, 0xE8B8, 0xF45E, 0xD130, 0xE89C, 0xF44F, 0xA220, 0xD118, 0xE88E,
0xA210, 0xD10C, 0xA208, 0xA204, 0xA360, 0xD1B8, 0xE8DE, 0xA330, 0xD19C, 0xE8CF,
0xA318, 0xD18E, 0xA30C, 0xA306, 0xA3B8, 0xD1DE, 0xA39C, 0xD1CF, 0xA38E, 0xA3DE,
0xD0B0, 0xE85C, 0xF42F, 0xA120, 0xD098, 0xE84E, 0xA110, 0xD08C, 0xE847, 0xA108,
0xD086, 0xA104, 0xD083, 0xA1B0, 0xD0DC, 0xE86F, 0xA198, 0xD0CE, 0xA18C, 0xD0C7,
0xA186, 0xA183, 0xD0EF, 0xA1C7, 0xA0A0, 0xD058, 0xE82E, 0xA090, 0xD04C, 0xE827,
0xA088, 0xD046, 0xA084, 0xD043, 0xA082, 0xA0D8, 0xA0CC, 0xA0C6, 0xA050, 0xE817,
0xD026, 0xD023, 0xA041, 0xE570, 0xF2BC, 0xF95F, 0xCA60, 0xE538, 0xF29E, 0xCA30,
0xE51C, 0xF28F, 0x9420, 0xCA18, 0x9410, 0xCB70, 0xE5BC, 0xF2DF, 0x9660, 0xCB38,
0xE59E, 0x9630, 0xCB1C, 0x9618, 0x960C, 0x9770, 0xCBBC, 0xE5DF, 0x9738, 0xCB9E,
0x971C, 0x970E, 0x97BC, 0xCBDF, 0x979E, 0x97DF, 0xED60, 0xF6B8, 0xFB5E, 0xED30,
0xF69C, 0xFB4F, 0xDA20, 0xED18, 0xF68E, 0xDA10, 0xED0C, 0xF687, 0xDA08, 0xED06,
0xC960, 0xE4B8, 0xF25E, 0xDB60, 0xC930, 0xE49C, 0xF24F, 0xDB30, 0xED9C, 0xF6CF,
0xB620, 0x9210, 0xC90C, 0xE487, 0xB610, 0xDB0C, 0xB608, 0x9360, 0xC9B8, 0xE4DE,
0xB760, 0x9330, 0xC99C, 0xE4CF, 0xB730, 0xDB9C, 0xEDCF, 0xB718, 0x930C, 0xB70C,
0x93B8, 0xC9DE, 0xB7B8, 0x939C, 0xC9CF, 0xB79C, 0xDBCF, 0xB78E, 0x93DE, 0xB7DE,
0x93CF, 0xB7CF, 0xECB0, 0xF65C, 0xFB2F, 0xD920, 0xEC98, 0xF64E, 0xD910, 0xEC8C,
0xF647, 0xD908, 0xEC86, 0xD904, 0xD902, 0xC8B0, 0xE45C, 0xF22F, 0xD9B0, 0xC898,
0xE44E, 0xB320, 0x9110, 0xECCE, 0xE447, 0xB310, 0x9108, 0xC886, 0xB308, 0xD986,
0xC883, 0x9102, 0x91B0, 0xC8DC, 0xE46F, 0xB3B0, 0x9198, 0xC8CE, 0xB398, 0xD9CE,
0xC8C7, 0xB38C, 0x9186, 0x9183, 0x91DC, 0xC8EF, 0xB3DC, 0x91CE, 0xB3CE, 0x91C7,
0xB3C7, 0xB3EF, 0xD8A0, 0xEC58, 0xF62E, 0xD890, 0xEC4C, 0xF627, 0xD888, 0xEC46,
0xD884, 0xEC43, 0xD882, 0xD881, 0x90A0, 0xC858, 0xE42E, 0xB1A0, 0x9090, 0xC84C,
0xE427, 0xB190, 0xD8CC, 0xEC67, 0xB188, 0x9084, 0xC843, 0xB184, 0xD8C3, 0xB182,
0x90D8, 0xC86E, 0xB1D8, 0x90CC, 0xC867, 0xB1CC, 0xD8E7, 0xB1C6, 0x90C3, 0xB1C3,
0xB1EE, 0xB1E7, 0xD850, 0xEC2C, 0xF617, 0xD848, 0xEC26, 0xD844, 0xEC23, 0xD842,
0xD841, 0x9050, 0xC82C, 0xE417, 0xB0D0, 0x9048, 0xC826, 0xB0C8, 0xD866, 0xC823,
0xB0C4, 0x9042, 0xB0C2, 0x9041, 0x906C, 0xB0EC, 0xB0E6, 0xB0E3, 0xEC16, 0xEC13,
0xD821, 0xC816, 0x9024, 0xB064, 0xB062, 0xB061, 0xC560, 0xE2B8, 0xF15E, 0xC530,
0xE29C, 0x8A20, 0xC518, 0xE28E, 0x8A10, 0xC50C, 0x8A08, 0x8A04, 0x8B60, 0xC5B8,
0xE2DE, 0x8B30, 0xC59C, 0xE2CF, 0x8B18, 0xC58E, 0x8B0C, 0x8B06, 0x8BB8, 0xC5DE,
0x8B9C, 0xC5CF, 0x8B8E, 0x8BDE, 0x8BCF, 0xE6B0, 0xF35C, 0xF9AF, 0xCD20, 0xE698,
0xF34E, 0xCD10, 0xE68C, 0xF347, 0xCD08, 0xE686, 0xCD04, 0xE683, 0xC4B0, 0xE25C,
0xF12F, 0xCDB0, 0xC498, 0xE24E, 0x9B20, 0x8910, 0xE6CE, 0xE247, 0x9B10, 0xCD8C,
0xC486, 0x9B08, 0x8904, 0x9B04, 0x89B0, 0xC4DC, 0xE26F, 0x9BB0, 0x8998, 0xE6EF,
0x9B98, 0xCDCE, 0xC4C7, 0x9B8C, 0x8986, 0x9B86, 0x89DC, 0xC4EF, 0x9BDC, 0x89CE,
0x9BCE, 0x89C7, 0x89EF, 0x9BEF, 0xEEA0, 0xF758, 0xFBAE, 0xEE90, 0xF74C, 0xFBA7,
0xEE88, 0xF746, 0xEE84, 0xF743, 0xEE82, 0xCCA0, 0xE658, 0xF32E, 0xDDA0, 0xCC90,
0xF76E, 0xF327, 0xDD90, 0xEECC, 0xF767, 0xDD88, 0xCC84, 0xE643, 0xDD84, 0xEEC3,
0xCC81, 0x88A0, 0xC458, 0xE22E, 0x99A0, 0x8890, 0xC44C, 0xE227, 0xBBA0, 0x9990,
0xCCCC, 0xE667, 0xBB90, 0xDDCC, 0xEEE7, 0xC443, 0xBB88, 0x9984, 0xCCC3, 0xBB84,
0x8881, 0x88D8, 0xC46E, 0x99D8, 0x88CC, 0xC467, 0xBBD8, 0x99CC, 0xCCE7, 0xBBCC,
0xDDE7, 0x88C3, 0x99C3, 0x88EE, 0x99EE, 0x88E7, 0xBBEE, 0x99E7, 0xEE50, 0xF72C,
0xFB97, 0xEE48, 0xF726, 0xEE44, 0xF723, 0xEE42, 0xEE41, 0xCC50, 0xE62C, 0xF317,
0xDCD0, 0xCC48, 0xF737, 0xDCC8, 0xEE66, 0xE623, 0xDCC4, 0xCC42, 0xDCC2, 0xCC41,
0xDCC1, 0x8850, 0xC42C, 0xE217, 0x98D0, 0x8848, 0xC426, 0xB9D0, 0x98C8, 0xCC66,
0xC423, 0xB9C8, 0xDCE6, 0x8842, 0xB9C4, 0x98C2, 0x8841, 0x98C1, 0x886C, 0xC437,
0x98EC, 0x8866, 0xB9EC, 0x98E6, 0x8863, 0xB9E6, 0x98E3, 0x8877, 0xB9F7, 0xEE28,
0xF716, 0xEE24, 0xF713, 0xEE22, 0xEE21, 0xCC28, 0xE616, 0xDC68, 0xCC24, 0xE613,
0xDC64, 0xEE33, 0xDC62, 0xCC21, 0xDC61, 0x8828, 0xC416, 0x9868, 0x8824, 0xC413,
0xB8E8, 0x9864, 0xCC33, 0xB8E4, 0xDC73, 0x8821, 0xB8E2, 0x9861, 0xB8E1, 0x9876,
0xB8F6, 0xB8F3, 0xF70B, 0xEE11, 0xE60B, 0xCC12, 0xCC11, 0x8814, 0x9834, 0xB874,
0x8811, 0x9831, 0xC2B0, 0x8520, 0xC298, 0x8510, 0xC28C, 0xE147, 0x8508, 0xC286,
0x8504, 0xC283, 0x85B0, 0xC2DC, 0xE16F, 0x8598, 0xC2CE, 0x858C, 0xC2C7, 0x8586,
0x8583, 0x85DC, 0xC2EF, 0x85CE, 0x85C7, 0x85EF, 0xC6A0, 0xE358, 0xF1AE, 0xC690,
0xE34C, 0xC688, 0xE346, 0xC684, 0xE343, 0xC682, 0x84A0, 0xC258, 0xE12E, 0x8DA0,
0x8490, 0xE36E, 0xE127, 0x8D90, 0xC6CC, 0xE367, 0x8D88, 0x8484, 0xC243, 0x8D84,
0xC6C3, 0x8481, 0x84D8, 0xC26E, 0x8DD8, 0x84CC, 0xC267, 0x8DCC, 0xC6E7, 0x8DC6,
0x84C3, 0x84EE, 0x8DEE, 0x84E7, 0x8DE7, 0xE750, 0xF3AC, 0xF9D7, 0xE748, 0xF3A6,
0xE744, 0xF3A3, 0xE742, 0xE741, 0xC650, 0xE32C, 0xCED0, 0xC648, 0xE326, 0xCEC8,
0xE766, 0xE323, 0xCEC4, 0xC642, 0xCEC2, 0xC641, 0xCEC1, 0x8450, 0xC22C, 0x8CD0,
0x8448, 0xE337, 0x9DD0, 0x8CC8, 0xC666, 0xC223, 0x9DC8, 0xCEE6, 0x8442, 0x9DC4,
0x8CC2, 0x8441, 0x8CC1, 0x846C, 0xC237, 0x8CEC, 0x8466, 0x9DEC, 0x8CE6, 0x8463,
0x9DE6, 0x8CE3, 0x8477, 0x8CF7, 0x9DF7, 0xF7A8, 0xFBD6, 0xF7A4, 0xFBD3, 0xF7A2,
0xF7A1, 0xE728, 0xF396, 0xEF68, 0xF7B6, 0xF393, 0xEF64, 0xF7B3, 0xEF62, 0xE721,
0xEF61, 0xC628, 0xE316, 0xCE68, 0xC624, 0xE313, 0xDEE8, 0xCE64, 0xE733, 0xDEE4,
0xEF73, 0xC621, 0xDEE2, 0xCE61, 0xDEE1, 0x8428, 0xC216, 0x8C68, 0x8424, 0xC213,
0x9CE8, 0x8C64, 0xC633, 0xBDE8, 0x9CE4, 0xCE73, 0x8421, 0xBDE4, 0xDEF3, 0x8C61,
0xBDE2, 0x8436, 0x8C76, 0x8433, 0x9CF6, 0x8C73, 0xBDF6, 0x9CF3, 0xBDF3, 0xF794,
0xFBCB, 0xF792, 0xF791, 0xE714, 0xF38B, 0xEF34, 0xF79B, 0xEF32, 0xE711, 0xEF31,
0xC614, 0xE30B, 0xCE34, 0xC612, 0xDE74, 0xCE32, 0xC611, 0xDE72, 0xCE31, 0xDE71,
0x8414, 0xC20B, 0x8C34, 0xC61B, 0x9C74, 0x8C32, 0x8411, 0xBCF4, 0x9C72, 0x8C31,
0xBCF2, 0x9C71, 0xBCF1, 0x8C3B, 0xBCFB, 0xF789, 0xEF1A, 0xEF19, 0xCE1A, 0xDE3A,
0xDE39, 0x8C1A, 0x9C3A, 0xBC7A, 0xBC79, 0x82A0, 0x8290, 0xC14C, 0x8288, 0x8284,
0x8282, 0x82D8, 0x82CC, 0x82C6, 0x82C3, 0x82EE, 0x82E7, 0xC350, 0xC348, 0xE1A6,
0xC344, 0xE1A3, 0xC342, 0xC341, 0x8250, 0xC12C, 0x86D0, 0xC36C, 0xC126, 0x86C8,
0xC366, 0x86C4, 0xC363, 0x86C2, 0x8241, 0x86C1, 0x826C, 0xC137, 0x86EC, 0xC377,
0x86E6, 0x8263, 0x86E3, 0x8277, 0x86F7, 0xE3A8, 0xE3A4, 0xE3A2, 0xE3A1, 0xC328,
0xC768, 0xE3B6, 0xE193, 0xC764, 0xE3B3, 0xC762, 0xC321, 0xC761, 0x8228, 0x8668,
0x8224, 0xC113, 0x8EE8, 0x8664, 0x8222, 0x8EE4, 0x8662, 0x8221, 0x8EE2, 0x8661,
0x8236, 0x8676, 0x8233, 0x8EF6, 0x8673, 0x8EF3, 0xF3D4, 0xF3D2, 0xF3D1, 0xE394,
0xE7B4, 0xF3DB, 0xE7B2, 0xE391, 0xE7B1, 0xC314, 0xE18B, 0xC734, 0xE39B, 0xCF74,
0xC732, 0xC311, 0xCF72, 0xC731, 0xCF71, 0x8214, 0xC10B, 0x8634, 0xC31B, 0x8E74,
0x8632, 0x8211, 0x9EF4, 0x8E72, 0x8631, 0x9EF2, 0x8E71, 0x821B, 0x863B, 0x8E7B,
0x9EFB, 0xFBEA, 0xFBE9, 0xF3CA, 0xF7DA, 0xF3C9, 0xF7D9, 0xE38A, 0xE79A, 0xE389,
0xEFBA, 0xE799, 0xEFB9, 0xC30A, 0xC71A, 0xC309, 0xCF3A, 0xC719, 0xDF7A, 0xFAB0,
0xFD5C, 0xF520, 0xFA98, 0xFD4E, 0xF510, 0xFA8C, 0xFD47, 0xF508, 0xFA86, 0xF504,
0xFA83, 0xF502, 0xF5B0, 0xFADC, 0xFD6F, 0xEB20, 0xF598, 0xFACE, 0xEB10, 0xF58C,
0xFAC7, 0xEB08, 0xF586, 0xEB04, 0xF583, 0xEB02, 0xEBB0, 0xF5DC, 0xFAEF, 0xD720,
0xEB98, 0xF5CE, 0xD710, 0xEB8C, 0xF5C7, 0xD708, 0xEB86, 0xD704, 0xEB83, 0xD702,
0xD7B0, 0xEBDC, 0xF5EF, 0xAF20, 0xD798, 0xEBCE, 0xAF10, 0xD78C, 0xEBC7, 0xAF08,
0xD786, 0xAF04, 0xD783, 0xAFB0, 0xD7DC, 0xEBEF, 0xAF98, 0xD7CE, 0xAF8C, 0xD7C7,
0xAF86, 0xAFDC, 0xD7EF, 0xAFCE, 0xAFC7, 0xF4A0, 0xFA58, 0xFD2E, 0xF490, 0xFA4C,
0xFD27, 0xF488, 0xFA46, 0xF484, 0xFA43, 0xF482, 0xF481, 0xE9A0, 0xF4D8, 0xFA6E,
0xE990, 0xF4CC, 0xFA67, 0xE988, 0xF4C6, 0xE984, 0xF4C3, 0xE982, 0xE981, 0xD3A0,
0xE9D8, 0xF4EE, 0xD390, 0xE9CC, 0xF4E7, 0xD388, 0xE9C6, 0xD384, 0xE9C3, 0xD382,
0xD381, 0xA7A0, 0xD3D8, 0xE9EE, 0xA790, 0xD3CC, 0xE9E7, 0xA788, 0xD3C6, 0xA784,
0xD3C3, 0xA782, 0xA7D8, 0xD3EE, 0xA7CC, 0xD3E7, 0xA7C6, 0xA7C3, 0xA7EE, 0xA7E7,
0xF450, 0xFA2C, 0xFD17, 0xF448, 0xFA26, 0xF444, 0xFA23, 0xF442, 0xF441, 0xE8D0,
0xF46C, 0xFA37, 0xE8C8, 0xF466, 0xE8C4, 0xF463, 0xE8C2, 0xE8C1, 0xD1D0, 0xE8EC,
0xF477, 0xD1C8, 0xE8E6, 0xD1C4, 0xE8E3, 0xD1C2, 0xD1C1, 0xA3D0, 0xD1EC, 0xE8F7,
0xA3C8, 0xD1E6, 0xA3C4, 0xD1E3, 0xA3C2, 0xA3C1, 0xA3EC, 0xD1F7, 0xA3E6, 0xA3E3,
0xA3F7, 0xF428, 0xFA16, 0xF424, 0xFA13, 0xF422, 0xF421, 0xE868, 0xF436, 0xE864,
0xF433, 0xE862, 0xE861, 0xD0E8, 0xE876, 0xD0E4, 0xE873, 0xD0E2, 0xD0E1, 0xA1E8,
0xD0F6, 0xA1E4, 0xD0F3, 0xA1E2, 0xA1E1, 0xA1F6, 0xA1F3, 0xF414, 0xFA0B, 0xF412,
0xF411, 0xE834, 0xF41B, 0xE832, 0xE831, 0xD074, 0xE83B, 0xD072, 0xD071, 0xA0F4,
0xD07B, 0xA0F2, 0xA0F1, 0xF40A, 0xF409, 0xE81A, 0xE819, 0xD03A, 0xD039, 0xF2A0,
0xF958, 0xFCAE, 0xF290, 0xF94C, 0xFCA7, 0xF288, 0xF946, 0xF284, 0xF943, 0xF282,
0xF281, 0xE5A0, 0xF2D8, 0xF96E, 0xE590, 0xF2CC, 0xF967, 0xE588, 0xF2C6, 0xE584,
0xF2C3, 0xE582, 0xE581, 0xCBA0, 0xE5D8, 0xF2EE, 0xCB90, 0xE5CC, 0xF2E7, 0xCB88,
0xE5C6, 0xCB84, 0xE5C3, 0xCB82, 0xCB81, 0x97A0, 0xCBD8, 0xE5EE, 0x9790, 0xCBCC,
0xE5E7, 0x9788, 0xCBC6, 0x9784, 0xCBC3, 0x9782, 0x97D8, 0xCBEE, 0x97CC, 0xCBE7,
0x97C6, 0x97C3, 0x97EE, 0x97E7, 0xFB50, 0xFDAC, 0xB5F8, 0xFB48, 0xFDA6, 0xB4FC,
0xFB44, 0xFDA3, 0xB47E, 0xFB42, 0xFB41, 0xF250, 0xF92C, 0xFC97, 0xF6D0, 0xF248,
0xFDB7, 0xF6C8, 0xFB66, 0xF923, 0xF6C4, 0xF242, 0xF6C2, 0xF241, 0xF6C1, 0xE4D0,
0xF26C, 0xF937, 0xEDD0, 0xE4C8, 0xF266, 0xEDC8, 0xF6E6, 0xF263, 0xEDC4, 0xE4C2,
0xEDC2, 0xE4C1, 0xEDC1, 0xC9D0, 0xE4EC, 0xF277, 0xDBD0, 0xC9C8, 0xE4E6, 0xDBC8,
0xEDE6, 0xE4E3, 0xDBC4, 0xC9C2, 0xDBC2, 0xC9C1, 0xDBC1, 0x93D0, 0xC9EC, 0xE4F7,
0xB7D0, 0x93C8, 0xC9E6, 0xB7C8, 0xDBE6, 0xC9E3, 0xB7C4, 0x93C2, 0xB7C2, 0x93C1,
0x93EC, 0xC9F7, 0xB7EC, 0x93E6, 0xB7E6, 0x93E3, 0xB7E3, 0x93F7, 0xFB28, 0xFD96,
0xB2FC, 0xFB24, 0xFD93, 0xB27E, 0xFB22, 0xB23F, 0xFB21, 0xF228, 0xF916, 0xF668,
0xF224, 0xF913, 0xF664, 0xFB33, 0xF662, 0xF221, 0xF661, 0xE468, 0xF236, 0xECE8,
0xE464, 0xF233, 0xECE4, 0xF673, 0xECE2, 0xE461, 0xECE1, 0xC8E8, 0xE476, 0xD9E8,
0xC8E4, 0xE473, 0xD9E4, 0xECF3, 0xD9E2, 0xC8E1, 0xD9E1, 0x91E8, 0xC8F6, 0xB3E8,
0x91E4, 0xC8F3, 0xB3E4, 0xD9F3, 0xB3E2, 0x91E1, 0xB3E1, 0x91F6, 0xB3F6, 0x91F3,
0xB3F3, 0xFB14, 0xFD8B, 0xB17E, 0xFB12, 0xB13F, 0xFB11, 0xF214, 0xF90B, 0xF634,
0xFB1B, 0xF632, 0xF211, 0xF631, 0xE434, 0xF21B, 0xEC74, 0xE432, 0xEC72, 0xE431,
0xEC71, 0xC874, 0xE43B, 0xD8F4, 0xEC7B, 0xD8F2, 0xC871, 0xD8F1, 0x90F4, 0xC87B,
0xB1F4, 0x90F2, 0xB1F2, 0x90F1, 0xB1F1, 0x90FB, 0xB1FB, 0xFB0A, 0xB0BF, 0xFB09,
0xF20A, 0xF61A, 0xF209, 0xF619, 0xE41A, 0xEC3A, 0xE419, 0xEC39, 0xC83A, 0xD87A,
0xC839, 0xD879, 0x907A, 0xB0FA, 0x9079, 0xB0F9, 0xFB05, 0xF205, 0xF60D, 0xE40D,
0xEC1D, 0xC81D, 0xD83D, 0xF150, 0xF8AC, 0xFC57, 0xF148, 0xF8A6, 0xF144, 0xF8A3,
0xF142, 0xF141, 0xE2D0, 0xF16C, 0xF8B7, 0xE2C8, 0xF166, 0xE2C4, 0xF163, 0xE2C2,
0xE2C1, 0xC5D0, 0xE2EC, 0xF177, 0xC5C8, 0xE2E6, 0xC5C4, 0xE2E3, 0xC5C2, 0xC5C1,
0x8BD0, 0xC5EC, 0xE2F7, 0x8BC8, 0xC5E6, 0x8BC4, 0xC5E3, 0x8BC2, 0x8BC1, 0x8BEC,
0xC5F7, 0x8BE6, 0x8BE3, 0x8BF7, 0xF9A8, 0xFCD6, 0x9AFC, 0xF9A4, 0xFCD3, 0x9A7E,
0xF9A2, 0x9A3F, 0xF9A1, 0xF128, 0xF896, 0xF368, 0xF124, 0xF893, 0xF364, 0xF9B3,
0xF362, 0xF121, 0xF361, 0xE268, 0xF136, 0xE6E8, 0xE264, 0xF133, 0xE6E4, 0xF373,
0xE6E2, 0xE261, 0xE6E1, 0xC4E8, 0xE276, 0xCDE8, 0xC4E4, 0xE273, 0xCDE4, 0xE6F3,
0xCDE2, 0xC4E1, 0xCDE1, 0x89E8, 0xC4F6, 0x9BE8, 0x89E4, 0xC4F3, 0x9BE4, 0xCDF3,
0x9BE2, 0x89E1, 0x9BE1, 0x89F6, 0x9BF6, 0x89F3, 0x9BF3, 0xFDD4, 0xBAF8, 0xDD7E,
0xFDD2, 0xBA7C, 0xDD3F, 0xFDD1, 0xBA3E, 0xBA1F, 0xF994, 0xFCCB, 0x997E, 0xFBB4,
0xFDDB, 0xBB7E, 0x993F, 0xFBB2, 0xF991, 0xBB3F, 0xFBB1, 0xF114, 0xF88B, 0xF334,
0xF112, 0xF774, 0xFBBB, 0xF111, 0xF772, 0xF331, 0xF771, 0xE234, 0xF11B, 0xE674,
0xE232, 0xEEF4, 0xE672, 0xE231, 0xEEF2, 0xE671, 0xEEF1, 0xC474, 0xE23B, 0xCCF4,
0xC472, 0xDDF4, 0xCCF2, 0xC471, 0xDDF2, 0xCCF1, 0xDDF1, 0x88F4, 0xC47B, 0x99F4,
0x88F2, 0xBBF4, 0x99F2, 0x88F1, 0xBBF2, 0x99F1, 0xBBF1, 0x88FB, 0x99FB, 0xFDCA,
0xB97C, 0xDCBF, 0xFDC9, 0xB93E, 0xB91F, 0xF98A, 0x98BF, 0xFB9A, 0xF989, 0xB9BF,
0xFB99, 0xF10A, 0xF31A, 0xF109, 0xF73A, 0xF319, 0xF739, 0xE21A, 0xE63A, 0xE219,
0xEE7A, 0xE639, 0xEE79, 0xC43A, 0xCC7A, 0xC439, 0xDCFA, 0xCC79, 0xDCF9, 0x887A,
0x98FA, 0x8879, 0xB9FA, 0x98F9, 0xB9F9, 0xFDC5, 0xB8BE, 0xB89F, 0xF985, 0xFB8D,
0xF105, 0xF30D, 0xF71D, 0xE20D, 0xE61D, 0xEE3D, 0xC41D, 0xCC3D, 0xDC7D, 0x883D,
0x987D, 0xB8FD, 0xB85F, 0xF0A8, 0xF856, 0xF0A4, 0xF853, 0xF0A2, 0xF0A1, 0xE168,
0xF0B6, 0xE164, 0xF0B3, 0xE162, 0xE161, 0xC2E8, 0xE176, 0xC2E4, 0xE173, 0xC2E2,
0xC2E1, 0x85E8, 0xC2F6, 0x85E4, 0xC2F3, 0x85E2, 0x85E1, 0x85F6, 0x85F3, 0xF8D4,
0xFC6B, 0x8D7E, 0xF8D2, 0x8D3F, 0xF8D1, 0xF094, 0xF84B, 0xF1B4, 0xF092, 0xF1B2,
0xF091, 0xF1B1, 0xE134, 0xF09B, 0xE374, 0xE132, 0xE372, 0xE131, 0xE371, 0xC274,
0xE13B, 0xC6F4, 0xC272, 0xC6F2, 0xC271, 0xC6F1, 0x84F4, 0xC27B, 0x8DF4, 0x84F2,
0x8DF2, 0x84F1, 0x8DF1, 0x84FB, 0x8DFB, 0xFCEA, 0x9D7C, 0xCEBF, 0xFCE9, 0x9D3E,
0x9D1F, 0xF8CA, 0x8CBF, 0xF9DA, 0xF8C9, 0x9DBF, 0xF9D9, 0xF08A, 0xF19A, 0xF089,
0xF3BA, 0xF199, 0xF3B9, 0xE11A, 0xE33A, 0xE119, 0xE77A, 0xE339, 0xE779, 0xC23A,
0xC67A, 0xC239, 0xCEFA, 0xC679, 0xCEF9, 0x847A, 0x8CFA, 0x8479, 0x9DFA, 0x8CF9,
0x9DF9, 0xBD78, 0xDEBE, 0xBD3C, 0xDE9F, 0xBD1E, 0xBD0F, 0xFCE5, 0x9CBE, 0xFDED,
0xBDBE, 0x9C9F, 0xBD9F, 0xF8C5, 0xF9CD, 0xFBDD, 0xF085, 0xF18D, 0xF39D, 0xF7BD,
0xE10D, 0xE31D, 0xE73D, 0xEF7D, 0xC21D, 0xC63D, 0xCE7D, 0xDEFD, 0x843D, 0x8C7D,
0x9CFD, 0xBCBC, 0xDE5F, 0xBC9E, 0xBC8F, 0x9C5F, 0xBCDF, 0xBC5E, 0xBC4F, 0xBC2F,
0xF054, 0xF052, 0xF051, 0xE0B4, 0xF05B, 0xE0B2, 0xE0B1, 0xC174, 0xE0BB, 0xC172,
0xC171, 0x82F4, 0xC17B, 0x82F2, 0x82F1, 0x82FB, 0xF86A, 0x86BF, 0xF869, 0xF04A,
0xF0DA, 0xF049, 0xF0D9, 0xE09A, 0xE1BA, 0xE099, 0xE1B9, 0xC13A, 0xC37A, 0xC139,
0xC379, 0x827A, 0x86FA, 0x8279, 0x86F9, 0xFC75, 0x8EBE, 0x8E9F, 0xF865, 0xF8ED,
0xF045, 0xF0CD, 0xF1DD, 0xE08D, 0xE19D, 0xE3BD, 0xC11D, 0xC33D, 0xC77D, 0x823D,
0x867D, 0x8EFD, 0x9EBC, 0xCF5F, 0x9E9E, 0x9E8F, 0x8E5F, 0x9EDF, 0xBEB8, 0xDF5E,
0xBE9C, 0xDF4F, 0xBE8E, 0xBE87, 0x9E5E, 0xBEDE, 0x9E4F, 0xBECF, 0xBE5C, 0xDF2F,
0xBE4E, 0xBE47, 0x9E2F, 0xBE6F, 0xBE2E, 0xBE27, 0xBE17, 0xE05A, 0xE059, 0xC0BA,
0xC0B9, 0x817A, 0x8179, 0xF06D, 0xE04D, 0xE0DD, 0xC09D, 0xC1BD, 0x813D, 0x837D,
0x875F, 0x8F5E, 0x8F4F, 0x9F5C, 0xCFAF, 0x9F4E, 0x9F47, 0x8F2F, 0x9F6F, 0xBF58,
0xDFAE, 0xBF4C, 0xDFA7, 0xBF46, 0xBF43, 0x9F2E, 0xBF6E, 0x9F27, 0xBF67, 0xBF2C,
0xDF97, 0xBF26, 0xBF23, 0x9F17, 0xBF37, 0xBF16, 0xBF13, 0x87AF, 0x8FAE, 0x8FA7,
0x9FAC, 0xCFD7, 0x9FA6, 0x9FA3, 0x8F97, 0x9FB7, 0x9F96, 0x9F93, 0xD5F0, 0xEAFC,
0xA9E0, 0xD4F8, 0xEA7E, 0xA8F0, 0xD47C, 0xEA3F, 0xA878, 0xD43E, 0xA83C, 0xFD68,
0xADF0, 0xD6FC, 0xFD64, 0xACF8, 0xD67E, 0xFD62, 0xAC7C, 0xD63F, 0xFD61, 0xAC3E,
0xFAE8, 0xFD76, 0xAEFC, 0xFAE4, 0xFD73, 0xAE7E, 0xFAE2, 0xAE3F, 0xFAE1, 0xF5E8,
0xFAF6, 0xF5E4, 0xFAF3, 0xF5E2, 0xF5E1, 0xEBE8, 0xF5F6, 0xEBE4, 0xF5F3, 0xEBE2,
0xEBE1, 0xD7E8, 0xEBF6, 0xD7E4, 0xEBF3, 0xD7E2, 0xA5E0, 0xD2F8, 0xE97E, 0xA4F0,
0xD27C, 0xE93F, 0xA478, 0xD23E, 0xA43C, 0xD21F, 0xA41E, 0xFD34, 0xA6F8, 0xD37E,
0xFD32, 0xA67C, 0xD33F, 0xFD31, 0xA63E, 0xA61F, 0xFA74, 0xFD3B, 0xA77E, 0xFA72,
0xA73F, 0xFA71, 0xF4F4, 0xFA7B, 0xF4F2, 0xF4F1, 0xE9F4, 0xF4FB, 0xE9F2, 0xE9F1,
0xD3F4, 0xE9FB, 0xD3F2, 0xD3F1, 0xA2F0, 0xD17C, 0xE8BF, 0xA278, 0xD13E, 0xA23C,
0xD11F, 0xA21E, 0xA20F, 0xFD1A, 0xA37C, 0xD1BF, 0xFD19, 0xA33E, 0xA31F, 0xFA3A,
0xA3BF, 0xFA39, 0xF47A, 0xF479, 0xE8FA, 0xE8F9, 0xD1FA, 0xD1F9, 0xA178, 0xD0BE,
0xA13C, 0xD09F, 0xA11E, 0xA10F, 0xFD0D, 0xA1BE, 0xA19F, 0xFA1D, 0xF43D, 0xE87D,
0xA0BC, 0xD05F, 0xA09E, 0xA08F, 0xA0DF, 0xA05E, 0xA04F, 0x95E0, 0xCAF8, 0xE57E,
0x94F0, 0xCA7C, 0xE53F, 0x9478, 0xCA3E, 0x943C, 0xCA1F, 0x941E, 0xFCB4, 0x96F8,
0xCB7E, 0xFCB2, 0x967C, 0xCB3F, 0xFCB1, 0x963E, 0x961F, 0xF974, 0xFCBB, 0x977E,
0xF972, 0x973F, 0xF971, 0xF2F4, 0xF97B, 0xF2F2, 0xF2F1, 0xE5F4, 0xF2FB, 0xE5F2,
0xE5F1, 0xCBF4, 0xE5FB, 0xCBF2, 0xCBF1, 0xDAF0, 0xED7C, 0xF6BF, 0xB4E0, 0xDA78,
0xED3E, 0xB470, 0xDA3C, 0xED1F, 0xB438, 0xDA1E, 0xB41C, 0xDA0F, 0xB40E, 0x92F0,
0xC97C, 0xE4BF, 0xB6F0, 0x9278, 0xC93E, 0xB678, 0xDB3E, 0xC91F, 0xB63C, 0x921E,
0xB61E, 0x920F, 0xB60F, 0xFC9A, 0x937C, 0xC9BF, 0xFDBA, 0xFC99, 0xB77C, 0x933E,
0xFDB9, 0xB73E, 0x931F, 0xB71F, 0xF93A, 0x93BF, 0xFB7A, 0xF939, 0xB7BF, 0xFB79,
0xF27A, 0xF6FA, 0xF279, 0xF6F9, 0xE4FA, 0xEDFA, 0xE4F9, 0xEDF9, 0xC9FA, 0xC9F9,
0xB2E0, 0xD978, 0xECBE, 0xB270, 0xD93C, 0xEC9F, 0xB238, 0xD91E, 0xB21C, 0xD90F,
0xB20E, 0xB207, 0x9178, 0xC8BE, 0xB378, 0x913C, 0xC89F, 0xB33C, 0xD99F, 0xB31E,
0x910F, 0xB30F, 0xFC8D, 0x91BE, 0xFD9D, 0xB3BE, 0x919F, 0xB39F, 0xF91D, 0xFB3D,
0xF23D, 0xF67D, 0xE47D, 0xECFD, 0xC8FD, 0xB170, 0xD8BC, 0xEC5F, 0xB138, 0xD89E,
0xB11C, 0xD88F, 0xB10E, 0xB107, 0x90BC, 0xC85F, 0xB1BC, 0x909E, 0xB19E, 0x908F,
0xB18F, 0x90DF, 0xB1DF, 0xB0B8, 0xD85E, 0xB09C, 0xD84F, 0xB08E, 0xB087, 0x905E,
0xB0DE, 0x904F, 0xB0CF, 0xB05C, 0xD82F, 0xB04E, 0xB047, 0x902F, 0xB06F, 0xB02E,
0xB027, 0x8AF0, 0xC57C, 0xE2BF, 0x8A78, 0xC53E, 0x8A3C, 0xC51F, 0x8A1E, 0x8A0F,
0xFC5A, 0x8B7C, 0xC5BF, 0xFC59, 0x8B3E, 0x8B1F, 0xF8BA, 0x8BBF, 0xF8B9, 0xF17A,
0xF179, 0xE2FA, 0xE2F9, 0xC5FA, 0xC5F9, 0x9AE0, 0xCD78, 0xE6BE, 0x9A70, 0xCD3C,
0xE69F, 0x9A38, 0xCD1E, 0x9A1C, 0xCD0F, 0x9A0E, 0x9A07, 0x8978, 0xC4BE, 0x9B78,
0x893C, 0xC49F, 0x9B3C, 0xCD9F, 0x9B1E, 0x890F, 0x9B0F, 0xFC4D, 0x89BE, 0xFCDD,
0x9BBE, 0x899F, 0x9B9F, 0xF89D, 0xF9BD, 0xF13D, 0xF37D, 0xE27D, 0xE6FD, 0xC4FD,
0xDD70, 0xEEBC, 0xF75F, 0xBA60, 0xDD38, 0xEE9E, 0xBA30, 0xDD1C, 0xEE8F, 0xBA18,
0xDD0E, 0xBA0C, 0xDD07, 0xBA06, 0x9970, 0xCCBC, 0xE65F, 0xBB70, 0x9938, 0xCC9E,
0xBB38, 0xDD9E, 0xCC8F, 0xBB1C, 0x990E, 0xBB0E, 0x9907, 0xBB07, 0x88BC, 0xC45F,
0x99BC, 0x889E, 0xBBBC, 0x999E, 0x888F, 0xBB9E, 0x998F, 0xBB8F, 0x88DF, 0x99DF,
0xBBDF, 0xB960, 0xDCB8, 0xEE5E, 0xB930, 0xDC9C, 0xEE4F, 0xB918, 0xDC8E, 0xB90C,
0xDC87, 0xB906, 0xB903, 0x98B8, 0xCC5E, 0xB9B8, 0x989C, 0xCC4F, 0xB99C, 0xDCCF,
0xB98E, 0x9887, 0xB987, 0x885E, 0x98DE, 0x884F, 0xB9DE, 0x98CF, 0xB9CF, 0xB8B0,
0xDC5C, 0xEE2F, 0xB898, 0xDC4E, 0xB88C, 0xDC47, 0xB886, 0xB883, 0x985C, 0xCC2F,
0xB8DC, 0x984E, 0xB8CE, 0x9847, 0xB8C7, 0x882F, 0x986F, 0xB8EF, 0xB858, 0xDC2E,
0xB84C, 0xDC27, 0xB846, 0xB843, 0x982E, 0xB86E, 0x9827, 0xB867, 0xB82C, 0xDC17,
0xB826, 0xB823, 0x9817, 0xB837, 0xB816, 0xB813, 0x8578, 0xC2BE, 0x853C, 0xC29F,
0x851E, 0x850F, 0x85BE, 0x859F, 0xF85D, 0xF0BD, 0xE17D, 0xC2FD, 0x8D70, 0xC6BC,
0xE35F, 0x8D38, 0xC69E, 0x8D1C, 0xC68F, 0x8D0E, 0x8D07, 0x84BC, 0xC25F, 0x8DBC,
0x849E, 0x8D9E, 0x848F, 0x8D8F, 0x84DF, 0x8DDF, 0x9D60, 0xCEB8, 0xE75E, 0x9D30,
0xCE9C, 0xE74F, 0x9D18, 0xCE8E, 0x9D0C, 0xCE87, 0x9D06, 0x9D03, 0x8CB8, 0xC65E,
0x9DB8, 0x8C9C, 0xC64F, 0x9D9C, 0x8C8E, 0x9D8E, 0x8C87, 0x9D87, 0x845E, 0x8CDE,
0x844F, 0x9DDE, 0x8CCF, 0x9DCF, 0xDEB0, 0xEF5C, 0xF7AF, 0xBD20, 0xDE98, 0xEF4E,
0xBD10, 0xDE8C, 0xEF47, 0xBD08, 0xDE86, 0xBD04, 0xDE83, 0xBD02, 0x9CB0, 0xCE5C,
0xE72F, 0xBDB0, 0x9C98, 0xCE4E, 0xBD98, 0xDECE, 0xCE47, 0xBD8C, 0x9C86, 0xBD86,
0x9C83, 0xBD83, 0x8C5C, 0xC62F, 0x9CDC, 0x8C4E, 0xBDDC, 0x9CCE, 0x8C47, 0xBDCE,
0x9CC7, 0xBDC7, 0x842F, 0x8C6F, 0x9CEF, 0xBDEF, 0xBCA0, 0xDE58, 0xEF2E, 0xBC90,
0xDE4C, 0xEF27, 0xBC88, 0xDE46, 0xBC84, 0xDE43, 0xBC82, 0xBC81, 0x9C58, 0xCE2E,
0xBCD8, 0x9C4C, 0xCE27, 0xBCCC, 0xDE67, 0xBCC6, 0x9C43, 0xBCC3, 0x8C2E, 0x9C6E,
0x8C27, 0xBCEE, 0x9C67, 0xBCE7, 0xBC50, 0xDE2C, 0xEF17, 0xBC48, 0xDE26, 0xBC44,
0xDE23, 0xBC42, 0xBC41, 0x9C2C, 0xCE17, 0xBC6C, 0x9C26, 0xBC66, 0x9C23, 0xBC63,
0x8C17, 0x9C37, 0xBC77, 0xBC28, 0xDE16, 0xBC24, 0xDE13, 0xBC22, 0xBC21, 0x9C16,
0xBC36, 0x9C13, 0xBC33, 0xBC14, 0xDE0B, 0xBC12, 0xBC11, 0x9C0B, 0xBC1B, 0x82BC,
0xC15F, 0x829E, 0x828F, 0x82DF, 0x86B8, 0xC35E, 0x869C, 0xC34F, 0x868E, 0x8687,
0x825E, 0x86DE, 0x824F, 0x86CF, 0x8EB0, 0xC75C, 0xE3AF, 0x8E98, 0xC74E, 0x8E8C,
0xC747, 0x8E86, 0x8E83, 0x865C, 0xC32F, 0x8EDC, 0x864E, 0x8ECE, 0x8647, 0x8EC7,
0x822F, 0x866F, 0x8EEF, 0x9EA0, 0xCF58, 0xE7AE, 0x9E90, 0xCF4C, 0xE7A7, 0x9E88,
0xCF46, 0x9E84, 0xCF43, 0x9E82, 0x9E81, 0x8E58, 0xC72E, 0x9ED8, 0x8E4C, 0xC727,
0x9ECC, 0xCF67, 0x9EC6, 0x8E43, 0x9EC3, 0x862E, 0x8E6E, 0x8627, 0x9EEE, 0x8E67,
0x9EE7, 0xDF50, 0xEFAC, 0xF7D7, 0xDF48, 0xEFA6, 0xDF44, 0xEFA3, 0xDF42, 0xDF41,
0x9E50, 0xCF2C, 0xE797, 0xBED0, 0x9E48, 0xCF26, 0xBEC8, 0xDF66, 0xCF23, 0xBEC4,
0x9E42, 0xBEC2, 0x9E41, 0xBEC1, 0x8E2C, 0xC717, 0x9E6C, 0x8E26, 0xBEEC, 0x9E66,
0x8E23, 0xBEE6, 0x9E63, 0xBEE3, 0x8617, 0x8E37, 0x9E77, 0xBEF7, 0xDF28, 0xEF96,
0xDF24, 0xEF93, 0xDF22, 0xDF21, 0x9E28, 0xCF16, 0xBE68, 0x9E24, 0xCF13, 0xBE64,
0xDF33, 0xBE62, 0x9E21, 0xBE61, 0x8E16, 0x9E36, 0x8E13, 0xBE76, 0x9E33, 0xBE73,
0xDF14, 0xEF8B, 0xDF12, 0xDF11, 0x9E14, 0xCF0B, 0xBE34, 0x9E12, 0xBE32, 0x9E11,
0xBE31, 0x8E0B, 0x9E1B, 0xBE3B, 0xDF0A, 0xDF09, 0x9E0A, 0xBE1A, 0x9E09, 0xBE19,
0x815E, 0x814F, 0x835C, 0xC1AF, 0x834E, 0x8347, 0x812F, 0x836F, 0x8758, 0xC3AE,
0x874C, 0xC3A7, 0x8746, 0x8743, 0x832E, 0x876E, 0x8327, 0x8767, 0x8F50, 0xC7AC,
0xE3D7, 0x8F48, 0xC7A6, 0x8F44, 0xC7A3, 0x8F42, 0x8F41, 0x872C, 0xC397, 0x8F6C,
0xC7B7, 0x8F66, 0x8723, 0x8F63, 0x8317, 0x8737, 0x8F77, 0xCFA8, 0xE7D6, 0xCFA4,
0xE7D3, 0xCFA2, 0xCFA1, 0x8F28, 0xC796, 0x9F68, 0xCFB6, 0xC793, 0x9F64, 0x8F22,
0x9F62, 0x8F21, 0x9F61, 0x8716, 0x8F36, 0x8713, 0x9F76, 0x8F33, 0x9F73, 0xEFD4,
0xF7EB, 0xEFD2, 0xEFD1, 0xCF94, 0xE7CB, 0xDFB4, 0xCF92, 0xDFB2, 0xCF91, 0xDFB1,
0x8F14, 0xC78B, 0x9F34, 0x8F12, 0xBF74, 0x9F32, 0x8F11, 0xBF72, 0x9F31, 0xBF71,
0x870B, 0x8F1B, 0x9F3B, 0xBF7B, 0xEFCA, 0xEFC9, 0xCF8A, 0xDF9A, 0xCF89, 0xDF99,
0x8F0A, 0x9F1A, 0x8F09, 0xBF3A, 0x9F19, 0xBF39, 0xEFC5, 0xCF85, 0xDF8D, 0x8F05,
0x9F0D, 0xBF1D, 0x81AE, 0x81A7, 0x83AC, 0xC1D7, 0x83A6, 0x83A3, 0x8197, 0x83B7,
0x87A8, 0xC3D6, 0x87A4, 0xC3D3, 0x87A2, 0x87A1, 0x8396, 0x87B6, 0x8393, 0x87B3,
0xC7D4, 0xE3EB, 0xC7D2, 0xC7D1, 0x8794, 0xC3CB, 0x8FB4, 0xC7DB, 0x8FB2, 0x8791,
0x8FB1, 0x838B, 0x879B, 0x8FBB, 0xE7EA, 0xE7E9, 0xC7CA, 0xCFDA, 0xC7C9, 0xCFD9,
0x878A, 0x8F9A, 0x8789, 0x9FBA, 0x8F99, 0x9FB9, 0xE7E5, 0xC7C5, 0xCFCD, 0x8785,
0x8F8D, 0x9F9D, 0x81D6, 0x81D3, 0x83D4, 0xC1EB, 0x83D2, 0x83D1, 0x81CB, 0x83DB,
0xC3EA, 0xC3E9, 0x83CA, 0x87DA, 0x83C9, 0x87D9, 0xE3F5
};
/* MicroPDF417 coefficients from ISO/IEC 24728:2006 Annex F */
INTERNAL_DATA const unsigned short pdf_Microcoeffs[344] = {
/* k = 7 */
76, 925, 537, 597, 784, 691, 437,
/* k = 8 */
237, 308, 436, 284, 646, 653, 428, 379,
/* k = 9 */
567, 527, 622, 257, 289, 362, 501, 441, 205,
/* k = 10 */
377, 457, 64, 244, 826, 841, 818, 691, 266, 612,
/* k = 11 */
462, 45, 565, 708, 825, 213, 15, 68, 327, 602, 904,
/* k = 12 */
597, 864, 757, 201, 646, 684, 347, 127, 388, 7, 69, 851,
/* k = 13 */
764, 713, 342, 384, 606, 583, 322, 592, 678, 204, 184, 394, 692,
/* k = 14 */
669, 677, 154, 187, 241, 286, 274, 354, 478, 915, 691, 833, 105, 215,
/* k = 15 */
460, 829, 476, 109, 904, 664, 230, 5, 80, 74, 550, 575, 147, 868, 642,
/* k = 16 */
274, 562, 232, 755, 599, 524, 801, 132, 295, 116, 442, 428, 295, 42, 176, 65,
/* k = 18 */
279, 577, 315, 624, 37, 855, 275, 739, 120, 297, 312, 202, 560, 321, 233, 756,
760, 573,
/* k = 21 */
108, 519, 781, 534, 129, 425, 681, 553, 422, 716, 763, 693, 624, 610, 310, 691,
347, 165, 193, 259, 568,
/* k = 26 */
443, 284, 887, 544, 788, 93, 477, 760, 331, 608, 269, 121, 159, 830, 446, 893,
699, 245, 441, 454, 325, 858, 131, 847, 764, 169,
/* k = 32 */
361, 575, 922, 525, 176, 586, 640, 321, 536, 742, 677, 742, 687, 284, 193, 517,
273, 494, 263, 147, 593, 800, 571, 320, 803, 133, 231, 390, 685, 330, 63, 410,
/* k = 38 */
234, 228, 438, 848, 133, 703, 529, 721, 788, 322, 280, 159, 738, 586, 388, 684,
445, 680, 245, 595, 614, 233, 812, 32, 284, 658, 745, 229, 95, 689, 920, 771,
554, 289, 231, 125, 117, 518,
/* k = 44 */
476, 36, 659, 848, 678, 64, 764, 840, 157, 915, 470, 876, 109, 25, 632, 405,
417, 436, 714, 60, 376, 97, 413, 706, 446, 21, 3, 773, 569, 267, 272, 213,
31, 560, 231, 758, 103, 271, 572, 436, 339, 730, 82, 285,
/* k = 50 */
923, 797, 576, 875, 156, 706, 63, 81, 257, 874, 411, 416, 778, 50, 205, 303,
188, 535, 909, 155, 637, 230, 534, 96, 575, 102, 264, 233, 919, 593, 865, 26,
579, 623, 766, 146, 10, 739, 246, 127, 71, 244, 211, 477, 920, 876, 427, 820,
718, 435
};
/* rows, columns, error codewords, k-offset of valid MicroPDF417 sizes from ISO/IEC 24728:2006 */
INTERNAL_DATA const unsigned short pdf_MicroVariants[170] = {
1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
11, 14, 17, 20, 24, 28, 8, 11, 14, 17, 20, 23, 26, 6, 8, 10, 12, 15, 20, 26, 32, 38, 44, 4, 6, 8, 10, 12, 15, 20, 26, 32, 38, 44,
7, 7, 7, 8, 8, 8, 8, 9, 9, 10, 11, 13, 15, 12, 14, 16, 18, 21, 26, 32, 38, 44, 50, 8, 12, 14, 16, 18, 21, 26, 32, 38, 44, 50,
0, 0, 0, 7, 7, 7, 7, 15, 15, 24, 34, 57, 84, 45, 70, 99, 115, 133, 154, 180, 212, 250, 294, 7, 45, 70, 99, 115, 133, 154, 180, 212, 250, 294
};
/* rows, columns, error codewords, k-offset */
/* following is Left RAP, Centre RAP, Right RAP and Start Cluster from ISO/IEC 24728:2006 tables 10, 11 and 12 */
INTERNAL_DATA const char pdf_RAPTable[136] = {
1, 8, 36, 19, 9, 25, 1, 1, 8, 36, 19, 9, 27, 1, 7, 15, 25, 37, 1, 1, 21, 15, 1, 47, 1, 7, 15, 25, 37, 1, 1, 21, 15, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 15, 25, 37, 17, 9, 29, 31, 25, 19, 1, 7, 15, 25, 37, 17, 9, 29, 31, 25,
9, 8, 36, 19, 17, 33, 1, 9, 8, 36, 19, 17, 35, 1, 7, 15, 25, 37, 33, 17, 37, 47, 49, 43, 1, 7, 15, 25, 37, 33, 17, 37, 47, 49,
0, 3, 6, 0, 6, 0, 0, 0, 3, 6, 0, 6, 6, 0, 0, 6, 0, 0, 0, 0, 6, 6, 0, 3, 0, 0, 6, 0, 0, 0, 0, 6, 6, 0
};
/* Left and Right Row Address Pattern from Table 2 */
INTERNAL_DATA const unsigned short pdf_rap_side[52] = {
0x322, 0x3A2, 0x3B2, 0x332, 0x372, 0x37A, 0x33A, 0x3BA, 0x39A, 0x3DA,
0x3CA, 0x38A, 0x30A, 0x31A, 0x312, 0x392, 0x3D2, 0x3D6, 0x3D4, 0x394,
0x3B4, 0x3A4, 0x3A6, 0x3AE, 0x3AC, 0x3A8, 0x328, 0x32C, 0x32E, 0x326,
0x336, 0x3B6, 0x396, 0x316, 0x314, 0x334, 0x374, 0x364, 0x366, 0x36E,
0x36C, 0x368, 0x348, 0x358, 0x35C, 0x35E, 0x34E, 0x34C, 0x344, 0x346,
0x342, 0x362
};
/* Centre Row Address Pattern from Table 2 */
INTERNAL_DATA const unsigned short pdf_rap_centre[52] = {
0x2CE, 0x24E, 0x26E, 0x22E, 0x226, 0x236, 0x216, 0x212, 0x21A, 0x23A,
0x232, 0x222, 0x262, 0x272, 0x27A, 0x2FA, 0x2F2, 0x2F6, 0x276, 0x274,
0x264, 0x266, 0x246, 0x242, 0x2C2, 0x2E2, 0x2E6, 0x2E4, 0x2EC, 0x26C,
0x22C, 0x228, 0x268, 0x2E8, 0x2C8, 0x2CC, 0x2C4, 0x2C6, 0x286, 0x28E,
0x28C, 0x29C, 0x298, 0x2B8, 0x2B0, 0x290, 0x2D0, 0x250, 0x258, 0x25C,
0x2DC, 0x2DE
};
#endif /* __PDF417_TABS_H */
| woo-j/zint | backend/pdf417_tabs.h | C | gpl-3.0 | 35,628 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.